dropshot 0.17.0

expose REST APIs from a Rust program
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
// Copyright 2025 Oxide Computer Company

//! Response compression support for Dropshot.

use crate::body::Body;
use async_compression::tokio::bufread::GzipEncoder;
use futures::{StreamExt, TryStreamExt};
use http::{HeaderMap, HeaderValue, Response};
use hyper::body::{Body as HttpBodyTrait, Frame};
use tokio_util::io::{ReaderStream, StreamReader};

/// Marker type for disabling compression on a response.
/// Insert this into response extensions to prevent compression:
/// ```ignore
/// response.extensions_mut().insert(NoCompression);
/// ```
#[derive(Debug, Clone, Copy)]
pub struct NoCompression;

/// Parses the `Accept-Encoding` header into a list of encodings and their
/// associated quality factors. Returns the encoding names in lowercase for
/// easier comparisons.
fn parse_accept_encoding(header: &HeaderValue) -> Vec<(String, f32)> {
    const DEFAULT_QUALITY: f32 = 1.0;

    let Ok(header_value) = header.to_str() else {
        return Vec::new();
    };

    header_value
        .split(',')
        .filter_map(|directive| {
            let mut parts = directive.trim().split(';');
            let encoding = parts.next()?.trim();
            if encoding.is_empty() {
                return None;
            }

            let mut quality = DEFAULT_QUALITY;
            for param in parts {
                let mut param = param.splitn(2, '=');
                let Some(name) = param.next() else {
                    continue;
                };
                let name = name.trim();

                let Some(value) = param.next() else {
                    continue;
                };
                let value = value.trim();

                if name.eq_ignore_ascii_case("q") {
                    if let Ok(parsed) = value.parse::<f32>() {
                        if parsed.is_finite() {
                            quality = parsed.clamp(0.0, 1.0);
                        }
                    }
                }
            }

            Some((encoding.to_ascii_lowercase(), quality))
        })
        .collect()
}

/// Checks if the request accepts gzip encoding based on the Accept-Encoding header.
/// Handles quality values (q parameter) using RFC-compliant preference rules.
pub fn accepts_gzip_encoding(headers: &HeaderMap<HeaderValue>) -> bool {
    let mut best_gzip_quality: Option<f32> = None;
    let mut best_wildcard_quality: Option<f32> = None;

    // RFC 9110 §5.3 allows the same header to appear multiple times,
    // semantically equivalent to a comma-separated list.
    // RFC 9110 §12.5.3 specifies that the most preferred (highest quality)
    // representation wins, so we retain the maximum q-value we see for each
    // relevant coding.
    for accept_encoding in headers.get_all(http::header::ACCEPT_ENCODING) {
        for (encoding, quality) in parse_accept_encoding(accept_encoding) {
            match encoding.as_str() {
                "gzip" => {
                    best_gzip_quality = Some(
                        best_gzip_quality
                            .map_or(quality, |current| current.max(quality)),
                    );
                }
                "*" => {
                    best_wildcard_quality = Some(
                        best_wildcard_quality
                            .map_or(quality, |current| current.max(quality)),
                    );
                }
                _ => {}
            }
        }
    }

    if let Some(quality) = best_gzip_quality {
        return quality > 0.0;
    }

    if let Some(quality) = best_wildcard_quality {
        return quality > 0.0;
    }

    false
}

/// Checks if a content type is compressible.
/// This is used to determine if the Vary: Accept-Encoding header should be added,
/// even if compression doesn't occur for this particular request.
pub fn is_compressible_content_type(
    response_headers: &HeaderMap<HeaderValue>,
) -> bool {
    // Only compress when we know the content type
    let Some(content_type) = response_headers.get(http::header::CONTENT_TYPE)
    else {
        return false;
    };
    let Ok(ct_str) = content_type.to_str() else {
        return false;
    };

    let ct_lower = ct_str.to_ascii_lowercase();

    // SSE streams prioritize latency over compression
    if ct_lower.starts_with("text/event-stream") {
        return false;
    }

    let is_compressible = ct_lower.starts_with("application/json")
        || ct_lower.starts_with("application/ndjson")
        || ct_lower.starts_with("application/x-ndjson")
        || ct_lower.starts_with("text/")
        || ct_lower.starts_with("application/xml")
        || ct_lower.starts_with("application/javascript")
        || ct_lower.starts_with("application/x-javascript");

    // RFC 6839 structured syntax suffixes (+json, +xml)
    let has_compressible_suffix =
        ct_lower.contains("+json") || ct_lower.contains("+xml");

    is_compressible || has_compressible_suffix
}

// Note that should_compress_response intentionally answers only "should
// Dropshot apply gzip?" rather than implementing full RFC 9110 content-coding
// negotiation.
//
// For example, a request with `Accept-Encoding: br, identity;q=0` is treated as
// "don't gzip" and will currently fall back to an uncompressed response if gzip
// is not applied, even though a fully compliant server would return 406 Not
// Acceptable because `identity` was explicitly rejected.
//
// If this ever matters for a real client, handle it after the compression
// decision by rejecting identity fallback with 406.

/// Determines if a response should be compressed with gzip.
pub fn should_compress_response(
    request_method: &http::Method,
    request_headers: &HeaderMap<HeaderValue>,
    response_status: http::StatusCode,
    response_headers: &HeaderMap<HeaderValue>,
    response_extensions: &http::Extensions,
) -> bool {
    // Responses that must not have a body per HTTP spec
    if response_status.is_informational()
        || response_status == http::StatusCode::NO_CONTENT
        || response_status == http::StatusCode::NOT_MODIFIED
    {
        return false;
    }

    // HEAD responses have no body
    if request_method == http::Method::HEAD {
        return false;
    }

    // Compressing partial content changes the meaning for clients
    if response_status == http::StatusCode::PARTIAL_CONTENT {
        return false;
    }

    if response_headers.contains_key(http::header::CONTENT_RANGE) {
        return false;
    }

    if !accepts_gzip_encoding(request_headers) {
        return false;
    }

    if response_headers.contains_key(http::header::CONTENT_ENCODING) {
        return false;
    }

    if response_extensions.get::<NoCompression>().is_some() {
        return false;
    }

    if let Some(content_length) =
        response_headers.get(http::header::CONTENT_LENGTH)
    {
        if let Ok(length_str) = content_length.to_str() {
            if let Ok(length) = length_str.parse::<u64>() {
                if length < MIN_COMPRESS_SIZE {
                    return false;
                }
            }
        }
    }

    // technically redundant with check outside of the call, but kept here
    // because it's logically part of "should compress?" question
    is_compressible_content_type(response_headers)
}

/// Minimum size in bytes for a response to be compressed.
/// Responses smaller than this won't benefit from compression and may actually get larger.
pub(crate) const MIN_COMPRESS_SIZE: u64 = 512;

/// Applies gzip compression to a response using streaming compression.
/// This function wraps the response body in a gzip encoder that compresses data
/// as it's being sent, avoiding the need to buffer the entire response in memory.
/// If the body has a known exact size smaller than MIN_COMPRESS_SIZE, compression is skipped.
pub fn apply_gzip_compression(response: Response<Body>) -> Response<Body> {
    let (mut parts, body) = response.into_parts();

    let size_hint = body.size_hint();
    if let Some(exact_size) = size_hint.exact() {
        if exact_size == 0 || exact_size < MIN_COMPRESS_SIZE {
            return Response::from_parts(parts, body);
        }
    }

    // Transform body into a compressed stream:
    // Body -> Stream<Bytes> -> AsyncRead -> GzipEncoder -> Stream<Bytes> -> Body
    let data_stream = body.into_data_stream();
    let io_stream = data_stream
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e));
    let async_read = StreamReader::new(io_stream);
    let gzip_encoder = GzipEncoder::new(tokio::io::BufReader::new(async_read));
    let compressed_stream = ReaderStream::new(gzip_encoder);

    let compressed_body = Body::wrap(http_body_util::StreamBody::new(
        compressed_stream.map(|result| {
            result.map(Frame::data).map_err(|e| {
                Box::new(e) as Box<dyn std::error::Error + Send + Sync>
            })
        }),
    ));

    parts.headers.insert(
        http::header::CONTENT_ENCODING,
        HeaderValue::from_static("gzip"),
    );

    // Vary header is critical for caching - prevents serving compressed
    // responses to clients that don't accept gzip
    add_vary_header(&mut parts.headers);

    // because we're streaming, we can't handle ranges and we don't know the
    // length of the response ahead of time
    parts.headers.remove(http::header::ACCEPT_RANGES);
    parts.headers.remove(http::header::CONTENT_LENGTH);

    Response::from_parts(parts, compressed_body)
}

fn header_value_contains_accept_encoding(value: &HeaderValue) -> bool {
    value.to_str().is_ok_and(|vary| {
        vary.split(',')
            .any(|v| v.trim().eq_ignore_ascii_case("accept-encoding"))
    })
}

/// Adds the Vary: Accept-Encoding header to a response if not already present.
/// This is critical for correct caching behavior with intermediate caches.
pub fn add_vary_header(headers: &mut HeaderMap<HeaderValue>) {
    let vary_values = headers.get_all(http::header::VARY);

    // can't and shouldn't add anything if we already have "*"
    // https://datatracker.ietf.org/doc/html/rfc7231#section-7.1.4
    if vary_values.iter().any(|v| v == "*") {
        return;
    }

    if !vary_values.iter().any(header_value_contains_accept_encoding) {
        headers.append(
            http::header::VARY,
            HeaderValue::from_static("Accept-Encoding"),
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use http::header::{
        ACCEPT_ENCODING, ACCEPT_RANGES, CONTENT_ENCODING, CONTENT_LENGTH,
        CONTENT_RANGE, CONTENT_TYPE, VARY,
    };
    use http::Extensions;

    fn v(s: &'static str) -> HeaderValue {
        HeaderValue::from_static(s)
    }

    #[test]
    fn test_accepts_gzip_encoding_basic() {
        let mut headers = HeaderMap::new();
        headers.insert(ACCEPT_ENCODING, v("gzip"));
        assert!(accepts_gzip_encoding(&headers));
    }

    #[test]
    fn test_should_compress_response_rejects_content_range() {
        let request_method = http::Method::GET;
        let mut request_headers = HeaderMap::new();
        request_headers.insert(ACCEPT_ENCODING, v("gzip"));

        let response_status = http::StatusCode::OK;
        let mut response_headers = HeaderMap::new();
        response_headers.insert(CONTENT_TYPE, v("application/json"));
        response_headers.insert(CONTENT_RANGE, v("bytes 0-100/200"));

        let response_extensions = Extensions::new();

        assert!(!should_compress_response(
            &request_method,
            &request_headers,
            response_status,
            &response_headers,
            &response_extensions,
        ));
    }

    #[test]
    fn test_should_compress_response_respects_content_length_threshold() {
        let request_method = http::Method::GET;
        let mut request_headers = HeaderMap::new();
        request_headers.insert(ACCEPT_ENCODING, v("gzip"));

        let response_status = http::StatusCode::OK;
        let mut response_headers = HeaderMap::new();
        response_headers.insert(CONTENT_TYPE, v("application/json"));
        response_headers.insert(
            CONTENT_LENGTH,
            HeaderValue::from_str(&(MIN_COMPRESS_SIZE - 1).to_string())
                .unwrap(),
        );

        let response_extensions = Extensions::new();

        assert!(!should_compress_response(
            &request_method,
            &request_headers,
            response_status,
            &response_headers,
            &response_extensions,
        ));
    }

    #[test]
    fn test_apply_gzip_compression_removes_accept_ranges_and_sets_vary() {
        let body = "x".repeat((MIN_COMPRESS_SIZE + 10) as usize);
        let response = Response::builder()
            .header(CONTENT_TYPE, "application/json")
            .header(ACCEPT_RANGES, "bytes")
            .body(Body::from(body))
            .unwrap();

        let compressed = apply_gzip_compression(response);
        let headers = compressed.headers();

        let gzip = v("gzip");
        assert_eq!(headers.get(CONTENT_ENCODING), Some(&gzip));
        assert!(!headers.contains_key(ACCEPT_RANGES));

        let vary_values: Vec<_> = headers
            .get_all(VARY)
            .iter()
            .map(|value| value.to_str().unwrap().to_string())
            .collect();
        assert!(vary_values
            .iter()
            .any(|value| value.eq_ignore_ascii_case("accept-encoding")));
    }

    #[test]
    fn test_apply_gzip_compression_avoids_duplicate_vary_entries() {
        let body = "x".repeat((MIN_COMPRESS_SIZE + 10) as usize);
        let response = Response::builder()
            .header(CONTENT_TYPE, "application/json")
            .header(VARY, "Accept-Encoding, Accept-Language")
            .body(Body::from(body))
            .unwrap();

        let compressed = apply_gzip_compression(response);
        let mut accept_encoding_count = 0;
        for value in compressed.headers().get_all(VARY).iter() {
            let text = value.to_str().unwrap();
            accept_encoding_count += text
                .split(',')
                .filter(|v| v.trim().eq_ignore_ascii_case("accept-encoding"))
                .count();
        }

        assert_eq!(accept_encoding_count, 1);
    }

    #[test]
    fn test_accepts_gzip_encoding_with_positive_quality() {
        let mut headers = HeaderMap::new();
        headers.insert(ACCEPT_ENCODING, HeaderValue::from_static("gzip;q=0.8"));
        assert!(accepts_gzip_encoding(&headers));
    }

    #[test]
    fn test_accepts_gzip_encoding_rejects_zero_quality() {
        let mut headers = HeaderMap::new();
        headers.insert(ACCEPT_ENCODING, HeaderValue::from_static("gzip;q=0"));
        assert!(!accepts_gzip_encoding(&headers));
    }

    #[test]
    fn test_accepts_gzip_encoding_wildcard() {
        let mut headers = HeaderMap::new();
        headers.insert(ACCEPT_ENCODING, v("*"));
        assert!(accepts_gzip_encoding(&headers));
    }

    #[test]
    fn test_accepts_gzip_encoding_wildcard_with_quality() {
        let mut headers = HeaderMap::new();
        headers.insert(ACCEPT_ENCODING, v("*;q=0.5"));
        assert!(accepts_gzip_encoding(&headers));
    }

    #[test]
    fn test_accepts_gzip_encoding_wildcard_rejected() {
        let mut headers = HeaderMap::new();
        headers.insert(ACCEPT_ENCODING, v("*;q=0"));
        assert!(!accepts_gzip_encoding(&headers));
    }

    #[test]
    fn test_accepts_gzip_encoding_multiple_encodings() {
        let mut headers = HeaderMap::new();
        headers.insert(ACCEPT_ENCODING, v("deflate, gzip, br"));
        assert!(accepts_gzip_encoding(&headers));
    }

    #[test]
    fn test_accepts_gzip_encoding_gzip_takes_precedence_over_wildcard() {
        // Explicit gzip rejection should override wildcard acceptance
        let mut headers = HeaderMap::new();
        headers.insert(ACCEPT_ENCODING, v("*;q=1.0, gzip;q=0"));
        assert!(!accepts_gzip_encoding(&headers));
    }

    #[test]
    fn test_accepts_gzip_encoding_gzip_acceptance_overrides_wildcard_rejection()
    {
        // Explicit gzip acceptance should work even if wildcard is rejected
        let mut headers = HeaderMap::new();
        headers.insert(ACCEPT_ENCODING, v("*;q=0, gzip;q=1.0"));
        assert!(accepts_gzip_encoding(&headers));
    }

    #[test]
    fn test_accepts_gzip_encoding_prefers_highest_quality() {
        let mut headers = HeaderMap::new();
        headers.insert(ACCEPT_ENCODING, v("gzip;q=0, gzip;q=0.5"));
        assert!(accepts_gzip_encoding(&headers));

        let mut headers = HeaderMap::new();
        headers.insert(ACCEPT_ENCODING, v("gzip;q=0.8, gzip;q=0"));
        assert!(accepts_gzip_encoding(&headers));

        let mut headers = HeaderMap::new();
        headers.insert(ACCEPT_ENCODING, v("gzip;q=0, *;q=1"));
        assert!(!accepts_gzip_encoding(&headers));
    }

    #[test]
    fn test_accepts_gzip_encoding_case_insensitive() {
        let mut headers = HeaderMap::new();
        headers.insert(ACCEPT_ENCODING, v("GZIP"));
        assert!(accepts_gzip_encoding(&headers));

        let mut headers = HeaderMap::new();
        headers.insert(ACCEPT_ENCODING, v("GzIp"));
        assert!(accepts_gzip_encoding(&headers));
    }

    #[test]
    fn test_accepts_gzip_encoding_no_header() {
        let headers = HeaderMap::new();
        assert!(!accepts_gzip_encoding(&headers));
    }

    #[test]
    fn test_accepts_gzip_encoding_with_spaces() {
        let mut headers = HeaderMap::new();
        headers.insert(ACCEPT_ENCODING, v("deflate , gzip ; q=0.8 , br"));
        assert!(accepts_gzip_encoding(&headers));
    }

    #[test]
    fn test_accepts_gzip_encoding_malformed_quality() {
        // If quality parsing fails, should default to 1.0
        let mut headers = HeaderMap::new();
        headers.insert(ACCEPT_ENCODING, v("gzip;q=invalid"));
        assert!(accepts_gzip_encoding(&headers));
    }

    #[test]
    fn test_accepts_gzip_encoding_ignores_malformed_parameters() {
        let mut headers = HeaderMap::new();
        headers.insert(ACCEPT_ENCODING, v("gzip;foo"));
        assert!(accepts_gzip_encoding(&headers));
    }

    #[test]
    fn test_accepts_gzip_encoding_non_finite_quality_defaults() {
        let mut headers = HeaderMap::new();
        headers.insert(ACCEPT_ENCODING, v("gzip;q=NaN"));
        assert!(accepts_gzip_encoding(&headers));
    }

    #[test]
    fn test_accepts_gzip_encoding_multiple_headers() {
        // RFC 9110 §5.3: multiple header lines are equivalent to comma-separated
        let mut headers = HeaderMap::new();
        headers.insert(ACCEPT_ENCODING, v("deflate"));
        headers.append(ACCEPT_ENCODING, v("gzip"));
        assert!(accepts_gzip_encoding(&headers));
    }

    #[test]
    fn test_should_compress_response_basic() {
        let method = http::Method::GET;
        let mut request_headers = HeaderMap::new();
        request_headers.insert(ACCEPT_ENCODING, v("gzip"));
        let status = http::StatusCode::OK;
        let mut response_headers = HeaderMap::new();
        response_headers.insert(CONTENT_TYPE, v("application/json"));
        let extensions = http::Extensions::new();

        assert!(should_compress_response(
            &method,
            &request_headers,
            status,
            &response_headers,
            &extensions
        ));
    }

    #[test]
    fn test_should_compress_response_head_method() {
        let method = http::Method::HEAD;
        let mut request_headers = HeaderMap::new();
        request_headers.insert(ACCEPT_ENCODING, v("gzip"));
        let status = http::StatusCode::OK;
        let mut response_headers = HeaderMap::new();
        response_headers.insert(CONTENT_TYPE, v("application/json"));
        let extensions = http::Extensions::new();

        assert!(!should_compress_response(
            &method,
            &request_headers,
            status,
            &response_headers,
            &extensions
        ));
    }

    #[test]
    fn test_should_compress_response_no_content() {
        let method = http::Method::GET;
        let mut request_headers = HeaderMap::new();
        request_headers.insert(ACCEPT_ENCODING, v("gzip"));
        let status = http::StatusCode::NO_CONTENT;
        let response_headers = HeaderMap::new();
        let extensions = http::Extensions::new();

        assert!(!should_compress_response(
            &method,
            &request_headers,
            status,
            &response_headers,
            &extensions
        ));
    }

    #[test]
    fn test_should_compress_response_not_modified() {
        let method = http::Method::GET;
        let mut request_headers = HeaderMap::new();
        request_headers.insert(ACCEPT_ENCODING, v("gzip"));
        let status = http::StatusCode::NOT_MODIFIED;
        let response_headers = HeaderMap::new();
        let extensions = http::Extensions::new();

        assert!(!should_compress_response(
            &method,
            &request_headers,
            status,
            &response_headers,
            &extensions
        ));
    }

    #[test]
    fn test_should_compress_response_partial_content() {
        let method = http::Method::GET;
        let mut request_headers = HeaderMap::new();
        request_headers.insert(ACCEPT_ENCODING, v("gzip"));
        let status = http::StatusCode::PARTIAL_CONTENT;
        let mut response_headers = HeaderMap::new();
        response_headers.insert(CONTENT_TYPE, v("application/json"));
        let extensions = http::Extensions::new();

        assert!(!should_compress_response(
            &method,
            &request_headers,
            status,
            &response_headers,
            &extensions
        ));
    }

    #[test]
    fn test_should_compress_response_no_accept_encoding() {
        let method = http::Method::GET;
        let request_headers = HeaderMap::new();
        let status = http::StatusCode::OK;
        let mut response_headers = HeaderMap::new();
        response_headers.insert(CONTENT_TYPE, v("application/json"));
        let extensions = http::Extensions::new();

        assert!(!should_compress_response(
            &method,
            &request_headers,
            status,
            &response_headers,
            &extensions
        ));
    }

    #[test]
    fn test_should_compress_response_already_encoded() {
        let method = http::Method::GET;
        let mut request_headers = HeaderMap::new();
        request_headers.insert(ACCEPT_ENCODING, v("gzip"));
        let status = http::StatusCode::OK;
        let mut response_headers = HeaderMap::new();
        response_headers.insert(CONTENT_TYPE, v("application/json"));
        response_headers.insert(CONTENT_ENCODING, v("br"));
        let extensions = http::Extensions::new();

        assert!(!should_compress_response(
            &method,
            &request_headers,
            status,
            &response_headers,
            &extensions
        ));
    }

    #[test]
    fn test_should_compress_response_no_compression_extension() {
        let method = http::Method::GET;
        let mut request_headers = HeaderMap::new();
        request_headers.insert(ACCEPT_ENCODING, v("gzip"));
        let status = http::StatusCode::OK;
        let mut response_headers = HeaderMap::new();
        response_headers.insert(CONTENT_TYPE, v("application/json"));
        let mut extensions = http::Extensions::new();
        extensions.insert(NoCompression);

        assert!(!should_compress_response(
            &method,
            &request_headers,
            status,
            &response_headers,
            &extensions
        ));
    }

    #[test]
    fn test_should_compress_response_no_content_type() {
        let method = http::Method::GET;
        let mut request_headers = HeaderMap::new();
        request_headers.insert(ACCEPT_ENCODING, v("gzip"));
        let status = http::StatusCode::OK;
        let response_headers = HeaderMap::new();
        let extensions = http::Extensions::new();

        assert!(!should_compress_response(
            &method,
            &request_headers,
            status,
            &response_headers,
            &extensions
        ));
    }

    #[test]
    fn test_should_compress_response_sse() {
        let method = http::Method::GET;
        let mut request_headers = HeaderMap::new();
        request_headers.insert(ACCEPT_ENCODING, v("gzip"));
        let status = http::StatusCode::OK;
        let mut response_headers = HeaderMap::new();
        response_headers.insert(CONTENT_TYPE, v("TEXT/EVENT-STREAM"));
        let extensions = http::Extensions::new();

        assert!(!should_compress_response(
            &method,
            &request_headers,
            status,
            &response_headers,
            &extensions
        ));
    }

    #[test]
    fn test_should_compress_response_compressible_content_types() {
        let method = http::Method::GET;
        let mut request_headers = HeaderMap::new();
        request_headers.insert(ACCEPT_ENCODING, v("gzip"));
        let status = http::StatusCode::OK;
        let extensions = http::Extensions::new();

        // Test various compressible content types
        let compressible_types = vec![
            "application/json",
            "APPLICATION/JSON",
            "text/plain",
            "text/html",
            "text/css",
            "application/xml",
            "application/javascript",
            "application/x-javascript",
            "application/problem+json",
            "application/problem+JSON",
            "application/hal+json",
            "application/soap+xml",
            "application/SOAP+XML",
        ];

        for content_type in compressible_types {
            let mut response_headers = HeaderMap::new();
            response_headers.insert(
                CONTENT_TYPE,
                HeaderValue::from_str(content_type).unwrap(),
            );

            assert!(
                should_compress_response(
                    &method,
                    &request_headers,
                    status,
                    &response_headers,
                    &extensions
                ),
                "Expected {} to be compressible",
                content_type
            );
        }
    }

    #[test]
    fn test_should_compress_response_non_compressible_content_types() {
        let method = http::Method::GET;
        let mut request_headers = HeaderMap::new();
        request_headers.insert(ACCEPT_ENCODING, v("gzip"));
        let status = http::StatusCode::OK;
        let extensions = http::Extensions::new();

        // Test various non-compressible content types
        let non_compressible_types = vec![
            "image/png",
            "image/jpeg",
            "video/mp4",
            "application/pdf",
            "application/zip",
            "application/gzip",
            "application/octet-stream",
        ];

        for content_type in non_compressible_types {
            let mut response_headers = HeaderMap::new();
            response_headers.insert(
                CONTENT_TYPE,
                HeaderValue::from_str(content_type).unwrap(),
            );

            assert!(
                !should_compress_response(
                    &method,
                    &request_headers,
                    status,
                    &response_headers,
                    &extensions
                ),
                "Expected {} to not be compressible",
                content_type
            );
        }
    }
}