aboutsummaryrefslogtreecommitdiffstats
path: root/src/transport/mycelium/real_daemons.rs
blob: 93095f8bdda9acdd0ffc3d8e99d945f731b8f2c0 (plain)
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
//! The transport against Mycelium's own daemons, supervised as a node supervises its own
//! (`MyceliumSetup::bootstrap`): two on loopback, one peering with the other, which carry
//! a message each way after idling, again and again. Ignored: it needs `mycelium` on the
//! `PATH` (Linux, as supervising does), and IPv6, which the daemons listen on for peers:
//! `cargo test --features most -- --ignored two_supervised_daemons`.

use std::sync::Arc;
use std::time::Duration;

use super::daemon::{MyceliumRuntime, MyceliumSpawnConfig};
use super::{MyceliumSetup, MyceliumTransport, encode_message};
use crate::transport::{MessageHandler, ParsedMessage, Transport, is_probe, wire};

/// How long the daemons may take to find each other's routes.
const ROUTED_WITHIN: Duration = Duration::from_secs(60);
/// Long enough for a send, and a delivery, on loopback.
const SOON: Duration = Duration::from_secs(5);

/// A supervised daemon, and the transport using it, taking what comes in.
async fn supervised(
    config: MyceliumSpawnConfig,
) -> (
    Arc<MyceliumTransport>,
    u16,
    tokio::sync::mpsc::UnboundedReceiver<ParsedMessage>,
) {
    let setup = MyceliumSetup::bootstrap(config).await.expect("a daemon");
    let port = match &setup.runtime {
        MyceliumRuntime::Supervised(daemon) => daemon.config.tcp_port,
        MyceliumRuntime::External => unreachable!("supervised"),
    };
    let transport = Arc::new(MyceliumTransport::connect(setup).await.expect("connected"));
    let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
    let handler: MessageHandler = Box::new(move |_, message, _| {
        let tx = tx.clone();
        Box::pin(async move {
            let _ = tx.send(message);
            Ok(())
        })
    });
    let consuming = transport.clone();
    tokio::spawn(async move { consuming.start_consumer(handler).await });
    (transport, port, rx)
}

fn a_message() -> ParsedMessage {
    wire::samples()
        .into_iter()
        .find(|message| !is_probe(message))
        .expect("a message other than a probe")
}

/// Sends from `from` to `to` (by its key), and waits for `taken` to have it.
async fn carried(
    from: &MyceliumTransport,
    to: &MyceliumTransport,
    taken: &mut tokio::sync::mpsc::UnboundedReceiver<ParsedMessage>,
) -> bool {
    let message = encode_message(to.local_id(), &a_message(), wire::VERSION).expect("encoded");
    let sent = tokio::time::timeout(SOON, from.send_encoded(&message)).await;
    assert!(matches!(sent, Ok(Ok(()))), "a send held up: {sent:?}");
    tokio::time::timeout(SOON, taken.recv())
        .await
        .is_ok_and(|got| got.is_some())
}

/// Two daemons, one peering with the other: once routed, each carries a message to the
/// other after idling, its send never held up by its own wait for what comes in.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[ignore = "needs mycelium on the PATH, and IPv6"]
async fn two_supervised_daemons_carry_messages_both_ways_after_idling() {
    let (a, port, mut taken_by_a) = supervised(MyceliumSpawnConfig {
        peers: Vec::new(),
        ..Default::default()
    })
    .await;
    let (b, _, mut taken_by_b) = supervised(MyceliumSpawnConfig {
        peers: vec![format!("tcp://127.0.0.1:{port}")],
        ..Default::default()
    })
    .await;
    // Until their routes are found, a message may go nowhere.
    let routed = tokio::time::timeout(ROUTED_WITHIN, async {
        while !carried(&b, &a, &mut taken_by_a).await {}
    })
    .await;
    assert!(routed.is_ok(), "no route between the daemons");
    // What the routes held back comes in late: not taken for what is sent below.
    tokio::time::sleep(Duration::from_secs(1)).await;
    while taken_by_a.try_recv().is_ok() || taken_by_b.try_recv().is_ok() {}
    for _ in 0..3 {
        tokio::time::sleep(Duration::from_secs(3)).await;
        assert!(
            carried(&a, &b, &mut taken_by_b).await,
            "a to b, after idling"
        );
        tokio::time::sleep(Duration::from_secs(3)).await;
        assert!(
            carried(&b, &a, &mut taken_by_a).await,
            "b to a, after idling"
        );
    }
}