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
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
// Copyright Proa Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::{
    convert::Infallible,
    future::Future,
    sync::{
        atomic::{AtomicUsize, Ordering},
        Arc,
    },
    time::Duration,
};

use axum::{
    body::{to_bytes, Body},
    http::{header, HeaderName, HeaderValue, Method, Request, StatusCode},
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use proa_core::{
    ComponentRole, DataLoader, HeadConfig, MdRenderSync, RenderOutcome, WebContext, WebRender,
    WriteBuf, WriteError,
};
use proa_framework_axum::{
    explicit_markdown, router_from_spec, FrameworkBuilder, PageCache, PageCacheLayer, Route,
    RouteResponse,
};
use proa_macros::{html, html_send, html_sync, md_sync};
use proa_stream::Suspense;
use tokio::sync::Notify;
use tower::{service_fn, Layer, ServiceExt};

fn request(uri: &str) -> Request<Body> {
    Request::builder().uri(uri).body(Body::empty()).unwrap()
}

async fn body(response: Response) -> String {
    String::from_utf8(
        to_bytes(response.into_body(), 1024 * 1024)
            .await
            .unwrap()
            .to_vec(),
    )
    .unwrap()
}

fn counter_app(layer: PageCacheLayer, calls: Arc<AtomicUsize>) -> Router {
    Router::new()
        .route(
            "/",
            get(move || {
                let calls = calls.clone();
                async move { calls.fetch_add(1, Ordering::SeqCst).to_string() }
            }),
        )
        .route_layer(layer)
}

#[tokio::test]
async fn cache_hits_skip_handler_and_revalidate_without_a_body() {
    let calls = Arc::new(AtomicUsize::new(0));
    let app = counter_app(PageCacheLayer::new("build-a"), calls.clone());
    let first = app.clone().oneshot(request("/")).await.unwrap();
    assert_eq!(first.headers()["x-proa-page-cache"], "MISS");
    assert_eq!(first.headers()[header::CACHE_CONTROL], "public, no-cache");
    let etag = first.headers()[header::ETAG].clone();
    assert_eq!(body(first).await, "0");
    let hit = app.clone().oneshot(request("/")).await.unwrap();
    assert_eq!(hit.headers()["x-proa-page-cache"], "HIT");
    assert_eq!(body(hit).await, "0");

    for validator in [
        etag.to_str().unwrap().to_owned(),
        format!("\"other\", W/{}", etag.to_str().unwrap()),
        "*".into(),
    ] {
        let mut req = request("/");
        req.headers_mut()
            .insert(header::IF_NONE_MATCH, validator.parse().unwrap());
        let response = app.clone().oneshot(req).await.unwrap();
        assert_eq!(response.status(), StatusCode::NOT_MODIFIED);
        assert_eq!(response.headers()[header::ETAG], etag);
        assert_eq!(
            response.headers()[header::CACHE_CONTROL],
            "public, no-cache"
        );
        assert!(response.headers().contains_key(header::VARY));
        assert_eq!(body(response).await, "");
    }
    assert_eq!(calls.load(Ordering::SeqCst), 1);
}

#[tokio::test]
async fn new_build_cannot_validate_the_previous_builds_page() {
    let old = counter_app(
        PageCacheLayer::new("old-build"),
        Arc::new(AtomicUsize::new(0)),
    );
    let old_response = old.oneshot(request("/")).await.unwrap();
    let old_etag = old_response.headers()[header::ETAG].clone();
    let new_calls = Arc::new(AtomicUsize::new(0));
    let new = counter_app(PageCacheLayer::new("new-build"), new_calls.clone());
    let mut req = request("/");
    req.headers_mut()
        .insert(header::IF_NONE_MATCH, old_etag.clone());
    let response = new.oneshot(req).await.unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    assert_ne!(response.headers()[header::ETAG], old_etag);
    assert_eq!(new_calls.load(Ordering::SeqCst), 1);
}

#[tokio::test]
async fn hosts_queries_and_representations_have_separate_entries() {
    let calls = Arc::new(AtomicUsize::new(0));
    let app = counter_app(PageCacheLayer::new("build"), calls.clone());
    for (url, host, accept, client) in [
        ("/?q=1", "a.example", "text/html", ""),
        ("/?q=2", "a.example", "text/html", ""),
        ("/?q=1", "b.example", "text/html", ""),
        ("/?q=1", "a.example", "text/markdown", ""),
        ("/?q=1", "a.example", "text/html", "1"),
    ] {
        for expected in ["MISS", "HIT"] {
            let req = Request::builder()
                .uri(url)
                .header("host", host)
                .header("accept", accept)
                .header("x-proa-client", client)
                .body(Body::empty())
                .unwrap();
            let response = app.clone().oneshot(req).await.unwrap();
            assert_eq!(response.headers()["x-proa-page-cache"], expected);
        }
    }
    assert_eq!(calls.load(Ordering::SeqCst), 5);
}

#[tokio::test]
async fn private_requests_bypass_existing_public_entries() {
    let calls = Arc::new(AtomicUsize::new(0));
    let app = counter_app(PageCacheLayer::new("build"), calls.clone());
    app.clone().oneshot(request("/")).await.unwrap();
    for (name, value) in [
        ("cookie", "session=secret"),
        ("authorization", "Bearer secret"),
        ("cache-control", "no-store"),
        ("range", "bytes=0-1"),
    ] {
        let mut req = request("/");
        req.headers_mut().insert(
            HeaderName::from_bytes(name.as_bytes()).unwrap(),
            value.parse().unwrap(),
        );
        let response = app.clone().oneshot(req).await.unwrap();
        assert_eq!(response.headers()["x-proa-page-cache"], "BYPASS");
        assert_eq!(
            response.headers()[header::CACHE_CONTROL],
            "private, no-store"
        );
    }
    let mut req = request("/");
    req.extensions_mut()
        .insert(proa_core::CspNonce::new("dGVzdA").unwrap());
    assert_eq!(
        app.clone().oneshot(req).await.unwrap().headers()["x-proa-page-cache"],
        "BYPASS"
    );
    assert_eq!(calls.load(Ordering::SeqCst), 6);
    assert_eq!(body(app.oneshot(request("/")).await.unwrap()).await, "0");
}

#[tokio::test]
async fn unsafe_responses_and_unknown_vary_fields_are_not_stored() {
    for (name, value) in [
        ("cache-control", "PRIVATE, max-age=60"),
        ("cache-control", "no-store"),
        ("cloudflare-cdn-cache-control", "no-store"),
        ("set-cookie", "session=secret"),
        ("vary", "*"),
        ("vary", "x-theme"),
        ("content-security-policy", "script-src 'nonce-dGVzdA'"),
    ] {
        let calls = Arc::new(AtomicUsize::new(0));
        let count = calls.clone();
        let service = PageCacheLayer::new("build").layer(service_fn(move |_| {
            count.fetch_add(1, Ordering::SeqCst);
            async move {
                Ok::<_, Infallible>(
                    Response::builder()
                        .header(name, value)
                        .body(Body::from("private"))
                        .unwrap(),
                )
            }
        }));
        for _ in 0..2 {
            assert_eq!(
                service
                    .clone()
                    .oneshot(request("/"))
                    .await
                    .unwrap()
                    .headers()["x-proa-page-cache"],
                "BYPASS"
            );
        }
        assert_eq!(calls.load(Ordering::SeqCst), 2, "{name}: {value}");
    }
}

#[tokio::test]
async fn registered_vary_fields_are_partitioned_and_cacheable() {
    let layer = PageCacheLayer::new("build").vary_on(HeaderName::from_static("x-theme"));
    let service = layer.layer(service_fn(|req: Request<Body>| async move {
        Ok::<_, Infallible>(
            Response::builder()
                .header("vary", "x-theme")
                .body(Body::from(
                    req.headers()["x-theme"].to_str().unwrap().to_owned(),
                ))
                .unwrap(),
        )
    }));
    for theme in ["light", "dark", "light"] {
        let req = Request::builder()
            .uri("/")
            .header("x-theme", theme)
            .body(Body::empty())
            .unwrap();
        assert_eq!(
            body(service.clone().oneshot(req).await.unwrap()).await,
            theme
        );
    }
}

#[tokio::test]
async fn head_hits_have_no_body_and_head_misses_never_seed_get() {
    let calls = Arc::new(AtomicUsize::new(0));
    let app = counter_app(PageCacheLayer::new("build"), calls.clone());
    let mut head = request("/");
    *head.method_mut() = Method::HEAD;
    assert_eq!(
        app.clone().oneshot(head).await.unwrap().headers()["x-proa-page-cache"],
        "BYPASS"
    );
    let get = app.clone().oneshot(request("/")).await.unwrap();
    assert_eq!(get.headers()["x-proa-page-cache"], "MISS");
    assert_eq!(body(get).await, "1");
    let mut head = request("/");
    *head.method_mut() = Method::HEAD;
    let response = app.oneshot(head).await.unwrap();
    assert_eq!(response.headers()["x-proa-page-cache"], "HIT");
    assert_eq!(response.headers()[header::CONTENT_LENGTH], "1");
    assert_eq!(body(response).await, "");
    assert_eq!(calls.load(Ordering::SeqCst), 2);
}

#[tokio::test]
async fn simultaneous_misses_render_once() {
    let calls = Arc::new(AtomicUsize::new(0));
    let count = calls.clone();
    let service = PageCacheLayer::new("build").layer(service_fn(move |_| {
        count.fetch_add(1, Ordering::SeqCst);
        async {
            tokio::task::yield_now().await;
            Ok::<_, Infallible>(Response::new(Body::from("complete")))
        }
    }));
    let responses =
        futures::future::join_all((0..16).map(|_| service.clone().oneshot(request("/")))).await;
    for response in responses {
        assert_eq!(body(response.unwrap()).await, "complete");
    }
    assert_eq!(calls.load(Ordering::SeqCst), 1);
}

#[tokio::test(start_paused = true)]
async fn isr_serves_stale_collapses_refreshes_and_retains_route_context() {
    let calls = Arc::new(AtomicUsize::new(0));
    let started = Arc::new(Notify::new());
    let release = Arc::new(Notify::new());
    let count = calls.clone();
    let signal = started.clone();
    let gate = release.clone();
    let routes = Router::new()
        .route(
            "/",
            get(move || {
                let count = count.clone();
                let signal = signal.clone();
                let gate = gate.clone();
                async move {
                    let generation = count.fetch_add(1, Ordering::SeqCst);
                    if generation > 0 {
                        signal.notify_one();
                        gate.notified().await;
                    }
                    RouteResponse::ssr(proa_core::text::text(if generation == 0 {
                        "initial"
                    } else {
                        "regenerated"
                    }))
                }
            }),
        )
        .route_layer(PageCacheLayer::new("build").revalidate(Duration::from_secs(3600)));
    let app = FrameworkBuilder::new().with_dynamic_routes(routes).build();

    let first = app.clone().oneshot(request("/")).await.unwrap();
    assert_eq!(first.status(), StatusCode::OK);
    let first_body = body(first).await;
    tokio::time::advance(Duration::from_secs(3601)).await;
    let stale = app.clone().oneshot(request("/")).await.unwrap();
    assert_eq!(stale.headers()["x-proa-page-cache"], "STALE");
    assert_eq!(body(stale).await, first_body);
    started.notified().await;
    for _ in 0..8 {
        assert_eq!(
            app.clone().oneshot(request("/")).await.unwrap().headers()["x-proa-page-cache"],
            "STALE"
        );
    }
    assert_eq!(calls.load(Ordering::SeqCst), 2);
    release.notify_one();
    tokio::task::yield_now().await;
    let refreshed = app.oneshot(request("/")).await.unwrap();
    assert_eq!(refreshed.status(), StatusCode::OK);
    assert_eq!(refreshed.headers()["x-proa-page-cache"], "HIT");
    assert_ne!(body(refreshed).await, first_body);
}

#[tokio::test(start_paused = true)]
async fn isr_releases_the_lock_when_stream_preparation_stalls() {
    let generations = Arc::new(AtomicUsize::new(0));
    let started = Arc::new(Notify::new());
    let routes = Router::new()
        .route(
            "/",
            get({
                let generations = generations.clone();
                let started = started.clone();
                move || {
                    let generation = generations.fetch_add(1, Ordering::SeqCst);
                    let started = started.clone();
                    async move {
                        if generation == 1 {
                            return RouteResponse::ssr_stream_send(html_send! {
                                {proa_core::await_send_component(async move {
                                    started.notify_one();
                                    std::future::pending::<()>().await;
                                    html_send! { <p>"unreachable"</p> }
                                })}
                            });
                        }
                        RouteResponse::ssr(generation)
                    }
                }
            }),
        )
        .route_layer(
            PageCacheLayer::new("build")
                .revalidate(Duration::from_secs(1))
                .with_timeout(Duration::from_millis(50)),
        );
    let app = FrameworkBuilder::new().with_dynamic_routes(routes).build();

    assert_eq!(
        body(app.clone().oneshot(request("/")).await.unwrap()).await,
        "0"
    );
    tokio::time::advance(Duration::from_secs(2)).await;

    let stale = app.clone().oneshot(request("/")).await.unwrap();
    assert_eq!(cache_status(&stale), "STALE");
    assert_eq!(body(stale).await, "0");
    started.notified().await;
    tokio::time::advance(Duration::from_millis(100)).await;

    let mut fresh = request("/");
    fresh
        .headers_mut()
        .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
    let response = tokio::time::timeout(Duration::from_secs(1), app.oneshot(fresh))
        .await
        .expect("stalled refresh must release the cache lock")
        .unwrap();
    assert_eq!(cache_status(&response), "MISS");
    assert_eq!(body(response).await, "2");
}

#[tokio::test(start_paused = true)]
async fn failed_refresh_keeps_stale_until_the_stale_window_expires() {
    let calls = Arc::new(AtomicUsize::new(0));
    let count = calls.clone();
    let service = PageCacheLayer::new("build")
        .revalidate(Duration::from_secs(10))
        .stale_while_revalidate(Duration::from_secs(20))
        .layer(service_fn(move |_| {
            let generation = count.fetch_add(1, Ordering::SeqCst);
            async move {
                Ok::<_, Infallible>(if generation == 0 {
                    "initial".into_response()
                } else {
                    StatusCode::SERVICE_UNAVAILABLE.into_response()
                })
            }
        }));
    let initial = body(service.clone().oneshot(request("/")).await.unwrap()).await;
    tokio::time::advance(Duration::from_secs(11)).await;
    assert_eq!(
        body(service.clone().oneshot(request("/")).await.unwrap()).await,
        initial
    );
    tokio::task::yield_now().await;
    assert_eq!(
        body(service.clone().oneshot(request("/")).await.unwrap()).await,
        initial
    );
    tokio::task::yield_now().await;
    tokio::time::advance(Duration::from_secs(20)).await;
    assert_eq!(
        service.oneshot(request("/")).await.unwrap().status(),
        StatusCode::SERVICE_UNAVAILABLE
    );
}

#[tokio::test]
async fn limits_evict_old_entries_and_pass_oversized_bodies_through() {
    let calls = Arc::new(AtomicUsize::new(0));
    let app = counter_app(
        PageCacheLayer::new("build").with_limits(1, 100),
        calls.clone(),
    );
    for uri in ["/?a", "/?b", "/?a"] {
        assert_eq!(
            app.clone().oneshot(request(uri)).await.unwrap().headers()["x-proa-page-cache"],
            "MISS"
        );
    }
    assert_eq!(calls.load(Ordering::SeqCst), 3);
    let app = counter_app(
        PageCacheLayer::new("build").with_limits(1, 0),
        calls.clone(),
    );
    for expected in ["3", "4"] {
        let response = app.clone().oneshot(request("/")).await.unwrap();
        assert_eq!(response.headers()["x-proa-page-cache"], "BYPASS");
        assert_eq!(body(response).await, expected);
    }
}

#[tokio::test(start_paused = true)]
async fn timeout_releases_the_miss_lock_for_later_requests() {
    let calls = Arc::new(AtomicUsize::new(0));
    let count = calls.clone();
    let service = PageCacheLayer::new("build")
        .with_timeout(Duration::from_secs(1))
        .layer(service_fn(move |_| {
            let n = count.fetch_add(1, Ordering::SeqCst);
            async move {
                if n == 0 {
                    std::future::pending::<()>().await;
                }
                Ok::<_, Infallible>(Response::new(Body::from("recovered")))
            }
        }));
    assert_eq!(
        service
            .clone()
            .oneshot(request("/"))
            .await
            .unwrap()
            .status(),
        StatusCode::GATEWAY_TIMEOUT
    );
    assert_eq!(
        body(service.oneshot(request("/")).await.unwrap()).await,
        "recovered"
    );
}

#[tokio::test]
async fn streaming_bodies_bypass_without_losing_chunks() {
    let service = PageCacheLayer::new("build").layer(service_fn(|_| async {
        let chunks = futures::stream::iter([Ok::<_, Infallible>("first"), Ok("second")]);
        Ok::<_, Infallible>(Response::new(Body::from_stream(chunks)))
    }));
    let response = service.oneshot(request("/")).await.unwrap();
    assert_eq!(response.headers()["x-proa-page-cache"], "BYPASS");
    assert_eq!(body(response).await, "firstsecond");
}

#[tokio::test]
async fn downstream_freshness_headers_cannot_hide_a_deployment() {
    let service = PageCacheLayer::new("build").layer(service_fn(|_| async {
        Ok::<_, Infallible>(
            Response::builder()
                .header("cache-control", "public, max-age=31536000")
                .header("cloudflare-cdn-cache-control", "max-age=31536000")
                .header("surrogate-control", "max-age=31536000")
                .body(Body::from("page"))
                .unwrap(),
        )
    }));
    for _ in 0..2 {
        let response = service.clone().oneshot(request("/")).await.unwrap();
        for name in [
            "cache-control",
            "cdn-cache-control",
            "cloudflare-cdn-cache-control",
            "vercel-cdn-cache-control",
        ] {
            assert_eq!(
                response.headers()[name],
                HeaderValue::from_static("public, no-cache")
            );
        }
        assert!(!response.headers().contains_key("surrogate-control"));
    }
}

/// Resolves after the streamed shell, so a stream shows its fallback first.
struct Slow;

impl<L: DataLoader, B: WriteBuf> WebRender<L, B> for Slow {
    fn render(
        self,
        cx: &mut WebContext<L, B>,
    ) -> RenderOutcome<impl Future<Output = Result<(), WriteError>>> {
        RenderOutcome::pending(async move {
            tokio::time::sleep(Duration::from_millis(5)).await;
            html! { <p>"resolved"</p> }.render(cx).resolve().await
        })
    }
}

/// A buffered page that chooses its own cache policy while rendering.
struct SelfCachingPage;

impl<L: DataLoader, B: WriteBuf> WebRender<L, B> for SelfCachingPage {
    fn render(
        self,
        cx: &mut WebContext<L, B>,
    ) -> RenderOutcome<impl Future<Output = Result<(), WriteError>>> {
        RenderOutcome::pending(async move {
            tokio::task::yield_now().await;
            assert!(cx.response_mut().insert_header(
                header::CACHE_CONTROL,
                HeaderValue::from_static("public, max-age=30"),
            ));
            html! { <p>"page"</p> }.render(cx).resolve().await
        })
    }
}

/// A managed-head page whose head hook chooses the cache policy.
struct HeadPolicyPage;

impl WebRender for HeadPolicyPage {
    const ROLE: ComponentRole = ComponentRole::PAGE;

    async fn render_head(&self, cx: &mut WebContext) -> Result<(), WriteError> {
        assert!(cx.response_mut().insert_header(
            header::CACHE_CONTROL,
            HeaderValue::from_static("public, max-age=86400"),
        ));
        Ok(())
    }

    fn render(
        self,
        cx: &mut WebContext,
    ) -> RenderOutcome<impl Future<Output = Result<(), WriteError>>> {
        html! {
            <html>
                <head>{cx.head()}</head>
                <body></body>
            </html>
        }
        .render(cx)
    }
}

struct Notes;

impl<L: DataLoader, B: WriteBuf> MdRenderSync<L, B> for Notes {
    fn render_md(self, cx: &mut WebContext<L, B>) -> Result<(), WriteError> {
        md_sync! { r###"
            # Notes
            "###
        }
        .render_md(cx)
    }
}

fn streamed_page() -> RouteResponse {
    RouteResponse::ssr_stream(html! {
        <main>
            {Suspense::new(Slow, html_sync! {
                <p>"loading"</p>
            })}
        </main>
    })
}

fn cache_control(response: &Response) -> Option<&str> {
    response
        .headers()
        .get(header::CACHE_CONTROL)
        .map(|value| value.to_str().unwrap())
}

async fn assert_cache_control(app: &Router, cases: &[(&str, Option<&str>)]) {
    for (uri, expected) in cases {
        let response = app.clone().oneshot(request(uri)).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK, "{uri}");
        assert_eq!(cache_control(&response), *expected, "{uri}");
        body(response).await;
    }
}

#[tokio::test]
async fn framework_documents_without_a_policy_are_private_no_store() {
    let routes = Router::new()
        .route(
            "/",
            get(|| async { RouteResponse::ssr(proa_core::text::text("page")) }),
        )
        .route("/async", get(|| async { RouteResponse::ssr_async(Slow) }))
        .route("/stream", get(|| async { streamed_page() }))
        .route(
            "/index.md",
            get(|| async { explicit_markdown(Notes).unwrap() }),
        )
        .route(
            "/own",
            get(|| async {
                (
                    [(header::CACHE_CONTROL, "public, max-age=60")],
                    RouteResponse::ssr_async(Slow),
                )
            }),
        )
        .route(
            "/page",
            get(|| async { RouteResponse::ssr_async(SelfCachingPage) }),
        )
        .route(
            "/edge",
            get(|| async {
                (
                    [("cdn-cache-control", "max-age=60")],
                    RouteResponse::ssr(proa_core::text::text("page")),
                )
            }),
        )
        .route("/plain", get(|| async { "ok" }));
    let app = FrameworkBuilder::new().with_dynamic_routes(routes).build();
    assert_cache_control(
        &app,
        &[
            ("/", Some("private, no-store")),
            ("/async", Some("private, no-store")),
            ("/stream", Some("private, no-store")),
            ("/index.md", Some("private, no-store")),
            ("/own", Some("public, max-age=60")),
            ("/page", Some("public, max-age=30")),
            ("/edge", None),
            ("/plain", None),
        ],
    )
    .await;
}

#[tokio::test]
async fn head_hook_cache_policies_survive_the_default() {
    let routes = Router::new()
        .route(
            "/async",
            get(|| async { RouteResponse::ssr_async(HeadPolicyPage) }),
        )
        .route(
            "/stream",
            get(|| async { RouteResponse::ssr_stream(HeadPolicyPage) }),
        );
    let app = FrameworkBuilder::new()
        .with_head(HeadConfig::default())
        .with_dynamic_routes(routes)
        .build();
    assert_cache_control(
        &app,
        &[
            ("/async", Some("public, max-age=86400")),
            ("/stream", Some("public, max-age=86400")),
        ],
    )
    .await;
}

fn page_cached_app(route: Route<()>) -> Router {
    let route = route.with_page_cache(PageCache::new().revalidate(Duration::from_secs(60)));
    let (routes, metadata) = router_from_spec(vec![route]);
    FrameworkBuilder::new()
        .with_dynamic_routes_and_metadata(routes, metadata)
        .build()
}

fn assert_cdn_policy(response: &Response) {
    assert_eq!(
        cache_control(response),
        Some("public, max-age=0, s-maxage=60, stale-while-revalidate=86400")
    );
    assert_eq!(
        response.headers()["cdn-cache-control"],
        "public, max-age=60, stale-while-revalidate=86400"
    );
}

async fn page_cached_stream_renders_in_order_for_the_cdn() {
    let app = page_cached_app(Route::endpoint("/", get(|| async { streamed_page() })));
    let response = app.clone().oneshot(request("/")).await.unwrap();
    assert_cdn_policy(&response);
    let html = body(response).await;
    assert!(html.contains("<p>resolved</p>"), "{html}");
    assert!(!html.contains("loading"), "{html}");
    assert!(!html.contains("proa-tpl-"), "{html}");

    // A request the CDN must not store keeps streaming.
    let mut private = request("/");
    private
        .headers_mut()
        .insert(header::COOKIE, HeaderValue::from_static("session=secret"));
    let response = app.oneshot(private).await.unwrap();
    assert_eq!(cache_control(&response), Some("private, no-store"));
    let html = body(response).await;
    assert!(
        html.contains("loading") && html.contains("proa-tpl-"),
        "{html}"
    );
}

#[tokio::test]
async fn page_cached_stream_renders_in_order_for_the_cdn_on_a_current_thread_runtime() {
    page_cached_stream_renders_in_order_for_the_cdn().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn page_cached_stream_renders_in_order_for_the_cdn_on_a_multi_thread_runtime() {
    page_cached_stream_renders_in_order_for_the_cdn().await;
}

#[tokio::test]
async fn page_cache_policy_replaces_the_page_policy_on_a_deferred_render() {
    let app = page_cached_app(Route::endpoint(
        "/",
        get(|| async { RouteResponse::ssr_async(SelfCachingPage) }),
    ));
    let response = app.oneshot(request("/")).await.unwrap();
    assert_cdn_policy(&response);
    assert_eq!(body(response).await, "<p>page</p>");
}

#[tokio::test]
async fn origin_page_cache_stores_a_streamed_document() {
    let calls = Arc::new(AtomicUsize::new(0));
    let count = calls.clone();
    let routes = Router::new()
        .route(
            "/",
            get(move || {
                count.fetch_add(1, Ordering::SeqCst);
                async { streamed_page() }
            }),
        )
        .route_layer(PageCacheLayer::new("build"));
    let app = FrameworkBuilder::new().with_dynamic_routes(routes).build();
    for expected in ["MISS", "HIT"] {
        let response = app.clone().oneshot(request("/")).await.unwrap();
        assert_eq!(response.headers()["x-proa-page-cache"], expected);
        assert_eq!(cache_control(&response), Some("public, no-cache"));
        let html = body(response).await;
        assert!(
            html.contains("<p>resolved</p>") && !html.contains("loading"),
            "{html}"
        );
    }
    assert_eq!(calls.load(Ordering::SeqCst), 1);
}

/// Resolves after `.0` milliseconds.
struct Sleeps(u64);

impl<L: DataLoader, B: WriteBuf> WebRender<L, B> for Sleeps {
    fn render(
        self,
        cx: &mut WebContext<L, B>,
    ) -> RenderOutcome<impl Future<Output = Result<(), WriteError>>> {
        RenderOutcome::pending(async move {
            tokio::time::sleep(Duration::from_millis(self.0)).await;
            html! { <p>"resolved"</p> }.render(cx).resolve().await
        })
    }
}

/// A shell, then a Suspense boundary that resolves after `ms`.
fn slow_streamed_page(ms: u64) -> RouteResponse {
    RouteResponse::ssr_stream(html! {
        <main>
            {Suspense::new(Sleeps(ms), html_sync! {
                <p>"loading"</p>
            })}
        </main>
    })
}

const STREAMED_PAGE: &str = "<main><p>resolved</p></main>";

fn cache_status(response: &Response) -> &str {
    response.headers()["x-proa-page-cache"].to_str().unwrap()
}

/// A route under an origin `PageCacheLayer`, counting handler calls.
fn origin_cached(
    layer: PageCacheLayer,
    page: fn() -> axum::response::Response,
) -> (Router, Arc<AtomicUsize>) {
    let calls = Arc::new(AtomicUsize::new(0));
    let count = calls.clone();
    let routes = Router::new()
        .route(
            "/",
            get(move || {
                count.fetch_add(1, Ordering::SeqCst);
                async move { page() }
            }),
        )
        .route_layer(layer);
    (
        FrameworkBuilder::new().with_dynamic_routes(routes).build(),
        calls,
    )
}

async fn an_outer_page_cache_stores_framework_documents() {
    let calls = Arc::new(AtomicUsize::new(0));
    let (sync, streamed) = (calls.clone(), calls.clone());
    let routes = Router::new()
        .route(
            "/",
            get(move || {
                sync.fetch_add(1, Ordering::SeqCst);
                async { RouteResponse::ssr(proa_core::text::text("page")) }
            }),
        )
        .route(
            "/stream",
            get(move || {
                streamed.fetch_add(1, Ordering::SeqCst);
                async { streamed_page() }
            }),
        );
    let app = FrameworkBuilder::new()
        .with_dynamic_routes(routes)
        .build()
        .layer(PageCacheLayer::new("build"));
    for (uri, page) in [("/", "page"), ("/stream", STREAMED_PAGE)] {
        for expected in ["MISS", "HIT"] {
            let response = app.clone().oneshot(request(uri)).await.unwrap();
            assert_eq!(response.status(), StatusCode::OK, "{uri}");
            assert_eq!(cache_status(&response), expected, "{uri}");
            assert_eq!(cache_control(&response), Some("public, no-cache"), "{uri}");
            assert_eq!(body(response).await, page, "{uri}");
        }
    }
    assert_eq!(calls.load(Ordering::SeqCst), 2);

    // A request the cache passes still gets the framework default.
    let mut private = request("/");
    private
        .headers_mut()
        .insert(header::COOKIE, HeaderValue::from_static("session=secret"));
    let response = app.oneshot(private).await.unwrap();
    assert_eq!(cache_status(&response), "BYPASS");
    assert_eq!(cache_control(&response), Some("private, no-store"));
}

#[tokio::test]
async fn an_outer_page_cache_stores_framework_documents_on_a_current_thread_runtime() {
    an_outer_page_cache_stores_framework_documents().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn an_outer_page_cache_stores_framework_documents_on_a_multi_thread_runtime() {
    an_outer_page_cache_stores_framework_documents().await;
}

/// How long the cache waits in the tests whose stream outlasts it, and when
/// that stream's boundary resolves. A stream's head is rendered on a worker
/// thread, so on a loaded machine it can take tens of milliseconds to leave:
/// a head that misses the deadline is a `BYPASS`, not the `MISS` these tests
/// expect. The deadline leaves room for that, and the boundary still resolves
/// well after it.
const STREAM_DEADLINE: Duration = Duration::from_millis(500);
const SLOW_BOUNDARY_MS: u64 = 1_000;

async fn streams_outlast_the_page_cache_timeout() {
    // The boundary resolves long after the cache stops waiting for it.
    let layer = PageCacheLayer::new("build").with_timeout(STREAM_DEADLINE);
    let (app, calls) = origin_cached(layer, || {
        slow_streamed_page(SLOW_BOUNDARY_MS).into_response()
    });
    for _ in 0..2 {
        let started = std::time::Instant::now();
        let response = app.clone().oneshot(request("/")).await.unwrap();
        let head = started.elapsed();
        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(cache_status(&response), "MISS");
        assert_eq!(cache_control(&response), Some("public, no-cache"));
        assert!(!response.headers().contains_key(header::ETAG));
        // The head leaves before the boundary resolves.
        assert!(
            head < Duration::from_millis(SLOW_BOUNDARY_MS),
            "head after {head:?}"
        );
        assert_eq!(body(response).await, STREAMED_PAGE);
    }
    // A page that outlasts the timeout is not stored.
    assert_eq!(calls.load(Ordering::SeqCst), 2);
}

#[tokio::test]
async fn streams_outlast_the_page_cache_timeout_on_a_current_thread_runtime() {
    streams_outlast_the_page_cache_timeout().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn streams_outlast_the_page_cache_timeout_on_a_multi_thread_runtime() {
    streams_outlast_the_page_cache_timeout().await;
}

#[tokio::test]
async fn an_outer_page_cache_lets_a_stream_outlast_its_first_chunk_deadline() {
    let routes = Router::new().route(
        "/",
        get(|| async {
            RouteResponse::ssr_stream(html! {
                {Suspense::new(Sleeps(SLOW_BOUNDARY_MS), html_sync! { <p>"loading"</p> })}
            })
        }),
    );
    let app = FrameworkBuilder::new()
        .with_dynamic_routes(routes)
        .build()
        .layer(PageCacheLayer::new("build").with_timeout(STREAM_DEADLINE));

    let started = std::time::Instant::now();
    let response = app.oneshot(request("/")).await.unwrap();
    let head = started.elapsed();
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(cache_status(&response), "MISS");
    assert_eq!(cache_control(&response), Some("public, no-cache"));
    // The head leaves when the render reaches the boundary.
    assert!(
        head < Duration::from_millis(SLOW_BOUNDARY_MS),
        "head after {head:?}"
    );
    assert_eq!(body(response).await, "<p>resolved</p>");
}

async fn cdn_cached_streams_outlast_the_request_timeout() {
    let route = Route::endpoint("/", get(|| async { slow_streamed_page(300) }))
        .with_page_cache(PageCache::new().revalidate(Duration::from_secs(60)));
    let (routes, metadata) = router_from_spec(vec![route]);
    let app = FrameworkBuilder::new()
        .with_request_timeout(Duration::from_millis(100))
        .with_dynamic_routes_and_metadata(routes, metadata)
        .build();
    let response = app.oneshot(request("/")).await.unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    assert_cdn_policy(&response);
    // The CDN stores the complete page; there is no fallback to replace.
    assert_eq!(body(response).await, STREAMED_PAGE);
}

#[tokio::test]
async fn cdn_cached_streams_outlast_the_request_timeout_on_a_current_thread_runtime() {
    cdn_cached_streams_outlast_the_request_timeout().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn cdn_cached_streams_outlast_the_request_timeout_on_a_multi_thread_runtime() {
    cdn_cached_streams_outlast_the_request_timeout().await;
}

/// A managed-head page whose head hook keeps every cache out.
struct PrivateHeadPage;

impl WebRender for PrivateHeadPage {
    const ROLE: ComponentRole = ComponentRole::PAGE;

    async fn render_head(&self, cx: &mut WebContext) -> Result<(), WriteError> {
        assert!(cx.response_mut().insert_header(
            header::CACHE_CONTROL,
            HeaderValue::from_static("private, no-store"),
        ));
        Ok(())
    }

    fn render(
        self,
        cx: &mut WebContext,
    ) -> RenderOutcome<impl Future<Output = Result<(), WriteError>>> {
        html! {
            <html>
                <head>{cx.head()}</head>
                <body>{Suspense::new(Sleeps(5), html_sync! { <p>"loading"</p> })}</body>
            </html>
        }
        .render(cx)
    }
}

#[tokio::test]
async fn cdn_policy_reads_a_streamed_head_hook_before_deciding() {
    let route = Route::endpoint(
        "/",
        get(|| async { RouteResponse::ssr_stream(PrivateHeadPage) }),
    )
    .with_page_cache(PageCache::new());
    let (routes, metadata) = router_from_spec(vec![route]);
    let app = FrameworkBuilder::new()
        .with_head(HeadConfig::default())
        .with_dynamic_routes_and_metadata(routes, metadata)
        .build();
    let response = app.oneshot(request("/")).await.unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    for name in ["cache-control", "cdn-cache-control", "surrogate-control"] {
        assert_eq!(response.headers()[name], "private, no-store", "{name}");
    }
    assert!(body(response).await.contains("<p>resolved</p>"));
}

async fn oversized_streams_are_delivered_and_not_stored() {
    let layer = PageCacheLayer::new("build").with_limits(8, 16);
    let (app, calls) = origin_cached(layer, || slow_streamed_page(5).into_response());
    for _ in 0..2 {
        let response = app.clone().oneshot(request("/")).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        // The size is unknown when the head leaves.
        assert_eq!(cache_status(&response), "MISS");
        assert_eq!(body(response).await, STREAMED_PAGE);
    }
    assert_eq!(calls.load(Ordering::SeqCst), 2);

    // Within the limit, the same page is stored once complete.
    let (app, calls) = origin_cached(PageCacheLayer::new("build"), || {
        slow_streamed_page(5).into_response()
    });
    for expected in ["MISS", "HIT"] {
        let response = app.clone().oneshot(request("/")).await.unwrap();
        assert_eq!(cache_status(&response), expected);
        assert_eq!(body(response).await, STREAMED_PAGE);
    }
    assert_eq!(calls.load(Ordering::SeqCst), 1);
}

#[tokio::test]
async fn oversized_streams_are_delivered_and_not_stored_on_a_current_thread_runtime() {
    oversized_streams_are_delivered_and_not_stored().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn oversized_streams_are_delivered_and_not_stored_on_a_multi_thread_runtime() {
    oversized_streams_are_delivered_and_not_stored().await;
}

/// Five concurrent requests: the slowest response head, and the time until
/// every body has arrived.
async fn five_at_once(app: &Router, status: &'static str) -> (Duration, Duration) {
    let started = std::time::Instant::now();
    let requests = (0..5).map(|_| {
        let app = app.clone();
        tokio::spawn(async move {
            let response = app.oneshot(request("/")).await.unwrap();
            let head = started.elapsed();
            assert_eq!(response.status(), StatusCode::OK);
            assert_eq!(cache_status(&response), status);
            assert_eq!(body(response).await, STREAMED_PAGE);
            head
        })
    });
    let heads = futures::future::join_all(requests).await;
    let slowest_head = heads.into_iter().map(Result::unwrap).max().unwrap();
    (slowest_head, started.elapsed())
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn uncacheable_streams_do_not_wait_for_each_other() {
    // Serialized behind the miss lock, five 200 ms renders take 1 s.
    let layer = PageCacheLayer::new("build").with_limits(8, 16);
    let (app, _) = origin_cached(layer, || slow_streamed_page(200).into_response());
    let (head, all) = five_at_once(&app, "MISS").await;
    assert!(
        head < Duration::from_millis(150),
        "oversized head: {head:?}"
    );
    assert!(all < Duration::from_millis(600), "oversized: {all:?}");

    // A head the cache cannot store bypasses at once and streams.
    let (app, _) = origin_cached(PageCacheLayer::new("build"), || {
        ([(header::SET_COOKIE, "visit=1")], slow_streamed_page(200)).into_response()
    });
    let (head, all) = five_at_once(&app, "BYPASS").await;
    assert!(
        head < Duration::from_millis(150),
        "Set-Cookie head: {head:?}"
    );
    assert!(all < Duration::from_millis(600), "Set-Cookie: {all:?}");
}

/// A page whose first output is a Suspense boundary resolving after `ms`.
fn boundary_first_page(ms: u64) -> RouteResponse {
    RouteResponse::ssr_stream(html! {
        {Suspense::new(Sleeps(ms), html_sync! { <p>"loading"</p> })}
    })
}

async fn origin_cached_streams_outlast_the_request_timeout() {
    // The origin cache records a stream as it is sent, so the response head
    // leaves before the request timeout and the complete page is stored.
    for page in [
        || slow_streamed_page(300).into_response(),
        || boundary_first_page(300).into_response(),
    ] {
        let calls = Arc::new(AtomicUsize::new(0));
        let count = calls.clone();
        let routes = Router::new()
            .route(
                "/",
                get(move || {
                    count.fetch_add(1, Ordering::SeqCst);
                    async move { page() }
                }),
            )
            .route_layer(PageCacheLayer::new("build"));
        let app = FrameworkBuilder::new()
            .with_request_timeout(Duration::from_millis(100))
            .with_dynamic_routes(routes)
            .build();
        let response = app.clone().oneshot(request("/")).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(cache_status(&response), "MISS");
        assert_eq!(cache_control(&response), Some("public, no-cache"));
        let html = body(response).await;
        assert!(
            html.contains("<p>resolved</p>") && !html.contains("loading"),
            "{html}"
        );

        let response = app.oneshot(request("/")).await.unwrap();
        assert_eq!(cache_status(&response), "HIT");
        assert_eq!(body(response).await, html);
        assert_eq!(calls.load(Ordering::SeqCst), 1);
    }
}

#[tokio::test]
async fn origin_cached_streams_outlast_the_request_timeout_on_a_current_thread_runtime() {
    origin_cached_streams_outlast_the_request_timeout().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn origin_cached_streams_outlast_the_request_timeout_on_a_multi_thread_runtime() {
    origin_cached_streams_outlast_the_request_timeout().await;
}

async fn cdn_cached_streams_that_open_with_a_boundary_outlast_the_request_timeout() {
    let route = Route::endpoint("/", get(|| async { boundary_first_page(300) }))
        .with_page_cache(PageCache::new().revalidate(Duration::from_secs(60)));
    let (routes, metadata) = router_from_spec(vec![route]);
    let app = FrameworkBuilder::new()
        .with_request_timeout(Duration::from_millis(100))
        .with_dynamic_routes_and_metadata(routes, metadata)
        .build();
    let response = app.oneshot(request("/")).await.unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    assert_cdn_policy(&response);
    assert_eq!(body(response).await, "<p>resolved</p>");
}

#[tokio::test]
async fn cdn_cached_streams_that_open_with_a_boundary_outlast_the_request_timeout_on_a_current_thread_runtime(
) {
    cdn_cached_streams_that_open_with_a_boundary_outlast_the_request_timeout().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn cdn_cached_streams_that_open_with_a_boundary_outlast_the_request_timeout_on_a_multi_thread_runtime(
) {
    cdn_cached_streams_that_open_with_a_boundary_outlast_the_request_timeout().await;
}

#[tokio::test]
async fn a_stream_the_client_abandons_is_not_stored() {
    use http_body_util::BodyExt as _;

    let (app, calls) = origin_cached(PageCacheLayer::new("build"), || {
        slow_streamed_page(50).into_response()
    });
    let response = app.clone().oneshot(request("/")).await.unwrap();
    assert_eq!(cache_status(&response), "MISS");
    let mut abandoned = response.into_body();
    let shell = abandoned
        .frame()
        .await
        .unwrap()
        .unwrap()
        .into_data()
        .unwrap();
    assert_eq!(&shell[..], b"<main>");
    drop(abandoned);

    for expected in ["MISS", "HIT"] {
        let response = app.clone().oneshot(request("/")).await.unwrap();
        assert_eq!(cache_status(&response), expected);
        assert_eq!(body(response).await, STREAMED_PAGE);
    }
    assert_eq!(calls.load(Ordering::SeqCst), 2);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn isr_stores_a_streamed_refresh() {
    let calls = Arc::new(AtomicUsize::new(0));
    let count = calls.clone();
    let routes = Router::new()
        .route(
            "/",
            get(move || {
                let generation = count.fetch_add(1, Ordering::SeqCst);
                async move {
                    RouteResponse::ssr_stream(html! {
                        <main>
                            {generation}
                            {Suspense::new(Sleeps(5), html_sync! { <p>"loading"</p> })}
                        </main>
                    })
                }
            }),
        )
        .route_layer(PageCacheLayer::new("build").revalidate(Duration::from_millis(200)));
    let app = FrameworkBuilder::new().with_dynamic_routes(routes).build();
    let page = |generation: usize| format!("<main>{generation}<p>resolved</p></main>");

    let first = app.clone().oneshot(request("/")).await.unwrap();
    assert_eq!(cache_status(&first), "MISS");
    assert_eq!(body(first).await, page(0));
    tokio::time::sleep(Duration::from_millis(250)).await;
    let stale = app.clone().oneshot(request("/")).await.unwrap();
    assert_eq!(cache_status(&stale), "STALE");
    assert_eq!(body(stale).await, page(0));

    // The refresh reads its stream to the end, which stores it.
    let deadline = std::time::Instant::now() + Duration::from_secs(2);
    loop {
        let response = app.clone().oneshot(request("/")).await.unwrap();
        let status = cache_status(&response).to_owned();
        let html = body(response).await;
        if status == "HIT" {
            assert_eq!(html, page(1));
            break;
        }
        assert_eq!(status, "STALE");
        assert!(
            std::time::Instant::now() < deadline,
            "the refresh was never stored"
        );
        tokio::time::sleep(Duration::from_millis(5)).await;
    }
    assert_eq!(calls.load(Ordering::SeqCst), 2);
}

/// Fails after an await, before the render reaches any Suspense boundary.
struct FailsBeforeBoundary;

impl<L: DataLoader, B: WriteBuf> WebRender<L, B> for FailsBeforeBoundary {
    fn render(
        self,
        _cx: &mut WebContext<L, B>,
    ) -> RenderOutcome<impl Future<Output = Result<(), WriteError>>> {
        RenderOutcome::pending(async move {
            tokio::task::yield_now().await;
            Err(WriteError::OutOfCapacity)
        })
    }
}

async fn page_cached_streams_that_fail_before_a_boundary_are_errors() {
    // The head commits when the render reaches a boundary, so a failure
    // before it still fails the response before its head.
    fn failing_page() -> RouteResponse {
        RouteResponse::ssr_stream(html! {
            {FailsBeforeBoundary}
            {Suspense::new(Sleeps(5), html_sync! { <p>"loading"</p> })}
        })
    }
    let cdn = page_cached_app(Route::endpoint("/", get(|| async { failing_page() })));
    let (origin, _) = origin_cached(PageCacheLayer::new("build"), || {
        failing_page().into_response()
    });
    for app in [cdn, origin] {
        let response = app.oneshot(request("/")).await.unwrap();
        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }
}

#[tokio::test]
async fn page_cached_streams_that_fail_before_a_boundary_are_errors_on_a_current_thread_runtime() {
    page_cached_streams_that_fail_before_a_boundary_are_errors().await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn page_cached_streams_that_fail_before_a_boundary_are_errors_on_a_multi_thread_runtime() {
    page_cached_streams_that_fail_before_a_boundary_are_errors().await;
}