use crate::{
error::Error,
handler::{Emit, HandlerError, Result},
middleware::{Flow, Middleware},
};
pub trait TombstoneRecord {
fn is_tombstone(&self) -> bool;
}
pub trait TombstonePublish<I>: Sized {
fn tombstone(input: &I) -> Result<Self>;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Policy {
Reject,
Skip,
}
#[derive(Clone, Copy, Debug)]
pub struct Tombstones {
policy: Policy,
}
impl Tombstones {
pub fn reject() -> Self {
Self {
policy: Policy::Reject,
}
}
pub fn skip() -> Self {
Self {
policy: Policy::Skip,
}
}
pub fn propagate() -> PropagateTombstones {
PropagateTombstones
}
}
impl<I, O> Middleware<I, O> for Tombstones
where
I: TombstoneRecord + Send + Sync + 'static,
O: Send + 'static,
{
async fn pre_handler(&self, input: I) -> Result<Flow<I, O>> {
if !input.is_tombstone() {
return Ok(Flow::Continue(input));
}
match self.policy {
Policy::Reject => Err(HandlerError::Reject(
Error::invalid_record("tombstone rejected before the handler").into(),
)),
Policy::Skip => Ok(Flow::Intercept(Emit::None)),
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct PropagateTombstones;
impl<I, O> Middleware<I, O> for PropagateTombstones
where
I: TombstoneRecord + Send + Sync + 'static,
O: TombstonePublish<I> + Send + 'static,
{
async fn pre_handler(&self, input: I) -> Result<Flow<I, O>> {
if !input.is_tombstone() {
return Ok(Flow::Continue(input));
}
O::tombstone(&input).map(|output| Flow::Intercept(Emit::One(output)))
}
}