Skip to main content

diode_http/
middleware.rs

1use std::mem::replace;
2use std::pin::Pin;
3use std::{marker::PhantomData, sync::Arc};
4
5use axum::response::Response;
6use axum::{extract::Request, response::IntoResponse};
7use diode::{
8    AddServiceExt as _, AppBuilder, AppContext, Dependencies, Plugin, Service,
9    ServiceDependencyExt as _,
10};
11
12/// The continuation passed to a [`MiddlewareService`]: runs the rest of the
13/// chain (the next middleware, or the route handler).
14///
15/// Call [`call`](Next::call) to forward the (possibly modified) request inward
16/// and obtain the response. Not calling it short-circuits the chain: your
17/// response is returned without running any inner middleware or the handler.
18pub trait Next: Send + Sync {
19    /// Forwards `request` to the rest of the chain and returns its response.
20    fn call(self, request: Request) -> impl Future<Output = Response> + Send;
21}
22
23struct NextImpl<T>(T);
24
25impl<T, R, E> Next for NextImpl<T>
26where
27    T: tower::Service<Request, Response = R, Error = E> + Send + Sync,
28    T::Future: Send + 'static,
29    R: IntoResponse,
30    E: IntoResponse,
31{
32    async fn call(mut self, request: Request) -> Response {
33        self.0.call(request).await.into_response()
34    }
35}
36
37#[doc(hidden)]
38pub struct MiddlewareLayerImpl<T>(pub Arc<T>);
39
40impl<T> Clone for MiddlewareLayerImpl<T> {
41    fn clone(&self) -> Self {
42        Self(self.0.clone())
43    }
44}
45
46impl<T, S> tower::Layer<S> for MiddlewareLayerImpl<T> {
47    type Service = MiddlewareServiceImpl<T, S>;
48
49    fn layer(&self, inner: S) -> Self::Service {
50        Self::Service {
51            service: self.0.clone(),
52            inner,
53        }
54    }
55}
56
57#[doc(hidden)]
58pub struct MiddlewareServiceImpl<T, S> {
59    service: Arc<T>,
60    inner: S,
61}
62
63impl<T, S> Clone for MiddlewareServiceImpl<T, S>
64where
65    S: Clone,
66{
67    fn clone(&self) -> Self {
68        Self {
69            service: self.service.clone(),
70            inner: self.inner.clone(),
71        }
72    }
73}
74
75impl<T, S> tower::Service<Request> for MiddlewareServiceImpl<T, S>
76where
77    T: MiddlewareService + 'static,
78    S: tower::Service<Request> + Clone + Send + Sync + 'static,
79    S::Response: IntoResponse,
80    S::Error: IntoResponse,
81    S::Future: Send + 'static,
82    T::Error: IntoResponse,
83{
84    type Response = Response;
85    type Error = S::Error;
86    type Future =
87        Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
88
89    fn poll_ready(
90        &mut self,
91        cx: &mut std::task::Context<'_>,
92    ) -> std::task::Poll<Result<(), Self::Error>> {
93        self.inner.poll_ready(cx)
94    }
95
96    fn call(&mut self, request: Request) -> Self::Future {
97        let clone = self.inner.clone();
98        let inner = replace(&mut self.inner, clone);
99        let layer = self.service.clone();
100        let next = NextImpl(inner);
101        Box::pin(async move {
102            match layer.call(request, next).await {
103                Ok(response) => Ok(response.into_response()),
104                Err(err) => Ok(err.into_response()),
105            }
106        })
107    }
108}
109
110/// Middleware that wraps request handling on an HTTP server.
111///
112/// A middleware receives each request together with a [`Next`] continuation. It
113/// may inspect or modify the request, short-circuit with its own response, or
114/// call `next` and then inspect or modify the response.
115///
116/// Middleware is a [`Service`], so it is built by the container and may hold
117/// injected dependencies. Attach it to routes with the
118/// `#[router(middleware = [..])]` / `#[route(middleware = [..])]` macro
119/// attributes, and register the service with
120/// [`AddMiddlewareExt::add_middleware`].
121///
122/// # Ordering
123///
124/// Within a `middleware = [A, B]` list the first entry is outermost: it runs
125/// first on the request and last on the response. Router-level middleware wraps
126/// route-level middleware. So `#[router(middleware = [A, B])]` combined with
127/// `#[route(middleware = [C, D])]` enters as `A, B, C, D` and unwinds as
128/// `D, C, B, A`.
129pub trait MiddlewareService: Service<Handle = Arc<Self>> {
130    /// Error type rendered into a response when
131    /// [`call`](MiddlewareService::call) returns `Err`.
132    type Error: IntoResponse;
133
134    /// Handles `request`, optionally delegating to `next`.
135    fn call(
136        &self,
137        request: Request,
138        next: impl Next,
139    ) -> impl Future<Output = Result<Response, Self::Error>> + Send;
140}
141
142struct MiddlewareProvider<T>(PhantomData<T>)
143where
144    T: MiddlewareService;
145
146impl<T> Plugin for MiddlewareProvider<T>
147where
148    T: MiddlewareService + 'static,
149{
150    async fn build(&self, _ctx: &AppContext) -> Result<(), diode::StdError> {
151        Ok(())
152    }
153
154    fn dependencies(&self) -> diode::Dependencies {
155        Dependencies::new().service::<T>()
156    }
157}
158
159/// Registers [`MiddlewareService`] implementations so the router macros can
160/// resolve them.
161///
162/// A middleware must be registered here for any router that references it via
163/// `#[router(middleware = [..])]` / `#[route(middleware = [..])]`; the generated
164/// [`RouterBuilder`](crate::RouterBuilder) looks up the middleware's handle while
165/// it builds.
166pub trait AddMiddlewareExt {
167    /// Registers the middleware service `T`.
168    ///
169    /// # Panics
170    ///
171    /// Panics if `T` is already registered as middleware. Guard with
172    /// [`has_middleware`](AddMiddlewareExt::has_middleware) when this can happen.
173    fn add_middleware<T>(&mut self) -> &mut Self
174    where
175        T: MiddlewareService + 'static;
176
177    /// Returns whether `T` is registered as middleware.
178    fn has_middleware<T>(&self) -> bool
179    where
180        T: MiddlewareService + 'static;
181}
182
183impl AddMiddlewareExt for AppBuilder {
184    fn add_middleware<T>(&mut self) -> &mut Self
185    where
186        T: MiddlewareService + 'static,
187    {
188        if !self.has_service::<T>() {
189            self.add_service::<T>();
190        }
191        self.add_plugin(MiddlewareProvider::<T>(PhantomData));
192        self
193    }
194
195    fn has_middleware<T>(&self) -> bool
196    where
197        T: MiddlewareService + 'static,
198    {
199        self.has_plugin::<MiddlewareProvider<T>>()
200    }
201}
202
203/// Declares a [`MiddlewareService`] as a [`Dependencies`] entry, so the plugin
204/// or service declaring it is built only after the middleware is registered.
205pub trait MiddlewareDependencyExt {
206    /// Adds `T` as a middleware dependency.
207    fn middleware<T>(self) -> Self
208    where
209        T: MiddlewareService + 'static;
210}
211
212impl MiddlewareDependencyExt for Dependencies {
213    fn middleware<T>(self) -> Self
214    where
215        T: MiddlewareService + 'static,
216    {
217        self.plugin::<MiddlewareProvider<T>>()
218    }
219}