Skip to main content

connectrpc_axum_core/
compression.rs

1//! Compression configuration types.
2//!
3//! This module provides configuration types for compression in ConnectRPC:
4//! - [`CompressionEncoding`]: Supported compression algorithms
5//! - [`CompressionLevel`]: Compression quality settings
6//! - [`CompressionConfig`]: Server/client compression configuration
7
8use crate::codec::BoxedCodec;
9
10#[cfg(any(
11    feature = "compression-gzip-stream",
12    feature = "compression-deflate-stream",
13    feature = "compression-br-stream",
14    feature = "compression-zstd-stream"
15))]
16use std::sync::OnceLock;
17
18#[cfg(feature = "compression-gzip-stream")]
19use crate::codec::GzipCodec;
20
21#[cfg(feature = "compression-deflate-stream")]
22use crate::codec::DeflateCodec;
23
24#[cfg(feature = "compression-br-stream")]
25use crate::codec::BrotliCodec;
26
27#[cfg(feature = "compression-zstd-stream")]
28use crate::codec::ZstdCodec;
29
30/// Supported compression encodings.
31///
32/// This enum is used for header parsing and negotiation.
33/// Use [`CompressionEncoding::codec()`] to get the actual codec implementation.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
35pub enum CompressionEncoding {
36    #[default]
37    Identity,
38    #[cfg(feature = "compression-gzip-stream")]
39    Gzip,
40    #[cfg(feature = "compression-deflate-stream")]
41    Deflate,
42    #[cfg(feature = "compression-br-stream")]
43    Brotli,
44    #[cfg(feature = "compression-zstd-stream")]
45    Zstd,
46}
47
48impl CompressionEncoding {
49    /// Parse from Content-Encoding or Connect-Content-Encoding header value.
50    ///
51    /// Encoding tokens are matched case-insensitively per RFC 7231.
52    /// Returns None for unsupported encodings (caller should return Unimplemented).
53    pub fn from_header(value: Option<&str>) -> Option<Self> {
54        let Some(value) = value else {
55            return Some(Self::Identity);
56        };
57        if value.is_empty() || value.eq_ignore_ascii_case("identity") {
58            return Some(Self::Identity);
59        }
60        #[cfg(feature = "compression-gzip-stream")]
61        if value.eq_ignore_ascii_case("gzip") {
62            return Some(Self::Gzip);
63        }
64        #[cfg(feature = "compression-deflate-stream")]
65        if value.eq_ignore_ascii_case("deflate") {
66            return Some(Self::Deflate);
67        }
68        #[cfg(feature = "compression-br-stream")]
69        if value.eq_ignore_ascii_case("br") {
70            return Some(Self::Brotli);
71        }
72        #[cfg(feature = "compression-zstd-stream")]
73        if value.eq_ignore_ascii_case("zstd") {
74            return Some(Self::Zstd);
75        }
76        None // unsupported
77    }
78
79    /// Get the header value string for this encoding.
80    pub fn as_str(&self) -> &'static str {
81        match self {
82            Self::Identity => "identity",
83            #[cfg(feature = "compression-gzip-stream")]
84            Self::Gzip => "gzip",
85            #[cfg(feature = "compression-deflate-stream")]
86            Self::Deflate => "deflate",
87            #[cfg(feature = "compression-br-stream")]
88            Self::Brotli => "br",
89            #[cfg(feature = "compression-zstd-stream")]
90            Self::Zstd => "zstd",
91        }
92    }
93
94    /// Returns true if this encoding is identity (no compression).
95    pub fn is_identity(&self) -> bool {
96        matches!(self, Self::Identity)
97    }
98
99    /// Get the codec for this encoding.
100    ///
101    /// Returns `None` for identity, `Some(BoxedCodec)` for others.
102    ///
103    /// Default codecs are cached in statics, so this is a cheap `Arc` clone
104    /// rather than a fresh allocation per call.
105    pub fn codec(&self) -> Option<BoxedCodec> {
106        match self {
107            Self::Identity => None,
108            #[cfg(feature = "compression-gzip-stream")]
109            Self::Gzip => {
110                static CODEC: OnceLock<BoxedCodec> = OnceLock::new();
111                Some(
112                    CODEC
113                        .get_or_init(|| BoxedCodec::new(GzipCodec::default()))
114                        .clone(),
115                )
116            }
117            #[cfg(feature = "compression-deflate-stream")]
118            Self::Deflate => {
119                static CODEC: OnceLock<BoxedCodec> = OnceLock::new();
120                Some(
121                    CODEC
122                        .get_or_init(|| BoxedCodec::new(DeflateCodec::default()))
123                        .clone(),
124                )
125            }
126            #[cfg(feature = "compression-br-stream")]
127            Self::Brotli => {
128                static CODEC: OnceLock<BoxedCodec> = OnceLock::new();
129                Some(
130                    CODEC
131                        .get_or_init(|| BoxedCodec::new(BrotliCodec::default()))
132                        .clone(),
133                )
134            }
135            #[cfg(feature = "compression-zstd-stream")]
136            Self::Zstd => {
137                static CODEC: OnceLock<BoxedCodec> = OnceLock::new();
138                Some(
139                    CODEC
140                        .get_or_init(|| BoxedCodec::new(ZstdCodec::default()))
141                        .clone(),
142                )
143            }
144        }
145    }
146
147    /// Get the codec for this encoding with the specified compression level.
148    ///
149    /// Returns `None` for identity, `Some(BoxedCodec)` for others.
150    #[allow(unused_variables)]
151    pub fn codec_with_level(&self, level: CompressionLevel) -> Option<BoxedCodec> {
152        match self {
153            Self::Identity => None,
154            #[cfg(feature = "compression-gzip-stream")]
155            Self::Gzip => Some(BoxedCodec::new(GzipCodec::with_level(level_to_flate2(
156                level,
157            )))),
158            #[cfg(feature = "compression-deflate-stream")]
159            Self::Deflate => Some(BoxedCodec::new(DeflateCodec::with_level(level_to_flate2(
160                level,
161            )))),
162            #[cfg(feature = "compression-br-stream")]
163            Self::Brotli => Some(BoxedCodec::new(BrotliCodec::with_quality(level_to_brotli(
164                level,
165            )))),
166            #[cfg(feature = "compression-zstd-stream")]
167            Self::Zstd => Some(BoxedCodec::new(ZstdCodec::with_level(level_to_zstd(level)))),
168        }
169    }
170}
171
172/// Compression level configuration.
173///
174/// This is a local definition that doesn't depend on tower-http,
175/// making it suitable for use in both client and server contexts.
176#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
177pub enum CompressionLevel {
178    /// Fastest compression (lowest ratio).
179    Fastest,
180    /// Best compression (highest ratio, slowest).
181    Best,
182    /// Default compression level for each algorithm.
183    #[default]
184    Default,
185    /// Precise compression level (algorithm-specific value).
186    Precise(u32),
187}
188
189impl CompressionLevel {
190    /// Create a compression level with a precise value.
191    ///
192    /// The value interpretation is algorithm-specific:
193    /// - gzip/deflate: 0-9 (0=no compression, 9=best)
194    /// - brotli: 0-11 (0=fastest, 11=best)
195    /// - zstd: 1-22 (1=fastest, 22=best)
196    pub fn precise(level: u32) -> Self {
197        CompressionLevel::Precise(level)
198    }
199}
200
201/// Convert CompressionLevel to flate2 gzip level (0-9).
202///
203/// Matches tower-http → async_compression behavior:
204/// - `Fastest` → 1
205/// - `Best` → 9
206/// - `Default` → 6
207/// - `Precise(n)` → n clamped to 0-9
208#[cfg(any(
209    feature = "compression-gzip-stream",
210    feature = "compression-deflate-stream"
211))]
212fn level_to_flate2(level: CompressionLevel) -> u32 {
213    match level {
214        CompressionLevel::Fastest => 1,
215        CompressionLevel::Best => 9,
216        CompressionLevel::Default => 6,
217        CompressionLevel::Precise(n) => n.clamp(0, 9),
218    }
219}
220
221/// Convert CompressionLevel to brotli quality (0-11).
222///
223/// tower-http overrides Default to 4 (NGINX default) for performance.
224#[cfg(feature = "compression-br-stream")]
225fn level_to_brotli(level: CompressionLevel) -> u32 {
226    match level {
227        CompressionLevel::Fastest => 0,
228        CompressionLevel::Best => 11,
229        CompressionLevel::Default => 4, // tower-http's custom default
230        CompressionLevel::Precise(n) => n.clamp(0, 11),
231    }
232}
233
234/// Convert CompressionLevel to zstd level (1-22).
235#[cfg(feature = "compression-zstd-stream")]
236fn level_to_zstd(level: CompressionLevel) -> i32 {
237    match level {
238        CompressionLevel::Fastest => 1,
239        CompressionLevel::Best => 22,
240        CompressionLevel::Default => 3,
241        CompressionLevel::Precise(n) => (n as i32).clamp(1, 22),
242    }
243}
244
245/// Compression configuration.
246///
247/// Used to configure compression behavior for both client and server.
248#[derive(Debug, Clone, Copy)]
249pub struct CompressionConfig {
250    /// Minimum bytes before compression is applied.
251    /// Default is 0 (compress everything), matching connect-go behavior.
252    /// Messages smaller than this threshold are sent uncompressed.
253    pub min_bytes: usize,
254    /// Compression level/quality.
255    pub level: CompressionLevel,
256}
257
258impl Default for CompressionConfig {
259    fn default() -> Self {
260        Self {
261            min_bytes: 0,
262            level: CompressionLevel::Default,
263        }
264    }
265}
266
267impl CompressionConfig {
268    /// Create a new compression config with the specified minimum bytes threshold.
269    pub fn new(min_bytes: usize) -> Self {
270        Self {
271            min_bytes,
272            level: CompressionLevel::Default,
273        }
274    }
275
276    /// Set the compression level.
277    pub fn level(mut self, level: CompressionLevel) -> Self {
278        self.level = level;
279        self
280    }
281
282    /// Disable compression by setting threshold to usize::MAX.
283    pub fn disabled() -> Self {
284        Self {
285            min_bytes: usize::MAX,
286            level: CompressionLevel::Default,
287        }
288    }
289
290    /// Check if compression is effectively disabled.
291    pub fn is_disabled(&self) -> bool {
292        self.min_bytes == usize::MAX
293    }
294}
295
296/// Returns a comma-separated string of supported encodings for error messages.
297pub fn supported_encodings_str() -> &'static str {
298    // Order: gzip, deflate, br, zstd, identity
299    static ENCODINGS: std::sync::OnceLock<String> = std::sync::OnceLock::new();
300    ENCODINGS.get_or_init(|| {
301        [
302            #[cfg(feature = "compression-gzip-stream")]
303            "gzip",
304            #[cfg(feature = "compression-deflate-stream")]
305            "deflate",
306            #[cfg(feature = "compression-br-stream")]
307            "br",
308            #[cfg(feature = "compression-zstd-stream")]
309            "zstd",
310            "identity",
311        ]
312        .join(", ")
313    })
314}
315
316/// Negotiate response encoding from Accept-Encoding header.
317///
318/// Follows connect-go's approach: first supported encoding wins (client preference order).
319/// Encoding tokens are matched case-insensitively per RFC 7231.
320/// Respects `q=0` which means "not acceptable" per RFC 7231.
321pub fn negotiate_response_encoding(accept: Option<&str>) -> CompressionEncoding {
322    let Some(accept) = accept else {
323        return CompressionEncoding::Identity;
324    };
325
326    for token in accept.split(',') {
327        let token = token.trim();
328        if token.is_empty() {
329            continue;
330        }
331
332        // Parse "gzip;q=0.5" into encoding="gzip", q_value=Some("0.5")
333        let (encoding, q_value) = match token.split_once(';') {
334            Some((enc, params)) => {
335                let q = params.split(';').find_map(|p| p.trim().strip_prefix("q="));
336                (enc.trim(), q)
337            }
338            None => (token, None),
339        };
340
341        // Skip if q=0 (explicitly disabled)
342        if let Some(q) = q_value {
343            let q = q.trim();
344            if q == "0" || q == "0.0" || q == "0.00" || q == "0.000" {
345                continue;
346            }
347        }
348
349        // Return first supported encoding
350        #[cfg(feature = "compression-gzip-stream")]
351        if encoding.eq_ignore_ascii_case("gzip") {
352            return CompressionEncoding::Gzip;
353        }
354        #[cfg(feature = "compression-deflate-stream")]
355        if encoding.eq_ignore_ascii_case("deflate") {
356            return CompressionEncoding::Deflate;
357        }
358        #[cfg(feature = "compression-br-stream")]
359        if encoding.eq_ignore_ascii_case("br") {
360            return CompressionEncoding::Brotli;
361        }
362        #[cfg(feature = "compression-zstd-stream")]
363        if encoding.eq_ignore_ascii_case("zstd") {
364            return CompressionEncoding::Zstd;
365        }
366        if encoding.eq_ignore_ascii_case("identity") {
367            return CompressionEncoding::Identity;
368        }
369    }
370
371    CompressionEncoding::Identity
372}
373
374/// Header name for Connect streaming request compression.
375pub const CONNECT_CONTENT_ENCODING: &str = "connect-content-encoding";
376
377/// Header name for Connect streaming response compression negotiation.
378pub const CONNECT_ACCEPT_ENCODING: &str = "connect-accept-encoding";
379
380#[cfg(test)]
381mod tests {
382    use super::*;
383
384    #[test]
385    fn test_compression_encoding_from_header_identity() {
386        assert_eq!(
387            CompressionEncoding::from_header(None),
388            Some(CompressionEncoding::Identity)
389        );
390        assert_eq!(
391            CompressionEncoding::from_header(Some("")),
392            Some(CompressionEncoding::Identity)
393        );
394        assert_eq!(
395            CompressionEncoding::from_header(Some("identity")),
396            Some(CompressionEncoding::Identity)
397        );
398        assert_eq!(CompressionEncoding::from_header(Some("lz4")), None);
399    }
400
401    #[cfg(feature = "compression-gzip-stream")]
402    #[test]
403    fn test_compression_encoding_from_header_gzip() {
404        assert_eq!(
405            CompressionEncoding::from_header(Some("gzip")),
406            Some(CompressionEncoding::Gzip)
407        );
408    }
409
410    #[test]
411    fn test_compression_encoding_as_str_identity() {
412        assert_eq!(CompressionEncoding::Identity.as_str(), "identity");
413    }
414
415    #[cfg(feature = "compression-gzip-stream")]
416    #[test]
417    fn test_compression_encoding_as_str_gzip() {
418        assert_eq!(CompressionEncoding::Gzip.as_str(), "gzip");
419    }
420
421    #[cfg(feature = "compression-gzip-stream")]
422    #[test]
423    fn test_compression_encoding_codec() {
424        assert!(CompressionEncoding::Identity.codec().is_none());
425        let codec = CompressionEncoding::Gzip.codec();
426        assert!(codec.is_some());
427        assert_eq!(codec.unwrap().name(), "gzip");
428    }
429
430    #[test]
431    fn test_compression_level_precise() {
432        assert_eq!(CompressionLevel::precise(5), CompressionLevel::Precise(5));
433    }
434
435    #[test]
436    fn test_compression_config_default() {
437        let config = CompressionConfig::default();
438        assert_eq!(config.min_bytes, 0);
439        assert_eq!(config.level, CompressionLevel::Default);
440    }
441
442    #[test]
443    fn test_compression_config_new() {
444        let config = CompressionConfig::new(512);
445        assert_eq!(config.min_bytes, 512);
446    }
447
448    #[test]
449    fn test_compression_config_disabled() {
450        let config = CompressionConfig::disabled();
451        assert_eq!(config.min_bytes, usize::MAX);
452        assert!(config.is_disabled());
453    }
454
455    #[test]
456    fn test_negotiate_response_encoding_identity() {
457        assert_eq!(
458            negotiate_response_encoding(None),
459            CompressionEncoding::Identity
460        );
461        assert_eq!(
462            negotiate_response_encoding(Some("")),
463            CompressionEncoding::Identity
464        );
465    }
466
467    #[cfg(feature = "compression-gzip-stream")]
468    #[test]
469    fn test_negotiate_response_encoding_gzip() {
470        assert_eq!(
471            negotiate_response_encoding(Some("gzip")),
472            CompressionEncoding::Gzip
473        );
474        assert_eq!(
475            negotiate_response_encoding(Some("gzip, identity")),
476            CompressionEncoding::Gzip
477        );
478    }
479
480    #[cfg(feature = "compression-gzip-stream")]
481    #[test]
482    fn test_negotiate_response_encoding_q_values() {
483        // q=0 means "not acceptable"
484        assert_eq!(
485            negotiate_response_encoding(Some("gzip;q=0")),
486            CompressionEncoding::Identity
487        );
488        assert_eq!(
489            negotiate_response_encoding(Some("gzip;q=0, identity")),
490            CompressionEncoding::Identity
491        );
492        // Non-zero q values should be accepted
493        assert_eq!(
494            negotiate_response_encoding(Some("gzip;q=1")),
495            CompressionEncoding::Gzip
496        );
497        assert_eq!(
498            negotiate_response_encoding(Some("gzip;q=0.5")),
499            CompressionEncoding::Gzip
500        );
501    }
502}