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
48pub fn validate_doc_id(doc_id: &str) -> Result<(), Error> {
49    if doc_id.is_empty() || doc_id.contains('\0') || doc_id.encode_utf16().count() > 1024 {
50        return Err(Error::new("INVALID_MESSAGE", "Invalid document ID"));
51    }
52    Ok(())
53}
54
55/// Checks the rows of one append, before any storage access. Returns their
56/// document, or `None` when there is no row.
57pub fn validate_rows(rows: &[PatchRow]) -> Result<Option<&str>, Error> {
58    if rows.len() > MAX_MESSAGE_ROWS {
59        return Err(Error::new("LIMIT_EXCEEDED", "Too many patch rows"));
60    }
61    let Some(first) = rows.first() else {
62        return Ok(None);
63    };
64    let doc_id = first.doc_id.as_str();
65    validate_doc_id(doc_id)?;
66    for row in rows {
67        validate_vector(&row.dependencies)?;
68        if row.doc_id != doc_id
69            || row.sid < 65536
70            || row.sid > MAX_SAFE_INTEGER
71            || row.clock < 1
72            || row.span < 1
73            || row.clock.saturating_add(row.span) > MAX_SAFE_INTEGER
74            || row.operations.is_empty()
75            || row.operations.len() > MAX_PATCH_BYTES
76            || own_clock(&row.dependencies, row.sid) > row.clock
77        {
78            return Err(Error::new("INVALID_MESSAGE", "Invalid storage segment"));
79        }
80    }
81    Ok(Some(doc_id))
82}
83
84/// The frames produced by one incoming frame.
85#[derive(Debug, Default, PartialEq, Eq)]
86pub struct RelayOutput {
87    pub doc_id: String,
88    /// Frames for the requesting peer, in order.
89    pub responses: Vec<Vec<u8>>,
90    /// Update frames (request ID 0) for the document's other peers, when the
91    /// upload stored anything: its rows, as they were received.
92    pub broadcast: Vec<Vec<u8>>,
93}
94
95/// Serve one protocol frame from the store, like `relayStoreMessage`. Rows are
96/// committed before the acknowledgement. A frame which cannot be decoded is an
97/// `Err`; every other failure becomes an error frame for the peer.
98pub fn relay_frame<T: PatchStore>(
99    store: &mut T,
100    bytes: &[u8],
101    session_doc: Option<&str>,
102) -> Result<RelayOutput, T::Error> {
103    let Message {
104        doc_id,
105        request_id,
106        body,
107    } = decode(bytes)?;
108    let mut output = RelayOutput {
109        doc_id,
110        ..RelayOutput::default()
111    };
112    if let Err(error) = serve(store, &mut output, request_id, body, session_doc) {
113        let error: Error = error.into();
114        output.broadcast.clear();
115        output.responses = vec![encode(&Message {
116            doc_id: output.doc_id.clone(),
117            request_id,
118            body: Body::Error {
119                code: error.code.to_owned(),
120                message: error.message,
121            },
122        })?];
123    }
124    Ok(output)
125}
126
127fn serve<T: PatchStore>(
128    store: &mut T,
129    output: &mut RelayOutput,
130    request_id: u64,
131    body: Body,
132    session_doc: Option<&str>,
133) -> Result<(), T::Error> {
134    let doc_id = output.doc_id.clone();
135    if session_doc.is_some_and(|pinned| pinned != doc_id) {
136        return Err(Error::new("INVALID_MESSAGE", "One document per session").into());
137    }
138    let frame = |request_id: u64, body: Body| {
139        encode(&Message {
140            doc_id: doc_id.clone(),
141            request_id,
142            body,
143        })
144    };
145    let rows = match body {
146        Body::Connect { vv } => {
147            let (rows, vv) = store.sync_state(&doc_id, &vv)?;
148            let chunks = chunk_rows(rows);
149            let last = chunks.len() - 1;
150            for (i, rows) in chunks.into_iter().enumerate() {
151                output.responses.push(frame(
152                    request_id,
153                    Body::Sync {
154                        found: !vv.is_empty(),
155                        complete: i == last,
156                        vv: vv.clone(),
157                        rows,
158                    },
159                )?);
160            }
161            return Ok(());
162        }
163        Body::SyncBack { rows, .. } | Body::Update { rows, .. } => rows,
164        _ => {
165            return Err(
166                Error::new("INVALID_MESSAGE", "Expected connect, syncBack or update").into(),
167            )
168        }
169    };
170    let result = store.append(&rows)?;
171    let inserted = result.inserted;
172    let vv = match result.vector {
173        Some(vector) => vector,
174        None => store.vector(&doc_id)?,
175    };
176    output
177        .responses
178        .push(frame(request_id, Body::Ack { vv: vv.clone() })?);
179    // Each receiver judges the rows against its own frontier.
180    if inserted > 0 {
181        for rows in chunk_rows(rows) {
182            let vv = vv.clone();
183            output.broadcast.push(frame(0, Body::Update { vv, rows })?);
184        }
185    }
186    Ok(())
187}
188
189/// Delivers frames to one session. Returns `false` once the peer is gone.
190pub trait Sink {
191    fn deliver(&self, session: u64, frame: Vec<u8>) -> bool;
192}
193impl<F: Fn(u64, Vec<u8>) -> bool> Sink for F {
194    fn deliver(&self, session: u64, frame: Vec<u8>) -> bool {
195        self(session, frame)
196    }
197}
198
199struct Session<S> {
200    doc_id: String,
201    owner: String,
202    sink: S,
203}
204
205/// One writer and its sessions: each session is pinned to a document, and rows
206/// stored through one session are forwarded to the document's other sessions.
207pub struct Hub<T, S> {
208    store: T,
209    sessions: BTreeMap<u64, Session<S>>,
210    next_session: u64,
211}
212
213impl<T: PatchStore, S: Sink> Hub<T, S> {
214    pub fn new(store: T) -> Self {
215        Self {
216            store,
217            sessions: BTreeMap::new(),
218            next_session: 1,
219        }
220    }
221    pub fn store(&mut self) -> &mut T {
222        &mut self.store
223    }
224    /// `owner` groups sessions for `close_owner`, e.g. a webview label.
225    pub fn open(&mut self, doc_id: &str, owner: &str, sink: S) -> Result<u64, T::Error> {
226        validate_doc_id(doc_id)?;
227        let session = self.next_session;
228        self.next_session += 1;
229        self.sessions.insert(
230            session,
231            Session {
232                doc_id: doc_id.to_owned(),
233                owner: owner.to_owned(),
234                sink,
235            },
236        );
237        Ok(session)
238    }
239    /// Relays one frame. Responses go to `session`, new rows to the document's other sessions.
240    pub fn send(&mut self, session: u64, bytes: &[u8]) -> Result<(), T::Error> {
241        let peer = self
242            .sessions
243            .get(&session)
244            .ok_or_else(|| Error::new("CLOSED", "Unknown or closed session"))?;
245        let output = relay_frame(&mut self.store, bytes, Some(&peer.doc_id))?;
246        for frame in output.responses {
247            if !peer.sink.deliver(session, frame) {
248                self.sessions.remove(&session);
249                return Err(Error::new("CLOSED", "Session receiver is gone").into());
250            }
251        }
252        if output.broadcast.is_empty() {
253            return Ok(());
254        }
255        let mut gone = Vec::new();
256        for (id, other) in &self.sessions {
257            if *id == session || other.doc_id != output.doc_id {
258                continue;
259            }
260            for frame in &output.broadcast {
261                if !other.sink.deliver(*id, frame.clone()) {
262                    gone.push(*id);
263                    break;
264                }
265            }
266        }
267        for id in gone {
268            self.sessions.remove(&id);
269        }
270        Ok(())
271    }
272    pub fn close(&mut self, session: u64) -> bool {
273        self.sessions.remove(&session).is_some()
274    }
275    /// Closes every session of an owner; returns how many were open.
276    pub fn close_owner(&mut self, owner: &str) -> usize {
277        let before = self.sessions.len();
278        self.sessions.retain(|_, session| session.owner != owner);
279        before - self.sessions.len()
280    }
281    pub fn session_count(&self) -> usize {
282        self.sessions.len()
283    }
284}