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_actions::surface::{FieldType, TypeSet};
240pub use tilo_actions::{Acting, Availability};
241pub use tilo_member_types::{DIRECT_CONVERSATION_PREFIX, MemberId, PersonId};
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        /// What it does leaves the system for good (`#[action(leaves)]`).
397        pub leaves: bool,
398        /// A change about the record rather than to it
399        /// (`#[action(housekeeping)]`).
400        pub housekeeping: bool,
401        pub answer: VerbAnswer,
402        /// It records a message someone received (`#[action(incoming_message)]`).
403        pub incoming_message: bool,
404        /// How its change is undone.
405        pub undo: VerbUndo,
406        /// Who listings offer it to (`#[action(audience = "agents")]`).
407        pub audience: tilo_actions::Audience,
408        pub collects: Option<&'static str>,
409        /// The parameter the content it collects arrives as.
410        pub content: Option<&'static str>,
411        pub item_field: Option<&'static str>,
412        /// The collection whose item it acts on, when it is offered on items
413        /// (`#[action(item = field)]`, or an item id its first parameter).
414        pub item: Option<&'static str>,
415        pub writes: &'static [&'static str],
416        /// The kind of step it takes (`#[action(step = "create")]`): what
417        /// presence says of it
418        /// ([`tilo_actions::StepKind`]). `None` for a verb whose declaration
419        /// names none, whose step reads as the part of the record it acts on.
420        pub step: Option<tilo_actions::StepKind>,
421        pub shape: crate::Shape,
422        pub params: &'static [ParamDecl],
423    }
424
425    /// What `#[resource]` declares of one parameter of a verb: static data,
426    /// made into the published parameter by one function for every verb.
427    #[derive(Clone, Copy)]
428    pub struct ParamDecl {
429        pub name: &'static str,
430        pub ty: ParamTypeOf,
431        pub description: &'static str,
432        /// The schema of the parameter's type.
433        pub schema: fn() -> serde_json::Value,
434        pub optional: bool,
435        pub place: PlaceIn,
436        pub example: Option<fn() -> serde_json::Value>,
437        /// Its type's fields are the verb's parameters, each its own.
438        pub flat: bool,
439        /// For a flattened parameter, its type's fields and their published
440        /// types, by name: what names an enum or record a nested argument is.
441        pub flat_types: Option<crate::surface::FlatTypes>,
442        /// It takes content another action produced, by its hash, beside
443        /// the verb's other parameters.
444        pub content: bool,
445        /// Its type in the surface's vocabulary.
446        pub field_type: crate::vocabulary::ParamFieldType,
447    }
448
449    /// A declared parameter's type.
450    #[derive(Clone, Copy)]
451    pub enum ParamTypeOf {
452        /// Known from the Rust type.
453        Known(ParamType),
454        /// Read off the schema of the (present) value's type.
455        Schema(fn() -> serde_json::Value),
456    }
457
458    /// A record's fields as an action's own parameters, typed as the record
459    /// declares them: what `#[param(flatten)]` publishes, so an argument that
460    /// is an enum names that enum rather than "any".
461    pub trait FlatFields {
462        /// The record's fields, in declaration order, with the types the
463        /// record declares them; the types it names are declared in `types`.
464        fn flat_fields(types: &mut crate::TypeSet) -> Vec<(String, crate::FieldType)>;
465    }
466
467    impl<T: crate::JsonSchema> FlatFields for T {
468        fn flat_fields(types: &mut crate::TypeSet) -> Vec<(String, crate::FieldType)> {
469            let crate::FieldType::Named(name) = <T as crate::JsonSchema>::field_type(types) else {
470                return Vec::new();
471            };
472            types
473                .get(&name)
474                .map(|record| {
475                    record
476                        .fields
477                        .iter()
478                        .map(|field| (field.name.clone(), field.ty.clone()))
479                        .collect()
480                })
481                .unwrap_or_default()
482        }
483    }
484
485    /// The published parameters of `params`.
486    #[must_use]
487    pub fn params_of(params: &[ParamDecl]) -> Vec<ActionParam> {
488        let mut out = Vec::with_capacity(params.len());
489        for param in params {
490            if param.flat {
491                out.extend(flat_params(&(param.schema)()));
492                continue;
493            }
494            let ty = match param.ty {
495                ParamTypeOf::Known(ty) => ty,
496                ParamTypeOf::Schema(schema) => param_type_of(&schema()),
497            };
498            let declared = declared_param(
499                param.name,
500                ty,
501                param.description,
502                param.schema,
503                param.optional,
504                param.place,
505                param.example,
506            );
507            out.push(if param.content {
508                declared.as_content()
509            } else {
510                declared
511            });
512        }
513        out
514    }
515
516    /// The declaration of the verb `verb`, built by `build`.
517    pub fn declare<R: crate::Resource>(
518        verb: VerbDecl,
519        build: fn(&ActionArgs, i64) -> Result<R::Action, String>,
520    ) -> crate::ActionDecl<R> {
521        let builds: crate::vocabulary::Builds =
522            std::sync::Arc::new(move |args, now_ms| match build(args, now_ms) {
523                Ok(action) => Ok(crate::Built::of::<R>(action)),
524                Err(reason) => Err(reason),
525            });
526        crate::ActionDecl::declared(verb_declaration(crate::vocabulary::<R>(), verb, builds))
527    }
528
529    /// The declaration of the verb `verb` of the record `R`, whose action
530    /// is its operation `O` decoded from the arguments: one build for
531    /// every verb of the record.
532    pub fn declare_verb<R, O>(verb: VerbDecl) -> crate::ActionDecl<R>
533    where
534        R: crate::Resource<Action = crate::Stamped<O>>,
535        O: serde::de::DeserializeOwned,
536    {
537        let (id, content) = (verb.id, verb.content);
538        let builds: crate::vocabulary::Builds = std::sync::Arc::new(move |args, now_ms| {
539            let arguments = verb_arguments(args, content);
540            match build_stamped::<O>(id, &arguments, now_ms) {
541                Ok(action) => Ok(crate::Built::of::<R>(action)),
542                Err(reason) => Err(reason),
543            }
544        });
545        crate::ActionDecl::declared(verb_declaration(crate::vocabulary::<R>(), verb, builds))
546    }
547
548    /// The arguments of a verb invoked with `args`, the content it collects
549    /// (if any) under its parameter `content`.
550    fn verb_arguments(
551        args: &ActionArgs,
552        content: Option<&'static str>,
553    ) -> serde_json::Map<String, serde_json::Value> {
554        let mut arguments = args.to_json();
555        if let Some(content) = content
556            && let Some(hash) = arguments.remove(PROMPTED_PARAM)
557        {
558            arguments.insert(String::from(content), hash);
559        }
560        arguments
561    }
562
563    /// The declaration of `verb` of the resource `vocabulary`, built by
564    /// `build`.
565    fn verb_declaration(
566        vocabulary: &crate::Vocabulary,
567        verb: VerbDecl,
568        build: crate::vocabulary::Builds,
569    ) -> crate::Declaration {
570        let written = verb.label.source;
571        let mut decl = crate::Declaration::new(
572            vocabulary,
573            verb.id,
574            written.to_owned(),
575            params_of(verb.params),
576            build,
577        );
578        decl.word = Some(verb.label);
579        decl.param_types = verb
580            .params
581            .iter()
582            .filter(|param| !param.flat)
583            .map(|param| (param.name, param.field_type))
584            .collect();
585        decl.flat_types = verb
586            .params
587            .iter()
588            .find(|param| param.flat)
589            .and_then(|param| param.flat_types);
590        decl.kind = verb.kind;
591        decl.keywords = verb
592            .keywords
593            .iter()
594            .map(|word| (*word).to_owned())
595            .collect();
596        decl.icon = verb.icon.map(str::to_owned);
597        decl.did = verb.did.map(str::to_owned);
598        decl.by_arguments = verb.by_arguments;
599        decl.writes = crate::footprint::declared(verb.shape, verb.item_field, verb.writes);
600        decl.item = verb.item;
601        // What the description says beyond its first line, the label.
602        let description = verb
603            .description
604            .strip_prefix(written)
605            .map_or(verb.description, |rest| {
606                rest.trim_start_matches('.').trim_start()
607            });
608        if !description.is_empty() {
609            decl.description = Some(description.to_owned());
610        }
611        decl.field = verb.field;
612        decl.destructive = verb.destructive;
613        decl.step = verb
614            .step
615            .or_else(|| verb.destructive.then_some(tilo_actions::StepKind::Delete));
616        // A create that declares the collection it adds to makes one of them:
617        // its step says that collection's noun ("an issue").
618        decl.creates = (decl.step == Some(tilo_actions::StepKind::Create))
619            .then(|| verb.writes.first().copied())
620            .flatten();
621        if verb.irreversible {
622            decl.tags.push(tilo_actions::IRREVERSIBLE_TAG.to_owned());
623        }
624        if verb.leaves {
625            decl.tags.push(tilo_actions::LEAVES_TAG.to_owned());
626        }
627        if verb.housekeeping {
628            decl.tags.push(tilo_actions::HOUSEKEEPING_TAG.to_owned());
629        }
630        if verb.incoming_message {
631            decl.tags
632                .push(tilo_actions::INCOMING_MESSAGE_TAG.to_owned());
633        }
634        if let Some(tag) = verb.audience.tag() {
635            decl.tags.push(tag.to_owned());
636        }
637        if verb.undo == VerbUndo::Compensation {
638            decl.tags
639                .push(tilo_actions::COMPENSATED_UNDO_TAG.to_owned());
640        }
641        match verb.answer {
642            VerbAnswer::Created => {}
643            VerbAnswer::Made => {
644                decl.result = Some(tilo_actions::ResultSpec::Json {
645                    schema: serde_json::json!({"type": "object"}),
646                });
647            }
648            // One result, or a list for several entries; nothing while the
649            // work is still queued.
650            VerbAnswer::Queued => {
651                decl.result = Some(tilo_actions::ResultSpec::Json {
652                    schema: serde_json::json!({"type": ["object", "array", "null"]}),
653                });
654            }
655        }
656        if let Some(prompt) = verb.collects {
657            decl.content = Some(prompt.to_owned());
658        }
659        decl
660    }
661
662    /// Where a declared parameter names a place in the record.
663    #[derive(Clone, Copy)]
664    pub enum PlaceIn {
665        /// It is no place.
666        Nowhere,
667        /// Anywhere in the record.
668        Record,
669        /// Among the items of this field.
670        Field(&'static str),
671    }
672
673    /// A verb's declared parameter, built by one function for every verb:
674    /// its schema is its type's, described, with the example when given. Its
675    /// name and description are a verb's own words and, at an effect, its
676    /// field's spelling and catalogue word, which is why it takes them the
677    /// way the constructors beside it do.
678    #[must_use]
679    pub fn declared_param(
680        name: impl Into<String>,
681        ty: ParamType,
682        description: impl Into<String>,
683        schema: fn() -> serde_json::Value,
684        optional: bool,
685        place: PlaceIn,
686        example: Option<fn() -> serde_json::Value>,
687    ) -> ActionParam {
688        let name = name.into();
689        let description = description.into();
690        let param = if optional {
691            ActionParam::optional_owned(name, ty, description)
692        } else {
693            ActionParam::required_owned(name, ty, description)
694        }
695        // The parameter carries its description; its schema does not say
696        // it again.
697        .with_schema(param_schema(schema(), "", example.map(|example| example())));
698        match place {
699            PlaceIn::Nowhere => param,
700            PlaceIn::Record => param.as_place(),
701            PlaceIn::Field(field) => param.as_place_in(field),
702        }
703    }
704
705    /// A parameter's schema: its type's, described, with an example.
706    #[must_use]
707    pub fn param_schema(
708        schema: serde_json::Value,
709        description: &str,
710        example: Option<serde_json::Value>,
711    ) -> serde_json::Value {
712        let mut schema = crate::schema::describe(schema, description);
713        if let (Some(example), serde_json::Value::Object(fields)) = (example, &mut schema) {
714            fields.insert("examples".into(), serde_json::Value::Array(vec![example]));
715        }
716        schema
717    }
718
719    /// `Some(T::default())` when `T` is `Default`, else `None`, decided
720    /// where `T` is concrete: `(&DefaultOf::<T>::new()).default_value()`
721    /// with [`HasDefault`] and [`NoDefault`] in scope. A skipped field reads
722    /// as its containing type's default this way.
723    pub struct DefaultOf<T>(::core::marker::PhantomData<T>);
724
725    impl<T> DefaultOf<T> {
726        #[must_use]
727        pub const fn new() -> Self {
728            Self(::core::marker::PhantomData)
729        }
730    }
731
732    impl<T> Default for DefaultOf<T> {
733        fn default() -> Self {
734            Self::new()
735        }
736    }
737
738    /// See [`DefaultOf`].
739    pub trait HasDefault<T> {
740        fn default_value(&self) -> Option<T>;
741    }
742
743    impl<T: Default> HasDefault<T> for DefaultOf<T> {
744        fn default_value(&self) -> Option<T> {
745            Some(T::default())
746        }
747    }
748
749    /// See [`DefaultOf`].
750    pub trait NoDefault<T> {
751        fn default_value(&self) -> Option<T>;
752    }
753
754    impl<T> NoDefault<T> for &DefaultOf<T> {
755        fn default_value(&self) -> Option<T> {
756            None
757        }
758    }
759
760    /// A number a field's `#[model(range = ..)]` bounds: its value, `None`
761    /// for an absent optional one.
762    pub trait DeclaredNumber {
763        fn declared_number(&self) -> Option<f64>;
764    }
765
766    macro_rules! declared_number {
767        ($($ty:ty),*) => {$(
768            impl DeclaredNumber for $ty {
769                #[allow(clippy::cast_precision_loss, clippy::cast_lossless, reason = "a range bound is a numeric limit far below 2^53")]
770                fn declared_number(&self) -> Option<f64> {
771                    Some(*self as f64)
772                }
773            }
774        )*};
775    }
776    declared_number!(u8, u16, u32, u64, usize, i8, i16, i32, i64, isize, f32, f64);
777
778    impl<T: DeclaredNumber> DeclaredNumber for Option<T> {
779        fn declared_number(&self) -> Option<f64> {
780            self.as_ref().and_then(DeclaredNumber::declared_number)
781        }
782    }
783
784    /// A text a field's `#[model(choices = ..)]` names: its value, `None` for
785    /// an absent optional one.
786    pub trait DeclaredChoice {
787        fn declared_choice(&self) -> Option<&str>;
788    }
789
790    impl DeclaredChoice for String {
791        fn declared_choice(&self) -> Option<&str> {
792            Some(self)
793        }
794    }
795
796    impl<T: DeclaredChoice> DeclaredChoice for Option<T> {
797        fn declared_choice(&self) -> Option<&str> {
798            self.as_ref().and_then(DeclaredChoice::declared_choice)
799        }
800    }
801
802    /// A declared range's bound, as the number it is.
803    #[must_use]
804    pub fn declared_bound(bound: &impl DeclaredNumber) -> f64 {
805        bound.declared_number().unwrap_or(f64::NAN)
806    }
807
808    /// Refused unless `value` lies within `low..=high`; `key` names the
809    /// field as a field edit's path does.
810    pub fn declared_range(
811        value: &impl DeclaredNumber,
812        low: f64,
813        high: f64,
814        key: &str,
815    ) -> Result<(), crate::Refusal> {
816        match value.declared_number() {
817            Some(number) if !(number.is_finite() && (low..=high).contains(&number)) => Err(
818                crate::Refusal::new(format!("`{key}` is between {low} and {high}")),
819            ),
820            _ => Ok(()),
821        }
822    }
823
824    /// Refused unless `value` is one of `choices`.
825    pub fn declared_choices(
826        value: &impl DeclaredChoice,
827        choices: &[&str],
828        key: &str,
829    ) -> Result<(), crate::Refusal> {
830        match value.declared_choice() {
831            Some(chosen) if !choices.contains(&chosen) => Err(crate::Refusal::new(format!(
832                "`{key}` is one of {}",
833                choices.join(", ")
834            ))),
835            _ => Ok(()),
836        }
837    }
838
839    /// Run `change` on the item of type `T` at `path` of the record `R`,
840    /// reading only that item, then write what changed where the item is
841    /// kept, checked, or remove the item where `change` asked to
842    /// ([`ActionCx::remove_item`](crate::ActionCx::remove_item)): an item
843    /// method applied. `None` where nothing is at `path`: the caller decides
844    /// on the whole resource then, where an item named by its label is
845    /// found, or one that is not there is refused with the items there are.
846    ///
847    /// # Errors
848    /// The item does not read as `T`, the method refused, or an edit did not
849    /// apply.
850    pub fn apply_item<R, T>(
851        doc: &mut crate::Doc,
852        cx: &mut crate::ActionCx,
853        path: &[crate::Segment],
854        change: impl FnOnce(&mut T, &mut crate::ActionCx) -> Result<(), crate::Refusal>,
855    ) -> Option<Result<(), crate::Refusal>>
856    where
857        R: crate::Fields,
858        T: crate::Model,
859    {
860        let obj = crate::Path::<R, T>::from_segments(path.to_vec()).object(doc)?;
861        Some(apply_item_at::<R, T>(doc, cx, path, &obj, change))
862    }
863
864    fn apply_item_at<R, T>(
865        doc: &mut crate::Doc,
866        cx: &mut crate::ActionCx,
867        path: &[crate::Segment],
868        obj: &automerge::ObjId,
869        change: impl FnOnce(&mut T, &mut crate::ActionCx) -> Result<(), crate::Refusal>,
870    ) -> Result<(), crate::Refusal>
871    where
872        R: crate::Fields,
873        T: crate::Model,
874    {
875        let refused = |error: crate::ModelError| crate::Refusal::new(error.to_string());
876        let map = automerge::Value::Object(automerge::ObjType::Map);
877        let before = T::load(doc, &map, obj).map_err(refused)?;
878        let mut after = T::load(doc, &map, obj).map_err(refused)?;
879        let _ = cx.take_item_removal();
880        change(&mut after, cx)?;
881        if cx.take_item_removal() {
882            let (Some(crate::Segment::Item(id)), Some(collection)) = (
883                path.last(),
884                path.len().checked_sub(1).and_then(|at| path.get(..at)),
885            ) else {
886                return Err(crate::Refusal::new(
887                    "only an item of a collection is removed",
888                ));
889            };
890            let op = crate::EditOp::RemoveItem { id: id.clone() };
891            return R::edit_fields(doc, &ROOT, collection, &op, cx).map_err(refused);
892        }
893        crate::Model::check(&after)?;
894        if after.stores_as(&before) {
895            return Ok(());
896        }
897        // Written where it is kept, as the resource's own write writes it:
898        // only what changed, its read-only fields too (a verb sets those,
899        // a field edit from outside never does).
900        let Some(automerge::Parent {
901            obj: parent,
902            prop: automerge::Prop::Map(key),
903            ..
904        }) = doc.parents(obj).ok().and_then(|mut parents| parents.next())
905        else {
906            return Err(crate::Refusal::new("the item is not kept under a key"));
907        };
908        after
909            .store(doc, crate::Slot::Key(&parent, &key))
910            .map_err(refused)
911    }
912
913    /// The first non-empty line of the text `value` carries: one part of a
914    /// label.
915    pub fn first_line<T: crate::Model>(value: &T) -> Option<String> {
916        let mut text = Vec::new();
917        value.collect_text(&mut text);
918        first_line_of(text)
919    }
920
921    pub use tilo_actions::params::param_type_of;
922
923    /// The parameters a `#[param(flatten)]` struct's schema lists: each
924    /// property by name, typed and described by its own schema, required as
925    /// the schema says.
926    #[must_use]
927    pub fn flat_params(schema: &serde_json::Value) -> Vec<ActionParam> {
928        let required: Vec<&str> = schema
929            .get("required")
930            .and_then(serde_json::Value::as_array)
931            .map(|names| names.iter().filter_map(serde_json::Value::as_str).collect())
932            .unwrap_or_default();
933        let Some(properties) = schema
934            .get("properties")
935            .and_then(serde_json::Value::as_object)
936        else {
937            return Vec::new();
938        };
939        properties
940            .iter()
941            .map(|(name, property)| {
942                let description = property
943                    .get("description")
944                    .and_then(serde_json::Value::as_str)
945                    .unwrap_or(name)
946                    .to_owned();
947                let ty = param_type_of(property);
948                let param = if required.contains(&name.as_str()) {
949                    ActionParam::required_owned(name.clone(), ty, description)
950                } else {
951                    ActionParam::optional_owned(name.clone(), ty, description)
952                };
953                // The parameter carries the description; its schema does not
954                // say it again.
955                let mut schema = property.clone();
956                if let Some(schema) = schema.as_object_mut() {
957                    schema.remove("description");
958                }
959                param.with_schema(schema)
960            })
961            .collect()
962    }
963
964    /// `value` in its JSON form, written as bytes and read back: the
965    /// byte serializer every recorded action already has serves, rather
966    /// than one more per type for `serde_json::to_value`.
967    ///
968    /// # Errors
969    /// Why `value` does not serialize.
970    #[inline(never)]
971    pub fn json_via_bytes<T: serde::Serialize + ?Sized>(
972        value: &T,
973    ) -> Result<serde_json::Value, serde_json::Error> {
974        let bytes = serde_json::to_vec(value)?;
975        value_of_bytes(&bytes)
976    }
977
978    /// The JSON value in `bytes`, parsed by code compiled once: a model
979    /// type's reader that parses its stored text calls this and then reads
980    /// itself out of the value, rather than compiling `serde_json`'s whole
981    /// text parser again for every app it is instantiated in.
982    #[inline(never)]
983    pub(crate) fn value_of_bytes(bytes: &[u8]) -> Result<serde_json::Value, serde_json::Error> {
984        serde_json::from_slice(bytes)
985    }
986
987    /// The action `id` with `arguments`, stamped `now_ms`, decoded as a
988    /// recorded action is (`{"op": {"action", "args"}, "at"}` from bytes):
989    /// one decoder per resource serves building and replaying.
990    pub fn build_stamped<O: serde::de::DeserializeOwned>(
991        id: &str,
992        arguments: &serde_json::Map<String, serde_json::Value>,
993        now_ms: i64,
994    ) -> Result<crate::Stamped<O>, String> {
995        let operation = serde_json::json!({ "action": id, "args": arguments });
996        O::deserialize(operation)
997            .map(|operation| crate::Stamped { operation, now_ms })
998            .map_err(|error| error.to_string())
999    }
1000
1001    pub use crate::resource::{default_search, kept_of, listed_of};
1002
1003    /// The arguments of a verb's JSON form: an object (`null` for none).
1004    ///
1005    /// # Errors
1006    /// Why `value` is no arguments object.
1007    #[inline(never)]
1008    pub fn args_object(
1009        value: serde_json::Value,
1010    ) -> Result<serde_json::Map<String, serde_json::Value>, serde_json::Error> {
1011        use serde::de::Error as _;
1012        match value {
1013            serde_json::Value::Object(args) => Ok(args),
1014            serde_json::Value::Null => Ok(serde_json::Map::new()),
1015            other => Err(serde_json::Error::invalid_type(
1016                serde::de::Unexpected::Other(&other.to_string()),
1017                &"the arguments as an object",
1018            )),
1019        }
1020    }
1021
1022    /// The argument `name` taken from `args`, decoded as a `T`; an absent
1023    /// one is `None` when `optional`, else missing.
1024    ///
1025    /// # Errors
1026    /// Why the argument is missing or not a `T`.
1027    pub fn arg<T: serde::de::DeserializeOwned>(
1028        args: &mut serde_json::Map<String, serde_json::Value>,
1029        name: &'static str,
1030        optional: bool,
1031    ) -> Result<T, serde_json::Error> {
1032        // Only the decode is per type: taking the argument out is compiled
1033        // once for every parameter of every action.
1034        T::deserialize(take_arg(args, name, optional)?)
1035    }
1036
1037    /// The argument `name` taken from `args`: `null` for an absent optional
1038    /// one, else missing.
1039    #[inline(never)]
1040    fn take_arg(
1041        args: &mut serde_json::Map<String, serde_json::Value>,
1042        name: &'static str,
1043        optional: bool,
1044    ) -> Result<serde_json::Value, serde_json::Error> {
1045        use serde::de::Error as _;
1046        match args.remove(name) {
1047            Some(value) => Ok(value),
1048            None if optional => Ok(serde_json::Value::Null),
1049            None => Err(serde_json::Error::missing_field(name)),
1050        }
1051    }
1052
1053    /// The action name and arguments of an action's JSON form
1054    /// (`{"action": .., "args": ..}`, the arguments `null` when absent).
1055    ///
1056    /// # Errors
1057    /// Why `value` is not an action.
1058    #[inline(never)]
1059    pub fn tagged(
1060        value: serde_json::Value,
1061    ) -> Result<(String, serde_json::Value), serde_json::Error> {
1062        use serde::de::Error as _;
1063        let serde_json::Value::Object(mut fields) = value else {
1064            return Err(serde_json::Error::custom("an action is an object"));
1065        };
1066        let Some(serde_json::Value::String(action)) = fields.remove("action") else {
1067            return Err(serde_json::Error::missing_field("action"));
1068        };
1069        Ok((
1070            action,
1071            fields.remove("args").unwrap_or(serde_json::Value::Null),
1072        ))
1073    }
1074
1075    /// The JSON form's schema of a record of `shape`: each field's under its
1076    /// key, read from the shape so it is built by one function for every
1077    /// record type.
1078    #[must_use]
1079    pub fn resource_value_schema(shape: crate::Shape) -> serde_json::Value {
1080        let properties: serde_json::Map<String, serde_json::Value> = shape
1081            .fields()
1082            .iter()
1083            .map(|field| (field.key.to_owned(), (field.schema)()))
1084            .collect();
1085        serde_json::json!({"type": "object", "properties": properties})
1086    }
1087
1088    /// The first non-empty line among `text`.
1089    #[inline(never)]
1090    pub(crate) fn first_line_of(text: Vec<String>) -> Option<String> {
1091        text.into_iter()
1092            .map(|line| line.lines().next().unwrap_or_default().trim().to_owned())
1093            .find(|line| !line.is_empty())
1094    }
1095
1096    /// A `#[model(check)]` function's result as a refusal.
1097    pub fn check_outcome<O: crate::Outcome>(outcome: O) -> Result<(), crate::Refusal> {
1098        outcome.into_result()
1099    }
1100}
1101
1102pub use tilo_actions::profiling;