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