Skip to main content

xmachines_workflow/
record.rs

1//! What a run gives, on one ordered stream, told apart by `kind`
2//! ([`Record`]): each event the machine emits, its snapshot after each chunk
3//! ([`Snapshot`]), and each chunk it rejects. A fault of the runner itself is
4//! data too ([`Fault`]), so it can cross a socket or a WIT. A run reopens of
5//! a [`Checkpoint`], and a stream of many runs carries each value in an
6//! [`Envelope`].
7
8use std::fmt;
9
10use serde::{Deserialize, Serialize};
11use serde_json::Value;
12
13use crate::input::Input;
14use crate::serde_util::{present, safe, safe_opt, whole};
15use crate::work::Work;
16
17/// Where the machine's root is: running, finished, failed, or stopped.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
19#[serde(rename_all = "lowercase")]
20pub enum Status {
21    /// Running.
22    Active,
23    /// Finished, with its output.
24    Done,
25    /// Failed, with its error.
26    Error,
27    /// Stopped.
28    Stopped,
29}
30
31impl Status {
32    /// The status as the protocol writes it: `active`, `done`, `error` or
33    /// `stopped`. `None` of another word.
34    pub fn parse(status: &str) -> Option<Self> {
35        Some(match status {
36            "active" => Self::Active,
37            "done" => Self::Done,
38            "error" => Self::Error,
39            "stopped" => Self::Stopped,
40            _ => return None,
41        })
42    }
43
44    /// The word the protocol writes.
45    pub fn as_str(self) -> &'static str {
46        match self {
47            Self::Active => "active",
48            Self::Done => "done",
49            Self::Error => "error",
50            Self::Stopped => "stopped",
51        }
52    }
53}
54
55/// Why the machine failed, as JSON: the message of what it threw, and the
56/// value itself as `data` where it was no error and no string. A rejection
57/// and a root in `error` give the same shape.
58#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
59pub struct Failure {
60    /// The message of what failed.
61    pub message: String,
62    /// The value the machine failed with, when it is no error or string:
63    /// `null` is kept.
64    #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "present")]
65    pub data: Option<Value>,
66}
67
68impl Failure {
69    /// A failure of `message` alone.
70    pub fn new(message: impl Into<String>) -> Self {
71        Self { message: message.into(), data: None }
72    }
73}
74
75/// The state of a run after a chunk: where the machine is, and what it needs
76/// from the host next. Every value is JSON. `state`, the engine's own, is
77/// there only at a checkpoint, and reopens the run on any engine that reads
78/// the same format.
79///
80/// `Ctx`, `Val`, `W` and `Out` are the machine's context, state value, work
81/// and output: JSON and the loose [`Work`] by default, or the types
82/// `xmachines-build` generates.
83#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
84#[serde(bound(
85    serialize = "Ctx: Serialize, Val: Serialize, W: Serialize, Out: Serialize",
86    deserialize = "Ctx: Deserialize<'de>, Val: Deserialize<'de>, W: Deserialize<'de>, Out: Deserialize<'de>"
87))]
88pub struct Snapshot<Ctx = Value, Val = Value, W = Work, Out = Value> {
89    /// Where the root is.
90    pub status: Status,
91    /// The state value, as `"idle"` or `{ "door": "open" }`.
92    pub value: Val,
93    /// The context.
94    pub context: Ctx,
95    /// What the machine gave when it finished, of `done`: `null` is kept.
96    #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "present")]
97    pub output: Option<Out>,
98    /// Why the machine failed, of `error`.
99    #[serde(default, skip_serializing_if = "Option::is_none")]
100    pub error: Option<Failure>,
101    /// The time the run reached, in whole milliseconds, a safe integer of
102    /// either sign.
103    #[serde(deserialize_with = "safe")]
104    pub time: i64,
105    /// When the next timer is due: write a time input of it then. None, of
106    /// no timer.
107    #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "safe_opt")]
108    pub deadline: Option<i64>,
109    /// The work the machine waits for, invoked work and host actions, in the
110    /// order it started.
111    pub work: Vec<W>,
112    /// The engine's persisted state, at a checkpoint alone.
113    #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "present")]
114    pub state: Option<Value>,
115}
116
117/// What a run gives, in the order it happened: the events each chunk made
118/// the machine emit, then its snapshot, or the chunk's rejection. Each chunk
119/// has exactly one terminal outcome of its `seq`: a snapshot, a rejection, or
120/// a [`Fault`]. Branch on `kind`, never on an event's `type`.
121///
122/// `Em`, `Snap` and `In` are what the machine emits, its snapshot and its
123/// inputs: JSON, the loose [`Snapshot`] and [`Input`] by default.
124#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
125#[serde(tag = "kind", rename_all = "lowercase")]
126pub enum Record<Em = Value, Snap = Snapshot, In = Input> {
127    /// An event the machine emitted, as it emitted it, while it applied chunk
128    /// `seq`.
129    Event {
130        /// The chunk's number.
131        #[serde(deserialize_with = "whole")]
132        seq: u64,
133        /// The event.
134        event: Em,
135    },
136    /// The run's state once chunk `seq` was applied: the chunk's terminal
137    /// outcome. A run gives one as it starts, of `seq` 0, or of the
138    /// checkpoint it reopened, and one after each chunk it applies.
139    Snapshot {
140        /// The chunk's number.
141        #[serde(deserialize_with = "whole")]
142        seq: u64,
143        /// The run's state.
144        snapshot: Box<Snap>,
145    },
146    /// A chunk the machine rejected: an event in it made a guard or an action
147    /// throw, or put the root in `error`. The chunk's terminal outcome: the
148    /// run is as it was before the chunk, and goes on.
149    Rejected {
150        /// The chunk's number.
151        #[serde(deserialize_with = "whole")]
152        seq: u64,
153        /// The chunk's inputs.
154        batch: Vec<In>,
155        /// Why.
156        error: Failure,
157    },
158}
159
160impl<Em, Snap, In> Record<Em, Snap, In> {
161    /// The number of the chunk the record is of.
162    pub fn seq(&self) -> u64 {
163        match self {
164            Self::Event { seq, .. } | Self::Snapshot { seq, .. } | Self::Rejected { seq, .. } => *seq,
165        }
166    }
167
168    /// Whether the record is its chunk's terminal outcome: a snapshot or a
169    /// rejection.
170    pub fn is_terminal(&self) -> bool {
171        !matches!(self, Self::Event { .. })
172    }
173}
174
175/// The stable code of a [`Fault`], which a caller matches on, and never the
176/// message: the codes of the workflow contract.
177#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
178#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
179pub enum FaultCode {
180    /// A chunk that is no input, nor a batch of inputs.
181    WorkflowInvalidInput,
182    /// A result of the other kind of work: `done` of invoked work, or
183    /// `resolved` or `rejected` of a host action.
184    WorkflowInvalidWorkResult,
185    /// A machine the engine can't load.
186    WorkflowInvalidMachine,
187    /// A snapshot to reopen of a state the engine can't restore.
188    WorkflowInvalidSnapshot,
189    /// A machine whose own code threw as it started, so the run has no state
190    /// to go on from.
191    WorkflowMachineFailed,
192    /// An engine that failed outside a step of the machine, so the run can't
193    /// go on.
194    WorkflowEngineFailed,
195    /// An edit of a machine's definition that can't apply.
196    WorkflowInvalidEdit,
197    /// A journal a host can't reopen a run of.
198    WorkflowInvalidJournal,
199    /// A journal whose append failed.
200    WorkflowJournalFailed,
201    /// A journal that refused an append of a writer behind another.
202    WorkflowJournalFenced,
203    /// A run its runner does not know.
204    WorkflowRunNotFound,
205    /// A write to a host that is closed.
206    WorkflowClosed,
207    /// A run another holder has, whose lease the claim did not get.
208    WorkflowLeaseRefused,
209    /// A lease whose release failed as its run closed.
210    WorkflowLeaseFailed,
211    /// A handler of a host action that failed: the host tries it again.
212    WorkflowHostActionFailed,
213    /// A host's durable wake that failed to set or clear.
214    WorkflowWakeFailed,
215    /// A listener of a store that failed as it heard of a record.
216    WorkflowListenerFailed,
217}
218
219impl FaultCode {
220    /// Whether the run goes on after a fault of this code, which is then its
221    /// chunk's terminal outcome: an input that is no input, or a result of
222    /// the other kind of work.
223    pub fn is_recoverable(self) -> bool {
224        matches!(self, Self::WorkflowInvalidInput | Self::WorkflowInvalidWorkResult)
225    }
226
227    /// The code as the protocol writes it, as `WORKFLOW_INVALID_INPUT`.
228    pub fn as_str(self) -> &'static str {
229        match self {
230            Self::WorkflowInvalidInput => "WORKFLOW_INVALID_INPUT",
231            Self::WorkflowInvalidWorkResult => "WORKFLOW_INVALID_WORK_RESULT",
232            Self::WorkflowInvalidMachine => "WORKFLOW_INVALID_MACHINE",
233            Self::WorkflowInvalidSnapshot => "WORKFLOW_INVALID_SNAPSHOT",
234            Self::WorkflowMachineFailed => "WORKFLOW_MACHINE_FAILED",
235            Self::WorkflowEngineFailed => "WORKFLOW_ENGINE_FAILED",
236            Self::WorkflowInvalidEdit => "WORKFLOW_INVALID_EDIT",
237            Self::WorkflowInvalidJournal => "WORKFLOW_INVALID_JOURNAL",
238            Self::WorkflowJournalFailed => "WORKFLOW_JOURNAL_FAILED",
239            Self::WorkflowJournalFenced => "WORKFLOW_JOURNAL_FENCED",
240            Self::WorkflowRunNotFound => "WORKFLOW_RUN_NOT_FOUND",
241            Self::WorkflowClosed => "WORKFLOW_CLOSED",
242            Self::WorkflowLeaseRefused => "WORKFLOW_LEASE_REFUSED",
243            Self::WorkflowLeaseFailed => "WORKFLOW_LEASE_FAILED",
244            Self::WorkflowHostActionFailed => "WORKFLOW_HOST_ACTION_FAILED",
245            Self::WorkflowWakeFailed => "WORKFLOW_WAKE_FAILED",
246            Self::WorkflowListenerFailed => "WORKFLOW_LISTENER_FAILED",
247        }
248    }
249
250    /// The code of the protocol's word, as `WORKFLOW_INVALID_INPUT`. `None`
251    /// of another word.
252    pub fn parse(code: &str) -> Option<Self> {
253        serde_json::from_value(Value::String(code.to_owned())).ok()
254    }
255}
256
257impl fmt::Display for FaultCode {
258    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
259        f.write_str(self.as_str())
260    }
261}
262
263/// A fault of the runner, never of the machine, as data: a chunk that is no
264/// input, a result of the other kind of work, or a run that can't go on. It
265/// is the terminal outcome of chunk `seq`, which then gave no record.
266#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
267#[serde(deny_unknown_fields)]
268pub struct Fault {
269    /// What kind of fault, which a caller matches on.
270    pub code: FaultCode,
271    /// Why, for a person. It never holds an event's data.
272    pub message: String,
273    /// The chunk the fault is of; 0 of one before any chunk.
274    #[serde(deserialize_with = "whole")]
275    pub seq: u64,
276}
277
278impl Fault {
279    /// A fault of `code` and `message`, of chunk `seq`.
280    pub fn new(code: FaultCode, message: impl Into<String>, seq: u64) -> Self {
281        Self { code, message: message.into(), seq }
282    }
283}
284
285impl fmt::Display for Fault {
286    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287        write!(f, "{}: {}", self.code, self.message)
288    }
289}
290
291impl std::error::Error for Fault {}
292
293/// Where a run reopens: a snapshot that holds the engine's `state`, and
294/// `seq`, the last chunk the run had read. A snapshot record of a checkpoint
295/// is one; a host that read chunks after it that gave no snapshot, as
296/// rejected ones, passes their last `seq` beside it.
297#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
298pub struct Checkpoint<Snap = Snapshot> {
299    /// The last chunk the run had read.
300    #[serde(deserialize_with = "whole")]
301    pub seq: u64,
302    /// The snapshot, with the engine's `state`.
303    pub snapshot: Snap,
304}
305
306/// A value of one run among many, on one stream: the run's id beside the
307/// value. A run's id is the host's, apart from its root actor's id.
308#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
309pub struct Envelope<V> {
310    /// The run's id.
311    pub run: String,
312    /// The chunk, the record or the fault.
313    pub value: V,
314    /// Of a record a runner gives again as it opens a run, of a chunk its
315    /// journal holds already: a sink publishes it again, and a clock or a
316    /// worker never reads it. Written only when it is `true`.
317    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
318    pub replayed: bool,
319    /// The key a runner opened the run by, so a sink names the run as its
320    /// source did.
321    #[serde(default, skip_serializing_if = "Option::is_none")]
322    pub key: Option<String>,
323}