use crate::action::action_trait::{Permission, PermissionMode};
use crate::action::{ActionContext, ApiResponse};
use crate::error::BaseError;
use async_trait::async_trait;
use std::any::{Any, TypeId};
use std::future::Future;
use std::pin::Pin;
use super::meta::ActionMeta;
#[async_trait]
pub trait Action: Send + Sync + 'static {
type Input: crate::definition::ParamInput
+ serde::de::DeserializeOwned
+ schemars::JsonSchema
+ Send
+ 'static;
type Output: serde::Serialize + schemars::JsonSchema + Send + 'static;
fn params() -> crate::definition::Params {
<Self::Input as crate::definition::ParamInput>::params()
}
fn calls(&self) -> Vec<crate::definition::ActionRef> {
Vec::new()
}
fn bind_registry(&self, _registry: &crate::definition::Registry) -> Result<(), BaseError> {
Ok(())
}
async fn index(
&self,
ctx: ActionContext,
input: Self::Input,
) -> Result<Self::Output, BaseError>;
}
#[async_trait]
impl<T> TypedHandler for T
where
T: Action,
{
type Input = T::Input;
type Output = T::Output;
async fn handle(
&self,
ctx: ActionContext,
input: Self::Input,
) -> Result<Self::Output, BaseError> {
self.index(ctx, input).await
}
fn handle_future(
&self,
ctx: ActionContext,
input: Self::Input,
) -> Pin<Box<dyn Future<Output = Result<Self::Output, BaseError>> + Send + '_>> {
<T as Action>::index(self, ctx, input)
}
fn decode_input(&self, ctx: &mut ActionContext) -> Result<Self::Input, BaseError> {
<Self::Input as crate::definition::ParamInput>::decode(&mut ctx.request)
}
fn bind_registry(&self, registry: &crate::definition::Registry) -> Result<(), BaseError> {
<T as Action>::bind_registry(self, registry)
}
}
#[async_trait]
pub trait TypedHandler: Send + Sync + 'static {
type Input: serde::de::DeserializeOwned + schemars::JsonSchema + Send + 'static;
type Output: serde::Serialize + schemars::JsonSchema + Send + 'static;
fn decode_input(&self, ctx: &mut ActionContext) -> Result<Self::Input, BaseError> {
ctx.extract_input_owned()
}
fn bind_registry(&self, _registry: &crate::definition::Registry) -> Result<(), BaseError> {
Ok(())
}
async fn handle(
&self,
ctx: ActionContext,
input: Self::Input,
) -> Result<Self::Output, BaseError>;
fn handle_future(
&self,
ctx: ActionContext,
input: Self::Input,
) -> Pin<Box<dyn Future<Output = Result<Self::Output, BaseError>> + Send + '_>> {
self.handle(ctx, input)
}
}
pub trait TypedAction: TypedHandler {
fn name(&self) -> &'static str;
fn display_name(&self) -> &'static str {
self.name()
}
fn description(&self) -> &'static str {
""
}
fn http_method(&self) -> crate::definition::HttpMethod {
crate::definition::HttpMethod::Post
}
fn path(&self) -> &'static str {
""
}
fn success_status(&self) -> u16 {
200
}
fn permissions(&self) -> &'static [Permission] {
&[]
}
fn is_public(&self) -> bool {
false
}
fn multipart_spec(&self) -> Option<crate::definition::MultipartSpec> {
None
}
fn response_kind(&self) -> crate::definition::ActionResponseKind {
crate::definition::ActionResponseKind::Json
}
fn permission_mode(&self) -> PermissionMode {
PermissionMode::default()
}
fn input_schema(&self) -> &'static schemars::schema::RootSchema;
fn output_schema(&self) -> &'static schemars::schema::RootSchema;
fn meta_static(&self) -> &'static ActionMeta;
}
#[async_trait]
pub trait DynAction: Send + Sync + 'static {
async fn dispatch(&self, ctx: ActionContext) -> Result<ApiResponse, BaseError>;
fn meta(&self) -> &'static ActionMeta;
fn input_type_id(&self) -> TypeId {
TypeId::of::<()>()
}
fn output_type_id(&self) -> TypeId {
TypeId::of::<()>()
}
async fn call_boxed(
&self,
_ctx: ActionContext,
_input: Box<dyn Any + Send>,
) -> Result<Box<dyn Any + Send>, BaseError> {
Err(BaseError::ConfigError(
"该 Action 未提供强类型内部调用入口".to_string(),
))
}
fn bind_registry(&self, _registry: &crate::definition::Registry) -> Result<(), BaseError> {
Ok(())
}
}
#[async_trait]
impl<T: TypedAction> DynAction for T {
async fn dispatch(&self, ctx: ActionContext) -> Result<ApiResponse, BaseError> {
use tracing::Instrument;
let action_name = self.meta().name;
let span = tracing::info_span!("handle", action = action_name);
#[cfg(feature = "metrics")]
let start = std::time::Instant::now();
#[cfg(feature = "metrics")]
let module: String = ctx.module.clone().unwrap_or_else(|| "unknown".to_string());
let result: Result<ApiResponse, BaseError> = async {
let mut ctx = ctx;
let input: T::Input = self.decode_input(&mut ctx)?;
let output = self.handle_future(ctx, input).await?;
super::response::wrap_dispatch_output(output, "成功")
}
.instrument(span)
.await;
#[cfg(feature = "metrics")]
{
let elapsed = start.elapsed().as_secs_f64();
metrics::histogram!(
"yang_action_duration_seconds",
"module" => module.clone(),
"action" => action_name,
)
.record(elapsed);
match &result {
Ok(_) => {
metrics::counter!(
"yang_action_requests_total",
"module" => module.clone(),
"action" => action_name,
"status" => "ok",
)
.increment(1);
}
Err(e) => {
metrics::counter!(
"yang_action_requests_total",
"module" => module.clone(),
"action" => action_name,
"status" => "error",
)
.increment(1);
metrics::counter!(
"yang_action_errors_total",
"module" => module,
"action" => action_name,
"code" => e.code_str(),
)
.increment(1);
}
}
}
result
}
fn meta(&self) -> &'static ActionMeta {
TypedAction::meta_static(self)
}
fn input_type_id(&self) -> TypeId {
TypeId::of::<T::Input>()
}
fn output_type_id(&self) -> TypeId {
TypeId::of::<T::Output>()
}
async fn call_boxed(
&self,
ctx: ActionContext,
input: Box<dyn Any + Send>,
) -> Result<Box<dyn Any + Send>, BaseError> {
let input = input.downcast::<T::Input>().map_err(|_| {
BaseError::ConfigError(format!("Action {} 的内部调用输入类型不匹配", self.name()))
})?;
let output = self.handle_future(ctx, *input).await?;
Ok(Box::new(output))
}
fn bind_registry(&self, registry: &crate::definition::Registry) -> Result<(), BaseError> {
TypedHandler::bind_registry(self, registry)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::action::{ActionContext, Request, ResponseAttachment, ResponseBody};
use crate::tools::ToolsBuilder;
use serde::Deserialize;
use std::sync::Arc;
use yang_base_derive::Action;
#[derive(Debug, Default, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
struct EmptyInput {}
#[derive(Action)]
#[action(name = "redirect_probe", display_name = "重定向探针")]
struct RedirectProbe;
#[async_trait]
impl TypedHandler for RedirectProbe {
type Input = EmptyInput;
type Output = ResponseBody;
async fn handle(
&self,
_ctx: ActionContext,
_input: Self::Input,
) -> Result<Self::Output, BaseError> {
Ok(ResponseBody::redirect("/next"))
}
}
#[derive(Debug, serde::Serialize, schemars::JsonSchema)]
struct PlainOutput {
value: i32,
}
#[derive(Action)]
#[action(name = "plain_probe", display_name = "普通探针")]
struct PlainProbe;
#[async_trait]
impl TypedHandler for PlainProbe {
type Input = EmptyInput;
type Output = PlainOutput;
async fn handle(
&self,
_ctx: ActionContext,
_input: Self::Input,
) -> Result<Self::Output, BaseError> {
Ok(PlainOutput { value: 1 })
}
}
fn test_context() -> ActionContext {
let tools = Arc::new(ToolsBuilder::new().build().expect("空 Tools 应构建成功"));
ActionContext::new(Request::new(serde_json::json!({})), tools)
}
#[tokio::test]
async fn dispatch_wraps_response_body_into_attachment() {
let response = RedirectProbe
.dispatch(test_context())
.await
.expect("dispatch 应成功");
assert_eq!(response.code, 0);
assert!(response.data.is_none());
assert_eq!(
response.attachment,
Some(ResponseAttachment::Redirect {
url: "/next".to_string(),
})
);
}
#[tokio::test]
async fn dispatch_keeps_plain_output_in_data() {
let response = PlainProbe
.dispatch(test_context())
.await
.expect("dispatch 应成功");
assert_eq!(response.data.as_ref().expect("应有 data")["value"], 1);
assert!(response.attachment.is_none());
}
}