Skip to main content

yang_base/action/
typed.rs

1//! 类型化 Action 三层 trait
2//!
3//! - `TypedHandler`: 用户唯一手写的 trait,处理 Input -> Output
4//! - `TypedAction`: 元信息层(由 `#[derive(Action)]` 派生)
5//! - `DynAction`: object-safe 擦除层,存入 router 派发
6//!
7//! 通过 `blanket impl<T: TypedAction> DynAction for T` 自动桥接。
8
9use crate::action::action_trait::{Permission, PermissionMode};
10use crate::action::{ActionContext, ApiResponse};
11use crate::error::BaseError;
12use async_trait::async_trait;
13use std::any::{Any, TypeId};
14use std::future::Future;
15use std::pin::Pin;
16
17use super::meta::ActionMeta;
18
19/// 面向业务的永久 Action 接口:params 由强类型 Input 生成,业务只实现 index。
20#[async_trait]
21pub trait Action: Send + Sync + 'static {
22    /// `params!` 生成的强类型输入。
23    type Input: crate::definition::ParamInput
24        + serde::de::DeserializeOwned
25        + schemars::JsonSchema
26        + Send
27        + 'static;
28
29    /// 强类型输出。
30    type Output: serde::Serialize + schemars::JsonSchema + Send + 'static;
31
32    /// 返回 Input 的唯一原生参数定义。
33    fn params() -> crate::definition::Params {
34        <Self::Input as crate::definition::ParamInput>::params()
35    }
36
37    /// 声明内部 Action 依赖;AppBuilder 在构建期交叉校验。
38    fn calls(&self) -> Vec<crate::definition::ActionRef> {
39        Vec::new()
40    }
41
42    /// 在 Registry 冻结后绑定 ActionLink;请求期不再解析名称。
43    fn bind_registry(&self, _registry: &crate::definition::Registry) -> Result<(), BaseError> {
44        Ok(())
45    }
46
47    /// 执行业务逻辑。
48    async fn index(
49        &self,
50        ctx: ActionContext,
51        input: Self::Input,
52    ) -> Result<Self::Output, BaseError>;
53}
54
55#[async_trait]
56impl<T> TypedHandler for T
57where
58    T: Action,
59{
60    type Input = T::Input;
61    type Output = T::Output;
62
63    async fn handle(
64        &self,
65        ctx: ActionContext,
66        input: Self::Input,
67    ) -> Result<Self::Output, BaseError> {
68        self.index(ctx, input).await
69    }
70
71    fn handle_future(
72        &self,
73        ctx: ActionContext,
74        input: Self::Input,
75    ) -> Pin<Box<dyn Future<Output = Result<Self::Output, BaseError>> + Send + '_>> {
76        <T as Action>::index(self, ctx, input)
77    }
78
79    fn decode_input(&self, ctx: &mut ActionContext) -> Result<Self::Input, BaseError> {
80        <Self::Input as crate::definition::ParamInput>::decode(&mut ctx.request)
81    }
82
83    fn bind_registry(&self, registry: &crate::definition::Registry) -> Result<(), BaseError> {
84        <T as Action>::bind_registry(self, registry)
85    }
86}
87
88/// 用户业务逻辑 trait。Input/Output 是编译期契约。
89#[async_trait]
90pub trait TypedHandler: Send + Sync + 'static {
91    /// 输入类型(请求体反序列化目标)
92    type Input: serde::de::DeserializeOwned + schemars::JsonSchema + Send + 'static;
93
94    /// 输出类型(响应数据序列化源)
95    type Output: serde::Serialize + schemars::JsonSchema + Send + 'static;
96
97    /// 从请求构造 Input。旧 TypedHandler 默认读取 body;原生 Action 由 ParamInput
98    /// 按 body/query/path/header 的静态定义覆盖该行为。
99    fn decode_input(&self, ctx: &mut ActionContext) -> Result<Self::Input, BaseError> {
100        ctx.extract_input_owned()
101    }
102
103    /// AppBuilder 构建期依赖绑定钩子。
104    fn bind_registry(&self, _registry: &crate::definition::Registry) -> Result<(), BaseError> {
105        Ok(())
106    }
107
108    /// 业务执行
109    async fn handle(
110        &self,
111        ctx: ActionContext,
112        input: Self::Input,
113    ) -> Result<Self::Output, BaseError>;
114
115    /// 返回 Handler future;原生 Action 覆盖此入口以避免 async-trait 适配层二次装箱。
116    fn handle_future(
117        &self,
118        ctx: ActionContext,
119        input: Self::Input,
120    ) -> Pin<Box<dyn Future<Output = Result<Self::Output, BaseError>> + Send + '_>> {
121        self.handle(ctx, input)
122    }
123}
124
125/// 元信息层。由 `#[derive(Action)]` 自动实现;用户不手写。
126pub trait TypedAction: TypedHandler {
127    /// Action 唯一标识
128    fn name(&self) -> &'static str;
129
130    /// 用户可见的显示名(默认返回 name)
131    fn display_name(&self) -> &'static str {
132        self.name()
133    }
134
135    /// 简介(默认返回空字符串)
136    fn description(&self) -> &'static str {
137        ""
138    }
139
140    /// 原子注册的 HTTP method;默认 POST。
141    fn http_method(&self) -> crate::definition::HttpMethod {
142        crate::definition::HttpMethod::Post
143    }
144
145    /// 原子注册的 HTTP path;未显式配置时由 Action 名生成 `/<name>`。
146    fn path(&self) -> &'static str {
147        ""
148    }
149
150    /// 成功响应状态码。
151    fn success_status(&self) -> u16 {
152        200
153    }
154
155    /// 所需权限列表(默认为空)
156    fn permissions(&self) -> &'static [Permission] {
157        &[]
158    }
159
160    /// 是否公开(默认 false)
161    fn is_public(&self) -> bool {
162        false
163    }
164
165    /// 可选的受限 multipart 请求契约;默认只接受 JSON。
166    fn multipart_spec(&self) -> Option<crate::definition::MultipartSpec> {
167        None
168    }
169
170    /// 成功响应的静态类别;默认是普通 JSON。
171    fn response_kind(&self) -> crate::definition::ActionResponseKind {
172        crate::definition::ActionResponseKind::Json
173    }
174
175    /// 权限匹配模式(默认 All,即 AND 语义)
176    fn permission_mode(&self) -> PermissionMode {
177        PermissionMode::default()
178    }
179
180    /// 入参 JSON Schema(OnceLock 生成)
181    fn input_schema(&self) -> &'static schemars::schema::RootSchema;
182
183    /// 出参 JSON Schema
184    fn output_schema(&self) -> &'static schemars::schema::RootSchema;
185
186    /// 静态元信息聚合体
187    fn meta_static(&self) -> &'static ActionMeta;
188}
189
190/// 擦除层:router 存 `Arc<dyn DynAction>` 派发。
191///
192/// 名称刻意与 crate 根的 `#[derive(Action)]` 宏区分;业务代码无需直接实现本 trait。
193#[async_trait]
194pub trait DynAction: Send + Sync + 'static {
195    /// 派发:从 ctx 中提取输入、执行业务逻辑、封装响应
196    async fn dispatch(&self, ctx: ActionContext) -> Result<ApiResponse, BaseError>;
197
198    /// 获取静态元信息
199    fn meta(&self) -> &'static ActionMeta;
200
201    /// 返回强类型输入的 TypeId;手写擦除实现默认不支持内部强类型调用。
202    fn input_type_id(&self) -> TypeId {
203        TypeId::of::<()>()
204    }
205
206    /// 返回强类型输出的 TypeId;手写擦除实现默认不支持内部强类型调用。
207    fn output_type_id(&self) -> TypeId {
208        TypeId::of::<()>()
209    }
210
211    /// 使用已经反序列化的输入直接调用 Handler,不经过 JSON。
212    async fn call_boxed(
213        &self,
214        _ctx: ActionContext,
215        _input: Box<dyn Any + Send>,
216    ) -> Result<Box<dyn Any + Send>, BaseError> {
217        Err(BaseError::ConfigError(
218            "该 Action 未提供强类型内部调用入口".to_string(),
219        ))
220    }
221
222    /// Registry 冻结后的构建期绑定钩子。
223    fn bind_registry(&self, _registry: &crate::definition::Registry) -> Result<(), BaseError> {
224        Ok(())
225    }
226}
227
228/// Blanket 桥接:所有 TypedAction 自动是 DynAction。
229#[async_trait]
230impl<T: TypedAction> DynAction for T {
231    async fn dispatch(&self, ctx: ActionContext) -> Result<ApiResponse, BaseError> {
232        use tracing::Instrument;
233
234        let action_name = self.meta().name;
235        // handler span:静态 span 名 + 借用的 action 名,成功路径零分配
236        let span = tracing::info_span!("handle", action = action_name);
237
238        // feature="metrics" 时在唯一必经边界埋点;关闭时整段 #[cfg] 消失零开销
239        #[cfg(feature = "metrics")]
240        let start = std::time::Instant::now();
241        // 在 ctx 被移动进 async 块前,捕获 module 标签(NEW-2:跨模块同名 Action 区分)。
242        // 未经路由的上下文 module 为 None,回退为 "unknown" 保持低基数。
243        #[cfg(feature = "metrics")]
244        let module: String = ctx.module.clone().unwrap_or_else(|| "unknown".to_string());
245
246        let result: Result<ApiResponse, BaseError> = async {
247            let mut ctx = ctx;
248            let input: T::Input = self.decode_input(&mut ctx)?;
249            let output = self.handle_future(ctx, input).await?;
250            // 输出去向统一收口:ResponseBody 转附件响应,其余照旧序列化进 data
251            super::response::wrap_dispatch_output(output, "成功")
252        }
253        .instrument(span)
254        .await;
255
256        #[cfg(feature = "metrics")]
257        {
258            let elapsed = start.elapsed().as_secs_f64();
259            metrics::histogram!(
260                "yang_action_duration_seconds",
261                "module" => module.clone(),
262                "action" => action_name,
263            )
264            .record(elapsed);
265            match &result {
266                Ok(_) => {
267                    metrics::counter!(
268                        "yang_action_requests_total",
269                        "module" => module.clone(),
270                        "action" => action_name,
271                        "status" => "ok",
272                    )
273                    .increment(1);
274                }
275                Err(e) => {
276                    metrics::counter!(
277                        "yang_action_requests_total",
278                        "module" => module.clone(),
279                        "action" => action_name,
280                        "status" => "error",
281                    )
282                    .increment(1);
283                    metrics::counter!(
284                        "yang_action_errors_total",
285                        "module" => module,
286                        "action" => action_name,
287                        "code" => e.code_str(),
288                    )
289                    .increment(1);
290                }
291            }
292        }
293
294        result
295    }
296
297    fn meta(&self) -> &'static ActionMeta {
298        TypedAction::meta_static(self)
299    }
300
301    fn input_type_id(&self) -> TypeId {
302        TypeId::of::<T::Input>()
303    }
304
305    fn output_type_id(&self) -> TypeId {
306        TypeId::of::<T::Output>()
307    }
308
309    async fn call_boxed(
310        &self,
311        ctx: ActionContext,
312        input: Box<dyn Any + Send>,
313    ) -> Result<Box<dyn Any + Send>, BaseError> {
314        let input = input.downcast::<T::Input>().map_err(|_| {
315            BaseError::ConfigError(format!("Action {} 的内部调用输入类型不匹配", self.name()))
316        })?;
317        let output = self.handle_future(ctx, *input).await?;
318        Ok(Box::new(output))
319    }
320
321    fn bind_registry(&self, registry: &crate::definition::Registry) -> Result<(), BaseError> {
322        TypedHandler::bind_registry(self, registry)
323    }
324}
325
326#[cfg(test)]
327mod tests {
328    use super::*;
329    use crate::action::{ActionContext, Request, ResponseAttachment, ResponseBody};
330    use crate::tools::ToolsBuilder;
331    use serde::Deserialize;
332    use std::sync::Arc;
333    use yang_base_derive::Action;
334
335    #[derive(Debug, Default, Deserialize, schemars::JsonSchema)]
336    #[serde(deny_unknown_fields)]
337    struct EmptyInput {}
338
339    /// 返回重定向附件的探针 Action。
340    #[derive(Action)]
341    #[action(name = "redirect_probe", display_name = "重定向探针")]
342    struct RedirectProbe;
343
344    #[async_trait]
345    impl TypedHandler for RedirectProbe {
346        type Input = EmptyInput;
347        type Output = ResponseBody;
348
349        async fn handle(
350            &self,
351            _ctx: ActionContext,
352            _input: Self::Input,
353        ) -> Result<Self::Output, BaseError> {
354            Ok(ResponseBody::redirect("/next"))
355        }
356    }
357
358    #[derive(Debug, serde::Serialize, schemars::JsonSchema)]
359    struct PlainOutput {
360        value: i32,
361    }
362
363    /// 返回普通 JSON 输出的对照 Action。
364    #[derive(Action)]
365    #[action(name = "plain_probe", display_name = "普通探针")]
366    struct PlainProbe;
367
368    #[async_trait]
369    impl TypedHandler for PlainProbe {
370        type Input = EmptyInput;
371        type Output = PlainOutput;
372
373        async fn handle(
374            &self,
375            _ctx: ActionContext,
376            _input: Self::Input,
377        ) -> Result<Self::Output, BaseError> {
378            Ok(PlainOutput { value: 1 })
379        }
380    }
381
382    fn test_context() -> ActionContext {
383        let tools = Arc::new(ToolsBuilder::new().build().expect("空 Tools 应构建成功"));
384        ActionContext::new(Request::new(serde_json::json!({})), tools)
385    }
386
387    #[tokio::test]
388    async fn dispatch_wraps_response_body_into_attachment() {
389        // ResponseBody 输出经 dispatch 后应成为附件,不进 data
390        let response = RedirectProbe
391            .dispatch(test_context())
392            .await
393            .expect("dispatch 应成功");
394        assert_eq!(response.code, 0);
395        assert!(response.data.is_none());
396        assert_eq!(
397            response.attachment,
398            Some(ResponseAttachment::Redirect {
399                url: "/next".to_string(),
400            })
401        );
402    }
403
404    #[tokio::test]
405    async fn dispatch_keeps_plain_output_in_data() {
406        // 普通输出照旧进 data,无附件
407        let response = PlainProbe
408            .dispatch(test_context())
409            .await
410            .expect("dispatch 应成功");
411        assert_eq!(response.data.as_ref().expect("应有 data")["value"], 1);
412        assert!(response.attachment.is_none());
413    }
414}