Skip to main content

tilo_resource/
reader.rs

1//! Keeping a resource's state current as its document changes, reading only
2//! what changed and what views look at.
3
4use std::any::Any;
5use std::collections::BTreeSet;
6use std::ops::Range;
7use std::rc::Rc;
8use tilo_sort::CompactSort as _;
9
10use automerge::ChangeHash;
11use automerge::transaction::Transactable;
12
13use crate::delta::{Delta, Tracker};
14use crate::model::{Doc, ModelError};
15use crate::resource::Resource;
16
17/// The parts of a large resource that views are looking at, in terms any
18/// resource can interpret: positions in its primary order (the paragraphs of
19/// a document, the rows of a sheet) and keyed parts (a comment thread, a
20/// clip). See [`Resource::load`].
21#[derive(Clone, Debug, Default, PartialEq, Eq)]
22pub struct Demand {
23    /// Positions in the resource's primary order.
24    pub ranges: Vec<Range<usize>>,
25    /// Keyed parts.
26    pub keys: BTreeSet<String>,
27}
28
29impl Demand {
30    /// Nothing beyond what [`Resource::read`] reads.
31    #[must_use]
32    pub fn none() -> Self {
33        Self::default()
34    }
35
36    /// One range of positions.
37    #[must_use]
38    pub fn range(range: Range<usize>) -> Self {
39        Self {
40            ranges: vec![range],
41            keys: BTreeSet::new(),
42        }
43    }
44
45    /// Also demand keyed parts.
46    #[must_use]
47    pub fn with_keys<K: Into<String>>(mut self, keys: impl IntoIterator<Item = K>) -> Self {
48        self.keys.extend(keys.into_iter().map(Into::into));
49        self
50    }
51
52    pub fn covers(&self, index: usize) -> bool {
53        self.ranges.iter().any(|range| range.contains(&index))
54    }
55
56    /// Every demanded position, ascending and without repeats, clamped to
57    /// `len` positions.
58    pub fn positions(&self, len: usize) -> impl Iterator<Item = usize> {
59        let mut positions: Vec<usize> = self
60            .ranges
61            .iter()
62            .flat_map(|range| range.start.min(len)..range.end.min(len))
63            .collect();
64        positions.compact_sort();
65        positions.dedup();
66        positions.into_iter()
67    }
68}
69
70/// The version `doc` holds, when it has no uncommitted edits.
71#[must_use]
72pub fn heads_of(doc: &Doc) -> Option<Vec<ChangeHash>> {
73    (doc.pending_ops() == 0).then(|| doc.base_heads())
74}
75
76/// The current state of one resource over one live document, kept up to date
77/// incrementally: each [`sync`](Self::sync) applies only what changed since
78/// the last one ([`Resource::refresh`]), and [`demand`](Self::demand) reads
79/// the parts views look at ([`Resource::load`]).
80///
81/// The framework keeps one per open resource; a custom surface running
82/// outside the framework (a standalone test harness) can keep its own.
83pub struct Reader<R: Resource> {
84    /// Everything but the state: the same for every resource.
85    core: Following,
86    state: Rc<R::State>,
87}
88
89/// What a reader keeps besides the state itself.
90struct Following {
91    tracker: Tracker,
92    demand: Demand,
93    revision: u64,
94    /// How many times a demand read more of the document: what the state
95    /// holds of it, not what it says.
96    loads: u64,
97    /// The last refresh failed part-way; the next sync reads everything.
98    stale: bool,
99    /// The open transaction last read: its base heads and length.
100    uncommitted: Option<(Vec<ChangeHash>, usize)>,
101    /// What the last sync that changed the state applied.
102    last: Delta,
103    /// Why the document last failed to read, until it reads again.
104    unreadable: Option<crate::Unreadable>,
105    /// The committed heads the state was last read whole at: a whole read
106    /// again at the same heads would read the same state, and is not done.
107    read_at: Option<Vec<ChangeHash>>,
108    /// Whether it reads every field, the `#[model(demanded)]` ones too:
109    /// a reader for something other than a view ([`Reader::read_all`]).
110    every_field: bool,
111}
112
113impl Following {
114    /// Following a document from `heads` (`None` when unknown: the first
115    /// sync reads everything again). Out of line, so every app's reader
116    /// calls the one copy in the runtime.
117    #[inline(never)]
118    fn at(heads: Option<Vec<ChangeHash>>) -> Self {
119        let read_at = heads.clone();
120        Self {
121            read_at,
122            ..Self::new(heads.map(Tracker::at).unwrap_or_default())
123        }
124    }
125
126    /// Following `doc` from where it stands, out of line as [`Self::at`].
127    #[inline(never)]
128    fn started(doc: &mut Doc) -> Self {
129        let mut tracker = Tracker::new();
130        tracker.start(doc);
131        Self {
132            read_at: heads_of(doc),
133            ..Self::new(tracker)
134        }
135    }
136
137    fn new(tracker: Tracker) -> Self {
138        Self {
139            tracker,
140            demand: Demand::none(),
141            revision: 0,
142            loads: 0,
143            stale: false,
144            uncommitted: None,
145            last: Delta::everything(),
146            unreadable: None,
147            read_at: None,
148            every_field: false,
149        }
150    }
151
152    /// Read the state whole as this reader reads: for a view, leaving the
153    /// `#[model(demanded)]` fields of what no view demanded unread.
154    fn read(&self, ops: &StateOps, doc: &Doc) -> Result<Box<dyn Any>, ModelError> {
155        if self.every_field {
156            (ops.read)(doc)
157        } else {
158            crate::table::for_view(|| (ops.read)(doc))
159        }
160    }
161}
162
163/// A resource's [`Resource`] functions a reader calls, the state erased.
164struct StateOps {
165    read: fn(&Doc) -> Result<Box<dyn Any>, ModelError>,
166    refresh: fn(&mut dyn Any, &Doc, &Delta) -> Result<(), ModelError>,
167    load: fn(&mut dyn Any, &Doc, &Demand) -> Result<(), ModelError>,
168    locate: fn(&dyn Any, &automerge::ObjId) -> Option<crate::delta::ObjPath>,
169    /// [`Resource::VERSION`].
170    version: u32,
171}
172
173struct OpsOf<R>(std::marker::PhantomData<R>);
174
175impl<R: Resource> OpsOf<R> {
176    const OPS: StateOps = StateOps {
177        read: |doc| R::read(doc).map(|state| Box::new(state) as Box<dyn Any>),
178        refresh: |state, doc, delta| match state.downcast_mut::<R::State>() {
179            Some(state) => R::refresh(state, doc, delta),
180            None => Err(ModelError::invalid("a state of another resource")),
181        },
182        load: |state, doc, demand| match state.downcast_mut::<R::State>() {
183            Some(state) => R::load(state, doc, demand),
184            None => Err(ModelError::invalid("a state of another resource")),
185        },
186        locate: |state, obj| R::locate(state.downcast_ref::<R::State>()?, obj),
187        version: R::VERSION,
188    };
189}
190
191/// A reader's state as its resource-independent part reaches it.
192trait StateSlot {
193    fn get(&self) -> &dyn Any;
194    /// The state to change in place, when nobody else holds it.
195    fn get_mut(&mut self) -> Option<&mut dyn Any>;
196    /// A copy of the state to bring up to date ([`Resource::copy_state`]).
197    fn copy(&self) -> Option<Box<dyn Any>>;
198    /// Replace the state with `state`, one of the resource's.
199    fn set(&mut self, state: Box<dyn Any>);
200}
201
202/// A reader's typed state, as a [`StateSlot`].
203struct Held<'a, R: Resource>(&'a mut Rc<R::State>);
204
205impl<R: Resource> StateSlot for Held<'_, R> {
206    fn get(&self) -> &dyn Any {
207        &**self.0
208    }
209
210    fn get_mut(&mut self) -> Option<&mut dyn Any> {
211        Rc::get_mut(self.0).map(|state| state as &mut dyn Any)
212    }
213
214    fn copy(&self) -> Option<Box<dyn Any>> {
215        R::copy_state(self.0).map(|state| Box::new(state) as Box<dyn Any>)
216    }
217
218    fn set(&mut self, state: Box<dyn Any>) {
219        if let Ok(state) = state.downcast::<R::State>() {
220            *self.0 = Rc::from(state);
221        }
222    }
223}
224
225impl<R: Resource> Reader<R> {
226    /// Read the resource from `doc` and start following its changes.
227    ///
228    /// A reader reads for views: a `#[model(demanded)]` field is read only
229    /// in the items a view demands ([`Self::demand`]), and a change to an
230    /// item reads what it touched in it. [`Self::read_all`] reads every
231    /// field.
232    pub fn open(doc: &mut Doc) -> Result<Self, ModelError> {
233        let mut state = crate::table::for_view(|| R::read(doc))?;
234        R::load(&mut state, doc, &Demand::none())?;
235        Ok(Self {
236            core: Following::started(doc),
237            state: Rc::new(state),
238        })
239    }
240
241    /// Read the resource from a document that may only be read, and follow
242    /// its changes from the next [`sync`](Self::sync) on.
243    pub fn read(doc: &Doc) -> Result<Self, ModelError> {
244        let mut state = crate::table::for_view(|| R::read(doc))?;
245        R::load(&mut state, doc, &Demand::none())?;
246        Ok(Self::with_state(state, heads_of(doc)))
247    }
248
249    /// [`Self::read`], reading every field as stored, the
250    /// `#[model(demanded)]` ones too, now and at every sync: what search
251    /// derives from a resource whose views read less of it.
252    pub fn read_all(doc: &Doc) -> Result<Self, ModelError> {
253        let mut state = R::read(doc)?;
254        R::load(&mut state, doc, &Demand::none())?;
255        let mut reader = Self::with_state(state, heads_of(doc));
256        reader.core.every_field = true;
257        Ok(reader)
258    }
259
260    /// Follow a document from a state already read from it at `heads`
261    /// (`None` when unknown: the first sync reads everything again).
262    pub fn with_state(state: R::State, heads: Option<Vec<ChangeHash>>) -> Self {
263        Self {
264            core: Following::at(heads),
265            state: Rc::new(state),
266        }
267    }
268
269    /// The current state. Cheap: shares the value.
270    ///
271    /// Holding the returned `Rc` across the next [`sync`](Self::sync) keeps
272    /// what it shows unchanged: that sync brings a copy up to date instead
273    /// ([`Resource::copy_state`]). The copy shares what the change did not
274    /// touch: every [`Collection`](crate::Collection) item, the items of each
275    /// [`Keyed`](crate::Keyed) or [`Ordered`](crate::Ordered) field (a
276    /// touched one is copied once), and the chunks of each
277    /// [`Map`](crate::Map), [`Set`](crate::Set) and [`Grid`](crate::Grid).
278    /// Plain fields (a `Vec`, a `BTreeMap`) are copied whole: a large one
279    /// belongs in one of those, and a view that needs only part of a state
280    /// keeps that part rather than the `Rc`.
281    pub fn state(&self) -> &Rc<R::State> {
282        &self.state
283    }
284
285    /// What the last sync that changed the state applied: the parts of the
286    /// document it touched, or [`Delta::everything`] when it read the state
287    /// whole (an open transaction, a failed refresh, the first read).
288    pub fn last_delta(&self) -> &Delta {
289        &self.core.last
290    }
291
292    /// Why the document does not read as the resource since the last sync,
293    /// if it does not: the state is then the last one that did read, and a
294    /// view shows this instead of it.
295    pub fn unreadable(&self) -> Option<&crate::Unreadable> {
296        self.core.unreadable.as_ref()
297    }
298
299    /// Increases whenever what the state says changes: the document moved,
300    /// or the state is presented again. Reading more of the same document
301    /// ([`Self::demand`]) is not a new revision.
302    pub fn revision(&self) -> u64 {
303        self.core.revision
304    }
305
306    /// Increases whenever a demand read parts of the document the state did
307    /// not hold yet ([`Self::demand`]).
308    pub fn loads(&self) -> u64 {
309        self.core.loads
310    }
311
312    /// Whether the state is `doc` as it stands: no change arrived since the
313    /// last sync.
314    pub fn follows(&self, doc: &Doc) -> bool {
315        self.core.follows(doc)
316    }
317
318    /// Whether `doc` holds every change of the last sync, so syncing to it
319    /// applies what moved since ([`Tracker::leads_to`]).
320    pub fn leads_to(&self, doc: &Doc) -> bool {
321        self.core.tracker.leads_to(doc)
322    }
323
324    /// Take `state` as the resource's state now, read elsewhere than from
325    /// a document this reader follows (a settings section, as the settings
326    /// document holds it): a new revision, in which everything changed.
327    pub fn replace(&mut self, state: R::State) {
328        self.state = Rc::new(state);
329        self.core.revision = self.core.revision.wrapping_add(1);
330        self.core.last = Delta::everything();
331        self.core.unreadable = None;
332    }
333
334    /// Count the unchanged state as a new revision, so everything following
335    /// it takes it again (a surface dropping an optimistic preview).
336    pub fn represent(&mut self) {
337        self.core.revision = self.core.revision.wrapping_add(1);
338    }
339
340    /// What views currently demand.
341    pub fn current_demand(&self) -> &Demand {
342        &self.core.demand
343    }
344
345    /// Apply whatever changed in `doc` since the last sync. Returns whether
346    /// the state changed.
347    ///
348    /// # Errors
349    /// Returns [`ModelError`] when the document no longer holds this
350    /// resource; the state is left as it was last read successfully and the
351    /// next sync reads it whole.
352    #[inline]
353    pub fn sync(&mut self, doc: &Doc) -> Result<bool, ModelError> {
354        self.core
355            .sync(&OpsOf::<R>::OPS, &mut Held::<R>(&mut self.state), doc)
356    }
357
358    /// Ask for the parts `demand` names (replacing the previous demand) and
359    /// read those not read yet. Returns whether the state changed.
360    #[inline(never)]
361    pub fn demand(&mut self, doc: &Doc, demand: Demand) -> Result<bool, ModelError>
362    where
363        R::State: Clone,
364    {
365        if demand == self.core.demand {
366            return Ok(false);
367        }
368        self.core.demand = demand;
369        R::load(Rc::make_mut(&mut self.state), doc, &self.core.demand)?;
370        self.core.loads = self.core.loads.wrapping_add(1);
371        Ok(true)
372    }
373
374    /// Read the state whole from `doc`, whatever the last sync saw move: so a
375    /// change this reader could not apply as a delta is reported
376    /// ([`Self::unreadable`]) rather than passed over, which a resource kept
377    /// small enough to read whole can afford on every sync. Returns whether
378    /// the state changed.
379    ///
380    /// # Errors
381    /// Returns [`ModelError`] when the document no longer holds this
382    /// resource; the state is left as it was last read successfully.
383    pub fn reread_whole(&mut self, doc: &Doc) -> Result<bool, ModelError> {
384        // The state was read at exactly this document: reading it whole
385        // again would find the same, and must not present it as new.
386        if self.core.unreadable.is_none()
387            && heads_of(doc).is_some_and(|heads| self.core.read_at.as_ref() == Some(&heads))
388        {
389            return Ok(false);
390        }
391        let before = self.core.revision;
392        self.core.stale = true;
393        self.core
394            .sync(&OpsOf::<R>::OPS, &mut Held::<R>(&mut self.state), doc)?;
395        Ok(self.core.revision != before)
396    }
397}
398
399impl Following {
400    fn follows(&self, doc: &Doc) -> bool {
401        !self.stale
402            && self.uncommitted.is_none()
403            && heads_of(doc).is_some_and(|heads| self.tracker.heads() == Some(heads.as_slice()))
404    }
405
406    /// [`Reader::sync`].
407    fn sync(
408        &mut self,
409        ops: &StateOps,
410        state: &mut dyn StateSlot,
411        doc: &Doc,
412    ) -> Result<bool, ModelError> {
413        // An open transaction belongs to whoever opened it, and closing it
414        // here would move their commit boundary. It has no version to diff
415        // from, so its state is read whole — once per change of the
416        // transaction — and the next sync after it closes diffs as usual.
417        if doc.pending_ops() > 0 {
418            let open = (doc.base_heads(), doc.pending_ops());
419            if self.uncommitted.as_ref() == Some(&open) {
420                return Ok(false);
421            }
422            self.uncommitted = Some(open);
423            self.apply(ops, state, doc, &Delta::everything())?;
424            return Ok(true);
425        }
426        let held = state.get();
427        let delta = self
428            .tracker
429            .committed_delta_located(doc, &|obj| (ops.locate)(held, obj));
430        let delta = if self.uncommitted.take().is_some() && delta.is_empty() {
431            // The transaction was rolled back: read what is left.
432            Delta::everything()
433        } else {
434            delta
435        };
436        let delta = if self.stale {
437            Delta::everything()
438        } else {
439            delta
440        };
441        if delta.is_empty() {
442            return Ok(false);
443        }
444        // Following the change a write on this thread just made, the items
445        // it stored are taken as they were written, not read back, whether
446        // the change is applied or the state read whole.
447        crate::apply_cache::taking_stored(doc, || self.apply(ops, state, doc, &delta))?;
448        Ok(true)
449    }
450
451    fn apply(
452        &mut self,
453        ops: &StateOps,
454        state: &mut dyn StateSlot,
455        doc: &Doc,
456        delta: &Delta,
457    ) -> Result<(), ModelError> {
458        let applied = self.apply_delta(ops, state, doc, delta);
459        self.unreadable = applied.as_ref().err().map(|error| crate::Unreadable {
460            reason: error.to_string(),
461            stored: crate::evolution::stored_version(doc),
462            expected: ops.version,
463        });
464        applied
465    }
466
467    fn apply_delta(
468        &mut self,
469        ops: &StateOps,
470        state: &mut dyn StateSlot,
471        doc: &Doc,
472        delta: &Delta,
473    ) -> Result<(), ModelError> {
474        self.stale = true;
475        let mut applied = delta.clone();
476        let replaced = match state.get_mut() {
477            Some(held) if !delta.is_everything() => {
478                if (ops.refresh)(held, doc, delta).is_err() {
479                    let mut read = self.read(ops, doc)?;
480                    (ops.load)(read.as_mut(), doc, &self.demand)?;
481                    applied = Delta::everything();
482                    Some(read)
483                } else {
484                    (ops.load)(held, doc, &self.demand)?;
485                    None
486                }
487            }
488            _ => {
489                // A view still holds the last state: bring a copy up to date
490                // rather than read the whole document again.
491                let copied = if delta.is_everything() {
492                    None
493                } else {
494                    crate::profiling::measure("resource.reader_copy", || state.copy())
495                };
496                let mut fresh = match copied {
497                    Some(mut copy) => {
498                        if (ops.refresh)(copy.as_mut(), doc, delta).is_err() {
499                            copy = self.read(ops, doc)?;
500                            applied = Delta::everything();
501                        }
502                        copy
503                    }
504                    None => self.read(ops, doc)?,
505                };
506                (ops.load)(fresh.as_mut(), doc, &self.demand)?;
507                Some(fresh)
508            }
509        };
510        self.last = applied;
511        if let Some(fresh) = replaced {
512            state.set(fresh);
513        }
514        // Only a whole read stands for what the document holds: one applied
515        // as a delta is still read whole once ([`Reader::reread_whole`]).
516        self.read_at = if self.last.is_everything() {
517            heads_of(doc)
518        } else {
519            None
520        };
521        self.stale = false;
522        self.revision = self.revision.wrapping_add(1);
523        Ok(())
524    }
525}