tilo-resource 0.5.2

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
509
510
511
512
513
514
515
516
517
518
519
520
//! The stored layout of a model, as data.
//!
//! [`Model::SHAPE`](crate::Model::SHAPE) describes how a value lives in the
//! document without reading it: which keys a record has, which of them are
//! keyed collections, what is written whole. Generic services use it to act on
//! any record correctly — History restores a past version field by field and
//! item by item, the way an action would have written it, instead of replacing
//! the document wholesale.
//!
//! `#[derive(Model)]` produces the shape of a struct from its fields; plain
//! types are [`Shape::Value`]. A type with its own layout may declare a shape
//! by hand, or keep the default and opt out of layout-aware services.

/// How one value is laid out in the document.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Shape {
    /// Written and restored whole: a scalar, a text, a list, a JSON value.
    Value,
    /// A map of named fields, each with its own shape.
    Record(&'static [FieldShape]),
    /// A keyed, ordered [`Collection`](crate::Collection) of items of one
    /// shape. Each item is stored under its id as an entry map holding its
    /// order key ([`ENTRY_ORDER_KEY`]) and its value ([`ENTRY_VALUE_KEY`]).
    Collection(&'static Shape),
    /// Items of one shape stored under the ids they carry
    /// ([`Keyed`](crate::Keyed)): each item's value directly under its id.
    Keyed(&'static Shape),
    /// A map (`BTreeMap<String, T>`) of values of one shape, each under its
    /// key: an edit inside an entry is about that entry, named by its key or
    /// its value's label.
    Map(&'static Shape),
}

/// Who may change a field without being asked, by what a change of it can
/// do to the person: every API decides it from the published field edit.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
pub enum Trust {
    /// Anyone with write access changes it.
    #[default]
    Ordinary,
    /// A change can expose the person (what others see of them, where their
    /// data goes): it asks for confirmation first, from whoever makes it.
    Sensitive,
    /// A change one way can weaken the person's security (a longer lock
    /// delay, notifications shown on the lock screen): a change that way is
    /// [`Self::Weakening`], any other is ordinary. Which way the value is
    /// now decides it, so without it every change counts as weakening.
    Weakens(tilo_action_policy::edits::Weaker<'static>),
    /// Any change can weaken the person's security (who may control this
    /// machine): it asks for confirmation and crosses a security boundary,
    /// so a caller acting for the person (an agent, a script) needs their
    /// own grant for it.
    Weakening,
}

impl Trust {
    /// The risk of an edit of a field of this trust.
    #[must_use]
    pub const fn risk(self) -> tilo_actions::RiskLevel {
        match self {
            Self::Ordinary => tilo_actions::RiskLevel::Low,
            Self::Sensitive => tilo_actions::RiskLevel::Destructive,
            Self::Weakens(_) | Self::Weakening => tilo_actions::RiskLevel::Privileged,
        }
    }
}

/// One named field of a [`Shape::Record`].
#[allow(
    clippy::struct_excessive_bools,
    reason = "each flag is one independent field attribute"
)]
#[derive(Clone, Copy, Debug)]
pub struct FieldShape {
    /// The key the field is stored under (after `#[model(rename)]`).
    pub key: &'static str,
    /// The record type the field belongs to, in kebab case (`snippet`): with
    /// the key it names the field in history messages
    /// (`<app>-<owner>-<key>`).
    pub owner: &'static str,
    /// The field's Rust name.
    pub name: &'static str,
    /// The field's Rust type, as written.
    pub ty: &'static str,
    /// What the field is, for people: its doc comment's first line, else its
    /// name in words. History falls back to it ("Changed *Folder*").
    pub title: &'static str,
    pub shape: Shape,
    /// `#[model(unit)]`: the field is its own storage unit (for a
    /// collection, each item is one), so a server can tell who may write it
    /// without reading content.
    pub unit: bool,
    /// `#[model(readonly)]`: published for reading, changed only by verbs.
    pub readonly: bool,
    /// `#[model(atom)]`: stored whole, last writer wins, so an edit sets
    /// all of it and never splices characters into it.
    pub atom: bool,
    /// `#[model(label)]`: the field names the record.
    pub label: bool,
    /// Where the field stands among those whose texts, joined by spaces,
    /// name the record before its `label` field does
    /// (`#[model(label = "first last")]` on the type): 1 for the first, 0
    /// when it is not one of them.
    pub label_part: u8,
    /// `#[model(remove = "quiet")]` on a collection: removing an item by
    /// field edit asks no confirmation. Otherwise it is destructive, as a
    /// delete verb is, so the generic edit is never a quieter way around it.
    pub quiet_remove: bool,
    /// `#[model(trust = "..")]`: who may change the field without being
    /// asked first.
    pub trust: Trust,
    /// The JSON Schema of the field's value ([`Model::value_schema`](crate::Model::value_schema)).
    pub schema: fn() -> serde_json::Value,
    /// The field's type in the language-neutral vocabulary
    /// ([`Model::field_type`](crate::Model::field_type)).
    pub field_type: fn(&mut crate::TypeSet) -> crate::FieldType,
    /// The first line of the field's text as stored ([`stored_text`]): what
    /// a label made of it reads, rich text included.
    pub text: StoredText,
    /// What the field reads as while its key is absent, for a scalar field
    /// ([`absent_scalar`]): history names it as the value an edit replaced.
    pub absent: fn() -> Option<serde_json::Value>,
    /// `#[model(resource)]`: the field holds a resource of its own type,
    /// published beneath the resource of the record holding it
    /// ([`NestedResource`](crate::child::NestedResource)).
    pub resource: Option<crate::child::NestedResource>,
}

/// `value`, the JSON form of a value of `shape`, without the record fields
/// that hold what their absent key reads as: what an edit that writes a new
/// value carries of it, which reads back as the whole value.
///
/// Only a record has such fields, and `T::SHAPE` is known where this is
/// instantiated, so for every other model this compiles to `value`.
#[must_use]
#[inline]
pub(crate) fn without_absent<T: crate::Model>(value: serde_json::Value) -> serde_json::Value {
    if matches!(T::SHAPE, Shape::Record(_)) {
        (T::TABLE.ops.without_absent)(T::TABLE, value)
    } else {
        value
    }
}

/// [`without_absent`] of a record, reached through its table's functions
/// rather than `T::SHAPE`, which would copy its field list into every caller.
pub(crate) fn resource_without_absent(
    table: &crate::table::ModelTable,
    value: serde_json::Value,
) -> serde_json::Value {
    match table.record().map(|record| record.shape) {
        Some(Shape::Record(fields)) => without_absent_fields(fields, value),
        _ => value,
    }
}

/// [`without_absent`] of a value that is no record: all of it.
pub(crate) fn kept_whole(
    _: &crate::table::ModelTable,
    value: serde_json::Value,
) -> serde_json::Value {
    value
}

#[inline(never)]
fn without_absent_fields(
    fields: &'static [FieldShape],
    mut value: serde_json::Value,
) -> serde_json::Value {
    if let serde_json::Value::Object(map) = &mut value {
        for field in fields {
            if let Some(absent) = (field.absent)()
                && map.get(field.key) == Some(&absent)
            {
                map.remove(field.key);
            }
        }
    }
    value
}

/// The value an absent key of a scalar `T` reads as, in JSON; `None` for a
/// type stored as an object or without an empty value.
#[must_use]
pub fn absent_scalar<T: crate::Model>() -> Option<serde_json::Value> {
    if T::SCALAR {
        T::missing().ok().map(|value| value.to_json())
    } else {
        None
    }
}

/// Reads the first line of a field's text from where it is stored.
pub type StoredText =
    fn(&crate::model::Doc, &automerge::Value<'_>, &automerge::ObjId) -> Option<String>;

/// The first non-empty line of the text a `T` stored as `value` at `id`
/// carries, as [`Model::label`](crate::Model::label) reads it from the value.
pub fn stored_text<T: crate::Model>(
    doc: &crate::model::Doc,
    value: &automerge::Value<'_>,
    id: &automerge::ObjId,
) -> Option<String> {
    // A value that loads on demand is read whole first.
    let mut stored = T::load(doc, value, id).ok()?;
    stored.read_whole(doc).ok()?;
    crate::__private::first_line(&stored)
}

/// Two fields are the same field when everything but their value schema's
/// function (which compares by address) is.
impl PartialEq for FieldShape {
    fn eq(&self, other: &Self) -> bool {
        self.key == other.key
            && self.owner == other.owner
            && self.name == other.name
            && self.ty == other.ty
            && self.title == other.title
            && self.shape == other.shape
            && self.unit == other.unit
            && self.readonly == other.readonly
            && self.atom == other.atom
            && self.label == other.label
            && self.quiet_remove == other.quiet_remove
            && self.trust == other.trust
            && self.resource.map(|nested| nested.kind) == other.resource.map(|nested| nested.kind)
    }
}

impl Eq for FieldShape {}

impl Shape {
    /// The fields of a record shape; none for any other.
    #[must_use]
    pub const fn fields(&self) -> &'static [FieldShape] {
        match self {
            Self::Record(fields) => fields,
            Self::Value | Self::Collection(_) | Self::Keyed(_) | Self::Map(_) => &[],
        }
    }

    /// The storage unit a change at `path` (from this shape's root) writes:
    /// the longest prefix of the path that ends at a `#[model(unit)]` field
    /// or an item of one. The record itself, the empty path, is a unit too.
    #[must_use]
    pub fn unit_of(&self, path: &[crate::path::Segment]) -> Vec<crate::path::Segment> {
        use crate::path::Segment;
        let mut unit = Vec::new();
        let mut shape = *self;
        let mut walked = Vec::new();
        let mut items_are_units = false;
        for segment in path {
            walked.push(segment.clone());
            match (shape, segment) {
                (Self::Record(fields), Segment::Field(key)) => {
                    let Some(field) = fields.iter().find(|field| field.key == key) else {
                        break;
                    };
                    shape = field.shape;
                    items_are_units =
                        field.unit && matches!(field.shape, Self::Collection(_) | Self::Keyed(_));
                    if field.unit && !items_are_units {
                        unit.clone_from(&walked);
                    }
                }
                (Self::Collection(item) | Self::Keyed(item), Segment::Item(_)) => {
                    shape = *item;
                    if items_are_units {
                        unit.clone_from(&walked);
                    }
                    items_are_units = false;
                }
                _ => break,
            }
        }
        unit
    }

    /// The fields below this shape that `select` answers for, by their
    /// dotted paths (`*` for an item), as
    /// [`tilo_action_policy::edits::dotted`] spells them.
    fn selected<X>(&self, select: impl Fn(&FieldShape) -> Option<X>) -> Vec<(String, X)> {
        fn walk<X>(
            shape: Shape,
            prefix: &str,
            select: &impl Fn(&FieldShape) -> Option<X>,
            out: &mut Vec<(String, X)>,
            depth: usize,
        ) {
            if depth > 16 {
                return;
            }
            match shape {
                Shape::Record(fields) => {
                    for field in fields {
                        let path = if prefix.is_empty() {
                            field.key.to_owned()
                        } else {
                            format!("{prefix}.{}", field.key)
                        };
                        if let Some(value) = select(field) {
                            out.push((path.clone(), value));
                        }
                        walk(field.shape, &path, select, out, depth.saturating_add(1));
                    }
                }
                Shape::Collection(item) | Shape::Keyed(item) | Shape::Map(item) => {
                    walk(
                        *item,
                        &format!("{prefix}.*"),
                        select,
                        out,
                        depth.saturating_add(1),
                    );
                }
                Shape::Value => {}
            }
        }
        let mut out = Vec::new();
        walk(*self, "", &select, &mut out, 0);
        out
    }

    /// The collections below this shape whose removals ask nothing
    /// (`#[model(remove = "quiet")]`), by their dotted paths (`*` for an
    /// item), as [`tilo_action_policy::edits::dotted`] spells them.
    #[must_use]
    pub fn quiet_removals(&self) -> Vec<String> {
        self.selected(|field| field.quiet_remove.then_some(()))
            .into_iter()
            .map(|(path, ())| path)
            .collect()
    }

    /// The fields below this shape that are not [`Trust::Ordinary`], by
    /// their dotted paths (`*` for an item), as
    /// [`tilo_action_policy::edits::dotted`] spells them.
    #[must_use]
    pub fn guarded_fields(&self) -> Vec<(String, Trust)> {
        self.selected(|field| (field.trust != Trust::Ordinary).then_some(field.trust))
    }

    /// The trust of the field at `path`: the strictest of the fields it is
    /// at or below.
    #[must_use]
    pub fn trust_at(&self, path: &[crate::path::Segment]) -> Trust {
        use crate::path::Segment;
        let mut shape = *self;
        let mut trust = Trust::Ordinary;
        for segment in path {
            match (shape, segment) {
                (Self::Record(fields), Segment::Field(key)) => {
                    let Some(field) = fields.iter().find(|field| field.key == key) else {
                        break;
                    };
                    trust = trust.max(field.trust);
                    shape = field.shape;
                }
                (
                    Self::Collection(item) | Self::Keyed(item) | Self::Map(item),
                    Segment::Item(_) | Segment::Key(_),
                ) => shape = *item,
                _ => break,
            }
        }
        trust
    }

    /// Whether the field at `path` is `#[model(readonly)]`.
    #[must_use]
    pub fn readonly_at(&self, path: &[crate::path::Segment]) -> bool {
        use crate::path::Segment;
        let mut shape = *self;
        for segment in path {
            match (shape, segment) {
                (Self::Record(fields), Segment::Field(key)) => {
                    let Some(field) = fields.iter().find(|field| field.key == key) else {
                        return false;
                    };
                    if field.readonly {
                        return true;
                    }
                    shape = field.shape;
                }
                (Self::Collection(item) | Self::Keyed(item), Segment::Item(_)) => shape = *item,
                _ => return false,
            }
        }
        false
    }

    /// The first field this lays out that is read only and `after` changes from `before`, by its
    /// path (`themes.mine.dark`): a field only the record's own verbs change, never a field edit.
    /// `before` and `after` are the record's JSON form ([`Model::to_json`](crate::Model::to_json)).
    #[must_use]
    pub fn changed_readonly<'a>(
        &self,
        before: Option<&'a serde_json::Value>,
        after: Option<&'a serde_json::Value>,
    ) -> Option<String> {
        self.changed_readonly_at("", before, after)
    }

    fn changed_readonly_at<'a>(
        &self,
        path: &str,
        before: Option<&'a serde_json::Value>,
        after: Option<&'a serde_json::Value>,
    ) -> Option<String> {
        let join = |key: &str| {
            if path.is_empty() {
                key.to_owned()
            } else {
                format!("{path}.{key}")
            }
        };
        match self {
            Self::Value => None,
            Self::Record(fields) => fields.iter().find_map(|field| {
                let path = join(field.key);
                let before = before.and_then(|value| value.get(field.key));
                let after = after.and_then(|value| value.get(field.key));
                if field.readonly {
                    (before != after).then_some(path)
                } else {
                    field.shape.changed_readonly_at(&path, before, after)
                }
            }),
            // A collection and a keyed collection are arrays of items, a collection's each
            // `{"id", "value"}`; a map's items sit under their keys.
            Self::Collection(item) => entries(before, after)
                .into_iter()
                .find_map(|(id, before, after)| item.changed_readonly_at(&join(id), before, after)),
            Self::Keyed(item) => {
                let count = [before, after]
                    .into_iter()
                    .flatten()
                    .filter_map(|value| value.as_array().map(Vec::len))
                    .max()
                    .unwrap_or_default();
                (0..count).find_map(|at| {
                    let before = before
                        .and_then(serde_json::Value::as_array)
                        .and_then(|items| items.get(at));
                    let after = after
                        .and_then(serde_json::Value::as_array)
                        .and_then(|items| items.get(at));
                    item.changed_readonly_at(&join("*"), before, after)
                })
            }
            Self::Map(item) => {
                let mut keys: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
                for value in [before, after].into_iter().flatten() {
                    keys.extend(
                        value
                            .as_object()
                            .into_iter()
                            .flatten()
                            .map(|(key, _)| key.as_str()),
                    );
                }
                keys.into_iter().find_map(|key| {
                    let before = before
                        .and_then(serde_json::Value::as_object)
                        .and_then(|entries| entries.get(key));
                    let after = after
                        .and_then(serde_json::Value::as_object)
                        .and_then(|entries| entries.get(key));
                    item.changed_readonly_at(&join(key), before, after)
                })
            }
        }
    }
}

/// One item of a collection's JSON form that changed: its id, and its value before and after (a
/// side that does not hold it is `None`).
type ChangedItem<'a> = (
    &'a str,
    Option<&'a serde_json::Value>,
    Option<&'a serde_json::Value>,
);

/// The items of a collection's JSON form in `before` and `after`, by id, each with its value: an
/// item only one side holds reads as `None` on the other.
fn entries<'a>(
    before: Option<&'a serde_json::Value>,
    after: Option<&'a serde_json::Value>,
) -> Vec<ChangedItem<'a>> {
    let values =
        |value: Option<&'a serde_json::Value>| -> Vec<(&'a str, Option<&'a serde_json::Value>)> {
            value
                .and_then(serde_json::Value::as_array)
                .into_iter()
                .flatten()
                .filter_map(|entry| {
                    let id = entry.get("id").and_then(serde_json::Value::as_str)?;
                    Some((id, entry.get("value")))
                })
                .collect()
        };
    let before = values(before);
    let after = values(after);
    let ids: std::collections::BTreeSet<&str> =
        before.iter().chain(&after).map(|(id, _)| *id).collect();
    let of = |items: &[(&'a str, Option<&'a serde_json::Value>)], id: &str| {
        items
            .iter()
            .find(|(held, _)| *held == id)
            .and_then(|(_, value)| *value)
    };
    ids.into_iter()
        .map(|id| (id, of(&before, id), of(&after, id)))
        .collect()
}

/// The key of a collection entry's order key.
pub const ENTRY_ORDER_KEY: &str = crate::collection::ORDER;
/// The key of a collection entry's value.
pub const ENTRY_VALUE_KEY: &str = crate::collection::VALUE;