guardian-db 0.15.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
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
use crate::address::Address;
/// Testes para KeyValueStore
///
/// Valida todas as operações principais do KV store usando IrohClient
use crate::address::GuardianDBAddress;
use crate::log::identity::{Identity, Signatures};
use crate::message_marshaler::PostcardMarshaler;
use crate::p2p::EventBus;
use crate::p2p::messaging::one_on_one_channel::new_channel_factory;
use crate::p2p::network::client::IrohClient;
use crate::p2p::network::config::ClientConfig;
use crate::stores::kv_store::GuardianDBKeyValue;
use crate::traits::NewStoreOptions;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use tempfile::TempDir;

// Contador atômico global para garantir endereços únicos em testes paralelos
static TEST_COUNTER: AtomicU64 = AtomicU64::new(0);

// ============= TEST HELPERS =============

/// Helper para criar uma identidade de teste
fn test_identity() -> Arc<Identity> {
    Arc::new(Identity::new(
        "test-user",
        "test-public-key",
        Signatures::new("test-id-sig", "test-pub-sig"),
    ))
}

/// Helper para criar um endereço de teste único para cada chamada
async fn test_address() -> Arc<dyn Address + Send + Sync> {
    use blake3;
    use std::time::{SystemTime, UNIX_EPOCH};

    // Cria um Hash único baseado no timestamp + contador atômico
    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_nanos();
    let counter = TEST_COUNTER.fetch_add(1, Ordering::SeqCst);
    let unique_data = format!("test-kvstore-{}-{}", timestamp, counter);
    let hash_bytes: [u8; 32] = blake3::hash(unique_data.as_bytes()).into();
    let hash = iroh_blobs::Hash::from(hash_bytes);

    Arc::new(GuardianDBAddress::new(
        hash,
        format!("test-kvstore-{}-{}", timestamp, counter),
    ))
}

/// Helper para criar um KeyValueStore de teste completo
async fn create_test_store() -> Result<(GuardianDBKeyValue, TempDir), Box<dyn std::error::Error>> {
    let temp_dir = TempDir::new()?;
    let client_config = ClientConfig {
        data_store_path: Some(temp_dir.path().to_path_buf()),
        ..ClientConfig::development()
    };

    let client = Arc::new(IrohClient::new(client_config).await?);
    let identity = test_identity();
    let address = test_address().await;

    // Cria componentes necessários para o store
    let event_bus = EventBus::new();
    let backend = client.backend().clone();
    let pubsub = Arc::new(backend.create_pubsub_interface().await?);
    let message_marshaler = Arc::new(PostcardMarshaler::new());

    // Cria DirectChannel usando o factory
    let channel_factory = new_channel_factory(client.clone()).await?;
    let payload_emitter = crate::p2p::PayloadEmitter::new(&event_bus).await?;
    let direct_channel = channel_factory(Arc::new(payload_emitter), None)
        .await
        .map_err(|e| format!("Failed to create DirectChannel: {}", e))?;

    let options = NewStoreOptions {
        event_bus: Some(event_bus),
        pubsub: Some(pubsub),
        message_marshaler: Some(message_marshaler),
        direct_channel: Some(direct_channel),
        directory: temp_dir.path().join("cache").to_string_lossy().to_string(),
        ..Default::default()
    };

    let store = GuardianDBKeyValue::new(client, identity, address, Some(options)).await?;

    Ok((store, temp_dir))
}

// ============= TESTES =============

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_kv_store_creation() {
        let result = create_test_store().await;
        assert!(result.is_ok(), "Should create KeyValueStore successfully");

        let (store, _temp_dir) = result.unwrap();
        assert_eq!(store.get_type(), "keyvalue");
        assert!(store.is_empty());
        assert_eq!(store.len(), 0);
    }

    #[tokio::test]
    async fn test_put_and_get() {
        let (mut store, _temp_dir) = create_test_store()
            .await
            .expect("Failed to create test store");

        // Put a value
        let key = "test_key";
        let value = b"test_value".to_vec();
        let result = store.put(key.to_string(), value.clone()).await;
        assert!(
            result.is_ok(),
            "Should put value successfully: {:?}",
            result
        );

        // Get the value
        let retrieved = store.get(key).expect("Failed to get value");
        assert!(retrieved.is_some(), "Should find the key");
        assert_eq!(retrieved.unwrap(), value);
    }

    #[tokio::test]
    async fn test_put_updates_existing_key() {
        let (mut store, _temp_dir) = create_test_store()
            .await
            .expect("Failed to create test store");

        let key = "update_key";

        // Put initial value
        store
            .put(key.to_string(), b"initial".to_vec())
            .await
            .expect("Failed to put initial value");

        // Update with new value
        store
            .put(key.to_string(), b"updated".to_vec())
            .await
            .expect("Failed to update value");

        // Verify updated value
        let retrieved = store.get(key).expect("Failed to get value");
        assert_eq!(retrieved.unwrap(), b"updated");
    }

    #[tokio::test]
    async fn test_delete() {
        let (mut store, _temp_dir) = create_test_store()
            .await
            .expect("Failed to create test store");

        let key = "delete_key";
        let value = b"delete_value".to_vec();

        // Put a value
        store
            .put(key.to_string(), value)
            .await
            .expect("Failed to put value");

        // Verify it exists
        assert!(store.contains_key(key));

        // Delete it
        let result = store.delete(key.to_string()).await;
        assert!(result.is_ok(), "Should delete successfully: {:?}", result);

        // Verify it's gone
        assert!(!store.contains_key(key));
        let retrieved = store.get(key).expect("Failed to get value");
        assert!(retrieved.is_none(), "Key should not exist after deletion");
    }

    #[tokio::test]
    async fn test_delete_nonexistent_key() {
        let (mut store, _temp_dir) = create_test_store()
            .await
            .expect("Failed to create test store");

        let result = store.delete("nonexistent".to_string()).await;
        assert!(
            result.is_err(),
            "Should error when deleting nonexistent key"
        );
    }

    #[tokio::test]
    async fn test_empty_key_validation() {
        let (mut store, _temp_dir) = create_test_store()
            .await
            .expect("Failed to create test store");

        // Test PUT with empty key
        let result = store.put("".to_string(), b"value".to_vec()).await;
        assert!(result.is_err(), "Should error on empty key for PUT");

        // Test GET with empty key
        let result = store.get("");
        assert!(result.is_err(), "Should error on empty key for GET");

        // Test DELETE with empty key
        let result = store.delete("".to_string()).await;
        assert!(result.is_err(), "Should error on empty key for DELETE");
    }

    #[tokio::test]
    async fn test_empty_value_validation() {
        let (mut store, _temp_dir) = create_test_store()
            .await
            .expect("Failed to create test store");

        let result = store.put("key".to_string(), Vec::new()).await;
        assert!(result.is_err(), "Should error on empty value");
    }

    #[tokio::test]
    async fn test_contains_key() {
        let (mut store, _temp_dir) = create_test_store()
            .await
            .expect("Failed to create test store");

        let key = "contains_key";

        // Should not exist initially
        assert!(!store.contains_key(key));

        // Put a value
        store
            .put(key.to_string(), b"value".to_vec())
            .await
            .expect("Failed to put value");

        // Should exist now
        assert!(store.contains_key(key));
    }

    #[tokio::test]
    async fn test_keys() {
        let (mut store, _temp_dir) = create_test_store()
            .await
            .expect("Failed to create test store");

        // Initially empty
        assert!(store.keys().is_empty());

        // Add some keys
        store
            .put("key1".to_string(), b"value1".to_vec())
            .await
            .expect("Failed to put key1");
        store
            .put("key2".to_string(), b"value2".to_vec())
            .await
            .expect("Failed to put key2");
        store
            .put("key3".to_string(), b"value3".to_vec())
            .await
            .expect("Failed to put key3");

        // Verify keys
        let keys = store.keys();
        assert_eq!(keys.len(), 3);
        assert!(keys.contains(&"key1".to_string()));
        assert!(keys.contains(&"key2".to_string()));
        assert!(keys.contains(&"key3".to_string()));
    }

    #[tokio::test]
    async fn test_all() {
        let (mut store, _temp_dir) = create_test_store()
            .await
            .expect("Failed to create test store");

        // Add multiple key-value pairs
        store
            .put("key1".to_string(), b"value1".to_vec())
            .await
            .expect("Failed to put key1");
        store
            .put("key2".to_string(), b"value2".to_vec())
            .await
            .expect("Failed to put key2");
        store
            .put("key3".to_string(), b"value3".to_vec())
            .await
            .expect("Failed to put key3");

        // Get all pairs
        let all = store.all();
        assert_eq!(all.len(), 3);
        assert_eq!(all.get("key1").unwrap(), b"value1");
        assert_eq!(all.get("key2").unwrap(), b"value2");
        assert_eq!(all.get("key3").unwrap(), b"value3");
    }

    #[tokio::test]
    async fn test_len_and_is_empty() {
        let (mut store, _temp_dir) = create_test_store()
            .await
            .expect("Failed to create test store");

        // Initially empty
        assert!(store.is_empty());
        assert_eq!(store.len(), 0);

        // Add one item
        store
            .put("key1".to_string(), b"value1".to_vec())
            .await
            .expect("Failed to put key1");
        assert!(!store.is_empty());
        assert_eq!(store.len(), 1);

        // Add more items
        store
            .put("key2".to_string(), b"value2".to_vec())
            .await
            .expect("Failed to put key2");
        store
            .put("key3".to_string(), b"value3".to_vec())
            .await
            .expect("Failed to put key3");
        assert_eq!(store.len(), 3);

        // Delete one
        store
            .delete("key2".to_string())
            .await
            .expect("Failed to delete key2");
        assert_eq!(store.len(), 2);
    }

    #[tokio::test]
    async fn test_multiple_operations_sequence() {
        let (mut store, _temp_dir) = create_test_store()
            .await
            .expect("Failed to create test store");

        // PUT
        store
            .put("seq_key".to_string(), b"value1".to_vec())
            .await
            .expect("Failed to put");
        assert_eq!(store.get("seq_key").unwrap().unwrap(), b"value1");

        // UPDATE
        store
            .put("seq_key".to_string(), b"value2".to_vec())
            .await
            .expect("Failed to update");
        assert_eq!(store.get("seq_key").unwrap().unwrap(), b"value2");

        // DELETE
        store
            .delete("seq_key".to_string())
            .await
            .expect("Failed to delete");
        assert!(store.get("seq_key").unwrap().is_none());

        // PUT AGAIN
        store
            .put("seq_key".to_string(), b"value3".to_vec())
            .await
            .expect("Failed to put again");
        assert_eq!(store.get("seq_key").unwrap().unwrap(), b"value3");
    }

    #[tokio::test]
    async fn test_binary_values() {
        let (mut store, _temp_dir) = create_test_store()
            .await
            .expect("Failed to create test store");

        // Test with binary data including null bytes
        let binary_data = vec![0x00, 0xFF, 0x42, 0x00, 0xAB, 0xCD, 0xEF];

        store
            .put("binary_key".to_string(), binary_data.clone())
            .await
            .expect("Failed to put binary data");

        let retrieved = store.get("binary_key").expect("Failed to get binary data");
        assert_eq!(retrieved.unwrap(), binary_data);
    }

    #[tokio::test]
    async fn test_large_value() {
        let (mut store, _temp_dir) = create_test_store()
            .await
            .expect("Failed to create test store");

        // Test with a large value (1MB)
        let large_value = vec![0x42u8; 1024 * 1024];

        store
            .put("large_key".to_string(), large_value.clone())
            .await
            .expect("Failed to put large value");

        let retrieved = store.get("large_key").expect("Failed to get large value");
        assert_eq!(retrieved.unwrap(), large_value);
    }

    #[tokio::test]
    async fn test_special_characters_in_keys() {
        let (mut store, _temp_dir) = create_test_store()
            .await
            .expect("Failed to create test store");

        let special_keys = vec![
            "key-with-dash",
            "key_with_underscore",
            "key.with.dots",
            "key/with/slashes",
            "key:with:colons",
            "key with spaces",
            "key@with#special$chars",
        ];

        for key in &special_keys {
            let value = format!("value for {}", key).into_bytes();
            store
                .put((*key).to_string(), value.clone())
                .await
                .unwrap_or_else(|_| panic!("Failed to put key: {}", key));

            let retrieved = store
                .get(key)
                .unwrap_or_else(|_| panic!("Failed to get key: {}", key));
            assert_eq!(retrieved.unwrap(), value);
        }
    }

    #[tokio::test]
    async fn test_integration_workflow() {
        let (mut store, _temp_dir) = create_test_store()
            .await
            .expect("Failed to create test store");

        // Scenario: User session management

        // 1. Create multiple sessions
        store
            .put("session:user1".to_string(), b"token123".to_vec())
            .await
            .expect("Failed to create session1");
        store
            .put("session:user2".to_string(), b"token456".to_vec())
            .await
            .expect("Failed to create session2");
        store
            .put("session:user3".to_string(), b"token789".to_vec())
            .await
            .expect("Failed to create session3");

        // 2. Verify all sessions exist
        assert_eq!(store.len(), 3);
        let all_sessions = store.all();
        assert_eq!(all_sessions.len(), 3);

        // 3. Update one session
        store
            .put("session:user2".to_string(), b"new_token456".to_vec())
            .await
            .expect("Failed to update session");
        assert_eq!(
            store.get("session:user2").unwrap().unwrap(),
            b"new_token456"
        );

        // 4. Delete expired session
        store
            .delete("session:user1".to_string())
            .await
            .expect("Failed to delete session");
        assert_eq!(store.len(), 2);

        // 5. Verify remaining sessions
        let remaining_keys = store.keys();
        assert_eq!(remaining_keys.len(), 2);
        assert!(remaining_keys.contains(&"session:user2".to_string()));
        assert!(remaining_keys.contains(&"session:user3".to_string()));
        assert!(!remaining_keys.contains(&"session:user1".to_string()));
    }

    #[tokio::test]
    async fn test_concurrent_operations() {
        let (mut store, _temp_dir) = create_test_store()
            .await
            .expect("Failed to create test store");

        // Add multiple items rapidly
        for i in 0..10 {
            let key = format!("concurrent_key_{}", i);
            let value = format!("value_{}", i).into_bytes();
            store
                .put(key, value)
                .await
                .unwrap_or_else(|_| panic!("Failed to put key: {}", i));
        }

        // Verify all items were added
        assert_eq!(store.len(), 10);

        // Verify all values are correct
        for i in 0..10 {
            let key = format!("concurrent_key_{}", i);
            let expected_value = format!("value_{}", i).into_bytes();
            let retrieved = store
                .get(&key)
                .unwrap_or_else(|_| panic!("Failed to get key: {}", key));
            assert_eq!(retrieved.unwrap(), expected_value);
        }
    }

    #[tokio::test]
    async fn test_utf8_values() {
        let (mut store, _temp_dir) = create_test_store()
            .await
            .expect("Failed to create test store");

        // Test with UTF-8 strings
        let utf8_values = [
            ("english", "Hello World"),
            ("portuguese", "Olá Mundo"),
            ("chinese", "你好世界"),
            ("arabic", "مرحبا بالعالم"),
            ("emoji", "🚀🎉✨"),
        ];

        for (key, value) in utf8_values {
            store
                .put(key.to_string(), value.as_bytes().to_vec())
                .await
                .unwrap_or_else(|_| panic!("Failed to put {}", key));

            let retrieved = store
                .get(key)
                .unwrap_or_else(|_| panic!("Failed to get {}", key));
            let retrieved_str = String::from_utf8(retrieved.unwrap()).expect("Invalid UTF-8");
            assert_eq!(retrieved_str, value);
        }
    }
}