xmachines-workflow 6.0.0

The record protocol of a statechart run, as serde types: chunks of events, time and work results in, events, snapshots and rejections out, faults as data
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
//! The synchronous step of a run: the [`Stepper`] trait, and [`Run`], the
//! stepper on `xmachines-runtime`. It numbers the chunks, checks their
//! shape, and turns what the runtime gave, or refused, into the chunk's
//! records or its fault. Every chunk gets exactly one terminal outcome of its
//! `seq`: a snapshot, a rejection, or a fault. No clock, no future, no I/O:
//! time is an input.

use std::sync::Arc;

use serde::de::{DeserializeOwned, Deserializer, Error as _};
use serde::ser::Serializer;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use xmachines_runtime::host::LoadOptions;
use xmachines_runtime::work::{ApplyError, Step, DEFAULT_MAX_TIMERS};
use xmachines_runtime::{js_numbers, Actor, EventType, Machine};

use crate::input::{invalid, Chunk};
use crate::record::{Checkpoint, Failure, Fault, FaultCode, Record, Snapshot, Status};
use crate::work::{Action, Invoke, Work};

/// One run, a chunk at a time: what `workflow()` and every host drive.
pub trait Stepper {
    /// One input of a chunk, as the stepper reads it.
    type Input;
    /// What the stepper gives of a chunk.
    type Record;

    /// Applies one chunk, all or nothing, and pushes its records to `out`:
    /// the events it made the machine emit, then its snapshot, or its
    /// rejection. Gives the chunk's `seq`. A fault is the chunk's terminal
    /// outcome, and gave no record: the run goes on after one whose code
    /// [`FaultCode::is_recoverable`], and gives the same fault again of every
    /// chunk after any other.
    fn apply(&mut self, chunk: Chunk<Self::Input>, out: &mut impl Extend<Self::Record>) -> Result<u64, Fault>;

    /// The number of the last chunk read.
    fn seq(&self) -> u64;
}

/// Which snapshots hold the engine's `state`: `"always"`, each; `"never"`,
/// none, as a local view needs none; or a number `n`, those whose `seq` is a
/// multiple of `n`, as a journal keeps one now and then.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Checkpoints {
    /// Each snapshot holds the state.
    #[default]
    Always,
    /// No snapshot holds the state.
    Never,
    /// The snapshots whose `seq` is a multiple of this number, 1 or more.
    Every(u64),
}

impl Checkpoints {
    /// Whether the snapshot of chunk `seq` holds the state.
    pub fn keeps(self, seq: u64) -> bool {
        match self {
            Self::Always => true,
            Self::Never => false,
            Self::Every(n) => n > 0 && seq.is_multiple_of(n),
        }
    }
}

impl Serialize for Checkpoints {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Always => serializer.serialize_str("always"),
            Self::Never => serializer.serialize_str("never"),
            Self::Every(n) => serializer.serialize_u64(*n),
        }
    }
}

impl<'de> Deserialize<'de> for Checkpoints {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = Value::deserialize(deserializer)?;
        match &value {
            Value::String(s) if s == "always" => Ok(Self::Always),
            Value::String(s) if s == "never" => Ok(Self::Never),
            _ => match crate::serde_util::safe_integer(&value) {
                Some(n) if n >= 1 => Ok(Self::Every(n as u64)),
                _ => Err(D::Error::custom("checkpoint is 'always', 'never', or a whole number of chunks, 1 or more")),
            },
        }
    }
}

/// What a run starts or reopens of, beside its machine: the workflow
/// contract's run options. Every field may be left out.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Options {
    /// The root actor's id: `root` by default. A run's own id is the host's.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub actor: Option<String>,
    /// The clock the run starts at, in whole milliseconds, a safe integer: 0
    /// by default. Not read when `from` reopens a run. The runtime starts a
    /// run at a time of 0 or more.
    #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::serde_util::safe_opt")]
    pub time: Option<i64>,
    /// The run's input, of a new run: `null` is kept. A run reopened of a
    /// checkpoint takes none.
    #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::serde_util::present")]
    pub input: Option<Value>,
    /// Which snapshots hold the engine's `state`: each, by default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub checkpoint: Option<Checkpoints>,
    /// How many timers a time input fires at most in a chunk of control
    /// inputs alone: 1000 by default. The run's records depend on it.
    #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::serde_util::whole_opt")]
    pub max_timers: Option<u64>,
    /// The bound of the work of one call, as the runtime's `maxSteps`: its
    /// default by default.
    #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "crate::serde_util::whole_opt")]
    pub max_steps: Option<u64>,
    /// The checkpoint to reopen the run of: it goes on from its state, its
    /// clock and its `seq`, and gives the same records of the same chunks it
    /// gave the first time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub from: Option<Checkpoint>,
}

/// What one chunk did to a run, before any record is made of it: the
/// cheap form of [`Run::step`], which leaves the snapshot to be made when it
/// is asked for ([`Run::snapshot`]).
#[derive(Debug, Clone, PartialEq)]
pub enum Applied {
    /// The chunk applied: the events the root emitted, in order. The run's
    /// state is [`Run::last`] now.
    Applied {
        /// The chunk's number.
        seq: u64,
        /// What the root emitted.
        emitted: Vec<Value>,
    },
    /// The machine rejected the chunk, and the run is as it was.
    Rejected {
        /// The chunk's number.
        seq: u64,
        /// The chunk's inputs.
        batch: Vec<Value>,
        /// Why.
        error: Failure,
    },
}

/// A run of a machine on `xmachines-runtime`, one chunk at a time: the
/// [`Stepper`] of the workflow contract. It applies a chunk with one call of
/// the runtime, which puts the run back itself when it refuses the chunk:
/// the machine is shared and never compiled again.
///
/// The snapshot is lazy: [`Run::step`] gives what a chunk did and keeps the
/// runtime's step; [`Run::snapshot`] makes the snapshot of it, and the
/// engine's `state` only when asked. [`Stepper::apply`] makes the records,
/// with the state at a checkpoint.
///
/// ```
/// use std::sync::Arc;
/// use serde_json::{json, Value};
/// use xmachines_runtime::{Machine, Registry};
/// use xmachines_workflow::{Chunk, Options, Record, Run, Stepper};
///
/// let machine = Arc::new(Machine::<Value, Value>::from_json(
///     &json!({ "initial": "a", "states": { "a": { "on": { "go": { "target": "b" } } }, "b": {} } }),
///     &Registry::new(),
/// ).unwrap());
/// let (mut run, opening) = Run::open(machine, Options::default()).unwrap();
/// assert_eq!(opening.len(), 1);
/// let mut records = Vec::new();
/// let seq = run.apply(Chunk::Batch(vec![json!({ "kind": "time", "now": 5 }), json!({ "type": "go" })]), &mut records).unwrap();
/// let Record::Snapshot { snapshot, .. } = &records[0] else { unreachable!() };
/// assert_eq!((seq, snapshot.value.clone(), snapshot.time), (1, json!("b"), 5));
/// ```
pub struct Run<C = Value, E = Value> {
    actor: Actor<C, E>,
    seq: u64,
    checkpoints: Checkpoints,
    /// The runtime's step after the last chunk that applied, and its `seq`.
    last: Step,
    /// The root's status of `last`.
    status: Status,
    last_seq: u64,
    /// The fault the run can't go on from, once it had one.
    broken: Option<Fault>,
    /// The argument lists of the root's `@xstate.log` actions of the last
    /// chunk that applied.
    logs: Vec<Vec<Value>>,
}

impl<C, E> std::fmt::Debug for Run<C, E> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Run").field("seq", &self.seq).field("last_seq", &self.last_seq).finish_non_exhaustive()
    }
}

/// The root's status of a step of the runtime: a word of no status is the
/// engine's failure, `WORKFLOW_ENGINE_FAILED`.
fn status_of(step: &Step, seq: u64) -> Result<Status, Fault> {
    Status::parse(&step.root.status).ok_or_else(|| {
        Fault::new(
            FaultCode::WorkflowEngineFailed,
            format!("The engine gave a status of no run: {:?}.", step.root.status),
            seq,
        )
    })
}

/// The fault of what the runtime refused as it started or reopened a run.
fn fault_of(error: ApplyError, fallback: FaultCode, seq: u64) -> Fault {
    let code = error.code().and_then(FaultCode::parse).unwrap_or(fallback);
    Fault::new(code, error.message(), seq)
}

impl<C, E> Run<C, E>
where
    C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
    E: EventType + Send + Sync,
{
    /// A run of `machine`, started, or reopened of `options.from`, and its
    /// opening records: the events the root emitted as it started and its
    /// snapshot, of `seq` 0, or the snapshot of the checkpoint it reopened.
    ///
    /// A start whose root fails is `WORKFLOW_MACHINE_FAILED`; a checkpoint
    /// with no `state`, or one the runtime can't restore,
    /// `WORKFLOW_INVALID_SNAPSHOT`; a `maxTimers` or a `checkpoint` of no
    /// whole number of 1 or more, a start time past `2^53 - 1`, or an `input`
    /// beside `from`, `WORKFLOW_INVALID_INPUT`.
    pub fn open(machine: Arc<Machine<C, E>>, options: Options) -> Result<(Self, Vec<Record>), Fault> {
        let invalid = |message: &str| Fault::new(FaultCode::WorkflowInvalidInput, message, 0);
        let max_timers = options.max_timers.unwrap_or(DEFAULT_MAX_TIMERS as u64);
        if max_timers < 1 {
            return Err(invalid("maxTimers is a whole number of timers, 1 or more."));
        }
        let checkpoints = options.checkpoint.unwrap_or_default();
        if checkpoints == Checkpoints::Every(0) {
            return Err(invalid("checkpoint is 'always', 'never', or a whole number of chunks, 1 or more."));
        }
        let mut load = LoadOptions::parse("", true).map_err(|e| invalid(&e))?;
        load.max_timers = usize::try_from(max_timers).unwrap_or(usize::MAX);
        if let Some(max_steps) = options.max_steps {
            load.max_steps = usize::try_from(max_steps).unwrap_or(usize::MAX);
        }
        let (actor, seq, reopened) = match options.from {
            None => {
                let start = xmachines_runtime::host::StartOptions { input: options.input, id: options.actor };
                let time = u64::try_from(options.time.unwrap_or(0))
                    .map_err(|_| invalid("The runtime starts a run at a time of 0 or more."))?;
                let actor =
                    load.start(machine, start, time).map_err(|e| fault_of(e, FaultCode::WorkflowMachineFailed, 0))?;
                (actor, 0, false)
            }
            Some(from) => {
                if options.input.is_some() {
                    return Err(invalid("A reopened run takes no input: it started of one already."));
                }
                let Some(state) = from.snapshot.state else {
                    return Err(Fault::new(
                        FaultCode::WorkflowInvalidSnapshot,
                        "The snapshot holds no state.",
                        from.seq,
                    ));
                };
                let actor = load
                    .restore(machine, &state)
                    .map_err(|e| fault_of(e, FaultCode::WorkflowInvalidSnapshot, from.seq))?;
                (actor, from.seq, true)
            }
        };
        let mut run = Self {
            actor,
            seq,
            checkpoints,
            last: empty_step(),
            status: Status::Active,
            last_seq: seq,
            broken: None,
            logs: Vec::new(),
        };
        let step = run.actor.apply(&[]).map_err(|e| fault_of(e, FaultCode::WorkflowEngineFailed, seq))?;
        run.status = status_of(&step, seq)?;
        run.logs = run.actor.take_logs();
        let mut opening = Vec::new();
        if !reopened {
            opening.extend(step.emitted.iter().map(|event| Record::Event { seq, event: event.clone() }));
        }
        run.last = step;
        opening.push(run.record());
        Ok((run, opening))
    }

    /// A run of an actor a host started or restored itself, as one of a
    /// changelog, migrated to a newer machine: the run goes on from the
    /// actor's state as the run of chunk `seq`, and its snapshots hold the
    /// state as `checkpoints` says. Gives no record: the host has its own of
    /// the actor. An actor whose runtime has broken is
    /// `WORKFLOW_ENGINE_FAILED`.
    pub fn from_actor(mut actor: Actor<C, E>, seq: u64, checkpoints: Checkpoints) -> Result<Self, Fault> {
        let last = actor.apply(&[]).map_err(|e| fault_of(e, FaultCode::WorkflowEngineFailed, seq))?;
        let status = status_of(&last, seq)?;
        let logs = actor.take_logs();
        Ok(Self { actor, seq, checkpoints, last, status, last_seq: seq, broken: None, logs })
    }

    /// Applies one chunk, all or nothing, and says what it did, making no
    /// snapshot: the cheap form, for a host that makes the snapshot only when
    /// it needs one ([`Run::snapshot`]), as a partition of a broker, once per
    /// commit. A fault is as of [`Stepper::apply`].
    pub fn step(&mut self, chunk: &Chunk<Value>) -> Result<Applied, Fault> {
        if let Some(broken) = &self.broken {
            return Err(Fault::new(
                FaultCode::WorkflowEngineFailed,
                format!("The run broke at chunk {}.", broken.seq),
                broken.seq,
            ));
        }
        self.seq += 1;
        let seq = self.seq;
        let batch = chunk.inputs();
        if let Some(why) = batch.iter().find_map(invalid) {
            return Err(Fault::new(FaultCode::WorkflowInvalidInput, format!("Chunk {seq}: {why}."), seq));
        }
        // A typed machine takes the events of its `Event` type alone; JSON takes any.
        if std::any::TypeId::of::<E>() != std::any::TypeId::of::<Value>()
            && batch.iter().any(|input| crate::input::is_event(input) && E::from_json(input.clone()).is_err())
        {
            return Err(Fault::new(
                FaultCode::WorkflowInvalidInput,
                format!("Chunk {seq}: an event is not an event of this machine."),
                seq,
            ));
        }
        match self.actor.apply(batch) {
            Ok(step) => {
                let status = match status_of(&step, seq) {
                    Ok(status) => status,
                    Err(fault) => return Err(self.break_at(fault)),
                };
                let emitted = step.emitted.clone();
                self.status = status;
                self.last = step;
                self.last_seq = seq;
                // Kept of this chunk alone, so a long run holds none of its past.
                self.logs = self.actor.take_logs();
                Ok(Applied::Applied { seq, emitted })
            }
            Err(ApplyError::Rejected { rejected }) => {
                // Time and work are facts, which the runtime never rejects: a rejection of a chunk of
                // them alone is the engine's own failure.
                if !batch.iter().any(crate::input::is_event) {
                    return Err(self.break_at(Fault::new(
                        FaultCode::WorkflowEngineFailed,
                        format!("The engine rejected chunk {seq}, of time and work alone."),
                        seq,
                    )));
                }
                let error = Failure { message: rejected.message, data: rejected.data };
                Ok(Applied::Rejected { seq, batch: batch.to_vec(), error })
            }
            Err(error) => {
                let code = error.code().and_then(FaultCode::parse).unwrap_or(FaultCode::WorkflowEngineFailed);
                let fault = Fault::new(code, format!("Chunk {seq}: {}", error.message()), seq);
                if code.is_recoverable() {
                    Err(fault)
                } else {
                    Err(self.break_at(fault))
                }
            }
        }
    }

    /// Keeps `fault` as the one the run can't go on from.
    fn break_at(&mut self, fault: Fault) -> Fault {
        self.broken = Some(fault.clone());
        fault
    }

    /// The runtime's step after the last chunk that applied, or of the
    /// opening: the root, the time, the deadline and the work, with no
    /// snapshot made.
    pub fn last(&self) -> &Step {
        &self.last
    }

    /// The snapshot of the last chunk that applied, or of the opening, with
    /// the engine's `state` when `with_state`.
    pub fn snapshot(&self, with_state: bool) -> Snapshot {
        let Step { root, time, deadline, work, .. } = &self.last;
        let mut context = root.context.clone();
        js_numbers(&mut context);
        let output = root.output.clone().map(|mut output| {
            js_numbers(&mut output);
            output
        });
        Snapshot {
            status: self.status,
            value: root.value.clone(),
            context,
            output,
            error: root.error.clone().map(|error| {
                serde_json::from_value(error.clone())
                    .unwrap_or_else(|_| Failure { message: error.to_string(), data: Some(error) })
            }),
            time: *time as i64,
            deadline: deadline.map(|d| d as i64),
            work: work.iter().cloned().map(Work::from).collect(),
            state: with_state.then(|| self.actor.persist()),
        }
    }

    /// The snapshot record of the last chunk that applied, with the state
    /// as the run's checkpoint setting has it.
    pub fn record(&self) -> Record {
        let seq = self.last_seq;
        Record::Snapshot { seq, snapshot: Box::new(self.snapshot(self.checkpoints.keeps(seq))) }
    }

    /// The run as a checkpoint now, whatever its checkpoint setting: its
    /// latest snapshot with the engine's `state`, and the number of the last
    /// chunk read, which a run reopens of (`from`).
    pub fn checkpoint(&self) -> Checkpoint {
        Checkpoint { seq: self.seq, snapshot: self.snapshot(true) }
    }

    /// Whether the root would take `event` now: some transition handles it.
    /// It selects by guards alone, never running what a transition does.
    /// An event of a type that starts with `xstate.`, which no caller writes,
    /// and an event a guard of throws on, are never taken. Changes nothing.
    /// A guard that reads the run's children or history answers of the real
    /// state here, while the kit's XState engine answers as if there were
    /// none: such a guard can answer differently in the two.
    pub fn can(&self, event: &Value) -> bool {
        event.get("type").is_some_and(Value::is_string) && self.actor.can_json(event).unwrap_or(false)
    }

    /// The runtime's actor, as a host reads it: its persisted system, by
    /// `persist_view`, written once per commit.
    pub fn actor(&self) -> &Actor<C, E> {
        &self.actor
    }

    /// The argument lists of the root's `@xstate.log` actions of the last
    /// chunk that applied, or of the opening: a run keeps no others.
    pub fn logs(&self) -> &[Vec<Value>] {
        &self.logs
    }

    /// Which snapshots hold the engine's `state`.
    pub fn checkpoints(&self) -> Checkpoints {
        self.checkpoints
    }

    /// How many timers a time input fires at most in a chunk of control
    /// inputs alone, as the run started with it.
    pub fn max_timers(&self) -> usize {
        self.actor.max_timers()
    }
}

impl<C, E> Stepper for Run<C, E>
where
    C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
    E: EventType + Send + Sync,
{
    type Input = Value;
    type Record = Record;

    fn apply(&mut self, chunk: Chunk<Value>, out: &mut impl Extend<Record>) -> Result<u64, Fault> {
        match self.step(&chunk)? {
            Applied::Applied { seq, emitted } => {
                out.extend(emitted.into_iter().map(|event| Record::Event { seq, event }));
                out.extend(std::iter::once(self.record()));
                Ok(seq)
            }
            Applied::Rejected { seq, batch, error } => {
                let batch = batch
                    .into_iter()
                    .map(|input| serde_json::from_value(input).expect("a checked input reads as one"))
                    .collect();
                out.extend(std::iter::once(Record::Rejected { seq, batch, error }));
                Ok(seq)
            }
        }
    }

    fn seq(&self) -> u64 {
        self.seq
    }
}

/// A step of nothing, as a run holds before its opening.
fn empty_step() -> Step {
    Step {
        emitted: Vec::new(),
        root: xmachines_runtime::work::Root {
            status: "active".into(),
            value: Value::Null,
            context: Value::Null,
            output: None,
            error: None,
        },
        time: 0,
        deadline: None,
        work: Vec::new(),
    }
}

impl From<xmachines_runtime::work::Work> for Work {
    fn from(work: xmachines_runtime::work::Work) -> Self {
        match work {
            xmachines_runtime::work::Work::Invoke { id, actor, src, input } => {
                Work::Invoke(Invoke { id, actor, src, input })
            }
            xmachines_runtime::work::Work::Action { id, actor, ty, params } => {
                Work::Action(Action { id, actor, ty, params })
            }
        }
    }
}