Skip to main content

tilo_resource/
collection.rs

1//! Items with identity: [`Id`] and the ordered, keyed [`Collection`].
2
3use std::fmt;
4use tilo_sort::CompactSort as _;
5
6use automerge::transaction::Transactable;
7use automerge::{ObjId, ObjType, ReadDoc, ScalarValue, Value};
8
9use std::collections::{HashMap, HashSet};
10use std::sync::{Arc, OnceLock};
11
12use crate::action::ActionCx;
13use crate::delta::{Delta, Touch};
14use crate::model::LocatedAt as _;
15use crate::model::{Doc, Model, ModelError, Slot, Stores, read_key};
16use crate::order;
17use crate::path::{EditOp, Segment, Settable};
18use crate::table::{ModelOps, ModelTable};
19use std::any::Any;
20
21/// A stable identity for an item in a resource. Minted deterministically by
22/// [`ActionCx::id`](crate::ActionCx::id), so replaying an action on another
23/// replica mints the same id.
24///
25/// The default id is empty: an item that refers to no other yet.
26#[derive(
27    Clone,
28    Debug,
29    Default,
30    PartialEq,
31    Eq,
32    PartialOrd,
33    Ord,
34    Hash,
35    serde::Serialize,
36    serde::Deserialize,
37)]
38#[serde(transparent)]
39pub struct Id(String);
40
41impl Id {
42    /// Adopt an id that was minted earlier (read from a document, a URL or an
43    /// action argument).
44    #[must_use]
45    pub fn from_raw(raw: impl Into<String>) -> Self {
46        Self(raw.into())
47    }
48
49    #[must_use]
50    pub fn as_str(&self) -> &str {
51        &self.0
52    }
53}
54
55impl fmt::Display for Id {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        f.write_str(&self.0)
58    }
59}
60
61impl From<&str> for Id {
62    fn from(raw: &str) -> Self {
63        Self(raw.to_owned())
64    }
65}
66
67impl From<String> for Id {
68    fn from(raw: String) -> Self {
69        Self(raw)
70    }
71}
72
73impl std::str::FromStr for Id {
74    type Err = std::convert::Infallible;
75    fn from_str(s: &str) -> Result<Self, Self::Err> {
76        Ok(Self(s.to_owned()))
77    }
78}
79
80impl Settable for Id {}
81impl Model for Id {
82    const SCALAR: bool = true;
83    crate::__own_table!(Id);
84    fn value_schema() -> serde_json::Value {
85        serde_json::json!({"type": "string"})
86    }
87    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
88        let _ = types;
89        crate::FieldType::Text
90    }
91    crate::model::leaf_paths!();
92    #[inline(never)]
93    fn to_json(&self) -> serde_json::Value {
94        serde_json::Value::String(self.0.clone())
95    }
96    #[inline(never)]
97    fn from_json(value: &serde_json::Value) -> Result<Self, ModelError> {
98        match value {
99            serde_json::Value::String(text) => Ok(Self(text.clone())),
100            _ => Err(ModelError::shape("an id")),
101        }
102    }
103    #[inline(never)]
104    fn load(_: &Doc, value: &Value<'_>, _: &ObjId) -> Result<Self, ModelError> {
105        match value {
106            Value::Scalar(scalar) => match scalar.as_ref() {
107                ScalarValue::Str(text) => Ok(Self(text.to_string())),
108                _ => Err(ModelError::shape("an id")),
109            },
110            Value::Object(_) => Err(ModelError::shape("an id")),
111        }
112    }
113    #[inline(never)]
114    fn store(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
115        slot.put_scalar(doc, ScalarValue::Str(self.0.as_str().into()))
116    }
117    fn fresh(&self, _: automerge::TextEncoding) -> crate::model::Fresh {
118        crate::model::Fresh::scalar(ScalarValue::Str(self.0.as_str().into()))
119    }
120}
121
122pub(crate) const ORDER: &str = "k";
123pub const VALUE: &str = "v";
124
125/// The keys from the document's root down to the map `obj`, as a model names its fields: an
126/// item's id for each collection on the way, never the entry key its value is kept under (`issues/<issue>/comments`
127/// for the comments of an issue). `None` where a list stands on the way.
128pub fn path_to(doc: &impl ReadDoc, obj: &ObjId) -> Option<Vec<String>> {
129    let mut path = Vec::new();
130    for parent in doc.parents(obj).ok()? {
131        match parent.prop {
132            automerge::Prop::Map(key) if key == VALUE => {}
133            automerge::Prop::Map(key) => path.push(key),
134            automerge::Prop::Seq(_) => return None,
135        }
136    }
137    path.reverse();
138    Some(path)
139}
140
141/// An ordered collection of items addressed by [`Id`].
142///
143/// Stored as a map from id to `{ k: order key, v: value }`. Editing an item
144/// writes only that item; a move rewrites one order key; concurrent inserts
145/// from several members interleave deterministically; deleting an item
146/// never disturbs another item's identity. This is the default container for
147/// anything a user adds, reorders or removes.
148///
149/// A collection read from a document remembers each item's order key, so a
150/// later change re-reads only the items it touched
151/// ([`Model::refresh`]) instead of the whole collection.
152///
153/// Cloning a collection shares its items: a clone copies one pointer per
154/// item, and an item is copied only when one of the collections sharing it
155/// changes it. A view holding the state it was shown therefore costs the
156/// next change one copied item, not a copy of every item.
157#[derive(Debug)]
158pub struct Collection<T> {
159    items: Vec<Entry<T>>,
160    /// Each id's position, built on the first lookup after the order
161    /// changed, so finding an item by id is constant time.
162    index: Index,
163    membership: Membership,
164    /// How to copy an item another collection still shares.
165    copier: Copier<T>,
166    /// Stored items that did not read, and why: left out of the items,
167    /// kept in the document for their repair ([`Self::quarantined`]).
168    quarantine: Vec<Quarantined>,
169    /// A quarantined item was repaired or discarded since the collection
170    /// was read: only a whole write stores that as a whole read and write
171    /// would, keeping the stored order key or deleting what it never read.
172    whole_write: bool,
173}
174
175/// A stored item of a [`Collection`] that does not read as its type, left
176/// out of the collection rather than making the whole record unreadable.
177///
178/// It stays in the document as it is. It is repaired by pushing a whole
179/// item under its id ([`Collection::push`]), which stores every field, or
180/// removed with the remove-item edit (or [`Collection::discard`]); a
181/// migration may rewrite it in place.
182#[derive(Clone, Debug, PartialEq, Eq)]
183pub struct Quarantined {
184    pub id: Id,
185    /// Why it does not read, where in the item.
186    pub reason: String,
187}
188
189impl<T: Clone> Clone for Collection<T> {
190    fn clone(&self) -> Self {
191        let copy: fn(&T) -> T = T::clone;
192        // Sharing starts here, so from here on either side may need to copy.
193        let _ = self.copier.0.set(copy);
194        Self {
195            items: self.items.clone(),
196            index: self.index.clone(),
197            membership: self.membership,
198            copier: Copier(OnceLock::from(copy)),
199            quarantine: self.quarantine.clone(),
200            whole_write: self.whole_write,
201        }
202    }
203}
204
205/// How a collection copies an item it shares with a clone. Recorded by the
206/// first clone: items are shared by cloning alone, and only a collection of
207/// `Clone` items clones.
208struct Copier<T>(OnceLock<fn(&T) -> T>);
209
210impl<T> Default for Copier<T> {
211    fn default() -> Self {
212        Self(OnceLock::new())
213    }
214}
215
216impl<T> fmt::Debug for Copier<T> {
217    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218        f.write_str("Copier")
219    }
220}
221
222impl<T> Copier<T> {
223    /// The item `item` holds, to change: copied first when another
224    /// collection still shares it, so that one keeps seeing it unchanged.
225    /// `None` only for a shared item with no copier, which cannot be.
226    fn unshare<'a>(&self, item: &'a mut Arc<T>) -> Option<&'a mut T> {
227        if Arc::get_mut(item).is_none()
228            && let Some(copy) = self.0.get()
229        {
230            *item = Arc::new(copy(item));
231        }
232        Arc::get_mut(item)
233    }
234
235    /// The item `item` holds, taken out of the collection: copied when
236    /// another collection still shares it.
237    fn take(&self, item: Arc<T>) -> Option<T> {
238        match Arc::try_unwrap(item) {
239            Ok(item) => Some(item),
240            Err(shared) => self.0.get().map(|copy| copy(&shared)),
241        }
242    }
243}
244
245/// Which ids a [`Collection`] holds, in which order, as one value to
246/// compare: two collections (or one collection at two times) with the same
247/// membership hold the same ids in the same order. A list view keeps it to
248/// tell that a change left its rows as they were without comparing every
249/// id. Different memberships say nothing: the ids may still be the same.
250#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
251pub struct Membership(u64);
252
253impl Membership {
254    /// The membership of every empty collection never changed since.
255    const EMPTY: Self = Self(0);
256
257    /// A membership no collection had before.
258    fn fresh() -> Self {
259        static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
260        Self(NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed))
261    }
262}
263
264/// Shared between clones until one of them moves an item.
265#[derive(Clone, Default)]
266struct Index(OnceLock<Arc<HashMap<Id, usize>>>);
267
268impl fmt::Debug for Index {
269    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
270        f.write_str("Index")
271    }
272}
273
274impl Index {
275    fn get<T>(&self, items: &[Entry<T>], id: &Id) -> Option<usize> {
276        if let Some(index) = self.0.get() {
277            return index.get(id).copied();
278        }
279        self.build(
280            items.len(),
281            &|position| items.get(position).map(|entry| &entry.id),
282            id,
283        )
284    }
285
286    /// Build the index of `count` ids (`id_at` each), then find `id`.
287    #[inline(never)]
288    fn build<'a>(
289        &self,
290        count: usize,
291        id_at: &dyn Fn(usize) -> Option<&'a Id>,
292        id: &Id,
293    ) -> Option<usize> {
294        let mut index = HashMap::with_capacity(count);
295        for position in 0..count {
296            if let Some(entry) = id_at(position) {
297                index.insert(entry.clone(), position);
298            }
299        }
300        let _ = self.0.set(Arc::new(index));
301        self.0.get()?.get(id).copied()
302    }
303
304    fn reset(&mut self) {
305        self.0 = OnceLock::new();
306    }
307
308    /// Note an item appended at `position`, keeping a built index.
309    fn appended(&mut self, id: &Id, position: usize) {
310        let Some(index) = self.0.get_mut() else {
311            return;
312        };
313        match Arc::get_mut(index) {
314            Some(index) => {
315                index.insert(id.clone(), position);
316            }
317            // A clone still looks items up in it: build a new one when next
318            // asked rather than copy this one now.
319            None => self.reset(),
320        }
321    }
322}
323
324#[derive(Debug)]
325struct Entry<T> {
326    id: Id,
327    /// The stored order key, when this entry was read from a document and
328    /// has not been moved since.
329    key: Option<String>,
330    item: Arc<T>,
331}
332
333impl<T> Clone for Entry<T> {
334    fn clone(&self) -> Self {
335        Self {
336            id: self.id.clone(),
337            key: self.key.clone(),
338            item: Arc::clone(&self.item),
339        }
340    }
341}
342
343impl<T> Entry<T> {
344    fn new(id: Id, item: T) -> Self {
345        Self {
346            id,
347            key: None,
348            item: Arc::new(item),
349        }
350    }
351}
352
353impl<T: PartialEq> PartialEq for Collection<T> {
354    /// Equal items in equal order; where each item's order key came from is
355    /// bookkeeping, not content. An item two clones still share is the same
356    /// value and is not compared field by field.
357    fn eq(&self, other: &Self) -> bool {
358        if self.items.len() != other.items.len() {
359            return false;
360        }
361        for at in 0..self.items.len() {
362            match (self.items.get(at), other.items.get(at)) {
363                (Some(a), Some(b))
364                    if a.id == b.id && (Arc::ptr_eq(&a.item, &b.item) || a.item == b.item) => {}
365                _ => return false,
366            }
367        }
368        true
369    }
370}
371
372impl<T> Default for Collection<T> {
373    fn default() -> Self {
374        Self {
375            items: Vec::new(),
376            index: Index::default(),
377            membership: Membership::EMPTY,
378            copier: Copier::default(),
379            quarantine: Vec::new(),
380            whole_write: false,
381        }
382    }
383}
384
385impl<T> Collection<T> {
386    #[must_use]
387    pub fn new() -> Self {
388        Self::default()
389    }
390
391    pub fn len(&self) -> usize {
392        self.items.len()
393    }
394
395    pub fn is_empty(&self) -> bool {
396        self.items.is_empty()
397    }
398
399    /// Which ids the collection holds, in which order ([`Membership`]).
400    /// Editing an item keeps it; adding, removing or moving one changes it.
401    pub fn membership(&self) -> Membership {
402        self.membership
403    }
404
405    /// The ids or their order may have changed.
406    fn moved(&mut self) {
407        self.membership = Membership::fresh();
408    }
409
410    /// Items in collection order.
411    #[allow(
412        clippy::iter_without_into_iter,
413        reason = "a collection iterates its items by id; `for` over it would hide which"
414    )]
415    pub fn iter(&self) -> Iter<'_, T> {
416        Iter(self.items.iter())
417    }
418
419    /// The item at `position` in collection order.
420    pub fn at(&self, position: usize) -> Option<(&Id, &T)> {
421        self.items
422            .get(position)
423            .map(|entry| (&entry.id, &*entry.item))
424    }
425
426    #[allow(
427        clippy::iter_without_into_iter,
428        reason = "a collection iterates its items by id; `for` over it would hide which"
429    )]
430    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
431        IterMut {
432            entries: self.items.iter_mut(),
433            copier: &self.copier,
434        }
435    }
436
437    pub fn values(&self) -> Values<'_, T> {
438        Values(self.items.iter())
439    }
440
441    pub fn ids(&self) -> Ids<'_, T> {
442        Ids(self.items.iter())
443    }
444
445    pub fn contains(&self, id: &Id) -> bool {
446        self.position(id).is_some()
447    }
448
449    pub fn position(&self, id: &Id) -> Option<usize> {
450        self.index.get(&self.items, id)
451    }
452
453    pub fn get(&self, id: &Id) -> Option<&T> {
454        let position = self.position(id)?;
455        self.items.get(position).map(|entry| &*entry.item)
456    }
457
458    /// The item `id`, to change. Copies it first when a clone of this
459    /// collection still shares it; no other item is copied.
460    pub fn get_mut(&mut self, id: &Id) -> Option<&mut T> {
461        let position = self.position(id)?;
462        let entry = self.items.get_mut(position)?;
463        self.copier.unshare(&mut entry.item)
464    }
465
466    /// The stored items that did not read, each with why: the view shows
467    /// the rest, and these are repaired by pushing a whole item under the
468    /// id or removed ([`Quarantined`]).
469    #[must_use]
470    pub fn quarantined(&self) -> &[Quarantined] {
471        &self.quarantine
472    }
473
474    /// Forget the quarantined item `id`: the next write deletes it from the
475    /// document, as it deletes any item no longer in the collection.
476    /// Whether it was quarantined.
477    pub fn discard(&mut self, id: &Id) -> bool {
478        forget_quarantined(&mut self.quarantine, &mut self.whole_write, id)
479    }
480
481    /// Stop holding the quarantined item `id`, as an item takes its place.
482    fn repaired(&mut self, id: &Id) {
483        forget_quarantined(&mut self.quarantine, &mut self.whole_write, id);
484    }
485
486    /// Append an item. Returns its id for chaining. An id already present
487    /// is replaced in place; a quarantined one is repaired by it.
488    pub fn push(&mut self, id: Id, item: T) -> Id {
489        self.push_shared(id, Arc::new(item))
490    }
491
492    /// [`Self::push`] of an item already shared.
493    fn push_shared(&mut self, id: Id, item: Arc<T>) -> Id {
494        self.repaired(&id);
495        if let Some(position) = self.position(&id)
496            && let Some(existing) = self.items.get_mut(position)
497        {
498            existing.item = item;
499            return id;
500        }
501        self.items.push(Entry {
502            id: id.clone(),
503            key: None,
504            item,
505        });
506        let position = self.items.len().saturating_sub(1);
507        self.index.appended(&id, position);
508        self.moved();
509        id
510    }
511
512    /// Insert an item at `index` (clamped to the end). An id already present
513    /// is moved there.
514    pub fn insert(&mut self, index: usize, id: Id, item: T) -> Id {
515        self.repaired(&id);
516        self.remove(&id);
517        let index = index.min(self.items.len());
518        self.items.insert(index, Entry::new(id.clone(), item));
519        self.index.reset();
520        self.moved();
521        id
522    }
523
524    pub fn remove(&mut self, id: &Id) -> Option<T> {
525        let index = self.position(id)?;
526        self.index.reset();
527        self.moved();
528        self.copier.take(self.items.remove(index).item)
529    }
530
531    /// Move an item to `index` (clamped to the end). Returns whether it exists.
532    pub fn move_to(&mut self, id: &Id, index: usize) -> bool {
533        let Some(from) = self.position(id) else {
534            return false;
535        };
536        let mut entry = self.items.remove(from);
537        entry.key = None;
538        let index = index.min(self.items.len());
539        self.items.insert(index, entry);
540        self.index.reset();
541        self.moved();
542        true
543    }
544
545    pub fn retain(&mut self, mut keep: impl FnMut(&Id, &T) -> bool) {
546        let before = self.items.len();
547        self.items.retain(|entry| keep(&entry.id, &*entry.item));
548        // Retaining only removes: the same length is the same ids.
549        if self.items.len() != before {
550            self.index.reset();
551            self.moved();
552        }
553    }
554
555    pub fn sort_by(&mut self, mut compare: impl FnMut(&T, &T) -> std::cmp::Ordering) {
556        crate::sort::sort_by(&mut self.items, |a, b| compare(&*a.item, &*b.item));
557        for entry in &mut self.items {
558            entry.key = None;
559        }
560        self.index.reset();
561        self.moved();
562    }
563}
564
565// Named iterators rather than closures over entries: one small set of
566// methods per item type, whatever a caller chains onto them.
567
568/// The items of a [`Collection`] with their ids, in order.
569pub struct Iter<'a, T>(std::slice::Iter<'a, Entry<T>>);
570/// The items of a [`Collection`], to change, with their ids. Each item a
571/// clone of the collection still shares is copied as it is reached.
572pub struct IterMut<'a, T> {
573    entries: std::slice::IterMut<'a, Entry<T>>,
574    copier: &'a Copier<T>,
575}
576/// The items of a [`Collection`], in order.
577pub struct Values<'a, T>(std::slice::Iter<'a, Entry<T>>);
578/// The ids of a [`Collection`], in order.
579pub struct Ids<'a, T>(std::slice::Iter<'a, Entry<T>>);
580
581impl<'a, T> Iterator for Iter<'a, T> {
582    type Item = (&'a Id, &'a T);
583    fn next(&mut self) -> Option<Self::Item> {
584        let entry = self.0.next()?;
585        Some((&entry.id, &*entry.item))
586    }
587    fn size_hint(&self) -> (usize, Option<usize>) {
588        self.0.size_hint()
589    }
590    fn last(mut self) -> Option<Self::Item> {
591        DoubleEndedIterator::next_back(&mut self)
592    }
593}
594impl<T> DoubleEndedIterator for Iter<'_, T> {
595    fn next_back(&mut self) -> Option<Self::Item> {
596        let entry = self.0.next_back()?;
597        Some((&entry.id, &*entry.item))
598    }
599}
600impl<T> ExactSizeIterator for Iter<'_, T> {}
601
602impl<'a, T> Iterator for IterMut<'a, T> {
603    type Item = (&'a Id, &'a mut T);
604    fn next(&mut self) -> Option<Self::Item> {
605        // An item is skipped only if it could not be unshared, which an
606        // item shared by cloning always can.
607        for entry in self.entries.by_ref() {
608            if let Some(item) = self.copier.unshare(&mut entry.item) {
609                return Some((&entry.id, item));
610            }
611        }
612        None
613    }
614    fn size_hint(&self) -> (usize, Option<usize>) {
615        self.entries.size_hint()
616    }
617}
618
619impl<'a, T> Iterator for Values<'a, T> {
620    type Item = &'a T;
621    fn next(&mut self) -> Option<Self::Item> {
622        Some(&*self.0.next()?.item)
623    }
624    fn size_hint(&self) -> (usize, Option<usize>) {
625        self.0.size_hint()
626    }
627    fn last(mut self) -> Option<Self::Item> {
628        DoubleEndedIterator::next_back(&mut self)
629    }
630}
631impl<T> DoubleEndedIterator for Values<'_, T> {
632    fn next_back(&mut self) -> Option<Self::Item> {
633        Some(&*self.0.next_back()?.item)
634    }
635}
636impl<T> ExactSizeIterator for Values<'_, T> {}
637
638impl<'a, T> Iterator for Ids<'a, T> {
639    type Item = &'a Id;
640    fn next(&mut self) -> Option<Self::Item> {
641        Some(&self.0.next()?.id)
642    }
643    fn size_hint(&self) -> (usize, Option<usize>) {
644        self.0.size_hint()
645    }
646    fn last(mut self) -> Option<Self::Item> {
647        DoubleEndedIterator::next_back(&mut self)
648    }
649}
650impl<T> DoubleEndedIterator for Ids<'_, T> {
651    fn next_back(&mut self) -> Option<Self::Item> {
652        Some(&self.0.next_back()?.id)
653    }
654}
655impl<T> ExactSizeIterator for Ids<'_, T> {}
656
657impl<T> std::ops::Index<&Id> for Collection<T> {
658    type Output = T;
659    #[allow(
660        clippy::panic,
661        reason = "indexing by an absent id is a caller bug, exactly like slice indexing"
662    )]
663    fn index(&self, id: &Id) -> &T {
664        match self.get(id) {
665            Some(item) => item,
666            None => panic!("no item with id {id} in collection"),
667        }
668    }
669}
670
671impl<T> FromIterator<(Id, T)> for Collection<T> {
672    fn from_iter<I: IntoIterator<Item = (Id, T)>>(iter: I) -> Self {
673        let mut collection = Self::default();
674        for (id, item) in iter {
675            collection.push(id, item);
676        }
677        collection
678    }
679}
680
681/// One item of a collection map as stored: its id, its order key, its entry and what the
682/// entry's value slot holds. [`stored_entries`] lists them in order.
683pub struct Stored {
684    pub id: Id,
685    pub key: String,
686    /// The entry's map; `None` for an item stored as its order key alone.
687    pub entry: Option<ObjId>,
688    /// What the entry's value slot holds, for reading the item.
689    pub value: crate::model::MapSlot,
690}
691
692/// An entry of a collection map, not read yet: see [`collection_entries`].
693pub struct StoredEntry {
694    id: Id,
695    slot: EntrySlot,
696}
697
698impl StoredEntry {
699    /// The id of the item the entry holds.
700    #[must_use]
701    pub fn id(&self) -> &Id {
702        &self.id
703    }
704}
705
706enum EntrySlot {
707    /// An item stored as its order key alone.
708    Order(String),
709    /// The entry's map, holding the order key and the value.
710    Map(ObjId),
711}
712
713/// Whether items of the type `item` are stored as their order key alone:
714/// an item that stores nothing (`()`, a [`Grid`](crate::Grid)'s rows and
715/// columns) needs no map around the key.
716pub(crate) fn order_only(item: &ModelTable) -> bool {
717    std::ptr::eq(item, <() as Model>::TABLE)
718}
719
720/// Write the entry of the item `id` under the order key `key` into the
721/// collection map `map`: the key itself for an item stored as its order key
722/// alone (`order_only`), else a map `{ k, v }` holding the item. Answers the
723/// entry's map, or `None` for an item stored as its order key alone.
724///
725/// An item that can be made whole goes in with its entry, in one batch
726/// ([`Stores::made_to`]): the entry, the item's fields and the maps they
727/// hold are one insert, where a store after the entry's would be another.
728pub(crate) fn put_entry(
729    doc: &mut Doc,
730    map: &ObjId,
731    id: &Id,
732    key: String,
733    order_only: bool,
734    item: &dyn Stores,
735) -> Result<Option<ObjId>, ModelError> {
736    if order_only {
737        crate::action::note_entry(map, id.as_str());
738        Slot::Key(map, id.as_str()).put_scalar(doc, ScalarValue::Str(key.into()))?;
739        return Ok(None);
740    }
741    let at = Slot::Key(map, id.as_str());
742    let entry = if let Some((Value::Object(ObjType::Map), entry)) = at.current(doc)? {
743        Slot::Key(&entry, ORDER).put_scalar(doc, ScalarValue::Str(key.into()))?;
744        item.store_to(doc, Slot::Key(&entry, VALUE))
745            .located(id.as_str())?;
746        entry
747    } else {
748        crate::action::note_entry(map, id.as_str());
749        if let Some((fields, later)) = item.made_to(doc.text_encoding()) {
750            // The entry is made with its order key and the item whole: one
751            // batch, the item's maps included.
752            let mut entry = std::collections::HashMap::with_capacity(2);
753            entry.insert(
754                ORDER.to_owned(),
755                automerge::hydrate::Value::Scalar(ScalarValue::Str(key.into())),
756            );
757            entry.insert(VALUE.to_owned(), automerge::hydrate::Value::Map(fields));
758            let made = at.make(doc, &automerge::hydrate::Value::Map(entry.into()))?;
759            let Some((Value::Object(ObjType::Map), value)) = doc.get(&made, VALUE)? else {
760                return Err(ModelError::invalid("an entry holds no item"));
761            };
762            item.write_later_to(doc, &value, &later)?;
763            made
764        } else {
765            // A new entry is made with its order key at once.
766            let mut made = std::collections::HashMap::with_capacity(1);
767            made.insert(
768                ORDER.to_owned(),
769                automerge::hydrate::Value::Scalar(ScalarValue::Str(key.into())),
770            );
771            let entry = at.make(doc, &automerge::hydrate::Value::Map(made.into()))?;
772            item.store_to(doc, Slot::Key(&entry, VALUE))
773                .located(id.as_str())?;
774            entry
775        }
776    };
777    Ok(Some(entry))
778}
779
780/// Write `items`, in this order, as the map from id to `{ k, v }` a
781/// [`Collection`] is stored as: items no longer there (and not
782/// `quarantined`) are deleted, every
783/// order key still consistent with the new order is kept (the longest
784/// increasing run), and keys are minted only for new or moved items.
785pub(crate) fn store_in_order(
786    doc: &mut Doc,
787    slot: Slot<'_>,
788    items: &[(&Id, &dyn Stores)],
789    (order_only, shared): (bool, &SharedAt<'_>),
790    quarantined: &dyn Fn(&Id) -> bool,
791) -> Result<(), ModelError> {
792    let map = slot.object(doc, ObjType::Map)?;
793    let stored = stored_entries(doc, &map);
794    let present: HashSet<&Id> = items.iter().map(|(id, _)| *id).collect();
795    for entry in &stored {
796        // An item that did not read is kept as it is stored, for its
797        // repair: not reading it is no reason to delete it.
798        if !present.contains(&entry.id) && !quarantined(&entry.id) {
799            doc.delete(&map, entry.id.as_str())?;
800        }
801    }
802    let by_id: HashMap<&Id, &str> = stored
803        .iter()
804        .map(|entry| (&entry.id, entry.key.as_str()))
805        .collect();
806    let keys = order_keys(items.iter().map(|(id, _)| *id), &by_id);
807    for (index, ((id, item), key)) in items.iter().zip(keys).enumerate() {
808        let new = !by_id.contains_key(id);
809        let entry = put_entry(doc, &map, id, key, order_only, *item)?;
810        if new && let Some(entry) = &entry {
811            let doc = &*doc;
812            note_stored(Slot::Key(entry, VALUE), &|value| shared(index, doc, value));
813        }
814    }
815    Ok(())
816}
817
818/// The item at a position, just stored whole into the new entry given, as
819/// reading it back gives ([`shared_item`]); `None` when that cannot be told.
820pub(crate) type SharedAt<'a> = dyn Fn(usize, &Doc, &ObjId) -> Option<Box<dyn Any>> + 'a;
821
822/// The item `shared` gives was just stored whole as `value`, an entry's:
823/// kept for the reader that follows this write
824/// ([`crate::apply_cache::note_stored`]).
825fn note_stored(value: Slot<'_>, shared: &dyn Fn(&ObjId) -> Option<Box<dyn Any>>) {
826    if let Slot::Key(entry, _) = value {
827        crate::apply_cache::note_stored(entry, &|| shared(entry));
828    }
829}
830
831/// The order key each of `ids` is stored under, given the keys `stored`
832/// holds: every stored key still consistent with the order (the longest
833/// increasing run) is kept; new and moved items get minted keys.
834fn order_keys<'a>(ids: impl Iterator<Item = &'a Id>, stored: &HashMap<&Id, &str>) -> Vec<String> {
835    let existing: Vec<Option<&str>> = ids.map(|id| stored.get(id).copied()).collect();
836    let kept = longest_increasing(&existing);
837    let mut keys: Vec<Option<String>> = vec![None; existing.len()];
838    for &index in &kept {
839        if let (Some(slot), Some(Some(key))) = (keys.get_mut(index), existing.get(index)) {
840            *slot = Some((*key).to_owned());
841        }
842    }
843    let mut index = 0;
844    while index < keys.len() {
845        if keys.get(index).is_some_and(Option::is_some) {
846            index = index.saturating_add(1);
847            continue;
848        }
849        let start = index;
850        while keys.get(index).is_some_and(Option::is_none) {
851            index = index.saturating_add(1);
852        }
853        let low = start
854            .checked_sub(1)
855            .and_then(|before| keys.get(before))
856            .and_then(Clone::clone);
857        let high = keys.get(index).and_then(Clone::clone);
858        let minted = order::sequence(low.as_deref(), high.as_deref(), index.saturating_sub(start));
859        for (offset, key) in minted.into_iter().enumerate() {
860            if let Some(slot) = keys.get_mut(start.saturating_add(offset)) {
861                *slot = Some(key);
862            }
863        }
864    }
865    keys.into_iter().map(Option::unwrap_or_default).collect()
866}
867
868/// Edit a map of `{ k, v }` entries (a [`Collection`], an
869/// [`Ordered`](crate::Ordered)) at `path`: into the item a path names, or
870/// insert, remove and move items. What depends on the item type comes in as
871/// functions, so this compiles once.
872pub(crate) struct EntryEdits<'a> {
873    /// Apply an edit inside the value slot of an item.
874    pub(crate) item: &'a EditAt<'a>,
875    /// A new item from its JSON form, checked, and the id it carries.
876    pub(crate) parse: &'a ParseItem<'a>,
877    /// The edit of the whole value, for any other operation.
878    pub(crate) whole: &'a EditWhole<'a>,
879    /// Items are stored as their order key alone ([`order_only`]).
880    pub(crate) order_only: bool,
881}
882
883/// [`Model::edit`] at a slot.
884pub(crate) type EditAt<'a> =
885    dyn Fn(&mut Doc, Slot<'_>, &[Segment], &EditOp, &mut ActionCx) -> Result<(), ModelError> + 'a;
886/// A new item from its JSON form, and the id it carries.
887pub(crate) type ParseItem<'a> =
888    dyn Fn(&serde_json::Value) -> Result<(Option<Id>, Box<dyn Stores + 'a>), ModelError> + 'a;
889pub(crate) type EditWhole<'a> =
890    dyn Fn(&mut Doc, Slot<'_>, &[Segment], &EditOp) -> Result<(), ModelError> + 'a;
891/// Write the item at a position over the one it was, in an entry's slot.
892type WriteChanged<'a> =
893    dyn Fn(usize, usize, &mut Doc, &ObjId, &Delta) -> Result<(), ModelError> + 'a;
894/// Store the item at a position, or the whole value, into a slot.
895type Created<'a> =
896    dyn Fn(usize, &mut Doc, &ObjId, &Id, String, bool) -> Result<Option<ObjId>, ModelError> + 'a;
897type StoreWhole<'a> = dyn Fn(&mut Doc, Slot<'_>) -> Result<(), ModelError> + 'a;
898
899pub(crate) fn edit_entries(
900    doc: &mut Doc,
901    slot: Slot<'_>,
902    path: &[Segment],
903    op: &EditOp,
904    cx: &mut ActionCx,
905    edits: &EntryEdits<'_>,
906) -> Result<(), ModelError> {
907    match (path.split_first(), op) {
908        (Some((Segment::Item(id), rest)), _) => {
909            let map = slot.object(doc, ObjType::Map)?;
910            let Some((Value::Object(ObjType::Map), entry)) = doc.get(&map, id.as_str())? else {
911                return Err(ModelError::invalid(format!("no item `{id}`")));
912            };
913            // An edit inside an item whose value is gone would make the
914            // value anew holding the edited field alone: an item missing
915            // every other field.
916            if !rest.is_empty() && doc.get(&entry, VALUE)?.is_none() {
917                return Err(ModelError::invalid(format!(
918                    "item `{id}` holds nothing to edit"
919                )));
920            }
921            (edits.item)(doc, Slot::Key(&entry, VALUE), rest, op, cx).located(id.as_str())
922        }
923        (None, EditOp::InsertItem { id, at, value }) => {
924            let (carried, item) = (edits.parse)(value)?;
925            let map = slot.object(doc, ObjType::Map)?;
926            let id = carried.or_else(|| id.clone()).unwrap_or_else(|| cx.id());
927            if doc.get(&map, id.as_str())?.is_some() {
928                return Err(ModelError::invalid(format!("an item `{id}` exists")));
929            }
930            let stored = stored_entries(doc, &map);
931            let key = key_at(&stored, at, None)?;
932            put_entry(doc, &map, &id, key, edits.order_only, item.as_ref()).map(drop)
933        }
934        (
935            None,
936            EditOp::UpsertItem {
937                matching,
938                value,
939                id,
940            },
941        ) => {
942            let map = slot.object(doc, ObjType::Map)?;
943            let mut entries = Vec::new();
944            let mut candidates = Vec::new();
945            for stored in stored_entries(doc, &map) {
946                let Some(entry) = stored.entry else { continue };
947                if let Some((Value::Object(ObjType::Map), fields)) = doc.get(&entry, VALUE)? {
948                    entries.push(entry);
949                    candidates.push(crate::upsert::Candidate {
950                        id: stored.id,
951                        fields,
952                    });
953                }
954            }
955            let found = crate::upsert::matching_one(doc, &candidates, matching)?
956                .and_then(|found| candidates.iter().position(|item| item.id == found.id));
957            if let Some(index) = found
958                && let (Some(entry), Some(item)) = (entries.get(index), candidates.get(index))
959            {
960                for (key, field) in crate::upsert::changed_fields(doc, &item.fields, value)? {
961                    (edits.item)(
962                        doc,
963                        Slot::Key(entry, VALUE),
964                        &[Segment::Field(key)],
965                        &EditOp::Set { value: field },
966                        cx,
967                    )
968                    .located(item.id.as_str())?;
969                }
970                return Ok(());
971            }
972            let insert = upserted(doc, &map, matching, value, id.as_ref())?;
973            edit_entries(doc, slot, path, &insert, cx, edits)
974        }
975        (None, EditOp::RemoveItem { id }) => {
976            let map = slot.object(doc, ObjType::Map)?;
977            if doc.get(&map, id.as_str())?.is_none() {
978                return Err(ModelError::invalid(format!("no item `{id}`")));
979            }
980            doc.delete(&map, id.as_str())?;
981            Ok(())
982        }
983        (None, EditOp::MoveTo { id, at }) => {
984            let map = slot.object(doc, ObjType::Map)?;
985            let stored = stored_entries(doc, &map);
986            let Some(entry) = stored.iter().find(|entry| &entry.id == id) else {
987                return Err(ModelError::invalid(format!("no item `{id}`")));
988            };
989            let key = key_at(&stored, at, Some(id))?;
990            match &entry.entry {
991                Some(entry) => {
992                    Slot::Key(entry, ORDER).put_scalar(doc, ScalarValue::Str(key.into()))
993                }
994                None => Slot::Key(&map, id.as_str()).put_scalar(doc, ScalarValue::Str(key.into())),
995            }
996        }
997        _ => (edits.whole)(doc, slot, path, op),
998    }
999}
1000
1001/// What [`store_entries_changed`] writes of the items through their type:
1002/// by position now (`now`) and in the record as it was (`was`).
1003pub(crate) struct EntryWrites<'a> {
1004    /// Whether the item now would store as the one it was.
1005    pub(crate) same: &'a dyn Fn(usize, usize) -> bool,
1006    /// Write the item at a position into a new entry of the collection map,
1007    /// under the id and order key given: the item made with its entry in one
1008    /// batch when it can be. Answers the entry's map, and keeps what was
1009    /// written for the read that follows.
1010    pub(crate) created: &'a Created<'a>,
1011    /// Write the item now over the value of the entry that held it.
1012    pub(crate) changed: &'a WriteChanged<'a>,
1013    /// Store the whole collection, when only the document can say.
1014    pub(crate) whole: &'a StoreWhole<'a>,
1015    /// Items are stored as their order key alone ([`order_only`]).
1016    pub(crate) order_only: bool,
1017}
1018
1019/// [`Model::store_changed`] of a map of `{ k, v }` entries: the items `ids`
1020/// over the `stored` ones (id and order key each) they replace; only new,
1021/// moved and changed items are visited, and an item someone else touched
1022/// (`dirty`) is written as `store` writes it.
1023pub(crate) fn store_entries_changed(
1024    doc: &mut Doc,
1025    slot: Slot<'_>,
1026    ids: &[&Id],
1027    stored: &[(&Id, Option<&str>)],
1028    dirty: &Delta,
1029    writes: &EntryWrites<'_>,
1030) -> Result<(), ModelError> {
1031    let current: HashSet<&Id> = ids.iter().copied().collect();
1032    // What was read from a document knows each item's stored order key;
1033    // with one missing, or an id twice over, only the document can say.
1034    if current.len() != ids.len() || stored.iter().any(|(_, key)| key.is_none()) {
1035        return (writes.whole)(doc, slot);
1036    }
1037    let map = slot.object(doc, ObjType::Map)?;
1038    // `stored` is in stored order, the order `store` deletes in.
1039    for (id, _) in stored {
1040        if !current.contains(id) {
1041            doc.delete(&map, id.as_str())?;
1042        }
1043    }
1044    let was: HashMap<&Id, (usize, &str)> = stored
1045        .iter()
1046        .enumerate()
1047        .filter_map(|(at, (id, key))| Some((*id, (at, (*key)?))))
1048        .collect();
1049    let by_id: HashMap<&Id, &str> = was.iter().map(|(id, (_, key))| (*id, *key)).collect();
1050    for ((now, id), key) in ids
1051        .iter()
1052        .enumerate()
1053        .zip(order_keys(ids.iter().copied(), &by_id))
1054    {
1055        let touched = dirty.key(&map, id.as_str());
1056        let Some(&(at, stored_key)) = was.get(id).filter(|_| touched != Touch::Written) else {
1057            // New here, or replaced by someone else: written whole.
1058            (writes.created)(now, doc, &map, id, key, writes.order_only)?;
1059            continue;
1060        };
1061        let kept = touched == Touch::Untouched && stored_key == key;
1062        if kept && (writes.same)(now, at) {
1063            continue;
1064        }
1065        // The entry this item was read from is gone from the document (a
1066        // change it raced deleted it): written whole, as a whole write
1067        // would, never as the fields that changed in an entry made now.
1068        if !writes.order_only
1069            && !matches!(
1070                doc.get(&map, id.as_str())?,
1071                Some((Value::Object(ObjType::Map), _))
1072            )
1073        {
1074            (writes.created)(now, doc, &map, id, key, false)?;
1075            continue;
1076        }
1077        if writes.order_only {
1078            if !kept {
1079                Slot::Key(&map, id.as_str()).put_scalar(doc, ScalarValue::Str(key.into()))?;
1080            }
1081            continue;
1082        }
1083        let entry = Slot::Key(&map, id.as_str()).object(doc, ObjType::Map)?;
1084        if !kept {
1085            Slot::Key(&entry, ORDER).put_scalar(doc, ScalarValue::Str(key.into()))?;
1086        }
1087        (writes.changed)(now, at, doc, &entry, dirty).located(id.as_str())?;
1088    }
1089    Ok(())
1090}
1091
1092/// What a change did to the entry `key` of a collection's map.
1093enum Touched {
1094    /// It is gone.
1095    Gone,
1096    /// Something inside the entry already read changed: its order key, when
1097    /// that changed, and its value's slot.
1098    Below { entry: ObjId, order: Option<String> },
1099    /// A new entry, or one replaced whole.
1100    Fresh { entry: ObjId, order: String },
1101    /// An item stored as its order key alone, new or moved.
1102    Order { order: String },
1103}
1104
1105/// How `delta` touched the entry `key` of the collection map `map`; `below`
1106/// when the entry was read before and only changed inside.
1107fn touched_entry(
1108    doc: &Doc,
1109    map: &ObjId,
1110    key: &str,
1111    delta: &Delta,
1112    below: bool,
1113) -> Result<Touched, ModelError> {
1114    let entry = match doc.get(map, key)? {
1115        Some((Value::Object(ObjType::Map), entry)) => entry,
1116        Some((Value::Scalar(scalar), _)) => {
1117            return match scalar.as_ref() {
1118                ScalarValue::Str(order) => Ok(Touched::Order {
1119                    order: order.to_string(),
1120                }),
1121                _ => Err(ModelError::shape("an order key").at(key)),
1122            };
1123        }
1124        _ => return Ok(Touched::Gone),
1125    };
1126    let order = |doc: &Doc| {
1127        read_key::<crate::Atom>(doc, &entry, ORDER)
1128            .map(|k| k.0)
1129            .located(key)
1130    };
1131    if below {
1132        let order = if delta.key(&entry, ORDER) == Touch::Untouched {
1133            None
1134        } else {
1135            Some(order(doc)?)
1136        };
1137        return Ok(Touched::Below { entry, order });
1138    }
1139    let order = order(doc)?;
1140    Ok(Touched::Fresh { entry, order })
1141}
1142
1143#[inline(never)]
1144fn entries_schema(item: serde_json::Value) -> serde_json::Value {
1145    let mut properties = serde_json::Map::new();
1146    properties.insert("id".into(), serde_json::json!({"type": "string"}));
1147    properties.insert("value".into(), item);
1148    let mut entry = serde_json::Map::new();
1149    entry.insert("type".into(), "object".into());
1150    entry.insert("properties".into(), properties.into());
1151    let mut schema = serde_json::Map::new();
1152    schema.insert("type".into(), "array".into());
1153    schema.insert("items".into(), entry.into());
1154    schema.into()
1155}
1156
1157/// An item's entry in a collection's JSON form.
1158#[inline(never)]
1159fn entry_json(id: &Id, value: serde_json::Value) -> serde_json::Value {
1160    let mut entry = serde_json::Map::new();
1161    entry.insert("id".into(), id.as_str().into());
1162    entry.insert("value".into(), value);
1163    entry.into()
1164}
1165
1166/// The id and value of the entry at `index` of a collection's JSON form.
1167#[inline(never)]
1168fn entry_parts(
1169    index: usize,
1170    entry: &serde_json::Value,
1171) -> Result<(Id, &serde_json::Value), ModelError> {
1172    let id = entry
1173        .get("id")
1174        .map(Id::from_json)
1175        .transpose()?
1176        .ok_or_else(|| {
1177            ModelError::Missing {
1178                path: index.to_string(),
1179            }
1180            .at("id")
1181        })?;
1182    Ok((id, entry.get("value").unwrap_or(&serde_json::Value::Null)))
1183}
1184
1185/// Read every `{ k, v }` entry of the map `id` in stored order, handing
1186/// each entry's value slot to `read`.
1187pub(crate) fn load_entries(
1188    doc: &Doc,
1189    value: &Value<'_>,
1190    id: &ObjId,
1191    read: &mut dyn FnMut(Stored) -> Result<(), ModelError>,
1192) -> Result<(), ModelError> {
1193    if !matches!(value, Value::Object(ObjType::Map)) {
1194        return Err(ModelError::shape("a collection"));
1195    }
1196    for stored in stored_entries(doc, id) {
1197        let at = stored.id.clone();
1198        read(stored).located(at.as_str())?;
1199    }
1200    Ok(())
1201}
1202
1203/// The positions of entries in stored order: by order key, ties by id.
1204/// Sorting positions rather than entries compiles one sort for every item
1205/// type.
1206fn stored_order(keys: &[(Option<&str>, &Id)]) -> Vec<usize> {
1207    let mut order: Vec<usize> = (0..keys.len()).collect();
1208    order.compact_sort_by(|&a, &b| keys.get(a).cmp(&keys.get(b)));
1209    order
1210}
1211
1212/// The entries of the collection map `map`, in one walk of the map, without reading any:
1213/// [`read_entry`] reads each and [`in_stored_order`] orders what they read, which is what
1214/// [`stored_entries`] does. Each read opens its entry's map, so a reader of a large
1215/// collection may spread the reads over threads.
1216#[must_use]
1217pub fn collection_entries(doc: &Doc, map: &ObjId) -> Vec<StoredEntry> {
1218    let mut entries = Vec::new();
1219    for item in doc.map_range(map, ..) {
1220        let id = Id(item.key.clone().into_owned());
1221        // An item stored as its order key alone.
1222        if let automerge::ValueRef::Scalar(automerge::ScalarValueRef::Str(order)) = &item.value {
1223            entries.push(StoredEntry {
1224                id,
1225                slot: EntrySlot::Order(order.to_string()),
1226            });
1227        } else if item.value == automerge::ValueRef::Object(ObjType::Map) {
1228            entries.push(StoredEntry {
1229                id,
1230                slot: EntrySlot::Map(item.id()),
1231            });
1232        }
1233    }
1234    entries
1235}
1236
1237/// The item an entry holds: its order key and value slot, read with one walk of the entry.
1238/// `None` for an entry without a readable order key: no entry anyone placed, left out, never
1239/// the reason its whole collection does not read.
1240#[must_use]
1241pub fn read_entry(doc: &Doc, entry: StoredEntry) -> Option<Stored> {
1242    match entry.slot {
1243        EntrySlot::Order(key) => Some(Stored {
1244            id: entry.id,
1245            key,
1246            entry: None,
1247            value: None,
1248        }),
1249        EntrySlot::Map(map) => {
1250            let [order, value] = crate::model::read_slots(doc, &map, [ORDER, VALUE]);
1251            let order = crate::model::load_slot::<crate::Atom>(doc, order, ORDER).ok()?;
1252            Some(Stored {
1253                id: entry.id,
1254                key: order.0,
1255                entry: Some(map),
1256                value,
1257            })
1258        }
1259    }
1260}
1261
1262/// Put read entries in stored order: by order key, ties by id.
1263pub fn in_stored_order(entries: &mut [Stored]) {
1264    // `(order key, id)` is unique, so an unstable sort orders as a stable one.
1265    entries.compact_sort_by(|a, b| a.key.cmp(&b.key).then_with(|| a.id.cmp(&b.id)));
1266}
1267
1268/// The stored entries of the collection map `map`, in order. One walk of
1269/// the map lists the entries and one walk of each entry reads its order key
1270/// and value slot: a lookup per key would open each map again.
1271pub(crate) fn stored_entries(doc: &Doc, map: &ObjId) -> Vec<Stored> {
1272    let mut entries: Vec<Stored> = collection_entries(doc, map)
1273        .into_iter()
1274        .filter_map(|entry| read_entry(doc, entry))
1275        .collect();
1276    in_stored_order(&mut entries);
1277    entries
1278}
1279
1280/// The ids of the items of the collection map `map`, in stored order, without reading any
1281/// item: what a reader that needs a collection's membership and order, and not its items,
1282/// walks.
1283#[must_use]
1284pub fn stored_ids(doc: &Doc, map: &ObjId) -> Vec<Id> {
1285    stored_entries(doc, map)
1286        .into_iter()
1287        .map(|stored| stored.id)
1288        .collect()
1289}
1290
1291/// The stored entry of the item `id` of the collection map `map`, with its order key: `None`
1292/// when there is no such item or it has no readable order key. One item is read without
1293/// listing the others: what a reader that keeps a collection's order applies a change by.
1294#[must_use]
1295pub fn stored_entry(doc: &Doc, map: &ObjId, id: &str) -> Option<Stored> {
1296    let slot = match doc.get(map, id).ok()?? {
1297        (Value::Scalar(scalar), _) => match scalar.as_ref() {
1298            ScalarValue::Str(order) => EntrySlot::Order(order.to_string()),
1299            _ => return None,
1300        },
1301        (Value::Object(ObjType::Map), entry) => EntrySlot::Map(entry),
1302        (Value::Object(_), _) => return None,
1303    };
1304    read_entry(
1305        doc,
1306        StoredEntry {
1307            id: Id(id.to_owned()),
1308            slot,
1309        },
1310    )
1311}
1312
1313/// The value map of the item `id` of the collection map `map`: `None` when there is no such
1314/// item, `Some(None)` for an item stored as its order key alone (it reads as its type's
1315/// default), so one item is reached without reading the others.
1316#[must_use]
1317pub fn stored_item(doc: &Doc, map: &ObjId, id: &str) -> Option<Option<ObjId>> {
1318    match doc.get(map, id).ok()?? {
1319        (Value::Scalar(_), _) => Some(None),
1320        (Value::Object(ObjType::Map), entry) => match doc.get(&entry, VALUE).ok().flatten() {
1321            Some((Value::Object(_), value)) => Some(Some(value)),
1322            _ => Some(None),
1323        },
1324        (Value::Object(_), _) => None,
1325    }
1326}
1327
1328/// An order key placing an item at `at` among `stored` (which may hold the
1329/// item itself, `moving`, which does not count).
1330pub(crate) fn key_at(
1331    stored: &[Stored],
1332    at: &crate::At,
1333    moving: Option<&Id>,
1334) -> Result<String, ModelError> {
1335    let others: Vec<&Stored> = stored
1336        .iter()
1337        .filter(|entry| Some(&entry.id) != moving)
1338        .collect();
1339    let ids: Vec<&Id> = others.iter().map(|entry| &entry.id).collect();
1340    let at = at.index(&ids)?;
1341    let low = at
1342        .checked_sub(1)
1343        .and_then(|before| others.get(before))
1344        .map(|entry| entry.key.as_str());
1345    let high = others.get(at).map(|entry| entry.key.as_str());
1346    Ok(order::between(low, high))
1347}
1348
1349/// The insert an upsert that matched no item of the map `map` makes: at the
1350/// end, under `id` when given, else under the id its key mints when no item
1351/// holds that one yet.
1352pub(crate) fn upserted(
1353    doc: &Doc,
1354    map: &ObjId,
1355    matching: &serde_json::Map<String, serde_json::Value>,
1356    value: &serde_json::Value,
1357    id: Option<&Id>,
1358) -> Result<EditOp, ModelError> {
1359    let minted = crate::upsert::key_id(matching);
1360    let id = if let Some(id) = id {
1361        Some(id.clone())
1362    } else {
1363        doc.get(map, minted.as_str())?.is_none().then_some(minted)
1364    };
1365    Ok(EditOp::InsertItem {
1366        id,
1367        at: crate::At::End,
1368        value: crate::upsert::inserted(matching, value)?,
1369    })
1370}
1371
1372/// Indices (into `keys`) of one longest strictly increasing subsequence.
1373fn longest_increasing(keys: &[Option<&str>]) -> Vec<usize> {
1374    // Patience sorting over the present keys, O(n log n).
1375    let mut tails: Vec<usize> = Vec::new();
1376    let mut previous: Vec<Option<usize>> = vec![None; keys.len()];
1377    for (index, key) in keys.iter().enumerate() {
1378        let Some(key) = key else { continue };
1379        let position =
1380            tails.partition_point(|&tail| keys.get(tail).copied().flatten() < Some(*key));
1381        if let Some(before) = position.checked_sub(1)
1382            && let Some(slot) = previous.get_mut(index)
1383        {
1384            *slot = tails.get(before).copied();
1385        }
1386        if position == tails.len() {
1387            tails.push(index);
1388        } else if let Some(tail) = tails.get_mut(position) {
1389            *tail = index;
1390        }
1391    }
1392    let mut chain = Vec::with_capacity(tails.len());
1393    let mut cursor = tails.last().copied();
1394    while let Some(index) = cursor {
1395        chain.push(index);
1396        cursor = previous.get(index).copied().flatten();
1397    }
1398    chain.reverse();
1399    chain
1400}
1401
1402impl<T: Model> Collection<T> {
1403    /// Read item `id` again from `map`, the collection's map in `doc`, with
1404    /// every field as stored: what a view's reader left unread of it
1405    /// (`#[model(demanded)]`) too. A resource's [`load`](crate::Resource::load)
1406    /// reads so the items a view demands. Whether the collection holds `id`
1407    /// and its entry read.
1408    ///
1409    /// # Errors
1410    /// Why the stored item does not read.
1411    pub fn read_whole(&mut self, doc: &Doc, map: &ObjId, id: &Id) -> Result<bool, ModelError> {
1412        read_item_whole(self, T::TABLE, doc, map, id)
1413    }
1414}
1415
1416/// [`Collection::read_whole`], compiled once for every item type.
1417#[inline(never)]
1418fn read_item_whole(
1419    entries: &mut dyn Entries,
1420    item: &'static ModelTable,
1421    doc: &Doc,
1422    map: &ObjId,
1423    id: &Id,
1424) -> Result<bool, ModelError> {
1425    let Some(at) = entries.find(id) else {
1426        return Ok(false);
1427    };
1428    let Some(stored) = stored_entry(doc, map, id.as_str()) else {
1429        return Ok(false);
1430    };
1431    let held = stored.value;
1432    crate::table::whole(|| {
1433        entries.replace_filled(at, Some(stored.key), &mut |into| {
1434            let held = held.as_ref().map(|(value, obj)| (value, obj));
1435            fill_item(item, doc, (map, id.as_str()), held, into)
1436                .map(drop)
1437                .located(VALUE)
1438        })
1439    })?;
1440    Ok(true)
1441}
1442
1443impl<T> Collection<T> {
1444    /// Sort the items as stored: by order key, ties by id.
1445    fn reorder_by_keys(&mut self) {
1446        let items = &self.items;
1447        let order = stored_order_of(items.len(), &|at| {
1448            items.get(at).map(|entry| (entry.key.as_deref(), &entry.id))
1449        });
1450        permute(order, &mut |at, from| self.items.swap(at, from));
1451    }
1452}
1453
1454/// [`stored_order`] of the `count` entries whose order key and id `key_at`
1455/// gives. Compiled once for every item type.
1456#[inline(never)]
1457fn stored_order_of<'a>(
1458    count: usize,
1459    key_at: &dyn Fn(usize) -> Option<(Option<&'a str>, &'a Id)>,
1460) -> Vec<usize> {
1461    let keys: Vec<(Option<&str>, &Id)> = (0..count).filter_map(key_at).collect();
1462    stored_order(&keys)
1463}
1464
1465/// Move the entry at `order[at]` to each position `at`, in place, one cycle
1466/// of the permutation at a time, swapping two positions with `swap`.
1467/// Compiled once for every item type.
1468#[inline(never)]
1469fn permute(mut order: Vec<usize>, swap: &mut dyn FnMut(usize, usize)) {
1470    for start in 0..order.len() {
1471        let mut at = start;
1472        while let Some(from) = order.get_mut(at).map(|from| std::mem::replace(from, at)) {
1473            if from == start {
1474                break;
1475            }
1476            swap(at, from);
1477            at = from;
1478        }
1479    }
1480}
1481
1482/// Forget the quarantined item `id` in `quarantine`, noting in
1483/// `whole_write` that only a whole write stores that; whether it was
1484/// quarantined. Compiled once for every item type.
1485#[inline(never)]
1486fn forget_quarantined(quarantine: &mut Vec<Quarantined>, whole_write: &mut bool, id: &Id) -> bool {
1487    let before = quarantine.len();
1488    quarantine.retain(|held| &held.id != id);
1489    let forgotten = quarantine.len() != before;
1490    *whole_write |= forgotten;
1491    forgotten
1492}
1493
1494/// Hold the stored item `id` in `quarantine`, for `reason`. Compiled once
1495/// for every item type.
1496#[inline(never)]
1497fn hold_quarantined(quarantine: &mut Vec<Quarantined>, id: Id, reason: String) {
1498    match quarantine.iter_mut().find(|held| held.id == id) {
1499        Some(held) => held.reason = reason,
1500        None => quarantine.push(Quarantined { id, reason }),
1501    }
1502}
1503
1504/// Stop holding `id` in `quarantine`. Compiled once for every item type.
1505#[inline(never)]
1506fn release_quarantined(quarantine: &mut Vec<Quarantined>, id: &Id) {
1507    quarantine.retain(|held| &held.id != id);
1508}
1509
1510impl<T: Model> crate::items::ItemSource for Collection<T> {
1511    fn item_collection(&self, field: &'static str) -> crate::items::ItemCollection {
1512        listed_items(T::TABLE, self, field)
1513    }
1514    fn item_presence(&self) -> usize {
1515        usize::from(!self.items.is_empty())
1516    }
1517    fn label_of_item(&self, id: &Id) -> Option<String> {
1518        let entries: &dyn Entries = self;
1519        let item = entries.item_at(entries.find(id)?)?;
1520        Some(label_of(T::TABLE, id, item))
1521    }
1522    fn item_texts(&self, field: &'static str, found: &mut Vec<crate::items::ItemText>) {
1523        item_texts(T::TABLE, self, field, found);
1524    }
1525    fn nested_items(&self, field: &'static str, out: &mut Vec<crate::items::ItemCollection>) {
1526        nested_items(T::TABLE, self, field, out);
1527    }
1528}
1529
1530/// Items with their ids, whatever their type and wherever their ids are
1531/// kept: what listing them for publication and search reads.
1532#[doc(hidden)]
1533pub trait ItemList {
1534    fn count(&self) -> usize;
1535    fn item(&self, at: usize) -> Option<(Id, &dyn Any)>;
1536    /// Whether `id` is an item kept out of the list because it no longer
1537    /// reads ([`Collection::quarantined`]).
1538    fn quarantines(&self, id: &str) -> bool {
1539        let _ = id;
1540        false
1541    }
1542}
1543
1544impl<T: Model> crate::table::PublishedItems for Collection<T> {
1545    const ITEM_TABLE: &'static ModelTable = T::TABLE;
1546}
1547
1548impl<T: 'static> ItemList for Collection<T> {
1549    fn count(&self) -> usize {
1550        self.items.len()
1551    }
1552
1553    fn item(&self, at: usize) -> Option<(Id, &dyn Any)> {
1554        let entry = self.items.get(at)?;
1555        Some((entry.id.clone(), &*entry.item as &dyn Any))
1556    }
1557
1558    fn quarantines(&self, id: &str) -> bool {
1559        self.quarantine.iter().any(|held| held.id.as_str() == id)
1560    }
1561}
1562
1563/// The label an item is offered under: its `#[model(label)]` (the word for an item nobody named
1564/// when that is blank), else its first text, else its id.
1565pub(crate) fn label_of(item: &ModelTable, id: &Id, value: &dyn Any) -> String {
1566    if let Some(label) = (item.ops.label)(item, value)
1567        && !label.is_empty()
1568    {
1569        return label;
1570    }
1571    // A record that names itself by a field of its own is named by that field alone: one nobody
1572    // named reads as the person's word for an item that has no name, never by its other text, so
1573    // what a list shows and what assistive tools announce are the same name.
1574    let names_itself = item.record().is_some_and(|record| {
1575        record.label.is_some() || record.label_with.is_some() || !record.label_parts.is_empty()
1576    });
1577    if names_itself {
1578        return crate::word!("resource-unnamed-item").read();
1579    }
1580    let mut text = Vec::new();
1581    (item.ops.collect_text)(item, value, &mut text);
1582    crate::__private::first_line_of(text).unwrap_or_else(|| id.to_string())
1583}
1584
1585/// [`ItemSource::item_collection`](crate::items::ItemSource::item_collection)
1586/// of `entries`, items of the type `item`.
1587pub(crate) fn listed_items(
1588    item: &ModelTable,
1589    entries: &dyn ItemList,
1590    field: &'static str,
1591) -> crate::items::ItemCollection {
1592    let mut labelled = false;
1593    let mut listed = Vec::new();
1594    for at in 0..entries.count().min(crate::items::ITEM_PAGE) {
1595        let Some((id, value)) = entries.item(at) else {
1596            continue;
1597        };
1598        if at == 0 {
1599            labelled = (item.ops.label)(item, value).is_some();
1600        }
1601        let label = label_of(item, &id, value);
1602        listed.push((id, label));
1603    }
1604    crate::items::ItemCollection {
1605        within: Vec::new(),
1606        field,
1607        labelled,
1608        items: listed,
1609    }
1610}
1611
1612/// [`ItemSource::item_texts`](crate::items::ItemSource::item_texts) of
1613/// `entries`.
1614pub(crate) fn item_texts(
1615    item: &ModelTable,
1616    entries: &dyn ItemList,
1617    field: &'static str,
1618    found: &mut Vec<crate::items::ItemText>,
1619) {
1620    for at in 0..entries.count() {
1621        let Some((id, value)) = entries.item(at) else {
1622            continue;
1623        };
1624        if let Some(label) = (item.ops.label)(item, value) {
1625            let mut text = Vec::new();
1626            (item.ops.collect_text)(item, value, &mut text);
1627            found.push(crate::items::ItemText {
1628                field,
1629                id,
1630                label,
1631                text: text.join("\n"),
1632            });
1633        }
1634    }
1635}
1636
1637/// [`ItemSource::nested_items`](crate::items::ItemSource::nested_items) of
1638/// `entries`.
1639pub(crate) fn nested_items(
1640    item: &ModelTable,
1641    entries: &dyn ItemList,
1642    field: &'static str,
1643    out: &mut Vec<crate::items::ItemCollection>,
1644) {
1645    for at in 0..entries.count().min(crate::items::ITEM_PAGE) {
1646        let Some((id, value)) = entries.item(at) else {
1647            continue;
1648        };
1649        for mut inner in (item.ops.nested_collections)(item, value) {
1650            inner.within.insert(0, (field, id.clone()));
1651            out.push(inner);
1652        }
1653    }
1654}
1655
1656impl<T: Model> Model for Collection<T> {
1657    fn value_schema() -> serde_json::Value {
1658        entries_schema(T::value_schema())
1659    }
1660    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
1661        crate::FieldType::Collection(Box::new(T::field_type(types)))
1662    }
1663    const SHAPE: crate::Shape = crate::Shape::Collection(&T::SHAPE);
1664    const CHECKS: bool = T::CHECKS;
1665    const OPS: bool = T::OPS;
1666    const TABLE: &'static ModelTable = &CollectionOf::<T>::TABLE;
1667    crate::model::leaf_paths!();
1668    crate::__table_functions!();
1669    fn missing() -> Result<Self, ModelError> {
1670        Ok(Self::default())
1671    }
1672}
1673
1674/// The item `fill` puts into an `Option` of its type, shared: the one copy
1675/// for each item type of what [`Entries::push_filled`] and
1676/// [`Entries::replace_filled`] do with the value itself, so the large moves
1677/// of a big item are compiled once rather than in each of them.
1678#[inline(never)]
1679fn filled_shared<T: 'static>(
1680    fill: &mut dyn FnMut(&mut dyn Any) -> Result<(), ModelError>,
1681) -> Result<Arc<T>, ModelError> {
1682    let mut slot: Option<T> = None;
1683    fill(&mut slot)?;
1684    crate::table::filled(slot).map(Arc::new)
1685}
1686
1687/// A collection's entries, whatever its item type: what the collection
1688/// functions below reach into one with.
1689pub(crate) trait Entries {
1690    fn count(&self) -> usize;
1691    fn id_at(&self, at: usize) -> Option<&Id>;
1692    fn order_at(&self, at: usize) -> Option<&str>;
1693    fn item_at(&self, at: usize) -> Option<&dyn Any>;
1694    fn item_at_mut(&mut self, at: usize) -> Option<&mut dyn Any>;
1695    fn find(&self, id: &Id) -> Option<usize>;
1696    /// Append an entry (with `replace`, replace the item of an id already
1697    /// present), its item put by `fill` into an `Option` of the item type.
1698    fn push_filled(
1699        &mut self,
1700        entry: (Id, Option<String>, bool),
1701        fill: &mut dyn FnMut(&mut dyn Any) -> Result<(), ModelError>,
1702    ) -> Result<(), ModelError>;
1703    /// Replace the entry at `at`, as [`Self::push_filled`].
1704    fn replace_filled(
1705        &mut self,
1706        at: usize,
1707        order: Option<String>,
1708        fill: &mut dyn FnMut(&mut dyn Any) -> Result<(), ModelError>,
1709    ) -> Result<(), ModelError>;
1710    fn remove_at(&mut self, at: usize);
1711    fn set_order(&mut self, at: usize, order: Option<String>);
1712    /// Sort the entries by their order keys; the ids may have moved.
1713    fn reorder(&mut self);
1714    /// The ids changed.
1715    fn changed(&mut self);
1716    /// Whether the stored item `id` is quarantined.
1717    fn is_quarantined(&self, id: &Id) -> bool;
1718    /// Hold the stored item `id` as quarantined, for `reason`.
1719    fn quarantine(&mut self, id: Id, reason: String);
1720    /// Stop holding `id` as quarantined: it reads again, or is gone.
1721    fn release(&mut self, id: &Id);
1722    /// Only a whole write stores the collection as it now is.
1723    fn needs_whole_write(&self) -> bool;
1724    /// The item at `at` as this collection shares it: an `Arc` of it, with
1725    /// how to copy it.
1726    fn shared_at(&self, at: usize) -> Option<Box<dyn Any>>;
1727    /// A copy of the item at `at`, changed by `settle`, as [`Self::shared_at`]
1728    /// gives an item; `None` when `settle` fails.
1729    fn settled_at(
1730        &self,
1731        at: usize,
1732        settle: &mut dyn FnMut(&mut dyn Any) -> bool,
1733    ) -> Option<Box<dyn Any>>;
1734    /// Put `stored`, an item as [`Self::shared_at`] gave it, at `at` or
1735    /// appended, as `entry`: its id and order key. Whether it was one of this
1736    /// collection's items.
1737    fn put_shared(&mut self, at: Option<usize>, entry: (Id, String), stored: &dyn Any) -> bool;
1738}
1739
1740impl<T: 'static> Entries for Collection<T> {
1741    fn count(&self) -> usize {
1742        self.items.len()
1743    }
1744
1745    fn id_at(&self, at: usize) -> Option<&Id> {
1746        self.items.get(at).map(|entry| &entry.id)
1747    }
1748
1749    fn order_at(&self, at: usize) -> Option<&str> {
1750        self.items.get(at)?.key.as_deref()
1751    }
1752
1753    fn item_at(&self, at: usize) -> Option<&dyn Any> {
1754        self.items.get(at).map(|entry| &*entry.item as &dyn Any)
1755    }
1756
1757    /// Copies the item first when a clone of the collection still shares
1758    /// it: a refresh changes only the items a change touched.
1759    fn item_at_mut(&mut self, at: usize) -> Option<&mut dyn Any> {
1760        let entry = self.items.get_mut(at)?;
1761        let item = self.copier.unshare(&mut entry.item)?;
1762        Some(item as &mut dyn Any)
1763    }
1764
1765    fn find(&self, id: &Id) -> Option<usize> {
1766        self.position(id)
1767    }
1768
1769    fn push_filled(
1770        &mut self,
1771        (id, order, replace): (Id, Option<String>, bool),
1772        fill: &mut dyn FnMut(&mut dyn Any) -> Result<(), ModelError>,
1773    ) -> Result<(), ModelError> {
1774        let item = filled_shared::<T>(fill)?;
1775        if replace {
1776            self.push_shared(id, item);
1777        } else {
1778            self.items.push(Entry {
1779                id,
1780                key: order,
1781                item,
1782            });
1783            self.index.reset();
1784        }
1785        Ok(())
1786    }
1787
1788    fn replace_filled(
1789        &mut self,
1790        at: usize,
1791        order: Option<String>,
1792        fill: &mut dyn FnMut(&mut dyn Any) -> Result<(), ModelError>,
1793    ) -> Result<(), ModelError> {
1794        let item = filled_shared::<T>(fill)?;
1795        if let Some(entry) = self.items.get_mut(at) {
1796            entry.item = item;
1797            entry.key = order;
1798        }
1799        Ok(())
1800    }
1801
1802    fn remove_at(&mut self, at: usize) {
1803        if at < self.items.len() {
1804            self.items.remove(at);
1805        }
1806    }
1807
1808    fn set_order(&mut self, at: usize, order: Option<String>) {
1809        if let Some(entry) = self.items.get_mut(at) {
1810            entry.key = order;
1811        }
1812    }
1813
1814    fn reorder(&mut self) {
1815        self.reorder_by_keys();
1816        self.index.reset();
1817        self.moved();
1818    }
1819
1820    fn changed(&mut self) {
1821        self.index.reset();
1822        self.moved();
1823    }
1824
1825    fn is_quarantined(&self, id: &Id) -> bool {
1826        self.quarantine.iter().any(|held| &held.id == id)
1827    }
1828
1829    fn quarantine(&mut self, id: Id, reason: String) {
1830        hold_quarantined(&mut self.quarantine, id, reason);
1831    }
1832
1833    fn release(&mut self, id: &Id) {
1834        release_quarantined(&mut self.quarantine, id);
1835    }
1836
1837    fn needs_whole_write(&self) -> bool {
1838        self.whole_write
1839    }
1840
1841    /// Only from a collection that can copy what it shares: the one taking it
1842    /// must be able to copy it before changing it.
1843    fn shared_at(&self, at: usize) -> Option<Box<dyn Any>> {
1844        let entry = self.items.get(at)?;
1845        let copy = *self.copier.0.get()?;
1846        Some(Box::new((Arc::clone(&entry.item), copy)))
1847    }
1848
1849    fn settled_at(
1850        &self,
1851        at: usize,
1852        settle: &mut dyn FnMut(&mut dyn Any) -> bool,
1853    ) -> Option<Box<dyn Any>> {
1854        let entry = self.items.get(at)?;
1855        let copy = *self.copier.0.get()?;
1856        let mut item = copy(&entry.item);
1857        settle(&mut item).then(|| Box::new((Arc::new(item), copy)) as Box<dyn Any>)
1858    }
1859
1860    fn put_shared(
1861        &mut self,
1862        at: Option<usize>,
1863        (id, order): (Id, String),
1864        stored: &dyn Any,
1865    ) -> bool {
1866        let Some((item, copy)) = stored.downcast_ref::<(Arc<T>, fn(&T) -> T)>() else {
1867            return false;
1868        };
1869        // Shared from here on: copied before it is changed.
1870        let _ = self.copier.0.set(*copy);
1871        let item = Arc::clone(item);
1872        if let Some(entry) = at.and_then(|at| self.items.get_mut(at)) {
1873            entry.item = item;
1874            entry.key = Some(order);
1875        } else {
1876            self.items.push(Entry {
1877                id,
1878                key: Some(order),
1879                item,
1880            });
1881            self.index.reset();
1882        }
1883        true
1884    }
1885}
1886
1887/// The item at `at` of `entries`, of the type `item`, just stored whole into
1888/// `entry`, as reading it back gives: as they share it, or, for an item
1889/// holding what reads back as the document's own structure (rich text), a
1890/// copy with that read again ([`crate::table::settle`]).
1891fn shared_item(
1892    item: &ModelTable,
1893    entries: &dyn Entries,
1894    at: usize,
1895    (doc, entry): (&Doc, &ObjId),
1896) -> Option<Box<dyn Any>> {
1897    if !item.has_ops {
1898        return entries.shared_at(at);
1899    }
1900    entries.settled_at(at, &mut |value| {
1901        crate::table::settle(item, value, doc, (entry, VALUE)).is_ok()
1902    })
1903}
1904
1905/// What `Collection<T>`'s table reaches into one with.
1906pub struct CollectionDesc {
1907    item: &'static ModelTable,
1908    entries: for<'a> fn(&'a dyn Any) -> Option<&'a dyn Entries>,
1909    entries_mut: for<'a> fn(&'a mut dyn Any) -> Option<&'a mut dyn Entries>,
1910    /// Put an empty collection into `out` (an `Option` of it), and hand it
1911    /// back.
1912    fresh: for<'a> fn(&'a mut dyn Any) -> Option<&'a mut dyn Entries>,
1913    /// An empty `Option` of a collection, the collection in a filled one,
1914    /// and moving it out over another.
1915    staged: (fn() -> Box<dyn Any>, crate::table::Unstage),
1916    replace: fn(&mut dyn Any, &mut dyn Any) -> Result<(), ModelError>,
1917    /// An empty `Option` of an item and the item in a filled one.
1918    item_staged: (fn() -> Box<dyn Any>, crate::table::Unstage),
1919}
1920
1921impl CollectionDesc {
1922    /// Its item type's table.
1923    pub(crate) const fn item(&self) -> &'static ModelTable {
1924        self.item
1925    }
1926}
1927
1928pub struct CollectionOf<T>(std::marker::PhantomData<T>);
1929
1930impl<T: Model> CollectionOf<T> {
1931    pub const DESC: CollectionDesc = CollectionDesc {
1932        item: T::TABLE,
1933        entries: entries_of::<T>,
1934        entries_mut: entries_mut_of::<T>,
1935        fresh: fresh_of::<T>,
1936        staged: (
1937            crate::table::empty_of::<Collection<T>>,
1938            crate::table::unwrap_of::<Collection<T>>,
1939        ),
1940        replace: crate::table::replace_of::<Collection<T>>,
1941        item_staged: (crate::table::empty_of::<T>, crate::table::unwrap_of::<T>),
1942    };
1943
1944    pub const TABLE: ModelTable = ModelTable::of_collection(&Self::DESC, T::CHECKS, T::OPS);
1945}
1946
1947fn entries_of<T: 'static>(value: &dyn Any) -> Option<&dyn Entries> {
1948    Some(value.downcast_ref::<Collection<T>>()? as &dyn Entries)
1949}
1950
1951fn entries_mut_of<T: 'static>(value: &mut dyn Any) -> Option<&mut dyn Entries> {
1952    Some(value.downcast_mut::<Collection<T>>()? as &mut dyn Entries)
1953}
1954
1955fn fresh_of<T: 'static>(out: &mut dyn Any) -> Option<&mut dyn Entries> {
1956    let out = out.downcast_mut::<Option<Collection<T>>>()?;
1957    let collection = out.insert(Collection::default());
1958    Some(collection as &mut dyn Entries)
1959}
1960
1961fn listed(table: &ModelTable) -> Result<&'static CollectionDesc, ModelError> {
1962    table.collection().ok_or_else(crate::table::mismatch)
1963}
1964
1965/// An item as [`store_in_order`] writes it, through its table.
1966pub(crate) struct TableItem<'a> {
1967    pub(crate) table: &'static ModelTable,
1968    pub(crate) value: &'a dyn Any,
1969}
1970
1971impl Stores for TableItem<'_> {
1972    fn store_to(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
1973        (self.table.ops.store)(self.table, self.value, doc, slot)
1974    }
1975
1976    fn made_to(&self, encoding: automerge::TextEncoding) -> Option<crate::table::Fields> {
1977        let desc = crate::table::described(self.table).ok()?;
1978        crate::table::fresh::fields_made_of(desc, self.value, encoding)
1979    }
1980
1981    fn write_later_to(
1982        &self,
1983        doc: &mut Doc,
1984        value: &ObjId,
1985        later: &[(usize, bool)],
1986    ) -> Result<(), ModelError> {
1987        let desc = crate::table::described(self.table)?;
1988        crate::table::fresh::write_later(desc, self.value, doc, value, later)
1989    }
1990}
1991
1992/// An item made from its JSON form, staged in an `Option` of its type.
1993struct StagedItem {
1994    table: &'static ModelTable,
1995    staged: Box<dyn Any>,
1996    unstage: crate::table::Unstage,
1997}
1998
1999impl Stores for StagedItem {
2000    fn store_to(&self, doc: &mut Doc, slot: Slot<'_>) -> Result<(), ModelError> {
2001        let value = (self.unstage)(self.staged.as_ref()).ok_or_else(crate::table::mismatch)?;
2002        (self.table.ops.store)(self.table, value, doc, slot)
2003    }
2004
2005    fn made_to(&self, encoding: automerge::TextEncoding) -> Option<crate::table::Fields> {
2006        let desc = crate::table::described(self.table).ok()?;
2007        let value = (self.unstage)(self.staged.as_ref())?;
2008        crate::table::fresh::fields_made_of(desc, value, encoding)
2009    }
2010
2011    fn write_later_to(
2012        &self,
2013        doc: &mut Doc,
2014        value: &ObjId,
2015        later: &[(usize, bool)],
2016    ) -> Result<(), ModelError> {
2017        let desc = crate::table::described(self.table)?;
2018        let item = (self.unstage)(self.staged.as_ref()).ok_or_else(crate::table::mismatch)?;
2019        crate::table::fresh::write_later(desc, item, doc, value, later)
2020    }
2021}
2022
2023/// Whether `error` says a stored value does not read as its type (absent,
2024/// of another shape, invalid): what quarantines one item rather than
2025/// failing its whole record. A document error is no such thing.
2026fn quarantines(error: &ModelError) -> bool {
2027    matches!(
2028        error,
2029        ModelError::Missing { .. } | ModelError::Shape { .. } | ModelError::Invalid { .. }
2030    )
2031}
2032
2033/// The value maps the entry `key` of the collection map `map` holds: the
2034/// winning entry's first, then those of the entries (and values) that
2035/// replicas made concurrently and the document keeps in conflict beside it.
2036fn conflicting_values(doc: &Doc, (map, key): (&ObjId, &str)) -> Vec<ObjId> {
2037    fn maps(doc: &Doc, obj: &ObjId, key: &str, out: &mut Vec<ObjId>) {
2038        if let Ok(Some((Value::Object(ObjType::Map), winner))) = doc.get(obj, key)
2039            && !out.contains(&winner)
2040        {
2041            out.push(winner);
2042        }
2043        for (value, id) in doc.get_all(obj, key).unwrap_or_default() {
2044            if matches!(value, Value::Object(ObjType::Map)) && !out.contains(&id) {
2045                out.push(id);
2046            }
2047        }
2048    }
2049    let mut entries = Vec::new();
2050    maps(doc, map, key, &mut entries);
2051    let mut values = Vec::new();
2052    for entry in &entries {
2053        maps(doc, entry, VALUE, &mut values);
2054    }
2055    values
2056}
2057
2058/// Read the item stored under the entry `key` of the collection map `map`
2059/// into `into` (an `Option` of `item`'s type), from the value slot `slot`
2060/// its entry holds. When that does not read and replicas made the entry
2061/// concurrently, the copies the document keeps in conflict are read as one
2062/// item, each field from the first copy holding it: the same id made on two
2063/// devices is one complete item, never one missing what the other copy
2064/// holds. `Ok(true)` when it was read so.
2065fn fill_item(
2066    item: &ModelTable,
2067    doc: &Doc,
2068    entry: (&ObjId, &str),
2069    slot: Option<(&Value<'_>, &ObjId)>,
2070    into: &mut dyn Any,
2071) -> Result<bool, ModelError> {
2072    let _read = crate::profiling::Phase::start("collection.read_item");
2073    let error = match crate::table::load_slot(item, doc, slot, into) {
2074        Ok(()) => return Ok(false),
2075        Err(error) if quarantines(&error) => error,
2076        Err(error) => return Err(error),
2077    };
2078    let copies = conflicting_values(doc, entry);
2079    if copies.len() < 2 {
2080        return Err(error);
2081    }
2082    let merged = match item.record() {
2083        Some(record) => crate::table::read_fields_merged(record, doc, &copies, into).is_ok(),
2084        None => copies.iter().any(|copy| {
2085            crate::table::load_slot(item, doc, Some((&Value::Object(ObjType::Map), copy)), into)
2086                .is_ok()
2087        }),
2088    };
2089    if merged { Ok(true) } else { Err(error) }
2090}
2091
2092/// The item just appended to `entries` was read from conflicting copies:
2093/// it forgets its order key, so the next write stores it whole, over the
2094/// winning copy, and the document holds it complete again.
2095fn mark_merged(entries: &mut dyn Entries) {
2096    if let Some(last) = entries.count().checked_sub(1) {
2097        entries.set_order(last, None);
2098    }
2099}
2100
2101/// Read a collection stored in the map `id` into `out`, a fresh one.
2102fn load_into(
2103    desc: &CollectionDesc,
2104    doc: &Doc,
2105    value: &Value<'_>,
2106    id: &ObjId,
2107    out: &mut dyn Entries,
2108) -> Result<(), ModelError> {
2109    let item = desc.item;
2110    load_entries(doc, value, id, &mut |stored| {
2111        // Stored by the write the state is read after: taken as it was written.
2112        if let Some(entry) = &stored.entry
2113            && crate::apply_cache::take_stored(entry, &mut |taken| {
2114                out.put_shared(None, (stored.id.clone(), stored.key.clone()), taken)
2115            })
2116        {
2117            return Ok(());
2118        }
2119        let slot = stored.value;
2120        let key = stored.id.clone();
2121        let mut merged = false;
2122        let read = out.push_filled((stored.id, Some(stored.key), false), &mut |into| {
2123            let slot = slot.as_ref().map(|(v, i)| (v, i));
2124            merged = fill_item(item, doc, (id, key.as_str()), slot, into).located(VALUE)?;
2125            Ok(())
2126        });
2127        match read {
2128            Ok(()) => {
2129                if merged {
2130                    mark_merged(&mut *out);
2131                }
2132                Ok(())
2133            }
2134            Err(error) if quarantines(&error) => {
2135                let reason = error.at(key.as_str()).to_string();
2136                out.quarantine(key, reason);
2137                Ok(())
2138            }
2139            Err(error) => Err(error),
2140        }
2141    })?;
2142    // What was read is a membership of its own.
2143    out.changed();
2144    Ok(())
2145}
2146
2147/// The functions of every [`Collection`], over its item type's table.
2148pub static COLLECTION_OPS: ModelOps = ModelOps {
2149    without_absent: crate::shape::kept_whole,
2150    // An empty collection is an empty map; one holding items mints their
2151    // order keys as its `store` writes them.
2152    fresh: |table, value, _| match table.collection().and_then(|desc| (desc.entries)(value)) {
2153        Some(entries) if entries.count() == 0 => {
2154            crate::model::Fresh::Value(automerge::hydrate::Value::map())
2155        }
2156        _ => crate::model::Fresh::Store,
2157    },
2158    to_json: |table, value| {
2159        let (Ok(desc), Some(entries)) = (
2160            listed(table),
2161            table.collection().and_then(|desc| (desc.entries)(value)),
2162        ) else {
2163            return serde_json::Value::Null;
2164        };
2165        let mut out = Vec::with_capacity(entries.count());
2166        for at in 0..entries.count() {
2167            if let (Some(id), Some(item)) = (entries.id_at(at), entries.item_at(at)) {
2168                out.push(entry_json(id, (desc.item.ops.to_json)(desc.item, item)));
2169            }
2170        }
2171        serde_json::Value::Array(out)
2172    },
2173    from_json: |table, value, out| {
2174        let desc = listed(table)?;
2175        let serde_json::Value::Array(items) = value else {
2176            return Err(ModelError::shape("a list of items"));
2177        };
2178        let collection = (desc.fresh)(out).ok_or_else(crate::table::mismatch)?;
2179        for (index, entry) in items.iter().enumerate() {
2180            let (id, value) = entry_parts(index, entry)?;
2181            let at = id.clone();
2182            collection.push_filled((id, None, true), &mut |into| {
2183                (desc.item.ops.from_json)(desc.item, value, into).located(at.as_str())
2184            })?;
2185        }
2186        Ok(())
2187    },
2188    load: |table, doc, value, id, out| {
2189        let desc = listed(table)?;
2190        let collection = (desc.fresh)(out).ok_or_else(crate::table::mismatch)?;
2191        load_into(desc, doc, value, id, collection)
2192    },
2193    missing: |table, out| {
2194        let desc = listed(table)?;
2195        (desc.fresh)(out).ok_or_else(crate::table::mismatch)?;
2196        Ok(())
2197    },
2198    reload: |table, target, doc, slot| {
2199        let desc = listed(table)?;
2200        let mut staged = (desc.staged.0)();
2201        match slot {
2202            Some((value, id)) => (COLLECTION_OPS.load)(table, doc, value, id, staged.as_mut())?,
2203            None => (COLLECTION_OPS.missing)(table, staged.as_mut())?,
2204        }
2205        (desc.replace)(target, staged.as_mut())
2206    },
2207    store: |table, value, doc, slot| {
2208        let desc = listed(table)?;
2209        let entries = (desc.entries)(value).ok_or_else(crate::table::mismatch)?;
2210        let mut held: Vec<(&Id, TableItem<'_>)> = Vec::with_capacity(entries.count());
2211        for at in 0..entries.count() {
2212            if let (Some(id), Some(item)) = (entries.id_at(at), entries.item_at(at)) {
2213                held.push((
2214                    id,
2215                    TableItem {
2216                        table: desc.item,
2217                        value: item,
2218                    },
2219                ));
2220            }
2221        }
2222        let mut items: Vec<(&Id, &dyn Stores)> = Vec::with_capacity(held.len());
2223        for (id, item) in &held {
2224            items.push((*id, item as &dyn Stores));
2225        }
2226        let shared = |at: usize, doc: &Doc, entry: &ObjId| {
2227            let at = entries.find(held.get(at)?.0)?;
2228            shared_item(desc.item, entries, at, (doc, entry))
2229        };
2230        store_in_order(doc, slot, &items, (order_only(desc.item), &shared), &|id| {
2231            entries.is_quarantined(id)
2232        })
2233    },
2234    stores_as: |table, value, before| {
2235        let Some(desc) = table.collection() else {
2236            return false;
2237        };
2238        let (Some(now), Some(was)) = ((desc.entries)(value), (desc.entries)(before)) else {
2239            return false;
2240        };
2241        if now.needs_whole_write() || now.count() != was.count() || !strictly_ordered_entries(was) {
2242            return false;
2243        }
2244        for at in 0..now.count() {
2245            match (
2246                now.id_at(at),
2247                was.id_at(at),
2248                now.item_at(at),
2249                was.item_at(at),
2250            ) {
2251                (Some(id), Some(was_id), Some(item), Some(was_item))
2252                    if id == was_id
2253                        && (one_item(item, was_item)
2254                            || (desc.item.ops.stores_as)(desc.item, item, was_item)) => {}
2255                _ => return false,
2256            }
2257        }
2258        true
2259    },
2260    store_changed: |table, value, before, doc, slot, dirty| {
2261        let desc = listed(table)?;
2262        let now = (desc.entries)(value).ok_or_else(crate::table::mismatch)?;
2263        let was = (desc.entries)(before).ok_or_else(crate::table::mismatch)?;
2264        if now.needs_whole_write() {
2265            return (COLLECTION_OPS.store)(table, value, doc, slot);
2266        }
2267        let mut ids: Vec<&Id> = Vec::with_capacity(now.count());
2268        for at in 0..now.count() {
2269            if let Some(id) = now.id_at(at) {
2270                ids.push(id);
2271            }
2272        }
2273        let mut stored: Vec<(&Id, Option<&str>)> = Vec::with_capacity(was.count());
2274        for at in 0..was.count() {
2275            if let Some(id) = was.id_at(at) {
2276                stored.push((id, was.order_at(at)));
2277            }
2278        }
2279        let item = desc.item;
2280        store_entries_changed(
2281            doc,
2282            slot,
2283            &ids,
2284            &stored,
2285            dirty,
2286            &EntryWrites {
2287                same: &|at_now, at_was| match (now.item_at(at_now), was.item_at(at_was)) {
2288                    (Some(now), Some(was)) => {
2289                        one_item(now, was) || (item.ops.stores_as)(item, now, was)
2290                    }
2291                    _ => false,
2292                },
2293                created: &|at_now, doc, map, id, key, order_only| {
2294                    let Some(value) = now.item_at(at_now) else {
2295                        return Ok(None);
2296                    };
2297                    let made = TableItem { table: item, value };
2298                    let entry = put_entry(doc, map, id, key, order_only, &made)?;
2299                    if let Some(entry) = &entry {
2300                        let doc = &*doc;
2301                        note_stored(Slot::Key(entry, VALUE), &|value| {
2302                            shared_item(item, now, at_now, (doc, value))
2303                        });
2304                    }
2305                    Ok(entry)
2306                },
2307                changed: &|at_now, at_was, doc, entry, dirty| match (
2308                    now.item_at(at_now),
2309                    was.item_at(at_was),
2310                ) {
2311                    (Some(value), Some(before)) => crate::table::write_key_changed(
2312                        item,
2313                        (value, before),
2314                        doc,
2315                        entry,
2316                        VALUE,
2317                        dirty,
2318                    ),
2319                    _ => Ok(()),
2320                },
2321                whole: &|doc, slot| (COLLECTION_OPS.store)(table, value, doc, slot),
2322                order_only: order_only(item),
2323            },
2324        )
2325    },
2326    refresh: |table, target, doc, value, id, delta| {
2327        refresh_entries(listed(table)?, table, target, doc, (value, id), delta)
2328    },
2329    read_whole: |_, _, _| Ok(()),
2330    edit: |table, doc, slot, path, op, cx| {
2331        let desc = listed(table)?;
2332        let item = desc.item;
2333        edit_entries(
2334            doc,
2335            slot,
2336            path,
2337            op,
2338            cx,
2339            &EntryEdits {
2340                item: &|doc, slot, path, op, cx| (item.ops.edit)(item, doc, slot, path, op, cx),
2341                parse: &|value| {
2342                    let mut staged = (desc.item_staged.0)();
2343                    (item.ops.from_json)(item, value, staged.as_mut())?;
2344                    let made =
2345                        (desc.item_staged.1)(staged.as_ref()).ok_or_else(crate::table::mismatch)?;
2346                    (item.ops.check)(item, made).map_err(ModelError::refused)?;
2347                    Ok((
2348                        None,
2349                        Box::new(StagedItem {
2350                            table: item,
2351                            staged,
2352                            unstage: desc.item_staged.1,
2353                        }) as Box<dyn Stores + '_>,
2354                    ))
2355                },
2356                whole: &|doc, slot, path, op| {
2357                    let staged = ((desc.staged.0)(), desc.staged.1);
2358                    crate::table::edit_whole(table, staged, false, doc, slot, path, op)
2359                },
2360                order_only: order_only(item),
2361            },
2362        )
2363    },
2364    diff: |table, before, after, path, out| {
2365        let Some(desc) = table.collection() else {
2366            return;
2367        };
2368        let (Some(was), Some(now)) = ((desc.entries)(before), (desc.entries)(after)) else {
2369            return;
2370        };
2371        diff_entries(desc.item, (was, now), path, out);
2372    },
2373    collect_text: |table, value, out| {
2374        if let Some(desc) = table.collection()
2375            && let Some(entries) = (desc.entries)(value)
2376        {
2377            for at in 0..entries.count() {
2378                if let Some(item) = entries.item_at(at) {
2379                    (desc.item.ops.collect_text)(desc.item, item, out);
2380                }
2381            }
2382        }
2383    },
2384    check: |table, value| {
2385        let Some(desc) = table.collection() else {
2386            return Ok(());
2387        };
2388        if !desc.item.checks {
2389            return Ok(());
2390        }
2391        if let Some(entries) = (desc.entries)(value) {
2392            for at in 0..entries.count() {
2393                if let Some(item) = entries.item_at(at) {
2394                    (desc.item.ops.check)(desc.item, item)?;
2395                }
2396            }
2397        }
2398        Ok(())
2399    },
2400    get_at: |table, value, path| match path.split_first() {
2401        None => Some(value),
2402        Some((Segment::Item(id), rest)) => {
2403            let desc = table.collection()?;
2404            let entries = (desc.entries)(value)?;
2405            let item = entries.item_at(entries.find(id)?)?;
2406            (desc.item.ops.get_at)(desc.item, item, rest)
2407        }
2408        Some(_) => None,
2409    },
2410    label: crate::table::no_label,
2411    nested_collections: crate::table::no_nested,
2412    op_coalesces: |table, path, previous, next| match path.split_first() {
2413        Some((Segment::Item(_), rest)) if table.has_ops => {
2414            let item = table.collection()?.item;
2415            (item.ops.op_coalesces)(item, rest, previous, next)
2416        }
2417        _ => None,
2418    },
2419    op_continuable: |table, path, op| match path.split_first() {
2420        Some((Segment::Item(_), rest)) if table.has_ops => {
2421            let item = table.collection()?.item;
2422            (item.ops.op_continuable)(item, rest, op)
2423        }
2424        _ => None,
2425    },
2426    op_describe: |table, path, op| match path.split_first() {
2427        Some((Segment::Item(_), rest)) if table.has_ops => {
2428            let item = table.collection()?.item;
2429            (item.ops.op_describe)(item, rest, op)
2430        }
2431        _ => None,
2432    },
2433    op_lands: |table, value, path, op| match path.split_first() {
2434        Some((Segment::Item(id), rest)) if table.has_ops => {
2435            let desc = table.collection()?;
2436            let entries = (desc.entries)(value)?;
2437            let item = entries.item_at(entries.find(id)?)?;
2438            (desc.item.ops.op_lands)(desc.item, item, rest, op)
2439        }
2440        _ => None,
2441    },
2442    op_schemas: |table, prefix, out| {
2443        if table.has_ops
2444            && let Some(desc) = table.collection()
2445        {
2446            (desc.item.ops.op_schemas)(desc.item, &format!("{prefix}*."), out);
2447        }
2448    },
2449};
2450
2451/// Whether two items are one item, which two clones of a collection still
2452/// share: it stores as it is without being compared, however its fields
2453/// compare (a value stored as JSON text compares only by writing it).
2454fn one_item(item: &dyn Any, other: &dyn Any) -> bool {
2455    std::ptr::addr_eq(item, other)
2456}
2457
2458/// Whether every entry has a stored order key, each above the one before:
2459/// the keys a write keeps all of.
2460fn strictly_ordered_entries(entries: &dyn Entries) -> bool {
2461    let mut previous: Option<&str> = None;
2462    for at in 0..entries.count() {
2463        let Some(key) = entries.order_at(at) else {
2464            return false;
2465        };
2466        if let Some(previous) = previous
2467            && previous >= key
2468        {
2469            return false;
2470        }
2471        previous = Some(key);
2472    }
2473    true
2474}
2475
2476/// The field edits that turn the entries `was` into `now` at `path`.
2477fn diff_entries(
2478    item: &ModelTable,
2479    (was, now): (&dyn Entries, &dyn Entries),
2480    path: &[Segment],
2481    out: &mut Vec<crate::Edit<()>>,
2482) {
2483    for at in 0..was.count() {
2484        let (Some(id), Some(before)) = (was.id_at(at), was.item_at(at)) else {
2485            continue;
2486        };
2487        match now.find(id).and_then(|position| now.item_at(position)) {
2488            // One item, which both still share: no edit.
2489            Some(next) if one_item(before, next) => {}
2490            Some(next) => {
2491                let mut path = path.to_vec();
2492                path.push(Segment::Item(id.clone()));
2493                (item.ops.diff)(item, before, next, &path, out);
2494            }
2495            None => out.push(crate::Edit::new(
2496                path.to_vec(),
2497                EditOp::RemoveItem { id: id.clone() },
2498            )),
2499        }
2500    }
2501    for index in 0..now.count() {
2502        let (Some(id), Some(next)) = (now.id_at(index), now.item_at(index)) else {
2503            continue;
2504        };
2505        match was.find(id) {
2506            Some(position) => {
2507                if position != index {
2508                    out.push(crate::Edit::new(
2509                        path.to_vec(),
2510                        EditOp::MoveTo {
2511                            id: id.clone(),
2512                            at: crate::At::Index(index),
2513                        },
2514                    ));
2515                }
2516            }
2517            None => out.push(crate::Edit::new(
2518                path.to_vec(),
2519                EditOp::InsertItem {
2520                    id: Some(id.clone()),
2521                    at: crate::At::Index(index),
2522                    value: (item.ops.to_json)(item, next),
2523                },
2524            )),
2525        }
2526    }
2527}
2528
2529/// [`Model::refresh`] of a collection: read anew when changed all over or
2530/// edited in memory since it was read, else only the entries `delta`
2531/// touched.
2532#[allow(
2533    clippy::too_many_lines,
2534    reason = "one pass over the touched entries: read, place, order and quarantine share its state"
2535)]
2536fn refresh_entries(
2537    desc: &CollectionDesc,
2538    table: &ModelTable,
2539    target: &mut dyn Any,
2540    doc: &Doc,
2541    (value, id): (&Value<'_>, &ObjId),
2542    delta: &Delta,
2543) -> Result<(), ModelError> {
2544    let touched = delta.under(id);
2545    let unkeyed = {
2546        let entries = (desc.entries)(target).ok_or_else(crate::table::mismatch)?;
2547        (0..entries.count()).any(|at| entries.order_at(at).is_none())
2548    };
2549    // A collection edited in memory since it was read no longer knows
2550    // every stored order key; read it again rather than guess.
2551    if touched.is_all() || unkeyed {
2552        return (COLLECTION_OPS.reload)(table, target, doc, Some((value, id)));
2553    }
2554    let item = desc.item;
2555    let entries = (desc.entries_mut)(target).ok_or_else(crate::table::mismatch)?;
2556    let mut reorder = false;
2557    for key in touched.keys() {
2558        let item_id = Id(key.to_owned());
2559        let position = entries.find(&item_id);
2560        let below = touched.key(key) == Touch::Below && position.is_some();
2561        let touched_now = match touched_entry(doc, id, key, delta, below) {
2562            Ok(touched_now) => touched_now,
2563            Err(error) if quarantines(&error) => {
2564                if let Some(position) = position {
2565                    entries.remove_at(position);
2566                    entries.changed();
2567                }
2568                entries.quarantine(item_id, error.to_string());
2569                continue;
2570            }
2571            Err(error) => return Err(error),
2572        };
2573        match touched_now {
2574            Touched::Gone => {
2575                entries.release(&item_id);
2576                if let Some(position) = position {
2577                    entries.remove_at(position);
2578                    entries.changed();
2579                }
2580            }
2581            // Something inside an item already read: its order key, its value.
2582            Touched::Below { entry, order } => {
2583                if let Some(position) = position {
2584                    if order.is_some() {
2585                        entries.set_order(position, order);
2586                        reorder = true;
2587                    }
2588                    let refreshed = match entries.item_at_mut(position) {
2589                        Some(existing) => {
2590                            crate::table::refresh_slot(item, existing, doc, &entry, VALUE, delta)
2591                                .located(key)
2592                        }
2593                        None => Ok(()),
2594                    };
2595                    match refreshed {
2596                        Ok(()) => {}
2597                        // It no longer reads: out of the items, held for repair.
2598                        Err(error) if quarantines(&error) => {
2599                            entries.remove_at(position);
2600                            entries.changed();
2601                            entries.quarantine(item_id, error.to_string());
2602                        }
2603                        Err(error) => return Err(error),
2604                    }
2605                }
2606            }
2607            // An item stored as its order key: new, or moved.
2608            Touched::Order { order } => {
2609                if let Some(position) = position {
2610                    entries.set_order(position, Some(order));
2611                } else {
2612                    entries.push_filled(
2613                        (item_id, Some(order), false),
2614                        &mut |into: &mut dyn Any| {
2615                            crate::table::load_slot(item, doc, None, into)
2616                                .located(VALUE)
2617                                .located(key)
2618                        },
2619                    )?;
2620                    entries.changed();
2621                }
2622                reorder = true;
2623            }
2624            // A new item, or one whose entry was replaced.
2625            Touched::Fresh { entry, order } => {
2626                // Stored by the write this follows: taken as it was written.
2627                let shared = crate::apply_cache::take_stored(&entry, &mut |stored| {
2628                    entries.put_shared(position, (item_id.clone(), order.clone()), stored)
2629                });
2630                if shared {
2631                    entries.release(&item_id);
2632                    if position.is_none() {
2633                        entries.changed();
2634                    }
2635                    reorder = true;
2636                    continue;
2637                }
2638                let slot = crate::model::get_slot(doc, &entry, VALUE).located(key)?;
2639                let mut merged = false;
2640                let mut fill = |into: &mut dyn Any| -> Result<(), ModelError> {
2641                    let slot = slot.as_ref().map(|(v, i)| (v, i));
2642                    merged = fill_item(item, doc, (id, key), slot, into)
2643                        .located(VALUE)
2644                        .located(key)?;
2645                    Ok(())
2646                };
2647                let read = match position {
2648                    Some(position) => entries.replace_filled(position, Some(order), &mut fill),
2649                    None => entries.push_filled((item_id.clone(), Some(order), false), &mut fill),
2650                };
2651                match read {
2652                    Ok(()) => {
2653                        entries.release(&item_id);
2654                        let at = if position.is_some() {
2655                            position
2656                        } else {
2657                            entries.changed();
2658                            entries.count().checked_sub(1)
2659                        };
2660                        if merged && let Some(at) = at {
2661                            entries.set_order(at, None);
2662                        }
2663                    }
2664                    // It does not read: out of the items, held for repair.
2665                    Err(error) if quarantines(&error) => {
2666                        if let Some(position) = position {
2667                            entries.remove_at(position);
2668                            entries.changed();
2669                        }
2670                        entries.quarantine(item_id, error.to_string());
2671                    }
2672                    Err(error) => return Err(error),
2673                }
2674                reorder = true;
2675            }
2676        }
2677    }
2678    // A moved order key or a new entry: sorting may move items.
2679    if reorder {
2680        entries.reorder();
2681    }
2682    Ok(())
2683}
2684
2685#[cfg(test)]
2686mod tests {
2687    use super::*;
2688    use crate::model::write_key;
2689    use automerge::ROOT;
2690    use tilo_automerge::ApplyIncoming;
2691
2692    fn ids(collection: &Collection<String>) -> Vec<String> {
2693        collection.values().cloned().collect()
2694    }
2695
2696    /// The collection read key by key: the oracle the one-walk read
2697    /// must equal, order keys included.
2698    fn read_key_by_key<T: Model>(doc: &Doc, map: &ObjId) -> Vec<(Id, Option<String>, T)> {
2699        let mut entries = Vec::new();
2700        for key in doc.keys(map) {
2701            let Some((Value::Object(ObjType::Map), entry)) = doc.get(map, key.as_str()).unwrap()
2702            else {
2703                continue;
2704            };
2705            let order: crate::Atom = read_key(doc, &entry, ORDER).unwrap();
2706            let item: T = read_key(doc, &entry, VALUE).unwrap();
2707            entries.push((Id(key), Some(order.0), item));
2708        }
2709        entries.compact_sort_by(|a, b| a.1.cmp(&b.1).then_with(|| a.0.cmp(&b.0)));
2710        entries
2711    }
2712
2713    tilo_test_env::scenario! {
2714        fn a_stored_collection_reads_walks_and_moves_by_key;
2715
2716        phase one_entry_reads_as_the_listing_has_it;
2717        {
2718            let mut doc = Doc::new();
2719            let mut list: Collection<u32> = Collection::new();
2720            for n in 0..20_u32 {
2721                list.push(Id::from_raw(format!("i{n:02}")), n);
2722            }
2723            write_key(&mut doc, &ROOT, "items", &list).unwrap();
2724            let Some((_, map)) = doc.get(&ROOT, "items").unwrap() else {
2725                panic!("the collection is stored");
2726            };
2727            for listed in stored_entries(&doc, &map) {
2728                let one = stored_entry(&doc, &map, listed.id.as_str()).expect("the entry");
2729                assert_eq!((one.id, one.key), (listed.id, listed.key));
2730            }
2731            assert!(stored_entry(&doc, &map, "nobody").is_none());
2732        }
2733
2734        phase one_walk_reads_what_key_by_key_reads;
2735        {
2736            let mut doc = Doc::new();
2737            let mut list: Collection<Vec<i64>> = Collection::new();
2738            for n in 0..40 {
2739                list.push(Id::from_raw(format!("i{n:02}")), vec![n]);
2740            }
2741            write_key(&mut doc, &ROOT, "items", &list).unwrap();
2742            doc.commit();
2743            // History under every key: moved order keys, rewritten values, a
2744            // removed item, and a stray non-entry value beside the entries.
2745            for round in 0..3_i64 {
2746                list.move_to(&Id::from_raw(format!("i{:02}", 39 - round)), 0);
2747                if let Some(item) = list.get_mut(&Id::from_raw("i05")) {
2748                    item.push(round);
2749                }
2750                write_key(&mut doc, &ROOT, "items", &list).unwrap();
2751                doc.commit();
2752            }
2753            list.remove(&Id::from_raw("i07"));
2754            write_key(&mut doc, &ROOT, "items", &list).unwrap();
2755            let Some((_, map)) = doc.get(&ROOT, "items").unwrap() else {
2756                panic!("the collection is stored");
2757            };
2758            doc.put(&map, "stray", 1_i64).unwrap();
2759            doc.commit();
2760            // Concurrent moves and inserts from two actors: conflicting order keys.
2761            let mut left = doc.fork();
2762            let mut right = doc.fork();
2763            let read: Collection<Vec<i64>> = read_key(&doc, &ROOT, "items").unwrap();
2764            let mut l = read.clone();
2765            l.move_to(&Id::from_raw("i10"), 2);
2766            l.insert(3, Id::from_raw("left"), vec![-1]);
2767            write_key(&mut left, &ROOT, "items", &l).unwrap();
2768            let mut r = read;
2769            r.move_to(&Id::from_raw("i10"), 30);
2770            r.insert(3, Id::from_raw("right"), vec![-2]);
2771            write_key(&mut right, &ROOT, "items", &r).unwrap();
2772            left.merge_incoming(&mut right).unwrap();
2773
2774            let Some((value, map)) = left.get(&ROOT, "items").unwrap() else {
2775                panic!("the collection is stored");
2776            };
2777            let read = Collection::<Vec<i64>>::load(&left, &value, &map).unwrap();
2778            let walked: Vec<_> = read
2779                .items
2780                .into_iter()
2781                .map(|entry| (entry.id, entry.key, (*entry.item).clone()))
2782                .collect();
2783            assert_eq!(walked, read_key_by_key::<Vec<i64>>(&left, &map));
2784            assert_eq!(walked.len(), 41);
2785        }
2786
2787        phase moves_touch_one_key_and_concurrent_inserts_keep_both;
2788        {
2789            let mut doc = Doc::new();
2790            let mut list: Collection<String> = Collection::new();
2791            for (n, word) in ["a", "b", "c", "d"].iter().enumerate() {
2792                list.push(Id::from_raw(format!("i{n}")), (*word).to_owned());
2793            }
2794            write_key(&mut doc, &ROOT, "items", &list).unwrap();
2795            doc.commit();
2796            list.move_to(&Id::from_raw("i3"), 0);
2797            write_key(&mut doc, &ROOT, "items", &list).unwrap();
2798            // One order key rewritten.
2799            assert_eq!(doc.pending_ops(), 1);
2800            doc.commit();
2801            let read: Collection<String> = read_key(&doc, &ROOT, "items").unwrap();
2802            assert_eq!(ids(&read), ["d", "a", "b", "c"]);
2803
2804            let mut left = doc.fork();
2805            let mut right = doc.fork();
2806            let mut l = read.clone();
2807            l.insert(1, Id::from_raw("left"), "L".into());
2808            write_key(&mut left, &ROOT, "items", &l).unwrap();
2809            let mut r = read;
2810            r.insert(1, Id::from_raw("right"), "R".into());
2811            r.remove(&Id::from_raw("i1"));
2812            write_key(&mut right, &ROOT, "items", &r).unwrap();
2813            left.merge_incoming(&mut right).unwrap();
2814            let merged: Collection<String> = read_key(&left, &ROOT, "items").unwrap();
2815            let merged = ids(&merged);
2816            assert_eq!(merged.len(), 5);
2817            assert_eq!(merged.first().map(String::as_str), Some("d"));
2818            assert!(merged.contains(&"L".to_owned()) && merged.contains(&"R".to_owned()));
2819            assert!(!merged.contains(&"b".to_owned()));
2820        }
2821    }
2822
2823    #[test]
2824    fn appended_items_keep_short_order_keys() {
2825        // One push per action, as a list someone adds to item by item, and a
2826        // bulk push: either way the stored keys stay a few characters long
2827        // (they grew by one character every ~6 items).
2828        let mut doc = Doc::new();
2829        let mut list: Collection<u32> = Collection::new();
2830        for n in 0..300_u32 {
2831            list.push(Id::from_raw(format!("one{n:05}")), n);
2832            write_key(&mut doc, &ROOT, "items", &list).unwrap();
2833            list = read_key(&doc, &ROOT, "items").unwrap();
2834        }
2835        for n in 0..10_000_u32 {
2836            list.push(Id::from_raw(format!("bulk{n:05}")), n);
2837        }
2838        write_key(&mut doc, &ROOT, "items", &list).unwrap();
2839        let Some((_, map)) = doc.get(&ROOT, "items").unwrap() else {
2840            panic!("the collection is stored");
2841        };
2842        let stored = stored_entries(&doc, &map);
2843        assert_eq!(stored.len(), 10_300);
2844        let longest = stored.iter().map(|entry| entry.key.len()).max().unwrap();
2845        assert!(longest <= 5, "longest order key: {longest} characters");
2846        let read: Collection<u32> = read_key(&doc, &ROOT, "items").unwrap();
2847        assert!(read.values().copied().eq((0..300).chain(0..10_000)));
2848    }
2849}