tilo_resource/shape.rs
1//! The stored layout of a model, as data.
2//!
3//! [`Model::SHAPE`](crate::Model::SHAPE) describes how a value lives in the
4//! document without reading it: which keys a record has, which of them are
5//! keyed collections, what is written whole. Generic services use it to act on
6//! any record correctly — History restores a past version field by field and
7//! item by item, the way an action would have written it, instead of replacing
8//! the document wholesale.
9//!
10//! `#[derive(Model)]` produces the shape of a struct from its fields; plain
11//! types are [`Shape::Value`]. A type with its own layout may declare a shape
12//! by hand, or keep the default and opt out of layout-aware services.
13
14/// How one value is laid out in the document.
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub enum Shape {
17 /// Written and restored whole: a scalar, a text, a list, a JSON value.
18 Value,
19 /// A map of named fields, each with its own shape.
20 Record(&'static [FieldShape]),
21 /// A keyed, ordered [`Collection`](crate::Collection) of items of one
22 /// shape. Each item is stored under its id as an entry map holding its
23 /// order key ([`ENTRY_ORDER_KEY`]) and its value ([`ENTRY_VALUE_KEY`]).
24 Collection(&'static Shape),
25 /// Items of one shape stored under the ids they carry
26 /// ([`Keyed`](crate::Keyed)): each item's value directly under its id.
27 Keyed(&'static Shape),
28 /// A map (`BTreeMap<String, T>`) of values of one shape, each under its
29 /// key: an edit inside an entry is about that entry, named by its key or
30 /// its value's label.
31 Map(&'static Shape),
32}
33
34/// Who may change a field without being asked, by what a change of it can
35/// do to the person: every API decides it from the published field edit.
36#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
37pub enum Trust {
38 /// Anyone with write access changes it.
39 #[default]
40 Ordinary,
41 /// A change can expose the person (what others see of them, where their
42 /// data goes): it asks for confirmation first, from whoever makes it.
43 Sensitive,
44 /// A change one way can weaken the person's security (a longer lock
45 /// delay, notifications shown on the lock screen): a change that way is
46 /// [`Self::Weakening`], any other is ordinary. Which way the value is
47 /// now decides it, so without it every change counts as weakening.
48 Weakens(tilo_action_policy::edits::Weaker<'static>),
49 /// Any change can weaken the person's security (who may control this
50 /// machine): it asks for confirmation and crosses a security boundary,
51 /// so a caller acting for the person (an agent, a script) needs their
52 /// own grant for it.
53 Weakening,
54}
55
56impl Trust {
57 /// The risk of an edit of a field of this trust.
58 #[must_use]
59 pub const fn risk(self) -> tilo_actions::RiskLevel {
60 match self {
61 Self::Ordinary => tilo_actions::RiskLevel::Low,
62 Self::Sensitive => tilo_actions::RiskLevel::Destructive,
63 Self::Weakens(_) | Self::Weakening => tilo_actions::RiskLevel::Privileged,
64 }
65 }
66}
67
68/// One named field of a [`Shape::Record`].
69#[allow(
70 clippy::struct_excessive_bools,
71 reason = "each flag is one independent field attribute"
72)]
73#[derive(Clone, Copy, Debug)]
74pub struct FieldShape {
75 /// The key the field is stored under (after `#[model(rename)]`).
76 pub key: &'static str,
77 /// The record type the field belongs to, in kebab case (`snippet`): with
78 /// the key it names the field in history messages
79 /// (`<app>-<owner>-<key>`).
80 pub owner: &'static str,
81 /// The field's Rust name.
82 pub name: &'static str,
83 /// The field's Rust type, as written.
84 pub ty: &'static str,
85 /// What the field is, for people: its doc comment's first line, else its
86 /// name in words. History falls back to it ("Changed *Folder*").
87 pub title: &'static str,
88 pub shape: Shape,
89 /// `#[model(unit)]`: the field is its own storage unit (for a
90 /// collection, each item is one), so a server can tell who may write it
91 /// without reading content.
92 pub unit: bool,
93 /// `#[model(readonly)]`: published for reading, changed only by verbs.
94 pub readonly: bool,
95 /// `#[model(atom)]`: stored whole, last writer wins, so an edit sets
96 /// all of it and never splices characters into it.
97 pub atom: bool,
98 /// `#[model(label)]`: the field names the record.
99 pub label: bool,
100 /// Where the field stands among those whose texts, joined by spaces,
101 /// name the record before its `label` field does
102 /// (`#[model(label = "first last")]` on the type): 1 for the first, 0
103 /// when it is not one of them.
104 pub label_part: u8,
105 /// `#[model(remove = "quiet")]` on a collection: removing an item by
106 /// field edit asks no confirmation. Otherwise it is destructive, as a
107 /// delete verb is, so the generic edit is never a quieter way around it.
108 pub quiet_remove: bool,
109 /// `#[model(trust = "..")]`: who may change the field without being
110 /// asked first.
111 pub trust: Trust,
112 /// The JSON Schema of the field's value ([`Model::value_schema`](crate::Model::value_schema)).
113 pub schema: fn() -> serde_json::Value,
114 /// The field's type in the language-neutral vocabulary
115 /// ([`Model::field_type`](crate::Model::field_type)).
116 pub field_type: fn(&mut crate::TypeSet) -> crate::FieldType,
117 /// The first line of the field's text as stored ([`stored_text`]): what
118 /// a label made of it reads, rich text included.
119 pub text: StoredText,
120 /// What the field reads as while its key is absent, for a scalar field
121 /// ([`absent_scalar`]): history names it as the value an edit replaced.
122 pub absent: fn() -> Option<serde_json::Value>,
123 /// `#[model(resource)]`: the field holds a resource of its own type,
124 /// published beneath the resource of the record holding it
125 /// ([`NestedResource`](crate::child::NestedResource)).
126 pub resource: Option<crate::child::NestedResource>,
127}
128
129/// `value`, the JSON form of a value of `shape`, without the record fields
130/// that hold what their absent key reads as: what an edit that writes a new
131/// value carries of it, which reads back as the whole value.
132///
133/// Only a record has such fields, and `T::SHAPE` is known where this is
134/// instantiated, so for every other model this compiles to `value`.
135#[must_use]
136#[inline]
137pub(crate) fn without_absent<T: crate::Model>(value: serde_json::Value) -> serde_json::Value {
138 if matches!(T::SHAPE, Shape::Record(_)) {
139 (T::TABLE.ops.without_absent)(T::TABLE, value)
140 } else {
141 value
142 }
143}
144
145/// [`without_absent`] of a record, reached through its table's functions
146/// rather than `T::SHAPE`, which would copy its field list into every caller.
147pub(crate) fn resource_without_absent(
148 table: &crate::table::ModelTable,
149 value: serde_json::Value,
150) -> serde_json::Value {
151 match table.record().map(|record| record.shape) {
152 Some(Shape::Record(fields)) => without_absent_fields(fields, value),
153 _ => value,
154 }
155}
156
157/// [`without_absent`] of a value that is no record: all of it.
158pub(crate) fn kept_whole(
159 _: &crate::table::ModelTable,
160 value: serde_json::Value,
161) -> serde_json::Value {
162 value
163}
164
165#[inline(never)]
166fn without_absent_fields(
167 fields: &'static [FieldShape],
168 mut value: serde_json::Value,
169) -> serde_json::Value {
170 if let serde_json::Value::Object(map) = &mut value {
171 for field in fields {
172 if let Some(absent) = (field.absent)()
173 && map.get(field.key) == Some(&absent)
174 {
175 map.remove(field.key);
176 }
177 }
178 }
179 value
180}
181
182/// The value an absent key of a scalar `T` reads as, in JSON; `None` for a
183/// type stored as an object or without an empty value.
184#[must_use]
185pub fn absent_scalar<T: crate::Model>() -> Option<serde_json::Value> {
186 if T::SCALAR {
187 T::missing().ok().map(|value| value.to_json())
188 } else {
189 None
190 }
191}
192
193/// Reads the first line of a field's text from where it is stored.
194pub type StoredText =
195 fn(&crate::model::Doc, &automerge::Value<'_>, &automerge::ObjId) -> Option<String>;
196
197/// The first non-empty line of the text a `T` stored as `value` at `id`
198/// carries, as [`Model::label`](crate::Model::label) reads it from the value.
199pub fn stored_text<T: crate::Model>(
200 doc: &crate::model::Doc,
201 value: &automerge::Value<'_>,
202 id: &automerge::ObjId,
203) -> Option<String> {
204 // A value that loads on demand is read whole first.
205 let mut stored = T::load(doc, value, id).ok()?;
206 stored.read_whole(doc).ok()?;
207 crate::__private::first_line(&stored)
208}
209
210/// Two fields are the same field when everything but their value schema's
211/// function (which compares by address) is.
212impl PartialEq for FieldShape {
213 fn eq(&self, other: &Self) -> bool {
214 self.key == other.key
215 && self.owner == other.owner
216 && self.name == other.name
217 && self.ty == other.ty
218 && self.title == other.title
219 && self.shape == other.shape
220 && self.unit == other.unit
221 && self.readonly == other.readonly
222 && self.atom == other.atom
223 && self.label == other.label
224 && self.quiet_remove == other.quiet_remove
225 && self.trust == other.trust
226 && self.resource.map(|nested| nested.kind) == other.resource.map(|nested| nested.kind)
227 }
228}
229
230impl Eq for FieldShape {}
231
232impl Shape {
233 /// The fields of a record shape; none for any other.
234 #[must_use]
235 pub const fn fields(&self) -> &'static [FieldShape] {
236 match self {
237 Self::Record(fields) => fields,
238 Self::Value | Self::Collection(_) | Self::Keyed(_) | Self::Map(_) => &[],
239 }
240 }
241
242 /// The storage unit a change at `path` (from this shape's root) writes:
243 /// the longest prefix of the path that ends at a `#[model(unit)]` field
244 /// or an item of one. The record itself, the empty path, is a unit too.
245 #[must_use]
246 pub fn unit_of(&self, path: &[crate::path::Segment]) -> Vec<crate::path::Segment> {
247 use crate::path::Segment;
248 let mut unit = Vec::new();
249 let mut shape = *self;
250 let mut walked = Vec::new();
251 let mut items_are_units = false;
252 for segment in path {
253 walked.push(segment.clone());
254 match (shape, segment) {
255 (Self::Record(fields), Segment::Field(key)) => {
256 let Some(field) = fields.iter().find(|field| field.key == key) else {
257 break;
258 };
259 shape = field.shape;
260 items_are_units =
261 field.unit && matches!(field.shape, Self::Collection(_) | Self::Keyed(_));
262 if field.unit && !items_are_units {
263 unit.clone_from(&walked);
264 }
265 }
266 (Self::Collection(item) | Self::Keyed(item), Segment::Item(_)) => {
267 shape = *item;
268 if items_are_units {
269 unit.clone_from(&walked);
270 }
271 items_are_units = false;
272 }
273 _ => break,
274 }
275 }
276 unit
277 }
278
279 /// The fields below this shape that `select` answers for, by their
280 /// dotted paths (`*` for an item), as
281 /// [`tilo_action_policy::edits::dotted`] spells them.
282 fn selected<X>(&self, select: impl Fn(&FieldShape) -> Option<X>) -> Vec<(String, X)> {
283 fn walk<X>(
284 shape: Shape,
285 prefix: &str,
286 select: &impl Fn(&FieldShape) -> Option<X>,
287 out: &mut Vec<(String, X)>,
288 depth: usize,
289 ) {
290 if depth > 16 {
291 return;
292 }
293 match shape {
294 Shape::Record(fields) => {
295 for field in fields {
296 let path = if prefix.is_empty() {
297 field.key.to_owned()
298 } else {
299 format!("{prefix}.{}", field.key)
300 };
301 if let Some(value) = select(field) {
302 out.push((path.clone(), value));
303 }
304 walk(field.shape, &path, select, out, depth.saturating_add(1));
305 }
306 }
307 Shape::Collection(item) | Shape::Keyed(item) | Shape::Map(item) => {
308 walk(
309 *item,
310 &format!("{prefix}.*"),
311 select,
312 out,
313 depth.saturating_add(1),
314 );
315 }
316 Shape::Value => {}
317 }
318 }
319 let mut out = Vec::new();
320 walk(*self, "", &select, &mut out, 0);
321 out
322 }
323
324 /// The collections below this shape whose removals ask nothing
325 /// (`#[model(remove = "quiet")]`), by their dotted paths (`*` for an
326 /// item), as [`tilo_action_policy::edits::dotted`] spells them.
327 #[must_use]
328 pub fn quiet_removals(&self) -> Vec<String> {
329 self.selected(|field| field.quiet_remove.then_some(()))
330 .into_iter()
331 .map(|(path, ())| path)
332 .collect()
333 }
334
335 /// The fields below this shape that are not [`Trust::Ordinary`], by
336 /// their dotted paths (`*` for an item), as
337 /// [`tilo_action_policy::edits::dotted`] spells them.
338 #[must_use]
339 pub fn guarded_fields(&self) -> Vec<(String, Trust)> {
340 self.selected(|field| (field.trust != Trust::Ordinary).then_some(field.trust))
341 }
342
343 /// The trust of the field at `path`: the strictest of the fields it is
344 /// at or below.
345 #[must_use]
346 pub fn trust_at(&self, path: &[crate::path::Segment]) -> Trust {
347 use crate::path::Segment;
348 let mut shape = *self;
349 let mut trust = Trust::Ordinary;
350 for segment in path {
351 match (shape, segment) {
352 (Self::Record(fields), Segment::Field(key)) => {
353 let Some(field) = fields.iter().find(|field| field.key == key) else {
354 break;
355 };
356 trust = trust.max(field.trust);
357 shape = field.shape;
358 }
359 (
360 Self::Collection(item) | Self::Keyed(item) | Self::Map(item),
361 Segment::Item(_) | Segment::Key(_),
362 ) => shape = *item,
363 _ => break,
364 }
365 }
366 trust
367 }
368
369 /// Whether the field at `path` is `#[model(readonly)]`.
370 #[must_use]
371 pub fn readonly_at(&self, path: &[crate::path::Segment]) -> bool {
372 use crate::path::Segment;
373 let mut shape = *self;
374 for segment in path {
375 match (shape, segment) {
376 (Self::Record(fields), Segment::Field(key)) => {
377 let Some(field) = fields.iter().find(|field| field.key == key) else {
378 return false;
379 };
380 if field.readonly {
381 return true;
382 }
383 shape = field.shape;
384 }
385 (Self::Collection(item) | Self::Keyed(item), Segment::Item(_)) => shape = *item,
386 _ => return false,
387 }
388 }
389 false
390 }
391
392 /// The first field this lays out that is read only and `after` changes from `before`, by its
393 /// path (`themes.mine.dark`): a field only the record's own verbs change, never a field edit.
394 /// `before` and `after` are the record's JSON form ([`Model::to_json`](crate::Model::to_json)).
395 #[must_use]
396 pub fn changed_readonly<'a>(
397 &self,
398 before: Option<&'a serde_json::Value>,
399 after: Option<&'a serde_json::Value>,
400 ) -> Option<String> {
401 self.changed_readonly_at("", before, after)
402 }
403
404 fn changed_readonly_at<'a>(
405 &self,
406 path: &str,
407 before: Option<&'a serde_json::Value>,
408 after: Option<&'a serde_json::Value>,
409 ) -> Option<String> {
410 let join = |key: &str| {
411 if path.is_empty() {
412 key.to_owned()
413 } else {
414 format!("{path}.{key}")
415 }
416 };
417 match self {
418 Self::Value => None,
419 Self::Record(fields) => fields.iter().find_map(|field| {
420 let path = join(field.key);
421 let before = before.and_then(|value| value.get(field.key));
422 let after = after.and_then(|value| value.get(field.key));
423 if field.readonly {
424 (before != after).then_some(path)
425 } else {
426 field.shape.changed_readonly_at(&path, before, after)
427 }
428 }),
429 // A collection and a keyed collection are arrays of items, a collection's each
430 // `{"id", "value"}`; a map's items sit under their keys.
431 Self::Collection(item) => entries(before, after)
432 .into_iter()
433 .find_map(|(id, before, after)| item.changed_readonly_at(&join(id), before, after)),
434 Self::Keyed(item) => {
435 let count = [before, after]
436 .into_iter()
437 .flatten()
438 .filter_map(|value| value.as_array().map(Vec::len))
439 .max()
440 .unwrap_or_default();
441 (0..count).find_map(|at| {
442 let before = before
443 .and_then(serde_json::Value::as_array)
444 .and_then(|items| items.get(at));
445 let after = after
446 .and_then(serde_json::Value::as_array)
447 .and_then(|items| items.get(at));
448 item.changed_readonly_at(&join("*"), before, after)
449 })
450 }
451 Self::Map(item) => {
452 let mut keys: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
453 for value in [before, after].into_iter().flatten() {
454 keys.extend(
455 value
456 .as_object()
457 .into_iter()
458 .flatten()
459 .map(|(key, _)| key.as_str()),
460 );
461 }
462 keys.into_iter().find_map(|key| {
463 let before = before
464 .and_then(serde_json::Value::as_object)
465 .and_then(|entries| entries.get(key));
466 let after = after
467 .and_then(serde_json::Value::as_object)
468 .and_then(|entries| entries.get(key));
469 item.changed_readonly_at(&join(key), before, after)
470 })
471 }
472 }
473 }
474}
475
476/// One item of a collection's JSON form that changed: its id, and its value before and after (a
477/// side that does not hold it is `None`).
478type ChangedItem<'a> = (
479 &'a str,
480 Option<&'a serde_json::Value>,
481 Option<&'a serde_json::Value>,
482);
483
484/// The items of a collection's JSON form in `before` and `after`, by id, each with its value: an
485/// item only one side holds reads as `None` on the other.
486fn entries<'a>(
487 before: Option<&'a serde_json::Value>,
488 after: Option<&'a serde_json::Value>,
489) -> Vec<ChangedItem<'a>> {
490 let values =
491 |value: Option<&'a serde_json::Value>| -> Vec<(&'a str, Option<&'a serde_json::Value>)> {
492 value
493 .and_then(serde_json::Value::as_array)
494 .into_iter()
495 .flatten()
496 .filter_map(|entry| {
497 let id = entry.get("id").and_then(serde_json::Value::as_str)?;
498 Some((id, entry.get("value")))
499 })
500 .collect()
501 };
502 let before = values(before);
503 let after = values(after);
504 let ids: std::collections::BTreeSet<&str> =
505 before.iter().chain(&after).map(|(id, _)| *id).collect();
506 let of = |items: &[(&'a str, Option<&'a serde_json::Value>)], id: &str| {
507 items
508 .iter()
509 .find(|(held, _)| *held == id)
510 .and_then(|(_, value)| *value)
511 };
512 ids.into_iter()
513 .map(|id| (id, of(&before, id), of(&after, id)))
514 .collect()
515}
516
517/// The key of a collection entry's order key.
518pub const ENTRY_ORDER_KEY: &str = crate::collection::ORDER;
519/// The key of a collection entry's value.
520pub const ENTRY_VALUE_KEY: &str = crate::collection::VALUE;