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 loses something Undo cannot bring back, beside
275    /// the document change Undo reverts (an account's secret every device
276    /// forgets). See [`IRREVERSIBLE_TAG`](crate::IRREVERSIBLE_TAG). Must be
277    /// a pure function of `self`.
278    fn irreversible(&self) -> bool {
279        false
280    }
281
282    /// Whether this value's undo is its own code's to compute
283    /// ([`inverse_encoded`](Self::inverse_encoded) may answer one): a device
284    /// applying it from an app's model module, which does not compute undo,
285    /// writes no entry another device would check that undo against. Must be
286    /// a pure function of `self`.
287    fn compensates(&self) -> bool {
288        false
289    }
290
291    /// What this value does and to which item, as history records it: a
292    /// field edit with its values before and after, a verb with its plain
293    /// arguments, or a group of those. Read from `doc` as it is before the
294    /// value applies, on the origin only; replicas replay it with the
295    /// change. `None` lets the executor describe the value as the verb its
296    /// encoded form names ([`crate::Described::from_encoded`]).
297    fn describe(&self, doc: &Doc) -> Option<crate::Described> {
298        let _ = doc;
299        None
300    }
301
302    /// The item this value made, read from `doc` with its writes as an open
303    /// transaction: what history names a change that creates something by
304    /// ("Created ‘Spring plans’"), which `doc` before the value applied could
305    /// not name because the item did not exist yet. `None` when the value
306    /// made no item of its own, or names none itself; the executor then keeps
307    /// the description it read before the value applied.
308    fn made(&self, doc: &Doc) -> Option<crate::entry::ActionItem> {
309        let _ = doc;
310        None
311    }
312
313    /// The actions this value is, one for each step it takes, when it stands for several: an
314    /// undo of three steps is three undos of one, newest first. The executor applies each as an
315    /// action of its own, so every change names the one step it moved, and a peer replays it as
316    /// that one action. Each is its payload under this value's type, with the action it decodes
317    /// to. `None` for a value that is one step, as almost every value is. Read from `doc` before
318    /// anything applies.
319    fn steps(&self, doc: &Doc) -> Option<Vec<ActionStep>> {
320        let _ = doc;
321        None
322    }
323}
324
325/// Whether Undo takes back a value with these facts: it changes the document
326/// alone ([`ActionKind::Undoable`](crate::ActionKind::Undoable)), as a
327/// person's step ([`ChangeKind::is_step`](crate::ChangeKind::is_step)), and
328/// loses nothing Undo cannot bring back ([`Action::irreversible`]). The one
329/// rule every host asks, whatever the value's type.
330#[must_use]
331pub fn undo_takes_back(
332    kind: crate::ActionKind,
333    change: crate::ChangeKind,
334    irreversible: bool,
335) -> bool {
336    kind == crate::ActionKind::Undoable && change.is_step() && !irreversible
337}
338
339/// Whether a value with these facts is confirmed before it applies: its risk
340/// asks for confirmation and Undo cannot take it back
341/// ([`RiskLevel::requires_confirmation_when`](crate::RiskLevel::requires_confirmation_when)).
342#[must_use]
343pub fn asks_first(
344    risk: crate::RiskLevel,
345    kind: crate::ActionKind,
346    change: crate::ChangeKind,
347    irreversible: bool,
348) -> bool {
349    risk.requires_confirmation_when(undo_takes_back(kind, change, irreversible))
350}
351
352/// A serialized action ready to cross a process/network boundary: the
353/// registry `type_id` plus the JSON payload the matching decoder
354/// reconstructs it from.
355#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
356pub struct EncodedAction {
357    pub type_id: String,
358    /// Written as its text where the action is written as text (JSON), and
359    /// as bytes elsewhere: never a list of numbers, one per byte.
360    #[serde(with = "payload_text")]
361    pub payload: Vec<u8>,
362}
363
364/// An action's payload, JSON text, as a string in a format written as text
365/// and as bytes in one that is not.
366mod payload_text {
367    use serde::de::Visitor;
368    use serde::ser::Error as _;
369    use serde::{Deserializer, Serializer};
370
371    pub(super) fn serialize<S: Serializer>(payload: &[u8], into: S) -> Result<S::Ok, S::Error> {
372        if into.is_human_readable() {
373            into.serialize_str(std::str::from_utf8(payload).map_err(S::Error::custom)?)
374        } else {
375            into.serialize_bytes(payload)
376        }
377    }
378
379    pub(super) fn deserialize<'de, D: Deserializer<'de>>(from: D) -> Result<Vec<u8>, D::Error> {
380        struct Payload;
381
382        impl Visitor<'_> for Payload {
383            type Value = Vec<u8>;
384
385            fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
386                formatter.write_str("an action's payload, as text or bytes")
387            }
388
389            fn visit_str<E: serde::de::Error>(self, text: &str) -> Result<Vec<u8>, E> {
390                Ok(text.as_bytes().to_vec())
391            }
392
393            fn visit_string<E: serde::de::Error>(self, text: String) -> Result<Vec<u8>, E> {
394                Ok(text.into_bytes())
395            }
396
397            fn visit_bytes<E: serde::de::Error>(self, bytes: &[u8]) -> Result<Vec<u8>, E> {
398                Ok(bytes.to_vec())
399            }
400
401            fn visit_byte_buf<E: serde::de::Error>(self, bytes: Vec<u8>) -> Result<Vec<u8>, E> {
402                Ok(bytes)
403            }
404        }
405
406        if from.is_human_readable() {
407            from.deserialize_string(Payload)
408        } else {
409            from.deserialize_byte_buf(Payload)
410        }
411    }
412}
413
414impl EncodedAction {
415    /// Serialize a concrete action under a registry `type_id`.
416    ///
417    /// # Errors
418    ///
419    /// Returns [`ActionError::Encode`] if `action` fails to serialize.
420    pub fn encode<A>(type_id: impl Into<String>, action: &A) -> Result<Self, ActionError>
421    where
422        A: Action + Serialize,
423    {
424        Self::encoded(type_id.into(), serde_json::to_vec(action))
425    }
426
427    /// The tail of [`Self::encode`] every action type shares.
428    #[inline(never)]
429    fn encoded(
430        type_id: String,
431        payload: Result<Vec<u8>, serde_json::Error>,
432    ) -> Result<Self, ActionError> {
433        Ok(Self::written(
434            type_id,
435            payload.map_err(ActionError::Encode)?,
436        ))
437    }
438
439    /// An action of `type_id` whose payload is `payload`, a group's written
440    /// with what its members share once ([`crate::group_form`]).
441    #[must_use]
442    pub fn written(type_id: String, payload: Vec<u8>) -> Self {
443        let payload = if crate::group_form::is_group(&type_id) {
444            crate::group_form::compact(&payload).unwrap_or(payload)
445        } else {
446            payload
447        };
448        Self { type_id, payload }
449    }
450
451    /// Serialize a non-document operation payload. Unlike [`Self::encode`],
452    /// this intentionally requires no [`Action`] implementation: effects and
453    /// views are handled by the owning application, not replayed into a CRDT.
454    ///
455    /// # Errors
456    ///
457    /// Returns [`ActionError::Encode`] if `payload` fails to serialize.
458    pub fn encode_operation<T>(type_id: impl Into<String>, payload: &T) -> Result<Self, ActionError>
459    where
460        T: Serialize,
461    {
462        Ok(Self {
463            type_id: type_id.into(),
464            payload: serde_json::to_vec(payload).map_err(ActionError::Encode)?,
465        })
466    }
467}
468
469#[cfg(test)]
470mod action_id_tests {
471    use super::ActionId;
472    use tilo_clock::time::{Duration, UNIX_EPOCH};
473
474    /// The id's time is the clock this process was given, never `std`'s own: an app's model runs
475    /// as a WebAssembly module with no `std` clock to ask, and mints its ids under the host's
476    /// pinned reading.
477    #[test]
478    fn an_id_is_minted_at_the_time_the_process_holds() {
479        let at = UNIX_EPOCH + Duration::from_millis(1_700_000_000_123);
480        let (first, second) =
481            tilo_clock::testing::with_wall(at, || (ActionId::new(), ActionId::new()));
482        for id in [first, second] {
483            let (seconds, nanos) = id.0.get_timestamp().expect("a version 7 id").to_unix();
484            assert_eq!(
485                seconds * 1_000 + u64::from(nanos) / 1_000_000,
486                1_700_000_000_123,
487                "the id carries the time the process holds"
488            );
489        }
490        assert!(first.0 < second.0, "an id sorts after the one before it");
491    }
492}
493
494#[cfg(test)]
495mod operation_kind_tests {
496    use super::OperationKind;
497    use crate::ActionKind;
498
499    /// What a window may report as a change of the person's history: a document or view change,
500    /// or a read the input made. An effect changes nothing a history records, so reporting one
501    /// would ask the broker to admit a change that does not exist.
502    #[test]
503    fn only_a_change_or_a_read_is_reported() {
504        for (kind, need, reported) in [
505            (OperationKind::Document, ActionKind::Undoable, true),
506            (OperationKind::Document, ActionKind::Read, true),
507            (OperationKind::View, ActionKind::Read, true),
508            (OperationKind::View, ActionKind::Outside, true),
509            (OperationKind::Effect, ActionKind::Outside, false),
510            (OperationKind::Effect, ActionKind::Undoable, false),
511            (OperationKind::Effect, ActionKind::Read, true),
512        ] {
513            assert_eq!(kind.reports_a_change(need), reported, "{kind:?}/{need:?}");
514        }
515    }
516
517    /// Only the canonical form round-trips; other spellings are refused.
518    #[test]
519    fn operation_kind_accepts_only_the_canonical_spelling() {
520        for (kind, canonical, lower) in [
521            (OperationKind::Document, "Document", "document"),
522            (OperationKind::Effect, "Effect", "effect"),
523            (OperationKind::View, "View", "view"),
524        ] {
525            assert_eq!(serde_json::to_value(kind).unwrap(), canonical);
526            assert_eq!(
527                serde_json::from_value::<OperationKind>(serde_json::json!(canonical)).unwrap(),
528                kind
529            );
530            assert!(serde_json::from_value::<OperationKind>(serde_json::json!(lower)).is_err());
531        }
532        assert!(serde_json::from_value::<OperationKind>(serde_json::json!("EFFECT")).is_err());
533    }
534}