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 ([`migrate`]). 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, LocatedAt as _, 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    stored_version_at(doc, &ROOT)
39}
40
41/// [`stored_version`] of the document whose root is `at`.
42#[must_use]
43pub fn stored_version_at(doc: &Doc, at: &ObjId) -> u32 {
44    doc.get(at, VERSION_KEY)
45        .ok()
46        .flatten()
47        .and_then(|(value, _)| version_of(&value))
48        .unwrap_or(1)
49}
50
51/// Record that `doc` is at `version` (nothing for the first version, so
52/// documents of apps that never changed their storage stay as they are).
53pub fn write_version(doc: &mut Doc, version: u32) -> Result<(), ModelError> {
54    write_version_at(doc, &ROOT, version)
55}
56
57/// [`write_version`] of the document whose root is `at`.
58pub fn write_version_at(doc: &mut Doc, at: &ObjId, version: u32) -> Result<(), ModelError> {
59    if version > 1 || doc.get(at, VERSION_KEY)?.is_some() {
60        doc.put(at, VERSION_KEY, ScalarValue::Uint(u64::from(version)))?;
61    }
62    Ok(())
63}
64
65/// Whether `doc` holds `R` at the version the app reads.
66///
67/// # Errors
68/// Returns why not: written by a newer version of the app, or waiting for
69/// [`migrate`].
70pub fn check_version<R: Resource>(doc: &Doc) -> Result<(), ModelError> {
71    check_version_at(R::VERSION, doc)
72}
73
74/// [`check_version`] of a resource read at `version`.
75fn check_version_at(version: u32, doc: &Doc) -> Result<(), ModelError> {
76    let stored = stored_version(doc);
77    match stored.cmp(&version) {
78        std::cmp::Ordering::Equal => Ok(()),
79        std::cmp::Ordering::Greater => Err(ModelError::invalid(format!(
80            "written by a newer version of the app (storage version {stored}, this app reads {version})"
81        ))),
82        std::cmp::Ordering::Less => Err(ModelError::invalid(format!(
83            "stored at version {stored}; it is brought up to version {version} when it opens"
84        ))),
85    }
86}
87
88/// Bring `doc` up to `R`'s version with its migration, and to this build's
89/// version key: once, as one housekeeping change made by an actor and at a
90/// time derived from the resource kind, the versions and the heads it starts
91/// from, so two devices migrating the same document produce the same change.
92/// Returns whether it changed anything.
93///
94/// # Errors
95/// Returns the migration's error; `doc` is left as it was.
96pub fn migrate<R: Resource>(doc: &mut Doc) -> Result<bool, ModelError> {
97    migrate_with(
98        (R::KIND, R::LABEL, R::VERSION),
99        &|doc: &mut Doc, from: u32| R::migrate(doc, from),
100        doc,
101    )
102}
103
104/// Whether [`migrate`] would change `doc`: it is older than `R`.
105#[must_use]
106pub fn needs_migrate<R: Resource>(doc: &Doc) -> bool {
107    stored_version(doc) < R::VERSION
108}
109
110/// [`migrate`] of the resource of the kind, label and storage version
111/// `resource`, whose migration is `migration`.
112fn migrate_with(
113    (kind, label, to): (&str, &str, u32),
114    migration: &dyn Fn(&mut Doc, u32) -> Result<(), ModelError>,
115    doc: &mut Doc,
116) -> Result<bool, ModelError> {
117    let from = stored_version(doc);
118    if from >= to {
119        return Ok(false);
120    }
121    let mut heads = doc.get_heads();
122    heads.compact_sort();
123    let mut hasher = blake3::Hasher::new();
124    hasher.update(b"tilo-resource/migration/v1");
125    hasher.update(kind.as_bytes());
126    hasher.update(&from.to_le_bytes());
127    hasher.update(&to.to_le_bytes());
128    for head in &heads {
129        hasher.update(&head.0);
130    }
131    let actor =
132        automerge::ActorId::from(hasher.finalize().as_bytes().get(..16).unwrap_or_default());
133    let mut migrated = doc.fork_at(&heads)?.with_actor(actor);
134    migration(&mut migrated, from)?;
135    migrated.put(ROOT, VERSION_KEY, ScalarValue::Uint(u64::from(to)))?;
136    let context = tilo_actions::ActionContext {
137        change: tilo_actions::ChangeKind::Housekeeping,
138        ..tilo_actions::ActionContext::for_resource(kind, kind, label).with_described(
139            tilo_actions::Described::new(tilo_actions::Did::history(
140                tilo_actions::HistoryOp::Migrate { to },
141                0,
142                None,
143            )),
144        )
145    };
146    let mut options = CommitOptions::default().with_time(0);
147    if let Some(message) = context.change_message() {
148        options = options.with_message(message);
149    }
150    migrated.commit_with(options);
151    let changes = migrated.get_changes(&heads);
152    doc.apply_incoming(changes)?;
153    Ok(true)
154}
155
156/// The value stored under `key` of the map `obj` as one JSON string (an old
157/// whole-value field), read with `T`'s serde form: `None` when the key holds
158/// no JSON string (absent, or already an object), `Some(None)` for JSON
159/// `null`. What a migration reads an old field with when its new type is not
160/// the old one's serde form.
161///
162/// # Errors
163/// Returns why the text does not read as `T`, or the document's error.
164pub fn read_json<T>(doc: &Doc, obj: &ObjId, key: &str) -> Result<Option<Option<T>>, ModelError>
165where
166    T: serde::de::DeserializeOwned,
167{
168    let text = match doc.get(obj, key)? {
169        Some((Value::Scalar(scalar), _)) => match scalar.as_ref() {
170            ScalarValue::Str(text) => text.to_string(),
171            ScalarValue::Null => return Ok(Some(None)),
172            _ => return Ok(None),
173        },
174        _ => return Ok(None),
175    };
176    if text == "null" {
177        return Ok(Some(None));
178    }
179    crate::__private::value_of_bytes(text.as_bytes())
180        .and_then(serde_json::from_value)
181        .map(|value| Some(Some(value)))
182        .map_err(|error| ModelError::invalid(error.to_string()).at(key))
183}
184
185/// Rewrite the value stored under `key` of the map `obj` as one JSON string
186/// (an old whole-value field, last writer wins) as the model type `T` stores
187/// it: the migration of a field whose type became a real model type. `T`
188/// reads the old text with its serde form, which is the form the text was
189/// written with, so `T` keeps that form (its serde attributes) unchanged.
190/// A key holding no JSON string (absent, or already an object) is left as
191/// it is; JSON `null` stores `T`'s empty value. Returns whether it rewrote
192/// the key.
193///
194/// # Errors
195/// Returns why the text does not read as `T`, or the document's error.
196pub fn retype_json<T>(doc: &mut Doc, obj: &ObjId, key: &str) -> Result<bool, ModelError>
197where
198    T: crate::Model + serde::de::DeserializeOwned,
199{
200    let Some(read) = read_json::<T>(doc, obj, key)? else {
201        return Ok(false);
202    };
203    let value = match read {
204        Some(value) => value,
205        None => T::missing().map_err(|error| error.at(key))?,
206    };
207    // A scalar is replaced in place; the value's own store writes the shape.
208    doc.delete(obj, key)?;
209    crate::model::write_key(doc, obj, key, &value)?;
210    Ok(true)
211}
212
213/// [`retype_json`] for every item of the [`Collection`](crate::Collection)
214/// stored under `key` of the map `obj`: the migration of a collection whose
215/// item type was stored as one JSON string. Returns how many items it
216/// rewrote.
217///
218/// # Errors
219/// Returns why an item's text does not read as `T`, or the document's error.
220pub fn retype_json_items<T>(doc: &mut Doc, obj: &ObjId, key: &str) -> Result<usize, ModelError>
221where
222    T: crate::Model + serde::de::DeserializeOwned,
223{
224    let Some((Value::Object(automerge::ObjType::Map), items)) = doc.get(obj, key)? else {
225        return Ok(0);
226    };
227    let mut rewrote: usize = 0;
228    for id in doc.keys(&items).collect::<Vec<_>>() {
229        if let Some((Value::Object(automerge::ObjType::Map), entry)) =
230            doc.get(&items, id.as_str())?
231            && retype_json::<T>(doc, &entry, crate::collection::VALUE).located(&id)?
232        {
233            rewrote = rewrote.saturating_add(1);
234        }
235    }
236    Ok(rewrote)
237}
238
239/// Rewrite the value stored under `key` of the map `obj` as `T` stores it
240/// now: read as it is, then stored again. The migration of a value holding a
241/// data enum whose fields an older version stored flat, beside the
242/// variant's name: the read takes them from those keys, and the store
243/// writes each under its variant's own key and drops the flat one. A key
244/// holding nothing is left as it is. Returns whether it rewrote the key.
245///
246/// # Errors
247/// Returns why the value does not read as `T`, or the document's error.
248pub fn retype_variant_fields<T: crate::Model>(
249    doc: &mut Doc,
250    obj: &ObjId,
251    key: &str,
252) -> Result<bool, ModelError> {
253    if doc.get(obj, key)?.is_none() {
254        return Ok(false);
255    }
256    let value: T = crate::read_key(doc, obj, key)?;
257    crate::write_key(doc, obj, key, &value)?;
258    Ok(true)
259}
260
261/// Write what the record `from` holds into the record `to`, another record of
262/// the same kind and storage version kept elsewhere: what a record moving
263/// from one store to another takes along. Every field is copied as it is
264/// stored, scalars with their types, maps, lists and texts; the record's own
265/// identity (its `tilo:` keys other than [`VERSION_KEY`]) stays `to`'s. A
266/// map or text `to` already holds at a key is written into rather than
267/// replaced, so what another writer adds to it concurrently is kept.
268///
269/// # Errors
270/// Returns the document's read or write error.
271pub fn copy_into(from: &Doc, to: &mut Doc) -> Result<(), ModelError> {
272    for key in from.keys(&ROOT).collect::<Vec<_>>() {
273        if key.starts_with("tilo:") && key != VERSION_KEY {
274            continue;
275        }
276        if let Some((value, obj)) = from.get(&ROOT, key.as_str())? {
277            copy_value(from, &value, &obj, to, &ROOT, Place::Key(&key))?;
278        }
279    }
280    Ok(())
281}
282
283/// Where [`copy_value`] writes: under a key of a map, or at an index of a
284/// list.
285enum Place<'a> {
286    Key(&'a str),
287    Insert(usize),
288}
289
290fn copy_value(
291    from: &Doc,
292    value: &Value<'_>,
293    obj: &ObjId,
294    to: &mut Doc,
295    into: &ObjId,
296    place: Place<'_>,
297) -> Result<(), ModelError> {
298    use automerge::ObjType;
299    let Value::Object(kind) = value else {
300        let Value::Scalar(scalar) = value else {
301            return Ok(());
302        };
303        let scalar = scalar.as_ref().clone();
304        match place {
305            Place::Key(key) => to.put(into, key, scalar)?,
306            Place::Insert(index) => to.insert(into, index, scalar)?,
307        }
308        return Ok(());
309    };
310    let kind = match kind {
311        ObjType::Table => ObjType::Map,
312        other => *other,
313    };
314    let held = match place {
315        Place::Key(key) => match to.get(into, key)? {
316            Some((Value::Object(held), id)) if held == kind => Some(id),
317            _ => None,
318        },
319        Place::Insert(_) => None,
320    };
321    let target = match (held, place) {
322        (Some(id), _) => id,
323        (None, Place::Key(key)) => to.put_object(into, key, kind)?,
324        (None, Place::Insert(index)) => to.insert_object(into, index, kind)?,
325    };
326    match kind {
327        ObjType::Text => {
328            let text = from.text(obj)?;
329            let length = to.length(&target);
330            to.splice_text(
331                &target,
332                0,
333                isize::try_from(length).unwrap_or(isize::MAX),
334                &text,
335            )?;
336        }
337        ObjType::List => {
338            let start = to.length(&target);
339            for index in 0..from.length(obj) {
340                if let Some((item, item_obj)) = from.get(obj, index)? {
341                    copy_value(
342                        from,
343                        &item,
344                        &item_obj,
345                        to,
346                        &target,
347                        Place::Insert(start.saturating_add(index)),
348                    )?;
349                }
350            }
351        }
352        ObjType::Map | ObjType::Table => {
353            for key in from.keys(obj).collect::<Vec<_>>() {
354                if let Some((item, item_obj)) = from.get(obj, key.as_str())? {
355                    copy_value(from, &item, &item_obj, to, &target, Place::Key(&key))?;
356                }
357            }
358        }
359    }
360    Ok(())
361}
362
363/// Write the keys of the JSON object `shape` into the map `obj` as an older
364/// version of an app stored them: what a migration's test builds the
365/// document it migrates from. An object is a map, an array a list, a string,
366/// a boolean and a number are scalars (an integer as `Int`), `null` is a
367/// null scalar, and `{"$text": "…"}` is a text object holding the string.
368///
369/// # Errors
370/// Returns the document's write error, or that `shape` is no object.
371pub fn fixture(doc: &mut Doc, obj: &ObjId, shape: &serde_json::Value) -> Result<(), ModelError> {
372    let serde_json::Value::Object(fields) = shape else {
373        return Err(ModelError::shape("an object of fields"));
374    };
375    for (key, value) in fields {
376        fixture_value(doc, crate::Slot::Key(obj, key), value)?;
377    }
378    Ok(())
379}
380
381fn fixture_value(
382    doc: &mut Doc,
383    slot: crate::Slot<'_>,
384    value: &serde_json::Value,
385) -> Result<(), ModelError> {
386    use automerge::ObjType;
387    use serde_json::Value as Json;
388    match value {
389        Json::Object(fields) if fields.len() == 1 && fields.contains_key("$text") => {
390            let Some(Json::String(text)) = fields.get("$text") else {
391                return Err(ModelError::shape("a text's string"));
392            };
393            let obj = slot.object(doc, ObjType::Text)?;
394            crate::TextEdit::ReplaceText { text: text.clone() }
395                .apply_under(doc, &obj)
396                .map_err(|error| ModelError::invalid(error.to_string()))
397        }
398        Json::Object(_) => {
399            let obj = slot.object(doc, ObjType::Map)?;
400            fixture(doc, &obj, value)
401        }
402        Json::Array(items) => {
403            let obj = slot.object(doc, ObjType::List)?;
404            for (index, item) in items.iter().enumerate() {
405                fixture_value(doc, crate::Slot::Insert(&obj, index), item)?;
406            }
407            Ok(())
408        }
409        Json::String(text) => slot.put_scalar(doc, ScalarValue::Str(text.as_str().into())),
410        Json::Bool(flag) => slot.put_scalar(doc, ScalarValue::Boolean(*flag)),
411        Json::Number(number) => slot.put_scalar(
412            doc,
413            match (number.as_i64(), number.as_u64(), number.as_f64()) {
414                (Some(int), _, _) => ScalarValue::Int(int),
415                (None, Some(uint), _) => ScalarValue::Uint(uint),
416                (None, None, Some(float)) => ScalarValue::F64(float),
417                (None, None, None) => return Err(ModelError::shape("a number")),
418            },
419        ),
420        Json::Null => slot.put_scalar(doc, ScalarValue::Null),
421    }
422}
423
424/// The map stored under `key` of `obj`, when it holds one: a nested record
425/// or a present `Option` of one, which a migration rewrites inside.
426pub fn map_at(doc: &Doc, obj: &ObjId, key: &str) -> Result<Option<ObjId>, ModelError> {
427    Ok(match doc.get(obj, key)? {
428        Some((Value::Object(automerge::ObjType::Map), map)) => Some(map),
429        _ => None,
430    })
431}
432
433/// The value maps of the items of the [`Collection`](crate::Collection)
434/// stored under `key` of the map `obj`, in no particular order: what a
435/// migration walks to rewrite a field of every item.
436pub fn collection_items(doc: &Doc, obj: &ObjId, key: &str) -> Result<Vec<ObjId>, ModelError> {
437    let Some((Value::Object(automerge::ObjType::Map), items)) = doc.get(obj, key)? else {
438        return Ok(Vec::new());
439    };
440    let mut out = Vec::new();
441    for id in doc.keys(&items).collect::<Vec<_>>() {
442        if let Some((Value::Object(automerge::ObjType::Map), item)) =
443            doc.get(&items, id.as_str())?
444            && let Some((Value::Object(automerge::ObjType::Map), value)) =
445                doc.get(&item, crate::collection::VALUE)?
446        {
447            out.push(value);
448        }
449    }
450    Ok(out)
451}
452
453/// The maps stored as the values of the map under `key` of `obj` (a
454/// `BTreeMap<String, T>` or [`Map`](crate::Map) of records), by key.
455pub fn map_values(doc: &Doc, obj: &ObjId, key: &str) -> Result<Vec<(String, ObjId)>, ModelError> {
456    let Some((Value::Object(automerge::ObjType::Map), map)) = doc.get(obj, key)? else {
457        return Ok(Vec::new());
458    };
459    let mut out = Vec::new();
460    for entry in doc.keys(&map).collect::<Vec<_>>() {
461        if let Some((Value::Object(automerge::ObjType::Map), value)) =
462            doc.get(&map, entry.as_str())?
463        {
464            out.push((entry, value));
465        }
466    }
467    Ok(out)
468}
469
470/// A document that does not read as its resource: what a view shows in
471/// place of stale state, and why each action is unavailable.
472#[derive(Clone, Debug, PartialEq, Eq)]
473pub struct Unreadable {
474    /// Why, in the words of the read: where it failed and what it expected.
475    pub reason: String,
476    /// The storage version the document names.
477    pub stored: u32,
478    /// The version the app reads.
479    pub expected: u32,
480}
481
482impl std::fmt::Display for Unreadable {
483    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
484        f.write_str(&self.reason)
485    }
486}
487
488impl Unreadable {
489    /// Why `doc` did not read as `R`, from the read's `error`.
490    #[must_use]
491    pub fn of<R: Resource>(doc: &Doc, error: &ModelError) -> Self {
492        Self {
493            reason: error.to_string(),
494            stored: stored_version(doc),
495            expected: R::VERSION,
496        }
497    }
498}
499
500/// Read `R` from `doc`, or say why it does not read.
501///
502/// # Errors
503/// Returns the [`Unreadable`] state.
504pub fn read_checked<R: Resource>(doc: &Doc) -> Result<R::State, Unreadable> {
505    check_version::<R>(doc)
506        .and_then(|()| R::read(doc))
507        .map_err(|error| Unreadable::of::<R>(doc, &error))
508}