tako-rs-plugins 2.0.0

Internal plugin and concrete-middleware implementations for tako-rs. Use the `tako-rs` umbrella crate instead.
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
#![cfg_attr(docsrs, doc(cfg(feature = "plugins")))]
//! HTTP response compression plugin supporting multiple algorithms and streaming.
//!
//! This module provides comprehensive HTTP response compression functionality for Tako
//! applications. It supports multiple compression algorithms including Gzip, Brotli, DEFLATE,
//! and optionally Zstandard, with configurable compression levels and streaming capabilities.
//! The plugin automatically negotiates compression based on client Accept-Encoding headers
//! and applies compression selectively based on content type, response size, and status code.
//!
//! The compression plugin can be applied at both router-level (all routes) and route-level
//! (specific routes), allowing different compression settings for different endpoints.
//!
//! # Examples
//!
//! ```rust
//! use tako::plugins::compression::CompressionBuilder;
//! use tako::plugins::TakoPlugin;
//! use tako::router::Router;
//! use tako::Method;
//!
//! async fn handler(_req: tako::types::Request) -> &'static str {
//!     "Response data"
//! }
//!
//! async fn api_handler(_req: tako::types::Request) -> &'static str {
//!     "Large API response"
//! }
//!
//! let mut router = Router::new();
//!
//! // Router-level: Basic compression setup (applied to all routes)
//! let compression = CompressionBuilder::new()
//!     .enable_gzip(true)
//!     .enable_brotli(true)
//!     .min_size(1024)
//!     .build();
//! router.plugin(compression);
//!
//! // Route-level: Advanced compression for specific API endpoint
//! let api_route = router.route(Method::GET, "/api/large-data", api_handler);
//! let advanced = CompressionBuilder::new()
//!     .enable_gzip(true)
//!     .gzip_level(9)
//!     .enable_brotli(true)
//!     .brotli_level(11)
//!     .enable_stream(true)
//!     .min_size(512)
//!     .build();
//! api_route.plugin(advanced);
//! ```

use std::io::Read;
use std::io::Write;

use anyhow::Result;
use async_trait::async_trait;
use bytes::Bytes;
use flate2::Compression as GzLevel;
use flate2::write::DeflateEncoder;
use flate2::write::GzEncoder;
use http::HeaderValue;
use http::StatusCode;
use http::header::ACCEPT_ENCODING;
use http::header::CONTENT_ENCODING;
use http::header::CONTENT_LENGTH;
use http::header::CONTENT_TYPE;
use http::header::VARY;
use http_body_util::BodyExt;

pub mod brotli_stream;
pub mod deflate_stream;
pub mod gzip_stream;
pub mod zstd_stream;

use tako_rs_core::body::TakoBody;
use tako_rs_core::middleware::Next;
use tako_rs_core::plugins::TakoPlugin;
use tako_rs_core::responder::Responder;
use tako_rs_core::router::Router;
use tako_rs_core::types::Request;
use tako_rs_core::types::Response;
#[cfg(feature = "zstd")]
use zstd::stream::encode_all as zstd_encode;

use crate::plugins::compression::brotli_stream::stream_brotli;
use crate::plugins::compression::deflate_stream::stream_deflate;
use crate::plugins::compression::gzip_stream::stream_gzip;
#[cfg(feature = "zstd")]
use crate::plugins::compression::zstd_stream::stream_zstd;

/// Supported HTTP compression encoding algorithms.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Encoding {
  /// Gzip compression (RFC 1952) - widely supported, good compression ratio.
  Gzip,
  /// Brotli compression (RFC 7932) - excellent compression ratio, modern browsers.
  Brotli,
  /// DEFLATE compression (RFC 1951) - fast compression, good compatibility.
  Deflate,
  /// Zstandard compression - high performance, excellent ratio (requires zstd feature).
  #[cfg(feature = "zstd")]
  #[cfg_attr(docsrs, doc(cfg(feature = "zstd")))]
  Zstd,
}

impl Encoding {
  /// Returns the HTTP Content-Encoding header value for this compression algorithm.
  fn as_str(&self) -> &'static str {
    match self {
      Encoding::Gzip => "gzip",
      Encoding::Brotli => "br",
      Encoding::Deflate => "deflate",
      #[cfg(feature = "zstd")]
      Encoding::Zstd => "zstd",
    }
  }
}

/// Content-type matching policy.
#[derive(Clone, Default)]
pub enum ContentTypePolicy {
  /// Default heuristic: text/*, anything containing `json`, `javascript`, `xml`.
  #[default]
  Default,
  /// Exact MIME types (case-insensitive). E.g. `["application/json", "text/html"]`.
  Exact(Vec<String>),
  /// MIME prefixes (case-insensitive). E.g. `["text/", "application/x-json-"]`.
  Prefix(Vec<String>),
  /// Caller-provided predicate. Receives the verbatim header value.
  Custom(std::sync::Arc<dyn Fn(&str) -> bool + Send + Sync + 'static>),
}

impl ContentTypePolicy {
  fn matches(&self, ct: &str) -> bool {
    let ct = ct.split(';').next().unwrap_or(ct).trim();
    match self {
      Self::Default => {
        ct.starts_with("text/")
          || ct.contains("json")
          || ct.contains("javascript")
          || ct.contains("xml")
      }
      Self::Exact(list) => list.iter().any(|m| m.eq_ignore_ascii_case(ct)),
      Self::Prefix(list) => {
        let lc = ct.to_ascii_lowercase();
        list.iter().any(|m| lc.starts_with(&m.to_ascii_lowercase()))
      }
      Self::Custom(f) => f(ct),
    }
  }
}

/// Configuration settings for HTTP response compression.
#[derive(Clone)]
pub struct Config {
  /// List of enabled compression encodings in preference order.
  pub enabled: Vec<Encoding>,
  /// Minimum response size in bytes required for compression to be applied.
  pub min_size: usize,
  /// Gzip compression level (1-9, where 9 is maximum compression).
  pub gzip_level: u32,
  /// Brotli compression level (1-11, where 11 is maximum compression).
  pub brotli_level: u32,
  /// DEFLATE compression level (1-9, where 9 is maximum compression).
  pub deflate_level: u32,
  /// Zstandard compression level (1-22, where 22 is maximum compression).
  #[cfg(feature = "zstd")]
  pub zstd_level: i32,
  /// Whether to use streaming compression instead of buffering entire responses.
  pub stream: bool,
  /// Which response content types are eligible for compression.
  pub content_types: ContentTypePolicy,
  /// When true (default), responses that look like they carry authenticated
  /// secrets (Set-Cookie present, or the request had Authorization /
  /// Proxy-Authorization / Cookie) are *not* compressed. This is the
  /// canonical CRIME / BREACH mitigation. Disable explicitly with
  /// [`CompressionBuilder::protect_sensitive`] when you have other
  /// mitigations (e.g. per-response random padding or rotated CSRF tokens).
  pub protect_sensitive: bool,
}

impl Default for Config {
  /// Provides sensible default compression configuration.
  fn default() -> Self {
    Self {
      enabled: vec![Encoding::Gzip, Encoding::Brotli, Encoding::Deflate],
      min_size: 1024,
      gzip_level: 5,
      brotli_level: 5,
      deflate_level: 5,
      #[cfg(feature = "zstd")]
      zstd_level: 3,
      stream: false,
      content_types: ContentTypePolicy::default(),
      protect_sensitive: true,
    }
  }
}

/// Builder for configuring HTTP response compression settings.
///
/// `CompressionBuilder` provides a fluent API for constructing compression plugin
/// configurations. It allows selective enabling/disabling of compression algorithms,
/// setting compression levels, and configuring behavior options like streaming and
/// minimum response size thresholds.
///
/// # Examples
///
/// ```rust
/// use tako::plugins::compression::CompressionBuilder;
///
/// // Basic setup with default settings
/// let basic = CompressionBuilder::new().build();
///
/// // Custom configuration
/// let custom = CompressionBuilder::new()
///     .enable_gzip(true)
///     .gzip_level(8)
///     .enable_brotli(true)
///     .brotli_level(6)
///     .enable_deflate(false)
///     .min_size(2048)
///     .enable_stream(true)
///     .build();
/// ```
pub struct CompressionBuilder(Config);

impl Default for CompressionBuilder {
  fn default() -> Self {
    Self::new()
  }
}

impl CompressionBuilder {
  /// Creates a new compression configuration builder with default settings.
  pub fn new() -> Self {
    Self(Config::default())
  }

  /// Enables or disables Gzip compression.
  pub fn enable_gzip(mut self, yes: bool) -> Self {
    if yes && !self.0.enabled.contains(&Encoding::Gzip) {
      self.0.enabled.push(Encoding::Gzip);
    }
    if !yes {
      self.0.enabled.retain(|e| *e != Encoding::Gzip);
    }
    self
  }

  /// Enables or disables Brotli compression.
  pub fn enable_brotli(mut self, yes: bool) -> Self {
    if yes && !self.0.enabled.contains(&Encoding::Brotli) {
      self.0.enabled.push(Encoding::Brotli);
    }
    if !yes {
      self.0.enabled.retain(|e| *e != Encoding::Brotli);
    }
    self
  }

  /// Enables or disables DEFLATE compression.
  pub fn enable_deflate(mut self, yes: bool) -> Self {
    if yes && !self.0.enabled.contains(&Encoding::Deflate) {
      self.0.enabled.push(Encoding::Deflate);
    }
    if !yes {
      self.0.enabled.retain(|e| *e != Encoding::Deflate);
    }
    self
  }

  /// Enables or disables Zstandard compression (requires zstd feature).
  #[cfg(feature = "zstd")]
  #[cfg_attr(docsrs, doc(cfg(feature = "zstd")))]
  pub fn enable_zstd(mut self, yes: bool) -> Self {
    if yes && !self.0.enabled.contains(&Encoding::Zstd) {
      self.0.enabled.push(Encoding::Zstd);
    }
    if !yes {
      self.0.enabled.retain(|e| *e != Encoding::Zstd);
    }
    self
  }

  /// Enables or disables streaming compression mode.
  pub fn enable_stream(mut self, stream: bool) -> Self {
    self.0.stream = stream;
    self
  }

  /// Sets the minimum response size threshold for compression.
  pub fn min_size(mut self, bytes: usize) -> Self {
    self.0.min_size = bytes;
    self
  }

  /// Replaces the content-type matching policy.
  pub fn content_types(mut self, policy: ContentTypePolicy) -> Self {
    self.0.content_types = policy;
    self
  }

  /// Sets the Gzip compression level (1-9).
  pub fn gzip_level(mut self, lvl: u32) -> Self {
    self.0.gzip_level = lvl.min(9);
    self
  }

  /// Sets the Brotli compression level (1-11).
  pub fn brotli_level(mut self, lvl: u32) -> Self {
    self.0.brotli_level = lvl.min(11);
    self
  }

  /// Sets the DEFLATE compression level (1-9).
  pub fn deflate_level(mut self, lvl: u32) -> Self {
    self.0.deflate_level = lvl.min(9);
    self
  }

  /// Sets the Zstandard compression level (1-22, requires zstd feature).
  #[cfg(feature = "zstd")]
  #[cfg_attr(docsrs, doc(cfg(feature = "zstd")))]
  pub fn zstd_level(mut self, lvl: i32) -> Self {
    self.0.zstd_level = lvl.clamp(1, 22);
    self
  }

  /// Toggle the CRIME/BREACH mitigation. Default is `true`: responses
  /// containing `Set-Cookie`, or whose request carried `Authorization`,
  /// `Proxy-Authorization`, or `Cookie`, are sent uncompressed. Setting this
  /// to `false` re-enables compression unconditionally โ€” only do so if you
  /// have an alternative mitigation (per-response padding, rotated tokens).
  pub fn protect_sensitive(mut self, on: bool) -> Self {
    self.0.protect_sensitive = on;
    self
  }

  /// Builds the compression plugin with the configured settings.
  pub fn build(self) -> CompressionPlugin {
    CompressionPlugin { cfg: self.0 }
  }
}

pub enum CompressionResponse<R>
where
  R: Responder,
{
  /// Plain, uncompressed response.
  Plain(R),
  /// Compressed or streaming response.
  Stream(R),
}

impl<R> Responder for CompressionResponse<R>
where
  R: Responder,
{
  fn into_response(self) -> Response {
    match self {
      CompressionResponse::Plain(r) => r.into_response(),
      CompressionResponse::Stream(r) => r.into_response(),
    }
  }
}

/// HTTP response compression plugin for Tako applications.
///
/// `CompressionPlugin` provides automatic response compression based on client
/// Accept-Encoding headers and configurable compression algorithms. It supports
/// multiple compression formats, streaming compression, and intelligent content
/// type detection to optimize bandwidth usage and response times.
///
/// # Examples
///
/// ```rust
/// use tako::plugins::compression::{CompressionPlugin, CompressionBuilder};
/// use tako::plugins::TakoPlugin;
/// use tako::router::Router;
///
/// // Use default settings
/// let compression = CompressionPlugin::default();
/// let mut router = Router::new();
/// router.plugin(compression);
///
/// // Custom configuration
/// let custom = CompressionBuilder::new()
///     .enable_gzip(true)
///     .enable_brotli(true)
///     .min_size(2048)
///     .build();
/// router.plugin(custom);
/// ```
#[derive(Clone)]
#[doc(alias = "compression")]
#[doc(alias = "gzip")]
#[doc(alias = "brotli")]
#[doc(alias = "deflate")]
pub struct CompressionPlugin {
  cfg: Config,
}

impl Default for CompressionPlugin {
  /// Creates a compression plugin with default configuration settings.
  fn default() -> Self {
    Self {
      cfg: Config::default(),
    }
  }
}

#[async_trait]
impl TakoPlugin for CompressionPlugin {
  /// Returns the plugin name for identification and debugging.
  fn name(&self) -> &'static str {
    "CompressionPlugin"
  }

  /// Sets up the compression plugin by registering middleware with the router.
  fn setup(&self, router: &Router) -> Result<()> {
    let cfg = self.cfg.clone();
    router.middleware(move |req, next| {
      let cfg = cfg.clone();
      let stream = cfg.stream;
      async move {
        if stream {
          CompressionResponse::Stream(
            compress_stream_middleware(req, next, cfg)
              .await
              .into_response(),
          )
        } else {
          CompressionResponse::Plain(compress_middleware(req, next, cfg).await.into_response())
        }
      }
    });
    Ok(())
  }
}

/// Middleware function for buffered response compression.
///
/// This middleware compresses entire response bodies in memory before sending them
/// to clients. It's more memory-intensive than streaming compression but may have
/// better compression ratios for smaller responses.
async fn compress_middleware(req: Request, next: Next, cfg: Config) -> impl Responder {
  let accepted = req
    .headers()
    .get(ACCEPT_ENCODING)
    .and_then(|v| v.to_str().ok())
    .unwrap_or("")
    .to_ascii_lowercase();
  let request_is_authenticated = cfg.protect_sensitive && request_carries_credentials(&req);

  // Process the request and get the response.
  let mut resp = next.run(req).await;
  let chosen = choose_encoding(&accepted, &cfg.enabled);

  // Skip compression for non-successful responses or if already encoded.
  let status = resp.status();
  if !(status.is_success() || status == StatusCode::NOT_MODIFIED) {
    return resp.into_response();
  }

  if resp.headers().contains_key(CONTENT_ENCODING) {
    return resp.into_response();
  }

  // CRIME/BREACH mitigation: compressing an authenticated response next to
  // attacker-controlled body content leaks the secret via the ciphertext
  // length. Skip compression entirely if either the request looked
  // authenticated or the response carries credentials.
  if cfg.protect_sensitive
    && (request_is_authenticated || resp.headers().contains_key(http::header::SET_COOKIE))
  {
    return resp.into_response();
  }

  // Skip compression for unsupported content types.
  if let Some(ct) = resp.headers().get(CONTENT_TYPE) {
    let ct = ct.to_str().unwrap_or("");
    if !cfg.content_types.matches(ct) {
      return resp.into_response();
    }
  }

  // The response is now compression-eligible. Always advertise that the
  // representation depends on `Accept-Encoding` so caches don't serve a
  // wrongly-encoded variant to a peer with different `Accept-Encoding`.
  ensure_vary_accept_encoding(resp.headers_mut());

  // Collect the response body and check its size.
  //
  // PPL-10: on body-collect failure the previous code overwrote the
  // handler's status with 502 and dropped the body. That obliterated any
  // intentional non-2xx the handler had produced โ€” a 401, 404, or 503 from
  // the handler showed up to clients as 502, distorting downstream
  // metrics and observability. The collect-failure was specifically a
  // *compression-side* problem (the middleware could not buffer the body
  // for compression), not a downstream-gateway error.
  //
  // Better: keep the handler's original status, strip `Content-Encoding`
  // (we won't be compressing after all), warn so operators see the
  // failure, and return an empty body. The status truth survives; the
  // compression attempt is silently elided.
  let body_bytes = if let Ok(c) = resp.body_mut().collect().await {
    c.to_bytes()
  } else {
    tracing::warn!(
      "compression middleware: response body collect() failed; \
       returning original status with empty body (no compression)"
    );
    resp.headers_mut().remove(http::header::CONTENT_ENCODING);
    *resp.body_mut() = TakoBody::empty();
    return resp.into_response();
  };
  if body_bytes.len() < cfg.min_size {
    *resp.body_mut() = TakoBody::from(body_bytes);
    return resp.into_response();
  }

  // Compress the response body if a suitable encoding is chosen. If the
  // encoder fails (out-of-memory, malformed input, etc.) we MUST NOT set
  // `Content-Encoding` to the chosen scheme while serving the raw body โ€”
  // the client would attempt to decode plain bytes as gzip/brotli and
  // fail. Track success explicitly and only advertise the encoding when
  // the compressed buffer was produced.
  if let Some(enc) = chosen {
    let compressed = match enc {
      Encoding::Gzip => compress_gzip(&body_bytes, cfg.gzip_level).ok(),
      Encoding::Brotli => compress_brotli(&body_bytes, cfg.brotli_level).ok(),
      Encoding::Deflate => compress_deflate(&body_bytes, cfg.deflate_level).ok(),
      #[cfg(feature = "zstd")]
      Encoding::Zstd => compress_zstd(&body_bytes, cfg.zstd_level).ok(),
    };
    if let Some(buf) = compressed {
      *resp.body_mut() = TakoBody::from(Bytes::from(buf));
      resp
        .headers_mut()
        .insert(CONTENT_ENCODING, HeaderValue::from_static(enc.as_str()));
      resp.headers_mut().remove(CONTENT_LENGTH);
    } else {
      tracing::warn!(
        encoding = enc.as_str(),
        "compression failed; serving identity"
      );
      *resp.body_mut() = TakoBody::from(body_bytes);
      resp.headers_mut().remove(CONTENT_ENCODING);
    }
  } else {
    *resp.body_mut() = TakoBody::from(body_bytes);
  }

  resp.into_response()
}

/// Middleware function for streaming response compression.
///
/// This middleware compresses response bodies on-the-fly as they stream to clients.
/// It's more memory-efficient than buffered compression but requires compatible
/// response body types that support streaming.
///
/// **Internal:** drop-shipped through `CompressionPlugin::setup` only. The
/// previous `pub` visibility was accidental โ€” not re-exported from the
/// umbrella crate and not part of the documented API. Demoted to
/// `pub(crate)` so the public surface stays committed to the plugin entry
/// point. If you need this on its own use `CompressionPlugin` and let the
/// builder install it.
pub(crate) async fn compress_stream_middleware(
  req: Request,
  next: Next,
  cfg: Config,
) -> impl Responder {
  // Parse the `Accept-Encoding` header to determine supported encodings.
  let accepted = req
    .headers()
    .get(ACCEPT_ENCODING)
    .and_then(|v| v.to_str().ok())
    .unwrap_or("")
    .to_ascii_lowercase();
  let request_is_authenticated = cfg.protect_sensitive && request_carries_credentials(&req);

  // Process the request and get the response.
  let mut resp = next.run(req).await;
  let chosen = choose_encoding(&accepted, &cfg.enabled);

  // Skip compression for non-successful responses or if already encoded.
  let status = resp.status();
  if !(status.is_success() || status == StatusCode::NOT_MODIFIED) {
    return resp.into_response();
  }

  if resp.headers().contains_key(CONTENT_ENCODING) {
    return resp.into_response();
  }

  // CRIME/BREACH mitigation: see `compress_middleware`.
  if cfg.protect_sensitive
    && (request_is_authenticated || resp.headers().contains_key(http::header::SET_COOKIE))
  {
    return resp.into_response();
  }

  // Skip compression for unsupported content types.
  if let Some(ct) = resp.headers().get(CONTENT_TYPE) {
    let ct = ct.to_str().unwrap_or("");
    if !cfg.content_types.matches(ct) {
      return resp.into_response();
    }
  }

  // The response is compression-eligible: advertise Vary regardless of whether we
  // actually apply an encoding, so caches key on `Accept-Encoding`.
  ensure_vary_accept_encoding(resp.headers_mut());

  // Estimate size from `Content-Length`.
  if let Some(len) = resp
    .headers()
    .get(CONTENT_LENGTH)
    .and_then(|v| v.to_str().ok())
    .and_then(|v| v.parse::<usize>().ok())
    && len < cfg.min_size
  {
    return resp.into_response();
  }

  if let Some(enc) = chosen {
    let body = std::mem::replace(resp.body_mut(), TakoBody::empty());
    let new_body = match enc {
      Encoding::Gzip => stream_gzip(body, cfg.gzip_level),
      Encoding::Brotli => stream_brotli(body, cfg.brotli_level),
      Encoding::Deflate => stream_deflate(body, cfg.deflate_level),
      #[cfg(feature = "zstd")]
      Encoding::Zstd => stream_zstd(body, cfg.zstd_level),
    };
    *resp.body_mut() = new_body;
    resp
      .headers_mut()
      .insert(CONTENT_ENCODING, HeaderValue::from_static(enc.as_str()));
    resp.headers_mut().remove(CONTENT_LENGTH);
  }

  resp.into_response()
}

/// Returns true if the request carries credentials that would make its
/// response a CRIME/BREACH target. The check is intentionally broad: any
/// auth header or cookie is treated as authenticated.
fn request_carries_credentials(req: &Request) -> bool {
  req.headers().contains_key(http::header::AUTHORIZATION)
    || req
      .headers()
      .contains_key(http::header::PROXY_AUTHORIZATION)
    || req.headers().contains_key(http::header::COOKIE)
}

/// Appends `Accept-Encoding` to the `Vary` header without duplicating it.
///
/// `Vary: Accept-Encoding` is required on every compression-eligible response
/// so shared caches don't serve a wrongly-encoded representation to a different
/// client.
fn ensure_vary_accept_encoding(headers: &mut http::HeaderMap) {
  let already_present = headers.get_all(VARY).iter().any(|v| {
    v.to_str().is_ok_and(|s| {
      s.split(',')
        .any(|tok| tok.trim().eq_ignore_ascii_case("Accept-Encoding"))
    })
  });
  if !already_present {
    headers.append(VARY, HeaderValue::from_static("Accept-Encoding"));
  }
}

/// Selects the best compression encoding based on client preferences and server capabilities.
///
/// Honors RFC 9110 quality values: a token with `q=0` is rejected, an unlisted
/// token defers to the wildcard `*` if present, otherwise it is unacceptable.
/// Server preference order is `br > gzip > deflate > zstd`.
fn choose_encoding(header: &str, enabled: &[Encoding]) -> Option<Encoding> {
  let parsed = parse_accept_encoding(header);
  // Pull `*` once โ€” it determines acceptance of any encoding not listed explicitly.
  let wildcard_q = parsed.iter().find(|(c, _)| c == "*").map(|(_, q)| *q);

  let acceptable = |enc: Encoding| -> bool {
    let name = enc.as_str();
    match parsed.iter().find(|(c, _)| c == name) {
      Some((_, q)) => *q > 0.0,
      None => wildcard_q.is_some_and(|q| q > 0.0),
    }
  };

  // Server preference order โ€” Brotli first for ratio, Gzip second for compatibility.
  let server_order: [Encoding; 3] = [Encoding::Brotli, Encoding::Gzip, Encoding::Deflate];
  for enc in server_order {
    if enabled.contains(&enc) && acceptable(enc) {
      return Some(enc);
    }
  }

  #[cfg(feature = "zstd")]
  {
    if enabled.contains(&Encoding::Zstd) && acceptable(Encoding::Zstd) {
      return Some(Encoding::Zstd);
    }
  }

  None
}

/// Parses an `Accept-Encoding` header into `(token, q)` pairs.
///
/// Tokens are lowercased. `q=` is honored when valid and absent โ†’ `1.0`.
///
/// PPL-15: per RFC 9110 / RFC 7231 ยง5.3, a malformed q-value (e.g.
/// `gzip;q=`, `gzip;q=banana`) means the entire entry MUST be ignored, not
/// silently defaulted to full strength. Previously a malformed q parsed to
/// `1.0`, so a client sending `gzip;q=` would erroneously get gzip as the
/// most preferred encoding even though they intended to disable it or
/// signal something else. Drop entries with a present-but-unparseable `q=`.
fn parse_accept_encoding(header: &str) -> Vec<(String, f32)> {
  header
    .split(',')
    .filter_map(|piece| {
      let piece = piece.trim();
      if piece.is_empty() {
        return None;
      }
      let mut parts = piece.split(';');
      let coding = parts.next()?.trim().to_ascii_lowercase();
      if coding.is_empty() {
        return None;
      }
      let mut q: f32 = 1.0;
      for param in parts {
        let param = param.trim();
        let qv = param
          .strip_prefix("q=")
          .or_else(|| param.strip_prefix("Q="));
        if let Some(qv) = qv {
          // Malformed q-value โ†’ drop the whole entry (RFC 9110).
          q = qv.parse().ok()?;
        }
      }
      Some((coding, q))
    })
    .collect()
}

/// Compresses data using Gzip algorithm.
fn compress_gzip(data: &[u8], lvl: u32) -> std::io::Result<Vec<u8>> {
  let mut enc = GzEncoder::new(Vec::new(), GzLevel::new(lvl));
  enc.write_all(data)?;
  enc.finish()
}

/// Compresses data using Brotli algorithm.
fn compress_brotli(data: &[u8], lvl: u32) -> std::io::Result<Vec<u8>> {
  let mut out = Vec::new();
  brotli::CompressorReader::new(data, 4096, lvl, 22)
    .read_to_end(&mut out)
    .map_err(|_| std::io::Error::other("Failed to compress data"))?;
  Ok(out)
}

/// Compresses data using DEFLATE algorithm.
fn compress_deflate(data: &[u8], lvl: u32) -> std::io::Result<Vec<u8>> {
  let mut enc = DeflateEncoder::new(Vec::new(), flate2::Compression::new(lvl));
  enc.write_all(data)?;
  enc.finish()
}

/// Compresses data using Zstandard algorithm (requires zstd feature).
#[cfg(feature = "zstd")]
#[cfg_attr(docsrs, doc(cfg(feature = "zstd")))]
fn compress_zstd(data: &[u8], lvl: i32) -> std::io::Result<Vec<u8>> {
  zstd_encode(data, lvl)
}