mod invocations;
mod position;
#[cfg(test)]
mod tests;
pub use position::{ActiveInvocation, ExportError, ImportError, Position, Status};
use crate::datamodel::system_variables::{EventType, SCXML_EVENT_PROCESSOR, scxml_location};
use crate::effect::Effect;
use crate::interpreter::{self, Event, MachineState, Route, Routes, StartOptions};
use crate::machine::Machine;
use predicator_rs::{Map, Value};
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::fmt;
use std::num::NonZeroU64;
const DEFAULT_ROUNDS: u64 = 10_000;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RoundBudget {
Rounds(NonZeroU64),
Unbounded,
}
impl Default for RoundBudget {
fn default() -> Self {
RoundBudget::Rounds(NonZeroU64::new(DEFAULT_ROUNDS).unwrap_or(NonZeroU64::MIN))
}
}
impl RoundBudget {
fn interpreter(self) -> interpreter::RoundBudget {
match self {
RoundBudget::Rounds(rounds) => interpreter::RoundBudget::Rounds(rounds.get()),
RoundBudget::Unbounded => interpreter::RoundBudget::Unbounded,
}
}
fn admits(self, count: u64) -> bool {
match self {
RoundBudget::Rounds(rounds) => count <= rounds.get(),
RoundBudget::Unbounded => true,
}
}
fn spent(self) -> u64 {
match self {
RoundBudget::Rounds(rounds) => rounds.get(),
RoundBudget::Unbounded => u64::MAX,
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub struct Options {
pub session_id: String,
pub datamodel: Map,
pub send_types: BTreeSet<String>,
pub round_budget: RoundBudget,
pub trace: bool,
}
impl Options {
pub fn new(session_id: impl Into<String>) -> Self {
Options {
session_id: session_id.into(),
datamodel: Map::new(),
send_types: BTreeSet::new(),
round_budget: RoundBudget::default(),
trace: false,
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
NotRunning,
#[non_exhaustive]
InvalidDuration {
ms: u64,
},
#[non_exhaustive]
BuiltInSendTypes {
types: Vec<String>,
},
}
impl fmt::Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::NotRunning => formatter.write_str("the chart has stopped"),
Error::InvalidDuration { ms } => write!(
formatter,
"a duration of {ms} ms moves the clock past its largest value"
),
Error::BuiltInSendTypes { types } => write!(
formatter,
"built-in send types cannot be registered: {}",
types.join(", ")
),
}
}
}
impl std::error::Error for Error {}
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct Moved {
pub state: State,
pub effects: Vec<Effect>,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub struct Done {
pub donedata: Value,
pub configuration: Vec<String>,
pub active_leaf_states: Vec<String>,
pub active_leaf_count: usize,
}
#[derive(Debug, Clone)]
struct Timer {
send_id: String,
due_ms: u64,
sequence: u64,
send: Delivery,
}
#[derive(Debug, Clone)]
struct Delivery {
target: Option<Value>,
event: Event,
}
#[derive(Debug, Clone)]
pub struct State {
core: MachineState,
session_id: String,
round_budget: RoundBudget,
trace: bool,
now_ms: u64,
timers: Vec<Timer>,
sequence: u64,
external_queue: VecDeque<Event>,
halted: bool,
done: Option<Done>,
invocations: BTreeMap<String, Invocation>,
mailbox: VecDeque<Mail>,
invoked_as: Option<String>,
cancelled: bool,
}
#[derive(Debug, Clone)]
struct Invocation {
completed: bool,
child: State,
}
#[derive(Debug, Clone)]
enum Mail {
Completed { invoke_id: String },
Event { invoke_id: String, event: Event },
Done { invoke_id: String, donedata: Value },
}
impl Mail {
fn invoke_id(&self) -> &str {
match self {
Mail::Completed { invoke_id }
| Mail::Event { invoke_id, .. }
| Mail::Done { invoke_id, .. } => invoke_id,
}
}
}
impl State {
fn fresh(
core: MachineState,
session_id: String,
round_budget: RoundBudget,
trace: bool,
) -> Self {
State {
core,
session_id,
round_budget,
trace,
now_ms: 0,
timers: Vec::new(),
sequence: 0,
external_queue: VecDeque::new(),
halted: false,
done: None,
invocations: BTreeMap::new(),
mailbox: VecDeque::new(),
invoked_as: None,
cancelled: false,
}
}
}
impl Machine {
pub fn start(&self, options: Options) -> Result<Moved, Error> {
let built_in: Vec<String> = options
.send_types
.iter()
.filter(|send_type| is_built_in(send_type))
.cloned()
.collect();
if !built_in.is_empty() {
return Err(Error::BuiltInSendTypes { types: built_in });
}
let ioprocessors = options
.send_types
.iter()
.map(|send_type| (send_type.as_str(), Value::Map(Map::new())))
.collect();
let routes = Routes {
sessions: BTreeSet::from([options.session_id.clone()]),
..Routes::default()
};
let started = interpreter::initialize(
self,
StartOptions {
session_id: options.session_id.clone(),
datamodel: options.datamodel,
send_types: options.send_types,
ioprocessors,
routes: Some(routes),
max_macrostep_rounds: options.round_budget.interpreter(),
},
);
let mut call = Call::open(State::fresh(
started.state,
options.session_id,
options.round_budget,
options.trace,
));
call.perform(started.effects);
call.drain();
Ok(call.close())
}
}
impl State {
pub fn step(&self, name: &str, data: Value) -> Result<Moved, Error> {
if !self.core.running {
return Err(Error::NotRunning);
}
let mut call = Call::open(self.clone());
call.external.push_back(Queued {
event: Event {
name: name.to_owned(),
event_type: EventType::External,
sendid: None,
origin: None,
origintype: None,
invokeid: None,
data,
},
counted: false,
});
call.drain();
Ok(call.close())
}
pub fn advance(&self, ms: u64) -> Result<Moved, Error> {
let until = self
.now_ms
.checked_add(ms)
.ok_or(Error::InvalidDuration { ms })?;
let mut call = Call::open(self.clone());
while let Some((path, due_ms, sequence)) = call.next_due(until) {
if due_ms > call.state.now_ms {
call.next_instant();
}
call.state.now_ms = due_ms;
call.fire_at(&path, sequence);
}
call.state.now_ms = until;
Ok(call.close())
}
pub fn configuration(&self) -> Vec<String> {
ids(&self.core, self.core.configuration.iter().copied())
}
pub fn active_leaf_states(&self) -> Vec<String> {
leaf_ids(&self.core, self.core.configuration.iter().copied())
}
pub fn active_leaf_count(&self) -> usize {
leaf_count(&self.core, self.core.configuration.iter().copied())
}
pub fn done(&self) -> Option<&Done> {
self.done.as_ref()
}
pub fn now_ms(&self) -> u64 {
self.now_ms
}
pub fn next_due_ms(&self) -> Option<u64> {
self.timers
.iter()
.map(|timer| timer.due_ms)
.chain(
self.invocations
.values()
.filter_map(|invocation| invocation.child.next_due_ms()),
)
.min()
}
}
fn is_built_in(send_type: &str) -> bool {
send_type == "scxml" || send_type == SCXML_EVENT_PROCESSOR
}
fn ids(core: &MachineState, indexes: impl Iterator<Item = usize>) -> Vec<String> {
let chart = core.chart();
let mut ids: Vec<String> = indexes
.filter_map(|index| chart.states.get(index).and_then(|state| state.id.clone()))
.collect();
ids.sort();
ids
}
fn leaf_ids(core: &MachineState, indexes: impl Iterator<Item = usize>) -> Vec<String> {
let chart = core.chart();
ids(
core,
indexes.filter(|&index| index < chart.states.len() && chart.is_atomic(index)),
)
}
fn leaf_count(core: &MachineState, indexes: impl Iterator<Item = usize>) -> usize {
let chart = core.chart();
indexes
.filter(|&index| index < chart.states.len() && chart.is_atomic(index))
.count()
}
#[derive(Debug)]
struct Queued {
event: Event,
counted: bool,
}
struct Call {
state: State,
external: VecDeque<Queued>,
mailbox: VecDeque<(Mail, bool)>,
outbox: Vec<(Mail, bool)>,
taking: Option<Event>,
effects: Vec<Effect>,
taken: u64,
sent_internal: u64,
spent: bool,
first_sequence: u64,
fired: u64,
}
impl Call {
fn open(mut state: State) -> Self {
let first_sequence = state.sequence;
let external = std::mem::take(&mut state.external_queue)
.into_iter()
.map(|event| Queued {
event,
counted: false,
})
.collect();
let mailbox = std::mem::take(&mut state.mailbox)
.into_iter()
.map(|mail| (mail, false))
.collect();
Call {
state,
external,
mailbox,
outbox: Vec::new(),
taking: None,
effects: Vec::new(),
taken: 0,
sent_internal: 0,
spent: false,
first_sequence,
fired: 0,
}
}
fn close(self) -> Moved {
let (state, effects, _) = self.finish();
Moved { state, effects }
}
fn finish(mut self) -> (State, Vec<Effect>, Vec<(Mail, bool)>) {
self.state.external_queue = self.external.into_iter().map(|q| q.event).collect();
self.state.mailbox = self.mailbox.into_iter().map(|(mail, _)| mail).collect();
(self.state, self.effects, self.outbox)
}
fn next_due(&self, until: u64) -> Option<(Vec<String>, u64, u64)> {
let mut pending = Vec::new();
pending_timers(&self.state, &mut Vec::new(), &mut pending);
pending
.into_iter()
.filter(|(_, due_ms, _)| *due_ms <= until)
.min_by_key(|(_, due_ms, sequence)| (*due_ms, *sequence))
}
fn fire_at(&mut self, path: &[String], sequence: u64) {
let Some((invoke_id, rest)) = path.split_first() else {
let Some(position) = self
.state
.timers
.iter()
.position(|timer| timer.sequence == sequence)
else {
return;
};
let timer = self.state.timers.remove(position);
self.count_fire(&timer);
let effects = self.route(timer.send, false);
self.perform(effects);
self.drain();
return;
};
self.within(invoke_id, |child| child.fire_at(rest, sequence));
self.drain();
}
fn drain(&mut self) {
while self.state.core.running && !self.state.halted {
if let Some(queued) = self.external.pop_front() {
if queued.counted && !self.count_taken() {
self.external.push_front(queued);
self.halt();
return;
}
self.take(queued.event);
continue;
}
let Some((mail, counted)) = self.mailbox.pop_front() else {
return;
};
if counted && !self.count_taken() {
self.mailbox.push_front((mail, counted));
self.halt();
return;
}
self.take_mail(mail);
}
}
fn count_taken(&mut self) -> bool {
let taken = self.taken.saturating_add(1);
if !self.state.round_budget.admits(taken) {
return false;
}
self.taken = taken;
true
}
fn take(&mut self, event: Event) {
self.stamp();
if let Ok(stepped) = interpreter::handle_event(&self.state.core, &event) {
self.state.core = stepped.state;
self.taking = Some(event);
self.perform(stepped.effects);
self.taking = None;
}
}
fn stamp(&mut self) {
self.state.core.routes = Some(Routes {
sessions: BTreeSet::from([self.state.session_id.clone()]),
parent: self.state.invoked_as.is_some(),
invokes: self.state.invocations.keys().cloned().collect(),
});
}
fn next_instant(&mut self) {
self.first_sequence = self.state.sequence;
self.taken = 0;
self.sent_internal = 0;
self.fired = 0;
}
fn count_fire(&mut self, timer: &Timer) {
if self.state.halted || timer.sequence < self.first_sequence {
return;
}
self.fired = self.fired.saturating_add(1);
if !self.state.round_budget.admits(self.fired) {
self.halt();
}
}
fn halt(&mut self) {
self.spent = true;
if self.state.halted {
return;
}
let budget = self.state.round_budget.spent();
self.perform(vec![interpreter::budget_exhausted(
&self.state.core,
budget,
)]);
}
fn perform(&mut self, effects: Vec<Effect>) {
let mut batch = effects;
while !batch.is_empty() {
self.announce(&batch);
let mut deferred = Vec::new();
for effect in batch {
self.effects.push(self.report(effect.clone()));
deferred.extend(self.perform_one(&effect));
}
batch = deferred;
}
}
fn report(&self, effect: Effect) -> Effect {
match self.state.invoked_as {
Some(_) => Effect::Child {
session_id: self.state.session_id.clone(),
effect: Box::new(effect),
},
None => effect,
}
}
fn perform_one(&mut self, effect: &Effect) -> Vec<Effect> {
match effect {
Effect::Send {
event,
target,
send_type,
data,
send_id,
id_from_author,
..
} if send_type.is_none() || !self.registered(send_type.as_ref()) => {
let delivery = self.delivery(event, target, data, send_id, *id_from_author);
self.route(delivery, true)
}
Effect::SendDelayed {
event,
target,
send_type,
data,
send_id,
id_from_author,
delay_ms,
..
} if send_type.is_none() || !self.registered(send_type.as_ref()) => {
let send = self.delivery(event, target, data, send_id, *id_from_author);
let delay = u64::try_from(*delay_ms).unwrap_or(0);
self.state.timers.push(Timer {
send_id: send_id.clone(),
due_ms: self.state.now_ms.saturating_add(delay),
sequence: self.state.sequence,
send,
});
self.state.sequence = self.state.sequence.saturating_add(1);
Vec::new()
}
Effect::Cancel { send_id, .. } => {
if let Value::String(send_id) = send_id {
self.state.timers.retain(|timer| timer.send_id != *send_id);
}
Vec::new()
}
Effect::Done {
donedata,
configuration,
..
} => {
self.state.done = Some(Done {
donedata: donedata.clone().unwrap_or(Value::Undefined),
configuration: ids(&self.state.core, configuration.iter().copied()),
active_leaf_states: leaf_ids(&self.state.core, configuration.iter().copied()),
active_leaf_count: leaf_count(&self.state.core, configuration.iter().copied()),
});
self.state.timers.clear();
self.external.clear();
self.mailbox.clear();
self.state.invocations.clear();
self.return_done(donedata.clone().unwrap_or(Value::Undefined));
Vec::new()
}
Effect::Invoke {
invoke_id,
invoke_type,
params,
content,
..
} => self.start_child(invoke_id, invoke_type.as_ref(), params, content.as_ref()),
Effect::CancelInvoke { invoke_id, .. } => {
self.cancel_child(invoke_id);
Vec::new()
}
Effect::Autoforward { invoke_id, .. } => {
if let Some(event) = self.taking.clone() {
self.deliver(invoke_id, event);
}
Vec::new()
}
Effect::BudgetExhausted { .. } => {
self.state.halted = true;
Vec::new()
}
_ => Vec::new(),
}
}
fn registered(&self, send_type: Option<&Value>) -> bool {
matches!(send_type, Some(Value::String(send_type)) if self.state.core.send_types.contains(send_type))
}
fn delivery(
&self,
event: &Option<Value>,
target: &Option<Value>,
data: &Value,
send_id: &str,
id_from_author: bool,
) -> Delivery {
let name = match event {
Some(Value::String(name)) => name.clone(),
_ => String::new(),
};
Delivery {
target: target.clone(),
event: Event {
name,
event_type: EventType::External,
sendid: id_from_author.then(|| send_id.to_owned()),
origin: Some(scxml_location(&self.state.session_id)),
origintype: Some(SCXML_EVENT_PROCESSOR.to_owned()),
invokeid: None,
data: data.clone(),
},
}
}
fn route(&mut self, send: Delivery, immediate: bool) -> Vec<Effect> {
match interpreter::parse_target(send.target.as_ref()) {
Route::Own => self.enqueue_own(send.event, immediate),
Route::Session(id) if id == self.state.session_id => {
self.enqueue_own(send.event, immediate)
}
Route::Parent if self.state.invoked_as.is_some() => {
if !self.state.halted || immediate {
self.post_to_parent(send.event, immediate);
}
Vec::new()
}
Route::Invoke(id) if self.state.invocations.contains_key(&id) => {
if !self.state.halted || immediate {
self.deliver(&id, send.event);
}
Vec::new()
}
Route::Internal => {
let mut event = send.event;
event.event_type = EventType::Internal;
event.origin = None;
event.origintype = None;
if !immediate {
return self.fired_internal(event);
}
self.sent_internal = self.sent_internal.saturating_add(1);
if self.state.round_budget.admits(self.sent_internal) {
self.deliver_internal(event)
} else {
self.spend(event)
}
}
_ => {
let mut event = Event::platform("error.communication", Value::Undefined);
event.sendid = send.event.sendid;
self.fired_internal(event)
}
}
}
fn fired_internal(&mut self, event: Event) -> Vec<Effect> {
if self.state.halted {
return Vec::new();
}
self.deliver_internal(event)
}
fn enqueue_own(&mut self, event: Event, counted: bool) -> Vec<Effect> {
self.external.push_back(Queued { event, counted });
Vec::new()
}
fn deliver_internal(&mut self, event: Event) -> Vec<Effect> {
if !self.state.core.running {
return Vec::new();
}
if self.spent {
self.state.core.enqueue(event);
return Vec::new();
}
self.stamp();
match interpreter::deliver_internal(&self.state.core, event) {
Ok(stepped) => {
self.state.core = stepped.state;
stepped.effects
}
Err(_) => Vec::new(),
}
}
fn spend(&mut self, event: Event) -> Vec<Effect> {
if !self.state.core.running {
return Vec::new();
}
self.spent = true;
self.state.core.enqueue(event);
if self.state.halted {
return Vec::new();
}
self.state.halted = true;
vec![interpreter::budget_exhausted(
&self.state.core,
self.state.round_budget.spent(),
)]
}
}
fn pending_timers(state: &State, path: &mut Vec<String>, out: &mut Vec<(Vec<String>, u64, u64)>) {
out.extend(
state
.timers
.iter()
.map(|timer| (path.clone(), timer.due_ms, timer.sequence)),
);
for (invoke_id, invocation) in &state.invocations {
path.push(invoke_id.clone());
pending_timers(&invocation.child, path, out);
path.pop();
}
}