zonai 0.0.2

Synchronous packet-framed TCP clients and servers
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
//! Packet TCP server with a background I/O thread.
//!
//! This module exposes a simple event stream (`Accept`, `Packet`, `Lost`) plus
//! `send()` for replies.
//!
//! The server is protocol agnostic. Implement:
//! - [`PacketIn`] to decode one incoming packet from a `Read`.
//! - [`PacketOut`] to encode one outgoing packet into a `Write`.
//!
//! Often you will use one type for both directions, but this isn't required.
//!
//! ## Quick start
//!
//! ```no_run
//! use std::io::{self, Read, Write};
//! use std::net::SocketAddr;
//! use zonai::{
//!     packet::{PacketIn, PacketOut},
//!     server::{Server, ServerEvent},
//! };
//!
//! // simple u16 big-endian length-prefixed UTF-8 string
//! #[derive(Clone, PartialEq, Eq)]
//! struct Packet(String);
//!
//! impl PacketIn for Packet {
//!     fn read(r: &mut impl Read) -> io::Result<Self> {
//!         let mut len = [0u8; 2];
//!         r.read_exact(&mut len)?;
//!         let n = u16::from_be_bytes(len) as usize;
//!         let mut buf = vec![0u8; n];
//!         r.read_exact(&mut buf)?;
//!         Ok(Packet(String::from_utf8(buf).expect("utf8")))
//!     }
//! }
//!
//! impl PacketOut for Packet {
//!     fn write(&self, w: &mut impl Write) -> io::Result<()> {
//!         let b = self.0.as_bytes();
//!         w.write_all(&(b.len() as u16).to_be_bytes())?;
//!         w.write_all(b)?;
//!         Ok(())
//!     }
//! }
//!
//! fn main() -> io::Result<()> {
//!     let addr: SocketAddr = "127.0.0.1:4000".parse().unwrap();
//!     let server = Server::<Packet, Packet>::bind(addr)?;
//!
//!     loop {
//!         match server.poll()? {
//!             Some(ServerEvent::Accept { client, peer_addr }) => {
//!                 println!("accepted {peer_addr}");
//!                 // say hello
//!                 server.send(client, Packet("hello".into()))?;
//!             }
//!             Some(ServerEvent::Packet { client, packet: Packet(s) }) => {
//!                 server.send(client, Packet(format!("got:{s}")))?;
//!             }
//!             Some(ServerEvent::Lost { client: _, error }) => {
//!                 if let Some(e) = error {
//!                     eprintln!("client lost: {e}");
//!                 }
//!                 // if None, it was clean, so no need to worry!
//!             }
//!             None => {
//!                 // no events right now
//!             }
//!         }
//!     }
//! }
//! ```
//!
//! ## Event semantics
//! - `Accept { client, peer_addr }`: a TCP connection was accepted, including
//!   its remote socket address.
//! - `Packet { client, packet }`: a full packet was decoded.
//! - `Lost { client, error }`: the client disconnected or was dropped.
//!   `error == None` means a clean/intentional close. Otherwise it's the cause.
//! - If the public event queue fills, accepts and socket reads pause until the
//!   application drains events with [`Server::poll`]. Lifecycle commands,
//!   queued writes, timeout expiration, and shutdown remain active.
//!
//! ## Framing contract
//! - `PacketIn::read` must decode exactly one incoming/serverbound packet from
//!   the given `Read`.
//! - `PacketOut::write` must encode exactly one outgoing/clientbound packet to
//!   the given `Write`.
//! - Return `Err(ErrorKind::UnexpectedEof)` when more bytes are needed;
//!   the server will buffer and retry later.
//! - On successful decode, the reader cursor position is treated as the number
//!   of bytes consumed. Decoders must not read beyond one packet.
//! - Return any other read error for protocol/fatal failures; the server drops
//!   the client and emits `Lost` with that error.
//! - With [`Server::bind_with_protocol_error`], `InvalidData` from `read`
//!   invokes the protocol error hook. The returned packet is queued on a
//!   priority path, then the client is disconnected after that packet flushes.
//!
//! ## Half-close & EOF behavior
//! - If the peer half closes write, the server flushes output that was already
//!   queued for that client, then finalizes the connection. Once EOF is
//!   processed, later `send()` commands for that client are rejected.
//! - If the peer half closes read, the server finalizes the connection.
//!
//! ## Buffers & backpressure
//! - Buffer and queue limits are controlled by [`ServerConfig`].
//! - Idle and packet-assembly timeouts are finite by default. An assembly
//!   deadline starts on the first incomplete decode and is not extended by
//!   incoming fragments. Either timeout can be explicitly disabled.
//! - Accepted sockets enable `TCP_NODELAY` and TCP keepalive by default. These
//!   options are configurable through [`ServerConfig`].
//! - [`Server::from_listener`] accepts a pre-bound listener for socket
//!   activation and deployment-specific listener configuration.
//! - Pending public events preserve order and are bounded by the configured
//!   maximum-client count plus one intake event.
//! - Accept, command, decode, read, and write budgets bound the work performed
//!   in one worker iteration. Unfinished readiness is resumed in FIFO order.
//! - `send()` is non-blocking. `Ok(())` means the send command was accepted
//!   into the server command queue, not that it was queued for that client,
//!   written to the socket, or delivered to the peer.
//! - `send()` returns an error if the packet command queue is full or the
//!   server has shut down. Disconnect and shutdown commands use a separate
//!   bounded priority queue.
//!
//! ## Features
//!
//! - `serde` implements `Serialize` and `Deserialize` for [`ServerConfig`].
#![cfg_attr(
    feature = "stats",
    doc = "- `stats` enables [`ServerStats`] and [`Server::stats`]. Byte counters include successful socket reads and writes; `bytes_consumed` tracks bytes accepted by successful packet decoders. Received-packet counters increase after decoding; sent-packet counters increase after all encoded bytes are written to the socket."
)]
#![cfg_attr(
    not(feature = "stats"),
    doc = "- `stats` enables `ServerStats` and `Server::stats`. Byte counters include successful socket reads and writes; `bytes_consumed` tracks bytes accepted by successful packet decoders. Received-packet counters increase after decoding; sent-packet counters increase after all encoded bytes are written to the socket."
)]
use std::{
    collections::{HashMap, VecDeque},
    fmt::Display,
    io::{self, Cursor, Read, Write},
    net::{Shutdown, SocketAddr, TcpListener as StdTcpListener},
    sync::{
        Arc, Mutex,
        atomic::{AtomicBool, AtomicU64, Ordering},
    },
    thread,
    time::Duration,
};

use crossbeam_channel::{Receiver, Sender, TryRecvError, TrySendError, bounded};
use mio::{
    Events, Interest, Poll, Token, Waker,
    event::Event,
    net::{TcpListener, TcpStream},
};
use socket2::{SockRef, TcpKeepalive};

use crate::packet::encode_bounded;
pub use crate::packet::{PacketIn, PacketOut};

/// Resource limits used by a [`Server`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, better_default::Default)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(default))]
pub struct ServerConfig {
    /// Maximum number of queued packet-send commands.
    #[default(DEFAULT_COMMAND_QUEUE_LIMIT)]
    pub command_queue_limit: usize,
    /// Maximum number of queued lifecycle commands.
    #[default(DEFAULT_CONTROL_QUEUE_LIMIT)]
    pub control_queue_limit: usize,
    /// Maximum number of queued public events.
    #[default(DEFAULT_EVENT_QUEUE_LIMIT)]
    pub event_queue_limit: usize,
    /// Maximum number of simultaneously connected clients.
    #[default(DEFAULT_MAX_CLIENTS)]
    pub max_clients: usize,
    /// Whether to disable Nagle's algorithm on accepted sockets.
    #[default(true)]
    pub nodelay: bool,
    /// TCP keepalive idle time for accepted sockets, or `None` to disable it.
    #[default(Some(DEFAULT_KEEPALIVE_TIME))]
    pub keepalive_time: Option<Duration>,
    /// Disconnect clients that have no successful reads or writes for this long.
    #[default(Some(DEFAULT_IDLE_TIMEOUT))]
    pub idle_timeout: Option<Duration>,
    /// Disconnect clients that take longer than this to assemble one packet.
    ///
    /// The deadline starts when a decoder first reports an incomplete buffered
    /// packet and does not move when more fragments arrive.
    #[default(Some(DEFAULT_PACKET_ASSEMBLY_TIMEOUT))]
    pub packet_assembly_timeout: Option<Duration>,
    /// Initial allocation for each client's incoming byte buffer.
    #[default(DEFAULT_INCOMING_BUFFER_INITIAL)]
    pub incoming_buffer_initial: usize,
    /// Maximum size of one client's incoming byte buffer.
    #[default(DEFAULT_INCOMING_BUFFER_LIMIT)]
    pub incoming_buffer_limit: usize,
    /// Maximum queued outgoing bytes per client and encoded packet size.
    #[default(DEFAULT_OUTGOING_BUFFER_LIMIT)]
    pub outgoing_buffer_limit: usize,
    /// Maximum queued outgoing bytes across all connected clients.
    #[default(DEFAULT_GLOBAL_OUTGOING_BUFFER_LIMIT)]
    pub global_outgoing_buffer_limit: usize,
    /// Maximum number of queued outgoing packets per client.
    #[default(DEFAULT_OUTGOING_PACKET_QUEUE_LIMIT)]
    pub outgoing_packet_queue_limit: usize,
    /// Maximum accepted connections processed in one worker iteration.
    #[default(DEFAULT_ACCEPT_BUDGET)]
    pub accept_budget: usize,
    /// Maximum lifecycle commands processed in one worker iteration.
    #[default(DEFAULT_CONTROL_COMMAND_BUDGET)]
    pub control_command_budget: usize,
    /// Maximum packet-send commands processed in one worker iteration.
    #[default(DEFAULT_PACKET_COMMAND_BUDGET)]
    pub packet_command_budget: usize,
    /// Maximum incoming packets decoded in one worker iteration.
    #[default(DEFAULT_PACKET_DECODE_BUDGET)]
    pub packet_decode_budget: usize,
    /// Maximum socket bytes read in one worker iteration.
    #[default(DEFAULT_READ_BYTE_BUDGET)]
    pub read_byte_budget: usize,
    /// Maximum socket bytes written in one worker iteration.
    #[default(DEFAULT_WRITE_BYTE_BUDGET)]
    pub write_byte_budget: usize,
}

impl ServerConfig {
    fn validate(self) -> io::Result<Self> {
        let nonzero = [
            (self.command_queue_limit, "command_queue_limit"),
            (self.control_queue_limit, "control_queue_limit"),
            (self.event_queue_limit, "event_queue_limit"),
            (self.max_clients, "max_clients"),
            (self.incoming_buffer_initial, "incoming_buffer_initial"),
            (self.outgoing_buffer_limit, "outgoing_buffer_limit"),
            (
                self.global_outgoing_buffer_limit,
                "global_outgoing_buffer_limit",
            ),
            (
                self.outgoing_packet_queue_limit,
                "outgoing_packet_queue_limit",
            ),
            (self.accept_budget, "accept_budget"),
            (self.control_command_budget, "control_command_budget"),
            (self.packet_command_budget, "packet_command_budget"),
            (self.packet_decode_budget, "packet_decode_budget"),
            (self.read_byte_budget, "read_byte_budget"),
            (self.write_byte_budget, "write_byte_budget"),
        ];
        if let Some((_, name)) = nonzero.into_iter().find(|(value, _)| *value == 0) {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!("{name} must be greater than zero"),
            ));
        }
        if self.incoming_buffer_limit < self.incoming_buffer_initial {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "incoming_buffer_limit must be at least incoming_buffer_initial",
            ));
        }
        if self.max_clients == usize::MAX {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "max_clients must be less than usize::MAX",
            ));
        }
        for (timeout, name) in [
            (self.idle_timeout, "idle_timeout"),
            (self.packet_assembly_timeout, "packet_assembly_timeout"),
            (self.keepalive_time, "keepalive_time"),
        ] {
            if timeout.is_some_and(|timeout| timeout.is_zero()) {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidInput,
                    format!("{name} must be greater than zero when enabled"),
                ));
            }
        }
        Ok(self)
    }
}

/// Default maximum number of queued packet-send commands.
pub const DEFAULT_COMMAND_QUEUE_LIMIT: usize = 4096 * 2;
/// Default maximum number of queued lifecycle commands.
pub const DEFAULT_CONTROL_QUEUE_LIMIT: usize = 1024;
/// Default maximum number of queued public events.
pub const DEFAULT_EVENT_QUEUE_LIMIT: usize = 4096;
/// Default maximum number of simultaneously connected clients.
pub const DEFAULT_MAX_CLIENTS: usize = 4096;
/// Default accepted-socket TCP keepalive idle time.
pub const DEFAULT_KEEPALIVE_TIME: Duration = Duration::from_secs(60);
/// Default inactivity timeout for connected clients.
pub const DEFAULT_IDLE_TIMEOUT: Duration = Duration::from_secs(5 * 60);
/// Default deadline for assembling one incoming packet.
pub const DEFAULT_PACKET_ASSEMBLY_TIMEOUT: Duration = Duration::from_secs(30);
/// Default initial incoming buffer allocation per client.
pub const DEFAULT_INCOMING_BUFFER_INITIAL: usize = 4096;
/// Default maximum incoming buffer size per client.
pub const DEFAULT_INCOMING_BUFFER_LIMIT: usize = 64 * 1024;
/// Default maximum queued outgoing bytes per client.
pub const DEFAULT_OUTGOING_BUFFER_LIMIT: usize = 1024 * 1024;
/// Default maximum queued outgoing bytes across all connected clients.
pub const DEFAULT_GLOBAL_OUTGOING_BUFFER_LIMIT: usize = 64 * 1024 * 1024;
/// Default maximum number of queued outgoing packets per client.
pub const DEFAULT_OUTGOING_PACKET_QUEUE_LIMIT: usize = 1024;
/// Default maximum accepted connections processed in one worker iteration.
pub const DEFAULT_ACCEPT_BUDGET: usize = 64;
/// Default maximum lifecycle commands processed in one worker iteration.
pub const DEFAULT_CONTROL_COMMAND_BUDGET: usize = 64;
/// Default maximum packet-send commands processed in one worker iteration.
pub const DEFAULT_PACKET_COMMAND_BUDGET: usize = 256;
/// Default maximum incoming packets decoded in one worker iteration.
pub const DEFAULT_PACKET_DECODE_BUDGET: usize = 256;
/// Default maximum socket bytes read in one worker iteration.
pub const DEFAULT_READ_BYTE_BUDGET: usize = 1024 * 1024;
/// Default maximum socket bytes written in one worker iteration.
pub const DEFAULT_WRITE_BYTE_BUDGET: usize = 1024 * 1024;

/// Reserved poll token used by the waker to interrupt polling when commands
/// arrive.
const WAKER_TOKEN: Token = Token(usize::MAX - 1);

type ProtocolErrorHook<O> = Arc<dyn Fn(&io::Error) -> O + Send + Sync + 'static>;

/// A packet server backed by a background thread that does all the hard
/// processing. This server handle can be cloned as needed, and every handle
/// is able to both send and receive packets.
///
/// To kill the server, every handle of it should be dropped.
#[derive(Clone)]
pub struct Server<I, O> {
    packet_commands_sender: Sender<ThreadCommand<O>>,
    control_commands_sender: Sender<ControlCommand>,
    events_receiver: Receiver<ThreadEvent<I>>,
    #[cfg(feature = "stats")]
    stats: Arc<SharedStats>,
    waker: Arc<Waker>,
    shutdown_requested: Arc<AtomicBool>,
    accepted_packet_commands: Arc<AtomicU64>,
    worker: Arc<WorkerHandle>,
    config: ServerConfig,
    local_addr: SocketAddr,
}

struct WorkerHandle {
    join: Mutex<Option<thread::JoinHandle<()>>>,
}

#[cfg(feature = "stats")]
#[derive(Default)]
struct SharedStats {
    bytes_received: AtomicU64,
    bytes_consumed: AtomicU64,
    bytes_sent: AtomicU64,
    packets_sent: AtomicU64,
    packets_received: AtomicU64,
}

/// A point-in-time snapshot of server traffic counters.
///
/// Counters use saturating atomic increments and therefore remain at
/// [`u64::MAX`] after reaching it.
#[cfg(feature = "stats")]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ServerStats {
    /// Total bytes read from client sockets.
    pub bytes_received: u64,
    /// Total bytes consumed by successful packet decoding.
    pub bytes_consumed: u64,
    /// Total bytes written to client sockets.
    pub bytes_sent: u64,
    /// Incoming packets successfully decoded.
    pub packets_received: u64,
    /// Outgoing packets whose encoded bytes fully flushed to the socket.
    pub packets_sent: u64,
}

impl<I, O> Server<I, O>
where
    I: PacketIn + Send + 'static,
    O: PacketOut + Send + 'static,
{
    /// Bind using default limits and a response for invalid incoming packets.
    pub fn bind_with_protocol_error(
        addr: SocketAddr,
        on_protocol_error: impl Fn(&io::Error) -> O + Send + Sync + 'static,
    ) -> io::Result<Self> {
        let hook: ProtocolErrorHook<O> = Arc::new(on_protocol_error);
        Self::bind_internal(addr, Some(hook))
    }

    /// Bind a packet server to `addr` using default limits.
    pub fn bind(addr: SocketAddr) -> io::Result<Self> {
        Self::bind_internal(addr, None)
    }

    /// Bind a packet server to `addr` using explicit resource limits.
    pub fn bind_with_config(addr: SocketAddr, config: ServerConfig) -> io::Result<Self> {
        Self::bind_internal_with_config(addr, None, config)
    }

    /// Bind using explicit limits and a response for invalid incoming packets.
    pub fn bind_with_config_and_protocol_error(
        addr: SocketAddr,
        config: ServerConfig,
        on_protocol_error: impl Fn(&io::Error) -> O + Send + Sync + 'static,
    ) -> io::Result<Self> {
        let hook: ProtocolErrorHook<O> = Arc::new(on_protocol_error);
        Self::bind_internal_with_config(addr, Some(hook), config)
    }

    /// Start a packet server from a pre-bound standard TCP listener.
    ///
    /// The listener is switched to nonblocking mode before the worker starts.
    pub fn from_listener(listener: StdTcpListener) -> io::Result<Self> {
        Self::from_listener_internal(listener, None, ServerConfig::default())
    }

    /// Start from a pre-bound listener with a response for invalid packets.
    pub fn from_listener_with_protocol_error(
        listener: StdTcpListener,
        on_protocol_error: impl Fn(&io::Error) -> O + Send + Sync + 'static,
    ) -> io::Result<Self> {
        let hook: ProtocolErrorHook<O> = Arc::new(on_protocol_error);
        Self::from_listener_internal(listener, Some(hook), ServerConfig::default())
    }

    /// Start from a pre-bound listener using explicit resource limits.
    pub fn from_listener_with_config(
        listener: StdTcpListener,
        config: ServerConfig,
    ) -> io::Result<Self> {
        Self::from_listener_internal(listener, None, config)
    }

    /// Start from a pre-bound listener with explicit limits and an invalid
    /// packet response.
    pub fn from_listener_with_config_and_protocol_error(
        listener: StdTcpListener,
        config: ServerConfig,
        on_protocol_error: impl Fn(&io::Error) -> O + Send + Sync + 'static,
    ) -> io::Result<Self> {
        let hook: ProtocolErrorHook<O> = Arc::new(on_protocol_error);
        Self::from_listener_internal(listener, Some(hook), config)
    }

    fn bind_internal(
        addr: SocketAddr,
        on_protocol_error: Option<ProtocolErrorHook<O>>,
    ) -> io::Result<Self> {
        Self::bind_internal_with_config(addr, on_protocol_error, ServerConfig::default())
    }

    fn bind_internal_with_config(
        addr: SocketAddr,
        on_protocol_error: Option<ProtocolErrorHook<O>>,
        config: ServerConfig,
    ) -> io::Result<Self> {
        let config = config.validate()?;
        let listener = TcpListener::bind(addr)?;
        Self::start(listener, on_protocol_error, config)
    }

    fn from_listener_internal(
        listener: StdTcpListener,
        on_protocol_error: Option<ProtocolErrorHook<O>>,
        config: ServerConfig,
    ) -> io::Result<Self> {
        let config = config.validate()?;
        listener.set_nonblocking(true)?;
        Self::start(TcpListener::from_std(listener), on_protocol_error, config)
    }

    fn start(
        mut listener: TcpListener,
        on_protocol_error: Option<ProtocolErrorHook<O>>,
        config: ServerConfig,
    ) -> io::Result<Self> {
        let poll = Poll::new()?;
        let waker = Arc::new(Waker::new(poll.registry(), WAKER_TOKEN)?);
        poll.registry()
            .register(&mut listener, LISTENER_TOKEN, Interest::READABLE)?;
        let local_addr = listener.local_addr()?;

        let (packet_commands_sender, packet_commands_receiver) =
            bounded(config.command_queue_limit);
        let (control_commands_sender, control_commands_receiver) =
            bounded(config.control_queue_limit);
        let (events_sender, events_receiver) = bounded(config.event_queue_limit);

        #[cfg(feature = "stats")]
        let stats = Arc::new(SharedStats::default());
        let shutdown_requested = Arc::new(AtomicBool::new(false));
        let accepted_packet_commands = Arc::new(AtomicU64::new(0));

        #[cfg(feature = "stats")]
        let stats_for_poll = Arc::clone(&stats);
        let shutdown_for_poll = Arc::clone(&shutdown_requested);

        // Public sends and lifecycle operations use separate queues so a full
        // packet-send queue cannot prevent disconnects or shutdown from being
        // observed by the worker.
        let join = thread::Builder::new()
            .name("Packet Poll Thread".to_string())
            .spawn(move || {
                PollThread::<I, O> {
                    packet_commands_receiver,
                    control_commands_receiver,
                    events_sender,
                    listener,
                    poll,
                    client_ids: ClientIdAllocator::new(),
                    clients: HashMap::new(),
                    ready_order: VecDeque::new(),
                    ready_events: HashMap::new(),
                    listener_retry_at: None,
                    control_commands_deferred: false,
                    packet_commands_deferred: false,
                    packet_commands_processed: 0,
                    pending_disconnects: VecDeque::new(),
                    pending_events: VecDeque::new(),
                    pending_event_limit: config.max_clients + 1,
                    total_queued_bytes: 0,
                    on_protocol_error,
                    #[cfg(feature = "stats")]
                    stats: stats_for_poll,
                    config,
                    shutdown_requested: shutdown_for_poll,
                }
                .run();
            })?;
        let worker = Arc::new(WorkerHandle {
            join: Mutex::new(Some(join)),
        });

        Ok(Self {
            packet_commands_sender,
            control_commands_sender,
            events_receiver,
            #[cfg(feature = "stats")]
            stats,
            waker,
            shutdown_requested,
            accepted_packet_commands,
            worker,
            config,
            local_addr,
        })
    }

    /// Poll events from this packet server.
    ///
    /// Returns `Ok(Some(event))` when an event is available, `Ok(None)` if
    /// there was no event, or an `Err` if the server encountered a fatal error.
    pub fn poll(&self) -> io::Result<Option<ServerEvent<I>>> {
        match self.events_receiver.try_recv() {
            Ok(ThreadEvent::Accept { id, peer_addr }) => Ok(Some(ServerEvent::Accept {
                client: ServerClient(id),
                peer_addr,
            })),
            Ok(ThreadEvent::Lost { id, error }) => Ok(Some(ServerEvent::Lost {
                client: ServerClient(id),
                error,
            })),
            Ok(ThreadEvent::ReceivePacket { id, packet }) => Ok(Some(ServerEvent::Packet {
                client: ServerClient(id),
                packet,
            })),
            Ok(ThreadEvent::UnrecoverableError { error }) => Err(error),
            Err(TryRecvError::Empty) => Ok(None),
            Err(TryRecvError::Disconnected) => Err(new_io_abort_error(
                "previous error made this server unusable",
            )),
        }
    }

    /// Queue a packet send command.
    ///
    /// `Ok(())` means the command was accepted by the server, not that the
    /// packet was accepted into the target client's queue, written to the
    /// socket, or delivered to the peer. A stale client handle, disconnected
    /// or closing client, per-client queue limit, encode error, or socket
    /// failure can still prevent delivery later. Packets rejected because the
    /// client is closing are not encoded.
    pub fn send(&self, client: ServerClient, packet: O) -> io::Result<()> {
        match self
            .packet_commands_sender
            .try_send(ThreadCommand::SendPacket {
                id: client.0,
                packet,
            }) {
            Ok(()) => {
                let _ = self.accepted_packet_commands.fetch_update(
                    Ordering::Release,
                    Ordering::Relaxed,
                    |current| Some(current.saturating_add(1)),
                );
                self.waker.wake()?;
                Ok(())
            }
            Err(TrySendError::Full(_)) => Err(io::Error::new(
                io::ErrorKind::WouldBlock,
                "server packet command queue is full",
            )),
            Err(TrySendError::Disconnected(_)) => {
                Err(new_io_abort_error("server command thread is stopped"))
            }
        }
    }

    /// Request client disconnection after prior send commands and queued writes
    /// flush.
    ///
    /// Sequential `send()` calls that returned before this call are processed
    /// before the client enters its terminal closing state. Later send commands
    /// are rejected without encoding. Calls made concurrently from cloned
    /// server handles have no defined ordering.
    pub fn disconnect(&self, client: ServerClient) -> io::Result<()> {
        let packet_command_cutoff = self.accepted_packet_commands.load(Ordering::Acquire);
        self.queue_control(ControlCommand::DisconnectClient {
            id: client.0,
            packet_command_cutoff,
        })
    }

    /// Request immediate client disconnection, discarding queued outgoing data.
    pub fn disconnect_now(&self, client: ServerClient) -> io::Result<()> {
        self.queue_control(ControlCommand::DisconnectClientNow { id: client.0 })
    }

    /// Shut down the server and close all connected clients.
    ///
    /// This wakes the poll thread, requests a clean server stop, and causes
    /// connected clients to be closed. Queued outgoing data is not guaranteed
    /// to flush; use per client [`disconnect`](Self::disconnect) when a final
    /// packet must be written before closing that client.
    pub fn shutdown(&self) -> io::Result<()> {
        self.shutdown_requested.store(true, Ordering::Release);
        let _ = self
            .control_commands_sender
            .try_send(ControlCommand::Shutdown);
        self.waker.wake()
    }

    /// Request shutdown and wait for the background worker to exit.
    ///
    /// Calling this method more than once is harmless. If the worker panicked,
    /// the first caller that joins it receives an error.
    pub fn shutdown_and_wait(&self) -> io::Result<()> {
        let wake_result = self.shutdown();
        let mut join = self
            .worker
            .join
            .lock()
            .map_err(|_| new_io_abort_error("server worker join lock is poisoned"))?;
        if let Some(join) = join.take() {
            join.join()
                .map_err(|_| new_io_abort_error("server worker thread panicked"))?;
        }
        wake_result
    }

    /// Return the active resource limits.
    pub fn config(&self) -> ServerConfig {
        self.config
    }

    /// Return the socket address the listener was bound to.
    pub fn local_addr(&self) -> SocketAddr {
        self.local_addr
    }

    fn queue_control(&self, command: ControlCommand) -> io::Result<()> {
        match self.control_commands_sender.try_send(command) {
            Ok(()) => {
                self.waker.wake()?;
                Ok(())
            }
            Err(TrySendError::Full(_)) => Err(io::Error::new(
                io::ErrorKind::WouldBlock,
                "server control command queue is full",
            )),
            Err(TrySendError::Disconnected(_)) => {
                Err(new_io_abort_error("server command thread is stopped"))
            }
        }
    }

    #[cfg(feature = "stats")]
    /// Return a point-in-time snapshot of server counters.
    pub fn stats(&self) -> ServerStats {
        ServerStats {
            bytes_received: self.stats.bytes_received.load(Ordering::Relaxed),
            bytes_consumed: self.stats.bytes_consumed.load(Ordering::Relaxed),
            bytes_sent: self.stats.bytes_sent.load(Ordering::Relaxed),
            packets_received: self.stats.packets_received.load(Ordering::Relaxed),
            packets_sent: self.stats.packets_sent.load(Ordering::Relaxed),
        }
    }
}

/// A handle to a client produced by a packet server. This handle can be used
/// with a server to send packets to a client.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ServerClient(ClientId);

impl Display for ServerClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}:{}", self.0.token.0, self.0.generation)
    }
}

impl ServerClient {
    /// Return the numeric id of this server client.
    #[inline]
    pub fn id(self) -> u64 {
        self.0.generation
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
struct ClientId {
    token: Token,
    generation: u64,
}

struct ClientIdAllocator {
    next_token: Token,
    next_generation: u64,
    free_tokens: Vec<Token>,
}

impl ClientIdAllocator {
    fn new() -> Self {
        Self {
            next_token: CLIENT_FIRST_TOKEN,
            next_generation: 1,
            free_tokens: Vec::new(),
        }
    }

    #[expect(
        clippy::expect_used,
        reason = "the only other option is to propagate a result type through
                  client acceptance, which isn't worth it for such a practically
                  unreachable condition"
    )]
    fn allocate(&mut self) -> ClientId {
        // Poll tokens are reused after disconnect so the registry space stays
        // small; the generation makes stale ServerClient handles harmless
        let token = if let Some(t) = self.free_tokens.pop() {
            t
        } else {
            let t = self.next_token;
            self.next_token = Token(t.0.checked_add(1).expect("out of client tokens"));
            t
        };
        let generation = self.next_generation;
        self.next_generation = self.next_generation.wrapping_add(1).max(1);
        ClientId { token, generation }
    }

    fn release(&mut self, token: Token) {
        self.free_tokens.push(token);
    }
}

/// An event produced by a [`Server`].
#[derive(Debug)]
pub enum ServerEvent<I> {
    /// A client connection was accepted.
    Accept {
        /// The client handle that was accepted.
        client: ServerClient,
        /// Remote socket address of the accepted client.
        peer_addr: SocketAddr,
    },
    /// A client connection ended.
    Lost {
        /// The client handle that was lost.
        client: ServerClient,
        /// Some error if that caused the client to be lost, no error means that the
        /// client was just kicked from the server or closed the connection itself.
        error: Option<io::Error>,
    },
    /// A packet was received from a client.
    Packet {
        /// The client handle that received the packet.
        client: ServerClient,
        /// Received packet.
        packet: I,
    },
}

/// Internal polling token used for the listening socket.
const LISTENER_TOKEN: Token = Token(0);
/// First token associated to a client.
const CLIENT_FIRST_TOKEN: Token = Token(1);

const POLL_TICK: Duration = Duration::from_millis(100);
const ACCEPT_RETRY_DELAY: Duration = Duration::from_millis(100);

/// Internal thread for polling the TCP listener and client events. Polling is
/// done in its own thread because it blocks until events are received, but we
/// also need to block for incoming commands, this would require we *select*
/// between poll events and channel commands, but we can't do that.
struct PollThread<I, O> {
    /// Bounded queue for packet sends from server handles.
    packet_commands_receiver: Receiver<ThreadCommand<O>>,
    /// Priority queue for lifecycle commands that must not be blocked by sends.
    control_commands_receiver: Receiver<ControlCommand>,
    /// Events sent to the handle.
    events_sender: Sender<ThreadEvent<I>>,
    /// The inner TCP listener.
    listener: TcpListener,
    /// The poll used for event listening TCP events.
    poll: Poll,
    client_ids: ClientIdAllocator,
    /// All clients.
    clients: HashMap<Token, PollClient>,
    /// Readiness for one token can arrive in several batches before we process
    /// it. Keep one merged event per token plus FIFO order so unfinished work
    /// resumes predictably without duplicate queue entries.
    ready_order: VecDeque<Token>,
    ready_events: HashMap<Token, ReadyEvent>,
    /// Accept errors caused by transient process/kernel pressure should not
    /// spin the worker. The listener readiness is retained and retried later.
    listener_retry_at: Option<std::time::Instant>,
    control_commands_deferred: bool,
    packet_commands_deferred: bool,
    packet_commands_processed: u64,
    /// Graceful disconnects wait until the packet-send queue has been drained
    /// through the command count observed by Server::disconnect().
    pending_disconnects: VecDeque<PendingDisconnect>,
    /// Events that could not fit in the public queue. While this is non-empty,
    /// new accepts and reads pause to keep event order and memory bounded.
    pending_events: VecDeque<ThreadEvent<I>>,
    pending_event_limit: usize,
    total_queued_bytes: usize,
    on_protocol_error: Option<ProtocolErrorHook<O>>,
    #[cfg(feature = "stats")]
    stats: Arc<SharedStats>,
    config: ServerConfig,
    shutdown_requested: Arc<AtomicBool>,
}

/// Internal structure for storing client
struct PollClient {
    stream: TcpStream,
    id: ClientId,
    _peer_addr: SocketAddr,
    /// Internal buffer to temporarily store incoming client's data.
    buf: Vec<u8>,
    /// Cursor in the receiving buffer (bytes currently filled).
    buf_cursor: usize,
    state: ClientState,
    outgoing: VecDeque<Vec<u8>>,
    outgoing_offset: usize,
    queued_bytes: usize,
    registered_readable: bool,
    registered_writable: bool,
    last_activity: std::time::Instant,
    packet_started_at: Option<std::time::Instant>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ClientState {
    Open,
    /// Application requested a graceful disconnect; writes already admitted to
    /// this client should flush, but later sends must be ignored.
    DisconnectAfterFlush,
    /// Peer sent EOF on its write side. We stop reading immediately, flush
    /// queued responses, then report a clean Lost event.
    PeerEofAfterFlush,
    /// Decoder reported InvalidData and the hook produced a final response.
    /// No further incoming bytes or queued sends should affect this client.
    ProtocolErrorAfterFlush,
}

impl ClientState {
    fn is_open(self) -> bool {
        self == Self::Open
    }
}

struct PendingDisconnect {
    id: ClientId,
    packet_command_cutoff: u64,
}

#[derive(Clone, Copy, Debug, better_default::Default)]
struct ReadyEvent {
    #[default(LISTENER_TOKEN)]
    token: Token,
    readable: bool,
    writable: bool,
    read_closed: bool,
    write_closed: bool,
}

impl ReadyEvent {
    fn from_mio(event: &Event) -> Self {
        Self {
            token: event.token(),
            readable: event.is_readable(),
            writable: event.is_writable(),
            read_closed: event.is_read_closed(),
            write_closed: event.is_write_closed(),
        }
    }

    fn writable(token: Token) -> Self {
        Self {
            token,
            writable: true,
            ..Self::default()
        }
    }

    fn merge(&mut self, other: Self) {
        debug_assert_eq!(self.token, other.token);
        self.readable |= other.readable;
        self.writable |= other.writable;
        self.read_closed |= other.read_closed;
        self.write_closed |= other.write_closed;
    }

    fn has_readiness(self) -> bool {
        self.readable || self.writable || self.read_closed || self.write_closed
    }
}

struct TickBudget {
    accepts: usize,
    control_commands: usize,
    packet_commands: usize,
    decoded_packets: usize,
    read_bytes: usize,
    written_bytes: usize,
}

impl TickBudget {
    fn new(config: ServerConfig) -> Self {
        Self {
            accepts: config.accept_budget,
            control_commands: config.control_command_budget,
            packet_commands: config.packet_command_budget,
            decoded_packets: config.packet_decode_budget,
            read_bytes: config.read_byte_budget,
            written_bytes: config.write_byte_budget,
        }
    }
}

#[derive(Clone, Copy, Debug, Default)]
struct WorkOutcome {
    keep_running: bool,
    retry: bool,
}

impl WorkOutcome {
    fn running(retry: bool) -> Self {
        Self {
            keep_running: true,
            retry,
        }
    }
}

impl<I: PacketIn, O: PacketOut> PollThread<I, O> {
    fn run(mut self) {
        let mut events = Events::with_capacity(128);

        while !self.shutdown_requested.load(Ordering::Acquire) {
            match self.poll_once(&mut events) {
                Ok(true) => {}
                Ok(false) => return,
                Err(e) => {
                    let mut event = ThreadEvent::UnrecoverableError { error: e };
                    loop {
                        match self.events_sender.try_send(event) {
                            Ok(()) | Err(TrySendError::Disconnected(_)) => break,
                            Err(TrySendError::Full(returned)) => {
                                if self.shutdown_requested.load(Ordering::Acquire) {
                                    break;
                                }
                                event = returned;
                                thread::sleep(Duration::from_millis(1));
                            }
                        }
                    }
                    return;
                }
            }
        }
        self.close_all(None);
    }

    fn poll_once(&mut self, events: &mut Events) -> io::Result<bool> {
        if self.shutdown_requested.load(Ordering::Acquire) {
            self.close_all(None);
            return Ok(false);
        }

        if !self.flush_pending_event() {
            return Ok(false);
        }

        let mut budget = TickBudget::new(self.config);
        if !self.drain_control_commands(&mut budget) {
            return Ok(false);
        }
        self.drain_packet_commands(&mut budget);

        // When the app is not draining public events, continuing to accept or
        // decode would only create more events we cannot publish. Writes,
        // control commands, and timeouts still run so existing clients can make
        // progress and administrative actions are not wedged
        let intake_paused = !self.pending_events.is_empty();
        let has_deferred_work = self.has_actionable_ready(intake_paused)
            || self.control_commands_deferred
            || self.packet_commands_deferred;
        let timeout = if has_deferred_work {
            Duration::ZERO
        } else {
            POLL_TICK
        };
        self.poll.poll(events, Some(timeout))?;
        for event in events.iter() {
            self.queue_ready_event(ReadyEvent::from_mio(event));
        }
        if !self.drain_control_commands(&mut budget) {
            return Ok(false);
        }
        self.drain_packet_commands(&mut budget);

        let ready_count = self.ready_order.len();
        for _ in 0..ready_count {
            let Some(token) = self.ready_order.pop_front() else {
                break;
            };
            let Some(event) = self.ready_events.remove(&token) else {
                continue;
            };
            let intake_paused = !self.pending_events.is_empty();
            if intake_paused && token == LISTENER_TOKEN {
                self.ready_events.insert(token, event);
                self.ready_order.push_back(token);
                continue;
            }
            let mut process_event = event;
            if intake_paused {
                // Preserve write-side progress under event backpressure, but
                // suppress reads because every decoded packet would need a
                // public event. Closed flags paired with readability are kept
                // for a later pass so EOF is handled in order after buffered
                // packets have had a chance to be published
                process_event.readable = false;
                if event.readable {
                    process_event.read_closed = false;
                    process_event.write_closed = false;
                }
            }
            let can_progress = if token == LISTENER_TOKEN {
                budget.accepts > 0
            } else {
                process_event.write_closed
                    || process_event.read_closed
                    || (process_event.writable && budget.written_bytes > 0)
                    || (process_event.readable
                        && budget.read_bytes > 0
                        && budget.decoded_packets > 0)
            };
            if !can_progress {
                self.ready_events.insert(token, event);
                let blocked_by_budget = if token == LISTENER_TOKEN {
                    !intake_paused && budget.accepts == 0
                } else {
                    (process_event.writable && budget.written_bytes == 0)
                        || (process_event.readable
                            && (budget.read_bytes == 0 || budget.decoded_packets == 0))
                };
                if blocked_by_budget {
                    // Put the blocked event at the front: later sockets should
                    // not leapfrog a token that is merely waiting for the next
                    // worker iteration's budget
                    self.ready_order.push_front(token);
                    break;
                }
                self.ready_order.push_back(token);
                continue;
            }

            let (keep_running, retry) = if token == LISTENER_TOKEN {
                let outcome = self.handle_listener(&mut budget)?;
                (outcome.keep_running, outcome.retry.then_some(event))
            } else {
                let (keep_running, mut retry) = self.handle_client(process_event, &mut budget);
                if intake_paused {
                    retry.readable |= event.readable;
                    retry.read_closed |= event.read_closed;
                    retry.write_closed |= event.write_closed;
                }
                (keep_running, retry.has_readiness().then_some(retry))
            };
            if !keep_running {
                return Ok(false);
            }
            if let Some(event) = retry {
                self.queue_ready_event(event);
            }
        }

        if !self.drain_control_commands(&mut budget) {
            return Ok(false);
        }
        self.drain_packet_commands(&mut budget);
        self.expire_timed_out_clients();

        if self.shutdown_requested.load(Ordering::Acquire) {
            self.close_all(None);
            return Ok(false);
        }

        Ok(true)
    }

    fn has_actionable_ready(&self, intake_paused: bool) -> bool {
        self.ready_events.values().any(|event| {
            if event.token == LISTENER_TOKEN {
                !intake_paused
                    && self
                        .listener_retry_at
                        .is_none_or(|retry_at| std::time::Instant::now() >= retry_at)
            } else {
                event.writable
                    || event.write_closed
                    || (!intake_paused && event.readable)
                    || (!event.readable && event.read_closed)
            }
        })
    }

    fn queue_ready_event(&mut self, event: ReadyEvent) {
        let token = event.token;
        if token == WAKER_TOKEN {
            return;
        }
        if token != LISTENER_TOKEN && !self.clients.contains_key(&token) {
            return;
        }

        if let Some(queued) = self.ready_events.get_mut(&token) {
            // A token may become readable and writable before we get back to it;
            // merging avoids duplicate queue entries and losing either signal
            queued.merge(event);
        } else {
            self.ready_events.insert(token, event);
            self.ready_order.push_back(token);
        }
    }

    /// Handle a readable polling event from the TCP listener stream.
    fn handle_listener(&mut self, budget: &mut TickBudget) -> io::Result<WorkOutcome> {
        if self
            .listener_retry_at
            .is_some_and(|retry_at| std::time::Instant::now() < retry_at)
        {
            return Ok(WorkOutcome::running(true));
        }

        while budget.accepts > 0 {
            let (mut stream, peer_addr) = match self.listener.accept() {
                Ok(accepted) => {
                    self.listener_retry_at = None;
                    accepted
                }
                Err(error) => match classify_accept_error(&error) {
                    AcceptErrorAction::Done => {
                        self.listener_retry_at = None;
                        return Ok(WorkOutcome::running(false));
                    }
                    AcceptErrorAction::RetryImmediately => {
                        budget.accepts -= 1;
                        continue;
                    }
                    AcceptErrorAction::RetryAfterBackoff => {
                        self.listener_retry_at =
                            Some(std::time::Instant::now() + ACCEPT_RETRY_DELAY);
                        return Ok(WorkOutcome::running(true));
                    }
                    AcceptErrorAction::Fatal => return Err(error),
                },
            };
            budget.accepts -= 1;

            if self.clients.len() >= self.config.max_clients {
                // Refuse excess connections before emitting Accept so callers
                // never receive a handle for a socket the worker will not track
                let _ = stream.shutdown(Shutdown::Both);
                continue;
            }
            if configure_accepted_stream(&stream, self.config).is_err() {
                let _ = stream.shutdown(Shutdown::Both);
                continue;
            }

            // get a new unique token and register events on this stream
            let id = self.client_ids.allocate();
            let token = id.token;
            self.poll
                .registry()
                .register(&mut stream, token, Interest::READABLE)?;

            self.clients.insert(
                token,
                PollClient {
                    stream,
                    id,
                    _peer_addr: peer_addr,
                    buf: vec![0u8; self.config.incoming_buffer_initial],
                    buf_cursor: 0,
                    state: ClientState::Open,
                    outgoing: VecDeque::new(),
                    outgoing_offset: 0,
                    queued_bytes: 0,
                    registered_readable: true,
                    registered_writable: false,
                    last_activity: std::time::Instant::now(),
                    packet_started_at: None,
                },
            );
            if !self.send_event(ThreadEvent::Accept { id, peer_addr }) {
                return Ok(WorkOutcome::default());
            }
            if !self.pending_events.is_empty() {
                return Ok(WorkOutcome::running(true));
            }
        }
        Ok(WorkOutcome::running(true))
    }

    /// Internal function to handle a polling event from a client. This function
    /// doesn't generate errors; if errors happen they are pushed as client
    /// events. The function returns `true` if the thread should continue.
    fn handle_client(&mut self, event: ReadyEvent, budget: &mut TickBudget) -> (bool, ReadyEvent) {
        let token = event.token;
        let mut retry = ReadyEvent {
            token,
            ..ReadyEvent::default()
        };

        if event.writable {
            match self.flush_client(token, &mut budget.written_bytes) {
                Err(e) => return (self.finalize_close(token, Some(e)), retry),
                Ok(outcome) if !outcome.keep_running => return (false, retry),
                Ok(outcome) => retry.writable = outcome.retry,
            }
        }

        if event.readable {
            match self.handle_client_read(token, budget) {
                Err(e) => return (self.finalize_close(token, Some(e)), retry),
                Ok(outcome) if !outcome.keep_running => return (false, retry),
                Ok(outcome) => retry.readable = outcome.retry,
            }
            if !self.pending_events.is_empty() {
                retry.read_closed = event.read_closed;
                retry.write_closed = event.write_closed;
                return (true, retry);
            }
        }

        if event.write_closed {
            return (
                self.finalize_close(token, Some(new_io_abort_error("peer write-closed"))),
                retry,
            );
        }
        if event.read_closed && retry.readable {
            retry.read_closed = true;
        } else if event.read_closed {
            return (self.mark_read_eof(token), retry);
        }
        (true, retry)
    }

    /// Handle a readable client event. This returns `false` if the global loop
    /// should stop.
    fn handle_client_read(
        &mut self,
        token: Token,
        budget: &mut TickBudget,
    ) -> io::Result<WorkOutcome> {
        let mut saw_eof = false;
        let mut receiver_connected = true;
        let mut protocol_error_packet = None;
        let mut retry = false;

        {
            let Some(client) = self.clients.get_mut(&token) else {
                return Ok(WorkOutcome::running(false));
            };
            if !client.state.is_open() {
                return Ok(WorkOutcome::running(false));
            }

            'read: loop {
                while client.buf_cursor > 0 {
                    if budget.decoded_packets == 0 {
                        retry = true;
                        break 'read;
                    }

                    let mut cursor = Cursor::new(&client.buf[..client.buf_cursor]);
                    match I::read(&mut cursor) {
                        Ok(packet) => {
                            let consumed = cursor.position() as usize;
                            if consumed == 0 {
                                return Err(new_io_abort_error("decoder made no progress"));
                            }

                            #[cfg(feature = "stats")]
                            atomic_saturating_add(&self.stats.bytes_consumed, consumed as u64);
                            #[cfg(feature = "stats")]
                            atomic_saturating_add(&self.stats.packets_received, 1);
                            budget.decoded_packets -= 1;

                            let event = ThreadEvent::ReceivePacket {
                                id: client.id,
                                packet,
                            };
                            match self.events_sender.try_send(event) {
                                Ok(()) => {}
                                Err(TrySendError::Full(event)) => {
                                    self.pending_events.push_back(event);
                                }
                                Err(TrySendError::Disconnected(_)) => {
                                    receiver_connected = false;
                                }
                            }

                            client.buf.copy_within(consumed..client.buf_cursor, 0);
                            client.buf_cursor -= consumed;
                            client.packet_started_at = None;
                            if !self.pending_events.is_empty() || !receiver_connected {
                                retry = receiver_connected;
                                break 'read;
                            }
                        }
                        Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => {
                            if client.buf_cursor == self.config.incoming_buffer_limit {
                                return Err(io::Error::new(
                                    io::ErrorKind::InvalidData,
                                    "incoming packet exceeded size limit",
                                ));
                            }
                            if self.config.packet_assembly_timeout.is_some() {
                                // Start once and intentionally do not refresh
                                // on later fragments; otherwise a slow trickle
                                // could hold memory forever without completing
                                // a packet
                                client
                                    .packet_started_at
                                    .get_or_insert_with(std::time::Instant::now);
                            }
                            break;
                        }
                        Err(e) if e.kind() == io::ErrorKind::InvalidData => {
                            if let Some(hook) = &self.on_protocol_error {
                                // The hook's response is queued after leaving
                                // this borrow, then the client enters a closing
                                // state. That gives protocol errors a chance to
                                // flush a final packet without allowing queued
                                // application sends to race in behind it
                                let packet = (hook)(&e);
                                protocol_error_packet = Some((client.id, packet));
                                break 'read;
                            } else {
                                return Err(e);
                            }
                        }
                        Err(e) => return Err(e),
                    }
                }

                if saw_eof {
                    if client.buf_cursor != 0 {
                        // EOF with buffered bytes means the decoder needed more
                        // data to finish the current packet, so the packet
                        // boundary is no longer trustworthy
                        return Err(io::Error::new(
                            io::ErrorKind::UnexpectedEof,
                            "peer closed with an incomplete packet",
                        ));
                    }
                    break;
                }

                if budget.read_bytes == 0 || budget.decoded_packets == 0 {
                    retry = true;
                    break;
                }

                if client.buf_cursor == client.buf.len() {
                    let new_len = (client.buf.len() * 2).min(self.config.incoming_buffer_limit);
                    client.buf.resize(new_len, 0);
                }

                debug_assert!(client.buf_cursor < client.buf.len());
                let read_end = client
                    .buf_cursor
                    .saturating_add(budget.read_bytes)
                    .min(client.buf.len());
                match (&client.stream).read(&mut client.buf[client.buf_cursor..read_end]) {
                    Ok(0) => saw_eof = true,
                    Ok(len) => {
                        client.buf_cursor += len;
                        budget.read_bytes -= len;
                        client.last_activity = std::time::Instant::now();
                        #[cfg(feature = "stats")]
                        atomic_saturating_add(&self.stats.bytes_received, len as u64);
                    }
                    Err(e) if e.kind() == io::ErrorKind::WouldBlock => break,
                    Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
                    Err(e) => return Err(e),
                }
            }
        }

        if let Some((id, packet)) = protocol_error_packet {
            self.handle_protocol_error_packet(id, packet);
            return Ok(WorkOutcome::running(false));
        }

        if !receiver_connected {
            return Ok(WorkOutcome::default());
        }
        if saw_eof {
            return Ok(WorkOutcome {
                keep_running: self.mark_read_eof(token),
                retry: false,
            });
        }
        Ok(WorkOutcome::running(retry))
    }

    fn finalize_close(&mut self, token: Token, error: Option<io::Error>) -> bool {
        let Some(client) = self.clients.remove(&token) else {
            return true;
        };

        self.ready_events.remove(&token);
        self.client_ids.release(token);
        self.total_queued_bytes = self.total_queued_bytes.saturating_sub(client.queued_bytes);
        let mut stream = client.stream;
        let _ = stream.shutdown(Shutdown::Both);
        let _ = self.poll.registry().deregister(&mut stream);
        self.send_event(ThreadEvent::Lost {
            id: client.id,
            error,
        })
    }

    fn mark_read_eof(&mut self, token: Token) -> bool {
        if let Some(client) = self.clients.get_mut(&token) {
            if client.state.is_open() {
                client.state = ClientState::PeerEofAfterFlush;
            }

            if client.outgoing.is_empty() {
                return self.finalize_close(token, None);
            }

            // Do not keep listening for new input after EOF. We only stay
            // registered for writability long enough to drain queued output
            if let Err(e) = self.update_client_interest(token) {
                return self.finalize_close(token, Some(e));
            }
        }
        true
    }

    fn drain_control_commands(&mut self, budget: &mut TickBudget) -> bool {
        while budget.control_commands > 0 {
            match self.control_commands_receiver.try_recv() {
                Ok(ControlCommand::DisconnectClient {
                    id,
                    packet_command_cutoff,
                }) => {
                    budget.control_commands -= 1;
                    // The cutoff preserves sequential API semantics: sends
                    // accepted before disconnect() are processed first, while
                    // later sends see the closing state and are ignored
                    self.pending_disconnects.push_back(PendingDisconnect {
                        id,
                        packet_command_cutoff,
                    });
                    self.finish_pending_disconnects();
                }
                Ok(ControlCommand::DisconnectClientNow { id }) => {
                    budget.control_commands -= 1;
                    self.close_current(id, None);
                }
                Ok(ControlCommand::Shutdown) => {
                    budget.control_commands -= 1;
                    self.shutdown_requested.store(true, Ordering::Release);
                    self.close_all(None);
                    return false;
                }
                Err(TryRecvError::Empty) => {
                    self.control_commands_deferred = false;
                    return true;
                }
                Err(TryRecvError::Disconnected) => return false,
            }
        }
        self.control_commands_deferred = true;
        true
    }

    fn drain_packet_commands(&mut self, budget: &mut TickBudget) {
        while budget.packet_commands > 0 {
            match self.packet_commands_receiver.try_recv() {
                Ok(ThreadCommand::SendPacket { id, packet }) => {
                    budget.packet_commands -= 1;
                    self.handle_client_send(id, packet);
                    self.packet_commands_processed =
                        self.packet_commands_processed.saturating_add(1);
                    self.finish_pending_disconnects();
                }
                Err(TryRecvError::Empty) => {
                    self.packet_commands_deferred = false;
                    return;
                }
                Err(TryRecvError::Disconnected) => return,
            }
        }
        self.packet_commands_deferred = true;
    }

    fn finish_pending_disconnects(&mut self) {
        let pending_count = self.pending_disconnects.len();
        for _ in 0..pending_count {
            let Some(pending) = self.pending_disconnects.pop_front() else {
                break;
            };
            if pending.packet_command_cutoff <= self.packet_commands_processed {
                self.handle_client_disconnect(pending.id);
            } else {
                self.pending_disconnects.push_back(pending);
            }
        }
    }

    fn handle_protocol_error_packet(&mut self, id: ClientId, packet: O) {
        let Some(client) = self.current_mut(id) else {
            return;
        };
        if !client.state.is_open() {
            return;
        }
        client.state = ClientState::ProtocolErrorAfterFlush;
        // Drop any partially-read bytes from the invalid stream. The only
        // remaining work for this client is sending the hook response
        client.buf_cursor = 0;
        self.queue_client_packet(id, packet);
    }

    fn handle_client_disconnect(&mut self, id: ClientId) {
        let Some(client) = self.current_mut(id) else {
            return;
        };
        let transitioned = client.state.is_open();
        if client.state.is_open() {
            client.state = ClientState::DisconnectAfterFlush;
        }
        if client.outgoing.is_empty() {
            let _ = self.close_current(id, None);
        } else if transitioned && let Err(error) = self.update_client_interest(id.token) {
            self.close_current(id, Some(error));
        }
    }

    fn handle_client_send(&mut self, id: ClientId, packet: O) {
        let Some(client) = self.current_mut(id) else {
            return;
        };
        if !client.state.is_open() {
            return;
        }
        self.queue_client_packet(id, packet);
    }

    fn queue_client_packet(&mut self, id: ClientId, packet: O) {
        let encoded = match encode_bounded(&packet, self.config.outgoing_buffer_limit) {
            Ok(encoded) => encoded,
            Err(e) => {
                self.close_current(id, Some(e));
                return;
            }
        };

        let Some(limit) = self.config.outgoing_buffer_limit.checked_sub(encoded.len()) else {
            self.close_current(
                id,
                Some(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "outgoing packet exceeded size limit",
                )),
            );
            return;
        };
        let packet_queue_limit = self.config.outgoing_packet_queue_limit;
        let Some(global_queued_bytes) = self.total_queued_bytes.checked_add(encoded.len()) else {
            self.close_current(
                id,
                Some(io::Error::new(
                    io::ErrorKind::OutOfMemory,
                    "global outgoing queue size overflow",
                )),
            );
            return;
        };
        if global_queued_bytes > self.config.global_outgoing_buffer_limit {
            self.close_current(
                id,
                Some(io::Error::new(
                    io::ErrorKind::OutOfMemory,
                    "global outgoing queue limit exceeded",
                )),
            );
            return;
        }
        let Some(client) = self.current_mut(id) else {
            return;
        };
        if client.queued_bytes > limit || client.outgoing.len() >= packet_queue_limit {
            self.close_current(
                id,
                Some(io::Error::new(
                    io::ErrorKind::OutOfMemory,
                    "client outgoing queue limit exceeded",
                )),
            );
            return;
        }
        client.queued_bytes += encoded.len();
        client.outgoing.push_back(encoded);
        self.total_queued_bytes = global_queued_bytes;
        if let Err(e) = self.update_client_interest(id.token) {
            self.close_current(id, Some(e));
        } else {
            // Mio will normally report writability again, but queueing a local
            // ready event lets newly queued packets flush without waiting for
            // another OS readiness notification
            self.queue_ready_event(ReadyEvent::writable(id.token));
        }
    }

    fn flush_client(&mut self, token: Token, budget: &mut usize) -> io::Result<WorkOutcome> {
        let Some(client) = self.clients.get_mut(&token) else {
            return Ok(WorkOutcome::running(false));
        };

        let mut retry = false;
        while let Some(front) = client.outgoing.front() {
            if *budget == 0 {
                retry = true;
                break;
            }
            let write_end = client
                .outgoing_offset
                .saturating_add(*budget)
                .min(front.len());
            match client
                .stream
                .write(&front[client.outgoing_offset..write_end])
            {
                Ok(0) => break,
                Ok(wrote) => {
                    *budget -= wrote;
                    client.queued_bytes = client.queued_bytes.saturating_sub(wrote);
                    self.total_queued_bytes = self.total_queued_bytes.saturating_sub(wrote);
                    client.outgoing_offset += wrote;
                    client.last_activity = std::time::Instant::now();
                    #[cfg(feature = "stats")]
                    atomic_saturating_add(&self.stats.bytes_sent, wrote as u64);
                    if client.outgoing_offset == front.len() {
                        client.outgoing.pop_front();
                        client.outgoing_offset = 0;
                        #[cfg(feature = "stats")]
                        atomic_saturating_add(&self.stats.packets_sent, 1);
                    }
                }
                Err(e) if e.kind() == io::ErrorKind::WouldBlock => break,
                Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
                Err(e) => return Err(e),
            }
        }

        let Some(client) = self.clients.get(&token) else {
            return Ok(WorkOutcome::running(false));
        };
        if client.outgoing.is_empty() && !client.state.is_open() {
            // All terminal states share the same final step: once queued bytes
            // are gone, close and emit Lost
            return Ok(WorkOutcome {
                keep_running: self.finalize_close(token, None),
                retry: false,
            });
        }
        self.update_client_interest(token)?;
        Ok(WorkOutcome::running(retry))
    }

    fn update_client_interest(&mut self, token: Token) -> io::Result<()> {
        let Some(client) = self.clients.get_mut(&token) else {
            return Ok(());
        };
        let wants_writable = !client.outgoing.is_empty();
        let wants_readable = client.state.is_open();
        if client.registered_readable == wants_readable
            && client.registered_writable == wants_writable
        {
            return Ok(());
        }
        client.registered_readable = wants_readable;
        client.registered_writable = wants_writable;
        // Closing states deliberately remove READABLE interest so the worker
        // cannot decode extra packets while waiting for queued writes to flush
        let interest = if !wants_readable {
            Interest::WRITABLE
        } else if wants_writable {
            Interest::READABLE | Interest::WRITABLE
        } else {
            Interest::READABLE
        };
        self.poll
            .registry()
            .reregister(&mut client.stream, token, interest)
    }

    fn current_mut(&mut self, id: ClientId) -> Option<&mut PollClient> {
        // Tokens are recycled. The generation check prevents stale handles from
        // mutating a newer connection that inherited the same poll token
        self.clients
            .get_mut(&id.token)
            .filter(|client| client.id == id)
    }

    fn close_current(&mut self, id: ClientId, error: Option<io::Error>) -> bool {
        self.clients
            .get(&id.token)
            .is_none_or(|client| client.id != id)
            || self.finalize_close(id.token, error)
    }

    fn send_event(&mut self, event: ThreadEvent<I>) -> bool {
        if !self.pending_events.is_empty() {
            if self.pending_events.len() >= self.pending_event_limit {
                return false;
            }
            // Preserve event order once we have overflowed the public channel;
            // bypassing this queue would let newer events overtake older ones
            self.pending_events.push_back(event);
            return true;
        }
        match self.events_sender.try_send(event) {
            Ok(()) => true,
            Err(TrySendError::Full(event)) => {
                debug_assert!(self.pending_event_limit > 0);
                self.pending_events.push_back(event);
                true
            }
            Err(TrySendError::Disconnected(_)) => false,
        }
    }

    fn flush_pending_event(&mut self) -> bool {
        while let Some(event) = self.pending_events.pop_front() {
            match self.events_sender.try_send(event) {
                Ok(()) => {}
                Err(TrySendError::Full(event)) => {
                    self.pending_events.push_front(event);
                    return true;
                }
                Err(TrySendError::Disconnected(_)) => return false,
            }
        }
        true
    }

    fn expire_timed_out_clients(&mut self) {
        let now = std::time::Instant::now();
        // Collect first so finalizing sockets can freely mutate the client map
        let expired: Vec<(Token, &'static str)> = self
            .clients
            .iter()
            .filter_map(|(&token, client)| {
                if client.state.is_open()
                    && self.config.packet_assembly_timeout.is_some_and(|timeout| {
                        client
                            .packet_started_at
                            .is_some_and(|started_at| now.duration_since(started_at) >= timeout)
                    })
                {
                    Some((token, "incoming packet assembly timeout elapsed"))
                } else if self
                    .config
                    .idle_timeout
                    .is_some_and(|timeout| now.duration_since(client.last_activity) >= timeout)
                {
                    Some((token, "client idle timeout elapsed"))
                } else {
                    None
                }
            })
            .collect();
        for (token, message) in expired {
            self.finalize_close(
                token,
                Some(io::Error::new(io::ErrorKind::TimedOut, message)),
            );
        }
    }

    fn close_all(&mut self, error: Option<io::Error>) {
        let tokens: Vec<Token> = self.clients.keys().copied().collect();
        for token in tokens {
            let err = error
                .as_ref()
                .map(|e| io::Error::new(e.kind(), e.to_string()));
            let _ = self.finalize_close(token, err);
        }
    }
}

enum ThreadCommand<O> {
    SendPacket { id: ClientId, packet: O },
}

enum ControlCommand {
    DisconnectClient {
        id: ClientId,
        packet_command_cutoff: u64,
    },
    DisconnectClientNow {
        id: ClientId,
    },
    Shutdown,
}

enum ThreadEvent<I> {
    Accept {
        id: ClientId,
        peer_addr: SocketAddr,
    },
    Lost {
        id: ClientId,
        error: Option<io::Error>,
    },
    ReceivePacket {
        id: ClientId,
        packet: I,
    },
    UnrecoverableError {
        error: io::Error,
    },
}

fn new_io_abort_error(message: &'static str) -> io::Error {
    io::Error::new(io::ErrorKind::ConnectionAborted, message)
}

fn configure_accepted_stream(stream: &TcpStream, config: ServerConfig) -> io::Result<()> {
    if let Err(error) = stream.set_nodelay(config.nodelay)
        && !is_best_effort_socket_option_error(&error)
    {
        return Err(error);
    }
    let socket = SockRef::from(stream);
    let keepalive_result = if let Some(time) = config.keepalive_time {
        socket.set_tcp_keepalive(&TcpKeepalive::new().with_time(time))
    } else {
        socket.set_keepalive(false)
    };
    if let Err(error) = keepalive_result
        && !is_best_effort_socket_option_error(&error)
    {
        return Err(error);
    }
    Ok(())
}

fn is_best_effort_socket_option_error(error: &io::Error) -> bool {
    matches!(
        error.kind(),
        io::ErrorKind::PermissionDenied | io::ErrorKind::Unsupported
    )
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum AcceptErrorAction {
    Done,
    RetryImmediately,
    RetryAfterBackoff,
    Fatal,
}

fn classify_accept_error(error: &io::Error) -> AcceptErrorAction {
    if error.kind() == io::ErrorKind::WouldBlock {
        return AcceptErrorAction::Done;
    }
    if matches!(
        error.kind(),
        io::ErrorKind::Interrupted | io::ErrorKind::ConnectionAborted
    ) {
        return AcceptErrorAction::RetryImmediately;
    }
    if error.kind() == io::ErrorKind::OutOfMemory {
        return AcceptErrorAction::RetryAfterBackoff;
    }
    if matches!(
        error.raw_os_error(),
        // Common Unix EMFILE, ENFILE, ENOMEM, and ENOBUFS values, followed by
        // their Winsock equivalents. These errors may clear after descriptors
        // or kernel socket buffers become available.
        Some(12 | 23 | 24 | 55 | 105 | 10024 | 10055)
    ) {
        AcceptErrorAction::RetryAfterBackoff
    } else {
        AcceptErrorAction::Fatal
    }
}

#[cfg(feature = "stats")]
fn atomic_saturating_add(counter: &AtomicU64, value: u64) {
    let _ = counter.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
        Some(current.saturating_add(value))
    });
}

#[cfg(test)]
mod tests {
    use super::{
        AcceptErrorAction, ClientIdAllocator, ServerClient, ServerConfig, classify_accept_error,
        configure_accepted_stream,
    };
    use mio::net::TcpStream as MioTcpStream;
    use socket2::SockRef;
    use std::{io, net::TcpListener, net::TcpStream, time::Duration};

    #[cfg(feature = "stats")]
    use super::atomic_saturating_add;
    #[cfg(feature = "stats")]
    use std::sync::atomic::{AtomicU64, Ordering};

    #[test]
    fn client_id_is_generation_not_token_packed_value() {
        let mut ids = ClientIdAllocator::new();
        let first = ids.allocate();
        ids.release(first.token);
        let second = ids.allocate();

        assert_eq!(first.token, second.token);
        assert_eq!(ServerClient(first).id(), 1);
        assert_eq!(ServerClient(second).id(), 2);
    }

    #[test]
    #[ignore = "socket option introspection is platform dependent"]
    fn accepted_socket_options_are_applied() -> io::Result<()> {
        let listener = TcpListener::bind("127.0.0.1:0")?;
        let client = TcpStream::connect(listener.local_addr()?)?;
        let (server, _) = listener.accept()?;
        server.set_nonblocking(true)?;
        let server = MioTcpStream::from_std(server);

        configure_accepted_stream(
            &server,
            ServerConfig {
                nodelay: true,
                keepalive_time: Some(Duration::from_secs(60)),
                ..ServerConfig::default()
            },
        )?;
        if let Ok(nodelay) = server.nodelay() {
            assert!(nodelay);
        }
        if let Ok(keepalive) = SockRef::from(&server).keepalive() {
            assert!(keepalive);
        }

        configure_accepted_stream(
            &server,
            ServerConfig {
                nodelay: false,
                keepalive_time: None,
                ..ServerConfig::default()
            },
        )?;
        if let Ok(nodelay) = server.nodelay() {
            assert!(!nodelay);
        }
        if let Ok(keepalive) = SockRef::from(&server).keepalive() {
            assert!(!keepalive);
        }
        drop(client);
        Ok(())
    }

    #[test]
    fn accept_errors_are_classified_for_retry() {
        assert_eq!(
            classify_accept_error(&io::Error::from(io::ErrorKind::WouldBlock)),
            AcceptErrorAction::Done
        );
        assert_eq!(
            classify_accept_error(&io::Error::from(io::ErrorKind::Interrupted)),
            AcceptErrorAction::RetryImmediately
        );
        assert_eq!(
            classify_accept_error(&io::Error::from(io::ErrorKind::ConnectionAborted)),
            AcceptErrorAction::RetryImmediately
        );
        assert_eq!(
            classify_accept_error(&io::Error::from_raw_os_error(24)),
            AcceptErrorAction::RetryAfterBackoff
        );
        assert_eq!(
            classify_accept_error(&io::Error::from(io::ErrorKind::PermissionDenied)),
            AcceptErrorAction::Fatal
        );
    }

    #[cfg(feature = "stats")]
    #[test]
    fn stats_counters_saturate() {
        let counter = AtomicU64::new(u64::MAX - 1);
        atomic_saturating_add(&counter, 2);
        assert_eq!(counter.load(Ordering::Relaxed), u64::MAX);
    }
}