kitsune2 0.4.0-dev.7

p2p / dht communication framework api
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
use bytes::Bytes;
use kitsune2::default_builder;
use kitsune2_api::{
    BoxFut, Builder, Config, DhtArc, DynKitsune, DynSpace, DynSpaceHandler, Id,
    K2Result, KitsuneHandler, LocalAgent, OpId, SpaceHandler, SpaceId,
    Timestamp,
};
use kitsune2_core::{
    Ed25519LocalAgent,
    factories::{
        MemoryOp,
        config::{CoreBootstrapConfig, CoreBootstrapModConfig},
    },
};
use kitsune2_gossip::{K2GossipConfig, K2GossipModConfig};
use kitsune2_test_utils::{
    bootstrap::TestBootstrapSrv, enable_tracing, iter_check, random_bytes,
    space::TEST_SPACE_ID,
};
#[cfg(all(
    not(feature = "transport-tx5-backend-go-pion"),
    feature = "transport-iroh"
))]
use kitsune2_transport_iroh::{
    IrohTransportFactory,
    config::{IrohTransportConfig, IrohTransportModConfig},
};
use std::sync::Arc;
#[cfg(feature = "transport-tx5-backend-go-pion")]
use {
    kitsune2_transport_tx5::{
        Tx5TransportFactory,
        config::{Tx5TransportConfig, Tx5TransportModConfig},
    },
    sbd_server::SbdServer,
};

fn create_op_list(num_ops: u16) -> (Vec<Bytes>, Vec<OpId>) {
    let mut ops = Vec::new();
    let mut op_ids = Vec::new();
    for _ in 0..num_ops {
        let op = MemoryOp::new(Timestamp::from_micros(0), random_bytes(256));
        let op_id = op.compute_op_id();
        ops.push(op.into());
        op_ids.push(op_id);
    }
    (ops, op_ids)
}

#[derive(Debug)]
struct TestKitsuneHandler;
impl KitsuneHandler for TestKitsuneHandler {
    fn create_space(
        &self,
        _space_id: SpaceId,
        _config_override: Option<&Config>,
    ) -> BoxFut<'_, K2Result<DynSpaceHandler>> {
        Box::pin(async {
            let space_handler: DynSpaceHandler = Arc::new(TestSpaceHandler);
            Ok(space_handler)
        })
    }
}

#[derive(Debug)]
struct TestSpaceHandler;
impl SpaceHandler for TestSpaceHandler {}

async fn make_kitsune_node(
    relay_server_url: &str,
    bootstrap_server_url: &str,
) -> DynKitsune {
    let kitsune_builder = Builder {
        #[cfg(feature = "transport-tx5-backend-go-pion")]
        transport: Tx5TransportFactory::create(),
        #[cfg(all(
            not(feature = "transport-tx5-backend-go-pion"),
            feature = "transport-iroh"
        ))]
        transport: IrohTransportFactory::create(),
        ..default_builder()
    }
    .with_default_config()
    .unwrap();
    kitsune_builder
        .config
        .set_module_config(&CoreBootstrapModConfig {
            core_bootstrap: CoreBootstrapConfig {
                server_url: Some(bootstrap_server_url.to_owned()),
                backoff_min_ms: 1000,
                backoff_max_ms: 1000,
            },
        })
        .unwrap();

    #[cfg(feature = "transport-tx5-backend-go-pion")]
    kitsune_builder
        .config
        .set_module_config(&Tx5TransportModConfig {
            tx5_transport: Tx5TransportConfig {
                server_url: relay_server_url.to_owned(),
                signal_allow_plain_text: true,
                timeout_s: 5,
                webrtc_connect_timeout_s: 3,
                ..Default::default()
            },
        })
        .unwrap();
    #[cfg(all(
        not(feature = "transport-tx5-backend-go-pion"),
        feature = "transport-iroh"
    ))]
    kitsune_builder
        .config
        .set_module_config(&IrohTransportModConfig {
            iroh_transport: IrohTransportConfig {
                relay_url: Some(relay_server_url.to_string()),
                relay_allow_plain_text: true,
                ..Default::default()
            },
        })
        .unwrap();

    kitsune_builder
        .config
        .set_module_config(&K2GossipModConfig {
            k2_gossip: K2GossipConfig {
                initiate_interval_ms: 1000,
                min_initiate_interval_ms: 100,
                initiate_jitter_ms: 100,
                round_timeout_ms: 10_000,
                ..Default::default()
            },
        })
        .unwrap();

    let kitsune_handler = Arc::new(TestKitsuneHandler);
    let kitsune = kitsune_builder.build().await.unwrap();
    kitsune
        .register_handler(kitsune_handler.clone())
        .await
        .unwrap();

    kitsune
}

#[cfg(feature = "transport-tx5-backend-go-pion")]
async fn sbd_signal_server() -> (String, SbdServer) {
    let signal_server = SbdServer::new(Arc::new(sbd_server::Config {
        bind: vec!["127.0.0.1:0".to_string()],
        ..Default::default()
    }))
    .await
    .unwrap();
    let relay_server_url = format!("ws://{}", signal_server.bind_addrs()[0]);
    (relay_server_url, signal_server)
}

/// For iroh transport, the relay functionality is integrated into the bootstrap server.
/// This function returns the relay URL (bootstrap server URL + /relay/).
/// Note: The trailing slash is important for proper URL construction.
#[cfg(all(
    not(feature = "transport-tx5-backend-go-pion"),
    feature = "transport-iroh"
))]
async fn iroh_relay_from_bootstrap(bootstrap: &TestBootstrapSrv) -> String {
    format!("{}/relay", bootstrap.addr())
}

async fn start_space(kitsune: &DynKitsune) -> DynSpace {
    let space = kitsune.space(TEST_SPACE_ID, None).await.unwrap();

    // Create an agent.
    let local_agent = Arc::new(Ed25519LocalAgent::default());
    local_agent.set_tgt_storage_arc_hint(DhtArc::FULL);

    // Join agent to local space.
    space.local_agent_join(local_agent.clone()).await.unwrap();

    // Wait for agent to publish their info to the bootstrap & peer store.
    iter_check!(5000, 100, {
        let agent = local_agent.agent().clone();
        match space.peer_store().get(agent.clone()).await {
            Ok(Some(peer)) => {
                tracing::info!("Found local agent in peer store: {:?}", peer);
                break;
            }
            Ok(None) => {
                tracing::debug!(
                    "Local agent not yet in peer store: {:?}",
                    agent
                );
            }
            Err(e) => {
                tracing::error!(
                    "Error getting local agent from peer store: {:?}",
                    e
                );
                panic!("Peer store error: {e:?}");
            }
        }
    });

    space
}

#[tokio::test]
async fn two_node_gossip() {
    enable_tracing();

    let bootstrap_server = TestBootstrapSrv::new(false).await;
    let bootstrap_server_url = bootstrap_server.addr().to_string();

    #[cfg(feature = "transport-tx5-backend-go-pion")]
    let (relay_server_url, _relay_server) = sbd_signal_server().await;

    #[cfg(all(
        not(feature = "transport-tx5-backend-go-pion"),
        feature = "transport-iroh"
    ))]
    let relay_server_url = iroh_relay_from_bootstrap(&bootstrap_server).await;

    // Create 2 Kitsune instances...
    let kitsune_1 =
        make_kitsune_node(&relay_server_url, &bootstrap_server_url).await;
    let kitsune_2 =
        make_kitsune_node(&relay_server_url, &bootstrap_server_url).await;

    // and 1 space with 1 joined agent each.
    let space_1 = start_space(&kitsune_1).await;
    let space_2 = start_space(&kitsune_2).await;

    // Insert ops into both spaces' op stores.
    let (ops_1, op_ids_1) = create_op_list(1000);
    space_1
        .op_store()
        .process_incoming_ops(ops_1.clone())
        .await
        .unwrap();
    let (ops_2, op_ids_2) = create_op_list(1000);
    space_2
        .op_store()
        .process_incoming_ops(ops_2.clone())
        .await
        .unwrap();

    // Wait for gossip to exchange all ops.
    iter_check!(60_000, 1_000, {
        let actual_ops_1 = space_1
            .op_store()
            .retrieve_ops(op_ids_2.clone())
            .await
            .unwrap();
        let actual_ops_2 = space_2
            .op_store()
            .retrieve_ops(op_ids_1.clone())
            .await
            .unwrap();
        if actual_ops_1.len() == ops_2.len()
            && actual_ops_2.len() == ops_1.len()
        {
            break;
        } else {
            tracing::info!(
                "space 1 actual ops received {}/expected {}",
                actual_ops_1.len(),
                ops_2.len()
            );
            tracing::info!(
                "space 2 actual ops received {}/expected {}",
                actual_ops_2.len(),
                ops_1.len()
            );
        }
    });
}

/// Test that space shutdown is reasonably clean:
/// - Start two Kitsune2 instances
/// - Record the initial number of Tokio tasks
/// - Start two spaces, one on each instance
/// - Join an agent to each space
/// - Create some ops in each space
/// - Wait for gossip to exchange all ops
/// - Have local agents leave the spaces
/// - Wait for all peers to declare a tombstone
/// - Shut down the spaces
/// - Wait for the spaces' tasks to be cleaned up
///
/// This isn't a perfect check for shutdown, but it's a reasonable expectation that if all the
/// Tokio tasks for a space are gone, then it's not actively doing work in the background.
#[cfg(feature = "transport-tx5-backend-go-pion")]
#[tokio::test]
async fn shutdown_space() {
    enable_tracing();

    let bootstrap_server = TestBootstrapSrv::new(false).await;
    let bootstrap_server_url = bootstrap_server.addr().to_string();

    #[cfg(feature = "transport-tx5-backend-go-pion")]
    let (relay_server_url, _relay_server) = sbd_signal_server().await;

    #[cfg(all(
        not(feature = "transport-tx5-backend-go-pion"),
        feature = "transport-iroh"
    ))]
    let relay_server_url = iroh_relay_from_bootstrap(&bootstrap_server).await;

    // Create 2 Kitsune instances..
    let kitsune_1 =
        make_kitsune_node(&relay_server_url, &bootstrap_server_url).await;
    let kitsune_2 =
        make_kitsune_node(&relay_server_url, &bootstrap_server_url).await;

    let metrics = tokio::runtime::Handle::current().metrics();
    let initial_tasks = metrics.num_alive_tasks();

    // and 1 space with 1 joined agent each.
    let space_1 = start_space(&kitsune_1).await;
    let space_2 = start_space(&kitsune_2).await;

    // Create some data for each agent
    let (ops_1, op_ids_1) = create_op_list(10);
    space_1
        .op_store()
        .process_incoming_ops(ops_1.clone())
        .await
        .unwrap();
    let (ops_2, op_ids_2) = create_op_list(10);
    space_2
        .op_store()
        .process_incoming_ops(ops_2.clone())
        .await
        .unwrap();

    // Wait for gossip to exchange all ops.
    iter_check!(15000, 500, {
        let actual_ops_1 = space_1
            .op_store()
            .retrieve_ops(op_ids_2.clone())
            .await
            .unwrap();
        let actual_ops_2 = space_2
            .op_store()
            .retrieve_ops(op_ids_1.clone())
            .await
            .unwrap();
        if actual_ops_1.len() == ops_2.len()
            && actual_ops_2.len() == ops_1.len()
        {
            break;
        } else {
            println!(
                "space 1 actual ops received {}/expected {}",
                actual_ops_1.len(),
                ops_2.len()
            );
            println!(
                "space 2 actual ops received {}/expected {}",
                actual_ops_2.len(),
                ops_1.len()
            );
        }
    });

    // Attempt to shut down a space while there are still agents joined.
    let err = kitsune_1.remove_space(TEST_SPACE_ID).await.unwrap_err();
    assert!(
        err.to_string()
            .contains("Cannot remove space with local agents"),
        "Got error: {err}"
    );

    // Leave the spaces.
    for local_agent in space_1.local_agent_store().get_all().await.unwrap() {
        space_1.local_agent_leave(local_agent.agent().clone()).await;
    }
    for local_agent in space_2.local_agent_store().get_all().await.unwrap() {
        space_2.local_agent_leave(local_agent.agent().clone()).await;
    }

    // Wait for all peers to declare a tombstone.
    iter_check!(5000, 500, {
        let all_peers_tombstone_1 = space_1
            .peer_store()
            .get_all()
            .await
            .unwrap()
            .iter()
            .all(|a| a.url.is_none());
        let all_peers_tombstone_2 = space_2
            .peer_store()
            .get_all()
            .await
            .unwrap()
            .iter()
            .all(|a| a.url.is_none());

        if all_peers_tombstone_1 && all_peers_tombstone_2 {
            break;
        } else {
            println!(
                "space 1 peers: {:?}",
                space_1.peer_store().get_all().await.unwrap()
            );
            println!(
                "space 2 peers: {:?}",
                space_2.peer_store().get_all().await.unwrap()
            );
        }
    });

    // Now that the spaces have been active and messaging each other, shut them down.
    drop(space_1);
    drop(space_2);
    kitsune_1.remove_space(TEST_SPACE_ID).await.unwrap();
    kitsune_2.remove_space(TEST_SPACE_ID).await.unwrap();

    // Wait for the space's tasks to be cleaned up.
    // This includes connection tasks, otherwise the task count would stay higher than the initial
    // count.
    iter_check!(30000, 100, {
        let current_tasks = metrics.num_alive_tasks();
        if current_tasks == initial_tasks {
            break;
        } else {
            println!(
                "Current tasks: {current_tasks}, Initial tasks: {initial_tasks}"
            );
        }
    });

    // The spaces should be gone.
    assert!(kitsune_1.space_if_exists(TEST_SPACE_ID).await.is_none());
    assert!(kitsune_2.space_if_exists(TEST_SPACE_ID).await.is_none());
}

#[tokio::test]
async fn test_space_should_not_start_without_bootstrap_url_configured() {
    enable_tracing();

    // Build Kitsune2 normally, but DO NOT set any bootstrap module config.
    let kitsune_builder = default_builder().with_default_config().unwrap();

    #[cfg(feature = "transport-tx5-backend-go-pion")]
    {
        let signal_server = SbdServer::new(Arc::new(sbd_server::Config {
            bind: vec!["127.0.0.1:0".to_string()],
            ..Default::default()
        }))
        .await
        .unwrap();
        let signal_server_url =
            format!("ws://{}", signal_server.bind_addrs()[0]);
        kitsune_builder
            .config
            .set_module_config(&Tx5TransportModConfig {
                tx5_transport: Tx5TransportConfig {
                    server_url: signal_server_url.to_owned(),
                    signal_allow_plain_text: true,
                    timeout_s: 5,
                    webrtc_connect_timeout_s: 3,
                    ..Default::default()
                },
            })
            .unwrap();
    }
    kitsune_builder
        .config
        .set_module_config(&K2GossipModConfig {
            k2_gossip: K2GossipConfig {
                initiate_interval_ms: 1000,
                min_initiate_interval_ms: 100,
                initiate_jitter_ms: 100,
                round_timeout_ms: 10_000,
                ..Default::default()
            },
        })
        .unwrap();

    // Build should succeed.
    let kitsune = kitsune_builder.build().await.expect("Build Kitsune2");

    // register handler
    let kitsune_handler = Arc::new(TestKitsuneHandler);
    kitsune
        .register_handler(kitsune_handler.clone())
        .await
        .expect("Register handler");

    // Creating a space MUST fail because there is no bootstrap config.
    let result = kitsune.space(TEST_SPACE_ID, None).await;

    assert!(
        result.is_err(),
        "Expected creating a space to fail when no bootstrap URL is configured"
    );
}

#[tokio::test]
async fn test_should_start_space_with_different_bootstrap_urls() {
    enable_tracing();

    // Create two independent bootstrap servers
    let bootstrap_a = TestBootstrapSrv::new(false).await;
    let bootstrap_b = TestBootstrapSrv::new(false).await;
    let bootstrap_url_a = bootstrap_a.addr().to_string();
    let bootstrap_url_b = bootstrap_b.addr().to_string();

    // Build Kitsune2 normally, but DO NOT set any bootstrap module config.
    let kitsune_builder = default_builder().with_default_config().unwrap();

    #[cfg(feature = "transport-tx5-backend-go-pion")]
    {
        let signal_server = SbdServer::new(Arc::new(sbd_server::Config {
            bind: vec!["127.0.0.1:0".to_string()],
            ..Default::default()
        }))
        .await
        .unwrap();
        let signal_server_url =
            format!("ws://{}", signal_server.bind_addrs()[0]);
        kitsune_builder
            .config
            .set_module_config(&Tx5TransportModConfig {
                tx5_transport: Tx5TransportConfig {
                    server_url: signal_server_url.to_owned(),
                    signal_allow_plain_text: true,
                    timeout_s: 5,
                    webrtc_connect_timeout_s: 3,
                    ..Default::default()
                },
            })
            .unwrap();
    }
    kitsune_builder
        .config
        .set_module_config(&K2GossipModConfig {
            k2_gossip: K2GossipConfig {
                initiate_interval_ms: 1000,
                min_initiate_interval_ms: 100,
                initiate_jitter_ms: 100,
                round_timeout_ms: 10_000,
                ..Default::default()
            },
        })
        .unwrap();

    let kitsune = kitsune_builder.build().await.unwrap();
    kitsune
        .register_handler(Arc::new(TestKitsuneHandler))
        .await
        .unwrap();

    // Custom configs for the two spaces
    let config_a = Config::default();
    config_a
        .set_module_config(&CoreBootstrapModConfig {
            core_bootstrap: CoreBootstrapConfig {
                server_url: Some(bootstrap_url_a.clone()),
                ..Default::default()
            },
        })
        .unwrap();

    let config_b = Config::default();
    config_b
        .set_module_config(&CoreBootstrapModConfig {
            core_bootstrap: CoreBootstrapConfig {
                server_url: Some(bootstrap_url_b.clone()),
                ..Default::default()
            },
        })
        .unwrap();

    // Create the two spaces with different bootstrap URLs
    let space_a = kitsune
        .space(TEST_SPACE_ID, Some(config_a))
        .await
        .expect("Create space A");

    let space_b = kitsune
        .space(SpaceId(Id(Bytes::from("space_b"))), Some(config_b))
        .await
        .expect("Create space B");

    // Attach a local agent to each space
    let agent_a = Arc::new(Ed25519LocalAgent::default());
    agent_a.set_tgt_storage_arc_hint(DhtArc::FULL);
    iter_check!(60_000, 1_000, {
        if space_a.local_agent_join(agent_a.clone()).await.is_ok() {
            break;
        }
    });
    let agent_b = Arc::new(Ed25519LocalAgent::default());
    agent_b.set_tgt_storage_arc_hint(DhtArc::FULL);
    iter_check!(60_000, 1_000, {
        if space_b.local_agent_join(agent_b.clone()).await.is_ok() {
            break;
        }
    });

    let agent_a_id = agent_a.agent();
    let agent_b_id = agent_b.agent();
    assert!(space_a.peer_store().get(agent_a_id.clone()).await.is_ok());
    assert!(space_b.peer_store().get(agent_b_id.clone()).await.is_ok());
    assert!(
        space_a
            .peer_store()
            .get(agent_b_id.clone())
            .await
            .unwrap()
            .is_none(),
        "Agent B should not be in space A's peer store"
    );
    assert!(
        space_b
            .peer_store()
            .get(agent_a_id.clone())
            .await
            .unwrap()
            .is_none(),
        "Agent A should not be in space B's peer store"
    );
}