syncular-ssp2 0.68.0

Syncular v2 SSP2 wire codec, implemented from SPEC.md alone (language-neutrality POC)
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
//! Conventions primitives (SPEC.md "Conventions and primitive encodings"):
//! little-endian fixed-width integers, `str`, `bytes`, `opt`, `bool`, `json`,
//! canonical maps. Shared by the envelope codec and the SSG2 segment codec.

use crate::error::{DecodeError, Result};
use crate::util::utf16_lt;

/// JS safe-integer contract: `i64` values must be within ±(2^53 − 1).
pub const I64_SAFE_MAX: i64 = 9_007_199_254_740_991;

const JSON_MAX_DEPTH: usize = 64;

/// Parse `raw` under the JSON validity rule (SPEC.md Conventions), which is
/// defined on the raw text: RFC 8259, at most 64 nested containers anywhere in
/// the text, every number token a finite binary64, no U+0000 and no unpaired
/// surrogate in any string token (key or value). The one definition for
/// envelope `json` fields, push-payload `json` columns and `blob_ref` values;
/// the TS core's `parseJsonDocument` accepts exactly the same documents.
///
/// `serde_json` parses every value, shadowed ones included, and rejects
/// numbers that overflow binary64 (correctly rounded through the
/// `float_roundtrip` feature, so `f64::MAX` written in full parses) and
/// unpaired surrogate escapes. One lexical pass adds depth and the `\u0000`
/// escape; a literal U+0000 is a control character that RFC 8259 rejects.
pub fn parse_json_document(raw: &str, what: &str) -> Result<serde_json::Value> {
    let value = serde_json::from_str(raw).map_err(|_| {
        DecodeError::invalid(format!(
            "{what} is not a JSON document under the validity rule"
        ))
    })?;
    let text = raw.as_bytes();
    let (mut depth, mut at) = (0usize, 0usize);
    while at < text.len() {
        match text[at] {
            b'[' | b'{' => {
                depth += 1;
                if depth > JSON_MAX_DEPTH {
                    return Err(DecodeError::invalid(format!(
                        "{what} nests deeper than {JSON_MAX_DEPTH} containers"
                    )));
                }
            }
            b']' | b'}' => depth -= 1,
            b'"' => {
                at += 1;
                while text[at] != b'"' {
                    if text[at] == b'\\' {
                        if text[at + 1..].starts_with(b"u0000") {
                            return Err(DecodeError::invalid(format!(
                                "{what} holds a string with U+0000"
                            )));
                        }
                        at += 1;
                    }
                    at += 1;
                }
            }
            _ => {}
        }
        at += 1;
    }
    Ok(value)
}

/// A raw `json`-typed value: validated to parse as a JSON document at decode
/// time, but preserved byte-for-byte (host-opaque; round-trip fidelity, never
/// re-canonicalization — Conventions `json` row).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RawJson(pub String);

impl RawJson {
    pub fn parse(&self) -> serde_json::Value {
        // Validated at construction; a parse failure here is a codec bug.
        serde_json::from_str(&self.0).expect("RawJson holds validated JSON")
    }
}

pub struct Reader<'a> {
    buf: &'a [u8],
    pos: usize,
}

impl<'a> Reader<'a> {
    pub fn new(buf: &'a [u8]) -> Self {
        Reader { buf, pos: 0 }
    }

    pub fn remaining(&self) -> usize {
        self.buf.len() - self.pos
    }

    pub fn is_empty(&self) -> bool {
        self.remaining() == 0
    }

    pub fn take(&mut self, n: usize, what: &str) -> Result<&'a [u8]> {
        if n > self.remaining() {
            return Err(DecodeError::invalid(format!(
                "truncated: need {n} bytes for {what}, have {}",
                self.remaining()
            )));
        }
        let s = &self.buf[self.pos..self.pos + n];
        self.pos += n;
        Ok(s)
    }

    pub fn u8(&mut self, what: &str) -> Result<u8> {
        Ok(self.take(1, what)?[0])
    }

    pub fn u16(&mut self, what: &str) -> Result<u16> {
        let b = self.take(2, what)?;
        Ok(u16::from_le_bytes([b[0], b[1]]))
    }

    pub fn u32(&mut self, what: &str) -> Result<u32> {
        let b = self.take(4, what)?;
        Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
    }

    pub fn i32(&mut self, what: &str) -> Result<i32> {
        let b = self.take(4, what)?;
        Ok(i32::from_le_bytes([b[0], b[1], b[2], b[3]]))
    }

    pub fn i64(&mut self, what: &str) -> Result<i64> {
        let b = self.take(8, what)?;
        let v = i64::from_le_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]);
        if !(-I64_SAFE_MAX..=I64_SAFE_MAX).contains(&v) {
            return Err(DecodeError::invalid(format!(
                "i64 field {what} = {v} outside the ±(2^53−1) safe-integer contract"
            )));
        }
        Ok(v)
    }

    pub fn f64(&mut self, what: &str) -> Result<f64> {
        let b = self.take(8, what)?;
        Ok(f64::from_le_bytes([
            b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],
        ]))
    }

    pub fn bool(&mut self, what: &str) -> Result<bool> {
        match self.u8(what)? {
            0x00 => Ok(false),
            0x01 => Ok(true),
            other => Err(DecodeError::invalid(format!(
                "bool field {what} has byte 0x{other:02x} (only 0x00/0x01 are valid)"
            ))),
        }
    }

    /// `opt(T)` presence byte: 0x00 absent, 0x01 present, anything else a
    /// decode error.
    pub fn presence(&mut self, what: &str) -> Result<bool> {
        match self.u8(what)? {
            0x00 => Ok(false),
            0x01 => Ok(true),
            other => Err(DecodeError::invalid(format!(
                "opt presence byte for {what} is 0x{other:02x} (only 0x00/0x01 are valid)"
            ))),
        }
    }

    pub fn str(&mut self, what: &str) -> Result<String> {
        let len = self.u32(what)? as usize;
        let raw = self.take(len, what)?;
        match std::str::from_utf8(raw) {
            Ok(s) => Ok(s.to_owned()),
            Err(_) => Err(DecodeError::invalid(format!(
                "str field {what} is not well-formed UTF-8"
            ))),
        }
    }

    pub fn bytes(&mut self, what: &str) -> Result<Vec<u8>> {
        let len = self.u32(what)? as usize;
        Ok(self.take(len, what)?.to_vec())
    }

    /// `json`: a `str` that must be a valid JSON document (Conventions JSON
    /// validity rule); the raw string is preserved verbatim for round-trip
    /// fidelity.
    pub fn json(&mut self, what: &str) -> Result<RawJson> {
        let s = self.str(what)?;
        parse_json_document(&s, what)?;
        Ok(RawJson(s))
    }

    /// `blob_ref` (§2.4 tag 7, §5.9.1): a `str` holding a canonical BlobRef
    /// document; validated at decode, raw string preserved for round-trip.
    pub fn blob_ref(&mut self, what: &str) -> Result<RawJson> {
        let s = self.str(what)?;
        crate::blob_ref::validate_blob_ref(&s)?;
        Ok(RawJson(s))
    }

    /// `map` of `str` → `list(str)`. Keys must be unique and in ascending
    /// code-unit order (canonical encoding); a violation is a decode error.
    pub fn scope_map(&mut self, what: &str) -> Result<Vec<(String, Vec<String>)>> {
        let count = self.u32(what)? as usize;
        let mut entries: Vec<(String, Vec<String>)> = Vec::with_capacity(count.min(1024));
        for _ in 0..count {
            let key = self.str(what)?;
            self.check_key_order(&entries.last().map(|(k, _)| k.as_str()), &key, what)?;
            let n = self.u32(what)? as usize;
            let mut values = Vec::with_capacity(n.min(1024));
            for _ in 0..n {
                values.push(self.str(what)?);
            }
            entries.push((key, values));
        }
        Ok(entries)
    }

    /// `map` of `str` → `str`, same canonical key rules.
    pub fn str_map(&mut self, what: &str) -> Result<Vec<(String, String)>> {
        let count = self.u32(what)? as usize;
        let mut entries: Vec<(String, String)> = Vec::with_capacity(count.min(1024));
        for _ in 0..count {
            let key = self.str(what)?;
            self.check_key_order(&entries.last().map(|(k, _)| k.as_str()), &key, what)?;
            let value = self.str(what)?;
            entries.push((key, value));
        }
        Ok(entries)
    }

    fn check_key_order(&self, prev: &Option<&str>, key: &str, what: &str) -> Result<()> {
        if let Some(prev) = prev {
            if !utf16_lt(prev, key) {
                return Err(DecodeError::invalid(format!(
                    "map {what}: key {key:?} is duplicate or out of canonical order after {prev:?}"
                )));
            }
        }
        Ok(())
    }
}

#[derive(Default)]
pub struct Writer {
    buf: Vec<u8>,
}

impl Writer {
    pub fn new() -> Self {
        Writer::default()
    }

    pub fn into_bytes(self) -> Vec<u8> {
        self.buf
    }

    pub fn raw(&mut self, bytes: &[u8]) {
        self.buf.extend_from_slice(bytes);
    }

    pub fn u8(&mut self, v: u8) {
        self.buf.push(v);
    }

    pub fn u16(&mut self, v: u16) {
        self.buf.extend_from_slice(&v.to_le_bytes());
    }

    pub fn u32(&mut self, v: u32) {
        self.buf.extend_from_slice(&v.to_le_bytes());
    }

    pub fn i32(&mut self, v: i32) {
        self.buf.extend_from_slice(&v.to_le_bytes());
    }

    pub fn i64(&mut self, v: i64) {
        self.buf.extend_from_slice(&v.to_le_bytes());
    }

    pub fn f64(&mut self, v: f64) {
        self.buf.extend_from_slice(&v.to_le_bytes());
    }

    pub fn bool(&mut self, v: bool) {
        self.buf.push(u8::from(v));
    }

    pub fn str(&mut self, s: &str) {
        self.u32(s.len() as u32);
        self.buf.extend_from_slice(s.as_bytes());
    }

    pub fn bytes(&mut self, b: &[u8]) {
        self.u32(b.len() as u32);
        self.buf.extend_from_slice(b);
    }

    pub fn opt<T>(&mut self, v: &Option<T>, mut write: impl FnMut(&mut Self, &T)) {
        match v {
            None => self.u8(0x00),
            Some(inner) => {
                self.u8(0x01);
                write(self, inner);
            }
        }
    }

    pub fn scope_map(&mut self, m: &[(String, Vec<String>)]) {
        self.u32(m.len() as u32);
        for (k, vs) in m {
            self.str(k);
            self.u32(vs.len() as u32);
            for v in vs {
                self.str(v);
            }
        }
    }

    pub fn str_map(&mut self, m: &[(String, String)]) {
        self.u32(m.len() as u32);
        for (k, v) in m {
            self.str(k);
            self.str(v);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::parse_json_document;

    fn nested(open: &str, close: &str, depth: usize) -> String {
        format!("{}{}", open.repeat(depth), close.repeat(depth))
    }

    /// The same probe table as the TS core's `json-document.test.ts`.
    #[test]
    fn the_json_validity_rule_matches_the_ts_core() {
        let probes: Vec<(&str, String, bool)> = vec![
            ("arrays nested 64 deep", nested("[", "]", 64), true),
            ("arrays nested 65 deep", nested("[", "]", 65), false),
            (
                "objects nested 64 deep",
                format!("{}{{}}{}", "{\"a\":".repeat(63), "}".repeat(63)),
                true,
            ),
            (
                "objects nested 65 deep",
                format!("{}{{}}{}", "{\"a\":".repeat(64), "}".repeat(64)),
                false,
            ),
            ("1e999", "1e999".into(), false),
            ("-1e999 inside an array", "[-1e999]".into(), false),
            ("1e-999 underflows to zero", "1e-999".into(), true),
            ("negative zero", "-0".into(), true),
            (
                "largest finite binary64",
                "1.7976931348623157e308".into(),
                true,
            ),
            ("rounds to infinity", "1.7976931348623159e308".into(), false),
            (
                "integer beyond 2^64",
                "123456789012345678901234567890".into(),
                true,
            ),
            ("unpaired high surrogate", r#""\ud800""#.into(), false),
            ("unpaired low surrogate", r#""\udc00""#.into(), false),
            (
                "high surrogate before a letter",
                r#""\ud800x""#.into(),
                false,
            ),
            ("escaped surrogate pair", r#""😀""#.into(), true),
            ("unpaired surrogate key", r#"{"\ud800":1}"#.into(), false),
            ("U+0000 escape", r#""\u0000""#.into(), false),
            ("U+0000 key", r#"{"\u0000":1}"#.into(), false),
            ("U+0000 deep inside", r#"[{"a":["x\u0000"]}]"#.into(), false),
            ("U+0001 escape", r#""\u0001""#.into(), true),
            ("raw U+0000 in a string", "\"a\0b\"".into(), false),
            ("duplicate keys", r#"{"a":1,"a":2}"#.into(), true),
            ("shadowed 1e999", r#"{"a":1e999,"a":1}"#.into(), false),
            (
                "shadowed unpaired surrogate",
                r#"{"a":"\ud800","a":1}"#.into(),
                false,
            ),
            (
                "shadowed U+0000 escape",
                r#"{"a":"\u0000","a":1}"#.into(),
                false,
            ),
            (
                "shadowed depth 64",
                format!("{{\"a\":{},\"a\":1}}", nested("[", "]", 63)),
                true,
            ),
            (
                "shadowed depth 65",
                format!("{{\"a\":{},\"a\":1}}", nested("[", "]", 64)),
                false,
            ),
            (
                "shadowed depth 128",
                format!("{{\"a\":{},\"a\":1}}", nested("[", "]", 127)),
                false,
            ),
            (
                "escaped backslash before u0000",
                r#""\\u0000""#.into(),
                true,
            ),
            (
                "brackets inside strings",
                r#"["[[[[", "}}}}"]"#.into(),
                true,
            ),
            (
                "insignificant whitespace",
                r#" { "a" : [ 1 , 2 ] } "#.into(),
                true,
            ),
            ("top-level true", "true".into(), true),
            ("top-level null", "null".into(), true),
            ("top-level string", r#""x""#.into(), true),
            ("top-level number", "7".into(), true),
            ("not JSON", "{not json".into(), false),
            ("trailing comma", "[1,]".into(), false),
            ("leading zero", "01".into(), false),
            ("NaN literal", "NaN".into(), false),
            ("byte order mark", "\u{feff}1".into(), false),
        ];
        for (name, raw, valid) in probes {
            match parse_json_document(&raw, "probe") {
                Ok(_) => assert!(valid, "{name}: accepted, expected a rejection"),
                Err(error) => {
                    assert!(!valid, "{name}: rejected: {}", error.detail);
                    assert_eq!(error.code.as_str(), "sync.invalid_request", "{name}");
                }
            }
        }
    }

    #[test]
    fn the_last_duplicate_key_wins() {
        let value = parse_json_document(r#"{"a":1,"a":[true]}"#, "probe").unwrap();
        assert_eq!(value, serde_json::json!({"a": [true]}));
    }
}