gun-rs 1.0.4

A realtime, decentralized, offline-first, graph data synchronization engine (Rust port)
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
//! Pluggable storage backends for persistent data
//!
//! This module provides storage abstractions for Gun, allowing data to be persisted
//! to disk or other backends. Multiple storage implementations are provided:
//!
//! - **MemoryStorage**: In-memory only (no persistence)
//! - **LocalStorage**: File-based storage (similar to browser localStorage)
//! - **SledStorage**: High-performance embedded database
//!
//! Based on Gun.js storage adapters (localStorage, RAD, S3, etc.). All storage
//! backends implement the [`Storage`](Storage) trait for a uniform interface.

use crate::error::{GunError, GunResult};
use crate::state::Node;
use async_trait::async_trait;
use parking_lot::RwLock;
use std::collections::{HashMap, HashSet};
use std::fs;
use std::io::{Read, Write};
use std::path::PathBuf;

/// Storage backend trait for persistent data storage
///
/// All storage backends in Gun implement this trait. It provides a simple interface
/// for storing and retrieving nodes by their soul (unique identifier).
///
/// Based on Gun.js storage adapters. The trait is async to support I/O operations
/// and is `Send + Sync` to work across threads.
///
/// # Example
///
/// ```rust,no_run
/// use gun::storage::{Storage, LocalStorage};
/// use gun::state::Node;
/// use std::sync::Arc;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let storage: Arc<dyn Storage> = Arc::new(LocalStorage::new("./gun_data")?);
///
/// let node = Node::with_soul("user_123".to_string());
/// storage.put("user_123", &node).await?;
///
/// if let Some(loaded_node) = storage.get("user_123").await? {
///     println!("Loaded node: {:?}", loaded_node);
/// }
/// # Ok(())
/// # }
/// ```
#[async_trait]
pub trait Storage: Send + Sync {
    /// Retrieve a node by its soul (unique identifier)
    ///
    /// # Arguments
    /// * `soul` - The unique identifier of the node to retrieve
    ///
    /// # Returns
    /// `Ok(Some(node))` if found, `Ok(None)` if not found, or `GunError` on failure.
    async fn get(&self, soul: &str) -> GunResult<Option<Node>>;

    /// Store a node by its soul (unique identifier)
    ///
    /// # Arguments
    /// * `soul` - The unique identifier for the node
    /// * `node` - The node to store
    ///
    /// # Returns
    /// `Ok(())` on success, or `GunError` on failure.
    async fn put(&self, soul: &str, node: &Node) -> GunResult<()>;

    /// Check if a node exists in storage
    ///
    /// # Arguments
    /// * `soul` - The unique identifier to check
    ///
    /// # Returns
    /// `Ok(true)` if the node exists, `Ok(false)` if not, or `GunError` on failure.
    async fn has(&self, soul: &str) -> GunResult<bool>;
}

/// In-memory storage backend (no persistence)
///
/// Stores data in a `HashMap` in memory. Data is lost when the instance is dropped.
/// This is useful for:
/// - Testing
/// - Temporary data
/// - Performance-critical scenarios where persistence isn't needed
///
/// # Thread Safety
///
/// `MemoryStorage` is thread-safe and can be shared across threads using `Arc<MemoryStorage>`.
///
/// # Example
///
/// ```rust,no_run
/// use gun::storage::{Storage, MemoryStorage};
/// use gun::state::Node;
/// use std::sync::Arc;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let storage = Arc::new(MemoryStorage::new());
/// let node = Node::with_soul("user_123".to_string());
/// storage.put("user_123", &node).await?;
/// # Ok(())
/// # }
/// ```
pub struct MemoryStorage {
    data: RwLock<HashMap<String, Node>>,
}

impl MemoryStorage {
    pub fn new() -> Self {
        Self {
            data: RwLock::new(HashMap::new()),
        }
    }
}

#[async_trait]
impl Storage for MemoryStorage {
    async fn get(&self, soul: &str) -> GunResult<Option<Node>> {
        let data = self.data.read();
        Ok(data.get(soul).cloned())
    }

    async fn put(&self, soul: &str, node: &Node) -> GunResult<()> {
        let mut data = self.data.write();
        data.insert(soul.to_string(), node.clone());
        Ok(())
    }

    async fn has(&self, soul: &str) -> GunResult<bool> {
        let data = self.data.read();
        Ok(data.contains_key(soul))
    }
}

impl Default for MemoryStorage {
    fn default() -> Self {
        Self::new()
    }
}

/// Sled-based persistent storage backend
///
/// Uses the [sled](https://docs.rs/sled) embedded database for high-performance,
/// persistent storage. This is recommended for:
/// - Large datasets
/// - High write throughput
/// - Production applications
///
/// Sled provides:
/// - ACID transactions
/// - High performance
/// - Automatic crash recovery
/// - Efficient storage format
///
/// # Thread Safety
///
/// `SledStorage` is thread-safe and can be shared across threads using `Arc<SledStorage>`.
///
/// # Example
///
/// ```rust,no_run
/// use gun::storage::{Storage, SledStorage};
/// use gun::state::Node;
/// use std::sync::Arc;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let storage = Arc::new(SledStorage::new("./gun_data")?);
/// let node = Node::with_soul("user_123".to_string());
/// storage.put("user_123", &node).await?;
/// # Ok(())
/// # }
/// ```
pub struct SledStorage {
    db: sled::Db,
}

impl SledStorage {
    /// Create a new SledStorage instance
    ///
    /// # Arguments
    /// * `path` - Directory path where the sled database will be stored
    ///
    /// # Returns
    /// `Ok(SledStorage)` if initialization succeeds, or `GunError` on failure.
    ///
    /// # Errors
    /// Returns `GunError::Storage` if the sled database cannot be opened or created.
    pub fn new(path: &str) -> GunResult<Self> {
        let db = sled::open(path)?;
        Ok(Self { db })
    }
}

#[async_trait]
impl Storage for SledStorage {
    async fn get(&self, soul: &str) -> GunResult<Option<Node>> {
        match self.db.get(soul)? {
            Some(ivec) => {
                let json_str = String::from_utf8(ivec.to_vec())
                    .map_err(|e| GunError::InvalidData(format!("Invalid UTF-8: {}", e)))?;
                let node: Node = serde_json::from_str(&json_str)?;
                Ok(Some(node))
            }
            None => Ok(None),
        }
    }

    async fn put(&self, soul: &str, node: &Node) -> GunResult<()> {
        let json_str = serde_json::to_string(node)?;
        self.db.insert(soul, json_str.as_bytes())?;
        self.db.flush_async().await?;
        Ok(())
    }

    async fn has(&self, soul: &str) -> GunResult<bool> {
        Ok(self.db.contains_key(soul)?)
    }
}

/// LocalStorage-equivalent storage for Rust
/// Provides a simple, persistent key-value store similar to browser localStorage
/// Stores data in JSON files on disk in a single directory
///
/// This is similar to browser localStorage in that it:
/// - Persists data to disk
/// - Provides simple get/put/has operations
/// - Stores data in a user-accessible location
/// - Is simpler than a full database (like Sled)
pub struct LocalStorage {
    data_dir: PathBuf,
    cache: RwLock<HashMap<String, Node>>, // In-memory cache for performance
    dirty: RwLock<HashSet<String>>,       // Track which keys need to be written to disk
}

impl LocalStorage {
    /// Create a new LocalStorage instance
    ///
    /// # Arguments
    /// * `data_dir` - Directory path where data will be stored (e.g., "./gun_data")
    ///
    /// Creates the directory if it doesn't exist
    pub fn new(data_dir: &str) -> GunResult<Self> {
        let path = PathBuf::from(data_dir);

        // Create directory if it doesn't exist
        fs::create_dir_all(&path).map_err(|e| {
            GunError::Io(std::io::Error::other(format!(
                "Failed to create storage directory: {}",
                e
            )))
        })?;

        // Load existing data into cache
        let cache = Self::load_all(&path)?;

        Ok(Self {
            data_dir: path,
            cache: RwLock::new(cache),
            dirty: RwLock::new(HashSet::new()),
        })
    }

    /// Load all data from disk into memory cache
    fn load_all(path: &PathBuf) -> GunResult<HashMap<String, Node>> {
        let mut data = HashMap::new();

        // Read all files in the directory
        if let Ok(entries) = fs::read_dir(path) {
            for entry in entries.flatten() {
                let file_path = entry.path();
                if file_path.is_file() {
                    if let Some(file_name) = file_path.file_name() {
                        if let Some(soul) = file_name.to_str() {
                            // Try to decode the filename (may be URL-encoded)
                            let soul = urlencoding::decode(soul)
                                .unwrap_or(std::borrow::Cow::Borrowed(soul))
                                .into_owned();

                            if let Ok(node) = Self::load_file(&file_path) {
                                data.insert(soul, node);
                            }
                        }
                    }
                }
            }
        }

        Ok(data)
    }

    /// Load a single file from disk
    fn load_file(path: &PathBuf) -> GunResult<Node> {
        let mut file = fs::File::open(path)?;
        let mut contents = String::new();
        file.read_to_string(&mut contents)?;
        let node: Node = serde_json::from_str(&contents)?;
        Ok(node)
    }

    /// Save a node to disk
    fn save_file(&self, soul: &str, node: &Node) -> GunResult<()> {
        // Encode soul as filename-safe (URL encoding)
        let encoded_soul = urlencoding::encode(soul);
        let file_path = self.data_dir.join(encoded_soul.as_ref());

        let json_str = serde_json::to_string_pretty(node).map_err(GunError::Serialization)?;

        // Write atomically: write to temp file, then rename
        let temp_path = file_path.with_extension("tmp");
        let mut file = fs::File::create(&temp_path)?;
        file.write_all(json_str.as_bytes())?;
        file.sync_all()?;
        drop(file);

        // Atomic rename
        fs::rename(&temp_path, &file_path)?;

        Ok(())
    }

    /// Flush dirty entries to disk
    pub async fn flush(&self) -> GunResult<()> {
        let dirty_keys: Vec<String> = {
            let dirty = self.dirty.read();
            dirty.iter().cloned().collect()
        };

        let cache = self.cache.read();
        for soul in dirty_keys {
            if let Some(node) = cache.get(&soul) {
                if let Err(e) = self.save_file(&soul, node) {
                    eprintln!("Error saving {} to disk: {}", soul, e);
                }
            }
        }

        // Clear dirty set
        let mut dirty = self.dirty.write();
        dirty.clear();

        Ok(())
    }
}

#[async_trait]
impl Storage for LocalStorage {
    async fn get(&self, soul: &str) -> GunResult<Option<Node>> {
        // Check cache first
        let cache = self.cache.read();
        Ok(cache.get(soul).cloned())
    }

    async fn put(&self, soul: &str, node: &Node) -> GunResult<()> {
        // Update cache
        {
            let mut cache = self.cache.write();
            cache.insert(soul.to_string(), node.clone());
        }

        // Mark as dirty for disk write
        {
            let mut dirty = self.dirty.write();
            dirty.insert(soul.to_string());
        }

        // Write to disk immediately (localStorage behavior)
        // Could be optimized to batch writes, but for now we match localStorage's synchronous behavior
        self.save_file(soul, node)?;

        // Remove from dirty set since we just wrote it
        let mut dirty = self.dirty.write();
        dirty.remove(soul);

        Ok(())
    }

    async fn has(&self, soul: &str) -> GunResult<bool> {
        let cache = self.cache.read();
        Ok(cache.contains_key(soul))
    }
}

// Implement Drop to flush on cleanup
impl Drop for LocalStorage {
    fn drop(&mut self) {
        // Flush any remaining dirty entries
        let dirty_keys: Vec<String> = {
            let dirty = self.dirty.read();
            dirty.iter().cloned().collect()
        };

        if !dirty_keys.is_empty() {
            let cache = self.cache.read();
            for soul in dirty_keys {
                if let Some(node) = cache.get(&soul) {
                    let _ = self.save_file(&soul, node);
                }
            }
        }
    }
}