moduforge_core/
middleware.rs1use std::sync::Arc;
2
3use crate::error::ForgeResult;
4use moduforge_state::{transaction::Transaction, state::State};
5
6#[async_trait::async_trait]
8pub trait Middleware: Send + Sync {
9 fn name(&self) -> String;
11
12 async fn before_dispatch(
14 &self,
15 transaction: &mut Transaction,
16 ) -> ForgeResult<()>;
17
18 async fn after_dispatch(
21 &self,
22 state: Option<Arc<State>>,
23 transactions: &[Transaction],
24 ) -> ForgeResult<Option<Transaction>>;
25}
26
27pub type ArcMiddleware = Arc<dyn Middleware>;
29
30#[derive(Clone)]
32pub struct MiddlewareStack {
33 pub middlewares: Vec<ArcMiddleware>,
34}
35
36impl MiddlewareStack {
37 pub fn new() -> Self {
38 Self { middlewares: Vec::new() }
39 }
40
41 pub fn add<M>(
42 &mut self,
43 middleware: M,
44 ) where
45 M: Middleware + 'static,
46 {
47 self.middlewares.push(Arc::new(middleware));
48 }
49
50 pub fn is_empty(&self) -> bool {
51 self.middlewares.is_empty()
52 }
53}
54
55impl Default for MiddlewareStack {
56 fn default() -> Self {
57 Self::new()
58 }
59}