reinhardt-websockets 0.2.0

WebSocket support for real-time bidirectional communication
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
#![allow(deprecated)] // `ConnectionConfig` is deprecated but still used internally during the compatibility window.

use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::RwLock;
use tokio::sync::mpsc;

/// Ping/pong keepalive configuration for WebSocket connections.
///
/// Controls how frequently ping frames are sent and how long
/// the server waits for a pong response before considering
/// the connection dead.
///
/// # Examples
///
/// ```
/// use reinhardt_websockets::connection::PingPongConfig;
/// use std::time::Duration;
///
/// // Use defaults (30s ping interval, 10s pong timeout)
/// let config = PingPongConfig::default();
/// assert_eq!(config.ping_interval(), Duration::from_secs(30));
/// assert_eq!(config.pong_timeout(), Duration::from_secs(10));
///
/// // Custom configuration
/// let config = PingPongConfig::new(
///     Duration::from_secs(15),
///     Duration::from_secs(5),
/// );
/// assert_eq!(config.ping_interval(), Duration::from_secs(15));
/// assert_eq!(config.pong_timeout(), Duration::from_secs(5));
/// ```
#[derive(Debug, Clone)]
pub struct PingPongConfig {
	/// Interval between ping frames sent to the client
	ping_interval: Duration,
	/// Maximum time to wait for a pong response before closing
	pong_timeout: Duration,
}

impl Default for PingPongConfig {
	fn default() -> Self {
		Self {
			ping_interval: Duration::from_secs(30),
			pong_timeout: Duration::from_secs(10),
		}
	}
}

impl PingPongConfig {
	/// Creates a new ping/pong configuration with the given intervals.
	///
	/// # Arguments
	///
	/// * `ping_interval` - How often to send ping frames
	/// * `pong_timeout` - How long to wait for a pong response
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::connection::PingPongConfig;
	/// use std::time::Duration;
	///
	/// let config = PingPongConfig::new(
	///     Duration::from_secs(20),
	///     Duration::from_secs(8),
	/// );
	/// assert_eq!(config.ping_interval(), Duration::from_secs(20));
	/// assert_eq!(config.pong_timeout(), Duration::from_secs(8));
	/// ```
	pub fn new(ping_interval: Duration, pong_timeout: Duration) -> Self {
		Self {
			ping_interval,
			pong_timeout,
		}
	}

	/// Returns the ping interval duration.
	pub fn ping_interval(&self) -> Duration {
		self.ping_interval
	}

	/// Returns the pong timeout duration.
	pub fn pong_timeout(&self) -> Duration {
		self.pong_timeout
	}

	/// Sets the ping interval duration.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::connection::PingPongConfig;
	/// use std::time::Duration;
	///
	/// let config = PingPongConfig::default()
	///     .with_ping_interval(Duration::from_secs(60));
	/// assert_eq!(config.ping_interval(), Duration::from_secs(60));
	/// ```
	pub fn with_ping_interval(mut self, interval: Duration) -> Self {
		self.ping_interval = interval;
		self
	}

	/// Sets the pong timeout duration.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::connection::PingPongConfig;
	/// use std::time::Duration;
	///
	/// let config = PingPongConfig::default()
	///     .with_pong_timeout(Duration::from_secs(15));
	/// assert_eq!(config.pong_timeout(), Duration::from_secs(15));
	/// ```
	pub fn with_pong_timeout(mut self, timeout: Duration) -> Self {
		self.pong_timeout = timeout;
		self
	}
}

/// Connection timeout configuration
///
/// This struct defines the timeout settings for WebSocket connections
/// to prevent resource exhaustion from idle connections.
///
/// # Fields
///
/// - `idle_timeout` - Maximum duration a connection can be idle before being closed (default: 5 minutes)
/// - `handshake_timeout` - Maximum duration for the WebSocket handshake to complete (default: 10 seconds)
/// - `cleanup_interval` - Interval for checking idle connections (default: 30 seconds)
///
/// # Examples
///
/// ```
/// use reinhardt_websockets::connection::ConnectionConfig;
/// use std::time::Duration;
///
/// let config = ConnectionConfig::new()
///     .with_idle_timeout(Duration::from_secs(300))
///     .with_handshake_timeout(Duration::from_secs(10))
///     .with_cleanup_interval(Duration::from_secs(30));
///
/// assert_eq!(config.idle_timeout(), Duration::from_secs(300));
/// assert_eq!(config.handshake_timeout(), Duration::from_secs(10));
/// assert_eq!(config.cleanup_interval(), Duration::from_secs(30));
/// ```
#[deprecated(
	since = "0.2.0",
	note = "Use `ConnectionSettings` with the `#[settings]` macro instead."
)]
#[derive(Debug, Clone)]
pub struct ConnectionConfig {
	idle_timeout: Duration,
	handshake_timeout: Duration,
	cleanup_interval: Duration,
	/// Maximum number of concurrent connections allowed (None for unlimited)
	max_connections: Option<usize>,
	/// Ping/pong keepalive configuration
	ping_config: PingPongConfig,
}

impl Default for ConnectionConfig {
	fn default() -> Self {
		Self {
			idle_timeout: Duration::from_secs(300), // 5 minutes default
			handshake_timeout: Duration::from_secs(10), // 10 seconds default
			cleanup_interval: Duration::from_secs(30), // 30 seconds default
			max_connections: None,                  // Unlimited by default
			ping_config: PingPongConfig::default(),
		}
	}
}

impl ConnectionConfig {
	/// Create a new connection configuration with default values
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::connection::ConnectionConfig;
	/// use std::time::Duration;
	///
	/// let config = ConnectionConfig::new();
	/// assert_eq!(config.idle_timeout(), Duration::from_secs(300));
	/// assert_eq!(config.handshake_timeout(), Duration::from_secs(10));
	/// assert_eq!(config.cleanup_interval(), Duration::from_secs(30));
	/// ```
	pub fn new() -> Self {
		Self::default()
	}

	/// Set the idle timeout duration
	///
	/// # Arguments
	///
	/// * `timeout` - Maximum duration a connection can be idle before being closed
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::connection::ConnectionConfig;
	/// use std::time::Duration;
	///
	/// let config = ConnectionConfig::new()
	///     .with_idle_timeout(Duration::from_secs(60));
	///
	/// assert_eq!(config.idle_timeout(), Duration::from_secs(60));
	/// ```
	pub fn with_idle_timeout(mut self, timeout: Duration) -> Self {
		self.idle_timeout = timeout;
		self
	}

	/// Set the handshake timeout duration
	///
	/// # Arguments
	///
	/// * `timeout` - Maximum duration for the WebSocket handshake to complete
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::connection::ConnectionConfig;
	/// use std::time::Duration;
	///
	/// let config = ConnectionConfig::new()
	///     .with_handshake_timeout(Duration::from_secs(5));
	///
	/// assert_eq!(config.handshake_timeout(), Duration::from_secs(5));
	/// ```
	pub fn with_handshake_timeout(mut self, timeout: Duration) -> Self {
		self.handshake_timeout = timeout;
		self
	}

	/// Set the cleanup interval for checking idle connections
	///
	/// # Arguments
	///
	/// * `interval` - How often to check for idle connections
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::connection::ConnectionConfig;
	/// use std::time::Duration;
	///
	/// let config = ConnectionConfig::new()
	///     .with_cleanup_interval(Duration::from_secs(15));
	///
	/// assert_eq!(config.cleanup_interval(), Duration::from_secs(15));
	/// ```
	pub fn with_cleanup_interval(mut self, interval: Duration) -> Self {
		self.cleanup_interval = interval;
		self
	}

	/// Get the idle timeout duration
	pub fn idle_timeout(&self) -> Duration {
		self.idle_timeout
	}

	/// Get the handshake timeout duration
	pub fn handshake_timeout(&self) -> Duration {
		self.handshake_timeout
	}

	/// Get the cleanup interval duration
	pub fn cleanup_interval(&self) -> Duration {
		self.cleanup_interval
	}

	/// Set the maximum number of concurrent connections
	///
	/// # Arguments
	///
	/// * `max` - Maximum number of connections allowed. Use `None` for unlimited.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::connection::ConnectionConfig;
	///
	/// let config = ConnectionConfig::new()
	///     .with_max_connections(Some(1000));
	///
	/// assert_eq!(config.max_connections(), Some(1000));
	/// ```
	pub fn with_max_connections(mut self, max: Option<usize>) -> Self {
		self.max_connections = max;
		self
	}

	/// Get the maximum number of concurrent connections
	pub fn max_connections(&self) -> Option<usize> {
		self.max_connections
	}

	/// Set the ping/pong keepalive configuration.
	///
	/// # Arguments
	///
	/// * `config` - The ping/pong configuration to use
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::connection::{ConnectionConfig, PingPongConfig};
	/// use std::time::Duration;
	///
	/// let ping_config = PingPongConfig::new(
	///     Duration::from_secs(15),
	///     Duration::from_secs(5),
	/// );
	/// let config = ConnectionConfig::new()
	///     .with_ping_config(ping_config);
	///
	/// assert_eq!(config.ping_config().ping_interval(), Duration::from_secs(15));
	/// assert_eq!(config.ping_config().pong_timeout(), Duration::from_secs(5));
	/// ```
	pub fn with_ping_config(mut self, config: PingPongConfig) -> Self {
		self.ping_config = config;
		self
	}

	/// Get the ping/pong keepalive configuration.
	pub fn ping_config(&self) -> &PingPongConfig {
		&self.ping_config
	}

	/// Create a configuration with no idle timeout (connections never time out)
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::connection::ConnectionConfig;
	///
	/// let config = ConnectionConfig::no_timeout();
	/// assert_eq!(config.idle_timeout(), std::time::Duration::MAX);
	/// assert_eq!(config.handshake_timeout(), std::time::Duration::MAX);
	/// ```
	pub fn no_timeout() -> Self {
		Self {
			idle_timeout: Duration::MAX,
			handshake_timeout: Duration::MAX,
			cleanup_interval: Duration::from_secs(30),
			max_connections: None,
			ping_config: PingPongConfig::default(),
		}
	}

	/// Create a strict configuration with short timeouts
	///
	/// - Idle timeout: 30 seconds
	/// - Handshake timeout: 5 seconds
	/// - Cleanup interval: 10 seconds
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::connection::ConnectionConfig;
	/// use std::time::Duration;
	///
	/// let config = ConnectionConfig::strict();
	/// assert_eq!(config.idle_timeout(), Duration::from_secs(30));
	/// assert_eq!(config.handshake_timeout(), Duration::from_secs(5));
	/// assert_eq!(config.cleanup_interval(), Duration::from_secs(10));
	/// ```
	pub fn strict() -> Self {
		Self {
			idle_timeout: Duration::from_secs(30),
			handshake_timeout: Duration::from_secs(5),
			cleanup_interval: Duration::from_secs(10),
			max_connections: None,
			ping_config: PingPongConfig::new(Duration::from_secs(10), Duration::from_secs(5)),
		}
	}

	/// Create a permissive configuration with long timeouts
	///
	/// - Idle timeout: 1 hour
	/// - Handshake timeout: 30 seconds
	/// - Cleanup interval: 60 seconds
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::connection::ConnectionConfig;
	/// use std::time::Duration;
	///
	/// let config = ConnectionConfig::permissive();
	/// assert_eq!(config.idle_timeout(), Duration::from_secs(3600));
	/// assert_eq!(config.handshake_timeout(), Duration::from_secs(30));
	/// assert_eq!(config.cleanup_interval(), Duration::from_secs(60));
	/// ```
	pub fn permissive() -> Self {
		Self {
			idle_timeout: Duration::from_secs(3600),
			handshake_timeout: Duration::from_secs(30),
			cleanup_interval: Duration::from_secs(60),
			max_connections: None,
			ping_config: PingPongConfig::new(Duration::from_secs(60), Duration::from_secs(30)),
		}
	}
}

/// Errors that can occur during WebSocket operations.
#[derive(Debug, thiserror::Error)]
pub enum WebSocketError {
	/// A connection-level error occurred.
	#[error("Connection error")]
	Connection(String),
	/// Failed to send a message to the peer.
	#[error("Send failed")]
	Send(String),
	/// Failed to receive a message from the peer.
	#[error("Receive failed")]
	Receive(String),
	/// A WebSocket protocol violation was detected.
	#[error("Protocol error")]
	Protocol(String),
	/// An internal server error occurred.
	#[error("Internal error")]
	Internal(String),
	/// The connection timed out after the given duration of inactivity.
	#[error("Connection timed out")]
	Timeout(Duration),
	/// Reconnection failed after the specified number of attempts.
	#[error("Reconnection failed")]
	ReconnectFailed(u32),
	/// The binary payload was invalid or could not be decoded.
	#[error("Invalid binary payload: {0}")]
	BinaryPayload(String),
	/// No pong response was received within the heartbeat timeout.
	#[error("Heartbeat timeout: no pong received within {0:?}")]
	HeartbeatTimeout(Duration),
	/// The consumer could not keep up with the message rate.
	#[error("Slow consumer: send timed out after {0:?}")]
	SlowConsumer(Duration),
}

impl WebSocketError {
	/// Returns a sanitized error message safe for client-facing communication.
	///
	/// Internal details (buffer sizes, queue depths, connection state, type names)
	/// are stripped to prevent information leakage.
	pub fn client_message(&self) -> &'static str {
		match self {
			Self::Connection(_) => "Connection error",
			Self::Send(_) => "Failed to send message",
			Self::Receive(_) => "Failed to receive message",
			Self::Protocol(_) => "Protocol error",
			Self::Internal(_) => "Internal server error",
			Self::Timeout(_) => "Connection timed out",
			Self::ReconnectFailed(_) => "Reconnection failed",
			Self::BinaryPayload(_) => "Invalid message format",
			Self::HeartbeatTimeout(_) => "Connection timed out",
			Self::SlowConsumer(_) => "Server overloaded",
		}
	}

	/// Returns the internal detail message for logging purposes.
	///
	/// This MUST NOT be sent to clients as it may contain sensitive
	/// internal state information.
	pub fn internal_detail(&self) -> String {
		match self {
			Self::Connection(msg) => format!("Connection error: {}", msg),
			Self::Send(msg) => format!("Send error: {}", msg),
			Self::Receive(msg) => format!("Receive error: {}", msg),
			Self::Protocol(msg) => format!("Protocol error: {}", msg),
			Self::Internal(msg) => format!("Internal error: {}", msg),
			Self::Timeout(d) => format!("Connection timeout: idle for {:?}", d),
			Self::ReconnectFailed(n) => format!("Reconnection failed after {} attempts", n),
			Self::BinaryPayload(msg) => format!("Invalid binary payload: {}", msg),
			Self::HeartbeatTimeout(d) => format!("Heartbeat timeout: no pong within {:?}", d),
			Self::SlowConsumer(d) => format!("Slow consumer: send timed out after {:?}", d),
		}
	}
}

/// A specialized `Result` type for WebSocket operations.
pub type WebSocketResult<T> = Result<T, WebSocketError>;

/// WebSocket message types
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(tag = "type")]
pub enum Message {
	/// A UTF-8 text message.
	Text {
		/// The text content of the message.
		data: String,
	},
	/// A binary message.
	Binary {
		/// The raw bytes of the message.
		data: Vec<u8>,
	},
	/// A ping control frame.
	Ping,
	/// A pong control frame (response to ping).
	Pong,
	/// A close control frame with status code and reason.
	Close {
		/// The WebSocket close status code.
		code: u16,
		/// A human-readable reason for closing.
		reason: String,
	},
}

impl Message {
	/// Creates a new text message.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::Message;
	///
	/// let msg = Message::text("Hello, World!".to_string());
	/// match msg {
	///     Message::Text { data } => assert_eq!(data, "Hello, World!"),
	///     _ => panic!("Expected text message"),
	/// }
	/// ```
	pub fn text(data: String) -> Self {
		Self::Text { data }
	}
	/// Creates a new binary message.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::Message;
	///
	/// let data = vec![0x48, 0x65, 0x6c, 0x6c, 0x6f]; // "Hello" in bytes
	/// let msg = Message::binary(data.clone());
	/// match msg {
	///     Message::Binary { data: d } => assert_eq!(d, data),
	///     _ => panic!("Expected binary message"),
	/// }
	/// ```
	pub fn binary(data: Vec<u8>) -> Self {
		Self::Binary { data }
	}
	/// Creates a text message containing JSON-serialized data.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::Message;
	/// use serde::Serialize;
	///
	/// #[derive(Serialize)]
	/// struct User {
	///     name: String,
	///     age: u32,
	/// }
	///
	/// let user = User {
	///     name: "Alice".to_string(),
	///     age: 30,
	/// };
	///
	/// let msg = Message::json(&user).unwrap();
	/// match msg {
	///     Message::Text { data } => {
	///         assert!(data.contains("Alice"));
	///         assert!(data.contains("30"));
	///     },
	///     _ => panic!("Expected text message"),
	/// }
	/// ```
	pub fn json<T: serde::Serialize>(data: &T) -> WebSocketResult<Self> {
		let json =
			serde_json::to_string(data).map_err(|e| WebSocketError::Protocol(e.to_string()))?;
		Ok(Self::text(json))
	}
	/// Parses the message content as JSON into the target type.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::Message;
	/// use serde::Deserialize;
	///
	/// #[derive(Deserialize, Debug, PartialEq)]
	/// struct User {
	///     name: String,
	///     age: u32,
	/// }
	///
	/// let msg = Message::text(r#"{"name":"Bob","age":25}"#.to_string());
	/// let user: User = msg.parse_json().unwrap();
	/// assert_eq!(user.name, "Bob");
	/// assert_eq!(user.age, 25);
	/// ```
	pub fn parse_json<T: serde::de::DeserializeOwned>(&self) -> WebSocketResult<T> {
		match self {
			Message::Text { data } => {
				serde_json::from_str(data).map_err(|e| WebSocketError::Protocol(e.to_string()))
			}
			_ => Err(WebSocketError::Protocol("Not a text message".to_string())),
		}
	}
}

/// WebSocket connection with activity tracking and timeout support
pub struct WebSocketConnection {
	id: String,
	tx: mpsc::UnboundedSender<Message>,
	closed: Arc<RwLock<bool>>,
	/// Subprotocol (negotiated protocol during WebSocket handshake)
	subprotocol: Option<String>,
	/// Timestamp of last activity on this connection
	last_activity: Arc<RwLock<Instant>>,
	/// Connection timeout configuration
	config: ConnectionConfig,
}

impl WebSocketConnection {
	/// Creates a new WebSocket connection with the given ID and sender.
	///
	/// Uses default [`ConnectionConfig`] for timeout settings.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::{WebSocketConnection, Message};
	/// use tokio::sync::mpsc;
	///
	/// let (tx, _rx) = mpsc::unbounded_channel();
	/// let conn = WebSocketConnection::new("connection_1".to_string(), tx);
	/// assert_eq!(conn.id(), "connection_1");
	/// ```
	pub fn new(id: String, tx: mpsc::UnboundedSender<Message>) -> Self {
		Self {
			id,
			tx,
			closed: Arc::new(RwLock::new(false)),
			subprotocol: None,
			last_activity: Arc::new(RwLock::new(Instant::now())),
			config: ConnectionConfig::default(),
		}
	}

	/// Creates a new WebSocket connection with the given ID, sender, and configuration.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::{WebSocketConnection, Message};
	/// use reinhardt_websockets::connection::ConnectionConfig;
	/// use tokio::sync::mpsc;
	/// use std::time::Duration;
	///
	/// let (tx, _rx) = mpsc::unbounded_channel();
	/// let config = ConnectionConfig::new()
	///     .with_idle_timeout(Duration::from_secs(60));
	/// let conn = WebSocketConnection::with_config("conn_1".to_string(), tx, config);
	/// assert_eq!(conn.id(), "conn_1");
	/// assert_eq!(conn.config().idle_timeout(), Duration::from_secs(60));
	/// ```
	pub fn with_config(
		id: String,
		tx: mpsc::UnboundedSender<Message>,
		config: ConnectionConfig,
	) -> Self {
		Self {
			id,
			tx,
			closed: Arc::new(RwLock::new(false)),
			subprotocol: None,
			last_activity: Arc::new(RwLock::new(Instant::now())),
			config,
		}
	}

	/// Creates a new WebSocket connection with the given ID, sender, and subprotocol.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::{WebSocketConnection, Message};
	/// use tokio::sync::mpsc;
	///
	/// let (tx, _rx) = mpsc::unbounded_channel();
	/// let conn = WebSocketConnection::with_subprotocol(
	///     "connection_1".to_string(),
	///     tx,
	///     Some("chat".to_string())
	/// );
	/// assert_eq!(conn.id(), "connection_1");
	/// assert_eq!(conn.subprotocol(), Some("chat"));
	/// ```
	pub fn with_subprotocol(
		id: String,
		tx: mpsc::UnboundedSender<Message>,
		subprotocol: Option<String>,
	) -> Self {
		Self {
			id,
			tx,
			closed: Arc::new(RwLock::new(false)),
			subprotocol,
			last_activity: Arc::new(RwLock::new(Instant::now())),
			config: ConnectionConfig::default(),
		}
	}

	/// Gets the negotiated subprotocol, if any.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::{WebSocketConnection, Message};
	/// use tokio::sync::mpsc;
	///
	/// let (tx, _rx) = mpsc::unbounded_channel();
	/// let conn = WebSocketConnection::with_subprotocol(
	///     "test".to_string(),
	///     tx,
	///     Some("chat".to_string())
	/// );
	/// assert_eq!(conn.subprotocol(), Some("chat"));
	/// ```
	pub fn subprotocol(&self) -> Option<&str> {
		self.subprotocol.as_deref()
	}

	/// Gets the connection ID.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::{WebSocketConnection, Message};
	/// use tokio::sync::mpsc;
	///
	/// let (tx, _rx) = mpsc::unbounded_channel();
	/// let conn = WebSocketConnection::new("test_id".to_string(), tx);
	/// assert_eq!(conn.id(), "test_id");
	/// ```
	pub fn id(&self) -> &str {
		&self.id
	}

	/// Gets the connection timeout configuration.
	pub fn config(&self) -> &ConnectionConfig {
		&self.config
	}

	/// Records activity on the connection, resetting the idle timer.
	///
	/// This is called automatically when sending messages, but can also be called
	/// manually to indicate that the connection is still active (e.g., when
	/// receiving messages from the client).
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::WebSocketConnection;
	/// use tokio::sync::mpsc;
	///
	/// # tokio_test::block_on(async {
	/// let (tx, _rx) = mpsc::unbounded_channel();
	/// let conn = WebSocketConnection::new("test".to_string(), tx);
	///
	/// conn.record_activity().await;
	/// assert!(!conn.is_idle().await);
	/// # });
	/// ```
	pub async fn record_activity(&self) {
		*self.last_activity.write().await = Instant::now();
	}

	/// Returns the duration since the last activity on this connection.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::WebSocketConnection;
	/// use tokio::sync::mpsc;
	/// use std::time::Duration;
	///
	/// # tokio_test::block_on(async {
	/// let (tx, _rx) = mpsc::unbounded_channel();
	/// let conn = WebSocketConnection::new("test".to_string(), tx);
	///
	/// let idle = conn.idle_duration().await;
	/// assert!(idle < Duration::from_secs(1));
	/// # });
	/// ```
	pub async fn idle_duration(&self) -> Duration {
		self.last_activity.read().await.elapsed()
	}

	/// Checks whether this connection has exceeded its idle timeout.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::WebSocketConnection;
	/// use tokio::sync::mpsc;
	///
	/// # tokio_test::block_on(async {
	/// let (tx, _rx) = mpsc::unbounded_channel();
	/// let conn = WebSocketConnection::new("test".to_string(), tx);
	///
	/// // A freshly created connection is not idle
	/// assert!(!conn.is_idle().await);
	/// # });
	/// ```
	pub async fn is_idle(&self) -> bool {
		self.idle_duration().await > self.config.idle_timeout
	}

	/// Sends a message through the WebSocket connection.
	///
	/// Records activity on the connection when a message is sent successfully.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::{WebSocketConnection, Message};
	/// use tokio::sync::mpsc;
	///
	/// # tokio_test::block_on(async {
	/// let (tx, mut rx) = mpsc::unbounded_channel();
	/// let conn = WebSocketConnection::new("test".to_string(), tx);
	///
	/// let message = Message::text("Hello".to_string());
	/// conn.send(message).await.unwrap();
	///
	/// let received = rx.recv().await.unwrap();
	/// assert!(matches!(received, Message::Text { .. }));
	/// # });
	/// ```
	pub async fn send(&self, message: Message) -> WebSocketResult<()> {
		if *self.closed.read().await {
			return Err(WebSocketError::Send("Connection closed".to_string()));
		}

		let result = self
			.tx
			.send(message)
			.map_err(|e| WebSocketError::Send(e.to_string()));

		if result.is_ok() {
			self.record_activity().await;
		}

		result
	}
	/// Sends a text message through the WebSocket connection.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::{WebSocketConnection, Message};
	/// use tokio::sync::mpsc;
	///
	/// # tokio_test::block_on(async {
	/// let (tx, mut rx) = mpsc::unbounded_channel();
	/// let conn = WebSocketConnection::new("test".to_string(), tx);
	///
	/// conn.send_text("Hello World".to_string()).await.unwrap();
	///
	/// let received = rx.recv().await.unwrap();
	/// match received {
	///     Message::Text { data } => assert_eq!(data, "Hello World"),
	///     _ => panic!("Expected text message"),
	/// }
	/// # });
	/// ```
	pub async fn send_text(&self, text: String) -> WebSocketResult<()> {
		self.send(Message::text(text)).await
	}
	/// Sends a binary message through the WebSocket connection.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::{WebSocketConnection, Message};
	/// use tokio::sync::mpsc;
	///
	/// # tokio_test::block_on(async {
	/// let (tx, mut rx) = mpsc::unbounded_channel();
	/// let conn = WebSocketConnection::new("test".to_string(), tx);
	///
	/// let binary_data = vec![0x48, 0x65, 0x6c, 0x6c, 0x6f]; // "Hello"
	/// conn.send_binary(binary_data.clone()).await.unwrap();
	///
	/// let received = rx.recv().await.unwrap();
	/// match received {
	///     Message::Binary { data } => assert_eq!(data, binary_data),
	///     _ => panic!("Expected binary message"),
	/// }
	/// # });
	/// ```
	pub async fn send_binary(&self, data: Vec<u8>) -> WebSocketResult<()> {
		self.send(Message::binary(data)).await
	}
	/// Sends a JSON message through the WebSocket connection.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::{WebSocketConnection, Message};
	/// use tokio::sync::mpsc;
	/// use serde::Serialize;
	///
	/// #[derive(Serialize)]
	/// struct User {
	///     name: String,
	///     age: u32,
	/// }
	///
	/// # tokio_test::block_on(async {
	/// let (tx, mut rx) = mpsc::unbounded_channel();
	/// let conn = WebSocketConnection::new("test".to_string(), tx);
	///
	/// let user = User { name: "Alice".to_string(), age: 30 };
	/// conn.send_json(&user).await.unwrap();
	///
	/// let received = rx.recv().await.unwrap();
	/// match received {
	///     Message::Text { data } => assert!(data.contains("Alice")),
	///     _ => panic!("Expected text message"),
	/// }
	/// # });
	/// ```
	pub async fn send_json<T: serde::Serialize>(&self, data: &T) -> WebSocketResult<()> {
		let message = Message::json(data)?;
		self.send(message).await
	}
	/// Closes the WebSocket connection.
	///
	/// The connection is always marked as closed regardless of whether the
	/// close frame could be sent. This ensures resource cleanup even when
	/// the underlying channel is already broken.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::{WebSocketConnection, Message};
	/// use tokio::sync::mpsc;
	///
	/// # tokio_test::block_on(async {
	/// let (tx, mut rx) = mpsc::unbounded_channel();
	/// let conn = WebSocketConnection::new("test".to_string(), tx);
	///
	/// conn.close().await.unwrap();
	/// assert!(conn.is_closed().await);
	/// # });
	/// ```
	pub async fn close(&self) -> WebSocketResult<()> {
		// Mark as closed first to prevent new sends
		*self.closed.write().await = true;

		// Best-effort send of close frame; connection is closed regardless
		self.tx
			.send(Message::Close {
				code: 1000,
				reason: "Normal closure".to_string(),
			})
			.map_err(|e| WebSocketError::Send(e.to_string()))
	}
	/// Closes the connection with a custom close code and reason.
	///
	/// The connection is always marked as closed regardless of whether the
	/// close frame could be sent. This ensures resource cleanup even when
	/// the underlying channel is already broken.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::{WebSocketConnection, Message};
	/// use tokio::sync::mpsc;
	///
	/// # tokio_test::block_on(async {
	/// let (tx, mut rx) = mpsc::unbounded_channel();
	/// let conn = WebSocketConnection::new("test".to_string(), tx);
	///
	/// conn.close_with_reason(1001, "Idle timeout".to_string()).await.unwrap();
	/// assert!(conn.is_closed().await);
	///
	/// let msg = rx.recv().await.unwrap();
	/// match msg {
	///     Message::Close { code, reason } => {
	///         assert_eq!(code, 1001);
	///         assert_eq!(reason, "Idle timeout");
	///     },
	///     _ => panic!("Expected close message"),
	/// }
	/// # });
	/// ```
	pub async fn close_with_reason(&self, code: u16, reason: String) -> WebSocketResult<()> {
		// Mark as closed first to prevent new sends
		*self.closed.write().await = true;

		// Best-effort send of close frame; connection is closed regardless
		self.tx
			.send(Message::Close { code, reason })
			.map_err(|e| WebSocketError::Send(e.to_string()))
	}

	/// Forces the connection closed without sending a close frame.
	///
	/// Use this for abnormal close paths where the underlying transport is
	/// already broken and sending a close frame would fail.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::WebSocketConnection;
	/// use tokio::sync::mpsc;
	///
	/// # tokio_test::block_on(async {
	/// let (tx, _rx) = mpsc::unbounded_channel();
	/// let conn = WebSocketConnection::new("test".to_string(), tx);
	///
	/// conn.force_close().await;
	/// assert!(conn.is_closed().await);
	/// # });
	/// ```
	pub async fn force_close(&self) {
		*self.closed.write().await = true;
	}

	/// Checks if the WebSocket connection is closed.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::{WebSocketConnection, Message};
	/// use tokio::sync::mpsc;
	///
	/// # tokio_test::block_on(async {
	/// let (tx, _rx) = mpsc::unbounded_channel();
	/// let conn = WebSocketConnection::new("test".to_string(), tx);
	///
	/// assert!(!conn.is_closed().await);
	/// # });
	/// ```
	pub async fn is_closed(&self) -> bool {
		*self.closed.read().await
	}
}

/// Monitors WebSocket connections for idle timeouts and cleans them up.
///
/// The monitor periodically checks all registered connections and closes
/// those that have exceeded their idle timeout. This prevents resource
/// exhaustion from idle connection holding attacks.
///
/// # Examples
///
/// ```
/// use reinhardt_websockets::connection::{ConnectionConfig, ConnectionTimeoutMonitor};
/// use reinhardt_websockets::WebSocketConnection;
/// use tokio::sync::mpsc;
/// use std::sync::Arc;
/// use std::time::Duration;
///
/// # tokio_test::block_on(async {
/// let config = ConnectionConfig::new()
///     .with_idle_timeout(Duration::from_secs(60))
///     .with_cleanup_interval(Duration::from_secs(10));
///
/// let monitor = ConnectionTimeoutMonitor::new(config);
///
/// let (tx, _rx) = mpsc::unbounded_channel();
/// let conn = Arc::new(WebSocketConnection::new("conn_1".to_string(), tx));
/// monitor.register(conn).await.unwrap();
///
/// assert_eq!(monitor.connection_count().await, 1);
/// # });
/// ```
pub struct ConnectionTimeoutMonitor {
	connections: Arc<RwLock<HashMap<String, Arc<WebSocketConnection>>>>,
	config: ConnectionConfig,
}

impl ConnectionTimeoutMonitor {
	/// Creates a new connection timeout monitor with the given configuration.
	pub fn new(config: ConnectionConfig) -> Self {
		Self {
			connections: Arc::new(RwLock::new(HashMap::new())),
			config,
		}
	}

	/// Registers a connection for timeout monitoring.
	///
	/// Returns `Ok(())` if the connection was registered, or `Err` if the
	/// maximum connection limit has been reached.
	pub async fn register(
		&self,
		connection: Arc<WebSocketConnection>,
	) -> Result<(), WebSocketError> {
		let mut connections = self.connections.write().await;

		if let Some(max) = self.config.max_connections
			&& connections.len() >= max
		{
			return Err(WebSocketError::Connection(format!(
				"maximum connection limit reached ({})",
				max
			)));
		}

		connections.insert(connection.id().to_string(), connection);
		Ok(())
	}

	/// Unregisters a connection from timeout monitoring.
	pub async fn unregister(&self, connection_id: &str) {
		self.connections.write().await.remove(connection_id);
	}

	/// Returns the number of currently monitored connections.
	pub async fn connection_count(&self) -> usize {
		self.connections.read().await.len()
	}

	/// Checks all connections and closes those that have exceeded their idle timeout.
	///
	/// Returns the IDs of connections that were closed due to timeout.
	pub async fn check_idle_connections(&self) -> Vec<String> {
		let connections = self.connections.read().await;
		let mut timed_out = Vec::new();

		for (id, conn) in connections.iter() {
			if conn.is_closed().await {
				timed_out.push(id.clone());
				continue;
			}

			let idle_duration = conn.idle_duration().await;
			if idle_duration > self.config.idle_timeout {
				let reason = format!(
					"Idle timeout: connection idle for {}s (limit: {}s)",
					idle_duration.as_secs(),
					self.config.idle_timeout.as_secs()
				);
				// Close with 1001 (Going Away) as per RFC 6455
				let _ = conn.close_with_reason(1001, reason).await;
				timed_out.push(id.clone());
			}
		}

		drop(connections);

		// Remove timed-out connections
		if !timed_out.is_empty() {
			let mut connections = self.connections.write().await;
			for id in &timed_out {
				connections.remove(id);
			}
		}

		timed_out
	}

	/// Gracefully shuts down all monitored connections.
	///
	/// Sends a Close frame (code 1001, "Going Away") to each active connection
	/// and removes it from monitoring. Already-closed connections are silently
	/// removed.
	///
	/// Returns the IDs of all connections that were shut down.
	pub async fn shutdown_all(&self) -> Vec<String> {
		let mut connections = self.connections.write().await;
		let mut shut_down = Vec::with_capacity(connections.len());

		for (id, conn) in connections.drain() {
			if !conn.is_closed().await {
				let _ = conn
					.close_with_reason(1001, "Server shutting down".to_string())
					.await;
			}
			shut_down.push(id);
		}

		shut_down
	}

	/// Starts the background monitoring task.
	///
	/// Returns a [`tokio::task::JoinHandle`] that can be used to abort the monitor.
	/// The monitor runs until the handle is aborted or the process exits.
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_websockets::connection::{ConnectionConfig, ConnectionTimeoutMonitor};
	/// use std::time::Duration;
	///
	/// # tokio_test::block_on(async {
	/// let config = ConnectionConfig::new()
	///     .with_cleanup_interval(Duration::from_millis(100));
	/// let monitor = std::sync::Arc::new(ConnectionTimeoutMonitor::new(config));
	///
	/// let handle = monitor.start();
	///
	/// // Monitor is running in background...
	/// tokio::time::sleep(Duration::from_millis(50)).await;
	///
	/// // Stop the monitor
	/// handle.abort();
	/// # });
	/// ```
	pub fn start(self: &Arc<Self>) -> tokio::task::JoinHandle<()> {
		let monitor = Arc::clone(self);
		tokio::spawn(async move {
			let mut interval = tokio::time::interval(monitor.config.cleanup_interval);
			loop {
				interval.tick().await;
				monitor.check_idle_connections().await;
			}
		})
	}
}

/// Configuration for heartbeat (ping/pong) monitoring.
///
/// Defines how often pings are sent and how long to wait for a pong
/// response before considering the connection dead.
///
/// # Examples
///
/// ```
/// use reinhardt_websockets::connection::HeartbeatConfig;
/// use std::time::Duration;
///
/// let config = HeartbeatConfig::new(
///     Duration::from_secs(30),
///     Duration::from_secs(10),
/// );
///
/// assert_eq!(config.ping_interval(), Duration::from_secs(30));
/// assert_eq!(config.pong_timeout(), Duration::from_secs(10));
/// ```
#[derive(Debug, Clone)]
pub struct HeartbeatConfig {
	/// Interval between outgoing pings
	ping_interval: Duration,
	/// Maximum time to wait for a pong response before closing
	pong_timeout: Duration,
}

impl HeartbeatConfig {
	/// Creates a new heartbeat configuration.
	pub fn new(ping_interval: Duration, pong_timeout: Duration) -> Self {
		Self {
			ping_interval,
			pong_timeout,
		}
	}

	/// Returns the ping interval.
	pub fn ping_interval(&self) -> Duration {
		self.ping_interval
	}

	/// Returns the pong timeout.
	pub fn pong_timeout(&self) -> Duration {
		self.pong_timeout
	}
}

impl Default for HeartbeatConfig {
	fn default() -> Self {
		Self {
			ping_interval: Duration::from_secs(30),
			pong_timeout: Duration::from_secs(10),
		}
	}
}

/// Monitors a WebSocket connection's heartbeat via ping/pong.
///
/// Sends periodic pings and tracks when the last pong was received.
/// When no pong arrives within the configured timeout, the connection
/// is force-closed and the monitor signals a heartbeat failure.
///
/// # Examples
///
/// ```
/// use reinhardt_websockets::connection::{HeartbeatConfig, HeartbeatMonitor};
/// use reinhardt_websockets::WebSocketConnection;
/// use tokio::sync::mpsc;
/// use std::sync::Arc;
/// use std::time::Duration;
///
/// # tokio_test::block_on(async {
/// let (tx, _rx) = mpsc::unbounded_channel();
/// let conn = Arc::new(WebSocketConnection::new("hb_test".to_string(), tx));
/// let config = HeartbeatConfig::default();
///
/// let monitor = HeartbeatMonitor::new(conn, config);
/// assert!(!monitor.is_timed_out().await);
/// # });
/// ```
pub struct HeartbeatMonitor {
	connection: Arc<WebSocketConnection>,
	config: HeartbeatConfig,
	last_pong: Arc<RwLock<Instant>>,
	timed_out: Arc<RwLock<bool>>,
	pong_notify: Arc<tokio::sync::Notify>,
}

impl HeartbeatMonitor {
	/// Creates a new heartbeat monitor for the given connection.
	pub fn new(connection: Arc<WebSocketConnection>, config: HeartbeatConfig) -> Self {
		Self {
			connection,
			config,
			last_pong: Arc::new(RwLock::new(Instant::now())),
			timed_out: Arc::new(RwLock::new(false)),
			pong_notify: Arc::new(tokio::sync::Notify::new()),
		}
	}

	/// Records a pong response, resetting the timeout tracker.
	///
	/// This also wakes up the heartbeat monitor's sleep so it can
	/// proceed immediately instead of waiting for the full pong timeout.
	pub async fn record_pong(&self) {
		*self.last_pong.write().await = Instant::now();
		self.pong_notify.notify_one();
	}

	/// Returns the duration since the last pong was received.
	pub async fn time_since_last_pong(&self) -> Duration {
		self.last_pong.read().await.elapsed()
	}

	/// Returns whether the heartbeat has timed out.
	pub async fn is_timed_out(&self) -> bool {
		*self.timed_out.read().await
	}

	/// Checks whether the pong timeout has been exceeded.
	///
	/// If the timeout is exceeded, the connection is force-closed and
	/// the method returns `true`.
	pub async fn check_heartbeat(&self) -> bool {
		let since_pong = self.time_since_last_pong().await;

		if since_pong > self.config.pong_timeout {
			self.connection.force_close().await;
			*self.timed_out.write().await = true;
			return true;
		}

		false
	}

	/// Sends a ping message through the connection.
	///
	/// Returns `Ok(())` if the ping was sent, or an error if the
	/// connection is already closed.
	pub async fn send_ping(&self) -> WebSocketResult<()> {
		self.connection.send(Message::Ping).await
	}

	/// Returns a reference to the heartbeat configuration.
	pub fn config(&self) -> &HeartbeatConfig {
		&self.config
	}

	/// Returns a reference to the monitored connection.
	pub fn connection(&self) -> &Arc<WebSocketConnection> {
		&self.connection
	}

	/// Starts a background task that periodically sends pings and checks
	/// for pong timeouts.
	///
	/// Returns a [`tokio::task::JoinHandle`] that can be aborted to stop
	/// the monitor. The task ends automatically when a heartbeat timeout
	/// occurs.
	pub fn start(self: &Arc<Self>) -> tokio::task::JoinHandle<()> {
		let monitor = Arc::clone(self);
		tokio::spawn(async move {
			let mut interval = tokio::time::interval(monitor.config.ping_interval);
			loop {
				interval.tick().await;

				if monitor.connection.is_closed().await {
					break;
				}

				// Best-effort ping; if send fails, check_heartbeat will catch it
				let _ = monitor.send_ping().await;

				// Wait for pong or timeout, whichever comes first.
				// If pong arrives early, we skip the remaining sleep and
				// proceed to the next ping interval immediately.
				tokio::select! {
					() = tokio::time::sleep(monitor.config.pong_timeout) => {
						// Timeout elapsed without pong notification
						if monitor.check_heartbeat().await {
							break;
						}
					}
					() = monitor.pong_notify.notified() => {
						// Pong received early; no need to wait further
					}
				}
			}
		})
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use rstest::rstest;

	#[rstest]
	fn test_message_text() {
		// Arrange
		let text = "Hello".to_string();

		// Act
		let msg = Message::text(text);

		// Assert
		match msg {
			Message::Text { data } => assert_eq!(data, "Hello"),
			_ => panic!("Expected text message"),
		}
	}

	#[rstest]
	fn test_message_json() {
		// Arrange
		#[derive(serde::Serialize)]
		struct TestData {
			value: i32,
		}
		let data = TestData { value: 42 };

		// Act
		let msg = Message::json(&data).unwrap();

		// Assert
		match msg {
			Message::Text { data } => assert!(data.contains("42")),
			_ => panic!("Expected text message"),
		}
	}

	#[rstest]
	#[tokio::test]
	async fn test_connection_send() {
		// Arrange
		let (tx, mut rx) = mpsc::unbounded_channel();
		let conn = WebSocketConnection::new("test".to_string(), tx);

		// Act
		conn.send_text("Hello".to_string()).await.unwrap();

		// Assert
		let received = rx.recv().await.unwrap();
		match received {
			Message::Text { data } => assert_eq!(data, "Hello"),
			_ => panic!("Expected text message"),
		}
	}

	#[rstest]
	fn test_connection_config_default() {
		// Arrange & Act
		let config = ConnectionConfig::new();

		// Assert
		assert_eq!(config.idle_timeout(), Duration::from_secs(300));
		assert_eq!(config.handshake_timeout(), Duration::from_secs(10));
		assert_eq!(config.cleanup_interval(), Duration::from_secs(30));
	}

	#[rstest]
	fn test_connection_config_strict() {
		// Arrange & Act
		let config = ConnectionConfig::strict();

		// Assert
		assert_eq!(config.idle_timeout(), Duration::from_secs(30));
		assert_eq!(config.handshake_timeout(), Duration::from_secs(5));
		assert_eq!(config.cleanup_interval(), Duration::from_secs(10));
	}

	#[rstest]
	fn test_connection_config_permissive() {
		// Arrange & Act
		let config = ConnectionConfig::permissive();

		// Assert
		assert_eq!(config.idle_timeout(), Duration::from_secs(3600));
		assert_eq!(config.handshake_timeout(), Duration::from_secs(30));
		assert_eq!(config.cleanup_interval(), Duration::from_secs(60));
	}

	#[rstest]
	fn test_connection_config_no_timeout() {
		// Arrange & Act
		let config = ConnectionConfig::no_timeout();

		// Assert
		assert_eq!(config.idle_timeout(), Duration::MAX);
		assert_eq!(config.handshake_timeout(), Duration::MAX);
	}

	#[rstest]
	fn test_connection_config_builder() {
		// Arrange & Act
		let config = ConnectionConfig::new()
			.with_idle_timeout(Duration::from_secs(120))
			.with_handshake_timeout(Duration::from_secs(15))
			.with_cleanup_interval(Duration::from_secs(20));

		// Assert
		assert_eq!(config.idle_timeout(), Duration::from_secs(120));
		assert_eq!(config.handshake_timeout(), Duration::from_secs(15));
		assert_eq!(config.cleanup_interval(), Duration::from_secs(20));
	}

	#[rstest]
	#[tokio::test]
	async fn test_connection_with_config() {
		// Arrange
		let config = ConnectionConfig::new().with_idle_timeout(Duration::from_secs(60));
		let (tx, _rx) = mpsc::unbounded_channel();

		// Act
		let conn = WebSocketConnection::with_config("test".to_string(), tx, config);

		// Assert
		assert_eq!(conn.config().idle_timeout(), Duration::from_secs(60));
		assert!(!conn.is_idle().await);
	}

	#[rstest]
	#[tokio::test]
	async fn test_connection_record_activity_resets_idle() {
		// Arrange
		let config = ConnectionConfig::new().with_idle_timeout(Duration::from_millis(50));
		let (tx, _rx) = mpsc::unbounded_channel();
		let conn = WebSocketConnection::with_config("test".to_string(), tx, config);

		// Act - wait for connection to become idle
		tokio::time::sleep(Duration::from_millis(60)).await;
		assert!(conn.is_idle().await);

		// Act - record activity to reset idle timer
		conn.record_activity().await;

		// Assert - connection should no longer be idle
		assert!(!conn.is_idle().await);
	}

	#[rstest]
	#[tokio::test]
	async fn test_connection_becomes_idle_after_timeout() {
		// Arrange
		let config = ConnectionConfig::new().with_idle_timeout(Duration::from_millis(50));
		let (tx, _rx) = mpsc::unbounded_channel();
		let conn = WebSocketConnection::with_config("test".to_string(), tx, config);

		// Act - wait for connection to exceed idle timeout
		tokio::time::sleep(Duration::from_millis(60)).await;

		// Assert
		assert!(conn.is_idle().await);
		assert!(conn.idle_duration().await >= Duration::from_millis(50));
	}

	#[rstest]
	#[tokio::test]
	async fn test_send_resets_activity() {
		// Arrange
		let config = ConnectionConfig::new().with_idle_timeout(Duration::from_millis(100));
		let (tx, mut _rx) = mpsc::unbounded_channel();
		let conn = WebSocketConnection::with_config("test".to_string(), tx, config);

		// Act - wait a bit then send
		tokio::time::sleep(Duration::from_millis(50)).await;
		conn.send_text("ping".to_string()).await.unwrap();

		// Assert - activity should be recent
		assert!(conn.idle_duration().await < Duration::from_millis(30));
		assert!(!conn.is_idle().await);
	}

	#[rstest]
	#[tokio::test]
	async fn test_close_with_reason() {
		// Arrange
		let (tx, mut rx) = mpsc::unbounded_channel();
		let conn = WebSocketConnection::new("test".to_string(), tx);

		// Act
		conn.close_with_reason(1001, "Idle timeout".to_string())
			.await
			.unwrap();

		// Assert
		assert!(conn.is_closed().await);
		let msg = rx.recv().await.unwrap();
		match msg {
			Message::Close { code, reason } => {
				assert_eq!(code, 1001);
				assert_eq!(reason, "Idle timeout");
			}
			_ => panic!("Expected close message"),
		}
	}

	#[rstest]
	#[tokio::test]
	async fn test_timeout_monitor_register_and_count() {
		// Arrange
		let config = ConnectionConfig::new();
		let monitor = ConnectionTimeoutMonitor::new(config);
		let (tx, _rx) = mpsc::unbounded_channel();
		let conn = Arc::new(WebSocketConnection::new("conn_1".to_string(), tx));

		// Act
		monitor.register(conn).await.unwrap();

		// Assert
		assert_eq!(monitor.connection_count().await, 1);
	}

	#[rstest]
	#[tokio::test]
	async fn test_timeout_monitor_unregister() {
		// Arrange
		let config = ConnectionConfig::new();
		let monitor = ConnectionTimeoutMonitor::new(config);
		let (tx, _rx) = mpsc::unbounded_channel();
		let conn = Arc::new(WebSocketConnection::new("conn_1".to_string(), tx));
		monitor.register(conn).await.unwrap();

		// Act
		monitor.unregister("conn_1").await;

		// Assert
		assert_eq!(monitor.connection_count().await, 0);
	}

	#[rstest]
	#[tokio::test]
	async fn test_timeout_monitor_closes_idle_connections() {
		// Arrange
		let config = ConnectionConfig::new().with_idle_timeout(Duration::from_millis(50));
		let monitor = ConnectionTimeoutMonitor::new(config);

		let (tx1, mut rx1) = mpsc::unbounded_channel();
		let conn1 = Arc::new(WebSocketConnection::with_config(
			"idle_conn".to_string(),
			tx1,
			ConnectionConfig::new().with_idle_timeout(Duration::from_millis(50)),
		));

		let (tx2, _rx2) = mpsc::unbounded_channel();
		let conn2 = Arc::new(WebSocketConnection::with_config(
			"active_conn".to_string(),
			tx2,
			ConnectionConfig::new().with_idle_timeout(Duration::from_secs(300)),
		));

		monitor.register(conn1).await.unwrap();
		monitor.register(conn2.clone()).await.unwrap();

		// Act - wait for idle timeout to expire
		tokio::time::sleep(Duration::from_millis(60)).await;
		// Keep active connection alive
		conn2.record_activity().await;

		let timed_out = monitor.check_idle_connections().await;

		// Assert
		assert_eq!(timed_out.len(), 1);
		assert_eq!(timed_out[0], "idle_conn");
		assert_eq!(monitor.connection_count().await, 1);

		// Verify the idle connection received a close message
		let msg = rx1.recv().await.unwrap();
		match msg {
			Message::Close { code, reason } => {
				assert_eq!(code, 1001);
				assert!(reason.contains("Idle timeout"));
			}
			_ => panic!("Expected close message for idle connection"),
		}
	}

	#[rstest]
	#[tokio::test]
	async fn test_timeout_monitor_removes_already_closed_connections() {
		// Arrange
		let config = ConnectionConfig::new();
		let monitor = ConnectionTimeoutMonitor::new(config);
		let (tx, _rx) = mpsc::unbounded_channel();
		let conn = Arc::new(WebSocketConnection::new("conn_1".to_string(), tx));
		conn.close().await.unwrap();
		monitor.register(conn).await.unwrap();

		// Act
		let timed_out = monitor.check_idle_connections().await;

		// Assert
		assert_eq!(timed_out.len(), 1);
		assert_eq!(timed_out[0], "conn_1");
		assert_eq!(monitor.connection_count().await, 0);
	}

	#[rstest]
	#[tokio::test]
	async fn test_timeout_monitor_background_task() {
		// Arrange
		let config = ConnectionConfig::new()
			.with_idle_timeout(Duration::from_millis(30))
			.with_cleanup_interval(Duration::from_millis(20));
		let monitor = Arc::new(ConnectionTimeoutMonitor::new(config));

		let (tx, mut rx) = mpsc::unbounded_channel();
		let conn = Arc::new(WebSocketConnection::with_config(
			"bg_conn".to_string(),
			tx,
			ConnectionConfig::new().with_idle_timeout(Duration::from_millis(30)),
		));
		monitor.register(conn).await.unwrap();

		// Act - start background monitor
		let handle = monitor.start();

		// Wait for the monitor to detect and close the idle connection
		tokio::time::sleep(Duration::from_millis(120)).await;

		// Assert
		assert_eq!(monitor.connection_count().await, 0);

		// Verify close message was sent
		let msg = rx.recv().await.unwrap();
		assert!(matches!(msg, Message::Close { .. }));

		// Cleanup
		handle.abort();
	}

	#[rstest]
	fn test_ping_pong_config_default() {
		// Arrange & Act
		let config = PingPongConfig::default();

		// Assert
		assert_eq!(config.ping_interval(), Duration::from_secs(30));
		assert_eq!(config.pong_timeout(), Duration::from_secs(10));
	}

	#[rstest]
	fn test_ping_pong_config_custom() {
		// Arrange & Act
		let config = PingPongConfig::new(Duration::from_secs(15), Duration::from_secs(5));

		// Assert
		assert_eq!(config.ping_interval(), Duration::from_secs(15));
		assert_eq!(config.pong_timeout(), Duration::from_secs(5));
	}

	#[rstest]
	fn test_ping_pong_config_builder() {
		// Arrange & Act
		let config = PingPongConfig::default()
			.with_ping_interval(Duration::from_secs(60))
			.with_pong_timeout(Duration::from_secs(20));

		// Assert
		assert_eq!(config.ping_interval(), Duration::from_secs(60));
		assert_eq!(config.pong_timeout(), Duration::from_secs(20));
	}

	#[rstest]
	fn test_connection_config_has_default_ping_config() {
		// Arrange & Act
		let config = ConnectionConfig::new();

		// Assert
		assert_eq!(
			config.ping_config().ping_interval(),
			Duration::from_secs(30)
		);
		assert_eq!(config.ping_config().pong_timeout(), Duration::from_secs(10));
	}

	#[rstest]
	fn test_connection_config_with_custom_ping_config() {
		// Arrange
		let ping_config = PingPongConfig::new(Duration::from_secs(15), Duration::from_secs(5));

		// Act
		let config = ConnectionConfig::new().with_ping_config(ping_config);

		// Assert
		assert_eq!(
			config.ping_config().ping_interval(),
			Duration::from_secs(15)
		);
		assert_eq!(config.ping_config().pong_timeout(), Duration::from_secs(5));
	}

	#[rstest]
	fn test_strict_config_has_aggressive_ping() {
		// Arrange & Act
		let config = ConnectionConfig::strict();

		// Assert
		assert_eq!(
			config.ping_config().ping_interval(),
			Duration::from_secs(10)
		);
		assert_eq!(config.ping_config().pong_timeout(), Duration::from_secs(5));
	}

	#[rstest]
	fn test_permissive_config_has_relaxed_ping() {
		// Arrange & Act
		let config = ConnectionConfig::permissive();

		// Assert
		assert_eq!(
			config.ping_config().ping_interval(),
			Duration::from_secs(60)
		);
		assert_eq!(config.ping_config().pong_timeout(), Duration::from_secs(30));
	}

	#[rstest]
	#[tokio::test]
	async fn test_timeout_monitor_rejects_when_max_connections_reached() {
		// Arrange
		let config = ConnectionConfig::new().with_max_connections(Some(1));
		let monitor = ConnectionTimeoutMonitor::new(config);

		let (tx1, _rx1) = mpsc::unbounded_channel();
		let conn1 = Arc::new(WebSocketConnection::new("conn_1".to_string(), tx1));

		let (tx2, _rx2) = mpsc::unbounded_channel();
		let conn2 = Arc::new(WebSocketConnection::new("conn_2".to_string(), tx2));

		// Act
		monitor.register(conn1).await.unwrap();
		let result = monitor.register(conn2).await;

		// Assert
		assert!(result.is_err());
		assert_eq!(monitor.connection_count().await, 1);
	}

	#[rstest]
	#[tokio::test]
	async fn test_force_close_marks_connection_closed() {
		// Arrange
		let (tx, _rx) = mpsc::unbounded_channel();
		let conn = WebSocketConnection::new("test".to_string(), tx);

		// Act
		conn.force_close().await;

		// Assert
		assert!(conn.is_closed().await);
	}

	#[rstest]
	#[tokio::test]
	async fn test_close_marks_closed_even_when_channel_dropped() {
		// Arrange
		let (tx, rx) = mpsc::unbounded_channel();
		let conn = WebSocketConnection::new("test".to_string(), tx);

		// Drop receiver to simulate broken channel
		drop(rx);

		// Act - close should still mark the connection as closed
		let result = conn.close().await;

		// Assert
		assert!(result.is_err()); // send fails because receiver is dropped
		assert!(conn.is_closed().await); // but connection is still marked closed
	}

	#[rstest]
	#[tokio::test]
	async fn test_close_with_reason_marks_closed_even_when_channel_dropped() {
		// Arrange
		let (tx, rx) = mpsc::unbounded_channel();
		let conn = WebSocketConnection::new("test".to_string(), tx);

		// Drop receiver to simulate broken channel
		drop(rx);

		// Act
		let result = conn
			.close_with_reason(1006, "Abnormal close".to_string())
			.await;

		// Assert
		assert!(result.is_err());
		assert!(conn.is_closed().await);
	}

	#[rstest]
	#[tokio::test]
	async fn test_send_after_force_close_returns_error() {
		// Arrange
		let (tx, _rx) = mpsc::unbounded_channel();
		let conn = WebSocketConnection::new("test".to_string(), tx);
		conn.force_close().await;

		// Act
		let result = conn.send_text("should fail".to_string()).await;

		// Assert
		assert!(result.is_err());
		assert!(matches!(result.unwrap_err(), WebSocketError::Send(_)));
	}

	#[rstest]
	fn test_heartbeat_config_default() {
		// Arrange & Act
		let config = HeartbeatConfig::default();

		// Assert
		assert_eq!(config.ping_interval(), Duration::from_secs(30));
		assert_eq!(config.pong_timeout(), Duration::from_secs(10));
	}

	#[rstest]
	fn test_heartbeat_config_custom() {
		// Arrange & Act
		let config = HeartbeatConfig::new(Duration::from_secs(15), Duration::from_secs(5));

		// Assert
		assert_eq!(config.ping_interval(), Duration::from_secs(15));
		assert_eq!(config.pong_timeout(), Duration::from_secs(5));
	}

	#[rstest]
	#[tokio::test]
	async fn test_heartbeat_monitor_initial_state() {
		// Arrange
		let (tx, _rx) = mpsc::unbounded_channel();
		let conn = Arc::new(WebSocketConnection::new("hb_test".to_string(), tx));
		let config = HeartbeatConfig::default();

		// Act
		let monitor = HeartbeatMonitor::new(conn, config);

		// Assert
		assert!(!monitor.is_timed_out().await);
		assert!(monitor.time_since_last_pong().await < Duration::from_secs(1));
	}

	#[rstest]
	#[tokio::test]
	async fn test_heartbeat_monitor_record_pong_resets_timer() {
		// Arrange
		let (tx, _rx) = mpsc::unbounded_channel();
		let conn = Arc::new(WebSocketConnection::new("hb_pong".to_string(), tx));
		let config = HeartbeatConfig::new(Duration::from_millis(50), Duration::from_millis(30));
		let monitor = HeartbeatMonitor::new(conn, config);

		// Act - wait then record pong
		tokio::time::sleep(Duration::from_millis(20)).await;
		monitor.record_pong().await;

		// Assert
		assert!(monitor.time_since_last_pong().await < Duration::from_millis(10));
	}

	#[rstest]
	#[tokio::test]
	async fn test_heartbeat_monitor_timeout_closes_connection() {
		// Arrange
		let (tx, _rx) = mpsc::unbounded_channel();
		let conn = Arc::new(WebSocketConnection::new("hb_timeout".to_string(), tx));
		let config = HeartbeatConfig::new(Duration::from_millis(50), Duration::from_millis(30));
		let monitor = HeartbeatMonitor::new(conn.clone(), config);

		// Act - wait past the pong timeout
		tokio::time::sleep(Duration::from_millis(40)).await;
		let timed_out = monitor.check_heartbeat().await;

		// Assert
		assert!(timed_out);
		assert!(monitor.is_timed_out().await);
		assert!(conn.is_closed().await);
	}

	#[rstest]
	#[tokio::test]
	async fn test_heartbeat_monitor_no_timeout_when_pong_received() {
		// Arrange
		let (tx, _rx) = mpsc::unbounded_channel();
		let conn = Arc::new(WebSocketConnection::new("hb_ok".to_string(), tx));
		let config = HeartbeatConfig::new(Duration::from_millis(100), Duration::from_millis(50));
		let monitor = HeartbeatMonitor::new(conn.clone(), config);

		// Act - record pong within timeout window
		tokio::time::sleep(Duration::from_millis(20)).await;
		monitor.record_pong().await;
		let timed_out = monitor.check_heartbeat().await;

		// Assert
		assert!(!timed_out);
		assert!(!monitor.is_timed_out().await);
		assert!(!conn.is_closed().await);
	}

	#[rstest]
	#[tokio::test]
	async fn test_heartbeat_monitor_send_ping() {
		// Arrange
		let (tx, mut rx) = mpsc::unbounded_channel();
		let conn = Arc::new(WebSocketConnection::new("hb_ping".to_string(), tx));
		let config = HeartbeatConfig::default();
		let monitor = HeartbeatMonitor::new(conn, config);

		// Act
		monitor.send_ping().await.unwrap();

		// Assert
		let msg = rx.recv().await.unwrap();
		assert!(matches!(msg, Message::Ping));
	}

	#[rstest]
	#[tokio::test]
	async fn test_heartbeat_monitor_early_pong_skips_full_sleep() {
		// Arrange
		let (tx, _rx) = mpsc::unbounded_channel();
		let conn = Arc::new(WebSocketConnection::new("hb_early".to_string(), tx));
		// Use a long pong_timeout to make the test obvious
		let config = HeartbeatConfig {
			ping_interval: Duration::from_secs(60),
			pong_timeout: Duration::from_secs(10),
		};
		let monitor = Arc::new(HeartbeatMonitor::new(conn, config));

		// Act: simulate pong arriving after a short delay
		let monitor_clone = Arc::clone(&monitor);
		tokio::spawn(async move {
			tokio::time::sleep(Duration::from_millis(50)).await;
			monitor_clone.record_pong().await;
		});

		// Send ping and wait for pong or timeout via select!
		let _ = monitor.send_ping().await;
		let start = Instant::now();

		tokio::select! {
			() = tokio::time::sleep(monitor.config.pong_timeout) => {
				panic!("Should not reach full timeout");
			}
			() = monitor.pong_notify.notified() => {
				// Pong received early
			}
		}

		// Assert: should complete well before the 10s pong_timeout
		let elapsed = start.elapsed();
		assert!(
			elapsed < Duration::from_secs(2),
			"Expected early wakeup but elapsed {:?}",
			elapsed
		);
	}

	#[rstest]
	fn test_websocket_error_binary_payload_variant() {
		// Arrange & Act
		let err = WebSocketError::BinaryPayload("invalid data".to_string());

		// Assert
		assert_eq!(err.to_string(), "Invalid binary payload: invalid data");
	}

	#[rstest]
	fn test_websocket_error_heartbeat_timeout_variant() {
		// Arrange & Act
		let err = WebSocketError::HeartbeatTimeout(Duration::from_secs(10));

		// Assert
		assert_eq!(
			err.to_string(),
			"Heartbeat timeout: no pong received within 10s"
		);
	}

	#[rstest]
	fn test_websocket_error_slow_consumer_variant() {
		// Arrange & Act
		let err = WebSocketError::SlowConsumer(Duration::from_secs(5));

		// Assert
		assert_eq!(err.to_string(), "Slow consumer: send timed out after 5s");
	}
}