Skip to main content

tilo_resource/
evolution.rs

1//! How a resource's storage changes between versions of its app.
2//!
3//! A record stores the schema version it was written at under one key
4//! ([`VERSION_KEY`], read by [`stored_version`]); `#[resource(version = N,
5//! migrate = path)]` declares the current one and how to bring an older
6//! document up to it ([`rewrite`], after its derived steps). A document that does not read as the
7//! model is [`Unreadable`]: views show why and actions report it, and stale
8//! state is never shown as current.
9
10use automerge::transaction::{CommitOptions, Transactable};
11use automerge::{ObjId, ROOT, ReadDoc, ScalarValue, Value};
12use tilo_automerge::ApplyIncoming;
13use tilo_sort::CompactSort as _;
14
15use crate::model::{Doc, ModelError};
16use crate::resource::Resource;
17
18/// The root key a document's schema version is stored under, when it is past
19/// the first. Every document keeps it here: an app's record, a settings
20/// document, a `tilo-doc` page.
21pub const VERSION_KEY: &str = "tilo:version";
22
23/// The `u32` a stored version scalar names.
24fn version_of(value: &Value<'_>) -> Option<u32> {
25    let Value::Scalar(scalar) = value else {
26        return None;
27    };
28    match scalar.as_ref() {
29        ScalarValue::Uint(version) => Some(u32::try_from(*version).unwrap_or(u32::MAX)),
30        ScalarValue::Int(version) => Some(u32::try_from(*version).unwrap_or(u32::MAX)),
31        _ => None,
32    }
33}
34
35/// The schema version `doc` was written at: 1 when it names none.
36#[must_use]
37pub fn stored_version(doc: &Doc) -> u32 {
38    doc.get(&ROOT, VERSION_KEY)
39        .ok()
40        .flatten()
41        .and_then(|(value, _)| version_of(&value))
42        .unwrap_or(1)
43}
44
45/// Record that `doc` is at `version` (nothing for the first version, so
46/// documents of apps that never changed their storage stay as they are).
47pub fn write_version(doc: &mut Doc, version: u32) -> Result<(), ModelError> {
48    write_version_at(doc, &ROOT, version)
49}
50
51/// [`write_version`] of the document whose root is `at`.
52pub fn write_version_at(doc: &mut Doc, at: &ObjId, version: u32) -> Result<(), ModelError> {
53    if version > 1 || doc.get(at, VERSION_KEY)?.is_some() {
54        doc.put(at, VERSION_KEY, ScalarValue::Uint(u64::from(version)))?;
55    }
56    Ok(())
57}
58
59/// The step that brings the record `scope` names to `version`: the change every holder makes alike,
60/// under an actor derived from the record, its workspace and the version alone, at time zero,
61/// writing the version key and nothing else. `before` holds exactly the link it follows, the
62/// record's founding for the first version and the step to the version before otherwise, so the
63/// chain a record stands on is one every holder derives ([`crate::founding::chain`]), however its
64/// content went on meanwhile.
65///
66/// # Errors
67/// When `before` holds no heads to step from, or the step cannot be committed.
68pub fn step(
69    scope: crate::founding::Scope<'_>,
70    version: u32,
71    before: &Doc,
72) -> Result<automerge::Change, automerge::AutomergeError> {
73    let crate::founding::Scope {
74        workspace,
75        kind,
76        id,
77    } = scope;
78    let mut doc = before.clone().with_actor(crate::genesis::actor(
79        id,
80        kind,
81        &format!("version {version} in {workspace}"),
82    ));
83    doc.put(ROOT, VERSION_KEY, ScalarValue::Uint(u64::from(version)))?;
84    let context = tilo_actions::ActionContext {
85        change: tilo_actions::ChangeKind::Housekeeping,
86        ..tilo_actions::ActionContext::for_resource(id, kind, kind).with_described(
87            tilo_actions::Described::new(tilo_actions::Did::history(
88                tilo_actions::HistoryOp::Migrate {
89                    to: version,
90                    rewrite: false,
91                },
92                0,
93                None,
94            )),
95        )
96    };
97    let mut options = CommitOptions::default().with_time(0);
98    if let Some(message) = context.change_message() {
99        options = options.with_message(message);
100    }
101    let hash = doc
102        .commit_with(options)
103        .ok_or(automerge::AutomergeError::Fail)?;
104    doc.get_change_by_hash(&hash)
105        .ok_or(automerge::AutomergeError::MissingHash(hash))
106}
107
108/// Whether `doc` holds `R` at a version this build reads: its own or an older one, whose chain
109/// of steps stops short and is brought up before it opens. A newer version only adds fields and
110/// containers to a type, so this build's fields are all still there and it reads them as far as
111/// it knows the record.
112///
113/// # Errors
114/// Returns why not: the record waits for its steps to be brought up.
115pub fn check_version<R: Resource>(doc: &Doc) -> Result<(), ModelError> {
116    let (stored, version) = (stored_version(doc), R::VERSION);
117    if stored < version {
118        return Err(ModelError::invalid(format!(
119            "stored at version {stored}; it is brought up to version {version} when it opens"
120        )));
121    }
122    Ok(())
123}
124
125/// Whether `doc` is older than `R`: its chain of steps stops short of `R`'s version, so it is
126/// brought up ([`crate::founding::bring_up`]) before it is read.
127#[must_use]
128pub fn needs_migrate<R: Resource>(doc: &Doc) -> bool {
129    stored_version(doc) < R::VERSION
130}
131
132/// The app's own rewrite of the record `scope` names for `version`, from the version `from` it
133/// stood at, by `migration` (its `#[resource(migrate = ..)]`): once, as one housekeeping change
134/// after the record's step to `version`, made by an actor and at a time derived from the record,
135/// its workspace, the version and the heads it starts from, so two holders rewriting the same
136/// history make the same change. It is decided as any write of the record's. A rewrite rewrites by
137/// key and never inserts list elements, so two holders rewriting apart converge on one item each.
138/// Whether it changed anything.
139///
140/// # Errors
141/// Returns the migration's error; `doc` is left as it was.
142pub fn rewrite(
143    (scope, version): (crate::founding::Scope<'_>, u32),
144    from: u32,
145    migration: &dyn Fn(&mut Doc, u32) -> Result<(), ModelError>,
146    doc: &mut Doc,
147) -> Result<bool, ModelError> {
148    let crate::founding::Scope {
149        workspace,
150        kind,
151        id,
152    } = scope;
153    let mut heads = doc.get_heads();
154    heads.compact_sort();
155    let mut on: Vec<String> = heads.iter().map(ToString::to_string).collect();
156    on.sort();
157    let actor = crate::genesis::actor(
158        id,
159        kind,
160        &format!(
161            "rewrite to version {version} on {} in {workspace}",
162            on.join(",")
163        ),
164    );
165    let mut migrated = doc.fork_at(&heads)?.with_actor(actor);
166    if from < version {
167        migration(&mut migrated, from)?;
168    }
169    // A record whose version key was written beside its chain (by an initializer, or a migration
170    // made before its steps were derived) reads that write against the step's: the rewrite,
171    // which follows both, says the version once.
172    if stored_version(&migrated) < version {
173        migrated.put(ROOT, VERSION_KEY, ScalarValue::Uint(u64::from(version)))?;
174    }
175    if migrated.pending_ops() == 0 {
176        return Ok(false);
177    }
178    let context = tilo_actions::ActionContext {
179        change: tilo_actions::ChangeKind::Housekeeping,
180        ..tilo_actions::ActionContext::for_resource(id, kind, kind).with_described(
181            tilo_actions::Described::new(tilo_actions::Did::history(
182                tilo_actions::HistoryOp::Migrate {
183                    to: version,
184                    rewrite: true,
185                },
186                0,
187                None,
188            )),
189        )
190    };
191    let mut options = CommitOptions::default().with_time(0);
192    if let Some(message) = context.change_message() {
193        options = options.with_message(message);
194    }
195    migrated.commit_with(options);
196    let changes = migrated.get_changes(&heads);
197    doc.apply_incoming(changes)?;
198    Ok(true)
199}
200
201/// Write what the record `from` holds into the record `to`, another record of
202/// the same kind and storage version kept elsewhere: what a record moving
203/// from one store to another takes along. Every field is copied as it is
204/// stored, scalars with their types, maps, lists and texts; the record's own
205/// identity (its `tilo:` keys other than [`VERSION_KEY`]) stays `to`'s. A
206/// map or text `to` already holds at a key is written into rather than
207/// replaced, so what another writer adds to it concurrently is kept.
208///
209/// # Errors
210/// Returns the document's read or write error.
211pub fn copy_into(from: &Doc, to: &mut Doc) -> Result<(), ModelError> {
212    for key in from.keys(&ROOT).collect::<Vec<_>>() {
213        if key.starts_with("tilo:") && key != VERSION_KEY {
214            continue;
215        }
216        if let Some((value, obj)) = from.get(&ROOT, key.as_str())? {
217            copy_value(from, &value, &obj, to, &ROOT, Place::Key(&key))?;
218        }
219    }
220    Ok(())
221}
222
223/// Where [`copy_value`] writes: under a key of a map, or at an index of a
224/// list.
225enum Place<'a> {
226    Key(&'a str),
227    Insert(usize),
228}
229
230fn copy_value(
231    from: &Doc,
232    value: &Value<'_>,
233    obj: &ObjId,
234    to: &mut Doc,
235    into: &ObjId,
236    place: Place<'_>,
237) -> Result<(), ModelError> {
238    use automerge::ObjType;
239    let Value::Object(kind) = value else {
240        let Value::Scalar(scalar) = value else {
241            return Ok(());
242        };
243        let scalar = scalar.as_ref().clone();
244        match place {
245            Place::Key(key) => to.put(into, key, scalar)?,
246            Place::Insert(index) => to.insert(into, index, scalar)?,
247        }
248        return Ok(());
249    };
250    let kind = match kind {
251        ObjType::Table => ObjType::Map,
252        other => *other,
253    };
254    let held = match place {
255        Place::Key(key) => match to.get(into, key)? {
256            Some((Value::Object(held), id)) if held == kind => Some(id),
257            _ => None,
258        },
259        Place::Insert(_) => None,
260    };
261    let target = match (held, place) {
262        (Some(id), _) => id,
263        (None, Place::Key(key)) => to.put_object(into, key, kind)?,
264        (None, Place::Insert(index)) => to.insert_object(into, index, kind)?,
265    };
266    match kind {
267        ObjType::Text => {
268            let text = from.text(obj)?;
269            let length = to.length(&target);
270            to.splice_text(
271                &target,
272                0,
273                isize::try_from(length).unwrap_or(isize::MAX),
274                &text,
275            )?;
276        }
277        ObjType::List => {
278            let start = to.length(&target);
279            for index in 0..from.length(obj) {
280                if let Some((item, item_obj)) = from.get(obj, index)? {
281                    copy_value(
282                        from,
283                        &item,
284                        &item_obj,
285                        to,
286                        &target,
287                        Place::Insert(start.saturating_add(index)),
288                    )?;
289                }
290            }
291        }
292        ObjType::Map | ObjType::Table => {
293            for key in from.keys(obj).collect::<Vec<_>>() {
294                if let Some((item, item_obj)) = from.get(obj, key.as_str())? {
295                    copy_value(from, &item, &item_obj, to, &target, Place::Key(&key))?;
296                }
297            }
298        }
299    }
300    Ok(())
301}
302
303/// Write the keys of the JSON object `shape` into the map `obj` as an older
304/// version of an app stored them: what a migration's test builds the
305/// document it migrates from. An object is a map, an array a list, a string,
306/// a boolean and a number are scalars (an integer as `Int`), `null` is a
307/// null scalar, and `{"$text": "…"}` is a text object holding the string.
308///
309/// # Errors
310/// Returns the document's write error, or that `shape` is no object.
311pub fn fixture(doc: &mut Doc, obj: &ObjId, shape: &serde_json::Value) -> Result<(), ModelError> {
312    let serde_json::Value::Object(fields) = shape else {
313        return Err(ModelError::shape("an object of fields"));
314    };
315    for (key, value) in fields {
316        fixture_value(doc, crate::Slot::Key(obj, key), value)?;
317    }
318    Ok(())
319}
320
321fn fixture_value(
322    doc: &mut Doc,
323    slot: crate::Slot<'_>,
324    value: &serde_json::Value,
325) -> Result<(), ModelError> {
326    use automerge::ObjType;
327    use serde_json::Value as Json;
328    match value {
329        Json::Object(fields) if fields.len() == 1 && fields.contains_key("$text") => {
330            let Some(Json::String(text)) = fields.get("$text") else {
331                return Err(ModelError::shape("a text's string"));
332            };
333            let obj = slot.object(doc, ObjType::Text)?;
334            crate::TextEdit::ReplaceText { text: text.clone() }
335                .apply_under(doc, &obj)
336                .map_err(|error| ModelError::invalid(error.to_string()))
337        }
338        Json::Object(_) => {
339            let obj = slot.object(doc, ObjType::Map)?;
340            fixture(doc, &obj, value)
341        }
342        Json::Array(items) => {
343            let obj = slot.object(doc, ObjType::List)?;
344            for (index, item) in items.iter().enumerate() {
345                fixture_value(doc, crate::Slot::Insert(&obj, index), item)?;
346            }
347            Ok(())
348        }
349        Json::String(text) => slot.put_scalar(doc, ScalarValue::Str(text.as_str().into())),
350        Json::Bool(flag) => slot.put_scalar(doc, ScalarValue::Boolean(*flag)),
351        Json::Number(number) => slot.put_scalar(
352            doc,
353            match (number.as_i64(), number.as_u64(), number.as_f64()) {
354                (Some(int), _, _) => ScalarValue::Int(int),
355                (None, Some(uint), _) => ScalarValue::Uint(uint),
356                (None, None, Some(float)) => ScalarValue::F64(float),
357                (None, None, None) => return Err(ModelError::shape("a number")),
358            },
359        ),
360        Json::Null => slot.put_scalar(doc, ScalarValue::Null),
361    }
362}
363
364/// A document that does not read as its resource: what a view shows in
365/// place of stale state, and why each action is unavailable.
366#[derive(Clone, Debug, PartialEq, Eq)]
367pub struct Unreadable {
368    /// Why, in the words of the read: where it failed and what it expected.
369    pub reason: String,
370    /// The storage version the document names.
371    pub stored: u32,
372    /// The version the app reads.
373    pub expected: u32,
374}
375
376impl std::fmt::Display for Unreadable {
377    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
378        f.write_str(&self.reason)
379    }
380}
381
382impl Unreadable {
383    /// Why `doc` did not read as `R`, from the read's `error`.
384    #[must_use]
385    pub fn of<R: Resource>(doc: &Doc, error: &ModelError) -> Self {
386        Self {
387            reason: error.to_string(),
388            stored: stored_version(doc),
389            expected: R::VERSION,
390        }
391    }
392}
393
394/// Read `R` from `doc`, or say why it does not read.
395///
396/// # Errors
397/// Returns the [`Unreadable`] state.
398pub fn read_checked<R: Resource>(doc: &Doc) -> Result<R::State, Unreadable> {
399    check_version::<R>(doc)
400        .and_then(|()| R::read(doc))
401        .map_err(|error| Unreadable::of::<R>(doc, &error))
402}