Skip to main content

pulsify_protocol/
lib.rs

1//! Pulsify protocol v1. The transport/patch journal is independent of a CRDT engine.
2use std::collections::{BTreeMap, BTreeSet};
3use std::fmt;
4
5mod store;
6pub use store::{
7    relay_frame, validate_doc_id, validate_rows, AppendResult, Hub, PatchStore, RelayOutput, Sink,
8};
9
10/// The version of operation payloads, their first byte.
11pub const OPERATIONS_VERSION: u8 = 3;
12/// The payload of a gap row: no operation. Its sequence numbers held writes
13/// that were replaced, and it stands where no earlier row can cover them.
14pub const GAP_OPERATIONS: [u8; 4] = [OPERATIONS_VERSION, 1, 0, 0];
15pub fn is_gap(operations: &[u8]) -> bool {
16    operations == GAP_OPERATIONS
17}
18
19/// What a journal or a store reads from the head of a last-value row.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub struct LastRegister<'a> {
22    pub lamport: u64,
23    /// The register, compared as bytes: the encoded target and field of the write.
24    pub register: &'a [u8],
25}
26
27/// A varuint of a payload head, read as leniently as the TypeScript codec does.
28fn head_uint(bytes: &[u8], pos: &mut usize) -> Option<u64> {
29    let mut value = 0_u64;
30    for shift in (0..=56).step_by(7) {
31        let byte = *bytes.get(*pos)?;
32        *pos += 1;
33        value |= u64::from(byte & 127) << shift;
34        if value > MAX_SAFE_INTEGER {
35            return None;
36        }
37        if byte < 128 {
38            return Some(value);
39        }
40    }
41    None
42}
43
44/// `None` unless the payload is one last-value write: exactly one operation of
45/// kind 7 (assign) or 8 (delete), to a register that keeps no history. Mirror
46/// of `lastRegisterOf`: nothing is decoded beyond the head,
47/// `version, lamport, schema, count = 1, kind, target, field`.
48pub fn last_register_of(operations: &[u8]) -> Option<LastRegister<'_>> {
49    let mut pos = 0;
50    // The next read fails when a length reaches beyond the payload.
51    let skip = |pos: &mut usize| -> Option<()> {
52        let length = usize::try_from(head_uint(operations, pos)?).ok()?;
53        *pos = pos.checked_add(length)?;
54        Some(())
55    };
56    if head_uint(operations, &mut pos)? != u64::from(OPERATIONS_VERSION) {
57        return None;
58    }
59    let lamport = head_uint(operations, &mut pos)?;
60    skip(&mut pos)?;
61    if head_uint(operations, &mut pos)? != 1 {
62        return None;
63    }
64    if !matches!(head_uint(operations, &mut pos)?, 7 | 8) {
65        return None;
66    }
67    let start = pos;
68    skip(&mut pos)?;
69    if head_uint(operations, &mut pos)? == 0 {
70        skip(&mut pos)?;
71    } else {
72        head_uint(operations, &mut pos)?;
73    }
74    Some(LastRegister {
75        lamport,
76        register: operations.get(start..pos)?,
77    })
78}
79
80pub const MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991;
81pub const MAX_FRAME_BYTES: usize = 8 * 1024 * 1024;
82pub const MAX_PATCH_BYTES: usize = 1024 * 1024;
83pub const MAX_VECTOR_ENTRIES: usize = 1024;
84pub const MAX_MESSAGE_ROWS: usize = 4096;
85pub const MAX_SCHEMA_NODES: usize = 300_000;
86const MAX_ROW_BATCH_NODES: usize = MAX_SCHEMA_NODES - (3 * MAX_VECTOR_ENTRIES + 16);
87pub type VersionVector = Vec<(u64, u64)>;
88
89#[derive(Debug, Clone, PartialEq, Eq)]
90pub struct Error {
91    pub code: &'static str,
92    pub message: String,
93}
94impl Error {
95    pub fn new(code: &'static str, message: impl Into<String>) -> Self {
96        Self {
97            code,
98            message: message.into(),
99        }
100    }
101}
102impl fmt::Display for Error {
103    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
104        write!(f, "{}: {}", self.code, self.message)
105    }
106}
107impl std::error::Error for Error {}
108type Result<T> = std::result::Result<T, Error>;
109fn invalid(message: &str) -> Error {
110    Error::new("INVALID_MESSAGE", message)
111}
112fn limit(message: &str) -> Error {
113    Error::new("LIMIT_EXCEEDED", message)
114}
115
116#[derive(Debug, Clone, PartialEq, Eq)]
117pub struct PatchRow {
118    pub doc_id: String,
119    pub sid: u64,
120    pub clock: u64,
121    pub span: u64,
122    pub dependencies: VersionVector,
123    pub operations: Vec<u8>,
124}
125impl PatchRow {
126    pub fn end(&self) -> u64 {
127        self.clock.saturating_add(self.span)
128    }
129    fn validate(&self, doc_id: &str) -> Result<()> {
130        validate_vector(&self.dependencies)?;
131        if self.doc_id != doc_id
132            || self.sid < 65536
133            || self.sid > MAX_SAFE_INTEGER
134            || self.clock == 0
135            || self.span == 0
136            || self.end() > MAX_SAFE_INTEGER
137            || self.operations.is_empty()
138            || own_clock(&self.dependencies, self.sid) > self.clock
139        {
140            return Err(invalid("Invalid patch segment"));
141        }
142        if self.operations.len() > MAX_PATCH_BYTES {
143            return Err(limit("Patch exceeds 1 MiB"));
144        }
145        Ok(())
146    }
147}
148#[derive(Debug, Clone, PartialEq, Eq)]
149pub enum Body {
150    Connect {
151        vv: VersionVector,
152    },
153    Sync {
154        found: bool,
155        complete: bool,
156        vv: VersionVector,
157        rows: Vec<PatchRow>,
158    },
159    SyncBack {
160        vv: VersionVector,
161        rows: Vec<PatchRow>,
162    },
163    Update {
164        vv: VersionVector,
165        rows: Vec<PatchRow>,
166    },
167    Ack {
168        vv: VersionVector,
169    },
170    Error {
171        code: String,
172        message: String,
173    },
174}
175#[derive(Debug, Clone, PartialEq, Eq)]
176pub struct Message {
177    pub doc_id: String,
178    pub request_id: u64,
179    pub body: Body,
180}
181impl Message {
182    fn validate(&self) -> Result<()> {
183        if self.doc_id.is_empty()
184            || self.doc_id.contains('\0')
185            || self.doc_id.encode_utf16().count() > 1024
186            || self.request_id > MAX_SAFE_INTEGER
187        {
188            return Err(invalid("Invalid message header"));
189        }
190        match &self.body {
191            Body::Connect { vv } | Body::Ack { vv } => validate_vector(vv)?,
192            Body::Sync { vv, rows, .. }
193            | Body::SyncBack { vv, rows }
194            | Body::Update { vv, rows } => {
195                validate_vector(vv)?;
196                if rows.len() > MAX_MESSAGE_ROWS {
197                    return Err(limit("Too many rows"));
198                }
199                for row in rows {
200                    row.validate(&self.doc_id)?;
201                }
202            }
203            Body::Error { .. } => {}
204        }
205        let nodes = match &self.body {
206            Body::Connect { vv } | Body::Ack { vv } => 8 + 3 * vv.len(),
207            Body::Sync { vv, rows, .. } => {
208                11 + 3 * vv.len() + rows.iter().map(row_nodes).sum::<usize>()
209            }
210            Body::SyncBack { vv, rows } | Body::Update { vv, rows } => {
211                9 + 3 * vv.len() + rows.iter().map(row_nodes).sum::<usize>()
212            }
213            Body::Error { .. } => 9,
214        };
215        if nodes > MAX_SCHEMA_NODES {
216            return Err(limit("Structure limit exceeded"));
217        }
218        Ok(())
219    }
220}
221fn own_clock(vv: &VersionVector, sid: u64) -> u64 {
222    vv.iter()
223        .find(|(id, _)| *id == sid)
224        .map(|(_, clock)| *clock)
225        .unwrap_or(0)
226}
227pub fn validate_vector(vv: &VersionVector) -> Result<()> {
228    if vv.len() > MAX_VECTOR_ENTRIES {
229        return Err(invalid("Too many actors"));
230    }
231    let mut previous = None;
232    for &(sid, clock) in vv {
233        if sid > MAX_SAFE_INTEGER
234            || clock == 0
235            || clock > MAX_SAFE_INTEGER
236            || previous.is_some_and(|id| sid <= id)
237        {
238            return Err(invalid(
239                "Vector must have unique sorted actors and positive clocks",
240            ));
241        }
242        previous = Some(sid);
243    }
244    Ok(())
245}
246fn covers(have: &BTreeMap<u64, u64>, required: &VersionVector) -> bool {
247    required
248        .iter()
249        .all(|(sid, clock)| have.get(sid).copied().unwrap_or(0) >= *clock)
250}
251
252struct Writer(Vec<u8>);
253impl Writer {
254    fn uint(&mut self, mut value: u64) {
255        while value >= 128 {
256            self.0.push((value as u8 & 127) | 128);
257            value >>= 7;
258        }
259        self.0.push(value as u8);
260    }
261    fn bytes(&mut self, value: &[u8]) {
262        self.uint(value.len() as u64);
263        self.0.extend_from_slice(value);
264    }
265    fn text(&mut self, value: &str) {
266        self.bytes(value.as_bytes());
267    }
268    fn vector(&mut self, vv: &VersionVector) {
269        self.uint(vv.len() as u64);
270        for (sid, clock) in vv {
271            self.uint(*sid);
272            self.uint(*clock);
273        }
274    }
275    fn rows(&mut self, rows: &[PatchRow]) {
276        self.uint(rows.len() as u64);
277        for row in rows {
278            self.text(&row.doc_id);
279            self.uint(row.sid);
280            self.uint(row.clock);
281            self.uint(row.span);
282            self.vector(&row.dependencies);
283            self.bytes(&row.operations);
284        }
285    }
286}
287struct Reader<'a> {
288    bytes: &'a [u8],
289    pos: usize,
290}
291impl<'a> Reader<'a> {
292    fn byte(&mut self) -> Result<u8> {
293        let b = self
294            .bytes
295            .get(self.pos)
296            .copied()
297            .ok_or_else(|| invalid("Truncated frame"))?;
298        self.pos += 1;
299        Ok(b)
300    }
301    fn uint(&mut self) -> Result<u64> {
302        let mut result = 0_u64;
303        for i in 0..8 {
304            let b = self.byte()?;
305            result |= u64::from(b & 127) << (7 * i);
306            if result > MAX_SAFE_INTEGER {
307                return Err(invalid("Integer overflow"));
308            }
309            if b < 128 {
310                if i > 0 && b == 0 {
311                    return Err(invalid("Non-canonical varint"));
312                }
313                return Ok(result);
314            }
315        }
316        Err(invalid("Integer overflow"))
317    }
318    fn count(&mut self, max: usize) -> Result<usize> {
319        let n = self.uint()?;
320        if n > max as u64 {
321            return Err(limit("Collection limit exceeded"));
322        }
323        Ok(n as usize)
324    }
325    fn bytes(&mut self, max: usize) -> Result<Vec<u8>> {
326        let n = self.count(max)?;
327        let end = self
328            .pos
329            .checked_add(n)
330            .ok_or_else(|| invalid("Length overflow"))?;
331        let result = self
332            .bytes
333            .get(self.pos..end)
334            .ok_or_else(|| invalid("Truncated bytes"))?
335            .to_vec();
336        self.pos = end;
337        Ok(result)
338    }
339    fn text(&mut self) -> Result<String> {
340        String::from_utf8(self.bytes(MAX_FRAME_BYTES)?).map_err(|_| invalid("Invalid UTF-8"))
341    }
342    fn boolean(&mut self) -> Result<bool> {
343        match self.byte()? {
344            0 => Ok(false),
345            1 => Ok(true),
346            _ => Err(invalid("Invalid boolean")),
347        }
348    }
349    fn vector(&mut self) -> Result<VersionVector> {
350        let n = self.count(MAX_VECTOR_ENTRIES)?;
351        let mut result = Vec::with_capacity(n);
352        for _ in 0..n {
353            result.push((self.uint()?, self.uint()?));
354        }
355        validate_vector(&result)?;
356        Ok(result)
357    }
358    fn rows(&mut self) -> Result<Vec<PatchRow>> {
359        let n = self.count(MAX_MESSAGE_ROWS)?;
360        let mut result = Vec::with_capacity(n);
361        for _ in 0..n {
362            result.push(PatchRow {
363                doc_id: self.text()?,
364                sid: self.uint()?,
365                clock: self.uint()?,
366                span: self.uint()?,
367                dependencies: self.vector()?,
368                operations: self.bytes(MAX_PATCH_BYTES)?,
369            });
370        }
371        Ok(result)
372    }
373}
374// Envelope v2 carries one lossless scalar run. Relays expand it without an
375// application schema; their outgoing v1 rows preserve every original identity.
376fn uint_size(mut n: u64) -> usize {
377    let mut size = 1;
378    while n >= 128 {
379        size += 1;
380        n >>= 7;
381    }
382    size
383}
384impl Reader<'_> {
385    fn run_rows(&mut self, doc_id: &str, vv_len: usize) -> Result<Vec<PatchRow>> {
386        let sid = self.uint()?;
387        let clock = self.uint()?;
388        let count = self.count(MAX_MESSAGE_ROWS)?;
389        let lamport = self.uint()?;
390        if sid < 65536
391            || clock == 0
392            || lamport == 0
393            || count < 2
394            || clock + count as u64 > MAX_SAFE_INTEGER
395            || lamport + count as u64 > MAX_SAFE_INTEGER
396        {
397            return Err(invalid("Invalid run range"));
398        }
399        let schema = self.text()?;
400        let target = self.text()?;
401        let tag = self.uint()?;
402        if tag > 1 {
403            return Err(invalid("Invalid run field"));
404        }
405        let field_text = if tag == 0 { Some(self.text()?) } else { None };
406        let field_number = if tag == 1 { self.uint()? } else { 0 };
407        let layout = self.uint()?;
408        let external = self.vector()?;
409        if external.iter().any(|(actor, _)| *actor == sid)
410            || external.len() + 1 > MAX_VECTOR_ENTRIES
411        {
412            return Err(invalid("Invalid run dependencies"));
413        }
414        if 16 + vv_len * 3 + count * (7 + 3 * (external.len() + 1)) > MAX_SCHEMA_NODES {
415            return Err(limit("Expanded run node limit"));
416        }
417        let mut prefix = Writer(Vec::new());
418        prefix.text(&schema);
419        prefix.uint(1);
420        prefix.uint(1);
421        prefix.text(&target);
422        prefix.uint(tag);
423        if let Some(field) = field_text {
424            prefix.text(&field);
425        } else {
426            prefix.uint(field_number);
427        }
428        prefix.uint(layout);
429        let mut values = Vec::with_capacity(count);
430        let mut expanded = self.bytes.len();
431        for i in 0..count {
432            let value = self.bytes(MAX_PATCH_BYTES)?;
433            let op_bytes = 1
434                + uint_size(lamport + i as u64)
435                + prefix.0.len()
436                + uint_size(value.len() as u64)
437                + value.len()
438                + 2;
439            if op_bytes > MAX_PATCH_BYTES {
440                return Err(limit("Expanded run payload limit"));
441            }
442            expanded += op_bytes
443                + (external.len() + usize::from(clock + i as u64 > 1)) * 16
444                + doc_id.encode_utf16().count() * 2
445                + 40;
446            if expanded > 64 * 1024 * 1024 {
447                return Err(limit("Expanded run byte limit"));
448            }
449            values.push(value);
450        }
451        let mut rows = Vec::with_capacity(count);
452        for (i, value) in values.into_iter().enumerate() {
453            let mut operations = Writer(vec![3]);
454            operations.uint(lamport + i as u64);
455            operations.0.extend_from_slice(&prefix.0);
456            operations.bytes(&value);
457            operations.uint(0);
458            operations.uint(0);
459            let mut dependencies = external.clone();
460            if clock + i as u64 > 1 {
461                let at = dependencies.partition_point(|(actor, _)| *actor < sid);
462                dependencies.insert(at, (sid, clock + i as u64));
463            }
464            rows.push(PatchRow {
465                doc_id: doc_id.to_owned(),
466                sid,
467                clock: clock + i as u64,
468                span: 1,
469                dependencies,
470                operations: operations.0,
471            });
472        }
473        Ok(rows)
474    }
475}
476
477pub fn encode(message: &Message) -> Result<Vec<u8>> {
478    message.validate()?;
479    let mut writer = Writer(vec![1, 3]);
480    writer.uint(match message.body {
481        Body::Connect { .. } => 1,
482        Body::Sync { .. } => 2,
483        Body::SyncBack { .. } => 3,
484        Body::Update { .. } => 4,
485        Body::Ack { .. } => 5,
486        Body::Error { .. } => 6,
487    });
488    writer.text(&message.doc_id);
489    writer.uint(message.request_id);
490    match &message.body {
491        Body::Connect { vv } | Body::Ack { vv } => writer.vector(vv),
492        Body::Sync {
493            found,
494            complete,
495            vv,
496            rows,
497        } => {
498            writer.0.push(*found as u8);
499            writer.0.push(*complete as u8);
500            writer.vector(vv);
501            writer.rows(rows);
502        }
503        Body::SyncBack { vv, rows } | Body::Update { vv, rows } => {
504            writer.vector(vv);
505            writer.rows(rows);
506        }
507        Body::Error { code, message } => {
508            writer.text(code);
509            writer.text(message);
510        }
511    }
512    if writer.0.len() > MAX_FRAME_BYTES {
513        return Err(limit("Frame exceeds 8 MiB"));
514    }
515    Ok(writer.0)
516}
517pub fn decode(bytes: &[u8]) -> Result<Message> {
518    if bytes.len() > MAX_FRAME_BYTES {
519        return Err(limit("Frame exceeds 8 MiB"));
520    }
521    let mut reader = Reader { bytes, pos: 0 };
522    let protocol = reader.uint()?;
523    let operations = reader.uint()?;
524    if !((protocol == 1 || protocol == 2) && operations == 3) {
525        return Err(Error::new(
526            "UNSUPPORTED_VERSION",
527            "Unsupported protocol or operation version",
528        ));
529    }
530    let kind = reader.uint()?;
531    if !(1..=6).contains(&kind) {
532        return Err(invalid("Unknown message kind"));
533    }
534    let doc_id = reader.text()?;
535    let request_id = reader.uint()?;
536    if protocol == 2 && !(2..=4).contains(&kind) {
537        return Err(invalid("Invalid run message kind"));
538    }
539    let body = match kind {
540        1 => Body::Connect {
541            vv: reader.vector()?,
542        },
543        2 => {
544            let found = reader.boolean()?;
545            let complete = reader.boolean()?;
546            let vv = reader.vector()?;
547            let rows = if protocol == 2 {
548                reader.run_rows(&doc_id, vv.len())?
549            } else {
550                reader.rows()?
551            };
552            Body::Sync {
553                found,
554                complete,
555                vv,
556                rows,
557            }
558        }
559        3 | 4 => {
560            let vv = reader.vector()?;
561            let rows = if protocol == 2 {
562                reader.run_rows(&doc_id, vv.len())?
563            } else {
564                reader.rows()?
565            };
566            if kind == 3 {
567                Body::SyncBack { vv, rows }
568            } else {
569                Body::Update { vv, rows }
570            }
571        }
572        5 => Body::Ack {
573            vv: reader.vector()?,
574        },
575        6 => Body::Error {
576            code: reader.text()?,
577            message: reader.text()?,
578        },
579        _ => unreachable!(),
580    };
581    if reader.pos != bytes.len() {
582        return Err(invalid("Trailing bytes"));
583    }
584    let message = Message {
585        doc_id,
586        request_id,
587        body,
588    };
589    message.validate()?;
590    Ok(message)
591}
592
593/// The row that holds a register without history: the newest write to it.
594#[derive(Clone, Copy, Debug)]
595struct Holder {
596    sid: u64,
597    clock: u64,
598    lamport: u64,
599}
600
601/// Journal bytes charged for a row.
602fn cost(row: &PatchRow) -> usize {
603    row.operations.len() + row.dependencies.len() * 16 + row.doc_id.encode_utf16().count() * 2 + 40
604}
605/// A row without operations, covering sequence numbers of replaced writes.
606fn gap_row(doc_id: &str, sid: u64, clock: u64, span: u64) -> PatchRow {
607    PatchRow {
608        doc_id: doc_id.to_owned(),
609        sid,
610        clock,
611        span,
612        dependencies: if clock > 1 {
613            vec![(sid, clock)]
614        } else {
615            vec![]
616        },
617        operations: GAP_OPERATIONS.to_vec(),
618    }
619}
620fn differ(held: &[u8], incoming: &[u8]) -> bool {
621    !is_gap(held) && !is_gap(incoming) && held != incoming
622}
623
624/// Opaque segments whose operations are immutable; the frontier advances only
625/// when dependencies exist. A register without history keeps one row, the
626/// newest write: see "Fields without history" in `docs/PROTOCOL.md`.
627#[derive(Clone, Debug)]
628pub struct PatchLog {
629    pub doc_id: String,
630    rows: BTreeMap<(u64, u64), PatchRow>,
631    pending: BTreeSet<(u64, u64)>,
632    frontier: BTreeMap<u64, u64>,
633    /// The row that holds each register without history.
634    registers: BTreeMap<Vec<u8>, Holder>,
635    bytes: usize,
636}
637impl PatchLog {
638    pub fn new(doc_id: &str) -> Self {
639        Self {
640            doc_id: doc_id.into(),
641            rows: BTreeMap::new(),
642            pending: BTreeSet::new(),
643            frontier: BTreeMap::new(),
644            registers: BTreeMap::new(),
645            bytes: 0,
646        }
647    }
648    pub fn vector(&self) -> VersionVector {
649        self.frontier
650            .iter()
651            .map(|(sid, clock)| (*sid, *clock))
652            .collect()
653    }
654    pub fn pending_count(&self) -> usize {
655        self.pending.len()
656    }
657    /// How many rows the journal holds, waiting ones included.
658    pub fn len(&self) -> usize {
659        self.rows.len()
660    }
661    pub fn is_empty(&self) -> bool {
662        self.rows.is_empty()
663    }
664    pub fn missing(&self, vv: &VersionVector) -> Vec<PatchRow> {
665        self.rows
666            .values()
667            .filter(|row| row.end() > own_clock(vv, row.sid))
668            .cloned()
669            .collect()
670    }
671    /// Stores rows atomically: a conflict leaves the journal as it was.
672    pub fn append(&mut self, rows: &[PatchRow]) -> Result<()> {
673        let mut next = self.clone();
674        next.insert(rows)?;
675        *self = next;
676        Ok(())
677    }
678
679    fn drop_row(&mut self, key: (u64, u64)) {
680        if let Some(row) = self.rows.remove(&key) {
681            self.bytes -= cost(&row);
682        }
683        self.pending.remove(&key);
684    }
685
686    fn insert(&mut self, rows: &[PatchRow]) -> Result<()> {
687        // A row that starts below its actor's frontier is already known, or was
688        // replaced here: only the sequence numbers its span covers beyond the
689        // frontier are news, and they come as a gap row to append.
690        let mut incoming: Vec<PatchRow> = Vec::with_capacity(rows.len());
691        let mut gaps: BTreeMap<u64, usize> = BTreeMap::new();
692        for row in rows {
693            row.validate(&self.doc_id)?;
694            let frontier = self.frontier.get(&row.sid).copied().unwrap_or(1);
695            if row.clock >= frontier {
696                incoming.push(row.clone());
697                continue;
698            }
699            if let Some(held) = self.rows.get(&(row.sid, row.clock)) {
700                if differ(&held.operations, &row.operations) {
701                    return Err(Error::new("CONFLICT", "Conflicting segment"));
702                }
703            }
704            if row.end() <= frontier {
705                continue;
706            }
707            let span = row.end() - frontier;
708            match gaps.get(&row.sid) {
709                Some(&at) => incoming[at].span = incoming[at].span.max(span),
710                None => {
711                    gaps.insert(row.sid, incoming.len());
712                    incoming.push(gap_row(&self.doc_id, row.sid, frontier, span));
713                }
714            }
715        }
716        for row in incoming {
717            let key = (row.sid, row.clock);
718            if let Some(existing) = self.rows.get(&key) {
719                // A span is how much a peer has replaced since: only contents conflict.
720                if differ(&existing.operations, &row.operations) {
721                    return Err(Error::new("CONFLICT", "Conflicting segment"));
722                }
723                // The longer span knows of more replaced writes: it takes the place.
724                if row.end() <= existing.end() {
725                    continue;
726                }
727                self.drop_row(key);
728            }
729            if let Some(before) = self.rows.range((row.sid, 0)..key).next_back().map(|e| e.1) {
730                // It starts among the writes that a waiting row has replaced.
731                if before.end() > row.clock {
732                    continue;
733                }
734                if own_clock(&row.dependencies, row.sid) < before.end() {
735                    return Err(Error::new("CONFLICT", "Actor history fork"));
736                }
737            }
738            // Rows still waiting whose sequence numbers this row declares replaced.
739            while let Some(after) = self
740                .rows
741                .range(key..=(row.sid, u64::MAX))
742                .next()
743                .map(|e| e.1)
744            {
745                if after.clock >= row.end() {
746                    if own_clock(&after.dependencies, row.sid) < row.end() {
747                        return Err(Error::new("CONFLICT", "Actor history fork"));
748                    }
749                    break;
750                }
751                self.drop_row((after.sid, after.clock));
752            }
753            self.bytes += cost(&row);
754            if self.rows.len() >= 100_000 || self.bytes > 64 * 1024 * 1024 {
755                return Err(limit("Document history limit exceeded"));
756            }
757            self.rows.insert(key, row);
758            self.pending.insert(key);
759        }
760        let mut fresh = Vec::new();
761        loop {
762            let ready: Vec<_> = self
763                .pending
764                .iter()
765                .filter(|key| {
766                    let row = &self.rows[key];
767                    covers(&self.frontier, &row.dependencies)
768                        && row.clock == self.frontier.get(&row.sid).copied().unwrap_or(1)
769                })
770                .copied()
771                .collect();
772            if ready.is_empty() {
773                break;
774            }
775            for key in ready {
776                let row = &self.rows[&key];
777                self.frontier.insert(row.sid, row.end());
778                self.pending.remove(&key);
779                fresh.push(key);
780            }
781        }
782        if self.frontier.len() > MAX_VECTOR_ENTRIES {
783            return Err(limit("Too many actors"));
784        }
785        for key in fresh {
786            self.settle(key);
787        }
788        Ok(())
789    }
790
791    /// Once a row is applicable: a register without history holds one row, the
792    /// newest write, and a gap folds into the row before it.
793    fn settle(&mut self, key: (u64, u64)) {
794        let Some(row) = self.rows.get(&key) else {
795            return;
796        };
797        if is_gap(&row.operations) {
798            return self.kill(key);
799        }
800        let Some(last) = last_register_of(&row.operations) else {
801            return;
802        };
803        let (lamport, register) = (last.lamport, last.register.to_vec());
804        let held = self.registers.get(&register).copied();
805        if let Some(held) = held {
806            if (held.sid, held.clock) == key {
807                return;
808            }
809            // Last writer wins, by Lamport time then actor: the same order as the
810            // register itself, so the row that stays is the value every replica shows.
811            if (held.lamport, held.sid) > (lamport, key.0) {
812                return self.kill(key);
813            }
814        }
815        let holder = Holder {
816            sid: key.0,
817            clock: key.1,
818            lamport,
819        };
820        self.registers.insert(register, holder);
821        if let Some(held) = held {
822            self.kill((held.sid, held.clock));
823        }
824    }
825
826    /// Remove a row; the row before it covers its sequence numbers, or a gap does.
827    fn kill(&mut self, key: (u64, u64)) {
828        let Some(row) = self.rows.get(&key) else {
829            return;
830        };
831        if self.pending.contains(&key) {
832            return;
833        }
834        let span = row.span;
835        let previous = self
836            .rows
837            .range((key.0, 0)..key)
838            .next_back()
839            .filter(|(at, previous)| previous.end() == key.1 && !self.pending.contains(at))
840            .map(|(at, _)| *at);
841        match previous {
842            Some(previous) => {
843                self.drop_row(key);
844                if let Some(previous) = self.rows.get_mut(&previous) {
845                    previous.span += span;
846                }
847            }
848            None if is_gap(&row.operations) => {}
849            None => {
850                let gap = gap_row(&self.doc_id, key.0, key.1, span);
851                self.bytes = self.bytes + cost(&gap) - cost(row);
852                self.rows.insert(key, gap);
853            }
854        }
855    }
856}
857
858fn row_nodes(row: &PatchRow) -> usize {
859    7 + 3 * row.dependencies.len()
860}
861
862/// Mirror of `chunkRows`: about 2 MiB, 4096 rows and the relay node budget per page.
863pub fn chunk_rows(rows: Vec<PatchRow>) -> Vec<Vec<PatchRow>> {
864    let mut chunks = Vec::new();
865    let mut chunk = Vec::new();
866    let mut bytes = 0;
867    let mut nodes = 0;
868    for row in rows {
869        let size = row.operations.len()
870            + row.dependencies.len() * 16
871            + row.doc_id.encode_utf16().count() * 4
872            + 64;
873        let cost = row_nodes(&row);
874        if !chunk.is_empty()
875            && (bytes + size > 2 * MAX_PATCH_BYTES
876                || chunk.len() >= MAX_MESSAGE_ROWS
877                || nodes + cost > MAX_ROW_BATCH_NODES)
878        {
879            chunks.push(std::mem::take(&mut chunk));
880            bytes = 0;
881            nodes = 0;
882        }
883        bytes += size;
884        nodes += cost;
885        chunk.push(row);
886    }
887    if !chunk.is_empty() || chunks.is_empty() {
888        chunks.push(chunk);
889    }
890    chunks
891}
892
893/// Single-peer reference relay for embedding or the line-based interoperability CLI.
894#[derive(Default)]
895pub struct Relay {
896    documents: BTreeMap<String, PatchLog>,
897}
898impl Relay {
899    pub fn receive(&mut self, message: Message) -> Result<Vec<Message>> {
900        message.validate()?;
901        let Message {
902            doc_id,
903            request_id,
904            body,
905        } = message;
906        let responses = match body {
907            Body::Connect { vv } => {
908                let log = self.documents.get(&doc_id);
909                let rows = log.map(|log| log.missing(&vv)).unwrap_or_default();
910                let vector = log.map(PatchLog::vector).unwrap_or_default();
911                let chunks = chunk_rows(rows);
912                let last = chunks.len() - 1;
913                chunks
914                    .into_iter()
915                    .enumerate()
916                    .map(|(i, rows)| Message {
917                        doc_id: doc_id.clone(),
918                        request_id,
919                        body: Body::Sync {
920                            found: log.is_some(),
921                            complete: i == last,
922                            vv: vector.clone(),
923                            rows,
924                        },
925                    })
926                    .collect()
927            }
928            Body::SyncBack { rows, .. } | Body::Update { rows, .. } => {
929                let log = self
930                    .documents
931                    .entry(doc_id.clone())
932                    .or_insert_with(|| PatchLog::new(&doc_id));
933                match log.append(&rows) {
934                    Ok(()) => vec![Message {
935                        doc_id,
936                        request_id,
937                        body: Body::Ack { vv: log.vector() },
938                    }],
939                    Err(error) => vec![Message {
940                        doc_id,
941                        request_id,
942                        body: Body::Error {
943                            code: error.code.into(),
944                            message: error.message,
945                        },
946                    }],
947                }
948            }
949            _ => return Err(invalid("Expected connect or patch upload")),
950        };
951        Ok(responses)
952    }
953}
954
955#[cfg(test)]
956mod tests {
957    use super::*;
958    #[test]
959    fn dense_vectors_are_chunked_within_the_shared_structure_budget() {
960        let vv: VersionVector = (0..1024).map(|i| (65536 + i, 1)).collect();
961        let rows: Vec<_> = (0..127)
962            .map(|i| PatchRow {
963                doc_id: "dense".into(),
964                sid: 200_000 + i,
965                clock: 1,
966                span: 1,
967                dependencies: vv.clone(),
968                operations: vec![1],
969            })
970            .collect();
971        let message = Message {
972            doc_id: "dense".into(),
973            request_id: 1,
974            body: Body::Update {
975                vv: vv.clone(),
976                rows: rows.clone(),
977            },
978        };
979        assert!(encode(&message).is_err());
980        let mut unchecked = Writer(vec![1, 3, 4]);
981        unchecked.text("dense");
982        unchecked.uint(1);
983        unchecked.vector(&vv);
984        unchecked.rows(&rows);
985        assert!(decode(&unchecked.0).is_err());
986        let chunks = chunk_rows(rows);
987        assert_eq!(chunks.len(), 2);
988        for rows in chunks {
989            let message = Message {
990                doc_id: "dense".into(),
991                request_id: 1,
992                body: Body::Sync {
993                    found: true,
994                    complete: true,
995                    vv: vv.clone(),
996                    rows,
997                },
998            };
999            assert_eq!(decode(&encode(&message).unwrap()).unwrap(), message);
1000        }
1001    }
1002    #[test]
1003    fn shared_binary_fixtures() {
1004        let fixtures: serde_json::Value =
1005            serde_json::from_str(include_str!("../../../fixtures/protocol.json")).unwrap();
1006        for fixture in fixtures["messages"].as_array().unwrap() {
1007            let bytes: Vec<u8> = fixture["bytes"]
1008                .as_array()
1009                .unwrap()
1010                .iter()
1011                .map(|b| b.as_u64().unwrap() as u8)
1012                .collect();
1013            let message = decode(&bytes).unwrap();
1014            assert_eq!(encode(&message).unwrap(), bytes, "{}", fixture["name"]);
1015            for i in 0..bytes.len() {
1016                assert!(decode(&bytes[..i]).is_err());
1017            }
1018            let mut trailing = bytes.clone();
1019            trailing.push(0);
1020            assert!(decode(&trailing).is_err());
1021        }
1022    }
1023    #[test]
1024    fn malformed_values() {
1025        assert!(decode(&[1, 3, 99]).is_err());
1026        assert!(decode(&[2, 1]).is_err());
1027        // State-only envelopes are never accepted as durable exact history.
1028        assert!(decode(&[3, 3, 4]).is_err());
1029        assert!(decode(&[1, 3, 1, 128, 0]).is_err());
1030        assert!(validate_vector(&vec![(65536, 1), (65536, 2)]).is_err());
1031        assert!(validate_vector(&vec![(65536, MAX_SAFE_INTEGER + 1)]).is_err());
1032        let mut seed = 42_u32;
1033        for n in 0..1000 {
1034            let mut bytes = vec![1, 3];
1035            for _ in 0..n % 64 {
1036                seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
1037                bytes.push(seed as u8);
1038            }
1039            let _ = decode(&bytes);
1040        }
1041    }
1042    #[test]
1043    fn gaps_duplicates_and_conflicts() {
1044        let first = PatchRow {
1045            doc_id: "test".into(),
1046            sid: 65536,
1047            clock: 1,
1048            span: 2,
1049            dependencies: vec![],
1050            operations: vec![1],
1051        };
1052        let second = PatchRow {
1053            clock: 3,
1054            dependencies: vec![(65536, 3)],
1055            ..first.clone()
1056        };
1057        let mut log = PatchLog::new("test");
1058        log.append(&[second.clone()]).unwrap();
1059        assert_eq!(log.vector(), vec![]);
1060        log.append(&[first.clone()]).unwrap();
1061        assert_eq!(log.vector(), vec![(65536, 5)]);
1062        assert_eq!(log.pending_count(), 0);
1063        log.append(&[first.clone(), second]).unwrap();
1064        assert!(log
1065            .append(&[PatchRow {
1066                operations: vec![2],
1067                ..first.clone()
1068            }])
1069            .is_err());
1070        // A row that starts among the writes another row covers is ignored.
1071        log.append(&[PatchRow { clock: 2, ..first }]).unwrap();
1072        assert_eq!(log.len(), 2);
1073        assert!(log.missing(&log.vector()).is_empty());
1074        // A fork: the next row does not build on the actor's history.
1075        let fork = PatchRow {
1076            doc_id: "test".into(),
1077            sid: 65536,
1078            clock: 5,
1079            span: 1,
1080            dependencies: vec![(65536, 4)],
1081            operations: vec![1],
1082        };
1083        assert_eq!(
1084            log.append(&[fork]).unwrap_err().message,
1085            "Actor history fork"
1086        );
1087    }
1088
1089    const A: u64 = 65536;
1090    const B: u64 = 65537;
1091    fn unhex(value: &str) -> Vec<u8> {
1092        (0..value.len())
1093            .step_by(2)
1094            .map(|i| u8::from_str_radix(&value[i..i + 2], 16).unwrap())
1095            .collect()
1096    }
1097    fn own(sid: u64, clock: u64) -> VersionVector {
1098        if clock > 1 {
1099            vec![(sid, clock)]
1100        } else {
1101            vec![]
1102        }
1103    }
1104    /// A row that is not a last-value write.
1105    fn kept(sid: u64, clock: u64) -> PatchRow {
1106        PatchRow {
1107            doc_id: "doc".into(),
1108            sid,
1109            clock,
1110            span: 1,
1111            dependencies: own(sid, clock),
1112            operations: vec![OPERATIONS_VERSION, clock as u8, 0, 1, 3, sid as u8],
1113        }
1114    }
1115    /// One kind 7 write to the numeric field `field` of the node "n".
1116    fn write(sid: u64, clock: u64, lamport: u8, field: u8) -> PatchRow {
1117        PatchRow {
1118            operations: vec![
1119                OPERATIONS_VERSION,
1120                lamport,
1121                0,
1122                1,
1123                7,
1124                1,
1125                b'n',
1126                1,
1127                field,
1128                sid as u8,
1129            ],
1130            ..kept(sid, clock)
1131        }
1132    }
1133    fn spans(log: &PatchLog) -> Vec<(u64, u64, u64)> {
1134        log.missing(&vec![])
1135            .iter()
1136            .map(|row| (row.sid, row.clock, row.span))
1137            .collect()
1138    }
1139
1140    #[test]
1141    fn reads_the_register_of_a_last_value_row() {
1142        // Rows written by the TypeScript engine: a deletion, then assignments
1143        // to a string field and to a numeric one.
1144        for (operations, lamport, register) in [
1145            (
1146                "030520356337343230653061663033343238346437303438313861633038323965383801080936353533363a313a320101",
1147                5,
1148                "0936353533363a313a320101",
1149            ),
1150            (
1151                "030620356337343230653061663033343238346437303438313861633038323965383801070936353533363a313a330001780a0201790000",
1152                6,
1153                "0936353533363a313a33000178",
1154            ),
1155            (
1156                "030720356337343230653061663033343238346437303438313861633038323965383801070936353533363a313a300100030201630000",
1157                7,
1158                "0936353533363a313a300100",
1159            ),
1160        ] {
1161            let operations = unhex(operations);
1162            let last = last_register_of(&operations).unwrap();
1163            assert_eq!((last.lamport, last.register), (lamport, &unhex(register)[..]));
1164            assert!(!is_gap(&operations));
1165            // Cut anywhere inside its head, it is not a last-value row.
1166            let head = operations.len() - last.register.len();
1167            for cut in 0..head {
1168                assert_eq!(last_register_of(&operations[..cut]), None);
1169            }
1170        }
1171        assert!(is_gap(&GAP_OPERATIONS) && is_gap(&[3, 1, 0, 0]));
1172        assert_eq!(last_register_of(&GAP_OPERATIONS), None);
1173        let one = write(A, 1, 9, 2).operations;
1174        assert_eq!(last_register_of(&one).unwrap().register, [1, b'n', 1, 2]);
1175        // Other kinds, two operations, another version or a length beyond the end.
1176        for (at, byte) in [(4, 1), (4, 2), (4, 9), (3, 2), (0, 2), (5, 200)] {
1177            let mut other = one.clone();
1178            other[at] = byte;
1179            assert_eq!(last_register_of(&other), None, "{other:?}");
1180        }
1181        assert!(!is_gap(&[3, 1, 0, 0, 0]) && !is_gap(&[3, 2, 0, 0]) && !is_gap(&[]));
1182    }
1183
1184    #[test]
1185    fn a_register_rewritten_many_times_keeps_one_row() {
1186        let mut log = PatchLog::new("doc");
1187        log.append(&[kept(A, 1), kept(B, 1)]).unwrap();
1188        for clock in 2..=300u64 {
1189            // Two registers of A, and one that B also writes with older times.
1190            let field = (clock % 2) as u8;
1191            log.append(&[write(A, clock, 100, field)]).unwrap();
1192            log.append(&[write(B, clock, 1, 0)]).unwrap();
1193        }
1194        // A: its first row and the last write to each register. B's writes all
1195        // arrived already replaced: its first row covers them.
1196        assert_eq!(
1197            spans(&log),
1198            vec![(A, 1, 298), (A, 299, 1), (A, 300, 1), (B, 1, 300)]
1199        );
1200        assert_eq!(log.vector(), vec![(A, 301), (B, 301)]);
1201        assert_eq!(log.registers.len(), 2);
1202        // The rows that stay are the newest writes.
1203        assert_eq!(
1204            log.missing(&vec![(A, 300), (B, 301)]),
1205            vec![write(A, 300, 100, 0)]
1206        );
1207    }
1208
1209    #[test]
1210    fn a_replaced_first_row_stays_as_a_gap() {
1211        let mut log = PatchLog::new("doc");
1212        log.append(&[write(A, 1, 1, 0)]).unwrap();
1213        log.append(&[write(B, 1, 2, 0)]).unwrap();
1214        let gap = gap_row("doc", A, 1, 1);
1215        assert_eq!(log.missing(&vec![]), vec![gap.clone(), write(B, 1, 2, 0)]);
1216        // The gap takes the replaced writes that follow, and folds into nothing.
1217        log.append(&[write(A, 2, 1, 0)]).unwrap();
1218        assert_eq!(spans(&log), vec![(A, 1, 2), (B, 1, 1)]);
1219        // A peer that kept less sends the same sequence numbers as a gap row.
1220        log.append(&[gap, write(A, 1, 1, 0)]).unwrap();
1221        log.append(&[gap_row("doc", B, 2, 3)]).unwrap();
1222        assert_eq!(spans(&log), vec![(A, 1, 2), (B, 1, 4)]);
1223        assert_eq!(log.vector(), vec![(A, 3), (B, 5)]);
1224    }
1225
1226    #[test]
1227    fn a_known_row_with_a_longer_span_moves_the_frontier() {
1228        let mut log = PatchLog::new("doc");
1229        log.append(&[kept(A, 1), kept(A, 2), kept(A, 7)]).unwrap();
1230        assert_eq!(log.pending_count(), 1);
1231        // The sender replaced two writes after the second one.
1232        let long = PatchRow {
1233            span: 3,
1234            ..kept(A, 2)
1235        };
1236        log.append(std::slice::from_ref(&long)).unwrap();
1237        assert_eq!(log.vector(), vec![(A, 5)]);
1238        assert_eq!(spans(&log), vec![(A, 1, 1), (A, 2, 3), (A, 7, 1)]);
1239        // Sent again, or shorter, it changes nothing; other contents conflict.
1240        log.append(&[long, kept(A, 2), kept(A, 1)]).unwrap();
1241        assert_eq!(log.vector(), vec![(A, 5)]);
1242        let changed = PatchRow {
1243            operations: vec![9],
1244            ..kept(A, 2)
1245        };
1246        assert_eq!(log.append(&[changed]).unwrap_err().code, "CONFLICT");
1247        // Up to a waiting row, which becomes applicable.
1248        log.append(&[PatchRow {
1249            span: 5,
1250            ..kept(A, 2)
1251        }])
1252        .unwrap();
1253        assert_eq!(log.vector(), vec![(A, 8)]);
1254        assert_eq!(spans(&log), vec![(A, 1, 1), (A, 2, 5), (A, 7, 1)]);
1255        assert_eq!(log.pending_count(), 0);
1256    }
1257
1258    #[test]
1259    fn a_row_replaces_the_waiting_rows_its_span_covers() {
1260        let mut log = PatchLog::new("doc");
1261        log.append(&[kept(A, 1), kept(A, 4), kept(A, 5), kept(A, 7)])
1262            .unwrap();
1263        assert_eq!(log.pending_count(), 3);
1264        // A waiting row that starts inside another one's span is dropped.
1265        let wide = PatchRow {
1266            span: 2,
1267            ..kept(A, 4)
1268        };
1269        log.append(&[wide.clone(), kept(A, 5)]).unwrap();
1270        assert_eq!(spans(&log), vec![(A, 1, 1), (A, 4, 2), (A, 7, 1)]);
1271        // The row at the frontier covers every waiting row up to the last.
1272        let long = PatchRow {
1273            span: 5,
1274            ..kept(A, 2)
1275        };
1276        log.append(&[long]).unwrap();
1277        assert_eq!(spans(&log), vec![(A, 1, 1), (A, 2, 5), (A, 7, 1)]);
1278        assert_eq!((log.vector(), log.pending_count()), (vec![(A, 8)], 0));
1279        // What it replaced is ignored from now on, whatever it holds.
1280        log.append(&[wide, kept(A, 5)]).unwrap();
1281        assert_eq!(log.len(), 3);
1282    }
1283
1284    #[test]
1285    fn actor_frontier_does_not_skip_an_undeclared_gap() {
1286        let mut log = PatchLog::new("gap");
1287        log.append(&[PatchRow {
1288            doc_id: "gap".into(),
1289            sid: 65536,
1290            clock: 10,
1291            span: 1,
1292            dependencies: vec![],
1293            operations: vec![1],
1294        }])
1295        .unwrap();
1296        assert!(log.vector().is_empty());
1297        assert_eq!(log.pending_count(), 1);
1298        assert!(encode(&Message {
1299            doc_id: "bad\0id".into(),
1300            request_id: 1,
1301            body: Body::Connect { vv: vec![] }
1302        })
1303        .is_err());
1304    }
1305}