use std::fmt;
pub type DisposerFn = Box<dyn FnOnce() -> Result<(), String> + Send>;
pub struct DisposableList {
disposers: Vec<DisposerFn>,
}
impl Default for DisposableList {
fn default() -> Self {
Self::new()
}
}
impl fmt::Debug for DisposableList {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DisposableList")
.field("pending_count", &self.disposers.len())
.finish()
}
}
impl DisposableList {
pub fn new() -> Self {
Self {
disposers: Vec::new(),
}
}
pub fn push<F>(&mut self, cleanup: F)
where
F: FnOnce() -> Result<(), String> + Send + 'static,
{
self.disposers.push(Box::new(cleanup));
}
pub fn register<F>(&mut self, cleanup: F)
where
F: FnOnce() -> Result<(), String> + Send + 'static,
{
self.push(cleanup);
}
pub fn len(&self) -> usize {
self.disposers.len()
}
pub fn is_empty(&self) -> bool {
self.disposers.is_empty()
}
pub fn dispose(mut self) -> Result<(), Vec<String>> {
let mut errors = Vec::new();
while let Some(disposer) = self.disposers.pop() {
if let Err(e) = disposer() {
errors.push(e);
}
}
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
}
#[cfg(any(feature = "native", feature = "db"))]
use rusqlite::Connection;
#[cfg(any(feature = "native", feature = "db"))]
use std::sync::{Arc, Mutex};
#[cfg(any(feature = "native", feature = "db"))]
pub struct SavepointGuard {
pub name: String,
pub token: crate::types::domain::SavepointToken,
pub conn: Arc<Mutex<Connection>>,
pub committed: bool,
}
#[cfg(any(feature = "native", feature = "db"))]
impl SavepointGuard {
pub fn new(conn: Arc<Mutex<Connection>>, name: impl Into<String>) -> Result<Self, String> {
let raw_name = name.into();
let token = crate::types::domain::SavepointToken::parse(&raw_name)
.unwrap_or_else(|_| crate::types::domain::SavepointToken::generate(&raw_name));
Self::with_token(conn, token)
}
pub fn with_token(
conn: Arc<Mutex<Connection>>,
token: crate::types::domain::SavepointToken,
) -> Result<Self, String> {
let token_str = token.as_str().to_string();
{
let c = conn.lock().map_err(|e| e.to_string())?;
c.execute_batch(&format!("SAVEPOINT {};", token_str))
.map_err(|e| format!("Failed to create savepoint {}: {}", token_str, e))?;
}
Ok(Self {
name: token_str,
token,
conn,
committed: false,
})
}
pub fn commit(&mut self) -> Result<(), String> {
if !self.committed {
let c = self.conn.lock().map_err(|e| e.to_string())?;
c.execute_batch(&format!("RELEASE SAVEPOINT {};", self.token.as_str()))
.map_err(|e| format!("Failed to release savepoint {}: {}", self.token.as_str(), e))?;
self.committed = true;
}
Ok(())
}
pub fn rollback(&mut self) -> Result<(), String> {
if !self.committed {
let c = self.conn.lock().map_err(|e| e.to_string())?;
c.execute_batch(&format!(
"ROLLBACK TO SAVEPOINT {}; RELEASE SAVEPOINT {};",
self.token.as_str(),
self.token.as_str()
))
.map_err(|e| format!("Failed to rollback savepoint {}: {}", self.token.as_str(), e))?;
self.committed = true;
}
Ok(())
}
}
#[cfg(any(feature = "native", feature = "db"))]
impl Drop for SavepointGuard {
fn drop(&mut self) {
if !self.committed
&& let Ok(c) = self.conn.lock() {
let _ = c.execute_batch(&format!(
"ROLLBACK TO SAVEPOINT {}; RELEASE SAVEPOINT {};",
self.token.as_str(),
self.token.as_str()
));
}
}
}
#[cfg(any(feature = "native", feature = "db"))]
pub struct TriDbSavepointGuard {
pub clm_root: String,
pub sp_name: String,
pub guards: Vec<SavepointGuard>,
pub committed: bool,
}
#[cfg(any(feature = "native", feature = "db"))]
impl TriDbSavepointGuard {
pub fn new(clm_root: &str, sp_name: &str, _is_rust: bool) -> Result<Self, String> {
let pillars = ["content_memory", "agent_identities", "execution_log"];
let mut guards = Vec::with_capacity(3);
for pillar in &pillars {
let conn = crate::db::get_writer_connection(pillar, clm_root)
.map_err(|e| e.to_string())?;
let token = crate::types::domain::SavepointToken::generate(&format!("{}_{}", sp_name, pillar));
let g = SavepointGuard::with_token(conn, token)?;
guards.push(g);
}
Ok(Self {
clm_root: clm_root.to_string(),
sp_name: sp_name.to_string(),
guards,
committed: false,
})
}
pub fn is_active(&self) -> bool {
!self.committed
}
pub fn commit(&mut self) -> Result<(), String> {
if !self.committed {
for g in &mut self.guards {
g.commit()?;
}
self.committed = true;
}
Ok(())
}
pub fn rollback(&mut self) -> Result<(), String> {
if !self.committed {
for g in &mut self.guards {
let _ = g.rollback();
}
self.committed = true;
}
Ok(())
}
}
#[cfg(any(feature = "native", feature = "db"))]
impl Drop for TriDbSavepointGuard {
fn drop(&mut self) {
if !self.committed {
let _ = self.rollback();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::{Arc, Mutex};
#[test]
#[cfg(any(feature = "native", feature = "db"))]
fn test_savepoint_guard_commit_and_rollback() {
let conn = rusqlite::Connection::open_in_memory().unwrap();
conn.execute("CREATE TABLE test (id INT, val TEXT);", []).unwrap();
let arc_conn = Arc::new(Mutex::new(conn));
{
let mut sp = SavepointGuard::new(arc_conn.clone(), "sp1").unwrap();
arc_conn.lock().unwrap().execute("INSERT INTO test VALUES (1, 'committed');", []).unwrap();
sp.commit().unwrap();
}
let count: i64 = arc_conn.lock().unwrap().query_row("SELECT count(*) FROM test WHERE id=1;", [], |r| r.get(0)).unwrap();
assert_eq!(count, 1);
{
let _sp = SavepointGuard::new(arc_conn.clone(), "sp2").unwrap();
arc_conn.lock().unwrap().execute("INSERT INTO test VALUES (2, 'aborted');", []).unwrap();
}
let count2: i64 = arc_conn.lock().unwrap().query_row("SELECT count(*) FROM test WHERE id=2;", [], |r| r.get(0)).unwrap();
assert_eq!(count2, 0);
}
#[test]
#[cfg(any(feature = "native", feature = "db"))]
fn test_savepoint_guard_submillisecond_rollback_benchmark() {
let conn = rusqlite::Connection::open_in_memory().unwrap();
conn.execute("CREATE TABLE card (hash TEXT PRIMARY KEY, content BLOB NOT NULL, g_time TEXT NOT NULL);", []).unwrap();
conn.execute("CREATE TABLE handle_registry (handle TEXT PRIMARY KEY, current_hash TEXT NOT NULL, created_at TEXT, updated_at TEXT);", []).unwrap();
let arc_conn = Arc::new(Mutex::new(conn));
let iterations = 100;
let mut durations_micros = Vec::with_capacity(iterations);
for i in 0..iterations {
let sp_name = format!("sp_bench_{}", i);
let mut sp = SavepointGuard::new(arc_conn.clone(), &sp_name).unwrap();
{
let c = arc_conn.lock().unwrap();
c.execute("INSERT INTO card (hash, content, g_time) VALUES (?1, ?2, datetime('now'))", rusqlite::params![format!("hash_{}", i), b"test_content"]).unwrap();
c.execute("INSERT INTO handle_registry (handle, current_hash, created_at, updated_at) VALUES (?1, ?2, datetime('now'), datetime('now'))", rusqlite::params![format!("mcard://bench/{}", i), format!("hash_{}", i)]).unwrap();
}
let t0 = std::time::Instant::now();
sp.rollback().unwrap();
let elapsed = t0.elapsed();
durations_micros.push(elapsed.as_micros() as f64);
let c = arc_conn.lock().unwrap();
let card_count: i64 = c.query_row("SELECT count(*) FROM card", [], |r| r.get(0)).unwrap();
let handle_count: i64 = c.query_row("SELECT count(*) FROM handle_registry", [], |r| r.get(0)).unwrap();
assert_eq!(card_count, 0, "card table must be empty after rollback at iteration {}", i);
assert_eq!(handle_count, 0, "handle_registry table must be empty after rollback at iteration {}", i);
}
durations_micros.sort_by(|a, b| a.partial_cmp(b).unwrap());
let p99_micros = durations_micros[(iterations as f64 * 0.99) as usize];
let p99_ms = p99_micros / 1000.0;
eprintln!("[RUST BENCHMARK] SavepointGuard rollback 100 iterations: p99 = {:.3}ms ({:.1}µs)", p99_ms, p99_micros);
assert!(p99_ms < 1.0, "Rust SavepointGuard p99 rollback must be < 1.0ms, got {:.3}ms", p99_ms);
}
#[test]
fn test_strict_lifo_unwinding() {
let execution_log = Arc::new(Mutex::new(Vec::<usize>::new()));
let mut list = DisposableList::new();
for i in 1..=4 {
let log_clone = Arc::clone(&execution_log);
list.push(move || {
log_clone.lock().unwrap().push(i);
Ok(())
});
}
assert_eq!(list.len(), 4);
assert!(list.dispose().is_ok());
let log = execution_log.lock().unwrap();
assert_eq!(*log, vec![4, 3, 2, 1]);
}
#[test]
fn test_unwind_continues_on_error() {
let execution_log = Arc::new(Mutex::new(Vec::<usize>::new()));
let mut list = DisposableList::new();
let l1 = Arc::clone(&execution_log);
list.push(move || {
l1.lock().unwrap().push(1);
Ok(())
});
let l2 = Arc::clone(&execution_log);
list.push(move || {
l2.lock().unwrap().push(2);
Err("Failed closing resource 2".to_string())
});
let l3 = Arc::clone(&execution_log);
list.push(move || {
l3.lock().unwrap().push(3);
Ok(())
});
let res = list.dispose();
assert!(res.is_err());
let errs = res.unwrap_err();
assert_eq!(errs.len(), 1);
assert_eq!(errs[0], "Failed closing resource 2");
let log = execution_log.lock().unwrap();
assert_eq!(*log, vec![3, 2, 1]);
}
}