moduforge_core/
middleware.rs

1use std::sync::Arc;
2
3use crate::error::ForgeResult;
4use moduforge_state::{transaction::Transaction, state::State};
5
6/// 可以用于事务处理的中间件 trait
7#[async_trait::async_trait]
8pub trait Middleware: Send + Sync {
9    /// 返回中间件的名称
10    fn name(&self) -> String;
11
12    /// 在事务到达核心分发之前处理事务
13    async fn before_dispatch(
14        &self,
15        transaction: &mut Transaction,
16    ) -> ForgeResult<()>;
17
18    /// 在核心分发之后处理结果
19    /// 返回一个可能包含需要额外处理的事务的 MiddlewareResult
20    async fn after_dispatch(
21        &self,
22        state: Option<Arc<State>>,
23        transactions: &[Transaction],
24    ) -> ForgeResult<Option<Transaction>>;
25}
26
27/// 用于事务处理的中间件类型别名
28pub type ArcMiddleware = Arc<dyn Middleware>;
29
30/// Middleware stack that holds multiple middleware
31#[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}