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

//! Shared HTML/Markdown representation negotiation for typed pages.

use super::response::{
    current_framework_request_context, defer, finalized_to_axum, framework_response_to_axum,
    multi_thread_runtime, RouteResponseFuture,
};
use axum::http::{
    header::{ACCEPT, LINK, VARY},
    HeaderMap, HeaderValue,
};
use axum::response::IntoResponse;
use futures::FutureExt as _;
use proa_core::{DataLoader, MdRenderSync, WriteError};
use proa_framework_core::{
    render_sync_markdown_response, FrameworkError, FrameworkRequestContext, FrameworkResponse,
    MarkdownResponse, RouteFinalization,
};
use std::future::IntoFuture;
use std::sync::Arc;

use super::RouteResponse;

/// Metadata for the stable Markdown representation of a canonical page.
///
/// The path is a template, fixed by the route rather than by the request. A
/// `{name}` capture is replaced with the matched route's parameter of that
/// name, so one `const` covers every record of a dynamic route. There is no
/// path to build per request and no `Link` or `Vary` header to set by hand:
///
/// ```
/// use axum::http::{HeaderMap, StatusCode};
/// use axum::response::IntoResponse;
/// use proa_framework_axum::{negotiate, MarkdownAlternate, RouteResponse};
/// # use proa_core::{MdRenderSync, WebContext, WebRenderSync, WriteError};
/// # #[derive(Clone, Copy)]
/// # struct IssuePage;
/// # impl WebRenderSync for IssuePage {
/// #     fn render(self, _cx: &mut WebContext) -> Result<(), WriteError> { Ok(()) }
/// # }
/// # impl MdRenderSync for IssuePage {
/// #     fn render_md(self, _cx: &mut WebContext) -> Result<(), WriteError> { Ok(()) }
/// # }
///
/// /// The Markdown representation of `/issues/{id}`.
/// const ISSUE_MARKDOWN: MarkdownAlternate = MarkdownAlternate::new("/issues/{id}/index.md");
///
/// /// `GET /issues/{id}`. The HTML response for `/issues/42` carries
/// /// `Link: </issues/42/index.md>; rel="alternate"; type="text/markdown"`
/// /// and `Vary: Accept`.
/// async fn issue(headers: HeaderMap) -> Result<impl IntoResponse, StatusCode> {
///     negotiate(&headers, RouteResponse::ssr(IssuePage), IssuePage, ISSUE_MARKDOWN)
///         .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
/// }
/// ```
///
/// Each capture expands to one percent-encoded path segment, so a `/` inside a
/// value becomes `%2F`; that includes the separators of a catch-all
/// parameter. A capture that names no parameter of the matched route is left
/// as written. The application's base path is prepended to the result.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MarkdownAlternate {
    path: &'static str,
}

impl MarkdownAlternate {
    /// Describe the Markdown representation served at `path`, an
    /// application-local path without the base path.
    ///
    /// A fixed page passes its path as is (`"/index.md"`). A dynamic route
    /// repeats its captures (`"/issues/{id}/index.md"` for `/issues/{id}`), and
    /// each one expands to the requested value when the `Link` header is
    /// written. See the [type documentation](Self) for an example.
    pub const fn new(path: &'static str) -> Self {
        Self { path }
    }

    /// The path template as written, before captures expand and the base path
    /// is prepended.
    pub const fn path(self) -> &'static str {
        self.path
    }

    /// Render an explicit alias sharing its canonical route's final capture.
    /// For `/guides/{slug}.md`, the renderer sees the same `slug` as on the HTML page.
    pub fn render_explicit<M: MdRenderSync>(
        self,
        markdown: M,
    ) -> Result<RepresentationResponse<proa_core::NoLoader>, WriteError> {
        let mut request = current_framework_request_context();
        let capture = self
            .path
            .rsplit('/')
            .next()
            .and_then(|segment| segment.strip_prefix('{'))
            .and_then(|segment| segment.strip_suffix("}.md"));
        if let (Some(key), Some(params)) = (capture, &request.route_params) {
            let params = proa_core::RouteParams::from_vec(
                params
                    .iter()
                    .map(|param| match param.value().strip_suffix(".md") {
                        Some(value) if param.key() == key => proa_core::RouteParam::new(key, value),
                        _ => param.clone(),
                    })
                    .collect(),
            );
            request.route_params = Some(params);
        }
        render_explicit_markdown(markdown, &request)
    }
}

/// A canonical page response after content negotiation.
///
/// The HTML variant preserves Proa's typed loader and streaming response. The
/// Markdown variant is rendered directly from the page's `MdRenderSync`
/// implementation and deliberately bypasses the HTML document shell.
pub enum RepresentationResponse<L: DataLoader> {
    Html {
        response: RouteResponse<L>,
        alternate: MarkdownAlternate,
    },
    Markdown {
        response: FrameworkResponse,
        canonical: bool,
    },
    /// A transferable root whose active render future stays local to finalization.
    MarkdownAsync {
        response: MarkdownResponse<L>,
        canonical: bool,
    },
}

impl<L: DataLoader + 'static> IntoResponse for RepresentationResponse<L> {
    fn into_response(self) -> axum::response::Response {
        match self {
            Self::Html {
                response,
                alternate,
            } => {
                let mut response = response.into_response();
                merge_accept_vary(response.headers_mut());
                response
                    .headers_mut()
                    .append(LINK, alternate_link(alternate));
                response
            }
            Self::Markdown {
                response,
                canonical,
            } => markdown_into_response(response, canonical),
            Self::MarkdownAsync {
                response,
                canonical,
            } => {
                let request = current_framework_request_context();
                // As for `RouteResponse`: block a multi-thread worker, or
                // defer on a current-thread runtime.
                let mut response = match multi_thread_runtime() {
                    Some(runtime) => finalized_to_axum(tokio::task::block_in_place(|| {
                        runtime
                            .block_on(response.finalize(&request))
                            .map_err(FrameworkError::from)
                    })),
                    None => defer(finalize_markdown(response, request)),
                };
                if canonical {
                    merge_accept_vary(response.headers_mut());
                }
                response
            }
        }
    }
}

/// Finish the render inside the handler, as for
/// [`RouteResponse`](RouteResponse#awaiting-buffered-renders):
/// `negotiate_async_with_loader(..).await`.
impl<L: DataLoader + 'static> IntoFuture for RepresentationResponse<L> {
    type Output = axum::response::Response;
    type IntoFuture = RouteResponseFuture;

    fn into_future(self) -> RouteResponseFuture {
        match self {
            Self::Html {
                response,
                alternate,
            } => {
                let link = alternate_link(alternate);
                response.into_future().map(move |response| {
                    merge_accept_vary(response.headers_mut());
                    response.headers_mut().append(LINK, link);
                })
            }
            Self::Markdown {
                response,
                canonical,
            } => RouteResponseFuture::ready(markdown_into_response(response, canonical)),
            Self::MarkdownAsync {
                response,
                canonical,
            } => {
                let request = current_framework_request_context();
                let rendering = RouteResponseFuture::render(finalize_markdown(response, request));
                if canonical {
                    rendering.map(|response| merge_accept_vary(response.headers_mut()))
                } else {
                    rendering
                }
            }
        }
    }
}

fn finalize_markdown<L: DataLoader + 'static>(
    response: MarkdownResponse<L>,
    request: FrameworkRequestContext,
) -> RouteFinalization {
    RouteFinalization::Local(Box::new(move || {
        async move {
            response
                .finalize(&request)
                .await
                .map_err(FrameworkError::from)
        }
        .boxed_local()
    }))
}

fn markdown_into_response(
    response: FrameworkResponse,
    canonical: bool,
) -> axum::response::Response {
    let mut response = framework_response_to_axum(response);
    if canonical {
        merge_accept_vary(response.headers_mut());
    }
    response
}

/// Negotiate a canonical page between browser HTML and semantic Markdown.
///
/// Markdown wins only when the client explicitly gives `text/markdown` a
/// positive quality greater than the quality applicable to HTML. Missing,
/// wildcard-only, invalid, and equal-preference requests stay on HTML.
pub fn negotiate<L, M>(
    headers: &HeaderMap,
    html: RouteResponse<L>,
    markdown: M,
    alternate: MarkdownAlternate,
) -> Result<RepresentationResponse<L>, WriteError>
where
    L: DataLoader,
    M: MdRenderSync,
{
    if prefers_markdown(headers) {
        Ok(RepresentationResponse::Markdown {
            response: render_sync_markdown_response(
                markdown,
                &current_framework_request_context(),
            )?,
            canonical: true,
        })
    } else {
        Ok(RepresentationResponse::Html {
            response: html,
            alternate,
        })
    }
}

/// Render the explicit stable `.md` representation without content
/// negotiation or an HTML document shell.
pub fn explicit_markdown<M>(
    markdown: M,
) -> Result<RepresentationResponse<proa_core::NoLoader>, WriteError>
where
    M: MdRenderSync,
{
    render_explicit_markdown(markdown, &current_framework_request_context())
}

fn render_explicit_markdown<M: MdRenderSync>(
    markdown: M,
    request: &proa_framework_core::FrameworkRequestContext,
) -> Result<RepresentationResponse<proa_core::NoLoader>, WriteError> {
    Ok(RepresentationResponse::Markdown {
        response: render_sync_markdown_response(markdown, request)?,
        canonical: false,
    })
}

/// Negotiate before rendering, preserving the supplied request-scoped loader.
///
/// This constructs an unopened plan. The handler remains `Send` even when the
/// renderer creates local state across `.await`. Await the plan in the
/// handler to run the selected render there, as with
/// [`RouteResponse`](RouteResponse#awaiting-buffered-renders); failures become
/// the standard HTTP render error.
pub fn negotiate_async_with_loader<L, M>(
    headers: &HeaderMap,
    html: RouteResponse<L>,
    markdown: M,
    loader: Arc<L>,
    alternate: MarkdownAlternate,
) -> RepresentationResponse<L>
where
    L: DataLoader + 'static,
    M: proa_core::MdRender<L> + Send + 'static,
{
    if prefers_markdown(headers) {
        RepresentationResponse::MarkdownAsync {
            response: MarkdownResponse::with_loader(markdown, loader),
            canonical: true,
        }
    } else {
        RepresentationResponse::Html {
            response: html,
            alternate,
        }
    }
}

/// Construct a loader-aware plan for a stable Markdown URL, without negotiation.
pub fn explicit_markdown_async_with_loader<L, M>(
    markdown: M,
    loader: Arc<L>,
) -> RepresentationResponse<L>
where
    L: DataLoader + 'static,
    M: proa_core::MdRender<L> + Send + 'static,
{
    RepresentationResponse::MarkdownAsync {
        response: MarkdownResponse::with_loader(markdown, loader),
        canonical: false,
    }
}

fn prefers_markdown(headers: &HeaderMap) -> bool {
    let Some(value) = headers.get(ACCEPT).and_then(|value| value.to_str().ok()) else {
        return false;
    };

    let ranges: Vec<MediaRange<'_>> = value.split(',').filter_map(MediaRange::parse).collect();
    let has_explicit_markdown = ranges.iter().any(|range| {
        range.ty.eq_ignore_ascii_case("text")
            && range.subtype.eq_ignore_ascii_case("markdown")
            && range.quality > 0
    });
    if !has_explicit_markdown {
        return false;
    }

    let markdown = quality_for(&ranges, "text", "markdown");
    let html = quality_for(&ranges, "text", "html");
    markdown > 0 && markdown > html
}

#[derive(Debug, Clone, Copy)]
struct MediaRange<'a> {
    ty: &'a str,
    subtype: &'a str,
    quality: u16,
}

impl<'a> MediaRange<'a> {
    fn parse(raw: &'a str) -> Option<Self> {
        let mut parts = raw.trim().split(';');
        let media = parts.next()?.trim();
        let (ty, subtype) = media.split_once('/')?;
        let ty = ty.trim();
        let subtype = subtype.trim();
        if ty.is_empty() || subtype.is_empty() {
            return None;
        }

        let mut quality = 1_000;
        for parameter in parts {
            let Some((name, value)) = parameter.trim().split_once('=') else {
                continue;
            };
            if name.trim().eq_ignore_ascii_case("q") {
                quality = parse_quality(value.trim())?;
            }
        }

        Some(Self {
            ty,
            subtype,
            quality,
        })
    }

    fn specificity(self, ty: &str, subtype: &str) -> Option<u8> {
        if self.ty == "*" && self.subtype == "*" {
            Some(0)
        } else if self.ty.eq_ignore_ascii_case(ty) && self.subtype == "*" {
            Some(1)
        } else if self.ty.eq_ignore_ascii_case(ty) && self.subtype.eq_ignore_ascii_case(subtype) {
            Some(2)
        } else {
            None
        }
    }
}

fn quality_for(ranges: &[MediaRange<'_>], ty: &str, subtype: &str) -> u16 {
    ranges
        .iter()
        .filter_map(|range| {
            range
                .specificity(ty, subtype)
                .map(|specificity| (specificity, range.quality))
        })
        .max_by_key(|(specificity, quality)| (*specificity, *quality))
        .map(|(_, quality)| quality)
        .unwrap_or(0)
}

fn parse_quality(raw: &str) -> Option<u16> {
    if raw == "0" {
        return Some(0);
    }
    if raw == "1" {
        return Some(1_000);
    }

    let (whole, fraction) = raw.split_once('.')?;
    if !matches!(whole, "0" | "1") || fraction.len() > 3 || fraction.is_empty() {
        return None;
    }
    if !fraction.bytes().all(|byte| byte.is_ascii_digit()) {
        return None;
    }
    let mut scaled = fraction.parse::<u16>().ok()?;
    for _ in fraction.len()..3 {
        scaled *= 10;
    }
    if whole == "1" {
        (scaled == 0).then_some(1_000)
    } else {
        Some(scaled)
    }
}

fn merge_accept_vary(headers: &mut HeaderMap) {
    let already_varies = headers.get_all(VARY).iter().any(|value| {
        value.to_str().is_ok_and(|text| {
            text.split(',')
                .any(|token| token.trim() == "*" || token.trim().eq_ignore_ascii_case("accept"))
        })
    });
    if !already_varies {
        headers.append(VARY, HeaderValue::from_static("Accept"));
    }
}

fn alternate_link(alternate: MarkdownAlternate) -> HeaderValue {
    use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
    use std::borrow::Cow;
    const SEGMENT: &percent_encoding::AsciiSet = &NON_ALPHANUMERIC
        .remove(b'-')
        .remove(b'.')
        .remove(b'_')
        .remove(b'~');
    let mut path = Cow::Borrowed(alternate.path());
    if path.contains('{') {
        let _ = super::context::ROUTE_CONTEXT.try_with(|ctx| {
            for param in ctx.borrow_mut().current_route_params() {
                let capture = format!("{{{}}}", param.key());
                if path.contains(&capture) {
                    path = Cow::Owned(path.replace(
                        &capture,
                        &utf8_percent_encode(param.value(), SEGMENT).to_string(),
                    ));
                }
            }
        });
    }
    HeaderValue::from_str(&format!(
        "<{}>; rel=\"alternate\"; type=\"text/markdown\"",
        super::app_url(&path)
    ))
    .expect("Markdown alternate paths must be valid header values")
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::body::Body;
    use axum::http::header::CONTENT_TYPE;
    use axum::http::StatusCode;
    use axum::{
        http::{header, Request},
        routing::get,
        Router,
    };
    use http_body_util::BodyExt;
    use proa_core::WebContext;
    use proa_core::{text::StaticRaw, WriteBuf, WriteError};
    use proa_macros::md_sync;
    use std::{collections::HashMap, sync::Arc};
    use tower::ServiceExt;

    use crate::route::context::RouteContextLayer;

    #[derive(Clone, Copy)]
    struct MarkdownPage;

    impl<Loader: ::proa_core::DataLoader, B: WriteBuf> MdRenderSync<Loader, B> for MarkdownPage {
        fn render_md(self, cx: &mut WebContext<Loader, B>) -> Result<(), WriteError> {
            md_sync! { r###"
                # Route dossier

                Semantic body.
                "###
            }
            .render_md(cx)
        }
    }

    fn headers(accept: Option<&str>) -> HeaderMap {
        let mut headers = HeaderMap::new();
        if let Some(accept) = accept {
            headers.insert(ACCEPT, HeaderValue::from_str(accept).unwrap());
        }
        headers
    }

    #[test]
    fn negotiation_defaults_to_html_for_absent_wildcard_equal_and_zero_quality() {
        for accept in [
            None,
            Some("*/*"),
            Some("text/*"),
            Some("text/html, text/markdown"),
            Some("text/html;q=0.8, text/markdown;q=0.8"),
            Some("text/markdown;q=0, text/html;q=0.1"),
            Some("text/markdown;q=0.5, */*;q=1"),
        ] {
            assert!(!prefers_markdown(&headers(accept)), "{accept:?}");
        }
    }

    #[test]
    fn negotiation_selects_explicitly_preferred_markdown() {
        for accept in [
            "text/markdown",
            "text/html;q=0.4, text/markdown;q=0.9",
            "application/json;q=1, text/markdown;q=0.2",
        ] {
            assert!(prefers_markdown(&headers(Some(accept))), "{accept}");
        }
    }

    #[tokio::test]
    async fn canonical_html_advertises_markdown_and_varies_on_accept() {
        let app = Router::new()
            .route(
                "/",
                get(|| async {
                    negotiate(
                        &headers(None),
                        RouteResponse::ssr(StaticRaw("<!DOCTYPE html><p>HTML</p>")),
                        MarkdownPage,
                        MarkdownAlternate::new("/index.md"),
                    )
                    .unwrap()
                }),
            )
            .layer(RouteContextLayer::new(Arc::new(HashMap::new())));
        let response = app.oneshot(Request::new(Body::empty())).await.unwrap();

        assert_eq!(response.headers()[VARY], "Accept");
        assert_eq!(
            response.headers()[LINK],
            "</index.md>; rel=\"alternate\"; type=\"text/markdown\""
        );
        assert_eq!(response.headers()[CONTENT_TYPE], "text/html; charset=utf-8");
    }

    #[tokio::test]
    async fn alternate_link_encodes_each_captured_segment() {
        let app = Router::new()
            .route(
                "/guides/{slug}",
                get(|| async {
                    negotiate(
                        &headers(None),
                        RouteResponse::ssr(StaticRaw("HTML")),
                        MarkdownPage,
                        MarkdownAlternate::new("/guides/{slug}.md"),
                    )
                    .unwrap()
                }),
            )
            .layer(RouteContextLayer::new(Arc::new(HashMap::new())));
        let request = Request::builder()
            .uri("/guides/a%2Fb%20c")
            .body(Body::empty())
            .unwrap();
        let response = app.oneshot(request).await.unwrap();
        assert_eq!(
            response.headers()[LINK],
            "</guides/a%2Fb%20c.md>; rel=\"alternate\"; type=\"text/markdown\""
        );
    }

    #[tokio::test]
    async fn explicit_alias_strips_one_suffix_from_only_the_final_capture() {
        struct Page;
        impl MdRenderSync for Page {
            fn render_md(self, cx: &mut WebContext) -> Result<(), WriteError> {
                let params = cx.route_params().unwrap();
                assert_eq!(params.get("section"), Some("a.md"));
                assert_eq!(params.get("slug"), Some("b/c.md"));
                Ok(())
            }
        }
        const ALTERNATE: MarkdownAlternate = MarkdownAlternate::new("/{section}/{slug}.md");
        let app = Router::new()
            .route(
                "/{section}/{slug}",
                get(|| async { ALTERNATE.render_explicit(Page).unwrap() }),
            )
            .layer(RouteContextLayer::new(Arc::new(HashMap::new())));
        let request = Request::builder()
            .uri("/a.md/b%2Fc.md.md")
            .body(Body::empty())
            .unwrap();
        let response = app.oneshot(request).await.unwrap();
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn canonical_and_explicit_markdown_bodies_are_identical() {
        let canonical = negotiate(
            &headers(Some("text/markdown")),
            RouteResponse::ssr(StaticRaw("unused")),
            MarkdownPage,
            MarkdownAlternate::new("/index.md"),
        )
        .unwrap()
        .into_response();
        let explicit = explicit_markdown(MarkdownPage).unwrap().into_response();

        assert_eq!(canonical.headers()[VARY], "Accept");
        assert!(explicit.headers().get(VARY).is_none());
        assert_eq!(
            canonical.headers()[CONTENT_TYPE],
            "text/markdown; charset=utf-8"
        );
        assert_eq!(
            explicit.headers()[CONTENT_TYPE],
            "text/markdown; charset=utf-8"
        );
        assert!(canonical.headers().get(header::LINK).is_none());

        let canonical = canonical.into_body().collect().await.unwrap().to_bytes();
        let explicit = explicit.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(canonical, explicit);
        assert_eq!(canonical, "# Route dossier\n\nSemantic body.\n\n");
    }
}

#[cfg(test)]
mod shared_context_tests {
    use super::*;
    use crate::route::context::{RouteContextLayer, ROUTE_CONTEXT};
    use axum::http::StatusCode;
    use axum::{
        body::Body,
        http::{header, Method, Request},
        routing::get,
        Router,
    };
    use http_body_util::BodyExt;
    use proa_core::{
        CspNonce, LoadError, LoadKey, LoadRequest, LoadValue, RenderOutcome, RouteParam,
        RouteParams, WebContext, WebRender, WriteBuf,
    };
    use std::{
        collections::HashMap,
        future::Future,
        rc::Rc,
        sync::{
            atomic::{AtomicUsize, Ordering},
            Mutex,
        },
    };
    use tower::ServiceExt;

    struct Loader {
        loads: AtomicUsize,
    }
    impl DataLoader for Loader {
        fn load(
            &self,
            _: &LoadRequest,
        ) -> impl Future<Output = Result<LoadValue, LoadError>> + Send {
            async move {
                tokio::task::yield_now().await;
                self.loads.fetch_add(1, Ordering::Relaxed);
                Ok(LoadValue::arc(Arc::new(String::from("*loaded*"))))
            }
        }
    }

    struct LoadedMarkdown {
        loader: Arc<Loader>,
    }
    impl proa_core::MdRender<Loader> for LoadedMarkdown {
        fn render_md(
            self,
            cx: &mut WebContext<Loader>,
        ) -> RenderOutcome<impl Future<Output = Result<(), WriteError>>> {
            RenderOutcome::pending(async move {
                assert!(Arc::ptr_eq(cx.loader(), &self.loader));
                assert_eq!(cx.request().method(), Some(&Method::GET));
                assert_eq!(cx.request().headers()["x-request"], "shared");
                assert_eq!(cx.request_location().unwrap().path(), "/article");
                assert_eq!(cx.route_params().unwrap().get("slug"), Some("article"));
                assert_eq!(cx.csp_nonce().unwrap().as_str(), "test-nonce");
                let local = Rc::new(7);
                let value = cx
                    .load_typed::<String>(LoadKey::named("article", "one"))
                    .await?;
                assert_eq!(*local, 7);
                cx.response_mut().set_status(StatusCode::CREATED);
                cx.response_mut()
                    .append_set_cookie(HeaderValue::from_static("a=1"));
                cx.response_mut()
                    .append_set_cookie(HeaderValue::from_static("b=2"));
                cx.response_mut()
                    .append_header(VARY, HeaderValue::from_static("Origin"));
                cx.response_mut()
                    .append_header(LINK, HeaderValue::from_static("</one>; rel=preload"));
                cx.response_mut()
                    .append_header(LINK, HeaderValue::from_static("</two>; rel=preload"));
                cx.head_mut().set_title("must not become an HTML shell");
                cx.write_md_text(value.as_str())
            })
        }
    }

    struct HtmlCount(Arc<AtomicUsize>);
    impl WebRender<Loader> for HtmlCount {
        fn render(
            self,
            cx: &mut WebContext<Loader>,
        ) -> RenderOutcome<impl Future<Output = Result<(), WriteError>>> {
            self.0.fetch_add(1, Ordering::Relaxed);
            // proa-perf-ok: fixed trusted markup probes representation selection in this test
            let written = cx.out.extend_static_str("<p>selected</p>");
            RenderOutcome::<std::future::Ready<_>>::Done(written)
        }
    }

    #[tokio::test]
    async fn negotiated_handler_defers_local_markdown_and_preserves_request_and_response() {
        negotiated_markdown_preserves_request_and_response(false).await;
    }

    #[tokio::test]
    async fn awaited_negotiated_markdown_preserves_request_and_response() {
        negotiated_markdown_preserves_request_and_response(true).await;
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn negotiated_markdown_preserves_request_and_response_on_a_multi_thread_runtime() {
        negotiated_markdown_preserves_request_and_response(false).await;
        negotiated_markdown_preserves_request_and_response(true).await;
    }

    async fn negotiated_markdown_preserves_request_and_response(awaited: bool) {
        let loader = Arc::new(Loader {
            loads: AtomicUsize::new(0),
        });
        let html_calls = Arc::new(AtomicUsize::new(0));
        let handler_loader = Arc::clone(&loader);
        let handler_html = Arc::clone(&html_calls);
        let app = Router::new()
            .route(
                "/article",
                get(move |headers: HeaderMap| {
                    let loader = Arc::clone(&handler_loader);
                    let calls = Arc::clone(&handler_html);
                    async move {
                        // The route matcher normally installs these before finalization.
                        ROUTE_CONTEXT.with(|context| {
                            context
                                .borrow_mut()
                                .set_route_params(RouteParams::from_vec(vec![RouteParam::new(
                                    "slug", "article",
                                )]));
                        });
                        let plan = negotiate_async_with_loader(
                            &headers,
                            RouteResponse::ssr_async_with_loader(
                                HtmlCount(calls),
                                Arc::clone(&loader),
                            ),
                            LoadedMarkdown {
                                loader: Arc::clone(&loader),
                            },
                            loader,
                            MarkdownAlternate::new("/article.md"),
                        );
                        if awaited {
                            plan.await
                        } else {
                            plan.into_response()
                        }
                    }
                }),
            )
            .layer(RouteContextLayer::new(Arc::new(HashMap::new())));
        let request = |accept| {
            let mut request = Request::builder()
                .uri("/article")
                .header(ACCEPT, accept)
                .header("x-request", "shared")
                .body(Body::empty())
                .unwrap();
            request
                .extensions_mut()
                .insert(CspNonce::new("test-nonce").unwrap());
            request
        };
        let response = app.clone().oneshot(request("text/markdown")).await.unwrap();
        assert_eq!(response.status(), StatusCode::CREATED);
        assert_eq!(
            response.headers()[header::CONTENT_TYPE],
            "text/markdown; charset=utf-8"
        );
        assert_eq!(
            response
                .headers()
                .get_all(header::SET_COOKIE)
                .iter()
                .count(),
            2
        );
        assert_eq!(response.headers().get_all(LINK).iter().count(), 2);
        assert_eq!(
            response.headers().get_all(VARY).iter().collect::<Vec<_>>(),
            ["Origin", "Accept"]
        );
        assert_eq!(
            response.into_body().collect().await.unwrap().to_bytes(),
            "\\*loaded\\*"
        );
        assert_eq!(loader.loads.load(Ordering::Relaxed), 1);
        assert_eq!(html_calls.load(Ordering::Relaxed), 0);
        let html = app.oneshot(request("text/html")).await.unwrap();
        assert_eq!(html.status(), StatusCode::OK);
        assert_eq!(
            html.headers().get_all(VARY).iter().collect::<Vec<_>>(),
            ["Accept"]
        );
        assert!(html.headers()[LINK]
            .to_str()
            .unwrap()
            .starts_with("</article.md>"));
        assert_eq!(html_calls.load(Ordering::Relaxed), 1);
        assert_eq!(loader.loads.load(Ordering::Relaxed), 1);
    }

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

    async fn assert_render_error(app: Router, uri: &str) {
        let response = app
            .oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap())
            .await
            .unwrap();
        assert_eq!(
            response.status(),
            StatusCode::INTERNAL_SERVER_ERROR,
            "{uri}"
        );
        assert!(!response.headers().contains_key(VARY), "{uri}");
        assert_eq!(
            response.into_body().collect().await.unwrap().to_bytes(),
            "render error",
            "{uri}"
        );
    }

    fn failing_markdown() -> Router {
        Router::new()
            .route(
                "/failed.md",
                get(|| async {
                    explicit_markdown_async_with_loader(Fails, Arc::new(proa_core::NoLoader))
                }),
            )
            .route(
                "/awaited.md",
                get(|| async {
                    explicit_markdown_async_with_loader(Fails, Arc::new(proa_core::NoLoader)).await
                }),
            )
    }

    #[tokio::test]
    async fn explicit_async_errors_use_http_render_error_mapping() {
        let app = failing_markdown().layer(RouteContextLayer::new(Arc::new(HashMap::new())));
        assert_render_error(app.clone(), "/failed.md").await;
        assert_render_error(app, "/awaited.md").await;
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn unawaited_markdown_renders_in_place_on_a_multi_thread_runtime() {
        // As before awaiting existed, no route context is needed here.
        assert_render_error(failing_markdown(), "/failed.md").await;
    }

    struct Pages {
        source: String,
        pointers: Arc<Mutex<Vec<usize>>>,
    }
    impl MdRenderSync for Pages {
        fn render_md(self, cx: &mut WebContext) -> Result<(), WriteError> {
            cx.write_md_trusted(&self.source)?;
            *self.pointers.lock().unwrap() = cx
                .out
                .slices()
                .filter(|p| !p.is_empty())
                .map(|p| p.as_ptr() as usize)
                .collect();
            Ok(())
        }
    }

    #[tokio::test]
    async fn standalone_buffered_response_transfers_pages_without_copying() {
        let pointers = Arc::new(Mutex::new(Vec::new()));
        let source = "page contents\n".repeat(900);
        let response = explicit_markdown(Pages {
            source: source.clone(),
            pointers: Arc::clone(&pointers),
        })
        .unwrap()
        .into_response();
        assert_eq!(
            response.headers()[header::CONTENT_LENGTH],
            source.len().to_string()
        );
        let mut body = response.into_body();
        let mut actual = Vec::new();
        let mut bytes = Vec::new();
        while let Some(frame) = body.frame().await {
            let chunk = frame.unwrap().into_data().unwrap();
            actual.push(chunk.as_ptr() as usize);
            bytes.extend_from_slice(&chunk);
        }
        assert_eq!(actual, *pointers.lock().unwrap());
        assert!(actual.len() > 1);
        assert_eq!(bytes, source.as_bytes());
    }

    #[test]
    fn vary_merging_keeps_existing_values_and_wildcard() {
        for value in ["Origin", "*", "aCcEpT, Origin"] {
            let mut headers = HeaderMap::new();
            headers.append(VARY, HeaderValue::from_str(value).unwrap());
            merge_accept_vary(&mut headers);
            assert_eq!(headers[VARY], value);
            assert_eq!(
                headers.get_all(VARY).iter().count(),
                if value == "Origin" { 2 } else { 1 }
            );
        }
    }
}