Skip to main content

briefcase_core/storage/
sync.rs

1//! Synchronous storage backend implementations
2//!
3//! This module provides synchronous variants of the storage backends
4//! for use cases that don't require async functionality.
5
6use super::{FlushResult, SnapshotQuery, StorageError};
7use crate::models::{DecisionSnapshot, Snapshot};
8use std::collections::HashMap;
9
10/// Synchronous storage backend trait
11pub trait SyncStorageBackend: Send + Sync {
12    /// Save a snapshot, return its ID
13    fn save(&self, snapshot: &Snapshot) -> Result<String, StorageError>;
14
15    /// Save a single decision snapshot
16    fn save_decision(&self, decision: &DecisionSnapshot) -> Result<String, StorageError>;
17
18    /// Load a snapshot by ID
19    fn load(&self, snapshot_id: &str) -> Result<Snapshot, StorageError>;
20
21    /// Load a decision by ID
22    fn load_decision(&self, decision_id: &str) -> Result<DecisionSnapshot, StorageError>;
23
24    /// Query snapshots with filters
25    fn query(&self, query: SnapshotQuery) -> Result<Vec<Snapshot>, StorageError>;
26
27    /// Delete a snapshot
28    fn delete(&self, snapshot_id: &str) -> Result<bool, StorageError>;
29
30    /// Flush pending writes (for batching backends)
31    fn flush(&self) -> Result<FlushResult, StorageError>;
32
33    /// Check health/connectivity
34    fn health_check(&self) -> Result<bool, StorageError>;
35}
36
37/// Synchronous SQLite backend implementation
38#[cfg(feature = "sqlite-storage")]
39pub struct SyncSqliteBackend {
40    inner: super::sqlite::SqliteBackend,
41}
42
43#[cfg(feature = "sqlite-storage")]
44impl SyncSqliteBackend {
45    /// Create or open a SQLite database at the given path
46    pub fn new(path: impl AsRef<std::path::Path>) -> Result<Self, StorageError> {
47        let inner = super::sqlite::SqliteBackend::new(path)?;
48        Ok(Self { inner })
49    }
50
51    /// Create an in-memory database (for testing)
52    pub fn in_memory() -> Result<Self, StorageError> {
53        let inner = super::sqlite::SqliteBackend::in_memory()?;
54        Ok(Self { inner })
55    }
56
57    /// Opt in to append-only writes; see
58    /// [`SqliteBackend::with_append_only`](super::sqlite::SqliteBackend::with_append_only).
59    pub fn with_append_only(mut self, append_only: bool) -> Self {
60        self.inner = self.inner.with_append_only(append_only);
61        self
62    }
63}
64
65#[cfg(feature = "sqlite-storage")]
66impl SyncStorageBackend for SyncSqliteBackend {
67    fn save(&self, snapshot: &Snapshot) -> Result<String, StorageError> {
68        self.inner.save_internal(snapshot)
69    }
70
71    fn save_decision(&self, decision: &DecisionSnapshot) -> Result<String, StorageError> {
72        self.inner.save_decision_internal(decision)
73    }
74
75    fn load(&self, snapshot_id: &str) -> Result<Snapshot, StorageError> {
76        self.inner.load_internal(snapshot_id)
77    }
78
79    fn load_decision(&self, decision_id: &str) -> Result<DecisionSnapshot, StorageError> {
80        let snapshot = self.load(decision_id)?;
81        if let Some(decision) = snapshot.decisions.first() {
82            Ok(decision.clone())
83        } else {
84            Err(StorageError::NotFound(format!(
85                "Decision {} not found",
86                decision_id
87            )))
88        }
89    }
90
91    fn query(&self, query: SnapshotQuery) -> Result<Vec<Snapshot>, StorageError> {
92        self.inner.query_internal(query)
93    }
94
95    fn delete(&self, snapshot_id: &str) -> Result<bool, StorageError> {
96        self.inner.delete_internal(snapshot_id)
97    }
98
99    fn flush(&self) -> Result<FlushResult, StorageError> {
100        let conn_guard = self.inner.lock_conn();
101
102        // Force WAL checkpoint; the pragma returns a status row
103        conn_guard
104            .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
105            .map_err(|e| {
106                StorageError::ConnectionError(format!("Failed to checkpoint WAL: {}", e))
107            })?;
108
109        // Get stats
110        let snapshot_count: i64 = conn_guard
111            .query_row("SELECT COUNT(*) FROM snapshots", [], |row| row.get(0))
112            .unwrap_or(0);
113
114        Ok(FlushResult {
115            snapshots_written: snapshot_count as usize,
116            bytes_written: 0, // SQLite doesn't easily report this
117            checkpoint_id: None,
118        })
119    }
120
121    fn health_check(&self) -> Result<bool, StorageError> {
122        let conn_guard = self.inner.lock_conn();
123
124        // Simple query to check connection
125        let _: i64 = conn_guard
126            .query_row("SELECT 1", [], |row| row.get(0))
127            .map_err(|e| StorageError::ConnectionError(format!("Health check failed: {}", e)))?;
128
129        Ok(true)
130    }
131}
132
133/// In-memory synchronous storage backend for simple use cases
134pub struct MemoryStorageBackend {
135    snapshots: std::sync::Mutex<HashMap<String, Snapshot>>,
136}
137
138impl MemoryStorageBackend {
139    /// Create a new in-memory storage backend
140    pub fn new() -> Self {
141        Self {
142            snapshots: std::sync::Mutex::new(HashMap::new()),
143        }
144    }
145
146    /// Every critical section is a single map operation, so the map is
147    /// consistent even if a holder panicked; recover instead of propagating
148    /// the poison as a panic.
149    fn lock_snapshots(&self) -> std::sync::MutexGuard<'_, HashMap<String, Snapshot>> {
150        self.snapshots
151            .lock()
152            .unwrap_or_else(std::sync::PoisonError::into_inner)
153    }
154}
155
156impl Default for MemoryStorageBackend {
157    fn default() -> Self {
158        Self::new()
159    }
160}
161
162impl SyncStorageBackend for MemoryStorageBackend {
163    fn save(&self, snapshot: &Snapshot) -> Result<String, StorageError> {
164        let snapshot_id = snapshot.metadata.snapshot_id.to_string();
165        let mut snapshots = self.lock_snapshots();
166        snapshots.insert(snapshot_id.clone(), snapshot.clone());
167        Ok(snapshot_id)
168    }
169
170    fn save_decision(&self, decision: &DecisionSnapshot) -> Result<String, StorageError> {
171        // For simplicity, save decisions as individual snapshots
172        let snapshot = Snapshot {
173            metadata: decision.metadata.clone(),
174            decisions: vec![decision.clone()],
175            snapshot_type: crate::models::SnapshotType::Decision,
176        };
177        self.save(&snapshot)
178    }
179
180    fn load(&self, snapshot_id: &str) -> Result<Snapshot, StorageError> {
181        let snapshots = self.lock_snapshots();
182        snapshots
183            .get(snapshot_id)
184            .cloned()
185            .ok_or_else(|| StorageError::NotFound(format!("Snapshot {} not found", snapshot_id)))
186    }
187
188    fn load_decision(&self, decision_id: &str) -> Result<DecisionSnapshot, StorageError> {
189        let snapshot = self.load(decision_id)?;
190        if let Some(decision) = snapshot.decisions.first() {
191            Ok(decision.clone())
192        } else {
193            Err(StorageError::NotFound(format!(
194                "Decision {} not found",
195                decision_id
196            )))
197        }
198    }
199
200    fn query(&self, query: SnapshotQuery) -> Result<Vec<Snapshot>, StorageError> {
201        let snapshots = self.lock_snapshots();
202        let mut results = Vec::new();
203
204        for snapshot in snapshots.values() {
205            if matches_query(snapshot, &query) {
206                results.push(snapshot.clone());
207            }
208        }
209
210        // Sort by timestamp (newest first)
211        results.sort_by_key(|b| std::cmp::Reverse(b.metadata.timestamp));
212
213        // Apply pagination
214        let offset = query.offset.unwrap_or(0);
215        let limit = query.limit.unwrap_or(usize::MAX);
216        let end = offset.saturating_add(limit).min(results.len());
217
218        Ok(results.get(offset..end).unwrap_or(&[]).to_vec())
219    }
220
221    fn delete(&self, snapshot_id: &str) -> Result<bool, StorageError> {
222        let mut snapshots = self.lock_snapshots();
223        Ok(snapshots.remove(snapshot_id).is_some())
224    }
225
226    fn flush(&self) -> Result<FlushResult, StorageError> {
227        let snapshots = self.lock_snapshots();
228        Ok(FlushResult {
229            snapshots_written: snapshots.len(),
230            bytes_written: 0, // Not meaningful for in-memory
231            checkpoint_id: None,
232        })
233    }
234
235    fn health_check(&self) -> Result<bool, StorageError> {
236        // Always healthy for in-memory backend
237        Ok(true)
238    }
239}
240
241/// Check if a snapshot matches query filters
242fn matches_query(snapshot: &Snapshot, query: &SnapshotQuery) -> bool {
243    // Check time range
244    if let Some(start_time) = query.start_time {
245        if snapshot.metadata.timestamp < start_time {
246            return false;
247        }
248    }
249
250    if let Some(end_time) = query.end_time {
251        if snapshot.metadata.timestamp > end_time {
252            return false;
253        }
254    }
255
256    // Check content filters
257    if query.function_name.is_some()
258        || query.module_name.is_some()
259        || query.model_name.is_some()
260        || query.tags.is_some()
261    {
262        for decision in &snapshot.decisions {
263            if let Some(function_name) = &query.function_name {
264                if decision.function_name != *function_name {
265                    continue;
266                }
267            }
268
269            if let Some(module_name) = &query.module_name {
270                if decision.module_name.as_ref() != Some(module_name) {
271                    continue;
272                }
273            }
274
275            if let Some(model_name) = &query.model_name {
276                if let Some(model_params) = &decision.model_parameters {
277                    if model_params.model_name != *model_name {
278                        continue;
279                    }
280                } else {
281                    continue;
282                }
283            }
284
285            if let Some(query_tags) = &query.tags {
286                let mut all_tags_match = true;
287                for (key, value) in query_tags {
288                    if decision.tags.get(key) != Some(value) {
289                        all_tags_match = false;
290                        break;
291                    }
292                }
293                if !all_tags_match {
294                    continue;
295                }
296            }
297
298            // If we get here, this decision matches all filters
299            return true;
300        }
301
302        // No decisions matched the filters
303        false
304    } else {
305        // No content filters, so it matches
306        true
307    }
308}
309
310#[cfg(test)]
311mod tests {
312    use super::*;
313    use crate::models::*;
314    use serde_json::json;
315
316    fn create_test_snapshot() -> Snapshot {
317        let input = Input::new("test_input", json!("value"), "string");
318        let output = Output::new("test_output", json!("result"), "string");
319        let model_params = ModelParameters::new("gpt-4");
320
321        let decision = DecisionSnapshot::new("test_function")
322            .with_module("test_module")
323            .add_input(input)
324            .add_output(output)
325            .with_model_parameters(model_params)
326            .add_tag("env", "test");
327
328        let mut snapshot = Snapshot::new(SnapshotType::Session);
329        snapshot.add_decision(decision);
330        snapshot
331    }
332
333    #[test]
334    fn test_memory_backend_basic_operations() {
335        let backend = MemoryStorageBackend::new();
336        let snapshot = create_test_snapshot();
337
338        // Save and load
339        let snapshot_id = backend.save(&snapshot).unwrap();
340        let loaded_snapshot = backend.load(&snapshot_id).unwrap();
341
342        assert_eq!(snapshot.decisions.len(), loaded_snapshot.decisions.len());
343        assert_eq!(snapshot.snapshot_type, loaded_snapshot.snapshot_type);
344
345        // Health check
346        assert!(backend.health_check().unwrap());
347
348        // Delete
349        assert!(backend.delete(&snapshot_id).unwrap());
350
351        // Should not find deleted snapshot
352        let result = backend.load(&snapshot_id);
353        assert!(matches!(result, Err(StorageError::NotFound(_))));
354    }
355
356    #[test]
357    fn test_memory_backend_query_by_function_name() {
358        let backend = MemoryStorageBackend::new();
359        let snapshot = create_test_snapshot();
360        backend.save(&snapshot).unwrap();
361
362        let query = SnapshotQuery::new().with_function_name("test_function");
363        let results = backend.query(query).unwrap();
364
365        assert_eq!(results.len(), 1);
366        assert_eq!(results[0].decisions[0].function_name, "test_function");
367    }
368
369    #[test]
370    fn test_memory_backend_query_offset_without_limit() {
371        let backend = MemoryStorageBackend::new();
372        for _ in 0..3 {
373            backend.save(&create_test_snapshot()).unwrap();
374        }
375
376        let query = SnapshotQuery::new().with_offset(1);
377        let results = backend.query(query).unwrap();
378        assert_eq!(results.len(), 2);
379
380        let query = SnapshotQuery::new().with_offset(5);
381        let results = backend.query(query).unwrap();
382        assert_eq!(results.len(), 0);
383    }
384
385    #[cfg(feature = "sqlite-storage")]
386    #[test]
387    fn test_sync_sqlite_flush_on_file_db() {
388        let dir = tempfile::tempdir().unwrap();
389        let backend = SyncSqliteBackend::new(dir.path().join("test.db")).unwrap();
390        backend.save(&create_test_snapshot()).unwrap();
391
392        let result = backend.flush().unwrap();
393        assert_eq!(result.snapshots_written, 1);
394    }
395
396    #[cfg(feature = "sqlite-storage")]
397    #[test]
398    fn test_sync_sqlite_backend() {
399        let backend = SyncSqliteBackend::in_memory().unwrap();
400        let snapshot = create_test_snapshot();
401
402        // Save and load
403        let snapshot_id = backend.save(&snapshot).unwrap();
404        let loaded_snapshot = backend.load(&snapshot_id).unwrap();
405
406        assert_eq!(snapshot.decisions.len(), loaded_snapshot.decisions.len());
407        assert_eq!(snapshot.snapshot_type, loaded_snapshot.snapshot_type);
408
409        // Health check
410        assert!(backend.health_check().unwrap());
411
412        // Delete
413        assert!(backend.delete(&snapshot_id).unwrap());
414
415        // Should not find deleted snapshot
416        let result = backend.load(&snapshot_id);
417        assert!(matches!(result, Err(StorageError::NotFound(_))));
418    }
419}