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
// Copyright Proa Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

//! Integration tests for buffered async `RouteResponse` rendering.
//!
//! Drives async `WebRender` and `WebRenderSend` components end-to-end: build
//! an axum router, install `RouteContextLayer`, fire a `oneshot` request, and
//! assert the rendered body contains the bytes the component produced
//! (including content written *after* a real `.await`).
//!
//! Handlers either await the response (`RouteResponse::ssr_async(page).await`)
//! or return it for `IntoResponse`. Most tests use the default
//! `#[tokio::test]` current-thread runtime, which is what application tests
//! reach for first: there an un-awaited buffered render must never block
//! inside the handler's `into_response`.

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

use axum::{
    body::{to_bytes, Body},
    http::{header, HeaderName, HeaderValue, Request, StatusCode},
    response::Response,
    routing::get,
    Router,
};
use proa_core::render::RenderOutcome;
use proa_core::{
    await_component, render_to_string_async, to_async, DataLoader, LoadError, LoadKey, LoadRequest,
    LoadValue, RenderBuffer, SendWebContext, WebContext, WebRender, WebRenderSend, WriteBuf,
    WriteError,
};
use proa_framework_axum::{
    router_from_spec, PageCache, PageCacheLayer, Route, RouteContextLayer, RouteResponse,
};
use proa_macros::{html, html_sync};
use tower::ServiceExt;

/// An async component that writes an opening tag, yields to the runtime,
/// then writes a closing tag. The yield is load-bearing: if the framework
/// doesn't actually drive the future past the first `.await`, the closing
/// tag is never emitted and the test fails.
struct AsyncGreeting {
    name: &'static str,
}

impl<L: ::proa_core::DataLoader> WebRender<L, RenderBuffer> for AsyncGreeting {
    fn render(
        self,
        cx: &mut WebContext<L, RenderBuffer>,
    ) -> RenderOutcome<impl Future<Output = Result<(), WriteError>>> {
        RenderOutcome::Pending(async move {
            // Disambiguate: Vec<u8> has both std's Extend (infallible) and
            // our WriteBuf::extend (fallible). Call the trait form explicitly.
            WriteBuf::extend_str(&mut cx.out, "<p>hello ")?;
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
            WriteBuf::extend_str(&mut cx.out, self.name)?;
            WriteBuf::extend_str(&mut cx.out, "</p>")?;
            Ok(())
        })
    }
}

struct AsyncHtmlLeaf {
    label: &'static str,
}

struct SyncHtmlLeaf {
    label: &'static str,
}

struct LocationEcho;
struct RouteParamEcho;
struct RequestEcho;
struct ResponseContextEcho;

struct LoadedHtmlLeaf {
    label: &'static str,
    load_key: &'static str,
}

#[derive(Default)]
struct CountingLoader {
    calls: Arc<AtomicUsize>,
}

impl<L: ::proa_core::DataLoader, B: WriteBuf> proa_core::WebRenderSync<L, B> for SyncHtmlLeaf {
    fn render(self, cx: &mut WebContext<L, B>) -> Result<(), WriteError> {
        proa_core::WebRenderSync::render(
            html_sync! {
                <span class="leaf">{self.label}</span>
            },
            cx,
        )
    }
}

impl<L: ::proa_core::DataLoader, B: WriteBuf> proa_core::WebRenderSync<L, B> for LocationEcho {
    fn render(self, cx: &mut WebContext<L, B>) -> Result<(), WriteError> {
        let location = cx
            .request_location()
            .expect("framework should install request location")
            .clone();
        let query = location.query().unwrap_or("");
        proa_core::WebRenderSync::render(
            html_sync! {
                <section data-path={location.path()} data-query={query}>{location.path()}</section>
            },
            cx,
        )
    }
}

impl<L: ::proa_core::DataLoader, B: WriteBuf> proa_core::WebRenderSync<L, B> for RouteParamEcho {
    fn render(self, cx: &mut WebContext<L, B>) -> Result<(), WriteError> {
        let id = cx.param("id").unwrap_or("").to_owned();
        proa_core::WebRenderSync::render(
            html_sync! {
                <section data-id={id.as_str()}>{id.as_str()}</section>
            },
            cx,
        )
    }
}

impl<L: ::proa_core::DataLoader, B: WriteBuf> proa_core::WebRenderSync<L, B> for RequestEcho {
    fn render(self, cx: &mut WebContext<L, B>) -> Result<(), WriteError> {
        let method = cx
            .request()
            .method()
            .map(http::Method::as_str)
            .unwrap_or("")
            .to_owned();
        let user_agent = cx.request().user_agent().unwrap_or("").to_owned();
        let theme = cx.request().cookie("theme").unwrap_or("").to_owned();
        proa_core::WebRenderSync::render(
            html_sync! {
                <section
                    data-method={method.as_str()}
                    data-agent={user_agent.as_str()}
                    data-theme={theme.as_str()}
                >
                    "request"
                </section>
            },
            cx,
        )
    }
}

impl<L: ::proa_core::DataLoader, B: WriteBuf> proa_core::WebRenderSync<L, B>
    for ResponseContextEcho
{
    fn render(self, cx: &mut WebContext<L, B>) -> Result<(), WriteError> {
        cx.response_mut().set_status(StatusCode::CREATED);
        cx.response_mut().insert_header(
            http::HeaderName::from_static("x-render-context"),
            http::HeaderValue::from_static("set"),
        );
        proa_core::WebRenderSync::render(
            html_sync! {
                <p>"response"</p>
            },
            cx,
        )
    }
}

impl DataLoader for CountingLoader {
    fn load(
        &self,
        _request: &LoadRequest,
    ) -> impl Future<Output = Result<LoadValue, LoadError>> + Send {
        let calls = Arc::clone(&self.calls);
        async move {
            calls.fetch_add(1, Ordering::SeqCst);
            tokio::time::sleep(std::time::Duration::from_millis(10)).await;
            Ok(LoadValue::bytes(bytes::Bytes::from_static(b"null")))
        }
    }
}

impl<L: ::proa_core::DataLoader> WebRender<L, RenderBuffer> for AsyncHtmlLeaf {
    fn render(
        self,
        cx: &mut WebContext<L, RenderBuffer>,
    ) -> RenderOutcome<impl Future<Output = Result<(), WriteError>>> {
        await_component(async move {
            tokio::task::yield_now().await;
            to_async(SyncHtmlLeaf { label: self.label })
        })
        .render(cx)
    }
}

impl<L: ::proa_core::DataLoader> WebRender<L, RenderBuffer> for LoadedHtmlLeaf {
    fn render(
        self,
        cx: &mut WebContext<L, RenderBuffer>,
    ) -> RenderOutcome<impl Future<Output = Result<(), WriteError>>> {
        let label = self.label;
        let load_key = self.load_key;
        RenderOutcome::pending(async move {
            let (): () = cx.load_json(LoadKey::named("panel", load_key)).await?;
            proa_core::render_child(cx, to_async(SyncHtmlLeaf { label })).await
        })
    }
}

#[tokio::test]
async fn ssr_async_renders_async_component() {
    let routes = vec![Route::endpoint(
        "/hello",
        get(|| async { RouteResponse::ssr_async(AsyncGreeting { name: "world" }) }),
    )];

    let (router, computed_metadata) = router_from_spec(routes);
    let app = router.layer(RouteContextLayer::new(computed_metadata));

    let response = app
        .oneshot(
            Request::builder()
                .uri("/hello")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);
    let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
    // Both pre-await and post-await bytes must be present; missing either
    // indicates the future was not driven to completion.
    assert_eq!(body.as_ref(), b"<p>hello world</p>");
}

#[tokio::test]
async fn ssr_async_sets_default_security_headers() {
    let routes = vec![Route::endpoint(
        "/hello",
        get(|| async { RouteResponse::ssr_async(AsyncGreeting { name: "security" }) }),
    )];

    let (router, computed_metadata) = router_from_spec(routes);
    let app = router.layer(RouteContextLayer::new(computed_metadata));

    let response = app
        .oneshot(
            Request::builder()
                .uri("/hello")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(
        response
            .headers()
            .get("x-content-type-options")
            .and_then(|h| h.to_str().ok()),
        Some("nosniff"),
        "buffered async SSR should emit the same default security headers as sync SSR"
    );
}

#[tokio::test]
async fn route_render_installs_request_location_on_context() {
    let routes = vec![Route::endpoint(
        "/dashboard",
        get(|| async { RouteResponse::ssr(LocationEcho) }),
    )];

    let (router, computed_metadata) = router_from_spec(routes);
    let app = router.layer(RouteContextLayer::new(computed_metadata));

    let response = app
        .oneshot(
            Request::builder()
                .uri("/dashboard?tab=analytics")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);
    let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
    assert_eq!(
        String::from_utf8(body.to_vec()).unwrap(),
        "<section data-path=\"/dashboard\" data-query=\"tab=analytics\">/dashboard</section>"
    );
}

#[tokio::test]
async fn route_render_installs_route_params_on_context() {
    let routes = vec![Route::endpoint(
        "/products/{id}",
        get(|| async { RouteResponse::ssr(RouteParamEcho) }),
    )];

    let (router, computed_metadata) = router_from_spec(routes);
    let app = router.layer(RouteContextLayer::new(computed_metadata));

    let response = app
        .oneshot(
            Request::builder()
                .uri("/products/42")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);
    let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
    assert_eq!(
        String::from_utf8(body.to_vec()).unwrap(),
        "<section data-id=\"42\">42</section>"
    );
}

#[tokio::test]
async fn route_render_installs_request_headers_on_context() {
    let routes = vec![Route::endpoint(
        "/request",
        get(|| async { RouteResponse::ssr(RequestEcho) }),
    )];

    let (router, computed_metadata) = router_from_spec(routes);
    let app = router.layer(RouteContextLayer::new(computed_metadata));

    let response = app
        .oneshot(
            Request::builder()
                .uri("/request")
                .header(http::header::USER_AGENT, "proa-test")
                .header(http::header::COOKIE, "theme=dark; session=abc123")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);
    let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
    assert_eq!(
        String::from_utf8(body.to_vec()).unwrap(),
        "<section data-method=\"GET\" data-agent=\"proa-test\" data-theme=\"dark\">request</section>"
    );
}

#[tokio::test]
async fn route_render_applies_staged_response_context() {
    let routes = vec![Route::endpoint(
        "/response",
        get(|| async { RouteResponse::ssr(ResponseContextEcho) }),
    )];

    let (router, computed_metadata) = router_from_spec(routes);
    let app = router.layer(RouteContextLayer::new(computed_metadata));

    let response = app
        .oneshot(
            Request::builder()
                .uri("/response")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::CREATED);
    assert_eq!(
        response
            .headers()
            .get("x-render-context")
            .and_then(|value| value.to_str().ok()),
        Some("set")
    );
    let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
    assert_eq!(String::from_utf8(body.to_vec()).unwrap(), "<p>response</p>");
}

#[tokio::test]
async fn html_macro_supports_async_children_and_borrowed_locals() {
    let suffix = String::from("tail");
    let page = html! {
        <section>
            <h1>"async html"</h1>
            {to_async(SyncGreeting { name: "world" })}
            {AsyncHtmlLeaf { label: "child" }}
            {if true {
                html! { <em>{suffix.as_str()}</em> }
            }}
        </section>
    };

    let html = render_to_string_async(page).await;
    assert_eq!(
        html,
        "<section><h1>async html</h1><p>sync world</p><span class=\"leaf\">child</span><em>tail</em></section>"
    );
}

/// A sync component routed through `ssr_async` via the explicit adapter.
/// Exercises the `RenderOutcome::Done` fast path with no real future polling.
struct SyncGreeting {
    name: &'static str,
}

impl<L: ::proa_core::DataLoader, B: WriteBuf> proa_core::WebRenderSync<L, B> for SyncGreeting {
    fn render(self, cx: &mut WebContext<L, B>) -> Result<(), WriteError> {
        cx.out.extend_str("<p>sync ")?;
        cx.out.extend_str(self.name)?;
        cx.out.extend_str("</p>")?;
        Ok(())
    }
}

#[tokio::test]
async fn ssr_async_accepts_sync_component_via_adapter() {
    let routes = vec![Route::endpoint(
        "/sync",
        get(|| async { RouteResponse::ssr_async(to_async(SyncGreeting { name: "adapter" })) }),
    )];

    let (router, computed_metadata) = router_from_spec(routes);
    let app = router.layer(RouteContextLayer::new(computed_metadata));

    let response = app
        .oneshot(Request::builder().uri("/sync").body(Body::empty()).unwrap())
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);
    let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
    assert_eq!(body.as_ref(), b"<p>sync adapter</p>");
}

#[tokio::test]
async fn ssr_async_dedupes_duplicate_loader_keys_within_request() {
    let loader = Arc::new(CountingLoader::default());
    let routes = vec![Route::endpoint(
        "/dedupe",
        get({
            let loader = Arc::clone(&loader);
            move || {
                let loader = Arc::clone(&loader);
                async move {
                    // Wrap the typed loader in a typed `DataResolver<L>` so
                    // dedupe still works without going through the dyn
                    // `DynLoaderHandle` path. `cx.load_json(...)` calls inside the
                    // page monomorphize on `DataResolver<CountingLoader>`,
                    // not on `DynLoaderHandle`.
                    let typed_loader =
                        std::sync::Arc::new(proa_stream::DataResolver::new_typed(loader));
                    RouteResponse::ssr_async_with_loader(
                        html! {
                            <main>
                                {LoadedHtmlLeaf {
                                    label: "first",
                                    load_key: "shared",
                                }}
                                {LoadedHtmlLeaf {
                                    label: "second",
                                    load_key: "shared",
                                }}
                            </main>
                        },
                        typed_loader,
                    )
                }
            }
        }),
    )];

    let (router, computed_metadata) = router_from_spec(routes);
    let app = router.layer(RouteContextLayer::new(computed_metadata));

    let response = app
        .oneshot(
            Request::builder()
                .uri("/dedupe")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();

    assert_eq!(response.status(), StatusCode::OK);
    let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
    assert_eq!(
        body.as_ref(),
        b"<main><span class=\"leaf\">first</span><span class=\"leaf\">second</span></main>"
    );
    assert_eq!(loader.calls.load(Ordering::SeqCst), 1);
}

/// Writes around a real yield in both the local and the `Send` render graph.
struct Yielding(&'static str);

impl WebRender for Yielding {
    fn render(
        self,
        cx: &mut WebContext,
    ) -> RenderOutcome<impl Future<Output = Result<(), WriteError>>> {
        RenderOutcome::pending(async move {
            WriteBuf::extend_str(&mut cx.out, "<p>")?;
            tokio::task::yield_now().await;
            WriteBuf::extend_str(&mut cx.out, self.0)?;
            WriteBuf::extend_str(&mut cx.out, "</p>")
        })
    }
}

impl WebRenderSend for Yielding {
    fn render_send(
        self,
        cx: &mut SendWebContext,
    ) -> RenderOutcome<impl Future<Output = Result<(), WriteError>> + Send> {
        RenderOutcome::pending(async move {
            cx.output_mut().extend_str("<p>")?;
            tokio::task::yield_now().await;
            cx.output_mut().extend_str(self.0)?;
            cx.output_mut().extend_str("</p>")
        })
    }
}

/// Stages status and headers only after an await.
struct Staged;

impl Staged {
    fn stage(response: &mut proa_core::ResponseContext) {
        response.set_status(StatusCode::CREATED);
        response.insert_header(
            HeaderName::from_static("x-render"),
            HeaderValue::from_static("async"),
        );
        response.append_header(header::VARY, HeaderValue::from_static("Origin"));
    }
}

impl WebRender for Staged {
    fn render(
        self,
        cx: &mut WebContext,
    ) -> RenderOutcome<impl Future<Output = Result<(), WriteError>>> {
        RenderOutcome::pending(async move {
            tokio::task::yield_now().await;
            Self::stage(cx.response_mut());
            WriteBuf::extend_str(&mut cx.out, "<p>staged</p>")
        })
    }
}

impl WebRenderSend for Staged {
    fn render_send(
        self,
        cx: &mut SendWebContext,
    ) -> RenderOutcome<impl Future<Output = Result<(), WriteError>> + Send> {
        RenderOutcome::pending(async move {
            tokio::task::yield_now().await;
            Self::stage(cx.response_mut());
            cx.output_mut().extend_str("<p>staged</p>")
        })
    }
}

/// Fails after an await, once response finalization has started.
struct Fails;

impl WebRender for Fails {
    fn render(
        self,
        _: &mut WebContext,
    ) -> RenderOutcome<impl Future<Output = Result<(), WriteError>>> {
        RenderOutcome::pending(async {
            tokio::task::yield_now().await;
            Err(WriteError::render("private diagnostic"))
        })
    }
}

impl WebRenderSend for Fails {
    fn render_send(
        self,
        _: &mut SendWebContext,
    ) -> RenderOutcome<impl Future<Output = Result<(), WriteError>> + Send> {
        RenderOutcome::pending(async {
            tokio::task::yield_now().await;
            Err(WriteError::render("private diagnostic"))
        })
    }
}

/// Reads the route's metadata after an await, as `render_metadata_head` does.
struct MetadataTitle;

impl WebRender for MetadataTitle {
    fn render(
        self,
        cx: &mut WebContext,
    ) -> RenderOutcome<impl Future<Output = Result<(), WriteError>>> {
        RenderOutcome::pending(async move {
            tokio::task::yield_now().await;
            let title = proa_framework_axum::resolved_metadata()
                .and_then(|metadata| metadata.title)
                .unwrap_or_default();
            WriteBuf::extend_str(&mut cx.out, &title)
        })
    }
}

fn app(routes: Vec<Route<()>>) -> Router {
    let (router, computed_metadata) = router_from_spec(routes);
    router.layer(RouteContextLayer::new(computed_metadata))
}

async fn fetch(app: &Router, uri: &str) -> Response {
    let request = Request::builder().uri(uri).body(Body::empty()).unwrap();
    tokio::time::timeout(Duration::from_secs(5), app.clone().oneshot(request))
        .await
        .expect("buffered async finalization must not hang")
        .unwrap()
}

async fn text(response: Response) -> String {
    String::from_utf8(
        to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap()
            .to_vec(),
    )
    .unwrap()
}

/// Both buffered constructors, with and without a `Send` render graph.
fn local_and_send<P>(page: fn() -> P) -> Vec<Route<()>>
where
    P: WebRender + WebRenderSend + Send + 'static,
{
    vec![
        Route::endpoint(
            "/local",
            get(move || async move { RouteResponse::ssr_async(page()) }),
        ),
        Route::endpoint(
            "/send",
            get(move || async move { RouteResponse::ssr_async_send(page()) }),
        ),
    ]
}

#[tokio::test]
async fn buffered_async_preserves_page_status_and_headers() {
    let app = app(local_and_send(|| Staged));
    for uri in ["/local", "/send"] {
        let response = fetch(&app, uri).await;
        assert_eq!(response.status(), StatusCode::CREATED, "{uri}");
        assert_eq!(response.headers()["x-render"], "async", "{uri}");
        assert_eq!(response.headers()[header::VARY], "Origin", "{uri}");
        assert_eq!(
            response.headers()["x-content-type-options"],
            "nosniff",
            "{uri}"
        );
        assert_eq!(
            response.headers()[header::CONTENT_TYPE],
            "text/html; charset=utf-8",
            "{uri}"
        );
        assert_eq!(text(response).await, "<p>staged</p>", "{uri}");
    }
}

#[tokio::test]
async fn buffered_async_render_errors_become_http_500() {
    let app = app(local_and_send(|| Fails));
    for uri in ["/local", "/send"] {
        let response = fetch(&app, uri).await;
        assert_eq!(
            response.status(),
            StatusCode::INTERNAL_SERVER_ERROR,
            "{uri}"
        );
        assert_eq!(text(response).await, "render error", "{uri}");
    }
}

#[tokio::test]
async fn buffered_async_client_payload_is_json() {
    let app = app(local_and_send(|| Staged));
    for uri in ["/local", "/send"] {
        let request = Request::builder()
            .uri(uri)
            .header("X-Proa-Client", "1")
            .body(Body::empty())
            .unwrap();
        let response = app.clone().oneshot(request).await.unwrap();
        assert_eq!(response.status(), StatusCode::CREATED, "{uri}");
        assert_eq!(
            response.headers()[header::CONTENT_TYPE],
            "application/json; charset=utf-8",
            "{uri}"
        );
        let payload: serde_json::Value = serde_json::from_str(&text(response).await).unwrap();
        assert_eq!(payload["html"], "<p>staged</p>", "{uri}");
    }
}

#[tokio::test]
async fn handler_wrappers_apply_over_the_rendered_page() {
    let app = app(vec![Route::endpoint(
        "/missing",
        get(|| async {
            (
                StatusCode::NOT_FOUND,
                [(header::CACHE_CONTROL, "no-store")],
                RouteResponse::ssr_async(Staged),
            )
        }),
    )]);
    let response = fetch(&app, "/missing").await;
    assert_eq!(response.status(), StatusCode::NOT_FOUND);
    assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store");
    assert_eq!(response.headers()["x-render"], "async");
    assert_eq!(text(response).await, "<p>staged</p>");
}

#[tokio::test]
async fn buffered_async_render_reads_its_route_context() {
    let app = app(vec![Route::page(
        "/about",
        "About us",
        get(|| async { RouteResponse::ssr_async(MetadataTitle) }),
    )]);
    let response = fetch(&app, "/about").await;
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(text(response).await, "About us");
}

#[tokio::test]
async fn origin_page_cache_stores_buffered_async_pages() {
    let calls = Arc::new(AtomicUsize::new(0));
    let route = |path: &'static str, send: bool| {
        let calls = Arc::clone(&calls);
        Route::endpoint(
            path,
            get(move || {
                calls.fetch_add(1, Ordering::SeqCst);
                async move {
                    if send {
                        RouteResponse::ssr_async_send(Yielding("cached"))
                    } else {
                        RouteResponse::ssr_async(Yielding("cached"))
                    }
                }
            }),
        )
        .with_page_cache(PageCacheLayer::new("build"))
    };
    let app = app(vec![route("/local", false), route("/send", true)]);
    for uri in ["/local", "/send"] {
        for expected in ["MISS", "HIT"] {
            let response = fetch(&app, uri).await;
            assert_eq!(response.status(), StatusCode::OK, "{uri}");
            assert_eq!(response.headers()["x-proa-page-cache"], expected, "{uri}");
            assert_eq!(text(response).await, "<p>cached</p>", "{uri}");
        }
    }
    assert_eq!(calls.load(Ordering::SeqCst), 2);
}

#[tokio::test]
async fn cdn_page_cache_sees_the_rendered_html() {
    let app = app(local_and_send(|| Yielding("edge"))
        .into_iter()
        .map(|route| route.with_page_cache(PageCache::new()))
        .collect());
    for uri in ["/local", "/send"] {
        let response = fetch(&app, uri).await;
        assert_eq!(response.status(), StatusCode::OK, "{uri}");
        let policy = response.headers()[header::CACHE_CONTROL].to_str().unwrap();
        assert!(policy.contains("public"), "{uri}: {policy}");
        assert_eq!(text(response).await, "<p>edge</p>", "{uri}");
    }
}

#[tokio::test]
async fn buffered_async_outside_route_context_is_a_clear_error() {
    let router = Router::new()
        .route(
            "/local",
            get(|| async { RouteResponse::ssr_async(Yielding("unreachable")) }),
        )
        .route(
            "/send",
            get(|| async { RouteResponse::ssr_async_send(Yielding("unreachable")) }),
        );
    for uri in ["/local", "/send"] {
        let response = fetch(&router, uri).await;
        assert_eq!(
            response.status(),
            StatusCode::INTERNAL_SERVER_ERROR,
            "{uri}"
        );
        assert_eq!(text(response).await, "invalid route context", "{uri}");
    }
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn buffered_async_renders_on_a_multi_thread_runtime() {
    let app = app(local_and_send(|| Yielding("threads")));
    for uri in ["/local", "/send"] {
        let response = fetch(&app, uri).await;
        assert_eq!(response.status(), StatusCode::OK, "{uri}");
        assert_eq!(text(response).await, "<p>threads</p>", "{uri}");
    }
}

/// Writes the name of the thread that polls the render.
struct ThreadName;

fn thread_name() -> String {
    std::thread::current().name().unwrap_or("").to_owned()
}

impl WebRender for ThreadName {
    fn render(
        self,
        cx: &mut WebContext,
    ) -> RenderOutcome<impl Future<Output = Result<(), WriteError>>> {
        RenderOutcome::pending(async move {
            tokio::task::yield_now().await;
            WriteBuf::extend_str(&mut cx.out, &thread_name())
        })
    }
}

impl WebRenderSend for ThreadName {
    fn render_send(
        self,
        cx: &mut SendWebContext,
    ) -> RenderOutcome<impl Future<Output = Result<(), WriteError>> + Send> {
        RenderOutcome::pending(async move {
            tokio::task::yield_now().await;
            cx.output_mut().extend_str(&thread_name())
        })
    }
}

#[tokio::test]
async fn send_renders_are_polled_directly_and_local_renders_stay_pinned() {
    let app = app(local_and_send(|| ThreadName));
    let local = text(fetch(&app, "/local").await).await;
    assert!(local.starts_with("proa-stream-"), "{local}");
    let send = text(fetch(&app, "/send").await).await;
    assert_eq!(send, thread_name());
}

/// Holds the render open so a burst is in flight at once.
struct Held;

impl WebRender for Held {
    fn render(
        self,
        cx: &mut WebContext,
    ) -> RenderOutcome<impl Future<Output = Result<(), WriteError>>> {
        RenderOutcome::pending(async move {
            tokio::time::sleep(Duration::from_millis(100)).await;
            WriteBuf::extend_str(&mut cx.out, "<p>held</p>")
        })
    }
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn buffered_async_bursts_queue_instead_of_failing() {
    // More concurrent pages than the default stream admission limit.
    let app = app(vec![Route::endpoint(
        "/held",
        get(|| async { RouteResponse::ssr_async(Held).await }),
    )]);
    let responses = futures::future::join_all((0..1_500).map(|_| fetch(&app, "/held"))).await;
    for response in responses {
        assert_eq!(response.status(), StatusCode::OK);
    }
}

#[tokio::test]
async fn an_explicit_200_wrapper_wins_like_any_other_status() {
    let app = app(vec![
        Route::endpoint(
            "/local",
            get(|| async { (StatusCode::OK, RouteResponse::ssr_async(Staged)) }),
        ),
        Route::endpoint(
            "/send",
            get(|| async { (StatusCode::OK, RouteResponse::ssr_async_send(Staged)) }),
        ),
        Route::endpoint(
            "/failed",
            get(|| async { (StatusCode::OK, RouteResponse::ssr_async(Fails)) }),
        ),
    ]);
    for uri in ["/local", "/send"] {
        let response = fetch(&app, uri).await;
        assert_eq!(response.status(), StatusCode::OK, "{uri}");
        assert_eq!(response.headers()["x-render"], "async", "{uri}");
        assert_eq!(text(response).await, "<p>staged</p>", "{uri}");
    }
    // As when the render ran inside `into_response`, the wrapper's status
    // also replaces the render error's 500.
    let response = fetch(&app, "/failed").await;
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(text(response).await, "render error");
}

#[tokio::test]
async fn middleware_outside_route_context_sees_only_final_statuses() {
    let seen = Arc::new(std::sync::Mutex::new(Vec::new()));
    let record = Arc::clone(&seen);
    let mut routes = local_and_send(|| Staged);
    routes.push(Route::endpoint(
        "/plain",
        get(|| async { RouteResponse::ssr_async(Yielding("plain")) }),
    ));
    let app = app(routes).layer(tower::util::MapResponseLayer::new(
        move |response: Response| {
            record.lock().unwrap().push(response.status());
            response
        },
    ));
    for uri in ["/local", "/send", "/plain"] {
        let response = fetch(&app, uri).await;
        assert_ne!(response.status().as_u16(), 299, "{uri}");
        assert!(!text(response).await.is_empty(), "{uri}");
    }
    assert_eq!(
        *seen.lock().unwrap(),
        [StatusCode::CREATED, StatusCode::CREATED, StatusCode::OK]
    );
}

/// Both buffered constructors, awaited in their handlers.
fn awaited_local_and_send<P>(page: fn() -> P) -> Vec<Route<()>>
where
    P: WebRender + WebRenderSend + Send + 'static,
{
    vec![
        Route::endpoint(
            "/local",
            get(move || async move { RouteResponse::ssr_async(page()).await }),
        ),
        Route::endpoint(
            "/send",
            get(move || async move { RouteResponse::ssr_async_send(page()).await }),
        ),
    ]
}

async fn awaited_renders_finish_in_the_handler() {
    let app = app(awaited_local_and_send(|| Staged));
    for uri in ["/local", "/send"] {
        let response = fetch(&app, uri).await;
        assert_eq!(response.status(), StatusCode::CREATED, "{uri}");
        assert_eq!(response.headers()["x-render"], "async", "{uri}");
        assert_eq!(response.headers()[header::VARY], "Origin", "{uri}");
        assert_eq!(text(response).await, "<p>staged</p>", "{uri}");
    }
    let app = self::app(awaited_local_and_send(|| Fails));
    for uri in ["/local", "/send"] {
        let response = fetch(&app, uri).await;
        let status = response.status();
        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR, "{uri}");
        assert_eq!(text(response).await, "render error", "{uri}");
    }
}

#[tokio::test]
async fn awaited_renders_finish_in_the_handler_on_a_current_thread_runtime() {
    awaited_renders_finish_in_the_handler().await;
}

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

#[tokio::test]
async fn awaited_sync_plans_streams_and_client_payloads_resolve() {
    let app = app(vec![
        Route::endpoint(
            "/sync",
            get(|| async { RouteResponse::ssr(SyncGreeting { name: "now" }).await }),
        ),
        Route::endpoint(
            "/stream",
            get(|| async { RouteResponse::ssr_stream(Yielding("streamed")).await }),
        ),
        Route::endpoint(
            "/local",
            get(|| async { RouteResponse::ssr_async(Staged).await }),
        ),
    ]);
    assert_eq!(text(fetch(&app, "/sync").await).await, "<p>sync now</p>");
    assert_eq!(text(fetch(&app, "/stream").await).await, "<p>streamed</p>");
    let request = Request::builder()
        .uri("/local")
        .header("X-Proa-Client", "1")
        .body(Body::empty())
        .unwrap();
    let response = app.clone().oneshot(request).await.unwrap();
    assert_eq!(response.status(), StatusCode::CREATED);
    let payload: serde_json::Value = serde_json::from_str(&text(response).await).unwrap();
    assert_eq!(payload["html"], "<p>staged</p>");
}

#[tokio::test]
async fn awaited_render_wrappers_apply_over_the_rendered_page() {
    let app = app(vec![
        Route::endpoint(
            "/missing",
            get(|| async {
                (
                    StatusCode::NOT_FOUND,
                    [(header::CACHE_CONTROL, "no-store")],
                    RouteResponse::ssr_async(Staged).await,
                )
            }),
        ),
        Route::endpoint(
            "/ok",
            get(|| async { (StatusCode::OK, RouteResponse::ssr_async_send(Staged).await) }),
        ),
    ]);
    let response = fetch(&app, "/missing").await;
    assert_eq!(response.status(), StatusCode::NOT_FOUND);
    assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store");
    assert_eq!(response.headers()["x-render"], "async");
    assert_eq!(text(response).await, "<p>staged</p>");
    let response = fetch(&app, "/ok").await;
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(response.headers()["x-render"], "async");
}

#[tokio::test]
async fn awaited_render_reads_its_route_context() {
    let app = app(vec![Route::page(
        "/about",
        "About us",
        get(|| async { RouteResponse::ssr_async(MetadataTitle).await }),
    )]);
    assert_eq!(text(fetch(&app, "/about").await).await, "About us");
}

#[tokio::test]
async fn awaited_render_outside_route_context_is_a_clear_error() {
    let router = Router::new()
        .route(
            "/local",
            get(|| async { RouteResponse::ssr_async(Yielding("unreachable")).await }),
        )
        .route(
            "/send",
            get(|| async { RouteResponse::ssr_async_send(Yielding("unreachable")).await }),
        );
    for uri in ["/local", "/send"] {
        let response = fetch(&router, uri).await;
        let status = response.status();
        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR, "{uri}");
        assert_eq!(text(response).await, "invalid route context", "{uri}");
    }
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn awaited_local_renders_run_on_the_pool_and_send_renders_on_the_handler() {
    let app = app(awaited_local_and_send(|| ThreadName));
    let local = text(fetch(&app, "/local").await).await;
    assert!(local.starts_with("proa-stream-"), "{local}");
    let send = text(fetch(&app, "/send").await).await;
    assert_eq!(send, thread_name());
}

#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn unawaited_renders_block_a_multi_thread_worker_as_before() {
    // Without `.await`, `into_response` renders in place with
    // `block_in_place`, on the handler's worker, local renders included.
    let app = app(local_and_send(|| ThreadName));
    for uri in ["/local", "/send"] {
        assert_eq!(text(fetch(&app, uri).await).await, thread_name(), "{uri}");
    }
}

/// Waits on a timer the runtime must keep driving.
struct Sleeps;

impl WebRender for Sleeps {
    fn render(
        self,
        cx: &mut WebContext,
    ) -> RenderOutcome<impl Future<Output = Result<(), WriteError>>> {
        RenderOutcome::pending(async move {
            tokio::time::sleep(Duration::from_millis(50)).await;
            WriteBuf::extend_str(&mut cx.out, "<p>slept</p>")
        })
    }
}

impl WebRenderSend for Sleeps {
    fn render_send(
        self,
        cx: &mut SendWebContext,
    ) -> RenderOutcome<impl Future<Output = Result<(), WriteError>> + Send> {
        RenderOutcome::pending(async move {
            tokio::time::sleep(Duration::from_millis(50)).await;
            cx.output_mut().extend_str("<p>slept</p>")
        })
    }
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn two_thousand_concurrent_awaited_renders_that_sleep_do_not_deadlock() {
    // Blocking each handler's worker in place, as un-awaited responses do
    // here, takes one blocking-pool thread per render; at this concurrency
    // the pool runs out and nothing drives the timer. Awaited renders hold
    // no thread while they wait.
    let app = app(awaited_local_and_send(|| Sleeps));
    for uri in ["/local", "/send"] {
        let requests: Vec<_> = (0..2_000)
            .map(|_| {
                let app = app.clone();
                tokio::spawn(async move {
                    let request = Request::builder().uri(uri).body(Body::empty()).unwrap();
                    let response = app.oneshot(request).await.unwrap();
                    (response.status(), text(response).await)
                })
            })
            .collect();
        let finished =
            tokio::time::timeout(Duration::from_secs(30), futures::future::join_all(requests))
                .await
                .expect("2,000 awaited renders must finish");
        for result in finished {
            let (status, body) = result.unwrap();
            assert_eq!(status, StatusCode::OK, "{uri}");
            assert_eq!(body, "<p>slept</p>", "{uri}");
        }
    }
}