Skip to main content

logicaffeine_data/crdt/
delta_buffer.rs

1//! Delta Buffer - Ring buffer for recent deltas.
2//!
3//! Stores recent deltas for efficient sync with late joiners.
4
5use super::causal::VClock;
6use serde::{Deserialize, Serialize};
7use std::collections::VecDeque;
8
9/// A ring buffer that stores recent deltas along with their versions.
10///
11/// When a peer requests sync, we can provide deltas since their last known
12/// version. If the gap is too large (oldest delta evicted), the peer needs
13/// a full state transfer instead.
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct DeltaBuffer<D> {
16    /// Ring buffer of (version, delta) pairs
17    deltas: VecDeque<(VClock, D)>,
18    /// Maximum number of deltas to retain
19    max_size: usize,
20    /// The oldest version we can provide deltas from
21    oldest_version: VClock,
22}
23
24impl<D: Clone> DeltaBuffer<D> {
25    /// Create a new buffer with the given capacity.
26    pub fn new(max_size: usize) -> Self {
27        Self {
28            deltas: VecDeque::with_capacity(max_size),
29            max_size,
30            oldest_version: VClock::new(),
31        }
32    }
33
34    /// Push a new delta with its associated version.
35    pub fn push(&mut self, version: VClock, delta: D) {
36        if self.deltas.len() >= self.max_size {
37            if let Some((old_version, _)) = self.deltas.pop_front() {
38                self.oldest_version = old_version;
39            }
40        }
41        self.deltas.push_back((version, delta));
42    }
43
44    /// Get all deltas since the given version.
45    ///
46    /// Returns `None` if the version is older than or equal to our oldest evicted delta.
47    /// Returns `Some(vec![])` if the peer is up-to-date.
48    pub fn deltas_since(&self, version: &VClock) -> Option<Vec<D>> {
49        // If we've evicted deltas and the peer is at or behind what we evicted,
50        // we can't help them catch up (they need the evicted delta).
51        if self.oldest_version != VClock::new() && self.oldest_version.dominates(version) {
52            return None;
53        }
54
55        // Return deltas that the peer hasn't seen
56        let result: Vec<D> = self
57            .deltas
58            .iter()
59            .filter(|(v, _)| !version.dominates(v))
60            .map(|(_, d)| d.clone())
61            .collect();
62
63        Some(result)
64    }
65
66    /// Check if we can provide deltas since the given version.
67    pub fn can_serve(&self, version: &VClock) -> bool {
68        self.deltas_since(version).is_some()
69    }
70
71    /// Get the number of deltas currently stored.
72    pub fn len(&self) -> usize {
73        self.deltas.len()
74    }
75
76    /// Check if the buffer is empty.
77    pub fn is_empty(&self) -> bool {
78        self.deltas.is_empty()
79    }
80}
81
82#[cfg(test)]
83#[path = "../../../logicaffeine_tests/unit/logicaffeine_data/crdt/delta_buffer/tests.rs"]
84mod tests;