Skip to main content

tilo_resource/
action.rs

1//! Typed actions over a record resource: a method on the record becomes a
2//! replayable, attributable, undoable operation.
3//!
4//! `#[resource]` turns every `#[action]` method into a variant of a generated
5//! operation enum implementing [`Operation`]. Applying it reads the record
6//! from the document, runs the method, and writes back only what the method
7//! changed — so the method is ordinary Rust over ordinary fields and the CRDT
8//! stays invisible.
9
10use std::any::Any;
11use std::marker::PhantomData;
12use tilo_sort::CompactSort as _;
13
14use automerge::ROOT;
15use serde::de::DeserializeOwned;
16use serde::{Deserialize, Serialize};
17use tilo_action_policy::MemberId;
18use tilo_actions::{ActionError, ExecutionLocus, RiskLevel};
19
20use crate::collection::Id;
21use crate::kind::ResourceKind;
22use crate::model::{Doc, Fields};
23use crate::resource::Resource;
24
25/// Deterministic services available while an action applies.
26///
27/// Everything here is a pure function of the action and the document it was
28/// authored against, so the origin and every replaying replica compute the
29/// same ids and see the same time.
30#[derive(Debug)]
31pub struct ActionCx {
32    preview: bool,
33    seed: [u8; 32],
34    minted: u64,
35    /// The ids [`Self::id`] minted, in order.
36    ids: Vec<Id>,
37    now_ms: i64,
38    author: Option<MemberId>,
39    invocation: Option<tilo_actions::InvocationId>,
40    /// An item method removes the item it acts on ([`Self::remove_item`]).
41    removes_item: bool,
42}
43
44/// Who invoked the action applying now, as its envelope pinned it.
45fn invoking_author() -> Option<MemberId> {
46    tilo_actions::reading_invoking_context(|context| {
47        context
48            .and_then(|context| context.invoker.as_ref())
49            .and_then(invoker_member)
50    })
51    .or_else(|| RESOURCE_ACTOR.with_borrow(Clone::clone))
52}
53
54/// The member an invoker acts as: the member itself, or for an automation the
55/// member it runs for.
56fn invoker_member(invoker: &tilo_actions::ActionInvoker) -> Option<MemberId> {
57    invoker
58        .acting
59        .members()
60        .first()
61        .map(|member| (*member).clone())
62}
63
64/// Who writes now: the invoker the envelope of the action applying now
65/// pinned; outside an action, the actor a record write is lent. Inside an
66/// action only its envelope counts, so every replica replaying it reads the
67/// same author.
68pub(crate) fn writing_author() -> Option<MemberId> {
69    tilo_actions::reading_invoking_context(|context| match context {
70        Some(context) => context.invoker.as_ref().and_then(invoker_member),
71        None => RESOURCE_ACTOR.with_borrow(Clone::clone),
72    })
73}
74
75thread_local! {
76    static RESOURCE_ACTOR: std::cell::RefCell<Option<MemberId>> = const { std::cell::RefCell::new(None) };
77}
78
79/// Attribution lent by the SDK's checked record callback. Compensation is
80/// calculated before an action envelope is installed, but must still see the
81/// actual admitted actor rather than an anonymous ambient host.
82///
83/// This supplies attribution only, never permission to access host resources.
84pub struct ResourceActorScope(Option<MemberId>);
85
86impl ResourceActorScope {
87    /// Lend the actor admitted by the record host for this callback.
88    #[must_use]
89    pub fn enter(actor: MemberId) -> Self {
90        Self(RESOURCE_ACTOR.replace(Some(actor)))
91    }
92}
93
94impl Drop for ResourceActorScope {
95    fn drop(&mut self) {
96        RESOURCE_ACTOR.replace(self.0.take());
97    }
98}
99
100fn invoking_invocation() -> Option<tilo_actions::InvocationId> {
101    tilo_actions::reading_invoking_context(|context| context?.source_invocation)
102}
103
104impl ActionCx {
105    /// Remove the item the item method running now acts on
106    /// (`#[action(item = field)]` with the item as its first parameter): what
107    /// it changed of the item is let go with it. The item is read and removed
108    /// alone, never the collection holding it, however many items that holds.
109    pub fn remove_item(&mut self) {
110        self.removes_item = true;
111    }
112
113    /// Whether the item method that ran asked for its item to be removed
114    /// ([`Self::remove_item`]), forgetting it.
115    #[doc(hidden)]
116    pub fn take_item_removal(&mut self) -> bool {
117        std::mem::take(&mut self.removes_item)
118    }
119
120    /// A context seeded from the document's heads and actor (both pinned by
121    /// the executor) and the action's own payload.
122    ///
123    /// Inside an [`ActionGroup`](crate::ActionGroup) the group's seed and the
124    /// member's position stand in for the heads, which a member cannot read
125    /// without committing the members before it as separate changes.
126    #[must_use]
127    pub fn for_apply(doc: &Doc, payload: &[u8], now_ms: i64) -> Self {
128        Self {
129            preview: tilo_actions::executor::is_replaying(),
130            seed: seed(doc, b"tilo-resource/action-seed/v1", payload),
131            minted: 0,
132            ids: Vec::new(),
133            now_ms,
134            author: invoking_author(),
135            invocation: invoking_invocation(),
136            removes_item: false,
137        }
138    }
139
140    /// A context for ids minted part-way through an action that has already
141    /// written: seeded like [`Self::for_apply`] but from the heads the action
142    /// started from, so reading them does not commit its writes so far as a
143    /// separate change.
144    #[must_use]
145    pub fn for_write(doc: &Doc, payload: &[u8]) -> Self {
146        let mut hasher = blake3::Hasher::new();
147        hasher.update(b"tilo-resource/write-seed/v1");
148        if let Some((group, position)) = crate::group::current_member() {
149            hasher.update(b"member");
150            hasher.update(&group);
151            hasher.update(&position.to_le_bytes());
152        } else {
153            hasher.update(doc.get_actor().to_bytes());
154            let mut heads = automerge::transaction::Transactable::base_heads(doc);
155            heads.compact_sort();
156            for head in heads {
157                hasher.update(&head.0);
158            }
159        }
160        hasher.update(payload);
161        Self {
162            preview: tilo_actions::executor::is_replaying(),
163            seed: *hasher.finalize().as_bytes(),
164            minted: 0,
165            ids: Vec::new(),
166            now_ms: 0,
167            author: invoking_author(),
168            invocation: invoking_invocation(),
169            removes_item: false,
170        }
171    }
172
173    /// Whether the runtime is evaluating compensation on a private record copy
174    /// or replaying an existing change. Neither may issue host-local approvals
175    /// or repeat outside effects; only a new invocation admits those.
176    #[must_use]
177    pub fn is_preview(&self) -> bool {
178        self.preview
179    }
180
181    /// A fresh id, unique to this action and stable under replay.
182    pub fn id(&mut self) -> Id {
183        let id = minted(&self.seed, self.minted);
184        self.minted = self.minted.saturating_add(1);
185        self.ids.push(id.clone());
186        note_minted(id.as_str());
187        id
188    }
189
190    /// A fresh UUID, unique to this action and stable under replay.
191    pub fn uuid(&mut self) -> uuid::Uuid {
192        let uuid = minted_uuid(&self.seed, self.minted);
193        self.minted = self.minted.saturating_add(1);
194        note_minted(&uuid.to_string());
195        uuid
196    }
197
198    /// Name the item this change is about, when the record holds no item for
199    /// it: the file a device will write, the entry the action queued. History
200    /// says the change by `label`, which is what a person reads, under `id`:
201    /// the id the change carries, which need not be a resource the app can
202    /// open. A change that makes or edits an item of the record itself says
203    /// so already, and keeps that item.
204    pub fn named(&mut self, id: impl Into<String>, label: impl Into<String>) {
205        NAMED.with(|named| {
206            named.borrow_mut().replace(tilo_actions::ActionItem {
207                id: id.into(),
208                label: label.into(),
209            });
210        });
211    }
212
213    /// The name software acting for someone (an agent, an app) acted under, as
214    /// the host that admitted it named it; empty for a person.
215    #[must_use]
216    pub fn acting_name(&self) -> String {
217        invoking_name()
218    }
219
220    /// The name and avatar a bot showed for this action instead of its own,
221    /// as the envelope pinned it; `None` for anyone else's action.
222    #[must_use]
223    pub fn appearance(&self) -> Option<tilo_actions::Appearance> {
224        tilo_actions::reading_invoking_context(|context| {
225            context?
226                .invoker
227                .as_ref()
228                .filter(|invoker| invoker.acting.is_bot())?
229                .appearance
230                .clone()
231        })
232    }
233
234    /// Who invoked the action (a person, an agent, an automation), as the
235    /// envelope pinned it.
236    #[must_use]
237    pub fn invoked_by(&self) -> Option<tilo_actions::Acting> {
238        tilo_actions::reading_invoking_context(|context| {
239            Some(context?.invoker.as_ref()?.acting.clone())
240        })
241    }
242
243    /// When the action was authored, in milliseconds since the Unix epoch, as
244    /// read once on the origin.
245    pub fn now_ms(&self) -> i64 {
246        self.now_ms
247    }
248
249    /// Who the action is by: the person or agent that invoked it, the same
250    /// id that member's own views read as `me`. Pinned with the action
251    /// like its time, so every replica reads the same author; the payload
252    /// need not carry it. `None` for an action applied with no invoker
253    /// (an edit written straight into a document outside the host).
254    pub fn author(&self) -> Option<&MemberId> {
255        self.author.as_ref()
256    }
257
258    /// The invocation admitted by the action API, pinned in the action
259    /// envelope so origin and replay observe the same correlation identity.
260    /// This is not caller authority; use [`Self::author`] for that.
261    pub const fn invocation(&self) -> Option<tilo_actions::InvocationId> {
262        self.invocation
263    }
264}
265
266fn uuid_from(digest: &[u8; 32]) -> uuid::Uuid {
267    let mut bytes = [0_u8; 16];
268    bytes.copy_from_slice(digest.get(..16).unwrap_or(&[0; 16]));
269    uuid::Builder::from_random_bytes(bytes).into_uuid()
270}
271
272thread_local! {
273    /// The ids the action applying last on this thread minted, in order.
274    static MINTED: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
275    /// The entries the action applying last on this thread made in a
276    /// collection: the collection map each item's id was made a key of.
277    static ENTRIES: std::cell::RefCell<std::collections::HashMap<String, automerge::ObjId>> =
278        std::cell::RefCell::new(std::collections::HashMap::new());
279    /// The item the action applying last on this thread said its change is
280    /// about, when the record holds no item for it (a file on a device): what
281    /// history names the change by.
282    static NAMED: std::cell::RefCell<Option<tilo_actions::ActionItem>> =
283        const { std::cell::RefCell::new(None) };
284}
285
286/// An action starts applying on this thread: nothing minted or made before
287/// it is its own.
288pub(crate) fn start_minting() {
289    drop(take_minted());
290    ENTRIES.with(|entries| entries.borrow_mut().clear());
291    NAMED.with(|named| named.borrow_mut().take());
292}
293
294/// Note that the action applying on this thread made the entry of the item
295/// `id` in the collection map `map`.
296pub(crate) fn note_entry(map: &automerge::ObjId, id: &str) {
297    ENTRIES.with(|entries| {
298        entries.borrow_mut().insert(id.to_owned(), map.clone());
299    });
300}
301
302/// The collection map the action applied last on this thread made the
303/// entry of the item `id` in, if it made one: where whoever answers what it
304/// made finds the item, without reading the change it wrote.
305#[must_use]
306pub fn minted_entry(id: &str) -> Option<automerge::ObjId> {
307    ENTRIES.with(|entries| entries.borrow().get(id).cloned())
308}
309
310/// The item the action applying last on this thread named as its change's
311/// ([`ActionCx::named`]), if it named one.
312pub(crate) fn named_item() -> Option<tilo_actions::ActionItem> {
313    NAMED.with_borrow(Clone::clone)
314}
315
316/// The ids of the entries the action applying last on this thread made in a
317/// collection, minted or handed to it, in no order.
318pub(crate) fn entries_so_far() -> Vec<String> {
319    ENTRIES.with_borrow(|entries| entries.keys().cloned().collect())
320}
321
322/// The ids the action applying last on this thread minted, as it minted
323/// them: for reading what it made, without taking them from whoever answers
324/// its caller ([`take_minted`]).
325pub(crate) fn minted_so_far() -> Vec<String> {
326    MINTED.with_borrow(Clone::clone)
327}
328
329/// Note `id` among the ids the action applying on this thread minted, for
330/// whichever caller answers what it made.
331pub(crate) fn note_minted(id: &str) {
332    MINTED.with(|minted| minted.borrow_mut().push(id.to_owned()));
333}
334
335/// The ids the record action applied last on this thread minted (items it
336/// added, a group's members' together), taken: what the API answers its
337/// caller with beside the action's own answer.
338#[must_use]
339pub fn take_minted() -> Vec<String> {
340    MINTED.with(|minted| std::mem::take(&mut *minted.borrow_mut()))
341}
342
343/// Note `ids` again, which [`take_minted`] took: what a layer that took them to answer its own
344/// caller puts back, so the caller that invoked the action learns what it made too.
345pub fn restore_minted(ids: impl IntoIterator<Item = String>) {
346    MINTED.with(|minted| minted.borrow_mut().extend(ids));
347}
348
349thread_local! {
350    /// The seed and count of the UUIDs [`fresh_uuid`] mints while a verb
351    /// performs on this thread.
352    static MINT: std::cell::Cell<Option<([u8; 32], u64)>> = const { std::cell::Cell::new(None) };
353}
354
355struct MintScope(Option<([u8; 32], u64)>);
356
357impl MintScope {
358    fn enter(cx: &ActionCx) -> Self {
359        let mut hasher = blake3::Hasher::new();
360        hasher.update(b"tilo-resource/fresh-uuid/v1");
361        hasher.update(&cx.seed);
362        let seed = *hasher.finalize().as_bytes();
363        Self(MINT.with(|mint| mint.replace(Some((seed, 0)))))
364    }
365}
366
367impl Drop for MintScope {
368    fn drop(&mut self) {
369        MINT.with(|mint| mint.set(self.0));
370    }
371}
372
373/// Who invoked the action applying now, as its envelope pinned it: what
374/// [`ActionCx::author`] reads, for domain code a verb calls without its
375/// context.
376#[must_use]
377pub fn invoking_member() -> Option<MemberId> {
378    invoking_author()
379}
380
381/// The name software acting for someone (an agent, an app) acted under in
382/// the action applying now: what [`ActionCx::acting_name`] reads, for domain
383/// code a verb calls without its context; empty for a person.
384#[must_use]
385pub fn invoking_name() -> String {
386    tilo_actions::reading_invoking_context(|context| {
387        context
388            .and_then(|context| context.invoker.as_ref())
389            .filter(|invoker| !invoker.acting.is_person())
390            .and_then(|invoker| invoker.name.clone())
391            .filter(|name| !name.trim().is_empty())
392            .unwrap_or_default()
393    })
394}
395
396/// A new UUID for domain code that makes things (a clip split in two, a
397/// marker): inside a verb it is minted from the action, so every replica
398/// makes the same one; anywhere else (a surface editing its local copy
399/// before it submits the edits) it is random.
400#[must_use]
401pub fn fresh_uuid() -> uuid::Uuid {
402    MINT.with(|mint| match mint.get() {
403        Some((seed, counter)) => {
404            mint.set(Some((seed, counter.saturating_add(1))));
405            let mut hasher = blake3::Hasher::new();
406            hasher.update(&seed);
407            hasher.update(&counter.to_le_bytes());
408            let uuid = uuid_from(hasher.finalize().as_bytes());
409            note_minted(&uuid.to_string());
410            uuid
411        }
412        None => uuid::Uuid::new_v4(),
413    })
414}
415
416fn minted_uuid(seed: &[u8; 32], counter: u64) -> uuid::Uuid {
417    let mut hasher = blake3::Hasher::new();
418    hasher.update(b"uuid");
419    hasher.update(seed);
420    hasher.update(&counter.to_le_bytes());
421    uuid_from(hasher.finalize().as_bytes())
422}
423
424fn minted(seed: &[u8; 32], counter: u64) -> Id {
425    let mut hasher = blake3::Hasher::new();
426    hasher.update(seed);
427    hasher.update(&counter.to_le_bytes());
428    let digest = hasher.finalize();
429    let hex = digest.to_hex();
430    Id::from_raw(hex.as_str().get(..20).unwrap_or_default())
431}
432
433/// The ids the action `envelope` committed minted with [`ActionCx::id`], in
434/// the order it minted them: how the one who invoked it learns which item
435/// its action created (the first id of a "new snippet"). For an action
436/// that is not a group, applied with nothing else pending.
437pub fn minted_ids(envelope: &tilo_actions::ActionEnvelope) -> impl Iterator<Item = Id> {
438    let seed = envelope_seed(envelope);
439    (0_u64..).map(move |counter| minted(&seed, counter))
440}
441
442/// What the action `envelope` committed may have minted at each count, in
443/// order: the id [`ActionCx::id`] mints there and the UUID [`ActionCx::uuid`]
444/// mints there instead, as the action minted one or the other.
445pub fn minted_keys(envelope: &tilo_actions::ActionEnvelope) -> impl Iterator<Item = [String; 2]> {
446    let seed = envelope_seed(envelope);
447    (0_u64..).map(move |counter| {
448        [
449            minted(&seed, counter).as_str().to_owned(),
450            minted_uuid(&seed, counter).to_string(),
451        ]
452    })
453}
454
455/// The seed the action `envelope` committed minted its ids from.
456fn envelope_seed(envelope: &tilo_actions::ActionEnvelope) -> [u8; 32] {
457    let mut hasher = blake3::Hasher::new();
458    hasher.update(b"tilo-resource/action-seed/v1");
459    hasher.update(envelope.actor().to_bytes());
460    let mut heads = envelope.base_heads.clone();
461    heads.compact_sort();
462    for head in &heads {
463        hasher.update(head);
464    }
465    hasher.update(&envelope.action.payload);
466    *hasher.finalize().as_bytes()
467}
468
469/// A deterministic seed for applying `payload` to `doc`: the document's
470/// actor and heads (both pinned by the executor), or, inside a group member,
471/// the group's seed and the member's position.
472pub(crate) fn seed(doc: &Doc, domain: &[u8], payload: &[u8]) -> [u8; 32] {
473    use automerge::transaction::Transactable as _;
474    let mut hasher = blake3::Hasher::new();
475    hasher.update(domain);
476    if let Some((group, position)) = crate::group::current_member() {
477        hasher.update(b"member");
478        hasher.update(&group);
479        hasher.update(&position.to_le_bytes());
480    } else {
481        hasher.update(doc.get_actor().to_bytes());
482        // The committed heads, and how far an open transaction has got past
483        // them: reading the heads must not commit a transaction someone else
484        // (a host stamping typing as one change) owns. With nothing pending
485        // this is exactly the document's heads.
486        let mut heads = doc.base_heads();
487        heads.compact_sort();
488        for head in heads {
489            hasher.update(&head.0);
490        }
491        let pending = doc.pending_ops();
492        if pending > 0 {
493            hasher.update(b"pending");
494            hasher.update(&u64::try_from(pending).unwrap_or(u64::MAX).to_le_bytes());
495        }
496    }
497    hasher.update(payload);
498    *hasher.finalize().as_bytes()
499}
500
501/// What an action method may return: nothing, or a refusal.
502pub trait Outcome {
503    fn into_result(self) -> Result<(), Refusal>;
504}
505
506impl Outcome for () {
507    fn into_result(self) -> Result<(), Refusal> {
508        Ok(())
509    }
510}
511
512impl<E: Into<Refusal>> Outcome for Result<(), E> {
513    fn into_result(self) -> Result<(), Refusal> {
514        self.map_err(Into::into)
515    }
516}
517
518pub use tilo_action_policy::ActionKind;
519
520pub use tilo_actions::ActionKey;
521
522/// One named operation of a record resource, generated by `#[resource]`.
523pub trait Operation: Serialize + DeserializeOwned + Clone + std::fmt::Debug + 'static {
524    type Record: Fields + 'static;
525
526    /// The resource kind the record is published as.
527    const KIND: &'static str;
528
529    /// The field edit this operation is, when it is one: it applies at its
530    /// path instead of through [`Self::perform`].
531    fn edit(&self) -> Option<&crate::Edit<Self::Record>> {
532        None
533    }
534
535    /// What this operation can do. `#[resource]` derives it from each
536    /// verb's signature.
537    fn kind(&self) -> ActionKind {
538        ActionKind::Undoable
539    }
540
541    /// Run the operation's method on the record.
542    fn perform(&self, record: &mut Self::Record, cx: &mut ActionCx) -> Result<(), Refusal>;
543
544    /// The units this operation may write beside the record unit (see
545    /// [`crate::footprint`]). `#[resource]` generates it: an item verb its
546    /// item, `#[action(writes = field)]` the fields named.
547    fn writes(&self) -> crate::footprint::Writes {
548        crate::footprint::Writes::record()
549    }
550
551    /// A copy of `record`, so the next action can start from it rather than
552    /// read the whole record from the document again. `#[resource]`
553    /// generates it for a `Clone` record; without one (the default) every
554    /// action reads the record whole.
555    fn snapshot(record: &Self::Record) -> Option<Self::Record> {
556        let _ = record;
557        None
558    }
559
560    /// The consequence class of this operation. `#[resource]` generates it
561    /// from `#[action(destructive)]`, so the
562    /// same method reached through the generic `apply` action is confirmed
563    /// exactly as its named declaration is.
564    fn risk(&self) -> RiskLevel {
565        RiskLevel::Low
566    }
567
568    /// What the operation is to the people sharing the record: content,
569    /// housekeeping about it, or content from outside that is nobody's undo
570    /// step. `#[resource]` generates it from `#[action(housekeeping)]` and
571    /// `#[action(external)]`.
572    fn change_kind(&self) -> tilo_actions::ChangeKind {
573        tilo_actions::ChangeKind::Content
574    }
575
576    /// Whether the operation records a message someone received.
577    /// `#[resource]` generates it from `#[action(incoming_message)]`.
578    fn incoming_message(&self) -> bool {
579        false
580    }
581
582    /// Whether the operation loses what Undo cannot bring back, beside its
583    /// document change. `#[resource]` generates it from
584    /// `#[action(irreversible)]`.
585    fn irreversible(&self) -> bool {
586        false
587    }
588
589    /// Whether only the app's own code applies this operation
590    /// (`#[action(by_app)]`): it is declared to no caller, and an action API that
591    /// decodes one refuses it. `#[resource]` generates it.
592    fn by_app(&self) -> bool {
593        false
594    }
595
596    /// Whether this operation declares the verb that undoes it
597    /// (`#[action(undo = path)]`).
598    fn compensates(&self) -> bool {
599        false
600    }
601
602    /// Whether every change of the record may queue an outside consequence
603    /// (`#[resource(queue = path)]`): [`Self::queue`] runs after each.
604    const QUEUES: bool = false;
605
606    /// Queue in the record's outboxes what the change from `before` to
607    /// `record` must do outside (`#[resource(queue = path)]`).
608    fn queue(record: &mut Self::Record, before: &Self::Record, cx: &mut ActionCx) {
609        let _ = (record, before, cx);
610    }
611
612    /// Apply an item method (`fn star(contact: &mut Contact)`) to its item
613    /// alone in `doc`: read the item, run the method, write what changed.
614    /// `None` for any other operation, or where the record holds an
615    /// invariant of its own.
616    fn perform_item(&self, doc: &mut Doc, cx: &mut ActionCx) -> Option<Result<(), Refusal>> {
617        let _ = (doc, cx);
618        None
619    }
620
621    /// The field edit `edit` as an operation of the record.
622    fn field_edit(edit: crate::Edit<Self::Record>) -> Option<Self> {
623        let _ = edit;
624        None
625    }
626
627    /// The verb that undoes this one, from the record before and after it
628    /// ran and the ids it minted (`#[action(undo = path)]`). `None` when it
629    /// declares none: undo then reverts the document by inverse patches.
630    fn compensation(
631        &self,
632        before: &Self::Record,
633        after: &Self::Record,
634        minted: &[Id],
635    ) -> Option<Result<Self, String>> {
636        let _ = (before, after, minted);
637        None
638    }
639}
640
641/// What a verb's declared undo (`#[action(undo = path)]`) is computed from:
642/// the record before and after the verb ran, the ids it minted (the outbox
643/// entry it queued) and its parameters. The undo returns the verb that
644/// compensates, which undo applies like any action, so its own outbox
645/// entries are queued and drained the same way, and which reads at that
646/// time how the original entry settled (where the trashed file went).
647pub struct Undoing<'a, R, P> {
648    pub before: &'a R,
649    pub after: &'a R,
650    pub minted: &'a [Id],
651    pub params: &'a P,
652}
653
654impl<R, P> Clone for Undoing<'_, R, P> {
655    fn clone(&self) -> Self {
656        *self
657    }
658}
659
660impl<R, P> Copy for Undoing<'_, R, P> {}
661
662/// A model error as the action's refusal: a function, not a closure per
663/// operation type.
664#[allow(
665    clippy::needless_pass_by_value,
666    reason = "`map_err` hands it the error by value"
667)]
668fn model_refused(error: crate::ModelError) -> ActionError {
669    ActionError::Refused(error.to_string())
670}
671
672/// A document error as the action's refusal.
673#[allow(
674    clippy::needless_pass_by_value,
675    reason = "`map_err` hands it the error by value"
676)]
677fn automerge_refused(error: automerge::AutomergeError) -> ActionError {
678    ActionError::Refused(error.to_string())
679}
680
681pub use tilo_actions::Refusal;
682
683/// A verb's refusal as the action's: one a caller decides on keeps its code.
684fn refusal_refused(refusal: Refusal) -> ActionError {
685    refusal.into()
686}
687
688/// A record operation with the origin's time attached: the replayable action
689/// of a `#[resource]` record.
690#[derive(Serialize, Clone)]
691pub struct Stamped<O> {
692    #[serde(rename = "op")]
693    pub operation: O,
694    #[serde(rename = "at", default)]
695    pub now_ms: i64,
696}
697
698impl<O: std::fmt::Debug> std::fmt::Debug for Stamped<O> {
699    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
700        fmt_stamped(&self.operation, self.now_ms, f)
701    }
702}
703
704fn fmt_stamped(
705    operation: &dyn std::fmt::Debug,
706    now_ms: i64,
707    f: &mut std::fmt::Formatter<'_>,
708) -> std::fmt::Result {
709    f.debug_struct("Stamped")
710        .field("operation", operation)
711        .field("now_ms", &now_ms)
712        .finish()
713}
714
715// Decoded through a JSON value whatever the deserializer: the operation's
716// decoder, one per record type, is compiled for that one deserializer.
717impl<'de, O: DeserializeOwned> Deserialize<'de> for Stamped<O> {
718    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
719        let value = serde_json::Value::deserialize(deserializer)?;
720        match Self::from_json(value) {
721            Ok(stamped) => Ok(stamped),
722            Err(error) => Err(serde::de::Error::custom(error)),
723        }
724    }
725}
726
727impl<O: DeserializeOwned> Stamped<O> {
728    /// The stamped operation in `value`, its JSON form.
729    ///
730    /// # Errors
731    /// Why `value` is not a stamped operation of `O`.
732    pub fn from_json(value: serde_json::Value) -> Result<Self, serde_json::Error> {
733        let (operation, now_ms) = stamped_parts(value)?;
734        Ok(Self {
735            operation: O::deserialize(operation)?,
736            now_ms,
737        })
738    }
739}
740
741/// The operation and time of a stamped operation's JSON form.
742#[inline(never)]
743fn stamped_parts(value: serde_json::Value) -> Result<(serde_json::Value, i64), serde_json::Error> {
744    use serde::de::Error as _;
745    let serde_json::Value::Object(mut fields) = value else {
746        return Err(serde_json::Error::custom(
747            "a stamped operation is an object",
748        ));
749    };
750    let operation = fields
751        .remove("op")
752        .ok_or_else(|| serde_json::Error::missing_field("op"))?;
753    let now_ms = match fields.remove("at") {
754        None | Some(serde_json::Value::Null) => 0,
755        Some(at) => i64::deserialize(at)?,
756    };
757    Ok((operation, now_ms))
758}
759
760/// Whether a field edit only records how an outbox entry settled or forgets
761/// one: bookkeeping of the outbox that queues nothing and is nobody's step.
762fn settles(operation: &impl Operation) -> bool {
763    matches!(
764        operation.edit().map(crate::Edit::op),
765        Some(crate::EditOp::Settle { .. } | crate::EditOp::Forget { .. })
766    )
767}
768
769/// `apply` to a copy of `doc`, dropped here: not generic, so a document's
770/// teardown is compiled once rather than for every resource's actions.
771#[inline(never)]
772fn on_copy(doc: &Doc, apply: &mut dyn FnMut(&mut Doc)) {
773    let mut copy = doc.clone();
774    apply(&mut copy);
775}
776
777impl<O: Operation> Stamped<O> {
778    /// Whether undoing this goes through `apply`, so what it queued outside
779    /// is compensated the same way: a verb that declares its undo, and every
780    /// change of a record that queues (`#[resource(queue = path)]`) a person
781    /// can take back.
782    fn compensated(&self) -> bool {
783        // Bookkeeping, content from outside and housekeeping are nobody's
784        // undo step: nothing compensates them, however much they wrote.
785        if settles(&self.operation)
786            || matches!(
787                self.operation.change_kind(),
788                tilo_actions::ChangeKind::External | tilo_actions::ChangeKind::Housekeeping
789            )
790        {
791            return false;
792        }
793        O::QUEUES || (self.operation.edit().is_none() && self.operation.compensates())
794    }
795
796    /// The record after this applies to `doc`, read apart from it, and the
797    /// ids it minted: under the seed its application will have, so they are
798    /// the ones it queues.
799    fn applied_to_copy(&self, doc: &Doc) -> Option<(O::Record, Vec<Id>)> {
800        let payload = serde_json::to_vec(self).ok()?;
801        if let Some(edit) = self.operation.edit() {
802            let mut cx = ActionCx::for_apply(doc, &payload, self.now_ms);
803            cx.preview = true;
804            let mut after = None;
805            on_copy(doc, &mut |copy| {
806                after = edit
807                    .apply(copy, &mut cx)
808                    .ok()
809                    .and_then(|()| O::Record::read_fields(copy, &ROOT).ok());
810            });
811            return Some((after?, cx.ids));
812        }
813        let mut after = O::Record::read_fields(doc, &ROOT).ok()?;
814        let mut cx = ActionCx::for_apply(doc, &payload, self.now_ms);
815        cx.preview = true;
816        let minting = MintScope::enter(&cx);
817        let performed = self.operation.perform(&mut after, &mut cx);
818        drop(minting);
819        performed.ok()?;
820        Some((after, cx.ids))
821    }
822
823    /// The action that undoes this one at the document `doc` it applies to:
824    /// the verb it declares (`#[action(undo = path)]`), or on a record that
825    /// queues, the field edits that restore what it changed, applied
826    /// through `apply` so the record's `queue` compensates outside.
827    fn compensation(&self, doc: &Doc) -> Option<tilo_actions::EncodedAction> {
828        if !self.compensated() {
829            return None;
830        }
831        let before = O::Record::read_fields(doc, &ROOT).ok()?;
832        let (after, minted) = self.applied_to_copy(doc)?;
833        if self.operation.edit().is_none() && self.operation.compensates() {
834            // An undo whose arguments do not build is a bug in the app the
835            // verb's tests catch; undo then reverts by inverse patches.
836            let operation = self
837                .operation
838                .compensation(&before, &after, &minted)?
839                .ok()?;
840            let undo = Self {
841                operation,
842                now_ms: self.now_ms,
843            };
844            return tilo_actions::EncodedAction::encode(O::KIND, &undo).ok();
845        }
846        let mut restore: Vec<crate::Edit<()>> = Vec::new();
847        crate::Model::diff(&after, &before, &[], &mut restore);
848        let mut members = Vec::with_capacity(restore.len());
849        for edit in restore {
850            members.push(Self {
851                operation: O::field_edit(edit.retyped())?,
852                now_ms: self.now_ms,
853            });
854        }
855        let restore = match members.len() {
856            0 => return None,
857            1 => tilo_actions::EncodedAction::encode(O::KIND, &members.pop()?).ok()?,
858            _ => tilo_actions::EncodedAction::encode(
859                crate::group::group_type_of(O::KIND),
860                &crate::ActionGroup { actions: members },
861            )
862            .ok()?,
863        };
864        if serde_json::to_vec(&restore).ok()?.len() <= tilo_actions::context::COMPENSATION_BUDGET {
865            return Some(restore);
866        }
867        // Too large to record (an import of thousands of items): undo
868        // derives the same restoring edits from the change itself.
869        let reverting = Reverting::<O> {
870            actor: doc.get_actor().to_hex_string(),
871            deps: doc
872                .committed_heads()
873                .iter()
874                .map(ToString::to_string)
875                .collect(),
876            now_ms: self.now_ms,
877            operation: PhantomData,
878        };
879        tilo_actions::EncodedAction::encode(reverting_type(O::KIND), &reverting).ok()
880    }
881}
882
883/// The type id [`Reverting`] actions of the record kind `kind` encode as.
884pub fn reverting_type(kind: &str) -> String {
885    format!("{kind}+revert")
886}
887
888/// The undo of one change of a record that queues, too large to record its
889/// restoring field edits: it names the change (its writer and the heads it
890/// was made on), derives the edits that restore what the change wrote from
891/// the record before and after it, applies them, and runs the record's
892/// `queue` so what the change queued outside is compensated.
893#[derive(Serialize)]
894#[serde(bound = "")]
895pub struct Reverting<O> {
896    actor: String,
897    deps: Vec<String>,
898    #[serde(rename = "at", default)]
899    now_ms: i64,
900    #[serde(skip)]
901    operation: PhantomData<O>,
902}
903
904// Decoded through a JSON value by one function for every record type.
905impl<'de, O> Deserialize<'de> for Reverting<O> {
906    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
907        let value = serde_json::Value::deserialize(deserializer)?;
908        let (actor, deps, now_ms) = match reverted(value) {
909            Ok(target) => target,
910            Err(error) => return Err(serde::de::Error::custom(error)),
911        };
912        Ok(Self {
913            actor,
914            deps,
915            now_ms,
916            operation: PhantomData,
917        })
918    }
919}
920
921/// The writer, heads and time a reverting action's JSON form names.
922#[inline(never)]
923fn reverted(value: serde_json::Value) -> Result<(String, Vec<String>, i64), serde_json::Error> {
924    #[derive(Deserialize)]
925    struct Form {
926        actor: String,
927        deps: Vec<String>,
928        #[serde(rename = "at", default)]
929        now_ms: i64,
930    }
931    let form = Form::deserialize(value)?;
932    Ok((form.actor, form.deps, form.now_ms))
933}
934
935impl<O> std::fmt::Debug for Reverting<O> {
936    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
937        f.debug_struct("Reverting")
938            .field("actor", &self.actor)
939            .field("deps", &self.deps)
940            .finish_non_exhaustive()
941    }
942}
943
944impl<O: Operation> Reverting<O> {
945    /// The change this takes back, by its writer and the heads it was made
946    /// on.
947    fn change(&self, doc: &mut Doc) -> Result<automerge::ChangeHash, ActionError> {
948        reverted_change(&self.actor, &self.deps, doc)
949    }
950}
951
952/// The change by `actor` made on the heads `deps`.
953#[inline(never)]
954fn reverted_change(
955    actor: &str,
956    deps: &[String],
957    doc: &mut Doc,
958) -> Result<automerge::ChangeHash, ActionError> {
959    let refused = |why: &str| ActionError::Refused(why.into());
960    let mut deps = deps
961        .iter()
962        .map(|hash| hash.parse())
963        .collect::<Result<Vec<automerge::ChangeHash>, _>>()
964        .map_err(|_| refused("a reverted change names invalid heads"))?;
965    deps.compact_sort();
966    doc.get_changes(&deps)
967        .into_iter()
968        .find(|change| {
969            change.actor_id().to_hex_string() == actor && {
970                let mut of = change.deps().to_vec();
971                of.compact_sort();
972                of == deps
973            }
974        })
975        .map(|change| change.hash())
976        .ok_or_else(|| refused("the change to take back is not in this document"))
977}
978
979impl<O: Operation> tilo_actions::Action for Reverting<O> {
980    fn apply(&self, doc: &mut Doc) -> Result<(), ActionError> {
981        let change = self.change(doc)?;
982        let payload = serde_json::to_vec(self).map_err(ActionError::Encode)?;
983        revert(
984            &ResourceOf::<O::Record>::OPS,
985            &|record, before, cx| {
986                if let (Some(record), Some(before)) = (
987                    record.downcast_mut::<O::Record>(),
988                    before.downcast_ref::<O::Record>(),
989                ) {
990                    O::queue(record, before, cx);
991                }
992            },
993            (change, &payload, self.now_ms),
994            doc,
995        )
996    }
997
998    fn locus(&self) -> ExecutionLocus {
999        ExecutionLocus::ClientLocal
1000    }
1001}
1002
1003/// [`Reverting::apply`] of the change `change`, encoded as `payload` at
1004/// `now_ms`, to a record of the type `record` whose `queue` is `queue`.
1005fn revert(
1006    record: &ResourceOps,
1007    queue: &dyn Fn(&mut dyn Any, &dyn Any, &mut ActionCx),
1008    (change, payload, now_ms): (automerge::ChangeHash, &[u8], i64),
1009    doc: &mut Doc,
1010) -> Result<(), ActionError> {
1011    let deps: Vec<automerge::ChangeHash> = doc
1012        .get_change_meta_by_hash(&change)
1013        .map(|meta| meta.deps)
1014        .unwrap_or_default();
1015    let before = {
1016        let at = doc.committed_fork_at(&deps).map_err(automerge_refused)?;
1017        (record.read)(&at).map_err(model_refused)?
1018    };
1019    let after = {
1020        let at = doc
1021            .committed_fork_at(&[change])
1022            .map_err(automerge_refused)?;
1023        (record.read)(&at).map_err(model_refused)?
1024    };
1025    let restore = (record.diff)(after.as_ref(), before.as_ref());
1026    let mut cx = ActionCx::for_apply(doc, payload, now_ms);
1027    let current = (record.read)(doc).map_err(model_refused)?;
1028    for edit in &restore {
1029        (record.edit)(edit, doc, &mut cx).map_err(model_refused)?;
1030    }
1031    let mut written = (record.read)(doc).map_err(model_refused)?;
1032    let minting = MintScope::enter(&cx);
1033    queue(written.as_mut(), current.as_ref(), &mut cx);
1034    drop(minting);
1035    (record.write)(written.as_ref(), doc).map_err(model_refused)
1036}
1037
1038/// Write the first record over the second, kept, with the changes `dirty`
1039/// others made since.
1040type WriteChanged =
1041    fn(&dyn Any, &dyn Any, &mut Doc, &crate::Delta) -> Result<(), crate::ModelError>;
1042
1043/// What applying an operation needs of its record's type, with the type
1044/// erased: a few functions per record type, so the apply itself is
1045/// compiled once rather than for every record.
1046pub(crate) struct ResourceOps {
1047    shape: crate::Shape,
1048    name: fn() -> &'static str,
1049    kind: fn() -> std::any::TypeId,
1050    read: fn(&Doc) -> Result<Box<dyn Any>, crate::ModelError>,
1051    write: fn(&dyn Any, &mut Doc) -> Result<(), crate::ModelError>,
1052    write_changed: WriteChanged,
1053    check: fn(&dyn Any) -> Result<(), Refusal>,
1054    refresh: fn(&mut dyn Any, &Doc, &crate::Delta) -> bool,
1055    /// The edits that turn the first record into the second.
1056    diff: fn(&dyn Any, &dyn Any) -> Vec<crate::Edit<()>>,
1057    edit: fn(&crate::Edit<()>, &mut Doc, &mut ActionCx) -> Result<(), crate::ModelError>,
1058}
1059
1060/// The record of `R` a [`ResourceOps`] function was handed.
1061fn resource_of<R: 'static>(record: &dyn Any) -> Result<&R, crate::ModelError> {
1062    match record.downcast_ref::<R>() {
1063        Some(record) => Ok(record),
1064        None => Err(crate::ModelError::invalid("a record of another type")),
1065    }
1066}
1067
1068fn read_resource<R: Fields + 'static>(doc: &Doc) -> Result<Box<dyn Any>, crate::ModelError> {
1069    match R::read_fields(doc, &ROOT) {
1070        Ok(record) => Ok(Box::new(record)),
1071        Err(error) => Err(error),
1072    }
1073}
1074
1075fn write_resource<R: Fields + 'static>(
1076    record: &dyn Any,
1077    doc: &mut Doc,
1078) -> Result<(), crate::ModelError> {
1079    resource_of::<R>(record)?.write_fields(doc, &ROOT)
1080}
1081
1082fn write_changed_resource<R: Fields + 'static>(
1083    record: &dyn Any,
1084    kept: &dyn Any,
1085    doc: &mut Doc,
1086    dirty: &crate::Delta,
1087) -> Result<(), crate::ModelError> {
1088    resource_of::<R>(record)?.write_changed_fields(resource_of::<R>(kept)?, doc, &ROOT, dirty)
1089}
1090
1091fn check_resource<R: Fields + 'static>(record: &dyn Any) -> Result<(), Refusal> {
1092    match record.downcast_ref::<R>() {
1093        Some(record) => crate::Model::check(record),
1094        None => Err(Refusal::new("a record of another type")),
1095    }
1096}
1097
1098fn refresh_resource<R: Fields + 'static>(
1099    record: &mut dyn Any,
1100    doc: &Doc,
1101    delta: &crate::Delta,
1102) -> bool {
1103    match record.downcast_mut::<R>() {
1104        Some(record) => record.refresh_fields(doc, &ROOT, delta).is_ok(),
1105        None => false,
1106    }
1107}
1108
1109fn diff_resources<R: Fields + 'static>(from: &dyn Any, to: &dyn Any) -> Vec<crate::Edit<()>> {
1110    let mut edits = Vec::new();
1111    if let (Some(from), Some(to)) = (from.downcast_ref::<R>(), to.downcast_ref::<R>()) {
1112        crate::Model::diff(from, to, &[], &mut edits);
1113    }
1114    edits
1115}
1116
1117fn edit_resource<R: Fields + 'static>(
1118    edit: &crate::Edit<()>,
1119    doc: &mut Doc,
1120    cx: &mut ActionCx,
1121) -> Result<(), crate::ModelError> {
1122    R::edit_fields(doc, &ROOT, edit.path(), edit.op(), cx)
1123}
1124
1125pub(crate) struct ResourceOf<R>(PhantomData<R>);
1126
1127impl<R: Fields + 'static> ResourceOf<R> {
1128    pub(crate) const OPS: ResourceOps = ResourceOps {
1129        shape: <R as crate::Model>::SHAPE,
1130        name: std::any::type_name::<R>,
1131        kind: std::any::TypeId::of::<R>,
1132        read: read_resource::<R>,
1133        write: write_resource::<R>,
1134        write_changed: write_changed_resource::<R>,
1135        check: check_resource::<R>,
1136        refresh: refresh_resource::<R>,
1137        diff: diff_resources::<R>,
1138        edit: edit_resource::<R>,
1139    };
1140}
1141
1142/// Apply `operation`, a field edit, at its path.
1143fn apply_edit(
1144    operation: &dyn Performs,
1145    doc: &mut Doc,
1146    cx: &mut ActionCx,
1147) -> Result<(), ActionError> {
1148    match operation.apply_edit(doc, cx) {
1149        Some(applied) => applied.map_err(model_refused),
1150        None => Ok(()),
1151    }
1152}
1153
1154/// One operation of a record, as [`apply_operation`] performs it.
1155trait Performs {
1156    fn is_edit(&self) -> bool;
1157    /// Apply it as the field edit it is; `None` when it is a verb.
1158    fn apply_edit(&self, doc: &mut Doc, cx: &mut ActionCx)
1159    -> Option<Result<(), crate::ModelError>>;
1160    fn queues(&self) -> bool;
1161    fn perform(&self, record: &mut dyn Any, cx: &mut ActionCx) -> Result<(), Refusal>;
1162    fn queue(&self, record: &mut dyn Any, before: &dyn Any, cx: &mut ActionCx);
1163    fn perform_item(&self, doc: &mut Doc, cx: &mut ActionCx) -> Option<Result<(), Refusal>>;
1164    fn writes(&self) -> crate::footprint::Writes;
1165    fn snapshot(&self, record: &dyn Any) -> Option<Box<dyn Any>>;
1166}
1167
1168impl<O: Operation> Performs for O {
1169    fn is_edit(&self) -> bool {
1170        self.edit().is_some()
1171    }
1172
1173    fn apply_edit(
1174        &self,
1175        doc: &mut Doc,
1176        cx: &mut ActionCx,
1177    ) -> Option<Result<(), crate::ModelError>> {
1178        let edit = self.edit()?;
1179        Some(O::Record::edit_fields(
1180            doc,
1181            &ROOT,
1182            edit.path(),
1183            edit.op(),
1184            cx,
1185        ))
1186    }
1187
1188    fn queues(&self) -> bool {
1189        O::QUEUES && !settles(self)
1190    }
1191
1192    fn perform(&self, record: &mut dyn Any, cx: &mut ActionCx) -> Result<(), Refusal> {
1193        match record.downcast_mut::<O::Record>() {
1194            Some(record) => Operation::perform(self, record, cx),
1195            None => Err(Refusal::new("a record of another type")),
1196        }
1197    }
1198
1199    fn queue(&self, record: &mut dyn Any, before: &dyn Any, cx: &mut ActionCx) {
1200        if let (Some(record), Some(before)) = (
1201            record.downcast_mut::<O::Record>(),
1202            before.downcast_ref::<O::Record>(),
1203        ) {
1204            O::queue(record, before, cx);
1205        }
1206    }
1207
1208    fn perform_item(&self, doc: &mut Doc, cx: &mut ActionCx) -> Option<Result<(), Refusal>> {
1209        Operation::perform_item(self, doc, cx)
1210    }
1211
1212    fn writes(&self) -> crate::footprint::Writes {
1213        Operation::writes(self)
1214    }
1215
1216    fn snapshot(&self, record: &dyn Any) -> Option<Box<dyn Any>> {
1217        let record = record.downcast_ref::<O::Record>()?;
1218        O::snapshot(record).map(|record| Box::new(record) as Box<dyn Any>)
1219    }
1220}
1221
1222/// Apply the field edit `operation` to the document; a record that queues
1223/// on its changes has its `queue` see the change the edit made.
1224fn apply_edit_queued(
1225    record: &'static ResourceOps,
1226    operation: &dyn Performs,
1227    doc: &mut Doc,
1228    cx: &mut ActionCx,
1229) -> Result<(), ActionError> {
1230    if !operation.queues() {
1231        return apply_edit(operation, doc, cx);
1232    }
1233    let before = (record.read)(doc).map_err(model_refused)?;
1234    apply_edit(operation, doc, cx)?;
1235    let mut after = (record.read)(doc).map_err(model_refused)?;
1236    let minting = MintScope::enter(cx);
1237    operation.queue(after.as_mut(), before.as_ref(), cx);
1238    drop(minting);
1239    (record.write)(after.as_ref(), doc).map_err(model_refused)
1240}
1241
1242/// Everything `doc` holds, read whole for one action: what an item method
1243/// never costs, as an observation of it says.
1244fn read_whole(ops: &'static ResourceOps, doc: &Doc) -> Result<Box<dyn Any>, ActionError> {
1245    let _whole = crate::profiling::Phase::start("resource.apply_whole_read");
1246    (ops.read)(doc).map_err(model_refused)
1247}
1248
1249/// [`Stamped::apply`] of `operation`, of a record of the type `record`,
1250/// encoded as `payload` at `now_ms`.
1251///
1252/// The record the previous action of this type left behind, brought up to
1253/// date with only the changes since, stands in for reading the whole
1254/// record, and the write compares with it instead of reading every field
1255/// back. Either way the action writes exactly the operations a whole read
1256/// and write would, so a replica replaying it, warm or cold, makes the
1257/// identical change.
1258fn apply_operation(
1259    record: &'static ResourceOps,
1260    operation: &dyn Performs,
1261    (payload, now_ms): (&[u8], i64),
1262    doc: &mut Doc,
1263) -> Result<(), ActionError> {
1264    // A group's members mint into one list; anything else starts afresh.
1265    if crate::group::current_member().is_none() {
1266        start_minting();
1267    }
1268    let mut cx = ActionCx::for_apply(doc, payload, now_ms);
1269    let shape = record.shape;
1270    let units = crate::footprint::has_units(shape);
1271    // The unit index, kept once something applied: a refused action
1272    // writes nothing.
1273    let index = |doc: &mut Doc| {
1274        if units {
1275            crate::footprint::index(doc, shape).map_err(automerge_refused)?;
1276        }
1277        Ok::<(), ActionError>(())
1278    };
1279    let queues = operation.queues();
1280    // A member of a group whose record the group holds in memory runs on it there; a member
1281    // that writes the document itself (a field edit, a change an outbox queues on) first
1282    // writes what the group holds, so it starts from the document as the group left it.
1283    let grouping = crate::group::grouping();
1284    if grouping {
1285        if !operation.is_edit() && !queues && held::holds(record) {
1286            return held::perform(record, operation, &mut cx);
1287        }
1288        held::flush(record, doc)?;
1289    }
1290    if operation.is_edit() {
1291        apply_edit_queued(record, operation, doc, &mut cx)?;
1292        return index(doc);
1293    }
1294    // An item method reads and writes its item alone; what it wrote is
1295    // its item's, within its footprint.
1296    if !queues {
1297        let minting = MintScope::enter(&cx);
1298        let performed = operation.perform_item(doc, &mut cx);
1299        drop(minting);
1300        if let Some(performed) = performed {
1301            performed.map_err(refusal_refused)?;
1302            return index(doc);
1303        }
1304    }
1305    // The record the previous action of this type left behind, brought
1306    // up to date with only the changes since, stands in for a whole read.
1307    let committed = automerge::transaction::Transactable::pending_ops(doc) == 0;
1308    let started = automerge::transaction::Transactable::base_heads(doc);
1309    let (mut current, dirty) =
1310        match crate::apply_cache::take_any((record.kind)(), doc, &record.refresh) {
1311            Some((warm, dirty)) => (warm, Some(dirty)),
1312            None => (read_whole(record, doc)?, None),
1313        };
1314    // A group's first member of a record that keeps no outbox starts the record the group
1315    // holds: every member after it runs on it in memory, and the group writes it once.
1316    if grouping && !queues {
1317        // The group checks the record it holds once, as it writes it.
1318        let base = operation.snapshot(current.as_ref());
1319        held::start(record, current, base, dirty);
1320        return held::perform(record, operation, &mut cx);
1321    }
1322    // What it was: for the record's `queue`, to hold what the verb
1323    // produced against its footprint, and for the next action to start from.
1324    let kept = if committed || queues || units || dirty.is_some() {
1325        operation.snapshot(current.as_ref())
1326    } else {
1327        None
1328    };
1329    let read_before;
1330    let before: Option<&dyn Any> = match (&kept, queues || units) {
1331        (_, false) => None,
1332        (Some(kept), true) => Some(kept.as_ref()),
1333        (None, true) => {
1334            read_before = (record.read)(doc).map_err(model_refused)?;
1335            Some(read_before.as_ref())
1336        }
1337    };
1338    let minting = MintScope::enter(&cx);
1339    let performed = operation.perform(current.as_mut(), &mut cx);
1340    if let (Ok(()), Some(before), true) = (&performed, before, queues) {
1341        operation.queue(current.as_mut(), before, &mut cx);
1342    }
1343    drop(minting);
1344    performed.map_err(refusal_refused)?;
1345    if grouping {
1346        // The group checks the record once, at its end.
1347        crate::group::check_or_defer(format!("{}@root", (record.name)()), doc, move |doc| {
1348            match (record.read)(doc) {
1349                Ok(read) => (record.check)(read.as_ref()),
1350                Err(error) => Err(Refusal::new(error.to_string())),
1351            }
1352        })
1353        .map_err(refusal_refused)?;
1354    } else {
1355        (record.check)(current.as_ref()).map_err(refusal_refused)?;
1356    }
1357    if let (Some(before), true) = (before, units) {
1358        let edits = (record.diff)(before, current.as_ref());
1359        crate::footprint::check_edits(shape, &edits, &operation.writes())
1360            .map_err(refusal_refused)?;
1361    }
1362    crate::apply_cache::begin_storing();
1363    match (&kept, &dirty) {
1364        (Some(kept), Some(dirty)) => {
1365            (record.write_changed)(current.as_ref(), kept.as_ref(), doc, dirty)
1366        }
1367        _ => (record.write)(current.as_ref(), doc),
1368    }
1369    .map_err(model_refused)?;
1370    index(doc)?;
1371    crate::apply_cache::seal_stored(doc);
1372    // Kept once all it wrote is written: the next action finds this one's
1373    // change by its size, or, inside a transaction still open, starts from
1374    // the record exactly as it was written.
1375    if committed {
1376        if let Some(kept) = kept {
1377            crate::apply_cache::keep_any((record.kind)(), kept, doc, &started);
1378        }
1379    } else {
1380        crate::apply_cache::keep_open((record.kind)(), current, doc);
1381    }
1382    Ok(())
1383}
1384
1385/// The records a group holds in memory while its members run, one per record type: read
1386/// once by the first member, changed by each member's verb in turn (each with its own
1387/// arguments, ids and attribution), and written once when the group ends or a member needs
1388/// the document itself. A thousand members of one record cost one read and one write of it,
1389/// not a thousand.
1390mod held {
1391    use std::any::{Any, TypeId};
1392    use std::cell::RefCell;
1393
1394    use tilo_actions::ActionError;
1395
1396    use super::{ActionCx, MintScope, Performs, ResourceOps, model_refused, refusal_refused};
1397    use crate::footprint::Footprints;
1398    use crate::model::Doc;
1399
1400    struct Held {
1401        record: &'static ResourceOps,
1402        /// The record as the members left it.
1403        current: Box<dyn Any>,
1404        /// The record as the document held it when the group took it; none when the record
1405        /// keeps no copy, and the document is read again for it.
1406        base: Option<Box<dyn Any>>,
1407        /// What others wrote since the cached record was last written: written again whole.
1408        /// `None` when the record was read whole, and is written whole.
1409        dirty: Option<crate::Delta>,
1410        /// Every unit the members declare.
1411        footprints: Footprints,
1412    }
1413
1414    thread_local! {
1415        /// `None` outside a group.
1416        static HELD: RefCell<Option<Vec<Held>>> = const { RefCell::new(None) };
1417    }
1418
1419    /// Begin holding records, for the outermost group on this thread.
1420    pub(crate) fn begin() {
1421        HELD.with(|held| *held.borrow_mut() = Some(Vec::new()));
1422    }
1423
1424    /// Stop holding records without writing them: the group refused.
1425    pub(crate) fn end() {
1426        HELD.with(|held| held.borrow_mut().take());
1427    }
1428
1429    fn kind(record: &ResourceOps) -> TypeId {
1430        (record.kind)()
1431    }
1432
1433    /// Whether the group holds the record `record`.
1434    pub(super) fn holds(record: &ResourceOps) -> bool {
1435        HELD.with(|held| {
1436            held.borrow()
1437                .as_ref()
1438                .is_some_and(|held| held.iter().any(|entry| kind(entry.record) == kind(record)))
1439        })
1440    }
1441
1442    /// Hold `current`, read from the document as `base` (with `dirty` written by others).
1443    pub(super) fn start(
1444        record: &'static ResourceOps,
1445        current: Box<dyn Any>,
1446        base: Option<Box<dyn Any>>,
1447        dirty: Option<crate::Delta>,
1448    ) {
1449        HELD.with(|held| {
1450            if let Some(held) = held.borrow_mut().as_mut() {
1451                held.push(Held {
1452                    record,
1453                    current,
1454                    base,
1455                    dirty,
1456                    footprints: Footprints::default(),
1457                });
1458            }
1459        });
1460    }
1461
1462    /// Run `operation`'s verb on the record the group holds.
1463    pub(super) fn perform(
1464        record: &'static ResourceOps,
1465        operation: &dyn Performs,
1466        cx: &mut ActionCx,
1467    ) -> Result<(), ActionError> {
1468        HELD.with(|held| {
1469            let mut held = held.borrow_mut();
1470            let entry = held
1471                .as_mut()
1472                .and_then(|held| {
1473                    held.iter_mut()
1474                        .find(|entry| kind(entry.record) == kind(record))
1475                })
1476                .ok_or_else(|| ActionError::Refused("the group does not hold the record".into()))?;
1477            let minting = MintScope::enter(cx);
1478            let performed = operation.perform(entry.current.as_mut(), cx);
1479            drop(minting);
1480            performed.map_err(refusal_refused)?;
1481            entry.footprints.add(&operation.writes());
1482            Ok(())
1483        })
1484    }
1485
1486    /// Write the record of `record`'s type the group holds, if it holds one, and stop holding
1487    /// it: what its members did, checked against every unit they declare.
1488    pub(super) fn flush(record: &ResourceOps, doc: &mut Doc) -> Result<(), ActionError> {
1489        let taken = HELD.with(|held| {
1490            let mut held = held.borrow_mut();
1491            let held = held.as_mut()?;
1492            let at = held
1493                .iter()
1494                .position(|entry| kind(entry.record) == kind(record))?;
1495            Some(held.remove(at))
1496        });
1497        match taken {
1498            Some(entry) => write(entry, doc, Checked::AtTheEnd),
1499            None => Ok(()),
1500        }
1501    }
1502
1503    /// Write every record the group holds: the group's end.
1504    pub(crate) fn flush_all(doc: &mut Doc) -> Result<(), ActionError> {
1505        let taken = HELD.with(|held| held.borrow_mut().as_mut().map(std::mem::take));
1506        for entry in taken.unwrap_or_default() {
1507            write(entry, doc, Checked::Now)?;
1508        }
1509        Ok(())
1510    }
1511
1512    /// When a held record written is checked.
1513    #[derive(Clone, Copy)]
1514    enum Checked {
1515        /// As it is held: it is written at the group's end.
1516        Now,
1517        /// As the document holds it at the group's end: a later member may still mend it.
1518        AtTheEnd,
1519    }
1520
1521    fn write(entry: Held, doc: &mut Doc, checked: Checked) -> Result<(), ActionError> {
1522        let Held {
1523            record,
1524            current,
1525            base,
1526            dirty,
1527            footprints,
1528        } = entry;
1529        let units = crate::footprint::has_units(record.shape);
1530        let read_base;
1531        let before: Option<&dyn Any> = match (&base, units) {
1532            (_, false) => None,
1533            (Some(base), true) => Some(base.as_ref()),
1534            (None, true) => {
1535                read_base = (record.read)(doc).map_err(model_refused)?;
1536                Some(read_base.as_ref())
1537            }
1538        };
1539        // What the members made is a record that holds, whatever it passed through on the way.
1540        match checked {
1541            Checked::Now => (record.check)(current.as_ref()).map_err(refusal_refused)?,
1542            Checked::AtTheEnd => {
1543                crate::group::check_or_defer(
1544                    format!("{}@root", (record.name)()),
1545                    doc,
1546                    move |doc| match (record.read)(doc) {
1547                        Ok(read) => (record.check)(read.as_ref()),
1548                        Err(error) => Err(crate::Refusal::new(error.to_string())),
1549                    },
1550                )
1551                .map_err(refusal_refused)?;
1552            }
1553        }
1554        if let Some(before) = before {
1555            let edits = (record.diff)(before, current.as_ref());
1556            crate::footprint::check_edits_of(record.shape, &edits, &footprints)
1557                .map_err(refusal_refused)?;
1558        }
1559        crate::apply_cache::begin_storing();
1560        match (&base, &dirty) {
1561            (Some(base), Some(dirty)) => {
1562                (record.write_changed)(current.as_ref(), base.as_ref(), doc, dirty)
1563            }
1564            _ => (record.write)(current.as_ref(), doc),
1565        }
1566        .map_err(model_refused)?;
1567        if units {
1568            crate::footprint::index(doc, record.shape).map_err(super::automerge_refused)?;
1569        }
1570        crate::apply_cache::seal_stored(doc);
1571        // The next action of its type in the same transaction starts from it as written.
1572        crate::apply_cache::keep_open((record.kind)(), current, doc);
1573        Ok(())
1574    }
1575}
1576
1577pub(crate) use held::{begin as hold_records, end as drop_held, flush_all as write_held};
1578
1579impl<O: Operation> tilo_actions::Action for Stamped<O> {
1580    /// Read the record, run the method, write back what changed
1581    /// (`apply_operation`).
1582    fn apply(&self, doc: &mut Doc) -> Result<(), ActionError> {
1583        let payload = serde_json::to_vec(self).map_err(ActionError::Encode)?;
1584        apply_operation(
1585            &ResourceOf::<O::Record>::OPS,
1586            &self.operation,
1587            (&payload, self.now_ms),
1588            doc,
1589        )
1590    }
1591
1592    fn locus(&self) -> ExecutionLocus {
1593        ExecutionLocus::ClientLocal
1594    }
1595
1596    fn risk(&self) -> RiskLevel {
1597        self.operation.risk()
1598    }
1599
1600    /// An outbox settlement is content from outside and forgetting a
1601    /// settled entry is housekeeping: neither is anyone's undo step, so an
1602    /// undo never sends a mail twice.
1603    fn change_kind(&self) -> tilo_actions::ChangeKind {
1604        match self.operation.edit().map(crate::Edit::op) {
1605            Some(crate::EditOp::Settle { .. }) => tilo_actions::ChangeKind::External,
1606            Some(crate::EditOp::Forget { .. }) => tilo_actions::ChangeKind::Housekeeping,
1607            _ => self.operation.change_kind(),
1608        }
1609    }
1610
1611    fn action_kind(&self) -> ActionKind {
1612        self.operation.kind()
1613    }
1614
1615    fn incoming_message(&self) -> bool {
1616        self.operation.incoming_message()
1617    }
1618
1619    fn irreversible(&self) -> bool {
1620        self.operation.irreversible()
1621    }
1622
1623    /// A verb that declares its undo is undone by applying that verb, and a
1624    /// change of a record that queues by applying the edits that restore it:
1625    /// either queues the compensating outside consequence.
1626    fn inverse_encoded(&self, doc: &Doc) -> Option<tilo_actions::EncodedAction> {
1627        self.compensation(doc)
1628    }
1629
1630    fn compensates(&self) -> bool {
1631        self.compensated()
1632    }
1633
1634    /// A field edit with the value before and after, or a verb with its
1635    /// plain arguments, and the item either addressed.
1636    fn describe(&self, doc: &Doc) -> Option<tilo_actions::Described> {
1637        let shape = <O::Record as crate::Model>::SHAPE;
1638        if let Some(edit) = self.operation.edit() {
1639            return crate::describe::edit(doc, shape, edit);
1640        }
1641        let value = crate::__private::json_via_bytes(&self.operation).ok()?;
1642        crate::describe::verb(doc, shape, O::KIND, &value)
1643    }
1644
1645    /// The item this verb made, read once it wrote: the record's item it
1646    /// added (a note, an issue, a message), or the item the app named as it
1647    /// ran (a file a device will write). The document before the verb applied
1648    /// held neither, so [`Self::describe`] could not name it.
1649    fn made(&self, doc: &Doc) -> Option<tilo_actions::ActionItem> {
1650        crate::describe::made::<O::Record>(doc)
1651    }
1652}
1653
1654/// A typed reference to one declared action of `R` taking input `A` — the
1655/// thing views bind controls to and tests apply. Generated by `#[resource]`
1656/// and `#[derive(Effect)]` as an associated constant per action
1657/// (`Note::EDIT`).
1658///
1659/// The key [`Self::key`] reads from it is how the framework binds a control:
1660/// it names the app, the resource kind and the action, so a control cannot
1661/// bind to an action another resource publishes, and an action a resource
1662/// stops publishing fails where it is bound rather than greying a button.
1663///
1664/// `A` is the action's argument, or a tuple of its arguments in order.
1665pub struct ActionRef<R, A> {
1666    pub id: &'static str,
1667    pub params: &'static [&'static str],
1668    /// The kind of resource that publishes the action, and so the app that
1669    /// publishes it: what [`Self::key`] names the action by.
1670    kind: ResourceKind,
1671    marker: PhantomData<fn(A) -> R>,
1672}
1673
1674impl<R, A> Clone for ActionRef<R, A> {
1675    fn clone(&self) -> Self {
1676        *self
1677    }
1678}
1679impl<R, A> Copy for ActionRef<R, A> {}
1680
1681impl<R, A> std::fmt::Debug for ActionRef<R, A> {
1682    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1683        f.debug_struct("ActionRef")
1684            .field("id", &self.id)
1685            .field("params", &self.params)
1686            .field("kind", &self.kind())
1687            .finish_non_exhaustive()
1688    }
1689}
1690
1691impl<R, A> ActionRef<R, A> {
1692    /// The action's public id.
1693    #[must_use]
1694    pub const fn id(&self) -> &'static str {
1695        self.id
1696    }
1697
1698    /// The names of the action's parameters, in order.
1699    #[must_use]
1700    pub const fn params(&self) -> &'static [&'static str] {
1701        self.params
1702    }
1703
1704    /// The resource kind that publishes the action.
1705    #[must_use]
1706    pub const fn kind(&self) -> &ResourceKind {
1707        &self.kind
1708    }
1709
1710    /// The stored form of this reference — the app, resource kind and public
1711    /// id a control is bound to an action by, and the shape a Shortcut step,
1712    /// an agent's plan or a palette entry keeps.
1713    #[must_use]
1714    pub fn key(&self) -> ActionKey {
1715        ActionKey::new(self.kind.declaring_app(), self.kind.kind(), self.id)
1716    }
1717}
1718
1719impl<E: crate::Effect, A> ActionRef<E, A> {
1720    /// The action this effect's declaration publishes, as the resource that
1721    /// offers the vocabulary publishes it: what a control binds to without a
1722    /// row carrying it.
1723    #[must_use]
1724    pub fn spec(&self) -> Option<tilo_actions::ActionSpec> {
1725        E::spec(self.id)
1726    }
1727
1728    /// A control's binding to this effect on `resource`, from its
1729    /// declaration: the resource's own address and the declared action, with
1730    /// no carrier row. A nullary effect binds as a button; one taking
1731    /// arguments is offered with them asked.
1732    ///
1733    /// # Errors
1734    /// The declaration publishes no such action, or it requires an argument
1735    /// this binding gives none.
1736    pub fn binding(
1737        &self,
1738        resource: impl Into<String>,
1739    ) -> Result<tilo_actions::ActionBinding<()>, tilo_actions::ActionBindingError> {
1740        let resource = resource.into();
1741        let spec = E::spec(self.id).ok_or_else(|| {
1742            tilo_actions::ActionBindingError::ActionNotExported {
1743                resource: resource.clone(),
1744                action: self.id.to_owned(),
1745            }
1746        })?;
1747        tilo_actions::ActionBinding::declared(resource, spec)
1748    }
1749}
1750
1751impl<R, A: Serialize> ActionRef<R, A> {
1752    /// The reference `#[resource]` and `#[derive(Effect)]` generate: action
1753    /// `id` taking the parameters `params`, of the kind `kind` declares. The
1754    /// kind is built by a `const fn` of a type's name alone, so it is the same
1755    /// value at every use and costs no initialisation.
1756    #[must_use]
1757    pub const fn new(
1758        id: &'static str,
1759        params: &'static [&'static str],
1760        kind: ResourceKind,
1761    ) -> Self {
1762        Self {
1763            id,
1764            params,
1765            kind,
1766            marker: PhantomData,
1767        }
1768    }
1769
1770    /// This action as the published resource `resource` offers it (the
1771    /// record, one of its items, or a resource a view or search hit derives
1772    /// from it, by its published id): what a search hit invokes or a test
1773    /// addresses through the host's API. The action's id comes from the
1774    /// typed reference, so it cannot name one the app does not declare.
1775    #[must_use]
1776    pub fn on(&self, resource: impl Into<String>) -> tilo_actions::ActionAddress {
1777        tilo_actions::ActionAddress::new(resource, self.id)
1778    }
1779
1780    /// The JSON arguments this input binds to: a verb's parameter struct
1781    /// as its fields, or positional inputs under the declared names.
1782    pub fn arguments(
1783        &self,
1784        input: &A,
1785    ) -> Result<serde_json::Map<String, serde_json::Value>, String> {
1786        // Through bytes: the serializer writing recorded actions serves
1787        // here too, rather than one more per parameter type.
1788        bind_serialized(
1789            self.id,
1790            self.params,
1791            crate::__private::json_via_bytes(input),
1792        )
1793    }
1794
1795    /// Fully apply the input: an invocation with nothing left to supply.
1796    /// A verb's parameter struct converts from its parameters in order: one
1797    /// value, or a tuple of several. An input that does not bind makes an
1798    /// invocation that refuses with why ([`Invoke::refusal`]), never one
1799    /// with empty arguments.
1800    pub fn with(&self, input: impl Into<A>) -> Invoke<R> {
1801        Invoke::bound(self.id, self.arguments(&input.into()))
1802    }
1803
1804    /// [`Self::with`], reporting an input that does not bind at once.
1805    pub fn try_with(&self, input: impl Into<A>) -> Result<Invoke<R>, String> {
1806        let invoke = self.with(input);
1807        match invoke.refusal {
1808            Some(refusal) => Err(refusal),
1809            None => Ok(invoke),
1810        }
1811    }
1812}
1813
1814/// [`bind_arguments`] of an action input as it serialized, or why it did
1815/// not: compiled once rather than for every input type.
1816#[inline(never)]
1817fn bind_serialized(
1818    id: &'static str,
1819    params: &'static [&'static str],
1820    value: Result<serde_json::Value, serde_json::Error>,
1821) -> Result<serde_json::Map<String, serde_json::Value>, String> {
1822    match value {
1823        Ok(value) => bind_arguments(id, params, value),
1824        Err(error) => Err(format!("`{id}`: {error}")),
1825    }
1826}
1827
1828/// The arguments `value` (an input in JSON form) binds to under the
1829/// declared parameter names: one compiled copy for every action reference.
1830fn bind_arguments(
1831    id: &str,
1832    params: &[&str],
1833    value: serde_json::Value,
1834) -> Result<serde_json::Map<String, serde_json::Value>, String> {
1835    // An absent option is left out, as a parameter not given.
1836    let given = |fields: Vec<(String, serde_json::Value)>| {
1837        fields
1838            .into_iter()
1839            .filter(|(_, value)| !value.is_null())
1840            .collect()
1841    };
1842    match (params, value) {
1843        ([], serde_json::Value::Object(fields)) => Ok(given(fields.into_iter().collect())),
1844        ([], serde_json::Value::Null) => Ok(serde_json::Map::new()),
1845        ([], other) => Err(format!("`{id}` takes named arguments, not `{other}`")),
1846        ([single], value) => Ok(given(vec![((*single).to_owned(), value)])),
1847        (names, serde_json::Value::Array(values)) if values.len() == names.len() => Ok(given(
1848            names
1849                .iter()
1850                .map(|name| (*name).to_owned())
1851                .zip(values)
1852                .collect(),
1853        )),
1854        (names, other) => Err(format!(
1855            "`{id}` takes {} arguments ({}), not `{other}`",
1856            names.len(),
1857            names.join(", ")
1858        )),
1859    }
1860}
1861
1862impl<R, A: Serialize> ActionRef<R, A> {
1863    /// Adapt a control's input to this action's arguments — typically to bind
1864    /// the item a row stands for: `Todo::SET_DONE.map(move |done| (id.clone(), done))`.
1865    pub fn map<I, T, F>(self, map: F) -> Mapped<R, A, F>
1866    where
1867        F: Fn(I) -> T,
1868        T: Into<A>,
1869    {
1870        Mapped { action: self, map }
1871    }
1872
1873    /// Adapt a control's input to this action's arguments where the input
1874    /// may not make any: `parse` reads the input (a draft's text) and makes
1875    /// the arguments only when it parses, through the types that refuse what
1876    /// the action would refuse ([`NonBlank`](crate::NonBlank)):
1877    /// `Tracker::CREATE.try_map(|title: String| Some(Create { title: NonBlank::parse(&title)?, .. }))`.
1878    ///
1879    /// An input `parse` makes nothing of invokes nothing; a control bound
1880    /// to a draft through it is disabled meanwhile. `parse` only reads: it
1881    /// also runs, as the draft changes, to tell whether the control can act.
1882    pub fn try_map<I, T, F>(self, parse: F) -> TryMapped<R, A, F>
1883    where
1884        F: Fn(I) -> Option<T>,
1885        T: Into<A>,
1886    {
1887        TryMapped {
1888            action: self,
1889            parse,
1890        }
1891    }
1892}
1893
1894/// An [`ActionRef`] behind an input adapter that may make no arguments. See
1895/// [`ActionRef::try_map`].
1896pub struct TryMapped<R, A, F> {
1897    action: ActionRef<R, A>,
1898    parse: F,
1899}
1900
1901impl<R, A, F: Clone> Clone for TryMapped<R, A, F> {
1902    fn clone(&self) -> Self {
1903        Self {
1904            action: self.action,
1905            parse: self.parse.clone(),
1906        }
1907    }
1908}
1909
1910/// An [`ActionRef`] behind an input adapter. See [`ActionRef::map`].
1911pub struct Mapped<R, A, F> {
1912    action: ActionRef<R, A>,
1913    map: F,
1914}
1915
1916impl<R, A, F: Clone> Clone for Mapped<R, A, F> {
1917    fn clone(&self) -> Self {
1918        Self {
1919            action: self.action,
1920            map: self.map.clone(),
1921        }
1922    }
1923}
1924
1925/// Something a control with input `I` can be bound to: an action and how the
1926/// control's value becomes that action's arguments.
1927pub trait Binds<R, I>: Send + Sync + 'static {
1928    fn action_id(&self) -> &'static str;
1929
1930    /// The key the action is published under — the app, resource kind and
1931    /// action id — which a control is bound against. A reference carries its
1932    /// own ([`ActionRef::key`]); anything else is bound as `R`'s own action
1933    /// under [`R`'s app](Resource::APP_ID) and kind.
1934    fn action_key(&self) -> ActionKey
1935    where
1936        R: Resource,
1937    {
1938        ActionKey::new(R::APP_ID, R::KIND, self.action_id())
1939    }
1940
1941    /// The arguments `input` binds to.
1942    ///
1943    /// # Errors
1944    /// Returns why `input` does not bind; the control invokes nothing.
1945    fn arguments(&self, input: I) -> Result<serde_json::Map<String, serde_json::Value>, String>;
1946}
1947
1948/// A control binds an action whose input its value converts to: a text
1949/// field binds a verb taking one `String`.
1950impl<R: 'static, A: Serialize + 'static, I: Into<A>> Binds<R, I> for ActionRef<R, A> {
1951    fn action_id(&self) -> &'static str {
1952        self.id
1953    }
1954    fn action_key(&self) -> ActionKey {
1955        ActionRef::key(self)
1956    }
1957    fn arguments(&self, input: I) -> Result<serde_json::Map<String, serde_json::Value>, String> {
1958        ActionRef::arguments(self, &input.into())
1959    }
1960}
1961
1962impl<R, A, I, T, F> Binds<R, I> for Mapped<R, A, F>
1963where
1964    R: 'static,
1965    A: Serialize + 'static,
1966    T: Into<A>,
1967    F: Fn(I) -> T + Send + Sync + 'static,
1968{
1969    fn action_id(&self) -> &'static str {
1970        self.action.id
1971    }
1972    fn action_key(&self) -> ActionKey {
1973        ActionRef::key(&self.action)
1974    }
1975    fn arguments(&self, input: I) -> Result<serde_json::Map<String, serde_json::Value>, String> {
1976        self.action.arguments(&(self.map)(input).into())
1977    }
1978}
1979
1980impl<R, A, I, T, F> Binds<R, I> for TryMapped<R, A, F>
1981where
1982    R: 'static,
1983    A: Serialize + 'static,
1984    T: Into<A>,
1985    F: Fn(I) -> Option<T> + Send + Sync + 'static,
1986{
1987    fn action_id(&self) -> &'static str {
1988        self.action.id
1989    }
1990    fn action_key(&self) -> ActionKey {
1991        ActionRef::key(&self.action)
1992    }
1993    fn arguments(&self, input: I) -> Result<serde_json::Map<String, serde_json::Value>, String> {
1994        let Some(parsed) = (self.parse)(input) else {
1995            return Err(no_arguments(self.action.id));
1996        };
1997        self.action.arguments(&parsed.into())
1998    }
1999}
2000
2001/// Why a [`TryMapped`] control invoked nothing: written once, not once per
2002/// adapter.
2003#[inline(never)]
2004fn no_arguments(id: &str) -> String {
2005    format!("the input makes no arguments for `{id}`")
2006}
2007
2008/// The input of an action that takes nothing: `()`, or a verb's empty
2009/// parameter struct.
2010pub trait NoParams {}
2011
2012impl NoParams for () {}
2013
2014/// A verb's generated parameter struct, linked to the verb it is the input
2015/// of. A form is a local value of it; submitting the form invokes
2016/// [`Self::ACTION`] with it.
2017pub trait Params: Serialize + DeserializeOwned + crate::JsonSchema + Clone + 'static {
2018    /// The resource the verb belongs to.
2019    type Resource;
2020    /// The typed paths into the parameters, one per parameter.
2021    type Paths: Clone;
2022    /// The verb.
2023    const ACTION: ActionRef<Self::Resource, Self>;
2024
2025    /// The typed paths into the parameters.
2026    fn paths() -> Self::Paths;
2027}
2028
2029impl<R, A: NoParams> ActionRef<R, A> {
2030    /// The invocation of a nullary action.
2031    pub fn invoke(&self) -> Invoke<R> {
2032        Invoke {
2033            id: self.id,
2034            arguments: serde_json::Map::new(),
2035            refusal: None,
2036            effect: false,
2037            on: None,
2038            marker: PhantomData,
2039        }
2040    }
2041}
2042
2043/// One fully specified invocation of a declared action, or of one of the
2044/// app's effects ([`Invoke::effect`]).
2045pub struct Invoke<R> {
2046    pub id: &'static str,
2047    pub arguments: serde_json::Map<String, serde_json::Value>,
2048    /// Why the input it was built from does not bind, if it does not.
2049    refusal: Option<String>,
2050    effect: bool,
2051    /// The published row it acts on ([`Self::on`]), when not the resource.
2052    on: Option<String>,
2053    marker: PhantomData<fn() -> R>,
2054}
2055
2056impl<R> Clone for Invoke<R> {
2057    fn clone(&self) -> Self {
2058        Self {
2059            id: self.id,
2060            arguments: self.arguments.clone(),
2061            refusal: self.refusal.clone(),
2062            effect: self.effect,
2063            on: self.on.clone(),
2064            marker: PhantomData,
2065        }
2066    }
2067}
2068
2069impl<R> std::fmt::Debug for Invoke<R> {
2070    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2071        f.debug_struct("Invoke")
2072            .field("id", &self.id)
2073            .field("arguments", &self.arguments)
2074            .field("refusal", &self.refusal)
2075            .field("effect", &self.effect)
2076            .field("on", &self.on)
2077            .finish()
2078    }
2079}
2080
2081impl<R> Invoke<R> {
2082    /// An invocation of one of the app's effects — show an item, refresh a
2083    /// list — through the same API as its actions: what a launch asks of
2084    /// an app beside editing its resource (`tilo-store:app/<id>` showing that
2085    /// app). It changes no document, so it never builds an action.
2086    ///
2087    /// An effect offered only on rows (`#[effect(row, on = Page)]`) acts on
2088    /// the row it is invoked on: name it with [`Self::on`]. Until then it
2089    /// refuses, saying so, since the resource does not offer it.
2090    pub fn effect<E: crate::Effect>(effect: &E) -> Self {
2091        let id = effect.id();
2092        let refusal = E::declaration(id)
2093            .is_some_and(|declaration| declaration.row)
2094            .then(|| format!("`{id}` is offered only on rows: invoke it on one"));
2095        Self {
2096            id,
2097            arguments: effect.arguments(),
2098            refusal,
2099            effect: true,
2100            on: None,
2101            marker: PhantomData,
2102        }
2103    }
2104
2105    /// This invocation on the published row `row` (the Browser's page, one
2106    /// download), which offers its action, rather than on the resource.
2107    #[must_use]
2108    pub fn on(mut self, row: impl Into<String>) -> Self {
2109        if self.effect {
2110            self.refusal = None;
2111        }
2112        self.on = Some(row.into());
2113        self
2114    }
2115
2116    /// The published row it acts on, when [`Self::on`] named one.
2117    pub fn row(&self) -> Option<&str> {
2118        self.on.as_deref()
2119    }
2120
2121    /// The invocation of action `id` with what its input bound to, or one
2122    /// that refuses with why it did not bind. Kept out of line: its body is
2123    /// the same for every resource, so the copies merge into one.
2124    #[inline(never)]
2125    pub(crate) fn bound(
2126        id: &'static str,
2127        bound: Result<serde_json::Map<String, serde_json::Value>, String>,
2128    ) -> Self {
2129        let (arguments, refusal) = match bound {
2130            Ok(arguments) => (arguments, None),
2131            Err(refusal) => (serde_json::Map::new(), Some(refusal)),
2132        };
2133        Self {
2134            id,
2135            arguments,
2136            refusal,
2137            effect: false,
2138            on: None,
2139            marker: PhantomData,
2140        }
2141    }
2142
2143    /// Why the input this invocation was built from does not bind: such an
2144    /// invocation refuses wherever it is submitted.
2145    pub fn refusal(&self) -> Option<&str> {
2146        self.refusal.as_deref()
2147    }
2148
2149    /// Whether this invokes an effect ([`Self::effect`]) rather than one of
2150    /// the resource's actions.
2151    pub fn is_effect(&self) -> bool {
2152        self.effect
2153    }
2154
2155    /// This invocation's action as the published resource `resource` (an
2156    /// item of the record, a child, a live row) offers it.
2157    #[must_use]
2158    pub fn address_on(&self, resource: impl Into<String>) -> tilo_actions::ActionAddress {
2159        tilo_actions::ActionAddress::new(resource, self.id)
2160    }
2161}
2162
2163impl<R: Resource> Invoke<R> {
2164    /// This invocation's action as the record's own resource publishes it.
2165    #[must_use]
2166    pub fn address(&self) -> tilo_actions::ActionAddress {
2167        self.address_on(R::KIND)
2168    }
2169
2170    /// An invocation of the generic [`APPLY`](crate::APPLY) action for one
2171    /// typed action value — the path for edits without a named declaration.
2172    ///
2173    /// # Errors
2174    /// Returns the serialization error of `action`.
2175    pub fn apply(action: &R::Action) -> Result<Self, serde_json::Error> {
2176        // A unit variant serializes as its name; written as a map it reads
2177        // back the same, and is the object the action's parameter takes.
2178        let value = match crate::__private::json_via_bytes(action)? {
2179            serde_json::Value::String(variant) => serde_json::Value::Object(
2180                serde_json::Map::from_iter([(variant, serde_json::Value::Null)]),
2181            ),
2182            value => value,
2183        };
2184        Ok(Self {
2185            id: crate::APPLY,
2186            arguments: serde_json::Map::from_iter([(crate::APPLY_PARAM.to_owned(), value)]),
2187            refusal: None,
2188            effect: false,
2189            on: None,
2190            marker: PhantomData,
2191        })
2192    }
2193
2194    /// An invocation of the field edit `edit` ([`FIELD_EDIT`](crate::FIELD_EDIT)).
2195    ///
2196    /// # Errors
2197    /// Returns the serialization error of `edit`.
2198    pub fn edit(edit: &crate::Edit<R>) -> Result<Self, serde_json::Error> {
2199        Ok(Self {
2200            id: crate::FIELD_EDIT,
2201            arguments: serde_json::Map::from_iter([(
2202                crate::EDIT_PARAM.to_owned(),
2203                crate::__private::json_via_bytes(edit)?,
2204            )]),
2205            refusal: None,
2206            effect: false,
2207            on: None,
2208            marker: PhantomData,
2209        })
2210    }
2211
2212    /// The field edit `edit`, or an invocation that refuses when it does
2213    /// not encode: [`Self::edit`] where an `Invoke` is expected
2214    /// (`replica.apply(paths.count.set(42))`).
2215    fn from_edit(edit: &crate::Edit<R>) -> Self {
2216        Self::edit(edit).unwrap_or_else(|error| Self {
2217            id: crate::FIELD_EDIT,
2218            arguments: serde_json::Map::new(),
2219            refusal: Some(error.to_string()),
2220            effect: false,
2221            on: None,
2222            marker: PhantomData,
2223        })
2224    }
2225
2226    /// Several invocations applied as one action: one change, one version,
2227    /// one undo step. Members that are groups themselves are flattened.
2228    pub fn group(members: impl IntoIterator<Item = Self>) -> Self {
2229        let mut actions = Vec::new();
2230        let mut refusal = None;
2231        for member in members {
2232            if refusal.is_none() {
2233                refusal.clone_from(&member.refusal);
2234            }
2235            if member.is_group() {
2236                if let Some(serde_json::Value::Array(inner)) =
2237                    member.arguments.get(crate::GROUP_PARAM)
2238                {
2239                    actions.extend(inner.iter().cloned());
2240                }
2241            } else {
2242                actions.push(serde_json::json!({
2243                    "action": member.id,
2244                    "args": member.arguments,
2245                }));
2246            }
2247        }
2248        Self {
2249            id: crate::GROUP,
2250            arguments: serde_json::Map::from_iter([(
2251                crate::GROUP_PARAM.to_owned(),
2252                serde_json::Value::Array(actions),
2253            )]),
2254            refusal,
2255            effect: false,
2256            on: None,
2257            marker: PhantomData,
2258        }
2259    }
2260
2261    /// Whether this is a [`group`](Self::group) of invocations.
2262    pub fn is_group(&self) -> bool {
2263        self.id == crate::GROUP
2264    }
2265
2266    /// Build the replayable action on this (origin) machine. A group builds
2267    /// with [`build_group`](crate::group::build_group).
2268    pub fn build(&self, now_ms: i64) -> Result<R::Action, String> {
2269        if let Some(refusal) = &self.refusal {
2270            return Err(refusal.clone());
2271        }
2272        // What only the app's own code applies has no declaration a caller
2273        // could name: it is built here, where the app invokes it.
2274        if let Some(built) = R::build_by_app(self.id, &self.arguments, now_ms) {
2275            return built;
2276        }
2277        crate::resource::build_action::<R>(self.id, &self.arguments, now_ms)
2278    }
2279}
2280
2281impl<R: Resource> From<crate::Edit<R>> for Invoke<R> {
2282    fn from(edit: crate::Edit<R>) -> Self {
2283        Self::from_edit(&edit)
2284    }
2285}
2286
2287impl<R: Resource> From<&crate::Edit<R>> for Invoke<R> {
2288    fn from(edit: &crate::Edit<R>) -> Self {
2289        Self::from_edit(edit)
2290    }
2291}
2292
2293#[cfg(test)]
2294mod seed_tests {
2295    use super::*;
2296    use automerge::transaction::Transactable as _;
2297
2298    #[test]
2299    fn a_seed_read_mid_transaction_leaves_it_open_and_moves_with_it() {
2300        let mut doc = Doc::new();
2301        doc.put(ROOT, "a", 1).unwrap();
2302        doc.commit();
2303        let committed = seed(&doc, b"test", b"payload");
2304        doc.put(ROOT, "b", 2).unwrap();
2305        let base = doc.base_heads();
2306        let open = seed(&doc, b"test", b"payload");
2307        assert!(doc.pending_ops() > 0, "reading the seed commits nothing");
2308        assert_eq!(doc.base_heads(), base);
2309        assert_ne!(open, committed, "an open transaction moves the seed");
2310        doc.put(ROOT, "c", 3).unwrap();
2311        assert_ne!(seed(&doc, b"test", b"payload"), open);
2312        doc.commit();
2313        assert_ne!(seed(&doc, b"test", b"payload"), committed);
2314    }
2315}