uni-store 1.1.0

Storage layer for Uni graph database - Lance datasets, LSM deltas, and WAL
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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
// SPDX-License-Identifier: Apache-2.0
// Copyright 2024-2026 Dragonscale Team

//! Cloud Storage Integration Tests
//!
//! Tests for the cloud storage module supporting S3, GCS, and Azure.
//! Uses InMemory store for fast local testing and LocalStack for S3 integration.
//!
//! To run LocalStack tests:
//! ```bash
//! docker run -d --name localstack -p 4566:4566 localstack/localstack
//! AWS_ACCESS_KEY_ID=test AWS_SECRET_ACCESS_KEY=test \
//!     cargo test --test cloud_integration_test -- --ignored
//! ```

use anyhow::Result;
use bytes::Bytes;
use std::sync::Arc;
use tempfile::tempdir;

use uni_common::CloudStorageConfig;
use uni_store::cloud::{build_cloud_store, build_store_from_url, copy_store_prefix, is_cloud_url};

#[test]
fn test_is_cloud_url_detection() {
    // Cloud URLs
    assert!(is_cloud_url("s3://bucket/path"));
    assert!(is_cloud_url("s3://my-bucket/prefix/data"));
    assert!(is_cloud_url("gs://bucket/path"));
    assert!(is_cloud_url("az://account/container"));
    assert!(is_cloud_url("azure://account/container/path"));

    // Local paths
    assert!(!is_cloud_url("/local/path"));
    assert!(!is_cloud_url("./relative/path"));
    assert!(!is_cloud_url("file:///local/path"));
    assert!(!is_cloud_url("C:\\Windows\\Path"));
}

#[test]
fn test_cloud_storage_config_s3() {
    let config = CloudStorageConfig::S3 {
        bucket: "test-bucket".to_string(),
        region: Some("us-east-1".to_string()),
        endpoint: Some("http://localhost:4566".to_string()),
        access_key_id: Some("test".to_string()),
        secret_access_key: Some("test".to_string()),
        session_token: None,
        virtual_hosted_style: false,
    };

    assert_eq!(config.bucket_name(), "test-bucket");
    assert_eq!(config.to_url(), "s3://test-bucket");
}

#[test]
fn test_cloud_storage_config_gcs() {
    let config = CloudStorageConfig::Gcs {
        bucket: "my-gcs-bucket".to_string(),
        service_account_path: Some("/path/to/key.json".to_string()),
        service_account_key: None,
    };

    assert_eq!(config.bucket_name(), "my-gcs-bucket");
    assert_eq!(config.to_url(), "gs://my-gcs-bucket");
}

#[test]
fn test_cloud_storage_config_azure() {
    let config = CloudStorageConfig::Azure {
        container: "mycontainer".to_string(),
        account: "myaccount".to_string(),
        access_key: Some("access-key".to_string()),
        sas_token: None,
    };

    assert_eq!(config.bucket_name(), "mycontainer");
    assert_eq!(config.to_url(), "az://myaccount/mycontainer");
}

#[tokio::test]
async fn test_build_store_from_local_path() -> Result<()> {
    let temp_dir = tempdir()?;
    let path = temp_dir.path().to_str().unwrap();

    let (store, prefix) = build_store_from_url(path)?;
    assert!(prefix.as_ref().is_empty());

    // Test basic put/get operations
    let test_path = object_store::path::Path::from("test.txt");
    store
        .put(&test_path, Bytes::from("hello world").into())
        .await?;

    let result = store.get(&test_path).await?.bytes().await?;
    assert_eq!(result.as_ref(), b"hello world");

    Ok(())
}

#[tokio::test]
async fn test_build_store_from_file_url() -> Result<()> {
    let temp_dir = tempdir()?;
    let path = temp_dir.path().to_str().unwrap();
    let file_url = format!("file://{}", path);

    let (store, prefix) = build_store_from_url(&file_url)?;
    assert!(prefix.as_ref().is_empty());

    // Verify the store works
    let test_path = object_store::path::Path::from("test.txt");
    store
        .put(&test_path, Bytes::from("file url test").into())
        .await?;

    let result = store.get(&test_path).await?.bytes().await?;
    assert_eq!(result.as_ref(), b"file url test");

    Ok(())
}

#[tokio::test]
async fn test_copy_store_prefix() -> Result<()> {
    use object_store::ObjectStore;
    use object_store::local::LocalFileSystem;
    use object_store::path::Path;

    let src_dir = tempdir()?;
    let dst_dir = tempdir()?;

    // Create source store and add some files
    let src_store: Arc<dyn ObjectStore> =
        Arc::new(LocalFileSystem::new_with_prefix(src_dir.path())?);

    src_store
        .put(
            &Path::from("data/file1.txt"),
            Bytes::from("content1").into(),
        )
        .await?;
    src_store
        .put(
            &Path::from("data/file2.txt"),
            Bytes::from("content2").into(),
        )
        .await?;
    src_store
        .put(
            &Path::from("data/subdir/file3.txt"),
            Bytes::from("content3").into(),
        )
        .await?;

    // Create destination store
    let dst_store: Arc<dyn ObjectStore> =
        Arc::new(LocalFileSystem::new_with_prefix(dst_dir.path())?);

    // Copy data/ prefix
    let copied = copy_store_prefix(
        &src_store,
        &dst_store,
        &Path::from("data"),
        &Path::from("backup/data"),
    )
    .await?;

    assert_eq!(copied, 3);

    // Verify files were copied
    let result = dst_store
        .get(&Path::from("backup/data/file1.txt"))
        .await?
        .bytes()
        .await?;
    assert_eq!(result.as_ref(), b"content1");

    let result = dst_store
        .get(&Path::from("backup/data/subdir/file3.txt"))
        .await?
        .bytes()
        .await?;
    assert_eq!(result.as_ref(), b"content3");

    Ok(())
}

// =============================================================================
// InMemory Object Store Tests (No External Dependencies)
// =============================================================================
// These tests use the InMemory object store to verify cloud functionality
// without requiring LocalStack, MinIO, or any external services.

#[tokio::test]
async fn test_inmemory_store_basic_operations() -> Result<()> {
    use object_store::ObjectStore;
    use object_store::memory::InMemory;
    use object_store::path::Path;

    let store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());

    // Test put
    let path = Path::from("test/hello.txt");
    store
        .put(&path, Bytes::from("Hello InMemory!").into())
        .await?;

    // Test get
    let result = store.get(&path).await?.bytes().await?;
    assert_eq!(result.as_ref(), b"Hello InMemory!");

    // Test list
    let list: Vec<_> = store
        .list(Some(&Path::from("test/")))
        .filter_map(|r| async { r.ok() })
        .collect()
        .await;
    assert_eq!(list.len(), 1);
    assert_eq!(list[0].location, path);

    // Test delete
    store.delete(&path).await?;
    assert!(store.get(&path).await.is_err());

    Ok(())
}

use futures::StreamExt;

#[tokio::test]
async fn test_copy_store_prefix_inmemory() -> Result<()> {
    use object_store::ObjectStore;
    use object_store::memory::InMemory;
    use object_store::path::Path;

    // Create source and destination InMemory stores
    let src_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
    let dst_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());

    // Populate source with test data
    src_store
        .put(
            &Path::from("data/file1.txt"),
            Bytes::from("content1").into(),
        )
        .await?;
    src_store
        .put(
            &Path::from("data/file2.txt"),
            Bytes::from("content2").into(),
        )
        .await?;
    src_store
        .put(
            &Path::from("data/nested/file3.txt"),
            Bytes::from("content3").into(),
        )
        .await?;
    src_store
        .put(
            &Path::from("other/ignored.txt"),
            Bytes::from("should not be copied").into(),
        )
        .await?;

    // Copy only the "data" prefix
    let copied = copy_store_prefix(
        &src_store,
        &dst_store,
        &Path::from("data"),
        &Path::from("backup"),
    )
    .await?;

    assert_eq!(copied, 3, "Should copy exactly 3 files from data/ prefix");

    // Verify files were copied with correct content
    let result = dst_store
        .get(&Path::from("backup/file1.txt"))
        .await?
        .bytes()
        .await?;
    assert_eq!(result.as_ref(), b"content1");

    let result = dst_store
        .get(&Path::from("backup/file2.txt"))
        .await?
        .bytes()
        .await?;
    assert_eq!(result.as_ref(), b"content2");

    let result = dst_store
        .get(&Path::from("backup/nested/file3.txt"))
        .await?
        .bytes()
        .await?;
    assert_eq!(result.as_ref(), b"content3");

    // Verify "other" prefix was NOT copied
    assert!(
        dst_store
            .get(&Path::from("backup/ignored.txt"))
            .await
            .is_err(),
        "Files outside the source prefix should not be copied"
    );

    Ok(())
}

#[tokio::test]
async fn test_copy_store_prefix_empty_source() -> Result<()> {
    use object_store::ObjectStore;
    use object_store::memory::InMemory;
    use object_store::path::Path;

    let src_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
    let dst_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());

    // Copy from empty prefix
    let copied = copy_store_prefix(
        &src_store,
        &dst_store,
        &Path::from("nonexistent"),
        &Path::from("backup"),
    )
    .await?;

    assert_eq!(copied, 0, "Copying empty prefix should return 0");

    Ok(())
}

#[tokio::test]
async fn test_copy_store_prefix_to_root() -> Result<()> {
    use object_store::ObjectStore;
    use object_store::memory::InMemory;
    use object_store::path::Path;

    let src_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
    let dst_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());

    src_store
        .put(&Path::from("data/test.txt"), Bytes::from("test").into())
        .await?;

    // Copy to root (empty prefix)
    let copied =
        copy_store_prefix(&src_store, &dst_store, &Path::from("data"), &Path::from("")).await?;

    assert_eq!(copied, 1);

    // File should be at root
    let result = dst_store
        .get(&Path::from("test.txt"))
        .await?
        .bytes()
        .await?;
    assert_eq!(result.as_ref(), b"test");

    Ok(())
}

#[tokio::test]
async fn test_copy_store_prefix_large_files() -> Result<()> {
    use object_store::ObjectStore;
    use object_store::memory::InMemory;
    use object_store::path::Path;

    let src_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
    let dst_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());

    // Create a larger file (1MB)
    let large_content = vec![0u8; 1024 * 1024];
    src_store
        .put(
            &Path::from("data/large.bin"),
            Bytes::from(large_content.clone()).into(),
        )
        .await?;

    let copied = copy_store_prefix(
        &src_store,
        &dst_store,
        &Path::from("data"),
        &Path::from("backup"),
    )
    .await?;

    assert_eq!(copied, 1);

    let result = dst_store
        .get(&Path::from("backup/large.bin"))
        .await?
        .bytes()
        .await?;
    assert_eq!(result.len(), 1024 * 1024);
    assert_eq!(result.as_ref(), large_content.as_slice());

    Ok(())
}

#[tokio::test]
async fn test_inmemory_simulated_backup_flow() -> Result<()> {
    use object_store::ObjectStore;
    use object_store::memory::InMemory;
    use object_store::path::Path;

    // Simulate a database with catalog and storage directories
    let db_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());
    let backup_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());

    // Create database structure
    db_store
        .put(
            &Path::from("catalog/schema.json"),
            Bytes::from(r#"{"version": 1}"#).into(),
        )
        .await?;
    db_store
        .put(
            &Path::from("catalog/snapshots/snap1.json"),
            Bytes::from(r#"{"id": "snap1"}"#).into(),
        )
        .await?;
    db_store
        .put(
            &Path::from("storage/vertices/Person.lance/data.lance"),
            Bytes::from("vertex data").into(),
        )
        .await?;
    db_store
        .put(
            &Path::from("storage/edges/KNOWS.lance/data.lance"),
            Bytes::from("edge data").into(),
        )
        .await?;

    // Backup catalog
    let catalog_copied = copy_store_prefix(
        &db_store,
        &backup_store,
        &Path::from("catalog"),
        &Path::from("backup-2024/catalog"),
    )
    .await?;
    assert_eq!(catalog_copied, 2);

    // Backup storage
    let storage_copied = copy_store_prefix(
        &db_store,
        &backup_store,
        &Path::from("storage"),
        &Path::from("backup-2024/storage"),
    )
    .await?;
    assert_eq!(storage_copied, 2);

    // Verify backup integrity
    let schema = backup_store
        .get(&Path::from("backup-2024/catalog/schema.json"))
        .await?
        .bytes()
        .await?;
    assert_eq!(schema.as_ref(), br#"{"version": 1}"#);

    let vertex_data = backup_store
        .get(&Path::from(
            "backup-2024/storage/vertices/Person.lance/data.lance",
        ))
        .await?
        .bytes()
        .await?;
    assert_eq!(vertex_data.as_ref(), b"vertex data");

    Ok(())
}

#[tokio::test]
async fn test_inmemory_cross_store_copy() -> Result<()> {
    use object_store::ObjectStore;
    use object_store::local::LocalFileSystem;
    use object_store::memory::InMemory;
    use object_store::path::Path;

    // Test copying from local filesystem to InMemory (simulates local->cloud backup)
    let local_dir = tempdir()?;
    let local_store: Arc<dyn ObjectStore> =
        Arc::new(LocalFileSystem::new_with_prefix(local_dir.path())?);
    let cloud_store: Arc<dyn ObjectStore> = Arc::new(InMemory::new());

    // Create local files
    local_store
        .put(
            &Path::from("data/local.txt"),
            Bytes::from("local file").into(),
        )
        .await?;

    // Copy local -> "cloud" (InMemory)
    let copied = copy_store_prefix(
        &local_store,
        &cloud_store,
        &Path::from("data"),
        &Path::from("cloud-backup"),
    )
    .await?;

    assert_eq!(copied, 1);

    let result = cloud_store
        .get(&Path::from("cloud-backup/local.txt"))
        .await?
        .bytes()
        .await?;
    assert_eq!(result.as_ref(), b"local file");

    // Now test copying from InMemory back to local (simulates cloud->local restore)
    let restore_dir = tempdir()?;
    let restore_store: Arc<dyn ObjectStore> =
        Arc::new(LocalFileSystem::new_with_prefix(restore_dir.path())?);

    let restored = copy_store_prefix(
        &cloud_store,
        &restore_store,
        &Path::from("cloud-backup"),
        &Path::from("restored"),
    )
    .await?;

    assert_eq!(restored, 1);

    let result = restore_store
        .get(&Path::from("restored/local.txt"))
        .await?
        .bytes()
        .await?;
    assert_eq!(result.as_ref(), b"local file");

    Ok(())
}

// =============================================================================
// S3/LocalStack Integration Tests - Run with --ignored
// =============================================================================
// Requires: LocalStack running on localhost:4566

#[tokio::test]
#[ignore = "Requires LocalStack running on localhost:4566"]
async fn test_s3_basic_operations() -> Result<()> {
    let config = CloudStorageConfig::S3 {
        bucket: "test-bucket".to_string(),
        region: Some("us-east-1".to_string()),
        endpoint: Some("http://localhost:4566".to_string()),
        access_key_id: Some("test".to_string()),
        secret_access_key: Some("test".to_string()),
        session_token: None,
        virtual_hosted_style: false,
    };

    // Create bucket first (LocalStack specific)
    create_localstack_bucket("test-bucket").await?;

    let store = build_cloud_store(&config)?;

    // Test put
    let path = object_store::path::Path::from("test/hello.txt");
    store
        .put(&path, Bytes::from("Hello from S3!").into())
        .await?;

    // Test get
    let result = store.get(&path).await?.bytes().await?;
    assert_eq!(result.as_ref(), b"Hello from S3!");

    // Test delete
    store.delete(&path).await?;

    // Verify deletion
    assert!(store.get(&path).await.is_err());

    Ok(())
}

#[tokio::test]
#[ignore = "Requires LocalStack running on localhost:4566"]
async fn test_s3_url_parsing() -> Result<()> {
    // Ensure bucket exists
    create_localstack_bucket("url-test-bucket").await?;

    // Set environment variables for URL-based store creation
    // SAFETY: This test runs in isolation; env var modification is safe here.
    unsafe {
        std::env::set_var("AWS_ACCESS_KEY_ID", "test");
        std::env::set_var("AWS_SECRET_ACCESS_KEY", "test");
        std::env::set_var("AWS_REGION", "us-east-1");
        std::env::set_var("AWS_ENDPOINT_URL", "http://localhost:4566");
    }

    let (store, prefix) = build_store_from_url("s3://url-test-bucket/data")?;

    assert_eq!(prefix.as_ref(), "data");

    // Test operations
    let path = object_store::path::Path::from("file.txt");
    store
        .put(&path, Bytes::from("URL test content").into())
        .await?;

    let result = store.get(&path).await?.bytes().await?;
    assert_eq!(result.as_ref(), b"URL test content");

    Ok(())
}

#[tokio::test]
#[ignore = "Requires LocalStack running on localhost:4566"]
async fn test_s3_copy_prefix() -> Result<()> {
    use object_store::path::Path;

    // Ensure buckets exist
    create_localstack_bucket("src-bucket").await?;
    create_localstack_bucket("dst-bucket").await?;

    let src_config = CloudStorageConfig::S3 {
        bucket: "src-bucket".to_string(),
        region: Some("us-east-1".to_string()),
        endpoint: Some("http://localhost:4566".to_string()),
        access_key_id: Some("test".to_string()),
        secret_access_key: Some("test".to_string()),
        session_token: None,
        virtual_hosted_style: false,
    };

    let dst_config = CloudStorageConfig::S3 {
        bucket: "dst-bucket".to_string(),
        region: Some("us-east-1".to_string()),
        endpoint: Some("http://localhost:4566".to_string()),
        access_key_id: Some("test".to_string()),
        secret_access_key: Some("test".to_string()),
        session_token: None,
        virtual_hosted_style: false,
    };

    let src_store = build_cloud_store(&src_config)?;
    let dst_store = build_cloud_store(&dst_config)?;

    // Create test files in source
    src_store
        .put(&Path::from("data/a.txt"), Bytes::from("file a").into())
        .await?;
    src_store
        .put(&Path::from("data/b.txt"), Bytes::from("file b").into())
        .await?;

    // Copy prefix
    let copied = copy_store_prefix(
        &src_store,
        &dst_store,
        &Path::from("data"),
        &Path::from("backup"),
    )
    .await?;

    assert_eq!(copied, 2);

    // Verify
    let result = dst_store
        .get(&Path::from("backup/a.txt"))
        .await?
        .bytes()
        .await?;
    assert_eq!(result.as_ref(), b"file a");

    Ok(())
}

/// Helper to create a bucket in LocalStack
async fn create_localstack_bucket(bucket: &str) -> Result<()> {
    use object_store::ObjectStore;
    use object_store::aws::AmazonS3Builder;

    // LocalStack accepts unsigned PUT /{bucket} for bucket creation in test env.
    let status = std::process::Command::new("curl")
        .args([
            "-sSf",
            "-X",
            "PUT",
            &format!("http://localhost:4566/{bucket}"),
        ])
        .status()?;
    if !status.success() {
        anyhow::bail!("failed to create localstack bucket: {bucket}");
    }

    let store = AmazonS3Builder::new()
        .with_bucket_name(bucket)
        .with_region("us-east-1")
        .with_endpoint("http://localhost:4566")
        .with_access_key_id("test")
        .with_secret_access_key("test")
        .with_allow_http(true)
        .with_virtual_hosted_style_request(false)
        .build()?;

    // Put marker to verify the bucket is usable.
    store
        .put(
            &object_store::path::Path::from(".marker"),
            Bytes::from("").into(),
        )
        .await?;

    Ok(())
}