Skip to main content

oxirs_cluster/
optimization.rs

1//! Storage and Serialization Optimization Module
2//!
3//! Provides binary encoding, compression, and performance optimizations
4//! for distributed storage operations.
5
6use anyhow::Result;
7use serde::{Deserialize, Serialize};
8use std::path::{Path, PathBuf};
9use tokio::fs::{File, OpenOptions};
10use tokio::io::{AsyncWrite, AsyncWriteExt};
11
12/// Binary serialization format with compression
13#[derive(Debug, Clone)]
14pub enum SerializationFormat {
15    /// JSON format (fallback)
16    Json,
17    /// MessagePack binary format
18    MessagePack,
19    /// CBOR binary format
20    Cbor,
21    /// Bincode format (fastest)
22    Bincode,
23}
24
25/// Compression algorithms
26#[derive(Debug, Clone)]
27pub enum CompressionAlgorithm {
28    /// No compression
29    None,
30    /// LZ4 (fast compression/decompression)
31    Lz4,
32    /// Zstd (good compression ratio)
33    Zstd,
34    /// Deflate (standard compression)
35    Deflate,
36}
37
38/// Serialization configuration
39#[derive(Debug, Clone)]
40pub struct SerializationConfig {
41    pub format: SerializationFormat,
42    pub compression: CompressionAlgorithm,
43    pub compression_level: i32,
44    pub enable_checksums: bool,
45}
46
47impl Default for SerializationConfig {
48    fn default() -> Self {
49        Self {
50            format: SerializationFormat::Bincode,
51            compression: CompressionAlgorithm::Lz4,
52            compression_level: 6,
53            enable_checksums: true,
54        }
55    }
56}
57
58/// Binary serializer with compression and integrity checking
59pub struct BinarySerializer {
60    config: SerializationConfig,
61}
62
63impl BinarySerializer {
64    pub fn new(config: SerializationConfig) -> Self {
65        Self { config }
66    }
67
68    /// Serialize data with compression and checksums
69    pub fn serialize<T: Serialize>(&self, data: &T) -> Result<Vec<u8>> {
70        // First serialize to binary format
71        let mut binary_data = match self.config.format {
72            SerializationFormat::Json => serde_json::to_vec(data)?,
73            SerializationFormat::MessagePack => rmp_serde::to_vec(data)?,
74            SerializationFormat::Cbor => {
75                let mut buf = Vec::new();
76                ciborium::ser::into_writer(data, &mut buf)
77                    .map_err(|e| anyhow::anyhow!("CBOR serialization failed: {e}"))?;
78                buf
79            }
80            SerializationFormat::Bincode => {
81                oxicode::serde::encode_to_vec(data, oxicode::config::standard())?
82            }
83        };
84
85        // Apply compression if enabled
86        binary_data = match self.config.compression {
87            CompressionAlgorithm::None => binary_data,
88            CompressionAlgorithm::Lz4 => self.compress_lz4(&binary_data)?,
89            CompressionAlgorithm::Zstd => self.compress_zstd(&binary_data)?,
90            CompressionAlgorithm::Deflate => self.compress_deflate(&binary_data)?,
91        };
92
93        // Add checksum if enabled
94        if self.config.enable_checksums {
95            let checksum = crc32fast::hash(&binary_data);
96            let mut result = Vec::with_capacity(binary_data.len() + 8);
97            result.extend_from_slice(&checksum.to_le_bytes());
98            result.extend_from_slice(&(binary_data.len() as u32).to_le_bytes());
99            result.extend_from_slice(&binary_data);
100            Ok(result)
101        } else {
102            Ok(binary_data)
103        }
104    }
105
106    /// Deserialize data with decompression and checksum validation
107    pub fn deserialize<T: for<'de> Deserialize<'de>>(&self, data: &[u8]) -> Result<T> {
108        let (binary_data, _expected_checksum) = if self.config.enable_checksums {
109            if data.len() < 8 {
110                return Err(anyhow::anyhow!("Data too short for checksum"));
111            }
112
113            let checksum = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
114            let length = u32::from_le_bytes([data[4], data[5], data[6], data[7]]) as usize;
115
116            if data.len() < 8 + length {
117                return Err(anyhow::anyhow!("Data length mismatch"));
118            }
119
120            let binary_data = &data[8..8 + length];
121            let computed_checksum = crc32fast::hash(binary_data);
122
123            if checksum != computed_checksum {
124                return Err(anyhow::anyhow!("Checksum validation failed"));
125            }
126
127            (binary_data, Some(checksum))
128        } else {
129            (data, None)
130        };
131
132        // Decompress if needed
133        let decompressed_data = match self.config.compression {
134            CompressionAlgorithm::None => binary_data.to_vec(),
135            CompressionAlgorithm::Lz4 => self.decompress_lz4(binary_data)?,
136            CompressionAlgorithm::Zstd => self.decompress_zstd(binary_data)?,
137            CompressionAlgorithm::Deflate => self.decompress_deflate(binary_data)?,
138        };
139
140        // Deserialize from binary format
141        let result = match self.config.format {
142            SerializationFormat::Json => serde_json::from_slice(&decompressed_data)?,
143            SerializationFormat::MessagePack => rmp_serde::from_slice(&decompressed_data)?,
144            SerializationFormat::Cbor => ciborium::de::from_reader(&decompressed_data[..])
145                .map_err(|e| anyhow::anyhow!("CBOR deserialization failed: {e}"))?,
146            SerializationFormat::Bincode => {
147                oxicode::serde::decode_from_slice(&decompressed_data, oxicode::config::standard())
148                    .map(|(v, _)| v)?
149            }
150        };
151
152        Ok(result)
153    }
154
155    /// Compress data using LZ4
156    fn compress_lz4(&self, data: &[u8]) -> Result<Vec<u8>> {
157        oxiarc_lz4::compress(data).map_err(|e| anyhow::anyhow!("LZ4 compression failed: {}", e))
158    }
159
160    /// Decompress LZ4 data
161    fn decompress_lz4(&self, data: &[u8]) -> Result<Vec<u8>> {
162        oxiarc_lz4::decompress(data, 100 * 1024 * 1024)
163            .map_err(|e| anyhow::anyhow!("LZ4 decompression failed: {}", e))
164    }
165
166    /// Compress data using Zstd
167    fn compress_zstd(&self, data: &[u8]) -> Result<Vec<u8>> {
168        oxiarc_zstd::encode_all(data, self.config.compression_level)
169            .map_err(|e| anyhow::anyhow!("Zstd compression failed: {}", e))
170    }
171
172    /// Decompress Zstd data
173    fn decompress_zstd(&self, data: &[u8]) -> Result<Vec<u8>> {
174        oxiarc_zstd::decode_all(data)
175            .map_err(|e| anyhow::anyhow!("Zstd decompression failed: {}", e))
176    }
177
178    /// Compress data using Deflate (zlib-wrapped DEFLATE stream)
179    fn compress_deflate(&self, data: &[u8]) -> Result<Vec<u8>> {
180        let level = self.config.compression_level.clamp(0, 9) as u8;
181        oxiarc_deflate::zlib_compress(data, level)
182            .map_err(|e| anyhow::anyhow!("Deflate compression failed: {}", e))
183    }
184
185    /// Decompress Deflate data (zlib-wrapped DEFLATE stream)
186    fn decompress_deflate(&self, data: &[u8]) -> Result<Vec<u8>> {
187        oxiarc_deflate::zlib_decompress(data)
188            .map_err(|e| anyhow::anyhow!("Deflate decompression failed: {}", e))
189    }
190}
191
192/// Atomic file writer with transaction semantics
193pub struct AtomicFileWriter {
194    temp_path: PathBuf,
195    final_path: PathBuf,
196    file: Option<File>,
197}
198
199impl AtomicFileWriter {
200    /// Create a new atomic file writer
201    pub async fn new<P: AsRef<Path>>(path: P) -> Result<Self> {
202        let final_path = path.as_ref().to_path_buf();
203        let temp_path = final_path.with_extension("tmp");
204
205        let file = OpenOptions::new()
206            .create(true)
207            .write(true)
208            .truncate(true)
209            .open(&temp_path)
210            .await?;
211
212        Ok(Self {
213            temp_path,
214            final_path,
215            file: Some(file),
216        })
217    }
218
219    /// Write data to the temporary file
220    pub async fn write(&mut self, data: &[u8]) -> Result<()> {
221        if let Some(ref mut file) = self.file {
222            file.write_all(data).await?;
223            file.sync_all().await?;
224        }
225        Ok(())
226    }
227
228    /// Commit the write by atomically moving the temp file to the final location
229    pub async fn commit(mut self) -> Result<()> {
230        if let Some(file) = self.file.take() {
231            file.sync_all().await?;
232            drop(file);
233            tokio::fs::rename(&self.temp_path, &self.final_path).await?;
234        }
235        Ok(())
236    }
237
238    /// Abort the write by removing the temporary file
239    pub async fn abort(self) -> Result<()> {
240        if self.temp_path.exists() {
241            tokio::fs::remove_file(&self.temp_path).await?;
242        }
243        Ok(())
244    }
245}
246
247impl Drop for AtomicFileWriter {
248    fn drop(&mut self) {
249        if self.temp_path.exists() {
250            let _ = std::fs::remove_file(&self.temp_path);
251        }
252    }
253}
254
255impl AsyncWrite for AtomicFileWriter {
256    fn poll_write(
257        mut self: std::pin::Pin<&mut Self>,
258        cx: &mut std::task::Context<'_>,
259        buf: &[u8],
260    ) -> std::task::Poll<std::io::Result<usize>> {
261        if let Some(ref mut file) = self.file {
262            let file_pin = std::pin::Pin::new(file);
263            file_pin.poll_write(cx, buf)
264        } else {
265            std::task::Poll::Ready(Err(std::io::Error::new(
266                std::io::ErrorKind::Other,
267                "File not open",
268            )))
269        }
270    }
271
272    fn poll_flush(
273        mut self: std::pin::Pin<&mut Self>,
274        cx: &mut std::task::Context<'_>,
275    ) -> std::task::Poll<std::io::Result<()>> {
276        if let Some(ref mut file) = self.file {
277            let file_pin = std::pin::Pin::new(file);
278            file_pin.poll_flush(cx)
279        } else {
280            std::task::Poll::Ready(Ok(()))
281        }
282    }
283
284    fn poll_shutdown(
285        mut self: std::pin::Pin<&mut Self>,
286        cx: &mut std::task::Context<'_>,
287    ) -> std::task::Poll<std::io::Result<()>> {
288        if let Some(ref mut file) = self.file {
289            let file_pin = std::pin::Pin::new(file);
290            file_pin.poll_shutdown(cx)
291        } else {
292            std::task::Poll::Ready(Ok(()))
293        }
294    }
295}
296
297/// Corruption detector using checksums and integrity verification
298pub struct CorruptionDetector {
299    enable_deep_scan: bool,
300}
301
302impl CorruptionDetector {
303    pub fn new(enable_deep_scan: bool) -> Self {
304        Self { enable_deep_scan }
305    }
306
307    /// Verify file integrity using checksums
308    pub async fn verify_file_integrity<P: AsRef<Path>>(&self, path: P) -> Result<bool> {
309        let path = path.as_ref();
310        if !path.exists() {
311            return Ok(false);
312        }
313
314        let metadata = tokio::fs::metadata(path).await?;
315        if metadata.len() == 0 {
316            return Ok(true); // Empty file is considered valid
317        }
318
319        // Basic integrity check - read the entire file
320        let data = tokio::fs::read(path).await?;
321
322        // Verify file isn't truncated
323        if (data.len() as u64) != metadata.len() {
324            return Ok(false);
325        }
326
327        if self.enable_deep_scan {
328            // Perform deep integrity check (checksum verification)
329            self.verify_content_integrity(&data).await
330        } else {
331            Ok(true)
332        }
333    }
334
335    /// Verify content integrity using checksums
336    async fn verify_content_integrity(&self, data: &[u8]) -> Result<bool> {
337        // For now, just verify the data is valid serialized format
338        // In a full implementation, this would verify embedded checksums
339        if data.len() >= 8 {
340            // Check if it looks like checksummed data
341            let checksum = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
342            let length = u32::from_le_bytes([data[4], data[5], data[6], data[7]]) as usize;
343
344            if data.len() >= 8 + length {
345                let content = &data[8..8 + length];
346                let computed = crc32fast::hash(content);
347                return Ok(checksum == computed);
348            }
349        }
350
351        Ok(true) // Assume valid if no checksum format detected
352    }
353
354    /// Repair corrupted files by attempting to recover valid data
355    pub async fn attempt_repair<P: AsRef<Path>>(&self, path: P) -> Result<bool> {
356        let path = path.as_ref();
357        if !path.exists() {
358            return Ok(false);
359        }
360
361        // Try to read and validate the file
362        let data = tokio::fs::read(path).await?;
363
364        // If the file appears to have partial checksum data, try to extract valid parts
365        if data.len() >= 8 {
366            let length = u32::from_le_bytes([data[4], data[5], data[6], data[7]]) as usize;
367
368            // If the length seems reasonable, try to extract that portion
369            if length > 0 && data.len() >= 8 + length {
370                let valid_data = &data[0..8 + length];
371
372                // Write the potentially valid data back
373                let backup_path = path.with_extension("backup");
374                tokio::fs::rename(path, &backup_path).await?;
375                tokio::fs::write(path, valid_data).await?;
376
377                return Ok(true);
378            }
379        }
380
381        Ok(false)
382    }
383
384    /// Validate file using comprehensive checks
385    pub async fn validate_file<P: AsRef<Path>>(&self, path: P) -> Result<bool> {
386        self.verify_file_integrity(path).await
387    }
388}
389
390/// Schema evolution support for backward compatibility
391#[derive(Debug, Clone, Serialize, Deserialize)]
392pub struct SchemaVersion {
393    pub major: u32,
394    pub minor: u32,
395    pub patch: u32,
396}
397
398impl SchemaVersion {
399    pub const CURRENT: SchemaVersion = SchemaVersion {
400        major: 1,
401        minor: 0,
402        patch: 0,
403    };
404
405    pub fn is_compatible(&self, other: &SchemaVersion) -> bool {
406        self.major == other.major && self.minor >= other.minor
407    }
408}
409
410/// Versioned data wrapper for schema evolution
411#[derive(Debug, Clone, Serialize, Deserialize)]
412pub struct VersionedData<T> {
413    pub version: SchemaVersion,
414    pub data: T,
415}
416
417impl<T> VersionedData<T> {
418    pub fn new(data: T) -> Self {
419        Self {
420            version: SchemaVersion::CURRENT,
421            data,
422        }
423    }
424
425    pub fn validate_compatibility(&self) -> Result<()> {
426        if !SchemaVersion::CURRENT.is_compatible(&self.version) {
427            return Err(anyhow::anyhow!(
428                "Incompatible schema version: {:?}, current: {:?}",
429                self.version,
430                SchemaVersion::CURRENT
431            ));
432        }
433        Ok(())
434    }
435}
436
437#[cfg(test)]
438mod tests {
439    use super::*;
440    use tempfile::TempDir;
441
442    #[tokio::test]
443    async fn test_binary_serialization() {
444        let config = SerializationConfig::default();
445        let serializer = BinarySerializer::new(config);
446
447        let data = vec!["hello".to_string(), "world".to_string()];
448        let serialized = serializer.serialize(&data).unwrap();
449        let deserialized: Vec<String> = serializer.deserialize(&serialized).unwrap();
450
451        assert_eq!(data, deserialized);
452    }
453
454    #[tokio::test]
455    async fn test_atomic_file_writer() {
456        let temp_dir = TempDir::new().unwrap();
457        let file_path = temp_dir.path().join("test.dat");
458
459        let mut writer = AtomicFileWriter::new(&file_path).await.unwrap();
460        writer.write_all(b"test data").await.unwrap();
461        writer.commit().await.unwrap();
462
463        let content = tokio::fs::read(&file_path).await.unwrap();
464        assert_eq!(content, b"test data");
465    }
466
467    #[tokio::test]
468    async fn test_corruption_detection() {
469        let temp_dir = TempDir::new().unwrap();
470        let file_path = temp_dir.path().join("test.dat");
471
472        let config = SerializationConfig::default();
473        let serializer = BinarySerializer::new(config);
474        let detector = CorruptionDetector::new(true);
475
476        let data = vec!["test".to_string()];
477        let serialized = serializer.serialize(&data).unwrap();
478        tokio::fs::write(&file_path, &serialized).await.unwrap();
479
480        assert!(detector.validate_file(&file_path).await.unwrap());
481
482        // Corrupt the file - flip a bit in the middle of the data
483        let mut corrupted = serialized.clone();
484        let corrupt_idx = corrupted.len() / 2; // Use middle of actual data
485        corrupted[corrupt_idx] = !corrupted[corrupt_idx]; // Flip a bit
486        tokio::fs::write(&file_path, &corrupted).await.unwrap();
487
488        assert!(!detector.validate_file(&file_path).await.unwrap());
489    }
490
491    #[test]
492    fn test_schema_version_compatibility() {
493        let v1_0_0 = SchemaVersion {
494            major: 1,
495            minor: 0,
496            patch: 0,
497        };
498        let v1_1_0 = SchemaVersion {
499            major: 1,
500            minor: 1,
501            patch: 0,
502        };
503        let v2_0_0 = SchemaVersion {
504            major: 2,
505            minor: 0,
506            patch: 0,
507        };
508
509        assert!(v1_1_0.is_compatible(&v1_0_0));
510        assert!(!v1_0_0.is_compatible(&v1_1_0));
511        assert!(!v2_0_0.is_compatible(&v1_0_0));
512    }
513}