guardian-db 0.19.0

High-performance, local-first decentralized database built on Rust and Iroh
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
use crate::guardian::error::{GuardianError, Result};
use serde::{Deserialize, Serialize};
use tracing::{debug, warn};

/// Serializes a value to bytes using postcard (a deterministic binary format).
///
/// This module wraps postcard to provide:
/// - Unified error handling with GuardianError
/// - Centralized logging/tracing
/// - A single place to add features (compression, validation, etc.)
/// - Easier future migration if needed
///
/// # Arguments
/// * `value` - Any type that implements `Serialize`
///
/// # Returns
/// * `Result<Vec<u8>>` - Serialized bytes or an error
///
/// # Example
/// ```ignore
/// use guardian_db::serialization::serialize;
/// use serde::{Serialize, Deserialize};
///
/// #[derive(Serialize, Deserialize)]
/// struct MyData {
///     id: String,
///     value: i32,
/// }
///
/// let data = MyData { id: "test".to_string(), value: 42 };
/// let bytes = serialize(&data)?;
/// ```
pub fn serialize<T: Serialize>(value: &T) -> Result<Vec<u8>> {
    let result = postcard::to_allocvec(value)
        .map_err(|e| GuardianError::Serialization(format!("Postcard serialization failed: {}", e)));

    if let Ok(ref bytes) = result {
        debug!("Serialized {} bytes", bytes.len());
    } else if let Err(ref e) = result {
        warn!("Serialization failed: {}", e);
    }

    result
}

/// Serializes with a maximum size (protection against very large structures).
///
/// Useful for preventing OOM on resource-constrained systems.
///
/// # Arguments
/// * `value` - The value to serialize
/// * `max_bytes` - The maximum allowed size
///
/// # Returns
/// * `Result<Vec<u8>>` - Bytes, or an error if the limit is exceeded
pub fn serialize_with_limit<T: Serialize>(value: &T, max_bytes: usize) -> Result<Vec<u8>> {
    let bytes = serialize(value)?;

    if bytes.len() > max_bytes {
        warn!(
            "Serialized data exceeds limit: {} > {} bytes",
            bytes.len(),
            max_bytes
        );
        return Err(GuardianError::Serialization(format!(
            "Serialized size {} exceeds limit of {} bytes",
            bytes.len(),
            max_bytes
        )));
    }

    Ok(bytes)
}

/// Deserializes bytes into a value using postcard.
///
/// # Arguments
/// * `bytes` - A byte slice previously serialized with `serialize()`
///
/// # Returns
/// * `Result<T>` - The deserialized value or an error
///
/// # Example
/// ```ignore
/// use guardian_db::serialization::{serialize, deserialize};
/// use serde::{Serialize, Deserialize};
///
/// #[derive(Serialize, Deserialize, PartialEq, Debug)]
/// struct MyData {
///     id: String,
///     value: i32,
/// }
///
/// let data = MyData { id: "test".to_string(), value: 42 };
/// let bytes = serialize(&data)?;
/// let decoded: MyData = deserialize(&bytes)?;
/// assert_eq!(data, decoded);
/// ```
pub fn deserialize<T: for<'de> Deserialize<'de>>(bytes: &[u8]) -> Result<T> {
    if bytes.is_empty() {
        warn!("Attempted to deserialize empty byte array");
        return Err(GuardianError::Serialization(
            "Cannot deserialize empty byte array".to_string(),
        ));
    }

    let result = postcard::from_bytes(bytes).map_err(|e| {
        GuardianError::Serialization(format!("Postcard deserialization failed: {}", e))
    });

    if result.is_ok() {
        debug!("Deserialized {} bytes", bytes.len());
    } else if let Err(ref e) = result {
        warn!("Deserialization failed: {}", e);
    }

    result
}

/// Computes the BLAKE3 hash of the serialized bytes.
///
/// Useful for integrity verification and identifier generation.
///
/// # Arguments
/// * `value` - The value to serialize and hash
///
/// # Returns
/// * `Result<[u8; 32]>` - The BLAKE3 hash (32 bytes)
pub fn serialize_and_hash<T: Serialize>(value: &T) -> Result<[u8; 32]> {
    let bytes = serialize(value)?;
    let hash = blake3::hash(&bytes);
    Ok(*hash.as_bytes())
}

/// Serialization statistics (for debugging/monitoring).
#[derive(Debug, Clone)]
pub struct SerializationStats {
    pub original_size: usize,
    pub serialized_size: usize,
    pub compression_ratio: f64,
}

impl SerializationStats {
    /// Builds stats from the original and serialized sizes, computing the
    /// compression ratio (serialized / original).
    pub fn new(original_size: usize, serialized_size: usize) -> Self {
        let compression_ratio = if original_size > 0 {
            serialized_size as f64 / original_size as f64
        } else {
            0.0
        };

        Self {
            original_size,
            serialized_size,
            compression_ratio,
        }
    }
}

/// Serializes and returns statistics (useful for benchmarking).
pub fn serialize_with_stats<T: Serialize>(value: &T) -> Result<(Vec<u8>, SerializationStats)> {
    let bytes = serialize(value)?;

    // Estimate the original size (JSON as a baseline).
    let json_size = serde_json::to_vec(value).map(|v| v.len()).unwrap_or(0);

    let stats = SerializationStats::new(json_size, bytes.len());

    debug!(
        "Serialization: {} bytes (postcard) vs {} bytes (JSON) - {:.1}% reduction",
        bytes.len(),
        json_size,
        (1.0 - stats.compression_ratio) * 100.0
    );

    Ok((bytes, stats))
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde::{Deserialize, Serialize};

    #[derive(Serialize, Deserialize, Debug, PartialEq)]
    struct TestData {
        id: String,
        value: i32,
        nested: NestedData,
    }

    #[derive(Serialize, Deserialize, Debug, PartialEq)]
    struct NestedData {
        flag: bool,
        items: Vec<String>,
    }

    #[test]
    fn test_serialize_with_limit() {
        let small_data = TestData {
            id: "small".to_string(),
            value: 42,
            nested: NestedData {
                flag: true,
                items: vec!["a".to_string()],
            },
        };

        // Should pass - generous limit.
        let result = serialize_with_limit(&small_data, 1000);
        assert!(result.is_ok());

        // Should fail - limit too low.
        let result = serialize_with_limit(&small_data, 10);
        assert!(result.is_err());

        if let Err(GuardianError::Serialization(msg)) = result {
            assert!(msg.contains("exceeds limit"));
        }
    }

    #[test]
    fn test_deserialize_empty_bytes() {
        let empty_bytes: Vec<u8> = vec![];
        let result: Result<TestData> = deserialize(&empty_bytes);

        assert!(result.is_err());
        if let Err(GuardianError::Serialization(msg)) = result {
            assert!(msg.contains("empty"));
        }
    }

    #[test]
    fn test_serialize_and_hash() {
        let data = TestData {
            id: "hash_test".to_string(),
            value: 999,
            nested: NestedData {
                flag: true,
                items: vec!["x".to_string()],
            },
        };

        // Hash must be deterministic.
        let hash1 = serialize_and_hash(&data).expect("Hash failed");
        let hash2 = serialize_and_hash(&data).expect("Hash failed");

        assert_eq!(hash1, hash2);
        assert_eq!(hash1.len(), 32); // BLAKE3 = 32 bytes

        println!("✅ BLAKE3 hash (hex): {}", hex::encode(hash1));
    }

    #[test]
    fn test_serialize_with_stats() {
        let data = TestData {
            id: "stats_test".to_string(),
            value: 12345,
            nested: NestedData {
                flag: false,
                items: vec![
                    "item1".to_string(),
                    "item2".to_string(),
                    "item3".to_string(),
                ],
            },
        };

        let (bytes, stats) = serialize_with_stats(&data).expect("Serialization with stats failed");

        assert!(!bytes.is_empty());
        assert!(stats.serialized_size > 0);
        assert!(stats.original_size > 0);
        assert!(
            stats.compression_ratio < 1.0,
            "Postcard should be smaller than JSON"
        );

        println!("📊 Stats:");
        println!("   Original (JSON): {} bytes", stats.original_size);
        println!("   Postcard:        {} bytes", stats.serialized_size);
        println!("   Ratio:           {:.2}", stats.compression_ratio);
        println!(
            "   Reduction:       {:.1}%",
            (1.0 - stats.compression_ratio) * 100.0
        );
    }

    #[test]
    fn test_roundtrip() {
        let data = TestData {
            id: "test123".to_string(),
            value: 42,
            nested: NestedData {
                flag: true,
                items: vec!["a".to_string(), "b".to_string(), "c".to_string()],
            },
        };

        let bytes = serialize(&data).expect("Serialization failed");
        let decoded: TestData = deserialize(&bytes).expect("Deserialization failed");

        assert_eq!(data, decoded);
    }

    #[test]
    fn test_determinism() {
        let data = TestData {
            id: "determinism_test".to_string(),
            value: 999,
            nested: NestedData {
                flag: false,
                items: vec!["x".to_string(), "y".to_string()],
            },
        };

        // Serialize 10 times and check that the bytes are identical.
        let mut all_bytes = Vec::new();
        for _ in 0..10 {
            let bytes = serialize(&data).expect("Serialization failed");
            all_bytes.push(bytes);
        }

        // Check that all results are identical.
        let first = &all_bytes[0];
        for bytes in &all_bytes[1..] {
            assert_eq!(first, bytes, "Serialization is not deterministic!");
        }
    }

    #[test]
    fn test_determinism_with_hash() {
        use blake3;

        let data = TestData {
            id: "hash_test".to_string(),
            value: 12345,
            nested: NestedData {
                flag: true,
                items: vec!["item1".to_string(), "item2".to_string()],
            },
        };

        // Serialize 10 times and check that the BLAKE3 hash is always the same.
        let hashes: Vec<String> = (0..10)
            .map(|_| {
                let bytes = serialize(&data).expect("Serialization failed");
                blake3::hash(&bytes).to_hex().to_string()
            })
            .collect();

        // All hashes must be identical.
        let first_hash = &hashes[0];
        for hash in &hashes[1..] {
            assert_eq!(
                first_hash, hash,
                "BLAKE3 hash varies - serialization is not deterministic!"
            );
        }

        println!("✅ Determinism verified - BLAKE3 hash: {}", first_hash);
    }

    #[test]
    fn test_empty_vec() {
        let data = TestData {
            id: String::new(),
            value: 0,
            nested: NestedData {
                flag: false,
                items: vec![],
            },
        };

        let bytes = serialize(&data).expect("Serialization failed");
        let decoded: TestData = deserialize(&bytes).expect("Deserialization failed");

        assert_eq!(data, decoded);
    }

    #[test]
    fn test_large_strings() {
        let large_string = "x".repeat(10000);
        let data = TestData {
            id: large_string.clone(),
            value: i32::MAX,
            nested: NestedData {
                flag: true,
                items: vec![large_string.clone(), large_string],
            },
        };

        let bytes = serialize(&data).expect("Serialization failed");
        let decoded: TestData = deserialize(&bytes).expect("Deserialization failed");

        assert_eq!(data, decoded);
    }

    #[test]
    fn test_invalid_bytes() {
        let invalid_bytes = vec![0xFF, 0xFF, 0xFF, 0xFF];
        let result: Result<TestData> = deserialize(&invalid_bytes);

        assert!(result.is_err(), "Should fail with invalid bytes");
    }

    #[test]
    fn test_size_comparison_with_json() {
        let data = TestData {
            id: "size_test".to_string(),
            value: 42,
            nested: NestedData {
                flag: true,
                items: vec!["a".to_string(), "b".to_string(), "c".to_string()],
            },
        };

        // Postcard
        let postcard_bytes = serialize(&data).expect("Postcard serialization failed");

        // JSON (for comparison).
        let json_bytes = serde_json::to_vec(&data).expect("JSON serialization failed");

        println!("Postcard size: {} bytes", postcard_bytes.len());
        println!("JSON size: {} bytes", json_bytes.len());
        println!(
            "Reduction: {:.1}%",
            (1.0 - (postcard_bytes.len() as f64 / json_bytes.len() as f64)) * 100.0
        );

        // Postcard should be significantly smaller.
        assert!(
            postcard_bytes.len() < json_bytes.len(),
            "Postcard should be smaller than JSON"
        );
    }
}