use crate::action::{ActionContext, ApiResponse, DynAction};
use crate::error::BaseError;
use crate::router::ModuleRouter;
use async_trait::async_trait;
use std::sync::Arc;
#[async_trait]
pub trait Middleware: Send + Sync + 'static {
async fn handle(&self, ctx: ActionContext, next: Next<'_>) -> Result<ApiResponse, BaseError>;
}
pub struct Next<'a> {
pub(crate) remaining: &'a [Arc<dyn Middleware>],
pub(crate) router: &'a ModuleRouter,
pub(crate) action: Arc<dyn DynAction>,
}
impl<'a> Next<'a> {
pub async fn run(self, ctx: ActionContext) -> Result<ApiResponse, BaseError> {
match self.remaining.split_first() {
Some((current, rest)) => {
let next = Next {
remaining: rest,
router: self.router,
action: self.action,
};
current.handle(ctx, next).await
}
None => self.router.authorize_and_dispatch(self.action, ctx).await,
}
}
}
pub struct RequestIdMiddleware;
#[async_trait]
impl Middleware for RequestIdMiddleware {
async fn handle(
&self,
mut ctx: ActionContext,
next: Next<'_>,
) -> Result<ApiResponse, BaseError> {
if let Some(raw) = ctx
.request
.headers
.get("X-Request-Id")
.or_else(|| ctx.request.headers.get("x-request-id"))
{
if let Some(rid) = crate::action::RequestId::parse_hex(raw) {
ctx = ctx.with_request_id(rid);
}
}
tracing::Span::current().record("request_id", tracing::field::display(ctx.request_id));
next.run(ctx).await
}
}