moduforge_core/
middleware.rs

1use std::sync::Arc;
2
3use crate::error::EditorResult;
4use moduforge_state::{transaction::Transaction, state::State};
5
6/// 表示中间件处理结果的结构体
7pub struct MiddlewareResult {
8    /// 原始处理结果
9    pub result: EditorResult<()>,
10    /// 需要额外处理的事务列表
11    pub additional_transaction: Option<Transaction>,
12}
13
14impl MiddlewareResult {
15    /// 创建一个只包含结果的处理结果
16    pub fn new(result: EditorResult<()>) -> Self {
17        Self { result, additional_transaction: None }
18    }
19
20    /// 创建一个包含结果和额外事务的处理结果
21    pub fn with_transactions(
22        result: EditorResult<()>,
23        transaction: Option<Transaction>,
24    ) -> Self {
25        Self { result, additional_transaction: transaction }
26    }
27}
28
29/// 可以用于事务处理的中间件 trait
30#[async_trait::async_trait]
31pub trait Middleware: Send + Sync {
32    /// 在事务到达核心分发之前处理事务
33    async fn before_dispatch(
34        &self,
35        transaction: &mut Transaction,
36    ) -> EditorResult<()>;
37
38    /// 在核心分发之后处理结果
39    /// 返回一个可能包含需要额外处理的事务的 MiddlewareResult
40    async fn after_dispatch(
41        &self,
42        state: Option<Arc<State>>,
43        transactions: &[Transaction],
44    ) -> EditorResult<MiddlewareResult>;
45}
46
47/// 用于事务处理的中间件类型别名
48pub type ArcMiddleware = Arc<dyn Middleware>;
49
50/// Middleware stack that holds multiple middleware
51#[derive(Clone)]
52pub struct MiddlewareStack {
53    pub middlewares: Vec<ArcMiddleware>,
54}
55
56impl MiddlewareStack {
57    pub fn new() -> Self {
58        Self { middlewares: Vec::new() }
59    }
60
61    pub fn add<M>(
62        &mut self,
63        middleware: M,
64    ) where
65        M: Middleware + 'static,
66    {
67        self.middlewares.push(Arc::new(middleware));
68    }
69
70    pub fn is_empty(&self) -> bool {
71        self.middlewares.is_empty()
72    }
73}
74
75impl Default for MiddlewareStack {
76    fn default() -> Self {
77        Self::new()
78    }
79}