Skip to main content

tilo_resource/
founding.rs

1//! The founding an app's record is derived from: what every holder makes of it alike.
2//!
3//! An app's record holds its content alone. Two devices that make the same record before they
4//! sync (a person's vault opened on a phone and a laptop at once) would each make the containers
5//! its fields keep their items in, and the items one of them adds first would land in a
6//! container the merge leaves behind. So the containers come first, in one change every holder
7//! derives from the record's workspace, kind and id alone ([`Scope`]): an actor derived from them
8//! makes it at time zero. The store admits that change only as the one it derives itself
9//! ([`structure`]); the app's own first values follow as any change of its.
10//!
11//! The workspace is part of every derivation. A record's id can be the same in every workspace
12//! (a workspace's own accounts record), and a change two workspaces both held would be one
13//! change in both: a host keeping both would refuse the second, and the hash would link records
14//! the workspaces keep apart.
15
16use automerge::transaction::{CommitOptions, Transactable as _};
17use automerge::{AutoCommit, ObjType, ROOT};
18use tilo_actions::surface::{FieldType, Surface};
19use tilo_automerge::ApplyIncoming as _;
20
21pub mod split;
22
23/// The record a founding and its steps are derived for: the record `id` of `kind` in the
24/// workspace `workspace`. A record is always one workspace's, so two workspaces holding a record
25/// of the same kind and id still derive changes of their own, and the holders within one derive
26/// the same.
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub struct Scope<'a> {
29    pub workspace: &'a str,
30    pub kind: &'a str,
31    pub id: &'a str,
32}
33
34impl Scope<'_> {
35    /// The actor the record's founding is made under ([`structure`]). It is salted apart from
36    /// the actor of the record's identity genesis, which is derived from the same id, kind and
37    /// workspace: two different changes under one actor and sequence number would not merge.
38    #[must_use]
39    pub fn founding_actor(self) -> automerge::ActorId {
40        crate::genesis::actor(
41            self.id,
42            self.kind,
43            &format!("founding in {}", self.workspace),
44        )
45    }
46}
47
48/// The containers at the root of `surface`'s record that its top-level fields keep their items
49/// in, by field name: a collection, map, set or outbox in a map, a list in a list, a record of
50/// its own in a map: what [`structure`] makes.
51///
52/// An outbox is one of them: it is a unit the kind declares, empty when the record is founded,
53/// and a record whose every field is read-only takes no write to make it. Built by its creator
54/// instead, it would be the one change such a kind could not take, from the app or anyone.
55#[must_use]
56pub fn containers(surface: &Surface) -> Vec<(String, ObjType)> {
57    let mut containers: Vec<(String, ObjType)> = surface
58        .fields
59        .iter()
60        .filter(|field| !field.path.contains('.'))
61        .filter_map(|field| {
62            let container = match &field.ty {
63                // A set is a map whose keys are its members, as the resource types keep one.
64                FieldType::Collection(_)
65                | FieldType::Map(_)
66                | FieldType::Set(_)
67                | FieldType::Outbox(_) => ObjType::Map,
68                FieldType::List(_) => ObjType::List,
69                FieldType::Named(_) if field.stored == "record" => ObjType::Map,
70                _ => return None,
71            };
72            Some((field.path.clone(), container))
73        })
74        .collect();
75    containers.sort_by(|a, b| a.0.cmp(&b.0));
76    containers.dedup_by(|a, b| a.0 == b.0);
77    containers
78}
79
80/// The containers a record of `surface`'s kind founds with: its own record's ([`containers`]),
81/// as the store reads the kind's type from the surface. A surface naming its record by its label
82/// declares no type of its kind, and an enum of its kind is no record: either founds with none.
83#[must_use]
84pub fn of_kind(surface: &Surface) -> Vec<(String, ObjType)> {
85    let named = |name: &str| surface.types.iter().find(|ty| ty.name == name);
86    let own = match named(&surface.kind) {
87        Some(ty) => !ty.is_enum(),
88        None => named(&surface.label).is_none(),
89    };
90    if own { containers(surface) } else { Vec::new() }
91}
92
93/// The derived founding of the record `scope` names, whose fields keep their items in the
94/// `containers` named at its root. A kind that keeps none founds with a change that holds nothing:
95/// every record has its founding as its first head, so a record nothing was written to yet is kept
96/// and read back like any other, and what follows the founding names it as its dependency.
97///
98/// # Errors
99/// When a container cannot be put at the root under its field's name (an empty name).
100pub fn structure(
101    scope: Scope<'_>,
102    containers: &[(String, ObjType)],
103) -> Result<automerge::Change, automerge::AutomergeError> {
104    let mut doc = AutoCommit::new().with_actor(scope.founding_actor());
105    for (field, container) in containers {
106        doc.put_object(ROOT, field.as_str(), *container)?;
107    }
108    let options = || {
109        CommitOptions::default()
110            .with_message(tilo_actions::FrameworkChange::Genesis.change_message())
111            .with_time(0)
112    };
113    // A kind keeping no container commits nothing, so its founding is an empty change.
114    let hash = match doc.commit_with(options()) {
115        Some(hash) => hash,
116        None => doc.empty_change(options()),
117    };
118    doc.get_change_by_hash(&hash)
119        .ok_or(automerge::AutomergeError::MissingHash(hash))
120}
121
122/// The derived founding of the record `scope` names ([`structure`]) followed by the steps that
123/// bring it to each version up to `version` ([`crate::evolution::step`]): the chain every
124/// holder of a record at `version` stands on. Each step follows the one before it, the first the
125/// founding, so two holders that wrote their own changes meanwhile still make it byte for byte
126/// alike.
127///
128/// # Errors
129/// When the founding or a step cannot be made ([`structure`]).
130pub fn chain(
131    scope: Scope<'_>,
132    version: u32,
133    containers: &[(String, ObjType)],
134) -> Result<Vec<automerge::Change>, automerge::AutomergeError> {
135    let founding = structure(scope, containers)?;
136    let mut doc = AutoCommit::new();
137    doc.apply_incoming([founding.clone()])?;
138    let mut chain = vec![founding];
139    for version in 1..=version {
140        let step = crate::evolution::step(scope, version, &doc)?;
141        doc.apply_incoming([step.clone()])?;
142        chain.push(step);
143    }
144    Ok(chain)
145}
146
147/// The step that brings the record `scope` names to `version`, on the chain [`chain`] derives:
148/// the one change a store admits under the migration verb for that version, and the one every
149/// holder writes.
150///
151/// # Errors
152/// When the chain cannot be made ([`chain`]), or `version` is no version a record steps to (0).
153pub fn migrate(
154    scope: Scope<'_>,
155    version: u32,
156    containers: &[(String, ObjType)],
157) -> Result<automerge::Change, automerge::AutomergeError> {
158    chain(scope, version, containers)?
159        .pop()
160        .filter(|_| version > 0)
161        .ok_or(automerge::AutomergeError::Fail)
162}
163
164/// Bring the record `scope` names, the app `app`'s, to `version`, in the one way every holder
165/// does: a record made before its founding was derived (two devices' own root containers) takes
166/// the founding and has what its devices made apart brought together
167/// ([`split::merge_split_containers`]); then the chain of steps up to `version`
168/// ([`chain`]) is written where it is not yet, and last the app's own `rewrite` of its content
169/// from the version the record stood at ([`crate::evolution::rewrite`]). Whether this
170/// changed anything.
171///
172/// # Errors
173/// When the founding, a step or the merge cannot be made, or the app's rewrite fails; `doc` is
174/// left with what was written before it.
175pub fn bring_up(
176    (scope, app): (Scope<'_>, &str),
177    version: u32,
178    containers: &[(String, ObjType)],
179    rewrite: &dyn Fn(&mut AutoCommit, u32) -> Result<(), crate::ModelError>,
180    doc: &mut AutoCommit,
181) -> Result<bool, crate::ModelError> {
182    let from = crate::evolution::stored_version(doc);
183    let mut changed = found((scope, app), containers, doc)?;
184    let chain = chain(scope, version, containers)?;
185    let missing: Vec<automerge::Change> = chain
186        .into_iter()
187        .filter(|link| doc.get_change_by_hash(&link.hash()).is_none())
188        .collect();
189    changed |= !missing.is_empty();
190    doc.apply_incoming(missing)?;
191    if from < version || crate::evolution::stored_version(doc) < version {
192        changed |= crate::evolution::rewrite((scope, version), from, rewrite, doc)?;
193    }
194    Ok(changed)
195}
196
197/// Give the record `scope` names, the app `app`'s, its derived founding when it was made without
198/// one (two devices' own root containers, before every holder derived it), and bring together
199/// what its devices made apart ([`split::merge_split_containers`]): once, the first part
200/// of [`bring_up`], and all a store that reads no type's version does on opening a record.
201/// Whether this changed anything.
202///
203/// # Errors
204/// When the founding or the merge cannot be made.
205pub fn found(
206    (scope, app): (Scope<'_>, &str),
207    containers: &[(String, ObjType)],
208    doc: &mut AutoCommit,
209) -> Result<bool, automerge::AutomergeError> {
210    let founding = structure(scope, containers)?;
211    if doc.get_change_by_hash(&founding.hash()).is_some() {
212        return Ok(false);
213    }
214    doc.apply_incoming([founding])?;
215    split::merge_split_containers(doc, scope, containers, app)?;
216    Ok(true)
217}
218
219/// [`bring_up`] of the record `id` of the resource type `R` in `workspace`, by the containers and
220/// version its surface declares and its own migration (`#[resource(migrate = ..)]`).
221///
222/// # Errors
223/// As [`bring_up`].
224pub fn bring_up_resource<R: crate::Resource>(
225    workspace: &str,
226    id: &str,
227    doc: &mut AutoCommit,
228) -> Result<bool, crate::ModelError> {
229    let scope = Scope {
230        workspace,
231        kind: R::KIND,
232        id,
233    };
234    bring_up(
235        (scope, R::APP_ID),
236        R::VERSION,
237        &of_kind(&crate::surface::surface_of::<R>()),
238        &|doc: &mut AutoCommit, from: u32| R::migrate(doc, from),
239        doc,
240    )
241}
242
243/// A new record `id` of `R` in `workspace`: its derived founding and the steps to `R`'s version
244/// ([`chain`]), then `R`'s first values, left uncommitted for the caller to commit under its own
245/// message. Its version comes from the chain alone, as every holder of the record derives it.
246///
247/// # Errors
248/// When the chain cannot be made, or `R`'s initializer fails.
249pub fn new_record<R: crate::Resource>(
250    workspace: &str,
251    id: &str,
252) -> Result<AutoCommit, crate::ModelError> {
253    let mut doc = AutoCommit::new();
254    let containers = of_kind(&crate::surface::surface_of::<R>());
255    let scope = Scope {
256        workspace,
257        kind: R::KIND,
258        id,
259    };
260    doc.apply_incoming(chain(scope, R::VERSION, &containers)?)?;
261    R::initialize(&mut doc)?;
262    Ok(doc)
263}
264
265#[cfg(test)]
266mod tests {
267    #![allow(clippy::unwrap_used, reason = "tests")]
268
269    use crate::evolution::{VERSION_KEY, stored_version};
270    use automerge::transaction::Transactable as _;
271    use automerge::{AutoCommit, ObjType, ROOT, ReadDoc as _};
272    use tilo_automerge::ApplyIncoming as _;
273
274    const KIND: &str = "test.founding.chain";
275    const ID: &str = "groceries";
276    const APP: &str = "test.app";
277    const SCOPE: super::Scope<'static> = super::Scope {
278        workspace: "6f1c1b62-4f5e-4b8a-9b52-1f8a3f0f3a11",
279        kind: KIND,
280        id: ID,
281    };
282
283    fn containers() -> Vec<(String, ObjType)> {
284        vec![("items".to_owned(), ObjType::Map)]
285    }
286
287    /// A record founded at `version` on a device of its own, with `wrote` written under `key` of
288    /// its items as that device's change.
289    fn device(version: u32, actor: u8, key: &str, wrote: &str) -> AutoCommit {
290        let mut doc = AutoCommit::new().with_actor(automerge::ActorId::from([actor; 16]));
291        doc.apply_incoming(super::chain(SCOPE, version, &containers()).unwrap())
292            .unwrap();
293        let (_, items) = doc.get(ROOT, "items").unwrap().unwrap();
294        doc.put(&items, key, wrote).unwrap();
295        doc.commit();
296        doc
297    }
298
299    /// A type whose versions change nothing but the version itself.
300    fn unchanged() -> impl Fn(&mut AutoCommit, u32) -> Result<(), crate::ModelError> {
301        |_, _| Ok(())
302    }
303
304    fn items(doc: &AutoCommit) -> Vec<String> {
305        let (_, items) = doc.get(ROOT, "items").unwrap().unwrap();
306        doc.keys(&items).collect()
307    }
308
309    /// A kind's outbox is one of its containers, founded empty on every holder alike: a record
310    /// whose every field is read-only would take no change to make it, from the app or anyone.
311    #[test]
312    fn a_kinds_queue_is_founded_with_its_containers() {
313        let surface: crate::Surface = serde_json::from_value(serde_json::json!({
314            "kind": "terminal.session",
315            "label": "Terminal",
316            "version": 1,
317            "fields": [
318                {
319                    "path": "requests",
320                    "type": {"outbox": {"named": "CommandRequest"}},
321                    "readonly": true,
322                    "unit": true
323                }
324            ],
325            "verbs": [],
326            "types": []
327        }))
328        .unwrap();
329        assert_eq!(
330            super::containers(&surface),
331            vec![("requests".to_owned(), ObjType::Map)],
332            "the outbox is founded like a map the kind keeps its items in"
333        );
334        let founding = super::structure(SCOPE, &super::containers(&surface)).unwrap();
335        let mut doc = AutoCommit::new();
336        doc.apply_incoming([founding]).unwrap();
337        assert_eq!(
338            doc.get(ROOT, "requests").unwrap().map(|(value, _)| value),
339            Some(automerge::Value::Object(ObjType::Map)),
340            "founded, and empty"
341        );
342    }
343
344    #[test]
345    fn two_devices_with_their_own_writes_step_a_record_up_byte_for_byte_alike() {
346        let mut here = device(1, 1, "milk", "2 l");
347        let mut there = device(1, 2, "eggs", "6");
348        let (own_heads, peer_heads) = (here.get_heads(), there.get_heads());
349        assert!(super::bring_up((SCOPE, APP), 3, &containers(), &unchanged(), &mut here).unwrap());
350        assert!(super::bring_up((SCOPE, APP), 3, &containers(), &unchanged(), &mut there).unwrap());
351        let bytes = |changes: Vec<automerge::Change>| -> Vec<Vec<u8>> {
352            changes
353                .into_iter()
354                .map(|change| change.raw_bytes().to_vec())
355                .collect()
356        };
357        let ours = bytes(here.get_changes(&own_heads));
358        let theirs = bytes(there.get_changes(&peer_heads));
359        // Each device wrote the steps to versions 2 and 3 and nothing else, and both wrote the
360        // same bytes: the derived ones, whatever each device's own writes were.
361        assert_eq!(ours, theirs);
362        assert_eq!(
363            ours,
364            bytes(super::chain(SCOPE, 3, &containers()).unwrap().split_off(2))
365        );
366        for (to, step) in (2..=3).zip(super::chain(SCOPE, 3, &containers()).unwrap().split_off(2)) {
367            assert_eq!(
368                super::migrate(SCOPE, to, &containers()).unwrap().hash(),
369                step.hash()
370            );
371        }
372        tilo_automerge::ApplyIncoming::merge_incoming(&mut here, &mut there).unwrap();
373        assert_eq!(stored_version(&here), 3);
374        assert_eq!(items(&here), ["eggs", "milk"]);
375        // Brought up already: nothing more.
376        assert!(!super::bring_up((SCOPE, APP), 3, &containers(), &unchanged(), &mut here).unwrap());
377    }
378
379    #[test]
380    fn a_rewrite_two_devices_make_apart_keeps_one_default() {
381        // Version 2 adds the record's tags, and each device's rewrite fills the default in on its
382        // own history: the two rewrites make the same key once, and each device's items stay.
383        let mut here = device(1, 1, "milk", "2 l");
384        let mut there = here.fork().with_actor(automerge::ActorId::from([2; 16]));
385        let (_, kept) = there.get(ROOT, "items").unwrap().unwrap();
386        there.put(&kept, "eggs", "6").unwrap();
387        there.commit();
388        let add_tags = |doc: &mut AutoCommit, from: u32| {
389            assert_eq!(from, 1);
390            let tags = doc.put_object(ROOT, "tags", ObjType::Map)?;
391            doc.put(&tags, "default", "kept")?;
392            Ok(())
393        };
394        super::bring_up((SCOPE, APP), 2, &containers(), &add_tags, &mut here).unwrap();
395        super::bring_up((SCOPE, APP), 2, &containers(), &add_tags, &mut there).unwrap();
396        tilo_automerge::ApplyIncoming::merge_incoming(&mut here, &mut there).unwrap();
397        let (_, tags) = here.get(ROOT, "tags").unwrap().unwrap();
398        assert_eq!(here.keys(&tags).collect::<Vec<_>>(), ["default"]);
399        assert_eq!(items(&here), ["eggs", "milk"]);
400        assert_eq!(stored_version(&here), 2);
401    }
402
403    #[test]
404    fn a_record_made_before_its_founding_was_derived_is_founded_once_and_brought_together() {
405        // Two devices each made the record's container of their own, and added to it.
406        let made = |actor: u8, key: &str| {
407            let mut doc = AutoCommit::new().with_actor(automerge::ActorId::from([actor; 16]));
408            let items = doc.put_object(ROOT, "items", ObjType::Map).unwrap();
409            doc.put(&items, key, "kept").unwrap();
410            doc.commit();
411            doc
412        };
413        let mut here = made(1, "milk");
414        let mut there = made(2, "eggs");
415        tilo_automerge::ApplyIncoming::merge_incoming(&mut here, &mut there).unwrap();
416        let mut again = here.fork();
417        assert!(super::bring_up((SCOPE, APP), 2, &containers(), &unchanged(), &mut here).unwrap());
418        assert!(super::bring_up((SCOPE, APP), 2, &containers(), &unchanged(), &mut again).unwrap());
419        // Every holder converts it alike.
420        assert_eq!(here.get_heads(), again.get_heads());
421        let founding = super::structure(SCOPE, &containers()).unwrap();
422        assert!(here.get_change_by_hash(&founding.hash()).is_some());
423        let mut held = items(&here);
424        held.sort();
425        assert_eq!(held, ["eggs", "milk"]);
426        assert_eq!(stored_version(&here), 2);
427        assert!(here.get(ROOT, VERSION_KEY).unwrap().is_some());
428        assert!(!super::bring_up((SCOPE, APP), 2, &containers(), &unchanged(), &mut here).unwrap());
429    }
430
431    #[test]
432    fn the_same_record_in_two_workspaces_shares_no_change() {
433        // A workspace's own records have the same id in every workspace; a host holding two
434        // workspaces keeps each one's apart, so neither the founding nor a step may be the same
435        // change in both.
436        let other = super::Scope {
437            workspace: "0b9d7a3e-2c41-4f6b-8e15-7a9c3d2e1f40",
438            ..SCOPE
439        };
440        let hashes = |scope| -> Vec<automerge::ChangeHash> {
441            super::chain(scope, 3, &containers())
442                .unwrap()
443                .iter()
444                .map(automerge::Change::hash)
445                .collect()
446        };
447        let (here, there) = (hashes(SCOPE), hashes(other));
448        assert_eq!(here.len(), 4);
449        assert!(here.iter().all(|hash| !there.contains(hash)));
450        assert_ne!(
451            super::structure(SCOPE, &containers()).unwrap().hash(),
452            super::structure(other, &containers()).unwrap().hash()
453        );
454        // Nor is its actor the one the record's identity genesis in its workspace is made under,
455        // which a record founded beside that genesis would hold two first changes of.
456        assert_ne!(
457            SCOPE.founding_actor(),
458            crate::genesis::actor(ID, KIND, SCOPE.workspace)
459        );
460        // Brought up from records each workspace's devices made apart, neither shares a change
461        // with the other either.
462        let mut here_doc = device(1, 1, "milk", "2 l");
463        let mut there_doc = AutoCommit::new().with_actor(automerge::ActorId::from([1; 16]));
464        there_doc
465            .apply_incoming(super::chain(other, 1, &containers()).unwrap())
466            .unwrap();
467        super::bring_up((SCOPE, APP), 3, &containers(), &unchanged(), &mut here_doc).unwrap();
468        super::bring_up((other, APP), 3, &containers(), &unchanged(), &mut there_doc).unwrap();
469        let held = |doc: &mut AutoCommit| -> Vec<automerge::ChangeHash> {
470            doc.get_changes(&[])
471                .iter()
472                .map(automerge::Change::hash)
473                .collect()
474        };
475        let there_held = held(&mut there_doc);
476        assert!(
477            held(&mut here_doc)
478                .iter()
479                .all(|hash| !there_held.contains(hash))
480        );
481    }
482}