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)]
181#[serde(from = "LegacyPullFields")]
182pub struct PullRequest {
183    /// The epoch the caller holds; `""` when it holds nothing.
184    #[serde(rename = "e")]
185    pub epoch: String,
186    /// The version the caller holds.
187    #[serde(rename = "v")]
188    pub version: u64,
189    /// The schema number: the `N` of the consumer's `.vN`.
190    #[serde(rename = "s")]
191    pub schema: u32,
192    /// The most rows to return (at most 500).
193    #[serde(rename = "l", default = "default_limit")]
194    pub limit: u32,
195    /// The last key of the previous page of a paged full copy.
196    #[serde(rename = "a", default, skip_serializing_if = "Option::is_none")]
197    pub resume: Option<String>,
198}
199
200// A legacy provider cannot safely answer a custom window as its ordinary collection.
201// WindowedPullRequest claims this field before forwarding the other fields here.
202#[derive(Deserialize)]
203struct LegacyPullFields {
204    e: String,
205    v: u64,
206    s: u32,
207    #[serde(default = "default_limit")]
208    l: u32,
209    a: Option<String>,
210    #[serde(
211        default,
212        rename = "window_days",
213        deserialize_with = "refuse_legacy_window"
214    )]
215    _window: (),
216}
217
218fn refuse_legacy_window<'de, D: Deserializer<'de>>(_: D) -> Result<(), D::Error> {
219    Err(de::Error::custom(
220        "custom history requires WindowedPullRequest",
221    ))
222}
223
224impl From<LegacyPullFields> for PullRequest {
225    fn from(fields: LegacyPullFields) -> Self {
226        Self {
227            epoch: fields.e,
228            version: fields.v,
229            schema: fields.s,
230            limit: fields.l,
231            resume: fields.a,
232        }
233    }
234}
235
236/// A positive history window representable on a JavaScript device.
237#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
238#[serde(try_from = "u64")]
239pub struct WindowDays(u64);
240
241impl TryFrom<u64> for WindowDays {
242    type Error = &'static str;
243
244    fn try_from(value: u64) -> Result<Self, Self::Error> {
245        if (1..=MAX_SAFE_INTEGER).contains(&value) {
246            Ok(Self(value))
247        } else {
248            Err("window_days must be a positive safe integer")
249        }
250    }
251}
252
253impl WindowDays {
254    /// Number of days requested by the device.
255    pub fn get(self) -> u64 {
256        self.0
257    }
258}
259
260// When present, the field is a number; explicit JSON null is invalid.
261fn present_days<'de, D: Deserializer<'de>>(d: D) -> Result<Option<WindowDays>, D::Error> {
262    WindowDays::deserialize(d).map(Some)
263}
264
265fn check_window_source(capability: &str, days: Option<WindowDays>) -> Result<(), &'static str> {
266    if days.is_none() {
267        return Ok(());
268    }
269    let recent = capability
270        .split_once('.')
271        .is_some_and(|(provider, collection)| {
272            !provider.is_empty()
273                && collection
274                    .strip_prefix("recent_")
275                    .and_then(|s| s.strip_suffix(".pull"))
276                    .is_some_and(|list| !list.is_empty() && !list.contains('.'))
277        });
278    if recent {
279        Ok(())
280    } else {
281        Err("window_days requires a recent collection")
282    }
283}
284
285/// The provider request for one of a recent collection's windows (ADR-395).
286/// Older four/five-slot requests reach the same provider without a day count.
287#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
288pub struct WindowedPullRequest {
289    /// The request cursor, schema and page limits.
290    #[serde(flatten)]
291    pub request: PullRequest,
292    /// The requested custom window. An absent count uses the default projection.
293    #[serde(
294        default,
295        deserialize_with = "present_days",
296        skip_serializing_if = "Option::is_none"
297    )]
298    pub window_days: Option<WindowDays>,
299}
300
301fn default_limit() -> u32 {
302    MAX_ROWS_PER_REPLY
303}
304
305impl PullRequest {
306    /// "I hold nothing": the first request for a collection.
307    pub fn initial(schema: u32) -> Self {
308        Self {
309            epoch: String::new(),
310            version: 0,
311            schema,
312            limit: MAX_ROWS_PER_REPLY,
313            resume: None,
314        }
315    }
316
317    /// Checks the request against the contract's limits. A limit above 500 is
318    /// not an error; the helper serves 500.
319    pub fn validate(&self) -> Result<(), String> {
320        if !self.epoch.is_empty() && !is_epoch(&self.epoch) {
321            return Err("e must be \"\" or 1-16 characters of [a-z0-9]".to_string());
322        }
323        if self.version > MAX_SAFE_INTEGER {
324            return Err("v must be at most 2^53 - 1".to_string());
325        }
326        if self.limit == 0 {
327            return Err("l must be at least 1".to_string());
328        }
329        if let Some(resume) = &self.resume {
330            validate_key(resume).map_err(|reason| format!("a {reason}"))?;
331            if self.epoch.is_empty() {
332                return Err("a resumes a full copy and needs that copy's e".to_string());
333            }
334        }
335        Ok(())
336    }
337
338    /// The row limit the helper serves: `l`, capped at 500.
339    pub fn effective_limit(&self) -> usize {
340        self.limit.min(MAX_ROWS_PER_REPLY) as usize
341    }
342}
343
344/// An app's answer to one pull (section 4.2).
345#[derive(Debug, Clone, PartialEq)]
346pub enum PullReply {
347    /// `{"e":"k3f9a2c1","v":41}`
348    NothingNew {
349        /// The ledger's epoch.
350        epoch: String,
351        /// The ledger's head, which the caller already holds.
352        version: u64,
353    },
354    /// `{"e":…,"v":43,"u":[…],"x":[…]}` plus `"m":1` when more remain.
355    Changes {
356        /// The ledger's epoch, the caller's too.
357        epoch: String,
358        /// The version the caller holds once it applied these changes: the head,
359        /// or, when cut (`more`), the version just before the first change whose
360        /// earlier value the ledger no longer knows.
361        version: u64,
362        /// Rows added or changed, in version order.
363        upserts: Vec<Row>,
364        /// Keys deleted.
365        deletes: Vec<String>,
366        /// More changes remain: ask again from `version`.
367        more: bool,
368    },
369    /// `{"e":…,"v":7,"f":1,"u":[…]}` plus `"n":"<last key>"` when more pages
370    /// remain, and `"h"` on a later page read after the head moved. Rows are in
371    /// key order.
372    FullCopy {
373        /// The epoch the copy is in.
374        epoch: String,
375        /// The copy's version: the head when page one was read. Every page of
376        /// one copy carries it, and the caller asks for the changes since it once
377        /// the last page is in.
378        version: u64,
379        /// The rows of this page, as they are when it is read.
380        rows: Vec<Row>,
381        /// The last key of this page when more pages remain.
382        next: Option<String>,
383        /// `"h"`, for the node only: the head when a later page was read, when it
384        /// is above `version`. The page's rows can be that new, so the node raises
385        /// its mark for the epoch to it; it is not passed to the device.
386        head: Option<u64>,
387    },
388}
389
390impl PullReply {
391    /// The reply's epoch.
392    pub fn epoch(&self) -> &str {
393        match self {
394            PullReply::NothingNew { epoch, .. }
395            | PullReply::Changes { epoch, .. }
396            | PullReply::FullCopy { epoch, .. } => epoch,
397        }
398    }
399
400    /// The version the caller holds once it applied the reply (for a full copy,
401    /// once its last page is in).
402    pub fn version(&self) -> u64 {
403        match self {
404            PullReply::NothingNew { version, .. }
405            | PullReply::Changes { version, .. }
406            | PullReply::FullCopy { version, .. } => *version,
407        }
408    }
409
410    /// The highest version whose data the reply can carry: `version`, or `"h"`
411    /// on a later page of a full copy. The node keeps, per epoch, the highest of
412    /// these it has passed on, and answers an announce below it with `rotate`.
413    pub fn handed_out(&self) -> u64 {
414        match self {
415            PullReply::FullCopy {
416                version,
417                head: Some(head),
418                ..
419            } => (*version).max(*head),
420            other => other.version(),
421        }
422    }
423
424    /// True when the caller must ask again to get the rest (`"m":1` or `"n"`).
425    /// The node records a reply's head only when this is false.
426    pub fn is_truncated(&self) -> bool {
427        match self {
428            PullReply::NothingNew { .. } => false,
429            PullReply::Changes { more, .. } => *more,
430            PullReply::FullCopy { next, .. } => next.is_some(),
431        }
432    }
433}
434
435impl Serialize for PullReply {
436    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
437        match self {
438            PullReply::NothingNew { epoch, version } => {
439                let mut map = serializer.serialize_map(Some(2))?;
440                map.serialize_entry("e", epoch)?;
441                map.serialize_entry("v", version)?;
442                map.end()
443            }
444            PullReply::Changes {
445                epoch,
446                version,
447                upserts,
448                deletes,
449                more,
450            } => {
451                let mut map = serializer.serialize_map(None)?;
452                map.serialize_entry("e", epoch)?;
453                serialize_changes_body(&mut map, *version, upserts, deletes, *more)?;
454                map.end()
455            }
456            PullReply::FullCopy {
457                epoch,
458                version,
459                rows,
460                next,
461                head,
462            } => {
463                let mut map = serializer.serialize_map(None)?;
464                serialize_full_copy_body(&mut map, epoch, *version, rows, next)?;
465                if let Some(head) = head {
466                    map.serialize_entry("h", head)?;
467                }
468                map.end()
469            }
470        }
471    }
472}
473
474fn serialize_changes_body<M: SerializeMap>(
475    map: &mut M,
476    version: u64,
477    upserts: &[Row],
478    deletes: &[String],
479    more: bool,
480) -> Result<(), M::Error> {
481    map.serialize_entry("v", &version)?;
482    map.serialize_entry("u", upserts)?;
483    map.serialize_entry("x", deletes)?;
484    if more {
485        map.serialize_entry("m", &1u8)?;
486    }
487    Ok(())
488}
489
490fn serialize_full_copy_body<M: SerializeMap>(
491    map: &mut M,
492    epoch: &str,
493    version: u64,
494    rows: &[Row],
495    next: &Option<String>,
496) -> Result<(), M::Error> {
497    map.serialize_entry("e", epoch)?;
498    map.serialize_entry("v", &version)?;
499    map.serialize_entry("f", &1u8)?;
500    map.serialize_entry("u", rows)?;
501    if let Some(next) = next {
502        map.serialize_entry("n", next)?;
503    }
504    Ok(())
505}
506
507/// Every key either reply object may carry; unknown keys are ignored.
508#[derive(Deserialize)]
509struct RawReply {
510    #[serde(default)]
511    e: Option<String>,
512    v: u64,
513    #[serde(default)]
514    f: Option<u8>,
515    #[serde(default)]
516    u: Option<Vec<Row>>,
517    #[serde(default)]
518    x: Option<Vec<String>>,
519    #[serde(default)]
520    m: Option<u8>,
521    #[serde(default)]
522    n: Option<String>,
523    #[serde(default)]
524    h: Option<u64>,
525}
526
527fn flag<E: de::Error>(name: &str, value: Option<u8>) -> Result<bool, E> {
528    match value {
529        None => Ok(false),
530        Some(1) => Ok(true),
531        Some(other) => Err(E::custom(format!(
532            "{name} must be 1 when present, got {other}"
533        ))),
534    }
535}
536
537impl<'de> Deserialize<'de> for PullReply {
538    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
539        let raw = RawReply::deserialize(deserializer)?;
540        let epoch = raw.e.ok_or_else(|| de::Error::missing_field("e"))?;
541        if flag::<D::Error>("f", raw.f)? {
542            return Ok(PullReply::FullCopy {
543                epoch,
544                version: raw.v,
545                rows: raw.u.unwrap_or_default(),
546                next: raw.n,
547                head: raw.h,
548            });
549        }
550        if raw.u.is_some() || raw.x.is_some() {
551            return Ok(PullReply::Changes {
552                epoch,
553                version: raw.v,
554                upserts: raw.u.unwrap_or_default(),
555                deletes: raw.x.unwrap_or_default(),
556                more: flag::<D::Error>("m", raw.m)?,
557            });
558        }
559        Ok(PullReply::NothingNew {
560            epoch,
561            version: raw.v,
562        })
563    }
564}
565
566/// One entry of a device check: `[pullCapability, schema, epoch, version]`, plus
567/// the resume key of a paged full copy as a fifth element.
568#[derive(Debug, Clone, PartialEq, Eq)]
569pub struct SyncEntry {
570    /// The pull capability (`friends.people.pull`).
571    pub capability: String,
572    /// The schema number the device reads.
573    pub schema: u32,
574    /// The epoch it holds (`""` for none); during a paged copy, page one's.
575    pub epoch: String,
576    /// The version it holds; during a paged copy, page one's.
577    pub version: u64,
578    /// The last key of the previous page, while a paged full copy is in progress.
579    pub resume: Option<String>,
580}
581
582impl SyncEntry {
583    /// The pull request the node sends the app for this entry.
584    pub fn pull_request(&self, limit: u32) -> PullRequest {
585        PullRequest {
586            epoch: self.epoch.clone(),
587            version: self.version,
588            schema: self.schema,
589            limit,
590            resume: self.resume.clone(),
591        }
592    }
593}
594
595impl SyncEntry {
596    fn serialize_with_days<S: Serializer>(
597        &self,
598        serializer: S,
599        days: Option<WindowDays>,
600    ) -> Result<S::Ok, S::Error> {
601        check_window_source(&self.capability, days).map_err(serde::ser::Error::custom)?;
602        let len = if days.is_some() {
603            6
604        } else if self.resume.is_some() {
605            5
606        } else {
607            4
608        };
609        let mut seq = serializer.serialize_seq(Some(len))?;
610        seq.serialize_element(&self.capability)?;
611        seq.serialize_element(&self.schema)?;
612        seq.serialize_element(&self.epoch)?;
613        seq.serialize_element(&self.version)?;
614        if let Some(days) = days {
615            seq.serialize_element(&self.resume)?;
616            seq.serialize_element(&days)?;
617        } else if let Some(resume) = &self.resume {
618            seq.serialize_element(resume)?;
619        }
620        seq.end()
621    }
622}
623
624impl Serialize for SyncEntry {
625    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
626        self.serialize_with_days(serializer, None)
627    }
628}
629
630impl<'de> Deserialize<'de> for SyncEntry {
631    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
632        let entry = WindowedSyncEntry::deserialize(deserializer)?;
633        if entry.window_days.is_some() {
634            return Err(de::Error::custom(
635                "custom history requires WindowedSyncEntry",
636            ));
637        }
638        Ok(entry.entry)
639    }
640}
641
642/// A device check that can also carry the six-slot custom-window form.
643#[derive(Debug, Clone, PartialEq, Eq)]
644pub struct WindowedSyncEntry {
645    /// The capability and its device cursor.
646    pub entry: SyncEntry,
647    /// The custom count carried in slot six.
648    pub window_days: Option<WindowDays>,
649}
650
651impl WindowedSyncEntry {
652    /// Forward this exact window and paging cursor to the provider.
653    pub fn pull_request(&self, limit: u32) -> WindowedPullRequest {
654        WindowedPullRequest {
655            request: self.entry.pull_request(limit),
656            window_days: self.window_days,
657        }
658    }
659}
660
661impl Serialize for WindowedSyncEntry {
662    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
663        self.entry.serialize_with_days(serializer, self.window_days)
664    }
665}
666
667impl<'de> Deserialize<'de> for WindowedSyncEntry {
668    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
669        struct EntryVisitor;
670        impl<'de> Visitor<'de> for EntryVisitor {
671            type Value = WindowedSyncEntry;
672            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
673                f.write_str(
674                    "a sync entry [capability, schema, epoch, version, resume?, window_days?]",
675                )
676            }
677            fn visit_seq<A: SeqAccess<'de>>(
678                self,
679                mut seq: A,
680            ) -> Result<WindowedSyncEntry, A::Error> {
681                let capability: String = seq
682                    .next_element()?
683                    .ok_or_else(|| de::Error::invalid_length(0, &self))?;
684                let schema: u32 = seq
685                    .next_element()?
686                    .ok_or_else(|| de::Error::invalid_length(1, &self))?;
687                let epoch: String = seq
688                    .next_element()?
689                    .ok_or_else(|| de::Error::invalid_length(2, &self))?;
690                let version: u64 = seq
691                    .next_element()?
692                    .ok_or_else(|| de::Error::invalid_length(3, &self))?;
693                let slot: Option<Option<String>> = seq.next_element()?;
694                let window_days: Option<WindowDays> = seq.next_element()?;
695                if slot == Some(None) && window_days.is_none() {
696                    return Err(de::Error::custom("a null resume slot requires window_days"));
697                }
698                check_window_source(&capability, window_days).map_err(de::Error::custom)?;
699                if seq.next_element::<de::IgnoredAny>()?.is_some() {
700                    return Err(de::Error::invalid_length(7, &self));
701                }
702                Ok(WindowedSyncEntry {
703                    entry: SyncEntry {
704                        capability,
705                        schema,
706                        epoch,
707                        version,
708                        resume: slot.flatten(),
709                    },
710                    window_days,
711                })
712            }
713        }
714        deserializer.deserialize_seq(EntryVisitor)
715    }
716}
717
718/// The payload of `core.replica.sync`: `{"c":[[…],[…]]}`, plus
719/// `"origin":"background"` on checks no person is waiting for.
720#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
721pub struct SyncRequest {
722    /// The entries, at most 64.
723    #[serde(rename = "c")]
724    pub entries: Vec<SyncEntry>,
725    /// `"background"` on checks no person is waiting for.
726    #[serde(default, skip_serializing_if = "Option::is_none")]
727    pub origin: Option<String>,
728}
729
730/// Parse a batch with any mixture of ordinary, paged, and custom-window checks.
731#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
732pub struct WindowedSyncRequest {
733    /// The ordered checks, including each window and cursor.
734    #[serde(rename = "c")]
735    pub entries: Vec<WindowedSyncEntry>,
736    /// `background` when no person is waiting for this batch.
737    #[serde(default, skip_serializing_if = "Option::is_none")]
738    pub origin: Option<String>,
739}
740
741/// Why the node could not answer one entry of a check.
742#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
743#[serde(rename_all = "lowercase")]
744pub enum SyncErrorCode {
745    /// No provider is registered for the capability.
746    Unknown,
747    /// The app does not serve the schema asked for.
748    Schema,
749    /// The app did not answer in time.
750    Unavailable,
751    /// The reply size cap was reached; ask again.
752    Busy,
753}
754
755impl SyncErrorCode {
756    /// The code as it travels: `unknown`, `schema`, `unavailable` or `busy`.
757    pub fn as_str(self) -> &'static str {
758        match self {
759            SyncErrorCode::Unknown => "unknown",
760            SyncErrorCode::Schema => "schema",
761            SyncErrorCode::Unavailable => "unavailable",
762            SyncErrorCode::Busy => "busy",
763        }
764    }
765
766    /// The code for its wire text; `None` for an unknown one.
767    pub fn parse(value: &str) -> Option<Self> {
768        match value {
769            "unknown" => Some(SyncErrorCode::Unknown),
770            "schema" => Some(SyncErrorCode::Schema),
771            "unavailable" => Some(SyncErrorCode::Unavailable),
772            "busy" => Some(SyncErrorCode::Busy),
773            _ => None,
774        }
775    }
776}
777
778/// The node's answer for one entry of a check (section 4.3): `0`, the changes
779/// (without `e`, which the device already holds), a full copy, or an error.
780#[derive(Debug, Clone, PartialEq)]
781pub enum SyncAnswer {
782    /// `0`: the device holds the head.
783    NothingNew,
784    /// `{"v":43,"u":[…],"x":[…]}` plus `"m":1`: see [`PullReply::Changes`].
785    Changes {
786        /// The version the device holds once it applied them.
787        version: u64,
788        /// Rows added or changed.
789        upserts: Vec<Row>,
790        /// Keys deleted.
791        deletes: Vec<String>,
792        /// More remain: ask again from `version`.
793        more: bool,
794    },
795    /// `{"e":…,"v":7,"f":1,"u":[…]}` plus `"n"`: see [`PullReply::FullCopy`]
796    /// (without `"h"`, which is for the node).
797    FullCopy {
798        /// The copy's epoch.
799        epoch: String,
800        /// The copy's version; every page of one copy carries page one's.
801        version: u64,
802        /// This page's rows, in key order.
803        rows: Vec<Row>,
804        /// The resume key for the next page, when more remain.
805        next: Option<String>,
806    },
807    /// `{"err":"<code>"}`.
808    Error(SyncErrorCode),
809}
810
811impl From<PullReply> for SyncAnswer {
812    fn from(reply: PullReply) -> Self {
813        match reply {
814            PullReply::NothingNew { .. } => SyncAnswer::NothingNew,
815            PullReply::Changes {
816                version,
817                upserts,
818                deletes,
819                more,
820                ..
821            } => SyncAnswer::Changes {
822                version,
823                upserts,
824                deletes,
825                more,
826            },
827            // `h` is for the node; the device continues a copy by its `(e, v)`.
828            PullReply::FullCopy {
829                epoch,
830                version,
831                rows,
832                next,
833                ..
834            } => SyncAnswer::FullCopy {
835                epoch,
836                version,
837                rows,
838                next,
839            },
840        }
841    }
842}
843
844impl Serialize for SyncAnswer {
845    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
846        match self {
847            SyncAnswer::NothingNew => serializer.serialize_u8(0),
848            SyncAnswer::Changes {
849                version,
850                upserts,
851                deletes,
852                more,
853            } => {
854                let mut map = serializer.serialize_map(None)?;
855                serialize_changes_body(&mut map, *version, upserts, deletes, *more)?;
856                map.end()
857            }
858            SyncAnswer::FullCopy {
859                epoch,
860                version,
861                rows,
862                next,
863            } => {
864                let mut map = serializer.serialize_map(None)?;
865                serialize_full_copy_body(&mut map, epoch, *version, rows, next)?;
866                map.end()
867            }
868            SyncAnswer::Error(code) => {
869                let mut map = serializer.serialize_map(Some(1))?;
870                map.serialize_entry("err", code.as_str())?;
871                map.end()
872            }
873        }
874    }
875}
876
877impl<'de> Deserialize<'de> for SyncAnswer {
878    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
879        let value = Value::deserialize(deserializer)?;
880        match &value {
881            Value::Number(number) if number.as_u64() == Some(0) => Ok(SyncAnswer::NothingNew),
882            Value::Object(object) => {
883                if let Some(code) = object.get("err") {
884                    let code = code
885                        .as_str()
886                        .and_then(SyncErrorCode::parse)
887                        .ok_or_else(|| de::Error::custom("err must be a known error code"))?;
888                    return Ok(SyncAnswer::Error(code));
889                }
890                let raw = RawReply::deserialize(value).map_err(de::Error::custom)?;
891                if flag::<D::Error>("f", raw.f)? {
892                    let epoch = raw.e.ok_or_else(|| de::Error::missing_field("e"))?;
893                    return Ok(SyncAnswer::FullCopy {
894                        epoch,
895                        version: raw.v,
896                        rows: raw.u.unwrap_or_default(),
897                        next: raw.n,
898                    });
899                }
900                Ok(SyncAnswer::Changes {
901                    version: raw.v,
902                    upserts: raw.u.unwrap_or_default(),
903                    deletes: raw.x.unwrap_or_default(),
904                    more: flag::<D::Error>("m", raw.m)?,
905                })
906            }
907            _ => Err(de::Error::custom(
908                "a sync answer is 0, a changes object, a full copy or an error",
909            )),
910        }
911    }
912}
913
914/// The `result` of `core.replica.sync`: `{"r":[…]}`, aligned with the request's
915/// entries by index.
916#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
917pub struct SyncReply {
918    /// One answer per entry, in the request's order.
919    #[serde(rename = "r")]
920    pub answers: Vec<SyncAnswer>,
921}
922
923/// The payload of `core.replica.announce`: `{"c":"friends.people.pull","e":"k3f9a2c1","v":42}`.
924#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
925pub struct Announce {
926    /// The pull capability whose head moved.
927    #[serde(rename = "c")]
928    pub capability: String,
929    /// Its epoch.
930    #[serde(rename = "e")]
931    pub epoch: String,
932    /// Its head.
933    #[serde(rename = "v")]
934    pub version: u64,
935}
936
937/// An announcement for one custom day window of a recent collection.
938#[derive(Debug, Clone, PartialEq, Eq)]
939pub struct WindowedAnnounce {
940    /// The source, epoch and version of the projection that changed.
941    pub announce: Announce,
942    /// The custom count whose independent head moved.
943    pub window_days: Option<WindowDays>,
944}
945
946impl Serialize for WindowedAnnounce {
947    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
948        check_window_source(&self.announce.capability, self.window_days)
949            .map_err(serde::ser::Error::custom)?;
950        #[derive(Serialize)]
951        struct Payload<'a> {
952            #[serde(flatten)]
953            announce: &'a Announce,
954            #[serde(skip_serializing_if = "Option::is_none")]
955            window_days: Option<WindowDays>,
956        }
957        Payload {
958            announce: &self.announce,
959            window_days: self.window_days,
960        }
961        .serialize(serializer)
962    }
963}
964
965impl<'de> Deserialize<'de> for WindowedAnnounce {
966    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
967        #[derive(Deserialize)]
968        struct Payload {
969            #[serde(flatten)]
970            announce: Announce,
971            #[serde(default, deserialize_with = "present_days")]
972            window_days: Option<WindowDays>,
973        }
974        let payload = Payload::deserialize(deserializer)?;
975        check_window_source(&payload.announce.capability, payload.window_days)
976            .map_err(de::Error::custom)?;
977        Ok(Self {
978            announce: payload.announce,
979            window_days: payload.window_days,
980        })
981    }
982}
983
984/// The node's answer to an announce: `{"ok":true}`, or `{"rotate":true}` when it
985/// has handed out a higher version of that epoch (the app's data went back in
986/// time).
987#[derive(Debug, Clone, Copy, PartialEq, Eq)]
988pub enum AnnounceReply {
989    /// `{"ok":true}`: the node took the head.
990    Ok,
991    /// `{"rotate":true}`: start a new epoch and announce again.
992    Rotate,
993}
994
995impl Serialize for AnnounceReply {
996    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
997        let mut map = serializer.serialize_map(Some(1))?;
998        match self {
999            AnnounceReply::Ok => map.serialize_entry("ok", &true)?,
1000            AnnounceReply::Rotate => map.serialize_entry("rotate", &true)?,
1001        }
1002        map.end()
1003    }
1004}
1005
1006impl<'de> Deserialize<'de> for AnnounceReply {
1007    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1008        #[derive(Deserialize)]
1009        struct Raw {
1010            #[serde(default)]
1011            ok: bool,
1012            #[serde(default)]
1013            rotate: bool,
1014        }
1015        let raw = Raw::deserialize(deserializer)?;
1016        if raw.rotate {
1017            Ok(AnnounceReply::Rotate)
1018        } else if raw.ok {
1019            Ok(AnnounceReply::Ok)
1020        } else {
1021            Err(de::Error::custom(
1022                "an announce reply is {\"ok\":true} or {\"rotate\":true}",
1023            ))
1024        }
1025    }
1026}
1027
1028/// One head in a `replica.heads` push: `["friends.people.pull","k3f9a2c1",42]`.
1029#[derive(Debug, Clone, PartialEq, Eq)]
1030pub struct PushedHead {
1031    /// The pull capability.
1032    pub capability: String,
1033    /// Its epoch.
1034    pub epoch: String,
1035    /// Its head.
1036    pub version: u64,
1037}
1038
1039impl Serialize for PushedHead {
1040    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1041        (&self.capability, &self.epoch, self.version).serialize(serializer)
1042    }
1043}
1044
1045impl<'de> Deserialize<'de> for PushedHead {
1046    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1047        let (capability, epoch, version) = <(String, String, u64)>::deserialize(deserializer)?;
1048        Ok(PushedHead {
1049            capability,
1050            epoch,
1051            version,
1052        })
1053    }
1054}
1055
1056/// The `data` of a `replica.heads` frame: `{"h":[[…]]}`.
1057#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1058pub struct HeadsData {
1059    /// The heads, one per capability that moved.
1060    #[serde(rename = "h")]
1061    pub heads: Vec<PushedHead>,
1062}
1063
1064/// `[a-z0-9]{1,16}`.
1065pub fn is_epoch(value: &str) -> bool {
1066    !value.is_empty()
1067        && value.len() <= MAX_EPOCH_CHARS
1068        && value
1069            .bytes()
1070            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
1071}
1072
1073/// A row key: 1–256 bytes, no control characters.
1074pub fn validate_key(key: &str) -> Result<(), String> {
1075    if key.is_empty() {
1076        return Err("key must not be empty".to_string());
1077    }
1078    if key.len() > MAX_KEY_BYTES {
1079        return Err(format!(
1080            "key is {} bytes; at most {MAX_KEY_BYTES} are allowed",
1081            key.len()
1082        ));
1083    }
1084    if key.chars().any(char::is_control) {
1085        return Err("key must not contain control characters".to_string());
1086    }
1087    Ok(())
1088}
1089
1090/// Whether `value` nests no deeper than [`MAX_VALUE_DEPTH`] levels. Walks the
1091/// value with an explicit stack and stops at the first level past the limit, so
1092/// a deep value is refused without using the call stack. The same rule as the
1093/// device's `isWithinReplicaValueDepth` and the TypeScript helper's
1094/// `isWithinValueDepth`; `tests/fixtures/value-depth.json` holds the shared cases.
1095pub fn value_within_depth(value: &Value) -> bool {
1096    let mut stack: Vec<(usize, &Value)> = vec![(1, value)];
1097    while let Some((level, value)) = stack.pop() {
1098        let is_container = matches!(value, Value::Array(_) | Value::Object(_));
1099        if is_container && level >= MAX_VALUE_DEPTH {
1100            return false;
1101        }
1102        match value {
1103            Value::Array(items) => stack.extend(items.iter().map(|child| (level + 1, child))),
1104            Value::Object(object) => stack.extend(object.values().map(|child| (level + 1, child))),
1105            _ => {}
1106        }
1107    }
1108    true
1109}
1110
1111/// The refusal of a value past [`MAX_VALUE_DEPTH`], the same text as the
1112/// TypeScript helper's.
1113pub(crate) const VALUE_TOO_DEEP: &str =
1114    "value nests 128 or more containers; at most 127 are allowed (the node's JSON limit)";
1115
1116/// The bytes one row adds inside `u` (its entry plus a separating comma).
1117pub(crate) fn encoded_row_bytes(row: &Row) -> usize {
1118    crate::digest::json_len_of_str(&row.key)
1119        + crate::digest::canonical_len(&row.value)
1120        + match (row.ord, row.part.is_empty()) {
1121            (0, true) => 0,
1122            (ord, true) => 1 + ord.to_string().len(),
1123            (ord, false) => 2 + ord.to_string().len() + crate::digest::json_len_of_str(&row.part),
1124        }
1125        // `[`, the comma after the key, `]`, and the comma before the next entry.
1126        + 4
1127}
1128
1129/// The bytes one delete adds inside `x`.
1130pub(crate) fn encoded_delete_bytes(key: &str) -> usize {
1131    crate::digest::json_len_of_str(key) + 1
1132}