weida 0.1.0-alpha.13

QUIC-native messaging framework: runtime, native QUIC transport, Req/Rep, Push/Pull, Pub/Sub, PAIR, SURVEY and BUS
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
//! Real QUIC and TLS over a simulated network
//! ([0042](../../../docs/decisions/0042-simulated-network.md)).
//!
//! Every runtime here is on one `SimNet`, so nothing opens a socket: identities, refusals,
//! redials and their events are the production code's, and the faults are the network's. The
//! tests marked `start_paused` run on a paused Tokio clock; each prints the wall time its
//! minutes of QUIC and redial time took, as a measurement and not as a bound.

use std::net::SocketAddr;
use std::time::Duration;

use weida::{
    Binding, ClientTls, EndpointAddr, Error, Fingerprint, GiveUp, Identity, Limits, Listener,
    LossCause, Network, PeerEvent, PeerEvents, PeerIdentity, Puller, ReconnectPolicy, Runtime,
    RuntimeConfig, ServerTls, SimNet, TransferMeta, Trust,
};

/// The expected time of a wait on the Tokio clock: generous, because under a paused clock it
/// costs no wall time, and a paused clock reaching it means nothing can run any more.
const WITHIN: Duration = Duration::from_secs(600);

async fn within_paused<F: Future>(f: F) -> F::Output {
    weida_testkit::within("a simulated-network step", WITHIN, f).await
}

/// A runtime on `net` whose redial starts at 5 ms and backs off to 600 s.
fn on(net: &SimNet) -> RuntimeConfig {
    RuntimeConfig {
        network: Network::sim(net),
        reconnect: ReconnectPolicy {
            initial: Duration::from_millis(5),
            max: Duration::from_secs(600),
            ..ReconnectPolicy::default()
        },
        ..RuntimeConfig::default()
    }
}

fn identity() -> (Identity, Fingerprint) {
    let identity = Identity::generate_for(["127.0.0.1"]).expect("identity");
    let fingerprint = identity.fingerprint().expect("fingerprint");
    (identity, fingerprint)
}

/// A QUIC server on the simulated network, stopped and started again on the same address.
struct SimServer {
    runtime: Runtime,
    listener: Listener,
    binding: Binding,
    addr: SocketAddr,
}

impl SimServer {
    async fn start(net: &SimNet, addr: SocketAddr, tls: impl Into<ServerTls>) -> SimServer {
        let runtime = Runtime::new(on(net)).expect("runtime");
        let listener = runtime.listener();
        let binding = listener.bind_quic(addr, tls).await.expect("bind");
        let addr = binding.local_addr();
        SimServer {
            runtime,
            listener,
            binding,
            addr,
        }
    }

    fn url(&self, path: &str, peer: Option<Fingerprint>) -> String {
        EndpointAddr {
            host: "127.0.0.1".into(),
            port: Some(self.addr.port()),
            path: path.into(),
            peer,
        }
        .to_string()
    }

    async fn stop(self) {
        self.binding.close().await;
    }
}

/// The next event that is not `Retrying`.
async fn next_transition(events: &mut PeerEvents) -> PeerEvent {
    within_paused(async {
        loop {
            match events.recv().await.expect("event stream open") {
                PeerEvent::Retrying { .. } => continue,
                event => return event,
            }
        }
    })
    .await
}

async fn pulled(puller: &Puller) -> Vec<u8> {
    let inbound = within_paused(puller.recv()).await.expect("recv");
    within_paused(inbound.collect(64 * 1024))
        .await
        .expect("collect")
}

/// Answers every request on `path` with its own body.
fn echo(server: &SimServer, path: &str) {
    let replier = server.listener.replier(path).expect("replier");
    tokio::spawn(async move {
        while let Ok(mut request) = replier.accept().await {
            let body = request.take_body().collect(1 << 20).await.expect("body");
            let mut reply = request.reply(TransferMeta::default()).await.expect("reply");
            reply.write_all(&body).await.expect("write");
            reply.finish().expect("finish");
        }
    });
}

async fn request(requester: &weida::Requester, body: &[u8]) -> Vec<u8> {
    let reply = within_paused(requester.request(body))
        .await
        .expect("request");
    within_paused(reply.collect(1 << 20)).await.expect("reply")
}

/// Claim: a client's key is proved over the simulated network exactly as over UDP: the server
/// sees `PeerIdentity::Key` of the client, and the client reached the key its URL pins.
#[tokio::test]
async fn a_pinned_client_proves_its_key_over_the_simulated_network() {
    let net = SimNet::new();
    let (server_id, server_fp) = identity();
    let (client_id, client_fp) = identity();
    let server = SimServer::start(
        &net,
        "127.0.0.1:0".parse().expect("addr"),
        ServerTls::new(server_id).require_client(Trust::pin(client_fp)),
    )
    .await;
    let replier = server.listener.replier("/who").expect("replier");
    tokio::spawn(async move {
        while let Ok(request) = replier.accept().await {
            let answer: &[u8] = if request.meta().peer == Some(PeerIdentity::Key(client_fp)) {
                b"ok"
            } else {
                b"anonymous"
            };
            let mut reply = request.reply(TransferMeta::default()).await.expect("reply");
            reply.write_all(answer).await.expect("write");
            reply.finish().expect("finish");
        }
    });

    let client = Runtime::new(on(&net)).expect("client");
    let requester = client.requester(ClientTls::new(Trust::by_address()).with_identity(client_id));
    within_paused(requester.connect(&server.url("/who", Some(server_fp))))
        .await
        .expect("connect");
    assert_eq!(request(&requester, b"who").await, b"ok");
    assert!(
        net.stats().delivered > 0,
        "the datagrams crossed the simulation"
    );

    client.shutdown().await;
    server.runtime.shutdown().await;
}

/// Claim: mTLS refuses a client without a key, and a pin refuses a server with another key,
/// naming the key that answered; the correctly pinned client still connects afterwards.
#[tokio::test]
async fn mtls_refuses_an_anonymous_client_and_a_pin_refuses_another_key() {
    let net = SimNet::new();
    let (server_id, server_fp) = identity();
    let (client_id, client_fp) = identity();
    let (_, other_fp) = identity();
    let server = SimServer::start(
        &net,
        "127.0.0.1:0".parse().expect("addr"),
        ServerTls::new(server_id).require_client(Trust::pin(client_fp)),
    )
    .await;
    echo(&server, "/echo");
    let client = Runtime::new(on(&net)).expect("client");

    let anonymous = client.requester(ClientTls::new(Trust::by_address()));
    let refused = within_paused(anonymous.connect(&server.url("/echo", Some(server_fp)))).await;
    assert!(
        refused.is_err(),
        "an anonymous client is refused: {refused:?}"
    );

    let mispinned =
        client.requester(ClientTls::new(Trust::by_address()).with_identity(client_id.clone()));
    match within_paused(mispinned.connect(&server.url("/echo", Some(other_fp)))).await {
        Err(Error::Untrusted(presented)) => assert_eq!(presented, server_fp),
        other => panic!("expected Untrusted, got {other:?}"),
    }

    let pinned = client.requester(ClientTls::new(Trust::by_address()).with_identity(client_id));
    within_paused(pinned.connect(&server.url("/echo", Some(server_fp))))
        .await
        .expect("the right pin connects");
    assert_eq!(request(&pinned, b"hi").await, b"hi");

    client.shutdown().await;
    server.runtime.shutdown().await;
}

/// Claim: a server closed and bound again on the same address drives the subscriber's events
/// as a restart does over UDP: `Lost { PeerClosed }`, `Connected` for the same key, and
/// `GaveUp { PeerChanged }` for a server with another key.
#[tokio::test(start_paused = true)]
async fn a_server_closed_and_bound_again_drives_the_subscriber_events() {
    let real = std::time::Instant::now();
    let net = SimNet::new();
    let (a_id, a_fp) = identity();
    let (b_id, b_fp) = identity();
    let first = SimServer::start(&net, "127.0.0.1:0".parse().expect("addr"), a_id.clone()).await;
    let addr = first.addr;
    let _publisher = first.listener.publisher("/events").expect("publisher");

    let client = Runtime::new(on(&net)).expect("client");
    let subscriber = client.subscriber(Trust::pin(a_fp).and_pin(b_fp));
    let mut events = subscriber.events();
    within_paused(subscriber.connect(&first.url("/events", None)))
        .await
        .expect("connect");
    assert!(matches!(
        next_transition(&mut events).await,
        PeerEvent::Connected { .. }
    ));

    first.stop().await;
    match next_transition(&mut events).await {
        PeerEvent::Lost { cause, .. } => assert_eq!(cause, LossCause::PeerClosed),
        other => panic!("expected Lost, got {other:?}"),
    }

    let again = SimServer::start(&net, addr, a_id).await;
    let _publisher = again.listener.publisher("/events").expect("publisher");
    assert!(matches!(
        next_transition(&mut events).await,
        PeerEvent::Connected { .. }
    ));

    again.stop().await;
    assert!(matches!(
        next_transition(&mut events).await,
        PeerEvent::Lost { .. }
    ));
    let replaced = SimServer::start(&net, addr, b_id).await;
    let _publisher = replaced.listener.publisher("/events").expect("publisher");
    match next_transition(&mut events).await {
        PeerEvent::GaveUp {
            why: GiveUp::PeerChanged { presented },
            ..
        } => assert_eq!(presented, Some(b_fp)),
        other => panic!("expected GaveUp PeerChanged, got {other:?}"),
    }

    client.shutdown().await;
    replaced.runtime.shutdown().await;
    eprintln!("took {:?} of wall time", real.elapsed());
}

/// Claim: a partition is an unannounced disconnect: the dialler learns of it at the idle
/// timeout, as `LossCause::IdleTimeout`, and once the path heals it redials the same binding
/// and delivers again.
#[tokio::test(start_paused = true)]
async fn a_partition_is_lost_at_the_idle_timeout_and_heal_redials() {
    let real = std::time::Instant::now();
    let net = SimNet::new();
    let (server_id, server_fp) = identity();
    let server = SimServer::start(&net, "127.0.0.1:0".parse().expect("addr"), server_id).await;
    let puller = server.listener.puller("/jobs").expect("puller");

    let client = Runtime::new(on(&net)).expect("client");
    let pusher = client.pusher(Trust::pin(server_fp));
    let mut events = pusher.events();
    within_paused(pusher.connect(&server.url("/jobs", None)))
        .await
        .expect("connect");
    assert!(matches!(
        next_transition(&mut events).await,
        PeerEvent::Connected { .. }
    ));

    let cut = tokio::time::Instant::now();
    net.partition(server.addr);
    match next_transition(&mut events).await {
        PeerEvent::Lost { cause, .. } => assert_eq!(cause, LossCause::IdleTimeout),
        other => panic!("expected Lost, got {other:?}"),
    }
    assert!(
        cut.elapsed() >= Limits::default().idle_timeout,
        "{:?}",
        cut.elapsed()
    );

    net.heal(server.addr);
    assert!(matches!(
        next_transition(&mut events).await,
        PeerEvent::Connected { .. }
    ));
    within_paused(pusher.send(b"after")).await.expect("send");
    assert_eq!(pulled(&puller).await, b"after");

    client.shutdown().await;
    server.runtime.shutdown().await;
    eprintln!("took {:?} of wall time", real.elapsed());
}

/// Claim: a one-way delay costs at least a round trip per request and loses nothing.
#[tokio::test(start_paused = true)]
async fn a_delayed_path_costs_a_round_trip_and_loses_nothing() {
    let real = std::time::Instant::now();
    let net = SimNet::new();
    let (server_id, server_fp) = identity();
    let server = SimServer::start(&net, "127.0.0.1:0".parse().expect("addr"), server_id).await;
    echo(&server, "/echo");
    let client = Runtime::new(on(&net)).expect("client");
    let requester = client.requester(Trust::pin(server_fp));
    within_paused(requester.connect(&server.url("/echo", None)))
        .await
        .expect("connect");

    net.set_delay(server.addr, Duration::from_millis(50));
    let body: Vec<u8> = (0..64 * 1024).map(|i| (i % 251) as u8).collect();
    let start = tokio::time::Instant::now();
    assert_eq!(request(&requester, &body).await, body);
    assert!(
        start.elapsed() >= Duration::from_millis(100),
        "{:?}",
        start.elapsed()
    );

    client.shutdown().await;
    server.runtime.shutdown().await;
    eprintln!("took {:?} of wall time", real.elapsed());
}

/// Claim: datagrams the network drops are QUIC's to retransmit: the exchange completes and the
/// drops are counted.
#[tokio::test(start_paused = true)]
async fn dropped_datagrams_are_retransmitted() {
    let real = std::time::Instant::now();
    let net = SimNet::new();
    let (server_id, server_fp) = identity();
    let server = SimServer::start(&net, "127.0.0.1:0".parse().expect("addr"), server_id).await;
    echo(&server, "/echo");
    let client = Runtime::new(on(&net)).expect("client");
    let requester = client.requester(Trust::pin(server_fp));
    within_paused(requester.connect(&server.url("/echo", None)))
        .await
        .expect("connect");

    let before = net.stats().dropped;
    net.drop_next(server.addr, 3);
    assert_eq!(request(&requester, b"through").await, b"through");
    assert!(net.stats().dropped >= before + 3, "{:?}", net.stats());

    client.shutdown().await;
    server.runtime.shutdown().await;
    eprintln!("took {:?} of wall time", real.elapsed());
}

/// Claim: a connection that stayed up for the policy's `max` restarts the redial schedule, on
/// the runtime's clock: after 1200 s of paused time the next loss is `Retrying { attempt: 1 }`,
/// not the attempt after the last outage's.
#[tokio::test(start_paused = true)]
async fn the_redial_schedule_restarts_after_a_connection_that_stayed_up() {
    let real = std::time::Instant::now();
    let net = SimNet::new();
    let (server_id, server_fp) = identity();
    let first = SimServer::start(
        &net,
        "127.0.0.1:0".parse().expect("addr"),
        server_id.clone(),
    )
    .await;
    let addr = first.addr;
    let _puller = first.listener.puller("/jobs").expect("puller");

    let client = Runtime::new(on(&net)).expect("client");
    let pusher = client.pusher(Trust::pin(server_fp));
    let mut events = pusher.events();
    within_paused(pusher.connect(&first.url("/jobs", None)))
        .await
        .expect("connect");
    assert!(matches!(
        next_transition(&mut events).await,
        PeerEvent::Connected { .. }
    ));

    first.stop().await;
    within_paused(async {
        loop {
            if let Some(PeerEvent::Retrying { attempt: 3, .. }) = events.recv().await {
                break;
            }
        }
    })
    .await;

    let second = SimServer::start(&net, addr, server_id).await;
    let _puller = second.listener.puller("/jobs").expect("puller");
    assert!(matches!(
        next_transition(&mut events).await,
        PeerEvent::Connected { .. }
    ));

    tokio::time::sleep(Duration::from_secs(1200)).await;
    second.stop().await;
    let attempt = within_paused(async {
        loop {
            match events.recv().await.expect("event stream open") {
                PeerEvent::Retrying { attempt, .. } => break attempt,
                PeerEvent::Lost { .. } => continue,
                other => panic!("expected Lost then Retrying, got {other:?}"),
            }
        }
    })
    .await;
    assert_eq!(
        attempt, 1,
        "a connection up for 1200 s earned a fresh schedule"
    );

    client.shutdown().await;
    eprintln!("took {:?} of wall time", real.elapsed());
}

/// Claim: a simulated address is taken while its binding serves and free again once the
/// binding closes, or once its runtime shuts down.
#[tokio::test]
async fn a_bound_address_is_free_again_once_its_binding_closes() {
    let net = SimNet::new();
    let (id, _) = identity();
    let first = SimServer::start(&net, "127.0.0.1:0".parse().expect("addr"), id.clone()).await;
    let addr = first.addr;

    let second = Runtime::new(on(&net)).expect("second");
    let second_listener = second.listener();
    match second_listener.bind_quic(addr, id.clone()).await {
        Err(Error::Io(e)) => assert_eq!(e.kind(), std::io::ErrorKind::AddrInUse),
        other => panic!("expected AddrInUse, got {other:?}"),
    }
    first.stop().await;
    let _held = second_listener
        .bind_quic(addr, id.clone())
        .await
        .expect("free once the binding closed");

    let third = Runtime::new(on(&net)).expect("third");
    let third_listener = third.listener();
    assert!(
        third_listener.bind_quic(addr, id.clone()).await.is_err(),
        "taken by the second runtime"
    );
    second.shutdown().await;
    let _bound = third_listener
        .bind_quic(addr, id)
        .await
        .expect("free once the runtime shut down");
    third.shutdown().await;
}

/// Pushes one body on a fresh pusher with `tls`, waits for its receipt, drops the pusher, and
/// returns the connection the server saw it on.
async fn push_once(
    client: &Runtime,
    tls: ClientTls,
    url: &str,
    puller: &Puller,
) -> weida::ConnectionId {
    let pusher = client.pusher(tls);
    within_paused(pusher.connect(url)).await.expect("connect");
    let mut transfer = within_paused(pusher.open(TransferMeta::default()))
        .await
        .expect("open");
    transfer.write_all(b"once").await.expect("write");
    within_paused(transfer.finish().expect("finish").delivered())
        .await
        .expect("delivered");
    let inbound = within_paused(puller.recv()).await.expect("recv");
    let connection = inbound.connection();
    within_paused(inbound.collect(64)).await.expect("collect");
    connection
}

/// Claim (B-383): a pooled connection nothing uses any more closes after the linger
/// (`Limits::idle_timeout`), so endpoints dialled with throwaway identities and dropped leave
/// the network silent instead of exchanging keep-alives for the runtime's life.
#[tokio::test(start_paused = true)]
async fn dropped_endpoints_leave_the_network_silent_after_the_linger() {
    let net = SimNet::new();
    let (server_id, server_fp) = identity();
    let server = SimServer::start(&net, "127.0.0.1:0".parse().expect("addr"), server_id).await;
    let puller = server.listener.puller("/sink").expect("puller");
    let url = server.url("/sink", Some(server_fp));
    let client = Runtime::new(on(&net)).expect("client");

    push_once(&client, ClientTls::new(Trust::by_address()), &url, &puller).await;
    for _ in 0..3 {
        let throwaway = Identity::generate().expect("identity");
        let tls = ClientTls::new(Trust::by_address()).with_identity(throwaway);
        push_once(&client, tls, &url, &puller).await;
    }

    let linger = Limits::default().idle_timeout;
    tokio::time::sleep(linger * 2).await;
    let quiet_from = net.stats().delivered;
    tokio::time::sleep(Duration::from_secs(120)).await;
    assert_eq!(
        net.stats().delivered,
        quiet_from,
        "no datagram crosses the network once every unused connection closed"
    );

    client.shutdown().await;
    server.runtime.shutdown().await;
}

/// Claim (B-383): within the linger a new endpoint on the same terms reuses the pooled
/// connection; after it, the connection is gone and the next endpoint dials a new one.
#[tokio::test(start_paused = true)]
async fn an_unused_connection_is_reused_within_the_linger_and_not_after() {
    let net = SimNet::new();
    let (server_id, server_fp) = identity();
    let server = SimServer::start(&net, "127.0.0.1:0".parse().expect("addr"), server_id).await;
    let puller = server.listener.puller("/sink").expect("puller");
    let url = server.url("/sink", Some(server_fp));
    let client = Runtime::new(on(&net)).expect("client");
    let tls = || ClientTls::new(Trust::by_address());
    let linger = Limits::default().idle_timeout;

    let first = push_once(&client, tls(), &url, &puller).await;
    tokio::time::sleep(linger / 2).await;
    let again = push_once(&client, tls(), &url, &puller).await;
    assert_eq!(
        again, first,
        "an endpoint within the linger reuses the connection"
    );

    tokio::time::sleep(linger * 2).await;
    let later = push_once(&client, tls(), &url, &puller).await;
    assert_ne!(
        later, first,
        "after the linger the unused connection was closed"
    );

    client.shutdown().await;
    server.runtime.shutdown().await;
}