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