repe 12.0.0

Rust implementation of the REPE RPC protocol (JSON-focused)
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
//! REST facade over a [`Registry`]: an HTTP gateway in front of a REPE core.
//!
//! This adds a front door; it does not replace one. Public clients get curl,
//! OpenAPI, and edge caching; clients that need the aligned numeric fast path,
//! notify, or sub-millisecond dispatch keep talking REPE to the same registry.
//!
//! The translation is mechanical rather than a redesign, because a REPE query is
//! an RFC 6901 JSON Pointer into a value tree and a REST resource is a path into
//! a value tree. [`Registry::dispatch`] already picks between three operations
//! from the body alone, and they are the three HTTP verbs worth having, with the
//! same safety and idempotency:
//!
//! | HTTP | Registry operation | Safe | Idempotent | Cacheable |
//! | --- | --- | --- | --- | --- |
//! | `GET` / `HEAD` | READ the value at the path | yes | yes | yes |
//! | `PUT` | WRITE the value at the path | no | yes | no |
//! | `POST` | CALL the function at the path | no | no | no |
//!
//! A verb aimed at the wrong kind of target is `405`, not a silent coercion:
//! that refusal is what keeps the facade from becoming RPC in a costume, paying
//! REST's costs while offering none of its guarantees.
//!
//! **This gateway does not authenticate anyone.** See [`RestConfig`] for what it
//! can and cannot bound, and put identity in front of it as you would TLS.
//!
//! The guide covers the caching rules, content negotiation, path mapping, and
//! the error model in full: <https://repe-org.github.io/repe-rs/rest/>.
//!
//! ```no_run
//! use repe::{Registry, rest::RestGateway};
//! use std::sync::Arc;
//!
//! # async fn run() -> Result<(), Box<dyn std::error::Error>> {
//! let registry = Arc::new(Registry::new());
//! registry.register_value("/counter", serde_json::json!(0))?;
//!
//! let gateway = RestGateway::new("/api/v1", Arc::clone(&registry));
//! let listener = tokio::net::TcpListener::bind("127.0.0.1:8080").await?;
//! gateway.serve(listener).await?;
//! # Ok(())
//! # }
//! ```
//!
//! ```text
//! $ curl -s localhost:8080/api/v1/counter
//! 0
//! $ curl -s -X PUT -d 42 localhost:8080/api/v1/counter
//! {"path":"/counter","status":"ok"}
//! ```

use crate::constants::ErrorCode;
use crate::registry::{Registry, RegistryError};
use serde_json::{Value, json};
use std::sync::Arc;
use std::time::Duration;

/// `application/json`, the default representation on both legs.
pub const MEDIA_JSON: &str = "application/json";
/// `application/x-beve`, the BEVE representation.
pub const MEDIA_BEVE: &str = "application/x-beve";
/// `application/problem+json`, RFC 9457 problem details, used for every failure.
pub const MEDIA_PROBLEM: &str = "application/problem+json";

/// The `Allow` set for a path holding a value (or holding nothing yet, which a
/// `PUT` may create).
const ALLOW_VALUE: &str = "GET, HEAD, PUT, OPTIONS";
/// The `Allow` set for a path holding a registered function.
const ALLOW_FUNCTION: &str = "GET, HEAD, POST, OPTIONS";
/// The `Allow` set when policy forbids mutation, or for a target no policy
/// permits writing.
const ALLOW_READ_ONLY: &str = "GET, HEAD, OPTIONS";
/// The `Allow` set reported for `OPTIONS *`, which asks about the server rather
/// than any one resource.
const ALLOW_SERVER: &str = "GET, HEAD, PUT, POST, OPTIONS";

/// Which of the two supported representations a body is in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Repr {
    Json,
    Beve,
}

impl Repr {
    fn media_type(self) -> &'static str {
        match self {
            Repr::Json => MEDIA_JSON,
            Repr::Beve => MEDIA_BEVE,
        }
    }
}

/// Gateway policy: what is reachable, how large, how cacheable, and how errors
/// are graded.
///
/// # This gateway has no authentication
///
/// Nothing here authenticates or authorizes a caller, and the defaults below are
/// chosen on the assumption that something in front of it does. Put it behind a
/// terminator that handles identity — an ingress, an API gateway, a sidecar —
/// exactly as you would put it behind one for TLS. The knobs here reduce blast
/// radius; they are not an access-control system.
#[derive(Debug, Clone)]
pub struct RestConfig {
    /// Reject a request body larger than this with `413`. Defaults to 1 MiB.
    ///
    /// This bounds the *facade*, not the protocol. A REST body is buffered whole
    /// before it can be decoded into a `serde_json::Value`, so an unbounded
    /// limit here is an unbounded allocation driven by an anonymous caller.
    /// Bulk payloads belong on the REPE side, which streams.
    pub max_body_bytes: usize,
    /// `Cache-Control` for successful reads. Defaults to `no-cache`:
    /// revalidate every time, which keeps `ETag` and `304` working while never
    /// serving stale state. Set a `max-age` where the data tolerates it — that
    /// is where the edge-caching win actually comes from.
    pub cache_control: Option<String>,
    /// The status for an [`ErrorCode::ApplicationErrorBase`] handler failure.
    /// Defaults to `500`.
    ///
    /// The gateway cannot know whether a given handler's error means "you sent
    /// the wrong thing" (`400`/`422`) or "something here is broken" (`500`), and
    /// guessing 4xx would tell clients not to retry failures that a retry would
    /// fix. `500` is the honest default; a deployment that knows what its
    /// handlers mean should say so here.
    pub application_error_status: u16,
    /// Serve reads only: answer every `PUT` and `POST` with `405`. Defaults to
    /// `false`.
    ///
    /// Reads are the traffic this facade exists for — they are the cacheable,
    /// safe, CDN-frontable half. A deployment that only needs to publish state
    /// should say so here rather than rely on an upstream to filter methods,
    /// because the mutation surface is otherwise reachable by anyone who can
    /// reach the port.
    pub read_only: bool,
    /// Permit a `PUT` at the mount itself, which the registry treats as a merge
    /// of the request object into the root. Defaults to `false`.
    ///
    /// Separate from [`read_only`](Self::read_only) because it is a different
    /// hazard: a root merge writes *keys the caller chose* rather than a value
    /// at a path the caller named, so it can introduce entirely new state and
    /// grow the in-memory tree without bound. A gateway that legitimately
    /// accepts writes to known leaves almost never wants that too.
    pub allow_root_write: bool,
    /// Accept BEVE request *bodies*. Defaults to `true`.
    ///
    /// This was off by default while `beve` 8's deserializer had no recursion
    /// limit: a few kilobytes of nested array tags overflowed the thread stack,
    /// and a Rust stack overflow aborts the process rather than unwinding into
    /// the per-connection catch, so one anonymous request took down every other
    /// connection with it. `beve` 9 bounds nesting at `beve::MAX_RECURSION_DEPTH`
    /// and reports the refusal as an ordinary error, which this gateway answers
    /// with a `400` like any other malformed body. BEVE responses were never
    /// affected — encoding is driven by the server's own data.
    ///
    /// Still a knob, because content negotiation is policy: a gateway that
    /// publishes a JSON-only contract can turn it off and refuse the media type
    /// outright rather than accept a representation it does not document.
    pub accept_beve_bodies: bool,
    /// Maximum connections served concurrently by [`serve`](RestGateway::serve).
    /// Defaults to 1024.
    ///
    /// Without a cap, every accepted socket becomes an unbounded task holding a
    /// file descriptor, so idle connections that never send a byte march the
    /// process to its descriptor limit. Past the cap, `serve` stops accepting
    /// until a connection finishes, which leaves the backlog to absorb the
    /// spike instead of the descriptor table.
    pub max_connections: usize,
    /// Maximum time [`serve`](RestGateway::serve) gives one request, from the
    /// moment its head is parsed to the moment a response is produced. Answers
    /// `408` and closes the connection on expiry. Defaults to 30 seconds;
    /// `None` disables it.
    ///
    /// A header-read timeout alone does not bound a request. A client that
    /// sends a complete, well-formed head promising `Content-Length: 100` and
    /// then sends no body holds its connection — and its slot under
    /// [`max_connections`](Self::max_connections) — for as long as it likes.
    /// A few hundred such sockets, costing an attacker almost nothing, stop the
    /// gateway from accepting anything at all. This is what bounds the body
    /// read, which is the half of a request the head timeout has already
    /// stopped watching.
    pub request_timeout: Option<Duration>,
}

impl Default for RestConfig {
    fn default() -> Self {
        Self {
            max_body_bytes: 1024 * 1024,
            cache_control: Some("no-cache".to_string()),
            application_error_status: 500,
            read_only: false,
            allow_root_write: false,
            accept_beve_bodies: true,
            max_connections: 1024,
            request_timeout: Some(Duration::from_secs(30)),
        }
    }
}

/// One inbound HTTP request, reduced to the parts the mapping reads.
///
/// Deliberately borrowed and transport-free: [`RestGateway::respond`] takes this
/// and returns a [`RestResponse`], so the entire mapping is exercisable without
/// a socket, a runtime, or hyper. The HTTP layer in [`RestGateway::serve`] does
/// nothing but fill this in and write the result back out.
#[derive(Debug, Clone, Copy)]
pub struct RestRequest<'a> {
    /// The HTTP method, case-sensitive as RFC 9110 requires.
    pub method: &'a str,
    /// The request target, query string included; it is split off here.
    pub target: &'a str,
    /// `Content-Type`, naming the request body's representation.
    pub content_type: Option<&'a str>,
    /// `Accept`, naming the preferred response representation.
    pub accept: Option<&'a str>,
    /// `If-None-Match`, for conditional reads.
    pub if_none_match: Option<&'a str>,
    /// `If-Match`, for conditional writes (optimistic concurrency).
    pub if_match: Option<&'a str>,
    /// The raw request body.
    pub body: &'a [u8],
}

impl<'a> RestRequest<'a> {
    /// A request with no headers and no body.
    pub fn new(method: &'a str, target: &'a str) -> Self {
        Self {
            method,
            target,
            content_type: None,
            accept: None,
            if_none_match: None,
            if_match: None,
            body: &[],
        }
    }

    /// Attach a body and the `Content-Type` describing it.
    pub fn with_body(mut self, content_type: &'a str, body: &'a [u8]) -> Self {
        self.content_type = Some(content_type);
        self.body = body;
        self
    }

    /// Attach an `Accept` header.
    pub fn with_accept(mut self, accept: &'a str) -> Self {
        self.accept = Some(accept);
        self
    }

    /// Attach an `If-None-Match` header.
    pub fn with_if_none_match(mut self, tag: &'a str) -> Self {
        self.if_none_match = Some(tag);
        self
    }

    /// Attach an `If-Match` header.
    pub fn with_if_match(mut self, tag: &'a str) -> Self {
        self.if_match = Some(tag);
        self
    }
}

/// One outbound HTTP response, reduced to the headers this gateway sets.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RestResponse {
    pub status: u16,
    pub content_type: Option<&'static str>,
    pub etag: Option<String>,
    pub cache_control: Option<String>,
    /// `Vary`, set on reads because the response representation depends on
    /// `Accept` and a shared cache must not mix the two.
    pub vary: Option<&'static str>,
    pub allow: Option<&'static str>,
    /// The originating REPE error code, echoed as `X-Repe-Error-Code`.
    pub repe_error_code: Option<u32>,
    /// Set for `HEAD`: `body` holds what `GET` would have returned, and the
    /// carrier must report its length but send none of it.
    pub omit_body: bool,
    pub body: Vec<u8>,
}

impl RestResponse {
    fn empty(status: u16) -> Self {
        Self {
            status,
            content_type: None,
            etag: None,
            cache_control: None,
            vary: None,
            allow: None,
            repe_error_code: None,
            omit_body: false,
            body: Vec::new(),
        }
    }

    /// An RFC 9457 problem-details failure.
    fn problem(status: u16, detail: impl Into<String>, repe_code: Option<u32>) -> Self {
        let mut problem = json!({
            "type": "about:blank",
            "title": reason_phrase(status),
            "status": status,
            "detail": detail.into(),
        });
        if let Some(code) = repe_code {
            problem["repe_code"] = json!(code);
        }
        Self {
            content_type: Some(MEDIA_PROBLEM),
            // RFC 9111 §4.2.2 makes 404 and 405 heuristically cacheable. A
            // cached 405 keeps its stale `Allow` after the target becomes a
            // function, leaving the resource unreachable through its only
            // correct verb; a cached 404 outlives the path being registered.
            cache_control: Some("no-store".to_string()),
            repe_error_code: repe_code,
            // `to_vec` on a Value built from object literals cannot fail: every
            // node is a plain JSON type with no custom Serialize impl to error.
            body: serde_json::to_vec(&problem).unwrap_or_default(),
            ..Self::empty(status)
        }
    }
}

/// An HTTP gateway mapping REST onto a [`Registry`].
///
/// See the [module docs](self) for the verb mapping, the caching rules, and the
/// error model.
#[derive(Clone)]
pub struct RestGateway {
    registry: Arc<Registry>,
    /// Normalized: empty for a root mount, otherwise `/`-prefixed with no
    /// trailing `/`.
    mount: String,
    config: RestConfig,
}

impl std::fmt::Debug for RestGateway {
    /// Hand-written because `Registry` holds `dyn RegistryCallable` handlers and
    /// is not `Debug`. The mount and the policy are what a reader wants anyway.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RestGateway")
            .field("mount", &self.mount)
            .field("config", &self.config)
            .finish_non_exhaustive()
    }
}

impl RestGateway {
    /// Mount `registry` under the URL prefix `mount` with default policy.
    ///
    /// `mount` is normalized exactly as [`Router::with_registry`] normalizes
    /// its prefix, through the same function: made absolute, stripped of a
    /// trailing separator, and empty for a root mount. `"/api/v1"`,
    /// `"/api/v1/"`, and `"api/v1"` all name the same mount.
    ///
    /// [`Router::with_registry`]: crate::server::Router::with_registry
    pub fn new(mount: &str, registry: Arc<Registry>) -> Self {
        Self::with_config(mount, registry, RestConfig::default())
    }

    /// [`new`](Self::new) with explicit policy.
    pub fn with_config(mount: &str, registry: Arc<Registry>, config: RestConfig) -> Self {
        Self {
            registry,
            mount: crate::registry::normalize_mount(mount),
            config,
        }
    }

    /// The registry this gateway fronts.
    pub fn registry(&self) -> &Arc<Registry> {
        &self.registry
    }

    /// Map one HTTP request onto a registry operation and back, with no
    /// transport involved.
    ///
    /// This is the whole facade. [`serve`](Self::serve) is a hyper shim over it,
    /// and any other HTTP stack can be one too.
    pub fn respond(&self, request: RestRequest<'_>) -> RestResponse {
        let path = request.target.split(['?', '#']).next().unwrap_or("");

        // RFC 9110 §9.3.7: `OPTIONS *` asks about the server as a whole rather
        // than a resource, so it never reaches the mount or the pointer mapping.
        if request.method == "OPTIONS" && path == "*" {
            let allow = if self.config.read_only {
                ALLOW_READ_ONLY
            } else {
                ALLOW_SERVER
            };
            return RestResponse {
                allow: Some(allow),
                ..RestResponse::empty(204)
            };
        }

        let Some(remainder) = self.strip_mount(path) else {
            return RestResponse::problem(
                404,
                format!("`{path}` is not under this gateway's mount"),
                None,
            );
        };

        let pointer = match path_to_pointer(remainder) {
            Ok(pointer) => pointer,
            Err(detail) => return RestResponse::problem(400, detail, None),
        };

        // A read needs no target probe: its `Allow` is never sent, and this is
        // the volume path the caching argument is about. Everything else pays
        // one lock acquisition to learn which verbs the target actually admits.
        match request.method {
            "GET" | "HEAD" => self.read(&pointer, request),
            _ => {
                let is_function = self.registry.is_function(&pointer);
                let allow = self.allow_for(is_function);
                match request.method {
                    "PUT" if is_function => method_not_allowed(
                        allow,
                        "this path is a function; a PUT would call it, which is not idempotent — use POST",
                    ),
                    "POST" if !is_function => method_not_allowed(
                        allow,
                        "this path is a value; a POST would write it, which is idempotent — use PUT",
                    ),
                    "PUT" | "POST" => self.write_or_call(&pointer, request, allow, is_function),
                    "OPTIONS" => RestResponse {
                        allow: Some(allow),
                        ..RestResponse::empty(204)
                    },
                    _ => method_not_allowed(allow, "unsupported method"),
                }
            }
        }
    }

    /// The `Allow` set for a target, narrowed by policy so that discovery
    /// reports what this gateway will actually do rather than what the registry
    /// could in principle support.
    fn allow_for(&self, is_function: bool) -> &'static str {
        match (self.config.read_only, is_function) {
            (true, _) => ALLOW_READ_ONLY,
            (false, true) => ALLOW_FUNCTION,
            (false, false) => ALLOW_VALUE,
        }
    }

    /// `GET` / `HEAD`: a registry READ, plus validators and conditional handling.
    fn read(&self, pointer: &str, request: RestRequest<'_>) -> RestResponse {
        let value = match self.registry.dispatch(pointer, None) {
            Ok(value) => value,
            Err(err) => return self.problem_for(err),
        };

        let (body, media) = match encode(&value, negotiate(request.accept)) {
            Ok(encoded) => encoded,
            Err(detail) => return RestResponse::problem(500, detail, None),
        };

        let etag = etag_for(&body);
        let cache_control = self.config.cache_control.clone();

        // A matching validator ends the request here — the point of the ETag.
        if let Some(header) = request.if_none_match
            && if_none_match_matches(header, &etag)
        {
            return RestResponse {
                etag: Some(etag),
                cache_control,
                vary: Some("Accept"),
                ..RestResponse::empty(304)
            };
        }

        RestResponse {
            status: 200,
            content_type: Some(media),
            etag: Some(etag),
            cache_control,
            vary: Some("Accept"),
            omit_body: request.method == "HEAD",
            body,
            ..RestResponse::empty(200)
        }
    }

    /// `PUT` / `POST`: a registry WRITE or CALL. The verb was already checked
    /// against the target kind by [`respond`](Self::respond).
    fn write_or_call(
        &self,
        pointer: &str,
        request: RestRequest<'_>,
        allow: &'static str,
        is_function: bool,
    ) -> RestResponse {
        if self.config.read_only {
            return method_not_allowed(allow, "this gateway is configured read-only");
        }

        // The empty pointer is the registry root, where a write is a merge of
        // the caller's object into the tree rather than an assignment at a path
        // the caller named. That admits arbitrary new keys and unbounded growth,
        // so it is its own decision rather than part of "writes are allowed".
        if crate::registry::addresses_root(pointer) && !self.config.allow_root_write {
            return method_not_allowed(
                ALLOW_READ_ONLY,
                "a write at the mount root would merge arbitrary keys into the registry; \
                 enable `RestConfig::allow_root_write` to permit it",
            );
        }

        // An empty body is how the registry spells READ. Letting one through
        // here would turn a write into a silent read that answers `200` with the
        // old value, so it is refused rather than reinterpreted.
        if request.body.is_empty() {
            return RestResponse::problem(
                400,
                "a body is required; send `null` for a call that takes no arguments",
                Some(ErrorCode::InvalidBody as u32),
            );
        }

        let repr = match self.body_repr(request.content_type) {
            Ok(repr) => repr,
            Err(detail) => {
                return RestResponse::problem(415, detail, Some(ErrorCode::InvalidBody as u32));
            }
        };

        let payload = match decode(request.body, repr) {
            Ok(payload) => payload,
            Err(detail) => {
                return RestResponse::problem(400, detail, Some(ErrorCode::InvalidBody as u32));
            }
        };

        // The verb was resolved against the target kind before we got here, so
        // dispatch stays committed to it. `Registry::dispatch` would re-decide
        // from the body alone, which reopens the window between the two: a
        // pointer that gains a function turns this PUT into a call taking the
        // write payload as arguments, and one that loses a function turns this
        // POST into a write.
        let value = if is_function {
            match self.registry.call(
                pointer,
                Some(payload),
                &crate::CallContext::detached(pointer),
            ) {
                Ok(value) => value,
                Err(err) => return self.problem_for(err),
            }
        } else {
            match self.conditional_write(pointer, payload, &request) {
                Ok(Some(value)) => value,
                Ok(None) => return precondition_failed(),
                Err(err) => return self.problem_for(err),
            }
        };

        let (body, media) = match encode(&value, negotiate(request.accept)) {
            Ok(encoded) => encoded,
            Err(detail) => return RestResponse::problem(500, detail, None),
        };

        RestResponse {
            content_type: Some(media),
            // `Vary` even though a mutation response is not cacheable today:
            // negotiation selected this representation, RFC 9110 §12.5.5 asks
            // for it whenever that is true, and it stops being a formality the
            // moment anyone gives these responses a freshness directive.
            vary: Some("Accept"),
            // No validator: `ETag` is a read concern, and the body here is an
            // acknowledgement rather than the resource's representation.
            body,
            ..RestResponse::empty(200)
        }
    }

    /// Write `payload`, honoring `If-Match` and `If-None-Match`.
    ///
    /// `Ok(None)` means a precondition failed and nothing was written.
    ///
    /// The comparison runs *inside* the registry's write lock rather than
    /// before it. Evaluating a validator with a separate read and then writing
    /// is check-then-act: two clients holding the same tag both see it match and
    /// both write, so the lost update the precondition exists to prevent happens
    /// anyway. RFC 9110 §13.1 asks for the evaluation and the action to be
    /// atomic for exactly this reason.
    fn conditional_write(
        &self,
        pointer: &str,
        payload: Value,
        request: &RestRequest<'_>,
    ) -> Result<Option<Value>, RegistryError> {
        let if_match = request.if_match;
        let if_none_match = request.if_none_match;
        if if_match.is_none() && if_none_match.is_none() {
            return self.registry.write_if(pointer, payload, |_| true);
        }

        self.registry.write_if(pointer, payload, |current| {
            // §13.1.1 (`If-Match`) and §13.1.2 (`If-None-Match`) are evaluated
            // against the same observation of the resource, so a caller may send
            // both and get a coherent answer.
            if let Some(header) = if_match
                && !precondition_present(current, header, if_match_matches)
            {
                return false;
            }
            if let Some(header) = if_none_match
                && precondition_present(current, header, if_none_match_matches)
            {
                return false;
            }
            true
        })
    }

    /// Pick a request-body representation from `Content-Type`. A missing header
    /// is JSON, which is what `curl -d` sends.
    fn body_repr(&self, content_type: Option<&str>) -> Result<Repr, &'static str> {
        let Some(content_type) = content_type else {
            return Ok(Repr::Json);
        };
        match bare_media(content_type, ';').as_str() {
            "" | MEDIA_JSON | "text/json" => Ok(Repr::Json),
            // `curl -d` defaults to this and means JSON often enough that
            // rejecting it would be pedantry at the cost of the primary use case.
            "application/x-www-form-urlencoded" => Ok(Repr::Json),
            MEDIA_BEVE | "application/beve" if self.config.accept_beve_bodies => Ok(Repr::Beve),
            MEDIA_BEVE | "application/beve" => Err(
                "BEVE request bodies are disabled; enable `RestConfig::accept_beve_bodies` \
                 or send application/json",
            ),
            _ => Err("unsupported Content-Type; send application/json"),
        }
    }

    /// Strip the mount prefix, or `None` if the path is not under it.
    fn strip_mount<'p>(&self, path: &'p str) -> Option<&'p str> {
        if self.mount.is_empty() {
            return Some(path);
        }
        let rest = path.strip_prefix(self.mount.as_str())?;
        // `/api/v1x` must not match the mount `/api/v1`: the prefix has to end
        // on a segment boundary or at the end of the path.
        if rest.is_empty() || rest.starts_with('/') {
            Some(rest)
        } else {
            None
        }
    }

    fn problem_for(&self, err: RegistryError) -> RestResponse {
        let code = err.code();
        RestResponse::problem(self.status_for(code), err.to_string(), Some(code as u32))
    }

    fn status_for(&self, code: ErrorCode) -> u16 {
        match code {
            ErrorCode::Ok => 200,
            ErrorCode::MethodNotFound => 404,
            ErrorCode::Timeout => 504,
            ErrorCode::ResourceExhausted => 503,
            ErrorCode::InternalError => 500,
            ErrorCode::ApplicationErrorBase => self.config.application_error_status,
            // Everything else the registry can raise is the caller's fault: a
            // malformed body, an unusable pointer, a body format this gateway
            // does not accept.
            _ => 400,
        }
    }
}

fn method_not_allowed(allow: &'static str, detail: &str) -> RestResponse {
    RestResponse {
        allow: Some(allow),
        ..RestResponse::problem(405, detail, None)
    }
}

/// Map a URL path (already stripped of the mount) onto a JSON Pointer.
///
/// Each segment is percent-decoded *and then* JSON-Pointer-escaped, in that
/// order and per segment. The order is the security-relevant part: decoding the
/// whole path first would let `%2F` decode into a `/` that then reads as a
/// segment separator, so `/items/a%2Fb` would address `b` inside `a` instead of
/// the single key `a/b`. Escaping after decoding turns it into the `~1` the
/// pointer spec asks for, and the injected separator cannot occur.
fn path_to_pointer(path: &str) -> Result<String, &'static str> {
    if path.is_empty() || path == "/" {
        return Ok(String::new());
    }
    // `/counter/` and `/counter` are the same resource. Without this, the
    // trailing slash would address the empty-string key beneath `counter`,
    // which is a legal pointer and never what the caller meant.
    let path = path.strip_suffix('/').unwrap_or(path);
    if path.is_empty() {
        return Ok(String::new());
    }
    if !path.starts_with('/') {
        return Err("request path must be absolute");
    }

    let mut pointer = String::with_capacity(path.len());
    for segment in path.split('/').skip(1) {
        pointer.push('/');
        pointer.push_str(&crate::registry::escape_token(&percent_decode(segment)?));
    }
    Ok(pointer)
}

fn percent_decode(segment: &str) -> Result<String, &'static str> {
    if !segment.contains('%') {
        return Ok(segment.to_string());
    }
    let bytes = segment.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' {
            if i + 2 >= bytes.len() {
                return Err("truncated percent-escape in request path");
            }
            let (hi, lo) = (hex_nibble(bytes[i + 1]), hex_nibble(bytes[i + 2]));
            let (Some(hi), Some(lo)) = (hi, lo) else {
                return Err("invalid percent-escape in request path");
            };
            out.push((hi << 4) | lo);
            i += 3;
        } else {
            out.push(bytes[i]);
            i += 1;
        }
    }
    String::from_utf8(out).map_err(|_| "percent-escape decoded to invalid UTF-8")
}

fn hex_nibble(byte: u8) -> Option<u8> {
    match byte {
        b'0'..=b'9' => Some(byte - b'0'),
        b'a'..=b'f' => Some(byte - b'a' + 10),
        b'A'..=b'F' => Some(byte - b'A' + 10),
        _ => None,
    }
}

/// Pick a response representation from `Accept`.
///
/// A pragmatic subset of RFC 9110 content negotiation: media types and `q`
/// values, no other parameters, no wildcard specificity ranking. That is enough
/// to separate two representations, which is all this gateway offers; anything
/// unrecognized falls back to JSON rather than answering `406`, because a client
/// that got JSON when it asked for something exotic is better served than one
/// that got nothing.
fn negotiate(accept: Option<&str>) -> Repr {
    let Some(accept) = accept else {
        return Repr::Json;
    };
    let mut best: Option<(u32, Repr)> = None;
    for entry in accept.split(',') {
        let media = bare_media(entry, ';');
        let mut quality = 1000;
        for param in entry.split(';').skip(1) {
            let param = param.trim();
            if let Some(value) = param
                .strip_prefix("q=")
                .or_else(|| param.strip_prefix("Q="))
            {
                quality = parse_quality(value);
            }
        }
        let repr = match media.as_str() {
            MEDIA_BEVE | "application/beve" => Repr::Beve,
            MEDIA_JSON | "application/*" | "*/*" => Repr::Json,
            _ => continue,
        };
        // `q=0` is an explicit refusal, not a weak preference.
        if quality == 0 {
            continue;
        }
        // Strictly greater, so equal weights keep the earlier entry — the
        // conventional tie-break, and the one that makes header order meaningful.
        if best.is_none_or(|(best_quality, _)| quality > best_quality) {
            best = Some((quality, repr));
        }
    }
    best.map_or(Repr::Json, |(_, repr)| repr)
}

/// Parse a `q` value into thousandths, clamped to `0..=1000`. An unparseable
/// weight is treated as the `1` default rather than as a refusal.
fn parse_quality(value: &str) -> u32 {
    value
        .trim()
        .parse::<f32>()
        .map_or(1000, |q| (q.clamp(0.0, 1.0) * 1000.0).round() as u32)
}

fn encode(value: &Value, repr: Repr) -> Result<(Vec<u8>, &'static str), &'static str> {
    let bytes = match repr {
        Repr::Json => serde_json::to_vec(value).map_err(|_| "response is not encodable as JSON")?,
        Repr::Beve => beve::to_vec(value).map_err(|_| "response is not encodable as BEVE")?,
    };
    Ok((bytes, repr.media_type()))
}

/// The bare media type from a header value: everything before the first
/// `delimiter`, trimmed and lowercased.
fn bare_media(value: &str, delimiter: char) -> String {
    value
        .split(delimiter)
        .next()
        .unwrap_or("")
        .trim()
        .to_ascii_lowercase()
}

fn decode(body: &[u8], repr: Repr) -> Result<Value, &'static str> {
    match repr {
        Repr::Json => serde_json::from_slice(body).map_err(|_| "request body is not valid JSON"),
        Repr::Beve => beve::from_slice(body).map_err(|_| "request body is not valid BEVE"),
    }
}

/// A strong `ETag` over the exact bytes sent, as FNV-1a/64.
///
/// FNV rather than [`std::hash::DefaultHasher`] because the tag has to agree
/// across processes: two instances of this gateway behind one load balancer must
/// hash a body identically or a shared cache will thrash. `DefaultHasher`'s
/// output is explicitly not stable across Rust releases, so two instances built
/// with different toolchains would disagree. FNV-1a is fully specified and
/// stable forever. It is not, and does not need to be, cryptographic: an `ETag`
/// is a change detector, not an integrity check.
fn etag_for(body: &[u8]) -> String {
    const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
    const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;

    let mut hash = FNV_OFFSET_BASIS;
    for byte in body {
        hash ^= u64::from(*byte);
        hash = hash.wrapping_mul(FNV_PRIME);
    }
    format!("\"{hash:016x}\"")
}

/// Evaluate one precondition header against the resource's current state.
///
/// `true` means the header's condition *holds* — `If-Match` matched, or
/// `If-None-Match` found a match. `*` means "any current representation", so it
/// holds exactly when the resource exists.
///
/// A tag is compared against both representations, because the tag the client
/// holds came from whichever one it negotiated on its read. That cannot wrongly
/// admit a stale write: changing the value changes both encodings, so a match in
/// either proves the state is unchanged.
fn precondition_present(
    current: Option<&Value>,
    header: &str,
    matches: fn(&str, &str) -> bool,
) -> bool {
    let Some(current) = current else {
        return false;
    };
    if header.split(',').any(|candidate| candidate.trim() == "*") {
        return true;
    }
    [Repr::Json, Repr::Beve]
        .into_iter()
        .any(|repr| encode(current, repr).is_ok_and(|(body, _)| matches(header, &etag_for(&body))))
}

fn precondition_failed() -> RestResponse {
    RestResponse::problem(
        412,
        "a precondition failed: the resource has changed, or does not exist, or already exists",
        None,
    )
}

/// `If-Match` uses the *strong* comparison function (RFC 9110 §13.1.1), so a
/// weak validator never satisfies it — unlike [`if_none_match_matches`].
fn if_match_matches(header: &str, etag: &str) -> bool {
    header.split(',').any(|candidate| candidate.trim() == etag)
}

fn if_none_match_matches(header: &str, etag: &str) -> bool {
    header.split(',').any(|candidate| {
        let candidate = candidate.trim();
        // `*` matches any current representation, so on a successful read it
        // always matches.
        candidate == "*" || candidate.strip_prefix("W/").unwrap_or(candidate) == etag
    })
}

/// The registered reason phrase for a status, from `http`'s own table rather
/// than a local copy that would have to be extended per status emitted.
fn reason_phrase(status: u16) -> &'static str {
    hyper::StatusCode::from_u16(status)
        .ok()
        .and_then(|status| status.canonical_reason())
        .unwrap_or("Error")
}

// ---------------------------------------------------------------------------
// HTTP layer
// ---------------------------------------------------------------------------
//
// Everything above is transport-free. This part does nothing but fill in a
// `RestRequest` from a hyper request and write a `RestResponse` back out, which
// is why the mapping's tests need no socket and this shim needs almost none.

use http_body_util::{BodyExt, Full, LengthLimitError, Limited};
use hyper::body::{Bytes, Incoming};
use hyper::{Request, Response};
use hyper_util::rt::{TokioExecutor, TokioIo, TokioTimer};
use hyper_util::server::conn::auto;
use std::convert::Infallible;

impl RestGateway {
    /// Serve this gateway on `listener` until the process ends.
    ///
    /// The accept loop does not give up: a failure that is not about one
    /// connection — descriptor exhaustion being the one that matters — is
    /// retried with a capped backoff rather than surfaced, because a gateway
    /// that stays down after the flood causing it has drained is the outcome
    /// the cap exists to prevent.
    ///
    /// Both HTTP/1.1 and HTTP/2 are served on the one listener via hyper's
    /// protocol-detecting builder: HTTP/2 for a client that arrives with prior
    /// knowledge (or via ALPN behind a TLS terminator), HTTP/1.1 for curl and
    /// for the origin leg behind a CDN. Nothing in the mapping depends on which
    /// one a request arrived over.
    ///
    /// TLS and authentication are deliberately out of scope. A gateway of this
    /// shape belongs behind a terminator that is already doing certificate
    /// rotation, ALPN, and identity; see [`RestConfig`] for what this side can
    /// and cannot bound.
    ///
    /// At most [`RestConfig::max_connections`] connections are served at once.
    /// Past that, `serve` stops accepting until one finishes, so a burst waits
    /// in the listen backlog rather than in the descriptor table. That cap is
    /// only as good as the bound on how long one connection can hold its slot,
    /// which is [`RestConfig::request_timeout`].
    pub async fn serve(self, listener: tokio::net::TcpListener) -> std::io::Result<()> {
        let gateway = Arc::new(self);
        let permits = Arc::new(tokio::sync::Semaphore::new(gateway.config.max_connections));
        let mut backoff = ACCEPT_BACKOFF;

        loop {
            // Taken before `accept`, so a full gateway leaves connections in the
            // backlog instead of accepting sockets it has no capacity to serve.
            // `close()` is never called on this semaphore, so acquiring cannot
            // fail.
            let Ok(permit) = Arc::clone(&permits).acquire_owned().await else {
                return Ok(());
            };

            let stream = match listener.accept().await {
                Ok((stream, _peer)) => {
                    backoff = ACCEPT_BACKOFF;
                    stream
                }
                // The connection died between the backlog and here. Routine.
                Err(err) if is_per_connection_accept_error(&err) => continue,
                Err(_) => {
                    // Everything else is treated as descriptor pressure, which
                    // is what `EMFILE`/`ENFILE` are — and Rust maps both to
                    // `Uncategorized`, so they cannot be matched by kind. Back
                    // off and keep trying rather than counting to a ceiling and
                    // returning: the whole point of surviving a descriptor
                    // flood is to still be serving once the attacker
                    // disconnects, and a loop that gives up after N failures
                    // stays down instead. Held connections drain on their own,
                    // and the backoff caps the spin at one attempt per
                    // `MAX_ACCEPT_BACKOFF`.
                    tokio::time::sleep(backoff).await;
                    backoff = (backoff * 2).min(MAX_ACCEPT_BACKOFF);
                    continue;
                }
            };

            let gateway = Arc::clone(&gateway);
            tokio::spawn(async move {
                let service = hyper::service::service_fn(move |request: Request<Incoming>| {
                    let gateway = Arc::clone(&gateway);
                    async move {
                        let response = match gateway.config.request_timeout {
                            Some(limit) => tokio::time::timeout(limit, gateway.handle(request))
                                .await
                                .unwrap_or_else(|_| request_timeout_response()),
                            None => gateway.handle(request).await,
                        };
                        Ok::<_, Infallible>(response)
                    }
                });
                let mut builder = auto::Builder::new(TokioExecutor::new());
                // Without a header timeout a client that connects and sends
                // nothing holds its task and its descriptor forever, which is
                // how an idle-connection flood reaches the descriptor limit
                // without ever sending a valid request.
                builder
                    .http1()
                    // The timer is not optional: hyper panics on a timeout set
                    // with no timer installed.
                    .timer(TokioTimer::new())
                    .header_read_timeout(HEADER_READ_TIMEOUT);
                // The connection's own errors are its own: a client that hangs
                // up mid-response is routine, and there is no caller left to
                // report it to.
                let _ = builder
                    .serve_connection(TokioIo::new(stream), service)
                    .await;
                drop(permit);
            });
        }
    }

    /// One hyper request in, one hyper response out.
    async fn handle(&self, request: Request<Incoming>) -> Response<Full<Bytes>> {
        let (parts, body) = request.into_parts();

        let method = parts.method.as_str().to_owned();
        let target = parts
            .uri
            .path_and_query()
            .map_or("/", |path_and_query| path_and_query.as_str())
            .to_owned();
        let header = |name: hyper::header::HeaderName| {
            parts
                .headers
                .get(name)
                .and_then(|value| value.to_str().ok())
                .map(str::to_owned)
        };
        let content_type = header(hyper::header::CONTENT_TYPE);
        let accept = header(hyper::header::ACCEPT);
        let if_none_match = header(hyper::header::IF_NONE_MATCH);
        let if_match = header(hyper::header::IF_MATCH);

        // `Limited` caps the body before it is buffered, so an oversized request
        // is refused rather than allocated. Checking `Content-Length` instead
        // would miss a chunked body that declares nothing.
        let body = match Limited::new(body, self.config.max_body_bytes)
            .collect()
            .await
        {
            Ok(collected) => collected.to_bytes(),
            Err(err) => {
                let response = if err.downcast_ref::<LengthLimitError>().is_some() {
                    RestResponse::problem(
                        413,
                        format!(
                            "request body exceeds the {}-byte limit",
                            self.config.max_body_bytes
                        ),
                        None,
                    )
                } else {
                    RestResponse::problem(400, "request body could not be read", None)
                };
                return to_hyper(response);
            }
        };

        to_hyper(self.respond(RestRequest {
            method: &method,
            target: &target,
            content_type: content_type.as_deref(),
            accept: accept.as_deref(),
            if_none_match: if_none_match.as_deref(),
            if_match: if_match.as_deref(),
            body: &body,
        }))
    }
}

/// How long a client may take to send its request head before the connection is
/// dropped. Bounds slowloris, which is otherwise a descriptor leak.
const HEADER_READ_TIMEOUT: Duration = Duration::from_secs(30);

/// First pause after an `accept` failure that is not about one connection, so
/// the retry is a pause rather than a busy loop. Doubles up to
/// [`MAX_ACCEPT_BACKOFF`] while failures continue, and resets on the next
/// successful accept.
const ACCEPT_BACKOFF: Duration = Duration::from_millis(50);

/// Ceiling for that pause. Bounds the spin under sustained descriptor pressure
/// without ever giving up on the listener, which would leave the gateway down
/// after the condition that caused it has cleared.
const MAX_ACCEPT_BACKOFF: Duration = Duration::from_secs(1);

/// Whether an `accept` failure was about the connection rather than the process.
///
/// Everything else — descriptor exhaustion (`EMFILE`/`ENFILE`), `ENOBUFS`, and
/// anything with no nameable [`std::io::ErrorKind`] — is retried with a backoff
/// instead. Ending the loop there is what lets an unauthenticated flood of idle
/// connections take the gateway down permanently: it stays down after the
/// attacker disconnects. Retrying without a backoff is the opposite failure, a
/// hot loop on a condition that needs time to clear, so the caller pairs this
/// with [`ACCEPT_BACKOFF`] and gives up only after
/// [`MAX_CONSECUTIVE_ACCEPT_FAILURES`] in a row.
fn is_per_connection_accept_error(err: &std::io::Error) -> bool {
    use std::io::ErrorKind;
    matches!(
        err.kind(),
        ErrorKind::ConnectionAborted | ErrorKind::ConnectionReset | ErrorKind::Interrupted
    )
}

/// The answer to a request that outlived [`RestConfig::request_timeout`].
///
/// `408` rather than `503`: the request itself did not arrive in time, which is
/// what the client can act on. `Connection: close` because the body it promised
/// is still unread, so the stream is no longer at a message boundary and the
/// connection cannot be reused.
fn request_timeout_response() -> Response<Full<Bytes>> {
    let mut response = to_hyper(RestResponse::problem(
        408,
        "the request was not completed within the gateway's time limit",
        None,
    ));
    response.headers_mut().insert(
        hyper::header::CONNECTION,
        hyper::header::HeaderValue::from_static("close"),
    );
    response
}

fn to_hyper(response: RestResponse) -> Response<Full<Bytes>> {
    let mut builder = Response::builder().status(response.status);
    if let Some(content_type) = response.content_type {
        builder = builder.header(hyper::header::CONTENT_TYPE, content_type);
    }
    if let Some(etag) = &response.etag {
        builder = builder.header(hyper::header::ETAG, etag);
    }
    if let Some(cache_control) = &response.cache_control {
        builder = builder.header(hyper::header::CACHE_CONTROL, cache_control);
    }
    if let Some(vary) = response.vary {
        builder = builder.header(hyper::header::VARY, vary);
    }
    if let Some(allow) = response.allow {
        builder = builder.header(hyper::header::ALLOW, allow);
    }
    if let Some(code) = response.repe_error_code {
        builder = builder.header("x-repe-error-code", code);
    }

    // A `HEAD` reports the length `GET` would have sent while sending none of
    // it, which RFC 9110 asks for and which a client sizing a download relies on.
    let built = if response.omit_body {
        builder
            .header(hyper::header::CONTENT_LENGTH, response.body.len())
            .body(Full::new(Bytes::new()))
    } else {
        builder.body(Full::new(Bytes::from(response.body)))
    };

    built.unwrap_or_else(|_| {
        // Only reachable if a header value built above is not a legal header
        // value. Every one of them is either a static string or hex/decimal
        // digits, so this is unreachable in practice — but a panic in a
        // connection task is not the way to find out otherwise.
        Response::builder()
            .status(500)
            .body(Full::new(Bytes::new()))
            .expect("a status-only response is always buildable")
    })
}

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

    fn gateway() -> RestGateway {
        gateway_with(RestConfig::default())
    }

    fn gateway_with(config: RestConfig) -> RestGateway {
        let registry = Arc::new(Registry::new());
        registry.register_value("/counter", json!(7)).unwrap();
        registry
            .register_value("/config", json!({ "verbose": false }))
            .unwrap();
        // A key with a literal `/` in it, reachable only through `~1`. This is
        // what the percent-decode-then-escape order exists to keep addressable.
        registry
            .register_value("/items/a~1b", json!("slashed"))
            .unwrap();
        registry
            .register_value("/tilde/a~0b", json!("tilded"))
            .unwrap();
        registry
            .register_function("/add", |params| {
                let Some(Value::Object(map)) = params else {
                    return Err((ErrorCode::InvalidBody, "expected an object".into()));
                };
                let a = map.get("a").and_then(Value::as_i64).unwrap_or(0);
                let b = map.get("b").and_then(Value::as_i64).unwrap_or(0);
                Ok(json!({ "result": a + b }))
            })
            .unwrap();
        registry
            .register_function("/boom", |_| {
                Err((ErrorCode::ApplicationErrorBase, "handler said no".into()))
            })
            .unwrap();
        RestGateway::with_config("/api/v1", registry, config)
    }

    fn json_body(response: &RestResponse) -> Value {
        serde_json::from_slice(&response.body).expect("response body is JSON")
    }

    // -- the verb mapping ---------------------------------------------------

    #[test]
    fn get_reads_a_value() {
        let response = gateway().respond(RestRequest::new("GET", "/api/v1/counter"));
        assert_eq!(response.status, 200);
        assert_eq!(response.content_type, Some(MEDIA_JSON));
        assert_eq!(json_body(&response), json!(7));
    }

    #[test]
    fn get_at_the_mount_itself_reads_the_whole_tree() {
        // The mount maps to the empty pointer, i.e. the registry root, so the
        // tree is browsable from one URL rather than only leaf by leaf.
        for target in ["/api/v1", "/api/v1/"] {
            let response = gateway().respond(RestRequest::new("GET", target));
            assert_eq!(response.status, 200, "{target}");
            assert_eq!(json_body(&response)["counter"], json!(7), "{target}");
        }
    }

    #[test]
    fn put_writes_a_value() {
        let gateway = gateway();
        let response = gateway
            .respond(RestRequest::new("PUT", "/api/v1/counter").with_body(MEDIA_JSON, b"42"));
        assert_eq!(response.status, 200);
        assert_eq!(
            gateway.registry().read_value("/counter").unwrap(),
            json!(42)
        );
    }

    #[test]
    fn post_calls_a_function() {
        let response = gateway().respond(
            RestRequest::new("POST", "/api/v1/add").with_body(MEDIA_JSON, br#"{"a":2,"b":3}"#),
        );
        assert_eq!(response.status, 200);
        assert_eq!(json_body(&response), json!({ "result": 5 }));
    }

    #[test]
    fn put_at_a_function_is_refused_rather_than_silently_calling_it() {
        // The guarantee being protected: a caller retried a PUT because PUT is
        // idempotent. Routing it into a function call would run the side effect
        // twice, so the verb mismatch has to be an error, not a coercion.
        let response =
            gateway().respond(RestRequest::new("PUT", "/api/v1/add").with_body(MEDIA_JSON, b"{}"));
        assert_eq!(response.status, 405);
        assert_eq!(response.allow, Some(ALLOW_FUNCTION));
        assert_eq!(response.content_type, Some(MEDIA_PROBLEM));
    }

    #[test]
    fn post_at_a_value_is_refused_rather_than_silently_writing_it() {
        // The mirror image: a value is idempotently writable, and answering a
        // POST would tell callers otherwise — which is how an API ends up with
        // POST on every route and REST's guarantees on none.
        let gateway = gateway();
        let response = gateway
            .respond(RestRequest::new("POST", "/api/v1/counter").with_body(MEDIA_JSON, b"1"));
        assert_eq!(response.status, 405);
        assert_eq!(response.allow, Some(ALLOW_VALUE));
        assert_eq!(
            gateway.registry().read_value("/counter").unwrap(),
            json!(7),
            "the refused POST must not have written"
        );
    }

    #[test]
    fn a_write_with_no_body_is_refused_rather_than_read() {
        // An empty body is how the registry spells READ, so letting one through
        // would answer a PUT with `200` and the *old* value, having written
        // nothing. That is the single most confusing outcome available here.
        // Each against the target kind its verb is legal for, so the empty-body
        // check is what answers rather than the verb guard.
        for (method, target) in [("PUT", "/api/v1/counter"), ("POST", "/api/v1/add")] {
            let response = gateway().respond(RestRequest::new(method, target));
            assert_eq!(response.status, 400, "{method} {target}");
            assert_eq!(
                response.repe_error_code,
                Some(ErrorCode::InvalidBody as u32),
                "{method} {target}"
            );
        }
    }

    #[test]
    fn a_no_argument_call_is_spelled_with_a_null_body() {
        let registry = Arc::new(Registry::new());
        registry
            .register_function("/ping", |_| Ok(json!("pong")))
            .unwrap();
        let gateway = RestGateway::new("/api/v1", registry);
        let response = gateway
            .respond(RestRequest::new("POST", "/api/v1/ping").with_body(MEDIA_JSON, b"null"));
        assert_eq!(response.status, 200);
        assert_eq!(json_body(&response), json!("pong"));
    }

    #[test]
    fn options_advertises_the_verbs_the_target_actually_supports() {
        let gateway = gateway();
        let value = gateway.respond(RestRequest::new("OPTIONS", "/api/v1/counter"));
        assert_eq!(value.status, 204);
        assert_eq!(value.allow, Some(ALLOW_VALUE));

        let function = gateway.respond(RestRequest::new("OPTIONS", "/api/v1/add"));
        assert_eq!(function.status, 204);
        assert_eq!(function.allow, Some(ALLOW_FUNCTION));
    }

    #[test]
    fn an_unsupported_method_is_405_with_allow() {
        let response = gateway().respond(RestRequest::new("DELETE", "/api/v1/counter"));
        assert_eq!(response.status, 405);
        assert_eq!(response.allow, Some(ALLOW_VALUE));
    }

    #[test]
    fn head_reports_the_length_without_the_body() {
        let gateway = gateway();
        let get = gateway.respond(RestRequest::new("GET", "/api/v1/config"));
        let head = gateway.respond(RestRequest::new("HEAD", "/api/v1/config"));
        assert!(head.omit_body);
        assert!(!get.omit_body);
        assert_eq!(head.body, get.body, "HEAD carries what GET would have sent");
        assert_eq!(head.etag, get.etag);
    }

    // -- caching ------------------------------------------------------------

    #[test]
    fn a_read_carries_a_validator_and_a_freshness_directive() {
        let response = gateway().respond(RestRequest::new("GET", "/api/v1/counter"));
        assert!(response.etag.is_some());
        assert_eq!(response.cache_control.as_deref(), Some("no-cache"));
        assert_eq!(response.vary, Some("Accept"));
    }

    #[test]
    fn a_write_carries_neither() {
        let response = gateway()
            .respond(RestRequest::new("PUT", "/api/v1/counter").with_body(MEDIA_JSON, b"1"));
        assert_eq!(response.etag, None);
        assert_eq!(response.cache_control, None);
    }

    #[test]
    fn a_matching_validator_answers_304_with_no_body() {
        let gateway = gateway();
        let first = gateway.respond(RestRequest::new("GET", "/api/v1/counter"));
        let tag = first.etag.clone().unwrap();

        let second =
            gateway.respond(RestRequest::new("GET", "/api/v1/counter").with_if_none_match(&tag));
        assert_eq!(second.status, 304);
        assert!(second.body.is_empty());
        assert_eq!(second.etag, first.etag, "304 still carries the validator");
    }

    #[test]
    fn a_stale_validator_answers_the_full_body() {
        let gateway = gateway();
        let response = gateway.respond(
            RestRequest::new("GET", "/api/v1/counter").with_if_none_match("\"0000000000000000\""),
        );
        assert_eq!(response.status, 200);
        assert_eq!(json_body(&response), json!(7));
    }

    #[test]
    fn the_validator_changes_when_the_value_does() {
        let gateway = gateway();
        let before = gateway.respond(RestRequest::new("GET", "/api/v1/counter"));
        gateway.respond(RestRequest::new("PUT", "/api/v1/counter").with_body(MEDIA_JSON, b"8"));
        let after = gateway.respond(RestRequest::new("GET", "/api/v1/counter"));
        assert_ne!(before.etag, after.etag);

        // And the stale validator no longer short-circuits.
        let conditional = gateway.respond(
            RestRequest::new("GET", "/api/v1/counter").with_if_none_match(&before.etag.unwrap()),
        );
        assert_eq!(conditional.status, 200);
    }

    #[test]
    fn a_weak_validator_and_a_star_both_match() {
        let gateway = gateway();
        let tag = gateway
            .respond(RestRequest::new("GET", "/api/v1/counter"))
            .etag
            .unwrap();

        for header in [format!("W/{tag}"), "*".to_string(), format!("\"x\", {tag}")] {
            let response = gateway
                .respond(RestRequest::new("GET", "/api/v1/counter").with_if_none_match(&header));
            assert_eq!(response.status, 304, "{header}");
        }
    }

    #[test]
    fn the_two_representations_get_different_validators() {
        // Why `Vary: Accept` is not optional: a shared cache keyed on URL alone
        // would hand the BEVE bytes to a JSON client under a tag that matched.
        let gateway = gateway();
        let as_json = gateway.respond(RestRequest::new("GET", "/api/v1/config"));
        let as_beve =
            gateway.respond(RestRequest::new("GET", "/api/v1/config").with_accept(MEDIA_BEVE));
        assert_ne!(as_json.etag, as_beve.etag);
        assert_eq!(as_json.vary, Some("Accept"));
        assert_eq!(as_beve.vary, Some("Accept"));
    }

    // -- content negotiation ------------------------------------------------

    #[test]
    fn beve_is_served_on_request_and_decodes_to_the_same_value() {
        let response =
            gateway().respond(RestRequest::new("GET", "/api/v1/config").with_accept(MEDIA_BEVE));
        assert_eq!(response.content_type, Some(MEDIA_BEVE));
        let decoded: Value = beve::from_slice(&response.body).unwrap();
        assert_eq!(decoded, json!({ "verbose": false }));
    }

    #[test]
    fn a_beve_request_body_is_accepted_by_default() {
        let body = beve::to_vec(&json!({ "a": 20, "b": 22 })).unwrap();
        let response =
            gateway().respond(RestRequest::new("POST", "/api/v1/add").with_body(MEDIA_BEVE, &body));
        assert_eq!(response.status, 200);
        assert_eq!(json_body(&response), json!({ "result": 42 }));
    }

    #[test]
    fn quality_values_are_honored() {
        let gateway = gateway();
        let cases = [
            ("application/json", MEDIA_JSON),
            ("application/x-beve", MEDIA_BEVE),
            ("*/*", MEDIA_JSON),
            (
                "application/json;q=0.1, application/x-beve;q=0.9",
                MEDIA_BEVE,
            ),
            (
                "application/json;q=0.9, application/x-beve;q=0.1",
                MEDIA_JSON,
            ),
            // An explicit refusal of BEVE, even listed first.
            ("application/x-beve;q=0, application/json", MEDIA_JSON),
            // A tie keeps the earlier entry, so header order stays meaningful.
            ("application/x-beve, application/json", MEDIA_BEVE),
            // Nothing recognized: JSON rather than a 406, since a client that
            // gets JSON is better served than one that gets nothing.
            ("text/plain", MEDIA_JSON),
        ];
        for (accept, expected) in cases {
            let response =
                gateway.respond(RestRequest::new("GET", "/api/v1/counter").with_accept(accept));
            assert_eq!(response.content_type, Some(expected), "Accept: {accept}");
        }
    }

    #[test]
    fn an_unsupported_content_type_is_415() {
        let response = gateway().respond(
            RestRequest::new("PUT", "/api/v1/counter").with_body("application/xml", b"<x/>"),
        );
        assert_eq!(response.status, 415);
    }

    #[test]
    fn a_missing_content_type_is_treated_as_json() {
        // What `curl -d` sends, and the single most common way this gateway will
        // be driven by hand.
        let mut request = RestRequest::new("PUT", "/api/v1/counter");
        request.body = b"99";
        let gateway = gateway();
        assert_eq!(gateway.respond(request).status, 200);
        assert_eq!(
            gateway.registry().read_value("/counter").unwrap(),
            json!(99)
        );
    }

    #[test]
    fn a_malformed_body_is_400_not_500() {
        let response = gateway()
            .respond(RestRequest::new("PUT", "/api/v1/counter").with_body(MEDIA_JSON, b"{oops"));
        assert_eq!(response.status, 400);
    }

    // -- paths --------------------------------------------------------------

    #[test]
    fn a_path_outside_the_mount_is_404() {
        for target in ["/counter", "/other/counter", "/"] {
            assert_eq!(
                gateway().respond(RestRequest::new("GET", target)).status,
                404,
                "{target}"
            );
        }
    }

    #[test]
    fn the_mount_must_match_on_a_segment_boundary() {
        // `/api/v1x` shares a textual prefix with `/api/v1` but is a different
        // path; a plain `strip_prefix` would have served it.
        assert_eq!(
            gateway()
                .respond(RestRequest::new("GET", "/api/v1x/counter"))
                .status,
            404
        );
    }

    #[test]
    fn a_percent_encoded_separator_stays_inside_one_segment() {
        // The injection this guards: decoding the whole path first would turn
        // `%2F` into a separator, addressing `b` inside `a` instead of the one
        // key `a/b`.
        let response = gateway().respond(RestRequest::new("GET", "/api/v1/items/a%2Fb"));
        assert_eq!(response.status, 200);
        assert_eq!(json_body(&response), json!("slashed"));
    }

    #[test]
    fn a_literal_tilde_in_a_segment_is_escaped_not_interpreted() {
        let response = gateway().respond(RestRequest::new("GET", "/api/v1/tilde/a~b"));
        assert_eq!(response.status, 200);
        assert_eq!(json_body(&response), json!("tilded"));
    }

    #[test]
    fn a_trailing_slash_is_the_same_resource() {
        let gateway = gateway();
        assert_eq!(
            gateway
                .respond(RestRequest::new("GET", "/api/v1/counter/"))
                .body,
            gateway
                .respond(RestRequest::new("GET", "/api/v1/counter"))
                .body
        );
    }

    #[test]
    fn the_query_string_and_fragment_are_not_part_of_the_resource() {
        let gateway = gateway();
        let plain = gateway.respond(RestRequest::new("GET", "/api/v1/counter"));
        for target in ["/api/v1/counter?pretty=1", "/api/v1/counter#x"] {
            assert_eq!(
                gateway.respond(RestRequest::new("GET", target)).body,
                plain.body,
                "{target}"
            );
        }
    }

    #[test]
    fn a_malformed_percent_escape_is_400() {
        for target in ["/api/v1/a%zz", "/api/v1/a%2"] {
            assert_eq!(
                gateway().respond(RestRequest::new("GET", target)).status,
                400,
                "{target}"
            );
        }
    }

    #[test]
    fn a_root_mount_serves_every_path() {
        let registry = Arc::new(Registry::new());
        registry.register_value("/counter", json!(1)).unwrap();
        for mount in ["", "/"] {
            let gateway = RestGateway::new(mount, Arc::clone(&registry));
            assert_eq!(
                gateway.respond(RestRequest::new("GET", "/counter")).status,
                200,
                "mount {mount:?}"
            );
        }
    }

    #[test]
    fn every_spelling_of_a_mount_names_the_same_mount() {
        // Normalized through the same function `Router::with_registry` uses, so
        // the two mount-taking APIs in this crate cannot read one string two
        // different ways.
        let registry = Arc::new(Registry::new());
        registry.register_value("/counter", json!(1)).unwrap();
        for mount in ["/api/v1", "/api/v1/", "api/v1"] {
            let gateway = RestGateway::new(mount, Arc::clone(&registry));
            assert_eq!(
                gateway
                    .respond(RestRequest::new("GET", "/api/v1/counter"))
                    .status,
                200,
                "mount {mount:?}"
            );
        }
    }

    // -- errors -------------------------------------------------------------

    #[test]
    fn a_missing_path_is_404_as_problem_details_carrying_the_repe_code() {
        let response = gateway().respond(RestRequest::new("GET", "/api/v1/absent"));
        assert_eq!(response.status, 404);
        assert_eq!(response.content_type, Some(MEDIA_PROBLEM));
        assert_eq!(
            response.repe_error_code,
            Some(ErrorCode::MethodNotFound as u32)
        );
        let problem = json_body(&response);
        assert_eq!(problem["status"], json!(404));
        assert_eq!(problem["title"], json!("Not Found"));
        assert_eq!(
            problem["repe_code"],
            json!(ErrorCode::MethodNotFound as u32)
        );
    }

    #[test]
    fn a_handler_error_defaults_to_500_and_is_configurable() {
        let default = gateway()
            .respond(RestRequest::new("POST", "/api/v1/boom").with_body(MEDIA_JSON, b"null"));
        assert_eq!(default.status, 500);
        assert_eq!(
            default.repe_error_code,
            Some(ErrorCode::ApplicationErrorBase as u32)
        );
        assert_eq!(json_body(&default)["detail"], json!("handler said no"));

        let remapped = gateway_with(RestConfig {
            application_error_status: 422,
            ..RestConfig::default()
        })
        .respond(RestRequest::new("POST", "/api/v1/boom").with_body(MEDIA_JSON, b"null"));
        assert_eq!(remapped.status, 422);
    }

    #[test]
    fn a_handler_rejecting_its_arguments_is_400() {
        // `InvalidBody` from inside a handler is still the caller's fault, so it
        // must not surface as a 500 that tells the client to retry.
        let response = gateway()
            .respond(RestRequest::new("POST", "/api/v1/add").with_body(MEDIA_JSON, b"[1,2]"));
        assert_eq!(response.status, 400);
    }

    // -- policy guards ------------------------------------------------------

    #[test]
    fn beve_request_bodies_are_refused_when_the_knob_is_off() {
        let gateway = gateway_with(RestConfig {
            accept_beve_bodies: false,
            ..RestConfig::default()
        });
        let body = beve::to_vec(&json!({ "a": 1, "b": 2 })).unwrap();
        let response =
            gateway.respond(RestRequest::new("POST", "/api/v1/add").with_body(MEDIA_BEVE, &body));
        assert_eq!(response.status, 415);

        // Responses are unaffected: encoding is driven by the server's own data,
        // so the knob is about what the gateway accepts, not what it publishes.
        let read =
            gateway.respond(RestRequest::new("GET", "/api/v1/config").with_accept(MEDIA_BEVE));
        assert_eq!(read.status, 200);
        assert_eq!(read.content_type, Some(MEDIA_BEVE));
    }

    #[test]
    fn a_deeply_nested_beve_body_is_answered_rather_than_aborting() {
        // Why BEVE bodies are on by default again. Nesting is declared by the
        // input, so before `beve` 9 this was a few KB of anonymous request that
        // aborted the process — a stack overflow does not unwind, so no `catch`
        // in the gateway or in hyper could contain it. It is now an ordinary
        // malformed body: 400, connection intact, every other request served.
        let mut body = Vec::new();
        for _ in 0..20_000 {
            body.extend_from_slice(&[0x05, 0x04]);
        }
        body.extend_from_slice(&[0x05, 0x00]);
        let response =
            gateway().respond(RestRequest::new("POST", "/api/v1/add").with_body(MEDIA_BEVE, &body));
        assert_eq!(response.status, 400);
    }

    #[test]
    fn read_only_refuses_every_mutation_and_says_so_in_allow() {
        let gateway = gateway_with(RestConfig {
            read_only: true,
            ..RestConfig::default()
        });
        for (method, target) in [("PUT", "/api/v1/counter"), ("POST", "/api/v1/add")] {
            let response =
                gateway.respond(RestRequest::new(method, target).with_body(MEDIA_JSON, b"1"));
            assert_eq!(response.status, 405, "{method} {target}");
            assert_eq!(response.allow, Some(ALLOW_READ_ONLY), "{method} {target}");
        }
        assert_eq!(gateway.registry().read_value("/counter").unwrap(), json!(7));

        // Discovery reports the narrowed set rather than what the registry could
        // in principle support.
        let options = gateway.respond(RestRequest::new("OPTIONS", "/api/v1/counter"));
        assert_eq!(options.allow, Some(ALLOW_READ_ONLY));
        assert_eq!(
            gateway
                .respond(RestRequest::new("GET", "/api/v1/counter"))
                .status,
            200
        );
    }

    #[test]
    fn a_write_at_the_mount_root_is_refused_unless_enabled() {
        // The registry treats the empty pointer as a merge of the request object
        // into the tree, so this writes keys the *caller* chose and can grow the
        // registry without bound — a different hazard from writing a named leaf.
        let gateway = gateway();
        let response = gateway.respond(
            RestRequest::new("PUT", "/api/v1").with_body(MEDIA_JSON, br#"{"injected":1}"#),
        );
        assert_eq!(response.status, 405);
        assert!(gateway.registry().read_value("/injected").is_err());

        let permissive = gateway_with(RestConfig {
            allow_root_write: true,
            ..RestConfig::default()
        });
        let response = permissive.respond(
            RestRequest::new("PUT", "/api/v1").with_body(MEDIA_JSON, br#"{"injected":1}"#),
        );
        assert_eq!(response.status, 200);
        assert_eq!(
            permissive.registry().read_value("/injected").unwrap(),
            json!(1)
        );
    }

    #[test]
    fn if_match_gates_the_write() {
        let gateway = gateway();
        let tag = gateway
            .respond(RestRequest::new("GET", "/api/v1/counter"))
            .etag
            .unwrap();

        // A stale validator must not write: this is the lost update a client
        // doing optimistic concurrency is relying on us to prevent.
        let stale = gateway.respond(
            RestRequest::new("PUT", "/api/v1/counter")
                .with_body(MEDIA_JSON, b"1")
                .with_if_match("\"0000000000000000\""),
        );
        assert_eq!(stale.status, 412);
        assert_eq!(gateway.registry().read_value("/counter").unwrap(), json!(7));

        // A current one proceeds.
        let fresh = gateway.respond(
            RestRequest::new("PUT", "/api/v1/counter")
                .with_body(MEDIA_JSON, b"1")
                .with_if_match(&tag),
        );
        assert_eq!(fresh.status, 200);
        assert_eq!(gateway.registry().read_value("/counter").unwrap(), json!(1));

        // And the tag that just succeeded is now stale, so a replay is refused.
        let replay = gateway.respond(
            RestRequest::new("PUT", "/api/v1/counter")
                .with_body(MEDIA_JSON, b"2")
                .with_if_match(&tag),
        );
        assert_eq!(replay.status, 412);
    }

    #[test]
    fn if_match_star_requires_the_resource_to_exist() {
        let gateway = gateway();
        let existing = gateway.respond(
            RestRequest::new("PUT", "/api/v1/counter")
                .with_body(MEDIA_JSON, b"1")
                .with_if_match("*"),
        );
        assert_eq!(existing.status, 200);

        let absent = gateway.respond(
            RestRequest::new("PUT", "/api/v1/absent")
                .with_body(MEDIA_JSON, b"1")
                .with_if_match("*"),
        );
        assert_eq!(absent.status, 412);
    }

    #[test]
    fn if_match_uses_strong_comparison() {
        // RFC 9110 §13.1.1: unlike If-None-Match, a weak validator never
        // satisfies If-Match, because it does not promise byte equality.
        let gateway = gateway();
        let tag = gateway
            .respond(RestRequest::new("GET", "/api/v1/counter"))
            .etag
            .unwrap();
        let response = gateway.respond(
            RestRequest::new("PUT", "/api/v1/counter")
                .with_body(MEDIA_JSON, b"1")
                .with_if_match(&format!("W/{tag}")),
        );
        assert_eq!(response.status, 412);
    }

    #[test]
    fn a_doubled_slash_does_not_reach_the_root() {
        // `//` maps to the pointer `"/"`, which is not the empty string but is
        // the root as far as `parse_pointer` is concerned. Two definitions of
        // "root" meant the policy check tested one and the write took the other.
        let gateway = gateway();
        for target in ["/api/v1", "/api/v1/", "/api/v1//"] {
            let response = gateway
                .respond(RestRequest::new("PUT", target).with_body(MEDIA_JSON, br#"{"x":1}"#));
            assert_eq!(response.status, 405, "{target}");
        }
        assert!(
            gateway.registry().read_value("/x").is_err(),
            "the root was written through one of the spellings above"
        );
    }

    #[test]
    fn a_permitted_root_write_still_works_through_every_spelling() {
        for target in ["/api/v1", "/api/v1/", "/api/v1//"] {
            let gateway = gateway_with(RestConfig {
                allow_root_write: true,
                ..RestConfig::default()
            });
            let response = gateway
                .respond(RestRequest::new("PUT", target).with_body(MEDIA_JSON, br#"{"x":1}"#));
            assert_eq!(response.status, 200, "{target}");
            assert_eq!(gateway.registry().read_value("/x").unwrap(), json!(1));
        }
    }

    #[test]
    fn if_none_match_star_refuses_to_overwrite() {
        // RFC 9110 §13.1.2: `If-None-Match: *` on a write means create-only.
        // Ignoring it tells a client its create succeeded while it silently
        // clobbered someone else's state.
        let gateway = gateway();
        let response = gateway.respond(
            RestRequest {
                if_none_match: Some("*"),
                ..RestRequest::new("PUT", "/api/v1/counter")
            }
            .with_body(MEDIA_JSON, b"99"),
        );
        assert_eq!(response.status, 412);
        assert_eq!(gateway.registry().read_value("/counter").unwrap(), json!(7));
    }

    #[test]
    fn if_none_match_star_permits_a_create() {
        let gateway = gateway();
        let response = gateway.respond(
            RestRequest {
                if_none_match: Some("*"),
                ..RestRequest::new("PUT", "/api/v1/fresh")
            }
            .with_body(MEDIA_JSON, b"1"),
        );
        assert_eq!(response.status, 200);
        assert_eq!(gateway.registry().read_value("/fresh").unwrap(), json!(1));
    }

    #[test]
    fn if_none_match_with_a_tag_refuses_a_matching_write() {
        let gateway = gateway();
        let tag = gateway
            .respond(RestRequest::new("GET", "/api/v1/counter"))
            .etag
            .unwrap();
        let response = gateway.respond(
            RestRequest {
                if_none_match: Some(&tag),
                ..RestRequest::new("PUT", "/api/v1/counter")
            }
            .with_body(MEDIA_JSON, b"99"),
        );
        assert_eq!(response.status, 412);
        assert_eq!(gateway.registry().read_value("/counter").unwrap(), json!(7));
    }

    #[test]
    fn exactly_one_racing_conditional_write_wins() {
        // The lost update `If-Match` exists to prevent. Evaluated before the
        // write rather than within it, every thread here sees the tag it
        // expected and several writes land.
        let gateway = Arc::new(gateway());
        let tag = gateway
            .respond(RestRequest::new("GET", "/api/v1/counter"))
            .etag
            .unwrap();

        let accepted = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let barrier = Arc::new(std::sync::Barrier::new(16));
        std::thread::scope(|scope| {
            for worker in 0..16 {
                let gateway = Arc::clone(&gateway);
                let accepted = Arc::clone(&accepted);
                let barrier = Arc::clone(&barrier);
                let tag = tag.clone();
                scope.spawn(move || {
                    // Offset so that no worker writes the value already stored.
                    // A worker that wrote it would leave the resource — and so
                    // its validator — unchanged, and the next worker's
                    // `If-Match` would legitimately match as well. That is
                    // `write_if` behaving correctly on a resource nobody
                    // changed, but it is indistinguishable here from the lost
                    // update this test exists to catch.
                    let body = (1000 + worker).to_string();
                    barrier.wait();
                    let response = gateway.respond(
                        RestRequest {
                            if_match: Some(&tag),
                            ..RestRequest::new("PUT", "/api/v1/counter")
                        }
                        .with_body(MEDIA_JSON, body.as_bytes()),
                    );
                    if response.status == 200 {
                        accepted.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                    }
                });
            }
        });

        assert_eq!(
            accepted.load(std::sync::atomic::Ordering::SeqCst),
            1,
            "more than one writer saw the same validator match"
        );
    }

    #[test]
    fn options_star_respects_read_only() {
        let gateway = gateway_with(RestConfig {
            read_only: true,
            ..RestConfig::default()
        });
        let response = gateway.respond(RestRequest::new("OPTIONS", "*"));
        assert_eq!(response.status, 204);
        assert_eq!(response.allow, Some(ALLOW_READ_ONLY));
    }

    #[test]
    fn a_write_never_becomes_a_call_and_a_call_never_becomes_a_write() {
        // The verb is resolved against the target kind before dispatch, so
        // dispatch must stay committed to it rather than re-deciding from the
        // body — which is what leaves a window for the target to change kind.
        let registry = Arc::new(Registry::new());
        registry.register_value("/value", json!(1)).unwrap();
        registry
            .register_function("/function", |_| Ok(json!("called")))
            .unwrap();

        assert!(
            registry.write_if("/function", json!(2), |_| true).is_err(),
            "a write reached a function"
        );
        assert!(
            registry
                .call(
                    "/value",
                    Some(json!(2)),
                    &crate::CallContext::detached("/value")
                )
                .is_err(),
            "a call reached a value"
        );
        assert_eq!(registry.read_value("/value").unwrap(), json!(1));
    }

    #[test]
    fn if_match_accepts_a_tag_from_either_representation() {
        // The client's tag came from whichever representation it negotiated, and
        // the gateway has no record of which. Matching either is safe: changing
        // the value changes both encodings.
        let gateway = gateway();
        let beve_tag = gateway
            .respond(RestRequest::new("GET", "/api/v1/counter").with_accept(MEDIA_BEVE))
            .etag
            .unwrap();
        let response = gateway.respond(
            RestRequest::new("PUT", "/api/v1/counter")
                .with_body(MEDIA_JSON, b"1")
                .with_if_match(&beve_tag),
        );
        assert_eq!(response.status, 200);
    }

    #[test]
    fn an_error_response_is_never_cacheable() {
        // RFC 9111 §4.2.2 makes 404 and 405 heuristically cacheable. A cached
        // 405 keeps its stale `Allow` after the path becomes a function, leaving
        // the resource unreachable through its only correct verb.
        let gateway = gateway();
        let cases = [
            gateway.respond(RestRequest::new("GET", "/api/v1/absent")),
            gateway.respond(RestRequest::new("DELETE", "/api/v1/counter")),
            gateway
                .respond(RestRequest::new("POST", "/api/v1/counter").with_body(MEDIA_JSON, b"1")),
        ];
        for response in cases {
            assert!(response.status >= 400);
            assert_eq!(response.cache_control.as_deref(), Some("no-store"));
        }
    }

    #[test]
    fn options_star_asks_about_the_server_not_a_resource() {
        // RFC 9110 §9.3.7, and the one OPTIONS form a generic HTTP tool sends.
        let response = gateway().respond(RestRequest::new("OPTIONS", "*"));
        assert_eq!(response.status, 204);
        assert_eq!(response.allow, Some(ALLOW_SERVER));
    }

    // -- units --------------------------------------------------------------

    #[test]
    fn path_to_pointer_cases() {
        let cases = [
            ("", ""),
            ("/", ""),
            ("/counter", "/counter"),
            ("/counter/", "/counter"),
            ("/a/b/c", "/a/b/c"),
            ("/a%2Fb", "/a~1b"),
            ("/a~b", "/a~0b"),
            ("/a%7Eb", "/a~0b"),
            ("/sp%20ace", "/sp ace"),
            // An empty middle segment is a legal pointer to an empty key, and
            // is left alone rather than collapsed.
            ("/a//b", "/a//b"),
        ];
        for (path, expected) in cases {
            assert_eq!(path_to_pointer(path).unwrap(), expected, "{path}");
        }
    }

    #[test]
    fn etag_is_stable_and_content_addressed() {
        assert_eq!(etag_for(b"abc"), etag_for(b"abc"));
        assert_ne!(etag_for(b"abc"), etag_for(b"abd"));
        // Pinned so a refactor cannot silently change the function: two gateway
        // instances that disagree would make a shared cache thrash rather than
        // fail, which is the kind of bug nobody notices.
        assert_eq!(etag_for(b""), "\"cbf29ce484222325\"");
        assert_eq!(etag_for(b"repe"), "\"4cac4e1fbfac553f\"");
    }
}