Skip to main content

pulsify_protocol/
store.rs

1//! What a durable patch store provides, and the frame relay and session hub
2//! built on it. `pulsify-sqlite` and `pulsify-rocksdb` implement [`PatchStore`].
3use crate::{
4    chunk_rows, decode, encode, own_clock, validate_vector, Body, Error, Message, PatchRow,
5    VersionVector, MAX_MESSAGE_ROWS, MAX_PATCH_BYTES, MAX_SAFE_INTEGER,
6};
7use std::collections::BTreeMap;
8
9#[derive(Debug, Clone, Default, PartialEq, Eq)]
10pub struct AppendResult {
11    /// Rows stored, plus the frontiers that a known row's longer span moved:
12    /// above zero, the upload is worth forwarding.
13    pub inserted: usize,
14    /// Rows that became ready, on arrival or once what they waited for came.
15    pub ready: usize,
16    pub pending: usize,
17    /// The committed vector of the document; `None` for an empty append.
18    pub vector: Option<VersionVector>,
19}
20
21/// Rows keyed by `(doc_id, sid, clock)`, whose operations are immutable. Rows
22/// stay pending until their actor prefix is contiguous and their dependencies
23/// are stored.
24///
25/// A store keeps the last value only of a field without history ("Fields
26/// without history" in `docs/PROTOCOL.md` and `docs/STORAGE.md`): once a
27/// last-value row is ready ([`last_register_of`](crate::last_register_of)), the
28/// older row of its register is removed. The row before the removed one grows
29/// its `span`, or a gap row ([`GAP_OPERATIONS`](crate::GAP_OPERATIONS)) stays.
30pub trait PatchStore {
31    /// Carries a Pulsify protocol error code, like [`Error`].
32    type Error: From<Error> + Into<Error>;
33    /// Validates and stores rows of one document atomically. Retransmissions
34    /// are ignored, whatever their span; a conflict (other operations at a
35    /// stored identity, or an actor fork) stores nothing.
36    fn append(&mut self, rows: &[PatchRow]) -> Result<AppendResult, Self::Error>;
37    fn vector(&self, doc_id: &str) -> Result<VersionVector, Self::Error>;
38    /// Ready rows the peer lacks, ordered by actor and clock.
39    fn missing(&self, doc_id: &str, remote: &VersionVector) -> Result<Vec<PatchRow>, Self::Error>;
40    /// `missing` and `vector` from one consistent snapshot.
41    fn sync_state(
42        &mut self,
43        doc_id: &str,
44        remote: &VersionVector,
45    ) -> Result<(Vec<PatchRow>, VersionVector), Self::Error>;
46}
47
48/// Persistent lifecycle for ID-prefix subtrees. Deleted IDs can never be reused.
49pub trait DocumentStore: PatchStore {
50    fn is_deleted(&self, doc_id: &str) -> Result<bool, Self::Error>;
51    fn delete_documents(&mut self, doc_id: &str, preserve_rows: bool)
52        -> Result<usize, Self::Error>;
53    fn recover_rows(&self, doc_id: &str) -> Result<Vec<PatchRow>, Self::Error>;
54    fn documents(
55        &self,
56        doc_id: &str,
57        after: &str,
58        limit: usize,
59    ) -> Result<Vec<String>, Self::Error>;
60}
61
62pub fn covers_document(prefix: &str, doc_id: &str) -> bool {
63    doc_id == prefix
64        || doc_id
65            .strip_prefix(prefix)
66            .is_some_and(|tail| tail.starts_with('/'))
67}
68
69pub fn document_prefixes(doc_id: &str) -> impl Iterator<Item = &str> {
70    std::iter::once(doc_id).chain(
71        doc_id
72            .match_indices('/')
73            .filter(|(i, _)| *i > 0)
74            .map(|(i, _)| &doc_id[..i]),
75    )
76}
77
78pub fn validate_doc_id(doc_id: &str) -> Result<(), Error> {
79    if doc_id.is_empty() || doc_id.contains('\0') || doc_id.encode_utf16().count() > 1024 {
80        return Err(Error::new("INVALID_MESSAGE", "Invalid document ID"));
81    }
82    Ok(())
83}
84
85/// Checks the rows of one append, before any storage access. Returns their
86/// document, or `None` when there is no row.
87pub fn validate_rows(rows: &[PatchRow]) -> Result<Option<&str>, Error> {
88    if rows.len() > MAX_MESSAGE_ROWS {
89        return Err(Error::new("LIMIT_EXCEEDED", "Too many patch rows"));
90    }
91    let Some(first) = rows.first() else {
92        return Ok(None);
93    };
94    let doc_id = first.doc_id.as_str();
95    validate_doc_id(doc_id)?;
96    for row in rows {
97        validate_vector(&row.dependencies)?;
98        if row.doc_id != doc_id
99            || row.sid < 65536
100            || row.sid > MAX_SAFE_INTEGER
101            || row.clock < 1
102            || row.span < 1
103            || row.clock.saturating_add(row.span) > MAX_SAFE_INTEGER
104            || row.operations.is_empty()
105            || row.operations.len() > MAX_PATCH_BYTES
106            || own_clock(&row.dependencies, row.sid) > row.clock
107        {
108            return Err(Error::new("INVALID_MESSAGE", "Invalid storage segment"));
109        }
110    }
111    Ok(Some(doc_id))
112}
113
114/// The frames produced by one incoming frame.
115#[derive(Debug, Default, PartialEq, Eq)]
116pub struct RelayOutput {
117    pub doc_id: String,
118    /// Frames for the requesting peer, in order.
119    pub responses: Vec<Vec<u8>>,
120    /// Update frames (request ID 0) for the document's other peers, when the
121    /// upload stored anything: its rows, as they were received.
122    pub broadcast: Vec<Vec<u8>>,
123}
124
125/// Serve one protocol frame from the store, like `relayStoreMessage`. Rows are
126/// committed before the acknowledgement. A frame which cannot be decoded is an
127/// `Err`; every other failure becomes an error frame for the peer.
128pub fn relay_frame<T: PatchStore>(
129    store: &mut T,
130    bytes: &[u8],
131    session_doc: Option<&str>,
132) -> Result<RelayOutput, T::Error> {
133    let Message {
134        doc_id,
135        request_id,
136        body,
137    } = decode(bytes)?;
138    let mut output = RelayOutput {
139        doc_id,
140        ..RelayOutput::default()
141    };
142    if let Err(error) = serve(store, &mut output, request_id, body, session_doc) {
143        let error: Error = error.into();
144        output.broadcast.clear();
145        output.responses = vec![encode(&Message {
146            doc_id: output.doc_id.clone(),
147            request_id,
148            body: Body::Error {
149                code: error.code.to_owned(),
150                message: error.message,
151            },
152        })?];
153    }
154    Ok(output)
155}
156
157fn serve<T: PatchStore>(
158    store: &mut T,
159    output: &mut RelayOutput,
160    request_id: u64,
161    body: Body,
162    session_doc: Option<&str>,
163) -> Result<(), T::Error> {
164    let doc_id = output.doc_id.clone();
165    if session_doc.is_some_and(|pinned| pinned != doc_id) {
166        return Err(Error::new("INVALID_MESSAGE", "One document per session").into());
167    }
168    let frame = |request_id: u64, body: Body| {
169        encode(&Message {
170            doc_id: doc_id.clone(),
171            request_id,
172            body,
173        })
174    };
175    let rows = match body {
176        Body::Connect { vv } => {
177            let (rows, vv) = store.sync_state(&doc_id, &vv)?;
178            let chunks = chunk_rows(rows);
179            let last = chunks.len() - 1;
180            for (i, rows) in chunks.into_iter().enumerate() {
181                output.responses.push(frame(
182                    request_id,
183                    Body::Sync {
184                        found: !vv.is_empty(),
185                        complete: i == last,
186                        vv: vv.clone(),
187                        rows,
188                    },
189                )?);
190            }
191            return Ok(());
192        }
193        Body::SyncBack { rows, .. } | Body::Update { rows, .. } => rows,
194        _ => {
195            return Err(
196                Error::new("INVALID_MESSAGE", "Expected connect, syncBack or update").into(),
197            )
198        }
199    };
200    let result = store.append(&rows)?;
201    let inserted = result.inserted;
202    let vv = match result.vector {
203        Some(vector) => vector,
204        None => store.vector(&doc_id)?,
205    };
206    output
207        .responses
208        .push(frame(request_id, Body::Ack { vv: vv.clone() })?);
209    // Each receiver judges the rows against its own frontier.
210    if inserted > 0 {
211        for rows in chunk_rows(rows) {
212            let vv = vv.clone();
213            output.broadcast.push(frame(0, Body::Update { vv, rows })?);
214        }
215    }
216    Ok(())
217}
218
219/// Delivers frames to one session. Returns `false` once the peer is gone.
220pub trait Sink {
221    fn deliver(&self, session: u64, frame: Vec<u8>) -> bool;
222}
223impl<F: Fn(u64, Vec<u8>) -> bool> Sink for F {
224    fn deliver(&self, session: u64, frame: Vec<u8>) -> bool {
225        self(session, frame)
226    }
227}
228
229struct Session<S> {
230    doc_id: String,
231    owner: String,
232    sink: S,
233}
234
235/// One writer and its sessions: each session is pinned to a document, and rows
236/// stored through one session are forwarded to the document's other sessions.
237pub struct Hub<T, S> {
238    store: T,
239    sessions: BTreeMap<u64, Session<S>>,
240    next_session: u64,
241}
242
243impl<T: PatchStore, S: Sink> Hub<T, S> {
244    pub fn new(store: T) -> Self {
245        Self {
246            store,
247            sessions: BTreeMap::new(),
248            next_session: 1,
249        }
250    }
251    pub fn store(&mut self) -> &mut T {
252        &mut self.store
253    }
254    /// `owner` groups sessions for `close_owner`, e.g. a webview label.
255    pub fn open(&mut self, doc_id: &str, owner: &str, sink: S) -> Result<u64, T::Error> {
256        validate_doc_id(doc_id)?;
257        let session = self.next_session;
258        self.next_session += 1;
259        self.sessions.insert(
260            session,
261            Session {
262                doc_id: doc_id.to_owned(),
263                owner: owner.to_owned(),
264                sink,
265            },
266        );
267        Ok(session)
268    }
269    /// Relays one frame. Responses go to `session`, new rows to the document's
270    /// other sessions. Stored rows are forwarded even when the sender's own
271    /// sink is gone: a retransmission stores nothing, so it would forward
272    /// nothing. That session is then closed, and the call fails with `CLOSED`.
273    pub fn send(&mut self, session: u64, bytes: &[u8]) -> Result<(), T::Error> {
274        let peer = self
275            .sessions
276            .get(&session)
277            .ok_or_else(|| Error::new("CLOSED", "Unknown or closed session"))?;
278        let output = relay_frame(&mut self.store, bytes, Some(&peer.doc_id))?;
279        let mut gone = Vec::new();
280        for frame in output.responses {
281            if !peer.sink.deliver(session, frame) {
282                gone.push(session);
283                break;
284            }
285        }
286        if !output.broadcast.is_empty() {
287            for (id, other) in &self.sessions {
288                if *id == session || other.doc_id != output.doc_id {
289                    continue;
290                }
291                for frame in &output.broadcast {
292                    if !other.sink.deliver(*id, frame.clone()) {
293                        gone.push(*id);
294                        break;
295                    }
296                }
297            }
298        }
299        let sender_gone = gone.first() == Some(&session);
300        for id in gone {
301            self.sessions.remove(&id);
302        }
303        if sender_gone {
304            return Err(Error::new("CLOSED", "Session receiver is gone").into());
305        }
306        Ok(())
307    }
308    /// Notify and close sessions only after their subtree has been durably retired.
309    pub fn retire_prefix(&mut self, prefix: &str) -> Result<usize, T::Error> {
310        validate_doc_id(prefix)?;
311        let ids: Vec<_> = self
312            .sessions
313            .iter()
314            .filter(|(_, peer)| covers_document(prefix, &peer.doc_id))
315            .map(|(id, _)| *id)
316            .collect();
317        for id in &ids {
318            if let Some(peer) = self.sessions.remove(id) {
319                let frame = encode(&Message {
320                    doc_id: peer.doc_id,
321                    request_id: 0,
322                    body: Body::Error {
323                        code: "NOT_FOUND".into(),
324                        message: "Document was permanently deleted".into(),
325                    },
326                })?;
327                peer.sink.deliver(*id, frame);
328            }
329        }
330        Ok(ids.len())
331    }
332    pub fn close(&mut self, session: u64) -> bool {
333        self.sessions.remove(&session).is_some()
334    }
335    /// Closes every session of an owner; returns how many were open.
336    pub fn close_owner(&mut self, owner: &str) -> usize {
337        let before = self.sessions.len();
338        self.sessions.retain(|_, session| session.owner != owner);
339        before - self.sessions.len()
340    }
341    pub fn session_count(&self) -> usize {
342        self.sessions.len()
343    }
344}
345
346impl<T: DocumentStore, S: Sink> Hub<T, S> {
347    /// Atomically retire stored data, then stop affected subscribers.
348    pub fn delete_documents(
349        &mut self,
350        prefix: &str,
351        preserve_rows: bool,
352    ) -> Result<usize, T::Error> {
353        let count = self.store.delete_documents(prefix, preserve_rows)?;
354        self.retire_prefix(prefix)?;
355        Ok(count)
356    }
357}