use super::{Done, RoundBudget, State, ids, is_built_in, leaf_count, leaf_ids};
use crate::interpreter::{self, Counters, MachineState, Routes, Sends};
use crate::machine::{Chart, Machine};
use predicator_rs::{Key, Map, Value};
use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::fmt;
#[cfg(test)]
mod tests;
const SESSION_ID: &str = "_sessionid";
const IOPROCESSORS: &str = "_ioprocessors";
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Status {
Running,
Done,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ActiveInvocation {
pub state: String,
pub invoke_index: u64,
pub invoke_id: String,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub struct Position {
pub identity: Value,
pub configuration: BTreeSet<String>,
pub entered_states: BTreeSet<String>,
pub states_to_invoke: BTreeSet<String>,
pub history_values: BTreeMap<String, BTreeSet<String>>,
pub active_invocations: Vec<ActiveInvocation>,
pub invoke_counter: u64,
pub send_counter: u64,
pub timer_counter: u64,
pub datamodel: Map,
pub running: bool,
pub status: Status,
pub macrostep: u64,
pub microstep: u64,
pub round: u64,
pub trace: bool,
pub max_macrostep_rounds: RoundBudget,
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExportError {
InternalQueueNotEmpty,
#[non_exhaustive]
UnnameableStates {
indexes: Vec<usize>,
},
}
impl fmt::Display for ExportError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ExportError::InternalQueueNotEmpty => {
formatter.write_str("the internal queue holds an event")
}
ExportError::UnnameableStates { indexes } => {
let indexes: Vec<String> = indexes.iter().map(usize::to_string).collect();
write!(
formatter,
"states with no id are in the position: {}",
indexes.join(", ")
)
}
}
}
}
impl std::error::Error for ExportError {}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ImportError {
NoSessionId,
#[non_exhaustive]
UnknownStateIds {
ids: Vec<String>,
},
#[non_exhaustive]
InvalidHistoryValue {
history: String,
},
#[non_exhaustive]
DuplicateInvocation {
state: String,
invoke_index: u64,
},
#[non_exhaustive]
UnknownInvoke {
state: String,
invoke_index: u64,
},
}
impl fmt::Display for ImportError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ImportError::NoSessionId => {
formatter.write_str("the datamodel's _sessionid is not a string")
}
ImportError::UnknownStateIds { ids } => {
write!(
formatter,
"the chart holds no state with these ids: {}",
ids.join(", ")
)
}
ImportError::InvalidHistoryValue { history } => {
write!(
formatter,
"the history value recorded for {history:?} cannot be restored"
)
}
ImportError::DuplicateInvocation {
state,
invoke_index,
} => write!(
formatter,
"two invocations name invoke {invoke_index} of {state:?}"
),
ImportError::UnknownInvoke {
state,
invoke_index,
} => write!(formatter, "{state:?} holds no invoke {invoke_index}"),
}
}
}
impl std::error::Error for ImportError {}
impl State {
pub fn export_position(&self) -> Result<Position, ExportError> {
let core = &self.core;
if !core.internal_queue.is_empty() {
return Err(ExportError::InternalQueueNotEmpty);
}
let chart = core.chart();
let unnameable: Vec<usize> = referenced(core)
.into_iter()
.filter(|&index| index != 0 && id_of(chart, index).is_none())
.collect();
if !unnameable.is_empty() {
return Err(ExportError::UnnameableStates {
indexes: unnameable,
});
}
let names = |indexes: &BTreeSet<usize>| -> BTreeSet<String> {
indexes
.iter()
.filter_map(|&index| id_of(chart, index))
.collect()
};
let history_values = core
.history
.iter()
.filter_map(|(&history, recorded)| {
id_of(chart, history).map(|history| (history, names(recorded)))
})
.collect();
let active_invocations = core
.active_invocations
.iter()
.filter_map(|(&(state, invoke_index), invoke_id)| {
id_of(chart, state).map(|state| ActiveInvocation {
state,
invoke_index,
invoke_id: invoke_id.clone(),
})
})
.collect();
Ok(Position {
identity: Value::Null,
configuration: names(&core.configuration),
entered_states: names(&core.entered_states),
states_to_invoke: names(&core.states_to_invoke),
history_values,
active_invocations,
invoke_counter: core.invoke_counter,
send_counter: core.sends.send_counter,
timer_counter: core.sends.timer_counter,
datamodel: core.datamodel.clone(),
running: core.running,
status: match core.status {
interpreter::Status::Running => Status::Running,
interpreter::Status::Done => Status::Done,
},
macrostep: core.counters.macrostep,
microstep: core.counters.microstep,
round: core.counters.round,
trace: self.trace,
max_macrostep_rounds: self.round_budget,
})
}
}
impl Machine {
pub fn import_position(&self, position: &Position) -> Result<State, ImportError> {
let session_id = match position.datamodel.get(&Key::from(SESSION_ID)) {
Some(Value::String(session_id)) => session_id.clone(),
_ => return Err(ImportError::NoSessionId),
};
let chart = self.chart();
let unknown: BTreeSet<&str> = named(position)
.filter(|id| !chart.id_to_index.contains_key(*id))
.collect();
if !unknown.is_empty() {
return Err(ImportError::UnknownStateIds {
ids: unknown.into_iter().map(str::to_owned).collect(),
});
}
let index = |id: &str| chart.id_to_index.get(id).copied().unwrap_or(0);
let indexes = |ids: &BTreeSet<String>| -> BTreeSet<usize> {
ids.iter().map(|id| index(id)).collect()
};
let mut history = BTreeMap::new();
for (key, recorded) in &position.history_values {
let restored = indexes(recorded);
if !restorable(chart, index(key), &restored) {
return Err(ImportError::InvalidHistoryValue {
history: key.clone(),
});
}
history.insert(index(key), restored);
}
let mut active_invocations = BTreeMap::new();
for invocation in &position.active_invocations {
let key = (index(&invocation.state), invocation.invoke_index);
let held = chart
.states
.get(key.0)
.map_or(0, |state| state.invoke.len());
if usize::try_from(invocation.invoke_index).map_or(true, |at| at >= held) {
return Err(ImportError::UnknownInvoke {
state: invocation.state.clone(),
invoke_index: invocation.invoke_index,
});
}
if active_invocations
.insert(key, invocation.invoke_id.clone())
.is_some()
{
return Err(ImportError::DuplicateInvocation {
state: invocation.state.clone(),
invoke_index: invocation.invoke_index,
});
}
}
let mut configuration = indexes(&position.configuration);
configuration.insert(0);
let mut entered_states = indexes(&position.entered_states);
entered_states.insert(0);
let core = MachineState {
machine: self.clone(),
configuration,
history,
datamodel: position.datamodel.clone(),
internal_queue: VecDeque::new(),
entered_states,
sends: Sends {
send_counter: position.send_counter,
timer_counter: position.timer_counter,
},
states_to_invoke: indexes(&position.states_to_invoke),
active_invocations,
invoke_counter: position.invoke_counter,
send_types: send_types(&position.datamodel),
routes: Some(Routes {
sessions: BTreeSet::from([session_id.clone()]),
..Routes::default()
}),
last_selection: None,
running: position.running,
status: match position.status {
Status::Running => interpreter::Status::Running,
Status::Done => interpreter::Status::Done,
},
counters: Counters {
macrostep: position.macrostep,
microstep: position.microstep,
round: position.round,
},
max_macrostep_rounds: position.max_macrostep_rounds.interpreter(),
};
let done = (position.status == Status::Done).then(|| Done {
donedata: Value::Undefined,
configuration: ids(&core, core.configuration.iter().copied()),
active_leaf_states: leaf_ids(&core, core.configuration.iter().copied()),
active_leaf_count: leaf_count(&core, core.configuration.iter().copied()),
});
let mut state = State::fresh(
core,
session_id,
position.max_macrostep_rounds,
position.trace,
);
state.done = done;
Ok(state)
}
}
fn id_of(chart: &Chart, index: usize) -> Option<String> {
chart.states.get(index).and_then(|state| state.id.clone())
}
fn referenced(core: &MachineState) -> BTreeSet<usize> {
let mut indexes: BTreeSet<usize> = core
.configuration
.iter()
.chain(&core.entered_states)
.chain(&core.states_to_invoke)
.copied()
.collect();
for (&history, recorded) in &core.history {
indexes.insert(history);
indexes.extend(recorded);
}
indexes.extend(core.active_invocations.keys().map(|&(state, _)| state));
indexes
}
fn named(position: &Position) -> impl Iterator<Item = &str> {
position
.configuration
.iter()
.chain(&position.entered_states)
.chain(&position.states_to_invoke)
.chain(
position
.history_values
.iter()
.flat_map(|(history, recorded)| std::iter::once(history).chain(recorded)),
)
.chain(position.active_invocations.iter().map(|item| &item.state))
.map(String::as_str)
}
fn restorable(chart: &Chart, history: usize, recorded: &BTreeSet<usize>) -> bool {
let Some(parent) = chart
.states
.get(history)
.filter(|_| chart.is_history(history))
.and_then(|state| state.parent)
else {
return false;
};
recorded
.iter()
.all(|&state| !chart.is_history(state) && chart.is_descendant(state, parent))
}
fn send_types(datamodel: &Map) -> BTreeSet<String> {
let Some(Value::Map(entries)) = datamodel.get(&Key::from(IOPROCESSORS)) else {
return BTreeSet::new();
};
entries
.keys()
.filter_map(|key| match key {
Key::String(send_type) if !is_built_in(send_type) => Some(send_type.clone()),
_ => None,
})
.collect()
}