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/// Middleware trait that can be implemented for transaction processing
30#[async_trait::async_trait]
31pub trait Middleware: Send + Sync {
32    /// Process the transaction before it reaches the core dispatch
33    async fn before_dispatch(
34        &self,
35        transaction: &mut Transaction,
36    ) -> EditorResult<()>;
37
38    /// Process the result after the core dispatch
39    /// Returns a MiddlewareResult that may contain additional transactions to be processed
40    async fn after_dispatch(
41        &self,
42        state: Option<Arc<State>>,
43    ) -> EditorResult<MiddlewareResult>;
44}
45
46/// Type alias for a boxed middleware
47pub type BoxedMiddleware = Box<dyn Middleware>;
48
49/// Middleware stack that holds multiple middleware
50pub struct MiddlewareStack {
51    pub middlewares: Vec<BoxedMiddleware>,
52}
53
54impl MiddlewareStack {
55    pub fn new() -> Self {
56        Self { middlewares: Vec::new() }
57    }
58
59    pub fn add<M>(
60        &mut self,
61        middleware: M,
62    ) where
63        M: Middleware + 'static,
64    {
65        self.middlewares.push(Box::new(middleware));
66    }
67
68    pub fn is_empty(&self) -> bool {
69        self.middlewares.is_empty()
70    }
71}
72
73impl Default for MiddlewareStack {
74    fn default() -> Self {
75        Self::new()
76    }
77}