Skip to main content

serenade_http/
async_kernel.rs

1//! Async HTTP kernel: middleware pipeline plus exception mapping.
2
3use crate::{
4    AsyncMiddleware, AsyncNext, AsyncRequestHandler, BoxFuture, DefaultExceptionHandler,
5    ExceptionHandler, HttpError, Request, Response, SyncToAsync,
6};
7
8/// Runs async middleware, then the controller, and maps errors to responses.
9///
10/// # Examples
11///
12/// ```
13/// use serenade_http::{AsyncHttpKernel, Request, Response};
14///
15/// let _kernel = AsyncHttpKernel::from_sync(|_request: &mut Request| {
16///     Ok(Response::text(200, "ok"))
17/// });
18/// ```
19pub struct AsyncHttpKernel {
20    middleware: Vec<Box<dyn AsyncMiddleware>>,
21    controller: Box<dyn AsyncRequestHandler>,
22    exceptions: Box<dyn ExceptionHandler>,
23}
24
25impl AsyncHttpKernel {
26    /// Kernel with async `controller` and [`DefaultExceptionHandler`].
27    #[must_use]
28    pub fn new(controller: impl AsyncRequestHandler + 'static) -> Self {
29        Self {
30            middleware: Vec::new(),
31            controller: Box::new(controller),
32            exceptions: Box::new(DefaultExceptionHandler),
33        }
34    }
35
36    /// Builds a kernel from an async function returning [`BoxFuture`].
37    #[must_use]
38    pub fn from_async_fn<F>(handler: F) -> Self
39    where
40        F: for<'req> Fn(&'req mut Request) -> BoxFuture<'req, Result<Response, HttpError>>
41            + Send
42            + Sync
43            + 'static,
44    {
45        Self::new(crate::AsyncFn(handler))
46    }
47
48    /// Wraps a sync [`crate::RequestHandler`] as an async kernel.
49    #[must_use]
50    pub fn from_sync(controller: impl crate::RequestHandler + 'static) -> Self {
51        Self::new(SyncToAsync(controller))
52    }
53
54    /// Replaces the exception mapper.
55    #[must_use]
56    pub fn with_exception_handler(mut self, handler: impl ExceptionHandler + 'static) -> Self {
57        self.exceptions = Box::new(handler);
58        self
59    }
60
61    /// Appends middleware. The first pushed layer is outermost (runs first).
62    pub fn push_middleware(&mut self, middleware: impl AsyncMiddleware + 'static) -> &mut Self {
63        self.middleware.push(Box::new(middleware));
64        self
65    }
66
67    /// Handles `request` and always returns a [`Response`].
68    #[must_use = "futures do nothing unless you await them"]
69    pub fn handle(&self, mut request: Request) -> BoxFuture<'_, Response> {
70        Box::pin(async move {
71            match self.dispatch(&mut request).await {
72                Ok(response) => response,
73                Err(error) => self.exceptions.handle(&error),
74            }
75        })
76    }
77
78    fn dispatch<'req>(
79        &'req self,
80        request: &'req mut Request,
81    ) -> BoxFuture<'req, Result<Response, HttpError>> {
82        AsyncNext {
83            middleware: &self.middleware,
84            controller: self.controller.as_ref(),
85        }
86        .run(request)
87    }
88}