clm-kernel 0.0.10

Cubical Logic Model (CLM) sovereign execution engine, CPN-VM, and Cordis spatiotemporal substrate
Documentation
//! SQLite Connection Pool ambient service provider (CRD-03).
//!
//! Normative Reference:
//!   clm/docs/spec/60-verification/crd_coeffect_taxonomy.yaml (service: sqlite_pool)

use std::sync::Mutex;
use std::collections::HashMap;

pub type PoolError = String;

#[derive(Debug, Clone)]
pub struct PooledConnection {
    pub id: String,
    pub is_active: bool,
}

pub use crate::fiber::savepoint_guard::SavepointGuard;

pub trait SqlitePoolService: Send + Sync {
    fn acquire(&self) -> Result<PooledConnection, PoolError>;
    fn release(&self, conn: PooledConnection);
    fn savepoint(&self, name: &str) -> Result<SavepointGuard, PoolError>;
    fn get_setting(&self, key: &str) -> Option<String>;
    fn set_setting(&self, key: &str, val: &str);
}

pub struct InMemorySqlitePool {
    pub db_path: String,
    pub settings: Mutex<HashMap<String, String>>,
    connections: Mutex<Vec<PooledConnection>>,
    counter: Mutex<usize>,
}

impl InMemorySqlitePool {
    pub fn new(db_path: &str) -> Self {
        let mut settings = HashMap::new();
        settings.insert("isolation_level".to_string(), "DEFERRED".to_string());
        settings.insert("timeout".to_string(), "5000".to_string());

        Self {
            db_path: db_path.to_string(),
            settings: Mutex::new(settings),
            connections: Mutex::new(Vec::new()),
            counter: Mutex::new(0),
        }
    }

    pub fn clone_pool(&self) -> Self {
        let cloned_settings = self.settings.lock().map(|s| s.clone()).unwrap_or_default();
        Self {
            db_path: self.db_path.clone(),
            settings: Mutex::new(cloned_settings),
            connections: Mutex::new(Vec::new()),
            counter: Mutex::new(0),
        }
    }
}

impl SqlitePoolService for InMemorySqlitePool {
    fn acquire(&self) -> Result<PooledConnection, PoolError> {
        let mut pool = self.connections.lock().map_err(|e| e.to_string())?;
        if let Some(conn) = pool.pop() {
            Ok(conn)
        } else {
            let mut c = self.counter.lock().map_err(|e| e.to_string())?;
            *c += 1;
            Ok(PooledConnection {
                id: format!("conn-{}", *c),
                is_active: true,
            })
        }
    }

    fn release(&self, mut conn: PooledConnection) {
        conn.is_active = false;
        if let Ok(mut pool) = self.connections.lock() {
            if pool.len() < 10 {
                pool.push(conn);
            }
        }
    }

    fn savepoint(&self, name: &str) -> Result<SavepointGuard, PoolError> {
        #[cfg(any(feature = "native", feature = "db"))]
        return SavepointGuard::idle(None, name);
        #[cfg(not(any(feature = "native", feature = "db")))]
        return SavepointGuard::idle(name);
    }

    fn get_setting(&self, key: &str) -> Option<String> {
        self.settings.lock().ok()?.get(key).cloned()
    }

    fn set_setting(&self, key: &str, val: &str) {
        if let Ok(mut s) = self.settings.lock() {
            s.insert(key.to_string(), val.to_string());
        }
    }
}