Skip to main content

briefcase_core/storage/
mod.rs

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