xmachines_runtime/work.rs
1//! The workflow contract's shapes, as an [`crate::Actor`] takes and gives
2//! them: the inputs of a chunk ([`Input`]), the work a run waits for
3//! ([`Work`]), what one chunk gives ([`Step`]), and the error that refuses a
4//! chunk ([`ApplyError`]), a rejection of the run or a fault of the runner.
5//!
6//! A control input has a `kind` of `time` or `work`, and never a `type`:
7//! `{ "kind": "time", "now" }` moves the clock, and
8//! `{ "kind": "work", "id", "outcome", "data"? }` settles work the run waits
9//! for. Anything else with a string `type` is an event. Time is a whole
10//! number of milliseconds, a safe integer of JavaScript (at most `2^53 - 1`
11//! either way), so that it is the same number there.
12
13use std::fmt;
14
15use serde::{Deserialize, Serialize};
16use serde_json::{Map, Value};
17
18/// The largest whole number a JavaScript number holds exactly, `2^53 - 1`:
19/// the largest time an input may carry, either way.
20pub const MAX_TIME: u64 = (1 << 53) - 1;
21
22/// How many timers a time input fires at most in a chunk of control inputs
23/// alone, of no other bound ([`crate::Actor::set_max_timers`]), as the
24/// workflow contract's default `maxTimers`.
25pub const DEFAULT_MAX_TIMERS: usize = 1000;
26
27/// How work ends: invoked work is `resolved` or `rejected`, a host action is
28/// `done`.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
30#[serde(rename_all = "lowercase")]
31pub enum Outcome {
32 /// Invoked work finished with its output in `data`.
33 Resolved,
34 /// Invoked work failed with its error in `data`.
35 Rejected,
36 /// The host did a host action.
37 Done,
38}
39
40/// One input of a chunk.
41#[derive(Debug, Clone, PartialEq)]
42pub enum Input {
43 /// An event for the root, with its `type`.
44 Event(Value),
45 /// Time moves to `now`, firing the timers due by then; a `now` behind
46 /// the clock, a negative one among them, leaves it where it is.
47 Time { now: i64 },
48 /// Work the run waits for ends. `data` is `Some(Value::Null)` for a
49 /// `null` the input carries, and `None` when it carries none; a result
50 /// of `done` carries none, not even `null`.
51 Work { id: String, outcome: Outcome, data: Option<Value> },
52}
53
54impl Input {
55 /// Reads an input from its JSON, as the workflow contract tells inputs
56 /// apart: a `kind` of `time` or `work` marks a control input, whatever
57 /// else it has, and one with a `type` is no input; anything else with a
58 /// string `type` is an event. A control input may carry keys it does not
59 /// read, but a result of `done` carries no `data`, not even `null`.
60 pub fn from_json(input: &Value) -> Result<Self, ApplyError> {
61 let Some(object) = input.as_object() else {
62 return Err(ApplyError::invalid_input("Each input is an object, an event or a control input."));
63 };
64 match object.get("kind").and_then(Value::as_str) {
65 Some(kind @ ("time" | "work")) => {
66 if object.contains_key("type") {
67 return Err(ApplyError::invalid_input("A control input has no type."));
68 }
69 if kind == "time" {
70 let now = object
71 .get("now")
72 .and_then(safe_integer)
73 .ok_or_else(|| ApplyError::invalid_input("A time input has a now of whole milliseconds."))?;
74 return Ok(Self::Time { now });
75 }
76 let id = object
77 .get("id")
78 .and_then(Value::as_str)
79 .ok_or_else(|| ApplyError::invalid_input("A work result has a string id."))?;
80 let outcome =
81 object.get("outcome").cloned().and_then(|o| serde_json::from_value(o).ok()).ok_or_else(|| {
82 ApplyError::invalid_input("A work result has an outcome, resolved, rejected or done.")
83 })?;
84 if outcome == Outcome::Done && object.contains_key("data") {
85 return Err(ApplyError::invalid_input("A work result of done has no data."));
86 }
87 Ok(Self::Work { id: id.to_owned(), outcome, data: object.get("data").cloned() })
88 }
89 _ if object.get("type").is_some_and(Value::is_string) => Ok(Self::Event(input.clone())),
90 _ if object.contains_key("kind") => {
91 Err(ApplyError::invalid_input("A control input is of kind time or work."))
92 }
93 _ => Err(ApplyError::invalid_input("An event has a string type.")),
94 }
95 }
96
97 /// The input as JSON, as [`Input::from_json`] reads it.
98 pub fn to_json(&self) -> Value {
99 match self {
100 Self::Event(event) => event.clone(),
101 Self::Time { now } => serde_json::json!({ "kind": "time", "now": now }),
102 Self::Work { id, outcome, data } => {
103 let mut m = Map::new();
104 m.insert("kind".into(), "work".into());
105 m.insert("id".into(), Value::String(id.clone()));
106 m.insert("outcome".into(), serde_json::to_value(outcome).unwrap_or_default());
107 if let Some(data) = data {
108 m.insert("data".into(), data.clone());
109 }
110 Value::Object(m)
111 }
112 }
113 }
114}
115
116/// A safe integer of JavaScript, `Number.isSafeInteger`: a whole number of
117/// at most `2^53 - 1` either way, also one written with a fraction of zero,
118/// as `5.0`, which is the same number there.
119fn safe_integer(now: &Value) -> Option<i64> {
120 let max = MAX_TIME as i64;
121 let whole = now.as_i64().or_else(|| {
122 let f = now.as_f64()?;
123 (f.fract() == 0.0 && f.abs() <= MAX_TIME as f64).then_some(f as i64)
124 })?;
125 (-max..=max).contains(&whole).then_some(whole)
126}
127
128/// Work the run waits for, in the order it started: invoked work, which the
129/// host settles `resolved` or `rejected`, or a host action, which it settles
130/// `done`. `kind` is always written.
131#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
132#[serde(tag = "kind", rename_all = "lowercase")]
133pub enum Work {
134 /// Invoked work: the actor at `actor` runs the logic `src` on `input`.
135 Invoke {
136 id: String,
137 actor: String,
138 src: String,
139 #[serde(default, skip_serializing_if = "Option::is_none")]
140 input: Option<Value>,
141 },
142 /// A host action: the actor at `actor` took the action `type` with
143 /// `params`.
144 Action {
145 id: String,
146 actor: String,
147 #[serde(rename = "type")]
148 ty: String,
149 #[serde(default, skip_serializing_if = "Option::is_none")]
150 params: Option<Value>,
151 },
152}
153
154impl Work {
155 /// The work's id, which its result names.
156 pub fn id(&self) -> &str {
157 match self {
158 Self::Invoke { id, .. } | Self::Action { id, .. } => id,
159 }
160 }
161}
162
163/// The root after a chunk.
164#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
165pub struct Root {
166 /// `active`, `done`, `error` or `stopped`.
167 pub status: String,
168 /// The state value; `null` when the root never started.
169 pub value: Value,
170 /// The context; `null` when the root never started.
171 pub context: Value,
172 #[serde(default, skip_serializing_if = "Option::is_none")]
173 pub output: Option<Value>,
174 /// The error of a root in `error`, as `{ "message", "data"? }`: the
175 /// message of what failed it, and the value itself as `data` when that
176 /// is no error or string.
177 #[serde(default, skip_serializing_if = "Option::is_none")]
178 pub error: Option<Value>,
179}
180
181/// What one chunk gave: the events the root emitted, the root, the time,
182/// the next deadline, and the work the run waits for.
183#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
184pub struct Step {
185 pub emitted: Vec<Value>,
186 pub root: Root,
187 pub time: u64,
188 #[serde(default, skip_serializing_if = "Option::is_none")]
189 pub deadline: Option<u64>,
190 pub work: Vec<Work>,
191}
192
193/// What a chunk that failed is: the root's error of a step, or a refused
194/// chunk's rejection, as the workflow contract writes it,
195/// `{ "message", "data"? }`: the message of what failed, and the value
196/// itself as `data` when that is no error or string.
197#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
198pub struct Failure {
199 pub message: String,
200 #[serde(default, skip_serializing_if = "Option::is_none")]
201 pub data: Option<Value>,
202}
203
204impl Failure {
205 /// A failure of `message` alone.
206 pub fn new(message: impl Into<String>) -> Self {
207 Self { message: message.into(), data: None }
208 }
209}
210
211/// Why a chunk was refused. The actor is then as it was before the chunk.
212/// It is one of two things, as the workflow contract tells them apart:
213///
214/// - a rejection, `{ "rejected": { "message", "data"? } }`: the run took
215/// the chunk and rejected it, as an event the machine failed on or an
216/// event to a run that is over; the run goes on as it was, and the
217/// contract records the chunk as rejected;
218/// - a fault of the runner, `{ "code", "message" }`: an input that is no
219/// input of the contract (`WORKFLOW_INVALID_INPUT`), a result of the
220/// other kind of work (`WORKFLOW_INVALID_WORK_RESULT`), or an engine that
221/// failed outside a step of the machine and can't go on
222/// (`WORKFLOW_ENGINE_FAILED`).
223///
224/// The hosts of [`crate::host`] give the same fault of what is no chunk: a start
225/// that fails (`WORKFLOW_MACHINE_FAILED`, or `WORKFLOW_INVALID_INPUT` of its
226/// options), a snapshot that does not restore (`WORKFLOW_INVALID_SNAPSHOT`)
227/// and a machine that does not load (`WORKFLOW_INVALID_MACHINE`, or
228/// `WORKFLOW_INVALID_INPUT` of its options).
229#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
230#[serde(untagged)]
231pub enum ApplyError {
232 /// The run rejected the chunk: the machine failed on an event, or the
233 /// run takes no event.
234 Rejected { rejected: Failure },
235 /// A fault of the runner, of the contract's code.
236 Fault { code: String, message: String },
237}
238
239impl ApplyError {
240 /// A fault of `code`.
241 pub fn fault(code: impl Into<String>, message: impl Into<String>) -> Self {
242 Self::Fault { code: code.into(), message: message.into() }
243 }
244
245 /// An input that is no input of the contract.
246 pub fn invalid_input(message: impl Into<String>) -> Self {
247 Self::fault("WORKFLOW_INVALID_INPUT", message)
248 }
249
250 /// A work result whose outcome does not fit its work.
251 pub fn invalid_work_result(message: impl Into<String>) -> Self {
252 Self::fault("WORKFLOW_INVALID_WORK_RESULT", message)
253 }
254
255 /// A chunk the run rejected, of `message`: the run is over and takes no
256 /// event, or the event is one the run never takes.
257 pub fn rejected(message: impl Into<String>) -> Self {
258 Self::Rejected { rejected: Failure::new(message) }
259 }
260
261 /// A chunk the run rejected of `failure`, as an event the machine failed
262 /// on: the root's error, `{ "message", "data"? }`.
263 pub fn rejected_with(failure: Failure) -> Self {
264 Self::Rejected { rejected: failure }
265 }
266
267 /// A start whose root failed, of `message`, so the run has no state to
268 /// go on from: `WORKFLOW_MACHINE_FAILED`, of no run.
269 pub fn start_failed(message: impl Into<String>) -> Self {
270 Self::fault("WORKFLOW_MACHINE_FAILED", message)
271 }
272
273 /// A snapshot a host could not restore a run from, of `message`:
274 /// `WORKFLOW_INVALID_SNAPSHOT`, of no run.
275 pub fn invalid_snapshot(message: impl Into<String>) -> Self {
276 Self::fault("WORKFLOW_INVALID_SNAPSHOT", message)
277 }
278
279 /// A definition a host could not compile into a machine, of `message`:
280 /// `WORKFLOW_INVALID_MACHINE`, of no run.
281 pub fn invalid_machine(message: impl Into<String>) -> Self {
282 Self::fault("WORKFLOW_INVALID_MACHINE", message)
283 }
284
285 /// The engine failed outside a step of the machine, as an undo that
286 /// could not put the run back, so the run can't go on.
287 pub fn engine_failed(message: impl Into<String>) -> Self {
288 Self::fault("WORKFLOW_ENGINE_FAILED", message)
289 }
290
291 /// The fault's code; `None` of a rejection.
292 pub fn code(&self) -> Option<&str> {
293 match self {
294 Self::Rejected { .. } => None,
295 Self::Fault { code, .. } => Some(code),
296 }
297 }
298
299 /// The message of the rejection or of the fault.
300 pub fn message(&self) -> &str {
301 match self {
302 Self::Rejected { rejected } => &rejected.message,
303 Self::Fault { message, .. } => message,
304 }
305 }
306
307 /// The rejection; `None` of a fault.
308 pub fn rejection(&self) -> Option<&Failure> {
309 match self {
310 Self::Rejected { rejected } => Some(rejected),
311 Self::Fault { .. } => None,
312 }
313 }
314}
315
316impl fmt::Display for ApplyError {
317 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
318 match self {
319 Self::Rejected { rejected } => write!(f, "rejected: {}", rejected.message),
320 Self::Fault { code, message } => write!(f, "{code}: {message}"),
321 }
322 }
323}
324
325impl std::error::Error for ApplyError {}
326
327/// XState's `decodeAddressSegment`, the inverse of
328/// [`crate::system::encode_address_segment`].
329pub(crate) fn decode_address_segment(segment: &str) -> String {
330 if segment.contains('%') {
331 segment.replace("%2F", "/").replace("%25", "%")
332 } else {
333 segment.to_owned()
334 }
335}