Skip to main content

zaun_community_protocol/client/
cursors.rs

1//! Stream cursors (§10): dedup, gap detection, events held aside until the gap is filled.
2
3mod bodies;
4mod cursor;
5
6pub use cursor::Cursor;
7pub(super) use cursor::Held;
8
9use std::collections::{BTreeMap, BTreeSet};
10
11use crate::command::object::Cursors;
12use crate::envelope::MAX_JSON_INTEGER;
13use crate::ids::ChannelId;
14
15/// Most events held aside per stream; later ones are dropped (the repair fetches them).
16const MAX_HELD: usize = 1_024;
17
18/// Which stream.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub(super) enum Key {
21    Member,
22    Channel(ChannelId),
23}
24
25/// The result of offering one sequenced event.
26#[derive(Debug)]
27pub(super) enum Offer {
28    /// `sequence ≤ cursor`: drop it.
29    Duplicate,
30    /// Apply these, in order (the event and any held ones it made contiguous).
31    Ready(Vec<Held>),
32    /// `sequence > cursor + 1`: held aside; `expected` is the missing sequence.
33    Gap { expected: u64 },
34}
35
36/// The member cursor and one cursor per channel (§10).
37///
38/// SPEC: §10 does not say where a channel's cursor starts when the client has none (a new
39/// channel, or one it never listed). It starts at 0, so a first event above 1 is a gap and
40/// `sync.resume` reports the channel's floor (§10.6), which then raises the cursor.
41#[derive(Debug, Clone, Default)]
42pub struct CursorTable {
43    member: Cursor,
44    channels: BTreeMap<ChannelId, Cursor>,
45    dirty: BTreeSet<ChannelId>,
46}
47
48impl CursorTable {
49    /// The member-stream cursor.
50    #[must_use]
51    pub const fn member(&self) -> u64 {
52        self.member.applied
53    }
54
55    /// A channel's cursor, if tracked.
56    #[must_use]
57    pub fn channel(&self, id: &ChannelId) -> Option<u64> {
58        self.channels.get(id).map(Cursor::applied)
59    }
60
61    /// Sets the member cursor exactly (after a snapshot, §10.1), dropping held events.
62    pub fn set_member(&mut self, seq: u64) {
63        self.member = Cursor {
64            applied: seq,
65            held: BTreeMap::new(),
66        };
67    }
68
69    /// Sets a channel cursor exactly (after paging history), dropping held events.
70    pub fn set_channel(&mut self, id: ChannelId, seq: u64) {
71        let cursor = Cursor {
72            applied: seq,
73            held: BTreeMap::new(),
74        };
75        self.channels.insert(id, cursor);
76        self.dirty.insert(id);
77    }
78
79    /// Stops tracking a channel (lost access, `sync.resume.hidden`).
80    pub fn remove_channel(&mut self, id: &ChannelId) {
81        self.channels.remove(id);
82        self.dirty.remove(id);
83    }
84
85    /// Raises cursors to the given ones (binding responses); never lowers them.
86    pub fn seed(&mut self, cursors: &Cursors) {
87        self.raise(Key::Member, cursors.member);
88        for c in &cursors.channels {
89            self.raise(Key::Channel(c.channel_id), c.seq);
90        }
91    }
92
93    fn cursor(&mut self, key: Key) -> &mut Cursor {
94        match key {
95            Key::Member => &mut self.member,
96            Key::Channel(id) => self.channels.entry(id).or_default(),
97        }
98    }
99
100    pub(super) fn offer(&mut self, key: Key, seq: u64, held: Held) -> Offer {
101        if let Key::Channel(id) = key {
102            self.dirty.insert(id);
103        }
104        let cursor = self.cursor(key);
105        if seq <= cursor.applied {
106            return Offer::Duplicate;
107        }
108        if seq > cursor.applied.saturating_add(1) {
109            if cursor.held.len() < MAX_HELD {
110                cursor.held.entry(seq).or_insert(held);
111            }
112            return Offer::Gap {
113                expected: cursor.applied.saturating_add(1),
114            };
115        }
116        cursor.applied = seq;
117        let mut ready = vec![held];
118        ready.extend(cursor.release());
119        Offer::Ready(ready)
120    }
121
122    /// Raises a cursor to `floor` (§10.6) and releases what became contiguous.
123    /// Host-supplied values are clamped to `2^53 − 1` (§2), so nothing overflows.
124    pub(super) fn raise(&mut self, key: Key, floor: u64) -> Vec<Held> {
125        let floor = floor.min(MAX_JSON_INTEGER);
126        let cursor = self.cursor(key);
127        cursor.applied = cursor.applied.max(floor);
128        cursor.release()
129    }
130
131    /// Accepts a gap the host cannot fill (§10.2: no `READ_MESSAGE_HISTORY`): jumps to the
132    /// first held event and releases from there.
133    pub(super) fn skip_gap(&mut self, key: Key) -> Vec<Held> {
134        let cursor = self.cursor(key);
135        match cursor.held.keys().next() {
136            Some(first) => {
137                cursor.applied = first - 1;
138                cursor.release()
139            }
140            None => Vec::new(),
141        }
142    }
143
144    /// Every stream with events held behind a gap.
145    pub(super) fn gap_keys(&self) -> Vec<Key> {
146        let member = (!self.member.held.is_empty()).then_some(Key::Member);
147        let channels = self
148            .channels
149            .iter()
150            .filter(|(_, c)| !c.held.is_empty())
151            .map(|(id, _)| Key::Channel(*id));
152        member.into_iter().chain(channels).collect()
153    }
154
155    pub(super) fn drop_held(&mut self, key: Key) {
156        self.cursor(key).held.clear();
157    }
158}