use alloc::boxed::Box;
use alloc::string::String;
use core::time::Duration;
use serde_json::value::RawValue;
use crate::engine::{
CallOptions, CallToken, Engine, EngineConfig, EngineError, Input, Instant, MemStore,
MessageStore, Output, Timer,
};
use crate::rpc::CallError;
use crate::types::MessageId;
use crate::version::Version;
use super::Recorder;
pub struct Sim<S: MessageStore = MemStore> {
engine: Engine<S>,
recorder: Recorder,
now: Instant,
timers: alloc::collections::BTreeMap<Timer, Instant>,
}
impl Sim<MemStore> {
#[must_use]
pub fn new(config: EngineConfig) -> Self {
Self::with_engine(Engine::new(config))
}
}
impl<S: MessageStore> Sim<S> {
#[must_use]
pub fn with_engine(engine: Engine<S>) -> Self {
Self {
engine,
recorder: Recorder::new(),
now: Instant::ZERO,
timers: alloc::collections::BTreeMap::new(),
}
}
pub fn engine(&self) -> &Engine<S> {
&self.engine
}
pub fn engine_mut(&mut self) -> &mut Engine<S> {
&mut self.engine
}
#[must_use]
pub fn now(&self) -> Instant {
self.now
}
pub fn connect(&mut self, version: Version) -> &mut Self {
self.engine.handle(self.now, Input::Connected { version });
self.turn()
}
pub fn disconnect(&mut self) -> &mut Self {
self.engine.handle(self.now, Input::Disconnected);
self.turn()
}
pub fn recv(&mut self, text: &str) -> &mut Self {
self.engine.handle(self.now, Input::Received(text));
self.turn()
}
pub fn advance(&mut self, by: Duration) -> &mut Self {
self.advance_to(self.now.saturating_add(by))
}
pub fn advance_to(&mut self, at: Instant) -> &mut Self {
if at > self.now {
self.now = at;
}
self.engine.handle(self.now, Input::Timeout);
self.turn()
}
pub fn advance_to_next_timer(&mut self) -> bool {
let Some(at) = self.timers.values().min().copied() else {
return false;
};
self.advance_to(at);
true
}
pub fn call(&mut self, action: &str, payload: &str) -> Result<CallToken, EngineError> {
self.call_with(action, payload, CallOptions::default())
}
pub fn call_with(
&mut self,
action: &str,
payload: &str,
options: CallOptions,
) -> Result<CallToken, EngineError> {
let token = self
.engine
.call_with(self.now, action, raw(payload), options);
self.turn();
token
}
pub fn respond(&mut self, id: &MessageId, payload: &str) -> Result<(), EngineError> {
let result = self.engine.respond(self.now, id, &raw(payload));
self.turn();
result
}
pub fn respond_error(&mut self, id: &MessageId, error: CallError) -> Result<(), EngineError> {
let result = self.engine.respond_error(self.now, id, error);
self.turn();
result
}
pub fn shutdown(&mut self, deadline: Duration) -> &mut Self {
let at = self.now.saturating_add(deadline);
self.engine.shutdown(self.now, at);
self.turn()
}
pub fn turn(&mut self) -> &mut Self {
self.recorder.drain(&mut self.engine);
for output in self.recorder.outputs() {
match output {
Output::SetTimer { timer, at } => {
self.timers.insert(*timer, *at);
}
Output::ClearTimer(timer) => {
self.timers.remove(timer);
}
_ => {}
}
}
let now = self.now;
self.timers.retain(|_, at| *at > now);
self
}
#[must_use]
pub fn recorder(&self) -> &Recorder {
&self.recorder
}
#[must_use]
pub fn armed(&self) -> alloc::vec::Vec<(Timer, Instant)> {
self.timers.iter().map(|(t, at)| (*t, *at)).collect()
}
#[must_use]
pub fn armed_at(&self, timer: Timer) -> Option<Instant> {
self.timers.get(&timer).copied()
}
}
impl<S: MessageStore> core::ops::Deref for Sim<S> {
type Target = Recorder;
fn deref(&self) -> &Recorder {
&self.recorder
}
}
fn raw(payload: &str) -> Box<RawValue> {
RawValue::from_string(String::from(payload))
.unwrap_or_else(|error| panic!("{payload} is not valid JSON: {error}"))
}