Skip to main content

xmachines_workflow/
input.rs

1//! What a run reads: events, which have a `type`, and two control inputs,
2//! time and the result of work, which have a `kind` and never a `type`
3//! ([`Input`], [`Control`]), one at a time or in batches applied all or
4//! nothing ([`Chunk`]).
5
6use serde::de::{DeserializeOwned, Deserializer, Error as _};
7use serde::ser::{SerializeMap, Serializer};
8use serde::{Deserialize, Serialize};
9use serde_json::{Map, Value};
10
11use crate::serde_util::safe_integer;
12
13/// How work ends: invoked work is `resolved` or `rejected`, a host action is
14/// `done`.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
16#[serde(rename_all = "lowercase")]
17pub enum Outcome {
18    /// Invoked work finished, with what it gave in `data`.
19    Resolved,
20    /// Invoked work failed, with why in `data`.
21    Rejected,
22    /// The host did a host action. Its result carries no `data`.
23    Done,
24}
25
26/// A control input: time, or the result of work. It has a `kind`, and never
27/// a `type`, so no event of a machine is one, whatever its `type`.
28///
29/// `D` is what a result of work carries, any JSON by default. A key the
30/// protocol does not read is kept in `extra` and written back after the
31/// keys it reads, so a rejected batch or a journal's chunk holds the input as
32/// it was written.
33#[derive(Debug, Clone, PartialEq)]
34pub enum Control<D = Value> {
35    /// `{ "kind": "time", "now" }`: moves the run's clock towards `now`, in
36    /// whole milliseconds, a safe integer of JavaScript, and fires each timer
37    /// due by then. A `now` behind the run's clock leaves it where it is.
38    Time {
39        /// The time to move to, in milliseconds.
40        now: i64,
41        /// The keys of the input the protocol does not read, in order.
42        extra: Map<String, Value>,
43    },
44    /// `{ "kind": "work", "id", "outcome", "data"? }`: settles work the run
45    /// waits for, by its `id`. `data` is `Some` of a `null` the input
46    /// carries, and `None` of none; a result of `done` carries none.
47    Work {
48        /// The work's id, as the snapshot's `work` lists it.
49        id: String,
50        /// How the work ended.
51        outcome: Outcome,
52        /// What invoked work gave, or why it failed.
53        data: Option<D>,
54        /// The keys of the input the protocol does not read, in order.
55        extra: Map<String, Value>,
56    },
57}
58
59impl<D> Control<D> {
60    /// The time input that moves the clock towards `now`.
61    pub fn time(now: i64) -> Self {
62        Self::Time { now, extra: Map::new() }
63    }
64
65    /// The result of invoked work `id` that gave `data`.
66    pub fn resolved(id: impl Into<String>, data: D) -> Self {
67        Self::Work { id: id.into(), outcome: Outcome::Resolved, data: Some(data), extra: Map::new() }
68    }
69
70    /// The result of invoked work `id` that failed with `error`.
71    pub fn rejected(id: impl Into<String>, error: D) -> Self {
72        Self::Work { id: id.into(), outcome: Outcome::Rejected, data: Some(error), extra: Map::new() }
73    }
74
75    /// The result of host action `id`, which the host did.
76    pub fn done(id: impl Into<String>) -> Self {
77        Self::Work { id: id.into(), outcome: Outcome::Done, data: None, extra: Map::new() }
78    }
79}
80
81/// One input: an event of the machine, which has a `type`, or a control
82/// input, which has a `kind`.
83///
84/// It is read as the workflow contract tells inputs apart, and never as an
85/// untagged enum: a `kind` of `time` or `work` marks a control input,
86/// whatever else it has, and one with a `type` is no input; anything else
87/// with a string `type` is an event, `Ev`, a stray `kind` of it among its own
88/// fields (`{ "type": "add", "kind": "book" }` is an event); and anything
89/// else is no input. [`invalid`] says why in the words of the contract.
90#[derive(Debug, Clone, PartialEq)]
91pub enum Input<Ev = Value, D = Value> {
92    /// An event for the root.
93    Event(Ev),
94    /// Time, or the result of work.
95    Control(Control<D>),
96}
97
98impl<Ev, D> From<Control<D>> for Input<Ev, D> {
99    fn from(control: Control<D>) -> Self {
100        Self::Control(control)
101    }
102}
103
104/// Why `input` is no input of the contract, in its words, or `None` of an
105/// input: the reason a run gives in the fault `WORKFLOW_INVALID_INPUT`.
106///
107/// ```
108/// use serde_json::json;
109/// use xmachines_workflow::invalid;
110///
111/// assert_eq!(invalid(&json!({ "type": "pay" })), None);
112/// assert_eq!(invalid(&json!({ "kind": "time", "now": 1, "type": "x" })), Some("a control input has no type"));
113/// assert_eq!(invalid(&json!({ "kind": "time", "now": 10.5 })), Some("a time input has a now of whole milliseconds"));
114/// ```
115pub fn invalid(input: &Value) -> Option<&'static str> {
116    let Some(object) = input.as_object() else {
117        return Some("each input is an object, an event or a control input");
118    };
119    match object.get("kind").and_then(Value::as_str) {
120        Some(kind @ ("time" | "work")) => {
121            if object.contains_key("type") {
122                return Some("a control input has no type");
123            }
124            if kind == "time" {
125                return match object.get("now").and_then(safe_integer) {
126                    Some(_) => None,
127                    None => Some("a time input has a now of whole milliseconds"),
128                };
129            }
130            if !object.get("id").is_some_and(Value::is_string) {
131                return Some("a work result has a string id");
132            }
133            match object.get("outcome").and_then(Value::as_str) {
134                Some("done") if object.contains_key("data") => Some("a work result of done has no data"),
135                Some("resolved" | "rejected" | "done") => None,
136                _ => Some("a work result has an outcome, resolved, rejected or done"),
137            }
138        }
139        _ if object.get("type").is_some_and(Value::is_string) => None,
140        _ if object.contains_key("kind") => Some("a control input is of kind time or work"),
141        _ => Some("an event has a string type"),
142    }
143}
144
145/// Whether `input` is an event as the run reads it: no `kind` of `time` or
146/// `work`, and a string `type`.
147pub fn is_event(input: &Value) -> bool {
148    !matches!(input.get("kind").and_then(Value::as_str), Some("time" | "work"))
149        && input.get("type").is_some_and(Value::is_string)
150}
151
152impl<Ev: DeserializeOwned, D: DeserializeOwned> Input<Ev, D> {
153    /// Reads an input of its JSON, as [`invalid`] tells it: an error that
154    /// names the rule of what is no input, or the event type's own error of an
155    /// event that is not one of `Ev`.
156    pub fn from_value(value: Value) -> Result<Self, serde_json::Error> {
157        if let Some(why) = invalid(&value) {
158            return Err(serde_json::Error::custom(why));
159        }
160        if is_event(&value) {
161            return Ev::deserialize(value).map(Input::Event);
162        }
163        let Value::Object(mut object) = value else { unreachable!("invalid() refuses what is no object") };
164        let control = if object.get("kind").and_then(Value::as_str) == Some("time") {
165            let now = object.remove("now").as_ref().and_then(safe_integer).unwrap_or_default();
166            object.remove("kind");
167            Control::Time { now, extra: object }
168        } else {
169            let id = match object.remove("id") {
170                Some(Value::String(id)) => id,
171                _ => unreachable!("invalid() refuses a work result of no string id"),
172            };
173            let outcome = Outcome::deserialize(object.remove("outcome").unwrap_or_default())?;
174            let data = object.remove("data").map(D::deserialize).transpose()?;
175            object.remove("kind");
176            Control::Work { id, outcome, data, extra: object }
177        };
178        Ok(Input::Control(control))
179    }
180}
181
182impl<'de, Ev: DeserializeOwned, D: DeserializeOwned> Deserialize<'de> for Input<Ev, D> {
183    fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
184        Self::from_value(Value::deserialize(deserializer)?).map_err(De::Error::custom)
185    }
186}
187
188impl<D: Serialize> Serialize for Control<D> {
189    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
190        match self {
191            Self::Time { now, extra } => {
192                let mut map = serializer.serialize_map(Some(2 + extra.len()))?;
193                map.serialize_entry("kind", "time")?;
194                map.serialize_entry("now", now)?;
195                for (key, value) in extra {
196                    map.serialize_entry(key, value)?;
197                }
198                map.end()
199            }
200            Self::Work { id, outcome, data, extra } => {
201                let mut map = serializer.serialize_map(Some(3 + usize::from(data.is_some()) + extra.len()))?;
202                map.serialize_entry("kind", "work")?;
203                map.serialize_entry("id", id)?;
204                map.serialize_entry("outcome", outcome)?;
205                if let Some(data) = data {
206                    map.serialize_entry("data", data)?;
207                }
208                for (key, value) in extra {
209                    map.serialize_entry(key, value)?;
210                }
211                map.end()
212            }
213        }
214    }
215}
216
217impl<'de, D: DeserializeOwned> Deserialize<'de> for Control<D> {
218    fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
219        let value = Value::deserialize(deserializer)?;
220        if !matches!(value.get("kind").and_then(Value::as_str), Some("time" | "work")) {
221            return Err(De::Error::custom("a control input is of kind time or work"));
222        }
223        match Input::<Map<String, Value>, D>::from_value(value).map_err(De::Error::custom)? {
224            Input::Control(control) => Ok(control),
225            Input::Event(_) => unreachable!("a kind of time or work is never an event"),
226        }
227    }
228}
229
230impl<Ev: Serialize, D: Serialize> Serialize for Input<Ev, D> {
231    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
232        match self {
233            Self::Event(event) => event.serialize(serializer),
234            Self::Control(control) => control.serialize(serializer),
235        }
236    }
237}
238
239/// What a run reads at once, as one `seq`: one input, or a batch, which the
240/// run applies all or nothing. A JSON array is a batch; anything else is one
241/// input.
242#[derive(Debug, Clone, PartialEq)]
243pub enum Chunk<I = Input> {
244    /// A batch of inputs, in order.
245    Batch(Vec<I>),
246    /// One input, as a batch of one.
247    One(I),
248}
249
250impl<I> Chunk<I> {
251    /// The inputs of the chunk, in order.
252    pub fn inputs(&self) -> &[I] {
253        match self {
254            Self::Batch(items) => items,
255            Self::One(item) => std::slice::from_ref(item),
256        }
257    }
258
259    /// The inputs of the chunk, as a batch.
260    pub fn into_batch(self) -> Vec<I> {
261        match self {
262            Self::Batch(items) => items,
263            Self::One(item) => vec![item],
264        }
265    }
266}
267
268impl<I> From<Vec<I>> for Chunk<I> {
269    fn from(items: Vec<I>) -> Self {
270        Self::Batch(items)
271    }
272}
273
274impl<I: Serialize> Serialize for Chunk<I> {
275    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
276        match self {
277            Self::Batch(items) => items.serialize(serializer),
278            Self::One(item) => item.serialize(serializer),
279        }
280    }
281}
282
283impl<'de, I: DeserializeOwned> Deserialize<'de> for Chunk<I> {
284    fn deserialize<De: Deserializer<'de>>(deserializer: De) -> Result<Self, De::Error> {
285        match Value::deserialize(deserializer)? {
286            Value::Array(items) => items
287                .into_iter()
288                .map(I::deserialize)
289                .collect::<Result<Vec<_>, _>>()
290                .map(Chunk::Batch)
291                .map_err(De::Error::custom),
292            one => I::deserialize(one).map(Chunk::One).map_err(De::Error::custom),
293        }
294    }
295}