use std::collections::BTreeMap;
use astrs_wire::Parameter;
use crate::error::OpResult;
use crate::event::OpEvent;
use crate::output::OpOutput;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Status {
Continue,
Finished,
}
impl Status {
#[must_use]
pub const fn is_continue(self) -> bool {
matches!(self, Self::Continue)
}
#[must_use]
pub const fn is_finished(self) -> bool {
matches!(self, Self::Finished)
}
}
pub trait Operator: Send + 'static {
fn configure(&mut self, config: &BTreeMap<String, Parameter>) -> OpResult<()> {
let _ = config;
Ok(())
}
fn on_start(&mut self, out: &mut OpOutput) -> OpResult<()> {
let _ = out;
Ok(())
}
fn on_event(&mut self, event: &OpEvent, out: &mut OpOutput) -> OpResult<Status>;
fn on_stop(&mut self, out: &mut OpOutput) -> OpResult<()> {
let _ = out;
Ok(())
}
fn on_reload(&mut self, out: &mut OpOutput) -> OpResult<()> {
let _ = out;
Ok(())
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
#[test]
fn status_predicates() {
assert!(Status::Continue.is_continue());
assert!(!Status::Continue.is_finished());
assert!(Status::Finished.is_finished());
assert!(!Status::Finished.is_continue());
}
#[derive(Default)]
struct Counter {
seen: u32,
started: bool,
stopped: bool,
reloaded: bool,
}
impl Operator for Counter {
fn on_start(&mut self, _out: &mut OpOutput) -> OpResult<()> {
self.started = true;
Ok(())
}
fn on_event(&mut self, event: &OpEvent, out: &mut OpOutput) -> OpResult<Status> {
match event {
OpEvent::Input { metadata, .. } => {
self.seen += 1;
out.send_bytes("count", metadata.clone(), vec![self.seen as u8])?;
Ok(Status::Continue)
}
OpEvent::Stop { .. } => Ok(Status::Finished),
_ => Ok(Status::Continue),
}
}
fn on_stop(&mut self, _out: &mut OpOutput) -> OpResult<()> {
self.stopped = true;
Ok(())
}
fn on_reload(&mut self, _out: &mut OpOutput) -> OpResult<()> {
self.reloaded = true;
self.seen = 0;
Ok(())
}
}
fn input_event(payload: Vec<u8>) -> OpEvent {
use astrs_time::HlcTimestamp;
use astrs_wire::{DataId, Metadata};
OpEvent::Input {
id: DataId::new("frames").unwrap(),
source: "camera/image".parse().unwrap(),
metadata: Metadata::new(HlcTimestamp::EPOCH),
payload,
}
}
#[test]
fn a_toy_operator_runs_through_a_scripted_sequence() {
let mut op = Counter::default();
let mut out = OpOutput::new();
op.on_start(&mut out).unwrap();
assert!(op.started);
for i in 0..3u8 {
let status = op.on_event(&input_event(vec![i]), &mut out).unwrap();
assert_eq!(status, Status::Continue);
}
assert_eq!(op.seen, 3);
assert_eq!(out.len(), 3);
let sends = out.drain();
assert_eq!(sends[2].payload(), &[3]);
op.on_reload(&mut out).unwrap();
assert!(op.reloaded);
assert_eq!(op.seen, 0);
let stop = OpEvent::Stop {
cause: astrs_wire::StopCause::Requested,
grace: None,
};
let status = op.on_event(&stop, &mut out).unwrap();
assert_eq!(status, Status::Finished);
op.on_stop(&mut out).unwrap();
assert!(op.stopped);
}
#[test]
fn operator_is_object_safe() {
let boxed: Box<dyn Operator> = Box::new(Counter::default());
drop(boxed);
}
#[test]
fn configure_defaults_to_a_no_op() {
let mut op = Counter::default();
let mut config = BTreeMap::new();
config.insert("threshold".to_owned(), Parameter::Float(0.5));
op.configure(&config).unwrap();
assert_eq!(op.seen, 0, "the default configure touches no state");
}
#[derive(Default)]
struct Thresholded {
threshold: i64,
labels: Vec<String>,
}
impl Operator for Thresholded {
fn configure(&mut self, config: &BTreeMap<String, Parameter>) -> OpResult<()> {
match config.get("threshold") {
Some(Parameter::Integer(value)) => self.threshold = *value,
Some(other) => {
return Err(crate::OpError::failed(format!(
"threshold must be an integer, got {other:?}"
)));
}
None => {}
}
if let Some(Parameter::ListString(values)) = config.get("labels") {
self.labels = values.clone();
}
Ok(())
}
fn on_event(&mut self, _event: &OpEvent, _out: &mut OpOutput) -> OpResult<Status> {
Ok(Status::Continue)
}
}
#[test]
fn configure_can_read_a_typed_config_map() {
let mut op = Thresholded::default();
let mut config = BTreeMap::new();
config.insert("threshold".to_owned(), Parameter::Integer(7));
config.insert(
"labels".to_owned(),
Parameter::ListString(vec!["person".to_owned(), "car".to_owned()]),
);
op.configure(&config).unwrap();
assert_eq!(op.threshold, 7);
assert_eq!(op.labels, vec!["person".to_owned(), "car".to_owned()]);
}
#[test]
fn configure_can_reject_a_bad_value() {
let mut op = Thresholded::default();
let mut config = BTreeMap::new();
config.insert("threshold".to_owned(), Parameter::String("nope".to_owned()));
let error = op.configure(&config).unwrap_err();
assert!(matches!(error, crate::OpError::Failed { .. }));
assert_eq!(op.threshold, 0, "the rejected value must never be applied");
}
}