ctb_storage/
db.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Database connection pooling, SQL execution, and schema migrations runner.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace crate prelude"
26)]
27pub(crate) use ctb_utilities::*;
28
29use anyhow::{Result, anyhow};
30use sea_query::{
31    Iden, IdenList, QueryStatementWriter, SchemaStatementBuilder, Write,
32};
33use std::{
34    collections::HashMap,
35    path::{Path, PathBuf},
36    sync::{OnceLock, RwLock},
37};
38use turso::{Builder, Connection, Database, EncryptionOpts};
39
40#[ipc_dto]
41#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
42pub struct TableRow {
43    pub columns: Vec<String>,
44    pub values: Vec<Vec<String>>,
45    pub page: u32,
46    pub total_pages: u32,
47    pub total_rows: u32,
48}
49
50static DB_POOL: OnceLock<RwLock<HashMap<PathBuf, Database>>> = OnceLock::new();
51static DB_POOL_CLEANUP_REGISTERED: OnceLock<()> = OnceLock::new();
52
53fn db_pool() -> &'static RwLock<HashMap<PathBuf, Database>> {
54    DB_POOL_CLEANUP_REGISTERED.get_or_init(|| {
55        ctb_utilities::testing::register_storage_dir_cleanup_hook(
56            close_databases_under_dir,
57        );
58    });
59    DB_POOL.get_or_init(|| RwLock::new(HashMap::new()))
60}
61
62/// Evicts and closes cached `Database` instances residing under `dir`, freeing
63/// their page-cache arenas and releasing open OS file handles.
64pub fn close_databases_under_dir(dir: &Path) {
65    let Some(pool_lock) = DB_POOL.get() else {
66        return;
67    };
68    let mut evicted = Vec::new();
69    if let Ok(mut pool) = pool_lock.write() {
70        let matching_keys: Vec<PathBuf> = pool
71            .keys()
72            .filter(|db_path| db_path.starts_with(dir))
73            .cloned()
74            .collect();
75        for key in matching_keys {
76            if let Some(db) = pool.remove(&key) {
77                evicted.push(db);
78            }
79        }
80    }
81    drop(evicted);
82}
83
84#[derive(sea_query::Iden)]
85#[iden(rename = "users")]
86enum Users {
87    Table,
88    #[iden(rename = "id")]
89    Id,
90    #[iden(rename = "username")]
91    Username,
92    #[iden(rename = "uuid")]
93    Uuid,
94    #[iden(rename = "auth")]
95    Auth,
96    #[iden(rename = "display_name")]
97    DisplayName,
98    #[iden(rename = "picture")]
99    Picture,
100    #[iden(rename = "key_encryption_key_params")]
101    KeyEncryptionKeyParams,
102    #[iden(rename = "wrapped_dek")]
103    WrappedDek,
104    #[iden(rename = "pubkey")]
105    Pubkey,
106}
107
108fn extract_user_id(name: &str) -> Option<u64> {
109    let path = Path::new(name);
110    let comps: Vec<_> = path.components().collect();
111    for (idx, comp) in comps.iter().enumerate() {
112        if let std::path::Component::Normal(val) = comp {
113            if val.to_str() == Some("graphs")
114                && idx.saturating_add(1) < comps.len()
115            {
116                if let Some(std::path::Component::Normal(id_str)) =
117                    comps.get(idx.saturating_add(1))
118                {
119                    if let Some(id_s) = id_str.to_str() {
120                        if let Ok(id) = id_s.parse::<u64>() {
121                            return Some(id);
122                        }
123                    }
124                }
125            }
126        }
127    }
128    None
129}
130
131pub async fn validate_and_get_user(
132    session_token: &str,
133) -> Result<crate::user::User> {
134    let user_id =
135        crate::user::session::validate_session(session_token.to_string())
136            .await?
137            .ok_or_else(|| {
138                anyhow!("Unauthorized: invalid or expired session")
139            })?;
140    let pub_info = crate::user::UserPublicInfo::get_by_id(user_id)
141        .ok_or_else(|| anyhow!("User not found"))?;
142    Ok(crate::user::User::from_public_info(
143        pub_info,
144        Some(session_token.to_string()),
145    ))
146}
147
148pub fn authorize_db_access(session_user_id: u64, db_name: &str) -> Result<()> {
149    if let Some(path_user_id) = extract_user_id(db_name) {
150        if path_user_id != session_user_id {
151            anyhow::bail!(
152                "Unauthorized database access: user {session_user_id} does not own {db_name}"
153            );
154        }
155    } else if db_name.starts_with("graphs/") {
156        anyhow::bail!(
157            "Unauthorized database access: invalid graph path {db_name}"
158        );
159    }
160    Ok(())
161}
162
163fn get_schema_type(name: &str) -> Option<crate::migrations::DbSchemaType> {
164    if name == "users" || name.starts_with("users/") {
165        Some(crate::migrations::DbSchemaType::Users)
166    } else if name.contains("graphs/") {
167        Some(crate::migrations::DbSchemaType::Nodes)
168    } else if name == "sync" {
169        Some(crate::migrations::DbSchemaType::Sync)
170    } else {
171        None
172    }
173}
174
175/// Resolve connection to the database.
176pub async fn get_connection(name: &str) -> Result<Connection> {
177    let path = get_db_path(name)?;
178
179    // 1. Read lock check
180    let db = {
181        let pool = db_pool()
182            .read()
183            .map_err(|e| anyhow!("Pool lock poisoned: {e}"))?;
184        pool.get(&path).cloned()
185    };
186
187    let db = if let Some(db) = db {
188        db
189    } else {
190        // 2. Build the database asynchronously outside the lock
191        let path_str = path.to_string_lossy().to_string();
192        let db = if let Some(user_id) = extract_user_id(name) {
193            let dek = crate::user::session::get_user_dek(user_id)?;
194            let builder = Builder::new_local(&path_str)
195                .experimental_encryption(true)
196                .with_encryption(EncryptionOpts {
197                    cipher: "aegis256".to_string(),
198                    hexkey: bin2hex(dek.as_slice()),
199                });
200            drop(dek);
201            builder.build().await?
202        } else {
203            Builder::new_local(&path_str).build().await?
204        };
205
206        // Run migrations on the newly initialized/built Database
207        let conn = db.connect()?;
208        conn.busy_timeout(std::time::Duration::from_millis(5000))?;
209        if let Some(schema_type) = get_schema_type(name) {
210            crate::migrations::run_migrations(&conn, schema_type).await?;
211        }
212
213        // 3. Write lock check/insert (double-checked)
214        let mut pool = db_pool()
215            .write()
216            .map_err(|e| anyhow!("Pool lock poisoned: {e}"))?;
217        if let Some(existing) = pool.get(&path) {
218            existing.clone()
219        } else {
220            pool.insert(path.clone(), db.clone());
221            db
222        }
223    };
224
225    let conn = db.connect()?;
226    conn.busy_timeout(std::time::Duration::from_millis(5000))?;
227    Ok(conn)
228}
229
230/// Helper to resolve the database path. Consolidates `users/` prefix into a single `users.db`.
231pub fn get_db_path(name: &str) -> Result<PathBuf> {
232    let storage_dir = ctb_utilities::storage::get_storage_dir()?;
233    let path =
234        if name.starts_with('/') || std::path::Path::new(name).is_absolute() {
235            if name.ends_with(".db") {
236                PathBuf::from(name)
237            } else {
238                PathBuf::from(format!("{name}.db"))
239            }
240        } else if name.starts_with("users/") {
241            storage_dir.join("users.db")
242        } else {
243            storage_dir.join(format!("{name}.db"))
244        };
245
246    if let Some(parent) = path.parent() {
247        std::fs::create_dir_all(parent)?;
248    }
249    Ok(path)
250}
251
252/// Helper to get a safe, valid SQL table name.
253pub fn get_table_name(name: &str) -> String {
254    name.replace(['/', '-'], "_")
255}
256
257/// Close and clear database connections for a deregistered user in `storage_dir`.
258pub fn close_connections_in_dir(
259    storage_dir: &Path,
260    user_id: u64,
261) -> Result<()> {
262    let path = storage_dir.join(format!("graphs/{user_id}/user_data.db"));
263    let mut pool = db_pool()
264        .write()
265        .map_err(|e| anyhow!("Pool lock poisoned: {e}"))?;
266    pool.remove(&path);
267    Ok(())
268}
269
270/// Close and clear database connections for a deregistered user.
271pub fn close_connections(user_id: u64) -> Result<()> {
272    let storage_dir = ctb_utilities::storage::get_storage_dir()?;
273    close_connections_in_dir(&storage_dir, user_id)
274}
275
276/// Convert `SeaQuery` Values to Turso Values.
277pub fn sea_values_to_turso(
278    values: sea_query::Values,
279) -> Result<Vec<turso::Value>> {
280    values
281        .into_iter()
282        .map(|val| match val {
283            sea_query::Value::Bool(Some(b)) => {
284                Ok(turso::Value::Integer(i64::from(b)))
285            }
286            sea_query::Value::TinyInt(Some(v)) => {
287                Ok(turso::Value::Integer(i64::from(v)))
288            }
289            sea_query::Value::SmallInt(Some(v)) => {
290                Ok(turso::Value::Integer(i64::from(v)))
291            }
292            sea_query::Value::Int(Some(v)) => {
293                Ok(turso::Value::Integer(i64::from(v)))
294            }
295            sea_query::Value::BigInt(Some(v)) => Ok(turso::Value::Integer(v)),
296            sea_query::Value::TinyUnsigned(Some(v)) => {
297                Ok(turso::Value::Integer(i64::from(v)))
298            }
299            sea_query::Value::SmallUnsigned(Some(v)) => {
300                Ok(turso::Value::Integer(i64::from(v)))
301            }
302            sea_query::Value::Unsigned(Some(v)) => {
303                Ok(turso::Value::Integer(i64::from(v)))
304            }
305            sea_query::Value::BigUnsigned(Some(v)) => {
306                let i = <i64 as TryFrom<_>>::try_from(v).context(
307                    "BigUnsigned value is out of bounds for Turso i64 integer",
308                )?;
309                Ok(turso::Value::Integer(i))
310            }
311            sea_query::Value::Float(Some(v)) => {
312                Ok(turso::Value::Real(f64::from(v)))
313            }
314            sea_query::Value::Double(Some(v)) => Ok(turso::Value::Real(v)),
315            sea_query::Value::String(Some(s)) => {
316                Ok(turso::Value::Text((*s).to_string()))
317            }
318            sea_query::Value::Char(Some(c)) => {
319                Ok(turso::Value::Text(c.to_string()))
320            }
321            sea_query::Value::Bytes(Some(b)) => {
322                Ok(turso::Value::Blob((*b).to_vec()))
323            }
324            _ => Ok(turso::Value::Null),
325        })
326        .collect()
327}