use std::collections::BTreeMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use crate::error::AxiamError;
use super::protocol::ReactorEvent;
use super::registry::{EVENT_REGISTRY, event_spec};
use super::runtime::ReactorDecision;
pub type BoxedReactorFuture = Pin<Box<dyn Future<Output = ReactorDecision> + Send>>;
type BoxedHandler = Arc<dyn Fn(ReactorEvent) -> BoxedReactorFuture + Send + Sync>;
pub trait ReactorHandlerFn {
const EVENT: &'static str;
fn call(event: ReactorEvent) -> BoxedReactorFuture;
}
#[derive(Default)]
pub struct ReactorRouter {
handlers: BTreeMap<&'static str, BoxedHandler>,
order: Vec<&'static str>,
errors: Vec<String>,
}
impl std::fmt::Debug for ReactorRouter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ReactorRouter")
.field("events", &self.order)
.field("errors", &self.errors)
.finish()
}
}
impl ReactorRouter {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn bind<F, Fut>(mut self, event: &'static str, handler: F) -> Self
where
F: Fn(ReactorEvent) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ReactorDecision> + Send + 'static,
{
if event_spec(event).is_none() {
let hookable: Vec<&str> = EVENT_REGISTRY.iter().map(|spec| spec.name).collect();
self.errors.push(format!(
"{event} is not a hookable reactor event; the registry is [{}]",
hookable.join(", ")
));
return self;
}
if self.handlers.contains_key(event) {
self.errors
.push(format!("reactor event {event} is already bound"));
return self;
}
self.handlers
.insert(event, Arc::new(move |ev| Box::pin(handler(ev))));
self.order.push(event);
self
}
#[must_use]
pub fn on<H: ReactorHandlerFn>(self) -> Self {
self.bind(H::EVENT, |event| H::call(event))
}
pub fn events(&self) -> &[&'static str] {
&self.order
}
pub fn build(
self,
) -> Result<impl Fn(ReactorEvent) -> BoxedReactorFuture + Send + Sync + 'static, AxiamError>
{
if !self.errors.is_empty() {
return Err(AxiamError::network(self.errors.join("; ")));
}
if self.handlers.is_empty() {
return Err(AxiamError::network(
"ReactorRouter has no bindings; bind at least one event",
));
}
let handlers = self.handlers;
Ok(move |event: ReactorEvent| -> BoxedReactorFuture {
match handlers.get(event.event.as_str()) {
Some(handler) => handler(event),
None => Box::pin(std::future::ready(ReactorDecision::Abstain)),
}
})
}
}