gtether 0.2.3

Highly concurrent multiplayer focused game engine, with an emphasis on realtime streamable asset management.
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
//! OSI layer 4 (transport) driver traits.
//!
//! This module contains the traits that are required to implement for [Networking] stack transport
//! layer drivers. These drivers control the OSI layer 4 (transport) implementation that a
//! Networking stack uses, an example being an implementation for
//! [GNS](https://github.com/ValveSoftware/GameNetworkingSockets), found in the [`gns`](super::gns)
//! module. For further details on the overall Networking stack structure, see the
//! [parent module](super).
//!
//! # Implementing
//!
//! Drivers pick and choose which traits they want to implement from this module. Each trait
//! describes a particular functionality or set of functionality that that driver will support. When
//! creating a [Networking] stack, the traits that the driver implements will expose the relevant
//! functionality on the Networking stack.
//!
//! At the very basic level, every driver is required to implement [NetDriver], which simply
//! describes how to "close" a driver. What this means is up to the driver, but once closed it is
//! not expected to be used again, and most functionality should yield [NetworkingError::Closed]
//! errors.
//!
//! Further functionality can be described by the following:
//!  * [NetDriverConnect] - The driver can connect to remote endpoints.
//!  * [NetDriverListen] - The driver can bind to and listen on sockets.
//!  * [NetDriverSend] - The driver can send to a single remote endpoint. This is typically
//!    implemented on client drivers in client/server setups, where the client only has one endpoint
//!    to connect to.
//!  * [NetDriverSendTo] - The driver can send to specific remote endpoints.
//!  * [NetDriverBroadcast] - The driver can broadcast to all connected endpoints.
//!
//! See each of these traits for more details.
//!
//! In addition, creation of drivers is described by an implementation of [NetDriverFactory]. This
//! factory implementation is what will be given to a [Networking] stack during construction, so
//! there should be a valid implementation for your driver.

use async_trait::async_trait;
use flagset::FlagSet;
use std::net::SocketAddr;
use std::sync::Arc;

use crate::net::message::MessageFlags;
use crate::net::{Connection, NetworkingApi, NetworkingError};

/// Lowest level [Networking][net] driver trait.
///
/// Every [Networking][net] driver is required to implement this trait.
///
/// [net]: super::Networking
#[async_trait]
pub trait NetDriver: Send + Sync + 'static {
    /// "Close" this driver.
    ///
    /// What this means is up to the driver, but once closed most methods should no longer function,
    /// and instead yield [NetworkingError::Closed] errors.
    ///
    /// Note that the driver may be "re-opened" e.g. by successive
    /// [`connect()`](NetDriverConnect::connect)/[`listen()`](NetDriverListen::listen) calls, if the
    /// driver wishes to allow such functionality.
    async fn close(&self);
}

/// Trait describing a [Networking](super::Networking) driver that can connect to remote endpoints.
///
/// How many endpoints can be connected to is up to the particular driver. For example, a
/// client/server architecture may only allow a client to connect to one server at a time, whereas
/// a peer-to-peer architecture may allow clients to connect to many other clients at once.
#[async_trait]
pub trait NetDriverConnect: NetDriver {
    /// Attempt to connect to the remote `socket_addr`.
    ///
    /// At this point in a connection workflow, the [Networking](super::Networking) stack has
    /// already generated and initialized a [Connection] ID, but the driver is responsible for
    /// performing the actual connection logic.
    ///
    /// If an existing connection needs to be closed before a new one can be connected, it is the
    /// responsibility of the driver to handle closing the existing connection.
    async fn connect(
        &self,
        connection: Connection,
        socket_addr: SocketAddr,
    ) -> Result<(), NetworkingError>;
}

/// Trait describing a [Networking](super::Networking) driver that can close individual
/// [Connections](Connection).
///
/// For drivers that can support multiple active connections at once, such as servers in
/// client/server architectures or clients in peer-to-peer architectures, this allows specific
/// individual connections to be closed without closing all connections.
#[async_trait]
pub trait NetDriverCloseConnection: NetDriver {
    /// Close the specified [Connection].
    ///
    /// If there is no connection for the specified [Connection] ID, this method is expected to be
    /// a noop.
    async fn close_connection(
        &self,
        connection: Connection,
    );
}

/// Trait describing a [Networking](super::Networking) driver that can bind to and listen on
/// sockets.
///
/// Generally, a driver only listens on one socket at a time, but this implementation is up to the
/// driver, and drivers can choose to allow multiple listens if they wish.
#[async_trait]
pub trait NetDriverListen: NetDriver {
    /// Bind to and listen on a socket.
    ///
    /// If an existing binding needs to be closed before a new one can be opened, it is the
    /// responsibility of the driver to handle closing the existing binding.
    async fn listen(
        &self,
        socket_addr: SocketAddr,
    ) -> Result<(), NetworkingError>;
}

/// Trait describing a [Networking](super::Networking) driver that can send messages.
///
/// This trait describes sending messages to exactly one endpoint, and therefore is only appropriate
/// if the driver can only have one connection. If the driver can have multiple connections,
/// [NetDriverSendTo] is a more appropriate trait.
pub trait NetDriverSend: NetDriver {
    /// Send raw message data.
    ///
    /// This method is expected to not block or otherwise wait. If blocking behavior is needed, it
    /// should be handed off to a separate thread or other non-blocking mechanism.
    fn send(
        &self,
        msg: Vec<u8>,
        flags: FlagSet<MessageFlags>,
    ) -> Result<(), NetworkingError>;
}

/// Trait describing a [Networking](super::Networking) driver that can send messages to endpoints.
///
/// This trait describes sending messages to specified endpoints. If the driver can only have a
/// single connection, [NetDriverSend] may be more appropriate.
pub trait NetDriverSendTo: NetDriver {
    /// Send raw message data to a specified connection.
    ///
    /// This method is expected to not block or otherwise wait. If blocking behavior is needed, it
    /// should be handed off to a separate thread or other non-blocking mechanism.
    fn send_to(
        &self,
        connection: Connection,
        msg: Vec<u8>,
        flags: FlagSet<MessageFlags>,
    ) -> Result<(), NetworkingError>;
}

/// Trait describing a [Networking](super::Networking) driver that can broadcast messages to all
/// connected endpoints.
///
/// This trait describes the capability to send a single message to all connections. This is
/// generally applicable for any driver that can have many connections.
pub trait NetDriverBroadcast: NetDriver {
    /// Send raw message data to all connections.
    fn broadcast(
        &self,
        msg: Vec<u8>,
        flags: FlagSet<MessageFlags>,
    ) -> Result<(), NetworkingError>;
}

/// Trait describing how to create a [Networking][net] driver.
///
/// This trait is what a [Networking][net] stack is created with, instead of a driver directly. This
/// allows the [Networking][net] stack to create a [NetworkingApi] to give to this factory.
///
/// Note that this trait is automatically implemented on any function with the following signature:
/// ```text
/// Fn(Arc<NetworkingApi>) -> Arc<D> where D: NetDriver
/// ```
///
/// [net]: super::Networking
pub trait NetDriverFactory<D: NetDriver> {
    /// Create a [NetDriver] using the given [NetworkingApi] instance.
    fn create(&self, api: Arc<NetworkingApi>) -> Arc<D>;
}

impl<D, F> NetDriverFactory<D> for F
where
    D: NetDriver,
    F: Fn(Arc<NetworkingApi>) -> Arc<D>,
{
    fn create(&self, api: Arc<NetworkingApi>) -> Arc<D> {
        self(api)
    }
}

/// "No-Operation" [NetDriver].
///
/// This basic [NetDriver] implementation represents "no" networking, and can be used where
/// networking is not actively required.
///
/// [NetDriverFactory] is implemented directly on this type, so an instance of this type can be
/// used as a factory for itself.
pub struct NoNetDriver;

impl NoNetDriver {
    /// Create a new NoNetDriver.
    #[inline]
    pub fn new() -> Arc<Self> {
        Arc::new(Self {})
    }
}

#[async_trait]
impl NetDriver for NoNetDriver {
    async fn close(&self) {
        /* noop */
    }
}

impl NetDriverFactory<NoNetDriver> for Arc<NoNetDriver> {
    #[inline]
    fn create(&self, _api: Arc<NetworkingApi>) -> Arc<NoNetDriver> {
        self.clone()
    }
}

/// Re-usable [NetDriver] test infrastructure.
///
/// This module contains helper structs and functions that can be used to test [NetDriver]
/// implementations and ensure they follow required specification.
///
/// While you can use these helpers directly to create your own tests, it is recommended to instead
/// use the provided macros to generate tests for your implementation. See the following:
///  * [`test_net_driver_client_server_core!`]
///  * [`test_net_driver_client_server_send!`]
///  * [`test_net_driver_client_server_send_to!`]
///  * [`test_net_driver_client_server_broadcast!`]
#[cfg(test)]
pub mod tests {
    use ahash::HashMap;
    use bitcode::{Decode, Encode};
    use educe::Educe;
    use parking_lot::{Mutex, RwLock};
    use smol::future;
    use smol::future::FutureExt;
    use std::convert::Infallible;
    use std::fmt;
    use std::fmt::{Debug, Display, Formatter};
    use std::future::Future;
    use std::net::Ipv4Addr;
    use std::pin::Pin;
    use std::sync::atomic::{AtomicU64, Ordering};
    use std::task::{Context, Poll, Waker};
    use std::time::{Duration, Instant};
    use tracing::debug;

    use crate::event::{Event, EventHandler};
    use crate::net::message::{Message, MessageBody};
    use crate::net::{Networking, NetworkingConnectEvent, NetworkingDisconnectEvent};

    use super::*;

    pub use gtether_derive::{
        test_net_driver_client_server_broadcast,
        test_net_driver_client_server_core,
        test_net_driver_client_server_send,
        test_net_driver_client_server_send_to,
    };

    /// Prelude containing all *Ext traits from this module.
    pub mod prelude {
        pub use super::{
            ClientServerStackFactoryExt,
            ConnectionPairSliceExt,
            NetTestBroadcastSliceExt,
            NetTestConnectSliceExt,
            NetTestSliceExt,
            TestConnectionSendSliceExt,
            TestConnectionSendToSliceExt,
            TestConnectionSliceExt,
        };
    }

    struct Timeout {
        time: Duration,
        deadline: Instant,
    }

    impl Timeout {
        fn new(time: Duration) -> Self {
            let deadline = Instant::now() + time;
            Self {
                time,
                deadline,
            }
        }

        fn run<T>(
            &self,
            fut: impl Future<Output = T>,
            context: impl AsRef<str>,
            extra: Option<fmt::Arguments>,
        ) -> T {
            let timeout_fn = async move {
                smol::Timer::at(self.deadline).await;
                match extra {
                    Some(extra) =>
                        panic!("Timeout ({:?}) reached while: {}; {}", self.time, context.as_ref(), extra),
                    None =>
                        panic!("Timeout ({:?}) reached while: {}", self.time, context.as_ref()),
                }
            };
            future::block_on(fut.or(timeout_fn))
        }
    }

    /// Simple [Message] that contains a [String].
    #[derive(Encode, Decode, MessageBody, Debug)]
    #[message_flag(Reliable)]
    pub struct TestMessage {
        pub value: String,
    }

    impl TestMessage {
        #[inline]
        pub fn new(value: impl Into<String>) -> Self {
            Self {
                value: value.into(),
            }
        }
    }

    /// Simple repliable [Message] that contains a [String].
    #[derive(Encode, Decode, MessageBody, Debug)]
    #[message_flag(Reliable)]
    #[message_reply(TestMessage)]
    pub struct TestMessageRepliable {
        pub value: String
    }

    impl TestMessageRepliable {
        #[inline]
        pub fn new(value: impl Into<String>) -> Self {
            Self {
                value: value.into(),
            }
        }
    }

    async fn execute_futures(futures: impl Iterator<Item=impl Future>) {
        let ex = smol::LocalExecutor::new();
        let tasks = futures
            .map(|fut| ex.spawn(fut))
            .collect::<Vec<_>>();
        ex.run(async {
            for task in tasks {
                task.await;
            }
        }).await;
    }

    /// Asserts that a given [NetworkingError] is equivalent to another.
    #[inline]
    pub fn assert_networking_error_eq(actual: NetworkingError, expected: &NetworkingError) {
        match expected {
            NetworkingError::InvalidAddress(expected_socket_addr) =>
                assert_matches!(actual, NetworkingError::InvalidAddress(socket_addr) if socket_addr == *expected_socket_addr),
            NetworkingError::InvalidConnection(expected_connection) =>
                assert_matches!(actual, NetworkingError::InvalidConnection(connection) if connection == *expected_connection),
            NetworkingError::Closed =>
                assert_matches!(actual, NetworkingError::Closed),
            NetworkingError::Cancelled =>
                assert_matches!(actual, NetworkingError::Cancelled),
            other => panic!("Unsupported expected error type: {other:?}"),
        }
    }

    /// ID used to identify [NetTest] instances.
    #[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
    pub struct NetTestId(u64);

    static NEXT_NET_TEST_ID: AtomicU64 = AtomicU64::new(1);

    impl NetTestId {
        fn new() -> Self {
            Self(NEXT_NET_TEST_ID.fetch_add(1, Ordering::SeqCst))
        }
    }

    impl Display for NetTestId {
        #[inline]
        fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
            write!(f, "net-test-{}", self.0)
        }
    }

    fn fmt_record_data(
        data: &RwLock<HashMap<Connection, HashMap<String, usize>>>,
        f: &mut Formatter<'_>,
    ) -> fmt::Result {
        let data = data.read();
        f.debug_map()
            .entries(data.iter().map(|(connection, stats)| {
                (connection.to_string(), stats)
            }))
            .finish()
    }

    #[derive(Educe)]
    #[educe(Debug)]
    struct Records {
        #[educe(Debug(method(std::fmt::Display::fmt)))]
        id: NetTestId,
        #[educe(Debug(method(fmt_record_data)))]
        inner: RwLock<HashMap<Connection, HashMap<String, usize>>>,
        #[educe(Debug(ignore))]
        wakers: Mutex<Vec<Waker>>,
    }

    impl Records {
        fn new(id: NetTestId) -> Self {
            Self {
                id,
                inner: RwLock::default(),
                wakers: Mutex::default(),
            }
        }

        fn record_message(&self, connection: Connection, msg: String) {
            debug!(id = %self.id, from = %connection, ?msg, "Recording message");
            let mut wakers = self.wakers.lock();
            let mut records = self.inner.write();
            let values: &mut HashMap<String, usize> = records.entry(connection).or_default();
            let value_count = values.entry(msg).or_default();
            *value_count += 1;
            let waker_count = wakers.len();
            for waker in wakers.drain(0..waker_count) {
                waker.wake();
            }
        }

        fn message_count_for_connection(
            &self,
            connection: Connection,
            value: impl AsRef<str>,
        ) -> usize {
            let records = self.inner.read();
            records.get(&connection)
                .map(|values| {
                    values.get(value.as_ref()).map(|v| *v).unwrap_or(0)
                })
                .unwrap_or(0)
        }

        fn wait_for_message_count_for_connection(
            self: &Arc<Self>,
            connection: Connection,
            value: impl AsRef<str>,
            count: usize,
        ) -> RecordCountFuture {
            let msg = value.as_ref().to_string();
            RecordCountFuture {
                count_type: RecordCountFutureType::ForConnection { connection, msg },
                threshold: count,
                records: self.clone(),
            }
        }

        fn message_count(&self, value: impl AsRef<str>) -> usize {
            let records = self.inner.read();
            records.values().map(|values| {
                values.get(value.as_ref()).map(|v| *v).unwrap_or(0)
            }).sum()
        }

        fn wait_for_message_count(
            self: &Arc<Self>,
            value: impl AsRef<str>,
            count: usize,
        ) -> RecordCountFuture {
            let msg = value.as_ref().to_string();
            RecordCountFuture {
                count_type: RecordCountFutureType::ForMessage { msg },
                threshold: count,
                records: self.clone(),
            }
        }

        fn total_message_count(&self) -> usize {
            let records = self.inner.read();
            records.values().map(|values| {
                values.values().sum::<usize>()
            }).sum()
        }

        fn wait_for_total_message_count(
            self: &Arc<Self>,
            count: usize,
        ) -> RecordCountFuture {
            RecordCountFuture {
                count_type: RecordCountFutureType::Total,
                threshold: count,
                records: self.clone(),
            }
        }

        fn clear(&self) {
            self.inner.write().clear();
        }
    }

    enum RecordCountFutureType {
        ForConnection {
            connection: Connection,
            msg: String,
        },
        ForMessage {
            msg: String,
        },
        Total,
    }

    struct RecordCountFuture {
        count_type: RecordCountFutureType,
        threshold: usize,
        records: Arc<Records>,
    }

    impl Future for RecordCountFuture {
        type Output = usize;

        fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
            let mut wakers = self.records.wakers.lock();

            let count = match &self.count_type {
                RecordCountFutureType::ForConnection { connection, msg } =>
                    self.records.message_count_for_connection(*connection, msg),
                RecordCountFutureType::ForMessage { msg } =>
                    self.records.message_count(msg),
                RecordCountFutureType::Total =>
                    self.records.total_message_count(),
            };

            if count >= self.threshold {
                Poll::Ready(count)
            } else {
                wakers.push(cx.waker().clone());
                Poll::Pending
            }
        }
    }

    struct NetworkingClosedFuture<D: NetDriver> {
        net: Arc<Networking<D>>,
        connection: Connection,
        #[allow(unused)]
        event_handler: Arc<dyn EventHandler<NetworkingDisconnectEvent>>,
        waker: Arc<Mutex<Waker>>,
    }

    impl<D: NetDriver> Future for NetworkingClosedFuture<D> {
        type Output = ();

        fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
            let mut waker = self.waker.lock();
            if self.net.connection_info(&self.connection).is_none() {
                Poll::Ready(())
            } else {
                *waker = cx.waker().clone();
                Poll::Pending
            }
        }
    }

    /// Wrapper around [Networking] that enables enhanced testing capabilities.
    ///
    /// Provides access to the wrapped [Networking] instance, but also provides methods to assert
    /// on various conditions or actions.
    #[derive(Educe)]
    #[educe(Debug)]
    pub struct NetTest<D: NetDriver> {
        #[educe(Debug(method(std::fmt::Display::fmt)))]
        id: NetTestId,
        #[educe(Debug(ignore))]
        net: Arc<Networking<D>>,
        records: Arc<Records>,
    }

    impl<D: NetDriver> NetTest<D> {
        pub fn new(driver_factory: impl NetDriverFactory<D>) -> Self {
            let id = NetTestId::new();
            let net = Arc::new(Networking::new(driver_factory));
            let records = Arc::new(Records::new(id));

            let handler_records = records.clone();
            net.insert_msg_handler(move |connection, msg: Message<TestMessage>| {
                let value = msg.body().value.clone();
                handler_records.record_message(connection, value);
                Ok::<_, Infallible>(())
            });

            Self {
                id,
                net,
                records,
            }
        }

        #[inline]
        pub fn net(&self) -> &Arc<Networking<D>> {
            &self.net
        }

        /// Waits for the given [Connection] to be closed.
        ///
        /// If the [Connection] is already closed (or never opened), yields immediately.
        ///
        /// Does not actively close the connection if it is open; only waits for it to be closed.
        pub async fn wait_for_connection_closed(&self, connection: Connection) {
            let waker = Arc::new(Mutex::new(Waker::noop().clone()));
            let event_waker = waker.clone();
            let event_handler = Arc::new(move |_: &mut Event<NetworkingDisconnectEvent>| {
                event_waker.lock().wake_by_ref();
            });
            self.net().event_bus().register(Arc::downgrade(&event_handler))
                .expect("NetworkingDisconnectEvent type should be valid");
            NetworkingClosedFuture {
                net: self.net.clone(),
                connection,
                event_handler: event_handler as _,
                waker,
            }.await;
        }

        /// Clear all message records.
        pub fn clear_records(&self) {
            self.records.clear();
        }

        /// Asserts that the total amount of messages that have been received by this [NetTest]
        /// equals the given `count`.
        pub fn assert_total_message_count(&self, count: usize) {
            assert_eq!(self.records.total_message_count(), count);
        }

        /// Waits for the total amount of messages that have been received by this [NetTest] to
        /// reach the given `count`.
        ///
        /// If the message count already meets or exceeds the given `count`, yields immediately.
        pub async fn wait_for_total_message_count(&self, count: usize) {
            self.records.wait_for_total_message_count(count).await;
        }

        /// Asserts that the amount of messages received that contained the given `msg` value equals
        /// the given `count`.
        pub fn assert_message_count(&self, msg: impl AsRef<str>, count: usize) {
            assert_eq!(self.records.message_count(msg), count);
        }

        /// Waits for the amount of messages received that contain the given `msg` to reach the
        /// given `count`.
        ///
        /// If the message count already meets or exceeds the given `count`, yields immediately.
        pub async fn wait_for_message_count(
            &self,
            msg: impl AsRef<str>,
            count: usize,
        ) {
            self.records.wait_for_message_count(msg, count).await;
        }

        /// Asserts that the amount of messages received for `connection` that contain the given
        /// `msg` value equals the given `count`.
        pub fn assert_connection_message_count(
            &self,
            connection: Connection,
            msg: impl AsRef<str>,
            count: usize,
        ) {
            assert_eq!(self.records.message_count_for_connection(connection, msg), count);
        }

        /// Waits for the amount of messages received for `connection` that contain the given `msg`
        /// value to reach the given `count`.
        ///
        /// If the message count already meets or exceeds the given `count`, yields immediately.
        pub async fn wait_for_connection_message_count(
            &self,
            connection: Connection,
            msg: impl AsRef<str>,
            count: usize,
        ) {
            self.records.wait_for_message_count_for_connection(connection, msg, count).await;
        }
    }

    /// Extension trait for slices of [NetTest].
    ///
    /// Implements many of the [NetTest] methods on slices, effectively executing those methods for
    /// each [NetTest] in the slice.
    #[async_trait(?Send)]
    pub trait NetTestSliceExt {
        /// Clear message records for all [NetTests](NetTest).
        fn clear_records(&self);

        /// Asserts the total message count for each [NetTest].
        ///
        /// See [NetTest::assert_total_message_count()].
        fn assert_total_message_count_for_each(&self, count: usize);

        /// Waits for the total amount of messages for each [NetTest].
        ///
        /// See [NetTest::wait_for_total_message_count()].
        async fn wait_for_total_message_count_for_each(&self, count: usize);

        /// Asserts the per-message count for each [NetTest].
        ///
        /// See [NetTest::assert_message_count()].
        fn assert_message_count_for_each(&self, msg: impl AsRef<str>, count: usize);

        /// Waits for the per-message count for each [NetTest].
        ///
        /// See [NetTest::wait_for_message_count()].
        async fn wait_for_message_count_for_each(&self, msg: impl AsRef<str>, count: usize);

        /// Asserts the per-connection, per-message count for each [NetTest].
        ///
        /// See [NetTest::assert_connection_message_count()].
        fn assert_connection_message_count_for_each(
            &self,
            connection: Connection,
            msg: impl AsRef<str>,
            count: usize,
        );

        /// Waits for the per-connection, per-message count for each [NetTest].
        ///
        /// See [NetTest::wait_for_connection_message_count()].
        async fn wait_for_connection_message_count_for_each(
            &self,
            connection: Connection,
            msg: impl AsRef<str>,
            count: usize,
        );
    }

    #[async_trait(?Send)]
    impl<D: NetDriver> NetTestSliceExt for [NetTest<D>] {
        fn clear_records(&self) {
            for net in self {
                net.clear_records();
            }
        }

        fn assert_total_message_count_for_each(&self, count: usize) {
            for net in self {
                net.assert_total_message_count(count);
            }
        }

        async fn wait_for_total_message_count_for_each(&self, count: usize) {
            execute_futures(self.iter().map(|net| {
                net.wait_for_total_message_count(count)
            })).await;
        }

        fn assert_message_count_for_each(&self, msg: impl AsRef<str>, count: usize) {
            for net in self {
                net.assert_message_count(msg.as_ref(), count);
            }
        }

        async fn wait_for_message_count_for_each(&self, msg: impl AsRef<str>, count: usize) {
            execute_futures(self.iter().map(|net| {
                net.wait_for_message_count(msg.as_ref(), count)
            })).await;
        }

        fn assert_connection_message_count_for_each(
            &self,
            connection: Connection,
            msg: impl AsRef<str>,
            count: usize,
        ) {
            for net in self {
                net.assert_connection_message_count(connection, msg.as_ref(), count);
            }
        }

        async fn wait_for_connection_message_count_for_each(
            &self,
            connection: Connection,
            msg: impl AsRef<str>,
            count: usize,
        ) {
            execute_futures(self.iter().map(|net| {
                net.wait_for_connection_message_count(connection, msg.as_ref(), count)
            })).await;
        }
    }

    /// Get an iterator for all valid socket ports to use for testing.
    ///
    /// This is configured via the environment variable `GTETHER_TEST_NET_DRIVER_PORTS`, using the
    /// format "<start>:<end>" (inclusive start, exclusive end). For example:
    /// ```text
    /// export GTETHER_TEST_NET_DRIVER_PORTS="9001:10000"
    /// ```
    ///
    /// If that environment variable is not set, or cannot be parsed, the default port range is
    /// `59000:60000`.
    pub fn testing_ports_from_env() -> impl Iterator<Item=u16> {
        let var_str = std::env::var("GTETHER_TEST_NET_DRIVER_PORTS")
            .unwrap_or("59000:60000".to_owned());
        let (start, end) = var_str.split_once(':')
            .unwrap_or(("59000", "60000"));
        let start = start.parse::<u16>().unwrap_or(59000);
        let end = end.parse::<u16>().unwrap_or(60000);
        start..end
    }

    impl<D: NetDriverListen> NetTest<D> {
        /// Asserts that a [NetTest] using a [NetDriverListen] driver can bind to a socket.
        ///
        /// Uses [testing_ports_from_env()] to iterate through and find a free port to bind to. If
        /// the chosen port is in use, will attempt to use the next port, and so on, until all ports
        /// from [testing_ports_from_env()] have been attempted. If no ports can be used, will
        /// panic.
        ///
        /// Returns the [SocketAddr] that was successfully listened on.
        pub async fn assert_listen(&self) -> SocketAddr {
            for port in testing_ports_from_env() {
                let socket_addr = SocketAddr::new(Ipv4Addr::LOCALHOST.into(), port);

                match self.net.listen(socket_addr).await {
                    Ok(_) => return socket_addr,
                    Err(NetworkingError::InvalidAddress(_)) => continue,
                    result => result.expect("Listen should succeed"),
                }
            }
            panic!("No port available to bind/listen on")
        }

        /// Asserts that a [NetTest] using a [NetDriverListen] driver errors in the expected way
        /// when attempting to bind to a socket.
        pub async fn assert_listen_error(
            &self,
            socket_addr: SocketAddr,
            expected_error: NetworkingError,
        ) {
            let error = self.net.listen(socket_addr).await
                .expect_err("Listen should fail");
            assert_networking_error_eq(error, &expected_error);
        }
    }

    impl<S: NetDriverConnect> NetTest<S> {
        /// Asserts that a [NetTest] using a [NetDriverConnect] driver can connect to a server.
        ///
        /// The given `dst` [NetTest] is used to determine the [Connection] ID from the server's
        /// side once connected. The given `socket_addr` should be the same address that `dst` is
        /// listening on. If it does not match, this method may wait indefinitely waiting for a
        /// connection that will not occur.
        ///
        /// Returns a [ConnectionPair] describing the successful connection.
        pub async fn assert_connect<'a, D: NetDriver>(
            &'a self,
            dst: &'a NetTest<D>,
            socket_addr: SocketAddr,
        ) -> ConnectionPair<'a, S, D> {
            let server_connection = Arc::new(Mutex::new(None));
            let event_server_connection = server_connection.clone();
            let fut = dst.net().event_bus().register_once(move |event: &mut Event<NetworkingConnectEvent>| {
                *event_server_connection.lock() = Some(event.connection());
            }).expect("NetworkingConnectEvent type should be valid");

            let src_to_dst = self.net.connect(socket_addr).await
                .expect("src should connect")
                .into_connection();
            fut.await.expect("NetworkingConnectEvent should fire successfully");

            let dst_to_src = server_connection.lock().take()
                .expect("server_connection should be set");

            ConnectionPair {
                src: TestConnection {
                    net: self,
                    connection: src_to_dst,
                },
                dst: TestConnection {
                    net: dst,
                    connection: dst_to_src,
                },
            }
        }
    }

    /// Extension trait for slices of [NetTest] that use a [NetDriverConnect] driver.
    ///
    /// Implements many of the [NetTest] methods on slices, effectively executing those methods for
    /// each [NetTest] in the slice.
    #[async_trait(?Send)]
    pub trait NetTestConnectSliceExt<S: NetDriverConnect> {
        /// Asserts that each client [NetTest] can connect to the given server [NetTest].
        ///
        /// See [NetTest::assert_connect()].
        async fn assert_connect<'a, D: NetDriver>(
            &'a self,
            dst: &'a NetTest<D>,
            socket_addr: SocketAddr,
        ) -> Vec<ConnectionPair<'a, S, D>>;

        /// Asserts that each client [NetTest] errors in the expected way when connecting.
        async fn assert_connect_error(
            &self,
            socket_addr: SocketAddr,
            expected_error: NetworkingError,
        );
    }

    #[async_trait(?Send)]
    impl<S: NetDriverConnect> NetTestConnectSliceExt<S> for [NetTest<S>] {
        async fn assert_connect<'a, D: NetDriver>(
            &'a self,
            dst: &'a NetTest<D>,
            socket_addr: SocketAddr,
        ) -> Vec<ConnectionPair<'a, S, D>> {
            let mut srcs_out = Vec::with_capacity(self.len());
            for src in self {
                // NOTE: These cannot run in parallel, otherwise the logic that determines dst_to_src
                //  will break
                let pair = src.assert_connect(dst, socket_addr).await;
                srcs_out.push(pair);
            }
            srcs_out
        }

        async fn assert_connect_error(
            &self,
            socket_addr: SocketAddr,
            expected_error: NetworkingError,
        ) {
            for src in self {
                let error = src.net().connect(socket_addr).await
                    .expect_err("Connect should fail");
                assert_networking_error_eq(error, &expected_error);
            }
        }
    }

    impl<D: NetDriverSend> NetTest<D> {
        /// Installs a message reply handler using a [NetDriverSend] driver.
        pub fn init_test_message_repliable_send_handler(
            &self,
            reply_fn: impl (Fn(String) -> String) + Send + Sync + 'static,
        ) {
            let handler_net = self.net.clone();
            let handler_records = self.records.clone();
            self.net.insert_msg_handler(move |connection, msg: Message<TestMessageRepliable>| {
                let value = msg.body().value.clone();
                handler_records.record_message(connection, value.clone());

                let reply = msg.reply(TestMessage {
                    value: reply_fn(value),
                });
                handler_net.send(reply)
            });
        }
    }

    impl<D: NetDriverSendTo> NetTest<D> {
        /// Installs a message reply handler using a [NetDriverSendTo] driver.
        pub fn init_test_message_repliable_send_to_handler(
            &self,
            reply_fn: impl (Fn(String) -> String) + Send + Sync + 'static,
        ) {
            let handler_net = self.net.clone();
            let handler_records = self.records.clone();
            self.net.insert_msg_handler(move |connection, msg: Message<TestMessageRepliable>| {
                let value = msg.body().value.clone();
                handler_records.record_message(connection, value.clone());

                let reply = msg.reply(TestMessage {
                    value: reply_fn(value),
                });
                handler_net.send_to(connection, reply)
            });
        }
    }

    impl<D: NetDriverBroadcast> NetTest<D> {
        /// Asserts that a [NetTest] using a [NetDriverBroadcast] driver can broadcast a message.
        pub fn assert_broadcast(&self, msg: impl Into<String>) {
            let msg = TestMessage::new(msg.into());
            self.net.broadcast(msg)
                .expect("Message should broadcast");
        }

        /// Asserts that a [NetTest] using a [NetDriverBroadcast] driver errors in the expected way
        /// when attempting to broadcast a message.
        pub fn assert_broadcast_error(&self, msg: impl Into<String>, expected_error: &NetworkingError) {
            let msg = TestMessage::new(msg.into());
            let error = self.net.broadcast(msg)
                .expect_err("Message should NOT broadcast");
            assert_networking_error_eq(error, expected_error);
        }
    }

    /// Extension trait for slices of [NetTest] that use a [NetDriverBroadcast] driver.
    ///
    /// Implements many of the [NetTest] methods on slices, effectively executing those methods for
    /// each [NetTest] in the slice.
    pub trait NetTestBroadcastSliceExt {
        /// Asserts that each [NetTest] can broadcast a message.
        ///
        /// See [NetTest::assert_broadcast()].
        fn assert_broadcast_all(&self, msg: impl Into<String>);

        /// Asserts that each [NetTest] errors in the expected way when broadcasting a message.
        ///
        /// See [NetTest::assert_broadcast_error()].
        fn assert_broadcast_error_all(&self, msg: impl Into<String>, expected_error: &NetworkingError);
    }

    impl<D: NetDriverBroadcast> NetTestBroadcastSliceExt for [NetTest<D>] {
        fn assert_broadcast_all(&self, msg: impl Into<String>) {
            let msg = msg.into();
            for net in self {
                net.assert_broadcast(&msg);
            }
        }

        fn assert_broadcast_error_all(&self, msg: impl Into<String>, expected_error: &NetworkingError) {
            let msg = msg.into();
            for net in self {
                net.assert_broadcast_error(&msg, expected_error);
            }
        }
    }

    /// Struct representing an actively connected [NetTest] and it's [Connection].
    /// 
    /// The internal [NetTest] is held by reference, meaning this struct is cheaply cloneable.
    pub struct TestConnection<'a, D: NetDriver> {
        pub net: &'a NetTest<D>,
        pub connection: Connection,
    }

    impl<'a, D: NetDriver> Debug for TestConnection<'a, D> {
        fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
            f.debug_struct("TestConnection")
                .field("net", &self.net)
                .field("connection", &self.connection)
                .field("closed", &self.net.net.connection_info(&self.connection).is_none())
                .finish()
        }
    }

    impl<'a, D: NetDriver> Clone for TestConnection<'a, D> {
        fn clone(&self) -> Self {
            Self {
                net: self.net,
                connection: self.connection,
            }
        }
    }

    impl<'a, D: NetDriver> TestConnection<'a, D> {
        /// Assert that this connection has been closed.
        #[inline]
        pub fn assert_closed(&self) {
            assert!(self.net.net.connection_info(&self.connection).is_none());
        }

        /// Wait for this connection to close.
        ///
        /// Does not actively close the connection if it is open; only waits for it to be closed.
        #[inline]
        pub async fn wait_for_closed(&self) {
            self.net.wait_for_connection_closed(self.connection).await;
        }
    }

    /// Extension trait for slices of [TestConnection].
    ///
    /// Implements many of the [TestConnection] methods on slices, effectively executing those
    /// methods for each [TestConnection] in the slice.
    #[async_trait(?Send)]
    pub trait TestConnectionSliceExt {
        /// Assert that each connection has been closed.
        fn assert_all_closed(&self);

        /// Wait for each connection to close.
        ///
        /// Does not actively close connections if they are open; only waits for them to be closed.
        async fn wait_for_all_closed(&self);
    }

    #[async_trait(?Send)]
    impl<'a, D: NetDriver> TestConnectionSliceExt for [TestConnection<'a, D>] {
        #[inline]
        fn assert_all_closed(&self) {
            for connection in self {
                connection.assert_closed();
            }
        }

        #[inline]
        async fn wait_for_all_closed(&self) {
            execute_futures(self.iter().map(TestConnection::wait_for_closed)).await;
        }
    }

    impl<'a, D: NetDriverSend> TestConnection<'a, D> {
        /// Asserts that a [NetTest] can send a message.
        pub fn assert_send(&self, msg: impl Into<String>) {
            let msg = TestMessage::new(msg.into());
            self.net.net.send(msg)
                .expect("Message should send");
        }

        /// Asserts that a [NetTest] errors in the expected way when attempting to send a message.
        pub fn assert_send_error(&self, msg: impl Into<String>, expected_error: &NetworkingError) {
            let msg = TestMessage::new(msg.into());
            let error = self.net.net.send(msg)
                .expect_err("Message should NOT send");
            assert_networking_error_eq(error, expected_error);
        }

        /// Asserts that a [NetTest] can send a repliable message and receive a response.
        pub async fn assert_send_recv(
            &self,
            msg: impl Into<String>,
            expected_reply: impl Into<String>,
        ) {
            let msg = TestMessageRepliable::new(msg.into());
            let reply = self.net.net.send_recv(msg)
                .expect("Message should send")
                .await;
            let msg_reply = reply.into_body().value;
            let expected_reply = expected_reply.into();
            assert_eq!(msg_reply, expected_reply);
            // Replies bypass normal handlers, so manually record
            self.net.records.record_message(self.connection, msg_reply);
        }
    }

    /// Extension trait for slices of [TestConnection] that use a [NetDriverSend] driver.
    ///
    /// Implements many of the [TestConnection] methods on slices, effectively executing those
    /// methods for each [TestConnection] in the slice.
    #[async_trait(?Send)]
    pub trait TestConnectionSendSliceExt {
        /// Asserts that each [NetTest] can send a message.
        fn assert_send_all(&self, msg: impl Into<String>);

        /// Asserts that each [NetTest] errors in the expected way when attempting to send a
        /// message.
        fn assert_send_error_all(&self, msg: impl Into<String>, expected_error: &NetworkingError);

        /// Asserts that each [NetTest] can send a repliable message and receive a response.
        async fn assert_send_recv_all(
            &self,
            msg: impl Into<String>,
            expected_reply: impl Into<String>,
        );
    }

    #[async_trait(?Send)]
    impl <'a, D: NetDriverSend> TestConnectionSendSliceExt for [TestConnection<'a, D>] {
        fn assert_send_all(&self, msg: impl Into<String>) {
            let msg = msg.into();
            for connection in self {
                connection.assert_send(&msg);
            }
        }

        fn assert_send_error_all(&self, msg: impl Into<String>, expected_error: &NetworkingError) {
            let msg = msg.into();
            for connection in self {
                connection.assert_send_error(&msg, expected_error);
            }
        }

        async fn assert_send_recv_all(
            &self,
            msg: impl Into<String>,
            expected_reply: impl Into<String>,
        ) {
            let msg = msg.into();
            let expected_reply = expected_reply.into();
            execute_futures(self.iter().map(|cn| {
                cn.assert_send_recv(&msg, &expected_reply)
            })).await;
        }
    }

    impl<'a, D: NetDriverSendTo> TestConnection<'a, D> {
        /// Asserts that a [NetTest] can send a message to a specific [Connection].
        ///
        /// The [Connection] used is the one associated with this [TestConnection].
        pub fn assert_send_to(&self, msg: impl Into<String>) {
            let msg = TestMessage::new(msg.into());
            self.net.net.send_to(self.connection, msg)
                .expect("Message should send");
        }

        /// Asserts that a [NetTest] errors in the expected way when attempting to send a message
        /// to a [Connection].
        ///
        /// The [Connection] used is the one associated with this [TestConnection].
        pub fn assert_send_to_error(&self, msg: impl Into<String>, expected_error: &NetworkingError) {
            let msg = TestMessage::new(msg.into());
            let error = self.net.net.send_to(self.connection, msg)
                .expect_err("Message should NOT send");
            assert_networking_error_eq(error, expected_error);
        }

        /// Asserts that a [NetTest] can send a repliable message to a specific [Connection] and
        /// receive a response.
        ///
        /// The [Connection] used is the one associated with this [TestConnection].
        pub async fn assert_send_recv_to(
            &self,
            msg: impl Into<String>,
            expected_reply: impl Into<String>,
        ) {
            let msg = TestMessageRepliable::new(msg.into());
            let reply = self.net.net.send_recv_to(self.connection, msg)
                .expect("Message should send")
                .await;
            let msg_reply = reply.into_body().value;
            let expected_reply = expected_reply.into();
            assert_eq!(msg_reply, expected_reply);
            // Replies bypass normal handlers, so manually record
            self.net.records.record_message(self.connection, msg_reply);
        }
    }

    /// Extension trait for slices of [TestConnection] that use a [NetDriverSendTo] driver.
    ///
    /// Implements many of the [TestConnection] methods on slices, effectively executing those
    /// methods for each [TestConnection] in the slice.
    #[async_trait(?Send)]
    pub trait TestConnectionSendToSliceExt {
        /// Asserts that each [NetTest] can send messages to a specific [Connection].
        ///
        /// See [TestConnection::assert_send_to()].
        fn assert_send_to_all(&self, msg: impl Into<String>);

        /// Asserts that each [NetTest] errors in the expected way when attempting to send a message
        /// to a [Connection].
        ///
        /// See [TestConnection::assert_send_to_error_all()].
        fn assert_send_to_error_all(&self, msg: impl Into<String>, expected_error: &NetworkingError);

        /// Asserts that each [NetTest] can send a repliable message to a specific [Connection] and
        /// receive a response.
        ///
        /// See [TestConnection::assert_send_recv_to_all()].
        async fn assert_send_recv_to_all(
            &self,
            msg: impl Into<String>,
            expected_reply: impl Into<String>,
        );
    }

    #[async_trait(?Send)]
    impl <'a, D: NetDriverSendTo> TestConnectionSendToSliceExt for [TestConnection<'a, D>] {
        fn assert_send_to_all(&self, msg: impl Into<String>) {
            let msg = msg.into();
            for connection in self {
                connection.assert_send_to(&msg);
            }
        }

        fn assert_send_to_error_all(&self, msg: impl Into<String>, expected_error: &NetworkingError) {
            let msg = msg.into();
            for connection in self {
                connection.assert_send_to_error(&msg, expected_error);
            }
        }

        async fn assert_send_recv_to_all(
            &self,
            msg: impl Into<String>,
            expected_reply: impl Into<String>,
        ) {
            let msg = msg.into();
            let expected_reply = expected_reply.into();
            execute_futures(self.iter().map(|cn| {
                cn.assert_send_recv_to(&msg, &expected_reply)
            })).await;
        }
    }

    /// A pair of [TestConnections](TestConnection) representing the two ends of an active
    /// connection.
    #[derive(Clone, Educe)]
    #[educe(Debug)]
    pub struct ConnectionPair<'a, S: NetDriver, D: NetDriver> {
        pub src: TestConnection<'a, S>,
        pub dst: TestConnection<'a, D>,
    }

    impl<'a, S: NetDriver, D: NetDriver> ConnectionPair<'a, S, D> {
        /// Close the `src` side and wait for the `dst` to acknowledge the closure.
        pub async fn close_src_and_wait(&self) {
            self.src.net.net.close().await;
            self.src.assert_closed();
            self.dst.wait_for_closed().await;
        }

        /// Close the `dst` side and wait for the `src` to acknowledge the closure.
        pub async fn close_dst_and_wait(&self) {
            self.dst.net.net.close().await;
            self.dst.assert_closed();
            self.src.wait_for_closed().await;
        }

        /// Flip the representation of this [ConnectionPair], such that the new pair uses the
        /// original `src` as `dst`, and the original `dst` as `src`. 
        pub fn flip(&self) -> ConnectionPair<'a, D, S> {
            ConnectionPair {
                src: self.dst.clone(),
                dst: self.src.clone(),
            }
        }
    }

    /// Extension trait for slices of [ConnectionPair].
    /// 
    /// Implements many of the [ConnectionPair] methods on slices, effectively executing those
    /// methods for each [ConnectionPair] in the slice.
    #[async_trait(?Send)]
    pub trait ConnectionPairSliceExt<'a, S: NetDriver, D: NetDriver> {
        /// Collect only all the `src` [TestConnections](TestConnection).
        fn srcs(&self) -> Vec<TestConnection<'a, S>>;
        
        /// Close each `src` side and wait for each `dst` to acknowledge the closure.
        async fn close_all_srcs_and_wait(&self);
        
        /// Collect only all the `dst` [TestConnections](TestConnection).
        fn dsts(&self) -> Vec<TestConnection<'a, D>>;

        /// Close each `dst` side and wait for each `src` to acknowledge the closure.
        async fn close_all_dsts_and_wait(&self);
        
        /// Flip the representation of each [ConnectionPair], such that the new pair uses the
        /// original `src` as `dst`, and the original `dst` as `src`. 
        fn flip(&self) -> Vec<ConnectionPair<'a, D, S>>;
    }

    #[async_trait(?Send)]
    impl<'a, S: NetDriver, D: NetDriver> ConnectionPairSliceExt<'a, S, D> for [ConnectionPair<'a, S, D>] {
        #[inline]
        fn srcs(&self) -> Vec<TestConnection<'a, S>> {
            self.iter()
                .map(|entry| entry.src.clone())
                .collect()
        }

        #[inline]
        async fn close_all_srcs_and_wait(&self) {
            execute_futures(self.iter().map(ConnectionPair::close_src_and_wait)).await;
        }

        #[inline]
        fn dsts(&self) -> Vec<TestConnection<'a, D>> {
            self.iter()
                .map(|entry| entry.dst.clone())
                .collect()
        }

        #[inline]
        async fn close_all_dsts_and_wait(&self) {
            execute_futures(self.iter().map(ConnectionPair::close_dst_and_wait)).await;
        }

        #[inline]
        fn flip(&self) -> Vec<ConnectionPair<'a, D, S>> {
            self.iter()
                .map(ConnectionPair::flip)
                .collect()
        }
    }

    /// Factory trait for creating an entire client/server collection of [Networking] stacks.
    pub trait ClientServerStackFactory: Default
    {
        /// The type of the client [NetDriver].
        type ClientDriver: NetDriverConnect;
        
        /// The type of the client [NetDriverFactory].
        type ClientDriverFactory: NetDriverFactory<Self::ClientDriver>;
        
        /// The type of the server [NetDriver].
        type ServerDriver: NetDriverListen;
        
        /// The type of the server [NetDriverFactory].
        type ServerDriverFactory: NetDriverFactory<Self::ServerDriver>;

        /// Create a client [NetDriverFactory].
        fn client_factory(&self) -> Self::ClientDriverFactory;
        
        /// Create a server [NetDriverFactory].
        fn server_factory(&self) -> Self::ServerDriverFactory;
    }

    /// Extension trait for additional functionality applied to [ClientServerStackFactory]
    /// implementations.
    pub trait ClientServerStackFactoryExt: ClientServerStackFactory {
        /// Create a client [NetTest].
        #[inline]
        fn create_client(&self) -> NetTest<Self::ClientDriver> {
            NetTest::new(self.client_factory())
        }

        /// Create a server [NetTest].
        #[inline]
        fn create_server(&self) -> NetTest<Self::ServerDriver> {
            NetTest::new(self.server_factory())
        }

        /// Create `CLIENT_COUNT` client [NetTests](NetTest), and one server [NetTest].
        /// 
        /// These [NetTests](NetTest) are _NOT_ connected to each other by default.
        fn create_stacks<const CLIENT_COUNT: usize>(
            &self,
        ) -> ([NetTest<Self::ClientDriver>; CLIENT_COUNT], NetTest<Self::ServerDriver>) {
            let clients: [NetTest<Self::ClientDriver>; CLIENT_COUNT] = core::array::from_fn(|_| {
                NetTest::new(self.client_factory())
            });

            let server = NetTest::new(self.server_factory());

            (clients, server)
        }
    }

    impl<F: ClientServerStackFactory> ClientServerStackFactoryExt for F {}

    /// Pre-defined test suites.
    /// 
    /// This module contains several pre-defined suites of tests that ensure implementations
    /// maintain the expected behavior of [NetDriver]'s. Usually, these test suites are not used
    /// directly, as they do not exist in individual function form. Instead, it is recommended to
    /// use the macros found in the [super module](super), such as
    /// [`test_net_driver_client_server_core!`].
    pub mod suites {
        use super::*;

        /// Client/Server test suite.
        /// 
        /// It is recommended to use the following macros instead of using this test suite directly:
        ///  * [`test_net_driver_client_server_core!`]
        ///  * [`test_net_driver_client_server_send!`]
        ///  * [`test_net_driver_client_server_send_to!`]
        ///  * [`test_net_driver_client_server_broadcast!`]
        #[derive(Default)]
        pub struct ClientServer<F>
        where
            F: ClientServerStackFactory,
        {
            stack_factory: F,
        }

        impl<F> ClientServer<F>
        where
            F: ClientServerStackFactory,
        {
            pub fn test_connect(&self, timeout: Duration) {
                let timeout = Timeout::new(timeout);

                let (clients, server) = self.stack_factory.create_stacks::<1>();

                let socket_addr = timeout.run(
                    server.assert_listen(),
                    "Server listening",
                    Some(format_args!("{server:#?}")),
                );
                timeout.run(
                    clients.assert_connect(&server, socket_addr),
                    "Clients connecting",
                    Some(format_args!("{clients:#?}")),
                );
            }

            pub fn test_listen_already_bound(&self, timeout: Duration) {
                let timeout = Timeout::new(timeout);

                let server = self.stack_factory.create_server();
                let server2 = self.stack_factory.create_server();

                let socket_addr = timeout.run(
                    server.assert_listen(),
                    "Server 1 listening",
                    Some(format_args!("{server:#?}")),
                );
                timeout.run(
                    server2.assert_listen_error(
                        socket_addr,
                        NetworkingError::InvalidAddress(socket_addr),
                    ),
                    "Server 2 listening",
                    Some(format_args!("{server2:#?}")),
                );
            }

            pub fn test_connect_cancelled(&self, timeout: Duration) {
                let timeout = Timeout::new(timeout);

                let (clients, server) = self.stack_factory.create_stacks::<1>();
                let socket_addr = timeout.run(
                    server.assert_listen(),
                    "Server listening",
                    Some(format_args!("{server:#?}")),
                );

                for client in &clients {
                    client.net().event_bus().register(move |event: &mut Event<NetworkingConnectEvent>| {
                        event.cancel();
                    }).expect("NetworkingConnectEvent type should be valid");
                }

                timeout.run(
                    clients.assert_connect_error(
                        socket_addr,
                        NetworkingError::Cancelled,
                    ),
                    "Clients connecting",
                    Some(format_args!("{clients:#?}")),
                );
            }

            pub fn test_connect_after_close(&self, timeout: Duration) {
                let timeout = Timeout::new(timeout);

                let (clients, server) = self.stack_factory.create_stacks::<1>();
                let socket_addr = timeout.run(
                    server.assert_listen(),
                    "Server listening",
                    Some(format_args!("{server:#?}")),
                );
                let connections = timeout.run(
                    clients.assert_connect(&server, socket_addr),
                    "Clients connecting",
                    Some(format_args!("{clients:#?}")),
                );

                timeout.run(
                    connections.close_all_srcs_and_wait(),
                    "Closing connections from clients",
                    Some(format_args!("{connections:#?}")),
                );
            }
        }

        impl<F> ClientServer<F>
        where
            F: ClientServerStackFactory,
            <F as ClientServerStackFactory>::ClientDriver: NetDriverSend,
        {
            pub fn test_send(&self, timeout: Duration) {
                let timeout = Timeout::new(timeout);

                let (clients, server) = self.stack_factory.create_stacks::<1>();
                let socket_addr = timeout.run(
                    server.assert_listen(),
                    "Server listening",
                    None,
                );
                let connections = timeout.run(
                    clients.assert_connect(&server, socket_addr),
                    "Clients connecting",
                    None,
                );

                connections.srcs().assert_send_all("client->server");

                timeout.run(
                    server.wait_for_total_message_count(clients.len()),
                    "Waiting for messages",
                    Some(format_args!("{connections:#?}")),
                );
                server.assert_message_count("client->server", clients.len());
                clients.assert_total_message_count_for_each(0);
            }

            pub fn test_send_many(&self, timeout: Duration) {
                let timeout = Timeout::new(timeout);

                let (clients, server) = self.stack_factory.create_stacks::<3>();
                let socket_addr = timeout.run(
                    server.assert_listen(),
                    "Server listening",
                    None,
                );
                let connections = timeout.run(
                    clients.assert_connect(&server, socket_addr),
                    "Clients connecting",
                    None,
                );

                connections.srcs().assert_send_all("client->server");

                timeout.run(
                    server.wait_for_total_message_count(clients.len()),
                    "Waiting for messages",
                    Some(format_args!("{connections:#?}")),
                );
                server.assert_message_count("client->server", clients.len());
                clients.assert_total_message_count_for_each(0);
            }

            pub fn test_send_closed_src(&self, timeout: Duration) {
                let timeout = Timeout::new(timeout);

                let (clients, server) = self.stack_factory.create_stacks::<1>();
                let socket_addr = timeout.run(
                    server.assert_listen(),
                    "Server listening",
                    None,
                );
                let connections = timeout.run(
                    clients.assert_connect(&server, socket_addr),
                    "Clients connecting",
                    None,
                );

                timeout.run(
                    connections.close_all_srcs_and_wait(),
                    "Closing clients",
                    Some(format_args!("{clients:#?}")),
                );
                connections.srcs().assert_send_error_all("client->server", &NetworkingError::Closed);

                server.assert_total_message_count(0);
                clients.assert_total_message_count_for_each(0);
            }

            pub fn test_send_closed_dst(&self, timeout: Duration) {
                let timeout = Timeout::new(timeout);

                let (clients, server) = self.stack_factory.create_stacks::<1>();
                let socket_addr = timeout.run(
                    server.assert_listen(),
                    "Server listening",
                    None,
                );
                let connections = timeout.run(
                    clients.assert_connect(&server, socket_addr),
                    "Clients connecting",
                    None,
                );

                timeout.run(
                    connections.close_all_dsts_and_wait(),
                    "Closing server",
                    Some(format_args!("{server:#?}")),
                );
                connections.srcs().assert_send_error_all("client->server", &NetworkingError::Closed);

                server.assert_total_message_count(0);
                clients.assert_total_message_count_for_each(0);
            }

            pub fn test_send_closed_partial(&self, timeout: Duration) {
                let timeout = Timeout::new(timeout);

                let (clients, server) = self.stack_factory.create_stacks::<3>();
                let socket_addr = timeout.run(
                    server.assert_listen(),
                    "Server listening",
                    None,
                );
                let connections = timeout.run(
                    clients.assert_connect(&server, socket_addr),
                    "Clients connecting",
                    None,
                );

                timeout.run(
                    connections[0].close_src_and_wait(),
                    "Closing client 0",
                    Some(format_args!("{clients:#?}")),
                );
                connections[1..].srcs().assert_send_all("client->server");

                timeout.run(
                    server.wait_for_total_message_count(clients.len() - 1),
                    "Waiting for messages",
                    Some(format_args!("{connections:#?}")),
                );
                server.assert_message_count("client->server", clients.len() - 1);
                clients.assert_total_message_count_for_each(0);
            }
        }

        impl<F> ClientServer<F>
        where
            F: ClientServerStackFactory,
            <F as ClientServerStackFactory>::ServerDriver: NetDriverSendTo,
        {
            pub fn test_send_to(&self, timeout: Duration) {
                let timeout = Timeout::new(timeout);

                let (clients, server) = self.stack_factory.create_stacks::<1>();
                let socket_addr = timeout.run(
                    server.assert_listen(),
                    "Server listening",
                    None,
                );
                let connections = timeout.run(
                    clients.assert_connect(&server, socket_addr),
                    "Clients connecting",
                    None,
                ).flip();

                connections.srcs().assert_send_to_all("server->client");

                timeout.run(
                    clients.wait_for_total_message_count_for_each(1),
                    "Waiting for messages",
                    Some(format_args!("{connections:#?}")),
                );
                clients.assert_message_count_for_each("server->client", 1);
                server.assert_total_message_count(0);
            }

            pub fn test_send_to_many(&self, timeout: Duration) {
                let timeout = Timeout::new(timeout);

                let (clients, server) = self.stack_factory.create_stacks::<3>();
                let socket_addr = timeout.run(
                    server.assert_listen(),
                    "Server listening",
                    None,
                );
                let connections = timeout.run(
                    clients.assert_connect(&server, socket_addr),
                    "Clients connecting",
                    None,
                ).flip();

                connections.srcs().assert_send_to_all("server->client");

                timeout.run(
                    clients.wait_for_total_message_count_for_each(1),
                    "Waiting for messages",
                    Some(format_args!("{connections:#?}")),
                );
                clients.assert_message_count_for_each("server->client", 1);
                server.assert_total_message_count(0);
            }

            pub fn test_send_to_closed_src(&self, timeout: Duration) {
                let timeout = Timeout::new(timeout);

                let (clients, server) = self.stack_factory.create_stacks::<1>();
                let socket_addr = timeout.run(
                    server.assert_listen(),
                    "Server listening",
                    None,
                );
                let connections = timeout.run(
                    clients.assert_connect(&server, socket_addr),
                    "Clients connecting",
                    None,
                ).flip();

                timeout.run(
                    connections.close_all_srcs_and_wait(),
                    "Closing server",
                    Some(format_args!("{clients:#?}")),
                );
                connections.srcs().assert_send_to_error_all("server->client", &NetworkingError::Closed);

                clients.assert_total_message_count_for_each(0);
                server.assert_total_message_count(0);
            }

            pub fn test_send_to_closed_dst(&self, timeout: Duration) {
                let timeout = Timeout::new(timeout);

                let (clients, server) = self.stack_factory.create_stacks::<1>();
                let socket_addr = timeout.run(
                    server.assert_listen(),
                    "Server listening",
                    None,
                );
                let connections = timeout.run(
                    clients.assert_connect(&server, socket_addr),
                    "Clients connecting",
                    None,
                ).flip();

                timeout.run(
                    connections.close_all_dsts_and_wait(),
                    "Closing clients",
                    Some(format_args!("{clients:#?}")),
                );
                for src in connections.srcs() {
                    let connection = src.connection;
                    src.assert_send_to_error("server->client", &NetworkingError::InvalidConnection(connection));
                }

                clients.assert_total_message_count_for_each(0);
                server.assert_total_message_count(0);
            }

            pub fn test_send_to_closed_partial(&self, timeout: Duration) {
                let timeout = Timeout::new(timeout);

                let (clients, server) = self.stack_factory.create_stacks::<1>();
                let socket_addr = timeout.run(
                    server.assert_listen(),
                    "Server listening",
                    None,
                );
                let connections = timeout.run(
                    clients.assert_connect(&server, socket_addr),
                    "Clients connecting",
                    None,
                ).flip();

                timeout.run(
                    connections[0].close_dst_and_wait(),
                    "Closing client 0",
                    Some(format_args!("{clients:#?}")),
                );
                connections[1..].srcs().assert_send_to_all("server->client");

                timeout.run(
                    clients[1..].wait_for_total_message_count_for_each(1),
                    "Waiting for messages",
                    Some(format_args!("{connections:#?}")),
                );
                clients[0].assert_total_message_count(0);
                clients[1..].assert_message_count_for_each("server->client", 1);
                server.assert_total_message_count(0);
            }

            pub fn test_send_to_invalid_connection(&self, timeout: Duration) {
                let timeout = Timeout::new(timeout);

                let (clients, server) = self.stack_factory.create_stacks::<1>();
                let socket_addr = timeout.run(
                    server.assert_listen(),
                    "Server listening",
                    None,
                );
                let mut connections = timeout.run(
                    clients.assert_connect(&server, socket_addr),
                    "Clients connecting",
                    None,
                ).flip();

                for connection in &mut connections {
                    connection.src.connection = Connection::INVALID;
                }

                connections.srcs().assert_send_to_error_all(
                    "server->client",
                    &NetworkingError::InvalidConnection(Connection::INVALID),
                );

                server.assert_total_message_count(0);
                clients.assert_total_message_count_for_each(0);
            }
        }

        impl<F> ClientServer<F>
        where
            F: ClientServerStackFactory,
            <F as ClientServerStackFactory>::ClientDriver: NetDriverSend,
            <F as ClientServerStackFactory>::ServerDriver: NetDriverSendTo,
        {
            pub fn test_send_recv(&self, timeout: Duration) {
                let timeout = Timeout::new(timeout);

                let (clients, server) = self.stack_factory.create_stacks::<1>();
                let socket_addr = timeout.run(
                    server.assert_listen(),
                    "Server listening",
                    None,
                );
                let connections = timeout.run(
                    clients.assert_connect(&server, socket_addr),
                    "Clients connecting",
                    None,
                );

                server.init_test_message_repliable_send_to_handler(|value| value + "-REPLY");

                timeout.run(
                    connections.srcs().assert_send_recv_all(
                        "client->server",
                        "client->server-REPLY",
                    ),
                    "Waiting for message replies",
                    Some(format_args!("{connections:#?}")),
                );

                timeout.run(
                    server.wait_for_total_message_count(clients.len()),
                    "Waiting for server-side messages",
                    Some(format_args!("{connections:#?}")),
                );
                server.assert_message_count("client->server", clients.len());
                timeout.run(
                    clients.wait_for_total_message_count_for_each(1),
                    "Waiting for client-side messages",
                    Some(format_args!("{connections:#?}")),
                );
                clients.assert_message_count_for_each("client->server-REPLY", 1);
            }

            pub fn test_send_recv_many(&self, timeout: Duration) {
                let timeout = Timeout::new(timeout);

                let (clients, server) = self.stack_factory.create_stacks::<3>();
                let socket_addr = timeout.run(
                    server.assert_listen(),
                    "Server listening",
                    None,
                );
                let connections = timeout.run(
                    clients.assert_connect(&server, socket_addr),
                    "Clients connecting",
                    None,
                );

                server.init_test_message_repliable_send_to_handler(|value| value + "-REPLY");

                timeout.run(
                    connections.srcs().assert_send_recv_all(
                        "client->server",
                        "client->server-REPLY",
                    ),
                    "Waiting for message replies",
                    Some(format_args!("{connections:#?}")),
                );

                timeout.run(
                    server.wait_for_total_message_count(clients.len()),
                    "Waiting for server-side messages",
                    Some(format_args!("{connections:#?}")),
                );
                server.assert_message_count("client->server", clients.len());
                timeout.run(
                    clients.wait_for_total_message_count_for_each(1),
                    "Waiting for client-side messages",
                    Some(format_args!("{connections:#?}")),
                );
                clients.assert_message_count_for_each("client->server-REPLY", 1);
            }

            pub fn test_send_recv_to(&self, timeout: Duration) {
                let timeout = Timeout::new(timeout);

                let (clients, server) = self.stack_factory.create_stacks::<1>();
                let socket_addr = timeout.run(
                    server.assert_listen(),
                    "Server listening",
                    None,
                );
                let connections = timeout.run(
                    clients.assert_connect(&server, socket_addr),
                    "Clients connecting",
                    None,
                ).flip();

                for client in &clients {
                    client.init_test_message_repliable_send_handler(|value| value + "-REPLY");
                }

                timeout.run(
                    connections.srcs().assert_send_recv_to_all(
                        "server->client",
                        "server->client-REPLY",
                    ),
                    "Waiting for message replies",
                    Some(format_args!("{connections:#?}")),
                );

                timeout.run(
                    clients.wait_for_total_message_count_for_each(1),
                    "Waiting for client-side messages",
                    Some(format_args!("{connections:#?}")),
                );
                clients.assert_message_count_for_each("server->client", 1);
                timeout.run(
                    server.wait_for_total_message_count(clients.len()),
                    "Waiting for server-side messages",
                    Some(format_args!("{connections:#?}")),
                );
                server.assert_message_count("server->client-REPLY", clients.len());
            }

            pub fn test_send_recv_to_many(&self, timeout: Duration) {
                let timeout = Timeout::new(timeout);

                let (clients, server) = self.stack_factory.create_stacks::<3>();
                let socket_addr = timeout.run(
                    server.assert_listen(),
                    "Server listening",
                    None,
                );
                let connections = timeout.run(
                    clients.assert_connect(&server, socket_addr),
                    "Clients connecting",
                    None,
                ).flip();

                for client in &clients {
                    client.init_test_message_repliable_send_handler(|value| value + "-REPLY");
                }

                timeout.run(
                    connections.srcs().assert_send_recv_to_all(
                        "server->client",
                        "server->client-REPLY",
                    ),
                    "Waiting for message replies",
                    Some(format_args!("{connections:#?}")),
                );

                timeout.run(
                    clients.wait_for_total_message_count_for_each(1),
                    "Waiting for client-side messages",
                    Some(format_args!("{connections:#?}")),
                );
                clients.assert_message_count_for_each("server->client", 1);
                timeout.run(
                    server.wait_for_total_message_count(clients.len()),
                    "Waiting for server-side messages",
                    Some(format_args!("{connections:#?}")),
                );
                server.assert_message_count("server->client-REPLY", clients.len());
            }
        }

        impl<F> ClientServer<F>
        where
            F: ClientServerStackFactory,
            <F as ClientServerStackFactory>::ServerDriver: NetDriverBroadcast,
        {
            pub fn test_broadcast(&self, timeout: Duration) {
                let timeout = Timeout::new(timeout);

                let (clients, server) = self.stack_factory.create_stacks::<3>();
                let socket_addr = timeout.run(
                    server.assert_listen(),
                    "Server listening",
                    None,
                );
                let _connections = timeout.run(
                    clients.assert_connect(&server, socket_addr),
                    "Clients connecting",
                    None,
                ).flip();

                server.assert_broadcast("server->BROADCAST");

                timeout.run(
                    clients.wait_for_total_message_count_for_each(1),
                    "Waiting for messages",
                    Some(format_args!("{clients:#?}")),
                );
                clients.assert_message_count_for_each("server->BROADCAST", 1);
                server.assert_total_message_count(0);
            }

            pub fn test_broadcast_closed_src(&self, timeout: Duration) {
                let timeout = Timeout::new(timeout);

                let (clients, server) = self.stack_factory.create_stacks::<3>();
                let socket_addr = timeout.run(
                    server.assert_listen(),
                    "Server listening",
                    None,
                );
                let connections = timeout.run(
                    clients.assert_connect(&server, socket_addr),
                    "Clients connecting",
                    None,
                ).flip();

                timeout.run(
                    connections.close_all_srcs_and_wait(),
                    "Closing connections from server",
                    Some(format_args!("{connections:#?}")),
                );
                server.assert_broadcast_error("server->BROADCAST", &NetworkingError::Closed);

                clients.assert_total_message_count_for_each(0);
                server.assert_total_message_count(0);
            }

            pub fn test_broadcast_closed_dst(&self, timeout: Duration) {
                let timeout = Timeout::new(timeout);

                let (clients, server) = self.stack_factory.create_stacks::<3>();
                let socket_addr = timeout.run(
                    server.assert_listen(),
                    "Server listening",
                    None,
                );
                let connections = timeout.run(
                    clients.assert_connect(&server, socket_addr),
                    "Clients connecting",
                    None,
                ).flip();

                timeout.run(
                    connections.close_all_dsts_and_wait(),
                    "Closing connections from clients",
                    Some(format_args!("{connections:#?}")),
                );
                server.assert_broadcast("server->BROADCAST");

                clients.assert_total_message_count_for_each(0);
                server.assert_total_message_count(0);
            }

            pub fn test_broadcast_closed_partial(&self, timeout: Duration) {
                let timeout = Timeout::new(timeout);

                let (clients, server) = self.stack_factory.create_stacks::<3>();
                let socket_addr = timeout.run(
                    server.assert_listen(),
                    "Server listening",
                    None,
                );
                let connections = timeout.run(
                    clients.assert_connect(&server, socket_addr),
                    "Clients connecting",
                    None,
                ).flip();

                timeout.run(
                    connections[0].close_dst_and_wait(),
                    "Closing connection 0",
                    Some(format_args!("{connections:#?}")),
                );
                server.assert_broadcast("server->BROADCAST");

                timeout.run(
                    clients[1..].wait_for_total_message_count_for_each(1),
                    "Waiting for messages",
                    Some(format_args!("{connections:#?}")),
                );
                clients[0].assert_total_message_count(0);
                clients[1..].assert_message_count_for_each("server->BROADCAST", 1);
                server.assert_total_message_count(0);
            }
        }
    }
}