1use crate::error::{ClusterError, Result};
8use scirs2_core::profiling::Profiler;
9use serde::{Deserialize, Serialize};
10use std::sync::atomic::{AtomicU64, Ordering};
11use std::sync::Arc;
12
13pub struct CompressionStrategy {
15 config: CompressionConfig,
16 #[allow(dead_code)]
17 profiler: Arc<Profiler>,
18 metrics: Arc<CompressionMetrics>,
19}
20
21#[derive(Debug, Clone, Serialize, Deserialize)]
23pub struct CompressionConfig {
24 pub default_algorithm: Algorithm,
26 pub auto_select: bool,
28 pub compression_threshold_bytes: usize,
30}
31
32impl Default for CompressionConfig {
33 fn default() -> Self {
34 Self {
35 default_algorithm: Algorithm::Zstd,
36 auto_select: true,
37 compression_threshold_bytes: 1024, }
39 }
40}
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
44pub enum Algorithm {
45 None,
47 Lz4,
49 Zstd,
51 Lzma,
53}
54
55impl std::fmt::Display for Algorithm {
56 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57 match self {
58 Algorithm::None => write!(f, "none"),
59 Algorithm::Lz4 => write!(f, "lz4"),
60 Algorithm::Zstd => write!(f, "zstd"),
61 Algorithm::Lzma => write!(f, "lzma"),
62 }
63 }
64}
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub enum AccessPattern {
69 Hot,
71 Warm,
73 Cold,
75}
76
77#[derive(Debug, Clone, Serialize, Deserialize)]
79pub struct CompressedData {
80 pub data: Vec<u8>,
82 pub original_size: usize,
84 pub algorithm: Algorithm,
86}
87
88pub struct CompressionMetrics {
90 total_bytes_in: AtomicU64,
91 total_bytes_out: AtomicU64,
92 compression_time_ns: AtomicU64,
93 decompression_time_ns: AtomicU64,
94 compression_count: AtomicU64,
95 decompression_count: AtomicU64,
96}
97
98impl Default for CompressionMetrics {
99 fn default() -> Self {
100 Self::new()
101 }
102}
103
104impl CompressionMetrics {
105 pub fn new() -> Self {
107 Self {
108 total_bytes_in: AtomicU64::new(0),
109 total_bytes_out: AtomicU64::new(0),
110 compression_time_ns: AtomicU64::new(0),
111 decompression_time_ns: AtomicU64::new(0),
112 compression_count: AtomicU64::new(0),
113 decompression_count: AtomicU64::new(0),
114 }
115 }
116
117 pub fn record_compression(
119 &self,
120 input_size: usize,
121 output_size: usize,
122 _algorithm: Algorithm,
123 elapsed_ns: u64,
124 ) {
125 self.total_bytes_in
126 .fetch_add(input_size as u64, Ordering::Relaxed);
127 self.total_bytes_out
128 .fetch_add(output_size as u64, Ordering::Relaxed);
129 self.compression_time_ns
130 .fetch_add(elapsed_ns, Ordering::Relaxed);
131 self.compression_count.fetch_add(1, Ordering::Relaxed);
132 }
133
134 pub fn record_decompression(&self, elapsed_ns: u64) {
136 self.decompression_time_ns
137 .fetch_add(elapsed_ns, Ordering::Relaxed);
138 self.decompression_count.fetch_add(1, Ordering::Relaxed);
139 }
140
141 pub fn compression_ratio(&self) -> f64 {
143 let bytes_in = self.total_bytes_in.load(Ordering::Relaxed) as f64;
144 let bytes_out = self.total_bytes_out.load(Ordering::Relaxed) as f64;
145 if bytes_in > 0.0 {
146 1.0 - (bytes_out / bytes_in)
147 } else {
148 0.0
149 }
150 }
151
152 pub fn compression_throughput_mbps(&self) -> f64 {
154 let bytes = self.total_bytes_in.load(Ordering::Relaxed) as f64;
155 let time_sec = self.compression_time_ns.load(Ordering::Relaxed) as f64 / 1_000_000_000.0;
156 if time_sec > 0.0 {
157 (bytes / 1_000_000.0) / time_sec
158 } else {
159 0.0
160 }
161 }
162
163 pub fn decompression_throughput_mbps(&self) -> f64 {
165 let bytes = self.total_bytes_out.load(Ordering::Relaxed) as f64;
166 let time_sec = self.decompression_time_ns.load(Ordering::Relaxed) as f64 / 1_000_000_000.0;
167 if time_sec > 0.0 {
168 (bytes / 1_000_000.0) / time_sec
169 } else {
170 0.0
171 }
172 }
173}
174
175impl CompressionStrategy {
176 pub fn new(config: CompressionConfig) -> Self {
178 Self {
179 config,
180 profiler: Arc::new(Profiler::new()),
181 metrics: Arc::new(CompressionMetrics::new()),
182 }
183 }
184
185 pub fn select_algorithm(&self, data: &[u8], access_pattern: AccessPattern) -> Algorithm {
187 if !self.config.auto_select {
188 return self.config.default_algorithm;
189 }
190
191 if data.len() < self.config.compression_threshold_bytes {
193 return Algorithm::None;
194 }
195
196 let compressibility = self.estimate_compressibility(data);
198 if compressibility < 0.1 {
199 return Algorithm::None;
201 }
202
203 match access_pattern {
205 AccessPattern::Hot => Algorithm::Lz4, AccessPattern::Warm => Algorithm::Zstd, AccessPattern::Cold => Algorithm::Lzma, }
209 }
210
211 pub fn compress(&self, data: &[u8]) -> Result<CompressedData> {
213 self.compress_with_pattern(data, AccessPattern::Warm)
214 }
215
216 pub fn compress_with_pattern(
218 &self,
219 data: &[u8],
220 access_pattern: AccessPattern,
221 ) -> Result<CompressedData> {
222 let algorithm = self.select_algorithm(data, access_pattern);
223
224 let start = std::time::Instant::now();
225 let compressed = match algorithm {
226 Algorithm::None => data.to_vec(),
227 Algorithm::Lz4 => self.compress_lz4(data)?,
228 Algorithm::Zstd => self.compress_zstd(data)?,
229 Algorithm::Lzma => self.compress_lzma(data)?,
230 };
231 let elapsed_ns = start.elapsed().as_nanos() as u64;
232
233 self.metrics
235 .record_compression(data.len(), compressed.len(), algorithm, elapsed_ns);
236
237 Ok(CompressedData {
238 data: compressed,
239 original_size: data.len(),
240 algorithm,
241 })
242 }
243
244 pub fn decompress(&self, compressed: &CompressedData) -> Result<Vec<u8>> {
246 let start = std::time::Instant::now();
247
248 let result = match compressed.algorithm {
249 Algorithm::None => Ok(compressed.data.clone()),
250 Algorithm::Lz4 => self.decompress_lz4(&compressed.data, compressed.original_size),
251 Algorithm::Zstd => self.decompress_zstd(&compressed.data, compressed.original_size),
252 Algorithm::Lzma => self.decompress_lzma(&compressed.data),
253 };
254
255 let elapsed_ns = start.elapsed().as_nanos() as u64;
256 self.metrics.record_decompression(elapsed_ns);
257
258 result
259 }
260
261 pub fn estimate_compressibility(&self, data: &[u8]) -> f64 {
264 if data.is_empty() {
265 return 0.0;
266 }
267
268 let mut counts = [0u32; 256];
270 for &byte in data {
271 counts[byte as usize] += 1;
272 }
273
274 let len = data.len() as f64;
276 let mut entropy = 0.0;
277 for &count in &counts {
278 if count > 0 {
279 let p = count as f64 / len;
280 entropy -= p * p.log2();
281 }
282 }
283
284 1.0 - (entropy / 8.0)
287 }
288
289 fn compress_lz4(&self, data: &[u8]) -> Result<Vec<u8>> {
291 oxiarc_lz4::compress(data)
292 .map_err(|e| ClusterError::Compression(format!("LZ4 compression failed: {e}")))
293 }
294
295 fn decompress_lz4(&self, data: &[u8], _expected_size: usize) -> Result<Vec<u8>> {
296 oxiarc_lz4::decompress(data, 100 * 1024 * 1024)
297 .map_err(|e| ClusterError::Compression(format!("LZ4 decompression failed: {e}")))
298 }
299
300 fn compress_zstd(&self, data: &[u8]) -> Result<Vec<u8>> {
302 oxiarc_zstd::encode_all(data, 3)
303 .map_err(|e| ClusterError::Compression(format!("Zstd compression failed: {e}")))
304 }
305
306 fn decompress_zstd(&self, data: &[u8], _expected_size: usize) -> Result<Vec<u8>> {
307 oxiarc_zstd::decode_all(data)
309 .map_err(|e| ClusterError::Compression(format!("Zstd decompression failed: {e}")))
310 }
311
312 fn compress_lzma(&self, data: &[u8]) -> Result<Vec<u8>> {
317 oxiarc_lzma::compress_bytes(data)
318 .map_err(|e| ClusterError::Compression(format!("LZMA compression failed: {e}")))
319 }
320
321 fn decompress_lzma(&self, data: &[u8]) -> Result<Vec<u8>> {
322 oxiarc_lzma::decompress_bytes(data)
323 .map_err(|e| ClusterError::Compression(format!("LZMA decompression failed: {e}")))
324 }
325
326 pub fn metrics(&self) -> &Arc<CompressionMetrics> {
328 &self.metrics
329 }
330
331 pub fn config(&self) -> &CompressionConfig {
333 &self.config
334 }
335}
336
337#[cfg(test)]
338mod tests {
339 use super::*;
340
341 #[test]
342 fn test_compression_strategy_creation() {
343 let config = CompressionConfig::default();
344 let strategy = CompressionStrategy::new(config);
345 assert!(strategy.config().auto_select);
346 }
347
348 #[test]
349 fn test_algorithm_selection_small_data() {
350 let config = CompressionConfig {
351 default_algorithm: Algorithm::Zstd,
352 auto_select: true,
353 compression_threshold_bytes: 1024,
354 };
355 let strategy = CompressionStrategy::new(config);
356
357 let small_data = vec![0u8; 512];
359 let algorithm = strategy.select_algorithm(&small_data, AccessPattern::Warm);
360 assert_eq!(algorithm, Algorithm::None);
361 }
362
363 #[test]
364 fn test_algorithm_selection_by_pattern() {
365 let config = CompressionConfig::default();
366 let strategy = CompressionStrategy::new(config);
367
368 let data = vec![65u8; 10000]; let hot_algo = strategy.select_algorithm(&data, AccessPattern::Hot);
371 assert_eq!(hot_algo, Algorithm::Lz4);
372
373 let warm_algo = strategy.select_algorithm(&data, AccessPattern::Warm);
374 assert_eq!(warm_algo, Algorithm::Zstd);
375
376 let cold_algo = strategy.select_algorithm(&data, AccessPattern::Cold);
377 assert_eq!(cold_algo, Algorithm::Lzma);
378 }
379
380 #[test]
381 fn test_compressibility_estimation() {
382 let config = CompressionConfig::default();
383 let strategy = CompressionStrategy::new(config);
384
385 let compressible = vec![42u8; 1000];
387 let score1 = strategy.estimate_compressibility(&compressible);
388 assert!(score1 > 0.9, "Expected high compressibility score");
389
390 use scirs2_core::random::Random;
392 let mut rng = Random::seed(
393 std::time::SystemTime::now()
394 .duration_since(std::time::UNIX_EPOCH)
395 .map_or(0, |d| d.as_secs()),
396 );
397 let random_data: Vec<u8> = (0..1000).map(|_| rng.random_range(0..256) as u8).collect();
398 let score2 = strategy.estimate_compressibility(&random_data);
399 assert!(
400 score2 < 0.2,
401 "Expected low compressibility score for random data"
402 );
403 }
404
405 #[test]
406 fn test_lz4_round_trip() {
407 let config = CompressionConfig {
408 default_algorithm: Algorithm::Lz4,
409 auto_select: false,
410 compression_threshold_bytes: 0,
411 };
412 let strategy = CompressionStrategy::new(config);
413
414 let original = b"Hello, world! This is a test string for LZ4 compression.".repeat(100);
415 let compressed = strategy.compress(&original).expect("Compression failed");
416 assert!(compressed.data.len() < original.len());
417 assert_eq!(compressed.algorithm, Algorithm::Lz4);
418
419 let decompressed = strategy
420 .decompress(&compressed)
421 .expect("Decompression failed");
422 assert_eq!(decompressed, original);
423 }
424
425 #[test]
426 fn test_zstd_round_trip() {
427 let config = CompressionConfig {
428 default_algorithm: Algorithm::Zstd,
429 auto_select: false,
430 compression_threshold_bytes: 0,
431 };
432 let strategy = CompressionStrategy::new(config);
433
434 let original = b"Hello, world! This is a test string for Zstd compression.".repeat(100);
435 let compressed = strategy.compress(&original).expect("Compression failed");
436 assert!(compressed.data.len() < original.len());
437 assert_eq!(compressed.algorithm, Algorithm::Zstd);
438
439 let decompressed = strategy
440 .decompress(&compressed)
441 .expect("Decompression failed");
442 assert_eq!(decompressed, original);
443 }
444
445 #[test]
446 fn test_lzma_round_trip() {
447 let config = CompressionConfig {
448 default_algorithm: Algorithm::Lzma,
449 auto_select: false,
450 compression_threshold_bytes: 0,
451 };
452 let strategy = CompressionStrategy::new(config);
453
454 let original = b"Hello, world! This is a test string for LZMA compression.".repeat(100);
455 let compressed = strategy.compress(&original).expect("Compression failed");
456 assert!(compressed.data.len() < original.len());
457 assert_eq!(compressed.algorithm, Algorithm::Lzma);
458
459 let decompressed = strategy
460 .decompress(&compressed)
461 .expect("Decompression failed");
462 assert_eq!(decompressed, original);
463 }
464
465 #[test]
469 fn test_lzma_round_trip_small_and_edge_inputs() {
470 let config = CompressionConfig {
471 default_algorithm: Algorithm::Lzma,
472 auto_select: false,
473 compression_threshold_bytes: 0,
474 };
475 let strategy = CompressionStrategy::new(config);
476
477 let cases: &[&[u8]] = &[b"", b"a", b"abc", b"The quick brown fox.", &[0xABu8; 33]];
478 for original in cases {
479 let compressed = strategy
480 .compress(original)
481 .expect("LZMA compression failed");
482 assert_eq!(compressed.algorithm, Algorithm::Lzma);
483 let decompressed = strategy
484 .decompress(&compressed)
485 .expect("LZMA decompression failed");
486 assert_eq!(
487 decompressed.as_slice(),
488 *original,
489 "LZMA round-trip failed for {}-byte input",
490 original.len()
491 );
492 }
493 }
494
495 #[test]
496 fn test_compression_metrics() {
497 let config = CompressionConfig::default();
498 let strategy = CompressionStrategy::new(config);
499
500 let original = b"Test data for metrics".repeat(100);
501 let _compressed = strategy.compress(&original).expect("Compression failed");
502
503 let metrics = strategy.metrics();
504 assert!(metrics.compression_ratio() > 0.0);
505 assert!(metrics.compression_throughput_mbps() > 0.0);
506 }
507
508 #[test]
509 fn test_none_algorithm() {
510 let config = CompressionConfig {
511 default_algorithm: Algorithm::None,
512 auto_select: false,
513 compression_threshold_bytes: 0,
514 };
515 let strategy = CompressionStrategy::new(config);
516
517 let original = b"Test data";
518 let compressed = strategy.compress(original).expect("Compression failed");
519 assert_eq!(compressed.data, original);
520 assert_eq!(compressed.algorithm, Algorithm::None);
521
522 let decompressed = strategy
523 .decompress(&compressed)
524 .expect("Decompression failed");
525 assert_eq!(decompressed, original);
526 }
527}