use crate::action::action_trait::{Permission, PermissionMode};
use crate::action::{ActionContext, ApiResponse};
use crate::error::BaseError;
use async_trait::async_trait;
use super::meta::ActionMeta;
#[async_trait]
pub trait TypedHandler: Send + Sync + 'static {
type Input: serde::de::DeserializeOwned + schemars::JsonSchema + Send;
type Output: serde::Serialize + schemars::JsonSchema + Send;
async fn handle(
&self,
ctx: ActionContext,
input: Self::Input,
) -> Result<Self::Output, BaseError>;
}
pub trait TypedAction: TypedHandler {
fn name(&self) -> &'static str;
fn display_name(&self) -> &'static str {
self.name()
}
fn description(&self) -> &'static str {
""
}
fn permissions(&self) -> &'static [Permission] {
&[]
}
fn is_public(&self) -> bool {
false
}
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;
}
#[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 = ctx.extract_input_owned()?;
let output = self.handle(ctx, input).await?;
ApiResponse::success(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)
}
}