xmachines_workflow/
text.rs1use std::sync::Arc;
9
10use serde::de::DeserializeOwned;
11use serde::Serialize;
12use serde_json::Value;
13use xmachines_runtime::{EventType, Machine};
14
15use crate::input::Chunk;
16use crate::record::{Fault, FaultCode};
17use crate::step::{Options, Run, Stepper};
18
19pub fn fault_json(fault: &Fault) -> String {
21 serde_json::to_string(fault).unwrap_or_default()
22}
23
24pub fn parse_options(text: &str) -> Result<Options, Fault> {
27 if text.trim().is_empty() {
28 return Ok(Options::default());
29 }
30 serde_json::from_str(text)
31 .map_err(|e| Fault::new(FaultCode::WorkflowInvalidInput, format!("The run options do not parse: {e}."), 0))
32}
33
34pub fn open<C, E>(
39 machine: Arc<Machine<C, E>>,
40 options: &str,
41 max_timers: usize,
42 max_steps: usize,
43) -> Result<(Run<C, E>, Vec<String>), String>
44where
45 C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
46 E: EventType + Send + Sync,
47{
48 let mut options = parse_options(options).map_err(|f| fault_json(&f))?;
49 options.max_timers.get_or_insert(max_timers as u64);
50 options.max_steps.get_or_insert(max_steps as u64);
51 let (run, opening) = Run::open(machine, options).map_err(|f| fault_json(&f))?;
52 Ok((run, opening.iter().map(|r| serde_json::to_string(r).unwrap_or_default()).collect()))
53}
54
55impl<C, E> Run<C, E>
56where
57 C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
58 E: EventType + Send + Sync,
59{
60 pub fn apply_text(&mut self, chunk: &str) -> Result<Vec<String>, String> {
65 let chunk: Chunk<Value> = match serde_json::from_str::<Value>(chunk) {
66 Ok(Value::Array(items)) => Chunk::Batch(items),
67 Ok(one) => Chunk::One(one),
68 Err(_) => Chunk::One(Value::Null),
69 };
70 let mut records = Vec::new();
71 self.apply(chunk, &mut records).map_err(|f| fault_json(&f))?;
72 Ok(records.iter().map(|r| serde_json::to_string(r).unwrap_or_default()).collect())
73 }
74
75 pub fn can_text(&self, event: &str) -> bool {
78 serde_json::from_str::<Value>(event).is_ok_and(|event| self.can(&event))
79 }
80
81 pub fn checkpoint_text(&self) -> String {
83 serde_json::to_string(&self.checkpoint()).unwrap_or_default()
84 }
85}