1use anyhow::Result;
7use serde::{Deserialize, Serialize};
8use std::path::{Path, PathBuf};
9use tokio::fs::{File, OpenOptions};
10use tokio::io::{AsyncWrite, AsyncWriteExt};
11
12#[derive(Debug, Clone)]
14pub enum SerializationFormat {
15 Json,
17 MessagePack,
19 Cbor,
21 Bincode,
23}
24
25#[derive(Debug, Clone)]
27pub enum CompressionAlgorithm {
28 None,
30 Lz4,
32 Zstd,
34 Deflate,
36}
37
38#[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
58pub struct BinarySerializer {
60 config: SerializationConfig,
61}
62
63impl BinarySerializer {
64 pub fn new(config: SerializationConfig) -> Self {
65 Self { config }
66 }
67
68 pub fn serialize<T: Serialize>(&self, data: &T) -> Result<Vec<u8>> {
70 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 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 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 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 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 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 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 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 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 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 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 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
192pub struct AtomicFileWriter {
194 temp_path: PathBuf,
195 final_path: PathBuf,
196 file: Option<File>,
197}
198
199impl AtomicFileWriter {
200 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 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 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 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
297pub 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 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); }
318
319 let data = tokio::fs::read(path).await?;
321
322 if (data.len() as u64) != metadata.len() {
324 return Ok(false);
325 }
326
327 if self.enable_deep_scan {
328 self.verify_content_integrity(&data).await
330 } else {
331 Ok(true)
332 }
333 }
334
335 async fn verify_content_integrity(&self, data: &[u8]) -> Result<bool> {
337 if data.len() >= 8 {
340 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) }
353
354 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 let data = tokio::fs::read(path).await?;
363
364 if data.len() >= 8 {
366 let length = u32::from_le_bytes([data[4], data[5], data[6], data[7]]) as usize;
367
368 if length > 0 && data.len() >= 8 + length {
370 let valid_data = &data[0..8 + length];
371
372 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 pub async fn validate_file<P: AsRef<Path>>(&self, path: P) -> Result<bool> {
386 self.verify_file_integrity(path).await
387 }
388}
389
390#[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#[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 let mut corrupted = serialized.clone();
484 let corrupt_idx = corrupted.len() / 2; corrupted[corrupt_idx] = !corrupted[corrupt_idx]; 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}