Skip to main content

clm_rust_core/services/
sqlite_pool.rs

1//! SQLite Connection Pool ambient service provider (CRD-03).
2//!
3//! Normative Reference:
4//!   clm/docs/spec/60-verification/crd_coeffect_taxonomy.yaml (service: sqlite_pool)
5
6use std::sync::Mutex;
7use std::collections::HashMap;
8
9pub type PoolError = String;
10
11#[derive(Debug, Clone)]
12pub struct PooledConnection {
13    pub id: String,
14    pub is_active: bool,
15}
16
17pub use crate::fiber::savepoint_guard::SavepointGuard;
18
19pub trait SqlitePoolService: Send + Sync {
20    fn acquire(&self) -> Result<PooledConnection, PoolError>;
21    fn release(&self, conn: PooledConnection);
22    fn savepoint(&self, name: &str) -> Result<SavepointGuard, PoolError>;
23    fn get_setting(&self, key: &str) -> Option<String>;
24    fn set_setting(&self, key: &str, val: &str);
25}
26
27pub struct InMemorySqlitePool {
28    pub db_path: String,
29    pub settings: Mutex<HashMap<String, String>>,
30    connections: Mutex<Vec<PooledConnection>>,
31    counter: Mutex<usize>,
32}
33
34impl InMemorySqlitePool {
35    pub fn new(db_path: &str) -> Self {
36        let mut settings = HashMap::new();
37        settings.insert("isolation_level".to_string(), "DEFERRED".to_string());
38        settings.insert("timeout".to_string(), "5000".to_string());
39
40        Self {
41            db_path: db_path.to_string(),
42            settings: Mutex::new(settings),
43            connections: Mutex::new(Vec::new()),
44            counter: Mutex::new(0),
45        }
46    }
47
48    pub fn clone_pool(&self) -> Self {
49        let cloned_settings = self.settings.lock().map(|s| s.clone()).unwrap_or_default();
50        Self {
51            db_path: self.db_path.clone(),
52            settings: Mutex::new(cloned_settings),
53            connections: Mutex::new(Vec::new()),
54            counter: Mutex::new(0),
55        }
56    }
57}
58
59impl SqlitePoolService for InMemorySqlitePool {
60    fn acquire(&self) -> Result<PooledConnection, PoolError> {
61        let mut pool = self.connections.lock().map_err(|e| e.to_string())?;
62        if let Some(conn) = pool.pop() {
63            Ok(conn)
64        } else {
65            let mut c = self.counter.lock().map_err(|e| e.to_string())?;
66            *c += 1;
67            Ok(PooledConnection {
68                id: format!("conn-{}", *c),
69                is_active: true,
70            })
71        }
72    }
73
74    fn release(&self, mut conn: PooledConnection) {
75        conn.is_active = false;
76        if let Ok(mut pool) = self.connections.lock() {
77            if pool.len() < 10 {
78                pool.push(conn);
79            }
80        }
81    }
82
83    fn savepoint(&self, name: &str) -> Result<SavepointGuard, PoolError> {
84        #[cfg(any(feature = "native", feature = "db"))]
85        return SavepointGuard::idle(None, name);
86        #[cfg(not(any(feature = "native", feature = "db")))]
87        return SavepointGuard::idle(name);
88    }
89
90    fn get_setting(&self, key: &str) -> Option<String> {
91        self.settings.lock().ok()?.get(key).cloned()
92    }
93
94    fn set_setting(&self, key: &str, val: &str) {
95        if let Ok(mut s) = self.settings.lock() {
96            s.insert(key.to_string(), val.to_string());
97        }
98    }
99}