use std::cell::{Cell, RefCell};
use std::sync::Arc;
use serde::de::DeserializeOwned;
use serde_json::Value;
use crate::core::Nid;
use crate::event::Ev;
use crate::machine::Machine;
use crate::system::{ActorRef, Context, FixedState, SystemError};
use crate::FixedMap;
use indexmap::IndexMap;
pub(crate) type GuardFn<C, E> = Box<dyn Fn(&GuardArgs<'_, C, E>) -> Result<bool, String> + Send + Sync>;
pub(crate) type ActionFn = crate::system::EffectExec;
pub(crate) type DelayFn<C, E> = Box<dyn Fn(&C, &Ev<E>) -> Result<u64, String> + Send + Sync>;
pub(crate) type ExprFn<C, E> = Arc<dyn Fn(&ExprArgs<'_, C, E>) -> Value + Send + Sync>;
pub(crate) type ContextFn = Arc<dyn Fn(&ContextArgs<'_>) -> Value + Send + Sync>;
pub(crate) type Factory<T> = Arc<dyn Fn(&Value) -> Result<T, String> + Send + Sync>;
pub struct GuardArgs<'a, C, E> {
pub context: &'a C,
pub event: &'a Ev<E>,
pub(crate) machine: &'a Machine<C, E>,
pub(crate) config: &'a [Nid],
}
impl<C, E> GuardArgs<'_, C, E> {
pub fn in_state(&self, id: &str) -> bool {
let id = id.strip_prefix('#').unwrap_or(id);
self.machine.node_by_id(id).is_some_and(|n| self.config.contains(&n))
}
}
pub struct ExprArgs<'a, C, E> {
pub context: &'a C,
pub event: &'a Ev<E>,
pub params: Option<&'a Value>,
pub input: Option<&'a Value>,
pub(crate) machine: &'a Machine<C, E>,
pub(crate) config: &'a [Nid],
pub(crate) enq: Option<&'a Enq<'a>>,
pub(crate) children: &'a IndexMap<String, ActorRef, FixedState>,
pub(crate) cx: &'a dyn SelfRefs,
pub(crate) error: &'a RefCell<Option<String>>,
}
pub(crate) trait SelfRefs {
fn self_ref(&self) -> ActorRef;
fn parent_ref(&self) -> Option<ActorRef>;
}
impl SelfRefs for RefCell<&mut (dyn Context + '_)> {
fn self_ref(&self) -> ActorRef {
self.borrow().self_ref()
}
fn parent_ref(&self) -> Option<ActorRef> {
self.borrow().parent_ref()
}
}
impl<C: serde::Serialize, E: crate::event::EventType> ExprArgs<'_, C, E> {
pub fn scope_json(&self) -> Result<Value, String> {
let mut scope = serde_json::Map::new();
let context = serde_json::to_value(self.context).map_err(|e| format!("the context does not serialize: {e}"))?;
scope.insert("context".into(), context);
scope.insert("event".into(), self.event.to_json());
if let Some(input) = self.input {
scope.insert("input".into(), input.clone());
}
if let Some(params) = self.params {
scope.insert("params".into(), params.clone());
}
scope.insert("self".into(), self.self_ref().to_json());
if let Some(parent) = self.parent_ref() {
scope.insert("parent".into(), parent.to_json());
}
if !self.children.is_empty() {
let children = self.children.iter().map(|(id, r)| (id.clone(), r.to_json())).collect();
scope.insert("children".into(), Value::Object(children));
}
Ok(Value::Object(scope))
}
}
impl<C, E> ExprArgs<'_, C, E> {
pub fn children(&self) -> &IndexMap<String, ActorRef, FixedState> {
self.children
}
pub fn self_ref(&self) -> ActorRef {
self.cx.self_ref()
}
pub fn parent_ref(&self) -> Option<ActorRef> {
self.cx.parent_ref()
}
pub fn fail(&self, message: impl Into<String>) {
self.error.borrow_mut().get_or_insert_with(|| message.into());
}
pub fn in_state(&self, id: &str) -> bool {
let id = id.strip_prefix('#').unwrap_or(id);
self.machine.node_by_id(id).is_some_and(|n| self.config.contains(&n))
}
pub fn enq(&self) -> Option<&Enq<'_>> {
self.enq
}
}
#[derive(Default)]
pub struct Enq<'a> {
pub(crate) ops: RefCell<Vec<EnqOp>>,
pub(crate) ids: Option<&'a dyn ChildIds>,
pub(crate) aborted: Cell<bool>,
pub(crate) failed: Cell<bool>,
}
pub(crate) trait ChildIds {
fn spawn(&self, src: &str, options: &SpawnOptions) -> Result<Spawn, SystemError>;
fn stop_child(&self, id: &str);
}
pub(crate) enum Spawn {
Created { id: String, child: ActorRef, counter: Option<(String, u64)> },
Predicted(String),
Abort,
}
#[derive(Debug, Clone, Default)]
pub struct SpawnOptions {
pub id: Option<String>,
pub input: Option<Value>,
pub system_id: Option<String>,
pub sync_snapshot: Option<bool>,
}
#[derive(Debug, Clone)]
pub(crate) enum EnqOp {
Raise {
event: Value,
delay: Option<u64>,
id: Option<String>,
},
Emit(Value),
Cancel(String),
Log(Vec<Value>),
Action {
name: String,
params: Value,
},
SendTo {
to: SendTarget,
event: Value,
delay: Option<u64>,
id: Option<String>,
},
Stop(String),
Spawn {
id: String,
child: ActorRef,
counter: Option<(String, u64)>,
},
Fail(SystemError),
}
#[derive(Debug, Clone)]
pub(crate) enum SendTarget {
Child(String),
Ref(ActorRef),
Nowhere,
Parent,
}
impl std::fmt::Debug for Enq<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Enq").field("ops", &self.ops).finish_non_exhaustive()
}
}
impl Enq<'_> {
pub fn raise(&self, event: Value) {
self.push(EnqOp::Raise { event, delay: None, id: None });
}
pub fn raise_delayed(&self, event: Value, delay_ms: u64, id: Option<&str>) {
self.push(EnqOp::Raise { event, delay: Some(delay_ms), id: id.map(str::to_owned) });
}
pub fn emit(&self, event: Value) {
self.push(EnqOp::Emit(event));
}
pub fn cancel(&self, id: &str) {
self.push(EnqOp::Cancel(id.to_owned()));
}
pub fn log(&self, args: Vec<Value>) {
self.push(EnqOp::Log(args));
}
pub fn action(&self, name: &str, params: Value) {
self.push(EnqOp::Action { name: name.to_owned(), params });
}
pub fn send_to(&self, child: &str, event: Value) {
self.push_send(SendTarget::Child(child.to_owned()), event, None, None);
}
pub fn send_to_delayed(&self, child: &str, event: Value, delay_ms: u64, id: Option<&str>) {
self.push_send(SendTarget::Child(child.to_owned()), event, Some(delay_ms), id);
}
pub fn send_to_ref(&self, actor: &Value, event: Value) {
self.push_send(Self::target(actor), event, None, None);
}
pub fn send_to_ref_delayed(&self, actor: &Value, event: Value, delay_ms: u64, id: Option<&str>) {
self.push_send(Self::target(actor), event, Some(delay_ms), id);
}
fn target(actor: &Value) -> SendTarget {
match actor {
Value::String(child) => SendTarget::Child(child.clone()),
other => ActorRef::from_json(other).map_or(SendTarget::Nowhere, SendTarget::Ref),
}
}
pub fn send_parent(&self, event: Value) {
self.push_send(SendTarget::Parent, event, None, None);
}
pub fn send_parent_delayed(&self, event: Value, delay_ms: u64, id: Option<&str>) {
self.push_send(SendTarget::Parent, event, Some(delay_ms), id);
}
pub fn stop(&self, child: &str) {
if self.ended() {
return;
}
if let Some(ids) = self.ids {
ids.stop_child(child);
}
self.push(EnqOp::Stop(child.to_owned()));
}
fn push(&self, op: EnqOp) {
if !self.ended() {
self.ops.borrow_mut().push(op);
}
}
pub(crate) fn ended(&self) -> bool {
self.aborted.get() || self.failed.get()
}
fn push_send(&self, to: SendTarget, event: Value, delay: Option<u64>, id: Option<&str>) {
self.push(EnqOp::SendTo { to, event, delay, id: id.map(str::to_owned) });
}
pub fn spawn(&self, src: &str, options: SpawnOptions) -> String {
if self.ended() {
return options.id.unwrap_or_default();
}
let Some(ids) = self.ids else {
return options.id.unwrap_or_else(|| format!("{src}:0"));
};
match ids.spawn(src, &options) {
Ok(Spawn::Created { id, child, counter }) => {
self.push(EnqOp::Spawn { id: id.clone(), child, counter });
id
}
Ok(Spawn::Predicted(id)) => id,
Ok(Spawn::Abort) => {
self.aborted.set(true);
options.id.unwrap_or_default()
}
Err(e) => {
self.push(EnqOp::Fail(e));
self.failed.set(true);
options.id.unwrap_or_default()
}
}
}
pub(crate) fn take(&self) -> Vec<EnqOp> {
std::mem::take(&mut self.ops.borrow_mut())
}
pub fn call(&self, op: &str, args: &[Value]) -> Result<Option<Value>, String> {
if self.ended() {
return Ok(None);
}
let arg = |i: usize| args.get(i).cloned().unwrap_or(Value::Null);
let delay = |options: &Value| {
let ms = options.get("delay")?.as_f64()?;
Some(if ms > 0.0 { ms.ceil() as u64 } else { 0 })
};
match op {
"action" => {
let name = arg(0);
let name = name.as_str().ok_or("enq(action, params): name the action as actions.<name>")?;
self.action(name, arg(1));
}
"raise" => {
let options = arg(1);
match delay(&options) {
Some(ms) => self.raise_delayed(arg(0), ms, options.get("id").and_then(Value::as_str)),
None => self.raise(arg(0)),
}
}
"emit" => self.emit(arg(0)),
"cancel" => self.cancel(arg(0).as_str().unwrap_or_default()),
"log" => self.log(args.to_vec()),
"sendTo" => {
let target = match arg(0) {
Value::Object(o) if !o.contains_key("@actor") => o.get("id").cloned().unwrap_or(Value::Null),
Value::Object(mut o) => {
o.remove("id");
Value::Object(o)
}
other => other,
};
let options = arg(2);
match delay(&options) {
Some(ms) => {
self.send_to_ref_delayed(&target, arg(1), ms, options.get("id").and_then(Value::as_str))
}
None => self.send_to_ref(&target, arg(1)),
}
}
"stop" => {
let target = arg(0);
if let Some(id) = target.as_str().or_else(|| target.get("id").and_then(Value::as_str)) {
self.stop(id);
}
}
"spawn" => {
let src = arg(0);
let src = src.as_str().ok_or("enq.spawn: the source must be a string (actors.<name>)")?;
return Ok(Some(Value::String(self.spawn(src, SpawnOptions::from_json(&arg(1))))));
}
other => return Err(format!("enq.{other} is not supported")),
}
Ok(None)
}
}
impl SpawnOptions {
pub fn from_json(options: &Value) -> Self {
Self {
id: options.get("id").and_then(Value::as_str).map(str::to_owned),
input: options.get("input").cloned(),
system_id: options.get("systemId").and_then(Value::as_str).map(str::to_owned),
sync_snapshot: options.get("syncSnapshot").and_then(Value::as_bool),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum HostActions {
#[default]
None,
Unimplemented,
Named(Vec<String>),
}
impl HostActions {
pub fn includes(&self, name: &str, implemented: bool) -> bool {
match self {
Self::None => false,
Self::Unimplemented => !implemented,
Self::Named(names) => names.iter().any(|n| n == name),
}
}
}
pub struct Registry<C, E> {
pub(crate) guards: FixedMap<String, Factory<GuardFn<C, E>>>,
pub(crate) actions: FixedMap<String, Factory<ActionFn>>,
pub(crate) delays: FixedMap<String, Factory<DelayFn<C, E>>>,
pub(crate) actors: Vec<(String, Arc<dyn crate::system::Logic>)>,
pub(crate) exprs: FixedMap<String, ExprFn<C, E>>,
pub(crate) contexts: FixedMap<String, ContextFn>,
pub(crate) evaluators: FixedMap<String, Arc<dyn Evaluator<C, E>>>,
pub(crate) host_actions: HostActions,
}
impl<C, E> Default for Registry<C, E> {
fn default() -> Self {
Self {
guards: FixedMap::default(),
actions: FixedMap::default(),
delays: FixedMap::default(),
actors: Vec::new(),
exprs: FixedMap::default(),
contexts: FixedMap::default(),
evaluators: FixedMap::default(),
host_actions: HostActions::None,
}
}
}
fn parse_params<P: DeserializeOwned>(params: &Value) -> Result<P, String> {
P::deserialize(params).map_err(|e| e.to_string())
}
impl<C: 'static, E: 'static> Registry<C, E> {
pub fn new() -> Self {
Self::default()
}
pub fn guard(
&mut self,
name: impl Into<String>,
f: impl Fn(&GuardArgs<'_, C, E>) -> bool + Send + Sync + 'static,
) -> &mut Self {
let f = Arc::new(f);
self.guards.insert(
name.into(),
Arc::new(move |_| {
let f = f.clone();
Ok(Box::new(move |args: &GuardArgs<'_, C, E>| Ok(f(args))) as GuardFn<C, E>)
}),
);
self
}
pub fn guard_with<P>(
&mut self,
name: impl Into<String>,
f: impl Fn(&GuardArgs<'_, C, E>, &P) -> bool + Send + Sync + 'static,
) -> &mut Self
where
P: DeserializeOwned + Send + Sync + 'static,
{
self.try_guard_with(name, move |args: &GuardArgs<'_, C, E>, p: &P| Ok(f(args, p)))
}
pub fn try_guard_with<P>(
&mut self,
name: impl Into<String>,
f: impl Fn(&GuardArgs<'_, C, E>, &P) -> Result<bool, String> + Send + Sync + 'static,
) -> &mut Self
where
P: DeserializeOwned + Send + Sync + 'static,
{
let f = Arc::new(f);
self.guards.insert(
name.into(),
Arc::new(move |params| {
let p: P = parse_params(params)?;
let f = f.clone();
Ok(Box::new(move |args: &GuardArgs<'_, C, E>| f(args, &p)) as GuardFn<C, E>)
}),
);
self
}
pub fn host_actions(&mut self, host_actions: HostActions) -> &mut Self {
self.host_actions = host_actions;
self
}
pub(crate) fn is_host_action(&self, name: &str) -> bool {
self.host_actions.includes(name, self.actions.contains_key(name))
}
pub fn action(&mut self, name: impl Into<String>, f: impl Fn() + Send + Sync + 'static) -> &mut Self {
let f = Arc::new(f);
self.actions.insert(
name.into(),
Arc::new(move |_| {
let f = f.clone();
Ok(Arc::new(move || {
f();
Ok(())
}) as ActionFn)
}),
);
self
}
pub fn action_with<P>(&mut self, name: impl Into<String>, f: impl Fn(&P) + Send + Sync + 'static) -> &mut Self
where
P: DeserializeOwned + Send + Sync + 'static,
{
self.try_action_with(name, move |p: &P| {
f(p);
Ok(())
})
}
pub fn try_action_with<P>(
&mut self,
name: impl Into<String>,
f: impl Fn(&P) -> Result<(), String> + Send + Sync + 'static,
) -> &mut Self
where
P: DeserializeOwned + Send + Sync + 'static,
{
let f = Arc::new(f);
self.actions.insert(
name.into(),
Arc::new(move |params| {
let p: P = parse_params(params)?;
let f = f.clone();
Ok(Arc::new(move || f(&p)) as ActionFn)
}),
);
self
}
pub fn actor(&mut self, name: impl Into<String>, logic: Arc<dyn crate::system::Logic>) -> &mut Self {
let name = name.into();
match self.actors.iter_mut().find(|(n, _)| *n == name) {
Some(entry) => entry.1 = logic,
None => self.actors.push((name, logic)),
}
self
}
pub fn delay(
&mut self,
name: impl Into<String>,
f: impl Fn(&C, &Ev<E>) -> u64 + Send + Sync + 'static,
) -> &mut Self {
self.try_delay(name, move |c: &C, e: &Ev<E>| Ok(f(c, e)))
}
pub fn try_delay(
&mut self,
name: impl Into<String>,
f: impl Fn(&C, &Ev<E>) -> Result<u64, String> + Send + Sync + 'static,
) -> &mut Self {
let f = Arc::new(f);
self.delays.insert(
name.into(),
Arc::new(move |_| {
let f = f.clone();
Ok(Box::new(move |c: &C, e: &Ev<E>| f(c, e)) as DelayFn<C, E>)
}),
);
self
}
pub fn delay_ms(&mut self, name: impl Into<String>, ms: u64) -> &mut Self {
self.delay(name, move |_, _| ms)
}
pub fn expr(
&mut self,
name: impl Into<String>,
f: impl Fn(&ExprArgs<'_, C, E>) -> Value + Send + Sync + 'static,
) -> &mut Self {
self.exprs.insert(name.into(), Arc::new(f));
self
}
pub fn context(
&mut self,
name: impl Into<String>,
f: impl Fn(Option<&Value>) -> Value + Send + Sync + 'static,
) -> &mut Self {
self.contexts.insert(name.into(), Arc::new(move |args: &ContextArgs<'_>| f(args.input)));
self
}
pub fn context_with(
&mut self,
name: impl Into<String>,
f: impl Fn(&ContextArgs<'_>) -> Value + Send + Sync + 'static,
) -> &mut Self {
self.contexts.insert(name.into(), Arc::new(f));
self
}
pub fn evaluator(&mut self, lang: impl Into<String>, evaluator: impl Evaluator<C, E> + 'static) -> &mut Self {
let lang = lang.into();
assert!(lang != crate::load::RUST_LANG, "the rust language is built in: use Registry::expr");
self.evaluators.insert(lang, Arc::new(evaluator));
self
}
}
pub(crate) trait Spawner {
fn spawn(&self, src: &str, options: SpawnOptions) -> Option<ActorRef>;
fn self_ref(&self) -> ActorRef;
fn fail(&self, message: String);
}
pub struct ContextArgs<'a> {
pub input: Option<&'a Value>,
pub(crate) spawner: Option<&'a dyn Spawner>,
}
impl ContextArgs<'_> {
pub fn self_ref(&self) -> Option<ActorRef> {
self.spawner.map(|s| s.self_ref())
}
pub fn fail(&self, message: impl Into<String>) {
if let Some(s) = self.spawner {
s.fail(message.into());
}
}
pub fn spawn(&self, src: &str, options: SpawnOptions) -> Value {
match self.spawner.and_then(|s| s.spawn(src, options)) {
Some(r) => r.to_json(),
None => Value::Null,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Slot {
Context,
Guard,
Choice,
TransitionContext,
Input,
Transition,
Action,
ActionParams,
Delay,
Output,
}
impl Slot {
pub fn as_str(self) -> &'static str {
match self {
Slot::Context => "context",
Slot::Guard => "guard",
Slot::Choice => "choice",
Slot::TransitionContext => "transitionContext",
Slot::Input => "input",
Slot::Transition => "transition",
Slot::Action => "action",
Slot::ActionParams => "actionParams",
Slot::Delay => "delay",
Slot::Output => "output",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CodeKind {
Code,
Expr,
}
impl CodeKind {
pub fn as_str(self) -> &'static str {
match self {
CodeKind::Code => "code",
CodeKind::Expr => "expr",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Code {
pub id: u64,
pub lang: String,
pub source: String,
pub kind: CodeKind,
pub slot: Slot,
pub path: String,
}
pub enum Scope<'s, 'a, C, E> {
Expr(&'s ExprArgs<'a, C, E>),
Context(&'s ContextArgs<'a>),
}
pub trait Evaluator<C, E>: Send + Sync {
fn eval(&self, code: &Code, scope: Scope<'_, '_, C, E>) -> Result<Value, String>;
}
impl<C, E, F> Evaluator<C, E> for F
where
F: Fn(&Code, Scope<'_, '_, C, E>) -> Result<Value, String> + Send + Sync,
{
fn eval(&self, code: &Code, scope: Scope<'_, '_, C, E>) -> Result<Value, String> {
self(code, scope)
}
}
impl<C, E> Evaluator<C, E> for Arc<dyn Evaluator<C, E>> {
fn eval(&self, code: &Code, scope: Scope<'_, '_, C, E>) -> Result<Value, String> {
(**self).eval(code, scope)
}
}
pub struct HostEvaluator<F>(pub F);
impl<F> HostEvaluator<F> {
fn code_json(code: &Code) -> String {
serde_json::json!({
"id": code.id,
"lang": code.lang,
"source": code.source,
"kind": code.kind.as_str(),
"slot": code.slot.as_str(),
"path": code.path,
})
.to_string()
}
}
impl<C, E, F> Evaluator<C, E> for HostEvaluator<F>
where
C: serde::Serialize,
E: crate::event::EventType,
F: Fn(&str, &str) -> String + Send + Sync,
{
fn eval(&self, code: &Code, scope: Scope<'_, '_, C, E>) -> Result<Value, String> {
let (scope, enq) = match scope {
Scope::Expr(a) => {
let mut json = a.scope_json()?;
json["enq"] = Value::Bool(a.enq.is_some());
(json, a.enq)
}
Scope::Context(a) => {
let mut json = serde_json::Map::new();
if let Some(input) = a.input {
json.insert("input".into(), input.clone());
}
if let Some(r) = a.self_ref() {
json.insert("self".into(), r.to_json());
}
(Value::Object(json), None)
}
};
let out = (self.0)(&Self::code_json(code), &scope.to_string());
let out: Value = serde_json::from_str(&out).map_err(|e| format!("the evaluator's result is not JSON: {e}"))?;
let Value::Object(mut out) = out else {
return Err(format!("the evaluator's result must be an object, not {out}"));
};
let error = match out.get("error") {
None => None,
Some(Value::String(message)) => Some(message.clone()),
Some(other) => return Err(format!("the evaluator's error must be a message string, not {other}")),
};
match out.get("enq") {
None => {}
Some(Value::Array(calls)) => {
let enq = enq.filter(|_| !calls.is_empty()).ok_or("enq is not available here");
for call in calls {
let parts = call.as_array().ok_or("an enq call is [op, ...args]")?;
let op = parts.first().and_then(Value::as_str).ok_or("an enq call is [op, ...args]")?;
if op == "spawn" && !parts.get(2).and_then(|o| o.get("id")).is_some_and(Value::is_string) {
return Err("enq.spawn from a host evaluator needs an explicit id: \
the id this runtime would choose cannot reach the code"
.into());
}
let enq = enq?;
enq.call(op, &parts[1..])?;
if enq.ended() {
return Ok(Value::Null);
}
}
}
Some(other) => {
return Err(format!("the evaluator's enq must be an array of [op, ...args] calls, not {other}"))
}
}
match error {
Some(message) => Err(message),
None => Ok(out.remove("value").unwrap_or(Value::Null)),
}
}
}