forked from anthropics/connect-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompression.rs
More file actions
1684 lines (1473 loc) · 58.6 KB
/
compression.rs
File metadata and controls
1684 lines (1473 loc) · 58.6 KB
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
//! Pluggable compression support for ConnectRPC.
//!
//! This module provides a trait-based compression system that allows users to
//! register custom compression providers. Built-in providers are available
//! for common algorithms when the corresponding features are enabled:
//!
//! - `gzip` - Gzip compression via flate2 (enabled by default)
//! - `zstd` - Zstandard compression via zstd (enabled by default)
//!
//! # Streaming Compression
//!
//! When the `streaming` feature is enabled (default), providers can also
//! support streaming compression/decompression for handling large payloads
//! without buffering the entire message in memory.
//!
//! # Example
//!
//! ```rust,ignore
//! use connectrpc::compression::{CompressionRegistry, GzipProvider, ZstdProvider};
//!
//! // Create a registry with built-in providers
//! let registry = CompressionRegistry::new()
//! .register(GzipProvider::default())
//! .register(ZstdProvider::default());
//!
//! // Or use the default registry (includes all feature-enabled providers)
//! let registry = CompressionRegistry::default();
//!
//! // Use with server
//! let server = Server::new(router).with_compression(registry);
//! ```
//!
//! # Custom Providers
//!
//! ```rust,ignore
//! use connectrpc::compression::CompressionProvider;
//!
//! struct MyCompression;
//!
//! impl CompressionProvider for MyCompression {
//! fn name(&self) -> &'static str { "my-algo" }
//! fn compress(&self, data: &[u8]) -> Result<Bytes, ConnectError> { ... }
//! fn decompressor<'a>(&self, data: &'a [u8]) -> Result<Box<dyn std::io::Read + 'a>, ConnectError> {
//! // Return a reader that yields decompressed bytes.
//! // The framework controls how much is read, so you get safe
//! // `decompress_with_limit` for free via `Read::take`.
//! ...
//! }
//! }
//!
//! let registry = CompressionRegistry::new()
//! .register(MyCompression);
//! ```
use std::collections::HashMap;
#[cfg(feature = "streaming")]
use std::pin::Pin;
use std::sync::Arc;
use bytes::Bytes;
#[cfg(feature = "streaming")]
use tokio::io::AsyncBufRead;
#[cfg(feature = "streaming")]
use tokio::io::AsyncRead;
use crate::error::ConnectError;
// ============================================================================
// Streaming Types
// ============================================================================
/// A boxed async reader for streaming compression/decompression.
#[cfg(feature = "streaming")]
pub type BoxedAsyncRead = Pin<Box<dyn AsyncRead + Send>>;
/// A boxed async buffered reader for streaming input.
#[cfg(feature = "streaming")]
pub type BoxedAsyncBufRead = Pin<Box<dyn AsyncBufRead + Send>>;
/// Trait for compression algorithm implementations.
///
/// Implement this trait to provide custom compression support. The only
/// required methods are [`name`](Self::name), [`compress`](Self::compress),
/// and [`decompressor`](Self::decompressor). The provided default for
/// [`decompress_with_limit`](Self::decompress_with_limit) is structurally
/// safe — the framework controls how many bytes are read from the
/// decompressor, using [`Read::take`](std::io::Read::take) to cap output and prevent unbounded
/// memory allocation from compression bombs.
///
/// All decompression goes through `decompress_with_limit` — there is no
/// unbounded `decompress` method, by design.
pub trait CompressionProvider: Send + Sync + 'static {
/// The encoding name for this algorithm.
///
/// This should match the value used in Content-Encoding headers
/// (e.g., "gzip", "zstd", "br").
fn name(&self) -> &'static str;
/// Compress the given data.
fn compress(&self, data: &[u8]) -> Result<Bytes, ConnectError>;
/// Return a reader that yields decompressed bytes from `data`.
///
/// This is the core decompression method that implementations must
/// provide. Most decompression libraries provide a `Read` adapter
/// (e.g. `flate2::read::GzDecoder`, `zstd::Decoder`,
/// `brotli::Decompressor`) — just wrap the input and return it.
///
/// The framework controls the read loop, so implementations do not
/// need to worry about size limits. The default
/// [`decompress_with_limit`](Self::decompress_with_limit) uses
/// `Read::take(max_size + 1)` to structurally bound memory.
fn decompressor<'a>(&self, data: &'a [u8])
-> Result<Box<dyn std::io::Read + 'a>, ConnectError>;
/// Decompress the given data with a size limit.
///
/// Returns an error if the decompressed data exceeds `max_size`.
/// This protects against compression bomb attacks.
///
/// The default implementation uses `Read::take(max_size + 1)` on the
/// reader from [`decompressor`](Self::decompressor) to structurally
/// bound memory — custom providers are safe without any extra work.
/// Built-in providers override this for performance.
fn decompress_with_limit(&self, data: &[u8], max_size: usize) -> Result<Bytes, ConnectError> {
use std::io::Read;
let reader = self.decompressor(data)?;
let capacity = if max_size < 64 * 1024 * 1024 {
max_size.saturating_add(1)
} else {
256
};
let mut buf = Vec::with_capacity(capacity);
reader
.take((max_size as u64).saturating_add(1))
.read_to_end(&mut buf)
.map_err(|e| ConnectError::internal(format!("decompression failed: {e}")))?;
if buf.len() > max_size {
return Err(ConnectError::resource_exhausted(format!(
"decompressed size exceeds limit {max_size}"
)));
}
Ok(Bytes::from(buf))
}
}
/// Trait for streaming compression support.
///
/// This trait extends [`CompressionProvider`] with streaming methods that
/// process data incrementally without buffering the entire payload in memory.
///
/// Available when the `streaming` feature is enabled (default).
#[cfg(feature = "streaming")]
pub trait StreamingCompressionProvider: CompressionProvider {
/// Create a streaming decompressor.
///
/// Returns an `AsyncRead` that decompresses data from the input reader.
fn decompress_stream(&self, reader: BoxedAsyncBufRead) -> BoxedAsyncRead;
/// Create a streaming compressor.
///
/// Returns an `AsyncRead` that compresses data from the input reader.
fn compress_stream(&self, reader: BoxedAsyncBufRead) -> BoxedAsyncRead;
}
/// Registry of compression providers.
///
/// The registry maps encoding names to their provider implementations.
/// Use [`CompressionRegistry::default()`] to get a registry with all
/// feature-enabled built-in providers.
#[derive(Clone)]
pub struct CompressionRegistry {
providers: Arc<HashMap<&'static str, Arc<dyn CompressionProvider>>>,
#[cfg(feature = "streaming")]
streaming_providers: Arc<HashMap<&'static str, Arc<dyn StreamingCompressionProvider>>>,
/// Cached, sorted, comma-joined list of supported encodings for
/// Accept-Encoding headers. Recomputed when providers are registered
/// (rather than on every request).
accept_encoding: Arc<str>,
}
impl std::fmt::Debug for CompressionRegistry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CompressionRegistry")
.field("providers", &self.providers.keys().collect::<Vec<_>>())
.finish()
}
}
impl CompressionRegistry {
/// Create an empty compression registry.
///
/// Use [`register`](Self::register) to add providers, or use
/// [`default`](Self::default) to get a registry with built-in providers.
pub fn new() -> Self {
Self {
providers: Arc::new(HashMap::new()),
#[cfg(feature = "streaming")]
streaming_providers: Arc::new(HashMap::new()),
accept_encoding: Arc::from(""),
}
}
/// Recompute the cached accept-encoding string from the current provider set.
fn rebuild_accept_encoding(&mut self) {
let mut encodings: Vec<_> = self.providers.keys().copied().collect();
encodings.sort_unstable();
self.accept_encoding = Arc::from(encodings.join(", "));
}
/// Register a compression provider.
///
/// Returns self for method chaining.
///
/// # Example
///
/// ```rust
/// # #[cfg(all(feature = "gzip", feature = "zstd"))] {
/// use connectrpc::compression::{CompressionRegistry, GzipProvider, ZstdProvider};
/// let registry = CompressionRegistry::new()
/// .register(GzipProvider::default())
/// .register(ZstdProvider::default());
/// assert!(registry.supports("gzip"));
/// assert!(registry.supports("zstd"));
/// # }
/// ```
#[must_use]
pub fn register<P: CompressionProvider>(mut self, provider: P) -> Self {
let providers = Arc::make_mut(&mut self.providers);
providers.insert(provider.name(), Arc::new(provider));
self.rebuild_accept_encoding();
self
}
/// Get a provider by encoding name.
///
/// Returns `None` if no provider is registered for the given name.
#[inline]
#[must_use]
pub fn get(&self, name: &str) -> Option<Arc<dyn CompressionProvider>> {
self.providers.get(name).cloned()
}
/// Check if a provider is registered for the given encoding name.
#[inline]
pub fn supports(&self, name: &str) -> bool {
self.providers.contains_key(name)
}
/// List all supported encoding names.
pub fn supported_encodings(&self) -> Vec<&'static str> {
self.providers.keys().copied().collect()
}
/// Get a comma-separated string of supported encodings.
///
/// Useful for Accept-Encoding headers. The string is computed once when
/// providers are registered and cached, so this is a cheap lookup.
#[inline]
pub fn accept_encoding_header(&self) -> &str {
&self.accept_encoding
}
/// Negotiate a response encoding based on the client's accept-encoding header.
///
/// Returns the first encoding from the client's preference list that this
/// registry supports, or None if only identity is acceptable.
///
/// Per the Connect spec, the accept-encoding header is treated as an ordered
/// list with most preferred first (no quality values).
///
/// If the client omits accept-encoding, the spec says the server may assume
/// the client accepts the same encoding used for the request (if any), plus identity.
pub fn negotiate_encoding(
&self,
accept_encoding: Option<&str>,
request_encoding: Option<&str>,
) -> Option<&'static str> {
// If client sent Accept-Encoding, use it
if let Some(accept) = accept_encoding {
for encoding in accept.split(',').map(|s| s.trim()) {
if encoding == "identity" {
continue; // identity means no compression
}
if let Some((key, _)) = self.providers.get_key_value(encoding) {
return Some(*key);
}
}
return None; // Client listed encodings but none supported
}
// Spec: if client omits accept-encoding, assume it accepts the request encoding
if let Some(req_enc) = request_encoding
&& req_enc != "identity"
&& let Some((key, _)) = self.providers.get_key_value(req_enc)
{
return Some(*key);
}
None // No compression
}
/// Decompress data using the specified encoding with a size limit.
///
/// Returns an error if the encoding is not supported or if the decompressed
/// data exceeds `max_size`. This protects against compression bomb attacks.
///
/// For identity encoding, returns the data without copying.
pub fn decompress_with_limit(
&self,
encoding: &str,
data: Bytes,
max_size: usize,
) -> Result<Bytes, ConnectError> {
// "identity" means no compression — return data without copying
if encoding == "identity" {
if data.len() > max_size {
return Err(ConnectError::resource_exhausted(format!(
"message size {} exceeds limit {}",
data.len(),
max_size
)));
}
return Ok(data);
}
let provider = self.get(encoding).ok_or_else(|| {
ConnectError::unimplemented(format!("unsupported compression encoding: {encoding}"))
})?;
// Per the Connect spec: "Servers must not attempt to decompress
// zero-length HTTP request content" (and the symmetric rule for
// clients). A zero-length body with Content-Encoding set is valid —
// clients may skip compressing empty payloads but still advertise
// the encoding. Return empty without invoking the decoder, which
// may reject empty input as an incomplete frame (zstd does).
// Checked AFTER resolving the encoding so unsupported encodings
// still error (conformance "unexpected-compression" test).
if data.is_empty() {
return Ok(data);
}
provider.decompress_with_limit(&data, max_size)
}
/// Compress data using the specified encoding.
///
/// Returns an error if the encoding is not supported.
pub fn compress(&self, encoding: &str, data: &[u8]) -> Result<Bytes, ConnectError> {
// "identity" means no compression
if encoding == "identity" {
return Ok(Bytes::copy_from_slice(data));
}
let provider = self.get(encoding).ok_or_else(|| {
ConnectError::unimplemented(format!("unsupported compression encoding: {encoding}"))
})?;
provider.compress(data)
}
/// Register a streaming compression provider.
///
/// This also registers the provider for buffered compression.
/// Returns self for method chaining.
///
/// Available when the `streaming` feature is enabled.
#[cfg(feature = "streaming")]
#[must_use]
pub fn register_streaming<P: StreamingCompressionProvider>(mut self, provider: P) -> Self {
let name = provider.name();
let provider = Arc::new(provider);
// Register for both buffered and streaming
let providers = Arc::make_mut(&mut self.providers);
providers.insert(name, provider.clone());
let streaming_providers = Arc::make_mut(&mut self.streaming_providers);
streaming_providers.insert(name, provider);
self.rebuild_accept_encoding();
self
}
/// Get a streaming provider by encoding name.
///
/// Returns `None` if no streaming provider is registered for the given name.
#[cfg(feature = "streaming")]
pub fn get_streaming(&self, name: &str) -> Option<Arc<dyn StreamingCompressionProvider>> {
self.streaming_providers.get(name).cloned()
}
/// Check if streaming compression is supported for the given encoding name.
#[cfg(feature = "streaming")]
pub fn supports_streaming(&self, name: &str) -> bool {
self.streaming_providers.contains_key(name)
}
/// Create a streaming decompressor for the specified encoding.
///
/// Returns an `AsyncRead` that decompresses data from the input reader.
/// Returns an error if the encoding is not supported for streaming.
#[cfg(feature = "streaming")]
pub fn decompress_stream(
&self,
encoding: &str,
reader: BoxedAsyncBufRead,
) -> Result<BoxedAsyncRead, ConnectError> {
// "identity" means no compression - just return the reader as-is
if encoding == "identity" {
return Ok(reader);
}
let provider = self.get_streaming(encoding).ok_or_else(|| {
ConnectError::unimplemented(format!(
"streaming decompression not supported for encoding: {encoding}"
))
})?;
Ok(provider.decompress_stream(reader))
}
/// Create a streaming compressor for the specified encoding.
///
/// Returns an `AsyncRead` that compresses data from the input reader.
/// Returns an error if the encoding is not supported for streaming.
#[cfg(feature = "streaming")]
pub fn compress_stream(
&self,
encoding: &str,
reader: BoxedAsyncBufRead,
) -> Result<BoxedAsyncRead, ConnectError> {
// "identity" means no compression - just return the reader as-is
if encoding == "identity" {
return Ok(reader);
}
let provider = self.get_streaming(encoding).ok_or_else(|| {
ConnectError::unimplemented(format!(
"streaming compression not supported for encoding: {encoding}"
))
})?;
Ok(provider.compress_stream(reader))
}
}
/// Policy controlling when compression is applied.
///
/// By default, messages below 1 KiB are not compressed — at that size,
/// compression overhead (headers, Huffman tables, checksums) typically
/// exceeds the space savings, and the CPU cost of initializing the
/// compressor dominates.
///
/// # Example
///
/// ```rust
/// use connectrpc::CompressionPolicy;
///
/// // Only compress messages >= 4 KiB
/// let policy = CompressionPolicy::default().min_size(4096);
/// assert!(!policy.should_compress(1024));
/// assert!(policy.should_compress(8192));
///
/// // Disable compression entirely
/// let policy = CompressionPolicy::disabled();
/// assert!(!policy.should_compress(1_000_000));
/// ```
#[derive(Debug, Clone, Copy)]
pub struct CompressionPolicy {
/// Whether compression is enabled at all.
enabled: bool,
/// Minimum message size in bytes before compression is applied.
/// Messages smaller than this are sent uncompressed.
min_size: usize,
}
/// Default minimum message size for compression (1 KiB).
///
/// Below this threshold, compression typically adds overhead without
/// meaningful size reduction. This matches common defaults in HTTP
/// servers and gRPC implementations (gRPC-Java uses 1 KiB).
pub const DEFAULT_COMPRESSION_MIN_SIZE: usize = 1024;
impl Default for CompressionPolicy {
fn default() -> Self {
Self {
enabled: true,
min_size: DEFAULT_COMPRESSION_MIN_SIZE,
}
}
}
impl CompressionPolicy {
/// Create a policy that disables compression entirely.
pub fn disabled() -> Self {
Self {
enabled: false,
min_size: 0,
}
}
/// Set the minimum message size for compression.
///
/// Messages smaller than this (in bytes, before compression) will
/// be sent uncompressed even if compression is negotiated.
#[must_use]
pub fn min_size(mut self, size: usize) -> Self {
self.min_size = size;
self
}
/// Check whether compression should be applied for a message of the given size.
///
/// Zero-length bodies are compressed when `min_size == 0` (useful for
/// conformance testing where the runner checks that advertised encodings
/// are used even for empty payloads). The Connect spec requires receivers
/// to skip decompression for zero-length content, so this is safe.
#[inline]
pub fn should_compress(&self, message_size: usize) -> bool {
self.enabled && message_size >= self.min_size
}
/// Return an effective policy that accounts for a per-call override.
///
/// - `None` → use this policy as-is.
/// - `Some(true)` → force compression (min_size = 0, enabled = true).
/// - `Some(false)` → disable compression.
pub(crate) fn with_override(&self, override_compress: Option<bool>) -> Self {
match override_compress {
None => *self,
Some(true) => Self {
enabled: true,
min_size: 0,
},
Some(false) => Self::disabled(),
}
}
}
impl Default for CompressionRegistry {
/// Create a registry with all feature-enabled built-in providers.
#[allow(unused_mut)]
fn default() -> Self {
let mut registry = Self::new();
// When streaming is enabled, use register_streaming to get both capabilities
#[cfg(all(feature = "gzip", feature = "streaming"))]
{
registry = registry.register_streaming(GzipProvider::default());
}
#[cfg(all(feature = "gzip", not(feature = "streaming")))]
{
registry = registry.register(GzipProvider::default());
}
#[cfg(all(feature = "zstd", feature = "streaming"))]
{
registry = registry.register_streaming(ZstdProvider::default());
}
#[cfg(all(feature = "zstd", not(feature = "streaming")))]
{
registry = registry.register(ZstdProvider::default());
}
registry
}
}
// ============================================================================
// Built-in Providers
// ============================================================================
/// Gzip compression provider with internal state pooling.
///
/// Pools `flate2::Compress` and `flate2::Decompress` objects to avoid the
/// ~200 KB allocation overhead per request that comes from creating fresh
/// gzip state tables. The pool is shared across all clones of the
/// `CompressionRegistry` that holds this provider (via `Arc`).
///
/// Available when the `gzip` feature is enabled (default).
#[cfg(feature = "gzip")]
pub struct GzipProvider {
/// Compression level (0-9, default is 6).
level: u32,
compressors: std::sync::Mutex<Vec<flate2::Compress>>,
decompressors: std::sync::Mutex<Vec<flate2::Decompress>>,
}
#[cfg(feature = "gzip")]
impl std::fmt::Debug for GzipProvider {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("GzipProvider")
.field("level", &self.level)
.field(
"pool_compressors",
&self.compressors.lock().map(|v| v.len()).unwrap_or(0),
)
.field(
"pool_decompressors",
&self.decompressors.lock().map(|v| v.len()).unwrap_or(0),
)
.finish()
}
}
#[cfg(feature = "gzip")]
impl Default for GzipProvider {
fn default() -> Self {
Self {
level: 6,
compressors: std::sync::Mutex::new(Vec::new()),
decompressors: std::sync::Mutex::new(Vec::new()),
}
}
}
#[cfg(feature = "gzip")]
impl GzipProvider {
/// Create a new Gzip provider with default compression level.
pub fn new() -> Self {
Self::default()
}
/// Create a new Gzip provider with the specified compression level.
///
/// Level should be 0-9, where 0 is no compression and 9 is maximum.
pub fn with_level(level: u32) -> Self {
Self {
level,
compressors: std::sync::Mutex::new(Vec::new()),
decompressors: std::sync::Mutex::new(Vec::new()),
}
}
/// Maximum number of compressor/decompressor instances to retain in
/// the pool. Excess instances are dropped to bound memory usage.
const MAX_POOL_SIZE: usize = 64;
fn take_compressor(&self) -> flate2::Compress {
self.compressors
.lock()
.unwrap_or_else(|e| e.into_inner())
.pop()
.unwrap_or_else(|| flate2::Compress::new(flate2::Compression::new(self.level), false))
}
fn return_compressor(&self, mut c: flate2::Compress) {
c.reset();
let mut pool = self.compressors.lock().unwrap_or_else(|e| e.into_inner());
if pool.len() < Self::MAX_POOL_SIZE {
pool.push(c);
}
}
fn take_decompressor(&self) -> flate2::Decompress {
self.decompressors
.lock()
.unwrap_or_else(|e| e.into_inner())
.pop()
.unwrap_or_else(|| flate2::Decompress::new(false))
}
fn return_decompressor(&self, mut d: flate2::Decompress) {
d.reset(false);
let mut pool = self.decompressors.lock().unwrap_or_else(|e| e.into_inner());
if pool.len() < Self::MAX_POOL_SIZE {
pool.push(d);
}
}
fn compress_inner(
compressor: &mut flate2::Compress,
data: &[u8],
) -> Result<Bytes, ConnectError> {
let mut output = Vec::with_capacity(data.len() + 32);
// Gzip header (RFC 1952): fixed 10 bytes, no optional fields
output.extend_from_slice(&[
0x1f, 0x8b, // magic
0x08, // method = deflate
0x00, // flags = none
0x00, 0x00, 0x00, 0x00, // mtime = 0
0x00, // extra flags
0xff, // OS = unknown
]);
// Deflate-compress the data
let start_in = compressor.total_in();
loop {
let consumed = (compressor.total_in() - start_in) as usize;
output.reserve(output.capacity().max(4096));
let status = compressor
.compress_vec(
&data[consumed..],
&mut output,
flate2::FlushCompress::Finish,
)
.map_err(|e| ConnectError::internal(format!("gzip compression failed: {e}")))?;
if status == flate2::Status::StreamEnd {
break;
}
}
// Gzip trailer: CRC32 + ISIZE (original size mod 2^32)
let mut crc = flate2::Crc::new();
crc.update(data);
output.extend_from_slice(&crc.sum().to_le_bytes());
output.extend_from_slice(&(data.len() as u32).to_le_bytes());
Ok(Bytes::from(output))
}
fn decompress_inner(
decompressor: &mut flate2::Decompress,
data: &[u8],
max_size: Option<usize>,
) -> Result<Bytes, ConnectError> {
let deflate_start = gzip_header_len(data)?;
let stream_data = &data[deflate_start..];
let capacity = match max_size {
// For very large limits (e.g. usize::MAX),
// use a growth-based strategy instead of pre-allocating.
Some(limit) if limit < 64 * 1024 * 1024 => limit.saturating_add(1),
_ => data.len().saturating_mul(2).max(256),
};
let mut output = Vec::with_capacity(capacity);
// Decompress the deflate stream, letting the decompressor find its
// own end-of-stream marker rather than pre-slicing.
let start_in = decompressor.total_in();
loop {
let consumed = (decompressor.total_in() - start_in) as usize;
if output.capacity() == output.len() {
if let Some(limit) = max_size
&& output.len() > limit
{
return Err(ConnectError::resource_exhausted(format!(
"decompressed size exceeds limit {limit}"
)));
}
output.reserve(output.len().max(4096));
}
let status = decompressor
.decompress_vec(
&stream_data[consumed..],
&mut output,
flate2::FlushDecompress::None,
)
.map_err(|e| ConnectError::internal(format!("gzip decompression failed: {e}")))?;
if status == flate2::Status::StreamEnd {
break;
}
}
if let Some(limit) = max_size
&& output.len() > limit
{
return Err(ConnectError::resource_exhausted(format!(
"decompressed size exceeds limit {limit}"
)));
}
// The 8-byte trailer (CRC32 + ISIZE) follows the deflate stream.
let deflate_consumed = (decompressor.total_in() - start_in) as usize;
let trailer_start = deflate_consumed;
if stream_data.len() < trailer_start + 8 {
return Err(ConnectError::internal("gzip data too short for trailer"));
}
let trailer = &stream_data[trailer_start..trailer_start + 8];
let expected_crc = u32::from_le_bytes([trailer[0], trailer[1], trailer[2], trailer[3]]);
let expected_size = u32::from_le_bytes([trailer[4], trailer[5], trailer[6], trailer[7]]);
let mut crc = flate2::Crc::new();
crc.update(&output);
if crc.sum() != expected_crc {
return Err(ConnectError::internal("gzip CRC32 mismatch"));
}
if expected_size != (output.len() as u32) {
return Err(ConnectError::internal("gzip size mismatch"));
}
Ok(Bytes::from(output))
}
}
/// Parse a gzip header (RFC 1952) and return the byte offset where the
/// deflate stream begins.
#[cfg(feature = "gzip")]
fn gzip_header_len(data: &[u8]) -> Result<usize, ConnectError> {
if data.len() < 10 {
return Err(ConnectError::internal("gzip data too short for header"));
}
if data[0] != 0x1f || data[1] != 0x8b {
return Err(ConnectError::internal("invalid gzip magic"));
}
if data[2] != 0x08 {
return Err(ConnectError::internal(
"unsupported gzip compression method",
));
}
let flags = data[3];
let mut pos = 10;
// FEXTRA
if flags & 0x04 != 0 {
if pos + 2 > data.len() {
return Err(ConnectError::internal("truncated gzip header"));
}
let xlen = u16::from_le_bytes([data[pos], data[pos + 1]]) as usize;
pos += 2 + xlen;
}
// FNAME (null-terminated)
if flags & 0x08 != 0 {
while pos < data.len() && data[pos] != 0 {
pos += 1;
}
if pos >= data.len() {
return Err(ConnectError::internal("truncated gzip header"));
}
pos += 1; // skip null terminator
}
// FCOMMENT (null-terminated)
if flags & 0x10 != 0 {
while pos < data.len() && data[pos] != 0 {
pos += 1;
}
if pos >= data.len() {
return Err(ConnectError::internal("truncated gzip header"));
}
pos += 1; // skip null terminator
}
// FHCRC
if flags & 0x02 != 0 {
pos += 2;
}
if pos > data.len() {
return Err(ConnectError::internal("truncated gzip header"));
}
Ok(pos)
}
#[cfg(feature = "gzip")]
impl CompressionProvider for GzipProvider {
fn name(&self) -> &'static str {
"gzip"
}
fn compress(&self, data: &[u8]) -> Result<Bytes, ConnectError> {
let mut compressor = self.take_compressor();
let result = Self::compress_inner(&mut compressor, data);
self.return_compressor(compressor);
result
}
fn decompressor<'a>(
&self,
data: &'a [u8],
) -> Result<Box<dyn std::io::Read + 'a>, ConnectError> {
Ok(Box::new(flate2::read::GzDecoder::new(data)))
}
fn decompress_with_limit(&self, data: &[u8], max_size: usize) -> Result<Bytes, ConnectError> {
let mut decompressor = self.take_decompressor();
let result = Self::decompress_inner(&mut decompressor, data, Some(max_size));
self.return_decompressor(decompressor);
result
}
}
#[cfg(all(feature = "gzip", feature = "streaming"))]
impl StreamingCompressionProvider for GzipProvider {
fn decompress_stream(&self, reader: BoxedAsyncBufRead) -> BoxedAsyncRead {
Box::pin(async_compression::tokio::bufread::GzipDecoder::new(reader))
}
fn compress_stream(&self, reader: BoxedAsyncBufRead) -> BoxedAsyncRead {
Box::pin(async_compression::tokio::bufread::GzipEncoder::new(reader))
}
}
/// Zstandard compression provider with internal compressor pooling.
///
/// Pools `zstd::bulk::Compressor` objects to avoid repeated allocation of
/// zstd compression contexts. Decompression uses the streaming decoder
/// (`zstd::Decoder`) which handles arbitrary compression ratios without
/// guessing output buffer sizes.
///
/// Available when the `zstd` feature is enabled (default).
#[cfg(feature = "zstd")]
pub struct ZstdProvider {
/// Compression level (1-22, default is 3).
level: i32,
compressors: std::sync::Mutex<Vec<zstd::bulk::Compressor<'static>>>,
}
#[cfg(feature = "zstd")]
impl std::fmt::Debug for ZstdProvider {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ZstdProvider")
.field("level", &self.level)
.field(
"pool_compressors",
&self.compressors.lock().map(|v| v.len()).unwrap_or(0),
)
.finish()
}
}
#[cfg(feature = "zstd")]
impl ZstdProvider {
const DEFAULT_LEVEL: i32 = 3;
/// Create a new Zstd provider with default compression level.
pub fn new() -> Self {
Self::default()
}
/// Create a new Zstd provider with the specified compression level.
///
/// Level should be 1-22, where higher values give better compression
/// but are slower.
pub fn with_level(level: i32) -> Self {
Self {
level,
compressors: std::sync::Mutex::new(Vec::new()),
}
}
}
#[cfg(feature = "zstd")]
impl Default for ZstdProvider {
fn default() -> Self {
Self {
level: Self::DEFAULT_LEVEL,
compressors: std::sync::Mutex::new(Vec::new()),
}
}
}
#[cfg(feature = "zstd")]
impl ZstdProvider {
/// Maximum number of compressor instances to retain in the pool.
const MAX_POOL_SIZE: usize = 64;
fn take_compressor(&self) -> Result<zstd::bulk::Compressor<'static>, ConnectError> {
if let Some(c) = self
.compressors
.lock()
.unwrap_or_else(|e| e.into_inner())
.pop()
{
return Ok(c);
}
zstd::bulk::Compressor::new(self.level)
.map_err(|e| ConnectError::internal(format!("failed to create zstd compressor: {e}")))
}
fn return_compressor(&self, c: zstd::bulk::Compressor<'static>) {
let mut pool = self.compressors.lock().unwrap_or_else(|e| e.into_inner());
if pool.len() < Self::MAX_POOL_SIZE {
pool.push(c);
}
}
/// Decompress zstd data with an optional output-size cap.
///
/// Uses the streaming decoder rather than `bulk::Decompressor` because
/// the bulk API requires guessing an output buffer size up front (and
/// fails if the guess is too small). The streaming decoder handles any
/// compression ratio and allows precise `Read::take()` bounding.
fn decompress_impl(data: &[u8], max_size: Option<usize>) -> Result<Bytes, ConnectError> {
use std::io::Read;
let mut decoder = zstd::Decoder::new(data)
.map_err(|e| ConnectError::internal(format!("zstd decompression failed: {e}")))?;
// Pre-size the output buffer using the same heuristic as GzipProvider:
// for reasonable limits, reserve limit+1; for huge/no limits, guess
// from input size. Avoids repeated reallocation in read_to_end.
let capacity = match max_size {
Some(limit) if limit < 64 * 1024 * 1024 => limit.saturating_add(1),
_ => data.len().saturating_mul(4).max(256),
};
let mut decompressed = Vec::with_capacity(capacity);
match max_size {
Some(limit) => {
// Read at most limit+1 so we can detect overflow without
// allocating the entire stream.
decoder
.take((limit as u64).saturating_add(1))