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