oxigdal-edge 0.1.4

Edge computing platform for OxiGDAL with offline-first architecture and minimal footprint
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
//! Edge-optimized compression for bandwidth-limited environments
//!
//! Provides compression strategies optimized for edge devices with
//! limited CPU and memory resources.

use crate::error::{EdgeError, Result};
use bytes::Bytes;
use serde::{Deserialize, Serialize};

/// Compression level
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CompressionLevel {
    /// Fastest compression, lower ratio
    Fast,
    /// Balanced compression and speed
    Balanced,
    /// Best compression ratio, slower
    Best,
}

impl CompressionLevel {
    /// Get LZ4 compression level
    pub fn lz4_level(&self) -> i32 {
        match self {
            Self::Fast => 1,
            Self::Balanced => 4,
            Self::Best => 9,
        }
    }

    /// Get deflate level as u8
    pub fn deflate_level_u8(&self) -> u8 {
        match self {
            Self::Fast => 1,
            Self::Balanced => 6,
            Self::Best => 9,
        }
    }
}

/// Compression strategy
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CompressionStrategy {
    /// LZ4 compression (fast, good for real-time)
    Lz4,
    /// Snappy compression (fast, good for throughput)
    Snappy,
    /// Deflate/GZIP (balanced)
    Deflate,
    /// No compression
    None,
}

impl CompressionStrategy {
    /// Select best strategy based on data characteristics
    pub fn auto_select(data: &[u8]) -> Self {
        // Simple heuristic based on data size and entropy
        if data.len() < 1024 {
            // Small data: no compression overhead
            Self::None
        } else if Self::estimate_entropy(data) > 0.9 {
            // High entropy (likely already compressed): skip compression
            Self::None
        } else if data.len() < 10 * 1024 {
            // Small to medium: use fast compression
            Self::Snappy
        } else {
            // Larger data: use balanced compression
            Self::Lz4
        }
    }

    /// Estimate Shannon entropy of data
    fn estimate_entropy(data: &[u8]) -> f64 {
        if data.is_empty() {
            return 0.0;
        }

        let mut counts = [0u32; 256];
        for &byte in data.iter().take(1024.min(data.len())) {
            counts[byte as usize] = counts[byte as usize].saturating_add(1);
        }

        let len = data.len().min(1024) as f64;
        let mut entropy = 0.0;

        for &count in &counts {
            if count > 0 {
                let p = count as f64 / len;
                entropy -= p * p.log2();
            }
        }

        entropy / 8.0 // Normalize to 0-1 range
    }
}

/// Edge compressor
pub struct EdgeCompressor {
    strategy: CompressionStrategy,
    level: CompressionLevel,
}

impl EdgeCompressor {
    /// Create new compressor with strategy and level
    pub fn new(strategy: CompressionStrategy, level: CompressionLevel) -> Self {
        Self { strategy, level }
    }

    /// Create compressor with auto-selected strategy
    pub fn auto() -> Self {
        Self {
            strategy: CompressionStrategy::Lz4,
            level: CompressionLevel::Balanced,
        }
    }

    /// Create fast compressor for real-time use
    pub fn fast() -> Self {
        Self {
            strategy: CompressionStrategy::Snappy,
            level: CompressionLevel::Fast,
        }
    }

    /// Create best compression for storage
    pub fn best() -> Self {
        Self {
            strategy: CompressionStrategy::Deflate,
            level: CompressionLevel::Best,
        }
    }

    /// Compress data
    pub fn compress(&self, data: &[u8]) -> Result<Bytes> {
        match self.strategy {
            CompressionStrategy::None => Ok(Bytes::copy_from_slice(data)),
            CompressionStrategy::Lz4 => self.compress_lz4(data),
            CompressionStrategy::Snappy => self.compress_snappy(data),
            CompressionStrategy::Deflate => self.compress_deflate(data),
        }
    }

    /// Decompress data
    pub fn decompress(&self, data: &[u8]) -> Result<Bytes> {
        match self.strategy {
            CompressionStrategy::None => Ok(Bytes::copy_from_slice(data)),
            CompressionStrategy::Lz4 => self.decompress_lz4(data),
            CompressionStrategy::Snappy => self.decompress_snappy(data),
            CompressionStrategy::Deflate => self.decompress_deflate(data),
        }
    }

    /// Compress with LZ4
    fn compress_lz4(&self, data: &[u8]) -> Result<Bytes> {
        // Compress with oxiarc-lz4 and prepend original size as 4-byte LE i32
        let compressed = oxiarc_lz4::compress_block_with_accel(data, self.level.lz4_level())
            .map_err(|e| EdgeError::compression(e.to_string()))?;
        let orig_size = data.len() as i32;
        let mut result = Vec::with_capacity(4 + compressed.len());
        result.extend_from_slice(&orig_size.to_le_bytes());
        result.extend_from_slice(&compressed);
        Ok(Bytes::from(result))
    }

    /// Decompress with LZ4
    fn decompress_lz4(&self, data: &[u8]) -> Result<Bytes> {
        // Data has 4-byte LE i32 size prefix followed by compressed block
        if data.len() < 4 {
            return Err(EdgeError::decompression("LZ4 data too short".to_string()));
        }
        let orig_size = i32::from_le_bytes([data[0], data[1], data[2], data[3]]) as usize;
        let decompressed = oxiarc_lz4::decompress_block(&data[4..], orig_size)
            .map_err(|e| EdgeError::decompression(e.to_string()))?;
        Ok(Bytes::from(decompressed))
    }

    /// Compress with Snappy
    fn compress_snappy(&self, data: &[u8]) -> Result<Bytes> {
        Ok(Bytes::from(oxiarc_snappy::compress(data)))
    }

    /// Decompress with Snappy
    fn decompress_snappy(&self, data: &[u8]) -> Result<Bytes> {
        oxiarc_snappy::decompress(data)
            .map(Bytes::from)
            .map_err(|e| EdgeError::decompression(e.to_string()))
    }

    /// Compress with Deflate
    fn compress_deflate(&self, data: &[u8]) -> Result<Bytes> {
        oxiarc_deflate::deflate(data, self.level.deflate_level_u8())
            .map(Bytes::from)
            .map_err(|e| EdgeError::compression(e.to_string()))
    }

    /// Decompress with Deflate
    fn decompress_deflate(&self, data: &[u8]) -> Result<Bytes> {
        oxiarc_deflate::inflate(data)
            .map(Bytes::from)
            .map_err(|e| EdgeError::decompression(e.to_string()))
    }

    /// Get compression ratio for data
    pub fn compression_ratio(&self, original_size: usize, compressed_size: usize) -> f64 {
        if original_size == 0 {
            return 0.0;
        }
        compressed_size as f64 / original_size as f64
    }

    /// Estimate compressed size without actually compressing
    pub fn estimate_compressed_size(&self, data: &[u8]) -> usize {
        match self.strategy {
            CompressionStrategy::None => data.len(),
            CompressionStrategy::Snappy => {
                // Snappy worst case: ~1.5x original size
                (data.len() as f64 * 1.5) as usize
            }
            CompressionStrategy::Lz4 => {
                // LZ4 worst case: original size + overhead
                data.len() + (data.len() / 255) + 16
            }
            CompressionStrategy::Deflate => {
                // Deflate worst case: ~1.1x original size
                (data.len() as f64 * 1.1) as usize
            }
        }
    }
}

/// Adaptive compressor that selects strategy based on data
pub struct AdaptiveCompressor {
    level: CompressionLevel,
}

impl AdaptiveCompressor {
    /// Create new adaptive compressor
    pub fn new(level: CompressionLevel) -> Self {
        Self { level }
    }

    /// Compress data with auto-selected strategy
    pub fn compress(&self, data: &[u8]) -> Result<(Bytes, CompressionStrategy)> {
        let strategy = CompressionStrategy::auto_select(data);
        let compressor = EdgeCompressor::new(strategy, self.level);
        let compressed = compressor.compress(data)?;
        Ok((compressed, strategy))
    }

    /// Decompress data with specified strategy
    pub fn decompress(&self, data: &[u8], strategy: CompressionStrategy) -> Result<Bytes> {
        let compressor = EdgeCompressor::new(strategy, self.level);
        compressor.decompress(data)
    }
}

/// Compressed data with metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompressedData {
    /// Compression strategy used
    pub strategy: CompressionStrategy,
    /// Original size
    pub original_size: usize,
    /// Compressed size
    pub compressed_size: usize,
    /// Compressed data
    pub data: Vec<u8>,
}

impl CompressedData {
    /// Create new compressed data
    pub fn new(strategy: CompressionStrategy, original_size: usize, data: Bytes) -> Self {
        let compressed_size = data.len();
        Self {
            strategy,
            original_size,
            compressed_size,
            data: data.to_vec(),
        }
    }

    /// Get compression ratio
    pub fn ratio(&self) -> f64 {
        if self.original_size == 0 {
            return 0.0;
        }
        self.compressed_size as f64 / self.original_size as f64
    }

    /// Get space saved in bytes
    pub fn space_saved(&self) -> usize {
        self.original_size.saturating_sub(self.compressed_size)
    }

    /// Get space saved as percentage
    pub fn space_saved_percent(&self) -> f64 {
        if self.original_size == 0 {
            return 0.0;
        }
        (self.space_saved() as f64 / self.original_size as f64) * 100.0
    }
}

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

    #[test]
    fn test_compression_lz4() -> Result<()> {
        let compressor = EdgeCompressor::new(CompressionStrategy::Lz4, CompressionLevel::Balanced);
        // Use larger data to ensure compression is beneficial
        let data = b"Hello, World! This is a test message for compression. \
                     Repeat this several times to make it worth compressing. \
                     Hello, World! This is a test message for compression.";

        let compressed = compressor.compress(data)?;
        let decompressed = compressor.decompress(&compressed)?;

        assert_eq!(&decompressed[..], &data[..]);
        // Note: For very small data, compression may not reduce size due to overhead
        // Just verify decompression works correctly

        Ok(())
    }

    #[test]
    fn test_compression_snappy() -> Result<()> {
        let compressor = EdgeCompressor::new(CompressionStrategy::Snappy, CompressionLevel::Fast);
        let data = b"Hello, World! This is a test message for compression.";

        let compressed = compressor.compress(data)?;
        let decompressed = compressor.decompress(&compressed)?;

        assert_eq!(&decompressed[..], &data[..]);

        Ok(())
    }

    #[test]
    fn test_compression_deflate() -> Result<()> {
        let compressor = EdgeCompressor::new(CompressionStrategy::Deflate, CompressionLevel::Best);
        let data = b"Hello, World! This is a test message for compression.";

        let compressed = compressor.compress(data)?;
        let decompressed = compressor.decompress(&compressed)?;

        assert_eq!(&decompressed[..], &data[..]);

        Ok(())
    }

    #[test]
    fn test_compression_none() -> Result<()> {
        let compressor = EdgeCompressor::new(CompressionStrategy::None, CompressionLevel::Fast);
        let data = b"Hello, World!";

        let compressed = compressor.compress(data)?;
        assert_eq!(&compressed[..], &data[..]);

        Ok(())
    }

    #[test]
    fn test_adaptive_compression() -> Result<()> {
        let compressor = AdaptiveCompressor::new(CompressionLevel::Balanced);
        let data = b"Hello, World! This is a test message for adaptive compression.";

        let (compressed, strategy) = compressor.compress(data)?;
        let decompressed = compressor.decompress(&compressed, strategy)?;

        assert_eq!(&decompressed[..], &data[..]);

        Ok(())
    }

    #[test]
    fn test_auto_select_strategy() {
        let small_data = b"Hi";
        let strategy = CompressionStrategy::auto_select(small_data);
        assert_eq!(strategy, CompressionStrategy::None);

        let medium_data = vec![0u8; 5000];
        let strategy = CompressionStrategy::auto_select(&medium_data);
        assert!(matches!(
            strategy,
            CompressionStrategy::Snappy | CompressionStrategy::Lz4
        ));
    }

    #[test]
    fn test_compression_ratio() {
        let compressor = EdgeCompressor::fast();
        let ratio = compressor.compression_ratio(1000, 500);
        assert_eq!(ratio, 0.5);
    }

    #[test]
    fn test_compressed_data_metadata() -> Result<()> {
        // Use larger, more compressible data to ensure compression works
        let original = b"Test data for compression. This message repeats. \
                         Test data for compression. This message repeats. \
                         Test data for compression. This message repeats.";
        let compressor = EdgeCompressor::fast();
        let compressed = compressor.compress(original)?;

        let metadata = CompressedData::new(CompressionStrategy::Snappy, original.len(), compressed);

        assert_eq!(metadata.original_size, original.len());
        // Compression ratio should be positive (can be > 1.0 if compression increases size due to overhead)
        assert!(metadata.ratio() > 0.0);
        // Space saved percentage can be negative if compression increased size
        assert!(
            metadata.space_saved_percent() >= -100.0 && metadata.space_saved_percent() <= 100.0
        );

        Ok(())
    }
}