1use super::{FlushResult, SnapshotQuery, StorageError};
7use crate::models::{DecisionSnapshot, Snapshot};
8use std::collections::HashMap;
9
10pub trait SyncStorageBackend: Send + Sync {
12 fn save(&self, snapshot: &Snapshot) -> Result<String, StorageError>;
14
15 fn save_decision(&self, decision: &DecisionSnapshot) -> Result<String, StorageError>;
17
18 fn load(&self, snapshot_id: &str) -> Result<Snapshot, StorageError>;
20
21 fn load_decision(&self, decision_id: &str) -> Result<DecisionSnapshot, StorageError>;
23
24 fn query(&self, query: SnapshotQuery) -> Result<Vec<Snapshot>, StorageError>;
26
27 fn delete(&self, snapshot_id: &str) -> Result<bool, StorageError>;
29
30 fn flush(&self) -> Result<FlushResult, StorageError>;
32
33 fn health_check(&self) -> Result<bool, StorageError>;
35}
36
37#[cfg(feature = "sqlite-storage")]
39pub struct SyncSqliteBackend {
40 inner: super::sqlite::SqliteBackend,
41}
42
43#[cfg(feature = "sqlite-storage")]
44impl SyncSqliteBackend {
45 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 pub fn in_memory() -> Result<Self, StorageError> {
53 let inner = super::sqlite::SqliteBackend::in_memory()?;
54 Ok(Self { inner })
55 }
56}
57
58#[cfg(feature = "sqlite-storage")]
59impl SyncStorageBackend for SyncSqliteBackend {
60 fn save(&self, snapshot: &Snapshot) -> Result<String, StorageError> {
61 self.inner.save_internal(snapshot)
62 }
63
64 fn save_decision(&self, decision: &DecisionSnapshot) -> Result<String, StorageError> {
65 self.inner.save_decision_internal(decision)
66 }
67
68 fn load(&self, snapshot_id: &str) -> Result<Snapshot, StorageError> {
69 self.inner.load_internal(snapshot_id)
70 }
71
72 fn load_decision(&self, decision_id: &str) -> Result<DecisionSnapshot, StorageError> {
73 let snapshot = self.load(decision_id)?;
74 if let Some(decision) = snapshot.decisions.first() {
75 Ok(decision.clone())
76 } else {
77 Err(StorageError::NotFound(format!(
78 "Decision {} not found",
79 decision_id
80 )))
81 }
82 }
83
84 fn query(&self, query: SnapshotQuery) -> Result<Vec<Snapshot>, StorageError> {
85 self.inner.query_internal(query)
86 }
87
88 fn delete(&self, snapshot_id: &str) -> Result<bool, StorageError> {
89 let conn_guard = self.inner.conn.lock().unwrap();
90
91 let rows_affected = conn_guard
92 .execute(
93 "DELETE FROM snapshots WHERE id = ?",
94 rusqlite::params![snapshot_id],
95 )
96 .map_err(|e| {
97 StorageError::ConnectionError(format!("Failed to delete snapshot: {}", e))
98 })?;
99
100 Ok(rows_affected > 0)
101 }
102
103 fn flush(&self) -> Result<FlushResult, StorageError> {
104 let conn_guard = self.inner.conn.lock().unwrap();
105
106 conn_guard
108 .query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
109 .map_err(|e| {
110 StorageError::ConnectionError(format!("Failed to checkpoint WAL: {}", e))
111 })?;
112
113 let snapshot_count: i64 = conn_guard
115 .query_row("SELECT COUNT(*) FROM snapshots", [], |row| row.get(0))
116 .unwrap_or(0);
117
118 Ok(FlushResult {
119 snapshots_written: snapshot_count as usize,
120 bytes_written: 0, checkpoint_id: None,
122 })
123 }
124
125 fn health_check(&self) -> Result<bool, StorageError> {
126 let conn_guard = self.inner.conn.lock().unwrap();
127
128 let _: i64 = conn_guard
130 .query_row("SELECT 1", [], |row| row.get(0))
131 .map_err(|e| StorageError::ConnectionError(format!("Health check failed: {}", e)))?;
132
133 Ok(true)
134 }
135}
136
137pub struct MemoryStorageBackend {
139 snapshots: std::sync::Mutex<HashMap<String, Snapshot>>,
140}
141
142impl MemoryStorageBackend {
143 pub fn new() -> Self {
145 Self {
146 snapshots: std::sync::Mutex::new(HashMap::new()),
147 }
148 }
149}
150
151impl Default for MemoryStorageBackend {
152 fn default() -> Self {
153 Self::new()
154 }
155}
156
157impl SyncStorageBackend for MemoryStorageBackend {
158 fn save(&self, snapshot: &Snapshot) -> Result<String, StorageError> {
159 let snapshot_id = snapshot.metadata.snapshot_id.to_string();
160 let mut snapshots = self.snapshots.lock().unwrap();
161 snapshots.insert(snapshot_id.clone(), snapshot.clone());
162 Ok(snapshot_id)
163 }
164
165 fn save_decision(&self, decision: &DecisionSnapshot) -> Result<String, StorageError> {
166 let snapshot = Snapshot {
168 metadata: decision.metadata.clone(),
169 decisions: vec![decision.clone()],
170 snapshot_type: crate::models::SnapshotType::Decision,
171 };
172 self.save(&snapshot)
173 }
174
175 fn load(&self, snapshot_id: &str) -> Result<Snapshot, StorageError> {
176 let snapshots = self.snapshots.lock().unwrap();
177 snapshots
178 .get(snapshot_id)
179 .cloned()
180 .ok_or_else(|| StorageError::NotFound(format!("Snapshot {} not found", snapshot_id)))
181 }
182
183 fn load_decision(&self, decision_id: &str) -> Result<DecisionSnapshot, StorageError> {
184 let snapshot = self.load(decision_id)?;
185 if let Some(decision) = snapshot.decisions.first() {
186 Ok(decision.clone())
187 } else {
188 Err(StorageError::NotFound(format!(
189 "Decision {} not found",
190 decision_id
191 )))
192 }
193 }
194
195 fn query(&self, query: SnapshotQuery) -> Result<Vec<Snapshot>, StorageError> {
196 let snapshots = self.snapshots.lock().unwrap();
197 let mut results = Vec::new();
198
199 for snapshot in snapshots.values() {
200 if matches_query(snapshot, &query) {
201 results.push(snapshot.clone());
202 }
203 }
204
205 results.sort_by_key(|b| std::cmp::Reverse(b.metadata.timestamp));
207
208 let offset = query.offset.unwrap_or(0);
210 let limit = query.limit.unwrap_or(usize::MAX);
211 let end = offset.saturating_add(limit).min(results.len());
212
213 Ok(results.get(offset..end).unwrap_or(&[]).to_vec())
214 }
215
216 fn delete(&self, snapshot_id: &str) -> Result<bool, StorageError> {
217 let mut snapshots = self.snapshots.lock().unwrap();
218 Ok(snapshots.remove(snapshot_id).is_some())
219 }
220
221 fn flush(&self) -> Result<FlushResult, StorageError> {
222 let snapshots = self.snapshots.lock().unwrap();
223 Ok(FlushResult {
224 snapshots_written: snapshots.len(),
225 bytes_written: 0, checkpoint_id: None,
227 })
228 }
229
230 fn health_check(&self) -> Result<bool, StorageError> {
231 Ok(true)
233 }
234}
235
236fn matches_query(snapshot: &Snapshot, query: &SnapshotQuery) -> bool {
238 if let Some(start_time) = query.start_time {
240 if snapshot.metadata.timestamp < start_time {
241 return false;
242 }
243 }
244
245 if let Some(end_time) = query.end_time {
246 if snapshot.metadata.timestamp > end_time {
247 return false;
248 }
249 }
250
251 if query.function_name.is_some()
253 || query.module_name.is_some()
254 || query.model_name.is_some()
255 || query.tags.is_some()
256 {
257 for decision in &snapshot.decisions {
258 if let Some(function_name) = &query.function_name {
259 if decision.function_name != *function_name {
260 continue;
261 }
262 }
263
264 if let Some(module_name) = &query.module_name {
265 if decision.module_name.as_ref() != Some(module_name) {
266 continue;
267 }
268 }
269
270 if let Some(model_name) = &query.model_name {
271 if let Some(model_params) = &decision.model_parameters {
272 if model_params.model_name != *model_name {
273 continue;
274 }
275 } else {
276 continue;
277 }
278 }
279
280 if let Some(query_tags) = &query.tags {
281 let mut all_tags_match = true;
282 for (key, value) in query_tags {
283 if decision.tags.get(key) != Some(value) {
284 all_tags_match = false;
285 break;
286 }
287 }
288 if !all_tags_match {
289 continue;
290 }
291 }
292
293 return true;
295 }
296
297 false
299 } else {
300 true
302 }
303}
304
305#[cfg(test)]
306mod tests {
307 use super::*;
308 use crate::models::*;
309 use serde_json::json;
310
311 fn create_test_snapshot() -> Snapshot {
312 let input = Input::new("test_input", json!("value"), "string");
313 let output = Output::new("test_output", json!("result"), "string");
314 let model_params = ModelParameters::new("gpt-4");
315
316 let decision = DecisionSnapshot::new("test_function")
317 .with_module("test_module")
318 .add_input(input)
319 .add_output(output)
320 .with_model_parameters(model_params)
321 .add_tag("env", "test");
322
323 let mut snapshot = Snapshot::new(SnapshotType::Session);
324 snapshot.add_decision(decision);
325 snapshot
326 }
327
328 #[test]
329 fn test_memory_backend_basic_operations() {
330 let backend = MemoryStorageBackend::new();
331 let snapshot = create_test_snapshot();
332
333 let snapshot_id = backend.save(&snapshot).unwrap();
335 let loaded_snapshot = backend.load(&snapshot_id).unwrap();
336
337 assert_eq!(snapshot.decisions.len(), loaded_snapshot.decisions.len());
338 assert_eq!(snapshot.snapshot_type, loaded_snapshot.snapshot_type);
339
340 assert!(backend.health_check().unwrap());
342
343 assert!(backend.delete(&snapshot_id).unwrap());
345
346 let result = backend.load(&snapshot_id);
348 assert!(matches!(result, Err(StorageError::NotFound(_))));
349 }
350
351 #[test]
352 fn test_memory_backend_query_by_function_name() {
353 let backend = MemoryStorageBackend::new();
354 let snapshot = create_test_snapshot();
355 backend.save(&snapshot).unwrap();
356
357 let query = SnapshotQuery::new().with_function_name("test_function");
358 let results = backend.query(query).unwrap();
359
360 assert_eq!(results.len(), 1);
361 assert_eq!(results[0].decisions[0].function_name, "test_function");
362 }
363
364 #[test]
365 fn test_memory_backend_query_offset_without_limit() {
366 let backend = MemoryStorageBackend::new();
367 for _ in 0..3 {
368 backend.save(&create_test_snapshot()).unwrap();
369 }
370
371 let query = SnapshotQuery::new().with_offset(1);
372 let results = backend.query(query).unwrap();
373 assert_eq!(results.len(), 2);
374
375 let query = SnapshotQuery::new().with_offset(5);
376 let results = backend.query(query).unwrap();
377 assert_eq!(results.len(), 0);
378 }
379
380 #[cfg(feature = "sqlite-storage")]
381 #[test]
382 fn test_sync_sqlite_flush_on_file_db() {
383 let dir = tempfile::tempdir().unwrap();
384 let backend = SyncSqliteBackend::new(dir.path().join("test.db")).unwrap();
385 backend.save(&create_test_snapshot()).unwrap();
386
387 let result = backend.flush().unwrap();
388 assert_eq!(result.snapshots_written, 1);
389 }
390
391 #[cfg(feature = "sqlite-storage")]
392 #[test]
393 fn test_sync_sqlite_backend() {
394 let backend = SyncSqliteBackend::in_memory().unwrap();
395 let snapshot = create_test_snapshot();
396
397 let snapshot_id = backend.save(&snapshot).unwrap();
399 let loaded_snapshot = backend.load(&snapshot_id).unwrap();
400
401 assert_eq!(snapshot.decisions.len(), loaded_snapshot.decisions.len());
402 assert_eq!(snapshot.snapshot_type, loaded_snapshot.snapshot_type);
403
404 assert!(backend.health_check().unwrap());
406
407 assert!(backend.delete(&snapshot_id).unwrap());
409
410 let result = backend.load(&snapshot_id);
412 assert!(matches!(result, Err(StorageError::NotFound(_))));
413 }
414}