atmst 0.0.1

light atproto-style merkle search tree impl.
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
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
use async_trait::async_trait;
use cid::Cid;
use fjall::{Config, PartitionHandle};
use lru::LruCache;
use std::num::NonZeroUsize;
use std::path::Path;
use std::sync::Arc;
use tokio::sync::Mutex;

use super::MstStorage;
use crate::error::{AtmosError, Result};
use crate::mst::node::MstNode;

/// Fjall-based persistent MST storage with optional LRU caching
pub struct FjallMstStorage {
    /// Fjall partition for storing MST nodes
    nodes: Arc<PartitionHandle>,
    /// Optional in-memory LRU cache for frequently accessed nodes
    cache: Option<Arc<Mutex<LruCache<Cid, MstNode>>>>,
    /// Serialization format configuration
    config: FjallStorageConfig,
}

impl std::fmt::Debug for FjallMstStorage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FjallMstStorage")
            .field("config", &self.config)
            .finish()
    }
}

impl Clone for FjallMstStorage {
    fn clone(&self) -> Self {
        Self {
            nodes: Arc::clone(&self.nodes),
            cache: self.cache.clone(),
            config: self.config.clone(),
        }
    }
}

/// Configuration for Fjall storage behavior
#[derive(Debug, Clone)]
pub struct FjallStorageConfig {
    /// Enable LRU caching
    pub enable_cache: bool,
    /// Maximum number of nodes to cache (if caching enabled)
    pub cache_capacity: usize,
    /// Serialization format
    pub serialization: SerializationFormat,
    /// Compression settings
    pub compression: CompressionConfig,
    /// Sync behavior
    pub sync_on_commit: bool,
}

/// Serialization format options
#[derive(Debug, Clone, Copy)]
pub enum SerializationFormat {
    /// Use bincode for fast, compact serialization
    Bincode,
    /// Use CBOR for IPLD compatibility
    Cbor,
}

/// Compression configuration
#[derive(Debug, Clone)]
pub struct CompressionConfig {
    pub enabled: bool,
    pub algorithm: CompressionAlgorithm,
}

#[derive(Debug, Clone, Copy)]
pub enum CompressionAlgorithm {
    Lz4,
    Zstd,
    None,
}

impl Default for FjallStorageConfig {
    fn default() -> Self {
        Self {
            enable_cache: true,
            cache_capacity: 10_000,
            serialization: SerializationFormat::Bincode,
            compression: CompressionConfig {
                enabled: true,
                algorithm: CompressionAlgorithm::Lz4,
            },
            sync_on_commit: false, // Async by default for better performance
        }
    }
}

impl FjallStorageConfig {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_cache(mut self, enabled: bool, capacity: usize) -> Self {
        self.enable_cache = enabled;
        self.cache_capacity = capacity;
        self
    }

    pub fn with_serialization(mut self, format: SerializationFormat) -> Self {
        self.serialization = format;
        self
    }

    pub fn with_compression(mut self, enabled: bool, algorithm: CompressionAlgorithm) -> Self {
        self.compression = CompressionConfig { enabled, algorithm };
        self
    }

    pub fn with_sync_on_commit(mut self, sync: bool) -> Self {
        self.sync_on_commit = sync;
        self
    }
}

impl FjallMstStorage {
    /// Create a new Fjall storage at the given path
    pub async fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
        Self::open_with_config(path, FjallStorageConfig::default()).await
    }

    /// Create a new Fjall storage with custom configuration
    pub async fn open_with_config<P: AsRef<Path>>(
        path: P,
        config: FjallStorageConfig,
    ) -> Result<Self> {
        // Configure Fjall database with basic settings
        let db = Config::new(path)
            .open()
            .map_err(|e| AtmosError::mst(format!("Failed to open Fjall database: {}", e)))?;

        // Create partition for MST nodes
        let nodes = Arc::new(
            db.open_partition("mst_nodes", fjall::PartitionCreateOptions::default())
                .map_err(|e| AtmosError::mst(format!("Failed to create partition: {}", e)))?,
        );

        // Initialize cache if enabled
        let cache = if config.enable_cache {
            let capacity = NonZeroUsize::new(config.cache_capacity)
                .ok_or_else(|| AtmosError::invalid_field("cache_capacity", "must be > 0"))?;
            Some(Arc::new(Mutex::new(LruCache::new(capacity))))
        } else {
            None
        };

        Ok(Self {
            nodes,
            cache,
            config,
        })
    }

    /// Create an in-memory temporary storage (useful for testing)
    pub async fn temporary() -> Result<Self> {
        let temp_dir = std::env::temp_dir().join(format!("fjall_mst_{}", uuid::Uuid::new_v4()));
        Self::open(&temp_dir).await
    }

    /// Compact the underlying database
    pub async fn compact(&self) -> Result<()> {
        // Fjall handles compaction automatically, so this is a no-op
        Ok(())
    }

    /// Get storage statistics
    pub async fn stats(&self) -> Result<FjallStorageStats> {
        let cache_stats = if let Some(cache) = &self.cache {
            let cache_guard = cache.lock().await;
            Some(CacheStats {
                capacity: cache_guard.cap().get(),
                len: cache_guard.len(),
                hit_rate: 0.0, // Would need separate hit/miss counters
            })
        } else {
            None
        };

        // Get actual key count using the len() method
        let total_keys = self.len().await?;

        // For disk usage, we'll estimate based on node count for now
        let estimated_disk_usage = (total_keys * 1024) as u64; // Rough estimate

        Ok(FjallStorageStats {
            disk_usage_bytes: estimated_disk_usage,
            total_keys: total_keys as u64,
            cache_stats,
        })
    }

    /// Serialize a node using the configured format
    fn serialize_node(&self, node: &MstNode) -> Result<Vec<u8>> {
        match self.config.serialization {
            SerializationFormat::Bincode => bincode::serialize(node)
                .map_err(|e| AtmosError::mst(format!("Bincode serialization failed: {}", e))),
            SerializationFormat::Cbor => {
                serde_ipld_dagcbor::to_vec(node).map_err(|e| AtmosError::CborEncodingGeneric(e))
            }
        }
    }

    /// Deserialize a node using the configured format
    fn deserialize_node(&self, data: &[u8]) -> Result<MstNode> {
        match self.config.serialization {
            SerializationFormat::Bincode => bincode::deserialize(data)
                .map_err(|e| AtmosError::mst(format!("Bincode deserialization failed: {}", e))),
            SerializationFormat::Cbor => {
                serde_ipld_dagcbor::from_slice(data).map_err(|e| AtmosError::CborDecodingGeneric(e))
            }
        }
    }
}

#[async_trait]
impl MstStorage for FjallMstStorage {
    async fn get_node(&self, cid: &Cid) -> Result<Option<MstNode>> {
        // Check cache first
        if let Some(cache) = &self.cache {
            let mut cache_guard = cache.lock().await;
            if let Some(node) = cache_guard.get(cid) {
                return Ok(Some(node.clone()));
            }
        }

        // Load from disk
        let cid_bytes = cid.to_bytes();
        if let Ok(Some(data)) = self.nodes.get(cid_bytes) {
            let node = self.deserialize_node(&data)?;

            // Cache for future access
            if let Some(cache) = &self.cache {
                let mut cache_guard = cache.lock().await;
                cache_guard.put(*cid, node.clone());
            }

            Ok(Some(node))
        } else {
            Ok(None)
        }
    }

    async fn insert_node(&self, cid: Cid, node: MstNode) -> Result<()> {
        let cid_bytes = cid.to_bytes();
        let data = self.serialize_node(&node)?;

        // Insert into Fjall
        self.nodes
            .insert(cid_bytes, data)
            .map_err(|e| AtmosError::mst(format!("Fjall insert failed: {}", e)))?;

        // Update cache
        if let Some(cache) = &self.cache {
            let mut cache_guard = cache.lock().await;
            cache_guard.put(cid, node);
        }

        Ok(())
    }

    async fn remove_node(&self, cid: &Cid) -> Result<Option<MstNode>> {
        let cid_bytes = cid.to_bytes();

        // Get the node first (for return value)
        let existing = self.get_node(cid).await?;

        // Remove from Fjall
        self.nodes
            .remove(cid_bytes)
            .map_err(|e| AtmosError::mst(format!("Fjall remove failed: {}", e)))?;

        // Remove from cache
        if let Some(cache) = &self.cache {
            let mut cache_guard = cache.lock().await;
            cache_guard.pop(cid);
        }

        Ok(existing)
    }

    async fn contains_node(&self, cid: &Cid) -> Result<bool> {
        // Check cache first
        if let Some(cache) = &self.cache {
            let cache_guard = cache.lock().await;
            if cache_guard.contains(cid) {
                return Ok(true);
            }
        }

        // Check Fjall
        let cid_bytes = cid.to_bytes();
        Ok(self.nodes.contains_key(cid_bytes).unwrap_or(false))
    }

    async fn len(&self) -> Result<usize> {
        // Count entries by iterating through all keys
        let iter = self.nodes.iter();
        let mut count = 0;

        for item in iter {
            match item {
                Ok(_) => count += 1,
                Err(e) => {
                    return Err(AtmosError::Io(std::io::Error::new(
                        std::io::ErrorKind::Other,
                        format!("Failed to iterate storage: {}", e),
                    )));
                }
            }
        }

        Ok(count)
    }

    async fn clear(&self) -> Result<()> {
        // Clear cache first
        if let Some(cache) = &self.cache {
            let mut cache_guard = cache.lock().await;
            cache_guard.clear();
        }

        // Clear all entries from Fjall storage
        let keys_to_remove: Vec<_> = self
            .nodes
            .iter()
            .filter_map(|item| match item {
                Ok((key, _)) => Some(key),
                Err(_) => None,
            })
            .collect();

        for key in keys_to_remove {
            if let Err(e) = self.nodes.remove(&*key) {
                return Err(AtmosError::Io(std::io::Error::new(
                    std::io::ErrorKind::Other,
                    format!("Failed to remove key during clear: {}", e),
                )));
            }
        }

        Ok(())
    }

    async fn all_cids(&self) -> Result<Vec<Cid>> {
        let mut cids = Vec::new();
        let iter = self.nodes.iter();

        for item in iter {
            match item {
                Ok((key, _)) => match Cid::try_from(key.as_ref()) {
                    Ok(cid) => cids.push(cid),
                    Err(e) => {
                        return Err(AtmosError::InvalidIpld {
                            message: format!("Failed to parse CID from key: {}", e),
                        });
                    }
                },
                Err(e) => {
                    return Err(AtmosError::Io(std::io::Error::new(
                        std::io::ErrorKind::Other,
                        format!("Failed to iterate storage: {}", e),
                    )));
                }
            }
        }

        Ok(cids)
    }

    async fn batch_insert(&self, nodes: Vec<(Cid, MstNode)>) -> Result<()> {
        if nodes.is_empty() {
            return Ok(());
        }

        // Fjall batch operations have a different API
        // For now, we'll insert one by one
        // TODO: Implement proper batch operations when Fjall API is stable
        let mut cache_updates = Vec::new();
        for (cid, node) in nodes {
            let cid_bytes = cid.to_bytes();
            let data = self.serialize_node(&node)?;

            self.nodes
                .insert(cid_bytes, data)
                .map_err(|e| AtmosError::mst(format!("Fjall insert failed: {}", e)))?;
            cache_updates.push((cid, node));
        }

        // Update cache after successful commit
        if let Some(cache) = &self.cache {
            let mut cache_guard = cache.lock().await;
            for (cid, node) in cache_updates {
                cache_guard.put(cid, node);
            }
        }

        Ok(())
    }

    async fn batch_remove(&self, cids: Vec<Cid>) -> Result<Vec<Option<MstNode>>> {
        if cids.is_empty() {
            return Ok(Vec::new());
        }

        // Get existing nodes first
        let mut removed_nodes = Vec::new();
        for cid in &cids {
            removed_nodes.push(self.get_node(cid).await?);
        }

        // Fjall batch operations have a different API
        // For now, we'll remove one by one
        for cid in &cids {
            let cid_bytes = cid.to_bytes();
            self.nodes
                .remove(cid_bytes)
                .map_err(|e| AtmosError::mst(format!("Fjall remove failed: {}", e)))?;
        }

        // Update cache after successful commit
        if let Some(cache) = &self.cache {
            let mut cache_guard = cache.lock().await;
            for cid in &cids {
                cache_guard.pop(cid);
            }
        }

        Ok(removed_nodes)
    }

    fn clone_storage(&self) -> Box<dyn MstStorage> {
        Box::new(self.clone())
    }
}

/// Storage statistics
#[derive(Debug, Clone)]
pub struct FjallStorageStats {
    pub disk_usage_bytes: u64,
    pub total_keys: u64,
    pub cache_stats: Option<CacheStats>,
}

#[derive(Debug, Clone)]
pub struct CacheStats {
    pub capacity: usize,
    pub len: usize,
    pub hit_rate: f64,
}

// Compression is handled differently in the current Fjall version
// This function is kept for compatibility but doesn't do anything
fn map_compression(_config: &CompressionConfig) {
    // No-op for now
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Bytes;
    use crate::mst::node::{MstNode, MstNodeLeaf};
    use multihash::Multihash;
    use sha2::Digest;
    use tempfile::TempDir;

    fn create_test_cid(data: &str) -> Cid {
        let hash = Multihash::wrap(0x12, &sha2::Sha256::digest(data.as_bytes())).unwrap();
        Cid::new_v1(0x71, hash)
    }

    fn create_test_node(entries: Vec<(usize, String, Cid, Option<Cid>)>) -> MstNode {
        let e = entries
            .into_iter()
            .map(|(p, k, v, t)| MstNodeLeaf {
                p,
                k: Bytes::from(k.into_bytes()),
                v,
                t,
            })
            .collect();

        MstNode::new(None, e)
    }

    #[tokio::test]
    async fn test_fjall_storage_basic_operations() {
        let temp_dir = TempDir::new().unwrap();
        let storage = FjallMstStorage::open(temp_dir.path()).await.unwrap();

        let cid = create_test_cid("test_node");
        let node = create_test_node(vec![(
            0,
            "key1".to_string(),
            create_test_cid("value1"),
            None,
        )]);

        // Test insert and get
        storage.insert_node(cid, node.clone()).await.unwrap();
        let retrieved = storage.get_node(&cid).await.unwrap();
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().entries().len(), 1);

        // Test contains
        assert!(storage.contains_node(&cid).await.unwrap());

        // Test len
        assert_eq!(storage.len().await.unwrap(), 1);

        // Test remove
        let removed = storage.remove_node(&cid).await.unwrap();
        assert!(removed.is_some());
        assert!(!storage.contains_node(&cid).await.unwrap());
        assert_eq!(storage.len().await.unwrap(), 0);
    }

    #[tokio::test]
    async fn test_fjall_storage_persistence() {
        let temp_dir = TempDir::new().unwrap();
        let path = temp_dir.path().to_path_buf();

        let cid = create_test_cid("persistent_node");
        let node = create_test_node(vec![(
            0,
            "persistent_key".to_string(),
            create_test_cid("persistent_value"),
            None,
        )]);

        // Insert data and close storage
        {
            let storage = FjallMstStorage::open(&path).await.unwrap();
            storage.insert_node(cid, node.clone()).await.unwrap();
        }

        // Reopen storage and verify data persists
        {
            let storage = FjallMstStorage::open(&path).await.unwrap();
            let retrieved = storage.get_node(&cid).await.unwrap();
            assert!(retrieved.is_some());
            assert_eq!(retrieved.unwrap().entries().len(), 1);
        }
    }

    #[tokio::test]
    async fn test_fjall_storage_batch_operations() {
        let temp_dir = TempDir::new().unwrap();
        let storage = FjallMstStorage::open(temp_dir.path()).await.unwrap();

        let nodes = vec![
            (
                create_test_cid("node1"),
                create_test_node(vec![(
                    0,
                    "key1".to_string(),
                    create_test_cid("value1"),
                    None,
                )]),
            ),
            (
                create_test_cid("node2"),
                create_test_node(vec![(
                    0,
                    "key2".to_string(),
                    create_test_cid("value2"),
                    None,
                )]),
            ),
        ];

        // Test batch insert
        storage.batch_insert(nodes.clone()).await.unwrap();
        assert_eq!(storage.len().await.unwrap(), 2);

        // Test batch remove
        let cids_to_remove: Vec<Cid> = nodes.iter().map(|(cid, _)| *cid).collect();
        let removed = storage.batch_remove(cids_to_remove).await.unwrap();
        assert_eq!(removed.len(), 2);
        assert!(removed[0].is_some());
        assert!(removed[1].is_some());
        assert_eq!(storage.len().await.unwrap(), 0);
    }

    #[tokio::test]
    async fn test_fjall_storage_configuration() {
        let temp_dir = TempDir::new().unwrap();

        let config = FjallStorageConfig::new()
            .with_cache(true, 1000)
            .with_serialization(SerializationFormat::Cbor)
            .with_compression(true, CompressionAlgorithm::Zstd)
            .with_sync_on_commit(true);

        let storage = FjallMstStorage::open_with_config(temp_dir.path(), config)
            .await
            .unwrap();

        // Verify cache is enabled
        assert!(storage.cache.is_some());

        // Test basic operations work with custom config
        let cid = create_test_cid("config_test");
        let node = create_test_node(vec![(
            0,
            "config_key".to_string(),
            create_test_cid("config_value"),
            None,
        )]);

        storage.insert_node(cid, node).await.unwrap();
        let retrieved = storage.get_node(&cid).await.unwrap();
        assert!(retrieved.is_some());
    }

    #[tokio::test]
    async fn test_fjall_storage_stats() {
        let temp_dir = TempDir::new().unwrap();
        let storage = FjallMstStorage::open(temp_dir.path()).await.unwrap();

        // Insert some data
        for i in 0..5 {
            let cid = create_test_cid(&format!("stats_node_{}", i));
            let node = create_test_node(vec![(
                0,
                format!("stats_key_{}", i),
                create_test_cid(&format!("stats_value_{}", i)),
                None,
            )]);
            storage.insert_node(cid, node).await.unwrap();
        }

        let stats = storage.stats().await.unwrap();
        assert_eq!(stats.total_keys, 5);
        assert!(stats.disk_usage_bytes > 0);
    }
}