rainier-middleware 2.0.0

Middleware as values, the request pipeline, and the built-in middleware set.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! The request pipeline — [`Middleware`], [`Next`] and [`Pipeline`].
//!
//! The middleware signature is `handle(request, next)`, and that shape is the
//! whole point: middleware sits *around* the rest of the chain rather than
//! merely before it, so one piece of middleware can inspect the response,
//! wrap the call in a transaction or a timer, or decline to call `next` at
//! all.
//!
//! ```
//! use rainier_http::{Request, Response, StatusCode};
//! use rainier_middleware::{Middleware, Next};
//!
//! struct BlockRobots;
//!
//! #[async_trait::async_trait]
//! impl Middleware for BlockRobots {
//!     async fn handle(&self, request: Request, next: Next) -> Response {
//!         if request.header("user-agent").is_some_and(|ua| ua.contains("bot")) {
//!             return Response::new(StatusCode::FORBIDDEN);   // short-circuit
//!         }
//!         let response = next.run(request).await;            // …or continue
//!         response.with_header("x-checked", "yes")           // …and adjust
//!     }
//! }
//! ```

use std::any::TypeId;
use std::sync::Arc;

use rainier_http::{Request, Response};
use rainier_support::BoxedFuture;

/// The concrete type behind a `dyn Middleware`.
///
/// A supertrait with a blanket impl rather than a defaulted method, because a
/// provided method returning `TypeId::of::<Self>()` needs `Self: Sized` and
/// would therefore not land in the vtable — where a `dyn Middleware` is the
/// only place it is ever wanted.
///
/// This is what makes `Route::without_middleware::<T>()` possible without
/// going back to comparing names.
///
/// The blanket impl is bound on [`Middleware`] rather than on
/// `Send + Sync + 'static`, and that is load-bearing. A wider bound would also
/// cover `Arc<dyn Middleware>`, and then `arc.concrete_type_id()` would resolve
/// to the `Arc`'s own type before auto-deref reached the trait object —
/// answering `TypeId::of::<Arc<dyn Middleware>>()` for every stage, so every
/// comparison matches everything. Narrowing it means that call cannot compile
/// against the wrapper and must go through the vtable, which is the only place
/// the real answer lives.
pub trait ConcreteMiddleware: Send + Sync + 'static {
    /// The `TypeId` of the implementing type.
    fn concrete_type_id(&self) -> TypeId;

    /// Its fully-qualified type name.
    fn concrete_type_name(&self) -> &'static str;
}

impl<T: Middleware> ConcreteMiddleware for T {
    fn concrete_type_id(&self) -> TypeId {
        TypeId::of::<T>()
    }

    fn concrete_type_name(&self) -> &'static str {
        std::any::type_name::<T>()
    }
}

/// A stage in the request pipeline.
#[async_trait::async_trait]
pub trait Middleware: ConcreteMiddleware {
    /// Handle the request, optionally calling `next`.
    ///
    /// Returning without calling `next.run(..)` short-circuits the pipeline —
    /// the handler and every later middleware are skipped. That is how
    /// authentication, rate limiting and CORS preflight all work.
    async fn handle(&self, request: Request, next: Next) -> Response;

    /// A label for diagnostics and `route:list`.
    ///
    /// Defaults to the type's short name. This is a **label**, not an
    /// identifier: nothing looks middleware up by it, so two stages sharing one
    /// is untidy rather than broken.
    fn name(&self) -> &'static str {
        short_type_name(self.concrete_type_name())
    }
}

/// `a::b::Thing<x::y::Z>` → `Thing<Z>`.
///
/// `route:list` is a table; a column of fully-qualified paths makes it
/// unreadable and tells you nothing the short name does not.
pub(crate) fn short_type_name(full: &'static str) -> &'static str {
    // Generic parameters are dropped along with the path, which is what keeps
    // `Authenticate<app::models::User>` from being wider than the terminal.
    let without_generics = full.split_once('<').map_or(full, |(head, _)| head);
    without_generics.rsplit("::").next().unwrap_or(without_generics)
}

/// The end of the pipeline — the thing that actually produces a response.
///
/// The router implements this; the pipeline itself has no idea what a route
/// is, which is what keeps this crate independent of `rainier-routing`.
pub trait Destination: Send + Sync + 'static {
    /// Produce the response.
    fn call(&self, request: Request) -> BoxedFuture<Response>;
}

/// Any async closure is a destination — useful for tests and for one-off
/// pipelines.
impl<F, Fut> Destination for F
where
    F: Fn(Request) -> Fut + Send + Sync + 'static,
    Fut: std::future::Future<Output = Response> + Send + 'static,
{
    fn call(&self, request: Request) -> BoxedFuture<Response> {
        Box::pin(self(request))
    }
}

/// The remainder of the pipeline, handed to each middleware.
pub struct Next {
    stages: Arc<[Arc<dyn Middleware>]>,
    index: usize,
    destination: Arc<dyn Destination>,
}

impl Next {
    /// Continue: run the next middleware, or the destination if this was the
    /// last one.
    pub fn run(self, request: Request) -> BoxedFuture<Response> {
        let Some(stage) = self.stages.get(self.index).cloned() else {
            return self.destination.call(request);
        };

        let next =
            Next { stages: self.stages, index: self.index + 1, destination: self.destination };

        // The `Arc` is moved into the future so the borrow of `*stage` that
        // `handle` takes stays alive for as long as the future does.
        Box::pin(async move { stage.handle(request, next).await })
    }

    /// How many stages are still to run, excluding the destination.
    pub fn remaining(&self) -> usize {
        self.stages.len().saturating_sub(self.index)
    }
}

impl std::fmt::Debug for Next {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Next").field("remaining", &self.remaining()).finish()
    }
}

/// Builds and runs a pipeline: a request, through some middleware, to a
/// destination.
///
/// ```
/// # use rainier_http::{Request, Response};
/// # use rainier_middleware::Pipeline;
/// # #[tokio::main] async fn main() {
/// let response = Pipeline::new()
///     .then(|_req: Request| async { Response::text("hello") })
///     .run(Request::builder().build())
///     .await;
///
/// assert_eq!(response.status(), 200);
/// # }
/// ```
#[derive(Default)]
pub struct Pipeline {
    stages: Vec<Arc<dyn Middleware>>,
}

impl Pipeline {
    /// An empty pipeline.
    pub fn new() -> Self {
        Self::default()
    }

    /// Append one middleware.
    pub fn through(mut self, middleware: impl Middleware) -> Self {
        self.stages.push(Arc::new(middleware));
        self
    }

    /// Append an already-shared middleware.
    pub fn through_arc(mut self, middleware: Arc<dyn Middleware>) -> Self {
        self.stages.push(middleware);
        self
    }

    /// Append several already-shared middleware, in order.
    pub fn through_all(
        mut self,
        middleware: impl IntoIterator<Item = Arc<dyn Middleware>>,
    ) -> Self {
        self.stages.extend(middleware);
        self
    }

    /// Close the pipeline with its destination.
    pub fn then(self, destination: impl Destination) -> ReadyPipeline {
        self.then_arc(Arc::new(destination))
    }

    /// [`then`](Self::then) with an already-shared destination.
    pub fn then_arc(self, destination: Arc<dyn Destination>) -> ReadyPipeline {
        ReadyPipeline { stages: self.stages.into(), destination }
    }

    /// How many stages are registered.
    pub fn len(&self) -> usize {
        self.stages.len()
    }

    /// Whether the pipeline has no middleware.
    pub fn is_empty(&self) -> bool {
        self.stages.is_empty()
    }
}

/// A pipeline with its destination attached, ready to run — and cheap to
/// re-run, which is what lets the router build one per route at boot rather
/// than per request.
#[derive(Clone)]
pub struct ReadyPipeline {
    stages: Arc<[Arc<dyn Middleware>]>,
    destination: Arc<dyn Destination>,
}

impl ReadyPipeline {
    /// Send a request through.
    pub async fn run(&self, request: Request) -> Response {
        Next {
            stages: Arc::clone(&self.stages),
            index: 0,
            destination: Arc::clone(&self.destination),
        }
        .run(request)
        .await
    }

    /// The names of the middleware, in order.
    pub fn stage_names(&self) -> Vec<&'static str> {
        self.stages.iter().map(|s| s.name()).collect()
    }
}

impl std::fmt::Debug for ReadyPipeline {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ReadyPipeline").field("stages", &self.stage_names()).finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rainier_http::StatusCode;
    use std::sync::Mutex;

    /// Records when it runs, on the way in and on the way out.
    struct Trace {
        tag: &'static str,
        log: Arc<Mutex<Vec<String>>>,
    }

    #[async_trait::async_trait]
    impl Middleware for Trace {
        async fn handle(&self, request: Request, next: Next) -> Response {
            self.log.lock().unwrap().push(format!("{}:before", self.tag));
            let response = next.run(request).await;
            self.log.lock().unwrap().push(format!("{}:after", self.tag));
            response
        }

        fn name(&self) -> &'static str {
            "Trace"
        }
    }

    struct ShortCircuit;

    #[async_trait::async_trait]
    impl Middleware for ShortCircuit {
        async fn handle(&self, _request: Request, _next: Next) -> Response {
            Response::new(StatusCode::FORBIDDEN)
        }
    }

    fn log() -> Arc<Mutex<Vec<String>>> {
        Arc::new(Mutex::new(Vec::new()))
    }

    #[tokio::test]
    async fn an_empty_pipeline_reaches_the_destination() {
        let response = Pipeline::new()
            .then(|_: Request| async { Response::text("hi") })
            .run(Request::builder().build())
            .await;
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn middleware_wraps_the_destination_in_order() {
        let log = log();
        let recorded = Arc::clone(&log);

        let destination_log = Arc::clone(&log);
        let response = Pipeline::new()
            .through(Trace { tag: "outer", log: Arc::clone(&log) })
            .through(Trace { tag: "inner", log: Arc::clone(&log) })
            .then(move |_: Request| {
                let log = Arc::clone(&destination_log);
                async move {
                    log.lock().unwrap().push("handler".into());
                    Response::text("ok")
                }
            })
            .run(Request::builder().build())
            .await;

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(
            *recorded.lock().unwrap(),
            vec!["outer:before", "inner:before", "handler", "inner:after", "outer:after"]
        );
    }

    #[tokio::test]
    async fn short_circuiting_skips_the_rest_and_the_handler() {
        let log = log();
        let recorded = Arc::clone(&log);

        let response = Pipeline::new()
            .through(Trace { tag: "outer", log: Arc::clone(&log) })
            .through(ShortCircuit)
            .through(Trace { tag: "never", log: Arc::clone(&log) })
            .then(|_: Request| async { Response::text("unreachable") })
            .run(Request::builder().build())
            .await;

        assert_eq!(response.status(), StatusCode::FORBIDDEN);
        // The outer middleware still sees the response on the way out.
        assert_eq!(*recorded.lock().unwrap(), vec!["outer:before", "outer:after"]);
    }

    #[tokio::test]
    async fn middleware_can_rewrite_the_request_and_the_response() {
        struct Tag;

        #[async_trait::async_trait]
        impl Middleware for Tag {
            async fn handle(&self, mut request: Request, next: Next) -> Response {
                request.merge_input(serde_json::json!({ "injected": "yes" }));
                next.run(request).await.with_header("x-tagged", "1")
            }
        }

        let response =
            Pipeline::new()
                .through(Tag)
                .then(|request: Request| async move {
                    Response::text(request.input_or("injected", "no"))
                })
                .run(Request::builder().build())
                .await;

        assert_eq!(response.header("x-tagged"), Some("1"));
        let body = response.into_http().into_body().collect().await.unwrap();
        assert_eq!(body, "yes");
    }

    #[tokio::test]
    async fn a_ready_pipeline_can_be_run_repeatedly() {
        let pipeline = Pipeline::new()
            .through(Trace { tag: "a", log: log() })
            .then(|_: Request| async { Response::text("ok") });

        for _ in 0..3 {
            assert_eq!(pipeline.run(Request::builder().build()).await.status(), StatusCode::OK);
        }
        assert_eq!(pipeline.stage_names(), vec!["Trace"]);
    }

    #[tokio::test]
    async fn next_reports_how_much_is_left() {
        struct CountRemaining(Arc<Mutex<Vec<usize>>>);

        #[async_trait::async_trait]
        impl Middleware for CountRemaining {
            async fn handle(&self, request: Request, next: Next) -> Response {
                self.0.lock().unwrap().push(next.remaining());
                next.run(request).await
            }
        }

        let seen = Arc::new(Mutex::new(Vec::new()));
        Pipeline::new()
            .through(CountRemaining(Arc::clone(&seen)))
            .through(CountRemaining(Arc::clone(&seen)))
            .then(|_: Request| async { Response::no_content() })
            .run(Request::builder().build())
            .await;

        assert_eq!(*seen.lock().unwrap(), vec![1, 0]);
    }
}