aegis-runtime-mv
Native Rust agent runtime: Axum WebSocket/SSE/REST gateway, heartbeat scheduler, dependency-aware task workflow, SQLite storage. Attachment of AienOS. Pre-alpha.
Brought by drakestapleton
aegis-runtime-mv / src / persistence / async_db.rs
| 1 | use super::error::PersistenceError; |
| 2 | use super::sqlite::schema::initialize_schema; |
| 3 | use rusqlite::Connection; |
| 4 | use std::path::{Path, PathBuf}; |
| 5 | use std::sync::{Arc, Mutex}; |
| 6 | |
| 7 | #[derive(Clone)] |
| 8 | pub struct AsyncDatabase { |
| 9 | conn: Arc<Mutex<Connection>>, |
| 10 | transcript_path: Option<PathBuf>, |
| 11 | } |
| 12 | |
| 13 | impl AsyncDatabase { |
| 14 | pub fn open(path: &Path) -> Result<Self, PersistenceError> { |
| 15 | let conn = Connection::open(path)?; |
| 16 | initialize_schema(&conn)?; |
| 17 | let transcript_path = path.parent().map(|p| p.join("transcript.jsonl")); |
| 18 | Ok(Self { |
| 19 | conn: Arc::new(Mutex::new(conn)), |
| 20 | transcript_path, |
| 21 | }) |
| 22 | } |
| 23 | |
| 24 | pub fn open_in_memory() -> Result<Self, PersistenceError> { |
| 25 | let conn = Connection::open_in_memory()?; |
| 26 | initialize_schema(&conn)?; |
| 27 | Ok(Self { |
| 28 | conn: Arc::new(Mutex::new(conn)), |
| 29 | transcript_path: None, |
| 30 | }) |
| 31 | } |
| 32 | |
| 33 | pub fn from_connection_arc( |
| 34 | conn: Arc<Mutex<Connection>>, |
| 35 | transcript_path: Option<PathBuf>, |
| 36 | ) -> Self { |
| 37 | Self { |
| 38 | conn, |
| 39 | transcript_path, |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | pub fn shared_conn(&self) -> Arc<Mutex<Connection>> { |
| 44 | Arc::clone(&self.conn) |
| 45 | } |
| 46 | |
| 47 | pub fn transcript_path(&self) -> Option<&PathBuf> { |
| 48 | self.transcript_path.as_ref() |
| 49 | } |
| 50 | |
| 51 | pub async fn interact<F, R>(&self, f: F) -> Result<R, PersistenceError> |
| 52 | where |
| 53 | F: FnOnce(&mut Connection) -> Result<R, PersistenceError> + Send + 'static, |
| 54 | R: Send + 'static, |
| 55 | { |
| 56 | let conn = Arc::clone(&self.conn); |
| 57 | tokio::task::spawn_blocking(move || { |
| 58 | let mut guard = conn.lock().map_err(|_| PersistenceError::LockPoisoned)?; |
| 59 | f(&mut guard) |
| 60 | }) |
| 61 | .await |
| 62 | .map_err(|e| PersistenceError::TaskJoin(e.to_string()))? |
| 63 | } |
| 64 | } |