aggligator 0.9.11

Aggregates multiple links (TCP or similar) into one connection having their combined bandwidth and provides resiliency against failure of individual links.
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
//! Multi-link tests.

use futures::{future, join};
use std::{
    future::IntoFuture,
    num::{NonZeroU32, NonZeroUsize},
    time::Duration,
};

#[cfg(feature = "js")]
use wasm_bindgen_test::wasm_bindgen_test;

use crate::test_data::send_and_verify;
use aggligator::{
    alc::{RecvError, SendError},
    cfg::{Cfg, LinkPing},
    connect::{connect, Server},
    control::DisconnectReason,
    exec::{
        self,
        time::{sleep, timeout},
    },
    TaskError,
};

mod test_channel;
mod test_data;

#[derive(Debug, Clone, Default)]
struct LinkDesc {
    cfg: test_channel::Cfg,
    pause: Option<(usize, Duration)>,
    fail: Option<usize>,
    block: Option<(usize, Duration)>,
}

async fn multi_link_test(
    link_descs: &[LinkDesc], cfg: Cfg, max_size: usize, count: usize, expected_speed: usize, should_fail: bool,
    terminate: Option<usize>,
) {
    let mut server_links = Vec::new();
    let mut client_links = Vec::new();
    let mut a_controls = Vec::new();
    let mut b_controls = Vec::new();

    for ld in link_descs {
        let (link_a_tx, link_a_rx, link_a_control) = test_channel::channel(ld.cfg.clone());
        let (link_b_tx, link_b_rx, link_b_control) = test_channel::channel(ld.cfg.clone());

        server_links.push((link_a_rx, link_b_tx));
        client_links.push((link_b_rx, link_a_tx));
        a_controls.push(link_a_control);
        b_controls.push(link_b_control);
    }

    let server_cfg = cfg.clone();
    let server_task = async move {
        println!("server: starting");
        let server = Server::new(server_cfg);

        println!("server: obtaining listener");
        let mut listener = server.listen().unwrap();

        let mut added_links = Vec::new();
        for (n, (rx, tx)) in server_links.into_iter().enumerate() {
            println!("server: adding incoming link {n}");
            added_links.push(server.add_incoming(tx, rx, format!("{n}"), &[]).await.unwrap());
        }

        println!("server: getting incoming connection");
        let mut incoming = listener.next().await.unwrap();

        let link_names = incoming.link_tags();
        println!("server: links of incoming connection: {link_names:?}");
        assert_eq!(link_names.len(), added_links.len());
        for n in 0..added_links.len() {
            assert!(link_names.iter().any(|name| name.as_str() == format!("{n}")));
        }

        println!("server: accepting incoming connection");
        let (task, ch, mut control) = incoming.accept();
        let task = exec::spawn(task.into_future());
        assert!(!control.is_terminated());

        println!("server: waiting for links");
        timeout(Duration::from_secs(1), async {
            while control.links().len() < added_links.len() {
                control.links_changed().await;
            }
        })
        .await
        .unwrap();

        let links = control.links();
        assert_eq!(links.len(), added_links.len());
        for n in 0..added_links.len() {
            assert!(links.iter().any(|link| link.tag().as_str() == format!("{n}")));
        }
        for link in links {
            assert!(!link.is_disconnected());
            assert!(link.disconnect_reason().is_none());
        }

        println!("server: sending and receiving test data");
        let (tx, mut rx) = ch.into_tx_rx();
        println!("server: maximum send size is {}", tx.max_size());

        let expected_send_err = match (should_fail, terminate) {
            (true, _) => Some(SendError::AllLinksFailed),
            (_, Some(_)) => Some(SendError::TaskTerminated),
            _ => None,
        };
        let expected_recv_err = match (should_fail, terminate) {
            (true, _) => Some(RecvError::AllLinksFailed),
            (_, Some(_)) => Some(RecvError::TaskTerminated),
            _ => None,
        };
        let speed = send_and_verify(
            "server",
            &tx,
            &mut rx,
            0,
            tx.max_size().min(max_size),
            count,
            |i| {
                for (n, desc) in link_descs.iter().enumerate() {
                    if let Some((when, dur)) = desc.pause {
                        if i == when {
                            println!("pausing link a {n}");
                            let ctrl = a_controls[n].clone();
                            exec::spawn(async move {
                                let _ = ctrl.pause_for(dur).await;
                                println!("unpausing link a {n}");
                            });
                        }
                    }
                    if let Some(when) = desc.fail {
                        if i == when {
                            println!("failing link a {n}");
                            let ctrl = a_controls[n].clone();
                            exec::spawn(async move { ctrl.disconnect().await });
                        }
                    }
                    if let Some((when, dur)) = desc.block {
                        if i == when {
                            println!("blocking link a {n}");
                            let link = added_links[n].clone();
                            link.set_blocked(true);
                            assert!(link.is_blocked());
                            exec::spawn(async move {
                                sleep(dur).await;
                                println!("unblocking link a {n}");
                                link.set_blocked(false);
                                assert!(!link.is_blocked());
                            });
                        }
                    }
                }
            },
            expected_send_err,
            expected_recv_err,
        )
        .await;

        println!("server: measured speed is {speed:.1} and expected speed is {expected_speed:.1}");
        #[cfg(not(debug_assertions))]
        if terminate.is_none() {
            assert!(speed as usize >= expected_speed, "server too slow");
        }

        for (n, (link, desc)) in added_links.iter().zip(link_descs).enumerate() {
            println!("server: link status {n}: {:?}", link.disconnect_reason());
            if desc.fail.is_some() {
                if !link.is_disconnected() {
                    println!("server: waiting for link {n} disconnect");
                }
                link.disconnected().await;
                match link.disconnect_reason() {
                    Some(reason) if reason.should_reconnect() => (),
                    other => panic!("no or wrong disconnect reason: {other:?}"),
                }
            } else if terminate.is_some() {
                if !link.is_disconnected() {
                    println!("server: waiting for link {n} disconnect");
                }
                link.disconnected().await;
                assert!(matches!(link.disconnect_reason(), Some(DisconnectReason::TaskTerminated)));
            } else {
                assert!(!link.is_disconnected());
            }
        }

        println!("server: dropping sender");
        drop(tx);

        if !should_fail && terminate.is_none() {
            println!("server: waiting for receive end");
            assert_eq!(rx.recv().await.unwrap(), None);
        }

        println!("server: waiting for termination notification");
        let result = control.terminated().await;
        if should_fail || terminate.is_some() {
            result.expect_err("control did not fail");
        } else {
            result.expect("control failed");
        }
        assert!(control.is_terminated());

        for (n, link) in added_links.iter().enumerate() {
            println!("server: waiting for link disconnect notification {n}");
            link.disconnected().await;
            let stats = link.stats();
            println!("server: Link {n} stats: {stats:?}");
        }

        println!("server: waiting for task termination");
        let result = task.await.unwrap();
        if !should_fail && terminate.is_none() {
            result.expect("server task failed");
            println!("server: done");
        } else {
            let err = result.expect_err("server task did not fail");
            println!("server error: {err}");
            if terminate.is_some() {
                assert!(matches!(err, TaskError::Terminated));
            }
        }
    };

    let client_task = async move {
        println!("client: starting outgoing link");
        let (task, outgoing, mut control) = connect(cfg);
        let task = exec::spawn(task.into_future());

        let mut added_links_tasks = Vec::new();
        for (n, (rx, tx)) in client_links.into_iter().enumerate() {
            println!("client: adding outgoing link {n}");
            added_links_tasks.push(control.add(tx, rx, format!("{n}"), &[]));
        }
        let added_links = future::try_join_all(added_links_tasks).await.unwrap();

        println!("client: waiting for links");
        timeout(Duration::from_secs(1), async {
            while control.links().len() < added_links.len() {
                control.links_changed().await;
            }
        })
        .await
        .unwrap();

        println!("client: checking link info");
        let links = control.links();
        println!("client: links of outgoing connection: {links:?}");
        assert_eq!(links.len(), added_links.len());
        for n in 0..added_links.len() {
            assert!(links.iter().any(|link| link.tag().as_str() == format!("{n}")));
        }
        for link in links {
            assert!(!link.is_disconnected());
            assert!(link.disconnect_reason().is_none());
        }

        println!("client: establishing connection");
        let ch = outgoing.connect().await.unwrap();

        println!("client: sending and receiving test data");
        let (tx, mut rx) = ch.into_tx_rx();

        let expected_send_err = match (should_fail, terminate) {
            (true, _) => Some(SendError::AllLinksFailed),
            (_, Some(_)) => Some(SendError::TaskTerminated),
            _ => None,
        };
        let expected_recv_err = match (should_fail, terminate) {
            (true, _) => Some(RecvError::AllLinksFailed),
            (_, Some(_)) => Some(RecvError::TaskTerminated),
            _ => None,
        };
        let speed = send_and_verify(
            "client",
            &tx,
            &mut rx,
            0,
            tx.max_size().min(max_size),
            count,
            |i| {
                for (n, desc) in link_descs.iter().enumerate() {
                    if let Some((when, dur)) = desc.pause {
                        if i == when {
                            println!("pausing link b {n}");
                            let ctrl = b_controls[n].clone();
                            exec::spawn(async move {
                                let _ = ctrl.pause_for(dur).await;
                                println!("unpausing link b {n}");
                            });
                        }
                    }
                    if let Some(when) = desc.fail {
                        if i == when {
                            println!("failing link b {n}");
                            let ctrl = b_controls[n].clone();
                            exec::spawn(async move { ctrl.disconnect().await });
                        }
                    }
                }

                match terminate {
                    Some(terminate) if terminate == i => {
                        println!("client: forcefully terminating connection");
                        control.terminate();
                    }
                    _ => (),
                }
            },
            expected_send_err,
            expected_recv_err,
        )
        .await;

        println!("client: measured speed is {speed:.1} and expected speed is {expected_speed:.1}");
        #[cfg(not(debug_assertions))]
        if terminate.is_none() {
            assert!(speed as usize >= expected_speed, "client too slow");
        }

        println!("client: dropping sender");
        drop(tx);

        println!("client: waiting for termination notification");
        let result = control.terminated().await;
        if should_fail || terminate.is_some() {
            result.expect_err("control did not fail");
        } else {
            result.expect("control failed");
        }
        assert!(control.is_terminated());

        println!("client: waiting for task termination");
        let result = task.await.unwrap();
        if !should_fail && terminate.is_none() {
            result.expect("client task failed");
            println!("client: task done");
        } else {
            let err = result.expect_err("client task did not fail");
            println!("client error: {err}");
            if terminate.is_some() {
                assert!(matches!(err, TaskError::Terminated));
            }
        }

        for (n, (link, desc)) in added_links.iter().zip(link_descs).enumerate() {
            println!("client: link status {n} (name: {}): {:?}", link.tag(), link.disconnect_reason());
            if desc.fail.is_some() {
                if !link.is_disconnected() {
                    println!("client: waiting for link {n} disconnect");
                }
                link.disconnected().await;
                match link.disconnect_reason() {
                    Some(reason) if reason.should_reconnect() => (),
                    Some(DisconnectReason::ConnectionClosed) => (),
                    other => panic!("no or wrong disconnect reason: {other:?}"),
                }
            } else if terminate.is_some() {
                if !link.is_disconnected() {
                    println!("client: waiting for link {n} disconnect");
                }
                link.disconnected().await;
                assert!(matches!(link.disconnect_reason(), Some(DisconnectReason::TaskTerminated)));
            }
        }

        for (n, link) in added_links.iter().enumerate() {
            println!("client: waiting for link disconnect notification {n}");
            link.disconnected().await;
            let stats = link.stats();
            println!("client: Link {n} stats: {stats:?}");
        }

        println!("client: done");
    };

    join!(server_task, client_task);
}

#[cfg_attr(not(feature = "js"), test_log::test(tokio::test(flavor = "multi_thread")))]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn five_x_unlimited_multi_thread() {
    let link_desc = LinkDesc {
        cfg: test_channel::Cfg { speed: 0, latency: None, ..Default::default() },
        ..Default::default()
    };
    let link_descs: Vec<_> = std::iter::repeat_n(link_desc, 5).collect();
    let alc_cfg = Cfg { ..Default::default() };

    multi_link_test(&link_descs, alc_cfg, 16384, 10000, 10_000_000, false, None).await;
}

#[cfg_attr(not(feature = "js"), test_log::test(tokio::test(flavor = "current_thread")))]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn five_x_unlimited_current_thread() {
    let link_desc = LinkDesc {
        cfg: test_channel::Cfg { speed: 0, latency: None, ..Default::default() },
        ..Default::default()
    };
    let link_descs: Vec<_> = std::iter::repeat_n(link_desc, 5).collect();
    let alc_cfg = Cfg { ..Default::default() };

    multi_link_test(&link_descs, alc_cfg, 16384, 10000, 10_000_000, false, None).await;
}

#[cfg_attr(not(feature = "js"), test_log::test(tokio::test(flavor = "multi_thread")))]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn five_x_very_high_latency() {
    let link_desc = LinkDesc {
        cfg: test_channel::Cfg {
            speed: 10_000_000,
            latency: Some(Duration::from_millis(1000)),
            buffer_size: 10_000_000,
            buffer_items: 50_000,
        },
        ..Default::default()
    };
    let link_descs: Vec<_> = std::iter::repeat_n(link_desc, 5).collect();

    let alc_cfg = Cfg {
        send_buffer: NonZeroU32::new(20_000_000).unwrap(),
        recv_buffer: NonZeroU32::new(20_000_000).unwrap(),
        send_queue: NonZeroUsize::new(50).unwrap(),
        recv_queue: NonZeroUsize::new(50).unwrap(),
        link_ack_timeout_max: Duration::from_secs(15),
        link_non_working_timeout: Duration::from_secs(30),
        link_unacked_init: NonZeroUsize::new(10_000_000).unwrap(),
        ..Default::default()
    };

    multi_link_test(&link_descs, alc_cfg, 16384, 30000, 4_000_000, false, None).await;
}

#[cfg_attr(not(feature = "js"), test_log::test(tokio::test(flavor = "multi_thread")))]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn five_x_blocked() {
    let link_desc = LinkDesc {
        cfg: test_channel::Cfg { speed: 0, latency: None, ..Default::default() },
        ..Default::default()
    };
    let mut link_descs: Vec<_> = std::iter::repeat_n(link_desc, 5).collect();

    link_descs[0].block = Some((0, Duration::from_secs(1)));
    link_descs[1].block = Some((1000, Duration::from_secs(1)));
    link_descs[2].block = Some((2000, Duration::from_secs(1)));
    link_descs[3].block = Some((5000, Duration::from_secs(1)));
    link_descs[4].block = Some((9990, Duration::from_secs(1)));

    let alc_cfg = Cfg { ..Default::default() };

    multi_link_test(&link_descs, alc_cfg, 16384, 10000, 10_000_000, false, None).await;
}

#[cfg_attr(not(feature = "js"), test_log::test(tokio::test(flavor = "multi_thread")))]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn ten_x_hundert_kb_per_s() {
    let link_desc = LinkDesc {
        cfg: test_channel::Cfg {
            speed: 100_000,
            latency: Some(Duration::from_millis(10)),
            buffer_size: 4096,
            ..Default::default()
        },
        ..Default::default()
    };
    let link_descs: Vec<_> = std::iter::repeat_n(link_desc, 10).collect();

    let alc_cfg = Cfg { ..Default::default() };

    multi_link_test(&link_descs, alc_cfg, 16384, 100, 500_000, false, None).await;
}

#[cfg_attr(not(feature = "js"), test_log::test(tokio::test(flavor = "multi_thread")))]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn ten_x_paused_link() {
    let link_desc = LinkDesc {
        cfg: test_channel::Cfg {
            speed: 1_000_000,
            latency: Some(Duration::from_millis(10)),
            buffer_size: 100_000,
            ..Default::default()
        },
        ..Default::default()
    };
    let mut link_descs = Vec::new();
    for n in 0..10 {
        link_descs.push(LinkDesc { pause: Some((n * 100, Duration::from_secs(3))), ..link_desc.clone() });
    }

    let alc_cfg = Cfg { link_retest_interval: Duration::from_secs(2), ..Default::default() };

    multi_link_test(&link_descs, alc_cfg, 16384, 10_000, 3_000_000, false, None).await;
}

#[cfg_attr(not(feature = "js"), test_log::test(tokio::test(flavor = "multi_thread")))]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn ten_x_failed_link() {
    let link_desc = LinkDesc {
        cfg: test_channel::Cfg {
            speed: 1_000_000,
            latency: Some(Duration::from_millis(10)),
            buffer_size: 100_000,
            ..Default::default()
        },
        ..Default::default()
    };
    let mut link_descs = Vec::new();
    for n in 0..10 {
        link_descs.push(LinkDesc {
            pause: if n % 2 == 0 { Some((n * 100, Duration::from_secs(1))) } else { None },
            fail: if n != 9 { Some(n * 100 + 50) } else { None },
            ..link_desc.clone()
        });
    }

    let alc_cfg = Cfg {
        link_retest_interval: Duration::from_secs(2),
        no_link_timeout: Duration::from_secs(10),
        ..Default::default()
    };

    timeout(Duration::from_secs(60), multi_link_test(&link_descs, alc_cfg, 16384, 2_000, 500_000, false, None))
        .await
        .unwrap();
}

#[cfg_attr(not(feature = "js"), test_log::test(tokio::test(flavor = "multi_thread")))]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn ten_x_all_failed_link() {
    let link_desc = LinkDesc {
        cfg: test_channel::Cfg {
            speed: 1_000_000,
            latency: Some(Duration::from_millis(10)),
            buffer_size: 100_000,
            ..Default::default()
        },
        ..Default::default()
    };
    let mut link_descs = Vec::new();
    for n in 0..10 {
        link_descs.push(LinkDesc {
            pause: if n % 2 == 0 { Some((n * 100, Duration::from_secs(1))) } else { None },
            fail: Some(n * 100 + 50),
            ..link_desc.clone()
        });
    }

    let alc_cfg = Cfg {
        link_retest_interval: Duration::from_secs(2),
        no_link_timeout: Duration::from_secs(5),
        ..Default::default()
    };

    multi_link_test(&link_descs, alc_cfg, 16384, 2_000, 0, true, None).await;
}

#[cfg_attr(not(feature = "js"), test_log::test(tokio::test(flavor = "multi_thread")))]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn ten_x_link_timeout() {
    let link_desc = LinkDesc {
        cfg: test_channel::Cfg {
            speed: 1_000_000,
            latency: Some(Duration::from_millis(10)),
            buffer_size: 100_000,
            ..Default::default()
        },
        ..Default::default()
    };
    let mut link_descs = Vec::new();
    for n in 0..10 {
        link_descs.push(LinkDesc {
            pause: if n != 9 { Some((n * 100, Duration::from_secs(10000))) } else { None },
            fail: if n != 9 { Some(1_000_000) } else { None },
            ..link_desc.clone()
        });
    }

    let alc_cfg = Cfg {
        link_ping_timeout: Duration::from_secs(10),
        link_non_working_timeout: Duration::from_secs(5),
        link_retest_interval: Duration::from_secs(2),
        no_link_timeout: Duration::from_secs(10),
        link_ping: LinkPing::WhenIdle(Duration::from_secs(1)),
        ..Default::default()
    };

    timeout(Duration::from_secs(60), multi_link_test(&link_descs, alc_cfg, 16384, 3_000, 0, false, None))
        .await
        .unwrap();
}

#[cfg_attr(not(feature = "js"), test_log::test(tokio::test(flavor = "multi_thread")))]
#[cfg_attr(feature = "js", wasm_bindgen_test)]
async fn forceful_termination() {
    let link_desc = LinkDesc {
        cfg: test_channel::Cfg {
            speed: 10_000_000,
            latency: Some(Duration::from_millis(1000)),
            buffer_size: 10_000_000,
            buffer_items: 50_000,
        },
        ..Default::default()
    };
    let link_descs: Vec<_> = std::iter::repeat_n(link_desc, 5).collect();

    let alc_cfg = Cfg {
        send_buffer: NonZeroU32::new(20_000_000).unwrap(),
        recv_buffer: NonZeroU32::new(20_000_000).unwrap(),
        send_queue: NonZeroUsize::new(50).unwrap(),
        recv_queue: NonZeroUsize::new(50).unwrap(),
        link_ack_timeout_max: Duration::from_secs(15),
        link_non_working_timeout: Duration::from_secs(30),
        link_unacked_init: NonZeroUsize::new(10_000_000).unwrap(),
        ..Default::default()
    };

    multi_link_test(&link_descs, alc_cfg, 16384, 30000, 4_000_000, false, Some(10000)).await;
}