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