moduforge_rules_expression/functions/state_guard.rs
1//! State 守卫模块
2//!
3//! 提供 RAII 模式的 State 管理,确保异常安全
4
5use std::sync::Arc;
6use moduforge_state::State;
7use super::custom::CustomFunctionRegistry;
8
9/// State 守卫,使用 RAII 模式自动管理 State 的设置和清理
10///
11/// 当 StateGuard 被创建时,会自动设置当前线程的 State 上下文
12/// 当 StateGuard 被丢弃时(包括异常情况),会自动清理 State 上下文
13///
14/// # 示例
15/// ```rust
16/// use std::sync::Arc;
17/// use moduforge_state::State;
18/// use moduforge_rules_expression::functions::StateGuard;
19///
20/// // 创建 State
21/// let state = Arc::new(create_test_state());
22///
23/// {
24/// // 设置 State 上下文
25/// let _guard = StateGuard::new(state);
26///
27/// // 在这个作用域内,自定义函数可以访问 State
28/// // 即使发生 panic,State 也会被正确清理
29///
30/// } // 这里 StateGuard 被自动丢弃,State 上下文被清理
31/// ```
32pub struct StateGuard {
33 _private: (),
34}
35
36impl StateGuard {
37 /// 创建新的 State 守卫
38 ///
39 /// # 参数
40 /// * `state` - 要设置的 State 对象
41 ///
42 /// # 返回值
43 /// 返回 StateGuard 实例,当其被丢弃时会自动清理 State
44 pub fn new(state: Arc<State>) -> Self {
45 CustomFunctionRegistry::set_current_state(Some(state));
46 Self { _private: () }
47 }
48
49 /// 创建空的 State 守卫(用于清理已有的 State)
50 ///
51 /// # 返回值
52 /// 返回 StateGuard 实例,会立即清理当前 State 并在丢弃时保持清理状态
53 pub fn empty() -> Self {
54 CustomFunctionRegistry::set_current_state(None);
55 Self { _private: () }
56 }
57
58 /// 获取当前是否有活跃的 State
59 ///
60 /// # 返回值
61 /// * `true` - 当前线程有活跃的 State
62 /// * `false` - 当前线程没有 State
63 pub fn has_active_state() -> bool {
64 CustomFunctionRegistry::has_current_state()
65 }
66}
67
68impl Drop for StateGuard {
69 /// 自动清理 State 上下文
70 ///
71 /// 当 StateGuard 被丢弃时(正常情况或异常情况),
72 /// 会自动清理当前线程的 State 上下文
73 fn drop(&mut self) {
74 CustomFunctionRegistry::set_current_state(None);
75 }
76}
77
78/// 便利宏,用于在指定作用域内设置 State
79///
80/// # 示例
81/// ```rust
82/// use moduforge_rules_expression::with_state;
83///
84/// let state = Arc::new(create_test_state());
85///
86/// with_state!(state => {
87/// // 在这个块内,State 是活跃的
88/// let result = isolate.run_standard("someExpression()")?;
89/// // 即使这里发生错误,State 也会被正确清理
90/// });
91/// // State 在这里已经被清理
92/// ```
93#[macro_export]
94macro_rules! with_state {
95 ($state:expr => $block:block) => {
96 {
97 let _guard = $crate::functions::StateGuard::new($state);
98 $block
99 }
100 };
101}
102
103/// 异步版本的 State 守卫便利函数
104///
105/// # 参数
106/// * `state` - 要设置的 State 对象
107/// * `future` - 要在 State 上下文中执行的异步操作
108///
109/// # 返回值
110/// 返回异步操作的结果
111///
112/// # 示例
113/// ```rust
114/// use moduforge_rules_expression::functions::with_state_async;
115///
116/// let state = Arc::new(create_test_state());
117///
118/// let result = with_state_async(state, async {
119/// let result1 = isolate.run_standard_with_state("expr1", state.clone()).await?;
120/// let result2 = isolate.run_unary_with_state("expr2", state.clone()).await?;
121/// Ok((result1, result2))
122/// }).await?;
123/// ```
124pub async fn with_state_async<T, F, Fut>(
125 state: Arc<State>,
126 future: F,
127) -> T
128where
129 F: FnOnce() -> Fut,
130 Fut: std::future::Future<Output = T>,
131{
132 let _guard = StateGuard::new(state);
133 future().await
134}
135
136#[cfg(test)]
137mod tests {
138 use super::*;
139 use std::sync::Arc;
140
141 #[test]
142 fn test_state_guard_basic() {
143 // 初始状态应该没有 State
144 assert!(!StateGuard::has_active_state());
145
146 {
147 // 创建一个模拟的 State(实际测试中需要真实的 State)
148 // let state = Arc::new(create_test_state());
149 // let _guard = StateGuard::new(state);
150
151 // 在这个作用域内应该有活跃的 State
152 // assert!(StateGuard::has_active_state());
153 }
154
155 // 离开作用域后,State 应该被清理
156 assert!(!StateGuard::has_active_state());
157 }
158
159 #[test]
160 fn test_state_guard_panic_safety() {
161 assert!(!StateGuard::has_active_state());
162
163 let result = std::panic::catch_unwind(|| {
164 // let state = Arc::new(create_test_state());
165 // let _guard = StateGuard::new(state);
166
167 // 模拟 panic
168 // panic!("测试 panic 安全性");
169 });
170
171 // 即使发生了 panic,State 也应该被正确清理
172 assert!(!StateGuard::has_active_state());
173 assert!(result.is_err());
174 }
175
176 #[test]
177 fn test_empty_guard() {
178 // 创建空守卫应该立即清理 State
179 let _guard = StateGuard::empty();
180 assert!(!StateGuard::has_active_state());
181 }
182}