Skip to main content

tilo_resource/
model.rs

1//! How typed values live in a resource's CRDT document.
2//!
3//! [`Model`] is the whole storage contract: read a value out of the slot its
4//! parent found, and write a value back touching only what changed. Every
5//! write is a *diff* — an unchanged scalar writes nothing, a string is spliced
6//! rather than replaced, a keyed collection moves one order key rather than
7//! renumbering — so concurrent edits from members merge field by field
8//! and an action that changes nothing commits nothing.
9//!
10//! Plain Rust types implement it here; `#[derive(Model)]` implements it for
11//! structs (a map, one key per field) and unit enums (a string). A resource
12//! type with its own storage layout implements it — or skips it and reads and
13//! writes the document itself, see [`crate::Resource`].
14
15use std::collections::BTreeMap;
16
17use automerge::transaction::Transactable;
18use automerge::{AutoCommit, ObjId, ObjType, ReadDoc, ScalarValue, Value};
19
20use crate::action::{ActionCx, Refusal};
21use crate::delta::{Delta, Touch};
22use crate::path::{EditOp, Path, Segment, Settable};
23
24/// The document every resource lives in.
25pub type Doc = AutoCommit;
26
27/// Why a document could not be read as, or written from, a typed value.
28#[derive(Debug, thiserror::Error)]
29pub enum ModelError {
30    #[error("{}expected {expected}", located(.path))]
31    Shape {
32        path: String,
33        expected: &'static str,
34    },
35    #[error("{}required value is missing", located(.path))]
36    Missing { path: String },
37    #[error("{}{message}", located(.path))]
38    Invalid { path: String, message: String },
39    #[error("document error: {0}")]
40    Automerge(#[from] automerge::AutomergeError),
41    /// A [`check`](Model::check) refused the change, in its own words.
42    #[error("{0}")]
43    Refused(String),
44    /// A [`check`](Model::check) refused the change for a reason a window tells
45    /// the person in their own language.
46    #[error("{0}")]
47    Declined(tilo_actions::Declined),
48}
49
50/// Where an error was found, as its message begins: `clips.title: `, or
51/// nothing at the record itself.
52fn located(path: &str) -> String {
53    if path.is_empty() {
54        String::new()
55    } else {
56        format!("{path}: ")
57    }
58}
59
60impl ModelError {
61    #[must_use]
62    pub fn shape(expected: &'static str) -> Self {
63        Self::Shape {
64            path: String::new(),
65            expected,
66        }
67    }
68
69    #[must_use]
70    pub fn invalid(message: impl Into<String>) -> Self {
71        Self::Invalid {
72            path: String::new(),
73            message: message.into(),
74        }
75    }
76
77    /// Prefix the location this error was found at, innermost last.
78    #[must_use]
79    #[inline(never)]
80    pub fn at(mut self, segment: &str) -> Self {
81        match &mut self {
82            Self::Shape { path, .. } | Self::Missing { path } | Self::Invalid { path, .. } => {
83                *path = if path.is_empty() {
84                    segment.to_owned()
85                } else {
86                    format!("{segment}.{path}")
87                };
88            }
89            Self::Automerge(_) | Self::Refused(_) | Self::Declined(_) => {}
90        }
91        self
92    }
93
94    /// A check's refusal, in its words: a model error names no code of its own.
95    #[must_use]
96    pub fn refused(refusal: Refusal) -> Self {
97        Self::Refused(refusal.into_reason())
98    }
99
100    /// An edit whose operation the value at its path does not support.
101    #[must_use]
102    pub fn unsupported(op: &EditOp) -> Self {
103        Self::invalid(format!("this value has no `{}` edit", op.name()))
104    }
105}
106
107/// What a value writes under a key of a map made just now
108/// ([`Model::fresh`]): what can be made with that map in one batch is, so an
109/// item made whole costs the batch, not an operation and a lookup per field.
110pub enum Fresh {
111    /// Nothing: the key stays absent, as for an absent `Option`.
112    Nothing,
113    /// This value, made with the map. A text in it is made with the marks
114    /// [`Model::store`] would set on it (a `String` field's author).
115    Value(automerge::hydrate::Value),
116    /// This value, made with the map too, whose [`Model::store`] writes into
117    /// it once the map is made: a rich text's schema, which its body is
118    /// written into, goes in with the map holding it rather than as an
119    /// insert of its own. [`storing_made`] is true while that store writes.
120    Made(automerge::hydrate::Value),
121    /// Written by [`Model::store`] once the map is made.
122    Store,
123}
124
125thread_local! {
126    /// Whether the value being stored at this moment was made with its map
127    /// in one batch ([`Fresh::Made`]).
128    static STORING_MADE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
129}
130
131/// Whether the value [`Model::store`] is writing now was made with its map in
132/// one batch ([`Fresh::Made`]): it starts from the map as made, with no
133/// earlier content to keep.
134#[must_use]
135pub fn storing_made() -> bool {
136    STORING_MADE.with(std::cell::Cell::get)
137}
138
139/// Call `store` with [`storing_made`] true, and leave it as it was.
140pub(crate) fn storing_made_around<T>(store: impl FnOnce() -> T) -> T {
141    struct Restore(bool);
142    impl Drop for Restore {
143        fn drop(&mut self) {
144            STORING_MADE.with(|made| made.set(self.0));
145        }
146    }
147    let was = STORING_MADE.with(|made| made.replace(true));
148    let _restore = Restore(was);
149    store()
150}
151
152impl Fresh {
153    /// A scalar made with the map.
154    #[must_use]
155    pub fn scalar(value: impl Into<ScalarValue>) -> Self {
156        Self::Value(automerge::hydrate::Value::Scalar(value.into()))
157    }
158}
159
160/// Where a value is written: a key of a map, an existing list element, or a
161/// new list element inserted at an index.
162#[derive(Clone, Copy, Debug)]
163pub enum Slot<'a> {
164    Key(&'a ObjId, &'a str),
165    Index(&'a ObjId, usize),
166    Insert(&'a ObjId, usize),
167}
168
169impl Slot<'_> {
170    /// What currently occupies this place. A new list element holds nothing.
171    pub fn current(self, doc: &Doc) -> Result<Option<(Value<'static>, ObjId)>, ModelError> {
172        let found = match self {
173            Slot::Key(obj, key) => doc.get(obj, key)?,
174            Slot::Index(obj, index) => doc.get(obj, index)?,
175            Slot::Insert(..) => None,
176        };
177        Ok(found.map(|(value, id)| (value.to_owned(), id)))
178    }
179
180    /// Write `value` unless the slot already holds an equal scalar.
181    pub fn put_scalar(self, doc: &mut Doc, value: ScalarValue) -> Result<(), ModelError> {
182        match self {
183            Slot::Key(obj, key) => {
184                if !matches!(doc.get(obj, key)?, Some((Value::Scalar(current), _)) if same_scalar(&current, &value))
185                {
186                    doc.put(obj, key, value)?;
187                }
188            }
189            Slot::Index(obj, index) => {
190                if !matches!(doc.get(obj, index)?, Some((Value::Scalar(current), _)) if same_scalar(&current, &value))
191                {
192                    doc.put(obj, index, value)?;
193                }
194            }
195            Slot::Insert(obj, index) => doc.insert(obj, index, value)?,
196        }
197        Ok(())
198    }
199
200    /// Make `value`, an object and everything in it, here at once, replacing
201    /// what was here: its id.
202    pub fn make(
203        self,
204        doc: &mut Doc,
205        value: &automerge::hydrate::Value,
206    ) -> Result<ObjId, ModelError> {
207        Ok(match self {
208            Self::Key(obj, key) => doc.batch_create_object(obj, key, value, false)?,
209            Self::Index(obj, index) => doc.batch_create_object(obj, index, value, false)?,
210            Self::Insert(obj, index) => doc.batch_create_object(obj, index, value, true)?,
211        })
212    }
213
214    /// The object of type `kind` in this slot, creating it (and replacing any
215    /// value of another shape) when absent.
216    pub fn object(self, doc: &mut Doc, kind: ObjType) -> Result<ObjId, ModelError> {
217        if let Some((Value::Object(existing), id)) = self.current(doc)?
218            && existing == kind
219        {
220            return Ok(id);
221        }
222        Ok(match self {
223            Slot::Key(obj, key) => doc.put_object(obj, key, kind)?,
224            Slot::Index(obj, index) => doc.put_object(obj, index, kind)?,
225            Slot::Insert(obj, index) => doc.insert_object(obj, index, kind)?,
226        })
227    }
228
229    /// Add `by` to the counter in this slot, creating it holding `by`.
230    pub fn increment(self, doc: &mut Doc, by: i64) -> Result<(), ModelError> {
231        let counter = matches!(
232            self.current(doc)?,
233            Some((Value::Scalar(scalar), _)) if matches!(scalar.as_ref(), ScalarValue::Counter(_))
234        );
235        if by == 0 && counter {
236            return Ok(());
237        }
238        match (self, counter) {
239            (Slot::Key(obj, key), true) => doc.increment(obj, key, by)?,
240            (Slot::Index(obj, index), true) => doc.increment(obj, index, by)?,
241            (slot, _) => {
242                let start = match slot.current(doc)? {
243                    Some((value, _)) => match scalar(&value) {
244                        Some(ScalarValue::Int(value)) => *value,
245                        _ => 0,
246                    },
247                    None => 0,
248                };
249                let value = ScalarValue::counter(start.saturating_add(by));
250                match slot {
251                    Slot::Key(obj, key) => doc.put(obj, key, value)?,
252                    Slot::Index(obj, index) => doc.put(obj, index, value)?,
253                    Slot::Insert(obj, index) => doc.insert(obj, index, value)?,
254                }
255            }
256        }
257        Ok(())
258    }
259
260    /// Remove whatever occupies this slot (a no-op for a new list element).
261    pub fn remove(self, doc: &mut Doc) -> Result<(), ModelError> {
262        match self {
263            Slot::Key(obj, key) => {
264                if doc.get(obj, key)?.is_some() {
265                    doc.delete(obj, key)?;
266                }
267            }
268            Slot::Index(obj, index) => doc.put(obj, index, ScalarValue::Null)?,
269            Slot::Insert(obj, index) => doc.insert(obj, index, ScalarValue::Null)?,
270        }
271        Ok(())
272    }
273}
274
275fn same_scalar(current: &ScalarValue, next: &ScalarValue) -> bool {
276    match (current, next) {
277        (ScalarValue::F64(a), ScalarValue::F64(b)) => a.to_bits() == b.to_bits(),
278        (a, b) => a == b,
279    }
280}
281
282/// A typed value stored in a CRDT document. See the module docs.
283pub trait Model: Sized + 'static {
284    /// How the value is laid out in the document; see [`Shape`](crate::Shape).
285    /// Types written whole keep the default.
286    const SHAPE: crate::Shape = crate::Shape::Value;
287
288    /// Whether this type or any value inside it has a `#[model(check)]`
289    /// invariant; [`Self::check`] has nothing to do otherwise.
290    const CHECKS: bool = false;
291
292    /// Whether this type or a value inside it has a vocabulary of its own
293    /// ([`Operations`](crate::Operations), rich text's): a record routes
294    /// those edits' gestures, landing places and schemas only into such
295    /// fields, and never instantiates the routing for the others.
296    const OPS: bool = false;
297
298    /// Whether `null` is a value of the type: an absent `Option`. A field
299    /// edit setting any other type to `null` is refused.
300    const NULLABLE: bool = false;
301
302    /// Whether [`store`](Self::store) writes one scalar, with nothing inside
303    /// it that a concurrent writer could add to. A record made just now
304    /// leaves out such a field holding its [`missing`](Self::missing) value:
305    /// an absent key reads as it. An object (text, a map, a list) is always
306    /// made with its record, so two writers fill the same one.
307    const SCALAR: bool = false;
308
309    /// The type's functions as data, which a record holding it reaches it
310    /// through ([`crate::table`]): by default its own functions, erased.
311    const TABLE: &'static crate::table::ModelTable = &crate::table::TableOf::<Self>::TABLE;
312
313    /// The typed paths into a value of this type, rooted in the record `R`:
314    /// a struct of field paths for a record, the [`Path`] itself for a value
315    /// edited whole or through its own operations.
316    type Paths<R>: Clone;
317
318    /// The paths of the value at `path`.
319    fn paths_at<R>(path: Path<R, Self>) -> Self::Paths<R>;
320
321    /// The value as JSON: what [`EditOp::Set`] carries and history shows.
322    fn to_json(&self) -> serde_json::Value;
323
324    /// A value from its [`Self::to_json`] form.
325    ///
326    /// # Errors
327    /// Returns [`ModelError`] when `value` has another shape.
328    fn from_json(value: &serde_json::Value) -> Result<Self, ModelError>;
329
330    /// Apply the field edit `op` at `path`, below the value in `slot`,
331    /// touching only what it changes, then run the invariants of the values
332    /// it touched. The default edits a value only as a whole.
333    #[inline(never)]
334    fn edit(
335        doc: &mut Doc,
336        slot: Slot<'_>,
337        path: &[Segment],
338        op: &EditOp,
339        cx: &mut ActionCx,
340    ) -> Result<(), ModelError> {
341        let _ = cx;
342        edit_whole::<Self>(doc, slot, path, op)
343    }
344
345    /// The field edits that turn `self` into `after`, at `path` below the
346    /// record: what a surface that edited a local copy submits. The default
347    /// sets the value whole when it changed; containers and records edit
348    /// only what differs, item by item and field by field. A value that
349    /// would store as it is ([`Self::stores_as`]) is compared in memory,
350    /// without turning either side into JSON.
351    #[inline(never)]
352    fn diff<R>(&self, after: &Self, path: &[Segment], out: &mut Vec<crate::Edit<R>>) {
353        if after.stores_as(self) {
354            return;
355        }
356        let value = after.to_json();
357        if self.to_json() != value {
358            out.push(crate::Edit::new(path.to_vec(), EditOp::Set { value }));
359        }
360    }
361
362    /// The item collections inside this value, when it is an item of a
363    /// collection itself (a slide's elements); `#[derive(Model)]` lists a
364    /// record's, the default has none.
365    fn nested_collections(&self) -> Vec<crate::items::ItemCollection> {
366        Vec::new()
367    }
368
369    /// The JSON Schema of this value's JSON form ([`Self::to_json`]), as
370    /// the published field edit describes what a path takes; the default
371    /// accepts any value.
372    fn value_schema() -> serde_json::Value {
373        serde_json::json!({})
374    }
375
376    /// This value's type in the language-neutral vocabulary a surface
377    /// publishes ([`FieldType`](crate::FieldType)), declaring the records
378    /// and enums it names in `types`. The default describes no type: any
379    /// value.
380    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
381        let _ = types;
382        crate::FieldType::Any
383    }
384
385    /// Read everything this value holds, for a field marked
386    /// `#[model(whole)]`: a value read lazily (rich text reads its
387    /// paragraphs as views ask for them) reads all of it, so every reader of
388    /// the record — a verb, search, `read_content` — sees all of it. The
389    /// default has nothing more to read.
390    ///
391    /// # Errors
392    /// Returns [`ModelError`] when the document no longer holds the value.
393    fn read_whole(&mut self, doc: &Doc) -> Result<(), ModelError> {
394        let _ = doc;
395        Ok(())
396    }
397
398    /// Run every `#[model(check)]` invariant of this value and the values
399    /// inside it.
400    fn check(&self) -> Result<(), Refusal> {
401        Ok(())
402    }
403
404    /// What names this value for people (`#[model(label)]`): history, search,
405    /// agents and item resources use it.
406    fn label(&self) -> Option<String> {
407        None
408    }
409
410    /// Whether two edits in the own vocabulary of the value at `path` below
411    /// this type are one gesture ([`Operations`](crate::Operations)); `None`
412    /// when nothing there has one.
413    fn op_coalesces(
414        path: &[Segment],
415        previous: &serde_json::Value,
416        next: &serde_json::Value,
417    ) -> Option<bool> {
418        let _ = (path, previous, next);
419        None
420    }
421
422    /// Whether a gesture may go on after the edit `op` at `path`.
423    fn op_continuable(path: &[Segment], op: &serde_json::Value) -> Option<bool> {
424        let _ = (path, op);
425        None
426    }
427    /// What the edit `op` at `path` below this type did, in the history
428    /// entry's terms ([`Operations::describe`](crate::Operations::describe)).
429    fn op_describe(path: &[Segment], op: &serde_json::Value) -> Option<crate::path::OpDescription> {
430        let _ = (path, op);
431        None
432    }
433
434    /// Where the actor of the edit `op` at `path` below this value is after
435    /// it applied.
436    fn op_lands(&self, path: &[Segment], op: &serde_json::Value) -> Option<crate::Place> {
437        let _ = (path, op);
438        None
439    }
440
441    /// The schemas of the own vocabularies of the values below this type,
442    /// by path pattern from `prefix` (`*` for every item).
443    fn op_schemas(prefix: &str, out: &mut Vec<(String, serde_json::Value)>) {
444        let _ = (prefix, out);
445    }
446
447    /// The value at `path` below this one, if it is there. A value with
448    /// nothing inside it is found only at the empty path.
449    fn get_at(&self, path: &[Segment]) -> Option<&dyn std::any::Any>
450    where
451        Self: 'static,
452    {
453        path.is_empty().then_some(self as &dyn std::any::Any)
454    }
455
456    /// Read from the value a parent found in its slot.
457    ///
458    /// # Errors
459    /// Returns [`ModelError`] when the stored value has another shape.
460    fn load(doc: &Doc, value: &Value<'_>, id: &ObjId) -> Result<Self, ModelError>;
461
462    /// The value of an absent slot. Types with a natural empty value return it,
463    /// so a field added to a schema reads older documents without migration.
464    ///
465    /// # Errors
466    /// Returns [`ModelError::Missing`] for types without an empty value.
467    fn missing() -> Result<Self, ModelError> {
468        Err(ModelError::Missing {
469            path: String::new(),
470        })
471    }
472
473    /// Write `self` into `slot`, changing only what differs from what the slot
474    /// already holds.
475    fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError>;
476
477    /// What [`store`](Self::store) writes under a key of a map made just
478    /// now, for the map to be made with it at once; `encoding` is the
479    /// document's text encoding. The default stores it once the map is made.
480    fn fresh(&self, encoding: automerge::TextEncoding) -> Fresh {
481        let _ = encoding;
482        Fresh::Store
483    }
484
485    /// Whether writing `self` over a slot that holds `before`, as a
486    /// [`store`](Self::store) left it, would change nothing: an in-memory
487    /// comparison, so an action that changed one item of a long collection
488    /// does not visit the others. Must only answer `true` when `store` would
489    /// write no operation; the default answers `false` (unknown).
490    #[inline(never)]
491    fn stores_as(&self, before: &Self) -> bool {
492        let _ = before;
493        false
494    }
495
496    /// Write `self` into `slot`, which holds `before`: exactly the operations
497    /// [`store`](Self::store) would write, found by comparing with `before`
498    /// where `store` would read the document.
499    ///
500    /// `before` is what [`load`](Self::load) reads from the slot now, and the
501    /// slot is as a `store` left it except where `dirty` (changes written by
502    /// someone else since) says otherwise: a slot `dirty` touched is written
503    /// as `store` would. The default is `store`. An action's write is
504    /// replayed on every replica, so an override that writes anything else
505    /// forks the document.
506    #[inline(never)]
507    fn store_changed(
508        &self,
509        before: &Self,
510        doc: &mut Doc,
511        slot: Slot<'_>,
512        dirty: &Delta,
513    ) -> Result<(), ModelError> {
514        let _ = (before, dirty);
515        self.store(doc, slot)
516    }
517
518    /// Bring a value read earlier up to date after the changes in `delta`,
519    /// re-reading only what they touched. `value` and `id` are what the
520    /// parent's slot holds now — the same object as when `self` was read, or
521    /// the parent would have read it anew. The default reads the value again,
522    /// which is right for scalars and short values.
523    ///
524    /// # Errors
525    /// Returns [`ModelError`] when the stored value has another shape.
526    #[inline(never)]
527    fn refresh(
528        &mut self,
529        doc: &Doc,
530        value: &Value<'_>,
531        id: &ObjId,
532        delta: &Delta,
533    ) -> Result<(), ModelError> {
534        let _ = delta;
535        *self = Self::load(doc, value, id)?;
536        Ok(())
537    }
538
539    /// Append the human-readable text this value carries, for search indexing.
540    fn collect_text(&self, _out: &mut Vec<String>) {}
541}
542
543/// A [`Model`] stored as the fields of a map. `#[derive(Model)]` implements
544/// it for structs with named fields; a record resource keeps its fields at
545/// the document root.
546pub trait Fields: Model {
547    /// The collection fields whose items are published as item resources
548    /// (`Collection`, `Keyed`, `Ordered`); `#[derive(Model)]` lists them.
549    const ITEM_FIELDS: &'static [&'static str] = &[];
550
551    /// # Errors
552    /// Returns [`ModelError`] when a field has another shape.
553    fn read_fields(doc: &Doc, obj: &ObjId) -> Result<Self, ModelError>;
554    fn write_fields(&self, doc: &mut Doc, obj: &ObjId) -> Result<(), ModelError>;
555
556    /// The items of each [`Collection`](crate::Collection) field, so actions
557    /// on an item can be offered on the item (see [`crate::items`]), at most
558    /// [`ITEM_PAGE`](crate::items::ITEM_PAGE) of each. `#[derive(Model)]`
559    /// lists them; the default has none.
560    fn item_collections(&self) -> Vec<crate::items::ItemCollection> {
561        Vec::new()
562    }
563
564    /// The label the item `id` of the collection field `field` is offered
565    /// under, or `None` when there is no such item.
566    fn item_label(&self, field: &str, id: &crate::Id) -> Option<String> {
567        let _ = (field, id);
568        None
569    }
570
571    /// The item of the collection field `field` that `reference` names: its
572    /// id, an address it is published under, or its label
573    /// ([`crate::table::item_named`]).
574    ///
575    /// # Errors
576    /// Refuses a reference that names none of the collection's items, saying
577    /// which there are.
578    fn item_named(&self, field: &str, reference: &str) -> Result<crate::Id, crate::Refusal> {
579        let _ = (field, reference);
580        Err(crate::Refusal::new("this record keeps no such items"))
581    }
582
583    /// [`item_named`](Self::item_named) in the words `what` names the items
584    /// by, where the collection's own field name is not what the app calls
585    /// them.
586    ///
587    /// # Errors
588    /// As [`item_named`](Self::item_named).
589    fn item_named_as(
590        &self,
591        field: &str,
592        _what: (&str, &str),
593        reference: &str,
594    ) -> Result<crate::Id, crate::Refusal> {
595        self.item_named(field, reference)
596    }
597
598    /// Whether the collection field `field` holds the item `id`
599    /// ([`crate::table::item_holds`]).
600    fn item_holds(&self, field: &str, id: &str) -> bool {
601        let _ = (field, id);
602        false
603    }
604
605    /// Whether `reference` is the id of an item of any of the record's
606    /// collections ([`crate::table::item_id_any`]).
607    fn item_id_any(&self, reference: &str) -> bool {
608        let _ = reference;
609        false
610    }
611    /// Every item of the collection fields whose type has a
612    /// `#[model(label)]`, with its text: what search indexes by default.
613    fn item_search(&self) -> Vec<crate::items::ItemText> {
614        Vec::new()
615    }
616
617    /// Apply the field edit `op` at `path` below the map `obj`; see
618    /// [`Model::edit`]. `#[derive(Model)]` routes each field segment to its
619    /// field; the default edits nothing.
620    fn edit_fields(
621        doc: &mut Doc,
622        obj: &ObjId,
623        path: &[Segment],
624        op: &EditOp,
625        cx: &mut ActionCx,
626    ) -> Result<(), ModelError> {
627        let _ = (doc, obj, path, cx);
628        Err(ModelError::unsupported(op))
629    }
630
631    /// How many items each [`Collection`](crate::Collection) field holds, by
632    /// field, in the order of [`item_collections`](Self::item_collections),
633    /// without listing them. `#[derive(Model)]` counts them; the default
634    /// lists them.
635    fn item_collection_sizes(&self) -> Vec<(&'static str, usize)> {
636        self.item_collections()
637            .iter()
638            .map(|collection| (collection.field, collection.items.len()))
639            .collect()
640    }
641
642    /// Write the fields to the map `obj`, which holds `before`: the
643    /// operations [`write_fields`](Self::write_fields) would write, with
644    /// each field compared to its value in `before` rather than read back
645    /// (see [`Model::store_changed`]). `#[derive(Model)]` writes only the
646    /// fields that changed; the default writes every field.
647    fn write_changed_fields(
648        &self,
649        before: &Self,
650        doc: &mut Doc,
651        obj: &ObjId,
652        dirty: &Delta,
653    ) -> Result<(), ModelError> {
654        let _ = (before, dirty);
655        self.write_fields(doc, obj)
656    }
657
658    /// Bring fields read earlier from the map `obj` up to date after the
659    /// changes in `delta`, re-reading only the fields they touched.
660    ///
661    /// # Errors
662    /// Returns [`ModelError`] when a touched field has another shape.
663    fn refresh_fields(&mut self, doc: &Doc, obj: &ObjId, delta: &Delta) -> Result<(), ModelError> {
664        if delta.touches(obj) {
665            *self = Self::read_fields(doc, obj)?;
666        }
667        Ok(())
668    }
669}
670
671/// Read the value under `key` of the map `obj`, or [`Model::missing`].
672///
673/// # Errors
674/// Returns [`ModelError`] located at `key`.
675#[inline(never)]
676pub fn read_key<T: Model>(doc: &Doc, obj: &ObjId, key: &str) -> Result<T, ModelError> {
677    let slot = get_slot(doc, obj, key)?;
678    load_at(doc, slot.as_ref().map(|(value, id)| (value, id)), key)
679}
680
681/// What `key` of the map `obj` holds, as [`ReadDoc::get`] answers it.
682///
683/// Every lookup and walk of the document here is a function that is not
684/// generic, and the generic ones only call it. A generic function is
685/// compiled again into each app that instantiates it, and Automerge's
686/// generic lookup and op-tree walk with it; these are compiled once, into
687/// the shared runtime every app maps.
688#[inline(never)]
689pub(crate) fn get_slot<'doc>(
690    doc: &'doc Doc,
691    obj: &ObjId,
692    key: &str,
693) -> Result<Option<(Value<'doc>, ObjId)>, ModelError> {
694    Ok(doc.get(obj, key)?)
695}
696
697/// What `index` of the list `obj` holds; not generic, as [`get_slot`].
698#[inline(never)]
699pub(crate) fn get_item<'doc>(
700    doc: &'doc Doc,
701    obj: &ObjId,
702    index: usize,
703) -> Result<Option<(Value<'doc>, ObjId)>, ModelError> {
704    Ok(doc.get(obj, index)?)
705}
706
707/// `T` read from what a key holds, or [`Model::missing`] when it holds
708/// nothing: the one generic body behind [`read_key`] and [`load_slot`].
709fn load_at<T: Model>(
710    doc: &Doc,
711    slot: Option<(&Value<'_>, &ObjId)>,
712    key: &str,
713) -> Result<T, ModelError> {
714    match slot {
715        Some((value, id)) => T::load(doc, value, id),
716        None => T::missing(),
717    }
718    .located(key)
719}
720
721/// What a key of a map holds: its current value and the id of the op that
722/// wrote it, as [`ReadDoc::get`] returns them.
723pub type MapSlot = Option<(Value<'static>, ObjId)>;
724
725/// What each of `keys` holds in the map `obj`, read in one ordered walk of
726/// the map instead of one lookup per key: a lookup opens the map anew each
727/// time, and a struct of `N` fields read field by field opens it `N` times.
728/// The walk stops once every key is found. Each slot is exactly what
729/// [`ReadDoc::get`] answers for its key (the winning value of a conflict, a
730/// counter with its increments).
731pub fn read_slots<const N: usize>(doc: &Doc, obj: &ObjId, keys: [&str; N]) -> [MapSlot; N] {
732    let mut slots = [const { None }; N];
733    fill_slots(doc, obj, &keys, &mut slots);
734    slots
735}
736
737/// [`read_slots`]' walk, out of its generic shell so that it is compiled once
738/// into the shared runtime rather than into every app that derives a
739/// [`Model`] with another number of fields.
740#[inline(never)]
741pub(crate) fn fill_slots(doc: &Doc, obj: &ObjId, keys: &[&str], slots: &mut [MapSlot]) {
742    let mut missing = keys.len();
743    if missing == 0 {
744        return;
745    }
746    for item in doc.map_range(obj, ..) {
747        let mut matched = false;
748        for (key, slot) in keys.iter().zip(slots.iter_mut()) {
749            if *key == item.key {
750                *slot = Some((item.value.clone().into_value(), item.id()));
751                missing = missing.saturating_sub(1);
752                matched = true;
753            }
754        }
755        if matched && missing == 0 {
756            break;
757        }
758    }
759}
760
761/// Every key of the map `obj` with what it holds, in key order, in one walk
762/// of the map. Not generic, for the reason [`fill_slots`] is not.
763#[inline(never)]
764pub(crate) fn map_slots(doc: &Doc, obj: &ObjId) -> Vec<(String, MapSlot)> {
765    doc.map_range(obj, ..)
766        .map(|item| {
767            let slot = Some((item.value.clone().into_value(), item.id()));
768            (item.key.into_owned(), slot)
769        })
770        .collect()
771}
772
773/// The slot at `index` of what [`read_slots`] returned, taken out of it, or
774/// an empty slot past its end. Not generic over the number of slots, so the
775/// derived reads share one copy.
776#[must_use]
777#[inline(never)]
778pub fn take_slot(slots: &mut [MapSlot], index: usize) -> MapSlot {
779    slots.get_mut(index).and_then(Option::take)
780}
781
782/// `T` read from a slot [`read_slots`] found under `key`,
783/// or [`Model::missing`]: what [`read_key`] answers for that key.
784///
785/// # Errors
786/// Returns [`ModelError`] located at `key`.
787pub fn load_slot<T: Model>(doc: &Doc, slot: MapSlot, key: &str) -> Result<T, ModelError> {
788    match slot {
789        Some((value, id)) => load_at(doc, Some((&value, &id)), key),
790        None => load_at(doc, None, key),
791    }
792}
793
794/// Bring `target`, read earlier from `key` of the map `obj`, up to date
795/// after the changes in `delta`: untouched keeps it, a written slot reads it
796/// again, a change inside the object it holds refreshes it in place.
797///
798/// # Errors
799/// Returns [`ModelError`] located at `key`.
800#[inline(never)]
801pub fn refresh_key<T: Model>(
802    target: &mut T,
803    doc: &Doc,
804    obj: &ObjId,
805    key: &str,
806    delta: &Delta,
807) -> Result<(), ModelError> {
808    match delta.key(obj, key) {
809        Touch::Untouched => Ok(()),
810        Touch::Written => {
811            *target = read_key(doc, obj, key)?;
812            Ok(())
813        }
814        Touch::Below => match get_slot(doc, obj, key)? {
815            Some((value, id)) => target.refresh(doc, &value, &id, delta),
816            None => match T::missing() {
817                Ok(missing) => {
818                    *target = missing;
819                    Ok(())
820                }
821                Err(error) => Err(error),
822            },
823        }
824        .located(key),
825    }
826}
827
828/// An error located at a key, as one function per value type rather than
829/// a closure per call.
830pub trait LocatedAt<T> {
831    /// The error, if any, located at `key`.
832    fn located(self, key: &str) -> Result<T, ModelError>;
833}
834
835impl<T> LocatedAt<T> for Result<T, ModelError> {
836    fn located(self, key: &str) -> Result<T, ModelError> {
837        match self {
838            Ok(value) => Ok(value),
839            Err(error) => Err(error.at(key)),
840        }
841    }
842}
843
844/// A value written through a vtable: code storing values of many types
845/// (the items of every collection) compiles once rather than per type.
846pub(crate) trait Stores {
847    fn store_to(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError>;
848
849    /// The value's fields as a map made with the collection's entry in one
850    /// batch, when the value can be made so (a value whose fields can): the
851    /// map, and by position the fields whose `store` writes into it after,
852    /// with whether the field itself was made with the map
853    /// ([`crate::table::Fields`]). `None` when it is written by `store_to`
854    /// whole.
855    fn made_to(&self, _: automerge::TextEncoding) -> Option<crate::table::Fields> {
856        None
857    }
858
859    /// Store the fields `later`, by position, of a value made with its entry
860    /// at `value`, into it.
861    ///
862    /// # Errors
863    /// The store's own error, located at the field.
864    fn write_later_to(
865        &self,
866        _: &mut Doc,
867        _: &ObjId,
868        _: &[(usize, bool)],
869    ) -> Result<(), ModelError> {
870        Ok(())
871    }
872}
873
874impl<T: Model> Stores for T {
875    fn store_to(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
876        self.store(doc, slot)
877    }
878
879    fn made_to(&self, encoding: automerge::TextEncoding) -> Option<crate::table::Fields> {
880        let desc = crate::table::described(T::TABLE).ok()?;
881        crate::table::fresh::fields_made_of(desc, self, encoding)
882    }
883
884    fn write_later_to(
885        &self,
886        doc: &mut Doc,
887        value: &ObjId,
888        later: &[(usize, bool)],
889    ) -> Result<(), ModelError> {
890        let desc = crate::table::described(T::TABLE)?;
891        crate::table::fresh::write_later(desc, self, doc, value, later)
892    }
893}
894
895/// Write `value` under `key` of the map `obj`.
896///
897/// # Errors
898/// Returns [`ModelError`] located at `key`.
899#[inline(never)]
900pub fn write_key<T: Model>(
901    doc: &mut Doc,
902    obj: &ObjId,
903    key: &str,
904    value: &T,
905) -> Result<(), ModelError> {
906    value.store(doc, Slot::Key(obj, key)).located(key)
907}
908
909/// [`Model::edit`] for a value edited only as a whole: `set` at its own
910/// path, checked before it is written.
911#[inline(never)]
912pub fn edit_whole<T: Model>(
913    doc: &mut Doc,
914    slot: Slot<'_>,
915    path: &[Segment],
916    op: &EditOp,
917) -> Result<(), ModelError> {
918    if let Some(segment) = path.first() {
919        return Err(ModelError::invalid(format!(
920            "nothing inside this value is called `{segment}`"
921        )));
922    }
923    match op {
924        EditOp::Set { value } if value.is_null() && !T::NULLABLE => Err(ModelError::invalid(
925            "`null` is no value of this field: set a value of its type",
926        )),
927        EditOp::Set { value } => {
928            let value = T::from_json(value)?;
929            value.check().map_err(ModelError::refused)?;
930            value.store(doc, slot)
931        }
932        other => Err(ModelError::unsupported(other)),
933    }
934}
935
936/// The JSON shape error of [`Model::from_json`].
937pub(crate) fn json_shape(expected: &'static str) -> ModelError {
938    ModelError::shape(expected)
939}
940
941/// Implements the path items of a type edited whole or through its own
942/// operations: its paths are the [`Path`] itself.
943#[macro_export]
944macro_rules! leaf_paths {
945    () => {
946        type Paths<R> = $crate::Path<R, Self>;
947        fn paths_at<R>(path: $crate::Path<R, Self>) -> $crate::Path<R, Self> {
948            path
949        }
950    };
951}
952pub(crate) use crate::leaf_paths;
953
954/// Implements every [`Model`] function a type's [`TABLE`](Model::TABLE)
955/// runs by forwarding it there: one set of functions for every type of its
956/// kind (a container over its item type's table, a unit enum, a value
957/// stored as JSON text).
958#[doc(hidden)]
959#[macro_export]
960macro_rules! __table_functions {
961    () => {
962        #[inline]
963        fn op_coalesces(
964            path: &[$crate::path::Segment],
965            previous: &$crate::__private::serde_json::Value,
966            next: &$crate::__private::serde_json::Value,
967        ) -> ::core::option::Option<bool> {
968            $crate::table::Run(Self::TABLE).op_coalesces(path, previous, next)
969        }
970        #[inline]
971        fn op_continuable(
972            path: &[$crate::path::Segment],
973            op: &$crate::__private::serde_json::Value,
974        ) -> ::core::option::Option<bool> {
975            $crate::table::Run(Self::TABLE).op_continuable(path, op)
976        }
977        #[inline]
978        fn op_describe(
979            path: &[$crate::path::Segment],
980            op: &$crate::__private::serde_json::Value,
981        ) -> ::core::option::Option<$crate::path::OpDescription> {
982            $crate::table::Run(Self::TABLE).op_describe(path, op)
983        }
984        #[inline]
985        fn op_lands(
986            &self,
987            path: &[$crate::path::Segment],
988            op: &$crate::__private::serde_json::Value,
989        ) -> ::core::option::Option<$crate::Place> {
990            $crate::table::Run(Self::TABLE).op_lands(self, path, op)
991        }
992        #[inline]
993        fn op_schemas(
994            prefix: &str,
995            out: &mut ::std::vec::Vec<(
996                ::std::string::String,
997                $crate::__private::serde_json::Value,
998            )>,
999        ) {
1000            $crate::table::Run(Self::TABLE).op_schemas(prefix, out);
1001        }
1002        #[inline]
1003        fn to_json(&self) -> $crate::__private::serde_json::Value {
1004            $crate::table::Run(Self::TABLE).to_json(self)
1005        }
1006        #[inline]
1007        fn from_json(
1008            value: &$crate::__private::serde_json::Value,
1009        ) -> ::core::result::Result<Self, $crate::model::ModelError> {
1010            $crate::table::Run(Self::TABLE).from_json(value)
1011        }
1012        #[inline]
1013        fn edit(
1014            doc: &mut $crate::model::Doc,
1015            slot: $crate::model::Slot<'_>,
1016            path: &[$crate::path::Segment],
1017            op: &$crate::path::EditOp,
1018            cx: &mut $crate::action::ActionCx,
1019        ) -> ::core::result::Result<(), $crate::model::ModelError> {
1020            $crate::table::Run(Self::TABLE).edit(doc, slot, path, op, cx)
1021        }
1022        #[inline]
1023        fn check(&self) -> ::core::result::Result<(), $crate::action::Refusal> {
1024            $crate::table::Run(Self::TABLE).check(self)
1025        }
1026        #[inline]
1027        fn get_at(
1028            &self,
1029            path: &[$crate::path::Segment],
1030        ) -> ::core::option::Option<&dyn ::core::any::Any> {
1031            $crate::table::Run(Self::TABLE).get_at(self, path)
1032        }
1033        #[inline]
1034        fn diff<R>(
1035            &self,
1036            after: &Self,
1037            path: &[$crate::path::Segment],
1038            out: &mut ::std::vec::Vec<$crate::Edit<R>>,
1039        ) {
1040            $crate::table::Run(Self::TABLE).diff(self, after, path, out);
1041        }
1042        #[inline]
1043        fn load(
1044            doc: &$crate::model::Doc,
1045            value: &$crate::__private::Value<'_>,
1046            id: &$crate::__private::ObjId,
1047        ) -> ::core::result::Result<Self, $crate::model::ModelError> {
1048            $crate::table::Run(Self::TABLE).load(doc, value, id)
1049        }
1050        #[inline]
1051        fn store(
1052            &self,
1053            doc: &mut $crate::model::Doc,
1054            slot: $crate::model::Slot<'_>,
1055        ) -> ::core::result::Result<(), $crate::model::ModelError> {
1056            $crate::table::Run(Self::TABLE).store(self, doc, slot)
1057        }
1058        #[inline]
1059        fn stores_as(&self, before: &Self) -> bool {
1060            $crate::table::Run(Self::TABLE).stores_as(self, before)
1061        }
1062        #[inline]
1063        fn store_changed(
1064            &self,
1065            before: &Self,
1066            doc: &mut $crate::model::Doc,
1067            slot: $crate::model::Slot<'_>,
1068            dirty: &$crate::delta::Delta,
1069        ) -> ::core::result::Result<(), $crate::model::ModelError> {
1070            $crate::table::Run(Self::TABLE).store_changed(self, before, doc, slot, dirty)
1071        }
1072        #[inline]
1073        fn refresh(
1074            &mut self,
1075            doc: &$crate::model::Doc,
1076            value: &$crate::__private::Value<'_>,
1077            id: &$crate::__private::ObjId,
1078            delta: &$crate::delta::Delta,
1079        ) -> ::core::result::Result<(), $crate::model::ModelError> {
1080            $crate::table::Run(Self::TABLE).refresh(self, doc, value, id, delta)
1081        }
1082        #[inline]
1083        fn collect_text(&self, out: &mut ::std::vec::Vec<::std::string::String>) {
1084            $crate::table::Run(Self::TABLE).collect_text(self, out);
1085        }
1086    };
1087}
1088
1089/// Implements [`Model`] (and [`Settable`]) for serde types stored whole as
1090/// one JSON string, last writer wins: values with no meaningful concurrent
1091/// merge (a tone curve, a keyframe track). The types need `Serialize`,
1092/// `Deserialize`, `Default` (the value of an absent slot) and `PartialEq`
1093/// holding only between values of equal JSON forms, as a derived one does:
1094/// the edits between two copies compare each value in memory, and serialise
1095/// only the ones that differ.
1096///
1097/// A type whose JSON form is one value of a known type names its schema and
1098/// its [`FieldType`](crate::FieldType) variant
1099/// (`json_model!(ResetDay => {"type": "integer"}, Int)`): its setter then
1100/// takes that value, and a surface publishes the field as that type. A type
1101/// that also derives [`JsonSchema`](crate::JsonSchema) publishes the record
1102/// that schema describes (`json_model!(TabletConfig => named)`), so a view
1103/// reads its fields rather than an opaque value.
1104#[macro_export]
1105macro_rules! json_model {
1106    ($ty:ty => named) => {
1107        impl $crate::Settable for $ty {}
1108        impl $crate::Model for $ty {
1109            $crate::leaf_paths!();
1110            const NULLABLE: bool = true;
1111            const TABLE: &'static $crate::table::ModelTable =
1112                &$crate::table::ModelTable::of_json(&$crate::table::JsonOf::<$ty>::COMPARED);
1113            $crate::__table_functions!();
1114            fn missing() -> ::core::result::Result<Self, $crate::ModelError> {
1115                ::core::result::Result::Ok(<Self as ::core::default::Default>::default())
1116            }
1117            fn field_type(types: &mut $crate::TypeSet) -> $crate::FieldType {
1118                <$ty as $crate::JsonSchema>::field_type(types)
1119            }
1120        }
1121    };
1122    ($ty:ty => $schema:tt, $field_type:ident) => {
1123        impl $crate::Settable for $ty {}
1124        impl $crate::Model for $ty {
1125            $crate::leaf_paths!();
1126            const NULLABLE: bool = true;
1127            const TABLE: &'static $crate::table::ModelTable =
1128                &$crate::table::ModelTable::of_json(&$crate::table::JsonOf::<$ty>::COMPARED);
1129            $crate::__table_functions!();
1130            fn missing() -> ::core::result::Result<Self, $crate::ModelError> {
1131                ::core::result::Result::Ok(<Self as ::core::default::Default>::default())
1132            }
1133            fn value_schema() -> $crate::__private::serde_json::Value {
1134                $crate::__private::serde_json::json!($schema)
1135            }
1136            fn field_type(types: &mut $crate::TypeSet) -> $crate::FieldType {
1137                let _ = types;
1138                $crate::FieldType::$field_type
1139            }
1140        }
1141    };
1142    ($($ty:ty),* $(,)?) => {$(
1143        impl $crate::Settable for $ty {}
1144        impl $crate::Model for $ty {
1145            $crate::leaf_paths!();
1146            // Its serde form decides; `null` reads as its default.
1147            const NULLABLE: bool = true;
1148            // Run by one set of functions for every value stored as JSON text.
1149            const TABLE: &'static $crate::table::ModelTable =
1150                &$crate::table::ModelTable::of_json(&$crate::table::JsonOf::<$ty>::COMPARED);
1151            $crate::__table_functions!();
1152            fn missing() -> ::core::result::Result<Self, $crate::ModelError> {
1153                ::core::result::Result::Ok(<Self as ::core::default::Default>::default())
1154            }
1155        }
1156    )*};
1157}
1158
1159/// Write `value` under `key` of the map `obj`, which holds `before`: the
1160/// operations [`write_key`] would write, without reading back what did not
1161/// change. See [`Model::store_changed`].
1162///
1163/// # Errors
1164/// Returns [`ModelError`] located at `key`.
1165#[inline(never)]
1166pub fn write_key_changed<T: Model>(
1167    doc: &mut Doc,
1168    obj: &ObjId,
1169    key: &str,
1170    value: &T,
1171    before: &T,
1172    dirty: &Delta,
1173) -> Result<(), ModelError> {
1174    match dirty.key(obj, key) {
1175        Touch::Written => write_key(doc, obj, key, value),
1176        Touch::Untouched if value.stores_as(before) => Ok(()),
1177        Touch::Untouched | Touch::Below => value
1178            .store_changed(before, doc, Slot::Key(obj, key), dirty)
1179            .located(key),
1180    }
1181}
1182
1183/// The key under which a data enum (`#[derive(Model)]` on an enum with
1184/// fields) names its variant, beside the variant's fields. No field may be
1185/// stored under a key beginning with `$`, so it never collides with one.
1186pub const VARIANT_KEY: &str = "$variant";
1187
1188/// The map a data enum's variant `variant` is stored in, in `slot`: made
1189/// when the slot holds anything else, its variant name written, and every
1190/// key but the name and `fields` (the keys this variant stores its fields
1191/// under) removed: another variant's fields, and the flat keys an older
1192/// layout stored fields under. Concurrent edits of the same variant merge
1193/// field by field, and a change of variant is one last-writer-wins write of
1194/// its name.
1195#[doc(hidden)]
1196#[inline(never)]
1197pub fn variant_map(
1198    doc: &mut Doc,
1199    slot: Slot<'_>,
1200    variant: &str,
1201    fields: &[&str],
1202) -> Result<ObjId, ModelError> {
1203    let obj = slot.object(doc, ObjType::Map)?;
1204    Slot::Key(&obj, VARIANT_KEY).put_scalar(doc, ScalarValue::Str(variant.into()))?;
1205    let stale: Vec<String> = doc
1206        .keys(&obj)
1207        .filter(|key| key.as_str() != VARIANT_KEY && !fields.contains(&key.as_str()))
1208        .collect();
1209    for key in stale {
1210        doc.delete(&obj, key.as_str())?;
1211    }
1212    Ok(obj)
1213}
1214
1215/// The field `key` of a data enum's variant, stored under `storage` of the
1216/// map `obj` (a key of its variant's own), or [`Model::missing`].
1217///
1218/// A document of the older layout stored each field under its bare name
1219/// beside the variant's: when `storage` holds nothing, that key is read, as
1220/// it was written. [`variant_map`] removes it the next time the value is
1221/// stored.
1222///
1223/// # Errors
1224/// Returns [`ModelError`] located at `key`.
1225#[doc(hidden)]
1226pub fn read_variant_field<T: Model>(
1227    doc: &Doc,
1228    obj: &ObjId,
1229    storage: &str,
1230    key: &str,
1231) -> Result<T, ModelError> {
1232    let slot = match get_slot(doc, obj, storage)? {
1233        Some(slot) => Some(slot),
1234        None => get_slot(doc, obj, key)?,
1235    };
1236    load_at(doc, slot.as_ref().map(|(value, id)| (value, id)), key)
1237}
1238
1239/// Write the field `key` of a data enum's variant under `storage` of the
1240/// map `obj`.
1241///
1242/// # Errors
1243/// Returns [`ModelError`] located at `key`.
1244#[doc(hidden)]
1245pub fn write_variant_field<T: Model>(
1246    doc: &mut Doc,
1247    obj: &ObjId,
1248    storage: &str,
1249    key: &str,
1250    value: &T,
1251) -> Result<(), ModelError> {
1252    value.store(doc, Slot::Key(obj, storage)).located(key)
1253}
1254
1255/// [`read_variant_field`] of a field stored whole (`#[model(atom)]`).
1256///
1257/// # Errors
1258/// Returns [`ModelError`] located at `key`.
1259#[doc(hidden)]
1260pub fn read_variant_atom<T: crate::table::Atomic>(
1261    doc: &Doc,
1262    obj: &ObjId,
1263    storage: &str,
1264    key: &str,
1265) -> Result<T, ModelError> {
1266    let slot = match get_slot(doc, obj, storage)? {
1267        Some(slot) => Some(slot),
1268        None => get_slot(doc, obj, key)?,
1269    };
1270    let atom = crate::table::Run(T::ATOM);
1271    match slot {
1272        Some((value, id)) => atom.load(doc, &value, &id),
1273        None => atom.missing(),
1274    }
1275    .located(key)
1276}
1277
1278/// [`write_variant_field`] of a field stored whole (`#[model(atom)]`).
1279///
1280/// # Errors
1281/// Returns [`ModelError`] located at `key`.
1282#[doc(hidden)]
1283pub fn write_variant_atom<T: crate::table::Atomic>(
1284    doc: &mut Doc,
1285    obj: &ObjId,
1286    storage: &str,
1287    key: &str,
1288    value: &T,
1289) -> Result<(), ModelError> {
1290    crate::table::Run(T::ATOM)
1291        .store(value, doc, Slot::Key(obj, storage))
1292        .located(key)
1293}
1294
1295/// The variant a data enum stored at `value` (the object `id`) names.
1296#[doc(hidden)]
1297#[inline(never)]
1298pub fn stored_variant(doc: &Doc, value: &Value<'_>, id: &ObjId) -> Result<String, ModelError> {
1299    if !matches!(value, Value::Object(ObjType::Map)) {
1300        return Err(ModelError::shape("a map naming its variant"));
1301    }
1302    match doc.get(id, VARIANT_KEY)? {
1303        Some((Value::Scalar(name), _)) => match name.as_ref() {
1304            ScalarValue::Str(name) => Ok(name.to_string()),
1305            _ => Err(ModelError::shape("a variant name").at(VARIANT_KEY)),
1306        },
1307        _ => Err(ModelError::shape("a variant name").at(VARIANT_KEY)),
1308    }
1309}
1310
1311/// The variant name and fields of a data enum's JSON form,
1312/// `{"$variant": name, field: value, ..}`.
1313#[doc(hidden)]
1314#[inline(never)]
1315pub fn json_variant(
1316    value: &serde_json::Value,
1317) -> Result<(&str, &serde_json::Map<String, serde_json::Value>), ModelError> {
1318    let serde_json::Value::Object(fields) = value else {
1319        return Err(json_shape("an object naming its variant"));
1320    };
1321    match fields.get(VARIANT_KEY) {
1322        Some(serde_json::Value::String(name)) => Ok((name.as_str(), fields)),
1323        _ => Err(json_shape("a variant name").at(VARIANT_KEY)),
1324    }
1325}
1326
1327/// The field `key` of a data enum's JSON form, or [`Model::missing`].
1328///
1329/// # Errors
1330/// Returns [`ModelError`] located at `key`.
1331#[doc(hidden)]
1332pub fn json_field<T: Model>(
1333    fields: &serde_json::Map<String, serde_json::Value>,
1334    key: &str,
1335) -> Result<T, ModelError> {
1336    match fields.get(key) {
1337        Some(value) => T::from_json(value),
1338        None => T::missing(),
1339    }
1340    .located(key)
1341}
1342
1343/// A data enum's JSON form: its variant name and its fields.
1344#[doc(hidden)]
1345#[must_use]
1346#[inline(never)]
1347pub fn json_of_variant(variant: &str, fields: Vec<(&str, serde_json::Value)>) -> serde_json::Value {
1348    let mut map = serde_json::Map::new();
1349    map.insert(VARIANT_KEY.to_owned(), serde_json::Value::from(variant));
1350    for (key, value) in fields {
1351        map.insert(key.to_owned(), value);
1352    }
1353    serde_json::Value::Object(map)
1354}
1355
1356/// That a data enum names a variant it does not have.
1357#[doc(hidden)]
1358#[must_use]
1359#[inline(never)]
1360pub fn unknown_variant(variant: &str) -> ModelError {
1361    ModelError::invalid(format!("no variant `{variant}`")).at(VARIANT_KEY)
1362}
1363
1364/// The JSON Schema of a data enum's variant `variant` with the fields
1365/// `fields` as `(key, schema)`.
1366#[doc(hidden)]
1367#[must_use]
1368#[inline(never)]
1369pub fn variant_schema(variant: &str, fields: Vec<(&str, serde_json::Value)>) -> serde_json::Value {
1370    let mut properties = vec![(VARIANT_KEY, crate::schema::constant(variant), true)];
1371    properties.extend(fields.into_iter().map(|(key, schema)| (key, schema, false)));
1372    crate::schema::object(properties)
1373}
1374
1375fn scalar<'v>(value: &'v Value<'_>) -> Option<&'v ScalarValue> {
1376    match value {
1377        Value::Scalar(scalar) => Some(scalar.as_ref()),
1378        Value::Object(_) => None,
1379    }
1380}
1381
1382impl Settable for bool {}
1383impl Model for bool {
1384    const SCALAR: bool = true;
1385    crate::__own_table!(bool);
1386    fn value_schema() -> serde_json::Value {
1387        serde_json::json!({"type": "boolean"})
1388    }
1389    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
1390        let _ = types;
1391        crate::FieldType::Bool
1392    }
1393    leaf_paths!();
1394    #[inline(never)]
1395    fn to_json(&self) -> serde_json::Value {
1396        serde_json::Value::Bool(*self)
1397    }
1398    #[inline(never)]
1399    fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
1400        match value {
1401            serde_json::Value::Bool(value) => Ok(*value),
1402            serde_json::Value::Null => Ok(false),
1403            _ => Err(json_shape("a boolean")),
1404        }
1405    }
1406    #[inline(never)]
1407    fn load(_: &Doc, value: &Value<'_>, _: &ObjId) -> Result<Self, ModelError> {
1408        match scalar(value) {
1409            Some(ScalarValue::Boolean(value)) => Ok(*value),
1410            Some(ScalarValue::Null) => Ok(false),
1411            _ => Err(ModelError::shape("a boolean")),
1412        }
1413    }
1414    fn missing() -> Result<Self, ModelError> {
1415        Ok(false)
1416    }
1417    #[inline(never)]
1418    fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
1419        slot.put_scalar(doc, ScalarValue::Boolean(*self))
1420    }
1421    fn fresh(&self, _: automerge::TextEncoding) -> Fresh {
1422        Fresh::scalar(ScalarValue::Boolean(*self))
1423    }
1424    #[inline(never)]
1425    fn stores_as(&self, before: &Self) -> bool {
1426        self == before
1427    }
1428}
1429
1430macro_rules! integer_model {
1431    ($($ty:ty),*) => {$(
1432        impl Settable for $ty {}
1433        impl Model for $ty {
1434            const SCALAR: bool = true;
1435            crate::__own_table!($ty);
1436            fn value_schema() -> serde_json::Value {
1437                serde_json::json!({"type": "integer"})
1438            }
1439            fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
1440                let _ = types;
1441                crate::FieldType::Int
1442            }
1443            leaf_paths!();
1444            fn to_json(&self) -> serde_json::Value {
1445                serde_json::Value::from(*self)
1446            }
1447            fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
1448                let wide: i128 = match value {
1449                    serde_json::Value::Number(number) => number
1450                        .as_i64()
1451                        .map(i128::from)
1452                        .or_else(|| number.as_u64().map(i128::from))
1453                        .ok_or_else(|| json_shape("an integer"))?,
1454                    serde_json::Value::Null => 0,
1455                    _ => return Err(json_shape("an integer")),
1456                };
1457                <$ty>::try_from(wide).map_err(|_| ModelError::invalid("integer out of range"))
1458            }
1459            fn load(_: &Doc, value: &Value<'_>, _: &ObjId) -> Result<Self, ModelError> {
1460                let wide: i128 = match scalar(value) {
1461                    Some(ScalarValue::Int(value)) => i128::from(*value),
1462                    Some(ScalarValue::Uint(value)) => i128::from(*value),
1463                    Some(ScalarValue::Counter(counter)) => i128::from(i64::from(counter)),
1464                    Some(ScalarValue::Timestamp(value)) => i128::from(*value),
1465                    Some(ScalarValue::Null) => 0,
1466                    _ => return Err(ModelError::shape("an integer")),
1467                };
1468                <$ty>::try_from(wide).map_err(|_| ModelError::invalid("integer out of range"))
1469            }
1470            fn missing() -> Result<Self, ModelError> {
1471                Ok(0)
1472            }
1473            fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
1474                let value = i64::try_from(*self)
1475                    .map(ScalarValue::Int)
1476                    .or_else(|_| u64::try_from(*self).map(ScalarValue::Uint))
1477                    .map_err(|_| ModelError::invalid("integer out of range"))?;
1478                slot.put_scalar(doc, value)
1479            }
1480            fn fresh(&self, _: automerge::TextEncoding) -> Fresh {
1481                match i64::try_from(*self) {
1482                    Ok(value) => Fresh::scalar(ScalarValue::Int(value)),
1483                    Err(_) => u64::try_from(*self)
1484                        .map_or(Fresh::Store, |value| Fresh::scalar(ScalarValue::Uint(value))),
1485                }
1486            }
1487            fn stores_as(&self, before: &Self) -> bool {
1488                self == before
1489            }
1490        }
1491    )*};
1492}
1493integer_model!(i8, i16, i32, i64, u8, u16, u32, u64, usize, isize);
1494
1495impl Settable for f64 {}
1496impl Model for f64 {
1497    const SCALAR: bool = true;
1498    crate::__own_table!(f64);
1499    fn value_schema() -> serde_json::Value {
1500        serde_json::json!({"type": "number"})
1501    }
1502    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
1503        let _ = types;
1504        crate::FieldType::Float
1505    }
1506    leaf_paths!();
1507    #[inline(never)]
1508    fn to_json(&self) -> serde_json::Value {
1509        serde_json::Number::from_f64(*self)
1510            .map_or(serde_json::Value::Null, serde_json::Value::Number)
1511    }
1512    #[inline(never)]
1513    fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
1514        match value {
1515            serde_json::Value::Number(number) => {
1516                number.as_f64().ok_or_else(|| json_shape("a number"))
1517            }
1518            serde_json::Value::Null => Ok(0.0),
1519            _ => Err(json_shape("a number")),
1520        }
1521    }
1522    #[allow(
1523        clippy::cast_precision_loss,
1524        reason = "integers written by older schemas widen to the stored float"
1525    )]
1526    #[inline(never)]
1527    fn load(_: &Doc, value: &Value<'_>, _: &ObjId) -> Result<Self, ModelError> {
1528        match scalar(value) {
1529            Some(ScalarValue::F64(value)) => Ok(*value),
1530            Some(ScalarValue::Int(value)) => Ok(*value as f64),
1531            Some(ScalarValue::Uint(value)) => Ok(*value as f64),
1532            Some(ScalarValue::Null) => Ok(0.0),
1533            _ => Err(ModelError::shape("a number")),
1534        }
1535    }
1536    fn missing() -> Result<Self, ModelError> {
1537        Ok(0.0)
1538    }
1539    #[inline(never)]
1540    fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
1541        slot.put_scalar(doc, ScalarValue::F64(*self))
1542    }
1543    fn fresh(&self, _: automerge::TextEncoding) -> Fresh {
1544        Fresh::scalar(ScalarValue::F64(*self))
1545    }
1546    #[inline(never)]
1547    fn stores_as(&self, before: &Self) -> bool {
1548        self.to_bits() == before.to_bits()
1549    }
1550}
1551
1552impl Settable for f32 {}
1553impl Model for f32 {
1554    const SCALAR: bool = true;
1555    crate::__own_table!(f32);
1556    fn value_schema() -> serde_json::Value {
1557        serde_json::json!({"type": "number"})
1558    }
1559    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
1560        let _ = types;
1561        crate::FieldType::Float
1562    }
1563    leaf_paths!();
1564    #[inline(never)]
1565    fn to_json(&self) -> serde_json::Value {
1566        f64::from(*self).to_json()
1567    }
1568    #[allow(
1569        clippy::cast_possible_truncation,
1570        reason = "an f32 field stores what it wrote, widened"
1571    )]
1572    #[inline(never)]
1573    fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
1574        f64::from_json(value).map(|value| value as f32)
1575    }
1576    #[allow(
1577        clippy::cast_possible_truncation,
1578        reason = "an f32 field stores what it wrote, widened"
1579    )]
1580    #[inline(never)]
1581    fn load(doc: &Doc, value: &Value<'_>, id: &ObjId) -> Result<Self, ModelError> {
1582        f64::load(doc, value, id).map(|value| value as f32)
1583    }
1584    fn missing() -> Result<Self, ModelError> {
1585        Ok(0.0)
1586    }
1587    #[inline(never)]
1588    fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
1589        f64::from(*self).store(doc, slot)
1590    }
1591    fn fresh(&self, encoding: automerge::TextEncoding) -> Fresh {
1592        f64::from(*self).fresh(encoding)
1593    }
1594    #[inline(never)]
1595    fn stores_as(&self, before: &Self) -> bool {
1596        self.to_bits() == before.to_bits()
1597    }
1598}
1599
1600/// Collaborative text: stored as an Automerge `Text` object and updated by
1601/// splicing only the changed span, so concurrent typing in one field merges
1602/// character by character. A string scalar written by an older schema reads
1603/// too and is upgraded on the first write.
1604impl Settable for String {}
1605impl Model for String {
1606    crate::__own_table!(String);
1607    fn value_schema() -> serde_json::Value {
1608        serde_json::json!({"type": "string"})
1609    }
1610    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
1611        let _ = types;
1612        crate::FieldType::Text
1613    }
1614    leaf_paths!();
1615    #[inline(never)]
1616    fn to_json(&self) -> serde_json::Value {
1617        serde_json::Value::String(self.clone())
1618    }
1619    #[inline(never)]
1620    fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
1621        match value {
1622            serde_json::Value::String(text) => Ok(text.clone()),
1623            serde_json::Value::Null => Ok(Self::new()),
1624            _ => Err(json_shape("text")),
1625        }
1626    }
1627    #[inline(never)]
1628    fn edit(
1629        doc: &mut Doc,
1630        slot: Slot<'_>,
1631        path: &[Segment],
1632        op: &EditOp,
1633        _cx: &mut ActionCx,
1634    ) -> Result<(), ModelError> {
1635        let edit = match op {
1636            EditOp::Splice { at, delete, insert } if path.is_empty() => crate::TextEdit::Splice {
1637                at: *at,
1638                delete: *delete,
1639                insert: insert.clone(),
1640            },
1641            EditOp::Replace { text } if path.is_empty() => {
1642                crate::TextEdit::ReplaceText { text: text.clone() }
1643            }
1644            _ => return edit_whole::<Self>(doc, slot, path, op),
1645        };
1646        let text = slot.object(doc, ObjType::Text)?;
1647        edit.apply_under(doc, &text).map_err(|error| match error {
1648            tilo_actions::ActionError::Refused(reason) => ModelError::Refused(reason),
1649            tilo_actions::ActionError::Declined(reason) => ModelError::Declined(reason),
1650            other => ModelError::invalid(other.to_string()),
1651        })
1652    }
1653    #[inline(never)]
1654    fn load(doc: &Doc, value: &Value<'_>, id: &ObjId) -> Result<Self, ModelError> {
1655        match value {
1656            Value::Object(ObjType::Text) => Ok(doc.text(id)?),
1657            Value::Scalar(scalar) => match scalar.as_ref() {
1658                ScalarValue::Str(text) => Ok(text.to_string()),
1659                ScalarValue::Null => Ok(Self::new()),
1660                _ => Err(ModelError::shape("text")),
1661            },
1662            Value::Object(_) => Err(ModelError::shape("text")),
1663        }
1664    }
1665    fn missing() -> Result<Self, ModelError> {
1666        Ok(Self::new())
1667    }
1668    #[inline(never)]
1669    fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
1670        let text = slot.object(doc, ObjType::Text)?;
1671        let current = doc.text(&text)?;
1672        if current != *self {
1673            splice_changed_span(doc, &text, &current, self)?;
1674        }
1675        Ok(())
1676    }
1677    /// Its text, made marked as its writer's.
1678    fn fresh(&self, encoding: automerge::TextEncoding) -> Fresh {
1679        Fresh::Value(automerge::hydrate::Value::Text(crate::text::authored(
1680            encoding, self,
1681        )))
1682    }
1683    #[inline(never)]
1684    fn stores_as(&self, before: &Self) -> bool {
1685        self == before
1686    }
1687    /// The one splice [`store`](Model::store) makes, found from `before`
1688    /// instead of reading the whole text back.
1689    #[inline(never)]
1690    fn store_changed(
1691        &self,
1692        before: &Self,
1693        doc: &mut Doc,
1694        slot: Slot<'_>,
1695        _dirty: &Delta,
1696    ) -> Result<(), ModelError> {
1697        let text = slot.object(doc, ObjType::Text)?;
1698        if before != self {
1699            splice_changed_span(doc, &text, before, self)?;
1700        }
1701        Ok(())
1702    }
1703    fn collect_text(&self, out: &mut Vec<String>) {
1704        if !self.is_empty() {
1705            out.push(self.clone());
1706        }
1707    }
1708}
1709
1710/// Replace the one span where `old` and `new` differ (after their common
1711/// prefix, before their common suffix) with a single splice.
1712///
1713/// One contiguous splice is what an edit is — typing, pasting, deleting a
1714/// selection — so it merges with a member's concurrent edits elsewhere
1715/// in the text, and it is a change the host's undo inverts exactly. (A
1716/// character-level diff of two unrelated strings scatters one edit across
1717/// many splices.)
1718///
1719/// So a whole-value `set` (or `replace`) racing another writer merges the
1720/// way two people typing do: edits to different parts both stay, and where
1721/// both rewrote the same span, the text either deleted stays deleted and
1722/// each one's new text comes through whole, one after the other. Automerge
1723/// orders concurrent insertions at one place by change and never mixes
1724/// their characters.
1725fn splice_changed_span(
1726    doc: &mut Doc,
1727    text: &ObjId,
1728    old: &str,
1729    new: &str,
1730) -> Result<(), ModelError> {
1731    let width = |part: &str| match doc.text_encoding() {
1732        automerge::TextEncoding::UnicodeCodePoint => Some(part.chars().count()),
1733        automerge::TextEncoding::Utf8CodeUnit => Some(part.len()),
1734        automerge::TextEncoding::Utf16CodeUnit => Some(part.encode_utf16().count()),
1735        automerge::TextEncoding::GraphemeCluster => None,
1736    };
1737    let prefix = old
1738        .char_indices()
1739        .zip(new.chars())
1740        .find(|((_, a), b)| a != b)
1741        .map_or_else(|| old.len().min(new.len()), |((index, _), _)| index);
1742    let prefix = (0..=prefix)
1743        .rev()
1744        .find(|&index| old.is_char_boundary(index) && new.is_char_boundary(index))
1745        .unwrap_or(0);
1746    let (old_rest, new_rest) = (
1747        old.get(prefix..).unwrap_or(""),
1748        new.get(prefix..).unwrap_or(""),
1749    );
1750    let suffix = old_rest
1751        .chars()
1752        .rev()
1753        .zip(new_rest.chars().rev())
1754        .take_while(|(a, b)| a == b)
1755        .map(|(a, _)| a.len_utf8())
1756        .sum::<usize>();
1757    let removed = old_rest
1758        .get(..old_rest.len().saturating_sub(suffix))
1759        .unwrap_or("");
1760    let inserted = new_rest
1761        .get(..new_rest.len().saturating_sub(suffix))
1762        .unwrap_or("");
1763    match (width(old.get(..prefix).unwrap_or("")), width(removed)) {
1764        (Some(position), Some(deleted)) => {
1765            let deleted =
1766                isize::try_from(deleted).map_err(|_| ModelError::invalid("text too long"))?;
1767            doc.splice_text(text, position, deleted, inserted)?;
1768            // The characters written are the writer's, as a plain text edit's are: a field's
1769            // stored text carries who wrote each run, so a member's and an agent's words
1770            // show in their colour wherever the text is read.
1771            crate::text::mark_authored(doc, text, position, inserted)
1772                .map_err(|error| ModelError::invalid(error.to_string()))?;
1773        }
1774        _ => doc.update_text(text, new)?,
1775    }
1776    Ok(())
1777}
1778
1779/// A string written whole: last writer wins. For identifiers, enum-like
1780/// codes and short values where character merging would be wrong.
1781#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
1782pub struct Atom(pub String);
1783
1784impl Settable for Atom {}
1785impl Model for Atom {
1786    const SCALAR: bool = true;
1787    crate::__own_table!(Atom);
1788    fn value_schema() -> serde_json::Value {
1789        serde_json::json!({"type": "string"})
1790    }
1791    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
1792        let _ = types;
1793        crate::FieldType::Text
1794    }
1795    leaf_paths!();
1796    #[inline(never)]
1797    fn to_json(&self) -> serde_json::Value {
1798        serde_json::Value::String(self.0.clone())
1799    }
1800    #[inline(never)]
1801    fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
1802        String::from_json(value).map(Self)
1803    }
1804    #[inline(never)]
1805    fn load(doc: &Doc, value: &Value<'_>, id: &ObjId) -> Result<Self, ModelError> {
1806        String::load(doc, value, id).map(Self)
1807    }
1808    fn missing() -> Result<Self, ModelError> {
1809        Ok(Self::default())
1810    }
1811    #[inline(never)]
1812    fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
1813        slot.put_scalar(doc, ScalarValue::Str(self.0.as_str().into()))
1814    }
1815    fn fresh(&self, _: automerge::TextEncoding) -> Fresh {
1816        Fresh::scalar(ScalarValue::Str(self.0.as_str().into()))
1817    }
1818    fn collect_text(&self, out: &mut Vec<String>) {
1819        if !self.0.is_empty() {
1820            out.push(self.0.clone());
1821        }
1822    }
1823    #[inline(never)]
1824    fn stores_as(&self, before: &Self) -> bool {
1825        self == before
1826    }
1827}
1828
1829impl Settable for uuid::Uuid {}
1830impl Model for uuid::Uuid {
1831    crate::__own_table!(uuid::Uuid);
1832    fn value_schema() -> serde_json::Value {
1833        serde_json::json!({"type": "string", "format": "uuid"})
1834    }
1835    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
1836        let _ = types;
1837        crate::FieldType::Text
1838    }
1839    leaf_paths!();
1840    #[inline(never)]
1841    fn to_json(&self) -> serde_json::Value {
1842        serde_json::Value::String(self.to_string())
1843    }
1844    #[inline(never)]
1845    fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
1846        match value {
1847            serde_json::Value::String(text) => {
1848                Self::parse_str(text).map_err(|error| ModelError::invalid(error.to_string()))
1849            }
1850            _ => Err(json_shape("a uuid")),
1851        }
1852    }
1853    #[inline(never)]
1854    fn load(_: &Doc, value: &Value<'_>, _: &ObjId) -> Result<Self, ModelError> {
1855        match scalar(value) {
1856            Some(ScalarValue::Str(text)) => {
1857                Self::parse_str(text).map_err(|error| ModelError::invalid(error.to_string()))
1858            }
1859            _ => Err(ModelError::shape("a uuid")),
1860        }
1861    }
1862    #[inline(never)]
1863    fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
1864        slot.put_scalar(doc, ScalarValue::Str(self.to_string().into()))
1865    }
1866    #[inline(never)]
1867    fn stores_as(&self, before: &Self) -> bool {
1868        self == before
1869    }
1870}
1871
1872/// `None` is an absent key (or a null list element).
1873impl<T: Settable> Settable for Option<T> {}
1874impl<T: Model> Model for Option<T> {
1875    fn value_schema() -> serde_json::Value {
1876        crate::schema::nullable(T::value_schema())
1877    }
1878    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
1879        crate::FieldType::Option(Box::new(T::field_type(types)))
1880    }
1881    const SHAPE: crate::Shape = T::SHAPE;
1882    const CHECKS: bool = T::CHECKS;
1883    const OPS: bool = T::OPS;
1884    const NULLABLE: bool = true;
1885    const TABLE: &'static crate::table::ModelTable = &crate::table::OptionOf::<T>::TABLE;
1886    leaf_paths!();
1887    crate::__table_functions!();
1888    fn label(&self) -> Option<String> {
1889        self.as_ref().and_then(Model::label)
1890    }
1891    fn missing() -> Result<Self, ModelError> {
1892        Ok(None)
1893    }
1894}
1895
1896impl<T: Settable> Settable for Box<T> {}
1897impl<T: Model> Model for Box<T> {
1898    const SCALAR: bool = T::SCALAR;
1899    fn value_schema() -> serde_json::Value {
1900        T::value_schema()
1901    }
1902    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
1903        T::field_type(types)
1904    }
1905    const SHAPE: crate::Shape = T::SHAPE;
1906    const CHECKS: bool = T::CHECKS;
1907    const OPS: bool = T::OPS;
1908    const NULLABLE: bool = T::NULLABLE;
1909    fn op_coalesces(
1910        path: &[Segment],
1911        previous: &serde_json::Value,
1912        next: &serde_json::Value,
1913    ) -> Option<bool> {
1914        if T::OPS {
1915            T::op_coalesces(path, previous, next)
1916        } else {
1917            None
1918        }
1919    }
1920    fn op_continuable(path: &[Segment], op: &serde_json::Value) -> Option<bool> {
1921        if T::OPS {
1922            T::op_continuable(path, op)
1923        } else {
1924            None
1925        }
1926    }
1927    fn op_describe(path: &[Segment], op: &serde_json::Value) -> Option<crate::path::OpDescription> {
1928        if T::OPS {
1929            T::op_describe(path, op)
1930        } else {
1931            None
1932        }
1933    }
1934    fn op_lands(&self, path: &[Segment], op: &serde_json::Value) -> Option<crate::Place> {
1935        if T::OPS {
1936            (**self).op_lands(path, op)
1937        } else {
1938            None
1939        }
1940    }
1941    fn op_schemas(prefix: &str, out: &mut Vec<(String, serde_json::Value)>) {
1942        if T::OPS {
1943            T::op_schemas(prefix, out);
1944        }
1945    }
1946    type Paths<R> = T::Paths<R>;
1947    fn paths_at<R>(path: Path<R, Self>) -> T::Paths<R> {
1948        T::paths_at(path.cast())
1949    }
1950    #[inline(never)]
1951    fn to_json(&self) -> serde_json::Value {
1952        (**self).to_json()
1953    }
1954    #[inline(never)]
1955    fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
1956        T::from_json(value).map(Box::new)
1957    }
1958    #[inline(never)]
1959    fn edit(
1960        doc: &mut Doc,
1961        slot: Slot<'_>,
1962        path: &[Segment],
1963        op: &EditOp,
1964        cx: &mut ActionCx,
1965    ) -> Result<(), ModelError> {
1966        T::edit(doc, slot, path, op, cx)
1967    }
1968    fn check(&self) -> Result<(), Refusal> {
1969        (**self).check()
1970    }
1971    #[inline(never)]
1972    fn diff<R>(&self, after: &Self, path: &[Segment], out: &mut Vec<crate::Edit<R>>) {
1973        (**self).diff(after, path, out);
1974    }
1975    fn label(&self) -> Option<String> {
1976        (**self).label()
1977    }
1978    fn get_at(&self, path: &[Segment]) -> Option<&dyn std::any::Any>
1979    where
1980        Self: 'static,
1981    {
1982        (**self).get_at(path)
1983    }
1984
1985    #[inline(never)]
1986    fn load(doc: &Doc, value: &Value<'_>, id: &ObjId) -> Result<Self, ModelError> {
1987        T::load(doc, value, id).map(Box::new)
1988    }
1989    fn missing() -> Result<Self, ModelError> {
1990        T::missing().map(Box::new)
1991    }
1992    #[inline(never)]
1993    fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
1994        (**self).store(doc, slot)
1995    }
1996    #[inline(never)]
1997    fn stores_as(&self, before: &Self) -> bool {
1998        (**self).stores_as(before)
1999    }
2000    #[inline(never)]
2001    fn store_changed(
2002        &self,
2003        before: &Self,
2004        doc: &mut Doc,
2005        slot: Slot<'_>,
2006        dirty: &Delta,
2007    ) -> Result<(), ModelError> {
2008        (**self).store_changed(before, doc, slot, dirty)
2009    }
2010    #[inline(never)]
2011    fn refresh(
2012        &mut self,
2013        doc: &Doc,
2014        value: &Value<'_>,
2015        id: &ObjId,
2016        delta: &Delta,
2017    ) -> Result<(), ModelError> {
2018        (**self).refresh(doc, value, id, delta)
2019    }
2020    fn collect_text(&self, out: &mut Vec<String>) {
2021        (**self).collect_text(out);
2022    }
2023}
2024
2025/// A list reconciled by position: elements present on both sides are written
2026/// in place, the tail is inserted or deleted. Use
2027/// [`Collection`](crate::Collection) for items with identity, where a move or
2028/// a concurrent insert must not rewrite the neighbours.
2029impl<T: Model> Settable for Vec<T> {}
2030impl<T: Model> Model for Vec<T> {
2031    fn value_schema() -> serde_json::Value {
2032        serde_json::json!({"type": "array", "items": T::value_schema()})
2033    }
2034    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
2035        crate::FieldType::List(Box::new(T::field_type(types)))
2036    }
2037    const CHECKS: bool = T::CHECKS;
2038    const OPS: bool = T::OPS;
2039    const TABLE: &'static crate::table::ModelTable = &crate::table::VecOf::<T>::TABLE;
2040    leaf_paths!();
2041    crate::__table_functions!();
2042    fn missing() -> Result<Self, ModelError> {
2043        Ok(Self::new())
2044    }
2045}
2046
2047/// A fixed number of values, stored as a list.
2048impl<T: Model, const N: usize> Settable for [T; N] {}
2049impl<T: Model, const N: usize> Model for [T; N] {
2050    fn value_schema() -> serde_json::Value {
2051        serde_json::json!({"type": "array", "items": T::value_schema(), "minItems": N, "maxItems": N})
2052    }
2053    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
2054        crate::FieldType::List(Box::new(T::field_type(types)))
2055    }
2056    const CHECKS: bool = T::CHECKS;
2057    const OPS: bool = T::OPS;
2058    leaf_paths!();
2059    #[inline(never)]
2060    fn to_json(&self) -> serde_json::Value {
2061        serde_json::Value::Array(self.iter().map(Model::to_json).collect())
2062    }
2063    #[inline(never)]
2064    fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
2065        let items = Vec::<T>::from_json(value)?;
2066        let count = items.len();
2067        items
2068            .try_into()
2069            .map_err(|_| ModelError::invalid(format!("expected {N} values, not {count}")))
2070    }
2071    #[inline(never)]
2072    fn load(doc: &Doc, value: &Value<'_>, id: &ObjId) -> Result<Self, ModelError> {
2073        let items = Vec::<T>::load(doc, value, id)?;
2074        let count = items.len();
2075        items
2076            .try_into()
2077            .map_err(|_| ModelError::invalid(format!("expected {N} values, not {count}")))
2078    }
2079    fn missing() -> Result<Self, ModelError> {
2080        let items = (0..N)
2081            .map(|_| T::missing())
2082            .collect::<Result<Vec<_>, _>>()?;
2083        items
2084            .try_into()
2085            .map_err(|_| ModelError::invalid("an empty array"))
2086    }
2087    #[inline(never)]
2088    fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
2089        let list = slot.object(doc, ObjType::List)?;
2090        let existing = doc.length(&list);
2091        for (index, item) in self.iter().enumerate() {
2092            let slot = if index < existing {
2093                Slot::Index(&list, index)
2094            } else {
2095                Slot::Insert(&list, index)
2096            };
2097            item.store(doc, slot).located(&index.to_string())?;
2098        }
2099        for index in (N..existing).rev() {
2100            doc.delete(&list, index)?;
2101        }
2102        Ok(())
2103    }
2104}
2105
2106/// A map reconciled key by key.
2107impl<T: Model> Settable for BTreeMap<String, T> {}
2108impl<T: Model> Model for BTreeMap<String, T> {
2109    const SHAPE: crate::Shape = crate::Shape::Map(&T::SHAPE);
2110    fn value_schema() -> serde_json::Value {
2111        serde_json::json!({"type": "object"})
2112    }
2113    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
2114        crate::FieldType::Map(Box::new(T::field_type(types)))
2115    }
2116    const CHECKS: bool = T::CHECKS;
2117    const OPS: bool = T::OPS;
2118    const TABLE: &'static crate::table::ModelTable = &crate::table::MapOf::<T>::TABLE;
2119    leaf_paths!();
2120    crate::__table_functions!();
2121    fn missing() -> Result<Self, ModelError> {
2122        Ok(Self::new())
2123    }
2124}
2125
2126/// Implements [`Model`] for a policy value whose fields are its own: it is
2127/// written as one JSON string and read back as it was written, with nothing
2128/// inside it merging field by field.
2129macro_rules! json_scalar {
2130    ($ty:path, $field_type:ident) => {
2131        impl Settable for $ty {}
2132        impl Model for $ty {
2133            const SCALAR: bool = true;
2134            crate::__own_table!($ty);
2135            fn value_schema() -> serde_json::Value {
2136                serde_json::json!({})
2137            }
2138            fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
2139                let _ = types;
2140                crate::FieldType::$field_type
2141            }
2142            type Paths<R> = crate::Path<R, Self>;
2143
2144            fn paths_at<R>(path: crate::Path<R, Self>) -> crate::Path<R, Self> {
2145                path
2146            }
2147
2148            #[inline(never)]
2149            fn to_json(&self) -> serde_json::Value {
2150                serde_json::to_value(self).unwrap_or(serde_json::Value::Null)
2151            }
2152
2153            #[inline(never)]
2154            fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
2155                serde_json::from_value(value.clone())
2156                    .map_err(|error| ModelError::invalid(error.to_string()))
2157            }
2158
2159            #[inline(never)]
2160            fn load(_: &Doc, value: &Value<'_>, _: &ObjId) -> Result<Self, ModelError> {
2161                match scalar(value) {
2162                    Some(ScalarValue::Str(text)) => serde_json::from_str(text)
2163                        .map_err(|error| ModelError::invalid(error.to_string())),
2164                    _ => Err(ModelError::shape("a stored member")),
2165                }
2166            }
2167
2168            #[inline(never)]
2169            fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
2170                let text = serde_json::to_string(self)
2171                    .map_err(|error| ModelError::invalid(error.to_string()))?;
2172                slot.put_scalar(doc, ScalarValue::Str(text.into()))
2173            }
2174
2175            fn fresh(&self, _: automerge::TextEncoding) -> Fresh {
2176                serde_json::to_string(self).map_or(Fresh::Store, |text| {
2177                    Fresh::scalar(ScalarValue::Str(text.into()))
2178                })
2179            }
2180
2181            #[inline(never)]
2182            fn stores_as(&self, before: &Self) -> bool {
2183                self == before
2184            }
2185        }
2186    };
2187}
2188
2189// A capability names who it reaches, and who granted it: the two policy values
2190// a stored record holds beside its scope.
2191json_scalar!(tilo_action_policy::MemberId, Actor);
2192json_scalar!(tilo_action_policy::Actor, Actor);
2193json_scalar!(tilo_action_policy::Grantee, Text);
2194json_scalar!(tilo_action_policy::Lifetime, Text);
2195
2196/// An app's id is the string it is: written as one, read as one.
2197impl Settable for tilo_app_id::AppId {}
2198impl Model for tilo_app_id::AppId {
2199    const SCALAR: bool = true;
2200    crate::__own_table!(tilo_app_id::AppId);
2201    fn value_schema() -> serde_json::Value {
2202        serde_json::json!({"type": "string"})
2203    }
2204    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
2205        let _ = types;
2206        crate::FieldType::Text
2207    }
2208    type Paths<R> = crate::Path<R, Self>;
2209
2210    fn paths_at<R>(path: crate::Path<R, Self>) -> crate::Path<R, Self> {
2211        path
2212    }
2213
2214    #[inline(never)]
2215    fn to_json(&self) -> serde_json::Value {
2216        serde_json::Value::String(self.as_str().to_owned())
2217    }
2218
2219    #[inline(never)]
2220    fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
2221        match value {
2222            serde_json::Value::String(text) => Ok(Self::new(text.clone())),
2223            _ => Err(ModelError::shape("an app id")),
2224        }
2225    }
2226
2227    #[inline(never)]
2228    fn load(_: &Doc, value: &Value<'_>, _: &ObjId) -> Result<Self, ModelError> {
2229        match scalar(value) {
2230            Some(ScalarValue::Str(text)) => Ok(Self::new(text.to_string())),
2231            _ => Err(ModelError::shape("an app id")),
2232        }
2233    }
2234
2235    #[inline(never)]
2236    fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
2237        slot.put_scalar(doc, ScalarValue::Str(self.as_str().to_owned().into()))
2238    }
2239
2240    fn fresh(&self, _: automerge::TextEncoding) -> Fresh {
2241        Fresh::scalar(ScalarValue::Str(self.as_str().to_owned().into()))
2242    }
2243
2244    #[inline(never)]
2245    fn stores_as(&self, before: &Self) -> bool {
2246        self == before
2247    }
2248}
2249
2250#[cfg(test)]
2251mod tests {
2252    use super::*;
2253    use automerge::ROOT;
2254    use tilo_automerge::ApplyIncoming;
2255
2256    tilo_test_env::scenario! {
2257        fn writes_become_minimal_mergeable_operations;
2258
2259        phase unchanged_writes_produce_no_operations;
2260        {
2261            let mut doc = Doc::new();
2262            write_key(&mut doc, &ROOT, "title", &"hello".to_owned()).unwrap();
2263            write_key(&mut doc, &ROOT, "count", &3_u32).unwrap();
2264            write_key(&mut doc, &ROOT, "tags", &vec![1_i64, 2]).unwrap();
2265            doc.commit();
2266            write_key(&mut doc, &ROOT, "title", &"hello".to_owned()).unwrap();
2267            write_key(&mut doc, &ROOT, "count", &3_u32).unwrap();
2268            write_key(&mut doc, &ROOT, "tags", &vec![1_i64, 2]).unwrap();
2269            assert_eq!(doc.pending_ops(), 0);
2270            assert_eq!(read_key::<String>(&doc, &ROOT, "title").unwrap(), "hello");
2271            assert_eq!(read_key::<Vec<i64>>(&doc, &ROOT, "tags").unwrap(), [1, 2]);
2272            assert_eq!(read_key::<Option<u8>>(&doc, &ROOT, "absent").unwrap(), None);
2273        }
2274
2275        phase text_splices_merge_concurrent_edits;
2276        {
2277            let mut base = Doc::new();
2278            write_key(&mut base, &ROOT, "body", &"hello world".to_owned()).unwrap();
2279            base.commit();
2280            let mut left = base.fork();
2281            let mut right = base.fork();
2282            write_key(&mut left, &ROOT, "body", &"hello brave world".to_owned()).unwrap();
2283            write_key(&mut right, &ROOT, "body", &"hello world!".to_owned()).unwrap();
2284            left.merge_incoming(&mut right).unwrap();
2285            assert_eq!(
2286                read_key::<String>(&left, &ROOT, "body").unwrap(),
2287                "hello brave world!"
2288            );
2289        }
2290
2291        phase a_text_edit_is_one_splice_of_the_changed_span;
2292        {
2293            for (old, new) in [
2294                ("first thought", "second thought"),
2295                ("café 日本語", "café 日本 語!"),
2296                ("abc", ""),
2297                ("", "abc"),
2298                ("aaa", "aa"),
2299                ("ab", "ba"),
2300            ] {
2301                let mut doc = Doc::new();
2302                write_key(&mut doc, &ROOT, "t", &old.to_owned()).unwrap();
2303                doc.commit();
2304                write_key(&mut doc, &ROOT, "t", &new.to_owned()).unwrap();
2305                doc.commit();
2306                assert_eq!(read_key::<String>(&doc, &ROOT, "t").unwrap(), new);
2307            }
2308        }
2309    }
2310}