Skip to main content

briefcase_core/storage/
buffered.rs

1//! Storage backend that groups decision writes into batches.
2//!
3//! Decisions accumulate in memory until the batch is full or [`flush`] is
4//! called, then go to the wrapped backend in one `save_decisions` round trip.
5//! Reads see pending decisions: `load_decision` consults the buffer first, and
6//! `load`/`query` write the buffer through before reading, so an id returned
7//! by `save_decision` resolves immediately and queries never miss it.
8//!
9//! Buffering trades durability for throughput: decisions that have not been
10//! flushed live only in memory and are lost if the process dies. Call
11//! [`flush`] before exit, or construct with `buffer_size` 1 to write through.
12//!
13//! [`flush`]: BufferedBackend::flush
14
15use crate::models::{DecisionSnapshot, Snapshot};
16use crate::storage::{FlushResult, SnapshotQuery, StorageBackend, StorageError};
17use async_trait::async_trait;
18use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
19
20pub struct BufferedBackend {
21    inner: Arc<dyn StorageBackend>,
22    batch_size: usize,
23    pending: Mutex<Vec<DecisionSnapshot>>,
24}
25
26impl BufferedBackend {
27    /// Wrap `inner`, writing through once `batch_size` decisions accumulate.
28    /// A `batch_size` of 0 or 1 disables buffering.
29    pub fn new(inner: Arc<dyn StorageBackend>, batch_size: usize) -> Self {
30        Self {
31            inner,
32            batch_size: batch_size.max(1),
33            pending: Mutex::new(Vec::new()),
34        }
35    }
36
37    /// Every critical section leaves the buffer consistent, so a poisoned
38    /// lock is recovered rather than propagated as a panic.
39    fn lock_pending(&self) -> MutexGuard<'_, Vec<DecisionSnapshot>> {
40        self.pending.lock().unwrap_or_else(PoisonError::into_inner)
41    }
42
43    /// Decisions accepted but not yet written to the wrapped backend.
44    pub fn pending(&self) -> usize {
45        self.lock_pending().len()
46    }
47
48    /// The backend being buffered, for reads that should bypass the buffer.
49    pub fn inner(&self) -> &Arc<dyn StorageBackend> {
50        &self.inner
51    }
52
53    fn take_pending(&self) -> Vec<DecisionSnapshot> {
54        std::mem::take(&mut *self.lock_pending())
55    }
56
57    async fn write_batch(&self, batch: Vec<DecisionSnapshot>) -> Result<usize, StorageError> {
58        if batch.is_empty() {
59            return Ok(0);
60        }
61        match self.inner.save_decisions(&batch).await {
62            Ok(ids) => Ok(ids.len()),
63            Err(e) => {
64                // Put the batch back so the caller can retry rather than
65                // silently losing records to a transient backend failure.
66                let mut pending = self.lock_pending();
67                let mut restored = batch;
68                restored.append(&mut pending);
69                *pending = restored;
70                Err(e)
71            }
72        }
73    }
74}
75
76#[async_trait]
77impl StorageBackend for BufferedBackend {
78    /// Snapshots are not buffered; they go straight through.
79    async fn save(&self, snapshot: &Snapshot) -> Result<String, StorageError> {
80        self.inner.save(snapshot).await
81    }
82
83    /// Buffer the decision and return its id immediately. The id is the
84    /// decision's own snapshot id, so it is valid before the write lands.
85    async fn save_decision(&self, decision: &DecisionSnapshot) -> Result<String, StorageError> {
86        let id = decision.metadata.snapshot_id.to_string();
87        let full = {
88            let mut pending = self.lock_pending();
89            pending.push(decision.clone());
90            pending.len() >= self.batch_size
91        };
92        if full {
93            let batch = self.take_pending();
94            self.write_batch(batch).await?;
95        }
96        Ok(id)
97    }
98
99    async fn save_decisions(
100        &self,
101        decisions: &[DecisionSnapshot],
102    ) -> Result<Vec<String>, StorageError> {
103        self.inner.save_decisions(decisions).await
104    }
105
106    /// Pending decisions are written through first, so a decision saved a
107    /// moment ago is loadable as a snapshot like any flushed one.
108    async fn load(&self, id: &str) -> Result<Snapshot, StorageError> {
109        let batch = self.take_pending();
110        self.write_batch(batch).await?;
111        self.inner.load(id).await
112    }
113
114    async fn load_decision(&self, id: &str) -> Result<DecisionSnapshot, StorageError> {
115        let buffered = {
116            let pending = self.lock_pending();
117            pending
118                .iter()
119                .find(|d| d.metadata.snapshot_id.to_string() == id)
120                .cloned()
121        };
122        match buffered {
123            Some(decision) => Ok(decision),
124            None => self.inner.load_decision(id).await,
125        }
126    }
127
128    /// Pending decisions are written through before the query runs, so the
129    /// wrapped backend's filtering, ordering and pagination apply to them too.
130    async fn query(&self, q: SnapshotQuery) -> Result<Vec<Snapshot>, StorageError> {
131        let batch = self.take_pending();
132        self.write_batch(batch).await?;
133        self.inner.query(q).await
134    }
135
136    async fn delete(&self, id: &str) -> Result<bool, StorageError> {
137        self.lock_pending()
138            .retain(|d| d.metadata.snapshot_id.to_string() != id);
139        self.inner.delete(id).await
140    }
141
142    /// Write everything pending, then flush the wrapped backend.
143    ///
144    /// `snapshots_written` counts the decisions this call wrote. Backends
145    /// report their own totals there (`SqliteBackend` returns the table's row
146    /// count), so the inner figure is deliberately not carried through.
147    async fn flush(&self) -> Result<FlushResult, StorageError> {
148        let batch = self.take_pending();
149        let written = self.write_batch(batch).await?;
150        let inner = self.inner.flush().await?;
151        Ok(FlushResult {
152            snapshots_written: written,
153            bytes_written: inner.bytes_written,
154            checkpoint_id: inner.checkpoint_id,
155        })
156    }
157
158    async fn health_check(&self) -> Result<bool, StorageError> {
159        self.inner.health_check().await
160    }
161}
162
163impl Drop for BufferedBackend {
164    fn drop(&mut self) {
165        // Drop cannot await, so the batch cannot be written here. Losing audit
166        // records in silence is worse than a line on stderr.
167        let pending = self.pending.lock().map(|p| p.len()).unwrap_or(0);
168        if pending > 0 {
169            eprintln!(
170                "briefcase: BufferedBackend dropped with {pending} unflushed decision(s); \
171                 call flush() before exit to persist them"
172            );
173        }
174    }
175}
176
177#[cfg(test)]
178mod tests {
179    use super::*;
180    use crate::models::Input;
181    use std::sync::atomic::{AtomicUsize, Ordering};
182
183    /// Counts how many times the wrapped backend was actually written to.
184    struct CountingBackend {
185        /// Calls that reached the backend, batched or not.
186        writes: AtomicUsize,
187        /// Decisions durably written across those calls.
188        decisions: AtomicUsize,
189    }
190
191    impl CountingBackend {
192        fn new() -> Self {
193            Self {
194                writes: AtomicUsize::new(0),
195                decisions: AtomicUsize::new(0),
196            }
197        }
198    }
199
200    #[async_trait]
201    impl StorageBackend for CountingBackend {
202        async fn save(&self, snapshot: &Snapshot) -> Result<String, StorageError> {
203            self.writes.fetch_add(1, Ordering::SeqCst);
204            self.decisions
205                .fetch_add(snapshot.decisions.len().max(1), Ordering::SeqCst);
206            Ok(snapshot.metadata.snapshot_id.to_string())
207        }
208        async fn save_decision(&self, decision: &DecisionSnapshot) -> Result<String, StorageError> {
209            self.writes.fetch_add(1, Ordering::SeqCst);
210            self.decisions.fetch_add(1, Ordering::SeqCst);
211            Ok(decision.metadata.snapshot_id.to_string())
212        }
213        async fn save_decisions(
214            &self,
215            decisions: &[DecisionSnapshot],
216        ) -> Result<Vec<String>, StorageError> {
217            // One call, however many decisions: that is what batching buys.
218            self.writes.fetch_add(1, Ordering::SeqCst);
219            self.decisions.fetch_add(decisions.len(), Ordering::SeqCst);
220            Ok(decisions
221                .iter()
222                .map(|d| d.metadata.snapshot_id.to_string())
223                .collect())
224        }
225        async fn load(&self, _id: &str) -> Result<Snapshot, StorageError> {
226            Err(StorageError::NotFound("load".into()))
227        }
228        async fn load_decision(&self, _id: &str) -> Result<DecisionSnapshot, StorageError> {
229            Err(StorageError::NotFound("load_decision".into()))
230        }
231        async fn query(&self, _q: SnapshotQuery) -> Result<Vec<Snapshot>, StorageError> {
232            Ok(Vec::new())
233        }
234        async fn delete(&self, _id: &str) -> Result<bool, StorageError> {
235            Ok(false)
236        }
237        async fn flush(&self) -> Result<FlushResult, StorageError> {
238            // Backends report their own totals here (SqliteBackend returns the
239            // whole table's row count), which must not be added to ours.
240            Ok(FlushResult {
241                snapshots_written: 99,
242                bytes_written: 0,
243                checkpoint_id: None,
244            })
245        }
246        async fn health_check(&self) -> Result<bool, StorageError> {
247            Ok(true)
248        }
249    }
250
251    fn decision(n: usize) -> DecisionSnapshot {
252        DecisionSnapshot::new(format!("f{n}")).add_input(Input::new(
253            "i",
254            serde_json::json!(n),
255            "int",
256        ))
257    }
258
259    #[tokio::test]
260    async fn buffers_writes_until_the_batch_is_full() {
261        let inner = Arc::new(CountingBackend::new());
262        let buffered = BufferedBackend::new(inner.clone(), 4);
263
264        for n in 0..3 {
265            buffered.save_decision(&decision(n)).await.unwrap();
266        }
267        assert_eq!(
268            inner.writes.load(Ordering::SeqCst),
269            0,
270            "three decisions under a batch size of four should still be buffered"
271        );
272
273        buffered.save_decision(&decision(3)).await.unwrap();
274        assert_eq!(
275            inner.writes.load(Ordering::SeqCst),
276            1,
277            "the fourth decision should trigger exactly one batched write"
278        );
279        assert_eq!(inner.decisions.load(Ordering::SeqCst), 4);
280    }
281
282    #[tokio::test]
283    async fn flush_writes_a_partial_batch() {
284        let inner = Arc::new(CountingBackend::new());
285        let buffered = BufferedBackend::new(inner.clone(), 100);
286
287        buffered.save_decision(&decision(0)).await.unwrap();
288        buffered.save_decision(&decision(1)).await.unwrap();
289        assert_eq!(inner.writes.load(Ordering::SeqCst), 0);
290
291        let result = buffered.flush().await.unwrap();
292        assert_eq!(
293            result.snapshots_written, 2,
294            "flush reports the decisions it wrote, not the backend's own tally"
295        );
296        assert_eq!(inner.decisions.load(Ordering::SeqCst), 2);
297    }
298
299    #[tokio::test]
300    async fn save_decision_returns_the_id_before_the_write_lands() {
301        let inner = Arc::new(CountingBackend::new());
302        let buffered = BufferedBackend::new(inner.clone(), 100);
303        let d = decision(0);
304        let expected = d.metadata.snapshot_id.to_string();
305
306        let returned = buffered.save_decision(&d).await.unwrap();
307
308        assert_eq!(
309            returned, expected,
310            "the caller needs a usable id immediately"
311        );
312        assert_eq!(inner.writes.load(Ordering::SeqCst), 0);
313    }
314
315    #[tokio::test]
316    async fn reads_see_buffered_decisions_before_they_are_flushed() {
317        let inner = Arc::new(CountingBackend::new());
318        let buffered = BufferedBackend::new(inner.clone(), 100);
319        let d = decision(7);
320        let id = buffered.save_decision(&d).await.unwrap();
321
322        // The wrapped backend cannot serve this yet, so the buffer must.
323        let loaded = buffered.load_decision(&id).await.unwrap();
324        assert_eq!(loaded.function_name, "f7");
325    }
326
327    #[cfg(feature = "sqlite-storage")]
328    #[tokio::test]
329    async fn query_and_load_see_unflushed_decisions() {
330        let inner = Arc::new(crate::storage::SqliteBackend::in_memory().unwrap());
331        let buffered = BufferedBackend::new(inner, 100);
332        let id = buffered.save_decision(&decision(1)).await.unwrap();
333        buffered.save_decision(&decision(2)).await.unwrap();
334
335        let found = buffered
336            .query(SnapshotQuery::new().with_function_name("f1"))
337            .await
338            .unwrap();
339        assert_eq!(found.len(), 1, "a pending decision must be queryable");
340        assert_eq!(buffered.query(SnapshotQuery::new()).await.unwrap().len(), 2);
341
342        let id3 = buffered.save_decision(&decision(3)).await.unwrap();
343        assert_eq!(buffered.load(&id3).await.unwrap().decisions.len(), 1);
344        assert!(buffered.load(&id).await.is_ok());
345    }
346
347    #[tokio::test]
348    async fn a_batch_size_of_one_writes_through() {
349        let inner = Arc::new(CountingBackend::new());
350        let buffered = BufferedBackend::new(inner.clone(), 1);
351        buffered.save_decision(&decision(0)).await.unwrap();
352        assert_eq!(
353            inner.decisions.load(Ordering::SeqCst),
354            1,
355            "buffer_size=1 must not defer anything"
356        );
357    }
358
359    #[tokio::test]
360    async fn pending_count_reports_unflushed_work() {
361        let inner = Arc::new(CountingBackend::new());
362        let buffered = BufferedBackend::new(inner.clone(), 100);
363        buffered.save_decision(&decision(0)).await.unwrap();
364        buffered.save_decision(&decision(1)).await.unwrap();
365        assert_eq!(buffered.pending(), 2);
366        buffered.flush().await.unwrap();
367        assert_eq!(buffered.pending(), 0);
368    }
369}