use crate::error::BoxError;
use std::{future::Future, result::Result as StdResult};
pub type Result<T> = StdResult<T, HandlerError>;
#[derive(Debug)]
pub enum Emit<T> {
None,
One(T),
Many(Vec<T>),
}
impl<T> Emit<T> {
pub fn map<U>(self, f: impl FnMut(T) -> U) -> Emit<U> {
let mut f = f;
match self {
Self::None => Emit::None,
Self::One(v) => Emit::One(f(v)),
Self::Many(v) => Emit::Many(v.into_iter().map(f).collect()),
}
}
pub(crate) fn values(self) -> Vec<T> {
match self {
Self::None => vec![],
Self::One(v) => vec![v],
Self::Many(v) => v,
}
}
}
#[derive(Debug)]
pub enum HandlerError {
Retry(BoxError),
Reject(BoxError),
Fatal(BoxError),
}
impl<E: Into<BoxError>> From<E> for HandlerError {
fn from(error: E) -> Self {
Self::Reject(error.into())
}
}
pub trait Classify<T> {
fn reject(self) -> Result<T>;
fn retry(self) -> Result<T>;
fn fatal(self) -> Result<T>;
}
impl<T, E: Into<BoxError>> Classify<T> for StdResult<T, E> {
fn reject(self) -> Result<T> {
self.map_err(|error| HandlerError::Reject(error.into()))
}
fn retry(self) -> Result<T> {
self.map_err(|error| HandlerError::Retry(error.into()))
}
fn fatal(self) -> Result<T> {
self.map_err(|error| HandlerError::Fatal(error.into()))
}
}
pub trait Handler<I>: Send + Sync + 'static {
type Output: Send + Sync + 'static;
fn handle(&self, input: I) -> impl Future<Output = Result<Self::Output>> + Send;
}
impl<I, O, F, Fut> Handler<I> for F
where
F: Fn(I) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<O>> + Send,
O: Send + Sync + 'static,
{
type Output = O;
fn handle(&self, input: I) -> impl Future<Output = Result<O>> + Send {
self(input)
}
}