ferriskey 0.1.1

Rust client for Valkey, built for FlowFabric. Forked from glide-core (valkey-glide).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
// Copyright Valkey GLIDE Project Contributors - SPDX Identifier: Apache-2.0

//! Compression module providing automatic compression and decompression capabilities
//! for Valkey Glide client operations.

use std::borrow::Cow;
use std::fmt;

use crate::request_type::RequestType;

/// Detailed compression error with context for debugging
#[derive(Debug, Clone, PartialEq)]
pub enum CompressionError {
    /// Compression operation failed with detailed context
    CompressionFailed {
        backend: String,
        level: Option<i32>,
        data_size: usize,
        reason: String,
    },
    /// Decompression operation failed with detailed context
    DecompressionFailed {
        backend: String,
        data_size: usize,
        reason: String,
    },
    /// Unsupported compression backend
    UnsupportedBackend { backend_name: String },
    /// Invalid compression configuration
    InvalidConfiguration { backend: String, reason: String },
}

impl std::fmt::Display for CompressionError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CompressionError::CompressionFailed {
                backend,
                level,
                data_size,
                reason,
            } => {
                write!(
                    f,
                    "Compression operation failed: {} encoding failed",
                    backend.to_uppercase()
                )?;
                if let Some(lvl) = level {
                    write!(f, " at level {}", lvl)?;
                }
                write!(f, " for {} data", format_size(*data_size))?;
                if !reason.is_empty() {
                    write!(f, ": {}", reason)?;
                }
                Ok(())
            }
            CompressionError::DecompressionFailed {
                backend,
                data_size,
                reason,
            } => {
                write!(
                    f,
                    "Decompression operation failed: {} decoding failed for {} data",
                    backend.to_uppercase(),
                    format_size(*data_size)
                )?;
                if !reason.is_empty() {
                    write!(f, ": {}", reason)?;
                }
                Ok(())
            }
            CompressionError::UnsupportedBackend { backend_name } => {
                write!(f, "Unsupported compression backend: '{}'", backend_name)
            }
            CompressionError::InvalidConfiguration { backend, reason } => {
                write!(
                    f,
                    "Invalid compression configuration for '{}': {}",
                    backend, reason
                )
            }
        }
    }
}

impl std::error::Error for CompressionError {}

impl CompressionError {
    pub fn compression_failed(
        backend: &str,
        level: Option<i32>,
        data_size: usize,
        reason: impl Into<String>,
    ) -> Self {
        Self::CompressionFailed {
            backend: backend.to_string(),
            level,
            data_size,
            reason: reason.into(),
        }
    }

    pub fn decompression_failed(
        backend: &str,
        data_size: usize,
        reason: impl Into<String>,
    ) -> Self {
        Self::DecompressionFailed {
            backend: backend.to_string(),
            data_size,
            reason: reason.into(),
        }
    }

    pub fn unsupported_backend(backend_name: impl Into<String>) -> Self {
        Self::UnsupportedBackend {
            backend_name: backend_name.into(),
        }
    }

    pub fn invalid_configuration(backend: impl Into<String>, reason: impl Into<String>) -> Self {
        Self::InvalidConfiguration {
            backend: backend.into(),
            reason: reason.into(),
        }
    }

    /// Returns the backend name associated with this error
    pub fn backend(&self) -> &str {
        match self {
            CompressionError::CompressionFailed { backend, .. } => backend,
            CompressionError::DecompressionFailed { backend, .. } => backend,
            CompressionError::InvalidConfiguration { backend, .. } => backend,
            CompressionError::UnsupportedBackend { backend_name } => backend_name,
        }
    }
}

/// Format byte size in human-readable format
fn format_size(bytes: usize) -> String {
    const KB: usize = 1024;
    const MB: usize = KB * 1024;
    const GB: usize = MB * 1024;

    if bytes >= GB {
        format!("{:.2}GB", bytes as f64 / GB as f64)
    } else if bytes >= MB {
        format!("{:.2}MB", bytes as f64 / MB as f64)
    } else if bytes >= KB {
        format!("{:.2}KB", bytes as f64 / KB as f64)
    } else {
        format!("{}B", bytes)
    }
}

pub type CompressionResult<T> = Result<T, CompressionError>;

pub trait CompressionBackend: Send + Sync + fmt::Debug {
    fn compress(&self, data: &[u8], level: Option<i32>) -> CompressionResult<Vec<u8>>;
    fn decompress(&self, data: &[u8]) -> CompressionResult<Vec<u8>>;
    fn is_compressed(&self, data: &[u8]) -> bool;
    fn backend_name(&self) -> &'static str;
    fn default_level(&self) -> Option<i32>;
    fn backend_id(&self) -> u8;
    fn validate_compression_level(&self, level: Option<i32>) -> CompressionResult<()>;
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CompressionBackendType {
    Zstd,
    Lz4,
}

impl CompressionBackendType {
    pub fn backend_id(&self) -> u8 {
        match self {
            CompressionBackendType::Zstd => 0x01,
            CompressionBackendType::Lz4 => 0x02,
        }
    }

    pub fn backend_name(&self) -> &'static str {
        match self {
            CompressionBackendType::Zstd => "zstd",
            CompressionBackendType::Lz4 => "lz4",
        }
    }

    pub fn default_level(&self) -> Option<i32> {
        match self {
            CompressionBackendType::Zstd => Some(3),
            CompressionBackendType::Lz4 => Some(0), // LZ4 default compression
        }
    }
}

impl std::fmt::Display for CompressionBackendType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.backend_name())
    }
}

impl std::str::FromStr for CompressionBackendType {
    type Err = CompressionError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "zstd" => Ok(CompressionBackendType::Zstd),
            "lz4" => Ok(CompressionBackendType::Lz4),
            _ => Err(CompressionError::unsupported_backend(s)),
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct CompressionConfig {
    pub enabled: bool,
    pub backend: CompressionBackendType,
    pub compression_level: Option<i32>,
    pub min_compression_size: usize,
}

impl CompressionConfig {
    pub fn new(backend: CompressionBackendType) -> Self {
        Self {
            enabled: true,
            backend,
            compression_level: backend.default_level(),
            min_compression_size: 64,
        }
    }

    pub fn disabled() -> Self {
        Self {
            enabled: false,
            backend: CompressionBackendType::Zstd,
            compression_level: None,
            min_compression_size: 64,
        }
    }

    pub fn with_compression_level(mut self, level: Option<i32>) -> Self {
        self.compression_level = level;
        self
    }

    pub fn with_min_compression_size(mut self, size: usize) -> Self {
        self.min_compression_size = size;
        self
    }

    pub fn validate(&self) -> CompressionResult<()> {
        if self.min_compression_size < MIN_COMPRESSED_SIZE {
            return Err(CompressionError::invalid_configuration(
                self.backend.backend_name(),
                format!(
                    "min_compression_size ({}) must be at least {}",
                    self.min_compression_size, MIN_COMPRESSED_SIZE
                ),
            ));
        }

        Ok(())
    }

    pub fn should_compress(&self, data_size: usize) -> bool {
        self.enabled && data_size >= self.min_compression_size
    }
}

impl Default for CompressionConfig {
    fn default() -> Self {
        Self::disabled()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CommandCompressionBehavior {
    CompressValues,
    DecompressValues,
    NoCompression,
}

impl std::fmt::Display for CommandCompressionBehavior {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CommandCompressionBehavior::CompressValues => write!(f, "CompressValues"),
            CommandCompressionBehavior::DecompressValues => write!(f, "DecompressValues"),
            CommandCompressionBehavior::NoCompression => write!(f, "NoCompression"),
        }
    }
}

#[derive(Debug)]
pub struct CompressionManager {
    backend: Box<dyn CompressionBackend>,
    config: CompressionConfig,
}

impl CompressionManager {
    pub fn new(
        backend: Box<dyn CompressionBackend>,
        config: CompressionConfig,
    ) -> CompressionResult<Self> {
        config.validate()?;

        if backend.backend_id() != config.backend.backend_id() {
            return Err(CompressionError::invalid_configuration(
                config.backend.backend_name(),
                format!(
                    "backend mismatch: expected {} (id: {}), got backend with id {}",
                    config.backend.backend_name(),
                    config.backend.backend_id(),
                    backend.backend_id()
                ),
            ));
        }

        // Validate compression level using backend-specific validation
        backend.validate_compression_level(config.compression_level)?;

        Ok(Self { backend, config })
    }

    pub fn should_compress(&self, data: &[u8]) -> bool {
        self.config.should_compress(data.len())
    }

    /// Attempts to compress the value with graceful fallback to original data
    pub fn compress_value<'a>(&self, value: &'a [u8]) -> Cow<'a, [u8]> {
        if !self.config.enabled || !self.should_compress(value) {
            return Cow::Borrowed(value);
        }

        if self.backend.is_compressed(value) {
            return Cow::Borrowed(value);
        }

        match self.backend.compress(value, self.config.compression_level) {
            Ok(compressed) => {
                if compressed.len() < value.len() {
                    Cow::Owned(compressed)
                } else {
                    Cow::Borrowed(value)
                }
            }
            Err(err) => {
                tracing::warn!(
                    target: "ferriskey",
                    event = "compression_failed",
                    error = %err,
                    "ferriskey: compression failed, passing through"
                );
                Cow::Borrowed(value)
            }
        }
    }

    pub fn decompress_value(&self, value: &[u8]) -> CompressionResult<Vec<u8>> {
        if !self.config.enabled {
            return Ok(value.to_vec());
        }

        if !has_magic_header(value) {
            return Ok(value.to_vec());
        }

        // Extract backend ID from header and route to appropriate backend
        if let Some(backend_id) = extract_backend_id(value) {
            // If the data was compressed with our configured backend, use it
            // This respects the client's compression configuration
            if backend_id == self.backend.backend_id() {
                self.backend.decompress(value)
            } else {
                let backend = get_backend_for_decompression(backend_id)?;
                backend.decompress(value)
            }
        } else {
            Ok(value.to_vec())
        }
    }

    pub fn config(&self) -> &CompressionConfig {
        &self.config
    }

    pub fn backend_name(&self) -> &'static str {
        self.backend.backend_name()
    }

    pub fn is_enabled(&self) -> bool {
        self.config.enabled
    }

    /// Attempts to decompress the value with graceful fallback to original data.
    ///
    /// On decompression failure, logs a warning and returns the original raw bytes.
    /// This is an intentional fallback: returning raw bytes prevents silent data
    /// corruption (the caller receives bytes it can inspect) while avoiding a hard
    /// error for a non-critical path.  Corruption would only occur if the bytes
    /// happened to look like valid data of the expected type, which is detectable
    /// by the caller.
    pub fn try_decompress_value(&self, value: &[u8]) -> Vec<u8> {
        self.decompress_value(value).unwrap_or_else(|err| {
            tracing::warn!("compression - Decompression failed, returning raw bytes as fallback: {err:?}");
            value.to_vec()
        })
    }
}

pub mod zstd_backend {
    use super::*;

    #[derive(Debug)]
    pub struct ZstdBackend {
        default_level: i32,
    }

    impl ZstdBackend {
        pub fn new() -> Self {
            Self { default_level: 3 }
        }
    }

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

    impl CompressionBackend for ZstdBackend {
        fn compress(&self, data: &[u8], level: Option<i32>) -> CompressionResult<Vec<u8>> {
            let compression_level = level.unwrap_or(self.default_level);

            self.validate_compression_level(Some(compression_level))?;

            let compressed_data = zstd::encode_all(data, compression_level).map_err(|e| {
                CompressionError::compression_failed(
                    self.backend_name(),
                    Some(compression_level),
                    data.len(),
                    e.to_string(),
                )
            })?;

            let header = create_header(self.backend_id());

            let mut result = Vec::with_capacity(header.len() + compressed_data.len());
            result.extend_from_slice(&header);
            result.extend_from_slice(&compressed_data);

            Ok(result)
        }

        fn decompress(&self, data: &[u8]) -> CompressionResult<Vec<u8>> {
            if !self.is_compressed(data) {
                return Err(CompressionError::decompression_failed(
                    self.backend_name(),
                    data.len(),
                    "data is not compressed or has invalid header",
                ));
            }

            let compressed_data = &data[HEADER_SIZE..];

            // Use streaming decoder with output size limit to prevent zip bombs.
            // Note: limit is approximate — actual output may exceed by up to one read chunk (~128KB).
            const MAX_DECOMPRESSED_SIZE: usize = 256 * 1024 * 1024; // 256 MB

            let mut decoder = zstd::stream::Decoder::new(compressed_data).map_err(|e| {
                CompressionError::decompression_failed(
                    self.backend_name(),
                    data.len(),
                    e.to_string(),
                )
            })?;

            let mut decompressed_data = Vec::new();
            let mut buf = [0u8; 64 * 1024]; // 64 KB read buffer
            loop {
                let n = std::io::Read::read(&mut decoder, &mut buf).map_err(|e| {
                    CompressionError::decompression_failed(
                        self.backend_name(),
                        data.len(),
                        e.to_string(),
                    )
                })?;
                if n == 0 {
                    break;
                }
                if decompressed_data.len() + n > MAX_DECOMPRESSED_SIZE {
                    return Err(CompressionError::decompression_failed(
                        self.backend_name(),
                        data.len(),
                        format!(
                            "Decompressed output exceeds maximum allowed size of {} bytes",
                            MAX_DECOMPRESSED_SIZE
                        ),
                    ));
                }
                decompressed_data.extend_from_slice(&buf[..n]);
            }

            Ok(decompressed_data)
        }

        fn is_compressed(&self, data: &[u8]) -> bool {
            has_magic_header(data) && extract_backend_id(data) == Some(self.backend_id())
        }

        fn backend_name(&self) -> &'static str {
            "zstd"
        }

        fn default_level(&self) -> Option<i32> {
            Some(self.default_level)
        }

        fn backend_id(&self) -> u8 {
            CompressionBackendType::Zstd.backend_id()
        }

        fn validate_compression_level(&self, level: Option<i32>) -> CompressionResult<()> {
            if let Some(level) = level {
                let range = zstd::compression_level_range();
                if !range.contains(&level) {
                    return Err(CompressionError::invalid_configuration(
                        self.backend_name(),
                        format!(
                            "compression level {} is out of valid range {}..={}",
                            level,
                            range.start(),
                            range.end()
                        ),
                    ));
                }
            }
            Ok(())
        }
    }
}

pub mod lz4_backend {
    use super::*;

    /// LZ4 compression level ranges:
    /// - Level 0: Default compression (balanced speed/ratio)
    /// - Levels 1-12: High compression mode (higher = better ratio, slower)
    /// - Levels < 0: Fast mode with acceleration (more negative = faster, lower ratio)
    const LZ4_MIN_LEVEL: i32 = -128; // Practical minimum for fast mode
    const LZ4_MAX_LEVEL: i32 = 12; // Maximum for high compression mode
    const LZ4_DEFAULT_LEVEL: i32 = 0;

    #[derive(Debug)]
    pub struct Lz4Backend {
        default_level: i32,
    }

    impl Lz4Backend {
        pub fn new() -> Self {
            Self {
                default_level: LZ4_DEFAULT_LEVEL,
            }
        }
    }

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

    impl CompressionBackend for Lz4Backend {
        fn compress(&self, data: &[u8], level: Option<i32>) -> CompressionResult<Vec<u8>> {
            let compression_level = level.unwrap_or(self.default_level);

            self.validate_compression_level(Some(compression_level))?;

            let original_size =
                i32::try_from(data.len()).map_err(|_| CompressionError::CompressionFailed {
                    backend: self.backend_name().to_string(),
                    level: None,
                    data_size: data.len(),
                    reason: format!(
                        "Data too large for LZ4: {} bytes (max: {} bytes)",
                        data.len(),
                        i32::MAX
                    ),
                })?;
            let size_bytes = (original_size as u32).to_le_bytes();

            // Choose compression mode based on level:
            // - level > 0: High compression mode
            // - level == 0: Default mode
            // - level < 0: Fast mode with acceleration
            let mode = if compression_level > 0 {
                Some(lz4::block::CompressionMode::HIGHCOMPRESSION(
                    compression_level,
                ))
            } else if compression_level < 0 {
                // Convert negative level to positive acceleration value
                Some(lz4::block::CompressionMode::FAST(-compression_level))
            } else {
                Some(lz4::block::CompressionMode::DEFAULT)
            };

            let compressed_block = lz4::block::compress(data, mode, false).map_err(|e| {
                CompressionError::compression_failed(
                    self.backend_name(),
                    Some(compression_level),
                    data.len(),
                    e.to_string(),
                )
            })?;

            let mut compressed_data = Vec::with_capacity(4 + compressed_block.len());
            compressed_data.extend_from_slice(&size_bytes);
            compressed_data.extend_from_slice(&compressed_block);

            let header = create_header(self.backend_id());

            let mut result = Vec::with_capacity(header.len() + compressed_data.len());
            result.extend_from_slice(&header);
            result.extend_from_slice(&compressed_data);

            Ok(result)
        }

        fn decompress(&self, data: &[u8]) -> CompressionResult<Vec<u8>> {
            if !self.is_compressed(data) {
                return Err(CompressionError::decompression_failed(
                    self.backend_name(),
                    data.len(),
                    "data is not compressed or has invalid header",
                ));
            }

            let compressed_data = &data[HEADER_SIZE..];

            if compressed_data.len() < 4 {
                return Err(CompressionError::decompression_failed(
                    self.backend_name(),
                    data.len(),
                    "compressed data too short: missing size header",
                ));
            }

            let size_bytes = &compressed_data[0..4];
            let original_size_u32 =
                u32::from_le_bytes([size_bytes[0], size_bytes[1], size_bytes[2], size_bytes[3]]);
            let compressed_block = &compressed_data[4..];

            // Validate decompressed size against a reasonable maximum to prevent
            // attacker-controlled allocations from a tiny payload
            const MAX_DECOMPRESSED_SIZE: u32 = 256 * 1024 * 1024; // 256 MB
            if original_size_u32 > MAX_DECOMPRESSED_SIZE {
                return Err(CompressionError::decompression_failed(
                    self.backend_name(),
                    data.len(),
                    format!(
                        "Declared uncompressed size {} bytes exceeds maximum allowed size of {} bytes",
                        original_size_u32, MAX_DECOMPRESSED_SIZE
                    ),
                ));
            }

            // LZ4 block decompression requires knowing the uncompressed size
            // The API uses i32, so we must reject sizes that don't fit
            let original_size = i32::try_from(original_size_u32).map_err(|_| {
                CompressionError::decompression_failed(
                    self.backend_name(),
                    data.len(),
                    format!(
                        "Uncompressed size {} bytes exceeds LZ4 block API limit ({} bytes)",
                        original_size_u32,
                        i32::MAX
                    ),
                )
            })?;

            let decompressed_data = lz4::block::decompress(compressed_block, Some(original_size))
                .map_err(|e| {
                CompressionError::decompression_failed(
                    self.backend_name(),
                    data.len(),
                    e.to_string(),
                )
            })?;

            Ok(decompressed_data)
        }

        fn is_compressed(&self, data: &[u8]) -> bool {
            has_magic_header(data) && extract_backend_id(data) == Some(self.backend_id())
        }

        fn backend_name(&self) -> &'static str {
            "lz4"
        }

        fn default_level(&self) -> Option<i32> {
            Some(self.default_level)
        }

        fn backend_id(&self) -> u8 {
            CompressionBackendType::Lz4.backend_id()
        }

        fn validate_compression_level(&self, level: Option<i32>) -> CompressionResult<()> {
            if let Some(level) = level
                && !(LZ4_MIN_LEVEL..=LZ4_MAX_LEVEL).contains(&level)
            {
                return Err(CompressionError::invalid_configuration(
                    self.backend_name(),
                    format!(
                        "compression level {} is out of valid range {}..={}",
                        level, LZ4_MIN_LEVEL, LZ4_MAX_LEVEL
                    ),
                ));
            }
            Ok(())
        }
    }
}

pub fn process_command_args_for_compression(
    args: &mut [Vec<u8>],
    request_type: RequestType,
    compression_manager: Option<&CompressionManager>,
) -> CompressionResult<()> {
    let Some(manager) = compression_manager else {
        return Ok(());
    };

    if !manager.is_enabled() {
        return Ok(());
    }

    let behavior = request_type.compression_behavior();
    if behavior != CommandCompressionBehavior::CompressValues {
        return Ok(());
    }

    match request_type {
        RequestType::Set => compress_single_value_command(args, manager, 1),
        RequestType::MSet | RequestType::MSetNX => compress_mset_command(args, manager),
        RequestType::SetEx => compress_single_value_command(args, manager, 2),
        RequestType::PSetEx => compress_single_value_command(args, manager, 2),
        RequestType::SetNX => compress_single_value_command(args, manager, 1),
        _ => Ok(()),
    }
}

fn compress_single_value_command(
    args: &mut [Vec<u8>],
    manager: &CompressionManager,
    value_index: usize,
) -> CompressionResult<()> {
    if args.len() <= value_index {
        return Ok(());
    }

    let compressed_value = manager.compress_value(&args[value_index]);
    args[value_index] = compressed_value.into_owned();
    Ok(())
}

fn compress_mset_command(
    args: &mut [Vec<u8>],
    manager: &CompressionManager,
) -> CompressionResult<()> {
    // MSET format: key1 value1 key2 value2 ...
    // Values are at indices 1, 3, 5, etc. (odd indices starting from 1)
    let mut i = 1;
    while i < args.len() {
        let compressed_value = manager.compress_value(&args[i]);
        args[i] = compressed_value.into_owned();
        i += 2; // Skip to next value (skip the key)
    }
    Ok(())
}

pub fn process_response_for_decompression(
    value: crate::value::Value,
    request_type: RequestType,
    compression_manager: Option<&CompressionManager>,
) -> CompressionResult<crate::value::Value> {
    use crate::value::Value;

    let Some(manager) = compression_manager else {
        return Ok(value);
    };

    if !manager.is_enabled() {
        return Ok(value);
    }

    let behavior = request_type.compression_behavior();
    if behavior != CommandCompressionBehavior::DecompressValues {
        return Ok(value);
    }

    if matches!(value, Value::Nil) {
        return Ok(value);
    }

    match request_type {
        RequestType::Get => decompress_single_value_response(value, manager),
        RequestType::MGet => decompress_mget_response(value, manager),
        RequestType::GetEx => decompress_single_value_response(value, manager),
        RequestType::GetDel => decompress_single_value_response(value, manager),
        RequestType::GetSet => decompress_single_value_response(value, manager),
        _ => Ok(value),
    }
}

pub fn decompress_single_value_response(
    value: crate::value::Value,
    manager: &CompressionManager,
) -> CompressionResult<crate::value::Value> {
    use crate::value::Value;

    match value {
        Value::BulkString(bytes) => {
            let decompressed = manager.try_decompress_value(&bytes);
            Ok(Value::BulkString(bytes::Bytes::from(decompressed)))
        }
        Value::SimpleString(s) => {
            let decompressed = manager.try_decompress_value(s.as_bytes());
            match String::from_utf8(decompressed) {
                Ok(decompressed_string) => Ok(Value::SimpleString(decompressed_string)),
                Err(e) => Ok(Value::BulkString(bytes::Bytes::from(e.into_bytes()))),
            }
        }
        _ => Ok(value),
    }
}

pub fn decompress_mget_response(
    value: crate::value::Value,
    manager: &CompressionManager,
) -> CompressionResult<crate::value::Value> {
    use crate::value::Value;

    match value {
        Value::Array(values) => {
            let decompressed: Vec<crate::value::Result<Value>> = values
                .into_iter()
                .map(|v| match v {
                    Ok(val) => Ok(Ok(decompress_single_value_response(val, manager)?)),
                    Err(e) => Ok(Err(e)),
                })
                .collect::<CompressionResult<Vec<_>>>()?;
            Ok(Value::Array(decompressed))
        }
        _ => Ok(value),
    }
}

/// Magic prefix for compressed data headers (first 3 bytes)
pub const MAGIC_PREFIX: [u8; 3] = [0x00, 0x01, 0x02];

/// Index in header for version byte and backend_id
pub const HEADER_VERSION_INDEX: usize = 3;
pub const HEADER_BACKEND_INDEX: usize = 4;

/// Current compression format version
pub const CURRENT_VERSION: u8 = 0x00;

/// Total header size: 3 bytes magic + 1 byte version + 1 byte backend_id
pub const HEADER_SIZE: usize = 5;
pub const MIN_COMPRESSED_SIZE: usize = HEADER_SIZE + 1;

/// Checks if data has a valid magic header (any version)
pub fn has_magic_header(data: &[u8]) -> bool {
    data.len() >= HEADER_SIZE && data[0..3] == MAGIC_PREFIX
}

/// Extracts the version byte from the header
/// Returns None if the data doesn't have a valid magic header
pub fn extract_version(data: &[u8]) -> Option<u8> {
    if has_magic_header(data) {
        Some(data[HEADER_VERSION_INDEX])
    } else {
        None
    }
}

/// Extracts the backend ID from the header
/// Returns None if the data doesn't have a valid magic header
pub fn extract_backend_id(data: &[u8]) -> Option<u8> {
    if has_magic_header(data) {
        Some(data[HEADER_BACKEND_INDEX])
    } else {
        None
    }
}

/// Checks if the data has a valid magic header with the current version
pub fn has_current_version_header(data: &[u8]) -> bool {
    extract_version(data) == Some(CURRENT_VERSION)
}

/// Creates a compression header with the current version
pub fn create_header(backend_id: u8) -> [u8; HEADER_SIZE] {
    create_header_with_version(backend_id, CURRENT_VERSION)
}

/// Creates a compression header with a specific version
/// This is useful for testing or supporting multiple versions
pub fn create_header_with_version(backend_id: u8, version: u8) -> [u8; HEADER_SIZE] {
    let mut header = [0u8; HEADER_SIZE];
    header[0..3].copy_from_slice(&MAGIC_PREFIX);
    header[HEADER_VERSION_INDEX] = version;
    header[HEADER_BACKEND_INDEX] = backend_id;
    header
}

/// Lazy-initialized static backends for decompression-only operations.
///
/// These backends are shared across all compression managers to avoid repeated allocations
/// when decompressing data from different backends. They are separate from the client's
/// configured backend because:
///
/// 1. **Performance**: Static backends are initialized once and reused, eliminating allocations
/// 2. **Configuration independence**: When decompressing, the compression config (level, etc.)
///    is irrelevant - we only need the decompression algorithm
/// 3. **Client backend priority**: The client's configured backend is still used for its own
///    compressed data, respecting the client's specific configuration
///
/// Thread-safe initialization is guaranteed by `OnceLock`.
mod static_backends {
    use super::*;
    use std::sync::OnceLock;

    static ZSTD_BACKEND: OnceLock<zstd_backend::ZstdBackend> = OnceLock::new();
    static LZ4_BACKEND: OnceLock<lz4_backend::Lz4Backend> = OnceLock::new();

    pub fn get_zstd_backend() -> &'static zstd_backend::ZstdBackend {
        ZSTD_BACKEND.get_or_init(zstd_backend::ZstdBackend::new)
    }

    pub fn get_lz4_backend() -> &'static lz4_backend::Lz4Backend {
        LZ4_BACKEND.get_or_init(lz4_backend::Lz4Backend::new)
    }
}

/// Gets a reference to a static backend for decompression based on backend ID.
/// These backends are shared and initialized once, avoiding repeated allocations.
fn get_backend_for_decompression(
    backend_id: u8,
) -> CompressionResult<&'static dyn CompressionBackend> {
    match backend_id {
        0x01 => Ok(static_backends::get_zstd_backend()),
        0x02 => Ok(static_backends::get_lz4_backend()),
        _ => Err(CompressionError::unsupported_backend(format!(
            "backend ID 0x{:02x}",
            backend_id
        ))),
    }
}