Skip to main content

briefcase_core/storage/
mod.rs

1use crate::models::{DecisionSnapshot, Snapshot};
2#[cfg(feature = "async")]
3use async_trait::async_trait;
4use chrono::{DateTime, Utc};
5use std::collections::HashMap;
6use thiserror::Error;
7
8pub mod buffered;
9#[cfg(feature = "sqlite-storage")]
10pub mod sqlite;
11pub mod sync;
12#[cfg(feature = "vcs-storage")]
13pub mod vcs;
14
15#[cfg(feature = "sqlite-storage")]
16pub use sqlite::SqliteBackend;
17#[cfg(feature = "sqlite-storage")]
18pub use sync::SyncSqliteBackend;
19pub use sync::{MemoryStorageBackend, SyncStorageBackend};
20
21/// Persistence contract for snapshots and decisions. Backends store payloads
22/// verbatim; PII sanitization is the capture layer's responsibility and runs
23/// before data reaches a backend.
24#[cfg(feature = "async")]
25#[async_trait]
26pub trait StorageBackend: Send + Sync {
27    /// Save a snapshot, return its ID
28    async fn save(&self, snapshot: &Snapshot) -> Result<String, StorageError>;
29
30    /// Save a single decision snapshot
31    async fn save_decision(&self, decision: &DecisionSnapshot) -> Result<String, StorageError>;
32
33    /// Load a snapshot by ID
34    async fn load(&self, snapshot_id: &str) -> Result<Snapshot, StorageError>;
35
36    /// Load a decision by ID
37    async fn load_decision(&self, decision_id: &str) -> Result<DecisionSnapshot, StorageError>;
38
39    /// Query snapshots with filters
40    async fn query(&self, query: SnapshotQuery) -> Result<Vec<Snapshot>, StorageError>;
41
42    /// Delete a snapshot
43    async fn delete(&self, snapshot_id: &str) -> Result<bool, StorageError>;
44
45    /// Flush pending writes (for batching backends)
46    async fn flush(&self) -> Result<FlushResult, StorageError>;
47
48    /// Check health/connectivity
49    async fn health_check(&self) -> Result<bool, StorageError>;
50}
51
52#[derive(Debug, Clone, Default)]
53pub struct SnapshotQuery {
54    pub function_name: Option<String>,
55    pub module_name: Option<String>,
56    pub model_name: Option<String>,
57    pub start_time: Option<DateTime<Utc>>,
58    pub end_time: Option<DateTime<Utc>>,
59    pub tags: Option<HashMap<String, String>>,
60    pub limit: Option<usize>,
61    pub offset: Option<usize>,
62}
63
64impl SnapshotQuery {
65    pub fn new() -> Self {
66        Self::default()
67    }
68
69    pub fn with_function_name(mut self, function_name: impl Into<String>) -> Self {
70        self.function_name = Some(function_name.into());
71        self
72    }
73
74    pub fn with_module_name(mut self, module_name: impl Into<String>) -> Self {
75        self.module_name = Some(module_name.into());
76        self
77    }
78
79    pub fn with_model_name(mut self, model_name: impl Into<String>) -> Self {
80        self.model_name = Some(model_name.into());
81        self
82    }
83
84    pub fn with_time_range(mut self, start: DateTime<Utc>, end: DateTime<Utc>) -> Self {
85        self.start_time = Some(start);
86        self.end_time = Some(end);
87        self
88    }
89
90    pub fn with_tag(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
91        if self.tags.is_none() {
92            self.tags = Some(HashMap::new());
93        }
94        self.tags.as_mut().unwrap().insert(key.into(), value.into());
95        self
96    }
97
98    pub fn with_limit(mut self, limit: usize) -> Self {
99        self.limit = Some(limit);
100        self
101    }
102
103    pub fn with_offset(mut self, offset: usize) -> Self {
104        self.offset = Some(offset);
105        self
106    }
107}
108
109#[derive(Debug, Clone)]
110pub struct FlushResult {
111    pub snapshots_written: usize,
112    pub bytes_written: usize,
113    pub checkpoint_id: Option<String>,
114}
115
116#[derive(Error, Debug, Clone, PartialEq)]
117pub enum StorageError {
118    #[error("Not found: {0}")]
119    NotFound(String),
120    #[error("Connection error: {0}")]
121    ConnectionError(String),
122    #[error("Serialization error: {0}")]
123    SerializationError(String),
124    #[error("Permission denied: {0}")]
125    PermissionDenied(String),
126    #[error("Quota exceeded")]
127    QuotaExceeded,
128    #[error("Invalid query: {0}")]
129    InvalidQuery(String),
130    #[error("IO error: {0}")]
131    IoError(String),
132}
133
134impl From<serde_json::Error> for StorageError {
135    fn from(err: serde_json::Error) -> Self {
136        StorageError::SerializationError(err.to_string())
137    }
138}
139
140impl From<std::io::Error> for StorageError {
141    fn from(err: std::io::Error) -> Self {
142        StorageError::IoError(err.to_string())
143    }
144}