inklog 0.3.0-rc.2

Enterprise-grade Rust logging infrastructure
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
// Copyright (c) 2026 Kirky.X
// SPDX-License-Identifier: MIT
//! Compression strategies for log files.
//!
//! This module provides a strategy pattern implementation for log file compression,
//! supporting multiple compression algorithms (Zstd, Gzip, etc.).

use crate::InklogError;
use std::fs::File;
use std::io::{BufReader, Read};
#[cfg(feature = "compression")]
use std::io::{BufWriter, Write};
use std::path::{Path, PathBuf};
use tracing::error;

/// Trait for compression strategies.
///
/// Implement this trait to define custom compression algorithms.
pub trait CompressionStrategy: Send + Sync {
    /// Compress the given data.
    fn compress(&self, data: &[u8]) -> Result<Vec<u8>, InklogError>;

    /// Decompress the given data.
    fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, InklogError>;

    /// Get the file extension for this compression format.
    fn extension(&self) -> &'static str;

    /// Get the name of this compression algorithm.
    fn name(&self) -> &'static str;

    /// Compress a file at the given path.
    fn compress_file(&self, path: &Path, level: i32) -> Result<PathBuf, InklogError>;
}

/// Zstd compression strategy.
#[cfg(feature = "compression")]
#[derive(Debug, Clone)]
pub struct ZstdCompression {
    level: i32,
}

#[cfg(feature = "compression")]
impl ZstdCompression {
    /// Create a new Zstd compression strategy with the given level (0-22).
    pub fn new(level: i32) -> Self {
        let level = level.clamp(0, 22);
        Self { level }
    }

    /// Get the compression level.
    pub fn level(&self) -> i32 {
        self.level
    }
}

#[cfg(feature = "compression")]
impl Default for ZstdCompression {
    fn default() -> Self {
        Self::new(3)
    }
}

#[cfg(feature = "compression")]
impl CompressionStrategy for ZstdCompression {
    fn compress(&self, data: &[u8]) -> Result<Vec<u8>, InklogError> {
        zstd::encode_all(data, self.level).map_err(|e| InklogError::CompressionError(e.to_string()))
    }

    fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, InklogError> {
        zstd::decode_all(data).map_err(|e| InklogError::CompressionError(e.to_string()))
    }

    fn extension(&self) -> &'static str {
        "zst"
    }

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

    fn compress_file(&self, path: &Path, level: i32) -> Result<PathBuf, InklogError> {
        compress_file_internal(path, level)
    }
}

/// No-op compression strategy (stores data uncompressed).
#[derive(Debug, Clone, Default)]
pub struct NoCompression;

impl CompressionStrategy for NoCompression {
    fn compress(&self, data: &[u8]) -> Result<Vec<u8>, InklogError> {
        Ok(data.to_vec())
    }

    fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, InklogError> {
        Ok(data.to_vec())
    }

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

    fn name(&self) -> &'static str {
        "none"
    }

    fn compress_file(&self, path: &Path, _level: i32) -> Result<PathBuf, InklogError> {
        Ok(path.to_path_buf())
    }
}

/// Gzip compression strategy.
#[derive(Debug, Clone)]
pub struct GzipCompression {
    level: u32,
}

impl GzipCompression {
    /// Create a new Gzip compression strategy with the given level (0-9).
    pub fn new(level: u32) -> Self {
        let level = level.clamp(0, 9);
        Self { level }
    }

    /// Get the compression level.
    pub fn level(&self) -> u32 {
        self.level
    }
}

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

impl CompressionStrategy for GzipCompression {
    fn compress(&self, data: &[u8]) -> Result<Vec<u8>, InklogError> {
        use flate2::Compression;
        use flate2::write::GzEncoder;

        let mut encoder = GzEncoder::new(Vec::new(), Compression::new(self.level));
        std::io::Write::write_all(&mut encoder, data)
            .map_err(|e| InklogError::CompressionError(e.to_string()))?;
        encoder
            .finish()
            .map_err(|e| InklogError::CompressionError(e.to_string()))
    }

    fn decompress(&self, data: &[u8]) -> Result<Vec<u8>, InklogError> {
        use flate2::read::GzDecoder;
        use std::io::Read;

        let mut decoder = GzDecoder::new(data);
        let mut decompressed = Vec::new();
        decoder
            .read_to_end(&mut decompressed)
            .map_err(|e| InklogError::CompressionError(e.to_string()))?;
        Ok(decompressed)
    }

    fn extension(&self) -> &'static str {
        "gz"
    }

    fn name(&self) -> &'static str {
        "gzip"
    }

    fn compress_file(&self, path: &Path, level: i32) -> Result<PathBuf, InklogError> {
        use flate2::Compression;
        use flate2::write::GzEncoder;

        let compressed_path = path.with_extension("gz");

        let input_file = File::open(path).map_err(|e| {
            error!("Failed to open file for compression: {}", e);
            InklogError::IoError(e)
        })?;

        let mut reader = BufReader::new(input_file);
        let output_file = File::create(&compressed_path).map_err(|e| {
            error!("Failed to create compressed file: {}", e);
            InklogError::IoError(e)
        })?;

        let level = level.clamp(0, 9) as u32;
        let mut encoder = GzEncoder::new(output_file, Compression::new(level));

        let mut buffer = [0u8; 8192];
        loop {
            let bytes_read = Read::read(&mut reader, &mut buffer)?;
            if bytes_read == 0 {
                break;
            }
            std::io::Write::write_all(&mut encoder, &buffer[..bytes_read])?;
        }

        encoder.finish().map_err(|e| {
            error!("Failed to finish compression: {}", e);
            InklogError::CompressionError(e.to_string())
        })?;

        if let Err(e) = std::fs::remove_file(path) {
            let mut args = fluent_bundle::FluentArgs::new();
            args.set("err", e.to_string());
            tracing::warn!(
                "{}",
                crate::i18n::tr_args("config-compression_remove_failed", args)
            );
        }

        Ok(compressed_path)
    }
}

/// Internal function to compress a file using Zstd.
#[cfg(feature = "compression")]
fn compress_file_internal(path: &Path, compression_level: i32) -> Result<PathBuf, InklogError> {
    let compressed_path = path.with_extension("zst");

    let input_file = File::open(path).map_err(|e| {
        error!("Failed to open file for compression: {}", e);
        InklogError::IoError(e)
    })?;

    let mut reader = BufReader::new(input_file);
    let output_file = File::create(&compressed_path).map_err(|e| {
        error!("Failed to create compressed file: {}", e);
        InklogError::IoError(e)
    })?;

    let mut encoder = zstd::stream::Encoder::new(output_file, compression_level).map_err(|e| {
        error!("Failed to create zstd encoder: {}", e);
        InklogError::CompressionError(e.to_string())
    })?;

    {
        let mut writer = BufWriter::new(encoder.by_ref());

        let mut buffer = [0u8; 8192];
        loop {
            let bytes_read = Read::read(&mut reader, &mut buffer)?;
            if bytes_read == 0 {
                break;
            }
            Write::write_all(&mut writer, &buffer[..bytes_read])?;
        }
    }

    encoder.finish().map_err(|e| {
        error!("Failed to finish compression: {}", e);
        InklogError::CompressionError(e.to_string())
    })?;

    if let Err(e) = std::fs::remove_file(path) {
        let mut args = fluent_bundle::FluentArgs::new();
        args.set("err", e.to_string());
        tracing::warn!(
            "{}",
            crate::i18n::tr_args("config-compression_remove_failed", args)
        );
    }

    Ok(compressed_path)
}

/// Compress a single file (legacy function for backward compatibility).
#[cfg(feature = "compression")]
pub fn compress_file(path: &Path, compression_level: i32) -> Result<PathBuf, InklogError> {
    compress_file_internal(path, compression_level)
}

/// Batch compress data.
#[cfg(feature = "compression")]
pub fn compress_data(data: &[u8], compression_level: i32) -> Result<Vec<u8>, InklogError> {
    zstd::encode_all(data, compression_level)
        .map_err(|e| InklogError::CompressionError(e.to_string()))
}

/// Compress string data.
#[cfg(feature = "compression")]
pub fn compress_string(data: &str, compression_level: i32) -> Result<Vec<u8>, InklogError> {
    compress_data(data.as_bytes(), compression_level)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[cfg(feature = "compression")]
    fn test_zstd_compression() {
        let strategy = ZstdCompression::new(3);
        let data = b"Hello, World! This is a test message for compression.";

        let compressed = strategy.compress(data).unwrap();
        assert!(!compressed.is_empty());

        let decompressed = strategy.decompress(&compressed).unwrap();
        assert_eq!(data.to_vec(), decompressed);
    }

    #[test]
    #[cfg(feature = "compression")]
    fn test_zstd_level_clamping() {
        let strategy = ZstdCompression::new(100);
        assert_eq!(strategy.level(), 22);

        let strategy = ZstdCompression::new(-10);
        assert_eq!(strategy.level(), 0);
    }

    #[test]
    fn test_no_compression() {
        let strategy = NoCompression;
        let data = b"Hello, World!";

        let compressed = strategy.compress(data).unwrap();
        assert_eq!(data.to_vec(), compressed);

        let decompressed = strategy.decompress(&compressed).unwrap();
        assert_eq!(data.to_vec(), decompressed);
    }

    #[test]
    #[cfg(feature = "compression")]
    fn test_extension() {
        let zstd = ZstdCompression::default();
        assert_eq!(zstd.extension(), "zst");

        let none = NoCompression;
        assert_eq!(none.extension(), "");
    }

    #[test]
    #[cfg(feature = "compression")]
    fn test_compress_data() {
        let data = b"Test data for compression";
        let compressed = compress_data(data, 3).unwrap();
        assert!(!compressed.is_empty());

        // Verify decompression works
        let decompressed = zstd::decode_all(&compressed[..]).unwrap();
        assert_eq!(data.to_vec(), decompressed);
    }

    #[test]
    fn test_gzip_compression() {
        let strategy = GzipCompression::new(6);
        let data = b"Hello, World! This is a test message for gzip compression.";

        let compressed = strategy.compress(data).unwrap();
        assert!(!compressed.is_empty());

        let decompressed = strategy.decompress(&compressed).unwrap();
        assert_eq!(data.to_vec(), decompressed);
    }

    #[test]
    fn test_gzip_level_clamping() {
        let strategy = GzipCompression::new(100);
        assert_eq!(strategy.level(), 9);

        let strategy = GzipCompression::new(0);
        assert_eq!(strategy.level(), 0);
    }

    #[test]
    fn test_gzip_extension() {
        let gzip = GzipCompression::default();
        assert_eq!(gzip.extension(), "gz");
        assert_eq!(gzip.name(), "gzip");
    }

    #[test]
    #[cfg(feature = "compression")]
    fn test_zstd_default_level() {
        let zstd = ZstdCompression::default();
        assert_eq!(zstd.level(), 3);
        assert_eq!(zstd.name(), "zstd");
    }

    #[test]
    #[cfg(feature = "compression")]
    fn test_zstd_compress_empty_data() {
        let strategy = ZstdCompression::new(3);
        let compressed = strategy.compress(b"").unwrap();
        let decompressed = strategy.decompress(&compressed).unwrap();
        assert!(decompressed.is_empty());
    }

    #[test]
    #[cfg(feature = "compression")]
    fn test_zstd_decompress_invalid_data_errors() {
        let strategy = ZstdCompression::new(3);
        let invalid_data = b"not valid zstd data";
        let result = strategy.decompress(invalid_data);
        assert!(matches!(result, Err(InklogError::CompressionError(_))));
    }

    #[test]
    fn test_no_compression_default_and_compress_file() {
        let strategy = NoCompression;
        assert_eq!(strategy.name(), "none");
        let path = Path::new("/tmp/nonexistent_file_for_test");
        let result = strategy.compress_file(path, 3);
        assert_eq!(result.unwrap(), path.to_path_buf());
    }

    #[test]
    fn test_gzip_compress_empty_data() {
        let strategy = GzipCompression::new(6);
        let compressed = strategy.compress(b"").unwrap();
        let decompressed = strategy.decompress(&compressed).unwrap();
        assert!(decompressed.is_empty());
    }

    #[test]
    fn test_gzip_decompress_invalid_data_errors() {
        let strategy = GzipCompression::new(6);
        let invalid_data = b"not valid gzip data";
        let result = strategy.decompress(invalid_data);
        assert!(matches!(result, Err(InklogError::CompressionError(_))));
    }

    #[test]
    fn test_gzip_default_level() {
        let gzip = GzipCompression::default();
        assert_eq!(gzip.level(), 6);
    }

    #[test]
    #[cfg(feature = "compression")]
    fn test_compress_string_function() {
        let data = "Hello, compression!";
        let compressed = compress_string(data, 3).unwrap();
        assert!(!compressed.is_empty());
        let decompressed = zstd::decode_all(&compressed[..]).unwrap();
        assert_eq!(data.as_bytes(), decompressed);
    }

    #[test]
    #[cfg(feature = "compression")]
    fn test_compress_data_empty() {
        let compressed = compress_data(b"", 3).unwrap();
        let decompressed = zstd::decode_all(&compressed[..]).unwrap();
        assert!(decompressed.is_empty());
    }

    #[test]
    #[cfg(feature = "compression")]
    fn test_compress_file_legacy_function() {
        use std::io::Write;
        let temp = tempfile::tempdir().unwrap();
        let file_path = temp.path().join("legacy_input.log");
        let mut file = File::create(&file_path).unwrap();
        writeln!(file, "test log line 1").unwrap();
        writeln!(file, "test log line 2").unwrap();
        drop(file);

        let compressed_path = compress_file(&file_path, 3).unwrap();
        assert!(compressed_path.extension().unwrap_or_default() == "zst");
        assert!(!file_path.exists(), "Original file should be removed");
        assert!(compressed_path.exists(), "Compressed file should exist");

        let compressed_bytes = std::fs::read(&compressed_path).unwrap();
        let decompressed = zstd::decode_all(&compressed_bytes[..]).unwrap();
        let text = String::from_utf8(decompressed).unwrap();
        assert!(text.contains("test log line 1"));
        assert!(text.contains("test log line 2"));
    }

    #[test]
    #[cfg(feature = "compression")]
    fn test_zstd_compress_file_via_strategy() {
        use std::io::Write;
        let temp = tempfile::tempdir().unwrap();
        let file_path = temp.path().join("strategy_input.log");
        let mut file = File::create(&file_path).unwrap();
        file.write_all(b"strategy compression test data").unwrap();
        drop(file);

        let strategy = ZstdCompression::new(3);
        let compressed_path = strategy.compress_file(&file_path, 5).unwrap();
        assert_eq!(compressed_path.extension().unwrap_or_default(), "zst");
        assert!(!file_path.exists(), "Original should be removed");
        assert!(compressed_path.exists());

        let compressed_bytes = std::fs::read(&compressed_path).unwrap();
        let decompressed = zstd::decode_all(&compressed_bytes[..]).unwrap();
        assert_eq!(decompressed, b"strategy compression test data");
    }

    #[test]
    #[cfg(feature = "compression")]
    fn test_zstd_compress_file_open_missing_errors() {
        let strategy = ZstdCompression::new(3);
        let result = strategy.compress_file(Path::new("/nonexistent/path/file.log"), 3);
        assert!(matches!(result, Err(InklogError::IoError(_))));
    }

    #[test]
    fn test_gzip_compress_file_via_strategy() {
        use std::io::Write;
        let temp = tempfile::tempdir().unwrap();
        let file_path = temp.path().join("gzip_input.log");
        let mut file = File::create(&file_path).unwrap();
        file.write_all(b"gzip strategy compression test").unwrap();
        drop(file);

        let strategy = GzipCompression::new(6);
        let compressed_path = strategy.compress_file(&file_path, 9).unwrap();
        assert_eq!(compressed_path.extension().unwrap_or_default(), "gz");
        assert!(!file_path.exists(), "Original should be removed");
        assert!(compressed_path.exists());

        let compressed_bytes = std::fs::read(&compressed_path).unwrap();
        let mut decoder = flate2::read::GzDecoder::new(&compressed_bytes[..]);
        let mut decompressed = Vec::new();
        std::io::Read::read_to_end(&mut decoder, &mut decompressed).unwrap();
        assert_eq!(decompressed, b"gzip strategy compression test");
    }

    #[test]
    fn test_gzip_compress_file_missing_input_errors() {
        let strategy = GzipCompression::new(6);
        let result = strategy.compress_file(Path::new("/nonexistent/gzip_input.log"), 6);
        assert!(matches!(result, Err(InklogError::IoError(_))));
    }

    #[test]
    #[cfg(feature = "compression")]
    fn test_zstd_large_data_roundtrip() {
        let strategy = ZstdCompression::new(9);
        let data: Vec<u8> = (0..10_000).map(|i| (i % 256) as u8).collect();
        let compressed = strategy.compress(&data).unwrap();
        assert!(
            compressed.len() < data.len(),
            "Should compress repetitive data"
        );
        let decompressed = strategy.decompress(&compressed).unwrap();
        assert_eq!(decompressed, data);
    }

    #[test]
    fn test_gzip_with_level_zero() {
        let strategy = GzipCompression::new(0);
        let data = b"data at level 0";
        let compressed = strategy.compress(data).unwrap();
        let decompressed = strategy.decompress(&compressed).unwrap();
        assert_eq!(data.to_vec(), decompressed);
    }

    #[test]
    #[cfg(feature = "compression")]
    fn test_zstd_with_max_level() {
        let strategy = ZstdCompression::new(22);
        let data = b"max level compression test";
        let compressed = strategy.compress(data).unwrap();
        let decompressed = strategy.decompress(&compressed).unwrap();
        assert_eq!(data.to_vec(), decompressed);
    }

    // =========================================================================
    // compress_file 错误路径:覆盖 File::create 失败分支
    // =========================================================================

    #[test]
    fn test_gzip_compress_file_create_output_fails_errors() {
        // 覆盖行 181-182:GzipCompression::compress_file 中 File::create 失败
        // 策略:输入文件存在,但 compressed_path(path.with_extension("gz"))
        // 指向一个已存在的目录 → File::create 返回 Err → 走 IoError 分支
        use std::io::Write;
        let temp = tempfile::tempdir().unwrap();
        let file_path = temp.path().join("input_create_fail.log");
        let mut file = File::create(&file_path).unwrap();
        file.write_all(b"data").unwrap();
        drop(file);

        // compressed_path = input_create_fail.gz(with_extension 替换扩展名)
        // 把它创建为目录,使 File::create 失败
        let compressed_path = temp.path().join("input_create_fail.gz");
        std::fs::create_dir(&compressed_path).unwrap();

        let strategy = GzipCompression::new(6);
        let result = strategy.compress_file(&file_path, 6);
        assert!(
            matches!(result, Err(InklogError::IoError(_))),
            "expected IoError when output file create fails, got: {:?}",
            result
        );
    }

    #[test]
    #[cfg(feature = "compression")]
    fn test_zstd_compress_file_internal_create_output_fails_errors() {
        // 覆盖行 219-220:compress_file_internal 中 File::create 失败
        // 同样的策略:把 compressed_path 创建为目录
        use std::io::Write;
        let temp = tempfile::tempdir().unwrap();
        let file_path = temp.path().join("zstd_input_create_fail.log");
        let mut file = File::create(&file_path).unwrap();
        file.write_all(b"data").unwrap();
        drop(file);

        // compressed_path = zstd_input_create_fail.zst
        let compressed_path = temp.path().join("zstd_input_create_fail.zst");
        std::fs::create_dir(&compressed_path).unwrap();

        // 直接调用 compress_file_internal 的公共入口 compress_file
        let result = compress_file(&file_path, 3);
        assert!(
            matches!(result, Err(InklogError::IoError(_))),
            "expected IoError when zstd output file create fails, got: {:?}",
            result
        );
    }

    #[test]
    #[cfg(feature = "compression")]
    fn test_zstd_compress_file_internal_invalid_level_clamped() {
        // zstd::stream::Encoder::new 对超出范围的 compression_level 会内部 clamp 到有效级别,
        // 而不是返回 Err。因此行 224-225(Encoder::new 失败分支)在实际中难以可靠触发。
        // 本测试验证 zstd 的 clamp 行为:传入 i32::MIN 应返回 Ok(而非 Err)。
        use std::io::Write;
        let temp = tempfile::tempdir().unwrap();
        let file_path = temp.path().join("invalid_level.log");
        let mut file = File::create(&file_path).unwrap();
        file.write_all(b"data").unwrap();
        drop(file);

        // zstd 会 clamp i32::MIN 到有效级别,返回 Ok
        let result = compress_file(&file_path, i32::MIN);
        assert!(
            result.is_ok(),
            "zstd should clamp invalid level and return Ok, got: {:?}",
            result
        );

        // 验证压缩文件已生成
        let compressed_path = result.unwrap();
        assert!(compressed_path.exists());
        assert!(compressed_path.extension().is_some_and(|ext| ext == "zst"));
    }
}