navree-http 1.4.0

Navree HttpModule: Navree's router and extractors, default Tower layers, JSON errors, controllers and route metadata.
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
use std::collections::VecDeque;
use std::convert::Infallible;
use std::io::Read;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::task::Waker;

use bytes::Bytes;
use http::Request;
use http::header::{ACCEPT_RANGES, CACHE_CONTROL, CONTENT_LENGTH, CONTENT_RANGE, ETAG};
use http_body::{Body as HttpBody, Frame, SizeHint};
use http_body_util::BodyExt;
use tower::{ServiceBuilder, ServiceExt, service_fn};

use super::*;
use crate::body::Body;

/// `text` repeated past the 32-byte floor.
fn long(text: &str) -> String {
    text.repeat(64)
}

fn request(accept: &[&str]) -> Request<Body> {
    let mut builder = Request::builder().uri("/");
    for value in accept {
        builder = builder.header(ACCEPT_ENCODING, *value);
    }
    builder.body(Body::empty()).unwrap()
}

/// Sends a request accepting `accept` through the layer, to a service that
/// answers `response`.
async fn send(accept: &[&str], response: Response<Body>) -> Response<Body> {
    let response = std::sync::Mutex::new(Some(response));
    let inner = service_fn(move |_: Request<Body>| {
        let response = response.lock().unwrap().take().expect("one call");
        async move { Ok::<_, Infallible>(response) }
    });
    ServiceBuilder::new()
        .layer(CompressionLayer::new())
        .service(inner)
        .oneshot(request(accept))
        .await
        .unwrap()
}

fn text(body: impl Into<Body>) -> Response<Body> {
    Response::builder()
        .header(CONTENT_TYPE, "text/plain")
        .body(body.into())
        .unwrap()
}

fn gzipped(response: &Response<Body>) -> bool {
    response
        .headers()
        .get(CONTENT_ENCODING)
        .map(HeaderValue::as_bytes)
        == Some(b"gzip")
}

fn gunzip(bytes: &[u8]) -> Vec<u8> {
    let mut text = Vec::new();
    flate2::read::GzDecoder::new(bytes)
        .read_to_end(&mut text)
        .expect("a whole gzip stream");
    text
}

async fn collect(response: Response<Body>) -> (Vec<Bytes>, Option<HeaderMap>) {
    let mut body = response.into_body();
    let mut data = Vec::new();
    let mut trailers = None;
    while let Some(frame) = body.frame().await {
        let frame = frame.unwrap();
        match frame.into_data() {
            Ok(chunk) => data.push(chunk),
            Err(frame) => trailers = frame.into_trailers().ok(),
        }
    }
    (data, trailers)
}

#[test]
fn the_client_chooses_gzip_by_its_accept_encoding() {
    let cases: &[(&[&str], bool)] = &[
        (&[], false),
        (&["gzip"], true),
        (&["GZip"], true),
        (&["x-gzip"], true),
        (&["  gzip  "], true),
        (&["br, deflate, gzip"], true),
        (&["br", "gzip"], true),
        (&["br"], false),
        (&["*"], false),
        (&["identity"], false),
        (&["gzip;q=0"], false),
        (&["gzip;q=0.000"], false),
        (&["gzip; q=0.001"], true),
        (&["gzip;Q=1"], true),
        (&["gzip;q=1.000"], true),
        (&["gzip;q=1.001"], false),
        (&["gzip;q=0.5, identity"], false),
        (&["gzip;q=0.5, identity;q=0.5"], true),
        (&["gzip;q=0.4, gzip;q=0.6, identity;q=0.5"], true),
        (&["identity;q=0, gzip;q=0.1"], true),
        (&["gzip;q=0.1234"], false),
        (&["gzip;q=.5"], false),
        (&["gzip;q=0."], false),
        (&["gzip;q=1."], true),
        (&["gzip;level=1"], false),
        (&["gzip;q=0.5;level=1"], false),
        (&["gzip ;q=0.5"], true),
        (&["gzip;q = 0.5"], false),
        (&["gzip;q=abc", "gzip;q=0.2"], true),
        (&["gzip,"], true),
        (&[",,gzip"], true),
        (&["gzipx"], false),
        (&["deflate"], false),
    ];
    for (accept, chosen) in cases {
        let mut headers = HeaderMap::new();
        for value in *accept {
            headers.append(ACCEPT_ENCODING, HeaderValue::from_static(value));
        }
        assert_eq!(accepts_gzip(&headers), *chosen, "{accept:?}");
    }
    // A value that is not visible ASCII is skipped, not the whole list.
    let mut headers = HeaderMap::new();
    headers.append(
        ACCEPT_ENCODING,
        HeaderValue::from_bytes(b"gzip\xff").unwrap(),
    );
    assert!(!accepts_gzip(&headers));
    headers.append(ACCEPT_ENCODING, HeaderValue::from_static("gzip"));
    assert!(accepts_gzip(&headers));
}

#[tokio::test]
async fn a_response_is_compressed_for_a_client_that_accepts_gzip() {
    let body = long("compressible text ");
    let response = send(
        &["gzip"],
        Response::builder()
            .header(CONTENT_TYPE, "text/plain")
            .header(CONTENT_LENGTH, body.len())
            .header(ACCEPT_RANGES, "bytes")
            .body(Body::from(body.clone()))
            .unwrap(),
    )
    .await;
    assert!(gzipped(&response));
    assert_eq!(response.headers()[VARY], "accept-encoding");
    assert!(!response.headers().contains_key(CONTENT_LENGTH));
    assert!(!response.headers().contains_key(ACCEPT_RANGES));
    assert_eq!(response.body().size_hint().exact(), None);
    assert!(!response.body().is_end_stream());
    let (data, _) = collect(response).await;
    assert_eq!(gunzip(&data.concat()), body.as_bytes());
}

#[tokio::test]
async fn a_client_that_does_not_accept_gzip_still_gets_the_vary() {
    let body = long("text ");
    let response = send(&["br"], text(body.clone())).await;
    assert!(!gzipped(&response));
    assert_eq!(response.headers()[VARY], "accept-encoding");
    assert_eq!(
        response.body().size_hint().exact(),
        Some(body.len() as u64),
        "an uncompressed body is passed on as it is"
    );
    let (data, _) = collect(response).await;
    assert_eq!(data.concat(), body.as_bytes());
}

#[tokio::test]
async fn some_responses_are_never_compressed() {
    let big = long("x");
    let cases: Vec<(&str, Response<Body>)> = vec![
        ("31 bytes", text("x".repeat(31))),
        (
            "a content-length under 32",
            Response::builder()
                .header(CONTENT_LENGTH, "31")
                .body(Body::from_stream(futures_util::stream::iter([Ok::<
                    _,
                    Infallible,
                >(
                    "x".repeat(31),
                )])))
                .unwrap(),
        ),
        (
            "already encoded",
            Response::builder()
                .header(CONTENT_ENCODING, "br")
                .body(Body::from(big.clone()))
                .unwrap(),
        ),
        (
            "a range",
            Response::builder()
                .status(StatusCode::PARTIAL_CONTENT)
                .header(CONTENT_RANGE, "bytes 0-99/200")
                .body(Body::from(big.clone()))
                .unwrap(),
        ),
        ("an image", typed("image/png", &big)),
        ("gRPC", typed("application/grpc", &big)),
        ("gRPC with protobuf", typed("application/grpc+proto", &big)),
        ("events", typed("text/event-stream", &big)),
        ("empty", text("")),
    ];
    for (name, response) in cases {
        let response = send(&["gzip"], response).await;
        assert!(!gzipped(&response), "{name}");
        assert!(!response.headers().contains_key(VARY), "{name}");
    }
}

fn typed(content_type: &str, body: &str) -> Response<Body> {
    Response::builder()
        .header(CONTENT_TYPE, content_type)
        .body(Body::from(body.to_owned()))
        .unwrap()
}

#[tokio::test]
async fn svg_grpc_web_and_unknown_sizes_are_compressed() {
    let big = long("x");
    let cases: Vec<(&str, Response<Body>)> = vec![
        ("32 bytes", text("x".repeat(32))),
        ("svg", typed("image/svg+xml", &big)),
        ("gRPC-Web", typed("application/grpc-web+proto", &big)),
        ("no content type", Response::new(Body::from(big.clone()))),
        (
            "a stream of unknown size",
            Response::new(Body::from_stream(futures_util::stream::iter([Ok::<
                _,
                Infallible,
            >(
                "x"
            )]))),
        ),
        (
            "a content-length that is not a number",
            Response::builder()
                .header(CONTENT_LENGTH, "ten")
                .body(Body::from_stream(futures_util::stream::iter([Ok::<
                    _,
                    Infallible,
                >(
                    "x"
                )])))
                .unwrap(),
        ),
    ];
    for (name, response) in cases {
        let response = send(&["gzip"], response).await;
        assert!(gzipped(&response), "{name}");
    }
}

#[tokio::test]
async fn an_existing_vary_on_accept_encoding_is_not_repeated() {
    for vary in [
        "Accept-Encoding",
        "origin, accept-encoding",
        "x-accept-encoding-v2",
    ] {
        let response = send(
            &["gzip"],
            Response::builder()
                .header(VARY, vary)
                .body(Body::from(long("x")))
                .unwrap(),
        )
        .await;
        let values: Vec<_> = response.headers().get_all(VARY).iter().collect();
        assert_eq!(values, [vary], "{vary}");
    }
    let response = send(
        &["gzip"],
        Response::builder()
            .header(VARY, "origin")
            .body(Body::from(long("x")))
            .unwrap(),
    )
    .await;
    let values: Vec<_> = response.headers().get_all(VARY).iter().collect();
    assert_eq!(values, ["origin", "accept-encoding"]);
}

/// A body that hands its frames over one poll at a time, with a `Pending`
/// wherever the script says so, and tells when it is dropped.
struct Scripted {
    steps: VecDeque<Step>,
    dropped: Arc<AtomicBool>,
}

enum Step {
    Data(&'static str),
    Pending,
    Trailers(HeaderMap),
    Fail(&'static str),
}

impl Scripted {
    fn new(steps: impl IntoIterator<Item = Step>) -> (Self, Arc<AtomicBool>) {
        let dropped = Arc::new(AtomicBool::new(false));
        let body = Scripted {
            steps: steps.into_iter().collect(),
            dropped: dropped.clone(),
        };
        (body, dropped)
    }
}

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

impl HttpBody for Scripted {
    type Data = Bytes;
    type Error = BoxError;

    fn poll_frame(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Bytes>, BoxError>>> {
        match self.steps.pop_front() {
            None => Poll::Ready(None),
            Some(Step::Data(data)) => Poll::Ready(Some(Ok(Frame::data(Bytes::from(data))))),
            Some(Step::Pending) => {
                cx.waker().wake_by_ref();
                Poll::Pending
            }
            Some(Step::Trailers(trailers)) => Poll::Ready(Some(Ok(Frame::trailers(trailers)))),
            Some(Step::Fail(message)) => Poll::Ready(Some(Err(message.into()))),
        }
    }

    fn size_hint(&self) -> SizeHint {
        SizeHint::new()
    }
}

/// What polling a body gives.
type PolledFrame<B> = Poll<Option<Result<Frame<<B as HttpBody>::Data>, <B as HttpBody>::Error>>>;

/// Polls `body` once, with a waker that does nothing.
fn poll_once<B: HttpBody + Unpin>(body: &mut B) -> PolledFrame<B> {
    Pin::new(body).poll_frame(&mut Context::from_waker(Waker::noop()))
}

#[tokio::test]
async fn what_a_slow_body_sent_so_far_reaches_the_client_before_it_waits() {
    let (body, _) = Scripted::new([
        Step::Data("the first part of a slow response, "),
        Step::Pending,
        Step::Data("and the rest of it, a while later"),
    ]);
    let response = send(&["gzip"], Response::new(Body::new(body))).await;
    assert!(gzipped(&response));
    let mut body = response.into_body();
    let Poll::Ready(Some(Ok(first))) = poll_once(&mut body) else {
        panic!("the first part goes out before the body waits");
    };
    let first = first.into_data().unwrap();
    // The first frame ends on a flush: a client decodes all of it now.
    let mut decoder = flate2::read::GzDecoder::new(&first[..]);
    let mut seen = Vec::new();
    let _ = decoder.read_to_end(&mut seen);
    assert_eq!(seen, b"the first part of a slow response, ");
    let mut all = first.to_vec();
    while let Some(frame) = body.frame().await {
        all.extend_from_slice(&frame.unwrap().into_data().unwrap());
    }
    assert_eq!(
        gunzip(&all),
        b"the first part of a slow response, and the rest of it, a while later"
    );
}

#[tokio::test]
async fn trailers_follow_the_compressed_data() {
    let mut trailers = HeaderMap::new();
    trailers.insert("x-checksum", HeaderValue::from_static("abc"));
    let (body, _) = Scripted::new([
        Step::Data("some data that is long enough to be compressed"),
        Step::Trailers(trailers.clone()),
    ]);
    let response = send(&["gzip"], Response::new(Body::new(body))).await;
    let (data, seen) = collect(response).await;
    assert_eq!(
        gunzip(&data.concat()),
        b"some data that is long enough to be compressed"
    );
    assert_eq!(seen, Some(trailers));
}

#[tokio::test]
async fn an_error_from_the_body_comes_out_as_it_is() {
    let (body, _) = Scripted::new([
        Step::Data("the start of a body that fails"),
        Step::Pending,
        Step::Fail("gone"),
    ]);
    let response = send(&["gzip"], Response::new(Body::new(body))).await;
    let mut body = response.into_body();
    let first = body.frame().await.unwrap().unwrap().into_data().unwrap();
    assert!(!first.is_empty());
    let error = body.frame().await.unwrap().unwrap_err();
    assert_eq!(error.to_string(), "gone");
}

#[tokio::test]
async fn an_empty_stream_is_an_empty_gzip_stream() {
    let (body, _) = Scripted::new([]);
    let response = send(&["gzip"], Response::new(Body::new(body))).await;
    assert!(gzipped(&response));
    let (data, _) = collect(response).await;
    assert_eq!(gunzip(&data.concat()), b"");
}

#[tokio::test]
async fn a_client_that_goes_away_drops_the_body() {
    let (body, dropped) = Scripted::new([
        Step::Data("the start of a long download, "),
        Step::Pending,
        Step::Data("never read"),
    ]);
    let response = send(&["gzip"], Response::new(Body::new(body))).await;
    let mut body = response.into_body();
    assert!(matches!(poll_once(&mut body), Poll::Ready(Some(Ok(_)))));
    assert!(!dropped.load(Ordering::SeqCst));
    drop(body);
    assert!(dropped.load(Ordering::SeqCst));
}

#[tokio::test]
async fn a_request_cancelled_before_its_response_drops_the_handler() {
    let dropped = Arc::new(AtomicBool::new(false));
    let seen = dropped.clone();
    let inner = service_fn(move |_: Request<Body>| {
        let guard = DropFlag(seen.clone());
        async move {
            let _guard = guard;
            std::future::pending::<()>().await;
            Ok::<_, Infallible>(Response::new(Body::empty()))
        }
    });
    let mut service = CompressionLayer::new().layer(inner);
    let future = service.call(request(&["gzip"]));
    let mut future = Box::pin(future);
    assert!(
        future
            .as_mut()
            .poll(&mut Context::from_waker(Waker::noop()))
            .is_pending()
    );
    drop(future);
    assert!(dropped.load(Ordering::SeqCst));
}

struct DropFlag(Arc<AtomicBool>);

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

#[tokio::test]
async fn a_body_that_is_always_ready_comes_out_in_frames_of_at_most_4_kib() {
    // Pseudo-random bytes barely compress: a megabyte in, about as much out.
    let mut state = 0x2545_f491_u32;
    let input: Vec<u8> = (0..1 << 20)
        .map(|_| {
            state ^= state << 13;
            state ^= state >> 17;
            state ^= state << 5;
            state as u8
        })
        .collect();
    let response = send(&["gzip"], Response::new(Body::from(input.clone()))).await;
    let (data, _) = collect(response).await;
    assert!(data.len() > 200, "{} frames", data.len());
    assert!(data.iter().all(|frame| frame.len() <= 4096));
    assert_eq!(gunzip(&data.concat()), input);
}

/// Bytes that are text one time in three and noise otherwise.
fn noise(len: usize) -> Vec<u8> {
    let mut state = 0x2545_f491_u32;
    (0..len)
        .map(|i| {
            state ^= state << 13;
            state ^= state >> 17;
            state ^= state << 5;
            if i % 3 == 0 {
                b"navree "[i % 7]
            } else {
                state as u8
            }
        })
        .collect()
}

/// Every frame of `body` gzipped, polled with a waker that does nothing.
fn frames(body: Body) -> Vec<Bytes> {
    let mut gzip = GzipBody::new(body);
    let mut frames = Vec::new();
    loop {
        match poll_once(&mut gzip) {
            Poll::Pending => {}
            Poll::Ready(None) => return frames,
            Poll::Ready(Some(frame)) => frames.push(frame.unwrap().into_data().unwrap()),
        }
    }
}

/// The frame sizes and the SHA-256 of all the bytes.
fn fingerprint(frames: &[Bytes]) -> (Vec<usize>, String) {
    use sha2::Digest;
    let sizes = frames.iter().map(Bytes::len).collect();
    (sizes, hex::encode(sha2::Sha256::digest(frames.concat())))
}

fn sizes(full: usize, frames: usize, rest: &[usize]) -> Vec<usize> {
    let mut sizes = vec![full; frames];
    sizes.extend_from_slice(rest);
    sizes
}

/// The exact bytes for fixed inputs, with flate2 on either deflate backend
/// it may be built with (miniz_oxide alone, or zlib-rs, which other crates
/// of the workspace turn on): framing and flushing are pinned down to the
/// byte.
#[test]
fn the_bytes_for_fixed_inputs_are_pinned_down() {
    let text = frames(Body::from("Navree compresses this line. ".repeat(200)));
    let expected = [
        (
            vec![80],
            "ee66fbfe069f81f55c7bb86b28f30599bcea86b8c3f6b86fff83322d179a8439",
        ),
        (
            vec![105],
            "ebe9575fa779f2e812b2da8669d33c64acda08067319328725a142aba2aa49a1",
        ),
    ];
    check("one chunk of text", &text, &expected);

    let (slow, _) = Scripted::new([
        Step::Data("the first part of a slow response, "),
        Step::Pending,
        Step::Data("and the rest of it, a while later"),
    ]);
    let slow = frames(Body::new(slow));
    let expected = [
        (
            vec![55, 36],
            "5816d56f9ab54101231f6925fd57978e873d75ce93c269d48f272dc921d27b40",
        ),
        (
            vec![51, 38],
            "b657e4e469931ec24a2afb49f6ee745e9650da93a669b38dd059f6c630f2a166",
        ),
    ];
    check("a slow body", &slow, &expected);
    // The first frame ends on a sync flush.
    assert!(slow[0].ends_with(&[0, 0, 0xff, 0xff]));

    let large = frames(Body::from(noise(256 * 1024)));
    let expected = [
        (
            sizes(4096, 56, &[2111]),
            "7868b86612e668ee30c8b7f8ef53fc073bcb42812ab8b619516e890af3a07c4d",
        ),
        (
            sizes(4096, 56, &[1980]),
            "cb4ec14481eacd8be65d365e5508b5506a13a56b62c9f1a56b1a92201708f775",
        ),
    ];
    check("256 KiB in one chunk", &large, &expected);

    let data = noise(150_000);
    let mut steps = Vec::new();
    for (i, chunk) in data.chunks(3000).enumerate() {
        steps.push(Bytes::copy_from_slice(chunk));
        if i % 7 == 6 {
            steps.push(Bytes::new());
        }
    }
    // An empty chunk stands for a wait here.
    let waits = Body::new(Waiting(steps.into()));
    let chunked = frames(waits);
    let mut zlib = sizes(4096, 22, &[3102, 994]);
    zlib.extend(sizes(4096, 8, &[3510, 586, 2120]));
    let expected = [
        (
            sizes(4096, 32, &[1566]),
            "144fa250f60106b77959d549b91d2a07af6790481c1ec25fba28496e574dffa5",
        ),
        (
            zlib,
            "f75bca2a33787d1671339d4058bbdf4a84217b724dbb66ddb1abddcc5824978b",
        ),
    ];
    check(
        "3000-byte chunks with a wait after every seventh",
        &chunked,
        &expected,
    );
    // Frames share 4 KiB buffers: two frames cut from one fill it.
    assert_eq!(gunzip(&chunked.concat()), data);
}

fn check(name: &str, frames: &[Bytes], expected: &[(Vec<usize>, &str)]) {
    let (sizes, digest) = fingerprint(frames);
    assert!(
        expected
            .iter()
            .any(|(want, hash)| *want == sizes && *hash == digest),
        "{name}: frames {sizes:?}, sha256 {digest}"
    );
}

/// Owned chunks, an empty one standing for a `Pending`.
struct Waiting(VecDeque<Bytes>);

impl HttpBody for Waiting {
    type Data = Bytes;
    type Error = Infallible;

    fn poll_frame(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Bytes>, Infallible>>> {
        match self.0.pop_front() {
            None => Poll::Ready(None),
            Some(chunk) if chunk.is_empty() => {
                cx.waker().wake_by_ref();
                Poll::Pending
            }
            Some(chunk) => Poll::Ready(Some(Ok(Frame::data(chunk)))),
        }
    }
}

/// A body that panics when it is polled after its end, as a stream may.
struct Strict {
    frames: VecDeque<Frame<Bytes>>,
    ended: bool,
}

impl HttpBody for Strict {
    type Data = Bytes;
    type Error = Infallible;

    fn poll_frame(
        mut self: Pin<&mut Self>,
        _cx: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Bytes>, Infallible>>> {
        assert!(!self.ended, "polled after its end");
        let next = self.frames.pop_front();
        self.ended = next.is_none();
        Poll::Ready(next.map(Ok))
    }
}

#[tokio::test]
async fn a_body_that_has_ended_is_not_polled_again() {
    let mut trailers = HeaderMap::new();
    trailers.insert("x-checksum", HeaderValue::from_static("abc"));
    for with_trailers in [false, true] {
        let mut frames = VecDeque::from([Frame::data(Bytes::from(long("streamed ")))]);
        if with_trailers {
            frames.push_back(Frame::trailers(trailers.clone()));
        }
        let body = Strict {
            frames,
            ended: false,
        };
        let response = send(&["gzip"], Response::new(Body::new(body))).await;
        let mut body = response.into_body();
        let mut data = Vec::new();
        while let Some(frame) = body.frame().await {
            if let Ok(chunk) = frame.unwrap().into_data() {
                data.extend_from_slice(&chunk);
            }
        }
        // Polled again after its end, it stays ended.
        assert!(body.frame().await.is_none());
        assert_eq!(gunzip(&data), long("streamed ").as_bytes());
    }
}

/// Media types don't depend on case.
#[tokio::test]
async fn the_exclusions_are_compared_without_regard_to_case() {
    for content_type in [
        "image/png",
        "Image/PNG",
        "IMAGE/JPEG",
        "Text/Event-Stream",
        "TEXT/EVENT-STREAM; charset=utf-8",
        "Application/GRPC",
        "APPLICATION/grpc+proto",
    ] {
        let response = Response::builder()
            .header(CONTENT_TYPE, content_type)
            .body(Body::from(long("x")))
            .unwrap();
        let response = send(&["gzip"], response).await;
        assert!(!gzipped(&response), "{content_type}");
        assert!(!response.headers().contains_key(VARY), "{content_type}");
    }
    for content_type in ["Image/SVG+XML", "Application/GRPC-Web", "TEXT/HTML"] {
        let response = Response::builder()
            .header(CONTENT_TYPE, content_type)
            .body(Body::from(long("x")))
            .unwrap();
        assert!(gzipped(&send(&["gzip"], response).await), "{content_type}");
    }
}

#[tokio::test]
async fn no_transform_is_honoured() {
    for values in [
        &["no-transform"][..],
        &["No-Transform"],
        &["public, max-age=60,no-transform"],
        &["public", "NO-TRANSFORM , max-age=60"],
    ] {
        let mut builder = Response::builder().header(CONTENT_TYPE, "text/plain");
        for value in values {
            builder = builder.header(CACHE_CONTROL, *value);
        }
        let response = send(&["gzip"], builder.body(Body::from(long("x"))).unwrap()).await;
        assert!(!gzipped(&response), "{values:?}");
        assert!(!response.headers().contains_key(VARY), "{values:?}");
    }
    for value in ["no-store", "no-transforms", "x=\"no-transform\""] {
        let response = Response::builder()
            .header(CONTENT_TYPE, "text/plain")
            .header(CACHE_CONTROL, value)
            .body(Body::from(long("x")))
            .unwrap();
        assert!(gzipped(&send(&["gzip"], response).await), "{value}");
    }
}

#[tokio::test]
async fn a_route_can_opt_out() {
    let route = |no_compression| {
        Arc::new(crate::route::RouteMeta {
            no_compression,
            ..Default::default()
        })
    };
    let mut response = text(long("x"));
    response.extensions_mut().insert(route(true));
    let response = send(&["gzip"], response).await;
    assert!(!gzipped(&response));
    assert!(!response.headers().contains_key(VARY));

    let mut response = text(long("x"));
    response.extensions_mut().insert(route(false));
    assert!(gzipped(&send(&["gzip"], response).await));
}

/// The gzip variant is not byte for byte the same as the plain one, so a
/// strong validator can't stay on it; a weak one says what is still true.
#[tokio::test]
async fn a_strong_etag_is_weakened_on_the_gzip_variant() {
    let tagged = |etag: &'static str| {
        Response::builder()
            .header(CONTENT_TYPE, "text/plain")
            .header(ETAG, etag)
            .body(Body::from(long("x")))
            .unwrap()
    };
    let response = send(&["gzip"], tagged("\"v1\"")).await;
    assert!(gzipped(&response));
    assert_eq!(response.headers()[ETAG], "W/\"v1\"");

    let response = send(&["gzip"], tagged("W/\"v1\"")).await;
    assert_eq!(response.headers()[ETAG], "W/\"v1\"");

    // The plain variant keeps it.
    let response = send(&["identity"], tagged("\"v1\"")).await;
    assert!(!gzipped(&response));
    assert_eq!(response.headers()[ETAG], "\"v1\"");
}

/// A status that has no body stays without one, whatever the body says of
/// its size.
#[tokio::test]
async fn a_status_without_a_body_is_not_compressed() {
    for status in [
        StatusCode::NO_CONTENT,
        StatusCode::RESET_CONTENT,
        StatusCode::NOT_MODIFIED,
    ] {
        let stream = futures_util::stream::empty::<Result<Bytes, Infallible>>();
        let response = Response::builder()
            .status(status)
            .header(CONTENT_TYPE, "text/plain")
            .body(Body::from_stream(stream))
            .unwrap();
        let response = send(&["gzip"], response).await;
        assert!(!gzipped(&response), "{status}");
        let (frames, _) = collect(response).await;
        assert!(frames.is_empty(), "{status}: {frames:?}");
    }
}

/// BREACH: with a secret and reflected input in one compressed body, a guess
/// that repeats the secret is shorter. A response that opts out doesn't say.
#[tokio::test]
async fn the_length_of_an_opted_out_response_says_nothing_of_a_guess() {
    let page = |guess: &str| {
        format!(
            "<form><input type=hidden name=_csrf value=\"q7zk2mvb4xjt3nrc\"></form>\
             <input name=q value=\"{guess}\"><p>Results for your search</p>"
        )
    };
    let length = |body: String, no_transform: bool| async move {
        let mut builder = Response::builder().header(CONTENT_TYPE, "text/html");
        if no_transform {
            builder = builder.header(CACHE_CONTROL, "no-transform");
        }
        let response = send(&["gzip"], builder.body(Body::from(body)).unwrap()).await;
        let (frames, _) = collect(response).await;
        frames.iter().map(Bytes::len).sum::<usize>()
    };
    let (right, wrong) = (
        page("_csrf value=\"q7zk2mvb"),
        page("_csrf value=\"zzzzzzzz"),
    );
    assert_eq!(right.len(), wrong.len());
    assert!(length(right.clone(), false).await < length(wrong.clone(), false).await);
    assert_eq!(length(right, true).await, length(wrong, true).await);
}

/// Sends a `method` request accepting `accept` through the layer.
async fn send_as(
    method: http::Method,
    accept: &[&str],
    response: Response<Body>,
) -> Response<Body> {
    let response = std::sync::Mutex::new(Some(response));
    let inner = service_fn(move |_: Request<Body>| {
        let response = response.lock().unwrap().take().expect("one call");
        async move { Ok::<_, Infallible>(response) }
    });
    let mut request = request(accept);
    *request.method_mut() = method;
    ServiceBuilder::new()
        .layer(CompressionLayer::new())
        .service(inner)
        .oneshot(request)
        .await
        .unwrap()
}

/// A body-less response to a `HEAD` request, as the router makes it from the
/// `GET` response: the head of the `GET` response, its length kept when it is
/// known.
fn head_of(get: Response<Body>) -> Response<Body> {
    let (mut parts, body) = get.into_parts();
    if let Some(length) = body.size_hint().exact() {
        parts.headers.insert(CONTENT_LENGTH, length.into());
    }
    Response::from_parts(parts, Body::empty())
}

/// The headers that say how a response is encoded, for comparing the answers
/// to `GET` and to `HEAD`. (`Content-Length` is another matter: a `GET`
/// response gets its length from its body when it is sent, and a `HEAD`
/// response has it set, unless the body is compressed.)
fn encoding_headers(response: &Response<Body>) -> Vec<(&'static str, Option<String>)> {
    ["content-encoding", "etag", "vary", "accept-ranges"]
        .into_iter()
        .map(|name| {
            let value = response.headers().get(name);
            (name, value.map(|v| v.to_str().unwrap().to_owned()))
        })
        .collect()
}

/// A `206` with a `multipart/byteranges` body has its ranges' headers inside,
/// and none of its own `Content-Range`.
#[tokio::test]
async fn a_partial_content_response_is_never_compressed() {
    for content_type in ["multipart/byteranges; boundary=x", "text/plain"] {
        let response = Response::builder()
            .status(StatusCode::PARTIAL_CONTENT)
            .header(CONTENT_TYPE, content_type)
            .body(Body::from(long("x")))
            .unwrap();
        let response = send(&["gzip"], response).await;
        assert!(!gzipped(&response), "{content_type}");
        assert!(!response.headers().contains_key(VARY), "{content_type}");
        let (frames, _) = collect(response).await;
        assert_eq!(frames.concat(), long("x").as_bytes(), "{content_type}");
    }
}

/// `HEAD` is the `GET` response without a body: the same fields, each as the
/// `GET` has it, though the router has emptied the body before the layer sees
/// it.
#[tokio::test]
async fn a_head_response_is_encoded_as_the_get_response_is() {
    let get = || {
        Response::builder()
            .header(CONTENT_TYPE, "text/plain")
            .header(ACCEPT_RANGES, "bytes")
            .header(ETAG, "\"v1\"")
            .body(Body::from(long("x")))
            .unwrap()
    };
    for accept in [&["gzip"][..], &["identity"], &["br"], &[]] {
        let wanted = send_as(http::Method::GET, accept, get()).await;
        let head = send_as(http::Method::HEAD, accept, head_of(get())).await;
        assert_eq!(
            encoding_headers(&head),
            encoding_headers(&wanted),
            "{accept:?}"
        );
        assert_eq!(gzipped(&head), gzipped(&wanted), "{accept:?}");
        assert_eq!(
            head.headers().get(CONTENT_LENGTH).is_some(),
            !gzipped(&head),
            "{accept:?}: the length of a body that is sent as it is"
        );
        let (frames, _) = collect(head).await;
        assert!(frames.is_empty(), "{accept:?}: a HEAD response has no body");
    }
    let head = send_as(http::Method::HEAD, &["gzip"], head_of(get())).await;
    assert!(gzipped(&head));
    assert_eq!(head.headers()[ETAG], "W/\"v1\"");
    assert_eq!(head.headers()[VARY], "accept-encoding");
    assert!(!head.headers().contains_key(CONTENT_LENGTH));
    assert!(!head.headers().contains_key(ACCEPT_RANGES));
}

/// The exclusions hold for `HEAD` as they do for `GET`: the length that `GET`
/// would send says whether the body is under the floor.
#[tokio::test]
async fn a_head_response_is_left_alone_when_the_get_response_would_be() {
    let small = || text("x".repeat(31));
    let wanted = send_as(http::Method::GET, &["gzip"], small()).await;
    let head = send_as(http::Method::HEAD, &["gzip"], head_of(small())).await;
    assert_eq!(encoding_headers(&head), encoding_headers(&wanted));
    assert!(!gzipped(&head));
    assert_eq!(head.headers()[CONTENT_LENGTH], "31");

    // A body of unknown size counts as large, for `GET` and so for `HEAD`.
    let stream = || {
        let chunks = futures_util::stream::iter([Ok::<_, Infallible>(long("x"))]);
        Response::builder()
            .header(CONTENT_TYPE, "text/plain")
            .body(Body::from_stream(chunks))
            .unwrap()
    };
    let wanted = send_as(http::Method::GET, &["gzip"], stream()).await;
    let head = send_as(http::Method::HEAD, &["gzip"], head_of(stream())).await;
    assert!(gzipped(&wanted));
    assert_eq!(encoding_headers(&head), encoding_headers(&wanted));

    for (name, response) in [
        (
            "no-transform",
            Response::builder()
                .header(CONTENT_TYPE, "text/plain")
                .header(CACHE_CONTROL, "no-transform")
                .body(Body::from(long("x")))
                .unwrap(),
        ),
        (
            "an image",
            Response::builder()
                .header(CONTENT_TYPE, "image/png")
                .body(Body::from(long("x")))
                .unwrap(),
        ),
    ] {
        let head = send_as(http::Method::HEAD, &["gzip"], head_of(response)).await;
        assert!(!gzipped(&head), "{name}");
        assert!(!head.headers().contains_key(VARY), "{name}");
        assert!(head.headers().contains_key(CONTENT_LENGTH), "{name}");
    }
}

/// A `304` has the fields a `200` for the same request would, `Vary` among
/// them: a cache that updates what it stores from it keeps the key it stores
/// the response under.
#[tokio::test]
async fn a_not_modified_response_varies_like_the_response_it_stands_for() {
    let not_modified = || {
        Response::builder()
            .status(StatusCode::NOT_MODIFIED)
            .header(ETAG, "\"v1\"")
            .body(Body::empty())
            .unwrap()
    };
    for accept in [&["gzip"][..], &["identity"], &[]] {
        let response = send(accept, not_modified()).await;
        assert_eq!(response.headers()[VARY], "accept-encoding", "{accept:?}");
        assert!(!gzipped(&response), "{accept:?}");
        assert_eq!(response.headers()[ETAG], "\"v1\"");
    }
    let response = send_as(http::Method::HEAD, &["gzip"], not_modified()).await;
    assert_eq!(response.headers()[VARY], "accept-encoding");

    // Not for a response that is never compressed.
    let mut opted_out = not_modified();
    opted_out
        .extensions_mut()
        .insert(Arc::new(crate::route::RouteMeta {
            no_compression: true,
            ..Default::default()
        }));
    assert!(
        !send(&["gzip"], opted_out)
            .await
            .headers()
            .contains_key(VARY)
    );
    let mut no_transform = not_modified();
    no_transform
        .headers_mut()
        .insert(CACHE_CONTROL, HeaderValue::from_static("no-transform"));
    let response = send(&["gzip"], no_transform).await;
    assert!(!response.headers().contains_key(VARY));
    // And once.
    let mut varied = not_modified();
    varied
        .headers_mut()
        .insert(VARY, HeaderValue::from_static("Accept-Encoding"));
    let response = send(&["gzip"], varied).await;
    assert_eq!(response.headers().get_all(VARY).iter().count(), 1);

    // The other statuses without a body say nothing of a representation.
    for status in [StatusCode::NO_CONTENT, StatusCode::RESET_CONTENT] {
        let response = Response::builder()
            .status(status)
            .body(Body::empty())
            .unwrap();
        let response = send(&["gzip"], response).await;
        assert!(!response.headers().contains_key(VARY), "{status}");
    }
}