use alloc::string::String;
use alloc::vec::Vec;
use crate::engine::{
CallFailure, CallOutcome, Engine, IncomingRequest, Instant, MessageStore, Output,
ProtocolViolation, Timer,
};
#[derive(Debug, Default)]
pub struct Recorder {
outputs: Vec<Output>,
}
impl Recorder {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn drain<S: MessageStore>(&mut self, engine: &mut Engine<S>) -> &mut Self {
self.outputs = engine.drain();
self
}
#[must_use]
pub fn outputs(&self) -> &[Output] {
&self.outputs
}
#[must_use]
pub fn frames(&self) -> Vec<&str> {
self.outputs
.iter()
.filter_map(|output| match output {
Output::Transmit(text) => Some(text.as_str()),
_ => None,
})
.collect()
}
#[must_use]
pub fn only_frame(&self) -> &str {
let frames = self.frames();
assert_eq!(
frames.len(),
1,
"expected exactly one frame, found {frames:?}"
);
frames[0]
}
#[must_use]
pub fn requests(&self) -> Vec<&IncomingRequest> {
self.outputs
.iter()
.filter_map(|output| match output {
Output::Request(request) => Some(request),
_ => None,
})
.collect()
}
#[must_use]
pub fn outcomes(&self) -> Vec<&CallOutcome> {
self.outputs
.iter()
.filter_map(|output| match output {
Output::Outcome(outcome) => Some(outcome),
_ => None,
})
.collect()
}
#[must_use]
pub fn failures(&self) -> Vec<(&str, &CallFailure)> {
self.outcomes()
.into_iter()
.filter_map(|outcome| {
outcome
.result
.as_ref()
.err()
.map(|failure| (outcome.action.as_str(), failure))
})
.collect()
}
#[must_use]
pub fn violations(&self) -> Vec<&ProtocolViolation> {
self.outputs
.iter()
.filter_map(|output| match output {
Output::Violation(violation) => Some(violation),
_ => None,
})
.collect()
}
#[must_use]
pub fn timers(&self) -> Vec<(Timer, Instant)> {
self.outputs
.iter()
.filter_map(|output| match output {
Output::SetTimer { timer, at } => Some((*timer, *at)),
_ => None,
})
.collect()
}
#[must_use]
pub fn timer(&self, timer: Timer) -> Option<Instant> {
self.timers()
.into_iter()
.rev()
.find(|(armed, _)| *armed == timer)
.map(|(_, at)| at)
}
#[must_use]
pub fn only_frame_id(&self) -> String {
let frame = self.only_frame();
let elements: Vec<&serde_json::value::RawValue> =
serde_json::from_str(frame).unwrap_or_else(|_| panic!("{frame} is not a JSON array"));
let id = elements
.get(1)
.and_then(|raw| serde_json::from_str::<String>(raw.get()).ok());
id.unwrap_or_else(|| panic!("{frame} has no string MessageId"))
}
}