autumn-web 0.3.0

An opinionated, convention-over-configuration web framework for Rust
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
//! Tower middleware that caches HTTP GET responses.
//!
//! Only caches `GET` requests that produce `200 OK` responses.
//! Non-GET methods and non-200 responses pass through untouched.
//!
//! # Usage
//!
//! ```rust,ignore
//! use autumn_web::prelude::*;
//! use autumn_web::cache::{CacheResponseLayer, MokaCache};
//!
//! let store = MokaCache::builder()
//!     .max_capacity(1000)
//!     .ttl(std::time::Duration::from_secs(300))
//!     .build();
//!
//! #[get("/users/{id}")]
//! #[intercept(CacheResponseLayer::from_cache(store))]
//! async fn get_user(Path(id): Path<i32>) -> Json<User> { ... }
//! ```

use std::convert::Infallible;
use std::sync::Arc;
use std::task::{Context, Poll};

use axum::body::Body;
use axum::http::{Method, StatusCode};
use http::Request;
use http_body_util::BodyExt;
use tower::{Layer, Service};

use super::Cache;

/// A cached HTTP response: status, headers, and body bytes.
#[derive(Clone)]
struct CachedResponse {
    status: StatusCode,
    headers: http::HeaderMap,
    body: bytes::Bytes,
}

/// Tower layer that caches HTTP GET responses.
///
/// Wrap around a handler via `#[intercept(CacheResponseLayer::from_cache(store))]`
/// or construct manually and apply with `.layer()`.
///
/// Caching rules:
/// - Only `GET` requests are cached.
/// - Only `200 OK` responses are cached.
/// - The cache key is the request URI path + query string.
#[derive(Clone)]
pub struct CacheResponseLayer {
    store: Arc<dyn Cache>,
}

impl CacheResponseLayer {
    /// Create a layer backed by the given cache store.
    pub fn from_cache(store: impl Cache + 'static) -> Self {
        Self {
            store: Arc::new(store),
        }
    }

    /// Create from an existing `Arc<dyn Cache>`.
    pub fn from_shared(store: Arc<dyn Cache>) -> Self {
        Self { store }
    }
}

impl<S> Layer<S> for CacheResponseLayer {
    type Service = CacheResponseService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        CacheResponseService {
            inner,
            store: self.store.clone(),
        }
    }
}

/// The [`Service`] produced by [`CacheResponseLayer`].
#[derive(Clone)]
pub struct CacheResponseService<S> {
    inner: S,
    store: Arc<dyn Cache>,
}

impl<S> Service<Request<Body>> for CacheResponseService<S>
where
    S: Service<Request<Body>, Response = axum::response::Response, Error = Infallible>
        + Clone
        + Send
        + 'static,
    S::Future: Send,
{
    type Response = axum::response::Response;
    type Error = Infallible;
    type Future = std::pin::Pin<
        Box<dyn std::future::Future<Output = Result<Self::Response, Self::Error>> + Send>,
    >;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, req: Request<Body>) -> Self::Future {
        // Only cache GET requests
        if req.method() != Method::GET {
            return Box::pin(self.inner.call(req));
        }

        // âš¡ Bolt Optimization:
        // Format the key into a stack-allocated buffer to avoid a heap allocation
        // on every cache check. Fall back to allocating a String only if the URI
        // is exceptionally long.
        let mut buf = [0u8; 512];
        let cache_key_str = {
            let mut cursor = &mut buf[..];
            if std::io::Write::write_fmt(&mut cursor, format_args!("http:{}", req.uri())).is_ok() {
                let len = 512 - cursor.len();
                std::str::from_utf8(&buf[..len]).unwrap_or_default()
            } else {
                ""
            }
        };

        let store = self.store.clone();

        let cache_hit = if cache_key_str.is_empty() {
            // Fallback for very long URIs
            super::get::<CachedResponse>(store.as_ref(), &format!("http:{}", req.uri()))
        } else {
            super::get::<CachedResponse>(store.as_ref(), cache_key_str)
        };

        // Check for a cache hit
        if let Some(cached) = cache_hit {
            return Box::pin(async move {
                let mut builder = axum::response::Response::builder().status(cached.status);
                if let Some(headers) = builder.headers_mut() {
                    headers.extend(cached.headers);
                }
                let resp = builder.body(Body::from(cached.body)).unwrap_or_else(|_| {
                    axum::response::Response::builder()
                        .status(StatusCode::INTERNAL_SERVER_ERROR)
                        .body(Body::empty())
                        .expect("infallible response builder")
                });
                Ok(resp)
            });
        }

        // Cache miss — call the inner service
        let mut inner = self.inner.clone();
        let cache_key = if cache_key_str.is_empty() {
            format!("http:{}", req.uri())
        } else {
            cache_key_str.to_owned()
        };

        Box::pin(async move {
            let response = inner.call(req).await?;

            // Only cache 200 OK responses
            if response.status() != StatusCode::OK {
                return Ok(response);
            }

            let (parts, body) = response.into_parts();

            // Buffer the body
            let Ok(collected) = body.collect().await else {
                let resp = axum::response::Response::builder()
                    .status(StatusCode::INTERNAL_SERVER_ERROR)
                    .body(Body::empty())
                    .expect("infallible response builder");
                return Ok(resp);
            };
            let body_bytes = collected.to_bytes();

            // Store in cache
            let cached = CachedResponse {
                status: parts.status,
                headers: parts.headers.clone(),
                body: body_bytes.clone(),
            };
            super::insert(store.as_ref(), &cache_key, cached);

            // Reconstruct the response
            let response = axum::response::Response::from_parts(parts, Body::from(body_bytes));
            Ok(response)
        })
    }
}

#[cfg(all(test, feature = "cache-moka"))]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use tower::{ServiceBuilder, ServiceExt};

    /// Build a test service that returns a fixed body and counts calls.
    fn counting_service(
        counter: Arc<AtomicUsize>,
        body: &'static str,
    ) -> impl Service<
        Request<Body>,
        Response = axum::response::Response,
        Error = Infallible,
        Future = impl std::future::Future<Output = Result<axum::response::Response, Infallible>> + Send,
    > + Clone
    + Send
    + 'static {
        let body = body.to_owned();
        tower::service_fn(move |_req: Request<Body>| {
            let counter = counter.clone();
            let body = body.clone();
            async move {
                counter.fetch_add(1, Ordering::SeqCst);
                Ok(axum::response::Response::builder()
                    .status(StatusCode::OK)
                    .body(Body::from(body))
                    .expect("infallible response builder"))
            }
        })
    }

    #[tokio::test]
    async fn caches_get_responses() {
        let store = super::super::MokaCache::new(100, None);
        let counter = Arc::new(AtomicUsize::new(0));

        let mut svc = ServiceBuilder::new()
            .layer(CacheResponseLayer::from_cache(store))
            .service(counting_service(counter.clone(), "hello"));

        // First request — cache miss
        let req = Request::get("/test")
            .body(Body::empty())
            .expect("infallible response builder");
        let resp = svc
            .ready()
            .await
            .expect("infallible response builder")
            .call(req)
            .await
            .expect("infallible response builder");
        assert_eq!(resp.status(), StatusCode::OK);
        let body = http_body_util::BodyExt::collect(resp.into_body())
            .await
            .expect("infallible response builder")
            .to_bytes();
        assert_eq!(body.as_ref(), b"hello");
        assert_eq!(counter.load(Ordering::SeqCst), 1);

        // Second request — cache hit, inner service NOT called
        let req = Request::get("/test")
            .body(Body::empty())
            .expect("infallible response builder");
        let resp = svc
            .ready()
            .await
            .expect("infallible response builder")
            .call(req)
            .await
            .expect("infallible response builder");
        assert_eq!(resp.status(), StatusCode::OK);
        let body = http_body_util::BodyExt::collect(resp.into_body())
            .await
            .expect("infallible response builder")
            .to_bytes();
        assert_eq!(body.as_ref(), b"hello");
        assert_eq!(
            counter.load(Ordering::SeqCst),
            1,
            "inner should not be called again"
        );
    }

    #[tokio::test]
    async fn does_not_cache_post_requests() {
        let store = super::super::MokaCache::new(100, None);
        let counter = Arc::new(AtomicUsize::new(0));

        let mut svc = ServiceBuilder::new()
            .layer(CacheResponseLayer::from_cache(store))
            .service(counting_service(counter.clone(), "created"));

        let req = Request::post("/items")
            .body(Body::empty())
            .expect("infallible response builder");
        let _resp = svc
            .ready()
            .await
            .expect("infallible response builder")
            .call(req)
            .await
            .expect("infallible response builder");
        assert_eq!(counter.load(Ordering::SeqCst), 1);

        let req = Request::post("/items")
            .body(Body::empty())
            .expect("infallible response builder");
        let _resp = svc
            .ready()
            .await
            .expect("infallible response builder")
            .call(req)
            .await
            .expect("infallible response builder");
        assert_eq!(
            counter.load(Ordering::SeqCst),
            2,
            "POST should not be cached"
        );
    }

    #[tokio::test]
    async fn does_not_cache_non_200_responses() {
        let store = super::super::MokaCache::new(100, None);
        let counter = Arc::new(AtomicUsize::new(0));

        let svc_inner = {
            let counter = counter.clone();
            tower::service_fn(move |_req: Request<Body>| {
                let counter = counter.clone();
                async move {
                    counter.fetch_add(1, Ordering::SeqCst);
                    Ok::<_, Infallible>(
                        axum::response::Response::builder()
                            .status(StatusCode::NOT_FOUND)
                            .body(Body::from("not found"))
                            .expect("infallible response builder"),
                    )
                }
            })
        };

        let mut svc = ServiceBuilder::new()
            .layer(CacheResponseLayer::from_cache(store))
            .service(svc_inner);

        let req = Request::get("/missing")
            .body(Body::empty())
            .expect("infallible response builder");
        let resp = svc
            .ready()
            .await
            .expect("infallible response builder")
            .call(req)
            .await
            .expect("infallible response builder");
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);

        let req = Request::get("/missing")
            .body(Body::empty())
            .expect("infallible response builder");
        let resp = svc
            .ready()
            .await
            .expect("infallible response builder")
            .call(req)
            .await
            .expect("infallible response builder");
        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
        assert_eq!(
            counter.load(Ordering::SeqCst),
            2,
            "404 should not be cached"
        );
    }

    #[tokio::test]
    async fn different_uris_cached_separately() {
        let store = super::super::MokaCache::new(100, None);
        let counter = Arc::new(AtomicUsize::new(0));

        let mut svc = ServiceBuilder::new()
            .layer(CacheResponseLayer::from_cache(store))
            .service(counting_service(counter.clone(), "ok"));

        let req = Request::get("/a")
            .body(Body::empty())
            .expect("infallible response builder");
        let _resp = svc
            .ready()
            .await
            .expect("infallible response builder")
            .call(req)
            .await
            .expect("infallible response builder");
        let req = Request::get("/b")
            .body(Body::empty())
            .expect("infallible response builder");
        let _resp = svc
            .ready()
            .await
            .expect("infallible response builder")
            .call(req)
            .await
            .expect("infallible response builder");
        assert_eq!(
            counter.load(Ordering::SeqCst),
            2,
            "different URIs should miss"
        );

        // But repeating /a should hit
        let req = Request::get("/a")
            .body(Body::empty())
            .expect("infallible response builder");
        let _resp = svc
            .ready()
            .await
            .expect("infallible response builder")
            .call(req)
            .await
            .expect("infallible response builder");
        assert_eq!(counter.load(Ordering::SeqCst), 2, "/a should be cached");
    }

    #[test]
    fn from_shared_accepts_arc() {
        let store = Arc::new(super::super::MokaCache::new(100, None));
        // Just verify from_shared compiles and the layer can be used
        let _layer = CacheResponseLayer::from_shared(store);
    }

    #[tokio::test]
    async fn caches_get_responses_very_long_uri() {
        let store = super::super::MokaCache::new(100, None);
        let counter = Arc::new(AtomicUsize::new(0));

        let mut svc = ServiceBuilder::new()
            .layer(CacheResponseLayer::from_cache(store))
            .service(counting_service(counter.clone(), "hello"));

        let long_uri = format!("/test/{}", "a".repeat(1000));

        let req1 = Request::get(&long_uri)
            .body(Body::empty())
            .expect("infallible response builder");

        let resp1 = svc
            .ready()
            .await
            .expect("infallible response builder")
            .call(req1)
            .await
            .expect("infallible response builder");

        assert_eq!(resp1.status(), StatusCode::OK);
        assert_eq!(counter.load(Ordering::SeqCst), 1);

        let req2 = Request::get(&long_uri)
            .body(Body::empty())
            .expect("infallible response builder");

        let resp2 = svc
            .ready()
            .await
            .expect("infallible response builder")
            .call(req2)
            .await
            .expect("infallible response builder");

        assert_eq!(resp2.status(), StatusCode::OK);
        assert_eq!(
            counter.load(Ordering::SeqCst),
            1,
            "Should be cached despite long URI"
        );
    }
}