use std::sync::Arc;
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::{json, Map, Value};
use crate::actor::RestoreOptions;
use crate::event::EventType;
use crate::machine::Machine;
use crate::system::{ActorRef, InitOptions, DEFAULT_MAX_STEPS};
use crate::Actor;
pub fn parse_json(what: &str, text: &str) -> Result<Value, String> {
serde_json::from_str(text).map_err(|e| format!("invalid {what} JSON: {e}"))
}
pub fn parse_event(text: &str) -> Result<Value, String> {
let event = parse_json("event", text)?;
if !event.get("type").is_some_and(Value::is_string) {
return Err("an event must be an object with a string \"type\"".into());
}
Ok(event)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OptionsFor {
Start,
Restore,
}
#[derive(Debug, Clone)]
pub struct HostOptions {
pub input: Option<Value>,
pub id: Option<String>,
pub children: Map<String, Value>,
pub max_steps: usize,
pub observe_system_emitted: bool,
}
impl Default for HostOptions {
fn default() -> Self {
Self {
input: None,
id: None,
children: Map::new(),
max_steps: DEFAULT_MAX_STEPS,
observe_system_emitted: false,
}
}
}
impl HostOptions {
pub fn parse(text: &str, call: OptionsFor, children: bool) -> Result<Self, String> {
let mut options = Self::default();
if text.trim().is_empty() {
return Ok(options);
}
let Value::Object(mut o) = parse_json("options", text)? else {
return Err("options must be a JSON object".into());
};
if call == OptionsFor::Restore {
let given = |k: &str| o.get(k).is_some_and(|v| k == "input" || !v.is_null());
if let Some(k) = ["input", "id"].into_iter().find(|k| given(k)) {
return Err(format!("options.{k} does not apply to restore: the snapshot holds it"));
}
}
options.input = o.remove("input");
match o.remove("id") {
None | Some(Value::Null) => {}
Some(Value::String(s)) => options.id = Some(s),
Some(_) => return Err("options.id must be a string".into()),
}
if children {
match o.remove("children") {
None | Some(Value::Null) => {}
Some(Value::Object(c)) => options.children = c,
Some(_) => return Err("options.children must map invoke sources to machine definitions".into()),
}
}
match o.remove("maxSteps") {
None | Some(Value::Null) => {}
Some(v) => {
options.max_steps = v
.as_u64()
.or_else(|| v.as_f64().filter(|f| f.fract() == 0.0 && *f >= 0.0).map(|f| f as u64))
.filter(|&n| n > 0)
.map(|n| usize::try_from(n).unwrap_or(usize::MAX))
.ok_or("options.maxSteps must be a positive integer")?
}
}
match o.remove("observeSystemEmitted") {
None | Some(Value::Null) => {}
Some(Value::Bool(b)) => options.observe_system_emitted = b,
Some(_) => return Err("options.observeSystemEmitted must be a boolean".into()),
}
if let Some(k) = o.keys().next() {
return Err(format!("unknown option \"{k}\""));
}
Ok(options)
}
pub fn start<C, E>(self, machine: Arc<Machine<C, E>>, now: u64) -> Result<Actor<C, E>, String>
where
C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
E: EventType + Send + Sync,
{
let init = InitOptions {
input: self.input,
id: self.id,
time: now,
max_steps: self.max_steps,
observe_system_emitted: self.observe_system_emitted,
..Default::default()
};
Actor::start_with(machine, init).map_err(|e| e.to_string())
}
pub fn restore<C, E>(&self, machine: Arc<Machine<C, E>>, snapshot: &Value) -> Result<Actor<C, E>, String>
where
C: Serialize + DeserializeOwned + Clone + Send + Sync + 'static,
E: EventType + Send + Sync,
{
let options = RestoreOptions { max_steps: self.max_steps, observe_system_emitted: self.observe_system_emitted };
Actor::restore_with(machine, snapshot, options).map_err(|e| e.to_string())
}
}
pub fn system_emitted_json(emitted: Vec<(ActorRef, Value)>) -> Vec<String> {
emitted.into_iter().map(|(actor, event)| json!({ "actor": actor.to_json(), "event": event }).to_string()).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn options_for_start_and_restore() {
let o = HostOptions::parse(r#"{ "input": 1, "id": "x", "maxSteps": 5 }"#, OptionsFor::Start, false).unwrap();
assert_eq!((o.input, o.id.as_deref(), o.max_steps), (Some(json!(1)), Some("x"), 5));
assert_eq!(HostOptions::parse("", OptionsFor::Restore, true).unwrap().max_steps, DEFAULT_MAX_STEPS);
let o = HostOptions::parse(r#"{ "maxSteps": 4294967299 }"#, OptionsFor::Restore, true).unwrap();
assert!(o.max_steps >= 4_294_967_295);
let o = HostOptions::parse(r#"{ "maxSteps": 5.0 }"#, OptionsFor::Start, true).unwrap();
assert_eq!(o.max_steps, 5);
let o = HostOptions::parse(r#"{ "maxSteps": 1e300 }"#, OptionsFor::Start, true).unwrap();
assert!(o.max_steps >= 4_294_967_295);
assert_eq!(HostOptions::parse(r#"{ "id": null }"#, OptionsFor::Restore, true).unwrap().id, None);
let err = |text, call, children| HostOptions::parse(text, call, children).unwrap_err();
assert_eq!(
err(r#"{ "id": "x" }"#, OptionsFor::Restore, true),
"options.id does not apply to restore: the snapshot holds it"
);
assert_eq!(
err(r#"{ "input": null }"#, OptionsFor::Restore, true),
"options.input does not apply to restore: the snapshot holds it"
);
assert_eq!(err(r#"{ "children": {} }"#, OptionsFor::Start, false), "unknown option \"children\"");
assert_eq!(
err(r#"{ "maxSteps": 0 }"#, OptionsFor::Start, false),
"options.maxSteps must be a positive integer"
);
assert_eq!(
err(r#"{ "observeSystemEmitted": 1 }"#, OptionsFor::Start, true),
"options.observeSystemEmitted must be a boolean"
);
assert_eq!(err("[]", OptionsFor::Start, true), "options must be a JSON object");
}
}