use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use crate::context::HttpContext;
use crate::error::Result;
use crate::http::Response;
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
pub trait Action: Send + Sync + 'static {
fn call(&self, ctx: HttpContext) -> BoxFuture<'static, Result<Response>>;
fn name(&self) -> &'static str {
std::any::type_name::<Self>()
}
fn openapi(&self) -> Option<crate::openapi::Operation> {
None
}
}
pub trait Middleware: Send + Sync + 'static {
fn handle<'a>(&'a self, ctx: HttpContext, next: Next) -> BoxFuture<'a, Result<Response>>;
}
pub struct Next {
stack: Arc<[Arc<dyn Middleware>]>,
index: usize,
action: Arc<dyn Action>,
}
impl Next {
pub(crate) fn new(stack: Arc<[Arc<dyn Middleware>]>, action: Arc<dyn Action>) -> Self {
Self {
stack,
index: 0,
action,
}
}
pub async fn run(mut self, ctx: HttpContext) -> Result<Response> {
match self.stack.get(self.index).cloned() {
Some(middleware) => {
self.index += 1;
middleware.handle(ctx, self).await
}
None => self.action.call(ctx).await,
}
}
}
impl std::fmt::Debug for Next {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Next")
.field("remaining", &(self.stack.len().saturating_sub(self.index)))
.finish()
}
}