use std::sync::Arc;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::Value;
use xmachines_runtime::{EventType, Machine};
use crate::input::Chunk;
use crate::record::{Fault, FaultCode};
use crate::step::{Options, Run, Stepper};
pub fn fault_json(fault: &Fault) -> String {
serde_json::to_string(fault).unwrap_or_default()
}
pub fn parse_options(text: &str) -> Result<Options, Fault> {
if text.trim().is_empty() {
return Ok(Options::default());
}
serde_json::from_str(text)
.map_err(|e| Fault::new(FaultCode::WorkflowInvalidInput, format!("The run options do not parse: {e}."), 0))
}
pub fn open<C, E>(
machine: Arc<Machine<C, E>>,
options: &str,
max_timers: usize,
max_steps: usize,
) -> Result<(Run<C, E>, Vec<String>), String>
where
C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
E: EventType + Send + Sync,
{
let mut options = parse_options(options).map_err(|f| fault_json(&f))?;
options.max_timers.get_or_insert(max_timers as u64);
options.max_steps.get_or_insert(max_steps as u64);
let (run, opening) = Run::open(machine, options).map_err(|f| fault_json(&f))?;
Ok((run, opening.iter().map(|r| serde_json::to_string(r).unwrap_or_default()).collect()))
}
impl<C, E> Run<C, E>
where
C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
E: EventType + Send + Sync,
{
pub fn apply_text(&mut self, chunk: &str) -> Result<Vec<String>, String> {
let chunk: Chunk<Value> = match serde_json::from_str::<Value>(chunk) {
Ok(Value::Array(items)) => Chunk::Batch(items),
Ok(one) => Chunk::One(one),
Err(_) => Chunk::One(Value::Null),
};
let mut records = Vec::new();
self.apply(chunk, &mut records).map_err(|f| fault_json(&f))?;
Ok(records.iter().map(|r| serde_json::to_string(r).unwrap_or_default()).collect())
}
pub fn can_text(&self, event: &str) -> bool {
serde_json::from_str::<Value>(event).is_ok_and(|event| self.can(&event))
}
pub fn checkpoint_text(&self) -> String {
serde_json::to_string(&self.checkpoint()).unwrap_or_default()
}
}