OXYGENHUB
# 4fe7d6045860 oxygen / crates / oxy-core / src / objects.rs
39.0 KiB · Rust · last changed Store large inserts as text blobs (change format 2) 1 month ago source blame history raw
1
//! Typed objects and their canonical encodings (spec §6, §7, §13.2).
2
//!
3
//! Encoding conventions not fixed by the spec text are defined here:
4
//! - Enum-like items (`TreeOp`, `Edit`) are maps whose key 0 is the variant tag.
5
//! - An `OpRef`/atom reference is `[bytes32, uint]`; `AtomRef::Start` is `0`
6
//!   and `AtomRef::End` is `1`.
7
//! - A `Mode` is an unsigned integer: bit 0 = executable, bit 1 = opaque.
8
//! - `NodeKind`: 0 = file, 1 = dir, 2 = symlink.
9
10
use crate::cbor::{self, Value};
11
use crate::hash::{hash_object, ChangeHash, KeyId, ObjectRef, ObjectType};
12
use crate::ids::{ChangeId, NodeId};
13
use std::collections::BTreeMap;
14
15
pub const FORMAT_VERSION: u64 = 1;
16
17
/// The change format writers produce (spec §6.1). Version 2 stores each
18
/// large insert's lines as a text blob; readers accept 1 and 2, and a
19
/// change keeps the version it was made in, so its hash never moves.
20
pub const CHANGE_VERSION: u64 = 2;
21
22
/// In a version 2 change, an insert whose lines encode (as a CBOR array of
23
/// byte strings) to at least this many bytes is stored as a text blob
24
/// holding exactly that encoding; a shorter one is inline (spec §6.1).
25
pub const TEXT_BLOB_MIN: usize = 4096;
26
27
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
28
pub enum ObjectError {
29
    #[error("cbor: {0}")]
30
    Cbor(#[from] cbor::CborError),
31
    #[error("schema: {0}")]
32
    Schema(String),
33
}
34
35
pub(crate) fn schema<T>(msg: impl Into<String>) -> Result<T, ObjectError> {
36
    Err(ObjectError::Schema(msg.into()))
37
}
38
39
pub(crate) type Map = BTreeMap<u64, Value>;
40
41
pub(crate) fn field<'a>(m: &'a Map, k: u64, what: &str) -> Result<&'a Value, ObjectError> {
42
    m.get(&k)
43
        .ok_or_else(|| ObjectError::Schema(format!("missing field {k} ({what})")))
44
}
45
pub(crate) fn uint(v: &Value, what: &str) -> Result<u64, ObjectError> {
46
    v.as_uint()
47
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected unsigned integer")))
48
}
49
pub(crate) fn u32_(v: &Value, what: &str) -> Result<u32, ObjectError> {
50
    u32::try_from(uint(v, what)?).map_err(|_| ObjectError::Schema(format!("{what}: exceeds u32")))
51
}
52
pub(crate) fn text<'a>(v: &'a Value, what: &str) -> Result<&'a str, ObjectError> {
53
    v.as_text()
54
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected text")))
55
}
56
pub(crate) fn array<'a>(v: &'a Value, what: &str) -> Result<&'a [Value], ObjectError> {
57
    v.as_array()
58
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected array")))
59
}
60
pub(crate) fn map<'a>(v: &'a Value, what: &str) -> Result<&'a Map, ObjectError> {
61
    v.as_map()
62
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected map")))
63
}
64
pub(crate) fn bytes<'a>(v: &'a Value, what: &str) -> Result<&'a [u8], ObjectError> {
65
    v.as_bytes()
66
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected bytes")))
67
}
68
pub(crate) fn oref(v: &Value, what: &str) -> Result<ObjectRef, ObjectError> {
69
    ObjectRef::from_slice(bytes(v, what)?)
70
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected 32 bytes")))
71
}
72
pub(crate) fn node_id(v: &Value, what: &str) -> Result<NodeId, ObjectError> {
73
    NodeId::from_slice(bytes(v, what)?)
74
        .ok_or_else(|| ObjectError::Schema(format!("{what}: expected 16 bytes")))
75
}
76
pub(crate) fn check_version(m: &Map) -> Result<(), ObjectError> {
77
    let v = uint(field(m, 0, "version")?, "version")?;
78
    if v != FORMAT_VERSION {
79
        return schema(format!("unsupported format version {v}"));
80
    }
81
    Ok(())
82
}
83
84
// ---------------------------------------------------------------- Hlc
85
86
/// Hybrid logical clock (spec §6.4).
87
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
88
pub struct Hlc {
89
    pub wall_ms: u64,
90
    pub logical: u32,
91
}
92
93
impl Hlc {
94
    pub fn now() -> Hlc {
95
        let wall_ms = std::time::SystemTime::now()
96
            .duration_since(std::time::UNIX_EPOCH)
97
            .map(|d| d.as_millis() as u64)
98
            .unwrap_or(0);
99
        Hlc {
100
            wall_ms,
101
            logical: 0,
102
        }
103
    }
104
    pub(crate) fn to_value(self) -> Value {
105
        Value::map([
106
            (0, Value::Uint(self.wall_ms)),
107
            (1, Value::Uint(self.logical as u64)),
108
        ])
109
    }
110
    pub(crate) fn from_value(v: &Value) -> Result<Hlc, ObjectError> {
111
        let m = map(v, "hlc")?;
112
        Ok(Hlc {
113
            wall_ms: uint(field(m, 0, "hlc.wall_ms")?, "hlc.wall_ms")?,
114
            logical: u32_(field(m, 1, "hlc.logical")?, "hlc.logical")?,
115
        })
116
    }
117
}
118
119
// ---------------------------------------------------------------- tree
120
121
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
122
pub enum NodeKind {
123
    File,
124
    Dir,
125
    Symlink,
126
    /// A nested repository pinned to a state (spec §7.8); content is a pin.
127
    Subrepo,
128
}
129
130
impl NodeKind {
131
    pub(crate) fn tag(self) -> u64 {
132
        match self {
133
            NodeKind::File => 0,
134
            NodeKind::Dir => 1,
135
            NodeKind::Symlink => 2,
136
            NodeKind::Subrepo => 3,
137
        }
138
    }
139
    pub(crate) fn from_tag(t: u64) -> Result<NodeKind, ObjectError> {
140
        Ok(match t {
141
            0 => NodeKind::File,
142
            1 => NodeKind::Dir,
143
            2 => NodeKind::Symlink,
144
            3 => NodeKind::Subrepo,
145
            _ => return schema(format!("unknown node kind {t}")),
146
        })
147
    }
148
}
149
150
/// Executable bit plus content mode (spec §7.1, §7.5).
151
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PartialOrd, Ord)]
152
pub struct Mode {
153
    pub exec: bool,
154
    pub opaque: bool,
155
}
156
157
impl Mode {
158
    pub const TEXT: Mode = Mode {
159
        exec: false,
160
        opaque: false,
161
    };
162
    pub const OPAQUE: Mode = Mode {
163
        exec: false,
164
        opaque: true,
165
    };
166
    pub(crate) fn bits(self) -> u64 {
167
        (self.exec as u64) | ((self.opaque as u64) << 1)
168
    }
169
    pub(crate) fn from_bits(b: u64) -> Result<Mode, ObjectError> {
170
        if b > 3 {
171
            return schema(format!("unknown mode bits {b}"));
172
        }
173
        Ok(Mode {
174
            exec: b & 1 != 0,
175
            opaque: b & 2 != 0,
176
        })
177
    }
178
}
179
180
/// Reference to a tree operation of some change: the placement or mode atom it
181
/// introduced. `change == ObjectRef::ZERO` means this change.
182
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
183
pub struct OpRef {
184
    pub change: ChangeHash,
185
    pub index: u32,
186
}
187
188
impl OpRef {
189
    fn to_value(self) -> Value {
190
        Value::Array(vec![
191
            Value::Bytes(self.change.0.to_vec()),
192
            Value::Uint(self.index as u64),
193
        ])
194
    }
195
    fn from_value(v: &Value, what: &str) -> Result<OpRef, ObjectError> {
196
        let a = array(v, what)?;
197
        if a.len() != 2 {
198
            return schema(format!("{what}: expected [hash, index]"));
199
        }
200
        Ok(OpRef {
201
            change: oref(&a[0], what)?,
202
            index: u32_(&a[1], what)?,
203
        })
204
    }
205
    /// Replace a self reference with the concrete change hash.
206
    pub fn resolve(self, me: ChangeHash) -> OpRef {
207
        if self.change.is_zero() {
208
            OpRef { change: me, ..self }
209
        } else {
210
            self
211
        }
212
    }
213
}
214
215
#[derive(Debug, Clone, PartialEq, Eq)]
216
pub enum TreeOp {
217
    AddNode {
218
        node: NodeId,
219
        kind: NodeKind,
220
        mode: Mode,
221
        parent: NodeId,
222
        name: String,
223
    },
224
    RemoveNode {
225
        node: NodeId,
226
        placement: OpRef,
227
    },
228
    Move {
229
        node: NodeId,
230
        old: OpRef,
231
        parent: NodeId,
232
        name: String,
233
    },
234
    SetMode {
235
        node: NodeId,
236
        old: OpRef,
237
        mode: Mode,
238
    },
239
}
240
241
/// Names must be valid, non-empty, not `.`/`..`, and free of `/` and NUL (spec §7.1).
242
pub fn validate_name(name: &str) -> Result<(), ObjectError> {
243
    if name.is_empty() || name == "." || name == ".." || name.contains('/') || name.contains('\0') {
244
        return schema(format!("invalid placement name {name:?}"));
245
    }
246
    Ok(())
247
}
248
249
impl TreeOp {
250
    pub fn node(&self) -> NodeId {
251
        match self {
252
            TreeOp::AddNode { node, .. }
253
            | TreeOp::RemoveNode { node, .. }
254
            | TreeOp::Move { node, .. }
255
            | TreeOp::SetMode { node, .. } => *node,
256
        }
257
    }
258
259
    fn to_value(&self) -> Value {
260
        let nid = |n: &NodeId| Value::Bytes(n.0.to_vec());
261
        match self {
262
            TreeOp::AddNode {
263
                node,
264
                kind,
265
                mode,
266
                parent,
267
                name,
268
            } => Value::map([
269
                (0, Value::Uint(0)),
270
                (1, nid(node)),
271
                (2, Value::Uint(kind.tag())),
272
                (3, Value::Uint(mode.bits())),
273
                (4, nid(parent)),
274
                (5, Value::Text(name.clone())),
275
            ]),
276
            TreeOp::RemoveNode { node, placement } => Value::map([
277
                (0, Value::Uint(1)),
278
                (1, nid(node)),
279
                (2, placement.to_value()),
280
            ]),
281
            TreeOp::Move {
282
                node,
283
                old,
284
                parent,
285
                name,
286
            } => Value::map([
287
                (0, Value::Uint(2)),
288
                (1, nid(node)),
289
                (2, old.to_value()),
290
                (4, nid(parent)),
291
                (5, Value::Text(name.clone())),
292
            ]),
293
            TreeOp::SetMode { node, old, mode } => Value::map([
294
                (0, Value::Uint(3)),
295
                (1, nid(node)),
296
                (2, old.to_value()),
297
                (3, Value::Uint(mode.bits())),
298
            ]),
299
        }
300
    }
301
302
    fn from_value(v: &Value) -> Result<TreeOp, ObjectError> {
303
        let m = map(v, "tree_op")?;
304
        let tag = uint(field(m, 0, "tree_op tag")?, "tree_op tag")?;
305
        let node = node_id(field(m, 1, "tree_op.node")?, "tree_op.node")?;
306
        let op = match tag {
307
            0 => {
308
                let name = text(field(m, 5, "name")?, "name")?.to_owned();
309
                validate_name(&name)?;
310
                TreeOp::AddNode {
311
                    node,
312
                    kind: NodeKind::from_tag(uint(field(m, 2, "kind")?, "kind")?)?,
313
                    mode: Mode::from_bits(uint(field(m, 3, "mode")?, "mode")?)?,
314
                    parent: node_id(field(m, 4, "parent")?, "parent")?,
315
                    name,
316
                }
317
            }
318
            1 => TreeOp::RemoveNode {
319
                node,
320
                placement: OpRef::from_value(field(m, 2, "placement")?, "placement")?,
321
            },
322
            2 => {
323
                let name = text(field(m, 5, "name")?, "name")?.to_owned();
324
                validate_name(&name)?;
325
                TreeOp::Move {
326
                    node,
327
                    old: OpRef::from_value(field(m, 2, "old")?, "old")?,
328
                    parent: node_id(field(m, 4, "parent")?, "parent")?,
329
                    name,
330
                }
331
            }
332
            3 => TreeOp::SetMode {
333
                node,
334
                old: OpRef::from_value(field(m, 2, "old")?, "old")?,
335
                mode: Mode::from_bits(uint(field(m, 3, "mode")?, "mode")?)?,
336
            },
337
            _ => return schema(format!("unknown tree op tag {tag}")),
338
        };
339
        if node.is_root() {
340
            return schema("tree op on the root node");
341
        }
342
        Ok(op)
343
    }
344
}
345
346
// ---------------------------------------------------------------- edits
347
348
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
349
pub enum AtomRef {
350
    Start,
351
    End,
352
    Atom { change: ChangeHash, index: u32 },
353
}
354
355
impl AtomRef {
356
    fn to_value(self) -> Value {
357
        match self {
358
            AtomRef::Start => Value::Uint(0),
359
            AtomRef::End => Value::Uint(1),
360
            AtomRef::Atom { change, index } => Value::Array(vec![
361
                Value::Bytes(change.0.to_vec()),
362
                Value::Uint(index as u64),
363
            ]),
364
        }
365
    }
366
    fn from_value(v: &Value, what: &str) -> Result<AtomRef, ObjectError> {
367
        match v {
368
            Value::Uint(0) => Ok(AtomRef::Start),
369
            Value::Uint(1) => Ok(AtomRef::End),
370
            Value::Array(a) if a.len() == 2 => Ok(AtomRef::Atom {
371
                change: oref(&a[0], what)?,
372
                index: u32_(&a[1], what)?,
373
            }),
374
            _ => schema(format!("{what}: expected atom reference")),
375
        }
376
    }
377
    pub fn resolve(self, me: ChangeHash) -> AtomRef {
378
        match self {
379
            AtomRef::Atom { change, index } if change.is_zero() => {
380
                AtomRef::Atom { change: me, index }
381
            }
382
            other => other,
383
        }
384
    }
385
}
386
387
/// Half-open range of atoms introduced by one change.
388
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
389
pub struct AtomRange {
390
    pub change: ChangeHash,
391
    pub from: u32,
392
    pub to: u32,
393
}
394
395
impl AtomRange {
396
    fn to_value(self) -> Value {
397
        Value::Array(vec![
398
            Value::Bytes(self.change.0.to_vec()),
399
            Value::Uint(self.from as u64),
400
            Value::Uint(self.to as u64),
401
        ])
402
    }
403
    fn from_value(v: &Value) -> Result<AtomRange, ObjectError> {
404
        let a = array(v, "atom range")?;
405
        if a.len() != 3 {
406
            return schema("atom range: expected [hash, from, to]");
407
        }
408
        let r = AtomRange {
409
            change: oref(&a[0], "range.change")?,
410
            from: u32_(&a[1], "range.from")?,
411
            to: u32_(&a[2], "range.to")?,
412
        };
413
        if r.from >= r.to {
414
            return schema("atom range: empty or inverted");
415
        }
416
        Ok(r)
417
    }
418
    pub fn resolve(self, me: ChangeHash) -> AtomRange {
419
        if self.change.is_zero() {
420
            AtomRange { change: me, ..self }
421
        } else {
422
            self
423
        }
424
    }
425
}
426
427
#[derive(Debug, Clone, PartialEq, Eq)]
428
pub enum Edit {
429
    Insert {
430
        node: NodeId,
431
        after: AtomRef,
432
        before: AtomRef,
433
        lines: Vec<Vec<u8>>,
434
    },
435
    Delete {
436
        node: NodeId,
437
        atoms: Vec<AtomRange>,
438
    },
439
    Replace {
440
        node: NodeId,
441
        old: Option<ObjectRef>,
442
        new: Option<ObjectRef>,
443
    },
444
}
445
446
impl Edit {
447
    pub fn node(&self) -> NodeId {
448
        match self {
449
            Edit::Insert { node, .. } | Edit::Delete { node, .. } | Edit::Replace { node, .. } => {
450
                *node
451
            }
452
        }
453
    }
454
455
    /// Whether this insert is stored as a text blob in a change of `version`.
456
    fn stored_text(&self, version: u64) -> bool {
457
        matches!(self, Edit::Insert { lines, .. }
458
            if version >= 2 && cbor::byte_strings_len(lines) >= TEXT_BLOB_MIN)
459
    }
460
461
    fn to_value(&self, version: u64, texts: &mut Option<&mut Vec<StoredText>>) -> Value {
462
        let nid = |n: &NodeId| Value::Bytes(n.0.to_vec());
463
        let opt = |o: &Option<ObjectRef>| match o {
464
            Some(r) => Value::Bytes(r.0.to_vec()),
465
            None => Value::Null,
466
        };
467
        match self {
468
            Edit::Insert {
469
                node,
470
                after,
471
                before,
472
                lines,
473
            } if self.stored_text(version) => {
474
                let content = cbor::encode_byte_strings(lines);
475
                let blob = Blob::of(&content);
476
                let r = blob.hash();
477
                if let Some(t) = texts {
478
                    t.push(StoredText { blob, content });
479
                }
480
                Value::map([
481
                    (0, Value::Uint(0)),
482
                    (1, nid(node)),
483
                    (2, after.to_value()),
484
                    (3, before.to_value()),
485
                    (5, Value::Bytes(r.0.to_vec())),
486
                    (6, Value::Uint(lines.len() as u64)),
487
                ])
488
            }
489
            Edit::Insert {
490
                node,
491
                after,
492
                before,
493
                lines,
494
            } => Value::map([
495
                (0, Value::Uint(0)),
496
                (1, nid(node)),
497
                (2, after.to_value()),
498
                (3, before.to_value()),
499
                (
500
                    4,
501
                    Value::Array(lines.iter().map(|l| Value::Bytes(l.clone())).collect()),
502
                ),
503
            ]),
504
            Edit::Delete { node, atoms } => Value::map([
505
                (0, Value::Uint(1)),
506
                (1, nid(node)),
507
                (
508
                    2,
509
                    Value::Array(atoms.iter().map(|r| r.to_value()).collect()),
510
                ),
511
            ]),
512
            Edit::Replace { node, old, new } => Value::map([
513
                (0, Value::Uint(2)),
514
                (1, nid(node)),
515
                (2, opt(old)),
516
                (3, opt(new)),
517
            ]),
518
        }
519
    }
520
521
    fn from_value(v: &Value, version: u64, resolve: &mut Resolver) -> Result<Edit, ObjectError> {
522
        let m = map(v, "edit")?;
523
        let tag = uint(field(m, 0, "edit tag")?, "edit tag")?;
524
        let node = node_id(field(m, 1, "edit.node")?, "edit.node")?;
525
        let opt = |v: &Value, what: &str| -> Result<Option<ObjectRef>, ObjectError> {
526
            if v.is_null() {
527
                Ok(None)
528
            } else {
529
                Ok(Some(oref(v, what)?))
530
            }
531
        };
532
        Ok(match tag {
533
            0 => {
534
                let lines = match (m.get(&4), m.get(&5)) {
535
                    (Some(inline), None) => {
536
                        let lines = array(inline, "lines")?
537
                            .iter()
538
                            .map(|l| bytes(l, "line").map(|b| b.to_vec()))
539
                            .collect::<Result<Vec<_>, _>>()?;
540
                        if version >= 2 && cbor::byte_strings_len(&lines) >= TEXT_BLOB_MIN {
541
                            return schema("an insert this large is stored as a text blob in a version 2 change");
542
                        }
543
                        lines
544
                    }
545
                    (None, Some(text)) if version >= 2 => {
546
                        let text = oref(text, "insert text")?;
547
                        let count = u32_(field(m, 6, "insert line count")?, "insert line count")?;
548
                        if count == 0 {
549
                            return schema("insert with no lines");
550
                        }
551
                        // The resolver checks the count (`text_lines`).
552
                        resolve(&text, count)?
553
                    }
554
                    _ => {
555
                        return schema(
556
                            "an insert has either its lines or, in a version 2 change, a text blob",
557
                        )
558
                    }
559
                };
560
                if lines.is_empty() {
561
                    return schema("insert with no lines");
562
                }
563
                Edit::Insert {
564
                    node,
565
                    after: AtomRef::from_value(field(m, 2, "after")?, "after")?,
566
                    before: AtomRef::from_value(field(m, 3, "before")?, "before")?,
567
                    lines,
568
                }
569
            }
570
            1 => {
571
                let atoms = array(field(m, 2, "atoms")?, "atoms")?
572
                    .iter()
573
                    .map(AtomRange::from_value)
574
                    .collect::<Result<Vec<_>, _>>()?;
575
                if atoms.is_empty() {
576
                    return schema("delete with no atoms");
577
                }
578
                Edit::Delete { node, atoms }
579
            }
580
            2 => Edit::Replace {
581
                node,
582
                old: opt(field(m, 2, "old")?, "old")?,
583
                new: opt(field(m, 3, "new")?, "new")?,
584
            },
585
            _ => return schema(format!("unknown edit tag {tag}")),
586
        })
587
    }
588
}
589
590
// ---------------------------------------------------------------- change
591
592
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
593
pub enum ChangeKind {
594
    Normal,
595
    Resolution,
596
    WorkingCopy,
597
}
598
599
impl ChangeKind {
600
    pub(crate) fn tag(self) -> u64 {
601
        match self {
602
            ChangeKind::Normal => 0,
603
            ChangeKind::Resolution => 1,
604
            ChangeKind::WorkingCopy => 2,
605
        }
606
    }
607
    pub(crate) fn from_tag(t: u64) -> Result<ChangeKind, ObjectError> {
608
        Ok(match t {
609
            0 => ChangeKind::Normal,
610
            1 => ChangeKind::Resolution,
611
            2 => ChangeKind::WorkingCopy,
612
            _ => return schema(format!("unknown change kind {t}")),
613
        })
614
    }
615
}
616
617
/// A change (spec §6.1). `deps` is kept sorted and unique by `normalize`.
618
#[derive(Debug, Clone, PartialEq, Eq)]
619
pub struct Change {
620
    /// The format this change is encoded in: [`CHANGE_VERSION`] for a new
621
    /// one, whatever it was made in for one read back.
622
    pub version: u64,
623
    pub change_id: ChangeId,
624
    pub deps: Vec<ChangeHash>,
625
    pub author: KeyId,
626
    pub hlc: Hlc,
627
    pub message: String,
628
    pub tree_ops: Vec<TreeOp>,
629
    pub edits: Vec<Edit>,
630
    pub kind: ChangeKind,
631
}
632
633
impl Change {
634
    pub fn normalize(&mut self) {
635
        self.deps.sort();
636
        self.deps.dedup();
637
    }
638
639
    pub fn to_value(&self) -> Value {
640
        self.value_with(&mut None)
641
    }
642
643
    fn value_with(&self, texts: &mut Option<&mut Vec<StoredText>>) -> Value {
644
        Value::map([
645
            (0, Value::Uint(self.version)),
646
            (1, Value::Bytes(self.change_id.0.to_vec())),
647
            (
648
                2,
649
                Value::Array(
650
                    self.deps
651
                        .iter()
652
                        .map(|d| Value::Bytes(d.0.to_vec()))
653
                        .collect(),
654
                ),
655
            ),
656
            (3, Value::Bytes(self.author.0.to_vec())),
657
            (4, self.hlc.to_value()),
658
            (5, Value::Text(self.message.clone())),
659
            (
660
                6,
661
                Value::Array(self.tree_ops.iter().map(|t| t.to_value()).collect()),
662
            ),
663
            (
664
                7,
665
                Value::Array(
666
                    self.edits
667
                        .iter()
668
                        .map(|e| e.to_value(self.version, texts))
669
                        .collect(),
670
                ),
671
            ),
672
            (8, Value::Uint(self.kind.tag())),
673
            (9, Value::Map(BTreeMap::new())),
674
        ])
675
    }
676
677
    pub fn encode(&self) -> Vec<u8> {
678
        debug_assert!(
679
            self.deps.windows(2).all(|w| w[0] < w[1]),
680
            "deps must be normalized"
681
        );
682
        cbor::encode(&self.to_value())
683
    }
684
685
    /// The encoding and the text blobs its large inserts are stored as,
686
    /// which must be stored with it.
687
    pub fn encode_parts(&self) -> (Vec<u8>, Vec<StoredText>) {
688
        debug_assert!(
689
            self.deps.windows(2).all(|w| w[0] < w[1]),
690
            "deps must be normalized"
691
        );
692
        let mut texts = Vec::new();
693
        let bytes = cbor::encode(&self.value_with(&mut Some(&mut texts)));
694
        (bytes, texts)
695
    }
696
697
    /// Whether any insert is stored as a text blob.
698
    pub fn has_stored_text(&self) -> bool {
699
        self.edits.iter().any(|e| e.stored_text(self.version))
700
    }
701
702
    pub fn hash(&self) -> ChangeHash {
703
        hash_object(ObjectType::Change, &self.encode())
704
    }
705
706
    /// Decode a change that stores no text blob; one that does needs
707
    /// [`Change::decode_with`] and something to read them from.
708
    pub fn decode(bytes: &[u8]) -> Result<Change, ObjectError> {
709
        Self::decode_with(bytes, &mut |r, _| {
710
            schema(format!(
711
                "text blob {} needs a store to read it from",
712
                r.short(12)
713
            ))
714
        })
715
    }
716
717
    /// Decode a change, reading each stored insert's lines with `resolve`
718
    /// (given the text blob and the line count the insert claims).
719
    pub fn decode_with(bytes: &[u8], resolve: &mut Resolver) -> Result<Change, ObjectError> {
720
        let v = cbor::decode(bytes)?;
721
        Self::from_value_with(&v, resolve)
722
    }
723
724
    pub fn from_value(v: &Value) -> Result<Change, ObjectError> {
725
        Self::from_value_with(v, &mut |r, _| {
726
            schema(format!(
727
                "text blob {} needs a store to read it from",
728
                r.short(12)
729
            ))
730
        })
731
    }
732
733
    fn from_value_with(v: &Value, resolve: &mut Resolver) -> Result<Change, ObjectError> {
734
        let m = map(v, "change")?;
735
        let version = uint(field(m, 0, "version")?, "version")?;
736
        if !(1..=CHANGE_VERSION).contains(&version) {
737
            return schema(format!("unsupported change format version {version}"));
738
        }
739
        let change_id = ChangeId::from_slice(bytes(field(m, 1, "change_id")?, "change_id")?)
740
            .ok_or_else(|| ObjectError::Schema("change_id: expected 16 bytes".into()))?;
741
        let deps = array(field(m, 2, "deps")?, "deps")?
742
            .iter()
743
            .map(|d| oref(d, "dep"))
744
            .collect::<Result<Vec<_>, _>>()?;
745
        if !deps.windows(2).all(|w| w[0] < w[1]) {
746
            return schema("deps must be sorted and unique");
747
        }
748
        if deps.iter().any(|d| d.is_zero()) {
749
            return schema("deps may not contain the self reference");
750
        }
751
        let extra = map(field(m, 9, "extra")?, "extra")?;
752
        if !extra.is_empty() {
753
            return schema("extra must be empty in format version 1");
754
        }
755
        Ok(Change {
756
            version,
757
            change_id,
758
            deps,
759
            author: oref(field(m, 3, "author")?, "author")?,
760
            hlc: Hlc::from_value(field(m, 4, "hlc")?)?,
761
            message: text(field(m, 5, "message")?, "message")?.to_owned(),
762
            tree_ops: array(field(m, 6, "tree_ops")?, "tree_ops")?
763
                .iter()
764
                .map(TreeOp::from_value)
765
                .collect::<Result<Vec<_>, _>>()?,
766
            edits: array(field(m, 7, "edits")?, "edits")?
767
                .iter()
768
                .map(|e| Edit::from_value(e, version, resolve))
769
                .collect::<Result<Vec<_>, _>>()?,
770
            kind: ChangeKind::from_tag(uint(field(m, 8, "kind")?, "kind")?)?,
771
        })
772
    }
773
}
774
775
/// Reads a stored insert's lines, given the text blob and the line count
776
/// the insert claims; [`text_lines`] reads and checks a blob's content.
777
pub type Resolver<'a> = dyn FnMut(&ObjectRef, u32) -> Result<Vec<Vec<u8>>, ObjectError> + 'a;
778
779
/// A large insert's lines as stored (spec §6.1): the blob and its content,
780
/// the canonical CBOR array of the lines' byte strings.
781
#[derive(Debug, Clone, PartialEq, Eq)]
782
pub struct StoredText {
783
    pub blob: Blob,
784
    pub content: Vec<u8>,
785
}
786
787
/// The lines a text blob's `content` holds, checked against the rules for
788
/// one: canonical, as many as the insert claims, and not short enough to
789
/// have been inline.
790
pub fn text_lines(content: &[u8], count: u32) -> Result<Vec<Vec<u8>>, ObjectError> {
791
    if content.len() < TEXT_BLOB_MIN {
792
        return schema(format!(
793
            "a text blob of {} bytes is short enough to be inline",
794
            content.len()
795
        ));
796
    }
797
    let v = cbor::decode(content)?;
798
    let lines = array(&v, "text blob")?
799
        .iter()
800
        .map(|l| bytes(l, "line").map(|b| b.to_vec()))
801
        .collect::<Result<Vec<_>, _>>()?;
802
    if lines.len() != count as usize {
803
        return schema(format!(
804
            "a text blob holds {} lines, the insert says {count}",
805
            lines.len()
806
        ));
807
    }
808
    Ok(lines)
809
}
810
811
// ---------------------------------------------------------------- blob
812
813
/// File content as an ordered list of chunks (spec §13.2).
814
#[derive(Debug, Clone, PartialEq, Eq)]
815
pub struct Blob {
816
    pub length: u64,
817
    pub chunks: Vec<ObjectRef>,
818
}
819
820
impl Blob {
821
    /// The blob for `content`: its chunks as content-defined chunking cuts
822
    /// them (spec §13.2).
823
    pub fn of(content: &[u8]) -> Blob {
824
        Blob {
825
            length: content.len() as u64,
826
            chunks: crate::chunk::chunks(content)
827
                .into_iter()
828
                .map(|c| hash_object(ObjectType::Chunk, c))
829
                .collect(),
830
        }
831
    }
832
833
    pub fn encode(&self) -> Vec<u8> {
834
        cbor::encode(&Value::map([
835
            (0, Value::Uint(FORMAT_VERSION)),
836
            (1, Value::Uint(self.length)),
837
            (
838
                2,
839
                Value::Array(
840
                    self.chunks
841
                        .iter()
842
                        .map(|c| Value::Bytes(c.0.to_vec()))
843
                        .collect(),
844
                ),
845
            ),
846
        ]))
847
    }
848
    pub fn hash(&self) -> ObjectRef {
849
        hash_object(ObjectType::Blob, &self.encode())
850
    }
851
    pub fn decode(bytes: &[u8]) -> Result<Blob, ObjectError> {
852
        let v = cbor::decode(bytes)?;
853
        let m = map(&v, "blob")?;
854
        check_version(m)?;
855
        Ok(Blob {
856
            length: uint(field(m, 1, "length")?, "length")?,
857
            chunks: array(field(m, 2, "chunks")?, "chunks")?
858
                .iter()
859
                .map(|c| oref(c, "chunk"))
860
                .collect::<Result<Vec<_>, _>>()?,
861
        })
862
    }
863
}
864
865
// ---------------------------------------------------------------- checkpoint
866
867
/// A materialized state (spec §11): the heads it stands for, how many changes
868
/// it holds, and a blob with the serialized graphs (`State::checkpoint_payload`).
869
#[derive(Debug, Clone, PartialEq, Eq)]
870
pub struct Checkpoint {
871
    pub heads: Vec<ChangeHash>,
872
    pub count: u64,
873
    pub payload: ObjectRef,
874
}
875
876
impl Checkpoint {
877
    pub fn encode(&self) -> Vec<u8> {
878
        cbor::encode(&Value::map([
879
            (0, Value::Uint(FORMAT_VERSION)),
880
            (
881
                1,
882
                Value::Array(
883
                    self.heads
884
                        .iter()
885
                        .map(|h| Value::Bytes(h.0.to_vec()))
886
                        .collect(),
887
                ),
888
            ),
889
            (2, Value::Uint(self.count)),
890
            (3, Value::Bytes(self.payload.0.to_vec())),
891
        ]))
892
    }
893
    pub fn hash(&self) -> ObjectRef {
894
        hash_object(ObjectType::Checkpoint, &self.encode())
895
    }
896
    pub fn decode(bytes: &[u8]) -> Result<Checkpoint, ObjectError> {
897
        let v = cbor::decode(bytes)?;
898
        let m = map(&v, "checkpoint")?;
899
        check_version(m)?;
900
        Ok(Checkpoint {
901
            heads: array(field(m, 1, "heads")?, "heads")?
902
                .iter()
903
                .map(|h| oref(h, "head"))
904
                .collect::<Result<Vec<_>, _>>()?,
905
            count: uint(field(m, 2, "count")?, "count")?,
906
            payload: oref(field(m, 3, "payload")?, "payload")?,
907
        })
908
    }
909
}
910
911
// ---------------------------------------------------------------- state
912
913
/// A state named by its heads (spec §10.1): what a bookmark or tag points at.
914
#[derive(Debug, Clone, PartialEq, Eq, Default)]
915
pub struct StateObject {
916
    pub heads: Vec<ChangeHash>,
917
}
918
919
impl StateObject {
920
    pub fn new(mut heads: Vec<ChangeHash>) -> StateObject {
921
        heads.sort();
922
        heads.dedup();
923
        StateObject { heads }
924
    }
925
    pub fn encode(&self) -> Vec<u8> {
926
        debug_assert!(self.heads.windows(2).all(|w| w[0] < w[1]));
927
        cbor::encode(&Value::map([
928
            (0, Value::Uint(FORMAT_VERSION)),
929
            (
930
                1,
931
                Value::Array(
932
                    self.heads
933
                        .iter()
934
                        .map(|h| Value::Bytes(h.0.to_vec()))
935
                        .collect(),
936
                ),
937
            ),
938
        ]))
939
    }
940
    pub fn hash(&self) -> ObjectRef {
941
        hash_object(ObjectType::State, &self.encode())
942
    }
943
    pub fn decode(bytes: &[u8]) -> Result<StateObject, ObjectError> {
944
        let v = cbor::decode(bytes)?;
945
        let m = map(&v, "state")?;
946
        check_version(m)?;
947
        let heads = array(field(m, 1, "heads")?, "heads")?
948
            .iter()
949
            .map(|h| oref(h, "head"))
950
            .collect::<Result<Vec<_>, _>>()?;
951
        if !heads.windows(2).all(|w| w[0] < w[1]) {
952
            return schema("state heads must be sorted and unique");
953
        }
954
        Ok(StateObject { heads })
955
    }
956
}
957
958
#[cfg(test)]
959
pub(crate) mod tests {
960
    use super::*;
961
962
    pub(crate) fn sample_change() -> Change {
963
        let n = NodeId([7; 16]);
964
        let dep = ObjectRef([1; 32]);
965
        let mut c = Change {
966
            version: crate::objects::CHANGE_VERSION,
967
            change_id: ChangeId([9; 16]),
968
            deps: vec![ObjectRef([2; 32]), dep],
969
            author: ObjectRef([3; 32]),
970
            hlc: Hlc {
971
                wall_ms: 1_700_000_000_000,
972
                logical: 4,
973
            },
974
            message: "Add greeting".into(),
975
            tree_ops: vec![
976
                TreeOp::AddNode {
977
                    node: n,
978
                    kind: NodeKind::File,
979
                    mode: Mode::TEXT,
980
                    parent: NodeId::ROOT,
981
                    name: "hello.txt".into(),
982
                },
983
                TreeOp::SetMode {
984
                    node: n,
985
                    old: OpRef {
986
                        change: ObjectRef::ZERO,
987
                        index: 0,
988
                    },
989
                    mode: Mode {
990
                        exec: true,
991
                        opaque: false,
992
                    },
993
                },
994
            ],
995
            edits: vec![
996
                Edit::Insert {
997
                    node: n,
998
                    after: AtomRef::Start,
999
                    before: AtomRef::End,
1000
                    lines: vec![b"hello\n".to_vec(), b"world\n".to_vec()],
1001
                },
1002
                Edit::Delete {
1003
                    node: n,
1004
                    atoms: vec![AtomRange {
1005
                        change: dep,
1006
                        from: 0,
1007
                        to: 2,
1008
                    }],
1009
                },
1010
                Edit::Replace {
1011
                    node: n,
1012
                    old: None,
1013
                    new: Some(ObjectRef([5; 32])),
1014
                },
1015
            ],
1016
            kind: ChangeKind::Normal,
1017
        };
1018
        c.normalize();
1019
        c
1020
    }
1021
1022
    #[test]
1023
    fn change_round_trips_and_hash_is_stable() {
1024
        let c = sample_change();
1025
        let bytes = c.encode();
1026
        let d = Change::decode(&bytes).unwrap();
1027
        assert_eq!(c, d);
1028
        assert_eq!(c.hash(), d.hash());
1029
        assert_eq!(d.encode(), bytes);
1030
        // Any semantic difference changes the hash.
1031
        let mut e = c.clone();
1032
        e.message.push('!');
1033
        assert_ne!(e.hash(), c.hash());
1034
    }
1035
1036
    #[test]
1037
    fn decode_rejects_bad_changes() {
1038
        let c = sample_change();
1039
        let mut v = c.to_value();
1040
        if let Value::Map(m) = &mut v {
1041
            m.insert(0, Value::Uint(3));
1042
        }
1043
        assert!(
1044
            matches!(Change::from_value(&v), Err(ObjectError::Schema(s)) if s.contains("version"))
1045
        );
1046
1047
        let mut v = c.to_value();
1048
        if let Value::Map(m) = &mut v {
1049
            m.insert(
1050
                2,
1051
                Value::Array(vec![Value::Bytes(vec![2; 32]), Value::Bytes(vec![1; 32])]),
1052
            );
1053
        }
1054
        assert!(
1055
            matches!(Change::from_value(&v), Err(ObjectError::Schema(s)) if s.contains("sorted"))
1056
        );
1057
1058
        let mut v = c.to_value();
1059
        if let Value::Map(m) = &mut v {
1060
            m.insert(9, Value::map([(0, Value::Null)]));
1061
        }
1062
        assert!(
1063
            matches!(Change::from_value(&v), Err(ObjectError::Schema(s)) if s.contains("extra"))
1064
        );
1065
    }
1066
1067
    fn big_lines(n: usize) -> Vec<Vec<u8>> {
1068
        (0..n)
1069
            .map(|i| format!("line {i} of a large insert\n").into_bytes())
1070
            .collect()
1071
    }
1072
1073
    fn with_insert(mut c: Change, lines: Vec<Vec<u8>>) -> Change {
1074
        c.edits[0] = Edit::Insert {
1075
            node: NodeId([7; 16]),
1076
            after: AtomRef::Start,
1077
            before: AtomRef::End,
1078
            lines,
1079
        };
1080
        c
1081
    }
1082
1083
    #[test]
1084
    fn large_inserts_are_stored_as_text_blobs() {
1085
        assert!(
1086
            !sample_change().has_stored_text(),
1087
            "a small insert stays inline"
1088
        );
1089
        let lines = big_lines(500);
1090
        let c = with_insert(sample_change(), lines.clone());
1091
        assert!(c.has_stored_text());
1092
        let (bytes, texts) = c.encode_parts();
1093
        assert_eq!(bytes, c.encode());
1094
        assert!(bytes.len() < 1024, "{}", bytes.len());
1095
        assert_eq!(texts.len(), 1);
1096
        assert_eq!(texts[0].content, cbor::encode_byte_strings(&lines));
1097
        assert_eq!(texts[0].blob, Blob::of(&texts[0].content));
1098
        assert!(Change::decode(&bytes).is_err(), "reading it needs the text");
1099
        let d = Change::decode_with(&bytes, &mut |r, n| {
1100
            assert_eq!(*r, texts[0].blob.hash());
1101
            text_lines(&texts[0].content, n)
1102
        })
1103
        .unwrap();
1104
        assert_eq!(d, c);
1105
        assert_eq!(d.hash(), c.hash());
1106
    }
1107
1108
    #[test]
1109
    fn version_1_changes_keep_their_inline_inserts_and_hashes() {
1110
        let mut c = with_insert(sample_change(), big_lines(500));
1111
        c.version = 1;
1112
        let bytes = c.encode();
1113
        assert!(bytes.len() > TEXT_BLOB_MIN);
1114
        let (again, texts) = c.encode_parts();
1115
        assert!(texts.is_empty());
1116
        assert_eq!(again, bytes);
1117
        let d = Change::decode(&bytes).unwrap();
1118
        assert_eq!(d.version, 1);
1119
        assert_eq!(d.encode(), bytes);
1120
        // The same inline insert in a version 2 change is not canonical.
1121
        let mut v = c.to_value();
1122
        if let Value::Map(m) = &mut v {
1123
            m.insert(0, Value::Uint(2));
1124
        }
1125
        assert!(
1126
            matches!(Change::from_value(&v), Err(ObjectError::Schema(s)) if s.contains("text blob"))
1127
        );
1128
    }
1129
1130
    #[test]
1131
    fn text_blobs_are_checked() {
1132
        let lines = big_lines(500);
1133
        let content = cbor::encode_byte_strings(&lines);
1134
        assert_eq!(content.len(), cbor::byte_strings_len(&lines));
1135
        assert_eq!(
1136
            content,
1137
            cbor::encode(&Value::Array(
1138
                lines.iter().map(|l| Value::Bytes(l.clone())).collect()
1139
            ))
1140
        );
1141
        assert_eq!(text_lines(&content, 500).unwrap(), lines);
1142
        assert!(text_lines(&content, 499).is_err());
1143
        let small = cbor::encode_byte_strings(&[b"x\n".to_vec()]);
1144
        assert!(text_lines(&small, 1).is_err(), "short enough to be inline");
1145
    }
1146
1147
    #[test]
1148
    fn names_are_validated() {
1149
        for bad in ["", ".", "..", "a/b", "a\0b"] {
1150
            assert!(validate_name(bad).is_err(), "{bad:?}");
1151
        }
1152
        assert!(validate_name("Foo.c").is_ok());
1153
        assert!(validate_name("...").is_ok());
1154
    }
1155
1156
    #[test]
1157
    fn mode_and_kind_tags() {
1158
        for m in [
1159
            Mode::TEXT,
1160
            Mode::OPAQUE,
1161
            Mode {
1162
                exec: true,
1163
                opaque: true,
1164
            },
1165
        ] {
1166
            assert_eq!(Mode::from_bits(m.bits()).unwrap(), m);
1167
        }
1168
        assert!(Mode::from_bits(4).is_err());
1169
        for k in [
1170
            NodeKind::File,
1171
            NodeKind::Dir,
1172
            NodeKind::Symlink,
1173
            NodeKind::Subrepo,
1174
        ] {
1175
            assert_eq!(NodeKind::from_tag(k.tag()).unwrap(), k);
1176
        }
1177
    }
1178
1179
    #[test]
1180
    fn self_references_resolve() {
1181
        let me = ObjectRef([8; 32]);
1182
        assert_eq!(
1183
            AtomRef::Atom {
1184
                change: ObjectRef::ZERO,
1185
                index: 3
1186
            }
1187
            .resolve(me),
1188
            AtomRef::Atom {
1189
                change: me,
1190
                index: 3
1191
            }
1192
        );
1193
        assert_eq!(AtomRef::Start.resolve(me), AtomRef::Start);
1194
        let other = ObjectRef([1; 32]);
1195
        assert_eq!(
1196
            OpRef {
1197
                change: other,
1198
                index: 1
1199
            }
1200
            .resolve(me)
1201
            .change,
1202
            other
1203
        );
1204
    }
1205
1206
    #[test]
1207
    fn state_object_round_trip() {
1208
        let st = StateObject::new(vec![
1209
            ObjectRef([2; 32]),
1210
            ObjectRef([1; 32]),
1211
            ObjectRef([2; 32]),
1212
        ]);
1213
        assert_eq!(st.heads, vec![ObjectRef([1; 32]), ObjectRef([2; 32])]);
1214
        assert_eq!(StateObject::decode(&st.encode()).unwrap(), st);
1215
        assert_eq!(StateObject::new(vec![]).heads, vec![]);
1216
        assert_ne!(StateObject::new(vec![]).hash(), st.hash());
1217
    }
1218
1219
    #[test]
1220
    fn blob_round_trip() {
1221
        let b = Blob {
1222
            length: 10,
1223
            chunks: vec![ObjectRef([1; 32]), ObjectRef([2; 32])],
1224
        };
1225
        assert_eq!(Blob::decode(&b.encode()).unwrap(), b);
1226
    }
1227
}