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
use crate::actor::*;
use crate::event::*;
use crate::HostApi;

mod actor;
pub(crate) use actor::meta_net;
use actor::*;

#[cfg(any(test, feature = "test_utils"))]
pub use actor::MockKitsuneP2pEventHandler;
use futures::future::BoxFuture;
use ghost_actor::GhostSender;

/// Spawn a new KitsuneP2p actor.
pub async fn spawn_kitsune_p2p(
    config: crate::KitsuneP2pConfig,
    tls_config: kitsune_p2p_types::tls::TlsConfig,
    host: HostApi,
) -> KitsuneP2pResult<(
    ghost_actor::GhostSender<KitsuneP2p>,
    KitsuneP2pEventReceiver,
)> {
    let (evt_send, evt_recv) = futures::channel::mpsc::channel(10);
    let builder = ghost_actor::actor_builder::GhostActorBuilder::new();

    let channel_factory = builder.channel_factory().clone();

    let internal_sender = channel_factory.create_channel::<Internal>().await?;

    let sender = channel_factory.create_channel::<KitsuneP2p>().await?;

    tokio::task::spawn(
        builder.spawn(
            KitsuneP2pActor::new(
                config,
                tls_config,
                channel_factory,
                internal_sender,
                evt_send,
                host,
            )
            .await?,
        ),
    );

    Ok((sender, evt_recv))
}

/// Spawn a new KitsuneP2p actor, using a closure to generate the HostApi.
/// Used for some test cases where the HostApi requires some of the intermediate
/// values created by this function.
pub async fn spawn_kitsune_p2p_with_fn<F, T>(
    config: crate::KitsuneP2pConfig,
    tls_config: kitsune_p2p_types::tls::TlsConfig,
    build_host: F,
) -> KitsuneP2pResult<(
    ghost_actor::GhostSender<KitsuneP2p>,
    KitsuneP2pEventReceiver,
    T,
)>
where
    F: FnOnce(GhostSender<KitsuneP2p>) -> BoxFuture<'static, (T, HostApi)>,
{
    let (evt_send, evt_recv) = futures::channel::mpsc::channel(10);
    let builder = ghost_actor::actor_builder::GhostActorBuilder::new();

    let channel_factory = builder.channel_factory().clone();

    let internal_sender = channel_factory.create_channel::<Internal>().await?;

    let sender = channel_factory.create_channel::<KitsuneP2p>().await?;

    let (t, host) = build_host(sender.clone()).await;

    tokio::task::spawn(
        builder.spawn(
            KitsuneP2pActor::new(
                config,
                tls_config,
                channel_factory,
                internal_sender,
                evt_send,
                host,
            )
            .await?,
        ),
    );

    Ok((sender, evt_recv, t))
}