Skip to main content

xmachines_workflow/
step.rs

1//! The synchronous step of a run: the [`Stepper`] trait, and [`Run`], the
2//! stepper on `xmachines-runtime`. It numbers the chunks, checks their
3//! shape, and turns what the runtime gave, or refused, into the chunk's
4//! records or its fault. Every chunk gets exactly one terminal outcome of its
5//! `seq`: a snapshot, a rejection, or a fault. No clock, no future, no I/O:
6//! time is an input.
7
8use std::sync::Arc;
9
10use serde::de::{DeserializeOwned, Deserializer, Error as _};
11use serde::ser::Serializer;
12use serde::{Deserialize, Serialize};
13use serde_json::Value;
14use xmachines_runtime::host::LoadOptions;
15use xmachines_runtime::work::{ApplyError, Step, DEFAULT_MAX_TIMERS};
16use xmachines_runtime::{js_numbers, Actor, EventType, Machine};
17
18use crate::input::{invalid, Chunk};
19use crate::record::{Checkpoint, Failure, Fault, FaultCode, Record, Snapshot, Status};
20use crate::work::{Action, Invoke, Work};
21
22/// One run, a chunk at a time: what `workflow()` and every host drive.
23pub trait Stepper {
24    /// One input of a chunk, as the stepper reads it.
25    type Input;
26    /// What the stepper gives of a chunk.
27    type Record;
28
29    /// Applies one chunk, all or nothing, and pushes its records to `out`:
30    /// the events it made the machine emit, then its snapshot, or its
31    /// rejection. Gives the chunk's `seq`. A fault is the chunk's terminal
32    /// outcome, and gave no record: the run goes on after one whose code
33    /// [`FaultCode::is_recoverable`], and gives the same fault again of every
34    /// chunk after any other.
35    fn apply(&mut self, chunk: Chunk<Self::Input>, out: &mut impl Extend<Self::Record>) -> Result<u64, Fault>;
36
37    /// The number of the last chunk read.
38    fn seq(&self) -> u64;
39}
40
41/// Which snapshots hold the engine's `state`: `"always"`, each; `"never"`,
42/// none, as a local view needs none; or a number `n`, those whose `seq` is a
43/// multiple of `n`, as a journal keeps one now and then.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
45pub enum Checkpoints {
46    /// Each snapshot holds the state.
47    #[default]
48    Always,
49    /// No snapshot holds the state.
50    Never,
51    /// The snapshots whose `seq` is a multiple of this number, 1 or more.
52    Every(u64),
53}
54
55impl Checkpoints {
56    /// Whether the snapshot of chunk `seq` holds the state.
57    pub fn keeps(self, seq: u64) -> bool {
58        match self {
59            Self::Always => true,
60            Self::Never => false,
61            Self::Every(n) => n > 0 && seq.is_multiple_of(n),
62        }
63    }
64}
65
66impl Serialize for Checkpoints {
67    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
68        match self {
69            Self::Always => serializer.serialize_str("always"),
70            Self::Never => serializer.serialize_str("never"),
71            Self::Every(n) => serializer.serialize_u64(*n),
72        }
73    }
74}
75
76impl<'de> Deserialize<'de> for Checkpoints {
77    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
78        let value = Value::deserialize(deserializer)?;
79        match &value {
80            Value::String(s) if s == "always" => Ok(Self::Always),
81            Value::String(s) if s == "never" => Ok(Self::Never),
82            _ => match crate::serde_util::safe_integer(&value) {
83                Some(n) if n >= 1 => Ok(Self::Every(n as u64)),
84                _ => Err(D::Error::custom("checkpoint is 'always', 'never', or a whole number of chunks, 1 or more")),
85            },
86        }
87    }
88}
89
90/// What a run starts or reopens of, beside its machine: the workflow
91/// contract's run options. Every field may be left out.
92#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
93#[serde(rename_all = "camelCase", deny_unknown_fields)]
94pub struct Options {
95    /// The root actor's id: `root` by default. A run's own id is the host's.
96    #[serde(default, skip_serializing_if = "Option::is_none")]
97    pub actor: Option<String>,
98    /// The clock the run starts at, in whole milliseconds, a safe integer: 0
99    /// by default. Not read when `from` reopens a run. The runtime starts a
100    /// run at a time of 0 or more.
101    #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::serde_util::safe_opt")]
102    pub time: Option<i64>,
103    /// The run's input, of a new run: `null` is kept. A run reopened of a
104    /// checkpoint takes none.
105    #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::serde_util::present")]
106    pub input: Option<Value>,
107    /// Which snapshots hold the engine's `state`: each, by default.
108    #[serde(default, skip_serializing_if = "Option::is_none")]
109    pub checkpoint: Option<Checkpoints>,
110    /// How many timers a time input fires at most in a chunk of control
111    /// inputs alone: 1000 by default. The run's records depend on it.
112    #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::serde_util::whole_opt")]
113    pub max_timers: Option<u64>,
114    /// The bound of the work of one call, as the runtime's `maxSteps`: its
115    /// default by default.
116    #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::serde_util::whole_opt")]
117    pub max_steps: Option<u64>,
118    /// The checkpoint to reopen the run of: it goes on from its state, its
119    /// clock and its `seq`, and gives the same records of the same chunks it
120    /// gave the first time.
121    #[serde(default, skip_serializing_if = "Option::is_none")]
122    pub from: Option<Checkpoint>,
123}
124
125/// What one chunk did to a run, before any record is made of it: the
126/// cheap form of [`Run::step`], which leaves the snapshot to be made when it
127/// is asked for ([`Run::snapshot`]).
128#[derive(Debug, Clone, PartialEq)]
129pub enum Applied {
130    /// The chunk applied: the events the root emitted, in order. The run's
131    /// state is [`Run::last`] now.
132    Applied {
133        /// The chunk's number.
134        seq: u64,
135        /// What the root emitted.
136        emitted: Vec<Value>,
137    },
138    /// The machine rejected the chunk, and the run is as it was.
139    Rejected {
140        /// The chunk's number.
141        seq: u64,
142        /// The chunk's inputs.
143        batch: Vec<Value>,
144        /// Why.
145        error: Failure,
146    },
147}
148
149/// A run of a machine on `xmachines-runtime`, one chunk at a time: the
150/// [`Stepper`] of the workflow contract. It applies a chunk with one call of
151/// the runtime, which puts the run back itself when it refuses the chunk:
152/// the machine is shared and never compiled again.
153///
154/// The snapshot is lazy: [`Run::step`] gives what a chunk did and keeps the
155/// runtime's step; [`Run::snapshot`] makes the snapshot of it, and the
156/// engine's `state` only when asked. [`Stepper::apply`] makes the records,
157/// with the state at a checkpoint.
158///
159/// ```
160/// use std::sync::Arc;
161/// use serde_json::{json, Value};
162/// use xmachines_runtime::{Machine, Registry};
163/// use xmachines_workflow::{Chunk, Options, Record, Run, Stepper};
164///
165/// let machine = Arc::new(Machine::<Value, Value>::from_json(
166///     &json!({ "initial": "a", "states": { "a": { "on": { "go": { "target": "b" } } }, "b": {} } }),
167///     &Registry::new(),
168/// ).unwrap());
169/// let (mut run, opening) = Run::open(machine, Options::default()).unwrap();
170/// assert_eq!(opening.len(), 1);
171/// let mut records = Vec::new();
172/// let seq = run.apply(Chunk::Batch(vec![json!({ "kind": "time", "now": 5 }), json!({ "type": "go" })]), &mut records).unwrap();
173/// let Record::Snapshot { snapshot, .. } = &records[0] else { unreachable!() };
174/// assert_eq!((seq, snapshot.value.clone(), snapshot.time), (1, json!("b"), 5));
175/// ```
176pub struct Run<C = Value, E = Value> {
177    actor: Actor<C, E>,
178    seq: u64,
179    checkpoints: Checkpoints,
180    /// The runtime's step after the last chunk that applied, and its `seq`.
181    last: Step,
182    /// The root's status of `last`.
183    status: Status,
184    last_seq: u64,
185    /// The fault the run can't go on from, once it had one.
186    broken: Option<Fault>,
187    /// The argument lists of the root's `@xstate.log` actions of the last
188    /// chunk that applied.
189    logs: Vec<Vec<Value>>,
190}
191
192impl<C, E> std::fmt::Debug for Run<C, E> {
193    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
194        f.debug_struct("Run").field("seq", &self.seq).field("last_seq", &self.last_seq).finish_non_exhaustive()
195    }
196}
197
198/// The root's status of a step of the runtime: a word of no status is the
199/// engine's failure, `WORKFLOW_ENGINE_FAILED`.
200fn status_of(step: &Step, seq: u64) -> Result<Status, Fault> {
201    Status::parse(&step.root.status).ok_or_else(|| {
202        Fault::new(
203            FaultCode::WorkflowEngineFailed,
204            format!("The engine gave a status of no run: {:?}.", step.root.status),
205            seq,
206        )
207    })
208}
209
210/// The fault of what the runtime refused as it started or reopened a run.
211fn fault_of(error: ApplyError, fallback: FaultCode, seq: u64) -> Fault {
212    let code = error.code().and_then(FaultCode::parse).unwrap_or(fallback);
213    Fault::new(code, error.message(), seq)
214}
215
216impl<C, E> Run<C, E>
217where
218    C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
219    E: EventType + Send + Sync,
220{
221    /// A run of `machine`, started, or reopened of `options.from`, and its
222    /// opening records: the events the root emitted as it started and its
223    /// snapshot, of `seq` 0, or the snapshot of the checkpoint it reopened.
224    ///
225    /// A start whose root fails is `WORKFLOW_MACHINE_FAILED`; a checkpoint
226    /// with no `state`, or one the runtime can't restore,
227    /// `WORKFLOW_INVALID_SNAPSHOT`; a `maxTimers` or a `checkpoint` of no
228    /// whole number of 1 or more, a start time past `2^53 - 1`, or an `input`
229    /// beside `from`, `WORKFLOW_INVALID_INPUT`.
230    pub fn open(machine: Arc<Machine<C, E>>, options: Options) -> Result<(Self, Vec<Record>), Fault> {
231        let invalid = |message: &str| Fault::new(FaultCode::WorkflowInvalidInput, message, 0);
232        let max_timers = options.max_timers.unwrap_or(DEFAULT_MAX_TIMERS as u64);
233        if max_timers < 1 {
234            return Err(invalid("maxTimers is a whole number of timers, 1 or more."));
235        }
236        let checkpoints = options.checkpoint.unwrap_or_default();
237        if checkpoints == Checkpoints::Every(0) {
238            return Err(invalid("checkpoint is 'always', 'never', or a whole number of chunks, 1 or more."));
239        }
240        let mut load = LoadOptions::parse("", true).map_err(|e| invalid(&e))?;
241        load.max_timers = usize::try_from(max_timers).unwrap_or(usize::MAX);
242        if let Some(max_steps) = options.max_steps {
243            load.max_steps = usize::try_from(max_steps).unwrap_or(usize::MAX);
244        }
245        let (actor, seq, reopened) = match options.from {
246            None => {
247                let start = xmachines_runtime::host::StartOptions { input: options.input, id: options.actor };
248                let time = u64::try_from(options.time.unwrap_or(0))
249                    .map_err(|_| invalid("The runtime starts a run at a time of 0 or more."))?;
250                let actor =
251                    load.start(machine, start, time).map_err(|e| fault_of(e, FaultCode::WorkflowMachineFailed, 0))?;
252                (actor, 0, false)
253            }
254            Some(from) => {
255                if options.input.is_some() {
256                    return Err(invalid("A reopened run takes no input: it started of one already."));
257                }
258                let Some(state) = from.snapshot.state else {
259                    return Err(Fault::new(
260                        FaultCode::WorkflowInvalidSnapshot,
261                        "The snapshot holds no state.",
262                        from.seq,
263                    ));
264                };
265                let actor = load
266                    .restore(machine, &state)
267                    .map_err(|e| fault_of(e, FaultCode::WorkflowInvalidSnapshot, from.seq))?;
268                (actor, from.seq, true)
269            }
270        };
271        let mut run = Self {
272            actor,
273            seq,
274            checkpoints,
275            last: empty_step(),
276            status: Status::Active,
277            last_seq: seq,
278            broken: None,
279            logs: Vec::new(),
280        };
281        let step = run.actor.apply(&[]).map_err(|e| fault_of(e, FaultCode::WorkflowEngineFailed, seq))?;
282        run.status = status_of(&step, seq)?;
283        run.logs = run.actor.take_logs();
284        let mut opening = Vec::new();
285        if !reopened {
286            opening.extend(step.emitted.iter().map(|event| Record::Event { seq, event: event.clone() }));
287        }
288        run.last = step;
289        opening.push(run.record());
290        Ok((run, opening))
291    }
292
293    /// A run of an actor a host started or restored itself, as one of a
294    /// changelog, migrated to a newer machine: the run goes on from the
295    /// actor's state as the run of chunk `seq`, and its snapshots hold the
296    /// state as `checkpoints` says. Gives no record: the host has its own of
297    /// the actor. An actor whose runtime has broken is
298    /// `WORKFLOW_ENGINE_FAILED`.
299    pub fn from_actor(mut actor: Actor<C, E>, seq: u64, checkpoints: Checkpoints) -> Result<Self, Fault> {
300        let last = actor.apply(&[]).map_err(|e| fault_of(e, FaultCode::WorkflowEngineFailed, seq))?;
301        let status = status_of(&last, seq)?;
302        let logs = actor.take_logs();
303        Ok(Self { actor, seq, checkpoints, last, status, last_seq: seq, broken: None, logs })
304    }
305
306    /// Applies one chunk, all or nothing, and says what it did, making no
307    /// snapshot: the cheap form, for a host that makes the snapshot only when
308    /// it needs one ([`Run::snapshot`]), as a partition of a broker, once per
309    /// commit. A fault is as of [`Stepper::apply`].
310    pub fn step(&mut self, chunk: &Chunk<Value>) -> Result<Applied, Fault> {
311        if let Some(broken) = &self.broken {
312            return Err(Fault::new(
313                FaultCode::WorkflowEngineFailed,
314                format!("The run broke at chunk {}.", broken.seq),
315                broken.seq,
316            ));
317        }
318        self.seq += 1;
319        let seq = self.seq;
320        let batch = chunk.inputs();
321        if let Some(why) = batch.iter().find_map(invalid) {
322            return Err(Fault::new(FaultCode::WorkflowInvalidInput, format!("Chunk {seq}: {why}."), seq));
323        }
324        // A typed machine takes the events of its `Event` type alone; JSON takes any.
325        if std::any::TypeId::of::<E>() != std::any::TypeId::of::<Value>()
326            && batch.iter().any(|input| crate::input::is_event(input) && E::from_json(input.clone()).is_err())
327        {
328            return Err(Fault::new(
329                FaultCode::WorkflowInvalidInput,
330                format!("Chunk {seq}: an event is not an event of this machine."),
331                seq,
332            ));
333        }
334        match self.actor.apply(batch) {
335            Ok(step) => {
336                let status = match status_of(&step, seq) {
337                    Ok(status) => status,
338                    Err(fault) => return Err(self.break_at(fault)),
339                };
340                let emitted = step.emitted.clone();
341                self.status = status;
342                self.last = step;
343                self.last_seq = seq;
344                // Kept of this chunk alone, so a long run holds none of its past.
345                self.logs = self.actor.take_logs();
346                Ok(Applied::Applied { seq, emitted })
347            }
348            Err(ApplyError::Rejected { rejected }) => {
349                // Time and work are facts, which the runtime never rejects: a rejection of a chunk of
350                // them alone is the engine's own failure.
351                if !batch.iter().any(crate::input::is_event) {
352                    return Err(self.break_at(Fault::new(
353                        FaultCode::WorkflowEngineFailed,
354                        format!("The engine rejected chunk {seq}, of time and work alone."),
355                        seq,
356                    )));
357                }
358                let error = Failure { message: rejected.message, data: rejected.data };
359                Ok(Applied::Rejected { seq, batch: batch.to_vec(), error })
360            }
361            Err(error) => {
362                let code = error.code().and_then(FaultCode::parse).unwrap_or(FaultCode::WorkflowEngineFailed);
363                let fault = Fault::new(code, format!("Chunk {seq}: {}", error.message()), seq);
364                if code.is_recoverable() {
365                    Err(fault)
366                } else {
367                    Err(self.break_at(fault))
368                }
369            }
370        }
371    }
372
373    /// Keeps `fault` as the one the run can't go on from.
374    fn break_at(&mut self, fault: Fault) -> Fault {
375        self.broken = Some(fault.clone());
376        fault
377    }
378
379    /// The runtime's step after the last chunk that applied, or of the
380    /// opening: the root, the time, the deadline and the work, with no
381    /// snapshot made.
382    pub fn last(&self) -> &Step {
383        &self.last
384    }
385
386    /// The snapshot of the last chunk that applied, or of the opening, with
387    /// the engine's `state` when `with_state`.
388    pub fn snapshot(&self, with_state: bool) -> Snapshot {
389        let Step { root, time, deadline, work, .. } = &self.last;
390        let mut context = root.context.clone();
391        js_numbers(&mut context);
392        let output = root.output.clone().map(|mut output| {
393            js_numbers(&mut output);
394            output
395        });
396        Snapshot {
397            status: self.status,
398            value: root.value.clone(),
399            context,
400            output,
401            error: root.error.clone().map(|error| {
402                serde_json::from_value(error.clone())
403                    .unwrap_or_else(|_| Failure { message: error.to_string(), data: Some(error) })
404            }),
405            time: *time as i64,
406            deadline: deadline.map(|d| d as i64),
407            work: work.iter().cloned().map(Work::from).collect(),
408            state: with_state.then(|| self.actor.persist()),
409        }
410    }
411
412    /// The snapshot record of the last chunk that applied, with the state
413    /// as the run's checkpoint setting has it.
414    pub fn record(&self) -> Record {
415        let seq = self.last_seq;
416        Record::Snapshot { seq, snapshot: Box::new(self.snapshot(self.checkpoints.keeps(seq))) }
417    }
418
419    /// The run as a checkpoint now, whatever its checkpoint setting: its
420    /// latest snapshot with the engine's `state`, and the number of the last
421    /// chunk read, which a run reopens of (`from`).
422    pub fn checkpoint(&self) -> Checkpoint {
423        Checkpoint { seq: self.seq, snapshot: self.snapshot(true) }
424    }
425
426    /// Whether the root would take `event` now: some transition handles it.
427    /// It selects by guards alone, never running what a transition does.
428    /// An event of a type that starts with `xstate.`, which no caller writes,
429    /// and an event a guard of throws on, are never taken. Changes nothing.
430    /// A guard that reads the run's children or history answers of the real
431    /// state here, while the kit's XState engine answers as if there were
432    /// none: such a guard can answer differently in the two.
433    pub fn can(&self, event: &Value) -> bool {
434        event.get("type").is_some_and(Value::is_string) && self.actor.can_json(event).unwrap_or(false)
435    }
436
437    /// The runtime's actor, as a host reads it: its persisted system, by
438    /// `persist_view`, written once per commit.
439    pub fn actor(&self) -> &Actor<C, E> {
440        &self.actor
441    }
442
443    /// The argument lists of the root's `@xstate.log` actions of the last
444    /// chunk that applied, or of the opening: a run keeps no others.
445    pub fn logs(&self) -> &[Vec<Value>] {
446        &self.logs
447    }
448
449    /// Which snapshots hold the engine's `state`.
450    pub fn checkpoints(&self) -> Checkpoints {
451        self.checkpoints
452    }
453
454    /// How many timers a time input fires at most in a chunk of control
455    /// inputs alone, as the run started with it.
456    pub fn max_timers(&self) -> usize {
457        self.actor.max_timers()
458    }
459}
460
461impl<C, E> Stepper for Run<C, E>
462where
463    C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
464    E: EventType + Send + Sync,
465{
466    type Input = Value;
467    type Record = Record;
468
469    fn apply(&mut self, chunk: Chunk<Value>, out: &mut impl Extend<Record>) -> Result<u64, Fault> {
470        match self.step(&chunk)? {
471            Applied::Applied { seq, emitted } => {
472                out.extend(emitted.into_iter().map(|event| Record::Event { seq, event }));
473                out.extend(std::iter::once(self.record()));
474                Ok(seq)
475            }
476            Applied::Rejected { seq, batch, error } => {
477                let batch = batch
478                    .into_iter()
479                    .map(|input| serde_json::from_value(input).expect("a checked input reads as one"))
480                    .collect();
481                out.extend(std::iter::once(Record::Rejected { seq, batch, error }));
482                Ok(seq)
483            }
484        }
485    }
486
487    fn seq(&self) -> u64 {
488        self.seq
489    }
490}
491
492/// A step of nothing, as a run holds before its opening.
493fn empty_step() -> Step {
494    Step {
495        emitted: Vec::new(),
496        root: xmachines_runtime::work::Root {
497            status: "active".into(),
498            value: Value::Null,
499            context: Value::Null,
500            output: None,
501            error: None,
502        },
503        time: 0,
504        deadline: None,
505        work: Vec::new(),
506    }
507}
508
509impl From<xmachines_runtime::work::Work> for Work {
510    fn from(work: xmachines_runtime::work::Work) -> Self {
511        match work {
512            xmachines_runtime::work::Work::Invoke { id, actor, src, input } => {
513                Work::Invoke(Invoke { id, actor, src, input })
514            }
515            xmachines_runtime::work::Work::Action { id, actor, ty, params } => {
516                Work::Action(Action { id, actor, ty, params })
517            }
518        }
519    }
520}