-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlib.rs
1420 lines (1152 loc) · 46.8 KB
/
lib.rs
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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![recursion_limit = "256"]
pub mod backend;
pub mod common;
pub mod constants;
pub mod group;
pub mod repo;
pub mod rpc;
use crate::constants::{
FAILED_TO_DESERIALIZE_KEYPAIR, FAILED_TO_LOAD_KEYPAIR, GROUP_NOT_FOUND, KEYPAIR_NOT_FOUND,
ROUTE_ID_DHT_KEY, TEST_GROUP_NAME, UNABLE_TO_GET_GROUP_NAME, UNABLE_TO_SET_GROUP_NAME,
UNABLE_TO_STORE_KEYPAIR,
};
use crate::backend::Backend;
use crate::common::{CommonKeypair, DHTEntity};
use iroh_blobs::Hash;
use veilid_core::{
vld0_generate_keypair, CryptoKey, CryptoTyped, TypedKey, VeilidUpdate, CRYPTO_KIND_VLD0,
VALID_CRYPTO_KINDS,
};
use veilid_iroh_blobs::iroh::VeilidIrohBlobs;
use serial_test::serial;
#[cfg(test)]
mod tests {
use super::*;
use anyhow::anyhow;
use anyhow::Result;
use bytes::Bytes;
use common::init_veilid;
use common::make_route;
use rpc::RpcClient;
use rpc::RpcService;
use std::path::Path;
use std::result;
use tmpdir::TmpDir;
use tokio::fs;
use tokio::join;
use tokio::sync::mpsc;
use tokio::time::sleep;
use tokio::time::Duration;
use tokio_stream::wrappers::ReceiverStream;
use tokio_stream::StreamExt;
#[tokio::test]
#[serial]
async fn blob_transfer() -> Result<()> {
let path = TmpDir::new("test_dweb_backend").await.unwrap();
fs::create_dir_all(path.as_ref())
.await
.expect("Failed to create base directory");
// Initialize the backend
let mut backend = Backend::new(path.as_ref()).expect("Unable to create Backend");
backend.start().await.expect("Unable to start");
// Create a group and a repo
let mut group = backend
.create_group()
.await
.expect("Unable to create group");
let repo = group.create_repo().await.expect("Unable to create repo");
let iroh_blobs = backend
.get_iroh_blobs()
.await
.expect("iroh_blobs not initialized");
// Prepare data to upload as a blob
let data_to_upload = b"Test data for blob".to_vec();
let (tx, rx) = mpsc::channel::<std::io::Result<Bytes>>(1);
tx.send(Ok(Bytes::from(data_to_upload.clone())))
.await
.unwrap();
drop(tx); // Close the sender
// upload the data as a blob and get the hash
let hash = iroh_blobs
.upload_from_stream(rx)
.await
.expect("Failed to upload blob");
// some delay to ensure blob is uploaded
tokio::time::sleep(Duration::from_millis(100)).await;
// download the blob
let receiver = iroh_blobs
.read_file(hash.clone())
.await
.expect("Failed to read blob");
// retrieve the data from the receiver
let mut retrieved_data = Vec::new();
let mut stream = ReceiverStream::new(receiver);
while let Some(chunk_result) = stream.next().await {
match chunk_result {
Ok(bytes) => retrieved_data.extend_from_slice(bytes.as_ref()),
Err(e) => panic!("Error reading data: {:?}", e),
}
}
// Verify that the downloaded data matches the uploaded data
assert_eq!(retrieved_data, data_to_upload);
backend.stop().await.expect("Unable to stop");
Ok(())
}
#[tokio::test]
#[serial]
async fn group_creation() -> Result<()> {
let path = TmpDir::new("test_dweb_backend").await.unwrap();
fs::create_dir_all(path.as_ref())
.await
.expect("Failed to create base directory");
let mut backend = Backend::new(path.as_ref()).expect("Unable to create Backend");
backend.start().await.expect("Unable to start");
let group = backend
.create_group()
.await
.expect("Unable to create group");
group
.set_name(TEST_GROUP_NAME)
.await
.expect(UNABLE_TO_SET_GROUP_NAME);
let name = group.get_name().await.expect(UNABLE_TO_GET_GROUP_NAME);
assert_eq!(name, TEST_GROUP_NAME);
backend.stop().await.expect("Unable to stop");
Ok(())
}
#[tokio::test]
#[serial]
async fn keypair_storage_and_retrieval() -> Result<()> {
let path = TmpDir::new("test_dweb_backend").await.unwrap();
fs::create_dir_all(path.as_ref())
.await
.expect("Failed to create base directory");
let mut backend = Backend::new(path.as_ref()).expect("Unable to create Backend");
backend.start().await.expect("Unable to start");
let group = backend
.create_group()
.await
.expect("Unable to create group");
backend.stop().await.expect("Unable to stop");
backend.start().await.expect("Unable to restart");
let mut loaded_group = backend.get_group(&group.id()).await.expect(GROUP_NOT_FOUND);
let veilid = backend.get_veilid_api().await.unwrap();
let protected_store = veilid.protected_store().unwrap();
let keypair_data = protected_store
.load_user_secret(group.id().to_string())
.expect(FAILED_TO_LOAD_KEYPAIR)
.expect(KEYPAIR_NOT_FOUND);
let retrieved_keypair: CommonKeypair =
serde_cbor::from_slice(&keypair_data).expect(FAILED_TO_DESERIALIZE_KEYPAIR);
// Check that the id matches group.id()
assert_eq!(retrieved_keypair.id, group.id());
// Check that the public_key matches the owner public key from the DHT record
assert_eq!(
retrieved_keypair.public_key,
loaded_group.get_dht_record().owner().clone()
);
// Check that the secret and encryption keys match
assert_eq!(retrieved_keypair.secret_key, group.get_secret_key());
assert_eq!(retrieved_keypair.encryption_key, group.get_encryption_key());
backend.stop().await.expect("Unable to stop");
Ok(())
}
#[tokio::test]
#[serial]
async fn repo_creation() -> Result<()> {
let path = TmpDir::new("test_dweb_backend").await.unwrap();
fs::create_dir_all(path.as_ref())
.await
.expect("Failed to create base directory");
let mut backend = Backend::new(path.as_ref()).expect("Unable to create Backend");
backend.start().await.expect("Unable to start");
// Step 1: Create a group before creating a repo
let mut group = backend
.create_group()
.await
.expect("Unable to create group");
// Step 2: Create a repo
let repo = group.create_repo().await.expect("Unable to create repo");
let repo_key = repo.get_id();
assert!(repo_key != CryptoKey::default(), "Repo ID should be set");
// Step 3: Set and verify the repo name
let repo_name = "Test Repo";
repo.set_name(repo_name)
.await
.expect("Unable to set repo name");
let name = repo.get_name().await.expect(UNABLE_TO_GET_GROUP_NAME);
assert_eq!(name, repo_name);
// Step 5: List known repos and verify the repo is in the list
let repos = group.list_repos().await;
assert!(repos.contains(&repo_key));
// Step 6: Retrieve the repo by key and check its name
let loaded_repo = group.get_repo(&repo_key).await.expect("Repo not found");
let retrieved_name = loaded_repo
.get_name()
.await
.expect("Unable to get repo name after restart");
assert_eq!(retrieved_name, repo_name);
backend.stop().await.expect("Unable to stop");
Ok(())
}
#[tokio::test]
#[serial]
async fn sending_message_via_private_route() -> Result<()> {
tokio::time::timeout(Duration::from_secs(888), async {
let path = TmpDir::new("test_dweb_backend").await.unwrap();
fs::create_dir_all(path.as_ref())
.await
.expect("Failed to create base directory");
let mut backend = Backend::new(path.as_ref()).expect("Unable to create Backend");
backend.start().await.expect("Unable to start");
// Add delay to ensure backend initialization
tokio::time::sleep(Duration::from_secs(2)).await;
// Create a group and a repo
let mut group = backend
.create_group()
.await
.expect("Unable to create group");
let repo = group.create_repo().await.expect("Unable to create repo");
let veilid_api = backend
.get_veilid_api()
.await
.expect("Failed to get VeilidAPI instance");
// Get the update receiver from the backend
let update_rx = backend
.subscribe_updates()
.await
.expect("Failed to subscribe to updates");
// Set up a channel to receive AppMessage updates
let (message_tx, mut message_rx) = mpsc::channel(1);
// Spawn a task to listen for updates
tokio::spawn(async move {
let mut rx = update_rx.resubscribe();
while let Ok(update) = rx.recv().await {
if let VeilidUpdate::AppMessage(app_message) = update {
// Optionally, filter by route_id or other criteria
message_tx.send(app_message).await.unwrap();
}
}
});
println!(
"Creating a new custom private route with valid crypto kinds: {:?}",
VALID_CRYPTO_KINDS
);
// Create a new private route
let (route_id, route_id_blob) = make_route(&veilid_api)
.await
.expect("Failed to create route after retries");
// Store the route_id_blob in DHT
repo.store_route_id_in_dht(route_id_blob.clone())
.await
.expect("Failed to store route ID blob in DHT");
// Define the message to send
let message = b"Test Message to Repo Owner".to_vec();
println!("Sending message to owner...");
// Send the message
repo.send_message_to_owner(&veilid_api, message.clone(), ROUTE_ID_DHT_KEY)
.await
.expect("Failed to send message to repo owner");
// Receive the message from the background task
let received_app_message = message_rx.recv().await.expect("Failed to receive message");
// Verify the message
assert_eq!(received_app_message.message(), message.as_slice());
backend.stop().await.expect("Unable to stop");
Ok::<(), anyhow::Error>(())
})
.await??;
Ok(())
}
#[tokio::test]
#[serial]
async fn known_group_persistence() -> Result<()> {
let path = TmpDir::new("test_dweb_backend").await.unwrap();
fs::create_dir_all(path.as_ref())
.await
.expect("Failed to create base directory");
let mut backend = Backend::new(path.as_ref()).expect("Unable to create Backend");
backend.start().await.expect("Unable to start");
let group = backend
.create_group()
.await
.expect("Unable to create group");
group
.set_name(TEST_GROUP_NAME)
.await
.expect(UNABLE_TO_SET_GROUP_NAME);
drop(group);
backend.stop().await.expect("Unable to stop");
backend.start().await.expect("Unable to restart");
let list = backend.list_groups().await?;
assert_eq!(list.len(), 1, "Group auto-loaded on start");
backend.stop().await.expect("Unable to stop");
Ok(())
}
#[tokio::test]
#[serial]
async fn group_name_persistence() -> Result<()> {
let path = TmpDir::new("test_dweb_backend").await.unwrap();
fs::create_dir_all(path.as_ref())
.await
.expect("Failed to create base directory");
let mut backend = Backend::new(path.as_ref()).expect("Unable to create Backend");
backend.start().await.expect("Unable to start");
let group = backend
.create_group()
.await
.expect("Unable to create group");
group
.set_name(TEST_GROUP_NAME)
.await
.expect(UNABLE_TO_SET_GROUP_NAME);
backend.stop().await.expect("Unable to stop");
backend.start().await.expect("Unable to restart");
let loaded_group = backend.get_group(&group.id()).await.expect(GROUP_NOT_FOUND);
let name = loaded_group
.get_name()
.await
.expect(UNABLE_TO_GET_GROUP_NAME);
assert_eq!(name, TEST_GROUP_NAME);
backend.stop().await.expect("Unable to stop");
Ok(())
}
#[tokio::test]
#[serial]
async fn repo_persistence() -> Result<()> {
let path = TmpDir::new("test_dweb_backend").await.unwrap();
fs::create_dir_all(path.as_ref())
.await
.expect("Failed to create base directory");
let mut backend = Backend::new(path.as_ref()).expect("Unable to create Backend");
backend.start().await.expect("Unable to start backend");
let mut group = backend
.create_group()
.await
.expect("Failed to create group");
let group_id = group.id();
// Drop the group and stop the backend
drop(group);
backend.stop().await.expect("Unable to stop backend");
// Restart backend and verify group and repo persistence
backend.start().await.expect("Unable to restart backend");
println!(
"Backend restarted, attempting to load group with ID: {:?}",
group_id
);
let mut reload_group = backend.get_group(&group_id).await.expect(GROUP_NOT_FOUND);
let loaded_group_id = reload_group.id();
// Drop the group and stop the backend
drop(reload_group);
backend.stop().await.expect("Unable to stop backend");
// Restart backend and verify group and repo persistence
backend.start().await.expect("Unable to restart backend");
println!(
"Backend restarted, attempting to load group with ID: {:?}",
loaded_group_id
);
let mut loaded_group = backend
.get_group(&loaded_group_id)
.await
.expect(GROUP_NOT_FOUND);
println!("group reloaded with id: {:?}", loaded_group_id);
let repo = loaded_group
.create_repo()
.await
.expect("Unable to create repo");
let repo_name = "Test Repo";
repo.set_name(repo_name)
.await
.expect("Unable to set repo name");
let initial_name = repo.get_name().await.expect("Unable to get repo name");
assert_eq!(initial_name, repo_name, "Initial repo name doesn't match");
let repo_id = repo.id();
println!("lib: Repo created with id: {:?}", repo_id);
// Check if the repo is listed after restart
let list = loaded_group.list_repos().await;
assert_eq!(list.len(), 1, "One repo got loaded back");
let loaded_repo = loaded_group
.get_own_repo()
.await
.expect("Repo not found after restart");
println!("a list of repos: {:?}", list);
let retrieved_name = loaded_repo
.get_name()
.await
.expect("Unable to get repo name after restart");
assert_eq!(
retrieved_name, repo_name,
"Repo name doesn't persist after restart"
);
// Drop the group again and test reloading
drop(loaded_group);
backend
.stop()
.await
.expect("Unable to stop backend after second drop");
backend
.start()
.await
.expect("Unable to restart backend after second drop");
// Verify the group and repos again
let reloaded_group = backend.get_group(&group_id).await.expect(GROUP_NOT_FOUND);
let reloaded_repos = reloaded_group.list_repos().await;
assert_eq!(
reloaded_repos.len(),
1,
"One repo loaded after second restart"
);
let another_list = reloaded_group.list_repos().await;
println!("Another list of repos: {:?}", another_list);
let reloaded_repo = reloaded_group
.get_own_repo()
.await
.expect("Repo not found after second restart");
let final_name = reloaded_repo
.get_name()
.await
.expect("Unable to get repo name after second restart");
assert_eq!(
final_name, repo_name,
"Repo name doesn't persist after second restart"
);
let known = backend.list_known_group_ids().await?;
assert_eq!(known.len(), 1, "One group got saved");
backend
.stop()
.await
.expect("Unable to stop backend after verification");
Ok(())
}
#[tokio::test]
#[serial]
async fn upload_blob_test() -> Result<()> {
let path = TmpDir::new("test_dweb_backend_upload_blob").await.unwrap();
fs::create_dir_all(path.as_ref())
.await
.expect("Failed to create base directory");
// Initialize the backend
let mut backend = Backend::new(path.as_ref()).expect("Unable to create Backend");
backend.start().await.expect("Unable to start");
// Create a group
let mut group = backend
.create_group()
.await
.expect("Unable to create group");
// Prepare a temporary file to upload as a blob
let tmp_file_path = path.as_ref().join("test_blob_file.txt");
let file_content = b"Test content for file upload";
fs::write(&tmp_file_path, file_content)
.await
.expect("Failed to write to temp file");
let repo = group.create_repo().await?;
// Upload the file as a blob and get the hash
let hash = repo
.upload_blob(tmp_file_path.clone())
.await
.expect("Failed to upload blob");
// Verify that the file was uploaded and the hash was written to the DHT
let dht_value = backend
.get_veilid_api()
.await
.expect("veilid_api not initialized")
.routing_context()
.expect("Failed to get routing context")
.get_dht_value(repo.dht_record.key().clone(), 1, false)
.await
.expect("Failed to retrieve DHT value");
if let Some(dht_value_data) = dht_value {
// Use the data() method to extract the byte slice
let dht_value_bytes = dht_value_data.data();
let dht_value_str = String::from_utf8(dht_value_bytes.to_vec())
.expect("Failed to convert ValueData to String");
assert_eq!(dht_value_str, hash.to_hex());
} else {
panic!("No value found in DHT for the given key");
}
// Read back the file using the hash
let iroh_blobs = backend
.get_iroh_blobs()
.await
.expect("iroh_blobs not initialized");
let receiver = iroh_blobs
.read_file(hash.clone())
.await
.expect("Failed to read blob");
// Retrieve the data from the receiver
let mut retrieved_data = Vec::new();
let mut stream = ReceiverStream::new(receiver);
while let Some(chunk_result) = stream.next().await {
match chunk_result {
Ok(bytes) => retrieved_data.extend_from_slice(bytes.as_ref()),
Err(e) => panic!("Error reading data: {:?}", e),
}
}
// Verify that the downloaded data matches the original file content
assert_eq!(retrieved_data, file_content);
backend.stop().await.expect("Unable to stop");
Ok(())
}
#[tokio::test]
#[serial]
async fn upload_blob_and_verify_protected_store() -> Result<()> {
let path = TmpDir::new("test_dweb_backend_upload_blob").await.unwrap();
fs::create_dir_all(path.as_ref())
.await
.expect("Failed to create base directory");
// Initialize the backend
let mut backend = Backend::new(path.as_ref()).expect("Unable to create Backend");
backend.start().await.expect("Unable to start");
// Create a group
let mut group = backend
.create_group()
.await
.expect("Unable to create group");
// Prepare a temporary file to upload as a blob
let tmp_file_path = path.as_ref().join("test_blob_file.txt");
let file_content = b"Test content for file upload";
fs::write(&tmp_file_path, file_content)
.await
.expect("Failed to write to temp file");
let protected_store = backend
.get_veilid_api()
.await
.unwrap()
.protected_store()
.unwrap();
let repo = group.create_repo().await?;
// Upload the file as a blob and get the hash
let hash = repo
.upload_blob(tmp_file_path.clone())
.await
.expect("Failed to upload blob");
// Verify that the file was uploaded and the hash was written to the DHT
let dht_value = backend
.get_veilid_api()
.await
.expect("veilid_api not initialized")
.routing_context()
.expect("Failed to get routing context")
.get_dht_value(repo.dht_record.key().clone(), 1, false)
.await
.expect("Failed to retrieve DHT value");
if let Some(dht_value_data) = dht_value {
// Use the data() method to extract the byte slice
let dht_value_bytes = dht_value_data.data();
let dht_value_str = String::from_utf8(dht_value_bytes.to_vec())
.expect("Failed to convert ValueData to String");
assert_eq!(dht_value_str, hash.to_hex());
} else {
panic!("No value found in DHT for the given key");
}
// Read back the file using the hash
let iroh_blobs = backend
.get_iroh_blobs()
.await
.expect("iroh_blobs not initialized");
let receiver = iroh_blobs
.read_file(hash.clone())
.await
.expect("Failed to read blob");
// Retrieve the data from the receiver
let mut retrieved_data = Vec::new();
let mut stream = ReceiverStream::new(receiver);
while let Some(chunk_result) = stream.next().await {
match chunk_result {
Ok(bytes) => retrieved_data.extend_from_slice(bytes.as_ref()),
Err(e) => panic!("Error reading data: {:?}", e),
}
}
// Verify that the downloaded data matches the original file content
assert_eq!(retrieved_data, file_content);
backend.stop().await.expect("Unable to stop");
Ok(())
}
#[tokio::test]
#[serial]
async fn test_join() {
let path = TmpDir::new("test_dweb_backend").await.unwrap();
fs::create_dir_all(path.as_ref())
.await
.expect("Failed to create base directory");
let mut backend = Backend::new(path.as_ref()).expect("Unable to create Backend");
backend.start().await.expect("Unable to start");
let group = backend
.create_group()
.await
.expect("Unable to create group");
group
.set_name(TEST_GROUP_NAME)
.await
.expect(UNABLE_TO_SET_GROUP_NAME);
let url = group.get_url();
let keys = backend::parse_url(https://github.com/url.as_str()).expect("URL was parsed back out");
assert_eq!(keys.id, group.id());
backend.stop().await.expect("Unable to stop");
}
#[tokio::test]
#[serial]
async fn list_repos_test() -> Result<()> {
let path = TmpDir::new("test_dweb_backend_list_repos").await.unwrap();
fs::create_dir_all(path.as_ref())
.await
.expect("Failed to create base directory");
let mut backend = Backend::new(path.as_ref()).expect("Unable to create Backend");
backend.start().await.expect("Unable to start");
// Create a group and two repos
let mut group = backend
.create_group()
.await
.expect("Unable to create group");
let repo1 = group.create_repo().await?.clone();
// List repos and verify
let repos = group.list_repos().await;
assert!(repos.contains(&repo1.get_id()));
backend.stop().await.expect("Unable to stop");
Ok(())
}
#[tokio::test]
#[serial]
async fn get_own_repo_test() -> Result<()> {
let path = TmpDir::new("test_dweb_backend_get_own_repo").await.unwrap();
fs::create_dir_all(path.as_ref())
.await
.expect("Failed to create base directory");
let mut backend = Backend::new(path.as_ref()).expect("Unable to create Backend");
backend.start().await.expect("Unable to start");
// Create a group and two repos, one writable
let mut group = backend
.create_group()
.await
.expect("Unable to create group");
let writable_repo = group.create_repo().await?.clone();
// Verify own repo is found
let own_repo = group.get_own_repo().await;
assert!(own_repo.is_some());
assert_eq!(own_repo.unwrap().get_id(), writable_repo.get_id());
backend.stop().await.expect("Unable to stop");
Ok(())
}
#[tokio::test]
#[serial]
async fn download_hash_from_peers_test() -> Result<()> {
let base_dir = TmpDir::new("test_dweb_backend_download_hash")
.await
.unwrap();
let base_dir_path = base_dir.to_path_buf();
let store1 =
iroh_blobs::store::fs::Store::load(base_dir.to_path_buf().join("iroh1")).await?;
let store2 =
iroh_blobs::store::fs::Store::load(base_dir.to_path_buf().join("iroh2")).await?;
let (v1_result, v2_result) = join!(
init_veilid(&base_dir_path, "downloadpeers1".to_string()),
init_veilid(&base_dir_path, "downloadpeers2".to_string())
);
let (veilid_api1, mut update_rx1) = v1_result?;
let (veilid_api2, mut update_rx2) = v2_result?;
fs::create_dir_all(base_dir.as_ref())
.await
.expect("Failed to create base directory");
let backend1 = Backend::from_dependencies(
&base_dir.to_path_buf(),
veilid_api1.clone(),
update_rx1,
store1,
)
.await
.unwrap();
let backend2 = Backend::from_dependencies(
&base_dir.to_path_buf(),
veilid_api2.clone(),
update_rx2,
store2,
)
.await
.unwrap();
// Create a group and a peer repo
let mut group = backend1
.create_group()
.await
.expect("Unable to create group");
group.set_name("Example").await?;
let mut peer_repo = group.create_repo().await?;
sleep(Duration::from_secs(2)).await;
let group2 = backend2.join_from_url(https://github.com/&group.get_url()).await?;
// Upload a test blob to the peer repo
let data_to_upload = Bytes::from("Test data for peer download");
let collection_name = "peer_repo_collection".to_string();
peer_repo
.iroh_blobs
.create_collection(&collection_name)
.await
.expect("Unable to create collection");
// Create a file stream using mpsc
let (tx, rx) = mpsc::channel(1);
tx.send(Ok(data_to_upload.clone())).await.unwrap();
drop(tx); // Close the sender
// Upload using the new method `upload_to`
let file_path = "test_file.txt".to_string();
let file_hash = peer_repo
.iroh_blobs
.upload_to(&collection_name, &file_path, rx)
.await
.expect("Failed to upload to collection");
// Add the uploaded file to the collection
let new_file_collection_hash = peer_repo
.iroh_blobs
.set_file(&collection_name, &file_path, &file_hash)
.await
.expect("Unable to add file to collection");
assert!(
!new_file_collection_hash.as_bytes().is_empty(),
"New collection hash after uploading a file should not be empty"
);
sleep(Duration::from_secs(2)).await;
// Download hash from peers
let mut retries = 10;
while retries > 0 {
if group2.download_hash_from_peers(&file_hash).await.is_ok() {
println!("Download success!");
break;
}
retries -= 1;
sleep(Duration::from_secs(4)).await;
}
assert!(
retries > 0,
"Failed to download hash from peers after retries"
);
backend1.stop().await?;
backend2.stop().await?;
Ok(())
}
#[tokio::test]
#[serial]
async fn peers_have_hash_test() -> Result<()> {
let base_dir: TmpDir = TmpDir::new("test_dweb_backend_peers_have_hash")
.await
.unwrap();
let base_dir_path = base_dir.to_path_buf();
let store1 =
iroh_blobs::store::fs::Store::load(base_dir.to_path_buf().join("iroh1")).await?;
let store2 =
iroh_blobs::store::fs::Store::load(base_dir.to_path_buf().join("iroh2")).await?;
let (v1_result, v2_result) = join!(
init_veilid(&base_dir_path, "downloadpeers1".to_string()),
init_veilid(&base_dir_path, "downloadpeers2".to_string())
);
let (veilid_api1, mut update_rx1) = v1_result?;
let (veilid_api2, mut update_rx2) = v2_result?;
fs::create_dir_all(base_dir.as_ref())
.await
.expect("Failed to create base directory");
let backend1 = Backend::from_dependencies(
&base_dir.to_path_buf(),
veilid_api1.clone(),
update_rx1,
store1,
)
.await
.unwrap();
let backend2 = Backend::from_dependencies(
&base_dir.to_path_buf(),
veilid_api2.clone(),
update_rx2,
store2,
)
.await
.unwrap();
// Create a group and a peer repo
let mut group1 = backend1
.create_group()
.await
.expect("Unable to create group");
let mut peer_repo = group1.create_repo().await?;
// Upload a test blob to the peer repo
let data_to_upload = Bytes::from("Test data for peer check");
let collection_name = "peer_repo_collection_check".to_string();
peer_repo
.iroh_blobs
.create_collection(&collection_name)
.await
.expect("Unable to create collection");
// Create a file stream using mpsc
let (tx, rx) = mpsc::channel(1);
tx.send(Ok(data_to_upload.clone())).await.unwrap();
drop(tx); // Close the sender
let iroh_blobs = backend1
.get_iroh_blobs()
.await
.expect("iroh_blobs not initialized");
// Upload using the new method `upload_to`
let file_path = "test_file_check.txt".to_string();
let file_hash = iroh_blobs
.upload_to(&collection_name, &file_path, rx)
.await
.expect("Failed to upload to collection");
// Add the uploaded file to the collection
let new_file_collection_hash = iroh_blobs
.set_file(&collection_name, &file_path, &file_hash)
.await
.expect("Unable to add file to collection");
assert!(
!new_file_collection_hash.as_bytes().is_empty(),
"New collection hash after uploading a file should not be empty"
);
sleep(Duration::from_secs(4)).await;
let joined_group = backend2
.join_from_url(https://github.com/&group1.get_url())
.await
.expect("Unable to join group on second peer");
assert!(
!new_file_collection_hash.as_bytes().is_empty(),
"New collection hash after uploading a file should not be empty"
);
// Retry checking if peers have the hash
let mut retries = 4;