tilo-resource 0.5.0

The Tilo resource layer: typed, hierarchical app resources.
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
//! What changed in a document since a resource was last read.
//!
//! Re-reading a whole resource on every change is fine for a settings record
//! and ruinous for a twenty-megabyte manuscript: one keystroke would cost a
//! read of the whole document. A [`Delta`] names the parts of the document a
//! set of changes touched, so a resource re-reads only those
//! ([`Resource::refresh`](crate::Resource::refresh)). A [`Tracker`] produces
//! deltas for one live document from the operations of the changes that
//! arrived, at a cost proportional to the change rather than to the
//! document.

use std::collections::{BTreeSet, HashMap};

use automerge::{ChangeHash, ObjId, Prop, ReadDoc};

use crate::model::Doc;

/// How the keys of one map object were touched.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Touched {
    /// Keys whose slot was written: a value put, replaced or deleted.
    written: BTreeSet<String>,
    /// Keys holding an object something inside of which changed.
    below: BTreeSet<String>,
    /// The object changed as a whole: a list or text edit, or an unknown
    /// change. Readers re-read it entirely.
    all: bool,
}

impl Touched {
    fn everything() -> Self {
        Self {
            all: true,
            ..Self::default()
        }
    }

    /// Nothing in the object changed.
    pub fn is_empty(&self) -> bool {
        !self.all && self.written.is_empty() && self.below.is_empty()
    }

    /// The object changed in a way that is not keyed: re-read it entirely.
    pub fn is_all(&self) -> bool {
        self.all
    }

    /// How `key` was touched.
    pub fn key(&self, key: &str) -> Touch {
        if self.all || self.written.contains(key) {
            Touch::Written
        } else if self.below.contains(key) {
            Touch::Below
        } else {
            Touch::Untouched
        }
    }

    /// Every key touched in any way, in key order. Empty when [`Self::is_all`].
    pub fn keys(&self) -> impl Iterator<Item = &str> {
        let mut keys: BTreeSet<&str> = self.written.iter().map(String::as_str).collect();
        keys.extend(self.below.iter().map(String::as_str));
        keys.into_iter()
    }

    /// Keys whose slot itself was written.
    pub fn written(&self) -> impl Iterator<Item = &str> {
        self.written.iter().map(String::as_str)
    }

    fn merge(&mut self, other: Self) {
        self.written.extend(other.written);
        self.below.extend(other.below);
        self.all |= other.all;
    }
}

/// How one key of a map was touched by a [`Delta`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Touch {
    /// Unchanged: keep what was read.
    Untouched,
    /// The slot holds a new value (or none): read it again.
    Written,
    /// The slot still holds the same object, and something inside it changed:
    /// refresh that object.
    Below,
}

#[derive(Clone, Debug, Default)]
enum Kind {
    #[default]
    Nothing,
    Everything,
    Indexed(HashMap<ObjId, Touched>),
}

/// The parts of a document some set of changes touched. See the module docs.
#[derive(Clone, Debug, Default)]
pub struct Delta {
    kind: Kind,
}

impl Delta {
    /// No change at all.
    #[must_use]
    pub fn nothing() -> Self {
        Self::default()
    }

    /// An unknown change: every reader re-reads everything.
    #[must_use]
    pub fn everything() -> Self {
        Self {
            kind: Kind::Everything,
        }
    }

    /// Add what `other` touched, so the deltas of several syncs read as one.
    pub fn merge(&mut self, other: Self) {
        self.kind = match (std::mem::take(&mut self.kind), other.kind) {
            (Kind::Everything, _) | (_, Kind::Everything) => Kind::Everything,
            (Kind::Nothing, other) | (other, Kind::Nothing) => other,
            (Kind::Indexed(mut index), Kind::Indexed(more)) => {
                for (obj, touched) in more {
                    index.entry(obj).or_default().merge(touched);
                }
                Kind::Indexed(index)
            }
        };
    }

    /// Nothing changed.
    pub fn is_empty(&self) -> bool {
        matches!(self.kind, Kind::Nothing)
    }

    /// The change is unknown: readers must re-read everything.
    pub fn is_everything(&self) -> bool {
        matches!(self.kind, Kind::Everything)
    }

    /// How the object `obj` was touched.
    pub fn under(&self, obj: &ObjId) -> Touched {
        match &self.kind {
            Kind::Nothing => Touched::default(),
            Kind::Everything => Touched::everything(),
            Kind::Indexed(index) => index.get(obj).cloned().unwrap_or_default(),
        }
    }

    /// Whether anything at or below `obj` changed.
    pub fn touches(&self, obj: &ObjId) -> bool {
        match &self.kind {
            Kind::Nothing => false,
            Kind::Everything => true,
            Kind::Indexed(index) => index.get(obj).is_some_and(|touched| !touched.is_empty()),
        }
    }

    /// How `key` of the map `obj` was touched.
    pub fn key(&self, obj: &ObjId, key: &str) -> Touch {
        match &self.kind {
            Kind::Nothing => Touch::Untouched,
            Kind::Everything => Touch::Written,
            Kind::Indexed(index) => index
                .get(obj)
                .map_or(Touch::Untouched, |touched| touched.key(key)),
        }
    }
}

/// Where an object sits: the path from the root to it, as `(parent, prop)`
/// pairs, root first — what a state already knowing an object answers
/// without asking the document (see [`Resource::locate`](crate::Resource::locate)).
pub type ObjPath = Vec<(ObjId, Prop)>;

/// Above this many new changes, or operations in them, a delta
/// is [`Delta::everything`]: reading the change would cost about as much as
/// reading the resource.
const MAX_CHANGES: usize = 4_096;
const MAX_OPS: u64 = 200_000;

/// A delta read: the version of the document it was read in, the changes it
/// was read from, sorted, and what they touched.
type Read = (Vec<ChangeHash>, Vec<ChangeHash>, Delta);

thread_local! {
    /// The delta read last. A write is followed by every reader of its
    /// document (the resource that made it, the next action starting from
    /// what it kept), each asking what the same changes touched; their
    /// operations are read once.
    static LAST: std::cell::RefCell<Option<Read>> = const { std::cell::RefCell::new(None) };
}

impl Delta {
    /// The delta `changes` make to `doc` (which already holds them), read from
    /// their operations: each touched object, and the path to it. Paths come
    /// from `locate` when it knows the object, from the changes themselves
    /// for objects they create, and otherwise from the document.
    pub fn from_changes(
        doc: &Doc,
        changes: &[automerge::Change],
        locate: &dyn Fn(&ObjId) -> Option<ObjPath>,
    ) -> Self {
        let mut at = doc.committed_heads();
        at.sort_unstable();
        let mut read: Vec<ChangeHash> = changes.iter().map(automerge::Change::hash).collect();
        read.sort_unstable();
        let known = LAST.with_borrow(|last| {
            last.as_ref()
                .filter(|(heads, hashes, _)| *heads == at && *hashes == read)
                .map(|(_, _, delta)| delta.clone())
        });
        if let Some(delta) = known {
            return delta;
        }
        let delta = Self::read_from(doc, changes, locate);
        LAST.with_borrow_mut(|last| *last = Some((at, read, delta.clone())));
        delta
    }

    /// [`Self::from_changes`], read from where the changes' operations write
    /// ([`automerge::Automerge::change_touches`]): no value is decoded.
    fn read_from(
        doc: &Doc,
        changes: &[automerge::Change],
        locate: &dyn Fn(&ObjId) -> Option<ObjPath>,
    ) -> Self {
        let committed = doc.committed_document();
        let mut index: HashMap<ObjId, Touched> = HashMap::new();
        let mut created: HashMap<ObjId, (ObjId, Option<String>)> = HashMap::new();
        let mut located: std::collections::HashSet<ObjId> = std::collections::HashSet::new();
        let mut touched = Vec::new();
        for change in changes {
            // A change naming an actor this document does not know is not one it holds.
            let Some(writes) = committed.change_touches(change) else {
                return Self::everything();
            };
            for (made, obj, key) in writes.made {
                created.insert(made, (obj, key));
            }
            for (obj, key) in writes.writes {
                let entry = match index.entry(obj) {
                    std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut(),
                    std::collections::hash_map::Entry::Vacant(entry) => {
                        touched.push(entry.key().clone());
                        entry.insert(Touched::default())
                    }
                };
                match key {
                    Some(key) => {
                        entry.written.insert(key);
                    }
                    None => entry.all = true,
                }
            }
        }
        for obj in touched {
            mark_path(doc, &obj, &created, locate, &mut located, &mut index);
        }
        Self {
            kind: Kind::Indexed(index),
        }
    }
}

/// Mark everything above `obj` as touched below the prop leading to it.
fn mark_path(
    doc: &Doc,
    obj: &ObjId,
    created: &HashMap<ObjId, (ObjId, Option<String>)>,
    locate: &dyn Fn(&ObjId) -> Option<ObjPath>,
    located: &mut std::collections::HashSet<ObjId>,
    index: &mut HashMap<ObjId, Touched>,
) {
    let mut current = obj.clone();
    loop {
        if current == automerge::ROOT || !located.insert(current.clone()) {
            return;
        }
        // An object these changes made hangs off an object they touched.
        if let Some((parent, key)) = created.get(&current) {
            let entry = index.entry(parent.clone()).or_default();
            match key {
                Some(key) => {
                    entry.below.insert(key.clone());
                }
                None => entry.all = true,
            }
            current = parent.clone();
            continue;
        }
        let path: Option<ObjPath> = locate(&current).or_else(|| {
            let parents: Vec<automerge::Parent> = doc.parents(&current).ok()?.collect();
            // An object no longer reachable changes nothing anyone reads.
            if parents.iter().any(|parent| !parent.visible) {
                return None;
            }
            Some(
                parents
                    .into_iter()
                    .rev()
                    .map(|parent| (parent.obj, parent.prop))
                    .collect(),
            )
        });
        for (parent, prop) in path.unwrap_or_default() {
            let entry = index.entry(parent.clone()).or_default();
            match prop {
                Prop::Map(key) => {
                    entry.below.insert(key);
                }
                Prop::Seq(_) => entry.all = true,
            }
            located.insert(parent);
        }
        return;
    }
}

/// Produces the [`Delta`] of one live document between successive reads,
/// from the operations of the changes that arrived in between: its cost
/// follows the change, however large the document.
#[derive(Debug, Default)]
pub struct Tracker {
    heads: Option<Vec<ChangeHash>>,
}

impl Tracker {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Start tracking from the document as it stands, for a state that was
    /// just read from it.
    pub fn start(&mut self, doc: &mut Doc) {
        self.heads = Some(doc.get_heads());
    }

    /// Track a document from `heads`, the version a state was read at.
    #[must_use]
    pub fn at(heads: Vec<ChangeHash>) -> Self {
        Self { heads: Some(heads) }
    }

    /// The heads the last delta ended at.
    pub fn heads(&self) -> Option<&[ChangeHash]> {
        self.heads.as_deref()
    }

    /// Whether `doc` holds every change this tracker last saw: what moved
    /// since is a delta of it, not another document.
    pub fn leads_to(&self, doc: &Doc) -> bool {
        let committed = doc.committed_document();
        self.heads.as_ref().is_some_and(|heads| {
            heads
                .iter()
                .all(|hash| committed.get_change_meta_by_hash(hash).is_some())
        })
    }

    /// What changed since the previous call (or [`Self::start`]). The first
    /// call of a tracker that was not started is [`Delta::everything`].
    pub fn delta(&mut self, doc: &mut Doc) -> Delta {
        self.delta_located(doc, &|_| None)
    }

    /// [`Self::delta`], with `locate` answering where objects the state
    /// already knows sit, so the document is not asked.
    pub fn delta_located(
        &mut self,
        doc: &mut Doc,
        locate: &dyn Fn(&ObjId) -> Option<ObjPath>,
    ) -> Delta {
        // Closes the open transaction, so its edits are part of the delta.
        doc.get_heads();
        self.committed_delta_located(doc, locate)
    }

    /// [`Self::delta_located`] up to the committed document, read through a
    /// shared reference: edits of a transaction still open come with the
    /// delta after it closes.
    pub fn committed_delta_located(
        &mut self,
        doc: &Doc,
        locate: &dyn Fn(&ObjId) -> Option<ObjPath>,
    ) -> Delta {
        let heads = doc.committed_heads();
        // Unmoved, the usual answer for a document followed every frame: told
        // before its history is looked into.
        if self.heads.as_ref() == Some(&heads) {
            return Delta::nothing();
        }
        let committed = doc.committed_document();
        // A version this document does not have: it was replaced wholesale.
        let moved_on = self.leads_to(doc);
        let Some(previous) = self.heads.replace(heads.clone()) else {
            return Delta::everything();
        };
        if previous == heads {
            return Delta::nothing();
        }
        if !moved_on {
            return Delta::everything();
        }
        let metas = committed.get_changes_meta(&previous);
        // A write on this thread that stored its items whole, alone since:
        // the reader takes those items rather than reads them, so their size
        // is no reason to read every other item again.
        let ops: u64 = match metas.as_slice() {
            [meta] if crate::apply_cache::stored_by(meta).is_some() => 0,
            metas => metas
                .iter()
                .map(|meta| meta.max_op.saturating_add(1).saturating_sub(meta.start_op))
                .sum(),
        };
        if metas.len() > MAX_CHANGES || ops > MAX_OPS {
            return Delta::everything();
        }
        let mut changes = Vec::with_capacity(metas.len());
        for meta in &metas {
            match committed.get_change_by_hash(&meta.hash) {
                Some(change) => changes.push(change),
                None => return Delta::everything(),
            }
        }
        Delta::from_changes(doc, &changes, locate)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use automerge::transaction::Transactable;
    use automerge::{ObjType, ROOT};

    tilo_test_env::scenario! {
        fn a_delta_names_what_changes_touched;

        phase a_splice_touches_the_path_to_its_text_and_nothing_else;
        {
            let mut doc = Doc::new();
            let blocks = doc.put_object(ROOT, "blocks", ObjType::Map).unwrap();
            let mut texts = Vec::new();
            for id in ["a", "b", "c"] {
                let block = doc.put_object(&blocks, id, ObjType::Map).unwrap();
                texts.push(doc.put_object(&block, "text", ObjType::Text).unwrap());
            }
            doc.commit();
            let mut tracker = Tracker::new();
            tracker.start(&mut doc);

            doc.splice_text(&texts[1], 0, 0, "hello").unwrap();
            let delta = tracker.delta(&mut doc);
            assert_eq!(delta.key(&ROOT, "blocks"), Touch::Below);
            let under = delta.under(&blocks);
            assert_eq!(under.keys().collect::<Vec<_>>(), ["b"]);
            assert_eq!(under.key("b"), Touch::Below);
            assert_eq!(under.key("a"), Touch::Untouched);
            assert!(delta.under(&texts[1]).is_all());
            assert!(!delta.touches(&texts[0]));

            assert!(tracker.delta(&mut doc).is_empty());

            doc.delete(&blocks, "c").unwrap();
            let delta = tracker.delta(&mut doc);
            assert_eq!(delta.under(&blocks).key("c"), Touch::Written);
            assert_eq!(doc.text(&texts[1]).unwrap(), "hello");
        }

        phase a_replaced_document_reads_as_everything_and_new_objects_locate_themselves;
        {
            let mut doc = Doc::new();
            doc.put(ROOT, "x", 1).unwrap();
            doc.commit();
            let mut tracker = Tracker::new();
            tracker.start(&mut doc);
            let blocks = doc.put_object(ROOT, "blocks", ObjType::Map).unwrap();
            let block = doc.put_object(&blocks, "new", ObjType::Map).unwrap();
            let text = doc.put_object(&block, "text", ObjType::Text).unwrap();
            doc.splice_text(&text, 0, 0, "fresh").unwrap();
            doc.commit();
            let delta = tracker.delta_located(&mut doc, &|_| panic!("created objects need no lookup"));
            assert_eq!(delta.key(&ROOT, "blocks"), Touch::Written);
            assert_eq!(delta.under(&blocks).key("new"), Touch::Written);
            assert!(delta.under(&text).is_all());

            let mut other = Doc::new();
            other.put(ROOT, "x", 9).unwrap();
            other.commit();
            let delta = tracker.delta(&mut other);
            assert!(delta.is_everything());
        }

        phase an_edit_located_by_the_state_asks_the_document_nothing;
        {
            let mut doc = Doc::new();
            let blocks = doc.put_object(ROOT, "blocks", ObjType::Map).unwrap();
            let block = doc.put_object(&blocks, "b", ObjType::Map).unwrap();
            let text = doc.put_object(&block, "text", ObjType::Text).unwrap();
            doc.commit();
            let mut tracker = Tracker::new();
            tracker.start(&mut doc);
            doc.splice_text(&text, 0, 0, "k").unwrap();
            doc.commit();
            let path = vec![
                (ROOT, Prop::Map("blocks".into())),
                (blocks.clone(), Prop::Map("b".into())),
                (block.clone(), Prop::Map("text".into())),
            ];
            let asked = std::cell::Cell::new(0);
            let delta = tracker.delta_located(&mut doc, &|obj| {
                asked.set(asked.get() + 1);
                (*obj == text).then(|| path.clone())
            });
            assert_eq!(asked.get(), 1);
            assert_eq!(delta.under(&blocks).key("b"), Touch::Below);
            assert_eq!(delta.under(&block).key("text"), Touch::Below);
        }

        phase merged_deltas_read_as_one;
        {
            let mut doc = Doc::new();
            doc.put(ROOT, "a", 1).unwrap();
            doc.put(ROOT, "b", 1).unwrap();
            doc.commit();
            let mut tracker = Tracker::new();
            tracker.start(&mut doc);
            doc.put(ROOT, "a", 2).unwrap();
            doc.commit();
            let mut merged = tracker.delta(&mut doc);
            doc.put(ROOT, "b", 2).unwrap();
            doc.commit();
            merged.merge(tracker.delta(&mut doc));
            assert_eq!(merged.key(&ROOT, "a"), Touch::Written);
            assert_eq!(merged.key(&ROOT, "b"), Touch::Written);
            let mut nothing = Delta::nothing();
            nothing.merge(merged.clone());
            assert_eq!(nothing.key(&ROOT, "b"), Touch::Written);
            merged.merge(Delta::everything());
            assert!(merged.is_everything());
        }
    }
}