Skip to main content

tilo_actions/
action.rs

1//! The [`Action`] trait and its serializable envelope-side vocabulary.
2//!
3//! An **Action** is the atomic unit of "play locally, replay anywhere":
4//! a *value* that deterministically mutates a CRDT document. The
5//! [executor](crate::executor) pins the Automerge actor id and commit
6//! timestamp from the action's envelope, so the resulting change is
7//! content-addressed identical on every replica (native Automerge
8//! exchange later dedupes rather than double-applying).
9//!
10//! Actions are **not** presentation — local-only state (rendering,
11//! selection, scroll) must never go through an action; only shared CRDT
12//! mutations do.
13
14use serde::{Deserialize, Serialize};
15
16/// The CRDT document an action mutates — aliased so call sites read as
17/// "mutate the Doc"; exactly [`automerge::AutoCommit`].
18pub type Doc = automerge::AutoCommit;
19
20/// Where an action executes, declared on the action type and carried on every
21/// envelope. [`ServerPreferred`](Self::ServerPreferred) retains its historical
22/// wire spelling, but is an authoritative-host requirement: absence of a host
23/// is a refusal, never permission for the client to perform the operation.
24#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
25pub enum ExecutionLocus {
26    /// This client applies the action locally and replicates the envelope;
27    /// peers replay it (verifying it was a valid mutation). The default.
28    #[default]
29    ClientLocal,
30    /// Requires authoritative execution on a host (e.g. a shared queue or
31    /// moderated reply). The dispatcher submits to the host and fails closed
32    /// when none is reachable.
33    ServerPreferred,
34}
35
36/// What an exported operation changes. Keeping this explicit prevents
37/// applications from disguising local effects or navigation as CRDT edits.
38#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
39pub enum OperationKind {
40    /// Deterministic shared-document mutation, decoded by `ActionRegistry`.
41    #[default]
42    Document,
43    /// Local or host-owned side effect (launch, filesystem, network, media).
44    Effect,
45    /// Local presentation/navigation change (selection, route, focused view).
46    View,
47}
48
49impl OperationKind {
50    pub const fn as_str(self) -> &'static str {
51        match self {
52            Self::Document => "document",
53            Self::Effect => "effect",
54            Self::View => "view",
55        }
56    }
57
58    /// Whether a window's report of this operation may stand as a change of the person's history:
59    /// a document or view change, or a read the input made (a press that asks and changes
60    /// nothing). An effect changes nothing a history records, and the broker admits no report of
61    /// one, so a window never reports an effect.
62    #[must_use]
63    pub fn reports_a_change(self, need: crate::ActionKind) -> bool {
64        matches!(self, Self::Document | Self::View) || need == crate::ActionKind::Read
65    }
66}
67
68pub use tilo_action_types::ActionId;
69
70/// Errors from encoding, decoding, or applying an action.
71#[derive(Debug, thiserror::Error)]
72pub enum ActionError {
73    /// The action's `apply` hit an Automerge error.
74    #[error("automerge error: {0}")]
75    Automerge(#[from] automerge::AutomergeError),
76    /// No decoder is registered for this action's `type_id`.
77    #[error("no decoder registered for action type `{0}`")]
78    UnknownType(String),
79    /// The payload could not be deserialized into the registered type.
80    #[error("failed to decode action `{type_id}`: {source}")]
81    Decode {
82        type_id: String,
83        source: serde_json::Error,
84    },
85    /// The concrete action could not be serialized into a payload.
86    #[error("failed to encode action: {0}")]
87    Encode(serde_json::Error),
88    /// The action was well-formed and the app declined to carry it out, in
89    /// its own words. Every other variant is a plumbing fault; this one is
90    /// the app answering — a caller must tell "I asked wrongly" from "I
91    /// asked correctly and the answer is no".
92    #[error("{0}")]
93    Refused(String),
94    /// The app declined for a reason a caller acts on rather than reads: the
95    /// thing it would add is there already, say. `code` names it stably, and
96    /// `message` says it in words for whoever reads.
97    #[error("{message}")]
98    Unavailable { code: String, message: String },
99    /// The app declined for one of the reasons a window tells the person in
100    /// their own language ([`Declined`]): a caller can say what happened
101    /// instead of showing them the plumbing.
102    #[error("{0}")]
103    Declined(Declined),
104}
105
106/// The most bytes one text may hold: what one action carries, and what one
107/// window carries in one string. One number for both, so a text an edit keeps
108/// is always a text the window can show.
109pub const MAX_TEXT_BYTES: usize = 8 * 1024 * 1024;
110
111/// The most a conversation's running summary holds, in bytes: what an agent
112/// keeps of the conversation it answers in, told to later turns in place of
113/// the messages before it, and the bound a resource keeping one applies.
114pub const RECALL_SUMMARY_BYTES: usize = 4 * 1024;
115
116/// Codes an app answers a condition with, for a caller that decides on the
117/// condition rather than reads the words beside it.
118pub mod codes {
119    /// A note imported from a source page is in the notebook already.
120    pub const NOTE_ALREADY_IMPORTED: &str = "note_already_imported";
121}
122
123/// Why an app declined an action, for the reasons a person is told rather than
124/// logged: the window says what happened and what to do, from the toolkit's
125/// catalogue.
126#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
127pub enum Declined {
128    /// What the action would change is not as it read it: a newer edit reached
129    /// the text first.
130    Changed,
131    /// The text the action carries is longer than one text may hold
132    /// ([`MAX_TEXT_BYTES`]).
133    TooLong,
134}
135
136impl Declined {
137    /// The catalogue message that says it, and the message's arguments: the toolkit's catalogue
138    /// holds the words, in every language it ships, so every window tells the same reason.
139    #[must_use]
140    pub fn words(self) -> (String, Vec<(String, String)>) {
141        match self {
142            Self::Changed => ("rich-text-changed-while-typing".to_owned(), Vec::new()),
143            Self::TooLong => (
144                "rich-text-too-long".to_owned(),
145                // A limit of a mebibyte and more reads as its megabytes.
146                vec![(
147                    "limit".to_owned(),
148                    format!("{} MB", MAX_TEXT_BYTES / (1024 * 1024)),
149                )],
150            ),
151        }
152    }
153}
154
155impl std::fmt::Display for Declined {
156    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157        f.write_str(match self {
158            Self::Changed => "the text changed since it was read",
159            Self::TooLong => "the text is longer than one text may hold",
160        })
161    }
162}
163
164/// A value that deterministically mutates a CRDT [`Doc`].
165///
166/// [`apply`](Action::apply) MUST be a pure function of `(self,
167/// doc-state)` — no wall-clock reads, no RNG, no local-only state — and
168/// MUST NOT commit; the [executor](crate::executor) owns the commit
169/// boundary (actor id + timestamp) so the change is content-addressed
170/// identical everywhere.
171///
172/// Concrete actions are app-defined enums deriving `Serialize`/
173/// `Deserialize`, registered by `type_id` in an
174/// [`ActionRegistry`](crate::registry::ActionRegistry) so a replaying
175/// peer can reconstruct them.
176/// One step of an action that stands for several ([`Action::steps`]): the action, and its payload
177/// under the type of the action it is a step of.
178pub type ActionStep = (Box<dyn Action>, Vec<u8>);
179
180pub trait Action: std::fmt::Debug {
181    /// Apply this action's mutation to `doc`. See the trait contract.
182    ///
183    /// # Errors
184    ///
185    /// Implementations return [`ActionError::Automerge`] for a document
186    /// write failure, or [`ActionError::Refused`] if the app declines to
187    /// carry out an otherwise well-formed action.
188    fn apply(&self, doc: &mut Doc) -> Result<(), ActionError>;
189
190    /// Where this action prefers to run. Defaults to [`ExecutionLocus::ClientLocal`].
191    fn locus(&self) -> ExecutionLocus {
192        ExecutionLocus::ClientLocal
193    }
194
195    /// The consequence class of this particular value — what it would do,
196    /// not what its type can do. A generic edit action classifies each value
197    /// (deleting a clip is [`Destructive`](crate::RiskLevel::Destructive),
198    /// trimming one is not), and the host asks for the same confirmation a
199    /// declared destructive action gets whenever
200    /// [`requires_confirmation`](crate::RiskLevel::requires_confirmation)
201    /// holds. Must be a pure function of `self`. Defaults to
202    /// [`Low`](crate::RiskLevel::Low).
203    fn risk(&self) -> crate::contract::RiskLevel {
204        crate::contract::RiskLevel::Low
205    }
206
207    /// The document action that undoes this one when `apply` records an
208    /// outside consequence in the document (an outbox entry, a filesystem op
209    /// queue). Computed against the document *before* this action runs, so a
210    /// delete can still read the row it removes.
211    ///
212    /// When this returns `Some`, undo applies that action through
213    /// [`Action::apply`] instead of writing Automerge inverse patches — so the
214    /// compensating queue entry is recorded the same way peers will replay it.
215    /// Pure CRDT actions with no outside consequence leave this as `None`;
216    /// inverse patches remain correct for them. Effects never participate:
217    /// they have no heads and are not undoable.
218    fn inverse_before(&self, doc: &Doc) -> Option<Self>
219    where
220        Self: Sized,
221    {
222        let _ = doc;
223        None
224    }
225
226    /// [`inverse_before`](Self::inverse_before) as an encoded action, so the
227    /// API can undo through `apply` after the concrete type has been erased.
228    ///
229    /// The palette, an agent and a script apply a decoded `dyn Action`. That
230    /// value cannot return `Self`. An action whose `apply` writes an outside
231    /// queue implements this and encodes the compensating action under the
232    /// same registry type id. The default is `None`: undo stays Automerge
233    /// inverse patches.
234    fn inverse_encoded(&self, doc: &Doc) -> Option<EncodedAction> {
235        let _ = doc;
236        None
237    }
238
239    /// Whether this value changes the document's content or is housekeeping
240    /// about it (a read marker, a reading position). The executor writes it
241    /// into the change's [`ActionContext`](crate::ActionContext), where a
242    /// workspace activity feed reads it. Must be a pure function of `self`.
243    /// Defaults to [`Content`](crate::context::ChangeKind::Content).
244    fn change_kind(&self) -> crate::context::ChangeKind {
245        crate::context::ChangeKind::Content
246    }
247
248    /// What kind of action this value is: whether it only changes the
249    /// document or also reaches outside it. Must be a pure function of
250    /// `self`. An action that records an outside consequence in the document
251    /// (an outbox entry) is [`Outside`](crate::ActionKind::Outside); the
252    /// default is [`Undoable`](crate::ActionKind::Undoable).
253    fn action_kind(&self) -> crate::ActionKind {
254        crate::ActionKind::Undoable
255    }
256
257    /// Whether this value records a message someone received (a chat post,
258    /// a delivered mail). The executor marks its change with
259    /// [`INCOMING_MESSAGE_FACET`](crate::INCOMING_MESSAGE_FACET). Must be a
260    /// pure function of `self`.
261    fn incoming_message(&self) -> bool {
262        false
263    }
264
265    /// The members who alone read what this value changes, when what it
266    /// changes says who reads it (a direct conversation); `None` when every
267    /// member who reads the record reads it. The executor marks its change
268    /// with [`READERS_FACET`](crate::READERS_FACET). Must be a pure function
269    /// of `self`.
270    fn readers(&self) -> Option<Vec<crate::MemberId>> {
271        None
272    }
273
274    /// Whether this value leaves the system for good (a message sent to
275    /// people outside it), so a person's own press of it always confirms
276    /// first. See [`LEAVES_TAG`](crate::LEAVES_TAG). Must be a pure function
277    /// of `self`.
278    fn leaves(&self) -> bool {
279        false
280    }
281
282    /// Whether this value loses something Undo cannot bring back, beside
283    /// the document change Undo reverts (an account's secret every device
284    /// forgets). See [`IRREVERSIBLE_TAG`](crate::IRREVERSIBLE_TAG). Must be
285    /// a pure function of `self`.
286    fn irreversible(&self) -> bool {
287        false
288    }
289
290    /// Whether this value's undo is its own code's to compute
291    /// ([`inverse_encoded`](Self::inverse_encoded) may answer one): a device
292    /// applying it from an app's model module, which does not compute undo,
293    /// writes no entry another device would check that undo against. Must be
294    /// a pure function of `self`.
295    fn compensates(&self) -> bool {
296        false
297    }
298
299    /// What this value does and to which item, as history records it: a
300    /// field edit with its values before and after, a verb with its plain
301    /// arguments, or a group of those. Read from `doc` as it is before the
302    /// value applies, on the origin only; replicas replay it with the
303    /// change. `None` lets the executor describe the value as the verb its
304    /// encoded form names ([`crate::Described::from_encoded`]).
305    fn describe(&self, doc: &Doc) -> Option<crate::Described> {
306        let _ = doc;
307        None
308    }
309
310    /// The item this value made, read from `doc` with its writes as an open
311    /// transaction: what history names a change that creates something by
312    /// ("Created ‘Spring plans’"), which `doc` before the value applied could
313    /// not name because the item did not exist yet. `None` when the value
314    /// made no item of its own, or names none itself; the executor then keeps
315    /// the description it read before the value applied.
316    fn made(&self, doc: &Doc) -> Option<crate::entry::ActionItem> {
317        let _ = doc;
318        None
319    }
320
321    /// The actions this value is, one for each step it takes, when it stands for several: an
322    /// undo of three steps is three undos of one, newest first. The executor applies each as an
323    /// action of its own, so every change names the one step it moved, and a peer replays it as
324    /// that one action. Each is its payload under this value's type, with the action it decodes
325    /// to. `None` for a value that is one step, as almost every value is. Read from `doc` before
326    /// anything applies.
327    fn steps(&self, doc: &Doc) -> Option<Vec<ActionStep>> {
328        let _ = doc;
329        None
330    }
331}
332
333/// Whether Undo takes back a value with these facts: it changes the document
334/// alone ([`ActionKind::Undoable`](crate::ActionKind::Undoable)), as a
335/// person's step ([`ChangeKind::is_step`](crate::ChangeKind::is_step)), and
336/// loses nothing Undo cannot bring back ([`Action::irreversible`]). The one
337/// rule every host asks, whatever the value's type.
338#[must_use]
339pub fn undo_takes_back(
340    kind: crate::ActionKind,
341    change: crate::ChangeKind,
342    irreversible: bool,
343) -> bool {
344    kind == crate::ActionKind::Undoable && change.is_step() && !irreversible
345}
346
347/// Whether a value with these facts is confirmed before it applies: its risk
348/// asks for confirmation and Undo cannot take it back
349/// ([`RiskLevel::requires_confirmation_when`](crate::RiskLevel::requires_confirmation_when)).
350#[must_use]
351pub fn asks_first(
352    risk: crate::RiskLevel,
353    kind: crate::ActionKind,
354    change: crate::ChangeKind,
355    irreversible: bool,
356) -> bool {
357    risk.requires_confirmation_when(undo_takes_back(kind, change, irreversible))
358}
359
360/// What a person's own press of `action` waits for, as its contract says it
361/// ([`ActionContract::confirms`](crate::ActionContract::confirms)), read from
362/// the value itself.
363#[must_use]
364pub fn press_confirms<A: Action + ?Sized>(action: &A) -> crate::Confirms {
365    if action.leaves() {
366        return crate::Confirms::Always;
367    }
368    let kind = action.action_kind();
369    let kind = if undo_takes_back(kind, action.change_kind(), action.irreversible()) {
370        crate::ActionKind::Undoable
371    } else if kind == crate::ActionKind::Read {
372        crate::ActionKind::Read
373    } else {
374        crate::ActionKind::Outside
375    };
376    kind.confirms(action.risk() == crate::RiskLevel::Destructive)
377}
378
379/// A serialized action ready to cross a process/network boundary: the
380/// registry `type_id` plus the JSON payload the matching decoder
381/// reconstructs it from.
382#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
383pub struct EncodedAction {
384    pub type_id: String,
385    /// Written as its text where the action is written as text (JSON), and
386    /// as bytes elsewhere: never a list of numbers, one per byte.
387    #[serde(with = "payload_text")]
388    pub payload: Vec<u8>,
389}
390
391/// An action's payload, JSON text, as a string in a format written as text
392/// and as bytes in one that is not.
393mod payload_text {
394    use serde::de::Visitor;
395    use serde::ser::Error as _;
396    use serde::{Deserializer, Serializer};
397
398    pub(super) fn serialize<S: Serializer>(payload: &[u8], into: S) -> Result<S::Ok, S::Error> {
399        if into.is_human_readable() {
400            into.serialize_str(std::str::from_utf8(payload).map_err(S::Error::custom)?)
401        } else {
402            into.serialize_bytes(payload)
403        }
404    }
405
406    pub(super) fn deserialize<'de, D: Deserializer<'de>>(from: D) -> Result<Vec<u8>, D::Error> {
407        struct Payload;
408
409        impl Visitor<'_> for Payload {
410            type Value = Vec<u8>;
411
412            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
413                formatter.write_str("an action's payload, as text or bytes")
414            }
415
416            fn visit_str<E: serde::de::Error>(self, text: &str) -> Result<Vec<u8>, E> {
417                Ok(text.as_bytes().to_vec())
418            }
419
420            fn visit_string<E: serde::de::Error>(self, text: String) -> Result<Vec<u8>, E> {
421                Ok(text.into_bytes())
422            }
423
424            fn visit_bytes<E: serde::de::Error>(self, bytes: &[u8]) -> Result<Vec<u8>, E> {
425                Ok(bytes.to_vec())
426            }
427
428            fn visit_byte_buf<E: serde::de::Error>(self, bytes: Vec<u8>) -> Result<Vec<u8>, E> {
429                Ok(bytes)
430            }
431        }
432
433        if from.is_human_readable() {
434            from.deserialize_string(Payload)
435        } else {
436            from.deserialize_byte_buf(Payload)
437        }
438    }
439}
440
441impl EncodedAction {
442    /// Serialize a concrete action under a registry `type_id`.
443    ///
444    /// # Errors
445    ///
446    /// Returns [`ActionError::Encode`] if `action` fails to serialize.
447    pub fn encode<A>(type_id: impl Into<String>, action: &A) -> Result<Self, ActionError>
448    where
449        A: Action + Serialize,
450    {
451        Self::encoded(type_id.into(), serde_json::to_vec(action))
452    }
453
454    /// The tail of [`Self::encode`] every action type shares.
455    #[inline(never)]
456    fn encoded(
457        type_id: String,
458        payload: Result<Vec<u8>, serde_json::Error>,
459    ) -> Result<Self, ActionError> {
460        Ok(Self::written(
461            type_id,
462            payload.map_err(ActionError::Encode)?,
463        ))
464    }
465
466    /// An action of `type_id` whose payload is `payload`, a group's written
467    /// with what its members share once ([`crate::group_form`]).
468    #[must_use]
469    pub fn written(type_id: String, payload: Vec<u8>) -> Self {
470        let payload = if crate::group_form::is_group(&type_id) {
471            crate::group_form::compact(&payload).unwrap_or(payload)
472        } else {
473            payload
474        };
475        Self { type_id, payload }
476    }
477
478    /// Serialize a non-document operation payload. Unlike [`Self::encode`],
479    /// this intentionally requires no [`Action`] implementation: effects and
480    /// views are handled by the owning application, not replayed into a CRDT.
481    ///
482    /// # Errors
483    ///
484    /// Returns [`ActionError::Encode`] if `payload` fails to serialize.
485    pub fn encode_operation<T>(type_id: impl Into<String>, payload: &T) -> Result<Self, ActionError>
486    where
487        T: Serialize,
488    {
489        Ok(Self {
490            type_id: type_id.into(),
491            payload: serde_json::to_vec(payload).map_err(ActionError::Encode)?,
492        })
493    }
494}
495
496#[cfg(test)]
497mod action_id_tests {
498    use super::ActionId;
499    use tilo_clock::time::{Duration, UNIX_EPOCH};
500
501    /// The id's time is the clock this process was given, never `std`'s own: an app's model runs
502    /// as a WebAssembly module with no `std` clock to ask, and mints its ids under the host's
503    /// pinned reading.
504    #[test]
505    fn an_id_is_minted_at_the_time_the_process_holds() {
506        let at = UNIX_EPOCH + Duration::from_millis(1_700_000_000_123);
507        let (first, second) =
508            tilo_clock::testing::with_wall(at, || (ActionId::new(), ActionId::new()));
509        for id in [first, second] {
510            let (seconds, nanos) = id.0.get_timestamp().expect("a version 7 id").to_unix();
511            assert_eq!(
512                seconds * 1_000 + u64::from(nanos) / 1_000_000,
513                1_700_000_000_123,
514                "the id carries the time the process holds"
515            );
516        }
517        assert!(first.0 < second.0, "an id sorts after the one before it");
518    }
519}
520
521#[cfg(test)]
522mod operation_kind_tests {
523    use super::OperationKind;
524    use crate::ActionKind;
525
526    /// What a window may report as a change of the person's history: a document or view change,
527    /// or a read the input made. An effect changes nothing a history records, so reporting one
528    /// would ask the broker to admit a change that does not exist.
529    #[test]
530    fn only_a_change_or_a_read_is_reported() {
531        for (kind, need, reported) in [
532            (OperationKind::Document, ActionKind::Undoable, true),
533            (OperationKind::Document, ActionKind::Read, true),
534            (OperationKind::View, ActionKind::Read, true),
535            (OperationKind::View, ActionKind::Outside, true),
536            (OperationKind::Effect, ActionKind::Outside, false),
537            (OperationKind::Effect, ActionKind::Undoable, false),
538            (OperationKind::Effect, ActionKind::Read, true),
539        ] {
540            assert_eq!(kind.reports_a_change(need), reported, "{kind:?}/{need:?}");
541        }
542    }
543
544    /// Only the canonical form round-trips; other spellings are refused.
545    #[test]
546    fn operation_kind_accepts_only_the_canonical_spelling() {
547        for (kind, canonical, lower) in [
548            (OperationKind::Document, "Document", "document"),
549            (OperationKind::Effect, "Effect", "effect"),
550            (OperationKind::View, "View", "view"),
551        ] {
552            assert_eq!(serde_json::to_value(kind).unwrap(), canonical);
553            assert_eq!(
554                serde_json::from_value::<OperationKind>(serde_json::json!(canonical)).unwrap(),
555                kind
556            );
557            assert!(serde_json::from_value::<OperationKind>(serde_json::json!(lower)).is_err());
558        }
559        assert!(serde_json::from_value::<OperationKind>(serde_json::json!("EFFECT")).is_err());
560    }
561}