node-app-replica 7.7.16

Change-only replication for Node app backends: a per-collection ledger (epoch, version, tombstones) that answers a device's pull with nothing new, the changes, or a full copy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
//! The replication contract's wire shapes (Phase 3 spec, section 4), byte for byte.
//!
//! Every type here serializes to the compact JSON the contract prints, with the
//! keys in the contract's order, whatever `serde_json` features the build
//! unifies. Deserialization is lenient where the contract is: it ignores keys it
//! does not know (the capability router stamps `caller` and `caller_ingress`
//! into every payload) and accepts the short forms of a row entry.
//!
//! The golden fixtures in `tests/fixtures/` hold the exact bytes; the TypeScript
//! helper and the client kernel read the same files.

use std::fmt;

use serde::de::{self, Deserializer, SeqAccess, Visitor};
use serde::ser::{SerializeMap, SerializeSeq, Serializer};
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// A row key: 1–256 bytes of UTF-8 with no control characters.
pub const MAX_KEY_BYTES: usize = 256;
/// A row value's encoded (compact JSON) size.
pub const MAX_VALUE_BYTES: usize = 65_536;
/// The largest `ord` magnitude and the largest version: 2^53 − 1, exact in a
/// JavaScript number.
pub const MAX_SAFE_INTEGER: u64 = (1 << 53) - 1;
/// A row's `part`: 0–128 bytes of UTF-8.
pub const MAX_PART_BYTES: usize = 128;
/// The deepest a row's value may nest, counted as the device's storage counts
/// it (`isWithinReplicaValueDepth` in `client/ports/src/replica.js`): the value
/// is level 1 and each container adds a level for what it holds, so 127 nested
/// containers are accepted and 128 refused. That is exactly what serde_json's
/// default recursion limit (128) parses, so the node can read every value the
/// helper serves. See [`value_within_depth`].
pub const MAX_VALUE_DEPTH: usize = 128;
/// An epoch: 1–16 characters of `[a-z0-9]`.
pub const MAX_EPOCH_CHARS: usize = 16;
/// The rows (upserts plus deletes) one reply carries for one collection.
pub const MAX_ROWS_PER_REPLY: u32 = 500;
/// The encoded bytes of the rows one reply carries for one collection.
pub const MAX_REPLY_ROW_BYTES: usize = 262_144;
/// Entries in one `core.replica.sync` request.
pub const MAX_SYNC_ENTRIES: usize = 64;
/// A whole `core.replica.sync` reply (under node-wire's 1 MiB frame).
pub const MAX_SYNC_REPLY_BYTES: usize = 786_432;

/// The device's batched check (node core).
pub const SYNC_CAPABILITY: &str = "core.replica.sync";
/// The app's "my head moved" notice (node core).
pub const ANNOUNCE_CAPABILITY: &str = "core.replica.announce";
/// The node's push to connected devices.
pub const HEADS_EVENT: &str = "replica.heads";
/// The capability error prefix for a schema the app does not serve.
pub const SCHEMA_UNSUPPORTED_PREFIX: &str = "replica_schema_unsupported:";

/// One row of a collection: a key, any JSON value, its order in the list and the
/// group it belongs to.
#[derive(Debug, Clone, PartialEq)]
pub struct Row {
    /// The row's identity in its collection: 1–256 bytes, no control characters.
    pub key: String,
    /// Any JSON value, at most 65,536 bytes encoded and 127 containers deep.
    pub value: Value,
    /// The row's position in its list; 0 when the list has no order of its own.
    pub ord: i64,
    /// A group the row belongs to (a conversation id for a message); `""` for none.
    pub part: String,
}

impl Row {
    /// A row with `ord` 0 and no `part`.
    pub fn new(key: impl Into<String>, value: Value) -> Self {
        Self {
            key: key.into(),
            value,
            ord: 0,
            part: String::new(),
        }
    }

    /// The row with its place in the list (|ord| ≤ 2^53 − 1).
    pub fn with_ord(mut self, ord: i64) -> Self {
        self.ord = ord;
        self
    }

    /// The row in a group (at most 128 bytes).
    pub fn with_part(mut self, part: impl Into<String>) -> Self {
        self.part = part.into();
        self
    }
}

/// `["<key>", <value>, <ord>, "<part>"]`, dropping a trailing `part` of `""` and
/// then a trailing `ord` of 0: `["k", {…}]` is a complete entry.
impl Serialize for Row {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let len = if !self.part.is_empty() {
            4
        } else if self.ord != 0 {
            3
        } else {
            2
        };
        let mut seq = serializer.serialize_seq(Some(len))?;
        seq.serialize_element(&self.key)?;
        seq.serialize_element(&CanonicalValue(&self.value))?;
        if len >= 3 {
            seq.serialize_element(&self.ord)?;
        }
        if len == 4 {
            seq.serialize_element(&self.part)?;
        }
        seq.end()
    }
}

impl<'de> Deserialize<'de> for Row {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct RowVisitor;
        impl<'de> Visitor<'de> for RowVisitor {
            type Value = Row;
            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("a row entry [key, value, ord?, part?]")
            }
            fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Row, A::Error> {
                let key: String = seq
                    .next_element()?
                    .ok_or_else(|| de::Error::invalid_length(0, &self))?;
                let value: Value = seq
                    .next_element()?
                    .ok_or_else(|| de::Error::invalid_length(1, &self))?;
                let ord: i64 = seq.next_element()?.unwrap_or(0);
                let part: String = seq.next_element()?.unwrap_or_default();
                if seq.next_element::<de::IgnoredAny>()?.is_some() {
                    return Err(de::Error::invalid_length(5, &self));
                }
                Ok(Row {
                    key,
                    value,
                    ord,
                    part,
                })
            }
        }
        deserializer.deserialize_seq(RowVisitor)
    }
}

/// A JSON value written with its object keys sorted, so a row's bytes do not
/// depend on whether the build enabled `serde_json/preserve_order`.
struct CanonicalValue<'a>(&'a Value);

impl Serialize for CanonicalValue<'_> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self.0 {
            Value::Array(items) => {
                let mut seq = serializer.serialize_seq(Some(items.len()))?;
                for item in items {
                    seq.serialize_element(&CanonicalValue(item))?;
                }
                seq.end()
            }
            Value::Object(object) => {
                let mut entries: Vec<(&String, &Value)> = object.iter().collect();
                entries.sort_by(|a, b| a.0.cmp(b.0));
                let mut map = serializer.serialize_map(Some(entries.len()))?;
                for (key, value) in entries {
                    map.serialize_entry(key, &CanonicalValue(value))?;
                }
                map.end()
            }
            other => other.serialize(serializer),
        }
    }
}

/// The request the node sends an app's pull capability:
/// `{"e":"k3f9a2c1","v":41,"s":1,"l":500}` plus `"a"` when resuming a paged
/// full copy.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PullRequest {
    /// The epoch the caller holds; `""` when it holds nothing.
    #[serde(rename = "e")]
    pub epoch: String,
    /// The version the caller holds.
    #[serde(rename = "v")]
    pub version: u64,
    /// The schema number: the `N` of the consumer's `.vN`.
    #[serde(rename = "s")]
    pub schema: u32,
    /// The most rows to return (at most 500).
    #[serde(rename = "l", default = "default_limit")]
    pub limit: u32,
    /// The last key of the previous page of a paged full copy.
    #[serde(rename = "a", default, skip_serializing_if = "Option::is_none")]
    pub resume: Option<String>,
}

fn default_limit() -> u32 {
    MAX_ROWS_PER_REPLY
}

impl PullRequest {
    /// "I hold nothing": the first request for a collection.
    pub fn initial(schema: u32) -> Self {
        Self {
            epoch: String::new(),
            version: 0,
            schema,
            limit: MAX_ROWS_PER_REPLY,
            resume: None,
        }
    }

    /// Checks the request against the contract's limits. A limit above 500 is
    /// not an error; the helper serves 500.
    pub fn validate(&self) -> Result<(), String> {
        if !self.epoch.is_empty() && !is_epoch(&self.epoch) {
            return Err("e must be \"\" or 1-16 characters of [a-z0-9]".to_string());
        }
        if self.version > MAX_SAFE_INTEGER {
            return Err("v must be at most 2^53 - 1".to_string());
        }
        if self.limit == 0 {
            return Err("l must be at least 1".to_string());
        }
        if let Some(resume) = &self.resume {
            validate_key(resume).map_err(|reason| format!("a {reason}"))?;
            if self.epoch.is_empty() {
                return Err("a resumes a full copy and needs that copy's e".to_string());
            }
        }
        Ok(())
    }

    /// The row limit the helper serves: `l`, capped at 500.
    pub fn effective_limit(&self) -> usize {
        self.limit.min(MAX_ROWS_PER_REPLY) as usize
    }
}

/// An app's answer to one pull (section 4.2).
#[derive(Debug, Clone, PartialEq)]
pub enum PullReply {
    /// `{"e":"k3f9a2c1","v":41}`
    NothingNew {
        /// The ledger's epoch.
        epoch: String,
        /// The ledger's head, which the caller already holds.
        version: u64,
    },
    /// `{"e":…,"v":43,"u":[…],"x":[…]}` plus `"m":1` when more remain.
    Changes {
        /// The ledger's epoch, the caller's too.
        epoch: String,
        /// The version the caller holds once it applied these changes: the head,
        /// or, when cut (`more`), the version just before the first change whose
        /// earlier value the ledger no longer knows.
        version: u64,
        /// Rows added or changed, in version order.
        upserts: Vec<Row>,
        /// Keys deleted.
        deletes: Vec<String>,
        /// More changes remain: ask again from `version`.
        more: bool,
    },
    /// `{"e":…,"v":7,"f":1,"u":[…]}` plus `"n":"<last key>"` when more pages
    /// remain, and `"h"` on a later page read after the head moved. Rows are in
    /// key order.
    FullCopy {
        /// The epoch the copy is in.
        epoch: String,
        /// The copy's version: the head when page one was read. Every page of
        /// one copy carries it, and the caller asks for the changes since it once
        /// the last page is in.
        version: u64,
        /// The rows of this page, as they are when it is read.
        rows: Vec<Row>,
        /// The last key of this page when more pages remain.
        next: Option<String>,
        /// `"h"`, for the node only: the head when a later page was read, when it
        /// is above `version`. The page's rows can be that new, so the node raises
        /// its mark for the epoch to it; it is not passed to the device.
        head: Option<u64>,
    },
}

impl PullReply {
    /// The reply's epoch.
    pub fn epoch(&self) -> &str {
        match self {
            PullReply::NothingNew { epoch, .. }
            | PullReply::Changes { epoch, .. }
            | PullReply::FullCopy { epoch, .. } => epoch,
        }
    }

    /// The version the caller holds once it applied the reply (for a full copy,
    /// once its last page is in).
    pub fn version(&self) -> u64 {
        match self {
            PullReply::NothingNew { version, .. }
            | PullReply::Changes { version, .. }
            | PullReply::FullCopy { version, .. } => *version,
        }
    }

    /// The highest version whose data the reply can carry: `version`, or `"h"`
    /// on a later page of a full copy. The node keeps, per epoch, the highest of
    /// these it has passed on, and answers an announce below it with `rotate`.
    pub fn handed_out(&self) -> u64 {
        match self {
            PullReply::FullCopy {
                version,
                head: Some(head),
                ..
            } => (*version).max(*head),
            other => other.version(),
        }
    }

    /// True when the caller must ask again to get the rest (`"m":1` or `"n"`).
    /// The node records a reply's head only when this is false.
    pub fn is_truncated(&self) -> bool {
        match self {
            PullReply::NothingNew { .. } => false,
            PullReply::Changes { more, .. } => *more,
            PullReply::FullCopy { next, .. } => next.is_some(),
        }
    }
}

impl Serialize for PullReply {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            PullReply::NothingNew { epoch, version } => {
                let mut map = serializer.serialize_map(Some(2))?;
                map.serialize_entry("e", epoch)?;
                map.serialize_entry("v", version)?;
                map.end()
            }
            PullReply::Changes {
                epoch,
                version,
                upserts,
                deletes,
                more,
            } => {
                let mut map = serializer.serialize_map(None)?;
                map.serialize_entry("e", epoch)?;
                serialize_changes_body(&mut map, *version, upserts, deletes, *more)?;
                map.end()
            }
            PullReply::FullCopy {
                epoch,
                version,
                rows,
                next,
                head,
            } => {
                let mut map = serializer.serialize_map(None)?;
                serialize_full_copy_body(&mut map, epoch, *version, rows, next)?;
                if let Some(head) = head {
                    map.serialize_entry("h", head)?;
                }
                map.end()
            }
        }
    }
}

fn serialize_changes_body<M: SerializeMap>(
    map: &mut M,
    version: u64,
    upserts: &[Row],
    deletes: &[String],
    more: bool,
) -> Result<(), M::Error> {
    map.serialize_entry("v", &version)?;
    map.serialize_entry("u", upserts)?;
    map.serialize_entry("x", deletes)?;
    if more {
        map.serialize_entry("m", &1u8)?;
    }
    Ok(())
}

fn serialize_full_copy_body<M: SerializeMap>(
    map: &mut M,
    epoch: &str,
    version: u64,
    rows: &[Row],
    next: &Option<String>,
) -> Result<(), M::Error> {
    map.serialize_entry("e", epoch)?;
    map.serialize_entry("v", &version)?;
    map.serialize_entry("f", &1u8)?;
    map.serialize_entry("u", rows)?;
    if let Some(next) = next {
        map.serialize_entry("n", next)?;
    }
    Ok(())
}

/// Every key either reply object may carry; unknown keys are ignored.
#[derive(Deserialize)]
struct RawReply {
    #[serde(default)]
    e: Option<String>,
    v: u64,
    #[serde(default)]
    f: Option<u8>,
    #[serde(default)]
    u: Option<Vec<Row>>,
    #[serde(default)]
    x: Option<Vec<String>>,
    #[serde(default)]
    m: Option<u8>,
    #[serde(default)]
    n: Option<String>,
    #[serde(default)]
    h: Option<u64>,
}

fn flag<E: de::Error>(name: &str, value: Option<u8>) -> Result<bool, E> {
    match value {
        None => Ok(false),
        Some(1) => Ok(true),
        Some(other) => Err(E::custom(format!(
            "{name} must be 1 when present, got {other}"
        ))),
    }
}

impl<'de> Deserialize<'de> for PullReply {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let raw = RawReply::deserialize(deserializer)?;
        let epoch = raw.e.ok_or_else(|| de::Error::missing_field("e"))?;
        if flag::<D::Error>("f", raw.f)? {
            return Ok(PullReply::FullCopy {
                epoch,
                version: raw.v,
                rows: raw.u.unwrap_or_default(),
                next: raw.n,
                head: raw.h,
            });
        }
        if raw.u.is_some() || raw.x.is_some() {
            return Ok(PullReply::Changes {
                epoch,
                version: raw.v,
                upserts: raw.u.unwrap_or_default(),
                deletes: raw.x.unwrap_or_default(),
                more: flag::<D::Error>("m", raw.m)?,
            });
        }
        Ok(PullReply::NothingNew {
            epoch,
            version: raw.v,
        })
    }
}

/// One entry of a device check: `[pullCapability, schema, epoch, version]`, plus
/// the resume key of a paged full copy as a fifth element.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SyncEntry {
    /// The pull capability (`friends.people.pull`).
    pub capability: String,
    /// The schema number the device reads.
    pub schema: u32,
    /// The epoch it holds (`""` for none); during a paged copy, page one's.
    pub epoch: String,
    /// The version it holds; during a paged copy, page one's.
    pub version: u64,
    /// The last key of the previous page, while a paged full copy is in progress.
    pub resume: Option<String>,
}

impl SyncEntry {
    /// The pull request the node sends the app for this entry.
    pub fn pull_request(&self, limit: u32) -> PullRequest {
        PullRequest {
            epoch: self.epoch.clone(),
            version: self.version,
            schema: self.schema,
            limit,
            resume: self.resume.clone(),
        }
    }
}

impl Serialize for SyncEntry {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let len = if self.resume.is_some() { 5 } else { 4 };
        let mut seq = serializer.serialize_seq(Some(len))?;
        seq.serialize_element(&self.capability)?;
        seq.serialize_element(&self.schema)?;
        seq.serialize_element(&self.epoch)?;
        seq.serialize_element(&self.version)?;
        if let Some(resume) = &self.resume {
            seq.serialize_element(resume)?;
        }
        seq.end()
    }
}

impl<'de> Deserialize<'de> for SyncEntry {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct EntryVisitor;
        impl<'de> Visitor<'de> for EntryVisitor {
            type Value = SyncEntry;
            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("a sync entry [capability, schema, epoch, version, resume?]")
            }
            fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<SyncEntry, A::Error> {
                let capability: String = seq
                    .next_element()?
                    .ok_or_else(|| de::Error::invalid_length(0, &self))?;
                let schema: u32 = seq
                    .next_element()?
                    .ok_or_else(|| de::Error::invalid_length(1, &self))?;
                let epoch: String = seq
                    .next_element()?
                    .ok_or_else(|| de::Error::invalid_length(2, &self))?;
                let version: u64 = seq
                    .next_element()?
                    .ok_or_else(|| de::Error::invalid_length(3, &self))?;
                let resume: Option<String> = seq.next_element()?;
                if seq.next_element::<de::IgnoredAny>()?.is_some() {
                    return Err(de::Error::invalid_length(6, &self));
                }
                Ok(SyncEntry {
                    capability,
                    schema,
                    epoch,
                    version,
                    resume,
                })
            }
        }
        deserializer.deserialize_seq(EntryVisitor)
    }
}

/// The payload of `core.replica.sync`: `{"c":[[…],[…]]}`, plus
/// `"origin":"background"` on checks no person is waiting for.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SyncRequest {
    /// The entries, at most 64.
    #[serde(rename = "c")]
    pub entries: Vec<SyncEntry>,
    /// `"background"` on checks no person is waiting for.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub origin: Option<String>,
}

/// Why the node could not answer one entry of a check.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SyncErrorCode {
    /// No provider is registered for the capability.
    Unknown,
    /// The app does not serve the schema asked for.
    Schema,
    /// The app did not answer in time.
    Unavailable,
    /// The reply size cap was reached; ask again.
    Busy,
}

impl SyncErrorCode {
    /// The code as it travels: `unknown`, `schema`, `unavailable` or `busy`.
    pub fn as_str(self) -> &'static str {
        match self {
            SyncErrorCode::Unknown => "unknown",
            SyncErrorCode::Schema => "schema",
            SyncErrorCode::Unavailable => "unavailable",
            SyncErrorCode::Busy => "busy",
        }
    }

    /// The code for its wire text; `None` for an unknown one.
    pub fn parse(value: &str) -> Option<Self> {
        match value {
            "unknown" => Some(SyncErrorCode::Unknown),
            "schema" => Some(SyncErrorCode::Schema),
            "unavailable" => Some(SyncErrorCode::Unavailable),
            "busy" => Some(SyncErrorCode::Busy),
            _ => None,
        }
    }
}

/// The node's answer for one entry of a check (section 4.3): `0`, the changes
/// (without `e`, which the device already holds), a full copy, or an error.
#[derive(Debug, Clone, PartialEq)]
pub enum SyncAnswer {
    /// `0`: the device holds the head.
    NothingNew,
    /// `{"v":43,"u":[…],"x":[…]}` plus `"m":1`: see [`PullReply::Changes`].
    Changes {
        /// The version the device holds once it applied them.
        version: u64,
        /// Rows added or changed.
        upserts: Vec<Row>,
        /// Keys deleted.
        deletes: Vec<String>,
        /// More remain: ask again from `version`.
        more: bool,
    },
    /// `{"e":…,"v":7,"f":1,"u":[…]}` plus `"n"`: see [`PullReply::FullCopy`]
    /// (without `"h"`, which is for the node).
    FullCopy {
        /// The copy's epoch.
        epoch: String,
        /// The copy's version; every page of one copy carries page one's.
        version: u64,
        /// This page's rows, in key order.
        rows: Vec<Row>,
        /// The resume key for the next page, when more remain.
        next: Option<String>,
    },
    /// `{"err":"<code>"}`.
    Error(SyncErrorCode),
}

impl From<PullReply> for SyncAnswer {
    fn from(reply: PullReply) -> Self {
        match reply {
            PullReply::NothingNew { .. } => SyncAnswer::NothingNew,
            PullReply::Changes {
                version,
                upserts,
                deletes,
                more,
                ..
            } => SyncAnswer::Changes {
                version,
                upserts,
                deletes,
                more,
            },
            // `h` is for the node; the device continues a copy by its `(e, v)`.
            PullReply::FullCopy {
                epoch,
                version,
                rows,
                next,
                ..
            } => SyncAnswer::FullCopy {
                epoch,
                version,
                rows,
                next,
            },
        }
    }
}

impl Serialize for SyncAnswer {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            SyncAnswer::NothingNew => serializer.serialize_u8(0),
            SyncAnswer::Changes {
                version,
                upserts,
                deletes,
                more,
            } => {
                let mut map = serializer.serialize_map(None)?;
                serialize_changes_body(&mut map, *version, upserts, deletes, *more)?;
                map.end()
            }
            SyncAnswer::FullCopy {
                epoch,
                version,
                rows,
                next,
            } => {
                let mut map = serializer.serialize_map(None)?;
                serialize_full_copy_body(&mut map, epoch, *version, rows, next)?;
                map.end()
            }
            SyncAnswer::Error(code) => {
                let mut map = serializer.serialize_map(Some(1))?;
                map.serialize_entry("err", code.as_str())?;
                map.end()
            }
        }
    }
}

impl<'de> Deserialize<'de> for SyncAnswer {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = Value::deserialize(deserializer)?;
        match &value {
            Value::Number(number) if number.as_u64() == Some(0) => Ok(SyncAnswer::NothingNew),
            Value::Object(object) => {
                if let Some(code) = object.get("err") {
                    let code = code
                        .as_str()
                        .and_then(SyncErrorCode::parse)
                        .ok_or_else(|| de::Error::custom("err must be a known error code"))?;
                    return Ok(SyncAnswer::Error(code));
                }
                let raw = RawReply::deserialize(value).map_err(de::Error::custom)?;
                if flag::<D::Error>("f", raw.f)? {
                    let epoch = raw.e.ok_or_else(|| de::Error::missing_field("e"))?;
                    return Ok(SyncAnswer::FullCopy {
                        epoch,
                        version: raw.v,
                        rows: raw.u.unwrap_or_default(),
                        next: raw.n,
                    });
                }
                Ok(SyncAnswer::Changes {
                    version: raw.v,
                    upserts: raw.u.unwrap_or_default(),
                    deletes: raw.x.unwrap_or_default(),
                    more: flag::<D::Error>("m", raw.m)?,
                })
            }
            _ => Err(de::Error::custom(
                "a sync answer is 0, a changes object, a full copy or an error",
            )),
        }
    }
}

/// The `result` of `core.replica.sync`: `{"r":[…]}`, aligned with the request's
/// entries by index.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SyncReply {
    /// One answer per entry, in the request's order.
    #[serde(rename = "r")]
    pub answers: Vec<SyncAnswer>,
}

/// The payload of `core.replica.announce`: `{"c":"friends.people.pull","e":"k3f9a2c1","v":42}`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Announce {
    /// The pull capability whose head moved.
    #[serde(rename = "c")]
    pub capability: String,
    /// Its epoch.
    #[serde(rename = "e")]
    pub epoch: String,
    /// Its head.
    #[serde(rename = "v")]
    pub version: u64,
}

/// The node's answer to an announce: `{"ok":true}`, or `{"rotate":true}` when it
/// has handed out a higher version of that epoch (the app's data went back in
/// time).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AnnounceReply {
    /// `{"ok":true}`: the node took the head.
    Ok,
    /// `{"rotate":true}`: start a new epoch and announce again.
    Rotate,
}

impl Serialize for AnnounceReply {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut map = serializer.serialize_map(Some(1))?;
        match self {
            AnnounceReply::Ok => map.serialize_entry("ok", &true)?,
            AnnounceReply::Rotate => map.serialize_entry("rotate", &true)?,
        }
        map.end()
    }
}

impl<'de> Deserialize<'de> for AnnounceReply {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        #[derive(Deserialize)]
        struct Raw {
            #[serde(default)]
            ok: bool,
            #[serde(default)]
            rotate: bool,
        }
        let raw = Raw::deserialize(deserializer)?;
        if raw.rotate {
            Ok(AnnounceReply::Rotate)
        } else if raw.ok {
            Ok(AnnounceReply::Ok)
        } else {
            Err(de::Error::custom(
                "an announce reply is {\"ok\":true} or {\"rotate\":true}",
            ))
        }
    }
}

/// One head in a `replica.heads` push: `["friends.people.pull","k3f9a2c1",42]`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PushedHead {
    /// The pull capability.
    pub capability: String,
    /// Its epoch.
    pub epoch: String,
    /// Its head.
    pub version: u64,
}

impl Serialize for PushedHead {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        (&self.capability, &self.epoch, self.version).serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for PushedHead {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let (capability, epoch, version) = <(String, String, u64)>::deserialize(deserializer)?;
        Ok(PushedHead {
            capability,
            epoch,
            version,
        })
    }
}

/// The `data` of a `replica.heads` frame: `{"h":[[…]]}`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HeadsData {
    /// The heads, one per capability that moved.
    #[serde(rename = "h")]
    pub heads: Vec<PushedHead>,
}

/// `[a-z0-9]{1,16}`.
pub fn is_epoch(value: &str) -> bool {
    !value.is_empty()
        && value.len() <= MAX_EPOCH_CHARS
        && value
            .bytes()
            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
}

/// A row key: 1–256 bytes, no control characters.
pub fn validate_key(key: &str) -> Result<(), String> {
    if key.is_empty() {
        return Err("key must not be empty".to_string());
    }
    if key.len() > MAX_KEY_BYTES {
        return Err(format!(
            "key is {} bytes; at most {MAX_KEY_BYTES} are allowed",
            key.len()
        ));
    }
    if key.chars().any(char::is_control) {
        return Err("key must not contain control characters".to_string());
    }
    Ok(())
}

/// Whether `value` nests no deeper than [`MAX_VALUE_DEPTH`] levels. Walks the
/// value with an explicit stack and stops at the first level past the limit, so
/// a deep value is refused without using the call stack. The same rule as the
/// device's `isWithinReplicaValueDepth` and the TypeScript helper's
/// `isWithinValueDepth`; `tests/fixtures/value-depth.json` holds the shared cases.
pub fn value_within_depth(value: &Value) -> bool {
    let mut stack: Vec<(usize, &Value)> = vec![(1, value)];
    while let Some((level, value)) = stack.pop() {
        let is_container = matches!(value, Value::Array(_) | Value::Object(_));
        if is_container && level >= MAX_VALUE_DEPTH {
            return false;
        }
        match value {
            Value::Array(items) => stack.extend(items.iter().map(|child| (level + 1, child))),
            Value::Object(object) => stack.extend(object.values().map(|child| (level + 1, child))),
            _ => {}
        }
    }
    true
}

/// The refusal of a value past [`MAX_VALUE_DEPTH`], the same text as the
/// TypeScript helper's.
pub(crate) const VALUE_TOO_DEEP: &str =
    "value nests 128 or more containers; at most 127 are allowed (the node's JSON limit)";

/// The bytes one row adds inside `u` (its entry plus a separating comma).
pub(crate) fn encoded_row_bytes(row: &Row) -> usize {
    crate::digest::json_len_of_str(&row.key)
        + crate::digest::canonical_len(&row.value)
        + match (row.ord, row.part.is_empty()) {
            (0, true) => 0,
            (ord, true) => 1 + ord.to_string().len(),
            (ord, false) => 2 + ord.to_string().len() + crate::digest::json_len_of_str(&row.part),
        }
        // `[`, the comma after the key, `]`, and the comma before the next entry.
        + 4
}

/// The bytes one delete adds inside `x`.
pub(crate) fn encoded_delete_bytes(key: &str) -> usize {
    crate::digest::json_len_of_str(key) + 1
}