rustdtp 0.9.0

Cross-platform networking interfaces for Rust.
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
//! Protocol server implementation.

use super::command_channel::*;
use super::timeout::*;
use crate::crypto::*;
use crate::error::{Error, Result};
use crate::util::*;
use serde::de::DeserializeOwned;
use serde::ser::Serialize;
use std::collections::HashMap;
use std::future::Future;
use std::marker::PhantomData;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpListener, TcpStream, ToSocketAddrs};
use tokio::sync::mpsc::{channel, Receiver, Sender};
use tokio::task::JoinHandle;

/// Configuration for a server's event callbacks.
///
/// # Events
///
/// There are four events for which callbacks can be registered:
///
///  - `connect`
///  - `disconnect`
///  - `receive`
///  - `stop`
///
/// All callbacks are optional, and can be registered for any combination of
/// these events. Note that each callback must be provided as a function or
/// closure returning a thread-safe future. The future will be awaited by the
/// runtime.
///
/// # Example
///
/// ```no_run
/// # use rustdtp::prelude::*;
///
/// # #[tokio::main]
/// # async fn main() {
/// let server = Server::builder()
///     .sending::<usize>()
///     .receiving::<String>()
///     .with_event_callbacks(
///         ServerEventCallbacks::new()
///             .on_connect(move |client_id| async move {
///                 // some async operation...
///                 println!("Client with ID {} connected", client_id);
///             })
///             .on_disconnect(move |client_id| async move {
///                 // some async operation...
///                 println!("Client with ID {} disconnected", client_id);
///             })
///             .on_receive(move |client_id, data| async move {
///                 // some async operation...
///                 println!("Received data from client with ID {}: {}", client_id, data);
///             })
///             .on_stop(move || async move {
///                 // some async operation...
///                 println!("Server closed");
///             })
///     )
///     .start(("127.0.0.1", 29275))
///     .await
///     .unwrap();
/// # }
/// ```
#[allow(clippy::type_complexity)]
#[must_use = "event callbacks do nothing unless you configure them for a server"]
pub struct ServerEventCallbacks<R>
where
    R: DeserializeOwned + 'static,
{
    /// The `connect` event callback.
    connect: Option<Arc<dyn Fn(usize) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>>,
    /// The `disconnect` event callback.
    disconnect:
        Option<Arc<dyn Fn(usize) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>>,
    /// The `receive` event callback.
    receive:
        Option<Arc<dyn Fn(usize, R) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>>,
    /// The `stop` event callback.
    stop: Option<Arc<dyn Fn() -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync>>,
}

impl<R> ServerEventCallbacks<R>
where
    R: DeserializeOwned + 'static,
{
    /// Creates a new server event callbacks configuration with all callbacks
    /// empty.
    pub const fn new() -> Self {
        Self {
            connect: None,
            disconnect: None,
            receive: None,
            stop: None,
        }
    }

    /// Registers a callback on the `connect` event.
    pub fn on_connect<C, F>(mut self, callback: C) -> Self
    where
        C: Fn(usize) -> F + Send + Sync + 'static,
        F: Future<Output = ()> + Send + 'static,
    {
        self.connect = Some(Arc::new(move |client_id| Box::pin((callback)(client_id))));
        self
    }

    /// Registers a callback on the `disconnect` event.
    pub fn on_disconnect<C, F>(mut self, callback: C) -> Self
    where
        C: Fn(usize) -> F + Send + Sync + 'static,
        F: Future<Output = ()> + Send + 'static,
    {
        self.disconnect = Some(Arc::new(move |client_id| Box::pin((callback)(client_id))));
        self
    }

    /// Registers a callback on the `receive` event.
    pub fn on_receive<C, F>(mut self, callback: C) -> Self
    where
        C: Fn(usize, R) -> F + Send + Sync + 'static,
        F: Future<Output = ()> + Send + 'static,
    {
        self.receive = Some(Arc::new(move |client_id, data| {
            Box::pin((callback)(client_id, data))
        }));
        self
    }

    /// Registers a callback on the `stop` event.
    pub fn on_stop<C, F>(mut self, callback: C) -> Self
    where
        C: Fn() -> F + Send + Sync + 'static,
        F: Future<Output = ()> + Send + 'static,
    {
        self.stop = Some(Arc::new(move || Box::pin((callback)())));
        self
    }
}

impl<R> Default for ServerEventCallbacks<R>
where
    R: DeserializeOwned + 'static,
{
    fn default() -> Self {
        Self::new()
    }
}

/// An event handling trait for the server.
///
/// # Events
///
/// There are four events for which methods can be implemented:
///
///  - `connect`
///  - `disconnect`
///  - `receive`
///  - `stop`
///
/// All method implementations are optional, and can be registered for any
/// combination of these events. Note that the type that implements the trait
/// must be `Send + Sync`, and that all event method futures must be `Send`.
///
/// # Example
///
/// ```no_run
/// # use rustdtp::prelude::*;
///
/// # #[tokio::main]
/// # async fn main() {
/// struct MyServerHandler;
///
/// impl ServerEventHandler<String> for MyServerHandler {
///     async fn on_connect(&self, client_id: usize) {
///         // some async operation...
///         println!("Client with ID {} connected", client_id);
///     }
///
///     async fn on_disconnect(&self, client_id: usize) {
///         // some async operation...
///         println!("Client with ID {} disconnected", client_id);
///     }
///
///     async fn on_receive(&self, client_id: usize, data: String) {
///         // some async operation...
///         println!("Received data from client with ID {}: {}", client_id, data);
///     }
///
///     async fn on_stop(&self) {
///         // some async operation...
///         println!("Server closed");
///     }
/// }
///
/// let server = Server::builder()
///     .sending::<usize>()
///     .receiving::<String>()
///     .with_event_handler(MyServerHandler)
///     .start(("127.0.0.1", 29275))
///     .await
///     .unwrap();
/// # }
/// ```
pub trait ServerEventHandler<R>
where
    Self: Send + Sync,
    R: DeserializeOwned + 'static,
{
    /// Handles the `connect` event.
    #[allow(unused_variables)]
    fn on_connect(&self, client_id: usize) -> impl Future<Output = ()> + Send {
        async {}
    }

    /// Handles the `disconnect` event.
    #[allow(unused_variables)]
    fn on_disconnect(&self, client_id: usize) -> impl Future<Output = ()> + Send {
        async {}
    }

    /// Handles the `receive` event.
    #[allow(unused_variables)]
    fn on_receive(&self, client_id: usize, data: R) -> impl Future<Output = ()> + Send {
        async {}
    }

    /// Handles the `stop` event.
    fn on_stop(&self) -> impl Future<Output = ()> + Send {
        async {}
    }
}

/// Unknown server sending type.
pub struct ServerSendingUnknown;

/// Known server sending type, stored as the type parameter `S`.
pub struct ServerSending<S>(PhantomData<fn() -> S>)
where
    S: Serialize + 'static;

/// A server sending marker trait.
trait ServerSendingConfig {}

impl ServerSendingConfig for ServerSendingUnknown {}

impl<S> ServerSendingConfig for ServerSending<S> where S: Serialize + 'static {}

/// Unknown server receiving type.
pub struct ServerReceivingUnknown;

/// Known server receiving type, stored as the type parameter `R`.
pub struct ServerReceiving<R>(PhantomData<fn() -> R>)
where
    R: DeserializeOwned + 'static;

/// A server receiving marker trait.
trait ServerReceivingConfig {}

impl ServerReceivingConfig for ServerReceivingUnknown {}

impl<R> ServerReceivingConfig for ServerReceiving<R> where R: DeserializeOwned + 'static {}

/// Unknown server event reporting type.
pub struct ServerEventReportingUnknown;

/// Known server event reporting type, stored as the type parameter `E`.
pub struct ServerEventReporting<E>(E);

/// Server event reporting via callbacks.
pub struct ServerEventReportingCallbacks<R>(ServerEventCallbacks<R>)
where
    R: DeserializeOwned + 'static;

/// Server event reporting via an event handler.
pub struct ServerEventReportingHandler<R, H>
where
    R: DeserializeOwned + 'static,
    H: ServerEventHandler<R>,
{
    /// The event handler instance.
    handler: H,
    /// Phantom `R` owner.
    phantom_receive: PhantomData<fn() -> R>,
}

/// Server event reporting via a channel.
pub struct ServerEventReportingChannel;

/// A server event reporting marker trait.
trait ServerEventReportingConfig {}

impl ServerEventReportingConfig for ServerEventReportingUnknown {}

impl<R> ServerEventReportingConfig for ServerEventReporting<ServerEventReportingCallbacks<R>> where
    R: DeserializeOwned + 'static
{
}

impl<R, H> ServerEventReportingConfig for ServerEventReporting<ServerEventReportingHandler<R, H>>
where
    R: DeserializeOwned + 'static,
    H: ServerEventHandler<R>,
{
}

impl ServerEventReportingConfig for ServerEventReporting<ServerEventReportingChannel> {}

/// A builder for the [`Server`].
///
/// An instance of this can be constructed using `ServerBuilder::new()` or
/// `Server::builder()`. The configuration information exists primarily at the
/// type-level, so it is impossible to misconfigure this.
///
/// This method of configuration is technically not necessary, but it is far
/// clearer and more explicit than simply configuring the `Server` type. Plus,
/// it provides additional ways of detecting events.
///
/// # Configuration
///
/// To configure the server, first provide the types that will be sent and
/// received through the server using the `.sending::<...>()` and
/// `.receiving::<...>()` methods. Then specify the way in which events will
/// be detected. There are three methods of receiving events:
///
/// - via callback functions (`.with_event_callbacks(...)`)
/// - via implementation of a handler trait (`.with_event_handler(...)`)
/// - via a channel (`.with_event_channel()`)
///
/// The channel method is the most versatile, hence why it's the `Server`'s
/// default implementation. The other methods are provided to support a
/// greater variety of program architectures.
///
/// Once configured, the `.start(...)` method, which is effectively identical
/// to the `Server::start(...)` method, can be called to start the server.
///
/// # Example
///
/// ```no_run
/// # use rustdtp::prelude::*;
///
/// # #[tokio::main]
/// # async fn main() {
/// let (server, server_events) = Server::builder()
///     .sending::<usize>()
///     .receiving::<String>()
///     .with_event_channel()
///     .start(("127.0.0.1", 29275))
///     .await
///     .unwrap();
/// # }
/// ```
#[allow(private_bounds)]
#[must_use = "server builders do nothing unless `start` is called"]
pub struct ServerBuilder<SC, RC, EC>
where
    SC: ServerSendingConfig,
    RC: ServerReceivingConfig,
    EC: ServerEventReportingConfig,
{
    /// Phantom marker for `SC` and `RC`.
    marker: PhantomData<fn() -> (SC, RC)>,
    /// The event reporting configuration.
    event_reporting: EC,
}

impl ServerBuilder<ServerSendingUnknown, ServerReceivingUnknown, ServerEventReportingUnknown> {
    /// Creates a new server builder.
    pub const fn new() -> Self {
        Self {
            marker: PhantomData,
            event_reporting: ServerEventReportingUnknown,
        }
    }
}

impl Default
    for ServerBuilder<ServerSendingUnknown, ServerReceivingUnknown, ServerEventReportingUnknown>
{
    fn default() -> Self {
        Self::new()
    }
}

#[allow(private_bounds)]
impl<RC, EC> ServerBuilder<ServerSendingUnknown, RC, EC>
where
    RC: ServerReceivingConfig,
    EC: ServerEventReportingConfig,
{
    /// Configures the type of data the server intends to send to clients.
    pub fn sending<S>(self) -> ServerBuilder<ServerSending<S>, RC, EC>
    where
        S: Serialize + 'static,
    {
        ServerBuilder {
            marker: PhantomData,
            event_reporting: self.event_reporting,
        }
    }
}

#[allow(private_bounds)]
impl<SC, EC> ServerBuilder<SC, ServerReceivingUnknown, EC>
where
    SC: ServerSendingConfig,
    EC: ServerEventReportingConfig,
{
    /// Configures the type of data the server intends to receive from
    /// clients.
    pub fn receiving<R>(self) -> ServerBuilder<SC, ServerReceiving<R>, EC>
    where
        R: DeserializeOwned + 'static,
    {
        ServerBuilder {
            marker: PhantomData,
            event_reporting: self.event_reporting,
        }
    }
}

impl<S, R> ServerBuilder<ServerSending<S>, ServerReceiving<R>, ServerEventReportingUnknown>
where
    S: Serialize + 'static,
    R: DeserializeOwned + 'static,
{
    /// Configures the server to receive events via callbacks.
    ///
    /// Using callbacks is typically considered an anti-pattern in Rust, so
    /// this should only be used if it makes sense in the context of the
    /// design of the code utilizing this API.
    ///
    /// See [`ServerEventCallbacks`] for more information and examples.
    pub fn with_event_callbacks(
        self,
        callbacks: ServerEventCallbacks<R>,
    ) -> ServerBuilder<
        ServerSending<S>,
        ServerReceiving<R>,
        ServerEventReporting<ServerEventReportingCallbacks<R>>,
    >
    where
        R: DeserializeOwned + 'static,
    {
        ServerBuilder {
            marker: PhantomData,
            event_reporting: ServerEventReporting(ServerEventReportingCallbacks(callbacks)),
        }
    }

    /// Configures the server to receive events via a trait implementation.
    ///
    /// This provides an approach to event handling that closely aligns with
    /// object-oriented practices.
    ///
    /// See [`ServerEventHandler`] for more information and examples.
    pub fn with_event_handler<H>(
        self,
        handler: H,
    ) -> ServerBuilder<
        ServerSending<S>,
        ServerReceiving<R>,
        ServerEventReporting<ServerEventReportingHandler<R, H>>,
    >
    where
        H: ServerEventHandler<R>,
    {
        ServerBuilder {
            marker: PhantomData,
            event_reporting: ServerEventReporting(ServerEventReportingHandler {
                handler,
                phantom_receive: PhantomData,
            }),
        }
    }

    /// Configures the server to receive events via a channel.
    ///
    /// This is the most versatile event handling strategy. In fact, all other
    /// event handling options use this implementation under the hood.
    /// Because of its flexibility, this will typically be the desired
    /// approach.
    pub fn with_event_channel(
        self,
    ) -> ServerBuilder<
        ServerSending<S>,
        ServerReceiving<R>,
        ServerEventReporting<ServerEventReportingChannel>,
    > {
        ServerBuilder {
            marker: PhantomData,
            event_reporting: ServerEventReporting(ServerEventReportingChannel),
        }
    }
}

impl<S, R>
    ServerBuilder<
        ServerSending<S>,
        ServerReceiving<R>,
        ServerEventReporting<ServerEventReportingCallbacks<R>>,
    >
where
    S: Serialize + 'static,
    R: DeserializeOwned + 'static,
{
    /// Starts the server. This is effectively identical to [`Server::start`].
    ///
    /// # Errors
    ///
    /// The set of errors that can occur are identical to that of
    /// [`Server::start`].
    #[allow(clippy::future_not_send)]
    pub async fn start<A>(self, addr: A) -> Result<ServerHandle<S>>
    where
        A: ToSocketAddrs,
    {
        let (server, mut server_events) = Server::<S, R>::start(addr).await?;
        let callbacks = self.event_reporting.0 .0;

        tokio::spawn(async move {
            while let Ok(event) = server_events.next_raw().await {
                match event {
                    ServerEventRawSafe::Connect { client_id } => {
                        if let Some(ref connect) = callbacks.connect {
                            let connect = Arc::clone(connect);
                            tokio::spawn(async move {
                                (*connect)(client_id).await;
                            });
                        }
                    }
                    ServerEventRawSafe::Disconnect { client_id } => {
                        if let Some(ref disconnect) = callbacks.disconnect {
                            let disconnect = Arc::clone(disconnect);
                            tokio::spawn(async move {
                                (*disconnect)(client_id).await;
                            });
                        }
                    }
                    ServerEventRawSafe::Receive { client_id, data } => {
                        if let Some(ref receive) = callbacks.receive {
                            let receive = Arc::clone(receive);
                            tokio::spawn(async move {
                                let data = data.deserialize();
                                (*receive)(client_id, data).await;
                            });
                        }
                    }
                    ServerEventRawSafe::Stop => {
                        if let Some(ref stop) = callbacks.stop {
                            let stop = Arc::clone(stop);
                            tokio::spawn(async move {
                                (*stop)().await;
                            });
                        }
                    }
                }
            }
        });

        Ok(server)
    }
}

impl<S, R, H>
    ServerBuilder<
        ServerSending<S>,
        ServerReceiving<R>,
        ServerEventReporting<ServerEventReportingHandler<R, H>>,
    >
where
    S: Serialize + 'static,
    R: DeserializeOwned + 'static,
    H: ServerEventHandler<R> + 'static,
{
    /// Starts the server. This is effectively identical to [`Server::start`].
    ///
    /// # Errors
    ///
    /// The set of errors that can occur are identical to that of
    /// [`Server::start`].
    #[allow(clippy::future_not_send)]
    pub async fn start<A>(self, addr: A) -> Result<ServerHandle<S>>
    where
        A: ToSocketAddrs,
    {
        let (server, mut server_events) = Server::<S, R>::start(addr).await?;
        let handler = Arc::new(self.event_reporting.0.handler);

        tokio::spawn(async move {
            while let Ok(event) = server_events.next_raw().await {
                match event {
                    ServerEventRawSafe::Connect { client_id } => {
                        let handler = Arc::clone(&handler);
                        tokio::spawn(async move {
                            handler.on_connect(client_id).await;
                        });
                    }
                    ServerEventRawSafe::Disconnect { client_id } => {
                        let handler = Arc::clone(&handler);
                        tokio::spawn(async move {
                            handler.on_disconnect(client_id).await;
                        });
                    }
                    ServerEventRawSafe::Receive { client_id, data } => {
                        let handler = Arc::clone(&handler);
                        tokio::spawn(async move {
                            let data = data.deserialize();
                            handler.on_receive(client_id, data).await;
                        });
                    }
                    ServerEventRawSafe::Stop => {
                        let handler = Arc::clone(&handler);
                        tokio::spawn(async move {
                            handler.on_stop().await;
                        });
                    }
                }
            }
        });

        Ok(server)
    }
}

impl<S, R>
    ServerBuilder<
        ServerSending<S>,
        ServerReceiving<R>,
        ServerEventReporting<ServerEventReportingChannel>,
    >
where
    S: Serialize + 'static,
    R: DeserializeOwned + 'static,
{
    /// Starts the server. This is effectively identical to [`Server::start`].
    ///
    /// # Errors
    ///
    /// The set of errors that can occur are identical to that of
    /// [`Server::start`].
    #[allow(clippy::future_not_send)]
    pub async fn start<A>(self, addr: A) -> Result<(ServerHandle<S>, ServerEventStream<R>)>
    where
        A: ToSocketAddrs,
    {
        Server::<S, R>::start(addr).await
    }
}

/// A command sent from the server handle to the background server task.
pub enum ServerCommand {
    /// Stop the server.
    Stop,
    /// Send data to a client.
    Send {
        /// The ID of the client to send the data to.
        client_id: usize,
        /// The data to send.
        data: Vec<u8>,
    },
    /// Send data to all clients.
    SendAll {
        /// The data to send.
        data: Vec<u8>,
    },
    /// Get the local server address.
    GetAddr,
    /// Get the address of a client.
    GetClientAddr {
        /// The ID of the client.
        client_id: usize,
    },
    /// Disconnect a client from the server.
    RemoveClient {
        /// The ID of the client.
        client_id: usize,
    },
}

/// The return value of a command executed on the background server task.
pub enum ServerCommandReturn {
    /// Stop return value.
    Stop(Result<()>),
    /// Sent data return value.
    Send(Result<()>),
    /// Sent data to all return value.
    SendAll(Result<()>),
    /// Local server address return value.
    GetAddr(Result<SocketAddr>),
    /// Client address return value.
    GetClientAddr(Result<SocketAddr>),
    /// Disconnect client return value.
    RemoveClient(Result<()>),
}

/// A command sent from the server background task to a client background task.
pub enum ServerClientCommand {
    /// Send data to the client.
    Send {
        /// The serialized data to send.
        data: Arc<[u8]>,
    },
    /// Get the address of the client.
    GetAddr,
    /// Disconnect the client.
    Remove,
}

/// The return value of a command executed on a client background task.
pub enum ServerClientCommandReturn {
    /// Send data return value.
    Send(Result<()>),
    /// Client address return value.
    GetAddr(Result<SocketAddr>),
    /// Disconnect client return value.
    Remove(Result<()>),
}

/// An event from the server.
///
/// ```no_run
/// use rustdtp::prelude::*;
///
/// #[tokio::main]
/// async fn main() {
///     // Create the server
///     let (mut server, mut server_events) = Server::builder()
///         .sending::<()>()
///         .receiving::<String>()
///         .with_event_channel()
///         .start(("127.0.0.1", 29275))
///         .await
///         .unwrap();
///
///     // Iterate over events
///     while let Ok(event) = server_events.next().await {
///         match event {
///             ServerEvent::Connect { client_id } => {
///                 println!("Client with ID {} connected", client_id);
///             }
///             ServerEvent::Disconnect { client_id } => {
///                 println!("Client with ID {} disconnected", client_id);
///             }
///             ServerEvent::Receive { client_id, data } => {
///                 println!("Client with ID {} sent: {}", client_id, data);
///             }
///             ServerEvent::Stop => {
///                 // No more events will be sent, and the loop will end
///                 println!("Server closed");
///             }
///         }
///     }
/// }
/// ```
#[derive(Debug, Clone)]
pub enum ServerEvent<R>
where
    R: DeserializeOwned + 'static,
{
    /// A client connected.
    Connect {
        /// The ID of the client that connected.
        client_id: usize,
    },
    /// A client disconnected.
    Disconnect {
        /// The ID of the client that disconnected.
        client_id: usize,
    },
    /// Data received from a client.
    Receive {
        /// The ID of the client that sent the data.
        client_id: usize,
        /// The data itself.
        data: R,
    },
    /// Server stopped.
    Stop,
}

/// Identical to `ServerEvent`, but with the received data in serialized form.
#[derive(Debug, Clone)]
enum ServerEventRaw {
    /// A client connected.
    Connect {
        /// The ID of the client that connected.
        client_id: usize,
    },
    /// A client disconnected.
    Disconnect {
        /// The ID of the client that disconnected.
        client_id: usize,
    },
    /// Data received from a client.
    Receive {
        /// The ID of the client that sent the data.
        client_id: usize,
        /// The data itself.
        data: Vec<u8>,
    },
    /// Server stopped.
    Stop,
}

impl ServerEventRaw {
    /// Deserializes this instance into a `ServerEvent`.
    fn deserialize<R>(&self) -> Result<ServerEvent<R>>
    where
        R: DeserializeOwned + 'static,
    {
        match self {
            Self::Connect { client_id } => Ok(ServerEvent::Connect {
                client_id: *client_id,
            }),
            Self::Disconnect { client_id } => Ok(ServerEvent::Disconnect {
                client_id: *client_id,
            }),
            Self::Receive { client_id, data } => {
                Ok(
                    serde_json::from_slice(data).map(|data| ServerEvent::Receive {
                        client_id: *client_id,
                        data,
                    })?,
                )
            }
            Self::Stop => Ok(ServerEvent::Stop),
        }
    }
}

/// The serialized data component of a server receive event. The data is
/// guaranteed to be deserializable into an instance of `R`.
#[derive(Debug, Clone)]
struct ServerEventRawSafeData<R>
where
    R: DeserializeOwned + 'static,
{
    /// The raw data.
    data: Vec<u8>,
    /// Phantom marker for `R`.
    marker: PhantomData<fn() -> R>,
}

/// Identical to `ServerEventRaw`, but with the guarantee that the data can be
/// deserialized into an instance of `R`.
#[derive(Debug, Clone)]
enum ServerEventRawSafe<R>
where
    R: DeserializeOwned + 'static,
{
    /// A client connected.
    Connect {
        /// The ID of the client that connected.
        client_id: usize,
    },
    /// A client disconnected.
    Disconnect {
        /// The ID of the client that disconnected.
        client_id: usize,
    },
    /// Data received from a client.
    Receive {
        /// The ID of the client that sent the data.
        client_id: usize,
        /// The data itself.
        data: ServerEventRawSafeData<R>,
    },
    /// Server stopped.
    Stop,
}

impl<R> TryFrom<ServerEventRaw> for ServerEventRawSafe<R>
where
    R: DeserializeOwned + 'static,
{
    type Error = Error;

    fn try_from(value: ServerEventRaw) -> std::result::Result<Self, Self::Error> {
        value.deserialize::<R>()?;

        Ok(match value {
            ServerEventRaw::Connect { client_id } => Self::Connect { client_id },
            ServerEventRaw::Disconnect { client_id } => Self::Disconnect { client_id },
            ServerEventRaw::Receive { client_id, data } => Self::Receive {
                client_id,
                data: ServerEventRawSafeData {
                    data,
                    marker: PhantomData,
                },
            },
            ServerEventRaw::Stop => Self::Stop,
        })
    }
}

impl<R> ServerEventRawSafeData<R>
where
    R: DeserializeOwned + 'static,
{
    /// Deserialize the raw data into an instance of `R`. This is guaranteed to
    /// succeed.
    fn deserialize(&self) -> R {
        serde_json::from_slice(&self.data).unwrap()
    }
}

impl<R> ServerEventRawSafe<R>
where
    R: DeserializeOwned + 'static,
{
    /// Deserializes this instance into a `ServerEvent`.
    #[allow(dead_code)]
    fn deserialize(&self) -> ServerEvent<R> {
        match self {
            Self::Connect { client_id } => ServerEvent::Connect {
                client_id: *client_id,
            },
            Self::Disconnect { client_id } => ServerEvent::Disconnect {
                client_id: *client_id,
            },
            Self::Receive { client_id, data } => ServerEvent::Receive {
                client_id: *client_id,
                data: data.deserialize(),
            },
            Self::Stop => ServerEvent::Stop,
        }
    }
}

/// An asynchronous stream of server events.
pub struct ServerEventStream<R>
where
    R: DeserializeOwned + 'static,
{
    /// The event receiver channel.
    event_receiver: Receiver<ServerEventRaw>,
    /// Phantom marker for `R`.
    marker: PhantomData<fn() -> R>,
}

impl<R> ServerEventStream<R>
where
    R: DeserializeOwned + 'static,
{
    /// Consumes and returns the next value in the stream.
    ///
    /// # Errors
    ///
    /// This will return an error if the stream is closed, or if there was an
    /// error while deserializing data received.
    pub async fn next(&mut self) -> Result<ServerEvent<R>> {
        match self.event_receiver.recv().await {
            Some(serialized_event) => serialized_event.deserialize(),
            None => Err(Error::ConnectionClosed),
        }
    }

    /// Identical to `next`, but doesn't deserialize the event. It does,
    /// however, validate that the event can be deserialized without error.
    async fn next_raw(&mut self) -> Result<ServerEventRawSafe<R>> {
        match self.event_receiver.recv().await {
            Some(serialized_event) => serialized_event.try_into(),
            None => Err(Error::ConnectionClosed),
        }
    }
}

/// A handle to the server.
pub struct ServerHandle<S>
where
    S: Serialize + 'static,
{
    /// The channel through which commands can be sent to the background task.
    server_command_sender: CommandChannelSender<ServerCommand, ServerCommandReturn>,
    /// The handle to the background task.
    server_task_handle: JoinHandle<Result<()>>,
    /// Phantom marker for `S`.
    marker: PhantomData<fn() -> S>,
}

impl<S> ServerHandle<S>
where
    S: Serialize + 'static,
{
    /// Stop the server, disconnect all clients, and shut down all network
    /// interfaces.
    ///
    /// Returns a result of the error variant if an error occurred while
    /// disconnecting clients.
    ///
    /// ```no_run
    /// use rustdtp::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     // Create the server
    ///     let (mut server, mut server_events) = Server::builder()
    ///         .sending::<()>()
    ///         .receiving::<String>()
    ///         .with_event_channel()
    ///         .start(("127.0.0.1", 29275))
    ///         .await
    ///         .unwrap();
    ///
    ///     // Wait for events until a client requests the server be stopped
    ///     while let Ok(event) = server_events.next().await {
    ///         match event {
    ///             // Stop the server when a client requests it be stopped
    ///             ServerEvent::Receive { client_id, data } => {
    ///                 if data.as_str() == "Stop the server!" {
    ///                     println!("Server stop requested");
    ///                     server.stop().await.unwrap();
    ///                     break;
    ///                 }
    ///             }
    ///             _ => {}  // Do nothing for other events
    ///         }
    ///     }
    ///
    ///     // The last event should be a stop event
    ///     assert!(matches!(server_events.next().await.unwrap(), ServerEvent::Stop));
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// This will return an error if the server socket has already closed, or if
    /// the underlying server loop returned an error.
    #[allow(clippy::missing_panics_doc)]
    pub async fn stop(mut self) -> Result<()> {
        let value = self
            .server_command_sender
            .send_command(ServerCommand::Stop)
            .await?;
        // `unwrap` is allowed, as an error is returned only when the underlying
        // task panics, which it never should
        self.server_task_handle.await.unwrap()?;
        unwrap_enum!(value, ServerCommandReturn::Stop)
    }

    /// Send data to a client.
    ///
    /// - `client_id`: the ID of the client to send the data to.
    /// - `data`: the data to send.
    ///
    /// Returns a result of the error variant if an error occurred while
    /// sending.
    ///
    /// ```no_run
    /// use rustdtp::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     // Create the server
    ///     let (mut server, mut server_events) = Server::builder()
    ///         .sending::<String>()
    ///         .receiving::<()>()
    ///         .with_event_channel()
    ///         .start(("127.0.0.1", 29275))
    ///         .await
    ///         .unwrap();
    ///
    ///     // Iterate over events
    ///     while let Ok(event) = server_events.next().await {
    ///         match event {
    ///             // When a client connects, send a greeting
    ///             ServerEvent::Connect { client_id } => {
    ///                 server.send(client_id, format!("Hello, client {}!", client_id)).await.unwrap();
    ///             }
    ///             _ => {}  // Do nothing for other events
    ///         }
    ///     }
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// This will return an error if the server socket has closed, or if data
    /// serialization fails.
    #[allow(clippy::future_not_send)]
    pub async fn send(&mut self, client_id: usize, data: S) -> Result<()> {
        let data_serialized = serde_json::to_vec(&data)?;
        let value = self
            .server_command_sender
            .send_command(ServerCommand::Send {
                client_id,
                data: data_serialized,
            })
            .await?;
        unwrap_enum!(value, ServerCommandReturn::Send)
    }

    /// Send data to all clients.
    ///
    /// - `data`: the data to send.
    ///
    /// Returns a result of the error variant if an error occurred while
    /// sending.
    ///
    /// ```no_run
    /// use rustdtp::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     // Create the server
    ///     let (mut server, mut server_events) = Server::builder()
    ///         .sending::<String>()
    ///         .receiving::<()>()
    ///         .with_event_channel()
    ///         .start(("127.0.0.1", 29275))
    ///         .await
    ///         .unwrap();
    ///
    ///     // Iterate over events
    ///     while let Ok(event) = server_events.next().await {
    ///         match event {
    ///             // When a client connects, notify all clients
    ///             ServerEvent::Connect { client_id } => {
    ///                 server.send_all(format!("A new client with ID {} has joined!", client_id)).await.unwrap();
    ///             }
    ///             _ => {}  // Do nothing for other events
    ///         }
    ///     }
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// This will return an error if the server socket has closed, or if data
    /// serialization fails.
    #[allow(clippy::future_not_send)]
    pub async fn send_all(&mut self, data: S) -> Result<()> {
        let data_serialized = serde_json::to_vec(&data)?;
        let value = self
            .server_command_sender
            .send_command(ServerCommand::SendAll {
                data: data_serialized,
            })
            .await?;
        unwrap_enum!(value, ServerCommandReturn::SendAll)
    }

    /// Get the address the server is listening on.
    ///
    /// Returns a result containing the address the server is listening on, or
    /// the error variant if an error occurred.
    ///
    /// ```no_run
    /// use rustdtp::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     // Create the server
    ///     let (mut server, mut server_events) = Server::builder()
    ///         .sending::<()>()
    ///         .receiving::<()>()
    ///         .with_event_channel()
    ///         .start(("127.0.0.1", 29275))
    ///         .await
    ///         .unwrap();
    ///
    ///     // Get the server address
    ///     let addr = server.get_addr().await.unwrap();
    ///     println!("Server listening on {}", addr);
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// This will return an error if the server socket has closed.
    pub async fn get_addr(&mut self) -> Result<SocketAddr> {
        let value = self
            .server_command_sender
            .send_command(ServerCommand::GetAddr)
            .await?;
        unwrap_enum!(value, ServerCommandReturn::GetAddr)
    }

    /// Get the address of a connected client.
    ///
    /// - `client_id`: the ID of the client.
    ///
    /// Returns a result containing the address of the client, or the error
    /// variant if the client ID is invalid.
    ///
    /// ```no_run
    /// use rustdtp::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     // Create the server
    ///     let (mut server, mut server_events) = Server::builder()
    ///         .sending::<()>()
    ///         .receiving::<()>()
    ///         .with_event_channel()
    ///         .start(("127.0.0.1", 29275))
    ///         .await
    ///         .unwrap();
    ///
    ///     // Iterate over events
    ///     while let Ok(event) = server_events.next().await {
    ///         match event {
    ///             // When a client connects, get their address
    ///             ServerEvent::Connect { client_id } => {
    ///                 let addr = server.get_client_addr(client_id).await.unwrap();
    ///                 println!("Client with ID {} connected from {}", client_id, addr);
    ///             }
    ///             _ => {}  // Do nothing for other events
    ///         }
    ///     }
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// This will return an error if the server socket has closed, or if the
    /// client ID is invalid.
    pub async fn get_client_addr(&mut self, client_id: usize) -> Result<SocketAddr> {
        let value = self
            .server_command_sender
            .send_command(ServerCommand::GetClientAddr { client_id })
            .await?;
        unwrap_enum!(value, ServerCommandReturn::GetClientAddr)
    }

    /// Disconnect a client from the server.
    ///
    /// - `client_id`: the ID of the client.
    ///
    /// Returns a result of the error variant if an error occurred while
    /// disconnecting the client, or if the client ID is invalid.
    ///
    /// ```no_run
    /// use rustdtp::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     // Create the server
    ///     let (mut server, mut server_events) = Server::builder()
    ///         .sending::<String>()
    ///         .receiving::<i32>()
    ///         .with_event_channel()
    ///         .start(("127.0.0.1", 29275))
    ///         .await
    ///         .unwrap();
    ///
    ///     // Iterate over events
    ///     while let Ok(event) = server_events.next().await {
    ///         match event {
    ///             // Disconnect a client if they send an even number
    ///             ServerEvent::Receive { client_id, data } => {
    ///                 if data % 2 == 0 {
    ///                     println!("Disconnecting client with ID {}", client_id);
    ///                     server.send(client_id, "Even numbers are not allowed".to_owned()).await.unwrap();
    ///                     server.remove_client(client_id).await.unwrap();
    ///                 }
    ///             }
    ///             _ => {}  // Do nothing for other events
    ///         }
    ///     }
    ///
    ///     // The last event should be a stop event
    ///     assert!(matches!(server_events.next().await.unwrap(), ServerEvent::Stop));
    /// }
    /// ```
    ///
    /// # Errors
    ///
    /// This will return an error if the server socket has closed, or if the
    /// client ID is invalid.
    pub async fn remove_client(&mut self, client_id: usize) -> Result<()> {
        let value = self
            .server_command_sender
            .send_command(ServerCommand::RemoveClient { client_id })
            .await?;
        unwrap_enum!(value, ServerCommandReturn::RemoveClient)
    }
}

/// A socket server.
///
/// The server takes two generic parameters:
///
/// - `S`: the type of data that will be **sent** to clients.
/// - `R`: the type of data that will be **received** from clients.
///
/// Both types must be serializable in order to be sent through the socket. When
/// creating clients, the types should be swapped, since the server's send type will be the client's receive type and vice versa.
///
/// ```no_run
/// use rustdtp::prelude::*;
///
/// #[tokio::main]
/// async fn main() {
///     // Create a server that receives strings and returns the length of each string
///     let (mut server, mut server_events) = Server::builder()
///         .sending::<usize>()
///         .receiving::<String>()
///         .with_event_channel()
///         .start(("127.0.0.1", 29275))
///         .await
///         .unwrap();
///
///     // Iterate over events
///     while let Ok(event) = server_events.next().await {
///         match event {
///             ServerEvent::Connect { client_id } => {
///                 println!("Client with ID {} connected", client_id);
///             }
///             ServerEvent::Disconnect { client_id } => {
///                 println!("Client with ID {} disconnected", client_id);
///             }
///             ServerEvent::Receive { client_id, data } => {
///                 // Send back the length of the string
///                 server.send(client_id, data.len()).await.unwrap();
///             }
///             ServerEvent::Stop => {
///                 // No more events will be sent, and the loop will end
///                 println!("Server closed");
///             }
///         }
///     }
/// }
/// ```
pub struct Server<S, R>
where
    S: Serialize + 'static,
    R: DeserializeOwned + 'static,
{
    /// Phantom marker for `S` and `R`.
    marker: PhantomData<fn() -> (S, R)>,
}

impl Server<(), ()> {
    /// Constructs a server builder. Use this for a clearer, more explicit,
    /// and more featureful server configuration. See [`ServerBuilder`] for
    /// more information.
    pub const fn builder(
    ) -> ServerBuilder<ServerSendingUnknown, ServerReceivingUnknown, ServerEventReportingUnknown>
    {
        ServerBuilder::new()
    }
}

impl<S, R> Server<S, R>
where
    S: Serialize + 'static,
    R: DeserializeOwned + 'static,
{
    /// Start a socket server.
    ///
    /// - `addr`: the address for the server to listen on.
    ///
    /// Returns a result containing a handle to the server and a channel from
    /// which to receive server events, or the error variant if an error
    /// occurred while starting the server.
    ///
    /// ```no_run
    /// use rustdtp::prelude::*;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let (mut server, mut server_events) = Server::builder()
    ///         .sending::<()>()
    ///         .receiving::<()>()
    ///         .with_event_channel()
    ///         .start(("127.0.0.1", 29275))
    ///         .await
    ///         .unwrap();
    /// }
    /// ```
    ///
    /// Neither the server handle nor the event receiver should be dropped until
    /// the server has been stopped. Prematurely dropping either one can cause
    /// unintended behavior.
    ///
    /// # Errors
    ///
    /// This will return an error if a TCP listener cannot be bound to the
    /// provided address.
    #[allow(clippy::future_not_send)]
    pub async fn start<A>(addr: A) -> Result<(ServerHandle<S>, ServerEventStream<R>)>
    where
        A: ToSocketAddrs,
    {
        // Server TCP listener
        let listener = TcpListener::bind(addr).await?;
        // Channels for sending commands from the server handle to the background server task
        let (server_command_sender, server_command_receiver) = command_channel();
        // Channels for sending event notifications from the background server task
        let (server_event_sender, server_event_receiver) = channel(CHANNEL_BUFFER_SIZE);

        // Start the background server task, saving the join handle for when the server is stopped
        let server_task_handle = tokio::spawn(server_handler(
            listener,
            server_event_sender,
            server_command_receiver,
        ));

        // Create a handle for the server
        let server_handle = ServerHandle {
            server_command_sender,
            server_task_handle,
            marker: PhantomData,
        };

        // Create an event stream for the server
        let server_event_stream = ServerEventStream {
            event_receiver: server_event_receiver,
            marker: PhantomData,
        };

        Ok((server_handle, server_event_stream))
    }
}

/// The server client loop. Handles received data and commands.
#[allow(clippy::too_many_lines)]
async fn server_client_loop(
    client_id: usize,
    mut socket: TcpStream,
    server_client_event_sender: Sender<ServerEventRaw>,
    mut client_command_receiver: CommandChannelReceiver<
        ServerClientCommand,
        ServerClientCommandReturn,
    >,
) -> Result<()> {
    // Generate X25519 keys
    let (public_key, secret_key) = dh_key_pair().await;
    // Send the public key to the client
    socket.write_all(public_key.as_bytes()).await?;
    // Flush the stream
    socket.flush().await?;

    // Buffer in which to receive the client's public key
    let mut other_public_key = [0; PUBLIC_KEY_SIZE];
    // Read the public key from the client
    handshake_timeout! {
        socket.read_exact(&mut other_public_key)
    }??;
    // Establish the shared AES key
    let aes_key = dh_shared_key(secret_key, other_public_key).await;

    // Buffer in which to receive the size portion of a message
    let mut size_buffer = [0; LEN_SIZE];

    // Client loop
    loop {
        // Await messages from the client
        // and commands from the background server task
        tokio::select! {
            // Read the size portion from the client socket
            read_value = socket.read(&mut size_buffer[..]) => {
                // Return an error if the socket could not be read
                let n_size = read_value?;

                // If there were no bytes read, or if there were fewer bytes
                // read than there should have been, close the socket
                if n_size != LEN_SIZE {
                    socket.shutdown().await?;
                    break;
                }

                // Decode the size portion of the message
                let encrypted_data_size = decode_message_size(&size_buffer);
                // Initialize the buffer for the data portion of the message
                let mut encrypted_data_buffer = vec![0; encrypted_data_size];

                // Read the data portion from the client socket, returning an
                // error if the socket could not be read
                let n_data = data_read_timeout! {
                    socket.read_exact(&mut encrypted_data_buffer[..])
                }??;

                // If there were no bytes read, or if there were fewer bytes
                // read than there should have been, close the socket
                if n_data != encrypted_data_size {
                    socket.shutdown().await?;
                    break;
                }

                // Decrypt the data
                let data_serialized = aes_decrypt(aes_key, encrypted_data_buffer.into()).await?;

                // Send an event to note that a piece of data has been received from
                // a client
                if let Err(_e) = server_client_event_sender.send(ServerEventRaw::Receive { client_id, data: data_serialized }).await {
                    // Sending failed, disconnect the client
                    socket.shutdown().await?;
                    break;
                }
            }
            // Process a command sent to the client
            client_command_value = client_command_receiver.recv_command() => {
                // Handle the command, or lack thereof if the channel is closed
                match client_command_value {
                    Ok(client_command) => {
                        // Process the command
                        match client_command {
                            ServerClientCommand::Send { data } => {
                                let value = 'val: {
                                    // Encrypt the serialized data
                                    let encrypted_data_buffer = break_on_err!(aes_encrypt(aes_key, data).await, 'val);
                                    // Encode the message size to a buffer
                                    let size_buffer = encode_message_size(encrypted_data_buffer.len());

                                    // Initialize the message buffer
                                    let mut buffer = vec![];
                                    // Extend the buffer to contain the payload
                                    // size
                                    buffer.extend_from_slice(&size_buffer);
                                    // Extend the buffer to contain the payload
                                    // data
                                    buffer.extend(&encrypted_data_buffer);

                                    // Write the data to the client socket
                                    break_on_err!(socket.write_all(&buffer).await, 'val);
                                    // Flush the stream
                                    break_on_err!(socket.flush().await, 'val);

                                    Ok(())
                                };

                                let error_occurred = value.is_err();

                                // Return the status of the send operation
                                if let Err(_e) = client_command_receiver.command_return(ServerClientCommandReturn::Send(value)).await {
                                    // Channel is closed, disconnect the client
                                    socket.shutdown().await?;
                                    break;
                                }

                                // If the send failed, disconnect the client
                                if error_occurred {
                                    socket.shutdown().await?;
                                    break;
                                }
                            },
                            ServerClientCommand::GetAddr => {
                                // Get the client socket's address
                                let addr = socket.peer_addr();

                                // Return the address
                                if let Err(_e) = client_command_receiver.command_return(ServerClientCommandReturn::GetAddr(addr.map_err(Into::into))).await {
                                    // Channel is closed, disconnect the client
                                    socket.shutdown().await?;
                                    break;
                                }
                            },
                            ServerClientCommand::Remove => {
                                // Disconnect the client
                                let value = socket.shutdown().await;

                                // Return the status of the remove operation,
                                // ignoring failures, since a failure indicates
                                // that the client has probably already
                                // disconnected
                                _ = client_command_receiver.command_return(ServerClientCommandReturn::Remove(value.map_err(Into::into))).await;

                                // Break the client loop
                                break;
                            },
                        }
                    },
                    Err(_e) => {
                        // Channel is closed, disconnect the client
                        socket.shutdown().await?;
                        break;
                    },
                }
            }
        }
    }

    Ok(())
}

/// Starts a server client loop in the background.
fn server_client_handler(
    client_id: usize,
    socket: TcpStream,
    server_client_event_sender: Sender<ServerEventRaw>,
    client_cleanup_sender: Sender<usize>,
) -> (
    CommandChannelSender<ServerClientCommand, ServerClientCommandReturn>,
    JoinHandle<Result<()>>,
) {
    // Channels for sending commands from the background server task to a background client task
    let (client_command_sender, client_command_receiver) = command_channel();

    // Start a background client task, saving the join handle for when the
    // server is stopped
    let client_task_handle = tokio::spawn(async move {
        let res = server_client_loop(
            client_id,
            socket,
            server_client_event_sender,
            client_command_receiver,
        )
        .await;

        // Tell the server to clean up after the client, ignoring failures,
        // since a failure indicates that the server has probably closed
        _ = client_cleanup_sender.send(client_id).await;

        res
    });

    (client_command_sender, client_task_handle)
}

/// The server loop. Handles incoming connections and commands.
#[allow(clippy::too_many_lines)]
async fn server_loop(
    listener: TcpListener,
    server_event_sender: Sender<ServerEventRaw>,
    mut server_command_receiver: CommandChannelReceiver<ServerCommand, ServerCommandReturn>,
    client_command_senders: &mut HashMap<
        usize,
        CommandChannelSender<ServerClientCommand, ServerClientCommandReturn>,
    >,
    client_join_handles: &mut HashMap<usize, JoinHandle<Result<()>>>,
) -> Result<()> {
    // ID assigned to the next client
    let mut next_client_id = 0usize;
    // Channel for indicating that a client needs to be cleaned up after
    let (server_client_cleanup_sender, mut server_client_cleanup_receiver) =
        channel::<usize>(CHANNEL_BUFFER_SIZE);

    // Server loop
    loop {
        // Await new clients connecting,
        // commands from the server handle,
        // and notifications of clients disconnecting
        tokio::select! {
            // Accept a connecting client
            accept_value = listener.accept() => {
                // Get the client socket, exiting if an error occurs
                let (socket, _) = accept_value?;
                // New client ID
                let client_id = next_client_id;
                // Increment next client ID
                next_client_id += 1;
                // Clone the event sender so the background client tasks can
                // send events
                let server_client_event_sender = server_event_sender.clone();
                // Clone the client cleanup sender to the background client
                // tasks can be cleaned up properly
                let client_cleanup_sender = server_client_cleanup_sender.clone();

                // Handle the new connection
                let (client_command_sender, client_task_handle) = server_client_handler(client_id, socket, server_client_event_sender, client_cleanup_sender);
                // Keep track of client command senders
                client_command_senders.insert(client_id, client_command_sender);
                // Keep track of client task handles
                client_join_handles.insert(client_id, client_task_handle);

                // Send an event to note that a client has connected
                // successfully
                if let Err(_e) = server_event_sender
                    .send(ServerEventRaw::Connect { client_id })
                    .await
                {
                    // Server is probably closed
                    break;
                }
            },
            // Process a command from the server handle
            command_value = server_command_receiver.recv_command() => {
                // Handle the command, or lack thereof if the channel is closed
                match command_value {
                    Ok(command) => {
                        match command {
                            ServerCommand::Stop => {
                                // If a command fails to send, the server has
                                // already closed, and the error can be ignored.
                                // It should be noted that this is not where the
                                // stop method actually returns its `Result`.
                                // This immediately returns with an `Ok` status.
                                // The real return value is the `Result`
                                // returned from the server task join handle.
                                _ = server_command_receiver.command_return(ServerCommandReturn::Stop(Ok(()))).await;

                                // Break the server loop, the clients will be
                                // disconnected before the task ends
                                break;
                            },
                            ServerCommand::Send { client_id, data } => {
                                let value = match client_command_senders.get_mut(&client_id) {
                                    Some(client_command_sender) => {
                                        // Turn `Vec<u8>` into `Arc<[u8]>`,
                                        // making it more easily shareable
                                        let shareable_data = Arc::<[u8]>::from(data);

                                        match client_command_sender.send_command(ServerClientCommand::Send { data: shareable_data }).await {
                                            Ok(return_value) => unwrap_enum!(return_value, ServerClientCommandReturn::Send),
                                            Err(_e) => {
                                                // The channel is closed, and
                                                // the client has probably been
                                                // disconnected, so the error
                                                // can be ignored
                                                Ok(())
                                            },
                                        }
                                    },
                                    None => Err(Error::InvalidClientId(client_id)),
                                };

                                // If a command fails to send, the client has probably disconnected,
                                // and the error can be ignored
                                _ = server_command_receiver.command_return(ServerCommandReturn::Send(value)).await;
                            },
                            ServerCommand::SendAll { data } => {
                                let value = {
                                    // Turn `Vec<u8>` into `Arc<[u8]>`, making
                                    // it more easily shareable
                                    let shareable_data = Arc::<[u8]>::from(data);

                                    let send_futures = client_command_senders.iter_mut().map(|(_client_id, client_command_sender)| async {
                                        match client_command_sender.send_command(ServerClientCommand::Send { data: Arc::clone(&shareable_data) }).await {
                                            Ok(return_value) => unwrap_enum!(return_value, ServerClientCommandReturn::Send),
                                            Err(_e) => {
                                                // The channel is closed, and
                                                // the client has probably been
                                                // disconnected, so the error
                                                // can be ignored
                                                Ok(())
                                            }
                                        }
                                    });

                                    let resolved = futures::future::join_all(send_futures).await;
                                    resolved.into_iter().collect::<Result<Vec<_>>>().map(|_| ())
                                };

                                // If a command fails to send, the client has
                                // probably disconnected, and the error can be
                                // ignored
                                _ = server_command_receiver.command_return(ServerCommandReturn::SendAll(value)).await;
                            },
                            ServerCommand::GetAddr => {
                                // Get the server listener's address
                                let addr = listener.local_addr();

                                // If a command fails to send, the client has
                                // probably disconnected, and the error can be
                                // ignored
                                _ = server_command_receiver.command_return(ServerCommandReturn::GetAddr(addr.map_err(Into::into))).await;
                            },
                            ServerCommand::GetClientAddr { client_id } => {
                                let value = match client_command_senders.get_mut(&client_id) {
                                    Some(client_command_sender) => match client_command_sender.send_command(ServerClientCommand::GetAddr).await {
                                        Ok(return_value) => unwrap_enum!(return_value, ServerClientCommandReturn::GetAddr),
                                        Err(_e) => {
                                            // The channel is closed, and the
                                            // client has probably been
                                            // disconnected, so the error can be
                                            // treated as an invalid client
                                            // error
                                            Err(Error::InvalidClientId(client_id))
                                        },
                                    },
                                    None => Err(Error::InvalidClientId(client_id)),
                                };

                                // If a command fails to send, the client has
                                // probably disconnected, and the error can be
                                // ignored
                                _ = server_command_receiver.command_return(ServerCommandReturn::GetClientAddr(value)).await;
                            },
                            ServerCommand::RemoveClient { client_id } => {
                                let value = match client_command_senders.get_mut(&client_id) {
                                    Some(client_command_sender) => match client_command_sender.send_command(ServerClientCommand::Remove).await {
                                        Ok(return_value) => unwrap_enum!(return_value, ServerClientCommandReturn::Remove),
                                        Err(_e) => {
                                            // The channel is closed, and the
                                            // client has probably been
                                            // disconnected, so the error can be
                                            // ignored
                                            Ok(())
                                        },
                                    },
                                    None => Err(Error::InvalidClientId(client_id)),
                                };

                                // If a command fails to send, the client has
                                // probably disconnected already, and the error
                                // can be ignored
                                _ = server_command_receiver.command_return(ServerCommandReturn::RemoveClient(value)).await;
                            },
                        }
                    },
                    Err(_e) => {
                        // Server is probably closed, exit
                        break;
                    },
                }
            }
            // Clean up after a disconnecting client
            disconnecting_client_id = server_client_cleanup_receiver.recv() => {
                match disconnecting_client_id {
                    Some(client_id) => {
                        // Remove the client's command sender, which will be
                        // dropped after this block ends
                        client_command_senders.remove(&client_id);

                        // Remove the client's join handle
                        if let Some(handle) = client_join_handles.remove(&client_id) {
                            // Join the client's handle
                            if let Err(e) = handle.await.unwrap() {
                                if cfg!(test) {
                                    // If testing, fail
                                    Err(e)?;
                                } else {
                                    // If not testing, ignore client handler
                                    // errors
                                }
                            }
                        }

                        // Send an event to note that a client has disconnected
                        if let Err(_e) = server_event_sender.send(ServerEventRaw::Disconnect { client_id }).await {
                            // Server is probably closed, exit
                            break;
                        }
                    },
                    None => {
                        // Server is probably closed, exit
                        break;
                    },
                }
            }
        }
    }

    Ok(())
}

/// Starts the server loop task in the background.
async fn server_handler(
    listener: TcpListener,
    server_event_sender: Sender<ServerEventRaw>,
    server_command_receiver: CommandChannelReceiver<ServerCommand, ServerCommandReturn>,
) -> Result<()> {
    // Collection of channels for sending commands from the background server
    // task to a background client task
    let mut client_command_senders: HashMap<
        usize,
        CommandChannelSender<ServerClientCommand, ServerClientCommandReturn>,
    > = HashMap::new();
    // Background client task join handles
    let mut client_join_handles: HashMap<usize, JoinHandle<Result<()>>> = HashMap::new();

    // Wrap server loop in a block to catch all exit scenarios
    let server_exit = server_loop(
        listener,
        server_event_sender.clone(),
        server_command_receiver,
        &mut client_command_senders,
        &mut client_join_handles,
    )
    .await;

    // Send a remove command to all clients
    futures::future::join_all(client_command_senders.into_values().map(
        |mut client_command_sender| async move {
            // If a command fails to send, the client has probably disconnected
            // already, and the error can be ignored
            _ = client_command_sender
                .send_command(ServerClientCommand::Remove)
                .await;
        },
    ))
    .await;

    // Join all background client tasks before exiting
    futures::future::join_all(client_join_handles.into_values().map(|handle| async move {
        if let Err(e) = handle.await.unwrap() {
            if cfg!(test) {
                // If testing, fail
                Err(e)?;
            } else {
                // If not testing, ignore client handler errors
            }
        }

        Ok(())
    }))
    .await
    .into_iter()
    .collect::<Result<Vec<_>>>()?;

    // Send a stop event, ignoring send errors
    _ = server_event_sender.send(ServerEventRaw::Stop).await;

    // Return server loop result
    server_exit
}