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