Skip to main content

node_app_replica/
wire.rs

1//! The replication contract's wire shapes (Phase 3 spec, section 4), byte for byte.
2//!
3//! Every type here serializes to the compact JSON the contract prints, with the
4//! keys in the contract's order, whatever `serde_json` features the build
5//! unifies. Deserialization is lenient where the contract is: it ignores keys it
6//! does not know (the capability router stamps `caller` and `caller_ingress`
7//! into every payload) and accepts the short forms of a row entry.
8//!
9//! The golden fixtures in `tests/fixtures/` hold the exact bytes; the TypeScript
10//! helper and the client kernel read the same files.
11
12use std::fmt;
13
14use serde::de::{self, Deserializer, SeqAccess, Visitor};
15use serde::ser::{SerializeMap, SerializeSeq, Serializer};
16use serde::{Deserialize, Serialize};
17use serde_json::Value;
18
19/// A row key: 1–256 bytes of UTF-8 with no control characters.
20pub const MAX_KEY_BYTES: usize = 256;
21/// A row value's encoded (compact JSON) size.
22pub const MAX_VALUE_BYTES: usize = 65_536;
23/// The largest `ord` magnitude and the largest version: 2^53 − 1, exact in a
24/// JavaScript number.
25pub const MAX_SAFE_INTEGER: u64 = (1 << 53) - 1;
26/// A row's `part`: 0–128 bytes of UTF-8.
27pub const MAX_PART_BYTES: usize = 128;
28/// The deepest a row's value may nest, counted as the device's storage counts
29/// it (`isWithinReplicaValueDepth` in `client/ports/src/replica.js`): the value
30/// is level 1 and each container adds a level for what it holds, so 127 nested
31/// containers are accepted and 128 refused. That is exactly what serde_json's
32/// default recursion limit (128) parses, so the node can read every value the
33/// helper serves. See [`value_within_depth`].
34pub const MAX_VALUE_DEPTH: usize = 128;
35/// An epoch: 1–16 characters of `[a-z0-9]`.
36pub const MAX_EPOCH_CHARS: usize = 16;
37/// The rows (upserts plus deletes) one reply carries for one collection.
38pub const MAX_ROWS_PER_REPLY: u32 = 500;
39/// The encoded bytes of the rows one reply carries for one collection.
40pub const MAX_REPLY_ROW_BYTES: usize = 262_144;
41/// Entries in one `core.replica.sync` request.
42pub const MAX_SYNC_ENTRIES: usize = 64;
43/// A whole `core.replica.sync` reply (under node-wire's 1 MiB frame).
44pub const MAX_SYNC_REPLY_BYTES: usize = 786_432;
45
46/// The device's batched check (node core).
47pub const SYNC_CAPABILITY: &str = "core.replica.sync";
48/// The app's "my head moved" notice (node core).
49pub const ANNOUNCE_CAPABILITY: &str = "core.replica.announce";
50/// The node's push to connected devices.
51pub const HEADS_EVENT: &str = "replica.heads";
52/// The capability error prefix for a schema the app does not serve.
53pub const SCHEMA_UNSUPPORTED_PREFIX: &str = "replica_schema_unsupported:";
54
55/// One row of a collection: a key, any JSON value, its order in the list and the
56/// group it belongs to.
57#[derive(Debug, Clone, PartialEq)]
58pub struct Row {
59    /// The row's identity in its collection: 1–256 bytes, no control characters.
60    pub key: String,
61    /// Any JSON value, at most 65,536 bytes encoded and 127 containers deep.
62    pub value: Value,
63    /// The row's position in its list; 0 when the list has no order of its own.
64    pub ord: i64,
65    /// A group the row belongs to (a conversation id for a message); `""` for none.
66    pub part: String,
67}
68
69impl Row {
70    /// A row with `ord` 0 and no `part`.
71    pub fn new(key: impl Into<String>, value: Value) -> Self {
72        Self {
73            key: key.into(),
74            value,
75            ord: 0,
76            part: String::new(),
77        }
78    }
79
80    /// The row with its place in the list (|ord| ≤ 2^53 − 1).
81    pub fn with_ord(mut self, ord: i64) -> Self {
82        self.ord = ord;
83        self
84    }
85
86    /// The row in a group (at most 128 bytes).
87    pub fn with_part(mut self, part: impl Into<String>) -> Self {
88        self.part = part.into();
89        self
90    }
91}
92
93/// `["<key>", <value>, <ord>, "<part>"]`, dropping a trailing `part` of `""` and
94/// then a trailing `ord` of 0: `["k", {…}]` is a complete entry.
95impl Serialize for Row {
96    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
97        let len = if !self.part.is_empty() {
98            4
99        } else if self.ord != 0 {
100            3
101        } else {
102            2
103        };
104        let mut seq = serializer.serialize_seq(Some(len))?;
105        seq.serialize_element(&self.key)?;
106        seq.serialize_element(&CanonicalValue(&self.value))?;
107        if len >= 3 {
108            seq.serialize_element(&self.ord)?;
109        }
110        if len == 4 {
111            seq.serialize_element(&self.part)?;
112        }
113        seq.end()
114    }
115}
116
117impl<'de> Deserialize<'de> for Row {
118    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
119        struct RowVisitor;
120        impl<'de> Visitor<'de> for RowVisitor {
121            type Value = Row;
122            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
123                f.write_str("a row entry [key, value, ord?, part?]")
124            }
125            fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Row, A::Error> {
126                let key: String = seq
127                    .next_element()?
128                    .ok_or_else(|| de::Error::invalid_length(0, &self))?;
129                let value: Value = seq
130                    .next_element()?
131                    .ok_or_else(|| de::Error::invalid_length(1, &self))?;
132                let ord: i64 = seq.next_element()?.unwrap_or(0);
133                let part: String = seq.next_element()?.unwrap_or_default();
134                if seq.next_element::<de::IgnoredAny>()?.is_some() {
135                    return Err(de::Error::invalid_length(5, &self));
136                }
137                Ok(Row {
138                    key,
139                    value,
140                    ord,
141                    part,
142                })
143            }
144        }
145        deserializer.deserialize_seq(RowVisitor)
146    }
147}
148
149/// A JSON value written with its object keys sorted, so a row's bytes do not
150/// depend on whether the build enabled `serde_json/preserve_order`.
151struct CanonicalValue<'a>(&'a Value);
152
153impl Serialize for CanonicalValue<'_> {
154    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
155        match self.0 {
156            Value::Array(items) => {
157                let mut seq = serializer.serialize_seq(Some(items.len()))?;
158                for item in items {
159                    seq.serialize_element(&CanonicalValue(item))?;
160                }
161                seq.end()
162            }
163            Value::Object(object) => {
164                let mut entries: Vec<(&String, &Value)> = object.iter().collect();
165                entries.sort_by(|a, b| a.0.cmp(b.0));
166                let mut map = serializer.serialize_map(Some(entries.len()))?;
167                for (key, value) in entries {
168                    map.serialize_entry(key, &CanonicalValue(value))?;
169                }
170                map.end()
171            }
172            other => other.serialize(serializer),
173        }
174    }
175}
176
177/// The request the node sends an app's pull capability:
178/// `{"e":"k3f9a2c1","v":41,"s":1,"l":500}` plus `"a"` when resuming a paged
179/// full copy.
180#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
181pub struct PullRequest {
182    /// The epoch the caller holds; `""` when it holds nothing.
183    #[serde(rename = "e")]
184    pub epoch: String,
185    /// The version the caller holds.
186    #[serde(rename = "v")]
187    pub version: u64,
188    /// The schema number: the `N` of the consumer's `.vN`.
189    #[serde(rename = "s")]
190    pub schema: u32,
191    /// The most rows to return (at most 500).
192    #[serde(rename = "l", default = "default_limit")]
193    pub limit: u32,
194    /// The last key of the previous page of a paged full copy.
195    #[serde(rename = "a", default, skip_serializing_if = "Option::is_none")]
196    pub resume: Option<String>,
197}
198
199fn default_limit() -> u32 {
200    MAX_ROWS_PER_REPLY
201}
202
203impl PullRequest {
204    /// "I hold nothing": the first request for a collection.
205    pub fn initial(schema: u32) -> Self {
206        Self {
207            epoch: String::new(),
208            version: 0,
209            schema,
210            limit: MAX_ROWS_PER_REPLY,
211            resume: None,
212        }
213    }
214
215    /// Checks the request against the contract's limits. A limit above 500 is
216    /// not an error; the helper serves 500.
217    pub fn validate(&self) -> Result<(), String> {
218        if !self.epoch.is_empty() && !is_epoch(&self.epoch) {
219            return Err("e must be \"\" or 1-16 characters of [a-z0-9]".to_string());
220        }
221        if self.version > MAX_SAFE_INTEGER {
222            return Err("v must be at most 2^53 - 1".to_string());
223        }
224        if self.limit == 0 {
225            return Err("l must be at least 1".to_string());
226        }
227        if let Some(resume) = &self.resume {
228            validate_key(resume).map_err(|reason| format!("a {reason}"))?;
229            if self.epoch.is_empty() {
230                return Err("a resumes a full copy and needs that copy's e".to_string());
231            }
232        }
233        Ok(())
234    }
235
236    /// The row limit the helper serves: `l`, capped at 500.
237    pub fn effective_limit(&self) -> usize {
238        self.limit.min(MAX_ROWS_PER_REPLY) as usize
239    }
240}
241
242/// An app's answer to one pull (section 4.2).
243#[derive(Debug, Clone, PartialEq)]
244pub enum PullReply {
245    /// `{"e":"k3f9a2c1","v":41}`
246    NothingNew {
247        /// The ledger's epoch.
248        epoch: String,
249        /// The ledger's head, which the caller already holds.
250        version: u64,
251    },
252    /// `{"e":…,"v":43,"u":[…],"x":[…]}` plus `"m":1` when more remain.
253    Changes {
254        /// The ledger's epoch, the caller's too.
255        epoch: String,
256        /// The version the caller holds once it applied these changes: the head,
257        /// or, when cut (`more`), the version just before the first change whose
258        /// earlier value the ledger no longer knows.
259        version: u64,
260        /// Rows added or changed, in version order.
261        upserts: Vec<Row>,
262        /// Keys deleted.
263        deletes: Vec<String>,
264        /// More changes remain: ask again from `version`.
265        more: bool,
266    },
267    /// `{"e":…,"v":7,"f":1,"u":[…]}` plus `"n":"<last key>"` when more pages
268    /// remain, and `"h"` on a later page read after the head moved. Rows are in
269    /// key order.
270    FullCopy {
271        /// The epoch the copy is in.
272        epoch: String,
273        /// The copy's version: the head when page one was read. Every page of
274        /// one copy carries it, and the caller asks for the changes since it once
275        /// the last page is in.
276        version: u64,
277        /// The rows of this page, as they are when it is read.
278        rows: Vec<Row>,
279        /// The last key of this page when more pages remain.
280        next: Option<String>,
281        /// `"h"`, for the node only: the head when a later page was read, when it
282        /// is above `version`. The page's rows can be that new, so the node raises
283        /// its mark for the epoch to it; it is not passed to the device.
284        head: Option<u64>,
285    },
286}
287
288impl PullReply {
289    /// The reply's epoch.
290    pub fn epoch(&self) -> &str {
291        match self {
292            PullReply::NothingNew { epoch, .. }
293            | PullReply::Changes { epoch, .. }
294            | PullReply::FullCopy { epoch, .. } => epoch,
295        }
296    }
297
298    /// The version the caller holds once it applied the reply (for a full copy,
299    /// once its last page is in).
300    pub fn version(&self) -> u64 {
301        match self {
302            PullReply::NothingNew { version, .. }
303            | PullReply::Changes { version, .. }
304            | PullReply::FullCopy { version, .. } => *version,
305        }
306    }
307
308    /// The highest version whose data the reply can carry: `version`, or `"h"`
309    /// on a later page of a full copy. The node keeps, per epoch, the highest of
310    /// these it has passed on, and answers an announce below it with `rotate`.
311    pub fn handed_out(&self) -> u64 {
312        match self {
313            PullReply::FullCopy {
314                version,
315                head: Some(head),
316                ..
317            } => (*version).max(*head),
318            other => other.version(),
319        }
320    }
321
322    /// True when the caller must ask again to get the rest (`"m":1` or `"n"`).
323    /// The node records a reply's head only when this is false.
324    pub fn is_truncated(&self) -> bool {
325        match self {
326            PullReply::NothingNew { .. } => false,
327            PullReply::Changes { more, .. } => *more,
328            PullReply::FullCopy { next, .. } => next.is_some(),
329        }
330    }
331}
332
333impl Serialize for PullReply {
334    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
335        match self {
336            PullReply::NothingNew { epoch, version } => {
337                let mut map = serializer.serialize_map(Some(2))?;
338                map.serialize_entry("e", epoch)?;
339                map.serialize_entry("v", version)?;
340                map.end()
341            }
342            PullReply::Changes {
343                epoch,
344                version,
345                upserts,
346                deletes,
347                more,
348            } => {
349                let mut map = serializer.serialize_map(None)?;
350                map.serialize_entry("e", epoch)?;
351                serialize_changes_body(&mut map, *version, upserts, deletes, *more)?;
352                map.end()
353            }
354            PullReply::FullCopy {
355                epoch,
356                version,
357                rows,
358                next,
359                head,
360            } => {
361                let mut map = serializer.serialize_map(None)?;
362                serialize_full_copy_body(&mut map, epoch, *version, rows, next)?;
363                if let Some(head) = head {
364                    map.serialize_entry("h", head)?;
365                }
366                map.end()
367            }
368        }
369    }
370}
371
372fn serialize_changes_body<M: SerializeMap>(
373    map: &mut M,
374    version: u64,
375    upserts: &[Row],
376    deletes: &[String],
377    more: bool,
378) -> Result<(), M::Error> {
379    map.serialize_entry("v", &version)?;
380    map.serialize_entry("u", upserts)?;
381    map.serialize_entry("x", deletes)?;
382    if more {
383        map.serialize_entry("m", &1u8)?;
384    }
385    Ok(())
386}
387
388fn serialize_full_copy_body<M: SerializeMap>(
389    map: &mut M,
390    epoch: &str,
391    version: u64,
392    rows: &[Row],
393    next: &Option<String>,
394) -> Result<(), M::Error> {
395    map.serialize_entry("e", epoch)?;
396    map.serialize_entry("v", &version)?;
397    map.serialize_entry("f", &1u8)?;
398    map.serialize_entry("u", rows)?;
399    if let Some(next) = next {
400        map.serialize_entry("n", next)?;
401    }
402    Ok(())
403}
404
405/// Every key either reply object may carry; unknown keys are ignored.
406#[derive(Deserialize)]
407struct RawReply {
408    #[serde(default)]
409    e: Option<String>,
410    v: u64,
411    #[serde(default)]
412    f: Option<u8>,
413    #[serde(default)]
414    u: Option<Vec<Row>>,
415    #[serde(default)]
416    x: Option<Vec<String>>,
417    #[serde(default)]
418    m: Option<u8>,
419    #[serde(default)]
420    n: Option<String>,
421    #[serde(default)]
422    h: Option<u64>,
423}
424
425fn flag<E: de::Error>(name: &str, value: Option<u8>) -> Result<bool, E> {
426    match value {
427        None => Ok(false),
428        Some(1) => Ok(true),
429        Some(other) => Err(E::custom(format!(
430            "{name} must be 1 when present, got {other}"
431        ))),
432    }
433}
434
435impl<'de> Deserialize<'de> for PullReply {
436    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
437        let raw = RawReply::deserialize(deserializer)?;
438        let epoch = raw.e.ok_or_else(|| de::Error::missing_field("e"))?;
439        if flag::<D::Error>("f", raw.f)? {
440            return Ok(PullReply::FullCopy {
441                epoch,
442                version: raw.v,
443                rows: raw.u.unwrap_or_default(),
444                next: raw.n,
445                head: raw.h,
446            });
447        }
448        if raw.u.is_some() || raw.x.is_some() {
449            return Ok(PullReply::Changes {
450                epoch,
451                version: raw.v,
452                upserts: raw.u.unwrap_or_default(),
453                deletes: raw.x.unwrap_or_default(),
454                more: flag::<D::Error>("m", raw.m)?,
455            });
456        }
457        Ok(PullReply::NothingNew {
458            epoch,
459            version: raw.v,
460        })
461    }
462}
463
464/// One entry of a device check: `[pullCapability, schema, epoch, version]`, plus
465/// the resume key of a paged full copy as a fifth element.
466#[derive(Debug, Clone, PartialEq, Eq)]
467pub struct SyncEntry {
468    /// The pull capability (`friends.people.pull`).
469    pub capability: String,
470    /// The schema number the device reads.
471    pub schema: u32,
472    /// The epoch it holds (`""` for none); during a paged copy, page one's.
473    pub epoch: String,
474    /// The version it holds; during a paged copy, page one's.
475    pub version: u64,
476    /// The last key of the previous page, while a paged full copy is in progress.
477    pub resume: Option<String>,
478}
479
480impl SyncEntry {
481    /// The pull request the node sends the app for this entry.
482    pub fn pull_request(&self, limit: u32) -> PullRequest {
483        PullRequest {
484            epoch: self.epoch.clone(),
485            version: self.version,
486            schema: self.schema,
487            limit,
488            resume: self.resume.clone(),
489        }
490    }
491}
492
493impl Serialize for SyncEntry {
494    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
495        let len = if self.resume.is_some() { 5 } else { 4 };
496        let mut seq = serializer.serialize_seq(Some(len))?;
497        seq.serialize_element(&self.capability)?;
498        seq.serialize_element(&self.schema)?;
499        seq.serialize_element(&self.epoch)?;
500        seq.serialize_element(&self.version)?;
501        if let Some(resume) = &self.resume {
502            seq.serialize_element(resume)?;
503        }
504        seq.end()
505    }
506}
507
508impl<'de> Deserialize<'de> for SyncEntry {
509    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
510        struct EntryVisitor;
511        impl<'de> Visitor<'de> for EntryVisitor {
512            type Value = SyncEntry;
513            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
514                f.write_str("a sync entry [capability, schema, epoch, version, resume?]")
515            }
516            fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<SyncEntry, A::Error> {
517                let capability: String = seq
518                    .next_element()?
519                    .ok_or_else(|| de::Error::invalid_length(0, &self))?;
520                let schema: u32 = seq
521                    .next_element()?
522                    .ok_or_else(|| de::Error::invalid_length(1, &self))?;
523                let epoch: String = seq
524                    .next_element()?
525                    .ok_or_else(|| de::Error::invalid_length(2, &self))?;
526                let version: u64 = seq
527                    .next_element()?
528                    .ok_or_else(|| de::Error::invalid_length(3, &self))?;
529                let resume: Option<String> = seq.next_element()?;
530                if seq.next_element::<de::IgnoredAny>()?.is_some() {
531                    return Err(de::Error::invalid_length(6, &self));
532                }
533                Ok(SyncEntry {
534                    capability,
535                    schema,
536                    epoch,
537                    version,
538                    resume,
539                })
540            }
541        }
542        deserializer.deserialize_seq(EntryVisitor)
543    }
544}
545
546/// The payload of `core.replica.sync`: `{"c":[[…],[…]]}`, plus
547/// `"origin":"background"` on checks no person is waiting for.
548#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
549pub struct SyncRequest {
550    /// The entries, at most 64.
551    #[serde(rename = "c")]
552    pub entries: Vec<SyncEntry>,
553    /// `"background"` on checks no person is waiting for.
554    #[serde(default, skip_serializing_if = "Option::is_none")]
555    pub origin: Option<String>,
556}
557
558/// Why the node could not answer one entry of a check.
559#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
560#[serde(rename_all = "lowercase")]
561pub enum SyncErrorCode {
562    /// No provider is registered for the capability.
563    Unknown,
564    /// The app does not serve the schema asked for.
565    Schema,
566    /// The app did not answer in time.
567    Unavailable,
568    /// The reply size cap was reached; ask again.
569    Busy,
570}
571
572impl SyncErrorCode {
573    /// The code as it travels: `unknown`, `schema`, `unavailable` or `busy`.
574    pub fn as_str(self) -> &'static str {
575        match self {
576            SyncErrorCode::Unknown => "unknown",
577            SyncErrorCode::Schema => "schema",
578            SyncErrorCode::Unavailable => "unavailable",
579            SyncErrorCode::Busy => "busy",
580        }
581    }
582
583    /// The code for its wire text; `None` for an unknown one.
584    pub fn parse(value: &str) -> Option<Self> {
585        match value {
586            "unknown" => Some(SyncErrorCode::Unknown),
587            "schema" => Some(SyncErrorCode::Schema),
588            "unavailable" => Some(SyncErrorCode::Unavailable),
589            "busy" => Some(SyncErrorCode::Busy),
590            _ => None,
591        }
592    }
593}
594
595/// The node's answer for one entry of a check (section 4.3): `0`, the changes
596/// (without `e`, which the device already holds), a full copy, or an error.
597#[derive(Debug, Clone, PartialEq)]
598pub enum SyncAnswer {
599    /// `0`: the device holds the head.
600    NothingNew,
601    /// `{"v":43,"u":[…],"x":[…]}` plus `"m":1`: see [`PullReply::Changes`].
602    Changes {
603        /// The version the device holds once it applied them.
604        version: u64,
605        /// Rows added or changed.
606        upserts: Vec<Row>,
607        /// Keys deleted.
608        deletes: Vec<String>,
609        /// More remain: ask again from `version`.
610        more: bool,
611    },
612    /// `{"e":…,"v":7,"f":1,"u":[…]}` plus `"n"`: see [`PullReply::FullCopy`]
613    /// (without `"h"`, which is for the node).
614    FullCopy {
615        /// The copy's epoch.
616        epoch: String,
617        /// The copy's version; every page of one copy carries page one's.
618        version: u64,
619        /// This page's rows, in key order.
620        rows: Vec<Row>,
621        /// The resume key for the next page, when more remain.
622        next: Option<String>,
623    },
624    /// `{"err":"<code>"}`.
625    Error(SyncErrorCode),
626}
627
628impl From<PullReply> for SyncAnswer {
629    fn from(reply: PullReply) -> Self {
630        match reply {
631            PullReply::NothingNew { .. } => SyncAnswer::NothingNew,
632            PullReply::Changes {
633                version,
634                upserts,
635                deletes,
636                more,
637                ..
638            } => SyncAnswer::Changes {
639                version,
640                upserts,
641                deletes,
642                more,
643            },
644            // `h` is for the node; the device continues a copy by its `(e, v)`.
645            PullReply::FullCopy {
646                epoch,
647                version,
648                rows,
649                next,
650                ..
651            } => SyncAnswer::FullCopy {
652                epoch,
653                version,
654                rows,
655                next,
656            },
657        }
658    }
659}
660
661impl Serialize for SyncAnswer {
662    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
663        match self {
664            SyncAnswer::NothingNew => serializer.serialize_u8(0),
665            SyncAnswer::Changes {
666                version,
667                upserts,
668                deletes,
669                more,
670            } => {
671                let mut map = serializer.serialize_map(None)?;
672                serialize_changes_body(&mut map, *version, upserts, deletes, *more)?;
673                map.end()
674            }
675            SyncAnswer::FullCopy {
676                epoch,
677                version,
678                rows,
679                next,
680            } => {
681                let mut map = serializer.serialize_map(None)?;
682                serialize_full_copy_body(&mut map, epoch, *version, rows, next)?;
683                map.end()
684            }
685            SyncAnswer::Error(code) => {
686                let mut map = serializer.serialize_map(Some(1))?;
687                map.serialize_entry("err", code.as_str())?;
688                map.end()
689            }
690        }
691    }
692}
693
694impl<'de> Deserialize<'de> for SyncAnswer {
695    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
696        let value = Value::deserialize(deserializer)?;
697        match &value {
698            Value::Number(number) if number.as_u64() == Some(0) => Ok(SyncAnswer::NothingNew),
699            Value::Object(object) => {
700                if let Some(code) = object.get("err") {
701                    let code = code
702                        .as_str()
703                        .and_then(SyncErrorCode::parse)
704                        .ok_or_else(|| de::Error::custom("err must be a known error code"))?;
705                    return Ok(SyncAnswer::Error(code));
706                }
707                let raw = RawReply::deserialize(value).map_err(de::Error::custom)?;
708                if flag::<D::Error>("f", raw.f)? {
709                    let epoch = raw.e.ok_or_else(|| de::Error::missing_field("e"))?;
710                    return Ok(SyncAnswer::FullCopy {
711                        epoch,
712                        version: raw.v,
713                        rows: raw.u.unwrap_or_default(),
714                        next: raw.n,
715                    });
716                }
717                Ok(SyncAnswer::Changes {
718                    version: raw.v,
719                    upserts: raw.u.unwrap_or_default(),
720                    deletes: raw.x.unwrap_or_default(),
721                    more: flag::<D::Error>("m", raw.m)?,
722                })
723            }
724            _ => Err(de::Error::custom(
725                "a sync answer is 0, a changes object, a full copy or an error",
726            )),
727        }
728    }
729}
730
731/// The `result` of `core.replica.sync`: `{"r":[…]}`, aligned with the request's
732/// entries by index.
733#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
734pub struct SyncReply {
735    /// One answer per entry, in the request's order.
736    #[serde(rename = "r")]
737    pub answers: Vec<SyncAnswer>,
738}
739
740/// The payload of `core.replica.announce`: `{"c":"friends.people.pull","e":"k3f9a2c1","v":42}`.
741#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
742pub struct Announce {
743    /// The pull capability whose head moved.
744    #[serde(rename = "c")]
745    pub capability: String,
746    /// Its epoch.
747    #[serde(rename = "e")]
748    pub epoch: String,
749    /// Its head.
750    #[serde(rename = "v")]
751    pub version: u64,
752}
753
754/// The node's answer to an announce: `{"ok":true}`, or `{"rotate":true}` when it
755/// has handed out a higher version of that epoch (the app's data went back in
756/// time).
757#[derive(Debug, Clone, Copy, PartialEq, Eq)]
758pub enum AnnounceReply {
759    /// `{"ok":true}`: the node took the head.
760    Ok,
761    /// `{"rotate":true}`: start a new epoch and announce again.
762    Rotate,
763}
764
765impl Serialize for AnnounceReply {
766    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
767        let mut map = serializer.serialize_map(Some(1))?;
768        match self {
769            AnnounceReply::Ok => map.serialize_entry("ok", &true)?,
770            AnnounceReply::Rotate => map.serialize_entry("rotate", &true)?,
771        }
772        map.end()
773    }
774}
775
776impl<'de> Deserialize<'de> for AnnounceReply {
777    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
778        #[derive(Deserialize)]
779        struct Raw {
780            #[serde(default)]
781            ok: bool,
782            #[serde(default)]
783            rotate: bool,
784        }
785        let raw = Raw::deserialize(deserializer)?;
786        if raw.rotate {
787            Ok(AnnounceReply::Rotate)
788        } else if raw.ok {
789            Ok(AnnounceReply::Ok)
790        } else {
791            Err(de::Error::custom(
792                "an announce reply is {\"ok\":true} or {\"rotate\":true}",
793            ))
794        }
795    }
796}
797
798/// One head in a `replica.heads` push: `["friends.people.pull","k3f9a2c1",42]`.
799#[derive(Debug, Clone, PartialEq, Eq)]
800pub struct PushedHead {
801    /// The pull capability.
802    pub capability: String,
803    /// Its epoch.
804    pub epoch: String,
805    /// Its head.
806    pub version: u64,
807}
808
809impl Serialize for PushedHead {
810    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
811        (&self.capability, &self.epoch, self.version).serialize(serializer)
812    }
813}
814
815impl<'de> Deserialize<'de> for PushedHead {
816    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
817        let (capability, epoch, version) = <(String, String, u64)>::deserialize(deserializer)?;
818        Ok(PushedHead {
819            capability,
820            epoch,
821            version,
822        })
823    }
824}
825
826/// The `data` of a `replica.heads` frame: `{"h":[[…]]}`.
827#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
828pub struct HeadsData {
829    /// The heads, one per capability that moved.
830    #[serde(rename = "h")]
831    pub heads: Vec<PushedHead>,
832}
833
834/// `[a-z0-9]{1,16}`.
835pub fn is_epoch(value: &str) -> bool {
836    !value.is_empty()
837        && value.len() <= MAX_EPOCH_CHARS
838        && value
839            .bytes()
840            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
841}
842
843/// A row key: 1–256 bytes, no control characters.
844pub fn validate_key(key: &str) -> Result<(), String> {
845    if key.is_empty() {
846        return Err("key must not be empty".to_string());
847    }
848    if key.len() > MAX_KEY_BYTES {
849        return Err(format!(
850            "key is {} bytes; at most {MAX_KEY_BYTES} are allowed",
851            key.len()
852        ));
853    }
854    if key.chars().any(char::is_control) {
855        return Err("key must not contain control characters".to_string());
856    }
857    Ok(())
858}
859
860/// Whether `value` nests no deeper than [`MAX_VALUE_DEPTH`] levels. Walks the
861/// value with an explicit stack and stops at the first level past the limit, so
862/// a deep value is refused without using the call stack. The same rule as the
863/// device's `isWithinReplicaValueDepth` and the TypeScript helper's
864/// `isWithinValueDepth`; `tests/fixtures/value-depth.json` holds the shared cases.
865pub fn value_within_depth(value: &Value) -> bool {
866    let mut stack: Vec<(usize, &Value)> = vec![(1, value)];
867    while let Some((level, value)) = stack.pop() {
868        let is_container = matches!(value, Value::Array(_) | Value::Object(_));
869        if is_container && level >= MAX_VALUE_DEPTH {
870            return false;
871        }
872        match value {
873            Value::Array(items) => stack.extend(items.iter().map(|child| (level + 1, child))),
874            Value::Object(object) => stack.extend(object.values().map(|child| (level + 1, child))),
875            _ => {}
876        }
877    }
878    true
879}
880
881/// The refusal of a value past [`MAX_VALUE_DEPTH`], the same text as the
882/// TypeScript helper's.
883pub(crate) const VALUE_TOO_DEEP: &str =
884    "value nests 128 or more containers; at most 127 are allowed (the node's JSON limit)";
885
886/// The bytes one row adds inside `u` (its entry plus a separating comma).
887pub(crate) fn encoded_row_bytes(row: &Row) -> usize {
888    crate::digest::json_len_of_str(&row.key)
889        + crate::digest::canonical_len(&row.value)
890        + match (row.ord, row.part.is_empty()) {
891            (0, true) => 0,
892            (ord, true) => 1 + ord.to_string().len(),
893            (ord, false) => 2 + ord.to_string().len() + crate::digest::json_len_of_str(&row.part),
894        }
895        // `[`, the comma after the key, `]`, and the comma before the next entry.
896        + 4
897}
898
899/// The bytes one delete adds inside `x`.
900pub(crate) fn encoded_delete_bytes(key: &str) -> usize {
901    crate::digest::json_len_of_str(key) + 1
902}