Skip to main content

weirdnet_sync/
log.rs

1//! Append-only per-node op log. A device never rewrites another node's entries.
2use crate::hlc::{Hlc, NodeId};
3use crate::protocol::PAGE_MAX;
4use serde::{Deserialize, Serialize};
5use std::collections::{BTreeMap, HashMap};
6
7/// One mutation in some node's log. `op` is the application's encoding; unknown `typ`
8/// values are stored and skipped by the application so a newer device can talk to an older one.
9#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
10pub struct LogEntry {
11    pub node_id: NodeId,
12    pub seq: u64,
13    pub hlc: Hlc,
14    pub typ: String,
15    pub record_id: String,
16    #[serde(with = "serde_bytes")]
17    pub op: Vec<u8>,
18}
19
20mod serde_bytes {
21    pub use crate::bytes::{deserialize, serialize};
22}
23
24/// A slice of one node's log, as sent in a `Page`.
25#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
26pub struct Page {
27    pub node_id: NodeId,
28    pub from_seq: u64,
29    pub to_seq: u64,
30    pub ops: Vec<LogEntry>,
31}
32
33/// In-memory log and peer cursors (the last seq applied from each peer, including ourselves).
34#[derive(Debug, Default, Clone)]
35pub struct OpLog {
36    entries: BTreeMap<(String, u64), LogEntry>,
37    /// Next seq this node will assign.
38    next: HashMap<String, u64>,
39    /// Last seq applied from each peer.
40    cursors: HashMap<String, u64>,
41    /// Per (node, type): every op of that type with `seq <=` this is applied.
42    type_cursors: HashMap<(String, String), u64>,
43}
44
45impl OpLog {
46    pub fn new() -> Self {
47        Self::default()
48    }
49
50    pub fn next_seq(&self, node: &NodeId) -> u64 {
51        self.next.get(&node.0).copied().unwrap_or(1)
52    }
53
54    pub fn cursor(&self, node: &NodeId) -> u64 {
55        self.cursors.get(&node.0).copied().unwrap_or(0)
56    }
57
58    pub fn cursors(&self) -> HashMap<NodeId, u64> {
59        self.cursors.iter().map(|(k, v)| (NodeId(k.clone()), *v)).collect()
60    }
61
62    pub fn set_cursor(&mut self, node: &NodeId, last_seq: u64) {
63        self.cursors.insert(node.0.clone(), last_seq);
64    }
65
66    /// How far this log holds every op of `typ` from `node`: the explicit
67    /// per-type cursor, or the contiguous prefix of `node`'s entries (all
68    /// types), whichever is further. A pull of one type resumes from here.
69    pub fn cursor_for(&self, node: &NodeId, typ: &str) -> u64 {
70        let explicit = self.type_cursors.get(&(node.0.clone(), typ.to_string())).copied().unwrap_or(0);
71        explicit.max(self.contiguous(node))
72    }
73
74    pub fn set_cursor_for(&mut self, node: &NodeId, typ: &str, last_seq: u64) {
75        self.type_cursors.insert((node.0.clone(), typ.to_string()), last_seq);
76    }
77
78    /// Per-type cursors, for an application to persist next to [`OpLog::cursors`].
79    pub fn type_cursors(&self) -> HashMap<(NodeId, String), u64> {
80        self.type_cursors.iter().map(|((n, t), v)| ((NodeId(n.clone()), t.clone()), *v)).collect()
81    }
82
83    /// Highest `k` such that every seq `1..=k` of `node` is held.
84    pub fn contiguous(&self, node: &NodeId) -> u64 {
85        let mut k = 0;
86        for e in self.iter_node(node) {
87            if e.seq != k + 1 {
88                break;
89            }
90            k = e.seq;
91        }
92        k
93    }
94
95    /// The newest HLC held from any node.
96    pub fn newest_hlc(&self) -> Option<&Hlc> {
97        self.entries.values().map(|e| &e.hlc).max_by(|a, b| a.cmp_total(b))
98    }
99
100    /// Ops of `typ` from `node` with `after_seq < seq <= known_to`, up to `limit` ops and
101    /// [`PAGE_MAX`] bytes. Missing seqs in that range are other types and are skipped, so
102    /// `known_to` must be [`OpLog::cursor_for`] (or less). `to_seq` is the last seq walked,
103    /// which may be past the last op returned; a puller resumes after it.
104    pub fn page_of_type(&self, node: &NodeId, typ: &str, after_seq: u64, known_to: u64, limit: usize) -> Page {
105        let mut ops = Vec::new();
106        let mut bytes = 0usize;
107        let mut to_seq = after_seq;
108        if known_to > after_seq {
109            let mut full = false;
110            for (_, e) in self.entries.range((node.0.clone(), after_seq + 1)..=(node.0.clone(), known_to)) {
111                if e.typ == typ {
112                    let add = 64 + e.typ.len() + e.record_id.len() + e.op.len();
113                    if !ops.is_empty() && (ops.len() >= limit || bytes + add > PAGE_MAX) {
114                        full = true;
115                        break;
116                    }
117                    bytes += add;
118                    ops.push(e.clone());
119                }
120                to_seq = e.seq;
121            }
122            if !full {
123                to_seq = known_to;
124            }
125        }
126        let from_seq = ops.first().map(|e| e.seq).unwrap_or(after_seq);
127        Page { node_id: node.clone(), from_seq, to_seq, ops }
128    }
129
130    /// Append a local mutation. `seq` is assigned here.
131    pub fn append(&mut self, node: NodeId, hlc: Hlc, typ: impl Into<String>, record_id: impl Into<String>, op: Vec<u8>) -> &LogEntry {
132        let seq = self.next_seq(&node);
133        let entry = LogEntry { node_id: node.clone(), seq, hlc, typ: typ.into(), record_id: record_id.into(), op };
134        self.entries.insert((node.0.clone(), seq), entry);
135        self.next.insert(node.0.clone(), seq + 1);
136        self.cursors.insert(node.0.clone(), seq);
137        self.entries.get(&(node.0, seq)).expect("just inserted")
138    }
139
140    pub fn get(&self, node: &NodeId, seq: u64) -> Option<&LogEntry> {
141        self.entries.get(&(node.0.clone(), seq))
142    }
143
144    pub fn len(&self) -> usize {
145        self.entries.len()
146    }
147
148    pub fn is_empty(&self) -> bool {
149        self.entries.is_empty()
150    }
151
152    /// Entries of `node` with `seq > after_seq`, up to `limit` and [`PAGE_MAX`] encoded bytes.
153    pub fn page(&self, node: &NodeId, after_seq: u64, limit: usize) -> Page {
154        let mut ops = Vec::new();
155        let mut bytes = 0usize;
156        for seq in (after_seq + 1).. {
157            let Some(e) = self.entries.get(&(node.0.clone(), seq)) else { break };
158            let add = 64 + e.typ.len() + e.record_id.len() + e.op.len();
159            if !ops.is_empty() && (ops.len() >= limit || bytes + add > PAGE_MAX) {
160                break;
161            }
162            if add > PAGE_MAX && ops.is_empty() {
163                // A single oversized op still goes out: the app must not write one this large,
164                // but dropping it would stall the cursor.
165                ops.push(e.clone());
166                break;
167            }
168            bytes += add;
169            ops.push(e.clone());
170            if ops.len() >= limit {
171                break;
172            }
173        }
174        let from_seq = ops.first().map(|e| e.seq).unwrap_or(after_seq);
175        let to_seq = ops.last().map(|e| e.seq).unwrap_or(after_seq);
176        Page { node_id: node.clone(), from_seq, to_seq, ops }
177    }
178
179    /// Integrate a remote page. Existing entries of that node are left untouched; gaps are
180    /// accepted and later pages fill them. Returns how many new entries were stored.
181    pub fn integrate(&mut self, page: &Page) -> usize {
182        let mut added = 0;
183        for e in &page.ops {
184            if e.node_id != page.node_id {
185                continue;
186            }
187            let key = (e.node_id.0.clone(), e.seq);
188            if self.entries.contains_key(&key) {
189                continue;
190            }
191            self.entries.insert(key, e.clone());
192            added += 1;
193            let next = self.next.entry(e.node_id.0.clone()).or_insert(1);
194            if e.seq + 1 > *next {
195                *next = e.seq + 1;
196            }
197        }
198        added
199    }
200
201    pub fn iter_node(&self, node: &NodeId) -> impl Iterator<Item = &LogEntry> {
202        let prefix = node.0.clone();
203        self.entries.range((prefix.clone(), 0)..(prefix.clone(), u64::MAX)).filter(move |((n, _), _)| *n == prefix).map(|(_, e)| e)
204    }
205}
206
207// Range with String and u64 is fine; (prefix, u64::MAX) includes seq MAX. Good.
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212
213    fn n(s: &str) -> NodeId {
214        NodeId::new(s)
215    }
216
217    fn h(ms: u64, node: &str) -> Hlc {
218        Hlc::new(ms, 0, n(node))
219    }
220
221    #[test]
222    fn append_assigns_seq_and_never_rewrites_a_peer() {
223        let mut log = OpLog::new();
224        let a1 = log.append(n("a"), h(1, "a"), "bookmarks", "r1", b"add".to_vec()).clone();
225        let a2 = log.append(n("a"), h(2, "a"), "bookmarks", "r1", b"edit".to_vec()).clone();
226        assert_eq!(a1.seq, 1);
227        assert_eq!(a2.seq, 2);
228        let remote = Page {
229            node_id: n("b"),
230            from_seq: 1,
231            to_seq: 1,
232            ops: vec![LogEntry { node_id: n("b"), seq: 1, hlc: h(3, "b"), typ: "bookmarks".into(), record_id: "r2".into(), op: b"x".to_vec() }],
233        };
234        assert_eq!(log.integrate(&remote), 1);
235        assert_eq!(log.integrate(&remote), 0);
236        assert_eq!(log.get(&n("a"), 1).unwrap().op, b"add");
237        assert_eq!(log.len(), 3);
238    }
239
240    #[test]
241    fn typed_pages_skip_other_types_and_resume_past_them() {
242        let mut log = OpLog::new();
243        log.append(n("a"), h(1, "a"), "bookmarks", "b1", vec![1]);
244        log.append(n("a"), h(2, "a"), "history", "v1", vec![2]);
245        log.append(n("a"), h(3, "a"), "bookmarks", "b2", vec![3]);
246        log.append(n("a"), h(4, "a"), "history", "v2", vec![4]);
247        log.append(n("a"), h(5, "a"), "bookmarks", "b3", vec![5]);
248        let known = log.cursor_for(&n("a"), "history");
249        assert_eq!(known, 5, "an authored stream is contiguous");
250        let p = log.page_of_type(&n("a"), "history", 0, known, 1);
251        assert_eq!(p.ops.iter().map(|e| e.seq).collect::<Vec<_>>(), [2]);
252        assert_eq!(p.to_seq, 3, "stops before the next op of the type that did not fit");
253        let p = log.page_of_type(&n("a"), "history", p.to_seq, known, 10);
254        assert_eq!(p.ops.iter().map(|e| e.seq).collect::<Vec<_>>(), [4]);
255        assert_eq!(p.to_seq, 5, "walks past trailing ops of other types");
256        let p = log.page_of_type(&n("a"), "history", 5, known, 10);
257        assert!(p.ops.is_empty());
258        assert_eq!(p.to_seq, 5);
259    }
260
261    #[test]
262    fn a_relayed_stream_is_served_only_as_far_as_it_is_known() {
263        let mut log = OpLog::new();
264        // We hold a's bookmarks 1 and 3 but not history 2 (never pulled).
265        let e = |seq, typ: &str| LogEntry { node_id: n("a"), seq, hlc: h(seq, "a"), typ: typ.into(), record_id: format!("r{seq}"), op: vec![] };
266        log.integrate(&Page { node_id: n("a"), from_seq: 1, to_seq: 3, ops: vec![e(1, "bookmarks"), e(3, "bookmarks")] });
267        assert_eq!(log.contiguous(&n("a")), 1);
268        assert_eq!(log.cursor_for(&n("a"), "history"), 1, "history 2 is unknown, not absent");
269        log.set_cursor_for(&n("a"), "bookmarks", 3);
270        assert_eq!(log.cursor_for(&n("a"), "bookmarks"), 3);
271        let p = log.page_of_type(&n("a"), "bookmarks", 0, 3, 10);
272        assert_eq!(p.ops.len(), 2);
273        assert_eq!(p.to_seq, 3);
274        assert!(log.page_of_type(&n("a"), "history", 0, log.cursor_for(&n("a"), "history"), 10).ops.is_empty());
275        assert_eq!(log.type_cursors().len(), 1);
276        assert_eq!(log.newest_hlc().unwrap().physical_ms, 3);
277    }
278
279    #[test]
280    fn page_starts_after_the_cursor_and_respects_limit() {
281        let mut log = OpLog::new();
282        for i in 0..5 {
283            log.append(n("a"), h(i, "a"), "bookmarks", format!("r{i}"), vec![i as u8]);
284        }
285        let p = log.page(&n("a"), 2, 2);
286        assert_eq!(p.from_seq, 3);
287        assert_eq!(p.to_seq, 4);
288        assert_eq!(p.ops.len(), 2);
289        let empty = log.page(&n("a"), 5, 10);
290        assert!(empty.ops.is_empty());
291        assert_eq!(empty.to_seq, 5);
292    }
293}