Skip to main content

tilo_resource/
storage.rs

1//! Storage types whose concurrent edits merge per element: [`Counter`],
2//! [`Set`], [`Grid`] and [`Outbox`], and [`Bytes`] for binary values.
3
4use std::collections::BTreeMap;
5use std::fmt;
6use tilo_sort::CompactSort as _;
7
8use automerge::transaction::Transactable;
9use automerge::{ObjId, ObjType, ReadDoc, ScalarValue, Value};
10use serde::{Deserialize, Serialize};
11
12use crate::action::{ActionCx, Refusal};
13use crate::chunk_map::ChunkMap;
14use crate::collection::{Collection, Id};
15use crate::delta::Delta;
16use crate::model::LocatedAt as _;
17use crate::model::{Doc, Model, ModelError, Slot, edit_whole, read_key, refresh_key, write_key};
18use crate::path::{EditOp, Segment, Settable};
19use crate::table::{MapEntries, ModelOps, ModelTable};
20use std::any::Any;
21
22/// Nothing: a value that stores nothing, for the members of a container that
23/// only orders ids (a [`Grid`]'s rows and columns).
24impl Model for () {
25    crate::__own_table!(());
26    crate::model::leaf_paths!();
27    #[inline(never)]
28    fn to_json(&self) -> serde_json::Value {
29        serde_json::Value::Null
30    }
31    #[inline(never)]
32    fn from_json(_: &serde_json::Value) -> Result<Self, ModelError> {
33        Ok(())
34    }
35    #[inline(never)]
36    fn load(_: &Doc, _: &Value<'_>, _: &ObjId) -> Result<Self, ModelError> {
37        Ok(())
38    }
39    fn missing() -> Result<Self, ModelError> {
40        Ok(())
41    }
42    /// Nothing is written: an absent slot reads as `()` already.
43    #[inline(never)]
44    fn store(&self, _: &mut Doc, _: Slot<'_>) -> Result<(), ModelError> {
45        Ok(())
46    }
47}
48
49/// A number whose concurrent changes add up: two people each adding one make
50/// two. Change it with [`Self::add`]; writing it back records the difference
51/// as an increment rather than a new value.
52#[derive(
53    Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
54)]
55#[serde(transparent)]
56pub struct Counter(i64);
57
58impl Counter {
59    #[must_use]
60    pub const fn new(value: i64) -> Self {
61        Self(value)
62    }
63
64    #[must_use]
65    pub const fn get(self) -> i64 {
66        self.0
67    }
68
69    pub fn add(&mut self, by: i64) {
70        self.0 = self.0.saturating_add(by);
71    }
72}
73
74impl fmt::Display for Counter {
75    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76        write!(f, "{}", self.0)
77    }
78}
79
80impl Model for Counter {
81    crate::__own_table!(Counter);
82    fn value_schema() -> serde_json::Value {
83        serde_json::json!({"type": "integer"})
84    }
85    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
86        let _ = types;
87        crate::FieldType::Int
88    }
89    crate::model::leaf_paths!();
90    #[inline(never)]
91    fn to_json(&self) -> serde_json::Value {
92        self.0.into()
93    }
94    #[inline(never)]
95    fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
96        i64::from_json(value).map(Self)
97    }
98    #[inline(never)]
99    fn load(doc: &Doc, value: &Value<'_>, id: &ObjId) -> Result<Self, ModelError> {
100        i64::load(doc, value, id).map(Self)
101    }
102    fn missing() -> Result<Self, ModelError> {
103        Ok(Self(0))
104    }
105    #[inline(never)]
106    fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
107        let stored = match slot.current(doc)? {
108            Some((value, id)) => i64::load(doc, &value, &id).unwrap_or(0),
109            None => 0,
110        };
111        let counter = matches!(
112            slot.current(doc)?,
113            Some((Value::Scalar(scalar), _)) if matches!(scalar.as_ref(), ScalarValue::Counter(_))
114        );
115        if counter {
116            slot.increment(doc, self.0.saturating_sub(stored))
117        } else {
118            slot.put_scalar(doc, ScalarValue::counter(self.0))
119        }
120    }
121    #[inline(never)]
122    fn edit(
123        doc: &mut Doc,
124        slot: Slot<'_>,
125        path: &[Segment],
126        op: &EditOp,
127        _cx: &mut ActionCx,
128    ) -> Result<(), ModelError> {
129        match op {
130            EditOp::Add { by } if path.is_empty() => slot.increment(doc, *by),
131            other => Err(ModelError::unsupported(other)),
132        }
133    }
134    #[inline(never)]
135    fn diff<R>(&self, after: &Self, path: &[Segment], out: &mut Vec<crate::Edit<R>>) {
136        if self.0 != after.0 {
137            out.push(crate::Edit::new(
138                path.to_vec(),
139                EditOp::Add {
140                    by: after.0.saturating_sub(self.0),
141                },
142            ));
143        }
144    }
145}
146
147#[cfg(test)]
148mod counter_tests {
149    use super::*;
150    use automerge::ROOT;
151
152    #[test]
153    fn saving_a_counter_over_an_integer_preserves_its_value() {
154        for (original, wanted) in [(5, 5), (5, 7), (-5, -7)] {
155            let mut doc = Doc::new();
156            doc.put(ROOT, "count", original).unwrap();
157            let mut count: Counter = read_key(&doc, &ROOT, "count").unwrap();
158            count.add(wanted - original);
159            write_key(&mut doc, &ROOT, "count", &count).unwrap();
160            assert_eq!(
161                read_key::<Counter>(&doc, &ROOT, "count").unwrap().get(),
162                wanted
163            );
164            count.add(1);
165            write_key(&mut doc, &ROOT, "count", &count).unwrap();
166            assert_eq!(
167                read_key::<Counter>(&doc, &ROOT, "count").unwrap().get(),
168                wanted + 1
169            );
170        }
171    }
172}
173
174/// The key an element of a [`Set`] is stored under: its JSON form, a string
175/// as itself.
176fn element_key<T: Model>(value: &T) -> String {
177    match value.to_json() {
178        serde_json::Value::String(text) => text,
179        other => other.to_string(),
180    }
181}
182
183/// A set whose concurrent adds and removes merge per element. Stored as a map
184/// keyed by each element's JSON form.
185///
186/// Clones share the elements in chunks: a copy costs a pointer per few dozen
187/// elements, and adding or removing one copies only its chunk.
188#[derive(Clone, Debug)]
189pub struct Set<T> {
190    elements: ChunkMap<T>,
191}
192
193impl<T> Default for Set<T> {
194    fn default() -> Self {
195        Self {
196            elements: ChunkMap::default(),
197        }
198    }
199}
200
201impl<T: PartialEq> PartialEq for Set<T> {
202    fn eq(&self, other: &Self) -> bool {
203        self.elements == other.elements
204    }
205}
206
207impl<T: Model> Set<T> {
208    #[must_use]
209    pub fn new() -> Self {
210        Self::default()
211    }
212
213    /// Add `value`; returns whether it was absent.
214    pub fn insert(&mut self, value: T) -> bool {
215        self.elements.insert(element_key(&value), value).is_none()
216    }
217
218    /// Remove `value`; returns whether it was present.
219    pub fn remove(&mut self, value: &T) -> bool {
220        self.elements.remove(&element_key(value)).is_some()
221    }
222
223    pub fn contains(&self, value: &T) -> bool {
224        self.elements.contains_key(&element_key(value))
225    }
226}
227
228impl<T> Set<T> {
229    pub fn len(&self) -> usize {
230        self.elements.len()
231    }
232
233    pub fn is_empty(&self) -> bool {
234        self.elements.is_empty()
235    }
236
237    /// The elements, ordered by their stored keys.
238    pub fn iter(&self) -> impl ExactSizeIterator<Item = &T> {
239        self.elements.values()
240    }
241}
242
243impl<T: Model> FromIterator<T> for Set<T> {
244    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
245        let mut set = Self::new();
246        for value in iter {
247            set.insert(value);
248        }
249        set
250    }
251}
252
253impl<T: Model> Model for Set<T> {
254    fn value_schema() -> serde_json::Value {
255        serde_json::json!({"type": "array", "items": T::value_schema()})
256    }
257    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
258        crate::FieldType::Set(Box::new(T::field_type(types)))
259    }
260    const CHECKS: bool = T::CHECKS;
261    const OPS: bool = T::OPS;
262    const TABLE: &'static ModelTable = &SetOf::<T>::TABLE;
263    crate::model::leaf_paths!();
264    crate::__table_functions!();
265    fn missing() -> Result<Self, ModelError> {
266        Ok(Self::new())
267    }
268}
269
270/// What `Set<T>`'s table reaches into one with: its elements, a map from
271/// each element's stored key.
272pub struct SetDesc {
273    item: &'static ModelTable,
274    elements: for<'a> fn(&'a dyn Any) -> Option<&'a dyn MapEntries>,
275    elements_mut: for<'a> fn(&'a mut dyn Any) -> Option<&'a mut dyn MapEntries>,
276    /// Put an empty set into `out` (an `Option` of it), and hand back its
277    /// elements.
278    fresh: for<'a> fn(&'a mut dyn Any) -> Option<&'a mut dyn MapEntries>,
279    staged: (fn() -> Box<dyn Any>, crate::table::Unstage),
280    replace: fn(&mut dyn Any, &mut dyn Any) -> Result<(), ModelError>,
281    item_staged: (fn() -> Box<dyn Any>, crate::table::Unstage),
282    /// The stored keys whose presence may differ between a set and
283    /// `before`, a set of the same type, in key order, once each: the keys
284    /// of the chunks the two do not share. `None` for values of another
285    /// type.
286    differing: for<'a> fn(&'a dyn Any, &'a dyn Any) -> Option<Vec<&'a str>>,
287}
288
289pub struct SetOf<T>(std::marker::PhantomData<T>);
290
291impl<T: Model> SetOf<T> {
292    pub const DESC: SetDesc = SetDesc {
293        item: T::TABLE,
294        elements: |value| Some(&value.downcast_ref::<Set<T>>()?.elements as &dyn MapEntries),
295        elements_mut: |value| {
296            Some(&mut value.downcast_mut::<Set<T>>()?.elements as &mut dyn MapEntries)
297        },
298        fresh: |out| {
299            let out = out.downcast_mut::<Option<Set<T>>>()?;
300            Some(&mut out.insert(Set::default()).elements as &mut dyn MapEntries)
301        },
302        staged: (
303            crate::table::empty_of::<Set<T>>,
304            crate::table::unwrap_of::<Set<T>>,
305        ),
306        replace: crate::table::replace_of::<Set<T>>,
307        item_staged: (crate::table::empty_of::<T>, crate::table::unwrap_of::<T>),
308        differing: |value, before| {
309            let (now, was) = (
310                value.downcast_ref::<Set<T>>()?,
311                before.downcast_ref::<Set<T>>()?,
312            );
313            Some(now.elements.differing_keys(&was.elements))
314        },
315    };
316
317    pub const TABLE: ModelTable = ModelTable::of_set(&Self::DESC, T::CHECKS);
318}
319
320fn sets(table: &ModelTable) -> Result<&'static SetDesc, ModelError> {
321    table.set().ok_or_else(crate::table::mismatch)
322}
323
324/// The stored key of a value whose JSON form is `json`: a string as
325/// itself.
326fn key_of_json(json: serde_json::Value) -> String {
327    match json {
328        serde_json::Value::String(text) => text,
329        other => other.to_string(),
330    }
331}
332
333/// Put the element stored under `key` into `out`, an `Option` of its type:
334/// its JSON form is the key as a string, else the key parsed as JSON.
335fn element_into(item: &ModelTable, key: &str, out: &mut dyn Any) -> Result<(), ModelError> {
336    if (item.ops.from_json)(item, &serde_json::Value::String(key.to_owned()), out).is_ok() {
337        return Ok(());
338    }
339    let value = serde_json::from_str::<serde_json::Value>(key)
340        .map_err(|error| ModelError::invalid(error.to_string()))?;
341    (item.ops.from_json)(item, &value, out)
342}
343
344/// An element from its JSON form, staged, with the key it is stored under.
345fn staged_element(
346    desc: &SetDesc,
347    value: &serde_json::Value,
348) -> Result<(String, Box<dyn Any>), ModelError> {
349    let mut staged = (desc.item_staged.0)();
350    (desc.item.ops.from_json)(desc.item, value, staged.as_mut())?;
351    let made = (desc.item_staged.1)(staged.as_ref()).ok_or_else(crate::table::mismatch)?;
352    Ok((
353        key_of_json((desc.item.ops.to_json)(desc.item, made)),
354        staged,
355    ))
356}
357
358/// The functions of every [`Set`]: each element a key of a map.
359pub static SET_OPS: ModelOps = ModelOps {
360    // Its elements, each a key holding `true`.
361    fresh: |table, value, _| {
362        let Some(elements) = table.set().and_then(|set| (set.elements)(value)) else {
363            return crate::model::Fresh::Store;
364        };
365        let mut made = std::collections::HashMap::with_capacity(elements.count());
366        elements.each(&mut |key, _| {
367            made.insert(key.to_owned(), automerge::hydrate::Value::scalar(true));
368        });
369        crate::model::Fresh::Value(automerge::hydrate::Value::Map(made.into()))
370    },
371    without_absent: crate::shape::kept_whole,
372    to_json: |table, value| {
373        let mut out = Vec::new();
374        if let Some(set) = table.set()
375            && let Some(elements) = (set.elements)(value)
376        {
377            elements.each(&mut |_, value| out.push((set.item.ops.to_json)(set.item, value)));
378        }
379        serde_json::Value::Array(out)
380    },
381    from_json: |table, value, out| {
382        let set = sets(table)?;
383        match value {
384            serde_json::Value::Array(values) => {
385                let mut made = Vec::with_capacity(values.len());
386                for value in values {
387                    made.push(staged_element(set, value)?);
388                }
389                let elements = (set.fresh)(out).ok_or_else(crate::table::mismatch)?;
390                for (key, mut staged) in made {
391                    elements.insert_moved(key, staged.as_mut())?;
392                }
393                Ok(())
394            }
395            serde_json::Value::Null => {
396                (set.fresh)(out).ok_or_else(crate::table::mismatch)?;
397                Ok(())
398            }
399            _ => Err(ModelError::shape("a list of elements")),
400        }
401    },
402    load: |table, doc, value, id, out| {
403        let set = sets(table)?;
404        if !matches!(value, Value::Object(ObjType::Map)) {
405            return Err(ModelError::shape("a set"));
406        }
407        let elements = (set.fresh)(out).ok_or_else(crate::table::mismatch)?;
408        for key in doc.keys(id) {
409            elements.insert_filled(key.clone(), &mut |into| element_into(set.item, &key, into))?;
410        }
411        Ok(())
412    },
413    missing: |table, out| {
414        (sets(table)?.fresh)(out).ok_or_else(crate::table::mismatch)?;
415        Ok(())
416    },
417    reload: |table, target, doc, slot| {
418        let set = sets(table)?;
419        let mut staged = (set.staged.0)();
420        match slot {
421            Some((value, id)) => (SET_OPS.load)(table, doc, value, id, staged.as_mut())?,
422            None => (SET_OPS.missing)(table, staged.as_mut())?,
423        }
424        (set.replace)(target, staged.as_mut())
425    },
426    store: |table, value, doc, slot| {
427        let set = sets(table)?;
428        let elements = (set.elements)(value).ok_or_else(crate::table::mismatch)?;
429        let map = slot.object(doc, ObjType::Map)?;
430        let stale: Vec<String> = doc
431            .keys(&map)
432            .filter(|key| elements.value(key).is_none())
433            .collect();
434        for key in stale {
435            doc.delete(&map, key.as_str())?;
436        }
437        let mut keys = Vec::with_capacity(elements.count());
438        elements.each(&mut |key, _| keys.push(key.to_owned()));
439        for key in keys {
440            if doc.get(&map, key.as_str())?.is_none() {
441                doc.put(&map, key.as_str(), true)?;
442            }
443        }
444        Ok(())
445    },
446    // The same elements: as many, and the same under every key of a chunk
447    // the two do not share (one they share holds the same keys).
448    stores_as: |table, value, before| {
449        let Some(set) = table.set() else {
450            return false;
451        };
452        let (Some(now), Some(was)) = ((set.elements)(value), (set.elements)(before)) else {
453            return false;
454        };
455        now.count() == was.count()
456            && (set.differing)(value, before).is_some_and(|keys| {
457                keys.into_iter()
458                    .all(|key| now.value(key).is_some() == was.value(key).is_some())
459            })
460    },
461    store_changed: |table, value, before, doc, slot, dirty| {
462        let set = sets(table)?;
463        let now = (set.elements)(value).ok_or_else(crate::table::mismatch)?;
464        let Some(differing) = (set.differing)(value, before) else {
465            return (SET_OPS.store)(table, value, doc, slot);
466        };
467        // A slot holding no map yet is written whole, as is a map someone
468        // else changed otherwise than key by key.
469        let Some((Value::Object(ObjType::Map), map)) = slot.current(doc)? else {
470            return (SET_OPS.store)(table, value, doc, slot);
471        };
472        let touched = dirty.under(&map);
473        if touched.is_all() {
474            return (SET_OPS.store)(table, value, doc, slot);
475        }
476        // Under any other key the map holds what `before` holds, as a store
477        // left it, and so does this set: storing writes nothing there.
478        let mut keys = differing;
479        keys.extend(touched.keys());
480        keys.compact_sort();
481        keys.dedup();
482        // What `store` writes: the stale keys deleted, then the missing
483        // ones put, both in key order.
484        for key in &keys {
485            if now.value(key).is_none() && doc.get(&map, *key)?.is_some() {
486                doc.delete(&map, *key)?;
487            }
488        }
489        for key in &keys {
490            if now.value(key).is_some() && doc.get(&map, *key)?.is_none() {
491                doc.put(&map, *key, true)?;
492            }
493        }
494        Ok(())
495    },
496    refresh: |table, target, doc, value, id, delta| {
497        let set = sets(table)?;
498        let touched = delta.under(id);
499        if touched.is_all() {
500            return (SET_OPS.reload)(table, target, doc, Some((value, id)));
501        }
502        let elements = (set.elements_mut)(target).ok_or_else(crate::table::mismatch)?;
503        for key in touched.keys() {
504            if doc.get(id, key)?.is_some() {
505                elements.insert_filled(key.to_owned(), &mut |into| {
506                    element_into(set.item, key, into)
507                })?;
508            } else {
509                elements.remove_key(key);
510            }
511        }
512        Ok(())
513    },
514    read_whole: |_, _, _| Ok(()),
515    edit: |table, doc, slot, path, op, _| {
516        let set = sets(table)?;
517        match op {
518            EditOp::Insert { value } if path.is_empty() => {
519                let (key, staged) = staged_element(set, value)?;
520                let made =
521                    (set.item_staged.1)(staged.as_ref()).ok_or_else(crate::table::mismatch)?;
522                (set.item.ops.check)(set.item, made).map_err(ModelError::refused)?;
523                let map = slot.object(doc, ObjType::Map)?;
524                if doc.get(&map, key.as_str())?.is_none() {
525                    doc.put(&map, key.as_str(), true)?;
526                }
527                Ok(())
528            }
529            EditOp::Remove { value } if path.is_empty() => {
530                let (key, _) = staged_element(set, value)?;
531                let map = slot.object(doc, ObjType::Map)?;
532                Slot::Key(&map, &key).remove(doc)
533            }
534            _ => crate::table::edit_whole(
535                table,
536                ((set.staged.0)(), set.staged.1),
537                false,
538                doc,
539                slot,
540                path,
541                op,
542            ),
543        }
544    },
545    diff: |table, before, after, path, out| {
546        let Some(set) = table.set() else {
547            return;
548        };
549        let (Some(was), Some(now)) = ((set.elements)(before), (set.elements)(after)) else {
550            return;
551        };
552        let edit = |op| crate::Edit::new(path.to_vec(), op);
553        // An element `before` holds and `after` does not: removed.
554        let removed = |key: &str, value: &dyn Any, out: &mut Vec<crate::Edit<()>>| {
555            if now.value(key).is_none() {
556                let value = (set.item.ops.to_json)(set.item, value);
557                out.push(edit(EditOp::Remove { value }));
558            }
559        };
560        // One `after` holds and `before` does not: added.
561        let added = |key: &str, value: &dyn Any, out: &mut Vec<crate::Edit<()>>| {
562            if was.value(key).is_none() {
563                let value = (set.item.ops.to_json)(set.item, value);
564                out.push(edit(EditOp::Insert { value }));
565            }
566        };
567        // Under any other key both hold the same element: no edit.
568        if let Some(keys) = (set.differing)(after, before) {
569            for key in &keys {
570                if let Some(value) = was.value(key) {
571                    removed(key, value, out);
572                }
573            }
574            for key in &keys {
575                if let Some(value) = now.value(key) {
576                    added(key, value, out);
577                }
578            }
579        } else {
580            was.each(&mut |key, value| removed(key, value, out));
581            now.each(&mut |key, value| added(key, value, out));
582        }
583    },
584    collect_text: |table, value, out| {
585        if let Some(set) = table.set()
586            && let Some(elements) = (set.elements)(value)
587        {
588            elements.each(&mut |_, value| (set.item.ops.collect_text)(set.item, value, out));
589        }
590    },
591    check: |table, value| {
592        let Some(set) = table.set() else {
593            return Ok(());
594        };
595        if !set.item.checks {
596            return Ok(());
597        }
598        let Some(elements) = (set.elements)(value) else {
599            return Ok(());
600        };
601        let mut checked = Ok(());
602        elements.each(&mut |_, value| {
603            if checked.is_ok() {
604                checked = (set.item.ops.check)(set.item, value);
605            }
606        });
607        checked
608    },
609    get_at: |_, value, path| path.is_empty().then_some(value),
610    label: crate::table::no_label,
611    nested_collections: crate::table::no_nested,
612    op_coalesces: |_, _, _, _| None,
613    op_continuable: |_, _, _| None,
614    op_describe: |_, _, _| None,
615    op_lands: |_, _, _, _| None,
616    op_schemas: |_, _, _| {},
617};
618
619/// Values up to this size are stored inside the document; larger ones by
620/// reference to their content.
621pub const BYTES_INLINE_LIMIT: usize = 1024;
622
623/// Binary data. Small values live inside the document; larger ones are kept
624/// in the content store, which carries them alongside the record, and the
625/// document keeps the reference to them. Written whole: last writer wins.
626///
627/// Whoever invokes the action that writes the data keeps it, sealed, in the
628/// window's store before the action is recorded ([`Self::keep`]); the action
629/// carries the reference, and every replica applying it stores that.
630#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
631pub enum Bytes {
632    #[default]
633    Empty,
634    /// The data itself, at most [`BYTES_INLINE_LIMIT`] bytes.
635    Inline(Vec<u8>),
636    /// Data kept in the content store: its BLAKE3 hash and length, and the
637    /// sealed reference (`<address>.<key>`) it is kept under. Data kept
638    /// before content was sealed has none, and is kept under its hash.
639    Blob {
640        hash: [u8; 32],
641        len: u64,
642        sealed: Option<String>,
643    },
644}
645
646impl Bytes {
647    /// `data` inline when it is small, else named by its hash alone, as
648    /// data was before it was sealed: what an action recorded with its bytes
649    /// inline replays to. Data to keep is kept with [`Self::keep`].
650    #[must_use]
651    pub fn of(data: &[u8]) -> Self {
652        if data.is_empty() {
653            Self::Empty
654        } else if data.len() <= BYTES_INLINE_LIMIT {
655            Self::Inline(data.to_vec())
656        } else {
657            Self::Blob {
658                hash: *blake3::hash(data).as_bytes(),
659                len: u64::try_from(data.len()).unwrap_or(u64::MAX),
660                sealed: None,
661            }
662        }
663    }
664
665    /// `data` as the side invoking an action hands it over: an argument
666    /// that is kept, sealed, in the window's store where the action is built
667    /// ([`crate::content::invoking`]), so the action carries the reference.
668    #[must_use]
669    pub fn to_keep(data: Vec<u8>) -> Self {
670        if data.is_empty() {
671            Self::Empty
672        } else {
673            Self::Inline(data)
674        }
675    }
676
677    /// `data`, kept in `store` unless it is small enough to live inside the
678    /// document: what the side invoking an action does with the data it
679    /// carries. A store that seals (a window's) keeps it under a key of its
680    /// own, which the answer carries.
681    ///
682    /// # Errors
683    /// Why the store refused the data.
684    pub fn keep(
685        store: &tilo_content::ContentStore,
686        data: &[u8],
687    ) -> Result<Self, tilo_content::ContentError> {
688        if data.len() <= BYTES_INLINE_LIMIT {
689            return Ok(Self::of(data));
690        }
691        let reference = store.put(data)?;
692        Ok(Self::kept_as(data, &reference))
693    }
694
695    /// `data`, kept in a content store under `reference`, however small.
696    #[must_use]
697    pub fn kept_as(data: &[u8], reference: &str) -> Self {
698        if data.is_empty() {
699            return Self::Empty;
700        }
701        Self::Blob {
702            hash: *blake3::hash(data).as_bytes(),
703            len: u64::try_from(data.len()).unwrap_or(u64::MAX),
704            sealed: tilo_content::is_sealed(reference).then(|| reference.to_owned()),
705        }
706    }
707
708    /// The data when it is inside the document.
709    #[must_use]
710    pub fn inline(&self) -> Option<&[u8]> {
711        match self {
712            Self::Empty => Some(&[]),
713            Self::Inline(data) => Some(data),
714            Self::Blob { .. } => None,
715        }
716    }
717
718    /// The reference a content store keeps the data under, when it is kept
719    /// outside the document.
720    #[must_use]
721    pub fn reference(&self) -> Option<String> {
722        match self {
723            Self::Blob {
724                sealed: Some(reference),
725                ..
726            } => Some(reference.clone()),
727            Self::Blob { hash, .. } => Some(blake3::Hash::from_bytes(*hash).to_hex().to_string()),
728            _ => None,
729        }
730    }
731
732    /// The data, read from `store` when it is kept there, and checked
733    /// against its hash. `None` while it is not here.
734    #[must_use]
735    pub fn read(&self, store: &tilo_content::ContentStore) -> Option<Vec<u8>> {
736        match self.inline() {
737            Some(data) => Some(data.to_vec()),
738            None => store
739                .read(&self.reference()?)
740                .filter(|data| blake3::hash(data).as_bytes() == &self.hash()),
741        }
742    }
743
744    /// The content hash of the data, however it is stored.
745    #[must_use]
746    pub fn hash(&self) -> [u8; 32] {
747        match self {
748            Self::Empty => *blake3::hash(&[]).as_bytes(),
749            Self::Inline(data) => *blake3::hash(data).as_bytes(),
750            Self::Blob { hash, .. } => *hash,
751        }
752    }
753
754    #[must_use]
755    pub fn len(&self) -> u64 {
756        match self {
757            Self::Empty => 0,
758            Self::Inline(data) => u64::try_from(data.len()).unwrap_or(u64::MAX),
759            Self::Blob { len, .. } => *len,
760        }
761    }
762
763    #[must_use]
764    pub fn is_empty(&self) -> bool {
765        self.len() == 0
766    }
767
768    /// A kept value's text: `blake3:<hex>:<len>`, then `:<reference>` when
769    /// sealed.
770    fn text(hash: &[u8; 32], len: u64, sealed: Option<&str>) -> String {
771        let hex = blake3::Hash::from_bytes(*hash).to_hex();
772        match sealed {
773            Some(reference) => format!("blake3:{hex}:{len}:{reference}"),
774            None => format!("blake3:{hex}:{len}"),
775        }
776    }
777
778    /// The address the content store keeps the data a stored value names
779    /// under: what a holder of the record keeps, asks for and serves (a
780    /// sealed value's ciphertext address). `None` for text that is not a
781    /// stored value of data kept outside the document.
782    #[must_use]
783    pub fn stored_address(text: &str) -> Option<String> {
784        Self::parse_text(text)
785            .ok()?
786            .reference()
787            .and_then(|reference| tilo_content::content_address(&reference))
788    }
789
790    fn parse_text(text: &str) -> Result<Self, ModelError> {
791        let invalid = || ModelError::invalid(format!("not a content reference: {text}"));
792        let rest = text.strip_prefix("blake3:").ok_or_else(invalid)?;
793        let mut parts = rest.splitn(3, ':');
794        let hash =
795            blake3::Hash::from_hex(parts.next().ok_or_else(invalid)?).map_err(|_| invalid())?;
796        let len = parts
797            .next()
798            .ok_or_else(invalid)?
799            .parse()
800            .map_err(|_| invalid())?;
801        let sealed = match parts.next() {
802            Some(reference) if tilo_content::is_sealed(reference) => Some(reference.to_owned()),
803            Some(_) => return Err(invalid()),
804            None => None,
805        };
806        Ok(Self::Blob {
807            hash: *hash.as_bytes(),
808            len,
809            sealed,
810        })
811    }
812
813    /// The value an action's argument names: its stored form, or, where the
814    /// action is invoked, the data inline or the reference to content
815    /// readable in the workspace — a `tilo.content:<reference>` address, or
816    /// the reference alone, as an operation that collects content takes it —
817    /// which is kept, sealed, in the window's store
818    /// ([`crate::content::invoking`]).
819    fn from_argument(value: serde_json::Value) -> Result<Self, String> {
820        match value {
821            serde_json::Value::Array(_) => {
822                let data: Vec<u8> =
823                    serde_json::from_value(value).map_err(|error| error.to_string())?;
824                if !crate::content::is_invoking() {
825                    // An action an earlier version recorded with its bytes inline.
826                    return Ok(Self::of(&data));
827                }
828                Self::keep_here(&data)
829            }
830            serde_json::Value::String(text) => Self::from_content_argument(&text),
831            other => Self::from_json(&other).map_err(|error| error.to_string()),
832        }
833    }
834
835    /// The data the text argument `text` names, read where the action is
836    /// invoked and kept in the window's store: a `tilo.content:<reference>`
837    /// address, or the reference alone — a plain hash, as content was named
838    /// before it was sealed, or an address and the key that opens it. Any
839    /// other text is the stored form ([`Self::parse_text`]), or no content.
840    fn from_content_argument(text: &str) -> Result<Self, String> {
841        let Some(reference) = tilo_actions::named_reference(text) else {
842            return Self::from_json(&serde_json::Value::String(text.to_owned()))
843                .map_err(|error| error.to_string());
844        };
845        if !crate::content::is_invoking() {
846            return Err(format!(
847                "{text} is read where the action is invoked, never where it replays"
848            ));
849        }
850        // Content the workspace keeps already is taken as the value the document
851        // keeps, which names it by its reference: the bytes never cross here.
852        if let Some(stored) = crate::content::given_form(reference) {
853            return Self::parse_text(&stored).map_err(|error| error.to_string());
854        }
855        let data = crate::content::read_hash(reference).map_err(|refusal| refusal.to_string())?;
856        if tilo_content::is_sealed(reference) {
857            Ok(Self::kept_as(&data, reference))
858        } else {
859            Self::keep_here(&data)
860        }
861    }
862
863    /// `data`, kept in the store of the window whose code is running.
864    fn keep_here(data: &[u8]) -> Result<Self, String> {
865        if data.len() <= BYTES_INLINE_LIMIT {
866            return Ok(Self::of(data));
867        }
868        let store = crate::content::current()
869            .ok_or("this window has no content store to keep the data in")?;
870        Self::keep(&store, data)
871            .map_err(|error| format!("the content store refused the data: {error}"))
872    }
873}
874
875impl serde::Serialize for Bytes {
876    /// Its stored form; data to keep ([`Self::to_keep`]) as the bytes
877    /// themselves, which the action's build keeps.
878    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
879        match self {
880            Self::Inline(data) if data.len() > BYTES_INLINE_LIMIT => {
881                serializer.collect_seq(data.iter())
882            }
883            stored => stored.to_json().serialize(serializer),
884        }
885    }
886}
887
888impl<'de> serde::Deserialize<'de> for Bytes {
889    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
890        let value = serde_json::Value::deserialize(deserializer)?;
891        Self::from_argument(value).map_err(serde::de::Error::custom)
892    }
893}
894
895impl crate::JsonSchema for Bytes {
896    /// The data inline, as integers, or a reference to content readable in
897    /// the workspace; or the value as the document keeps it.
898    fn json_schema() -> serde_json::Value {
899        serde_json::json!({
900            "oneOf": [
901                {"type": "array", "items": {"type": "integer", "minimum": 0, "maximum": 255}},
902                {
903                    "type": "string",
904                    tilo_actions::CONTENT_ANNOTATION: true,
905                    "pattern": "^tilo\\.content:[0-9a-f]{64}(\\.[A-Za-z0-9_-]{43})?$",
906                },
907                {
908                    "type": "string",
909                    "pattern": "^blake3:[0-9a-f]{64}:[0-9]+(:[0-9a-f]{64}\\.[A-Za-z0-9_-]{43})?$",
910                },
911                {"type": "object", "properties": {"inline": {"type": "array"}}},
912                {"type": "null"},
913            ]
914        })
915    }
916}
917
918impl Settable for Bytes {}
919impl Model for Bytes {
920    crate::__own_table!(Bytes);
921    crate::model::leaf_paths!();
922    /// `null` is the empty value.
923    const NULLABLE: bool = true;
924    /// Inline data as `{ "inline": [bytes] }`, a reference as its
925    /// `blake3:<hex>:<len>` string.
926    #[inline(never)]
927    fn to_json(&self) -> serde_json::Value {
928        match self {
929            Self::Empty => serde_json::Value::Null,
930            Self::Inline(data) => serde_json::json!({ "inline": data }),
931            Self::Blob { hash, len, sealed } => {
932                serde_json::Value::String(Self::text(hash, *len, sealed.as_deref()))
933            }
934        }
935    }
936    #[inline(never)]
937    fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
938        match value {
939            serde_json::Value::Null => Ok(Self::Empty),
940            serde_json::Value::String(text) => Self::parse_text(text),
941            serde_json::Value::Object(fields) => {
942                let data: Vec<u8> = fields
943                    .get("inline")
944                    .cloned()
945                    .map(serde_json::from_value)
946                    .transpose()
947                    .map_err(|error| ModelError::invalid(error.to_string()))?
948                    .unwrap_or_default();
949                if data.len() > BYTES_INLINE_LIMIT {
950                    return Err(ModelError::invalid("inline data is too large"));
951                }
952                Ok(if data.is_empty() {
953                    Self::Empty
954                } else {
955                    Self::Inline(data)
956                })
957            }
958            _ => Err(ModelError::shape("bytes")),
959        }
960    }
961    #[inline(never)]
962    fn load(_: &Doc, value: &Value<'_>, _: &ObjId) -> Result<Self, ModelError> {
963        match value {
964            Value::Scalar(scalar) => match scalar.as_ref() {
965                ScalarValue::Bytes(data) if data.is_empty() => Ok(Self::Empty),
966                ScalarValue::Bytes(data) => Ok(Self::Inline(data.clone())),
967                ScalarValue::Str(text) => Self::parse_text(text),
968                ScalarValue::Null => Ok(Self::Empty),
969                _ => Err(ModelError::shape("bytes")),
970            },
971            Value::Object(_) => Err(ModelError::shape("bytes")),
972        }
973    }
974    fn missing() -> Result<Self, ModelError> {
975        Ok(Self::Empty)
976    }
977    #[inline(never)]
978    fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
979        match self {
980            Self::Empty => slot.put_scalar(doc, ScalarValue::Null),
981            Self::Inline(data) => slot.put_scalar(doc, ScalarValue::Bytes(data.clone())),
982            Self::Blob { hash, len, sealed } => slot.put_scalar(
983                doc,
984                ScalarValue::Str(Self::text(hash, *len, sealed.as_deref()).into()),
985            ),
986        }
987    }
988}
989
990const ROWS: &str = "rows";
991const COLUMNS: &str = "columns";
992const CELLS: &str = "cells";
993
994/// The key a cell is stored under in the grid's `cells` map.
995fn cell_key(row: &str, column: &str) -> String {
996    format!("{row}/{column}")
997}
998
999/// Every cell `cells` (the grid's `cells` map) holds, by row then column.
1000fn read_cells<T: Model>(doc: &Doc, grid: &ObjId) -> Result<ChunkMap<RowCells<T>>, ModelError> {
1001    let mut out: BTreeMap<String, RowCells<T>> = BTreeMap::new();
1002    let Some((Value::Object(ObjType::Map), cells)) = doc.get(grid, CELLS)? else {
1003        return Ok(ChunkMap::default());
1004    };
1005    for key in doc.keys(&cells) {
1006        let Some((row, column)) = key.split_once('/') else {
1007            continue;
1008        };
1009        let value = read_key::<T>(doc, &cells, &key)?;
1010        out.entry(row.to_owned())
1011            .or_default()
1012            .insert(column.to_owned(), value);
1013    }
1014    Ok(out.into())
1015}
1016
1017/// A table of cells addressed by stable row and column ids. Inserting or
1018/// removing a row or column keeps every other cell's identity, concurrent
1019/// edits merge per cell, and empty cells take no space.
1020///
1021/// Stored as a map: `rows` and `columns` are ordered like a
1022/// [`Collection`]'s items, `cells` maps `<row>/<column>` to each non-empty
1023/// cell. Cells sit flat in one map made with the grid, so no write ever
1024/// makes an object per row: two people writing into a row they both just
1025/// added both keep their cells.
1026///
1027/// Clones share the cells, rows in chunks: a copy of a sheet costs a pointer
1028/// per few dozen rows, and writing a cell copies only its rows' chunk.
1029#[derive(Clone, Debug)]
1030pub struct Grid<T> {
1031    rows: Collection<()>,
1032    columns: Collection<()>,
1033    cells: ChunkMap<RowCells<T>>,
1034}
1035
1036/// The cells of one row, by column, sorted: a row holds a few cells, and a
1037/// map per row would take a whole tree node for each.
1038#[derive(Clone, Debug, PartialEq)]
1039struct RowCells<T>(Vec<(String, T)>);
1040
1041impl<T> Default for RowCells<T> {
1042    fn default() -> Self {
1043        Self(Vec::new())
1044    }
1045}
1046
1047impl<T> RowCells<T> {
1048    fn find(&self, column: &str) -> Result<usize, usize> {
1049        self.0
1050            .binary_search_by(|(held, _)| held.as_str().cmp(column))
1051    }
1052
1053    fn get(&self, column: &str) -> Option<&T> {
1054        let at = self.find(column).ok()?;
1055        self.0.get(at).map(|(_, value)| value)
1056    }
1057
1058    fn get_mut(&mut self, column: &str) -> Option<&mut T> {
1059        let at = self.find(column).ok()?;
1060        self.0.get_mut(at).map(|(_, value)| value)
1061    }
1062
1063    fn contains_key(&self, column: &str) -> bool {
1064        self.find(column).is_ok()
1065    }
1066
1067    fn insert(&mut self, column: String, value: T) {
1068        match self.find(&column) {
1069            Ok(at) => {
1070                if let Some(held) = self.0.get_mut(at) {
1071                    held.1 = value;
1072                }
1073            }
1074            Err(at) => {
1075                // Most rows hold one cell: the first takes no room for
1076                // more; a row that grows past it grows as a list does.
1077                if self.0.capacity() == 0 {
1078                    self.0.reserve_exact(1);
1079                }
1080                self.0.insert(at, (column, value));
1081            }
1082        }
1083    }
1084
1085    fn remove(&mut self, column: &str) {
1086        if let Ok(at) = self.find(column) {
1087            self.0.remove(at);
1088        }
1089    }
1090
1091    fn is_empty(&self) -> bool {
1092        self.0.is_empty()
1093    }
1094
1095    fn len(&self) -> usize {
1096        self.0.len()
1097    }
1098
1099    fn iter(&self) -> impl Iterator<Item = (&String, &T)> {
1100        self.0.iter().map(|(column, value)| (column, value))
1101    }
1102
1103    fn values(&self) -> impl Iterator<Item = &T> {
1104        self.0.iter().map(|(_, value)| value)
1105    }
1106}
1107
1108impl<T> Default for Grid<T> {
1109    fn default() -> Self {
1110        Self {
1111            rows: Collection::new(),
1112            columns: Collection::new(),
1113            cells: ChunkMap::default(),
1114        }
1115    }
1116}
1117
1118impl<T: PartialEq> PartialEq for Grid<T> {
1119    fn eq(&self, other: &Self) -> bool {
1120        self.rows == other.rows && self.columns == other.columns && self.cells == other.cells
1121    }
1122}
1123
1124impl<T> Grid<T> {
1125    #[must_use]
1126    pub fn new() -> Self {
1127        Self::default()
1128    }
1129
1130    /// Row ids in order.
1131    pub fn rows(&self) -> impl DoubleEndedIterator<Item = &Id> + ExactSizeIterator {
1132        self.rows.ids()
1133    }
1134
1135    /// Column ids in order.
1136    pub fn columns(&self) -> impl DoubleEndedIterator<Item = &Id> + ExactSizeIterator {
1137        self.columns.ids()
1138    }
1139
1140    pub fn cell(&self, row: &Id, column: &Id) -> Option<&T> {
1141        self.cells.get(row.as_str())?.get(column.as_str())
1142    }
1143
1144    pub fn cell_mut(&mut self, row: &Id, column: &Id) -> Option<&mut T> {
1145        self.cells.get_mut(row.as_str())?.get_mut(column.as_str())
1146    }
1147
1148    /// Set (`Some`) or clear (`None`) the cell at `row`, `column`. A cell of
1149    /// a row or column that does not exist is not set.
1150    pub fn set_cell(&mut self, row: &Id, column: &Id, value: Option<T>) -> bool {
1151        if !self.rows.contains(row) || !self.columns.contains(column) {
1152            return false;
1153        }
1154        match value {
1155            Some(value) => {
1156                if let Some(cells) = self
1157                    .cells
1158                    .get_or_insert_with(row.as_str(), RowCells::default)
1159                {
1160                    cells.insert(column.as_str().to_owned(), value);
1161                }
1162            }
1163            None => {
1164                if let Some(cells) = self.cells.get_mut(row.as_str()) {
1165                    cells.remove(column.as_str());
1166                    if cells.is_empty() {
1167                        self.cells.remove(row.as_str());
1168                    }
1169                }
1170            }
1171        }
1172        true
1173    }
1174
1175    /// Insert a row at `at` (clamped).
1176    pub fn insert_row(&mut self, at: usize, id: Id) -> Id {
1177        self.rows.insert(at, id, ())
1178    }
1179
1180    /// Insert a column at `at` (clamped).
1181    pub fn insert_column(&mut self, at: usize, id: Id) -> Id {
1182        self.columns.insert(at, id, ())
1183    }
1184
1185    pub fn remove_row(&mut self, row: &Id) -> bool {
1186        self.cells.remove(row.as_str());
1187        self.rows.remove(row).is_some()
1188    }
1189
1190    pub fn remove_column(&mut self, column: &Id) -> bool {
1191        // Only the rows holding a cell of the column change.
1192        self.cells.retain_where(
1193            |cells| cells.contains_key(column.as_str()),
1194            |cells| {
1195                cells.remove(column.as_str());
1196                !cells.is_empty()
1197            },
1198        );
1199        self.columns.remove(column).is_some()
1200    }
1201
1202    /// The non-empty cells of `rows` (in key order), as [`Self::cells`]
1203    /// lists them.
1204    fn cells_in<'a>(&'a self, rows: &'a [&'a str]) -> impl Iterator<Item = (Id, Id, &'a T)> {
1205        rows.iter().flat_map(move |row| {
1206            self.cells.get(row).into_iter().flat_map(move |cells| {
1207                cells.iter().map(move |(column, value)| {
1208                    (Id::from_raw(*row), Id::from_raw(column.clone()), value)
1209                })
1210            })
1211        })
1212    }
1213
1214    /// Whether any cell satisfies `predicate`, by its value alone: no row or column id is made
1215    /// to ask.
1216    pub fn any(&self, mut predicate: impl FnMut(&T) -> bool) -> bool {
1217        self.cells
1218            .iter()
1219            .any(|(_, cells)| cells.values().any(&mut predicate))
1220    }
1221
1222    /// Every non-empty cell: row, column, value.
1223    pub fn cells(&self) -> impl Iterator<Item = (Id, Id, &T)> {
1224        self.cells.iter().flat_map(|(row, cells)| {
1225            cells.iter().map(move |(column, value)| {
1226                (
1227                    Id::from_raw(row.clone()),
1228                    Id::from_raw(column.clone()),
1229                    value,
1230                )
1231            })
1232        })
1233    }
1234}
1235
1236impl<T: Model> Grid<T> {
1237    /// Write the cells into the grid's `cells` map as [`Model::store`]
1238    /// does: stale cells deleted in key order, then every cell.
1239    fn store_cells(&self, doc: &mut Doc, cells: &ObjId) -> Result<(), ModelError> {
1240        let held: std::collections::BTreeSet<String> = self
1241            .cells()
1242            .map(|(row, column, _)| cell_key(row.as_str(), column.as_str()))
1243            .collect();
1244        let stale: Vec<String> = doc.keys(cells).filter(|key| !held.contains(key)).collect();
1245        for key in stale {
1246            doc.delete(cells, key.as_str())?;
1247        }
1248        for (row, column, value) in self.cells() {
1249            let key = cell_key(row.as_str(), column.as_str());
1250            value.store(doc, Slot::Key(cells, &key)).located(&key)?;
1251        }
1252        Ok(())
1253    }
1254
1255    /// Bring the cells read earlier up to date after `delta`, reading only
1256    /// the cells it touched.
1257    fn refresh_cells(&mut self, doc: &Doc, grid: &ObjId, delta: &Delta) -> Result<(), ModelError> {
1258        let Some((Value::Object(ObjType::Map), cells)) = doc.get(grid, CELLS)? else {
1259            self.cells.clear();
1260            return Ok(());
1261        };
1262        let touched = delta.under(&cells);
1263        if touched.is_all() {
1264            self.cells = read_cells(doc, grid)?;
1265            return Ok(());
1266        }
1267        for key in touched.keys() {
1268            let Some((row, column)) = key.split_once('/') else {
1269                continue;
1270            };
1271            let Some((value, id)) = doc.get(&cells, key)? else {
1272                if let Some(row_cells) = self.cells.get_mut(row) {
1273                    row_cells.remove(column);
1274                    if row_cells.is_empty() {
1275                        self.cells.remove(row);
1276                    }
1277                }
1278                continue;
1279            };
1280            let existing = self
1281                .cells
1282                .get_mut(row)
1283                .and_then(|row_cells| row_cells.get_mut(column));
1284            match existing {
1285                Some(cell) if touched.key(key) == crate::delta::Touch::Below => {
1286                    cell.refresh(doc, &value, &id, delta).located(key)?;
1287                }
1288                _ => {
1289                    let cell = T::load(doc, &value, &id).located(key)?;
1290                    if let Some(cells) = self.cells.get_or_insert_with(row, RowCells::default) {
1291                        cells.insert(column.to_owned(), cell);
1292                    }
1293                }
1294            }
1295        }
1296        Ok(())
1297    }
1298}
1299
1300fn grid_map(doc: &mut Doc, slot: Slot<'_>) -> Result<ObjId, ModelError> {
1301    slot.object(doc, ObjType::Map)
1302}
1303
1304impl<T: Model> Model for Grid<T> {
1305    const CHECKS: bool = T::CHECKS;
1306    const OPS: bool = T::OPS;
1307    crate::model::leaf_paths!();
1308    #[inline(never)]
1309    fn diff<R>(&self, after: &Self, path: &[Segment], out: &mut Vec<crate::Edit<R>>) {
1310        let edit = |op| crate::Edit::new(path.to_vec(), op);
1311        for row in self.rows() {
1312            if !after.rows.contains(row) {
1313                out.push(edit(EditOp::RemoveRow { id: row.clone() }));
1314            }
1315        }
1316        for column in self.columns() {
1317            if !after.columns.contains(column) {
1318                out.push(edit(EditOp::RemoveColumn { id: column.clone() }));
1319            }
1320        }
1321        for (at, row) in after.rows().enumerate() {
1322            if !self.rows.contains(row) {
1323                out.push(edit(EditOp::InsertRow {
1324                    id: Some(row.clone()),
1325                    at,
1326                }));
1327            }
1328        }
1329        for (at, column) in after.columns().enumerate() {
1330            if !self.columns.contains(column) {
1331                out.push(edit(EditOp::InsertColumn {
1332                    id: Some(column.clone()),
1333                    at,
1334                }));
1335            }
1336        }
1337        // Rows of cells in a chunk both grids share hold the same cells: only
1338        // the others are compared, in the order of all of them.
1339        let rows = after.cells.differing_keys(&self.cells);
1340        for (row, column, value) in after.cells_in(&rows) {
1341            match self.cell(&row, &column) {
1342                Some(before) => {
1343                    let mut at = path.to_vec();
1344                    at.push(Segment::Cell { row, column });
1345                    before.diff(value, &at, out);
1346                }
1347                None => out.push(edit(EditOp::SetCell {
1348                    row,
1349                    column,
1350                    value: Some(value.to_json()),
1351                })),
1352            }
1353        }
1354        for (row, column, _) in self.cells_in(&rows) {
1355            if after.rows.contains(&row)
1356                && after.columns.contains(&column)
1357                && after.cell(&row, &column).is_none()
1358            {
1359                out.push(edit(EditOp::SetCell {
1360                    row,
1361                    column,
1362                    value: None,
1363                }));
1364            }
1365        }
1366    }
1367    fn op_coalesces(
1368        path: &[Segment],
1369        previous: &serde_json::Value,
1370        next: &serde_json::Value,
1371    ) -> Option<bool> {
1372        match path.split_first() {
1373            Some((Segment::Cell { .. }, rest)) if T::OPS => T::op_coalesces(rest, previous, next),
1374            _ => None,
1375        }
1376    }
1377    fn op_continuable(path: &[Segment], op: &serde_json::Value) -> Option<bool> {
1378        match path.split_first() {
1379            Some((Segment::Cell { .. }, rest)) if T::OPS => T::op_continuable(rest, op),
1380            _ => None,
1381        }
1382    }
1383    fn op_describe(path: &[Segment], op: &serde_json::Value) -> Option<crate::path::OpDescription> {
1384        match path.split_first() {
1385            Some((Segment::Cell { .. }, rest)) if T::OPS => T::op_describe(rest, op),
1386            _ => None,
1387        }
1388    }
1389    fn op_lands(&self, path: &[Segment], op: &serde_json::Value) -> Option<crate::Place> {
1390        match path.split_first() {
1391            Some((Segment::Cell { row, column }, rest)) => {
1392                self.cell(row, column)?.op_lands(rest, op)
1393            }
1394            _ => None,
1395        }
1396    }
1397    fn op_schemas(prefix: &str, out: &mut Vec<(String, serde_json::Value)>) {
1398        if T::OPS {
1399            T::op_schemas(&format!("{prefix}*."), out);
1400        }
1401    }
1402    #[inline(never)]
1403    fn to_json(&self) -> serde_json::Value {
1404        serde_json::json!({
1405            "rows": self.rows.ids().map(Id::as_str).collect::<Vec<_>>(),
1406            "columns": self.columns.ids().map(Id::as_str).collect::<Vec<_>>(),
1407            "cells": self
1408                .cells()
1409                .map(|(row, column, value)| serde_json::json!({
1410                    "row": row.as_str(),
1411                    "column": column.as_str(),
1412                    "value": value.to_json(),
1413                }))
1414                .collect::<Vec<_>>(),
1415        })
1416    }
1417    #[inline(never)]
1418    fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
1419        if value.is_null() {
1420            return Ok(Self::new());
1421        }
1422        let ids = |key: &str| -> Result<Vec<Id>, ModelError> {
1423            value
1424                .get(key)
1425                .map_or(Ok(Vec::new()), Vec::<Id>::from_json)
1426                .located(key)
1427        };
1428        let mut grid = Self::new();
1429        for (at, id) in ids(ROWS)?.into_iter().enumerate() {
1430            grid.insert_row(at, id);
1431        }
1432        for (at, id) in ids(COLUMNS)?.into_iter().enumerate() {
1433            grid.insert_column(at, id);
1434        }
1435        for cell in value
1436            .get(CELLS)
1437            .and_then(serde_json::Value::as_array)
1438            .into_iter()
1439            .flatten()
1440        {
1441            let field = |key: &str| {
1442                cell.get(key)
1443                    .map(Id::from_json)
1444                    .transpose()?
1445                    .ok_or_else(|| ModelError::Missing {
1446                        path: key.to_owned(),
1447                    })
1448            };
1449            let (row, column) = (field("row")?, field("column")?);
1450            let value = T::from_json(cell.get("value").unwrap_or(&serde_json::Value::Null))?;
1451            if !grid.set_cell(&row, &column, Some(value)) {
1452                return Err(ModelError::invalid(format!("no cell {row}:{column}")));
1453            }
1454        }
1455        Ok(grid)
1456    }
1457    #[inline(never)]
1458    fn load(doc: &Doc, value: &Value<'_>, id: &ObjId) -> Result<Self, ModelError> {
1459        if !matches!(value, Value::Object(ObjType::Map)) {
1460            return Err(ModelError::shape("a grid"));
1461        }
1462        Ok(Self {
1463            rows: read_key(doc, id, ROWS)?,
1464            columns: read_key(doc, id, COLUMNS)?,
1465            cells: read_cells(doc, id)?,
1466        })
1467    }
1468    fn missing() -> Result<Self, ModelError> {
1469        Ok(Self::new())
1470    }
1471    /// The same rows, columns and cells, each storing as before. Rows of
1472    /// cells in a chunk both grids share are the same rows, and are not
1473    /// compared.
1474    #[inline(never)]
1475    fn stores_as(&self, before: &Self) -> bool {
1476        self.rows.stores_as(&before.rows)
1477            && self.columns.stores_as(&before.columns)
1478            && self.cells.len() == before.cells.len()
1479            && self
1480                .cells
1481                .differing_keys(&before.cells)
1482                .into_iter()
1483                .all(|row| match (self.cells.get(row), before.cells.get(row)) {
1484                    (Some(cells), Some(was)) => {
1485                        cells.len() == was.len()
1486                            && cells.iter().all(|(column, value)| {
1487                                was.get(column).is_some_and(|was| value.stores_as(was))
1488                            })
1489                    }
1490                    (None, None) => true,
1491                    _ => false,
1492                })
1493    }
1494    /// What [`store`](Model::store) writes, from `before` instead of the
1495    /// document: rows and columns as their collections write them, then the
1496    /// stale cells deleted in key order and only the cells that differ from
1497    /// `before`, or that someone else touched (`dirty`), written.
1498    #[inline(never)]
1499    fn store_changed(
1500        &self,
1501        before: &Self,
1502        doc: &mut Doc,
1503        slot: Slot<'_>,
1504        dirty: &Delta,
1505    ) -> Result<(), ModelError> {
1506        let map = grid_map(doc, slot)?;
1507        crate::model::write_key_changed(doc, &map, ROWS, &self.rows, &before.rows, dirty)?;
1508        crate::model::write_key_changed(doc, &map, COLUMNS, &self.columns, &before.columns, dirty)?;
1509        let replaced = dirty.key(&map, CELLS) == crate::delta::Touch::Written;
1510        let cells = Slot::Key(&map, CELLS).object(doc, ObjType::Map)?;
1511        let touched = dirty.under(&cells);
1512        if replaced || touched.is_all() {
1513            return self.store_cells(doc, &cells);
1514        }
1515        // Rows of cells in a chunk both grids share are the same rows, held
1516        // as a store left them: only the other rows, and the rows of cells
1517        // someone else wrote, are visited.
1518        let mut rows: std::collections::BTreeSet<&str> = self
1519            .cells
1520            .differing_keys(&before.cells)
1521            .into_iter()
1522            .collect();
1523        rows.extend(
1524            touched
1525                .keys()
1526                .filter_map(|key| Some(key.split_once('/')?.0)),
1527        );
1528        // What the map may hold that this grid does not: the cells those
1529        // rows held before and any key someone else wrote, in the map's key
1530        // order.
1531        let mut candidates: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
1532        for row in &rows {
1533            if let Some(was) = before.cells.get(row) {
1534                candidates.extend(was.iter().map(|(column, _)| cell_key(row, column)));
1535            }
1536        }
1537        candidates.extend(touched.keys().map(str::to_owned));
1538        for key in candidates {
1539            let held = key.split_once('/').is_some_and(|(row, column)| {
1540                self.cells
1541                    .get(row)
1542                    .is_some_and(|cells| cells.contains_key(column))
1543            });
1544            if !held && doc.get(&cells, key.as_str())?.is_some() {
1545                doc.delete(&cells, key.as_str())?;
1546            }
1547        }
1548        // Then the cells of those rows, in the order `store` writes them.
1549        for row in rows {
1550            let Some(held) = self.cells.get(row) else {
1551                continue;
1552            };
1553            for (column, value) in held.iter() {
1554                let key = cell_key(row, column);
1555                let slot = Slot::Key(&cells, &key);
1556                let was = before.cells.get(row).and_then(|was| was.get(column));
1557                match (touched.key(&key), was) {
1558                    (crate::delta::Touch::Untouched, Some(was)) if value.stores_as(was) => {}
1559                    (crate::delta::Touch::Untouched | crate::delta::Touch::Below, Some(was)) => {
1560                        value.store_changed(was, doc, slot, dirty).located(&key)?;
1561                    }
1562                    _ => value.store(doc, slot).located(&key)?,
1563                }
1564            }
1565        }
1566        Ok(())
1567    }
1568    #[inline(never)]
1569    fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
1570        let map = grid_map(doc, slot)?;
1571        write_key(doc, &map, ROWS, &self.rows)?;
1572        write_key(doc, &map, COLUMNS, &self.columns)?;
1573        let cells = Slot::Key(&map, CELLS).object(doc, ObjType::Map)?;
1574        self.store_cells(doc, &cells)
1575    }
1576    #[inline(never)]
1577    fn refresh(
1578        &mut self,
1579        doc: &Doc,
1580        value: &Value<'_>,
1581        id: &ObjId,
1582        delta: &Delta,
1583    ) -> Result<(), ModelError> {
1584        if delta.under(id).is_all() {
1585            *self = Self::load(doc, value, id)?;
1586            return Ok(());
1587        }
1588        refresh_key(&mut self.rows, doc, id, ROWS, delta)?;
1589        refresh_key(&mut self.columns, doc, id, COLUMNS, delta)?;
1590        match delta.key(id, CELLS) {
1591            crate::delta::Touch::Untouched => Ok(()),
1592            crate::delta::Touch::Written => {
1593                self.cells = read_cells(doc, id)?;
1594                Ok(())
1595            }
1596            // Only the cells the change touched are read again: a keystroke
1597            // in one cell reads that cell, not the sheet.
1598            crate::delta::Touch::Below => self.refresh_cells(doc, id, delta),
1599        }
1600    }
1601    #[allow(
1602        clippy::too_many_lines,
1603        reason = "one arm per grid operation, read top to bottom"
1604    )]
1605    #[inline(never)]
1606    fn edit(
1607        doc: &mut Doc,
1608        slot: Slot<'_>,
1609        path: &[Segment],
1610        op: &EditOp,
1611        cx: &mut ActionCx,
1612    ) -> Result<(), ModelError> {
1613        let map = grid_map(doc, slot)?;
1614        let exists = |doc: &Doc, key: &str, id: &Id| -> Result<bool, ModelError> {
1615            Ok(match doc.get(&map, key)? {
1616                Some((_, axis)) => doc.get(&axis, id.as_str())?.is_some(),
1617                None => false,
1618            })
1619        };
1620        match (path.split_first(), op) {
1621            (Some((Segment::Cell { row, column }, rest)), op) => {
1622                if !exists(doc, ROWS, row)? || !exists(doc, COLUMNS, column)? {
1623                    return Err(ModelError::invalid(format!("no cell {row}:{column}")));
1624                }
1625                let cells = Slot::Key(&map, CELLS).object(doc, ObjType::Map)?;
1626                let key = cell_key(row.as_str(), column.as_str());
1627                let slot = Slot::Key(&cells, &key);
1628                if rest.is_empty() && matches!(op, EditOp::Set { .. }) {
1629                    return edit_whole::<T>(doc, slot, rest, op);
1630                }
1631                if slot.current(doc)?.is_none() {
1632                    return Err(ModelError::invalid(format!(
1633                        "the cell {row}:{column} is empty"
1634                    )));
1635                }
1636                T::edit(doc, slot, rest, op, cx)
1637            }
1638            (None, EditOp::SetCell { row, column, value }) => {
1639                if !exists(doc, ROWS, row)? || !exists(doc, COLUMNS, column)? {
1640                    return Err(ModelError::invalid(format!("no cell {row}:{column}")));
1641                }
1642                let cells = Slot::Key(&map, CELLS).object(doc, ObjType::Map)?;
1643                let key = cell_key(row.as_str(), column.as_str());
1644                match value {
1645                    Some(value) => {
1646                        let value = T::from_json(value)?;
1647                        value.check().map_err(ModelError::refused)?;
1648                        value.store(doc, Slot::Key(&cells, &key))
1649                    }
1650                    None => Slot::Key(&cells, &key).remove(doc),
1651                }
1652            }
1653            (None, EditOp::InsertRow { id, at } | EditOp::InsertColumn { id, at }) => {
1654                let axis = if matches!(op, EditOp::InsertRow { .. }) {
1655                    ROWS
1656                } else {
1657                    COLUMNS
1658                };
1659                let id = id.clone().unwrap_or_else(|| cx.id());
1660                Collection::<()>::edit(
1661                    doc,
1662                    Slot::Key(&map, axis),
1663                    &[],
1664                    &EditOp::InsertItem {
1665                        id: Some(id),
1666                        at: crate::At::Index(*at),
1667                        value: serde_json::Value::Null,
1668                    },
1669                    cx,
1670                )?;
1671                Ok(())
1672            }
1673            (None, EditOp::RemoveRow { id }) => {
1674                Collection::<()>::edit(
1675                    doc,
1676                    Slot::Key(&map, ROWS),
1677                    &[],
1678                    &EditOp::RemoveItem { id: id.clone() },
1679                    cx,
1680                )?;
1681                if let Some((_, cells)) = doc.get(&map, CELLS)? {
1682                    let prefix = format!("{id}/");
1683                    let gone: Vec<String> = doc
1684                        .keys(&cells)
1685                        .filter(|key| key.starts_with(&prefix))
1686                        .collect();
1687                    for key in gone {
1688                        doc.delete(&cells, key.as_str())?;
1689                    }
1690                }
1691                Ok(())
1692            }
1693            (None, EditOp::RemoveColumn { id }) => {
1694                Collection::<()>::edit(
1695                    doc,
1696                    Slot::Key(&map, COLUMNS),
1697                    &[],
1698                    &EditOp::RemoveItem { id: id.clone() },
1699                    cx,
1700                )?;
1701                if let Some((_, cells)) = doc.get(&map, CELLS)? {
1702                    let suffix = format!("/{id}");
1703                    let gone: Vec<String> = doc
1704                        .keys(&cells)
1705                        .filter(|key| key.ends_with(&suffix))
1706                        .collect();
1707                    for key in gone {
1708                        doc.delete(&cells, key.as_str())?;
1709                    }
1710                }
1711                Ok(())
1712            }
1713            _ => edit_whole::<Self>(doc, slot, path, op),
1714        }
1715    }
1716    fn check(&self) -> Result<(), Refusal> {
1717        if T::CHECKS {
1718            for cells in self.cells.values() {
1719                cells.values().try_for_each(Model::check)?;
1720            }
1721        }
1722        Ok(())
1723    }
1724    fn get_at(&self, path: &[Segment]) -> Option<&dyn std::any::Any>
1725    where
1726        Self: 'static,
1727    {
1728        match path.split_first() {
1729            None => Some(self),
1730            Some((Segment::Cell { row, column }, rest)) => self.cell(row, column)?.get_at(rest),
1731            Some(_) => None,
1732        }
1733    }
1734    fn collect_text(&self, out: &mut Vec<String>) {
1735        for cells in self.cells.values() {
1736            for value in cells.values() {
1737                value.collect_text(out);
1738            }
1739        }
1740    }
1741}
1742
1743/// How the owning device settled an [`Outbox`] entry, with what its handler
1744/// reports back (`O`): where a trashed file went, the name a copy got, the
1745/// id a server gave the upload.
1746///
1747/// Its JSON form is `{"state": "done", "result": O}` or `{"state": "failed",
1748/// "result": {"reason": .., "partial": O}}`, `partial` left out when nothing
1749/// was done. It is read through one JSON value
1750/// ([`Settled::from_json_value`]), so `O` is decoded by its value decoder
1751/// alone, never through serde's buffered copy of a tagged enum.
1752#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
1753#[serde(tag = "state", content = "result", rename_all = "kebab-case")]
1754pub enum Settled<O = ()> {
1755    /// The outside consequence happened.
1756    Done(O),
1757    /// It failed for good, in the handler's words, after doing `partial`.
1758    Failed { reason: String, partial: O },
1759}
1760
1761impl<O> Settled<O> {
1762    /// Whether the consequence happened.
1763    #[must_use]
1764    pub const fn is_done(&self) -> bool {
1765        matches!(self, Self::Done(_))
1766    }
1767
1768    /// What the handler did: all of it, or the part done before it failed.
1769    #[must_use]
1770    pub const fn result(&self) -> &O {
1771        match self {
1772            Self::Done(result)
1773            | Self::Failed {
1774                partial: result, ..
1775            } => result,
1776        }
1777    }
1778
1779    /// Why it failed, if it did.
1780    #[must_use]
1781    pub fn reason(&self) -> Option<&str> {
1782        match self {
1783            Self::Done(_) => None,
1784            Self::Failed { reason, .. } => Some(reason),
1785        }
1786    }
1787}
1788
1789impl<'de, O: serde::de::DeserializeOwned + Default> Deserialize<'de> for Settled<O> {
1790    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1791        let value = <serde_json::Value as Deserialize>::deserialize(deserializer)?;
1792        Self::from_json_value(value).map_err(serde::de::Error::custom)
1793    }
1794}
1795
1796impl<O: serde::de::DeserializeOwned + Default> Settled<O> {
1797    /// Read from its JSON form.
1798    pub fn from_json_value(value: serde_json::Value) -> Result<Self, serde_json::Error> {
1799        Ok(match settled_parts(value)? {
1800            (true, result) => Self::Done(serde_json::from_value(result)?),
1801            (false, result) => {
1802                let (reason, partial) = failed_parts(result)?;
1803                Self::Failed {
1804                    reason,
1805                    partial: partial
1806                        .map(serde_json::from_value)
1807                        .transpose()?
1808                        .unwrap_or_default(),
1809                }
1810            }
1811        })
1812    }
1813}
1814
1815/// Whether a settlement's JSON form says done, and its `result`.
1816#[inline(never)]
1817fn settled_parts(value: serde_json::Value) -> Result<(bool, serde_json::Value), serde_json::Error> {
1818    use serde::de::Error as _;
1819    let serde_json::Value::Object(mut fields) = value else {
1820        return Err(serde_json::Error::custom("a settlement is an object"));
1821    };
1822    let done = match fields.remove("state") {
1823        Some(serde_json::Value::String(state)) if state == "done" => true,
1824        Some(serde_json::Value::String(state)) if state == "failed" => false,
1825        Some(serde_json::Value::String(state)) => {
1826            return Err(serde_json::Error::unknown_variant(
1827                &state,
1828                &["done", "failed"],
1829            ));
1830        }
1831        Some(_) => return Err(serde_json::Error::custom("`state` is a string")),
1832        None => return Err(serde_json::Error::missing_field("state")),
1833    };
1834    let result = fields
1835        .remove("result")
1836        .ok_or_else(|| serde_json::Error::missing_field("result"))?;
1837    Ok((done, result))
1838}
1839
1840/// A failed settlement's `reason` and its `partial` result, absent when it
1841/// did nothing: whoever settles may not know `O`, as a connector's host
1842/// relaying the service's refusal does not.
1843#[inline(never)]
1844fn failed_parts(
1845    result: serde_json::Value,
1846) -> Result<(String, Option<serde_json::Value>), serde_json::Error> {
1847    use serde::de::Error as _;
1848    let serde_json::Value::Object(mut fields) = result else {
1849        return Err(serde_json::Error::custom("a failure is an object"));
1850    };
1851    let reason = match fields.remove("reason") {
1852        Some(serde_json::Value::String(reason)) => reason,
1853        Some(_) => return Err(serde_json::Error::custom("`reason` is a string")),
1854        None => return Err(serde_json::Error::missing_field("reason")),
1855    };
1856    Ok((reason, fields.remove("partial")))
1857}
1858
1859impl<O: Default> Settled<O> {
1860    /// Failed for good with nothing done.
1861    #[must_use]
1862    pub fn failed(reason: impl Into<String>) -> Self {
1863        Self::Failed {
1864            reason: reason.into(),
1865            partial: O::default(),
1866        }
1867    }
1868}
1869
1870/// A settlement stores as one JSON value: it is written once, by the owning
1871/// device.
1872impl<O: Serialize + serde::de::DeserializeOwned + Default + 'static> Model for Settled<O> {
1873    crate::model::leaf_paths!();
1874    #[inline(never)]
1875    fn to_json(&self) -> serde_json::Value {
1876        crate::__private::json_via_bytes(self).unwrap_or(serde_json::Value::Null)
1877    }
1878    #[inline(never)]
1879    fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
1880        Self::from_json_value(value.clone()).map_err(|error| ModelError::invalid(error.to_string()))
1881    }
1882    #[inline(never)]
1883    fn load(doc: &Doc, value: &Value<'_>, id: &ObjId) -> Result<Self, ModelError> {
1884        let text = String::load(doc, value, id)?;
1885        crate::__private::value_of_bytes(text.as_bytes())
1886            .and_then(Self::from_json_value)
1887            .map_err(|error| ModelError::invalid(error.to_string()))
1888    }
1889    #[inline(never)]
1890    fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
1891        let text =
1892            serde_json::to_string(self).map_err(|error| ModelError::invalid(error.to_string()))?;
1893        slot.put_scalar(doc, ScalarValue::Str(text.into()))
1894    }
1895}
1896
1897/// One queued outside consequence and, once the owning device ran it, how
1898/// it settled.
1899#[derive(Clone, Debug, PartialEq)]
1900pub struct OutboxEntry<T, O = ()> {
1901    pub value: T,
1902    pub settled: Option<Settled<O>>,
1903    /// The steps (change hashes) whose undo or redo queued this entry: they
1904    /// count as taken back (or brought back) once it settles done.
1905    pub compensates: Vec<String>,
1906}
1907
1908const ENTRY_VALUE: &str = "value";
1909const ENTRY_SETTLED: &str = "settled";
1910const ENTRY_COMPENSATES: &str = "compensates";
1911
1912/// The undo or redo of `steps` completed: the entry they waited for settled
1913/// done. A step whose undo waits for nothing (settled already, or another
1914/// device's history) is left as it is.
1915fn settle_steps(doc: &mut Doc, steps: &[String]) {
1916    for step in steps {
1917        let _ = tilo_actions::settle_compensation(doc, step);
1918    }
1919}
1920
1921impl<T: Model, O: Serialize + serde::de::DeserializeOwned + Default + 'static> Model
1922    for OutboxEntry<T, O>
1923{
1924    const CHECKS: bool = T::CHECKS;
1925    const OPS: bool = T::OPS;
1926    crate::model::leaf_paths!();
1927    #[inline(never)]
1928    fn to_json(&self) -> serde_json::Value {
1929        serde_json::json!({
1930            ENTRY_VALUE: self.value.to_json(),
1931            ENTRY_SETTLED: self.settled.to_json(),
1932            ENTRY_COMPENSATES: self.compensates.to_json(),
1933        })
1934    }
1935    #[inline(never)]
1936    fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
1937        let null = serde_json::Value::Null;
1938        Ok(Self {
1939            value: T::from_json(value.get(ENTRY_VALUE).unwrap_or(&null))?,
1940            settled: Option::<Settled<O>>::from_json(value.get(ENTRY_SETTLED).unwrap_or(&null))?,
1941            compensates: match value.get(ENTRY_COMPENSATES) {
1942                Some(steps) => Vec::from_json(steps)?,
1943                None => Vec::new(),
1944            },
1945        })
1946    }
1947    #[inline(never)]
1948    fn load(doc: &Doc, value: &Value<'_>, id: &ObjId) -> Result<Self, ModelError> {
1949        if !matches!(value, Value::Object(ObjType::Map)) {
1950            return Err(ModelError::shape("an outbox entry"));
1951        }
1952        Ok(Self {
1953            value: read_key(doc, id, ENTRY_VALUE)?,
1954            settled: read_key(doc, id, ENTRY_SETTLED)?,
1955            compensates: read_key(doc, id, ENTRY_COMPENSATES)?,
1956        })
1957    }
1958    #[inline(never)]
1959    fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
1960        let map = slot.object(doc, ObjType::Map)?;
1961        let was_done = read_key::<Option<Settled<O>>>(doc, &map, ENTRY_SETTLED)
1962            .ok()
1963            .flatten()
1964            .is_some_and(|settled| settled.is_done());
1965        write_key(doc, &map, ENTRY_VALUE, &self.value)?;
1966        write_key(doc, &map, ENTRY_SETTLED, &self.settled)?;
1967        write_key(doc, &map, ENTRY_COMPENSATES, &self.compensates)?;
1968        // A verb that settles the entry done completes the undo it was.
1969        if !was_done && self.settled.as_ref().is_some_and(Settled::is_done) {
1970            settle_steps(doc, &self.compensates);
1971        }
1972        Ok(())
1973    }
1974    fn check(&self) -> Result<(), Refusal> {
1975        self.value.check()
1976    }
1977}
1978
1979/// Outside consequences of the record's actions, queued in the document: a
1980/// mail to send, an event to upload, a file to move. A verb that takes
1981/// `&mut Outbox<T, O>` pushes entries and is an Outside action.
1982///
1983/// Every replica replays the entries; only the device that owns an entry
1984/// carries it out. The framework drains the outbox there, runs the app's
1985/// handler for each [`pending`](Self::pending) entry and records how it
1986/// settled, with the handler's result `O`, through the
1987/// [`settle`](crate::Path::settle) edit: content from outside, nobody's undo
1988/// step. A verb reads a settlement with [`Self::outcome`] (a revert needs
1989/// to know where the trashed file went), may settle an entry itself
1990/// ([`Self::settle`]) and forgets settled entries ([`Self::forget`],
1991/// [`Self::prune`]).
1992#[derive(Clone, Debug)]
1993pub struct Outbox<T, O = ()> {
1994    entries: Collection<OutboxEntry<T, O>>,
1995}
1996
1997impl<T, O> Default for Outbox<T, O> {
1998    fn default() -> Self {
1999        Self {
2000            entries: Collection::new(),
2001        }
2002    }
2003}
2004
2005impl<T: PartialEq, O: PartialEq> PartialEq for Outbox<T, O> {
2006    fn eq(&self, other: &Self) -> bool {
2007        self.entries == other.entries
2008    }
2009}
2010
2011impl<T, O> Outbox<T, O> {
2012    #[must_use]
2013    pub fn new() -> Self {
2014        Self::default()
2015    }
2016
2017    /// Queue `value` under `id` (mint it with [`ActionCx::id`]). Queued by
2018    /// an undo's or a redo's compensating action, it records the steps it
2019    /// settles.
2020    pub fn push(&mut self, id: Id, value: T) -> Id {
2021        self.entries.push(
2022            id,
2023            OutboxEntry {
2024                value,
2025                settled: None,
2026                compensates: tilo_actions::await_compensation(),
2027            },
2028        )
2029    }
2030
2031    /// The entries the owning device has yet to run, oldest first.
2032    pub fn pending(&self) -> impl Iterator<Item = (&Id, &T)> {
2033        self.entries
2034            .iter()
2035            .filter(|(_, entry)| entry.settled.is_none())
2036            .map(|(id, entry)| (id, &entry.value))
2037    }
2038
2039    /// Every entry, settled or not, oldest first.
2040    pub fn entries(&self) -> impl ExactSizeIterator<Item = (&Id, &OutboxEntry<T, O>)> {
2041        self.entries.iter()
2042    }
2043
2044    pub fn get(&self, id: &Id) -> Option<&OutboxEntry<T, O>> {
2045        self.entries.get(id)
2046    }
2047
2048    /// How the entry `id` settled; `None` while it is pending or when there
2049    /// is no such entry.
2050    pub fn outcome(&self, id: &Id) -> Option<&Settled<O>> {
2051        self.entries.get(id)?.settled.as_ref()
2052    }
2053
2054    /// Record how the entry `id` settled, from a verb. Whether there is
2055    /// such an entry.
2056    pub fn settle(&mut self, id: &Id, outcome: Settled<O>) -> bool {
2057        self.entries.get_mut(id).is_some_and(|entry| {
2058            entry.settled = Some(outcome);
2059            true
2060        })
2061    }
2062
2063    /// Forget the entry `id`. A pending entry forgotten is never carried
2064    /// out.
2065    pub fn forget(&mut self, id: &Id) -> Option<OutboxEntry<T, O>> {
2066        self.entries.remove(id)
2067    }
2068
2069    /// Forget the oldest settled entries beyond the newest `keep`; pending
2070    /// ones stay.
2071    pub fn prune(&mut self, keep: usize) {
2072        let settled = self
2073            .entries
2074            .iter()
2075            .filter(|(_, entry)| entry.settled.is_some())
2076            .count();
2077        let mut excess = settled.saturating_sub(keep);
2078        self.entries.retain(|_, entry| {
2079            if excess > 0 && entry.settled.is_some() {
2080                excess = excess.saturating_sub(1);
2081                return false;
2082            }
2083            true
2084        });
2085    }
2086
2087    pub fn len(&self) -> usize {
2088        self.entries.len()
2089    }
2090
2091    pub fn is_empty(&self) -> bool {
2092        self.entries.is_empty()
2093    }
2094}
2095
2096/// The map of entries an outbox stored in `slot` keeps, and the entry `id`
2097/// in it.
2098fn outbox_entry(doc: &mut Doc, slot: Slot<'_>, id: &Id) -> Result<(ObjId, ObjId), ModelError> {
2099    let map = slot.object(doc, ObjType::Map)?;
2100    let Some((Value::Object(ObjType::Map), entry)) = doc.get(&map, id.as_str())? else {
2101        return Err(ModelError::invalid(format!("no outbox entry `{id}`")));
2102    };
2103    let Some((Value::Object(ObjType::Map), value)) = doc.get(&entry, crate::collection::VALUE)?
2104    else {
2105        return Err(ModelError::invalid(format!("no outbox entry `{id}`")));
2106    };
2107    Ok((map, value))
2108}
2109
2110impl<T: Model, O: Serialize + serde::de::DeserializeOwned + Default + 'static> Model
2111    for Outbox<T, O>
2112{
2113    const CHECKS: bool = T::CHECKS;
2114    const OPS: bool = T::OPS;
2115    crate::model::leaf_paths!();
2116    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
2117        crate::FieldType::Outbox(Box::new(T::field_type(types)))
2118    }
2119    #[inline(never)]
2120    fn to_json(&self) -> serde_json::Value {
2121        self.entries.to_json()
2122    }
2123    #[inline(never)]
2124    fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
2125        Collection::from_json(value).map(|entries| Self { entries })
2126    }
2127    #[inline(never)]
2128    fn load(doc: &Doc, value: &Value<'_>, id: &ObjId) -> Result<Self, ModelError> {
2129        Collection::load(doc, value, id).map(|entries| Self { entries })
2130    }
2131    fn missing() -> Result<Self, ModelError> {
2132        Ok(Self::new())
2133    }
2134    #[inline(never)]
2135    fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
2136        self.entries.store(doc, slot)
2137    }
2138    #[inline(never)]
2139    fn refresh(
2140        &mut self,
2141        doc: &Doc,
2142        value: &Value<'_>,
2143        id: &ObjId,
2144        delta: &Delta,
2145    ) -> Result<(), ModelError> {
2146        self.entries.refresh(doc, value, id, delta)
2147    }
2148    /// Entries are queued by verbs; an edit settles one or forgets a
2149    /// settled one.
2150    #[inline(never)]
2151    fn edit(
2152        doc: &mut Doc,
2153        slot: Slot<'_>,
2154        path: &[Segment],
2155        op: &EditOp,
2156        _cx: &mut ActionCx,
2157    ) -> Result<(), ModelError> {
2158        edit_outbox(doc, slot, path, op, settled_text::<O>)
2159    }
2160    fn check(&self) -> Result<(), Refusal> {
2161        self.entries.check()
2162    }
2163    #[inline(never)]
2164    fn diff<R>(&self, after: &Self, path: &[Segment], out: &mut Vec<crate::Edit<R>>) {
2165        let mut edits = Vec::new();
2166        diff_outboxes(
2167            (&self.entries, &after.entries),
2168            settled_json::<T, O>,
2169            path,
2170            &mut edits,
2171        );
2172        out.extend(crate::path::retyped_all(edits));
2173    }
2174}
2175
2176/// What a settlement of an outbox of results `O` stores, from its JSON form,
2177/// and whether it settled done.
2178fn settled_text<O: Serialize + serde::de::DeserializeOwned + Default + 'static>(
2179    outcome: &serde_json::Value,
2180) -> Result<(String, bool), ModelError> {
2181    let outcome = Settled::<O>::from_json(outcome)?;
2182    let text =
2183        serde_json::to_string(&outcome).map_err(|error| ModelError::invalid(error.to_string()))?;
2184    Ok((text, outcome.is_done()))
2185}
2186
2187/// The settlement of the outbox entry `item`, as JSON; `None` while it is
2188/// pending.
2189fn settled_json<T: Model, O: Serialize + serde::de::DeserializeOwned + Default + 'static>(
2190    item: &dyn std::any::Any,
2191) -> Option<serde_json::Value> {
2192    item.downcast_ref::<OutboxEntry<T, O>>()?
2193        .settled
2194        .as_ref()
2195        .map(Model::to_json)
2196}
2197
2198/// [`Model::edit`] of an outbox: settle an entry, or forget a settled one.
2199/// `settled` makes a settlement's stored text from its JSON form.
2200fn edit_outbox(
2201    doc: &mut Doc,
2202    slot: Slot<'_>,
2203    path: &[Segment],
2204    op: &EditOp,
2205    settled: fn(&serde_json::Value) -> Result<(String, bool), ModelError>,
2206) -> Result<(), ModelError> {
2207    match (path, op) {
2208        ([], EditOp::Settle { id, outcome }) => {
2209            let (text, done) = settled(outcome)?;
2210            let (_, value) = outbox_entry(doc, slot, id)?;
2211            Slot::Key(&value, ENTRY_SETTLED).put_scalar(doc, ScalarValue::Str(text.into()))?;
2212            // Done, it completes the undo or redo it was queued by; a
2213            // failure leaves that step as it was.
2214            if done {
2215                let steps: Vec<String> = read_key(doc, &value, ENTRY_COMPENSATES)?;
2216                settle_steps(doc, &steps);
2217            }
2218            Ok(())
2219        }
2220        ([], EditOp::Forget { id }) => {
2221            let (map, value) = outbox_entry(doc, slot, id)?;
2222            let pending = !matches!(
2223                doc.get(&value, ENTRY_SETTLED)?,
2224                Some((Value::Scalar(scalar), _)) if !matches!(scalar.as_ref(), ScalarValue::Null)
2225            );
2226            if pending {
2227                return Err(ModelError::refused(Refusal::new(format!(
2228                    "outbox entry `{id}` is still pending"
2229                ))));
2230            }
2231            doc.delete(&map, id.as_str())?;
2232            Ok(())
2233        }
2234        _ => Err(ModelError::unsupported(op)),
2235    }
2236}
2237
2238/// [`Model::diff`] of two outboxes' entries (`before`, `after`): a settle
2239/// for each entry whose settlement changed, a forget for each settled entry
2240/// gone. `settled` reads an entry's settlement as JSON.
2241fn diff_outboxes(
2242    (before, after): (
2243        &dyn crate::collection::Entries,
2244        &dyn crate::collection::Entries,
2245    ),
2246    settled: fn(&dyn std::any::Any) -> Option<serde_json::Value>,
2247    path: &[Segment],
2248    out: &mut Vec<crate::Edit<()>>,
2249) {
2250    let settled_at =
2251        |entries: &dyn crate::collection::Entries, at: usize| entries.item_at(at).and_then(settled);
2252    for at in 0..after.count() {
2253        let Some(id) = after.id_at(at) else {
2254            continue;
2255        };
2256        if let (Some(outcome), Some(was)) = (settled_at(after, at), before.find(id))
2257            && settled_at(before, was).as_ref() != Some(&outcome)
2258        {
2259            out.push(crate::Edit::new(
2260                path.to_vec(),
2261                EditOp::Settle {
2262                    id: id.clone(),
2263                    outcome,
2264                },
2265            ));
2266        }
2267    }
2268    for at in 0..before.count() {
2269        let Some(id) = before.id_at(at) else {
2270            continue;
2271        };
2272        if settled_at(before, at).is_some() && after.find(id).is_none() {
2273            out.push(crate::Edit::new(
2274                path.to_vec(),
2275                EditOp::Forget { id: id.clone() },
2276            ));
2277        }
2278    }
2279}