Skip to main content

tilo_resource/
lib.rs

1//! # The Tilo resource layer
2//!
3//! A Tilo app's state is a set of **resources**: typed, versioned, shared
4//! values the system owns. This crate is the layer that turns a Rust type into
5//! one. It has no rendering, windowing or widget dependency. The UI toolkit
6//! uses only its document-generic parts (history, stamped commits, replay);
7//! `tilo-app` binds resources to views.
8//!
9//! ## The golden path
10//!
11//! ```
12//! use tilo_resource::{ActionCx, Collection, Id, Model, resource};
13//!
14//! #[derive(Model, Default)]
15//! pub struct Todo {
16//!     pub items: Collection<Item>,
17//! }
18//!
19//! #[derive(Model, Default)]
20//! pub struct Item {
21//!     pub title: String,
22//!     pub done: bool,
23//! }
24//!
25//! #[resource(kind = "example.todo")]
26//! impl Todo {
27//!     /// Add an item.
28//!     #[action]
29//!     pub fn add(&mut self, cx: &mut ActionCx, title: String) {
30//!         self.items.push(cx.id(), Item { title, done: false });
31//!     }
32//!
33//!     /// Mark an item done or not done.
34//!     #[action]
35//!     pub fn set_done(&mut self, item: Id, done: bool) -> Result<(), &'static str> {
36//!         self.items.get_mut(&item).ok_or("no such item")?.done = done;
37//!         Ok(())
38//!     }
39//! }
40//!
41//! // Tests are replay: apply actions the way a control, the palette, an agent
42//! // or a script would, and assert on state.
43//! fn main() {
44//!     // A replica names the app whose record it is before it applies anything: every device
45//!     // decides its changes against that app's surface.
46//!     let mut replica = tilo_resource::Replica::<Todo>::new().in_app("so.tilo.todo", "Todo");
47//!     replica.apply(Todo::ADD.with("Buy milk")).unwrap();
48//!     let id = replica.state().unwrap().items.ids().next().unwrap().clone();
49//!     replica.apply(Todo::SET_DONE.with((id, true))).unwrap();
50//!     assert!(replica.state().unwrap().items.values().all(|item| item.done));
51//! }
52//! ```
53//!
54//! That is the whole app-side state layer. From it the app gets, without
55//! writing any of it:
56//!
57//! * **storage and sync** — the resource is an Automerge document; every field
58//!   write is a minimal diff, text is spliced, collections are keyed and
59//!   fractionally ordered, so members' concurrent edits merge;
60//! * **replayable actions** — each `#[action]` method is a serializable
61//!   operation with typed parameters, applied deterministically (ids and time
62//!   come from [`ActionCx`]) and replayed byte-identically on every replica;
63//! * **exposure** — the same declarations are what the palette, agents and
64//!   scripts list and invoke ([`publish`]), with permissions per action, and
65//!   the generic [`APPLY`] operation publishes a JSON Schema of the action
66//!   vocabulary ([`Resource::action_schema`], [`JsonSchema`]);
67//! * **history** — every action is a change attributed to its author with its
68//!   label and time ([`history`]); any version can be read back
69//!   ([`history::read_at`]) and restored, field by field and item by item,
70//!   from the record's stored [`Shape`];
71//! * **search** — text fields are indexed by default ([`Resource::search`]);
72//! * **reading** — a record whose declaration names a document read answers
73//!   the framework's `read` with what it holds, as typed data
74//!   ([`read::fields`] for a record whose fields are all it holds), so an
75//!   agent, a script or the SDK with no window open reads any record through
76//!   the same action, permissions and audit as everything else;
77//! * **lookup by kind** — a host that works with whatever a workspace holds
78//!   reads, publishes and replays any registered type from the kind its
79//!   record names ([`Kinds`], [`ResourceKind`]);
80//! * **document machinery** — fractional [`order`] keys, stamped commits and
81//!   positional replay ([`history`]), writing large content as a few changes
82//!   ([`batch`]) and id-aligned structural [`diff`]s, shared by every
83//!   resource type including the hand-written ones;
84//! * **incremental reads** — after a change only what it touched is read
85//!   again ([`Resource::refresh`], [`Delta`]); a record resource gets this
86//!   field by field and item by item, and a resource too large to read whole
87//!   reads what views look at ([`Resource::load`], [`Demand`]).
88//!
89//! ## Custom resource types
90//!
91//! A type with its own layout and merge semantics — a rich-text document, a
92//! sheet — implements [`Resource`] by hand: [`read`](Resource::read) its
93//! state from a document, name its replayable [`Action`](Resource::Action)
94//! type, and optionally [`declarations`](Resource::declarations) for named,
95//! typed palette entries. The SDK ships those types (`RichText`, plain text,
96//! `Grid`); an app derives its record with `#[derive(Model)]` and
97//! `#[resource]` and holds them as fields, never implementing `Resource`
98//! itself (docs/architecture/resources.md §8). Such a type gets exactly the
99//! same services. Edits without a named declaration travel as the generic
100//! [`APPLY`] action, so nothing a custom surface does has to bypass
101//! permissions, history or undo. `APPLY` is for surfaces, agents and
102//! scripts, never a palette row; each value's own
103//! [`risk`](tilo_actions::Action::risk) decides whether it needs
104//! confirmation, so a destructive typed edit is treated exactly as a
105//! declared destructive action is: what Undo takes back runs at once and
106//! offers Undo, and only what it cannot is confirmed.
107
108// The derives name this crate by its path, here as in an app.
109extern crate self as tilo_resource;
110
111mod absolute_path;
112pub mod action;
113mod apply_cache;
114pub mod batch;
115pub mod child;
116pub mod children;
117mod chunk_map;
118mod clock;
119pub mod collection;
120#[cfg(test)]
121mod concurrent_text_tests;
122pub mod content;
123mod cow;
124mod dates;
125mod search_preview;
126pub use search_preview::SearchPreview;
127pub mod delta;
128pub mod derived;
129mod describe;
130pub mod diff;
131pub mod effect;
132pub mod evolution;
133pub mod footprint;
134pub mod genesis;
135pub mod group;
136pub mod history;
137pub mod items;
138mod kept;
139pub mod keyed;
140pub mod kind;
141pub mod label;
142mod map;
143pub mod members;
144pub mod model;
145mod non_blank;
146pub mod order;
147pub mod ordered;
148pub mod origin;
149pub mod path;
150pub mod reactions;
151pub mod read;
152pub mod reader;
153mod recents;
154pub mod recording;
155pub mod replica;
156pub mod resource;
157pub mod row;
158pub mod schema;
159pub mod schema_check;
160pub mod search_default;
161pub use tilo_actions::search_index;
162pub mod shape;
163pub mod share;
164pub mod sort;
165pub mod status;
166pub mod storage;
167pub mod stored_items;
168pub mod surface;
169pub mod table;
170pub mod text;
171pub mod unreadable;
172mod upsert;
173mod value;
174pub mod vocabulary;
175pub mod words;
176
177pub use __private::FlatFields;
178pub use absolute_path::{AbsolutePath, RelativePath};
179pub use action::{
180    ActionCx, ActionKey, ActionKind, ActionRef, Binds, Invoke, Mapped, NoParams, Operation,
181    Outcome, Params, Refusal, Reverting, Stamped, TryMapped, Undoing, fresh_uuid, invoking_member,
182    invoking_name, minted_entry, minted_ids, minted_keys, restore_minted, reverting_type,
183    take_minted,
184};
185/// A change a document reports, as an `answer` hook reads what its action did.
186pub use automerge::Patch;
187pub use child::{child_resource_id, publish_child};
188pub use children::{ChildList, ChildRef, Children, Trashed};
189pub use clock::HybridClock;
190pub use collection::{
191    Collection, Id, Membership, Quarantined, stored_entry, stored_ids, stored_item,
192};
193pub use delta::{Delta, ObjPath, Touch, Touched, Tracker};
194pub use derived::{Bound, Derived};
195pub use effect::{
196    Answers, Effect, EffectDecl, EffectDecodeError, EffectOffload, EffectTarget, NoEffect, decode,
197    offer,
198};
199pub use evolution::Unreadable;
200pub use group::{ActionGroup, GROUP, GROUP_PARAM};
201pub use keyed::{ById, Identified, ItemStorage, Items, Keyed};
202pub use kind::{Kinds, ResourceKind};
203pub use map::Map;
204pub use model::{
205    Atom, Doc, Fields, Fresh, LocatedAt, MapSlot, Model, ModelError, Slot, VARIANT_KEY, edit_whole,
206    load_slot, read_key, read_slots, refresh_key, take_slot, write_key, write_key_changed,
207};
208pub use non_blank::{Blank, NonBlank};
209pub use ordered::{Arranged, Ordered};
210pub use origin::Origin;
211pub use path::{
212    At, Edit, EditOp, OP_ARGUMENTS, Operations, Path, Segment, Settable, op_argument_schema,
213    op_arguments, op_usage, outbox_settle_arguments,
214};
215pub use reactions::{
216    Reaction, ReactionGroup, Reactions, Reactor, custom_emoji_name, reaction_emoji,
217    valid_custom_emoji_name,
218};
219pub use reader::{Demand, Reader, heads_of};
220pub use recents::Recents;
221pub use replica::{AppNamed, NoApp, Replica};
222pub use resource::{
223    APPLY, APPLY_PARAM, ActionDecl, BuildAction, EDIT_PARAM, FIELD_EDIT, HeadInputs, NamesItem,
224    NoAction, Place, Resource, ScopeDecl, SearchBody, SearchEntry, SearchPiece, SearchRow,
225    SearchRowShape, SearchText, SearchWeight, SharedResource, bind_declaration, build_action,
226    by_app_refusal, child_by_id, declaration_spec, default_search, encode, head_inputs, need_of,
227    origin_now_ms, publish, publish_head, publish_head_of, reset_type_schemas, scope_contains,
228    spec_kind, state_from_reading, with_origin_clock,
229};
230pub use row::{Handle, LiveRow, RowBindings, typed_resource};
231pub use schema::JsonSchema;
232pub use shape::{FieldShape, Shape, StoredText, Trust, absent_scalar, stored_text};
233pub use status::EffectStatus;
234pub use storage::{Bytes, Counter, Grid, Outbox, OutboxEntry, Set, Settled};
235pub use surface::Surface;
236pub use text::{PlainText, TextEdit};
237pub use tilo_action_policy::edits::Weaker;
238pub use tilo_action_policy::{DIRECT_CONVERSATION_PREFIX, MemberId, PersonId};
239pub use tilo_actions::surface::{FieldType, TypeSet};
240pub use tilo_actions::{Acting, Availability};
241pub use tilo_resource_macros::{Effect, JsonSchema, Model, Row, committed_surface, resource};
242pub use tilo_sort::{Frecency, frecency};
243pub use unreadable::withhold_document_actions;
244pub use vocabulary::{Built, Declaration, Vocabulary, vocabulary};
245
246/// A word of the catalogue beside the crate that names it,
247/// `word!("files-rename-here")`: a [`label::Word`] read in the person's
248/// language whenever what carries it is published. A key the crate's
249/// `locales/en-US.ftl` does not hold does not build;
250/// `word!("key", catalogue = "tests/locales")` reads another catalogue.
251///
252/// A word that names what a person is looking at carries it as an argument —
253/// `word!("files-folder-rename-selected", name = file.0)` — which the
254/// catalogue's message shows with its placeable (`Rename “{ $name }”`) in
255/// every language the crate translates it into, and a count by its forms
256/// (`{ $count -> [one] … }`). An argument the message has no placeable for,
257/// or a placeable with no argument, does not build.
258#[macro_export]
259macro_rules! word {
260    ($($input:tt)*) => {
261        $crate::__private::word!($crate, $($input)*)
262    };
263}
264
265/// Items the generated code refers to. Not part of the public API.
266#[doc(hidden)]
267pub mod __private {
268    pub use automerge::{ObjId, ObjType, Patch, ROOT, ReadDoc, ScalarValue, Value};
269    pub use serde;
270    pub use serde_json;
271    pub use tilo_actions::{
272        ActionArgs, ActionKind, ActionParam, ActionRegistry, ActionSpec, Audience, ChangeKind,
273        HOST_RENDER_TAG, OperationKind, PROMPTED_PARAM, ParamType, ResourceSpec, ResourceViewSpec,
274        RiskLevel, SCREEN_PLACE_TAG, SCREEN_TAG, StepKind, picked_address_schema,
275        picked_resource_schema,
276    };
277    pub use tilo_resource_macros::word;
278
279    pub use crate::apply_cache::forget_all;
280
281    /// Whether `record` holds an item where the nested item verb `action`
282    /// acts: what its children would offer it bound on.
283    #[must_use]
284    pub fn holds_nested_items(
285        record: &crate::table::ResourceDesc,
286        state: &dyn std::any::Any,
287        action: &crate::items::ItemAction,
288    ) -> bool {
289        let Some(field) = action.collection else {
290            return false;
291        };
292        let mut path: Vec<&str> = action.within.to_vec();
293        path.push(field);
294        crate::table::holds_nested_items(record, state, &path)
295    }
296
297    /// A record to copy, if its type can be copied: `#[resource]` asks for
298    /// `(&&Snapshot(record)).snapshot()`, which method resolution answers
299    /// with [`SnapshotByClone`] for a `Clone` record and with
300    /// [`SnapshotUnavailable`] otherwise.
301    pub struct Snapshot<'a, T>(pub &'a T);
302
303    /// A copy of a `Clone` record.
304    pub trait SnapshotByClone<T> {
305        fn snapshot(&self) -> Option<T>;
306    }
307
308    impl<T: Clone> SnapshotByClone<T> for &Snapshot<'_, T> {
309        fn snapshot(&self) -> Option<T> {
310            Some(self.0.clone())
311        }
312    }
313
314    /// No copy of a record that cannot be cloned.
315    pub trait SnapshotUnavailable<T> {
316        fn snapshot(&self) -> Option<T>;
317    }
318
319    impl<T> SnapshotUnavailable<T> for Snapshot<'_, T> {
320        fn snapshot(&self) -> Option<T> {
321            None
322        }
323    }
324
325    /// `T`'s value of a field `key` the document does not hold, located at
326    /// it: one function per field type, not a closure per field.
327    ///
328    /// # Errors
329    /// Why `T` has no such value.
330    use crate::model::LocatedAt as _;
331
332    /// The field edit `op` at `rest` inside the field `key` of `obj`,
333    /// located at it.
334    pub fn edit_at<T: crate::Model>(
335        doc: &mut crate::Doc,
336        obj: &ObjId,
337        key: &str,
338        rest: &[crate::Segment],
339        op: &crate::EditOp,
340        cx: &mut crate::ActionCx,
341    ) -> Result<(), crate::ModelError> {
342        T::edit(doc, crate::Slot::Key(obj, key), rest, op, cx).located(key)
343    }
344
345    /// How a verb's change is undone.
346    #[derive(Clone, Copy, PartialEq, Eq)]
347    pub enum VerbUndo {
348        /// By reverting the document: the change is all there is.
349        Revert,
350        /// By its compensating verb (`#[action(undo = ...)]`): it also
351        /// queued an outside consequence, which only that takes back.
352        Compensation,
353    }
354
355    /// What a verb answers its caller.
356    #[derive(Clone, Copy, PartialEq, Eq)]
357    pub enum VerbAnswer {
358        /// Only the items it created.
359        Created,
360        /// What it made (`#[action(answers)]`, [`crate::Resource::answer`]).
361        Made,
362        /// What the outside work it queued came back with, once a host
363        /// performed it.
364        Queued,
365    }
366
367    /// What `#[resource]` declares of one verb, besides how it is built.
368    #[derive(Clone)]
369    #[allow(
370        clippy::struct_excessive_bools,
371        reason = "one independent `#[action(...)]` flag each, as the macro reads them"
372    )]
373    pub struct VerbDecl {
374        pub id: &'static str,
375        pub label: crate::label::Word,
376        /// The other words people use for it (`keywords = "…"`).
377        pub keywords: &'static [&'static str],
378        /// Its own picture (`icon = "…"`), by its Lucide name.
379        pub icon: Option<&'static str>,
380        /// What it did, in the app's own words (`did = "…"`), read after who
381        /// did it.
382        pub did: Option<&'static str>,
383        pub description: &'static str,
384        pub kind: ActionKind,
385        /// Whether one invocation's kind is decided by its arguments
386        /// (`#[action(local = path)]`); `kind` is then the least it is.
387        pub by_arguments: bool,
388        pub field: Option<&'static str>,
389        pub destructive: bool,
390        /// It also loses what Undo cannot bring back
391        /// (`#[action(irreversible)]`).
392        pub irreversible: bool,
393        /// A change about the record rather than to it
394        /// (`#[action(housekeeping)]`).
395        pub housekeeping: bool,
396        pub answer: VerbAnswer,
397        /// It records a message someone received (`#[action(incoming_message)]`).
398        pub incoming_message: bool,
399        /// How its change is undone.
400        pub undo: VerbUndo,
401        /// Who listings offer it to (`#[action(audience = "agents")]`).
402        pub audience: tilo_actions::Audience,
403        pub collects: Option<&'static str>,
404        /// The parameter the content it collects arrives as.
405        pub content: Option<&'static str>,
406        pub item_field: Option<&'static str>,
407        /// The collection whose item it acts on, when it is offered on items
408        /// (`#[action(item = field)]`, or an item id its first parameter).
409        pub item: Option<&'static str>,
410        pub writes: &'static [&'static str],
411        /// The kind of step it takes (`#[action(step = "create")]`): what
412        /// presence says of it
413        /// ([`tilo_actions::StepKind`]). `None` for a verb whose declaration
414        /// names none, whose step reads as the part of the record it acts on.
415        pub step: Option<tilo_actions::StepKind>,
416        pub shape: crate::Shape,
417        pub params: &'static [ParamDecl],
418    }
419
420    /// What `#[resource]` declares of one parameter of a verb: static data,
421    /// made into the published parameter by one function for every verb.
422    #[derive(Clone, Copy)]
423    pub struct ParamDecl {
424        pub name: &'static str,
425        pub ty: ParamTypeOf,
426        pub description: &'static str,
427        /// The schema of the parameter's type.
428        pub schema: fn() -> serde_json::Value,
429        pub optional: bool,
430        pub place: PlaceIn,
431        pub example: Option<fn() -> serde_json::Value>,
432        /// Its type's fields are the verb's parameters, each its own.
433        pub flat: bool,
434        /// For a flattened parameter, its type's fields and their published
435        /// types, by name: what names an enum or record a nested argument is.
436        pub flat_types: Option<crate::surface::FlatTypes>,
437        /// It takes content another action produced, by its hash, beside
438        /// the verb's other parameters.
439        pub content: bool,
440        /// Its type in the surface's vocabulary.
441        pub field_type: crate::vocabulary::ParamFieldType,
442    }
443
444    /// A declared parameter's type.
445    #[derive(Clone, Copy)]
446    pub enum ParamTypeOf {
447        /// Known from the Rust type.
448        Known(ParamType),
449        /// Read off the schema of the (present) value's type.
450        Schema(fn() -> serde_json::Value),
451    }
452
453    /// A record's fields as an action's own parameters, typed as the record
454    /// declares them: what `#[param(flatten)]` publishes, so an argument that
455    /// is an enum names that enum rather than "any".
456    pub trait FlatFields {
457        /// The record's fields, in declaration order, with the types the
458        /// record declares them; the types it names are declared in `types`.
459        fn flat_fields(types: &mut crate::TypeSet) -> Vec<(String, crate::FieldType)>;
460    }
461
462    impl<T: crate::JsonSchema> FlatFields for T {
463        fn flat_fields(types: &mut crate::TypeSet) -> Vec<(String, crate::FieldType)> {
464            let crate::FieldType::Named(name) = <T as crate::JsonSchema>::field_type(types) else {
465                return Vec::new();
466            };
467            types
468                .get(&name)
469                .map(|record| {
470                    record
471                        .fields
472                        .iter()
473                        .map(|field| (field.name.clone(), field.ty.clone()))
474                        .collect()
475                })
476                .unwrap_or_default()
477        }
478    }
479
480    /// The published parameters of `params`.
481    #[must_use]
482    pub fn params_of(params: &[ParamDecl]) -> Vec<ActionParam> {
483        let mut out = Vec::with_capacity(params.len());
484        for param in params {
485            if param.flat {
486                out.extend(flat_params(&(param.schema)()));
487                continue;
488            }
489            let ty = match param.ty {
490                ParamTypeOf::Known(ty) => ty,
491                ParamTypeOf::Schema(schema) => param_type_of(&schema()),
492            };
493            let declared = declared_param(
494                param.name,
495                ty,
496                param.description,
497                param.schema,
498                param.optional,
499                param.place,
500                param.example,
501            );
502            out.push(if param.content {
503                declared.as_content()
504            } else {
505                declared
506            });
507        }
508        out
509    }
510
511    /// The declaration of the verb `verb`, built by `build`.
512    pub fn declare<R: crate::Resource>(
513        verb: VerbDecl,
514        build: fn(&ActionArgs, i64) -> Result<R::Action, String>,
515    ) -> crate::ActionDecl<R> {
516        let builds: crate::vocabulary::Builds =
517            std::sync::Arc::new(move |args, now_ms| match build(args, now_ms) {
518                Ok(action) => Ok(crate::Built::of::<R>(action)),
519                Err(reason) => Err(reason),
520            });
521        crate::ActionDecl::declared(verb_declaration(crate::vocabulary::<R>(), verb, builds))
522    }
523
524    /// The declaration of the verb `verb` of the record `R`, whose action
525    /// is its operation `O` decoded from the arguments: one build for
526    /// every verb of the record.
527    pub fn declare_verb<R, O>(verb: VerbDecl) -> crate::ActionDecl<R>
528    where
529        R: crate::Resource<Action = crate::Stamped<O>>,
530        O: serde::de::DeserializeOwned,
531    {
532        let (id, content) = (verb.id, verb.content);
533        let builds: crate::vocabulary::Builds = std::sync::Arc::new(move |args, now_ms| {
534            let arguments = verb_arguments(args, content);
535            match build_stamped::<O>(id, &arguments, now_ms) {
536                Ok(action) => Ok(crate::Built::of::<R>(action)),
537                Err(reason) => Err(reason),
538            }
539        });
540        crate::ActionDecl::declared(verb_declaration(crate::vocabulary::<R>(), verb, builds))
541    }
542
543    /// The arguments of a verb invoked with `args`, the content it collects
544    /// (if any) under its parameter `content`.
545    fn verb_arguments(
546        args: &ActionArgs,
547        content: Option<&'static str>,
548    ) -> serde_json::Map<String, serde_json::Value> {
549        let mut arguments = args.to_json();
550        if let Some(content) = content
551            && let Some(hash) = arguments.remove(PROMPTED_PARAM)
552        {
553            arguments.insert(String::from(content), hash);
554        }
555        arguments
556    }
557
558    /// The declaration of `verb` of the resource `vocabulary`, built by
559    /// `build`.
560    fn verb_declaration(
561        vocabulary: &crate::Vocabulary,
562        verb: VerbDecl,
563        build: crate::vocabulary::Builds,
564    ) -> crate::Declaration {
565        let written = verb.label.source;
566        let mut decl = crate::Declaration::new(
567            vocabulary,
568            verb.id,
569            written.to_owned(),
570            params_of(verb.params),
571            build,
572        );
573        decl.word = Some(verb.label);
574        decl.param_types = verb
575            .params
576            .iter()
577            .filter(|param| !param.flat)
578            .map(|param| (param.name, param.field_type))
579            .collect();
580        decl.flat_types = verb
581            .params
582            .iter()
583            .find(|param| param.flat)
584            .and_then(|param| param.flat_types);
585        decl.kind = verb.kind;
586        decl.keywords = verb
587            .keywords
588            .iter()
589            .map(|word| (*word).to_owned())
590            .collect();
591        decl.icon = verb.icon.map(str::to_owned);
592        decl.did = verb.did.map(str::to_owned);
593        decl.by_arguments = verb.by_arguments;
594        decl.writes = crate::footprint::declared(verb.shape, verb.item_field, verb.writes);
595        decl.item = verb.item;
596        // What the description says beyond its first line, the label.
597        let description = verb
598            .description
599            .strip_prefix(written)
600            .map_or(verb.description, |rest| {
601                rest.trim_start_matches('.').trim_start()
602            });
603        if !description.is_empty() {
604            decl.description = Some(description.to_owned());
605        }
606        decl.field = verb.field;
607        decl.destructive = verb.destructive;
608        decl.step = verb
609            .step
610            .or_else(|| verb.destructive.then_some(tilo_actions::StepKind::Delete));
611        // A create that declares the collection it adds to makes one of them:
612        // its step says that collection's noun ("an issue").
613        decl.creates = (decl.step == Some(tilo_actions::StepKind::Create))
614            .then(|| verb.writes.first().copied())
615            .flatten();
616        if verb.irreversible {
617            decl.tags.push(tilo_actions::IRREVERSIBLE_TAG.to_owned());
618        }
619        if verb.housekeeping {
620            decl.tags.push(tilo_actions::HOUSEKEEPING_TAG.to_owned());
621        }
622        if verb.incoming_message {
623            decl.tags
624                .push(tilo_actions::INCOMING_MESSAGE_TAG.to_owned());
625        }
626        if let Some(tag) = verb.audience.tag() {
627            decl.tags.push(tag.to_owned());
628        }
629        if verb.undo == VerbUndo::Compensation {
630            decl.tags
631                .push(tilo_actions::COMPENSATED_UNDO_TAG.to_owned());
632        }
633        match verb.answer {
634            VerbAnswer::Created => {}
635            VerbAnswer::Made => {
636                decl.result = Some(tilo_actions::ResultSpec::Json {
637                    schema: serde_json::json!({"type": "object"}),
638                });
639            }
640            // One result, or a list for several entries; nothing while the
641            // work is still queued.
642            VerbAnswer::Queued => {
643                decl.result = Some(tilo_actions::ResultSpec::Json {
644                    schema: serde_json::json!({"type": ["object", "array", "null"]}),
645                });
646            }
647        }
648        if let Some(prompt) = verb.collects {
649            decl.content = Some(prompt.to_owned());
650        }
651        decl
652    }
653
654    /// Where a declared parameter names a place in the record.
655    #[derive(Clone, Copy)]
656    pub enum PlaceIn {
657        /// It is no place.
658        Nowhere,
659        /// Anywhere in the record.
660        Record,
661        /// Among the items of this field.
662        Field(&'static str),
663    }
664
665    /// A verb's declared parameter, built by one function for every verb:
666    /// its schema is its type's, described, with the example when given. Its
667    /// name and description are a verb's own words and, at an effect, its
668    /// field's spelling and catalogue word, which is why it takes them the
669    /// way the constructors beside it do.
670    #[must_use]
671    pub fn declared_param(
672        name: impl Into<String>,
673        ty: ParamType,
674        description: impl Into<String>,
675        schema: fn() -> serde_json::Value,
676        optional: bool,
677        place: PlaceIn,
678        example: Option<fn() -> serde_json::Value>,
679    ) -> ActionParam {
680        let name = name.into();
681        let description = description.into();
682        let param = if optional {
683            ActionParam::optional_owned(name, ty, description)
684        } else {
685            ActionParam::required_owned(name, ty, description)
686        }
687        // The parameter carries its description; its schema does not say
688        // it again.
689        .with_schema(param_schema(schema(), "", example.map(|example| example())));
690        match place {
691            PlaceIn::Nowhere => param,
692            PlaceIn::Record => param.as_place(),
693            PlaceIn::Field(field) => param.as_place_in(field),
694        }
695    }
696
697    /// A parameter's schema: its type's, described, with an example.
698    #[must_use]
699    pub fn param_schema(
700        schema: serde_json::Value,
701        description: &str,
702        example: Option<serde_json::Value>,
703    ) -> serde_json::Value {
704        let mut schema = crate::schema::describe(schema, description);
705        if let (Some(example), serde_json::Value::Object(fields)) = (example, &mut schema) {
706            fields.insert("examples".into(), serde_json::Value::Array(vec![example]));
707        }
708        schema
709    }
710
711    /// `Some(T::default())` when `T` is `Default`, else `None`, decided
712    /// where `T` is concrete: `(&DefaultOf::<T>::new()).default_value()`
713    /// with [`HasDefault`] and [`NoDefault`] in scope. A skipped field reads
714    /// as its containing type's default this way.
715    pub struct DefaultOf<T>(::core::marker::PhantomData<T>);
716
717    impl<T> DefaultOf<T> {
718        #[must_use]
719        pub const fn new() -> Self {
720            Self(::core::marker::PhantomData)
721        }
722    }
723
724    impl<T> Default for DefaultOf<T> {
725        fn default() -> Self {
726            Self::new()
727        }
728    }
729
730    /// See [`DefaultOf`].
731    pub trait HasDefault<T> {
732        fn default_value(&self) -> Option<T>;
733    }
734
735    impl<T: Default> HasDefault<T> for DefaultOf<T> {
736        fn default_value(&self) -> Option<T> {
737            Some(T::default())
738        }
739    }
740
741    /// See [`DefaultOf`].
742    pub trait NoDefault<T> {
743        fn default_value(&self) -> Option<T>;
744    }
745
746    impl<T> NoDefault<T> for &DefaultOf<T> {
747        fn default_value(&self) -> Option<T> {
748            None
749        }
750    }
751
752    /// A number a field's `#[model(range = ..)]` bounds: its value, `None`
753    /// for an absent optional one.
754    pub trait DeclaredNumber {
755        fn declared_number(&self) -> Option<f64>;
756    }
757
758    macro_rules! declared_number {
759        ($($ty:ty),*) => {$(
760            impl DeclaredNumber for $ty {
761                #[allow(clippy::cast_precision_loss, clippy::cast_lossless, reason = "a range bound is a numeric limit far below 2^53")]
762                fn declared_number(&self) -> Option<f64> {
763                    Some(*self as f64)
764                }
765            }
766        )*};
767    }
768    declared_number!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize, f32, f64);
769
770    impl<T: DeclaredNumber> DeclaredNumber for Option<T> {
771        fn declared_number(&self) -> Option<f64> {
772            self.as_ref().and_then(DeclaredNumber::declared_number)
773        }
774    }
775
776    /// A text a field's `#[model(choices = ..)]` names: its value, `None` for
777    /// an absent optional one.
778    pub trait DeclaredChoice {
779        fn declared_choice(&self) -> Option<&str>;
780    }
781
782    impl DeclaredChoice for String {
783        fn declared_choice(&self) -> Option<&str> {
784            Some(self)
785        }
786    }
787
788    impl<T: DeclaredChoice> DeclaredChoice for Option<T> {
789        fn declared_choice(&self) -> Option<&str> {
790            self.as_ref().and_then(DeclaredChoice::declared_choice)
791        }
792    }
793
794    /// A declared range's bound, as the number it is.
795    #[must_use]
796    pub fn declared_bound(bound: &impl DeclaredNumber) -> f64 {
797        bound.declared_number().unwrap_or(f64::NAN)
798    }
799
800    /// Refused unless `value` lies within `low..=high`; `key` names the
801    /// field as a field edit's path does.
802    pub fn declared_range(
803        value: &impl DeclaredNumber,
804        low: f64,
805        high: f64,
806        key: &str,
807    ) -> Result<(), crate::Refusal> {
808        match value.declared_number() {
809            Some(number) if !(number.is_finite() && (low..=high).contains(&number)) => Err(
810                crate::Refusal::new(format!("`{key}` is between {low} and {high}")),
811            ),
812            _ => Ok(()),
813        }
814    }
815
816    /// Refused unless `value` is one of `choices`.
817    pub fn declared_choices(
818        value: &impl DeclaredChoice,
819        choices: &[&str],
820        key: &str,
821    ) -> Result<(), crate::Refusal> {
822        match value.declared_choice() {
823            Some(chosen) if !choices.contains(&chosen) => Err(crate::Refusal::new(format!(
824                "`{key}` is one of {}",
825                choices.join(", ")
826            ))),
827            _ => Ok(()),
828        }
829    }
830
831    /// Run `change` on the item of type `T` at `path` of the record `R`,
832    /// reading only that item, then write what changed where the item is
833    /// kept, checked, or remove the item where `change` asked to
834    /// ([`ActionCx::remove_item`](crate::ActionCx::remove_item)): an item
835    /// method applied. `None` where nothing is at `path`: the caller decides
836    /// on the whole resource then, where an item named by its label is
837    /// found, or one that is not there is refused with the items there are.
838    ///
839    /// # Errors
840    /// The item does not read as `T`, the method refused, or an edit did not
841    /// apply.
842    pub fn apply_item<R, T>(
843        doc: &mut crate::Doc,
844        cx: &mut crate::ActionCx,
845        path: &[crate::Segment],
846        change: impl FnOnce(&mut T, &mut crate::ActionCx) -> Result<(), crate::Refusal>,
847    ) -> Option<Result<(), crate::Refusal>>
848    where
849        R: crate::Fields,
850        T: crate::Model,
851    {
852        let obj = crate::Path::<R, T>::from_segments(path.to_vec()).object(doc)?;
853        Some(apply_item_at::<R, T>(doc, cx, path, &obj, change))
854    }
855
856    fn apply_item_at<R, T>(
857        doc: &mut crate::Doc,
858        cx: &mut crate::ActionCx,
859        path: &[crate::Segment],
860        obj: &automerge::ObjId,
861        change: impl FnOnce(&mut T, &mut crate::ActionCx) -> Result<(), crate::Refusal>,
862    ) -> Result<(), crate::Refusal>
863    where
864        R: crate::Fields,
865        T: crate::Model,
866    {
867        let refused = |error: crate::ModelError| crate::Refusal::new(error.to_string());
868        let map = automerge::Value::Object(automerge::ObjType::Map);
869        let before = T::load(doc, &map, obj).map_err(refused)?;
870        let mut after = T::load(doc, &map, obj).map_err(refused)?;
871        let _ = cx.take_item_removal();
872        change(&mut after, cx)?;
873        if cx.take_item_removal() {
874            let (Some(crate::Segment::Item(id)), Some(collection)) = (
875                path.last(),
876                path.len().checked_sub(1).and_then(|at| path.get(..at)),
877            ) else {
878                return Err(crate::Refusal::new(
879                    "only an item of a collection is removed",
880                ));
881            };
882            let op = crate::EditOp::RemoveItem { id: id.clone() };
883            return R::edit_fields(doc, &ROOT, collection, &op, cx).map_err(refused);
884        }
885        crate::Model::check(&after)?;
886        if after.stores_as(&before) {
887            return Ok(());
888        }
889        // Written where it is kept, as the resource's own write writes it:
890        // only what changed, its read-only fields too (a verb sets those,
891        // a field edit from outside never does).
892        let Some(automerge::Parent {
893            obj: parent,
894            prop: automerge::Prop::Map(key),
895            ..
896        }) = doc.parents(obj).ok().and_then(|mut parents| parents.next())
897        else {
898            return Err(crate::Refusal::new("the item is not kept under a key"));
899        };
900        after
901            .store(doc, crate::Slot::Key(&parent, &key))
902            .map_err(refused)
903    }
904
905    /// The first non-empty line of the text `value` carries: one part of a
906    /// label.
907    pub fn first_line<T: crate::Model>(value: &T) -> Option<String> {
908        let mut text = Vec::new();
909        value.collect_text(&mut text);
910        first_line_of(text)
911    }
912
913    pub use tilo_actions::params::param_type_of;
914
915    /// The parameters a `#[param(flatten)]` struct's schema lists: each
916    /// property by name, typed and described by its own schema, required as
917    /// the schema says.
918    #[must_use]
919    pub fn flat_params(schema: &serde_json::Value) -> Vec<ActionParam> {
920        let required: Vec<&str> = schema
921            .get("required")
922            .and_then(serde_json::Value::as_array)
923            .map(|names| names.iter().filter_map(serde_json::Value::as_str).collect())
924            .unwrap_or_default();
925        let Some(properties) = schema
926            .get("properties")
927            .and_then(serde_json::Value::as_object)
928        else {
929            return Vec::new();
930        };
931        properties
932            .iter()
933            .map(|(name, property)| {
934                let description = property
935                    .get("description")
936                    .and_then(serde_json::Value::as_str)
937                    .unwrap_or(name)
938                    .to_owned();
939                let ty = param_type_of(property);
940                let param = if required.contains(&name.as_str()) {
941                    ActionParam::required_owned(name.clone(), ty, description)
942                } else {
943                    ActionParam::optional_owned(name.clone(), ty, description)
944                };
945                // The parameter carries the description; its schema does not
946                // say it again.
947                let mut schema = property.clone();
948                if let Some(schema) = schema.as_object_mut() {
949                    schema.remove("description");
950                }
951                param.with_schema(schema)
952            })
953            .collect()
954    }
955
956    /// `value` in its JSON form, written as bytes and read back: the
957    /// byte serializer every recorded action already has serves, rather
958    /// than one more per type for `serde_json::to_value`.
959    ///
960    /// # Errors
961    /// Why `value` does not serialize.
962    #[inline(never)]
963    pub fn json_via_bytes<T: serde::Serialize + ?Sized>(
964        value: &T,
965    ) -> Result<serde_json::Value, serde_json::Error> {
966        let bytes = serde_json::to_vec(value)?;
967        value_of_bytes(&bytes)
968    }
969
970    /// The JSON value in `bytes`, parsed by code compiled once: a model
971    /// type's reader that parses its stored text calls this and then reads
972    /// itself out of the value, rather than compiling `serde_json`'s whole
973    /// text parser again for every app it is instantiated in.
974    #[inline(never)]
975    pub(crate) fn value_of_bytes(bytes: &[u8]) -> Result<serde_json::Value, serde_json::Error> {
976        serde_json::from_slice(bytes)
977    }
978
979    /// The action `id` with `arguments`, stamped `now_ms`, decoded as a
980    /// recorded action is (`{"op": {"action", "args"}, "at"}` from bytes):
981    /// one decoder per resource serves building and replaying.
982    pub fn build_stamped<O: serde::de::DeserializeOwned>(
983        id: &str,
984        arguments: &serde_json::Map<String, serde_json::Value>,
985        now_ms: i64,
986    ) -> Result<crate::Stamped<O>, String> {
987        let operation = serde_json::json!({ "action": id, "args": arguments });
988        O::deserialize(operation)
989            .map(|operation| crate::Stamped { operation, now_ms })
990            .map_err(|error| error.to_string())
991    }
992
993    pub use crate::resource::{default_search, kept_of, listed_of};
994
995    /// The arguments of a verb's JSON form: an object (`null` for none).
996    ///
997    /// # Errors
998    /// Why `value` is no arguments object.
999    #[inline(never)]
1000    pub fn args_object(
1001        value: serde_json::Value,
1002    ) -> Result<serde_json::Map<String, serde_json::Value>, serde_json::Error> {
1003        use serde::de::Error as _;
1004        match value {
1005            serde_json::Value::Object(args) => Ok(args),
1006            serde_json::Value::Null => Ok(serde_json::Map::new()),
1007            other => Err(serde_json::Error::invalid_type(
1008                serde::de::Unexpected::Other(&other.to_string()),
1009                &"the arguments as an object",
1010            )),
1011        }
1012    }
1013
1014    /// The argument `name` taken from `args`, decoded as a `T`; an absent
1015    /// one is `None` when `optional`, else missing.
1016    ///
1017    /// # Errors
1018    /// Why the argument is missing or not a `T`.
1019    pub fn arg<T: serde::de::DeserializeOwned>(
1020        args: &mut serde_json::Map<String, serde_json::Value>,
1021        name: &'static str,
1022        optional: bool,
1023    ) -> Result<T, serde_json::Error> {
1024        // Only the decode is per type: taking the argument out is compiled
1025        // once for every parameter of every action.
1026        T::deserialize(take_arg(args, name, optional)?)
1027    }
1028
1029    /// The argument `name` taken from `args`: `null` for an absent optional
1030    /// one, else missing.
1031    #[inline(never)]
1032    fn take_arg(
1033        args: &mut serde_json::Map<String, serde_json::Value>,
1034        name: &'static str,
1035        optional: bool,
1036    ) -> Result<serde_json::Value, serde_json::Error> {
1037        use serde::de::Error as _;
1038        match args.remove(name) {
1039            Some(value) => Ok(value),
1040            None if optional => Ok(serde_json::Value::Null),
1041            None => Err(serde_json::Error::missing_field(name)),
1042        }
1043    }
1044
1045    /// The action name and arguments of an action's JSON form
1046    /// (`{"action": .., "args": ..}`, the arguments `null` when absent).
1047    ///
1048    /// # Errors
1049    /// Why `value` is not an action.
1050    #[inline(never)]
1051    pub fn tagged(
1052        value: serde_json::Value,
1053    ) -> Result<(String, serde_json::Value), serde_json::Error> {
1054        use serde::de::Error as _;
1055        let serde_json::Value::Object(mut fields) = value else {
1056            return Err(serde_json::Error::custom("an action is an object"));
1057        };
1058        let Some(serde_json::Value::String(action)) = fields.remove("action") else {
1059            return Err(serde_json::Error::missing_field("action"));
1060        };
1061        Ok((
1062            action,
1063            fields.remove("args").unwrap_or(serde_json::Value::Null),
1064        ))
1065    }
1066
1067    /// The JSON form's schema of a record of `shape`: each field's under its
1068    /// key, read from the shape so it is built by one function for every
1069    /// record type.
1070    #[must_use]
1071    pub fn resource_value_schema(shape: crate::Shape) -> serde_json::Value {
1072        let properties: serde_json::Map<String, serde_json::Value> = shape
1073            .fields()
1074            .iter()
1075            .map(|field| (field.key.to_owned(), (field.schema)()))
1076            .collect();
1077        serde_json::json!({"type": "object", "properties": properties})
1078    }
1079
1080    /// The first non-empty line among `text`.
1081    #[inline(never)]
1082    pub(crate) fn first_line_of(text: Vec<String>) -> Option<String> {
1083        text.into_iter()
1084            .map(|line| line.lines().next().unwrap_or_default().trim().to_owned())
1085            .find(|line| !line.is_empty())
1086    }
1087
1088    /// A `#[model(check)]` function's result as a refusal.
1089    pub fn check_outcome<O: crate::Outcome>(outcome: O) -> Result<(), crate::Refusal> {
1090        outcome.into_result()
1091    }
1092}
1093
1094pub use tilo_actions::profiling;