toolkit-zero 5.11.0

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

use std::{
    future::Future,
    net::SocketAddr,
    pin::Pin,
    sync::Arc,
};
use serde::{de::DeserializeOwned, Serialize};

pub use super::SerializationKey;
pub use toolkit_zero_macros::mechanism;

// ─── Internal future / handler types ─────────────────────────────────────────

type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send + 'static>>;
type HandlerFn = Arc<dyn Fn(IncomingRequest) -> BoxFuture<http::Response<bytes::Bytes>> + Send + Sync>;

/// Raw data extracted from an incoming HTTP request, passed to every route handler.
pub(crate) struct IncomingRequest {
    /// Raw body bytes (empty for GET / HEAD / etc.).
    body: bytes::Bytes,
    /// Raw query string — everything after `?`; empty string when absent.
    query: String,
    /// Request headers.
    #[allow(dead_code)]
    headers: http::HeaderMap,
}

// ─── Rejection ────────────────────────────────────────────────────────────────

/// An HTTP-level error value returned from route handlers.
///
/// Returning `Err(rejection)` from an `onconnect` closure sends the corresponding
/// HTTP status code with an empty body to the client.
///
/// The most common source is [`forbidden()`] (produces `403 Forbidden`).
pub struct Rejection {
    status: http::StatusCode,
}

impl Rejection {
    fn new(status: http::StatusCode) -> Self {
        Self { status }
    }

    /// Builds a `403 Forbidden` rejection.
    pub fn forbidden() -> Self {
        Self::new(http::StatusCode::FORBIDDEN)
    }

    /// Builds a `400 Bad Request` rejection.
    pub fn bad_request() -> Self {
        Self::new(http::StatusCode::BAD_REQUEST)
    }

    /// Builds a `500 Internal Server Error` rejection.
    pub fn internal() -> Self {
        Self::new(http::StatusCode::INTERNAL_SERVER_ERROR)
    }

    fn into_response(self) -> http::Response<bytes::Bytes> {
        http::Response::builder()
            .status(self.status)
            .body(bytes::Bytes::new())
            .unwrap()
    }
}

// ─── Reply ────────────────────────────────────────────────────────────────────

/// A value that can be converted into a fully-formed HTTP response.
///
/// Implemented for all types returned by the [`reply!`] macro and the standalone
/// reply helpers.  You may also implement it for your own types.
pub trait Reply: Send {
    /// Consumes `self` and returns a complete HTTP response.
    fn into_response(self) -> http::Response<bytes::Bytes>;
}

/// An empty `200 OK` reply — returned by `reply!()`.
pub struct EmptyReply;

impl Reply for EmptyReply {
    fn into_response(self) -> http::Response<bytes::Bytes> {
        http::Response::builder()
            .status(http::StatusCode::OK)
            .body(bytes::Bytes::new())
            .unwrap()
    }
}

/// An HTML body reply — returned by [`html_reply`].
pub struct HtmlReply {
    body: String,
}

impl Reply for HtmlReply {
    fn into_response(self) -> http::Response<bytes::Bytes> {
        http::Response::builder()
            .status(http::StatusCode::OK)
            .header(http::header::CONTENT_TYPE, "text/html; charset=utf-8")
            .body(bytes::Bytes::from(self.body.into_bytes()))
            .unwrap()
    }
}

/// Wraps `content` into a `200 OK` HTML response.
pub fn html_reply(content: impl Into<String>) -> HtmlReply {
    HtmlReply { body: content.into() }
}

// Internal JSON reply — used by reply_with_json / reply_with_status_and_json.
struct JsonReply {
    body: bytes::Bytes,
    status: http::StatusCode,
}

impl Reply for JsonReply {
    fn into_response(self) -> http::Response<bytes::Bytes> {
        http::Response::builder()
            .status(self.status)
            .header(http::header::CONTENT_TYPE, "application/json")
            .body(self.body)
            .unwrap()
    }
}

// Passthrough — allows `http::Response<bytes::Bytes>` to satisfy the Reply bound directly.
impl Reply for http::Response<bytes::Bytes> {
    fn into_response(self) -> http::Response<bytes::Bytes> {
        self
    }
}

// ─── SocketType ───────────────────────────────────────────────────────────────

/// A fully assembled, type-erased HTTP route ready to be registered on a [`Server`].
///
/// This is the final product of every builder chain.  Pass it to [`Server::mechanism`]
/// to mount it.  Internally stores the HTTP method, the path pattern, and a
/// reference-counted async handler closure — cloning a `SocketType` is cheap
/// (just an `Arc` clone of the handler).
pub struct SocketType {
    pub(crate) method: http::Method,
    pub(crate) path:   String,
    pub(crate) handler: HandlerFn,
}

impl Clone for SocketType {
    fn clone(&self) -> Self {
        Self {
            method:  self.method.clone(),
            path:    self.path.clone(),
            handler: Arc::clone(&self.handler),
        }
    }
}

// ─── HttpMethod ───────────────────────────────────────────────────────────────

#[derive(Clone, Copy, Debug)]
enum HttpMethod {
    Get, Post, Put, Delete, Patch, Head, Options,
}

impl HttpMethod {
    fn to_http(self) -> http::Method {
        match self {
            HttpMethod::Get     => http::Method::GET,
            HttpMethod::Post    => http::Method::POST,
            HttpMethod::Put     => http::Method::PUT,
            HttpMethod::Delete  => http::Method::DELETE,
            HttpMethod::Patch   => http::Method::PATCH,
            HttpMethod::Head    => http::Method::HEAD,
            HttpMethod::Options => http::Method::OPTIONS,
        }
    }
}

// ─── Path matching ────────────────────────────────────────────────────────────

fn path_matches(pattern: &str, actual_path: &str) -> bool {
    let pat: Vec<&str> = pattern
        .trim_matches('/')
        .split('/')
        .filter(|s| !s.is_empty())
        .collect();
    let act: Vec<&str> = actual_path
        .trim_matches('/')
        .split('/')
        .filter(|s| !s.is_empty())
        .collect();
    pat == act
}

// ─── ServerMechanism ──────────────────────────────────────────────────────────

/// Entry point for building an HTTP route.
///
/// Pairs an HTTP method with a URL path and acts as the root of a fluent builder chain.
/// Optionally attach shared state, a JSON body expectation, or URL query parameter
/// deserialisation — then finalise with [`onconnect`](ServerMechanism::onconnect) (async)
/// or [`onconnect_sync`](ServerMechanism::onconnect_sync) (sync) to produce a
/// [`SocketType`] ready to be mounted on a [`Server`].
///
/// # Example
/// ```rust,no_run
/// # use toolkit_zero::socket::server::{ServerMechanism, Status};
/// # use toolkit_zero::socket::server::reply;
/// # use serde::{Deserialize, Serialize};
/// # use std::sync::{Arc, Mutex};
/// # #[derive(Deserialize, Serialize)] struct Item { id: u32, name: String }
/// # #[derive(Deserialize)] struct CreateItem { name: String }
/// # #[derive(Deserialize)] struct SearchQuery { q: String }
///
/// // Plain GET — no body, no state
/// let health = ServerMechanism::get("/health")
///     .onconnect(|| async { reply!() });
///
/// // POST — JSON body deserialised into `CreateItem`
/// let create = ServerMechanism::post("/items")
///     .json::<CreateItem>()
///     .onconnect(|body| async move {
///         let item = Item { id: 1, name: body.name };
///         reply!(json => item, status => Status::Created)
///     });
///
/// // GET — shared counter state injected on every request
/// let counter: Arc<Mutex<u64>> = Arc::new(Mutex::new(0));
/// let count_route = ServerMechanism::get("/count")
///     .state(counter.clone())
///     .onconnect(|state| async move {
///         let n = *state.lock().unwrap();
///         reply!(json => n)
///     });
/// ```
pub struct ServerMechanism {
    method: HttpMethod,
    path: String,
}

impl ServerMechanism {
    fn instance(method: HttpMethod, path: impl Into<String>) -> Self {
        let path = path.into();
        log::debug!("Creating {:?} route at '{}'", method, path);
        Self { method, path }
    }

    /// Creates a route matching HTTP `GET` requests at `path`.
    pub fn get(path: impl Into<String>) -> Self { Self::instance(HttpMethod::Get, path) }

    /// Creates a route matching HTTP `POST` requests at `path`.
    pub fn post(path: impl Into<String>) -> Self { Self::instance(HttpMethod::Post, path) }

    /// Creates a route matching HTTP `PUT` requests at `path`.
    pub fn put(path: impl Into<String>) -> Self { Self::instance(HttpMethod::Put, path) }

    /// Creates a route matching HTTP `DELETE` requests at `path`.
    pub fn delete(path: impl Into<String>) -> Self { Self::instance(HttpMethod::Delete, path) }

    /// Creates a route matching HTTP `PATCH` requests at `path`.
    pub fn patch(path: impl Into<String>) -> Self { Self::instance(HttpMethod::Patch, path) }

    /// Creates a route matching HTTP `HEAD` requests at `path`.
    pub fn head(path: impl Into<String>) -> Self { Self::instance(HttpMethod::Head, path) }

    /// Creates a route matching HTTP `OPTIONS` requests at `path`.
    pub fn options(path: impl Into<String>) -> Self { Self::instance(HttpMethod::Options, path) }

    /// Attaches shared state `S` to this route, transitioning to [`StatefulSocketBuilder`].
    ///
    /// A fresh clone of `S` is injected into the handler on every request.
    pub fn state<S: Clone + Send + Sync + 'static>(self, state: S) -> StatefulSocketBuilder<S> {
        log::trace!("Attaching state to {:?} route at '{}'", self.method, self.path);
        StatefulSocketBuilder { base: self, state }
    }

    /// Declares that this route expects a JSON-encoded request body, transitioning to
    /// [`JsonSocketBuilder`].
    pub fn json<T: DeserializeOwned + Send>(self) -> JsonSocketBuilder<T> {
        log::trace!("Attaching JSON body expectation to {:?} route at '{}'", self.method, self.path);
        JsonSocketBuilder { base: self, _phantom: std::marker::PhantomData }
    }

    /// Declares that this route extracts its input from URL query parameters, transitioning
    /// to [`QuerySocketBuilder`].
    pub fn query<T: DeserializeOwned + Send>(self) -> QuerySocketBuilder<T> {
        log::trace!("Attaching query parameter expectation to {:?} route at '{}'", self.method, self.path);
        QuerySocketBuilder { base: self, _phantom: std::marker::PhantomData }
    }

    /// Declares that this route expects an authenticated-encrypted request body
    /// (ChaCha20-Poly1305), transitioning to [`EncryptedBodyBuilder`].
    pub fn encryption<T>(self, key: SerializationKey) -> EncryptedBodyBuilder<T> {
        log::trace!("Attaching encrypted body to {:?} route at '{}'", self.method, self.path);
        EncryptedBodyBuilder { base: self, key, _phantom: std::marker::PhantomData }
    }

    /// Declares that this route expects authenticated-encrypted URL query parameters
    /// (ChaCha20-Poly1305), transitioning to [`EncryptedQueryBuilder`].
    pub fn encrypted_query<T>(self, key: SerializationKey) -> EncryptedQueryBuilder<T> {
        log::trace!("Attaching encrypted query to {:?} route at '{}'", self.method, self.path);
        EncryptedQueryBuilder { base: self, key, _phantom: std::marker::PhantomData }
    }

    /// Finalises this route with an async handler that receives no arguments.
    ///
    /// Returns a [`SocketType`] ready to be passed to [`Server::mechanism`].
    ///
    /// # Example
    /// ```rust,no_run
    /// # use toolkit_zero::socket::server::ServerMechanism;
    /// # use toolkit_zero::socket::server::reply;
    /// # use serde::Serialize;
    /// # #[derive(Serialize)] struct Pong { ok: bool }
    ///
    /// let route = ServerMechanism::get("/ping")
    ///     .onconnect(|| async {
    ///         reply!(json => Pong { ok: true })
    ///     });
    /// ```
    pub fn onconnect<F, Fut, Re>(self, handler: F) -> SocketType
    where
        F: Fn() -> Fut + Clone + Send + Sync + 'static,
        Fut: Future<Output = Result<Re, Rejection>> + Send,
        Re: Reply + Send,
    {
        log::debug!("Finalising async {:?} route at '{}' (no args)", self.method, self.path);
        let method = self.method.to_http();
        let path   = self.path.clone();
        SocketType {
            method,
            path,
            handler: Arc::new(move |_req: IncomingRequest| {
                let h = handler.clone();
                Box::pin(async move {
                    match h().await {
                        Ok(r)  => r.into_response(),
                        Err(e) => e.into_response(),
                    }
                })
            }),
        }
    }

    /// Finalises this route with a **synchronous** handler that receives no arguments.
    ///
    /// # Safety
    ///
    /// Every incoming request spawns an independent task on Tokio's blocking thread pool.
    /// The pool caps the number of live OS threads (default 512), but the queue of waiting
    /// tasks is unbounded — under a traffic surge, tasks accumulate without limit, consuming
    /// unbounded memory and causing severe latency spikes or OOM crashes. Additionally, any
    /// panic inside the handler is silently converted into a 500 response, masking runtime
    /// errors. Callers must ensure the handler completes quickly and that adequate
    /// backpressure or rate limiting is applied externally.
    pub unsafe fn onconnect_sync<F, Re>(self, handler: F) -> SocketType
    where
        F: Fn() -> Result<Re, Rejection> + Clone + Send + Sync + 'static,
        Re: Reply + Send + 'static,
    {
        log::warn!(
            "Registering sync handler on {:?} '{}' — ensure rate-limiting is applied externally",
            self.method, self.path
        );
        let method = self.method.to_http();
        let path   = self.path.clone();
        SocketType {
            method,
            path,
            handler: Arc::new(move |_req: IncomingRequest| {
                let h = handler.clone();
                Box::pin(async move {
                    match tokio::task::spawn_blocking(move || h()).await {
                        Ok(Ok(r))  => r.into_response(),
                        Ok(Err(e)) => e.into_response(),
                        Err(_) => {
                            log::warn!("Sync handler panicked; returning 500");
                            Rejection::internal().into_response()
                        }
                    }
                })
            }),
        }
    }
}

// ─── JsonSocketBuilder ────────────────────────────────────────────────────────

/// Route builder that expects and deserialises a JSON request body of type `T`.
///
/// Obtained from [`ServerMechanism::json`]. Optionally attach shared state via
/// [`state`](JsonSocketBuilder::state), or finalise immediately with
/// [`onconnect`](JsonSocketBuilder::onconnect) /
/// [`onconnect_sync`](JsonSocketBuilder::onconnect_sync).
pub struct JsonSocketBuilder<T> {
    base: ServerMechanism,
    _phantom: std::marker::PhantomData<T>,
}

impl<T: DeserializeOwned + Send + 'static> JsonSocketBuilder<T> {
    /// Finalises this route with an async handler that receives the deserialised JSON body.
    pub fn onconnect<F, Fut, Re>(self, handler: F) -> SocketType
    where
        F: Fn(T) -> Fut + Clone + Send + Sync + 'static,
        Fut: Future<Output = Result<Re, Rejection>> + Send,
        Re: Reply + Send,
    {
        log::debug!(
            "Finalising async {:?} route at '{}' (JSON body)",
            self.base.method, self.base.path
        );
        let method = self.base.method.to_http();
        let path   = self.base.path.clone();
        SocketType {
            method,
            path,
            handler: Arc::new(move |req: IncomingRequest| {
                let h = handler.clone();
                Box::pin(async move {
                    let body: T = match serde_json::from_slice(&req.body) {
                        Ok(v)  => v,
                        Err(e) => {
                            log::debug!("JSON body parse failed: {}", e);
                            return Rejection::bad_request().into_response();
                        }
                    };
                    match h(body).await {
                        Ok(r)  => r.into_response(),
                        Err(e) => e.into_response(),
                    }
                })
            }),
        }
    }

    /// Finalises this route with a **synchronous** handler that receives the deserialised
    /// JSON body.
    ///
    /// # Safety
    /// See [`ServerMechanism::onconnect_sync`] for the thread-pool safety notes.
    pub unsafe fn onconnect_sync<F, Re>(self, handler: F) -> SocketType
    where
        F: Fn(T) -> Result<Re, Rejection> + Clone + Send + Sync + 'static,
        Re: Reply + Send + 'static,
    {
        log::warn!(
            "Registering sync handler on {:?} '{}' (JSON body) — ensure rate-limiting is applied externally",
            self.base.method, self.base.path
        );
        let method = self.base.method.to_http();
        let path   = self.base.path.clone();
        SocketType {
            method,
            path,
            handler: Arc::new(move |req: IncomingRequest| {
                let h = handler.clone();
                Box::pin(async move {
                    let body: T = match serde_json::from_slice(&req.body) {
                        Ok(v)  => v,
                        Err(e) => {
                            log::debug!("JSON body parse failed (sync): {}", e);
                            return Rejection::bad_request().into_response();
                        }
                    };
                    match tokio::task::spawn_blocking(move || h(body)).await {
                        Ok(Ok(r))  => r.into_response(),
                        Ok(Err(e)) => e.into_response(),
                        Err(_) => {
                            log::warn!("Sync handler (JSON body) panicked; returning 500");
                            Rejection::internal().into_response()
                        }
                    }
                })
            }),
        }
    }

    /// Attaches shared state `S`, transitioning to [`StatefulJsonSocketBuilder`].
    pub fn state<S: Clone + Send + Sync + 'static>(
        self, state: S,
    ) -> StatefulJsonSocketBuilder<T, S> {
        StatefulJsonSocketBuilder {
            base: self.base,
            state,
            _phantom: std::marker::PhantomData,
        }
    }
}

// ─── QuerySocketBuilder ───────────────────────────────────────────────────────

/// Route builder that expects and deserialises URL query parameters of type `T`.
///
/// Obtained from [`ServerMechanism::query`]. Optionally attach shared state via
/// [`state`](QuerySocketBuilder::state), or finalise immediately with
/// [`onconnect`](QuerySocketBuilder::onconnect) /
/// [`onconnect_sync`](QuerySocketBuilder::onconnect_sync).
pub struct QuerySocketBuilder<T> {
    base: ServerMechanism,
    _phantom: std::marker::PhantomData<T>,
}

impl<T: DeserializeOwned + Send + 'static> QuerySocketBuilder<T> {
    /// Finalises this route with an async handler that receives the deserialised query
    /// parameters.
    pub fn onconnect<F, Fut, Re>(self, handler: F) -> SocketType
    where
        F: Fn(T) -> Fut + Clone + Send + Sync + 'static,
        Fut: Future<Output = Result<Re, Rejection>> + Send,
        Re: Reply + Send,
    {
        log::debug!(
            "Finalising async {:?} route at '{}' (query params)",
            self.base.method, self.base.path
        );
        let method = self.base.method.to_http();
        let path   = self.base.path.clone();
        SocketType {
            method,
            path,
            handler: Arc::new(move |req: IncomingRequest| {
                let h = handler.clone();
                Box::pin(async move {
                    let params: T = match serde_urlencoded::from_str(&req.query) {
                        Ok(v)  => v,
                        Err(e) => {
                            log::debug!("query param parse failed: {}", e);
                            return Rejection::bad_request().into_response();
                        }
                    };
                    match h(params).await {
                        Ok(r)  => r.into_response(),
                        Err(e) => e.into_response(),
                    }
                })
            }),
        }
    }

    /// Finalises this route with a **synchronous** handler that receives the deserialised
    /// query parameters.
    ///
    /// # Safety
    /// See [`ServerMechanism::onconnect_sync`] for the thread-pool safety notes.
    pub unsafe fn onconnect_sync<F, Re>(self, handler: F) -> SocketType
    where
        F: Fn(T) -> Result<Re, Rejection> + Clone + Send + Sync + 'static,
        Re: Reply + Send + 'static,
    {
        log::warn!(
            "Registering sync handler on {:?} '{}' (query params) — ensure rate-limiting is applied externally",
            self.base.method, self.base.path
        );
        let method = self.base.method.to_http();
        let path   = self.base.path.clone();
        SocketType {
            method,
            path,
            handler: Arc::new(move |req: IncomingRequest| {
                let h = handler.clone();
                Box::pin(async move {
                    let params: T = match serde_urlencoded::from_str(&req.query) {
                        Ok(v)  => v,
                        Err(e) => {
                            log::debug!("query param parse failed (sync): {}", e);
                            return Rejection::bad_request().into_response();
                        }
                    };
                    match tokio::task::spawn_blocking(move || h(params)).await {
                        Ok(Ok(r))  => r.into_response(),
                        Ok(Err(e)) => e.into_response(),
                        Err(_) => {
                            log::warn!("Sync handler (query params) panicked; returning 500");
                            Rejection::internal().into_response()
                        }
                    }
                })
            }),
        }
    }

    /// Attaches shared state `S`, transitioning to [`StatefulQuerySocketBuilder`].
    pub fn state<S: Clone + Send + Sync + 'static>(
        self, state: S,
    ) -> StatefulQuerySocketBuilder<T, S> {
        StatefulQuerySocketBuilder {
            base: self.base,
            state,
            _phantom: std::marker::PhantomData,
        }
    }
}

// ─── StatefulSocketBuilder ────────────────────────────────────────────────────

/// Route builder that carries shared state `S` with no body or query expectation.
///
/// Obtained from [`ServerMechanism::state`]. `S` must be `Clone + Send + Sync + 'static`.
pub struct StatefulSocketBuilder<S> {
    base: ServerMechanism,
    state: S,
}

impl<S: Clone + Send + Sync + 'static> StatefulSocketBuilder<S> {
    /// Adds a JSON body expectation, transitioning to [`StatefulJsonSocketBuilder`].
    pub fn json<T: DeserializeOwned + Send>(self) -> StatefulJsonSocketBuilder<T, S> {
        StatefulJsonSocketBuilder {
            base: self.base,
            state: self.state,
            _phantom: std::marker::PhantomData,
        }
    }

    /// Adds a query parameter expectation, transitioning to [`StatefulQuerySocketBuilder`].
    pub fn query<T: DeserializeOwned + Send>(self) -> StatefulQuerySocketBuilder<T, S> {
        StatefulQuerySocketBuilder {
            base: self.base,
            state: self.state,
            _phantom: std::marker::PhantomData,
        }
    }

    /// Adds an encrypted body expectation, transitioning to [`StatefulEncryptedBodyBuilder`].
    pub fn encryption<T>(self, key: SerializationKey) -> StatefulEncryptedBodyBuilder<T, S> {
        StatefulEncryptedBodyBuilder {
            base: self.base,
            key,
            state: self.state,
            _phantom: std::marker::PhantomData,
        }
    }

    /// Adds an encrypted query expectation, transitioning to [`StatefulEncryptedQueryBuilder`].
    pub fn encrypted_query<T>(self, key: SerializationKey) -> StatefulEncryptedQueryBuilder<T, S> {
        StatefulEncryptedQueryBuilder {
            base: self.base,
            key,
            state: self.state,
            _phantom: std::marker::PhantomData,
        }
    }

    /// Finalises this route with an async handler that receives only the shared state.
    pub fn onconnect<F, Fut, Re>(self, handler: F) -> SocketType
    where
        F: Fn(S) -> Fut + Clone + Send + Sync + 'static,
        Fut: Future<Output = Result<Re, Rejection>> + Send,
        Re: Reply + Send,
    {
        log::debug!(
            "Finalising async {:?} route at '{}' (state)",
            self.base.method, self.base.path
        );
        let method = self.base.method.to_http();
        let path   = self.base.path.clone();
        let state  = self.state;
        SocketType {
            method,
            path,
            handler: Arc::new(move |_req: IncomingRequest| {
                let h = handler.clone();
                let s = state.clone();
                Box::pin(async move {
                    match h(s).await {
                        Ok(r)  => r.into_response(),
                        Err(e) => e.into_response(),
                    }
                })
            }),
        }
    }

    /// Finalises this route with a **synchronous** handler that receives only the shared
    /// state.
    ///
    /// # Safety
    /// See [`ServerMechanism::onconnect_sync`] for the thread-pool safety notes.
    pub unsafe fn onconnect_sync<F, Re>(self, handler: F) -> SocketType
    where
        F: Fn(S) -> Result<Re, Rejection> + Clone + Send + Sync + 'static,
        Re: Reply + Send + 'static,
    {
        log::warn!(
            "Registering sync handler on {:?} '{}' (state) — ensure rate-limiting and lock-free state are in place",
            self.base.method, self.base.path
        );
        let method = self.base.method.to_http();
        let path   = self.base.path.clone();
        let state  = self.state;
        SocketType {
            method,
            path,
            handler: Arc::new(move |_req: IncomingRequest| {
                let h = handler.clone();
                let s = state.clone();
                Box::pin(async move {
                    match tokio::task::spawn_blocking(move || h(s)).await {
                        Ok(Ok(r))  => r.into_response(),
                        Ok(Err(e)) => e.into_response(),
                        Err(_) => {
                            log::warn!("Sync handler (state) panicked; returning 500");
                            Rejection::internal().into_response()
                        }
                    }
                })
            }),
        }
    }
}

// ─── StatefulJsonSocketBuilder ────────────────────────────────────────────────

/// Route builder that carries shared state `S` and expects a JSON body of type `T`.
///
/// Obtained from [`JsonSocketBuilder::state`] or [`StatefulSocketBuilder::json`].
pub struct StatefulJsonSocketBuilder<T, S> {
    base:     ServerMechanism,
    state:    S,
    _phantom: std::marker::PhantomData<T>,
}

impl<T: DeserializeOwned + Send + 'static, S: Clone + Send + Sync + 'static>
    StatefulJsonSocketBuilder<T, S>
{
    /// Finalises this route with an async handler that receives `(state: S, body: T)`.
    pub fn onconnect<F, Fut, Re>(self, handler: F) -> SocketType
    where
        F: Fn(S, T) -> Fut + Clone + Send + Sync + 'static,
        Fut: Future<Output = Result<Re, Rejection>> + Send,
        Re: Reply + Send,
    {
        log::debug!(
            "Finalising async {:?} route at '{}' (state + JSON body)",
            self.base.method, self.base.path
        );
        let method = self.base.method.to_http();
        let path   = self.base.path.clone();
        let state  = self.state;
        SocketType {
            method,
            path,
            handler: Arc::new(move |req: IncomingRequest| {
                let h = handler.clone();
                let s = state.clone();
                Box::pin(async move {
                    let body: T = match serde_json::from_slice(&req.body) {
                        Ok(v)  => v,
                        Err(e) => {
                            log::debug!("JSON body parse failed (state): {}", e);
                            return Rejection::bad_request().into_response();
                        }
                    };
                    match h(s, body).await {
                        Ok(r)  => r.into_response(),
                        Err(e) => e.into_response(),
                    }
                })
            }),
        }
    }

    /// Finalises this route with a **synchronous** handler that receives `(state: S, body: T)`.
    ///
    /// # Safety
    /// See [`ServerMechanism::onconnect_sync`] for the thread-pool safety notes.
    pub unsafe fn onconnect_sync<F, Re>(self, handler: F) -> SocketType
    where
        F: Fn(S, T) -> Result<Re, Rejection> + Clone + Send + Sync + 'static,
        Re: Reply + Send + 'static,
    {
        log::warn!(
            "Registering sync handler on {:?} '{}' (state + JSON body) — ensure rate-limiting and lock-free state are in place",
            self.base.method, self.base.path
        );
        let method = self.base.method.to_http();
        let path   = self.base.path.clone();
        let state  = self.state;
        SocketType {
            method,
            path,
            handler: Arc::new(move |req: IncomingRequest| {
                let h = handler.clone();
                let s = state.clone();
                Box::pin(async move {
                    let body: T = match serde_json::from_slice(&req.body) {
                        Ok(v)  => v,
                        Err(e) => {
                            log::debug!("JSON body parse failed (state+sync): {}", e);
                            return Rejection::bad_request().into_response();
                        }
                    };
                    match tokio::task::spawn_blocking(move || h(s, body)).await {
                        Ok(Ok(r))  => r.into_response(),
                        Ok(Err(e)) => e.into_response(),
                        Err(_) => {
                            log::warn!("Sync handler (state + JSON body) panicked; returning 500");
                            Rejection::internal().into_response()
                        }
                    }
                })
            }),
        }
    }
}

// ─── StatefulQuerySocketBuilder ───────────────────────────────────────────────

/// Route builder that carries shared state `S` and expects URL query parameters of type `T`.
///
/// Obtained from [`QuerySocketBuilder::state`] or [`StatefulSocketBuilder::query`].
pub struct StatefulQuerySocketBuilder<T, S> {
    base:     ServerMechanism,
    state:    S,
    _phantom: std::marker::PhantomData<T>,
}

impl<T: DeserializeOwned + Send + 'static, S: Clone + Send + Sync + 'static>
    StatefulQuerySocketBuilder<T, S>
{
    /// Finalises this route with an async handler that receives `(state: S, query: T)`.
    pub fn onconnect<F, Fut, Re>(self, handler: F) -> SocketType
    where
        F: Fn(S, T) -> Fut + Clone + Send + Sync + 'static,
        Fut: Future<Output = Result<Re, Rejection>> + Send,
        Re: Reply + Send,
    {
        log::debug!(
            "Finalising async {:?} route at '{}' (state + query params)",
            self.base.method, self.base.path
        );
        let method = self.base.method.to_http();
        let path   = self.base.path.clone();
        let state  = self.state;
        SocketType {
            method,
            path,
            handler: Arc::new(move |req: IncomingRequest| {
                let h = handler.clone();
                let s = state.clone();
                Box::pin(async move {
                    let params: T = match serde_urlencoded::from_str(&req.query) {
                        Ok(v)  => v,
                        Err(e) => {
                            log::debug!("query param parse failed (state): {}", e);
                            return Rejection::bad_request().into_response();
                        }
                    };
                    match h(s, params).await {
                        Ok(r)  => r.into_response(),
                        Err(e) => e.into_response(),
                    }
                })
            }),
        }
    }

    /// Finalises this route with a **synchronous** handler that receives `(state: S, query: T)`.
    ///
    /// # Safety
    /// See [`ServerMechanism::onconnect_sync`] for the thread-pool safety notes.
    pub unsafe fn onconnect_sync<F, Re>(self, handler: F) -> SocketType
    where
        F: Fn(S, T) -> Result<Re, Rejection> + Clone + Send + Sync + 'static,
        Re: Reply + Send + 'static,
    {
        log::warn!(
            "Registering sync handler on {:?} '{}' (state + query params) — ensure rate-limiting and lock-free state are in place",
            self.base.method, self.base.path
        );
        let method = self.base.method.to_http();
        let path   = self.base.path.clone();
        let state  = self.state;
        SocketType {
            method,
            path,
            handler: Arc::new(move |req: IncomingRequest| {
                let h = handler.clone();
                let s = state.clone();
                Box::pin(async move {
                    let params: T = match serde_urlencoded::from_str(&req.query) {
                        Ok(v)  => v,
                        Err(e) => {
                            log::debug!("query param parse failed (state+sync): {}", e);
                            return Rejection::bad_request().into_response();
                        }
                    };
                    match tokio::task::spawn_blocking(move || h(s, params)).await {
                        Ok(Ok(r))  => r.into_response(),
                        Ok(Err(e)) => e.into_response(),
                        Err(_) => {
                            log::warn!("Sync handler (state + query params) panicked; returning 500");
                            Rejection::internal().into_response()
                        }
                    }
                })
            }),
        }
    }
}

// ─── EncryptedBodyBuilder ────────────────────────────────────────────────────

/// Route builder that expects an authenticated-encrypted request body of type `T`
/// (ChaCha20-Poly1305).
///
/// Obtained from [`ServerMechanism::encryption`].  On each matching request the raw
/// body bytes are decrypted using the [`SerializationKey`] supplied there.  If
/// decryption fails the route immediately returns `403 Forbidden`.
///
/// Optionally attach shared state via [`state`](EncryptedBodyBuilder::state) before
/// finalising with [`onconnect`](EncryptedBodyBuilder::onconnect) /
/// [`onconnect_sync`](EncryptedBodyBuilder::onconnect_sync).
pub struct EncryptedBodyBuilder<T> {
    base:     ServerMechanism,
    key:      SerializationKey,
    _phantom: std::marker::PhantomData<T>,
}

impl<T> EncryptedBodyBuilder<T>
where
    T: bincode::Decode<()> + Send + 'static,
{
    /// Finalises this route with an async handler that receives the decrypted body as `T`.
    pub fn onconnect<F, Fut, Re>(self, handler: F) -> SocketType
    where
        F: Fn(T) -> Fut + Clone + Send + Sync + 'static,
        Fut: Future<Output = Result<Re, Rejection>> + Send,
        Re: Reply + Send,
    {
        log::debug!(
            "Finalising async {:?} route at '{}' (encrypted body)",
            self.base.method, self.base.path
        );
        let method = self.base.method.to_http();
        let path   = self.base.path.clone();
        let key    = self.key;
        SocketType {
            method,
            path,
            handler: Arc::new(move |req: IncomingRequest| {
                let h   = handler.clone();
                let key = key.clone();
                Box::pin(async move {
                    let value: T = match decode_body(&req.body, &key) {
                        Ok(v)  => v,
                        Err(e) => return e.into_response(),
                    };
                    match h(value).await {
                        Ok(r)  => r.into_response(),
                        Err(e) => e.into_response(),
                    }
                })
            }),
        }
    }

    /// Finalises this route with a **synchronous** handler that receives the decrypted
    /// body as `T`.
    ///
    /// # Safety
    /// See [`ServerMechanism::onconnect_sync`] for the thread-pool safety notes.
    pub unsafe fn onconnect_sync<F, Re>(self, handler: F) -> SocketType
    where
        F: Fn(T) -> Result<Re, Rejection> + Clone + Send + Sync + 'static,
        Re: Reply + Send + 'static,
    {
        log::warn!(
            "Registering sync handler on {:?} '{}' (encrypted body) — ensure rate-limiting is applied externally",
            self.base.method, self.base.path
        );
        let method = self.base.method.to_http();
        let path   = self.base.path.clone();
        let key    = self.key;
        SocketType {
            method,
            path,
            handler: Arc::new(move |req: IncomingRequest| {
                let h   = handler.clone();
                let key = key.clone();
                Box::pin(async move {
                    let value: T = match decode_body(&req.body, &key) {
                        Ok(v)  => v,
                        Err(e) => return e.into_response(),
                    };
                    match tokio::task::spawn_blocking(move || h(value)).await {
                        Ok(Ok(r))  => r.into_response(),
                        Ok(Err(e)) => e.into_response(),
                        Err(_) => {
                            log::warn!("Sync encrypted handler panicked; returning 500");
                            Rejection::internal().into_response()
                        }
                    }
                })
            }),
        }
    }

    /// Attaches shared state `S`, transitioning to [`StatefulEncryptedBodyBuilder`].
    pub fn state<S: Clone + Send + Sync + 'static>(
        self, state: S,
    ) -> StatefulEncryptedBodyBuilder<T, S> {
        StatefulEncryptedBodyBuilder {
            base: self.base,
            key: self.key,
            state,
            _phantom: std::marker::PhantomData,
        }
    }
}

// ─── EncryptedQueryBuilder ────────────────────────────────────────────────────

/// Route builder that expects authenticated-encrypted URL query parameters of type `T`
/// (ChaCha20-Poly1305).
///
/// Obtained from [`ServerMechanism::encrypted_query`].  The client must send a single
/// `?data=<base64url>` query parameter.  Any failure returns `403 Forbidden`.
///
/// Optionally attach shared state via [`state`](EncryptedQueryBuilder::state) before
/// finalising with [`onconnect`](EncryptedQueryBuilder::onconnect).
pub struct EncryptedQueryBuilder<T> {
    base:     ServerMechanism,
    key:      SerializationKey,
    _phantom: std::marker::PhantomData<T>,
}

impl<T> EncryptedQueryBuilder<T>
where
    T: bincode::Decode<()> + Send + 'static,
{
    /// Finalises this route with an async handler that receives the decrypted query
    /// parameters as `T`.
    pub fn onconnect<F, Fut, Re>(self, handler: F) -> SocketType
    where
        F: Fn(T) -> Fut + Clone + Send + Sync + 'static,
        Fut: Future<Output = Result<Re, Rejection>> + Send,
        Re: Reply + Send,
    {
        log::debug!(
            "Finalising async {:?} route at '{}' (encrypted query)",
            self.base.method, self.base.path
        );
        let method = self.base.method.to_http();
        let path   = self.base.path.clone();
        let key    = self.key;
        SocketType {
            method,
            path,
            handler: Arc::new(move |req: IncomingRequest| {
                let h   = handler.clone();
                let key = key.clone();
                Box::pin(async move {
                    let value: T = match decode_query(&req.query, &key) {
                        Ok(v)  => v,
                        Err(e) => return e.into_response(),
                    };
                    match h(value).await {
                        Ok(r)  => r.into_response(),
                        Err(e) => e.into_response(),
                    }
                })
            }),
        }
    }

    /// Attaches shared state `S`, transitioning to [`StatefulEncryptedQueryBuilder`].
    pub fn state<S: Clone + Send + Sync + 'static>(
        self, state: S,
    ) -> StatefulEncryptedQueryBuilder<T, S> {
        StatefulEncryptedQueryBuilder {
            base: self.base,
            key: self.key,
            state,
            _phantom: std::marker::PhantomData,
        }
    }
}

// ─── StatefulEncryptedBodyBuilder ────────────────────────────────────────────

/// Route builder carrying shared state `S` and an authenticated-encrypted request body
/// of type `T` (ChaCha20-Poly1305).
///
/// Obtained from [`EncryptedBodyBuilder::state`] or [`StatefulSocketBuilder::encryption`].
pub struct StatefulEncryptedBodyBuilder<T, S> {
    base:     ServerMechanism,
    key:      SerializationKey,
    state:    S,
    _phantom: std::marker::PhantomData<T>,
}

impl<T, S> StatefulEncryptedBodyBuilder<T, S>
where
    T: bincode::Decode<()> + Send + 'static,
    S: Clone + Send + Sync + 'static,
{
    /// Finalises this route with an async handler that receives `(state: S, body: T)`.
    pub fn onconnect<F, Fut, Re>(self, handler: F) -> SocketType
    where
        F: Fn(S, T) -> Fut + Clone + Send + Sync + 'static,
        Fut: Future<Output = Result<Re, Rejection>> + Send,
        Re: Reply + Send,
    {
        log::debug!(
            "Finalising async {:?} route at '{}' (state + encrypted body)",
            self.base.method, self.base.path
        );
        let method = self.base.method.to_http();
        let path   = self.base.path.clone();
        let key    = self.key;
        let state  = self.state;
        SocketType {
            method,
            path,
            handler: Arc::new(move |req: IncomingRequest| {
                let h   = handler.clone();
                let key = key.clone();
                let s   = state.clone();
                Box::pin(async move {
                    let value: T = match decode_body(&req.body, &key) {
                        Ok(v)  => v,
                        Err(e) => return e.into_response(),
                    };
                    match h(s, value).await {
                        Ok(r)  => r.into_response(),
                        Err(e) => e.into_response(),
                    }
                })
            }),
        }
    }
}

// ─── StatefulEncryptedQueryBuilder ───────────────────────────────────────────

/// Route builder carrying shared state `S` and authenticated-encrypted query parameters
/// of type `T` (ChaCha20-Poly1305).
///
/// Obtained from [`EncryptedQueryBuilder::state`] or
/// [`StatefulSocketBuilder::encrypted_query`].
pub struct StatefulEncryptedQueryBuilder<T, S> {
    base:     ServerMechanism,
    key:      SerializationKey,
    state:    S,
    _phantom: std::marker::PhantomData<T>,
}

impl<T, S> StatefulEncryptedQueryBuilder<T, S>
where
    T: bincode::Decode<()> + Send + 'static,
    S: Clone + Send + Sync + 'static,
{
    /// Finalises this route with an async handler that receives `(state: S, query: T)`.
    pub fn onconnect<F, Fut, Re>(self, handler: F) -> SocketType
    where
        F: Fn(S, T) -> Fut + Clone + Send + Sync + 'static,
        Fut: Future<Output = Result<Re, Rejection>> + Send,
        Re: Reply + Send,
    {
        log::debug!(
            "Finalising async {:?} route at '{}' (state + encrypted query)",
            self.base.method, self.base.path
        );
        let method = self.base.method.to_http();
        let path   = self.base.path.clone();
        let key    = self.key;
        let state  = self.state;
        SocketType {
            method,
            path,
            handler: Arc::new(move |req: IncomingRequest| {
                let h   = handler.clone();
                let key = key.clone();
                let s   = state.clone();
                Box::pin(async move {
                    let value: T = match decode_query(&req.query, &key) {
                        Ok(v)  => v,
                        Err(e) => return e.into_response(),
                    };
                    match h(s, value).await {
                        Ok(r)  => r.into_response(),
                        Err(e) => e.into_response(),
                    }
                })
            }),
        }
    }
}

// ─── Internal decode helpers ─────────────────────────────────────────────────

/// Decrypt an authenticated-encrypted request body into `T`, returning 403 on failure.
fn decode_body<T: bincode::Decode<()>>(
    raw: &bytes::Bytes,
    key: &SerializationKey,
) -> Result<T, Rejection> {
    crate::serialization::open(raw, key.veil_key()).map_err(|e| {
        log::debug!("body decryption failed (key mismatch or corrupt body): {}", e);
        Rejection::forbidden()
    })
}

/// Decrypt an authenticated-encrypted `?data=<base64url>` query into `T`, returning 403 on failure.
fn decode_query<T: bincode::Decode<()>>(
    raw_query: &str,
    key: &SerializationKey,
) -> Result<T, Rejection> {
    use base64::Engine;

    #[derive(serde::Deserialize)]
    struct DataParam { data: String }

    let q: DataParam = serde_urlencoded::from_str(raw_query).map_err(|_| {
        log::debug!("encrypted query missing `data` parameter");
        Rejection::bad_request()
    })?;

    let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
        .decode(&q.data)
        .map_err(|e| {
            log::debug!("base64url decode failed: {}", e);
            Rejection::forbidden()
        })?;

    crate::serialization::open(&bytes, key.veil_key()).map_err(|e| {
        log::debug!("query decryption failed: {}", e);
        Rejection::forbidden()
    })
}

/// Returns a `403 Forbidden` rejection.
///
/// Use in route handlers to deny access:
/// ```rust,no_run
/// # use toolkit_zero::socket::server::*;
/// # let _ = ServerMechanism::post("/secure")
/// #     .onconnect(|| async { Err::<EmptyReply, _>(forbidden()) });
/// ```
pub fn forbidden() -> Rejection {
    Rejection::forbidden()
}

// ─── Status ───────────────────────────────────────────────────────────────────

/// A collection of common HTTP status codes used with the reply helpers.
///
/// Converts into `http::StatusCode` via [`From`] and is accepted by
/// [`reply_with_status`] and [`reply_with_status_and_json`].  Also usable directly
/// in the [`reply!`] macro via the `status => Status::X` argument.
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub enum Status {
    // 2xx
    Ok,
    Created,
    Accepted,
    NoContent,
    // 3xx
    MovedPermanently,
    Found,
    NotModified,
    TemporaryRedirect,
    PermanentRedirect,
    // 4xx
    BadRequest,
    Unauthorized,
    Forbidden,
    NotFound,
    MethodNotAllowed,
    Conflict,
    Gone,
    UnprocessableEntity,
    TooManyRequests,
    // 5xx
    InternalServerError,
    NotImplemented,
    BadGateway,
    ServiceUnavailable,
    GatewayTimeout,
}

impl From<Status> for http::StatusCode {
    fn from(s: Status) -> Self {
        match s {
            Status::Ok                  => http::StatusCode::OK,
            Status::Created             => http::StatusCode::CREATED,
            Status::Accepted            => http::StatusCode::ACCEPTED,
            Status::NoContent           => http::StatusCode::NO_CONTENT,
            Status::MovedPermanently    => http::StatusCode::MOVED_PERMANENTLY,
            Status::Found               => http::StatusCode::FOUND,
            Status::NotModified         => http::StatusCode::NOT_MODIFIED,
            Status::TemporaryRedirect   => http::StatusCode::TEMPORARY_REDIRECT,
            Status::PermanentRedirect   => http::StatusCode::PERMANENT_REDIRECT,
            Status::BadRequest          => http::StatusCode::BAD_REQUEST,
            Status::Unauthorized        => http::StatusCode::UNAUTHORIZED,
            Status::Forbidden           => http::StatusCode::FORBIDDEN,
            Status::NotFound            => http::StatusCode::NOT_FOUND,
            Status::MethodNotAllowed    => http::StatusCode::METHOD_NOT_ALLOWED,
            Status::Conflict            => http::StatusCode::CONFLICT,
            Status::Gone                => http::StatusCode::GONE,
            Status::UnprocessableEntity => http::StatusCode::UNPROCESSABLE_ENTITY,
            Status::TooManyRequests     => http::StatusCode::TOO_MANY_REQUESTS,
            Status::InternalServerError => http::StatusCode::INTERNAL_SERVER_ERROR,
            Status::NotImplemented      => http::StatusCode::NOT_IMPLEMENTED,
            Status::BadGateway          => http::StatusCode::BAD_GATEWAY,
            Status::ServiceUnavailable  => http::StatusCode::SERVICE_UNAVAILABLE,
            Status::GatewayTimeout      => http::StatusCode::GATEWAY_TIMEOUT,
        }
    }
}

// ─── Server ───────────────────────────────────────────────────────────────────

/// The HTTP server that owns and dispatches a collection of [`SocketType`] routes.
///
/// Build routes through the [`ServerMechanism`] builder chain, register each with
/// [`mechanism`](Server::mechanism), then start the server with [`serve`](Server::serve).
///
/// # Example
/// ```rust,no_run
/// # use toolkit_zero::socket::server::{Server, ServerMechanism, Status};
/// # use toolkit_zero::socket::server::reply;
/// # use serde::Serialize;
/// # #[derive(Serialize)] struct Pong { ok: bool }
///
/// let mut server = Server::default();
///
/// server
///     .mechanism(
///         ServerMechanism::get("/ping")
///             .onconnect(|| async { reply!(json => Pong { ok: true }) })
///     )
///     .mechanism(
///         ServerMechanism::delete("/session")
///             .onconnect(|| async { reply!() })
///     );
///
/// // Blocks forever — call only to actually run the server:
/// // server.serve(([0, 0, 0, 0], 8080)).await;
/// ```
///
/// # Caution
/// Calling [`serve`](Server::serve) with no routes registered will result in a server
/// that returns `404 Not Found` for every request.
pub struct Server {
    mechanisms: Vec<SocketType>,
}

impl Default for Server {
    fn default() -> Self {
        Self::new()
    }
}

impl Server {
    fn new() -> Self {
        Self { mechanisms: Vec::new() }
    }
    /// Registers a [`SocketType`] route on this server.
    ///
    /// Routes are evaluated in registration order.  Returns `&mut Self` for chaining.
    pub fn mechanism(&mut self, mech: SocketType) -> &mut Self {
        self.mechanisms.push(mech);
        log::debug!("Route registered (total: {})", self.mechanisms.len());
        self
    }

    /// Binds to `addr` and starts serving all registered routes.
    ///
    /// Returns a [`ServerFuture`] that can be:
    /// - **`.await`'d** — runs the server in the current task (infinite loop)
    /// - **`.background()`'d** — spawns the server as a Tokio background task
    ///
    /// # Panics
    /// Panics if the address cannot be bound.
    pub fn serve(self, addr: impl Into<SocketAddr>) -> ServerFuture {
        let addr   = addr.into();
        let routes = Arc::new(tokio::sync::RwLock::new(self.mechanisms));
        ServerFuture::new(async move {
            log::info!("Server binding to {}", addr);
            run_hyper_server(routes, addr, std::future::pending::<()>()).await;
        })
    }

    /// Binds to `addr`, serves all registered routes, and shuts down gracefully when
    /// `shutdown` resolves.
    ///
    /// Returns a [`ServerFuture`] that can be `.await`'d or `.background()`'d.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use tokio::sync::oneshot;
    ///
    /// # #[tokio::main]
    /// # async fn main() {
    /// let (tx, rx) = oneshot::channel::<()>();
    /// # let mut server = toolkit_zero::socket::server::Server::default();
    ///
    /// let handle = server.serve_with_graceful_shutdown(
    ///     ([127, 0, 0, 1], 8080),
    ///     async move { rx.await.ok(); },
    /// ).background();
    /// tx.send(()).ok();
    /// handle.await.ok();
    /// # }
    /// ```
    pub fn serve_with_graceful_shutdown(
        self,
        addr: impl Into<std::net::SocketAddr>,
        shutdown: impl std::future::Future<Output = ()> + Send + 'static,
    ) -> ServerFuture {
        let addr   = addr.into();
        let routes = Arc::new(tokio::sync::RwLock::new(self.mechanisms));
        ServerFuture::new(async move {
            log::info!("Server binding to {} (graceful shutdown enabled)", addr);
            run_hyper_server(routes, addr, shutdown).await;
        })
    }

    /// Serves all registered routes from an already-bound `listener`, shutting down
    /// gracefully when `shutdown` resolves.
    ///
    /// Returns a [`ServerFuture`] that can be `.await`'d or `.background()`'d.
    ///
    /// Use this when port `0` is passed to `TcpListener::bind` and you need to know
    /// the actual OS-assigned port before the server starts.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use tokio::net::TcpListener;
    /// use tokio::sync::oneshot;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> std::io::Result<()> {
    /// let listener = TcpListener::bind("127.0.0.1:0").await?;
    /// let port = listener.local_addr()?.port();
    ///
    /// let (tx, rx) = oneshot::channel::<()>();
    /// # let mut server = toolkit_zero::socket::server::Server::default();
    ///
    /// let handle = server
    ///     .serve_from_listener(listener, async move { rx.await.ok(); })
    ///     .background();
    /// tx.send(()).ok();
    /// handle.await.ok();
    /// # Ok(())
    /// # }
    /// ```
    pub fn serve_from_listener(
        self,
        listener: tokio::net::TcpListener,
        shutdown: impl std::future::Future<Output = ()> + Send + 'static,
    ) -> ServerFuture {
        let routes = Arc::new(tokio::sync::RwLock::new(self.mechanisms));
        ServerFuture::new(async move {
            log::info!(
                "Server running on {} (graceful shutdown enabled)",
                listener.local_addr().map(|a| a.to_string()).unwrap_or_else(|_| "?".into())
            );
            run_hyper_server_inner(routes, listener, shutdown).await;
        })
    }

    /// Binds to `addr`, serves all registered routes, and shuts down gracefully
    /// when a Ctrl+C / SIGINT signal is received.
    ///
    /// This is the idiomatic entry point for production use — in-flight requests
    /// drain completely before the server process exits.
    ///
    /// Returns a [`ServerFuture`] that can be:
    /// - **`.await`'d** — runs the server in the current task until interrupted
    /// - **`.background()`'d** — spawns the server as a Tokio background task
    ///   and returns a `JoinHandle<()>`; the task stops gracefully on Ctrl+C
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toolkit_zero::socket::server::{Server, ServerMechanism, reply};
    /// use serde::Serialize;
    ///
    /// #[derive(Serialize)] struct Pong { ok: bool }
    ///
    /// # #[tokio::main]
    /// # async fn main() {
    /// let mut server = Server::default();
    /// server.mechanism(
    ///     ServerMechanism::get("/ping")
    ///         .onconnect(|| async { reply!(json => Pong { ok: true }) })
    /// );
    ///
    /// // Run in foreground until Ctrl+C:
    /// // server.rebind(([127, 0, 0, 1], 8080)).await;
    ///
    /// // Or spawn in background, stops gracefully on Ctrl+C:
    /// let handle = server.rebind(([127, 0, 0, 1], 8080)).background();
    /// // ... do other work ...
    /// handle.await.ok();
    /// # }
    /// ```
    pub fn rebind(self, addr: impl Into<std::net::SocketAddr>) -> ServerFuture {
        let addr   = addr.into();
        let routes = Arc::new(tokio::sync::RwLock::new(self.mechanisms));
        ServerFuture::new(async move {
            log::info!("Server binding to {} (graceful shutdown on Ctrl+C)", addr);
            run_hyper_server(
                routes,
                addr,
                async {
                    tokio::signal::ctrl_c().await.ok();
                    log::info!("Interrupt received — draining in-flight connections");
                },
            ).await;
        })
    }

    /// Starts all registered routes in a background Tokio task and returns a
    /// [`BackgroundServer`] handle.
    ///
    /// Unlike `serve*` + `.background()`, this method keeps a live route table
    /// inside the handle, enabling:
    ///
    /// - [`BackgroundServer::rebind`]     — graceful stop + restart on a new address
    /// - [`BackgroundServer::mechanism`]   — add routes **without restarting**
    /// - [`BackgroundServer::addr`]        — query the current bind address
    /// - [`BackgroundServer::stop`]        — shut down and await completion
    ///
    /// The TCP port is bound **before** spawning the background task, so a bind
    /// failure is returned to the caller immediately rather than silently breaking
    /// the [`BackgroundServer`] handle.
    ///
    /// # Errors
    ///
    /// Returns [`std::io::Error`] if the address cannot be bound
    /// (port already in use, insufficient permissions, etc.).
    ///
    /// # Panics
    ///
    /// Panics if called outside a Tokio runtime.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use toolkit_zero::socket::server::{Server, ServerMechanism, reply};
    /// # use serde::Serialize;
    /// # #[derive(Serialize)] struct Pong { ok: bool }
    /// # #[tokio::main]
    /// # async fn main() {
    /// let mut server = Server::default();
    /// server.mechanism(
    ///     ServerMechanism::get("/ping")
    ///         .onconnect(|| async { reply!(json => Pong { ok: true }) })
    /// );
    ///
    /// let mut bg = server.serve_managed(([127, 0, 0, 1], 8080)).unwrap();
    /// assert_eq!(bg.addr().port(), 8080);
    ///
    /// bg.rebind(([127, 0, 0, 1], 9090)).await.unwrap();
    /// assert_eq!(bg.addr().port(), 9090);
    ///
    /// bg.stop().await;
    /// # }
    /// ```
    pub fn serve_managed(self, addr: impl Into<std::net::SocketAddr>) -> Result<BackgroundServer, std::io::Error> {
        let addr = addr.into();
        // Bind synchronously so the caller can observe a bind failure immediately,
        // rather than discovering it through a silently-broken BackgroundServer handle.
        let std_listener = std::net::TcpListener::bind(addr)?;
        std_listener.set_nonblocking(true)?;
        let routes = Arc::new(tokio::sync::RwLock::new(self.mechanisms));
        let (tx, rx) = tokio::sync::oneshot::channel::<()>();
        let routes_ref = Arc::clone(&routes);
        let handle = tokio::spawn(async move {
            // SAFETY: set_nonblocking(true) was called before this point.
            let listener = tokio::net::TcpListener::from_std(std_listener)
                .expect("from_std: listener must be non-blocking");
            log::info!("server bound to {}", addr);
            run_hyper_server_inner(routes_ref, listener, async { rx.await.ok(); }).await;
        });
        Ok(BackgroundServer {
            routes,
            addr,
            shutdown_tx: Some(tx),
            handle: Some(handle),
        })
    }
}

// ─── ServerFuture ────────────────────────────────────────────────────────────

/// Opaque future returned by [`Server::serve`], [`Server::serve_with_graceful_shutdown`],
/// and [`Server::serve_from_listener`].
///
/// A `ServerFuture` can be used in two ways:
///
/// - **`.await`** — drives the server inline in the current task.
/// - **`.background()`** — spawns the server on a new Tokio task and returns a
///   [`tokio::task::JoinHandle<()>`] immediately.
pub struct ServerFuture(Pin<Box<dyn Future<Output = ()> + Send + 'static>>);

impl ServerFuture {
    fn new(fut: impl Future<Output = ()> + Send + 'static) -> Self {
        Self(Box::pin(fut))
    }

    /// Spawns the server on a new Tokio background task and returns a `JoinHandle<()>`.
    ///
    /// # Panics
    /// Panics if called outside a Tokio runtime.
    pub fn background(self) -> tokio::task::JoinHandle<()> {
        tokio::spawn(self.0)
    }
}

impl std::future::IntoFuture for ServerFuture {
    type Output     = ();
    type IntoFuture = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;
    fn into_future(self) -> Self::IntoFuture {
        self.0
    }
}

// ─── Internal: dispatch + server loop ────────────────────────────────────────

/// Dispatch a single hyper request to the matching route handler.
async fn dispatch(
    routes: &Arc<tokio::sync::RwLock<Vec<SocketType>>>,
    req: hyper::Request<hyper::body::Incoming>,
) -> http::Response<bytes::Bytes> {
    use http_body_util::BodyExt;

    let (parts, body) = req.into_parts();
    let path    = parts.uri.path().to_owned();
    let query   = parts.uri.query().unwrap_or("").to_owned();
    let method  = parts.method.clone();
    let headers = parts.headers.clone();

    // Collect body bytes before acquiring the route lock.
    let body_bytes = match body.collect().await {
        Ok(c) => c.to_bytes(),
        Err(e) => {
            log::debug!("failed to read request body: {}", e);
            return http::Response::builder()
                .status(http::StatusCode::BAD_REQUEST)
                .body(bytes::Bytes::new())
                .unwrap();
        }
    };

    // Hold lock only long enough to clone the matching handler Arc.
    let handler = {
        let guard = routes.read().await;
        guard
            .iter()
            .find(|s| s.method == method && path_matches(&s.path, &path))
            .map(|s| Arc::clone(&s.handler))
    };

    match handler {
        Some(h) => {
            h(IncomingRequest { body: body_bytes, query, headers }).await
        }
        None => {
            log::debug!("No route matched {} {}", method, path);
            http::Response::builder()
                .status(http::StatusCode::NOT_FOUND)
                .body(bytes::Bytes::new())
                .unwrap()
        }
    }
}

/// Core server loop — drives an already-bound listener with graceful shutdown.
///
/// Uses `hyper::server::conn::http1::Builder` (HTTP/1.1) whose `Connection<IO, S>`
/// has no lifetime tied to the builder, making it `'static` and compatible with
/// `tokio::spawn` and `GracefulShutdown::watch`.
async fn run_hyper_server_inner(
    routes:   Arc<tokio::sync::RwLock<Vec<SocketType>>>,
    listener: tokio::net::TcpListener,
    shutdown: impl Future<Output = ()> + Send + 'static,
) {
    use hyper_util::server::graceful::GracefulShutdown;
    use hyper_util::rt::TokioIo;
    use hyper::server::conn::http1;

    let graceful = GracefulShutdown::new();
    let mut shutdown = std::pin::pin!(shutdown);

    loop {
        tokio::select! {
            result = listener.accept() => {
                let (stream, remote) = match result {
                    Ok(pair) => pair,
                    Err(e) => {
                        log::warn!("accept error: {}", e);
                        continue;
                    }
                };
                log::trace!("accepted connection from {}", remote);

                let routes_ref = Arc::clone(&routes);
                // http1::Builder::serve_connection returns Connection<IO, S> with no
                // builder-lifetime, so it is 'static when IO + S are 'static.
                let conn = http1::Builder::new().serve_connection(
                    TokioIo::new(stream),
                    hyper::service::service_fn(move |req| {
                        let r = Arc::clone(&routes_ref);
                        async move {
                            let resp = dispatch(&r, req).await;
                            let (parts, body) = resp.into_parts();
                            Ok::<_, std::convert::Infallible>(
                                http::Response::from_parts(
                                    parts,
                                    http_body_util::Full::new(body),
                                )
                            )
                        }
                    }),
                );
                let fut = graceful.watch(conn);
                tokio::spawn(async move {
                    if let Err(e) = fut.await {
                        log::debug!("connection error: {}", e);
                    }
                });
            }
            _ = &mut shutdown => {
                log::info!("shutdown signal received — draining in-flight connections");
                break;
            }
        }
    }

    // Free the TCP port so a rebound server can bind immediately.
    drop(listener);

    // Block until every in-flight request completes.
    graceful.shutdown().await;
    log::info!("all connections drained");
}

/// Bind to `addr` then delegate to [`run_hyper_server_inner`].
async fn run_hyper_server(
    routes:   Arc<tokio::sync::RwLock<Vec<SocketType>>>,
    addr:     SocketAddr,
    shutdown: impl Future<Output = ()> + Send + 'static,
) {
    let listener = match tokio::net::TcpListener::bind(addr).await {
        Ok(l) => {
            log::info!("server bound to {}", addr);
            l
        }
        Err(e) => {
            log::error!("failed to bind {}: {}", addr, e);
            panic!("server bind failed: {}", e);
        }
    };
    run_hyper_server_inner(routes, listener, shutdown).await;
}

// ─── BackgroundServer ─────────────────────────────────────────────────────────

/// A managed, background HTTP server returned by [`Server::serve_managed`].
///
/// The server starts as soon as `serve_managed` is called.  Use this handle to:
///
/// - [`addr`](BackgroundServer::addr) — query the current bind address
/// - [`rebind`](BackgroundServer::rebind) — gracefully migrate to a new address
/// - [`mechanism`](BackgroundServer::mechanism) — add a route live, **no restart**
/// - [`stop`](BackgroundServer::stop) — shut down and await the task
///
/// # Routes are preserved across `rebind`
/// All routes registered before [`serve_managed`](Server::serve_managed), plus any
/// added via [`mechanism`](BackgroundServer::mechanism), are automatically carried over when
/// [`rebind`](BackgroundServer::rebind) restarts the server.
///
/// # Ownership
/// Dropping a `BackgroundServer` without calling [`stop`](BackgroundServer::stop)
/// leaves the background task running until the Tokio runtime exits.
///
/// # Example
/// ```rust,no_run
/// # use toolkit_zero::socket::server::Server;
/// # use serde::Serialize;
/// # use toolkit_zero::socket::server::reply;
/// # #[derive(Serialize)] struct Pong { ok: bool }
/// # #[tokio::main]
/// # async fn main() {
/// let mut server = Server::default();
/// server.mechanism(
///     toolkit_zero::socket::server::ServerMechanism::get("/ping")
///         .onconnect(|| async { reply!(json => Pong { ok: true }) })
/// );
/// let mut bg = server.serve_managed(([127, 0, 0, 1], 8080)).unwrap();
/// assert_eq!(bg.addr().port(), 8080);
///
/// bg.rebind(([127, 0, 0, 1], 9090)).await.unwrap();
/// assert_eq!(bg.addr().port(), 9090);
///
/// bg.stop().await;
/// # }
/// ```
#[must_use = "dropping BackgroundServer leaves the background task running; call .stop().await to shut it down"]
pub struct BackgroundServer {
    /// Shared mutable route table — written by [`mechanism`](BackgroundServer::mechanism), read by the server loop.
    routes:      Arc<tokio::sync::RwLock<Vec<SocketType>>>,
    addr:        std::net::SocketAddr,
    shutdown_tx: Option<tokio::sync::oneshot::Sender<()>>,
    handle:      Option<tokio::task::JoinHandle<()>>,
}

impl BackgroundServer {
    /// Returns the address the server is currently bound to.
    pub fn addr(&self) -> std::net::SocketAddr {
        self.addr
    }

    /// Shuts the server down gracefully and awaits the background task.
    ///
    /// In-flight requests complete before the server stops.
    pub async fn stop(mut self) {
        if let Some(tx) = self.shutdown_tx.take() {
            let _ = tx.send(());
        }
        if let Some(h) = self.handle.take() {
            let _ = h.await;
        }
    }

    /// Migrates the server to `addr` with zero route loss:
    ///
    /// 1. Sends a graceful shutdown signal to the current instance.
    /// 2. Waits for all in-flight requests to complete.
    /// 3. Spawns a fresh server task on the new address with the same routes.
    ///
    /// After this method returns, [`addr`](BackgroundServer::addr) reflects the
    /// new address and the server is accepting connections.
    ///
    /// # Example
    /// ```rust,no_run
    /// # use toolkit_zero::socket::server::Server;
    /// # use serde::Serialize;
    /// # use toolkit_zero::socket::server::reply;
    /// # #[derive(Serialize)] struct Pong { ok: bool }
    /// # #[tokio::main]
    /// # async fn main() {
    /// # let mut server = Server::default();
    /// # server.mechanism(
    /// #     toolkit_zero::socket::server::ServerMechanism::get("/ping")
    /// #         .onconnect(|| async { reply!(json => Pong { ok: true }) })
    /// # );
    /// let mut bg = server.serve_managed(([127, 0, 0, 1], 8080)).unwrap();
    ///
    /// bg.rebind(([127, 0, 0, 1], 9090)).await.unwrap();
    /// assert_eq!(bg.addr().port(), 9090);
    ///
    /// bg.stop().await;
    /// # }
    /// ```
    pub async fn rebind(&mut self, addr: impl Into<std::net::SocketAddr>) -> Result<(), std::io::Error> {
        let new_addr = addr.into();
        // Bind the new address first — if it fails, the current server is unaffected.
        let std_listener = std::net::TcpListener::bind(new_addr)?;
        std_listener.set_nonblocking(true)?;
        // 1. Graceful shutdown of the current server.
        if let Some(tx) = self.shutdown_tx.take() {
            let _ = tx.send(());
        }
        // 2. Wait for all in-flight requests to drain.
        if let Some(h) = self.handle.take() {
            let _ = h.await;
        }
        // 3. Start on the new address, sharing the existing route table.
        let (tx, rx) = tokio::sync::oneshot::channel::<()>();
        self.shutdown_tx = Some(tx);
        self.addr        = new_addr;
        let routes = Arc::clone(&self.routes);
        self.handle = Some(tokio::spawn(async move {
            // SAFETY: set_nonblocking(true) was called before this point.
            let listener = tokio::net::TcpListener::from_std(std_listener)
                .expect("from_std: listener must be non-blocking");
            run_hyper_server_inner(routes, listener, async { rx.await.ok(); }).await;
        }));
        log::info!("Server rebound to {}", new_addr);
        Ok(())
    }

    /// Registers a new route on the **running** server without any restart.
    ///
    /// Because routes are stored in an `Arc<RwLock<Vec<SocketType>>>` shared between
    /// this handle and the server's dispatch loop, writing through the lock makes the
    /// new route visible to the next incoming request immediately — no TCP port gap,
    /// no in-flight request interruption.
    ///
    /// Returns `&mut Self` for chaining.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use toolkit_zero::socket::server::{Server, ServerMechanism, reply};
    /// use serde::Serialize;
    ///
    /// #[derive(Serialize)] struct Pong   { ok:  bool   }
    /// #[derive(Serialize)] struct Status { msg: String }
    ///
    /// # #[tokio::main]
    /// # async fn main() {
    /// let mut server = Server::default();
    /// server.mechanism(
    ///     ServerMechanism::get("/ping")
    ///         .onconnect(|| async { reply!(json => Pong { ok: true }) })
    /// );
    ///
    /// let mut bg = server.serve_managed(([127, 0, 0, 1], 8080)).unwrap();
    ///
    /// bg.mechanism(
    ///     ServerMechanism::get("/status")
    ///         .onconnect(|| async { reply!(json => Status { msg: "enabled".into() }) })
    /// ).await;
    ///
    /// // /status is now live alongside /ping — no restart.
    /// bg.stop().await;
    /// # }
    /// ```
    pub async fn mechanism(&mut self, mech: SocketType) -> &mut Self {
        self.routes.write().await.push(mech);
        log::debug!(
            "mechanism: live route added (total = {})",
            self.routes.read().await.len()
        );
        self
    }
}

// ─── Reply helpers ────────────────────────────────────────────────────────────

/// Wraps `reply` with the given HTTP `status` code and returns it as a result.
///
/// Pairs with the [`reply!`] macro form `reply!(message => ..., status => ...)`.
pub fn reply_with_status(
    status: Status,
    reply: impl Reply,
) -> Result<http::Response<bytes::Bytes>, Rejection> {
    let mut resp = reply.into_response();
    *resp.status_mut() = status.into();
    Ok(resp)
}

/// Returns an empty `200 OK` reply result.
///
/// Equivalent to `reply!()`.
pub fn reply() -> Result<impl Reply, Rejection> {
    Ok::<_, Rejection>(EmptyReply)
}

/// Serialises `json` as a JSON body and returns it as a `200 OK` reply result.
///
/// `T` must implement `serde::Serialize`.  Equivalent to `reply!(json => ...)`.
pub fn reply_with_json<T: Serialize>(
    json: &T,
) -> Result<impl Reply + use<T>, Rejection> {
    let bytes = serde_json::to_vec(json).map_err(|_| Rejection::internal())?;
    Ok::<_, Rejection>(JsonReply {
        body:   bytes::Bytes::from(bytes),
        status: http::StatusCode::OK,
    })
}

/// Serialises `json` as a JSON body, attaches the given HTTP `status`, and returns a result.
///
/// `T` must implement `serde::Serialize`.  Equivalent to `reply!(json => ..., status => ...)`.
pub fn reply_with_status_and_json<T: Serialize>(
    status: Status,
    json: &T,
) -> Result<impl Reply + use<T>, Rejection> {
    let bytes = serde_json::to_vec(json).map_err(|_| Rejection::internal())?;
    Ok::<_, Rejection>(JsonReply {
        body:   bytes::Bytes::from(bytes),
        status: status.into(),
    })
}

/// Seals `value` with `key` and returns it as an `application/octet-stream` response (`200 OK`).
///
/// `T` must implement `bincode::Encode`.
/// Equivalent to `reply!(sealed => value, key => key)`.
pub fn reply_sealed<T: bincode::Encode>(
    value: &T,
    key: SerializationKey,
) -> Result<http::Response<bytes::Bytes>, Rejection> {
    sealed_response(value, key, None)
}

/// Seals `value` with `key`, attaches the given HTTP `status`, and returns it as a result.
///
/// Equivalent to `reply!(sealed => value, key => key, status => Status::X)`.
pub fn reply_sealed_with_status<T: bincode::Encode>(
    value: &T,
    key: SerializationKey,
    status: Status,
) -> Result<http::Response<bytes::Bytes>, Rejection> {
    sealed_response(value, key, Some(status))
}

fn sealed_response<T: bincode::Encode>(
    value: &T,
    key: SerializationKey,
    status: Option<Status>,
) -> Result<http::Response<bytes::Bytes>, Rejection> {
    let code: http::StatusCode = status.map(Into::into).unwrap_or(http::StatusCode::OK);
    let sealed = crate::serialization::seal(value, key.veil_key())
        .map_err(|_| Rejection::internal())?;
    Ok(http::Response::builder()
        .status(code)
        .header(http::header::CONTENT_TYPE, "application/octet-stream")
        .body(bytes::Bytes::from(sealed))
        .unwrap())
}

// ─── reply! macro ─────────────────────────────────────────────────────────────

/// Convenience macro for constructing reply results inside route handlers.
///
/// | Syntax | Equivalent | Description |
/// |---|---|---|
/// | `reply!()` | [`reply()`] | Empty `200 OK` response. |
/// | `reply!(message => expr, status => Status::X)` | [`reply_with_status`] | Any `Reply` with a status code. |
/// | `reply!(json => expr)` | [`reply_with_json`] | JSON body with `200 OK`. |
/// | `reply!(json => expr, status => Status::X)` | [`reply_with_status_and_json`] | JSON body with a status code. |
/// | `reply!(sealed => expr, key => key)` | [`reply_sealed`] | Encrypted body, `200 OK`. |
/// | `reply!(sealed => expr, key => key, status => Status::X)` | [`reply_sealed_with_status`] | Encrypted body with status. |
///
/// # Example
/// ```rust,no_run
/// # use toolkit_zero::socket::server::{ServerMechanism, Status};
/// # use toolkit_zero::socket::server::reply;
/// # use serde::{Deserialize, Serialize};
/// # #[derive(Deserialize, Serialize)] struct Item { id: u32, name: String }
///
/// // Empty 200 OK
/// let ping = ServerMechanism::get("/ping")
///     .onconnect(|| async { reply!() });
///
/// // JSON body, 200 OK
/// let list = ServerMechanism::get("/items")
///     .onconnect(|| async {
///         let items: Vec<Item> = vec![];
///         reply!(json => items)
///     });
///
/// // JSON body with a custom status
/// let create = ServerMechanism::post("/items")
///     .json::<Item>()
///     .onconnect(|item| async move {
///         reply!(json => item, status => Status::Created)
///     });
/// ```
#[doc(hidden)]
#[macro_export]
macro_rules! reply {
    () => {{
        $crate::socket::server::reply()
    }};

    (message => $message: expr, status => $status: expr) => {{
        $crate::socket::server::reply_with_status($status, $message)
    }};

    (json => $json: expr) => {{
        $crate::socket::server::reply_with_json(&$json)
    }};

    (json => $json: expr, status => $status: expr) => {{
        $crate::socket::server::reply_with_status_and_json($status, &$json)
    }};

    (sealed => $val: expr, key => $key: expr) => {{
        $crate::socket::server::reply_sealed(&$val, $key)
    }};

    (sealed => $val: expr, key => $key: expr, status => $status: expr) => {{
        $crate::socket::server::reply_sealed_with_status(&$val, $key, $status)
    }};
}

/// Re-export the [`reply!`] macro so it is accessible as
/// `toolkit_zero::socket::server::reply` and included in glob imports.
pub use crate::reply;