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_BUDGET;
4use crate::record::{Value, is_chunk_type};
5use serde::{Deserialize, Serialize};
6use std::collections::{BTreeMap, BTreeSet, HashMap};
7
8/// One mutation in some node's log. `op` is the application's encoding; unknown `typ`
9/// values are stored and skipped by the application so a newer device can talk to an older one.
10#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
11pub struct LogEntry {
12    pub node_id: NodeId,
13    pub seq: u64,
14    pub hlc: Hlc,
15    pub typ: String,
16    pub record_id: String,
17    #[serde(with = "serde_bytes")]
18    pub op: Vec<u8>,
19    /// The full value when `op` is only a fallback (chunked or sealed; see
20    /// [`crate::record`]). Absent before 0.4, and dropped by older peers.
21    #[serde(default, skip_serializing_if = "Option::is_none")]
22    pub value: Option<Value>,
23}
24
25impl LogEntry {
26    /// Rough encoded size, for page budgeting.
27    pub fn wire_size(&self) -> usize {
28        64 + self.typ.len() + self.record_id.len() + self.op.len() + self.value.as_ref().map_or(0, Value::wire_size)
29    }
30}
31
32mod serde_bytes {
33    pub use crate::bytes::{deserialize, serialize};
34}
35
36/// A slice of one node's log, as sent in a `Page`.
37#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
38pub struct Page {
39    pub node_id: NodeId,
40    pub from_seq: u64,
41    pub to_seq: u64,
42    pub ops: Vec<LogEntry>,
43}
44
45/// In-memory log and peer cursors (the last seq applied from each peer, including ourselves).
46#[derive(Debug, Default, Clone)]
47pub struct OpLog {
48    entries: BTreeMap<(String, u64), LogEntry>,
49    /// Next seq this node will assign.
50    next: HashMap<String, u64>,
51    /// Last seq applied from each peer.
52    cursors: HashMap<String, u64>,
53    /// Per (node, type): every op of that type with `seq <=` this is applied.
54    type_cursors: HashMap<(String, String), u64>,
55    /// Chunk entries by (chunk type, hex hash).
56    chunk_index: HashMap<(String, String), Vec<(String, u64)>>,
57    /// Entries whose value is chunked, by type.
58    blobs: HashMap<String, BTreeSet<(String, u64)>>,
59}
60
61impl OpLog {
62    pub fn new() -> Self {
63        Self::default()
64    }
65
66    pub fn next_seq(&self, node: &NodeId) -> u64 {
67        self.next.get(&node.0).copied().unwrap_or(1)
68    }
69
70    pub fn cursor(&self, node: &NodeId) -> u64 {
71        self.cursors.get(&node.0).copied().unwrap_or(0)
72    }
73
74    pub fn cursors(&self) -> HashMap<NodeId, u64> {
75        self.cursors.iter().map(|(k, v)| (NodeId(k.clone()), *v)).collect()
76    }
77
78    pub fn set_cursor(&mut self, node: &NodeId, last_seq: u64) {
79        self.cursors.insert(node.0.clone(), last_seq);
80    }
81
82    /// How far this log holds every op of `typ` from `node`: the explicit
83    /// per-type cursor, or the contiguous prefix of `node`'s entries (all
84    /// types), whichever is further. A pull of one type resumes from here.
85    pub fn cursor_for(&self, node: &NodeId, typ: &str) -> u64 {
86        let explicit = self.type_cursors.get(&(node.0.clone(), typ.to_string())).copied().unwrap_or(0);
87        explicit.max(self.contiguous(node))
88    }
89
90    pub fn set_cursor_for(&mut self, node: &NodeId, typ: &str, last_seq: u64) {
91        self.type_cursors.insert((node.0.clone(), typ.to_string()), last_seq);
92    }
93
94    /// Per-type cursors, for an application to persist next to [`OpLog::cursors`].
95    pub fn type_cursors(&self) -> HashMap<(NodeId, String), u64> {
96        self.type_cursors.iter().map(|((n, t), v)| ((NodeId(n.clone()), t.clone()), *v)).collect()
97    }
98
99    /// Highest `k` such that every seq `1..=k` of `node` is held.
100    pub fn contiguous(&self, node: &NodeId) -> u64 {
101        let mut k = 0;
102        for e in self.iter_node(node) {
103            if e.seq != k + 1 {
104                break;
105            }
106            k = e.seq;
107        }
108        k
109    }
110
111    /// The newest HLC held from any node.
112    pub fn newest_hlc(&self) -> Option<&Hlc> {
113        self.entries.values().map(|e| &e.hlc).max_by(|a, b| a.cmp_total(b))
114    }
115
116    /// Ops of `typ` from `node` with `after_seq < seq <= known_to`, up to `limit` ops and
117    /// [`PAGE_BUDGET`] bytes. Missing seqs in that range are other types and are skipped, so
118    /// `known_to` must be [`OpLog::cursor_for`] (or less). `to_seq` is the last seq walked,
119    /// which may be past the last op returned; a puller resumes after it.
120    pub fn page_of_type(&self, node: &NodeId, typ: &str, after_seq: u64, known_to: u64, limit: usize) -> Page {
121        let mut ops = Vec::new();
122        let mut bytes = 0usize;
123        let mut to_seq = after_seq;
124        if known_to > after_seq {
125            let mut full = false;
126            for (_, e) in self.entries.range((node.0.clone(), after_seq + 1)..=(node.0.clone(), known_to)) {
127                if e.typ == typ {
128                    let add = e.wire_size();
129                    if !ops.is_empty() && (ops.len() >= limit || bytes + add > PAGE_BUDGET) {
130                        full = true;
131                        break;
132                    }
133                    bytes += add;
134                    ops.push(e.clone());
135                }
136                to_seq = e.seq;
137            }
138            if !full {
139                to_seq = known_to;
140            }
141        }
142        let from_seq = ops.first().map(|e| e.seq).unwrap_or(after_seq);
143        Page { node_id: node.clone(), from_seq, to_seq, ops }
144    }
145
146    /// Append a local mutation. `seq` is assigned here.
147    pub fn append(&mut self, node: NodeId, hlc: Hlc, typ: impl Into<String>, record_id: impl Into<String>, op: Vec<u8>) -> &LogEntry {
148        let seq = self.next_seq(&node);
149        let entry = LogEntry { node_id: node.clone(), seq, hlc, typ: typ.into(), record_id: record_id.into(), op, value: None };
150        self.index(&entry);
151        self.entries.insert((node.0.clone(), seq), entry);
152        self.next.insert(node.0.clone(), seq + 1);
153        self.cursors.insert(node.0.clone(), seq);
154        self.entries.get(&(node.0, seq)).expect("just inserted")
155    }
156
157    /// Append a local entry with a [`Value`] (see [`crate::SyncState::write`]).
158    pub fn append_value(
159        &mut self,
160        node: NodeId,
161        hlc: Hlc,
162        typ: impl Into<String>,
163        record_id: impl Into<String>,
164        op: Vec<u8>,
165        value: Value,
166    ) -> &LogEntry {
167        let seq = self.next_seq(&node);
168        let entry = LogEntry { node_id: node.clone(), seq, hlc, typ: typ.into(), record_id: record_id.into(), op, value: Some(value) };
169        self.index(&entry);
170        self.entries.insert((node.0.clone(), seq), entry);
171        self.next.insert(node.0.clone(), seq + 1);
172        self.cursors.insert(node.0.clone(), seq);
173        self.entries.get(&(node.0, seq)).expect("just inserted")
174    }
175
176    fn index(&mut self, e: &LogEntry) {
177        if is_chunk_type(&e.typ) {
178            self.chunk_index.entry((e.typ.clone(), e.record_id.clone())).or_default().push((e.node_id.0.clone(), e.seq));
179        }
180        if e.value.as_ref().is_some_and(|v| v.blob.is_some()) {
181            self.blobs.entry(e.typ.clone()).or_default().insert((e.node_id.0.clone(), e.seq));
182        }
183    }
184
185    /// The bytes of chunk `hash` of chunk type `ctyp`, from any entry whose bytes hash to it.
186    pub fn chunk(&self, ctyp: &str, hash: &[u8]) -> Option<&[u8]> {
187        let at = self.chunk_index.get(&(ctyp.to_string(), hex::encode(hash)))?;
188        at.iter()
189            .filter_map(|(n, s)| self.entries.get(&(n.clone(), *s)))
190            .map(|e| e.op.as_slice())
191            .find(|b| blake3::hash(b).as_bytes()[..] == hash[..])
192    }
193
194    /// Whether `node` already wrote chunk `hash` of `ctyp` (local writes reuse it).
195    pub fn has_own_chunk(&self, node: &NodeId, ctyp: &str, hash: &[u8]) -> bool {
196        self.chunk_index.get(&(ctyp.to_string(), hex::encode(hash))).is_some_and(|at| {
197            at.iter().any(|(n, s)| *n == node.0 && self.entries.get(&(n.clone(), *s)).is_some_and(|e| blake3::hash(&e.op).as_bytes()[..] == hash[..]))
198        })
199    }
200
201    /// Entries of `typ` whose chunked value is not complete yet.
202    pub fn pending_blobs(&self, typ: &str) -> Vec<&LogEntry> {
203        let ctyp = crate::record::chunk_type(typ);
204        let Some(set) = self.blobs.get(typ) else { return Vec::new() };
205        set.iter()
206            .filter_map(|(n, s)| self.entries.get(&(n.clone(), *s)))
207            .filter(|e| e.value.as_ref().and_then(|v| v.blob.as_ref()).is_some_and(|b| b.chunk_hashes().any(|h| self.chunk(&ctyp, h).is_none())))
208            .collect()
209    }
210
211    pub fn get(&self, node: &NodeId, seq: u64) -> Option<&LogEntry> {
212        self.entries.get(&(node.0.clone(), seq))
213    }
214
215    pub fn len(&self) -> usize {
216        self.entries.len()
217    }
218
219    pub fn is_empty(&self) -> bool {
220        self.entries.is_empty()
221    }
222
223    /// Entries of `node` with `seq > after_seq`, up to `limit` and [`PAGE_BUDGET`] plaintext bytes.
224    pub fn page(&self, node: &NodeId, after_seq: u64, limit: usize) -> Page {
225        let mut ops = Vec::new();
226        let mut bytes = 0usize;
227        for seq in (after_seq + 1).. {
228            let Some(e) = self.entries.get(&(node.0.clone(), seq)) else { break };
229            let add = e.wire_size();
230            if !ops.is_empty() && (ops.len() >= limit || bytes + add > PAGE_BUDGET) {
231                break;
232            }
233            if add > PAGE_BUDGET && ops.is_empty() {
234                // A single oversized op still goes out: the app must not write one this large,
235                // but dropping it would stall the cursor.
236                ops.push(e.clone());
237                break;
238            }
239            bytes += add;
240            ops.push(e.clone());
241            if ops.len() >= limit {
242                break;
243            }
244        }
245        let from_seq = ops.first().map(|e| e.seq).unwrap_or(after_seq);
246        let to_seq = ops.last().map(|e| e.seq).unwrap_or(after_seq);
247        Page { node_id: node.clone(), from_seq, to_seq, ops }
248    }
249
250    /// Integrate a remote page. Existing entries of that node are left untouched; gaps are
251    /// accepted and later pages fill them. Returns how many new entries were stored.
252    pub fn integrate(&mut self, page: &Page) -> usize {
253        let mut added = 0;
254        for e in &page.ops {
255            if e.node_id != page.node_id {
256                continue;
257            }
258            let key = (e.node_id.0.clone(), e.seq);
259            if self.entries.contains_key(&key) {
260                continue;
261            }
262            self.index(e);
263            self.entries.insert(key, e.clone());
264            added += 1;
265            let next = self.next.entry(e.node_id.0.clone()).or_insert(1);
266            if e.seq + 1 > *next {
267                *next = e.seq + 1;
268            }
269        }
270        added
271    }
272
273    /// Every entry held, by node then seq.
274    pub fn iter(&self) -> impl Iterator<Item = &LogEntry> {
275        self.entries.values()
276    }
277
278    pub fn iter_node(&self, node: &NodeId) -> impl Iterator<Item = &LogEntry> {
279        let prefix = node.0.clone();
280        self.entries.range((prefix.clone(), 0)..(prefix.clone(), u64::MAX)).filter(move |((n, _), _)| *n == prefix).map(|(_, e)| e)
281    }
282}
283
284// Range with String and u64 is fine; (prefix, u64::MAX) includes seq MAX. Good.
285
286#[cfg(test)]
287mod tests {
288    use super::*;
289
290    fn n(s: &str) -> NodeId {
291        NodeId::new(s)
292    }
293
294    fn h(ms: u64, node: &str) -> Hlc {
295        Hlc::new(ms, 0, n(node))
296    }
297
298    #[test]
299    fn append_assigns_seq_and_never_rewrites_a_peer() {
300        let mut log = OpLog::new();
301        let a1 = log.append(n("a"), h(1, "a"), "bookmarks", "r1", b"add".to_vec()).clone();
302        let a2 = log.append(n("a"), h(2, "a"), "bookmarks", "r1", b"edit".to_vec()).clone();
303        assert_eq!(a1.seq, 1);
304        assert_eq!(a2.seq, 2);
305        let remote = Page {
306            node_id: n("b"),
307            from_seq: 1,
308            to_seq: 1,
309            ops: vec![LogEntry {
310                node_id: n("b"),
311                seq: 1,
312                hlc: h(3, "b"),
313                typ: "bookmarks".into(),
314                record_id: "r2".into(),
315                op: b"x".to_vec(),
316                value: None,
317            }],
318        };
319        assert_eq!(log.integrate(&remote), 1);
320        assert_eq!(log.integrate(&remote), 0);
321        assert_eq!(log.get(&n("a"), 1).unwrap().op, b"add");
322        assert_eq!(log.len(), 3);
323    }
324
325    #[test]
326    fn typed_pages_skip_other_types_and_resume_past_them() {
327        let mut log = OpLog::new();
328        log.append(n("a"), h(1, "a"), "bookmarks", "b1", vec![1]);
329        log.append(n("a"), h(2, "a"), "history", "v1", vec![2]);
330        log.append(n("a"), h(3, "a"), "bookmarks", "b2", vec![3]);
331        log.append(n("a"), h(4, "a"), "history", "v2", vec![4]);
332        log.append(n("a"), h(5, "a"), "bookmarks", "b3", vec![5]);
333        let known = log.cursor_for(&n("a"), "history");
334        assert_eq!(known, 5, "an authored stream is contiguous");
335        let p = log.page_of_type(&n("a"), "history", 0, known, 1);
336        assert_eq!(p.ops.iter().map(|e| e.seq).collect::<Vec<_>>(), [2]);
337        assert_eq!(p.to_seq, 3, "stops before the next op of the type that did not fit");
338        let p = log.page_of_type(&n("a"), "history", p.to_seq, known, 10);
339        assert_eq!(p.ops.iter().map(|e| e.seq).collect::<Vec<_>>(), [4]);
340        assert_eq!(p.to_seq, 5, "walks past trailing ops of other types");
341        let p = log.page_of_type(&n("a"), "history", 5, known, 10);
342        assert!(p.ops.is_empty());
343        assert_eq!(p.to_seq, 5);
344    }
345
346    #[test]
347    fn a_relayed_stream_is_served_only_as_far_as_it_is_known() {
348        let mut log = OpLog::new();
349        // We hold a's bookmarks 1 and 3 but not history 2 (never pulled).
350        let e = |seq, typ: &str| LogEntry {
351            node_id: n("a"),
352            seq,
353            hlc: h(seq, "a"),
354            typ: typ.into(),
355            record_id: format!("r{seq}"),
356            op: vec![],
357            value: None,
358        };
359        log.integrate(&Page { node_id: n("a"), from_seq: 1, to_seq: 3, ops: vec![e(1, "bookmarks"), e(3, "bookmarks")] });
360        assert_eq!(log.contiguous(&n("a")), 1);
361        assert_eq!(log.cursor_for(&n("a"), "history"), 1, "history 2 is unknown, not absent");
362        log.set_cursor_for(&n("a"), "bookmarks", 3);
363        assert_eq!(log.cursor_for(&n("a"), "bookmarks"), 3);
364        let p = log.page_of_type(&n("a"), "bookmarks", 0, 3, 10);
365        assert_eq!(p.ops.len(), 2);
366        assert_eq!(p.to_seq, 3);
367        assert!(log.page_of_type(&n("a"), "history", 0, log.cursor_for(&n("a"), "history"), 10).ops.is_empty());
368        assert_eq!(log.type_cursors().len(), 1);
369        assert_eq!(log.newest_hlc().unwrap().physical_ms, 3);
370    }
371
372    #[test]
373    fn page_starts_after_the_cursor_and_respects_limit() {
374        let mut log = OpLog::new();
375        for i in 0..5 {
376            log.append(n("a"), h(i, "a"), "bookmarks", format!("r{i}"), vec![i as u8]);
377        }
378        let p = log.page(&n("a"), 2, 2);
379        assert_eq!(p.from_seq, 3);
380        assert_eq!(p.to_seq, 4);
381        assert_eq!(p.ops.len(), 2);
382        let empty = log.page(&n("a"), 5, 10);
383        assert!(empty.ops.is_empty());
384        assert_eq!(empty.to_seq, 5);
385    }
386}