Skip to main content

tilo_resource/
delta.rs

1//! What changed in a document since a resource was last read.
2//!
3//! Re-reading a whole resource on every change is fine for a settings record
4//! and ruinous for a twenty-megabyte manuscript: one keystroke would cost a
5//! read of the whole document. A [`Delta`] names the parts of the document a
6//! set of changes touched, so a resource re-reads only those
7//! ([`Resource::refresh`](crate::Resource::refresh)). A [`Tracker`] produces
8//! deltas for one live document from the operations of the changes that
9//! arrived, at a cost proportional to the change rather than to the
10//! document.
11
12use std::collections::{BTreeSet, HashMap};
13
14use automerge::{ChangeHash, ObjId, Prop, ReadDoc};
15
16use crate::model::Doc;
17
18/// How the keys of one map object were touched.
19#[derive(Clone, Debug, Default, PartialEq, Eq)]
20pub struct Touched {
21    /// Keys whose slot was written: a value put, replaced or deleted.
22    written: BTreeSet<String>,
23    /// Keys holding an object something inside of which changed.
24    below: BTreeSet<String>,
25    /// The object changed as a whole: a list or text edit, or an unknown
26    /// change. Readers re-read it entirely.
27    all: bool,
28}
29
30impl Touched {
31    fn everything() -> Self {
32        Self {
33            all: true,
34            ..Self::default()
35        }
36    }
37
38    /// Nothing in the object changed.
39    pub fn is_empty(&self) -> bool {
40        !self.all && self.written.is_empty() && self.below.is_empty()
41    }
42
43    /// The object changed in a way that is not keyed: re-read it entirely.
44    pub fn is_all(&self) -> bool {
45        self.all
46    }
47
48    /// How `key` was touched.
49    pub fn key(&self, key: &str) -> Touch {
50        if self.all || self.written.contains(key) {
51            Touch::Written
52        } else if self.below.contains(key) {
53            Touch::Below
54        } else {
55            Touch::Untouched
56        }
57    }
58
59    /// Every key touched in any way, in key order. Empty when [`Self::is_all`].
60    pub fn keys(&self) -> impl Iterator<Item = &str> {
61        let mut keys: BTreeSet<&str> = self.written.iter().map(String::as_str).collect();
62        keys.extend(self.below.iter().map(String::as_str));
63        keys.into_iter()
64    }
65
66    /// Keys whose slot itself was written.
67    pub fn written(&self) -> impl Iterator<Item = &str> {
68        self.written.iter().map(String::as_str)
69    }
70
71    fn merge(&mut self, other: Self) {
72        self.written.extend(other.written);
73        self.below.extend(other.below);
74        self.all |= other.all;
75    }
76}
77
78/// How one key of a map was touched by a [`Delta`].
79#[derive(Clone, Copy, Debug, PartialEq, Eq)]
80pub enum Touch {
81    /// Unchanged: keep what was read.
82    Untouched,
83    /// The slot holds a new value (or none): read it again.
84    Written,
85    /// The slot still holds the same object, and something inside it changed:
86    /// refresh that object.
87    Below,
88}
89
90#[derive(Clone, Debug, Default)]
91enum Kind {
92    #[default]
93    Nothing,
94    Everything,
95    Indexed(HashMap<ObjId, Touched>),
96}
97
98/// The parts of a document some set of changes touched. See the module docs.
99#[derive(Clone, Debug, Default)]
100pub struct Delta {
101    kind: Kind,
102}
103
104impl Delta {
105    /// No change at all.
106    #[must_use]
107    pub fn nothing() -> Self {
108        Self::default()
109    }
110
111    /// An unknown change: every reader re-reads everything.
112    #[must_use]
113    pub fn everything() -> Self {
114        Self {
115            kind: Kind::Everything,
116        }
117    }
118
119    /// Add what `other` touched, so the deltas of several syncs read as one.
120    pub fn merge(&mut self, other: Self) {
121        self.kind = match (std::mem::take(&mut self.kind), other.kind) {
122            (Kind::Everything, _) | (_, Kind::Everything) => Kind::Everything,
123            (Kind::Nothing, other) | (other, Kind::Nothing) => other,
124            (Kind::Indexed(mut index), Kind::Indexed(more)) => {
125                for (obj, touched) in more {
126                    index.entry(obj).or_default().merge(touched);
127                }
128                Kind::Indexed(index)
129            }
130        };
131    }
132
133    /// Nothing changed.
134    pub fn is_empty(&self) -> bool {
135        matches!(self.kind, Kind::Nothing)
136    }
137
138    /// The change is unknown: readers must re-read everything.
139    pub fn is_everything(&self) -> bool {
140        matches!(self.kind, Kind::Everything)
141    }
142
143    /// How the object `obj` was touched.
144    pub fn under(&self, obj: &ObjId) -> Touched {
145        match &self.kind {
146            Kind::Nothing => Touched::default(),
147            Kind::Everything => Touched::everything(),
148            Kind::Indexed(index) => index.get(obj).cloned().unwrap_or_default(),
149        }
150    }
151
152    /// Whether anything at or below `obj` changed.
153    pub fn touches(&self, obj: &ObjId) -> bool {
154        match &self.kind {
155            Kind::Nothing => false,
156            Kind::Everything => true,
157            Kind::Indexed(index) => index.get(obj).is_some_and(|touched| !touched.is_empty()),
158        }
159    }
160
161    /// How `key` of the map `obj` was touched.
162    pub fn key(&self, obj: &ObjId, key: &str) -> Touch {
163        match &self.kind {
164            Kind::Nothing => Touch::Untouched,
165            Kind::Everything => Touch::Written,
166            Kind::Indexed(index) => index
167                .get(obj)
168                .map_or(Touch::Untouched, |touched| touched.key(key)),
169        }
170    }
171}
172
173/// Where an object sits: the path from the root to it, as `(parent, prop)`
174/// pairs, root first — what a state already knowing an object answers
175/// without asking the document (see [`Resource::locate`](crate::Resource::locate)).
176pub type ObjPath = Vec<(ObjId, Prop)>;
177
178/// Above this many new changes, or operations in them, a delta
179/// is [`Delta::everything`]: reading the change would cost about as much as
180/// reading the resource.
181const MAX_CHANGES: usize = 4_096;
182const MAX_OPS: u64 = 200_000;
183
184/// A delta read: the version of the document it was read in, the changes it
185/// was read from, sorted, and what they touched.
186type Read = (Vec<ChangeHash>, Vec<ChangeHash>, Delta);
187
188thread_local! {
189    /// The delta read last. A write is followed by every reader of its
190    /// document (the resource that made it, the next action starting from
191    /// what it kept), each asking what the same changes touched; their
192    /// operations are read once.
193    static LAST: std::cell::RefCell<Option<Read>> = const { std::cell::RefCell::new(None) };
194}
195
196impl Delta {
197    /// The delta `changes` make to `doc` (which already holds them), read from
198    /// their operations: each touched object, and the path to it. Paths come
199    /// from `locate` when it knows the object, from the changes themselves
200    /// for objects they create, and otherwise from the document.
201    pub fn from_changes(
202        doc: &Doc,
203        changes: &[automerge::Change],
204        locate: &dyn Fn(&ObjId) -> Option<ObjPath>,
205    ) -> Self {
206        let mut at = doc.committed_heads();
207        at.sort_unstable();
208        let mut read: Vec<ChangeHash> = changes.iter().map(automerge::Change::hash).collect();
209        read.sort_unstable();
210        let known = LAST.with_borrow(|last| {
211            last.as_ref()
212                .filter(|(heads, hashes, _)| *heads == at && *hashes == read)
213                .map(|(_, _, delta)| delta.clone())
214        });
215        if let Some(delta) = known {
216            return delta;
217        }
218        let delta = Self::read_from(doc, changes, locate);
219        LAST.with_borrow_mut(|last| *last = Some((at, read, delta.clone())));
220        delta
221    }
222
223    /// [`Self::from_changes`], read from where the changes' operations write
224    /// ([`automerge::Automerge::change_touches`]): no value is decoded.
225    fn read_from(
226        doc: &Doc,
227        changes: &[automerge::Change],
228        locate: &dyn Fn(&ObjId) -> Option<ObjPath>,
229    ) -> Self {
230        let committed = doc.committed_document();
231        let mut index: HashMap<ObjId, Touched> = HashMap::new();
232        let mut created: HashMap<ObjId, (ObjId, Option<String>)> = HashMap::new();
233        let mut located: std::collections::HashSet<ObjId> = std::collections::HashSet::new();
234        let mut touched = Vec::new();
235        for change in changes {
236            // A change naming an actor this document does not know is not one it holds.
237            let Some(writes) = committed.change_touches(change) else {
238                return Self::everything();
239            };
240            for (made, obj, key) in writes.made {
241                created.insert(made, (obj, key));
242            }
243            for (obj, key) in writes.writes {
244                let entry = match index.entry(obj) {
245                    std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut(),
246                    std::collections::hash_map::Entry::Vacant(entry) => {
247                        touched.push(entry.key().clone());
248                        entry.insert(Touched::default())
249                    }
250                };
251                match key {
252                    Some(key) => {
253                        entry.written.insert(key);
254                    }
255                    None => entry.all = true,
256                }
257            }
258        }
259        for obj in touched {
260            mark_path(doc, &obj, &created, locate, &mut located, &mut index);
261        }
262        Self {
263            kind: Kind::Indexed(index),
264        }
265    }
266}
267
268/// Mark everything above `obj` as touched below the prop leading to it.
269fn mark_path(
270    doc: &Doc,
271    obj: &ObjId,
272    created: &HashMap<ObjId, (ObjId, Option<String>)>,
273    locate: &dyn Fn(&ObjId) -> Option<ObjPath>,
274    located: &mut std::collections::HashSet<ObjId>,
275    index: &mut HashMap<ObjId, Touched>,
276) {
277    let mut current = obj.clone();
278    loop {
279        if current == automerge::ROOT || !located.insert(current.clone()) {
280            return;
281        }
282        // An object these changes made hangs off an object they touched.
283        if let Some((parent, key)) = created.get(&current) {
284            let entry = index.entry(parent.clone()).or_default();
285            match key {
286                Some(key) => {
287                    entry.below.insert(key.clone());
288                }
289                None => entry.all = true,
290            }
291            current = parent.clone();
292            continue;
293        }
294        let path: Option<ObjPath> = locate(&current).or_else(|| {
295            let parents: Vec<automerge::Parent> = doc.parents(&current).ok()?.collect();
296            // An object no longer reachable changes nothing anyone reads.
297            if parents.iter().any(|parent| !parent.visible) {
298                return None;
299            }
300            Some(
301                parents
302                    .into_iter()
303                    .rev()
304                    .map(|parent| (parent.obj, parent.prop))
305                    .collect(),
306            )
307        });
308        for (parent, prop) in path.unwrap_or_default() {
309            let entry = index.entry(parent.clone()).or_default();
310            match prop {
311                Prop::Map(key) => {
312                    entry.below.insert(key);
313                }
314                Prop::Seq(_) => entry.all = true,
315            }
316            located.insert(parent);
317        }
318        return;
319    }
320}
321
322/// Produces the [`Delta`] of one live document between successive reads,
323/// from the operations of the changes that arrived in between: its cost
324/// follows the change, however large the document.
325#[derive(Debug, Default)]
326pub struct Tracker {
327    heads: Option<Vec<ChangeHash>>,
328}
329
330impl Tracker {
331    #[must_use]
332    pub fn new() -> Self {
333        Self::default()
334    }
335
336    /// Start tracking from the document as it stands, for a state that was
337    /// just read from it.
338    pub fn start(&mut self, doc: &mut Doc) {
339        self.heads = Some(doc.get_heads());
340    }
341
342    /// Track a document from `heads`, the version a state was read at.
343    #[must_use]
344    pub fn at(heads: Vec<ChangeHash>) -> Self {
345        Self { heads: Some(heads) }
346    }
347
348    /// The heads the last delta ended at.
349    pub fn heads(&self) -> Option<&[ChangeHash]> {
350        self.heads.as_deref()
351    }
352
353    /// Whether `doc` holds every change this tracker last saw: what moved
354    /// since is a delta of it, not another document.
355    pub fn leads_to(&self, doc: &Doc) -> bool {
356        let committed = doc.committed_document();
357        self.heads.as_ref().is_some_and(|heads| {
358            heads
359                .iter()
360                .all(|hash| committed.get_change_meta_by_hash(hash).is_some())
361        })
362    }
363
364    /// What changed since the previous call (or [`Self::start`]). The first
365    /// call of a tracker that was not started is [`Delta::everything`].
366    pub fn delta(&mut self, doc: &mut Doc) -> Delta {
367        self.delta_located(doc, &|_| None)
368    }
369
370    /// [`Self::delta`], with `locate` answering where objects the state
371    /// already knows sit, so the document is not asked.
372    pub fn delta_located(
373        &mut self,
374        doc: &mut Doc,
375        locate: &dyn Fn(&ObjId) -> Option<ObjPath>,
376    ) -> Delta {
377        // Closes the open transaction, so its edits are part of the delta.
378        doc.get_heads();
379        self.committed_delta_located(doc, locate)
380    }
381
382    /// [`Self::delta_located`] up to the committed document, read through a
383    /// shared reference: edits of a transaction still open come with the
384    /// delta after it closes.
385    pub fn committed_delta_located(
386        &mut self,
387        doc: &Doc,
388        locate: &dyn Fn(&ObjId) -> Option<ObjPath>,
389    ) -> Delta {
390        let heads = doc.committed_heads();
391        // Unmoved, the usual answer for a document followed every frame: told
392        // before its history is looked into.
393        if self.heads.as_ref() == Some(&heads) {
394            return Delta::nothing();
395        }
396        let committed = doc.committed_document();
397        // A version this document does not have: it was replaced wholesale.
398        let moved_on = self.leads_to(doc);
399        let Some(previous) = self.heads.replace(heads.clone()) else {
400            return Delta::everything();
401        };
402        if previous == heads {
403            return Delta::nothing();
404        }
405        if !moved_on {
406            return Delta::everything();
407        }
408        let metas = committed.get_changes_meta(&previous);
409        // A write on this thread that stored its items whole, alone since:
410        // the reader takes those items rather than reads them, so their size
411        // is no reason to read every other item again.
412        let ops: u64 = match metas.as_slice() {
413            [meta] if crate::apply_cache::stored_by(meta).is_some() => 0,
414            metas => metas
415                .iter()
416                .map(|meta| meta.max_op.saturating_add(1).saturating_sub(meta.start_op))
417                .sum(),
418        };
419        if metas.len() > MAX_CHANGES || ops > MAX_OPS {
420            return Delta::everything();
421        }
422        let mut changes = Vec::with_capacity(metas.len());
423        for meta in &metas {
424            match committed.get_change_by_hash(&meta.hash) {
425                Some(change) => changes.push(change),
426                None => return Delta::everything(),
427            }
428        }
429        Delta::from_changes(doc, &changes, locate)
430    }
431}
432
433#[cfg(test)]
434mod tests {
435    use super::*;
436    use automerge::transaction::Transactable;
437    use automerge::{ObjType, ROOT};
438
439    tilo_test_env::scenario! {
440        fn a_delta_names_what_changes_touched;
441
442        phase a_splice_touches_the_path_to_its_text_and_nothing_else;
443        {
444            let mut doc = Doc::new();
445            let blocks = doc.put_object(ROOT, "blocks", ObjType::Map).unwrap();
446            let mut texts = Vec::new();
447            for id in ["a", "b", "c"] {
448                let block = doc.put_object(&blocks, id, ObjType::Map).unwrap();
449                texts.push(doc.put_object(&block, "text", ObjType::Text).unwrap());
450            }
451            doc.commit();
452            let mut tracker = Tracker::new();
453            tracker.start(&mut doc);
454
455            doc.splice_text(&texts[1], 0, 0, "hello").unwrap();
456            let delta = tracker.delta(&mut doc);
457            assert_eq!(delta.key(&ROOT, "blocks"), Touch::Below);
458            let under = delta.under(&blocks);
459            assert_eq!(under.keys().collect::<Vec<_>>(), ["b"]);
460            assert_eq!(under.key("b"), Touch::Below);
461            assert_eq!(under.key("a"), Touch::Untouched);
462            assert!(delta.under(&texts[1]).is_all());
463            assert!(!delta.touches(&texts[0]));
464
465            assert!(tracker.delta(&mut doc).is_empty());
466
467            doc.delete(&blocks, "c").unwrap();
468            let delta = tracker.delta(&mut doc);
469            assert_eq!(delta.under(&blocks).key("c"), Touch::Written);
470            assert_eq!(doc.text(&texts[1]).unwrap(), "hello");
471        }
472
473        phase a_replaced_document_reads_as_everything_and_new_objects_locate_themselves;
474        {
475            let mut doc = Doc::new();
476            doc.put(ROOT, "x", 1).unwrap();
477            doc.commit();
478            let mut tracker = Tracker::new();
479            tracker.start(&mut doc);
480            let blocks = doc.put_object(ROOT, "blocks", ObjType::Map).unwrap();
481            let block = doc.put_object(&blocks, "new", ObjType::Map).unwrap();
482            let text = doc.put_object(&block, "text", ObjType::Text).unwrap();
483            doc.splice_text(&text, 0, 0, "fresh").unwrap();
484            doc.commit();
485            let delta = tracker.delta_located(&mut doc, &|_| panic!("created objects need no lookup"));
486            assert_eq!(delta.key(&ROOT, "blocks"), Touch::Written);
487            assert_eq!(delta.under(&blocks).key("new"), Touch::Written);
488            assert!(delta.under(&text).is_all());
489
490            let mut other = Doc::new();
491            other.put(ROOT, "x", 9).unwrap();
492            other.commit();
493            let delta = tracker.delta(&mut other);
494            assert!(delta.is_everything());
495        }
496
497        phase an_edit_located_by_the_state_asks_the_document_nothing;
498        {
499            let mut doc = Doc::new();
500            let blocks = doc.put_object(ROOT, "blocks", ObjType::Map).unwrap();
501            let block = doc.put_object(&blocks, "b", ObjType::Map).unwrap();
502            let text = doc.put_object(&block, "text", ObjType::Text).unwrap();
503            doc.commit();
504            let mut tracker = Tracker::new();
505            tracker.start(&mut doc);
506            doc.splice_text(&text, 0, 0, "k").unwrap();
507            doc.commit();
508            let path = vec![
509                (ROOT, Prop::Map("blocks".into())),
510                (blocks.clone(), Prop::Map("b".into())),
511                (block.clone(), Prop::Map("text".into())),
512            ];
513            let asked = std::cell::Cell::new(0);
514            let delta = tracker.delta_located(&mut doc, &|obj| {
515                asked.set(asked.get() + 1);
516                (*obj == text).then(|| path.clone())
517            });
518            assert_eq!(asked.get(), 1);
519            assert_eq!(delta.under(&blocks).key("b"), Touch::Below);
520            assert_eq!(delta.under(&block).key("text"), Touch::Below);
521        }
522
523        phase merged_deltas_read_as_one;
524        {
525            let mut doc = Doc::new();
526            doc.put(ROOT, "a", 1).unwrap();
527            doc.put(ROOT, "b", 1).unwrap();
528            doc.commit();
529            let mut tracker = Tracker::new();
530            tracker.start(&mut doc);
531            doc.put(ROOT, "a", 2).unwrap();
532            doc.commit();
533            let mut merged = tracker.delta(&mut doc);
534            doc.put(ROOT, "b", 2).unwrap();
535            doc.commit();
536            merged.merge(tracker.delta(&mut doc));
537            assert_eq!(merged.key(&ROOT, "a"), Touch::Written);
538            assert_eq!(merged.key(&ROOT, "b"), Touch::Written);
539            let mut nothing = Delta::nothing();
540            nothing.merge(merged.clone());
541            assert_eq!(nothing.key(&ROOT, "b"), Touch::Written);
542            merged.merge(Delta::everything());
543            assert!(merged.is_everything());
544        }
545    }
546}