1use 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#[async_trait]
21pub trait Action: Send + Sync + 'static {
22 type Input: crate::definition::ParamInput
24 + serde::de::DeserializeOwned
25 + schemars::JsonSchema
26 + Send
27 + 'static;
28
29 type Output: serde::Serialize + schemars::JsonSchema + Send + 'static;
31
32 fn params() -> crate::definition::Params {
34 <Self::Input as crate::definition::ParamInput>::params()
35 }
36
37 fn calls(&self) -> Vec<crate::definition::ActionRef> {
39 Vec::new()
40 }
41
42 fn bind_registry(&self, _registry: &crate::definition::Registry) -> Result<(), BaseError> {
44 Ok(())
45 }
46
47 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#[async_trait]
90pub trait TypedHandler: Send + Sync + 'static {
91 type Input: serde::de::DeserializeOwned + schemars::JsonSchema + Send + 'static;
93
94 type Output: serde::Serialize + schemars::JsonSchema + Send + 'static;
96
97 fn decode_input(&self, ctx: &mut ActionContext) -> Result<Self::Input, BaseError> {
100 ctx.extract_input_owned()
101 }
102
103 fn bind_registry(&self, _registry: &crate::definition::Registry) -> Result<(), BaseError> {
105 Ok(())
106 }
107
108 async fn handle(
110 &self,
111 ctx: ActionContext,
112 input: Self::Input,
113 ) -> Result<Self::Output, BaseError>;
114
115 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
125pub trait TypedAction: TypedHandler {
127 fn name(&self) -> &'static str;
129
130 fn display_name(&self) -> &'static str {
132 self.name()
133 }
134
135 fn description(&self) -> &'static str {
137 ""
138 }
139
140 fn http_method(&self) -> crate::definition::HttpMethod {
142 crate::definition::HttpMethod::Post
143 }
144
145 fn path(&self) -> &'static str {
147 ""
148 }
149
150 fn success_status(&self) -> u16 {
152 200
153 }
154
155 fn permissions(&self) -> &'static [Permission] {
157 &[]
158 }
159
160 fn is_public(&self) -> bool {
162 false
163 }
164
165 fn multipart_spec(&self) -> Option<crate::definition::MultipartSpec> {
167 None
168 }
169
170 fn response_kind(&self) -> crate::definition::ActionResponseKind {
172 crate::definition::ActionResponseKind::Json
173 }
174
175 fn permission_mode(&self) -> PermissionMode {
177 PermissionMode::default()
178 }
179
180 fn input_schema(&self) -> &'static schemars::schema::RootSchema;
182
183 fn output_schema(&self) -> &'static schemars::schema::RootSchema;
185
186 fn meta_static(&self) -> &'static ActionMeta;
188}
189
190#[async_trait]
194pub trait DynAction: Send + Sync + 'static {
195 async fn dispatch(&self, ctx: ActionContext) -> Result<ApiResponse, BaseError>;
197
198 fn meta(&self) -> &'static ActionMeta;
200
201 fn input_type_id(&self) -> TypeId {
203 TypeId::of::<()>()
204 }
205
206 fn output_type_id(&self) -> TypeId {
208 TypeId::of::<()>()
209 }
210
211 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 fn bind_registry(&self, _registry: &crate::definition::Registry) -> Result<(), BaseError> {
224 Ok(())
225 }
226}
227
228#[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 let span = tracing::info_span!("handle", action = action_name);
237
238 #[cfg(feature = "metrics")]
240 let start = std::time::Instant::now();
241 #[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 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 #[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 #[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 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 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}