tilo-resource 0.5.0

The Tilo resource layer: typed, hierarchical app resources.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! How a resource's storage changes between versions of its app.
//!
//! A record stores the schema version it was written at under one key
//! ([`VERSION_KEY`], read by [`stored_version`]); `#[resource(version = N,
//! migrate = path)]` declares the current one and how to bring an older
//! document up to it ([`migrate`]). A document that does not read as the
//! model is [`Unreadable`]: views show why and actions report it, and stale
//! state is never shown as current.

use automerge::transaction::{CommitOptions, Transactable};
use automerge::{ObjId, ROOT, ReadDoc, ScalarValue, Value};
use tilo_automerge::ApplyIncoming;
use tilo_sort::CompactSort as _;

use crate::model::{Doc, LocatedAt as _, ModelError};
use crate::resource::Resource;

/// The root key a document's schema version is stored under, when it is past
/// the first. Every document keeps it here: an app's record, a settings
/// document, a `tilo-doc` page.
pub const VERSION_KEY: &str = "tilo:version";

/// The `u32` a stored version scalar names.
fn version_of(value: &Value<'_>) -> Option<u32> {
    let Value::Scalar(scalar) = value else {
        return None;
    };
    match scalar.as_ref() {
        ScalarValue::Uint(version) => Some(u32::try_from(*version).unwrap_or(u32::MAX)),
        ScalarValue::Int(version) => Some(u32::try_from(*version).unwrap_or(u32::MAX)),
        _ => None,
    }
}

/// The schema version `doc` was written at: 1 when it names none.
#[must_use]
pub fn stored_version(doc: &Doc) -> u32 {
    stored_version_at(doc, &ROOT)
}

/// [`stored_version`] of the document whose root is `at`.
#[must_use]
pub fn stored_version_at(doc: &Doc, at: &ObjId) -> u32 {
    doc.get(at, VERSION_KEY)
        .ok()
        .flatten()
        .and_then(|(value, _)| version_of(&value))
        .unwrap_or(1)
}

/// Record that `doc` is at `version` (nothing for the first version, so
/// documents of apps that never changed their storage stay as they are).
pub fn write_version(doc: &mut Doc, version: u32) -> Result<(), ModelError> {
    write_version_at(doc, &ROOT, version)
}

/// [`write_version`] of the document whose root is `at`.
pub fn write_version_at(doc: &mut Doc, at: &ObjId, version: u32) -> Result<(), ModelError> {
    if version > 1 || doc.get(at, VERSION_KEY)?.is_some() {
        doc.put(at, VERSION_KEY, ScalarValue::Uint(u64::from(version)))?;
    }
    Ok(())
}

/// Whether `doc` holds `R` at the version the app reads.
///
/// # Errors
/// Returns why not: written by a newer version of the app, or waiting for
/// [`migrate`].
pub fn check_version<R: Resource>(doc: &Doc) -> Result<(), ModelError> {
    check_version_at(R::VERSION, doc)
}

/// [`check_version`] of a resource read at `version`.
fn check_version_at(version: u32, doc: &Doc) -> Result<(), ModelError> {
    let stored = stored_version(doc);
    match stored.cmp(&version) {
        std::cmp::Ordering::Equal => Ok(()),
        std::cmp::Ordering::Greater => Err(ModelError::invalid(format!(
            "written by a newer version of the app (storage version {stored}, this app reads {version})"
        ))),
        std::cmp::Ordering::Less => Err(ModelError::invalid(format!(
            "stored at version {stored}; it is brought up to version {version} when it opens"
        ))),
    }
}

/// Bring `doc` up to `R`'s version with its migration, and to this build's
/// version key: once, as one housekeeping change made by an actor and at a
/// time derived from the resource kind, the versions and the heads it starts
/// from, so two devices migrating the same document produce the same change.
/// Returns whether it changed anything.
///
/// # Errors
/// Returns the migration's error; `doc` is left as it was.
pub fn migrate<R: Resource>(doc: &mut Doc) -> Result<bool, ModelError> {
    migrate_with(
        (R::KIND, R::LABEL, R::VERSION),
        &|doc: &mut Doc, from: u32| R::migrate(doc, from),
        doc,
    )
}

/// Whether [`migrate`] would change `doc`: it is older than `R`.
#[must_use]
pub fn needs_migrate<R: Resource>(doc: &Doc) -> bool {
    stored_version(doc) < R::VERSION
}

/// [`migrate`] of the resource of the kind, label and storage version
/// `resource`, whose migration is `migration`.
fn migrate_with(
    (kind, label, to): (&str, &str, u32),
    migration: &dyn Fn(&mut Doc, u32) -> Result<(), ModelError>,
    doc: &mut Doc,
) -> Result<bool, ModelError> {
    let from = stored_version(doc);
    if from >= to {
        return Ok(false);
    }
    let mut heads = doc.get_heads();
    heads.compact_sort();
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"tilo-resource/migration/v1");
    hasher.update(kind.as_bytes());
    hasher.update(&from.to_le_bytes());
    hasher.update(&to.to_le_bytes());
    for head in &heads {
        hasher.update(&head.0);
    }
    let actor =
        automerge::ActorId::from(hasher.finalize().as_bytes().get(..16).unwrap_or_default());
    let mut migrated = doc.fork_at(&heads)?.with_actor(actor);
    migration(&mut migrated, from)?;
    migrated.put(ROOT, VERSION_KEY, ScalarValue::Uint(u64::from(to)))?;
    let context = tilo_actions::ActionContext {
        change: tilo_actions::ChangeKind::Housekeeping,
        ..tilo_actions::ActionContext::for_resource(kind, kind, label).with_described(
            tilo_actions::Described::new(tilo_actions::Did::history(
                tilo_actions::HistoryOp::Migrate { to },
                0,
                None,
            )),
        )
    };
    let mut options = CommitOptions::default().with_time(0);
    if let Some(message) = context.change_message() {
        options = options.with_message(message);
    }
    migrated.commit_with(options);
    let changes = migrated.get_changes(&heads);
    doc.apply_incoming(changes)?;
    Ok(true)
}

/// The value stored under `key` of the map `obj` as one JSON string (an old
/// whole-value field), read with `T`'s serde form: `None` when the key holds
/// no JSON string (absent, or already an object), `Some(None)` for JSON
/// `null`. What a migration reads an old field with when its new type is not
/// the old one's serde form.
///
/// # Errors
/// Returns why the text does not read as `T`, or the document's error.
pub fn read_json<T>(doc: &Doc, obj: &ObjId, key: &str) -> Result<Option<Option<T>>, ModelError>
where
    T: serde::de::DeserializeOwned,
{
    let text = match doc.get(obj, key)? {
        Some((Value::Scalar(scalar), _)) => match scalar.as_ref() {
            ScalarValue::Str(text) => text.to_string(),
            ScalarValue::Null => return Ok(Some(None)),
            _ => return Ok(None),
        },
        _ => return Ok(None),
    };
    if text == "null" {
        return Ok(Some(None));
    }
    crate::__private::value_of_bytes(text.as_bytes())
        .and_then(serde_json::from_value)
        .map(|value| Some(Some(value)))
        .map_err(|error| ModelError::invalid(error.to_string()).at(key))
}

/// Rewrite the value stored under `key` of the map `obj` as one JSON string
/// (an old whole-value field, last writer wins) as the model type `T` stores
/// it: the migration of a field whose type became a real model type. `T`
/// reads the old text with its serde form, which is the form the text was
/// written with, so `T` keeps that form (its serde attributes) unchanged.
/// A key holding no JSON string (absent, or already an object) is left as
/// it is; JSON `null` stores `T`'s empty value. Returns whether it rewrote
/// the key.
///
/// # Errors
/// Returns why the text does not read as `T`, or the document's error.
pub fn retype_json<T>(doc: &mut Doc, obj: &ObjId, key: &str) -> Result<bool, ModelError>
where
    T: crate::Model + serde::de::DeserializeOwned,
{
    let Some(read) = read_json::<T>(doc, obj, key)? else {
        return Ok(false);
    };
    let value = match read {
        Some(value) => value,
        None => T::missing().map_err(|error| error.at(key))?,
    };
    // A scalar is replaced in place; the value's own store writes the shape.
    doc.delete(obj, key)?;
    crate::model::write_key(doc, obj, key, &value)?;
    Ok(true)
}

/// [`retype_json`] for every item of the [`Collection`](crate::Collection)
/// stored under `key` of the map `obj`: the migration of a collection whose
/// item type was stored as one JSON string. Returns how many items it
/// rewrote.
///
/// # Errors
/// Returns why an item's text does not read as `T`, or the document's error.
pub fn retype_json_items<T>(doc: &mut Doc, obj: &ObjId, key: &str) -> Result<usize, ModelError>
where
    T: crate::Model + serde::de::DeserializeOwned,
{
    let Some((Value::Object(automerge::ObjType::Map), items)) = doc.get(obj, key)? else {
        return Ok(0);
    };
    let mut rewrote: usize = 0;
    for id in doc.keys(&items).collect::<Vec<_>>() {
        if let Some((Value::Object(automerge::ObjType::Map), entry)) =
            doc.get(&items, id.as_str())?
            && retype_json::<T>(doc, &entry, crate::collection::VALUE).located(&id)?
        {
            rewrote = rewrote.saturating_add(1);
        }
    }
    Ok(rewrote)
}

/// Rewrite the value stored under `key` of the map `obj` as `T` stores it
/// now: read as it is, then stored again. The migration of a value holding a
/// data enum whose fields an older version stored flat, beside the
/// variant's name: the read takes them from those keys, and the store
/// writes each under its variant's own key and drops the flat one. A key
/// holding nothing is left as it is. Returns whether it rewrote the key.
///
/// # Errors
/// Returns why the value does not read as `T`, or the document's error.
pub fn retype_variant_fields<T: crate::Model>(
    doc: &mut Doc,
    obj: &ObjId,
    key: &str,
) -> Result<bool, ModelError> {
    if doc.get(obj, key)?.is_none() {
        return Ok(false);
    }
    let value: T = crate::read_key(doc, obj, key)?;
    crate::write_key(doc, obj, key, &value)?;
    Ok(true)
}

/// Write what the record `from` holds into the record `to`, another record of
/// the same kind and storage version kept elsewhere: what a record moving
/// from one store to another takes along. Every field is copied as it is
/// stored, scalars with their types, maps, lists and texts; the record's own
/// identity (its `tilo:` keys other than [`VERSION_KEY`]) stays `to`'s. A
/// map or text `to` already holds at a key is written into rather than
/// replaced, so what another writer adds to it concurrently is kept.
///
/// # Errors
/// Returns the document's read or write error.
pub fn copy_into(from: &Doc, to: &mut Doc) -> Result<(), ModelError> {
    for key in from.keys(&ROOT).collect::<Vec<_>>() {
        if key.starts_with("tilo:") && key != VERSION_KEY {
            continue;
        }
        if let Some((value, obj)) = from.get(&ROOT, key.as_str())? {
            copy_value(from, &value, &obj, to, &ROOT, Place::Key(&key))?;
        }
    }
    Ok(())
}

/// Where [`copy_value`] writes: under a key of a map, or at an index of a
/// list.
enum Place<'a> {
    Key(&'a str),
    Insert(usize),
}

fn copy_value(
    from: &Doc,
    value: &Value<'_>,
    obj: &ObjId,
    to: &mut Doc,
    into: &ObjId,
    place: Place<'_>,
) -> Result<(), ModelError> {
    use automerge::ObjType;
    let Value::Object(kind) = value else {
        let Value::Scalar(scalar) = value else {
            return Ok(());
        };
        let scalar = scalar.as_ref().clone();
        match place {
            Place::Key(key) => to.put(into, key, scalar)?,
            Place::Insert(index) => to.insert(into, index, scalar)?,
        }
        return Ok(());
    };
    let kind = match kind {
        ObjType::Table => ObjType::Map,
        other => *other,
    };
    let held = match place {
        Place::Key(key) => match to.get(into, key)? {
            Some((Value::Object(held), id)) if held == kind => Some(id),
            _ => None,
        },
        Place::Insert(_) => None,
    };
    let target = match (held, place) {
        (Some(id), _) => id,
        (None, Place::Key(key)) => to.put_object(into, key, kind)?,
        (None, Place::Insert(index)) => to.insert_object(into, index, kind)?,
    };
    match kind {
        ObjType::Text => {
            let text = from.text(obj)?;
            let length = to.length(&target);
            to.splice_text(
                &target,
                0,
                isize::try_from(length).unwrap_or(isize::MAX),
                &text,
            )?;
        }
        ObjType::List => {
            let start = to.length(&target);
            for index in 0..from.length(obj) {
                if let Some((item, item_obj)) = from.get(obj, index)? {
                    copy_value(
                        from,
                        &item,
                        &item_obj,
                        to,
                        &target,
                        Place::Insert(start.saturating_add(index)),
                    )?;
                }
            }
        }
        ObjType::Map | ObjType::Table => {
            for key in from.keys(obj).collect::<Vec<_>>() {
                if let Some((item, item_obj)) = from.get(obj, key.as_str())? {
                    copy_value(from, &item, &item_obj, to, &target, Place::Key(&key))?;
                }
            }
        }
    }
    Ok(())
}

/// Write the keys of the JSON object `shape` into the map `obj` as an older
/// version of an app stored them: what a migration's test builds the
/// document it migrates from. An object is a map, an array a list, a string,
/// a boolean and a number are scalars (an integer as `Int`), `null` is a
/// null scalar, and `{"$text": "…"}` is a text object holding the string.
///
/// # Errors
/// Returns the document's write error, or that `shape` is no object.
pub fn fixture(doc: &mut Doc, obj: &ObjId, shape: &serde_json::Value) -> Result<(), ModelError> {
    let serde_json::Value::Object(fields) = shape else {
        return Err(ModelError::shape("an object of fields"));
    };
    for (key, value) in fields {
        fixture_value(doc, crate::Slot::Key(obj, key), value)?;
    }
    Ok(())
}

fn fixture_value(
    doc: &mut Doc,
    slot: crate::Slot<'_>,
    value: &serde_json::Value,
) -> Result<(), ModelError> {
    use automerge::ObjType;
    use serde_json::Value as Json;
    match value {
        Json::Object(fields) if fields.len() == 1 && fields.contains_key("$text") => {
            let Some(Json::String(text)) = fields.get("$text") else {
                return Err(ModelError::shape("a text's string"));
            };
            let obj = slot.object(doc, ObjType::Text)?;
            crate::TextEdit::ReplaceText { text: text.clone() }
                .apply_under(doc, &obj)
                .map_err(|error| ModelError::invalid(error.to_string()))
        }
        Json::Object(_) => {
            let obj = slot.object(doc, ObjType::Map)?;
            fixture(doc, &obj, value)
        }
        Json::Array(items) => {
            let obj = slot.object(doc, ObjType::List)?;
            for (index, item) in items.iter().enumerate() {
                fixture_value(doc, crate::Slot::Insert(&obj, index), item)?;
            }
            Ok(())
        }
        Json::String(text) => slot.put_scalar(doc, ScalarValue::Str(text.as_str().into())),
        Json::Bool(flag) => slot.put_scalar(doc, ScalarValue::Boolean(*flag)),
        Json::Number(number) => slot.put_scalar(
            doc,
            match (number.as_i64(), number.as_u64(), number.as_f64()) {
                (Some(int), _, _) => ScalarValue::Int(int),
                (None, Some(uint), _) => ScalarValue::Uint(uint),
                (None, None, Some(float)) => ScalarValue::F64(float),
                (None, None, None) => return Err(ModelError::shape("a number")),
            },
        ),
        Json::Null => slot.put_scalar(doc, ScalarValue::Null),
    }
}

/// The map stored under `key` of `obj`, when it holds one: a nested record
/// or a present `Option` of one, which a migration rewrites inside.
pub fn map_at(doc: &Doc, obj: &ObjId, key: &str) -> Result<Option<ObjId>, ModelError> {
    Ok(match doc.get(obj, key)? {
        Some((Value::Object(automerge::ObjType::Map), map)) => Some(map),
        _ => None,
    })
}

/// The value maps of the items of the [`Collection`](crate::Collection)
/// stored under `key` of the map `obj`, in no particular order: what a
/// migration walks to rewrite a field of every item.
pub fn collection_items(doc: &Doc, obj: &ObjId, key: &str) -> Result<Vec<ObjId>, ModelError> {
    let Some((Value::Object(automerge::ObjType::Map), items)) = doc.get(obj, key)? else {
        return Ok(Vec::new());
    };
    let mut out = Vec::new();
    for id in doc.keys(&items).collect::<Vec<_>>() {
        if let Some((Value::Object(automerge::ObjType::Map), item)) =
            doc.get(&items, id.as_str())?
            && let Some((Value::Object(automerge::ObjType::Map), value)) =
                doc.get(&item, crate::collection::VALUE)?
        {
            out.push(value);
        }
    }
    Ok(out)
}

/// The maps stored as the values of the map under `key` of `obj` (a
/// `BTreeMap<String, T>` or [`Map`](crate::Map) of records), by key.
pub fn map_values(doc: &Doc, obj: &ObjId, key: &str) -> Result<Vec<(String, ObjId)>, ModelError> {
    let Some((Value::Object(automerge::ObjType::Map), map)) = doc.get(obj, key)? else {
        return Ok(Vec::new());
    };
    let mut out = Vec::new();
    for entry in doc.keys(&map).collect::<Vec<_>>() {
        if let Some((Value::Object(automerge::ObjType::Map), value)) =
            doc.get(&map, entry.as_str())?
        {
            out.push((entry, value));
        }
    }
    Ok(out)
}

/// A document that does not read as its resource: what a view shows in
/// place of stale state, and why each action is unavailable.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Unreadable {
    /// Why, in the words of the read: where it failed and what it expected.
    pub reason: String,
    /// The storage version the document names.
    pub stored: u32,
    /// The version the app reads.
    pub expected: u32,
}

impl std::fmt::Display for Unreadable {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.reason)
    }
}

impl Unreadable {
    /// Why `doc` did not read as `R`, from the read's `error`.
    #[must_use]
    pub fn of<R: Resource>(doc: &Doc, error: &ModelError) -> Self {
        Self {
            reason: error.to_string(),
            stored: stored_version(doc),
            expected: R::VERSION,
        }
    }
}

/// Read `R` from `doc`, or say why it does not read.
///
/// # Errors
/// Returns the [`Unreadable`] state.
pub fn read_checked<R: Resource>(doc: &Doc) -> Result<R::State, Unreadable> {
    check_version::<R>(doc)
        .and_then(|()| R::read(doc))
        .map_err(|error| Unreadable::of::<R>(doc, &error))
}