noosphere 0.16.1

A high-level package for dealing with accessing the Noosphere
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
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
#![cfg(all(feature = "test-kubo", not(target_arch = "wasm32")))]

//! Integration tests that expect "full stack" Noosphere to be available, including
//! name system and block syndication backend (e.g., IPFS Kubo). The tests in this
//! module represent basic distributed system scenarios.

// TODO(#629): Remove this when we migrate off of `release-please`
extern crate noosphere_cli_dev as noosphere_cli;
extern crate noosphere_ns_dev as noosphere_ns;

#[macro_use]
extern crate tracing;

use anyhow::{anyhow, Result};
use instant::Duration;
use noosphere::sphere::SphereContextBuilder;
use noosphere_cli::helpers::{start_name_system_server, SpherePair};
use noosphere_common::helpers::wait;
use noosphere_core::{
    context::{
        HasMutableSphereContext, HasSphereContext, SphereContentRead, SphereContentWrite,
        SphereCursor, SpherePetnameRead, SpherePetnameWrite, SphereReplicaRead, SphereReplicaWrite,
        SphereSync, SphereWalker,
    },
    data::{ContentType, Did, Link, MemoIpld},
    stream::memo_history_stream,
    tracing::initialize_tracing,
};
use noosphere_ns::{server::HttpClient, NameResolver};
use std::collections::BTreeSet;
use std::sync::Arc;
use tokio::io::AsyncReadExt;
use tokio_stream::StreamExt;
use url::Url;

#[tokio::test]
async fn gateway_publishes_and_resolves_petnames_configured_by_the_client() -> Result<()> {
    initialize_tracing(None);

    let ipfs_url = Url::parse("http://127.0.0.1:5001")?;
    let (ns_url, ns_task) = start_name_system_server(&ipfs_url).await?;

    let mut base_pair = SpherePair::new("BASE", &ipfs_url, &ns_url).await?;
    let mut other_pair = SpherePair::new("OTHER", &ipfs_url, &ns_url).await?;

    base_pair.start_gateway().await?;
    other_pair.start_gateway().await?;

    let other_version = other_pair
        .spawn(|mut ctx| async move {
            ctx.write("foo", "text/plain", "bar".as_ref(), None).await?;
            let version = ctx.save(None).await?;
            ctx.sync().await?;
            wait(1).await;
            Ok(version)
        })
        .await?;

    {
        let other_pair_identity = other_pair.client.identity.clone();
        let other_link = base_pair
            .spawn(|mut ctx| async move {
                ctx.set_petname("thirdparty", Some(other_pair_identity))
                    .await?;
                ctx.save(None).await?;
                ctx.sync().await?;
                wait(1).await;

                ctx.sync().await?;
                ctx.resolve_petname("thirdparty").await
            })
            .await?;
        assert_eq!(other_link, Some(other_version));
    }

    ns_task.abort();
    base_pair.stop_gateway().await?;
    other_pair.stop_gateway().await?;

    // Restart gateway and name system, ensuring republishing occurs
    let (ns_url, ns_task) = start_name_system_server(&ipfs_url).await?;
    let ns_client = HttpClient::new(ns_url.clone()).await?;
    assert!(
        ns_client
            .resolve(&base_pair.client.identity)
            .await?
            .is_none(),
        "new name system does not contain client identity"
    );

    base_pair.ns_url = ns_url.clone();
    base_pair.start_gateway().await?;
    wait(1).await;

    assert!(
        ns_client
            .resolve(&base_pair.client.identity)
            .await?
            .is_some(),
        "the gateway republishes records on start."
    );
    base_pair.stop_gateway().await?;
    ns_task.abort();
    Ok(())
}

/// Test that we can read from an adjacent, followed sphere, as well
/// as a followed sphere's followed sphere.
#[tokio::test]
async fn traverse_spheres_and_read_content_via_noosphere_gateway_via_ipfs() -> Result<()> {
    initialize_tracing(None);

    let ipfs_url = Url::parse("http://127.0.0.1:5001")?;
    let (ns_url, ns_task) = start_name_system_server(&ipfs_url).await?;

    let mut pair_1 = SpherePair::new("pair_1", &ipfs_url, &ns_url).await?;
    let mut pair_2 = SpherePair::new("pair_2", &ipfs_url, &ns_url).await?;
    let mut pair_3 = SpherePair::new("pair_3", &ipfs_url, &ns_url).await?;

    pair_1.start_gateway().await?;
    pair_2.start_gateway().await?;
    pair_3.start_gateway().await?;

    // Write some content in each sphere and track the versions after saving for later
    for pair in [&pair_1, &pair_2, &pair_3] {
        let name = pair.name.clone();
        let mut ctx = pair.sphere_context().await?;
        ctx.write("my-name", "text/plain", name.as_ref(), None)
            .await?;
        ctx.save(None).await?;
        ctx.sync().await?;
    }
    wait(1).await;

    let id_2 = pair_2.client.identity.clone();
    let id_3 = pair_3.client.identity.clone();

    let pair_2_version = pair_2
        .spawn(|mut ctx| async move {
            ctx.set_petname("pair_3".into(), Some(id_3)).await?;
            ctx.save(None).await?;
            ctx.sync().await?;
            wait(1).await;
            ctx.sync().await?;
            assert!(ctx.resolve_petname("pair_3").await?.is_some());
            Ok(ctx.version().await?)
        })
        .await?;

    pair_1
        .spawn(move |mut ctx| async move {
            ctx.set_petname("pair_2".into(), Some(id_2)).await?;
            ctx.save(None).await?;
            ctx.sync().await?;
            wait(1).await;
            ctx.sync().await?;
            assert_eq!(ctx.resolve_petname("pair_2").await?, Some(pair_2_version));
            Ok(())
        })
        .await?;

    pair_1
        .spawn(|mut ctx| async move {
            ctx.sync().await?;
            let cursor = SphereCursor::latest(Arc::new(ctx.sphere_context().await?.clone()));
            let pair_2_context = cursor
                .traverse_by_petnames(&["pair_2".to_string()])
                .await?
                .unwrap();

            debug!("Reading file from local third party sphere context...");
            let mut file = pair_2_context.read("my-name").await?.unwrap();
            let mut content = String::new();
            file.contents.read_to_string(&mut content).await?;
            assert_eq!(
                content.as_str(),
                "pair_2",
                "can read content from adjacent sphere"
            );

            // TODO(#320)
            let pair_3_context = pair_2_context
                .traverse_by_petnames(&["pair_3".to_string()])
                .await?
                .unwrap();

            debug!("Reading file from local leap-following third party sphere context...");

            let mut file = pair_3_context.read("my-name").await?.unwrap();
            let mut content = String::new();
            file.contents.read_to_string(&mut content).await.unwrap();
            assert_eq!(
                content.as_str(),
                "pair_3",
                "can read content from adjacent-adjacent sphere"
            );
            Ok(())
        })
        .await?;
    ns_task.abort();
    Ok(())
}

#[tokio::test]
async fn synchronize_petnames_as_they_are_added_and_removed() -> Result<()> {
    initialize_tracing(None);

    let ipfs_url = Url::parse("http://127.0.0.1:5001").unwrap();
    let (ns_url, ns_task) = start_name_system_server(&ipfs_url).await.unwrap();

    let mut base_pair = SpherePair::new("BASE", &ipfs_url, &ns_url).await?;
    let mut other_pair = SpherePair::new("OTHER", &ipfs_url, &ns_url).await?;
    let mut third_pair = SpherePair::new("THIRD", &ipfs_url, &ns_url).await?;

    base_pair.start_gateway().await?;
    other_pair.start_gateway().await?;
    third_pair.start_gateway().await?;

    let other_pair_id = other_pair.client.identity.clone();
    let other_version = other_pair
        .spawn(|mut ctx| async move {
            ctx.write("foo", "text/plain", "bar".as_ref(), None).await?;
            let version = ctx.save(None).await?;
            ctx.sync().await?;
            wait(1).await;
            Ok(version)
        })
        .await?;

    let third_pair_id = third_pair.client.identity.clone();
    let third_version = third_pair
        .spawn(|mut ctx| async move {
            ctx.write("bar", "text/plain", "baz".as_ref(), None).await?;
            let version = ctx.save(None).await?;
            ctx.sync().await?;
            wait(1).await;
            Ok(version)
        })
        .await?;

    base_pair
        .spawn(move |mut ctx| async move {
            ctx.set_petname("thirdparty", Some(other_pair_id)).await?;
            ctx.save(None).await?;
            ctx.sync().await?;
            wait(1).await;

            ctx.sync().await?;
            let other_link = ctx.resolve_petname("thirdparty").await?;
            assert_eq!(other_link, Some(other_version.clone()));

            let resolved = ctx.resolve_petname("thirdparty").await?;
            assert!(resolved.is_some());

            info!("UNSETTING 'thirdparty' as a petname and syncing again...");
            ctx.set_petname("thirdparty", None).await?;
            ctx.save(None).await?;
            ctx.sync().await?;
            wait(1).await;
            ctx.sync().await?;
            let resolved = ctx.resolve_petname("thirdparty").await?;
            assert!(resolved.is_none());
            let recorded = ctx.get_petname("thirdparty").await?;
            assert!(recorded.is_none());

            info!("SETTING 'thirdparty' petname to a different identity and syncing again...");
            ctx.set_petname("thirdparty", Some(third_pair_id.clone()))
                .await?;
            ctx.save(None).await?;
            ctx.sync().await?;
            wait(1).await;
            ctx.sync().await?;

            let saved_id = ctx.get_petname("thirdparty").await?;
            assert_eq!(saved_id, Some(third_pair_id));

            let third_link = ctx.resolve_petname("thirdparty").await?;
            assert_eq!(third_link, Some(third_version.clone()));

            Ok(())
        })
        .await?;

    ns_task.abort();
    Ok(())
}

#[tokio::test]
async fn traverse_spheres_and_get_incremental_updates_via_noosphere_gateway_via_ipfs() -> Result<()>
{
    initialize_tracing(None);

    let ipfs_url = Url::parse("http://127.0.0.1:5001")?;
    let (ns_url, ns_task) = start_name_system_server(&ipfs_url).await?;

    let mut pair_1 = SpherePair::new("pair_1", &ipfs_url, &ns_url).await?;
    let mut pair_2 = SpherePair::new("pair_2", &ipfs_url, &ns_url).await?;

    pair_1.start_gateway().await?;
    pair_2.start_gateway().await?;

    // Write some content in each sphere and track the versions after saving for later
    for pair in [&pair_1, &pair_2] {
        let name = pair.name.clone();
        let mut ctx = pair.sphere_context().await?;
        ctx.write("my-name", "text/plain", name.as_ref(), None)
            .await?;
        ctx.save(None).await?;
        ctx.sync().await?;
    }
    wait(1).await;

    let id_2 = pair_2.client.identity.clone();
    let pair_2_version = pair_2.sphere_context().await?.version().await?;

    pair_1
        .spawn(move |mut ctx| async move {
            ctx.set_petname("pair_2".into(), Some(id_2)).await?;
            ctx.save(None).await?;
            ctx.sync().await?;
            wait(1).await;
            ctx.sync().await?;
            assert_eq!(ctx.resolve_petname("pair_2").await?, Some(pair_2_version));
            Ok(())
        })
        .await?;

    pair_1
        .spawn(|mut ctx| async move {
            wait(1).await;
            ctx.sync().await?;
            let cursor = SphereCursor::latest(Arc::new(ctx.sphere_context().await?.clone()));
            let pair_2_context = cursor
                .traverse_by_petnames(&["pair_2".to_string()])
                .await?
                .unwrap();

            debug!("Reading file from local third party sphere context...");
            let mut file = pair_2_context.read("my-name").await?.unwrap();
            let mut content = String::new();
            file.contents.read_to_string(&mut content).await?;
            assert_eq!(
                content.as_str(),
                "pair_2",
                "can read content from adjacent sphere"
            );

            Ok(())
        })
        .await?;

    pair_2
        .spawn(|mut ctx| async move {
            ctx.write("foo", &ContentType::Text, "foo".as_bytes(), None)
                .await?;
            ctx.save(None).await?;

            ctx.write("bar", &ContentType::Text, "bar".as_bytes(), None)
                .await?;
            ctx.save(None).await?;

            ctx.write("baz", &ContentType::Text, "baz".as_bytes(), None)
                .await?;
            ctx.save(None).await?;

            ctx.remove("my-name").await?;
            ctx.save(None).await?;

            let latest_version = ctx.sync().await?;
            info!("Expect version: {}", latest_version);

            wait(1).await;

            Ok(())
        })
        .await?;

    let pair_2_identity = pair_2.sphere_context().await?.identity().await?;

    pair_1
        .spawn(|mut ctx| async move {
            // Set and sync a new petname to "force" name resolution in the gateway
            ctx.set_petname("foo", Some(Did("did:key:foo".into())))
                .await?;
            ctx.save(None).await?;
            ctx.sync().await?;
            wait(1).await;
            ctx.sync().await?;

            let cursor = SphereCursor::latest(Arc::new(ctx.sphere_context().await?.clone()));
            let pair_2_context = cursor
                .traverse_by_petnames(&vec!["pair_2".into()])
                .await?
                .unwrap();

            // Verify the identity hasn't been messed up to catch regressions
            // https://github.com/subconsciousnetwork/subconscious/issues/675
            let identity = pair_2_context.identity().await?;
            assert_eq!(identity, pair_2_identity);

            let version = pair_2_context.version().await?;
            info!("Have version: {}", version);

            let mut file = pair_2_context.read("baz").await?.unwrap();
            let mut content = String::new();
            file.contents.read_to_string(&mut content).await?;
            assert_eq!(content.as_str(), "baz");

            Ok(())
        })
        .await?;

    ns_task.abort();
    Ok(())
}

#[tokio::test]
async fn replicate_older_version_of_peer_than_the_one_you_have() -> Result<()> {
    initialize_tracing(None);

    let ipfs_url = Url::parse("http://127.0.0.1:5001")?;
    let (ns_url, ns_task) = start_name_system_server(&ipfs_url).await?;

    let mut pair_1 = SpherePair::new("pair_1", &ipfs_url, &ns_url).await?;
    let mut pair_2 = SpherePair::new("pair_2", &ipfs_url, &ns_url).await?;
    let mut pair_3 = SpherePair::new("pair_3", &ipfs_url, &ns_url).await?;

    pair_1.start_gateway().await?;
    pair_2.start_gateway().await?;
    pair_3.start_gateway().await?;

    let id_3 = pair_3.client.identity.clone();

    pair_3
        .spawn(|mut ctx| async move {
            ctx.sync().await?;
            Ok(())
        })
        .await?;

    // sphere_2 follows sphere_3
    pair_2
        .spawn(|mut ctx| async move {
            ctx.set_petname("pair_3".into(), Some(id_3)).await?;
            ctx.save(None).await?;
            ctx.sync().await?;
            wait(1).await;
            ctx.sync().await?;
            assert!(ctx.resolve_petname("pair_3").await?.is_some());
            Ok(ctx.version().await?)
        })
        .await?;

    let id_2 = pair_2.client.identity.clone();
    let id_3 = pair_3.client.identity.clone();

    // sphere_3 writes some initial content
    let sphere_3_first_version = pair_3
        .spawn(move |mut ctx| async move {
            ctx.write("foo", &ContentType::Text, "foo".as_bytes(), None)
                .await?;
            ctx.save(None).await?;
            let cid = ctx.sync().await?;
            Ok(cid)
        })
        .await?;

    {
        let sphere_3_first_version = sphere_3_first_version.clone();
        // sphere_2 updates with sphere_3's initial content
        pair_2
            .spawn(move |mut ctx| async move {
                // Set and sync a new petname to "force" name resolution in the gateway
                ctx.set_petname("foo", Some(Did("did:key:foo".into())))
                    .await?;
                ctx.save(None).await?;
                ctx.sync().await?;
                wait(1).await;
                ctx.sync().await?;
                assert_eq!(
                    ctx.resolve_petname("pair_3").await?,
                    Some(sphere_3_first_version)
                );

                Ok(())
            })
            .await?;
    }
    // sphere_3 makes a bunch of additional changes
    let sphere_3_newest_version = pair_3
        .spawn(move |mut ctx| async move {
            ctx.write("foo", &ContentType::Text, "foo2".as_bytes(), None)
                .await?;
            ctx.save(None).await?;
            ctx.write("bar", &ContentType::Text, "bar".as_bytes(), None)
                .await?;
            ctx.save(None).await?;
            ctx.write("baz", &ContentType::Text, "baz".as_bytes(), None)
                .await?;
            ctx.save(None).await?;
            ctx.remove("bar").await?;
            ctx.save(None).await?;
            let cid = ctx.sync().await?;
            Ok(cid)
        })
        .await?;

    // sphere_1 follows sphere_2 and sphere_3, then...
    // sphere_1 gets the latest version of sphere_3 and traverses to sphere_2's
    // sphere_3 (which is an older version than the oldest version sphere_1 has
    // seen)
    pair_1
        .spawn(move |mut ctx| async move {
            ctx.set_petname("pair_2".into(), Some(id_2)).await?;
            ctx.set_petname("pair_3".into(), Some(id_3)).await?;
            ctx.save(None).await?;
            ctx.sync().await?;
            wait(1).await;
            ctx.sync().await?;
            let cid = ctx.resolve_petname("pair_3").await?.unwrap();

            assert_eq!(cid, sphere_3_newest_version);

            let cursor = SphereCursor::latest(Arc::new(ctx.sphere_context().await?.clone()));
            let sphere_1_sphere_3_cursor = cursor
                .traverse_by_petnames(&["pair_3".to_string()])
                .await?
                .unwrap();

            // File we added
            let mut file = sphere_1_sphere_3_cursor.read("baz").await?.unwrap();
            let mut content = String::new();
            file.contents.read_to_string(&mut content).await?;

            assert_eq!(content, "baz");

            // File we removed
            let file = sphere_1_sphere_3_cursor.read("bar").await?;
            assert!(file.is_none());

            // File we changed
            let mut file = sphere_1_sphere_3_cursor.read("foo").await?.unwrap();
            let mut content = String::new();
            file.contents.read_to_string(&mut content).await?;

            assert_eq!(content, "foo2");

            let sphere_1_sphere_2_cursor = cursor
                .traverse_by_petnames(&["pair_2".to_string()])
                .await?
                .unwrap();

            assert_eq!(
                sphere_1_sphere_2_cursor.resolve_petname("pair_3").await?,
                Some(sphere_3_first_version)
            );

            let sphere_1_sphere_2_sphere_3_cursor = sphere_1_sphere_2_cursor
                .traverse_by_petnames(&["pair_3".into()])
                .await?
                .unwrap();

            let mut file = sphere_1_sphere_2_sphere_3_cursor
                .read("foo")
                .await?
                .unwrap();
            let mut content = String::new();
            file.contents.read_to_string(&mut content).await?;

            assert_eq!(content, "foo");

            Ok(())
        })
        .await?;

    ns_task.abort();
    Ok(())
}

#[tokio::test]
async fn local_lineage_remains_sparse_as_graph_changes_accrue_over_time() -> Result<()> {
    initialize_tracing(None);

    let ipfs_url = Url::parse("http://127.0.0.1:5001")?;
    let (ns_url, ns_task) = start_name_system_server(&ipfs_url).await?;

    let mut pair_1 = SpherePair::new("pair_1", &ipfs_url, &ns_url).await?;
    let mut pair_2 = SpherePair::new("pair_2", &ipfs_url, &ns_url).await?;

    pair_1.start_gateway().await?;
    pair_2.start_gateway().await?;

    pair_2
        .spawn(move |mut ctx| async move {
            ctx.write("peer-content", "text/plain", "baz".as_bytes(), None)
                .await?;

            ctx.save(None).await?;
            ctx.sync().await?;
            Ok(())
        })
        .await?;

    let sphere_2_id = pair_2.client.identity.clone();

    pair_1
        .spawn(move |mut ctx| async move {
            ctx.write("some-content", "text/plain", "foobar".as_bytes(), None)
                .await?;

            ctx.save(None).await?;
            ctx.sync().await?;

            ctx.write("new-content", "text/plain", "foobar2".as_bytes(), None)
                .await?;

            ctx.save(None).await?;
            ctx.sync().await?;

            ctx.set_petname("my-peer", Some(sphere_2_id)).await?;
            ctx.save(None).await?;

            ctx.sync().await?;
            wait(1).await;
            ctx.sync().await?;

            Ok(())
        })
        .await?;

    pair_2
        .spawn(|mut ctx| async move {
            ctx.write("peer-content", "text/plain", "baz".as_bytes(), None)
                .await?;
            ctx.save(None).await?;
            ctx.sync().await?;

            Ok(())
        })
        .await?;

    pair_1
        .spawn(|mut ctx| async move {
            ctx.sync().await?;
            wait(1).await;
            ctx.sync().await?;

            let walker = SphereWalker::from(&ctx);

            let content_history = walker.content_change_stream(None);
            tokio::pin!(content_history);

            let history = content_history
                .collect::<Result<Vec<(Link<MemoIpld>, BTreeSet<String>)>>>()
                .await?;

            for (cid, changes) in history.iter() {
                trace!("{}: {:?}", cid.to_string(), changes);
            }

            for (index, (version, content_changes)) in history.iter().enumerate() {
                debug!(history_index = ?index, version = ?version, changes = ?content_changes);
                match index {
                    0 => {
                        assert!(content_changes.contains(&"some-content".to_owned()));
                        assert_eq!(content_changes.len(), 1);
                    }
                    1 => {
                        assert!(content_changes.contains(&"new-content".to_owned()));
                        assert_eq!(content_changes.len(), 1);
                    }
                    _ => {
                        unreachable!("There should only be two revisions to content!")
                    }
                }
            }

            Ok(())
        })
        .await?;

    ns_task.abort();
    Ok(())
}

#[tokio::test]
async fn all_of_client_history_is_made_manifest_on_the_gateway_after_sync() -> Result<()> {
    initialize_tracing(None);

    let ipfs_url = Url::parse("http://127.0.0.1:5001")?;
    let (ns_url, ns_task) = start_name_system_server(&ipfs_url).await?;

    let mut pair_1 = SpherePair::new("ONE", &ipfs_url, &ns_url).await?;
    let mut pair_2 = SpherePair::new("TWO", &ipfs_url, &ns_url).await?;

    pair_1.start_gateway().await?;
    pair_2.start_gateway().await?;

    let _ = pair_2
        .spawn(|mut ctx| async move {
            ctx.write("foo", &ContentType::Text, "bar".as_bytes(), None)
                .await?;
            ctx.save(None).await?;
            Ok(ctx.sync().await?)
        })
        .await?;

    let sphere_2_identity = pair_2.client.identity.clone();

    let final_client_version = pair_1
        .spawn(move |mut ctx| async move {
            for value in ["one", "two", "three"] {
                ctx.write(value, &ContentType::Text, value.as_bytes(), None)
                    .await?;
                ctx.save(None).await?;
            }

            ctx.sync().await?;

            ctx.set_petname("two", Some(sphere_2_identity)).await?;

            ctx.save(None).await?;

            ctx.sync().await?;

            for value in ["one", "two", "three"] {
                ctx.set_petname(value, Some(Did(format!("did:key:{}", value))))
                    .await?;
                ctx.save(None).await?;
            }

            ctx.sync().await?;

            wait(1).await;

            Ok(ctx.sync().await?)
        })
        .await?;

    // Stream all of the blocks of client history as represented in gateway's storage
    let block_stream = memo_history_stream(
        pair_1.gateway.workspace.db().await?,
        &final_client_version,
        None,
        true,
    );

    tokio::pin!(block_stream);

    while let Some(_) = block_stream.try_next().await? {}

    ns_task.abort();

    Ok(())
}

#[tokio::test]
async fn fall_back_to_local_content_when_kubo_times_out_on_block() -> Result<()> {
    initialize_tracing(None);

    let ipfs_url = Url::parse("http://127.0.0.1:5001")?;
    let (ns_url, ns_task) = start_name_system_server(&ipfs_url).await?;

    let mut pair_1 = SpherePair::new("ONE", &ipfs_url, &ns_url).await?;
    let mut pair_2 = SpherePair::new("TWO", &ipfs_url, &ns_url).await?;

    let sphere_1_identity = pair_1.client.identity.clone();

    pair_1.start_gateway().await?;
    pair_2.start_gateway().await?;

    let fallback_version = pair_1
        .spawn(|mut ctx| async move {
            ctx.write("foo", &ContentType::Text, b"bar".as_ref(), None)
                .await?;
            ctx.save(None).await?;
            let fallback_version = ctx.sync().await?;
            wait(1).await;

            Ok(fallback_version)
        })
        .await?;

    pair_2
        .spawn(|mut ctx| async move {
            ctx.set_petname("one", Some(sphere_1_identity)).await?;
            ctx.save(None).await?;
            ctx.sync().await?;
            wait(1).await;
            ctx.sync().await?;

            // Traverse to peer at a known-to-be-available version to ensure it
            // becomes locally cached
            let cursor = SphereCursor::latest(ctx);
            let _ = cursor.traverse_by_petnames(&[String::from("one")]).await?;

            Ok(())
        })
        .await?;

    let unavailable_link_record = pair_1
        .spawn(|mut ctx| async move {
            // Make some changes but don't sync to simulate unavailable blocks
            ctx.write("baz", &ContentType::Text, b"foo".as_ref(), None)
                .await?;
            ctx.save(None).await?;

            Ok(ctx
                .create_link_record(Some(Duration::from_secs(120)))
                .await?)
        })
        .await?;

    pair_2
        .spawn(move |mut ctx| async move {
            ctx.set_petname_record("one", &unavailable_link_record)
                .await?;

            ctx.save(None).await?;

            let cursor = SphereCursor::latest(ctx);

            let peer = cursor
                .traverse_by_petnames(&[String::from("one")])
                .await?
                .unwrap();

            assert_eq!(peer.version().await?, fallback_version);

            Ok(())
        })
        .await?;

    ns_task.abort();

    Ok(())
}

#[tokio::test]
async fn recover_a_sphere_and_sync_changes_with_the_noosphere() -> Result<()> {
    initialize_tracing(None);

    let ipfs_url = Url::parse("http://127.0.0.1:5001")?;
    let (ns_url, ns_task) = start_name_system_server(&ipfs_url).await?;

    let mut sphere_pair_1 = SpherePair::new("one", &ipfs_url, &ns_url).await?;
    let mut sphere_pair_2 = SpherePair::new("two", &ipfs_url, &ns_url).await?;

    sphere_pair_1.start_gateway().await?;
    sphere_pair_2.start_gateway().await?;

    sphere_pair_2
        .spawn(|mut ctx| async move {
            ctx.write("foo", &ContentType::Text, b"bar".as_ref(), None)
                .await?;
            ctx.save(None).await?;
            ctx.sync().await?;
            Ok(())
        })
        .await?;

    let sphere_pair_2_identity = sphere_pair_2.client.identity.clone();

    sphere_pair_1
        .spawn(move |mut ctx| async move {
            for value in ["one", "two", "three"] {
                ctx.write(value, &ContentType::Text, value.as_bytes(), None)
                    .await?;
                ctx.save(None).await?;
            }

            ctx.set_petname("two", Some(sphere_pair_2_identity)).await?;
            ctx.save(None).await?;

            ctx.sync().await?;
            wait(1).await;
            ctx.sync().await?;

            Ok(())
        })
        .await?;

    {
        // NOTE: We initialize the builder before simulating corruption because
        // we don't have a convenient way to get the critical inputs (e.g.,
        // gateway URL) otherwise. In practice, these values should be recorded
        // on the side by the embedder for use in recovery scenarios such as
        // this.
        let recovery_builder = SphereContextBuilder::default()
            .recover_sphere(&sphere_pair_1.client.identity)
            .at_storage_path(sphere_pair_1.client.sphere_root())
            .reading_keys_from(sphere_pair_1.client.workspace.key_storage().clone())
            .using_mnemonic(Some(&sphere_pair_1.client.mnemonic))
            .using_key(&sphere_pair_1.client.key_name)
            .syncing_to(Some(&sphere_pair_1.client.workspace.gateway_url().await?));

        sphere_pair_1.client.workspace.release_sphere_context();

        sphere_pair_1.client.simulate_storage_corruption().await?;

        assert!(sphere_pair_1
            .client
            .workspace
            .sphere_context()
            .await
            .is_err());

        // Perform the recovery:
        recovery_builder.build().await?;
    }

    sphere_pair_1
        .spawn(move |ctx| async move {
            for value in ["one", "two", "three"] {
                let mut contents = String::new();
                let mut file = ctx
                    .read(value)
                    .await?
                    .ok_or_else(|| anyhow!("Could not read file"))?;
                file.contents.read_to_string(&mut contents).await?;
                assert_eq!(value, contents);
            }
            Ok(())
        })
        .await?;

    let sphere_2_version = sphere_pair_2
        .spawn(|mut ctx| async move {
            ctx.write("foo", &ContentType::Text, b"baz".as_ref(), None)
                .await?;
            ctx.save(None).await?;
            Ok(ctx.sync().await?)
        })
        .await?;

    sphere_pair_1
        .spawn(move |mut ctx| async move {
            ctx.write("four", &ContentType::Text, b"four".as_ref(), None)
                .await?;
            ctx.save(None).await?;

            ctx.sync().await?;
            wait(1).await;
            ctx.sync().await?;

            let peer_ctx = SphereCursor::latest(ctx)
                .traverse_by_petnames(&["two".into()])
                .await?
                .unwrap();

            let peer_version = peer_ctx.version().await?;

            assert_eq!(sphere_2_version, peer_version);

            Ok(())
        })
        .await?;

    ns_task.abort();

    Ok(())
}