proa_framework_axum 0.4.3

Axum and Tokio adapter for Proa SSR applications.
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
// Copyright Proa Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

//! Build-scoped, bounded caching of public buffered route responses.
//!
//! This is an origin cache. Downstream caches must revalidate so deploying a
//! new executable cannot leave an old HTML response fresh at an unrelated CDN.

use base16ct::HexDisplay;
use std::{
    cell::RefCell,
    collections::HashMap,
    future::Future,
    io::{self, Read},
    pin::Pin,
    sync::{Arc, OnceLock},
    task::{Context, Poll},
    time::Duration,
};

use axum::{
    body::{to_bytes, Body, Bytes, HttpBody},
    http::{header, HeaderMap, HeaderName, HeaderValue, Method, Request, StatusCode},
    response::{IntoResponse, Response},
};
use bytes::BytesMut;
use futures::{stream, StreamExt};
use http_body_util::BodyExt as _;
use parking_lot::Mutex;
use sha2::{Digest, Sha256};
use tokio::{
    sync::{Mutex as AsyncMutex, OwnedMutexGuard},
    time::Instant,
};
use tower::{Layer, Service, ServiceExt};

use super::{
    cdn_cache::{prepare_cacheable_stream, CacheableStream},
    context::ROUTE_CONTEXT,
    response::DeferredFrameworkStream,
};

type Key = [u8; 32];
const STATUS: &str = "x-proa-page-cache";
const LOCK_COUNT: usize = 64;

/// Cache selected public routes in memory, separately for each application build.
///
/// Construct once at startup and attach with [`super::Route::with_page_cache`].
/// It also supports ordinary Tower layering. Clones share bounded storage. A hit skips
/// the inner handler, loaders, and rendering; it clones reference-counted
/// response bytes rather than copying the HTML.
///
/// [`for_current_build`](Self::for_current_build) hashes the executable once
/// per process. [`new`](Self::new) accepts an explicit deployment identifier
/// when external assets or configuration also need to version the build.
/// Storage is process-local and starts empty on every restart.
///
/// Only opt in routes whose output is public. Authentication/authorization
/// middleware must run outside this layer. Cookie and Authorization requests,
/// per-request CSP nonces, errors, private/no-store responses, unknown Vary
/// fields, and streaming bodies bypass storage. On requests the cache may
/// store, a streamed RouteResponse streams in order, which ends in the same
/// bytes as a buffered render. The cache sends it at once, as a MISS without
/// an ETag, and stores it if the body ends within the body limit and the
/// timeout. A streamed page whose head rules out storage bypasses at once.
/// Concurrent misses for a streamed page each render.
///
/// Responses use `public, no-cache` downstream and a generated ETag. This
/// allows browser revalidation without rerendering and prevents an ordinary
/// CDN from retaining old HTML across deployment changes.
#[derive(Clone)]
pub struct PageCacheLayer {
    build: Key,
    cache: Arc<Cache>,
    revalidate: Option<Duration>,
    stale_window: Duration,
    timeout: Duration,
    max_entries: usize,
    max_body_bytes: usize,
    vary: Arc<Vec<HeaderName>>,
}

impl PageCacheLayer {
    /// Start a cache for a deployment identifier covering all page inputs.
    pub fn new(build_id: impl AsRef<[u8]>) -> Self {
        assert!(
            !build_id.as_ref().is_empty(),
            "page cache build ID must not be empty"
        );
        Self {
            build: Sha256::digest(build_id.as_ref()).into(),
            cache: Arc::new(Cache {
                pages: Mutex::new(HashMap::new()),
                locks: std::array::from_fn(|_| Arc::new(AsyncMutex::new(()))),
            }),
            revalidate: None,
            stale_window: Duration::from_secs(86400),
            timeout: Duration::from_secs(30),
            max_entries: 128,
            max_body_bytes: 256 * 1024,
            vary: Arc::new(vec![
                header::ACCEPT,
                header::ACCEPT_ENCODING,
                header::ACCEPT_LANGUAGE,
                HeaderName::from_static("x-proa-client"),
            ]),
        }
    }

    /// Identify the application by hashing its executable at startup.
    ///
    /// The fingerprint is computed once per process using a bounded buffer.
    /// Use `new(deployment_id)` instead if runtime configuration or external
    /// assets change independently of the executable. Construct before serving
    /// requests: reading the executable performs synchronous filesystem I/O.
    pub fn for_current_build() -> io::Result<Self> {
        static BUILD: OnceLock<Key> = OnceLock::new();
        let build = match BUILD.get() {
            Some(build) => *build,
            None => {
                let mut file = std::fs::File::open(std::env::current_exe()?)?;
                let mut hasher = Sha256::new();
                let mut buffer = [0; 64 * 1024];
                loop {
                    let len = file.read(&mut buffer)?;
                    if len == 0 {
                        break;
                    }
                    hasher.update(&buffer[..len]);
                }
                *BUILD.get_or_init(|| hasher.finalize().into())
            }
        };
        Ok(Self::new(build))
    }

    /// Enable request-driven background regeneration after this interval.
    ///
    /// One request refreshes a stale entry while other requests reuse it.
    /// Failed refreshes retain the old entry. After the stale window expires,
    /// requests wait for regeneration and receive any origin error directly.
    pub fn revalidate(mut self, interval: Duration) -> Self {
        assert!(
            !interval.is_zero(),
            "page revalidation interval must be positive"
        );
        self.revalidate = Some(interval);
        self
    }

    /// Limit stale serving after the interval expires (default: one day).
    pub fn stale_while_revalidate(mut self, window: Duration) -> Self {
        self.stale_window = window;
        self
    }

    /// Bound each render/body collection, including background work (30s default).
    ///
    /// A buffered page that misses the deadline is a 504. A streamed page
    /// is never held back or cut short by it; one that ends after it is not
    /// stored.
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        assert!(!timeout.is_zero(), "page cache timeout must be positive");
        self.timeout = timeout;
        self
    }

    /// Set entry and body-size limits (default: 128 entries of up to 256 KiB).
    ///
    /// Oversized responses bypass caching. Insertion evicts the oldest entry
    /// when full. Response headers are separately limited to 64 KiB per entry.
    pub fn with_limits(mut self, max_entries: usize, max_body_bytes: usize) -> Self {
        assert!(max_entries > 0, "page cache must allow at least one entry");
        self.max_entries = max_entries;
        self.max_body_bytes = max_body_bytes;
        self
    }

    /// Include another public representation selector in the cache key.
    ///
    /// Accept, Accept-Encoding, Accept-Language and X-Proa-Client are included
    /// by default. The URI (including query), authority, Host, forwarded host
    /// and forwarded scheme also partition entries. Responses with other Vary
    /// fields bypass storage until those fields are registered here.
    pub fn vary_on(mut self, header: HeaderName) -> Self {
        if !self.vary.contains(&header) {
            Arc::make_mut(&mut self.vary).push(header);
        }
        self
    }

    fn key(&self, request: &Request<Body>) -> Key {
        let mut hash = Sha256::new();
        hash.update(self.build);
        hash.update(
            self.revalidate
                .map(|v| v.as_nanos())
                .unwrap_or(u128::MAX)
                .to_le_bytes(),
        );
        hash.update(self.stale_window.as_nanos().to_le_bytes());
        hash_field(
            &mut hash,
            request.uri().scheme_str().unwrap_or("").as_bytes(),
        );
        hash_field(
            &mut hash,
            request
                .uri()
                .authority()
                .map(|a| a.as_str())
                .unwrap_or("")
                .as_bytes(),
        );
        hash_field(
            &mut hash,
            request
                .uri()
                .path_and_query()
                .map(|p| p.as_str())
                .unwrap_or("/")
                .as_bytes(),
        );
        for name in [
            header::HOST,
            HeaderName::from_static("x-forwarded-host"),
            HeaderName::from_static("x-forwarded-proto"),
        ]
        .iter()
        .chain(self.vary.iter())
        {
            hash_field(&mut hash, name.as_str().as_bytes());
            for value in request.headers().get_all(name) {
                hash_field(&mut hash, value.as_bytes());
            }
            // Separate an absent header from a present empty value.
            hash.update(u64::MAX.to_le_bytes());
        }
        if let Some(assets) = request.extensions().get::<crate::PublicAssets>() {
            hash_field(&mut hash, assets.cache_key().as_bytes());
        }
        hash.finalize().into()
    }

    fn get(&self, key: &Key) -> Option<Arc<CachedPage>> {
        self.cache.pages.lock().get(key).cloned()
    }

    fn fresh(&self, page: &CachedPage) -> bool {
        self.revalidate
            .is_none_or(|interval| page.created.elapsed() < interval)
    }

    fn may_serve_stale(&self, page: &CachedPage) -> bool {
        self.revalidate.is_some_and(|interval| {
            page.created.elapsed() < interval.saturating_add(self.stale_window)
        })
    }

    fn insert(&self, key: Key, page: Arc<CachedPage>) {
        let mut pages = self.cache.pages.lock();
        if !pages.contains_key(&key) && pages.len() >= self.max_entries {
            if let Some(oldest) = pages
                .iter()
                .min_by_key(|(_, page)| page.created)
                .map(|(key, _)| *key)
            {
                pages.remove(&oldest);
            }
        }
        pages.insert(key, page);
    }
}

impl<S> Layer<S> for PageCacheLayer {
    type Service = PageCacheService<S>;

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

/// Tower service produced by [`PageCacheLayer`].
#[derive(Clone)]
pub struct PageCacheService<S> {
    inner: S,
    layer: PageCacheLayer,
}

impl<S> Service<Request<Body>> for PageCacheService<S>
where
    S: Service<Request<Body>, Response = Response> + Clone + Send + 'static,
    S::Future: Send + 'static,
    S::Error: Send + 'static,
{
    type Response = Response;
    type Error = S::Error;
    type Future = Pin<Box<dyn Future<Output = Result<Response, S::Error>> + Send>>;

    fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        // Hits need no inner capacity. On misses, oneshot polls the cloned
        // inner service for readiness before calling it.
        Poll::Ready(Ok(()))
    }

    fn call(&mut self, request: Request<Body>) -> Self::Future {
        let layer = self.layer.clone();
        let inner = self.inner.clone();
        Box::pin(async move {
            if bypass_request(&request) {
                return pass(inner, request).await;
            }
            let key = layer.key(&request);
            let headers = request.headers().clone();
            let head = request.method() == Method::HEAD;
            if let Some(page) = layer.get(&key) {
                if layer.fresh(&page) {
                    return Ok(page.response(&headers, head, "HIT"));
                }
                if layer.may_serve_stale(&page)
                    && !has_directive(&headers, header::CACHE_CONTROL, "no-cache")
                    && !has_directive(&headers, header::CACHE_CONTROL, "max-age")
                    && !head
                {
                    let response = page.response(&headers, false, "STALE");
                    if let Ok(guard) = layer.cache.locks[key[0] as usize % LOCK_COUNT]
                        .clone()
                        .try_lock_owned()
                    {
                        // Tokio task locals do not propagate through spawn.
                        // Retain the route params and metadata for
                        // RouteResponse finalization in the refresh task.
                        let context = ROUTE_CONTEXT.try_with(|cx| cx.borrow().clone()).ok();
                        tokio::spawn(async move {
                            let _guard = guard;
                            let refresh = async {
                                if layer
                                    .get(&key)
                                    .is_some_and(|current| !Arc::ptr_eq(&current, &page))
                                {
                                    return;
                                }
                                // The background task owns the coalescing guard. Bound
                                // stream preparation as well as the body read so a render
                                // stalled before its first chunk releases the guard.
                                let regenerate = async {
                                    let (response, _) =
                                        fetch(&layer, key, inner, request, None).await?;
                                    read_recording(response).await;
                                    Ok::<(), S::Error>(())
                                };
                                match tokio::time::timeout(layer.timeout, regenerate).await {
                                    Ok(Ok(())) => {}
                                    Ok(Err(_)) => {
                                        tracing::warn!("page cache background regeneration failed");
                                    }
                                    Err(_) => {
                                        tracing::warn!(
                                            "page cache background regeneration timed out"
                                        );
                                    }
                                }
                            };
                            if let Some(context) = context {
                                ROUTE_CONTEXT.scope(RefCell::new(context), refresh).await;
                            } else {
                                refresh.await;
                            }
                        });
                    }
                    return Ok(response);
                }
            }
            // Never seed a GET entry from a HEAD response with an empty body.
            if head {
                return pass(inner, request).await;
            }
            // Fixed lock stripes bound coordination memory as well as stored
            // pages. Cancellation/panics release the guard automatically.
            let lock = layer.cache.locks[key[0] as usize % LOCK_COUNT]
                .clone()
                .lock_owned()
                .await;
            if let Some(page) = layer.get(&key).filter(|page| layer.fresh(page)) {
                return Ok(page.response(&headers, false, "HIT"));
            }
            let (response, page) = fetch(&layer, key, inner, request, Some(lock)).await?;
            Ok(match page {
                Some(page) if matches_etag(&headers, &page.etag) => {
                    page.response(&headers, false, "MISS")
                }
                _ => response,
            })
        })
    }
}

struct Cache {
    pages: Mutex<HashMap<Key, Arc<CachedPage>>>,
    locks: [Arc<AsyncMutex<()>>; LOCK_COUNT],
}

struct CachedPage {
    headers: HeaderMap,
    body: Bytes,
    etag: HeaderValue,
    created: Instant,
}

impl CachedPage {
    fn response(&self, request_headers: &HeaderMap, head: bool, status: &'static str) -> Response {
        let not_modified = matches_etag(request_headers, &self.etag);
        let mut response = Response::new(if head || not_modified {
            Body::empty()
        } else {
            Body::from(self.body.clone())
        });
        *response.headers_mut() = self.headers.clone();
        response
            .headers_mut()
            .insert(STATUS, HeaderValue::from_static(status));
        if not_modified {
            *response.status_mut() = StatusCode::NOT_MODIFIED;
            response.headers_mut().remove(header::CONTENT_LENGTH);
        }
        response
    }
}

/// Render a miss and store it when cacheable.
///
/// `lock` coalesces concurrent misses for the key. It is released as soon
/// as the response turns out to be a stream: like any streamed page, its
/// misses then render independently, so a stream never waits behind another
/// request's render.
async fn fetch<S>(
    layer: &PageCacheLayer,
    key: Key,
    inner: S,
    mut request: Request<Body>,
    lock: Option<OwnedMutexGuard<()>>,
) -> Result<(Response, Option<Arc<CachedPage>>), S::Error>
where
    S: Service<Request<Body>, Response = Response> + Send,
    S::Future: Send,
{
    // The cache owns validators. An origin 304 cannot populate an empty entry.
    request.headers_mut().remove(header::IF_NONE_MATCH);
    request.headers_mut().remove(header::IF_MODIFIED_SINCE);
    super::cdn_cache::may_store(&mut request);
    let deadline = Instant::now() + layer.timeout;
    let render = async {
        let response = inner.oneshot(request).await?;
        Ok(super::response::finish_deferred_render(response).await)
    };
    let response = match tokio::time::timeout_at(deadline, render).await {
        Ok(response) => response?,
        Err(_) => return Ok((timed_out(), None)),
    };
    if response.extensions().get::<CacheableStream>().is_some() {
        drop(lock);
        let response = prepare_cacheable_stream(response).await;
        return Ok((record_stream(layer, key, response, deadline), None));
    }
    if !cacheable_response(layer, &response) {
        return Ok((uncacheable(layer, key, response), None));
    }
    let (parts, body) = response.into_parts();
    match tokio::time::timeout_at(deadline, to_bytes(body, layer.max_body_bytes)).await {
        Ok(Ok(bytes)) => Ok(store(layer, key, parts, bytes)),
        Ok(Err(error)) => {
            tracing::warn!(%error, "page cache could not collect response body");
            Ok((
                bypass((StatusCode::BAD_GATEWAY, "page response failed").into_response()),
                None,
            ))
        }
        Err(_) => Ok((timed_out(), None)),
    }
}

fn timed_out() -> Response {
    tracing::warn!("page cache regeneration timed out");
    bypass((StatusCode::GATEWAY_TIMEOUT, "page regeneration timed out").into_response())
}

/// Pass a response the cache will not store.
fn uncacheable(layer: &PageCacheLayer, key: Key, response: Response) -> Response {
    // Keep stale public content on transient server failures only.
    if !response.status().is_server_error() {
        layer.cache.pages.lock().remove(&key);
    }
    bypass(response)
}

/// Send an in-order stream at once, and store it once it ends.
///
/// The head decides first: a page the cache cannot store bypasses. Otherwise
/// the page leaves as a MISS and the cache keeps a copy of each chunk it
/// sends. The page is stored when its body ends within the size limit and
/// the cache deadline. A body that outgrows the limit, fails, or ends late
/// is still delivered as it renders and is not stored, so the cache never
/// holds back a response head or cuts a body short. The copy is freed as
/// soon as the page cannot be stored, even while a chunk is pending.
fn record_stream(
    layer: &PageCacheLayer,
    key: Key,
    response: Response,
    deadline: Instant,
) -> Response {
    if !super::cdn_cache::prepared_cacheable_stream(&response) || !cacheable_head(layer, &response)
    {
        return uncacheable(layer, key, response);
    }
    if Instant::now() >= deadline {
        // An outer cache opens the stream after its timed lookup. A page that
        // took the whole deadline to start cannot be stored in time.
        tracing::warn!("page cache stopped recording a stream at its timeout");
        return bypass(response);
    }
    let (mut parts, body) = response.into_parts();
    page_head(layer, &mut parts.headers);
    let page = PartialPage {
        layer: layer.clone(),
        key,
        headers: parts.headers.clone(),
        chunks: Vec::new(),
        len: 0,
        deadline,
    };
    parts
        .headers
        .insert(STATUS, HeaderValue::from_static("MISS"));
    let state = (Some(body.into_data_stream()), Some(page));
    let body = stream::unfold(state, |(data, mut page)| async move {
        let mut data = data?;
        let next = match page.as_ref().map(|page| page.deadline) {
            Some(deadline) => match tokio::time::timeout_at(deadline, data.next()).await {
                Ok(next) => next,
                Err(_) => {
                    // Too late to store: free the copy and keep delivering.
                    tracing::warn!("page cache stopped recording a stream at its timeout");
                    page = None;
                    data.next().await
                }
            },
            None => data.next().await,
        };
        match next {
            Some(Ok(chunk)) => {
                if page.as_mut().is_some_and(|page| !page.push(&chunk)) {
                    // Too large to store: deliver it, and drop any stale copy.
                    if let Some(page) = page.take() {
                        page.layer.cache.pages.lock().remove(&page.key);
                    }
                }
                Some((Ok(chunk), (Some(data), page)))
            }
            // A failed body is not stored.
            Some(Err(error)) => Some((Err(error), (None, None))),
            None => {
                if let Some(page) = page {
                    page.store();
                }
                None
            }
        }
    });
    Response::from_parts(parts, Body::from_stream(body))
}

/// Read a streamed MISS to its end, which stores it.
async fn read_recording(response: Response) {
    if response
        .headers()
        .get(STATUS)
        .is_some_and(|status| status == "MISS")
    {
        let mut body = response.into_body();
        while let Some(Ok(_)) = body.frame().await {}
    }
}

/// The part of a streamed page recorded so far.
struct PartialPage {
    layer: PageCacheLayer,
    key: Key,
    headers: HeaderMap,
    chunks: Vec<Bytes>,
    len: usize,
    deadline: Instant,
}

impl PartialPage {
    /// Record a chunk, or report that the page outgrew the body limit.
    fn push(&mut self, chunk: &Bytes) -> bool {
        self.len += chunk.len();
        if self.len > self.layer.max_body_bytes {
            return false;
        }
        self.chunks.push(chunk.clone());
        true
    }

    fn store(self) {
        if Instant::now() > self.deadline {
            tracing::warn!("page cache did not store a stream that ended after its timeout");
            return;
        }
        let body = concat(self.chunks, self.len);
        insert_page(&self.layer, self.key, self.headers, body);
    }
}

fn concat(chunks: Vec<Bytes>, len: usize) -> Bytes {
    match <[Bytes; 1]>::try_from(chunks) {
        Ok([bytes]) => bytes,
        Err(chunks) => {
            let mut bytes = BytesMut::with_capacity(len);
            for chunk in chunks {
                bytes.extend_from_slice(&chunk);
            }
            bytes.freeze()
        }
    }
}

/// Set the downstream policy and the cache's Vary fields on a page's head.
fn page_head(layer: &PageCacheLayer, headers: &mut HeaderMap) {
    downstream_policy(headers, "public, no-cache");
    for name in layer.vary.iter() {
        if !headers.get_all(header::VARY).iter().any(|value| {
            value.to_str().is_ok_and(|value| {
                value
                    .split(',')
                    .any(|field| field.trim().eq_ignore_ascii_case(name.as_str()))
            })
        }) {
            headers.append(
                header::VARY,
                HeaderValue::from_str(name.as_str()).expect("header name is a valid value"),
            );
        }
    }
}

/// Store a complete page, with its validator and length.
fn insert_page(
    layer: &PageCacheLayer,
    key: Key,
    mut headers: HeaderMap,
    body: Bytes,
) -> Arc<CachedPage> {
    let mut hash = Sha256::new();
    hash.update(key);
    hash.update(&body);
    let etag = HeaderValue::from_str(&format!("\"{:x}\"", HexDisplay(&hash.finalize())))
        .expect("hex digest is a valid ETag");
    headers.insert(header::ETAG, etag.clone());
    headers.insert(header::CONTENT_LENGTH, HeaderValue::from(body.len()));
    let page = Arc::new(CachedPage {
        headers,
        body,
        etag,
        created: Instant::now(),
    });
    layer.insert(key, page.clone());
    page
}

/// Store a complete page and build its MISS response.
fn store(
    layer: &PageCacheLayer,
    key: Key,
    mut parts: axum::http::response::Parts,
    bytes: Bytes,
) -> (Response, Option<Arc<CachedPage>>) {
    page_head(layer, &mut parts.headers);
    let page = insert_page(
        layer,
        key,
        std::mem::take(&mut parts.headers),
        bytes.clone(),
    );
    parts.headers = page.headers.clone();
    parts
        .headers
        .insert(STATUS, HeaderValue::from_static("MISS"));
    (Response::from_parts(parts, Body::from(bytes)), Some(page))
}

/// Serve a request the cache must not store. The render finishes first, so
/// the bypass policy edits the page, not a deferred placeholder.
async fn pass<S>(inner: S, request: Request<Body>) -> Result<Response, S::Error>
where
    S: Service<Request<Body>, Response = Response> + Send,
    S::Future: Send,
{
    let response = inner.oneshot(request).await?;
    Ok(bypass(
        super::response::finish_deferred_render(response).await,
    ))
}

pub(super) fn bypass_request(request: &Request<Body>) -> bool {
    !matches!(*request.method(), Method::GET | Method::HEAD)
        || !request.body().is_end_stream()
        || request.extensions().get::<proa_core::CspNonce>().is_some()
        || [
            header::AUTHORIZATION,
            header::COOKIE,
            header::RANGE,
            header::IF_MATCH,
            header::IF_UNMODIFIED_SINCE,
        ]
        .iter()
        .any(|name| request.headers().contains_key(name))
        || has_directive(request.headers(), header::CACHE_CONTROL, "no-store")
}

fn cacheable_response(layer: &PageCacheLayer, response: &Response) -> bool {
    response
        .extensions()
        .get::<DeferredFrameworkStream>()
        .is_none()
        && response
            .body()
            .size_hint()
            .exact()
            .is_some_and(|len| len <= layer.max_body_bytes as u64)
        && cacheable_head(layer, response)
}

/// Whether the status and headers allow storage, whatever the body.
fn cacheable_head(layer: &PageCacheLayer, response: &Response) -> bool {
    let headers = response.headers();
    response.status() == StatusCode::OK
        && !headers.contains_key(header::SET_COOKIE)
        && !headers.contains_key(header::TRAILER)
        && !headers.contains_key(header::CONTENT_RANGE)
        && headers
            .iter()
            .map(|(name, value)| name.as_str().len().saturating_add(value.len()))
            .sum::<usize>()
            <= 64 * 1024
        && [
            header::CACHE_CONTROL,
            HeaderName::from_static("cdn-cache-control"),
            HeaderName::from_static("cloudflare-cdn-cache-control"),
            HeaderName::from_static("vercel-cdn-cache-control"),
        ]
        .iter()
        .all(|name| {
            !has_directive(headers, name.clone(), "private")
                && !has_directive(headers, name.clone(), "no-store")
        })
        && [
            header::CONTENT_SECURITY_POLICY,
            header::CONTENT_SECURITY_POLICY_REPORT_ONLY,
        ]
        .iter()
        .all(|name| {
            headers
                .get_all(name)
                .iter()
                .all(|value| value.to_str().is_ok_and(|value| !value.contains("'nonce-")))
        })
        && headers.get_all(header::VARY).iter().all(|value| {
            value.to_str().is_ok_and(|value| {
                value.split(',').all(|field| {
                    let field = field.trim();
                    field.is_empty()
                        || layer
                            .vary
                            .iter()
                            .any(|name| field.eq_ignore_ascii_case(name.as_str()))
                })
            })
        })
}

fn downstream_policy(headers: &mut HeaderMap, policy: &'static str) {
    for name in [
        "cache-control",
        "cdn-cache-control",
        "cloudflare-cdn-cache-control",
        "vercel-cdn-cache-control",
    ] {
        headers.insert(name, HeaderValue::from_static(policy));
    }
    headers.remove("surrogate-control");
    headers.remove(header::EXPIRES);
    headers.remove(header::AGE);
}

fn bypass(mut response: Response) -> Response {
    downstream_policy(response.headers_mut(), "private, no-store");
    response
        .headers_mut()
        .insert(STATUS, HeaderValue::from_static("BYPASS"));
    response
}

fn has_directive(headers: &HeaderMap, name: HeaderName, directive: &str) -> bool {
    headers.get_all(name).iter().any(|value| {
        value.to_str().map_or(true, |value| {
            value.split(',').any(|part| {
                part.split('=')
                    .next()
                    .unwrap_or("")
                    .trim()
                    .eq_ignore_ascii_case(directive)
            })
        })
    })
}

fn matches_etag(headers: &HeaderMap, etag: &HeaderValue) -> bool {
    headers.get_all(header::IF_NONE_MATCH).iter().any(|value| {
        value.to_str().is_ok_and(|value| {
            value.split(',').any(|candidate| {
                let candidate = candidate.trim();
                candidate == "*"
                    || candidate.strip_prefix("W/").unwrap_or(candidate).as_bytes()
                        == etag.as_bytes()
            })
        })
    })
}

fn hash_field(hash: &mut Sha256, bytes: &[u8]) {
    hash.update((bytes.len() as u64).to_le_bytes());
    hash.update(bytes);
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicBool, Ordering};

    /// Chunk bytes that report when the last copy is dropped.
    struct Tracked(Arc<AtomicBool>);

    impl AsRef<[u8]> for Tracked {
        fn as_ref(&self) -> &[u8] {
            b"<p>first</p>"
        }
    }

    impl Drop for Tracked {
        fn drop(&mut self) {
            self.0.store(true, Ordering::SeqCst);
        }
    }

    #[tokio::test(start_paused = true)]
    async fn a_recording_past_its_deadline_frees_its_copy() {
        let layer = PageCacheLayer::new("build").with_timeout(Duration::from_millis(100));
        let key = [7; 32];
        let (chunks, rx) = futures::channel::mpsc::unbounded::<Result<Bytes, io::Error>>();
        let mut response = Response::builder()
            .header(header::CONTENT_TYPE, "text/html; charset=utf-8")
            .body(Body::from_stream(rx))
            .unwrap();
        response.extensions_mut().insert(CacheableStream::default());
        let response = record_stream(&layer, key, response, Instant::now() + layer.timeout);
        assert_eq!(response.headers()[STATUS], "MISS");
        let mut body = response.into_body();

        let freed = Arc::new(AtomicBool::new(false));
        chunks
            .unbounded_send(Ok(Bytes::from_owner(Tracked(freed.clone()))))
            .unwrap();
        let first = body.frame().await.unwrap().unwrap().into_data().unwrap();
        assert_eq!(first, "<p>first</p>");
        drop(first);
        assert!(!freed.load(Ordering::SeqCst), "the recording keeps a copy");

        // The next chunk is still pending when the deadline passes.
        let waiting = tokio::time::timeout(Duration::from_millis(150), body.frame()).await;
        assert!(waiting.is_err());
        assert!(freed.load(Ordering::SeqCst), "the expired copy was freed");

        chunks
            .unbounded_send(Ok(Bytes::from_static(b"<p>last</p>")))
            .unwrap();
        drop(chunks);
        let rest = body.collect().await.unwrap().to_bytes();
        assert_eq!(rest, "<p>last</p>");
        assert!(layer.cache.pages.lock().get(&key).is_none());
    }
}