Skip to main content

serenade_messenger/
middleware.rs

1//! Dispatch context and middleware for the sync message bus.
2
3use std::any::Any;
4
5use crate::MessengerError;
6
7/// Whether the bus is dispatching a command or an event.
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum DispatchKind {
10    /// Single-handler command.
11    Command,
12    /// Fan-out event.
13    Event,
14}
15
16/// Context passed to each middleware for one dispatch.
17///
18/// `'msg` names the borrowed command/event payload lifetime.
19#[derive(Clone, Copy)]
20pub struct DispatchContext<'msg> {
21    /// [`crate::Message::NAME`] for the payload.
22    pub message_name: &'static str,
23    /// Command vs event dispatch.
24    pub kind: DispatchKind,
25    /// Erased message payload (command or event).
26    pub payload: &'msg dyn Any,
27}
28
29/// Onion layer around handler execution.
30///
31/// Middlewares run in registration order (first registered is outermost). Call `next` to
32/// continue toward the handler (or reject without calling `next`).
33pub trait Middleware: Send + Sync {
34    /// Runs this layer, optionally calling `next`.
35    ///
36    /// # Errors
37    ///
38    /// Return [`MessengerError`] to abort the dispatch (after or instead of `next`).
39    fn handle(
40        &self,
41        ctx: &DispatchContext<'_>,
42        next: &dyn Fn() -> Result<(), MessengerError>,
43    ) -> Result<(), MessengerError>;
44}
45
46/// Sink used by [`LoggingMiddleware`] (apps typically forward to `tracing`;
47/// see `docs-dev/OBSERVABILITY.md`).
48pub trait LogSink: Send + Sync {
49    /// Records that a message is entering the pipeline.
50    fn record(&self, ctx: &DispatchContext<'_>);
51}
52
53/// Middleware that records each dispatch through a [`LogSink`].
54#[derive(Debug, Clone)]
55pub struct LoggingMiddleware<S> {
56    sink: S,
57}
58
59impl<S> LoggingMiddleware<S> {
60    /// Creates a logging layer around `sink`.
61    #[must_use]
62    pub const fn new(sink: S) -> Self {
63        Self { sink }
64    }
65}
66
67impl<S: LogSink> Middleware for LoggingMiddleware<S> {
68    fn handle(
69        &self,
70        ctx: &DispatchContext<'_>,
71        next: &dyn Fn() -> Result<(), MessengerError>,
72    ) -> Result<(), MessengerError> {
73        self.sink.record(ctx);
74        next()
75    }
76}
77
78/// Hook used by [`ValidationMiddleware`] before the handler runs.
79pub trait ValidateHook: Send + Sync {
80    /// Returns `Ok(())` when the message may proceed.
81    ///
82    /// # Errors
83    ///
84    /// Reject invalid messages (typically [`MessengerError::Rejected`]).
85    fn validate(&self, ctx: &DispatchContext<'_>) -> Result<(), MessengerError>;
86}
87
88/// Middleware that runs a [`ValidateHook`] before calling `next`.
89#[derive(Debug, Clone)]
90pub struct ValidationMiddleware<V> {
91    validator: V,
92}
93
94impl<V> ValidationMiddleware<V> {
95    /// Creates a validation layer around `validator`.
96    #[must_use]
97    pub const fn new(validator: V) -> Self {
98        Self { validator }
99    }
100}
101
102impl<V: ValidateHook> Middleware for ValidationMiddleware<V> {
103    fn handle(
104        &self,
105        ctx: &DispatchContext<'_>,
106        next: &dyn Fn() -> Result<(), MessengerError>,
107    ) -> Result<(), MessengerError> {
108        self.validator.validate(ctx)?;
109        next()
110    }
111}