dustnet-server 0.3.0

ATP static-server library; install dustnetd to run a server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
#![forbid(unsafe_code)]
// Remote clients choose every byte this server frames and every path it is
// asked to serve, so an operation
// that can panic on out-of-range input is a denial of service against every
// other connection the process is holding. Denied in non-test builds only:
// tests assert on known-good values, where `unwrap` is the clearer spelling.
#![cfg_attr(
    not(test),
    deny(
        clippy::indexing_slicing,
        clippy::unwrap_used,
        clippy::expect_used,
        clippy::panic
    )
)]

//! Bounded, plugin-free static ATP server.

mod certs;
pub mod include;
pub mod input;
mod live_watch;
pub mod session;
mod transport;

use std::collections::HashMap;
use std::net::IpAddr;
use std::path::{Component, Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use dustnet_core::protocol::frame::{MessageType, RawFrame, allocate_frame_body};
use dustnet_core::protocol::message::{
    ErrorMessage, GetMessage, HelloMessage, InputMessage, PageFlags, PageMessage, SubscribeMessage,
    SubscribeMode, UpdateMessage, WelcomeMessage,
};
use dustnet_core::protocol::{
    MAX_PAGE_MESSAGE_SIZE, MAX_WASM_MODULE_SIZE, PROTOCOL_VERSION, ProtocolError,
    SUPPORTED_CAPABILITIES,
};
use tokio::io::AsyncReadExt;
use tokio::sync::{mpsc, watch};

use crate::live_watch::{
    ChangeSource, LiveGeneration, LiveWatcher, ManualChangeSource, NotifyChangeSource,
    WatchRegistry,
};
use crate::transport::{AtpListener, AtpServerStream};

/// Default server-wide connection ceiling.
///
/// An idle connection costs memory; a TLS handshake costs CPU. Holding
/// connections open is therefore the cheaper side of the trade, and the number
/// that used to sit here reflected the old per-connection subscription polling
/// rather than any protocol limit. Operators can raise or lower it with
/// `--max-connections`; note that the process also needs an `RLIMIT_NOFILE`
/// above this value, which the OS will not grant on our behalf (see
/// `docs/guides/production-support.md`).
pub const DEFAULT_MAX_CONNECTIONS: usize = 2048;

/// Default per-source-IP connection ceiling.
pub const DEFAULT_MAX_CONNECTIONS_PER_IP: usize = 4;
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10);
const READ_TIMEOUT: Duration = Duration::from_secs(30);
const WRITE_TIMEOUT: Duration = Duration::from_secs(10);
const DRAIN_TIMEOUT: Duration = Duration::from_secs(5);
const MAX_SUBSCRIPTIONS_PER_CONNECTION: usize = 16;
const MAX_SERVER_SUBSCRIPTION_BYTES: usize = 128 * 1024 * 1024;

#[derive(Clone, Debug)]
pub(crate) struct SubscriptionBudget {
    state: Arc<Mutex<SubscriptionBudgetState>>,
}

#[derive(Debug)]
struct SubscriptionBudgetState {
    used: usize,
    limit: usize,
}

impl SubscriptionBudget {
    pub(crate) fn new(limit: usize) -> Self {
        Self {
            state: Arc::new(Mutex::new(SubscriptionBudgetState { used: 0, limit })),
        }
    }

    pub(crate) fn reserve(&self, requested: usize) -> Result<SubscriptionLease, ProtocolError> {
        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
        let next = state
            .used
            .checked_add(requested)
            .ok_or(ProtocolError::ResourceExhausted { requested })?;
        if next > state.limit {
            let (used, limit) = (state.used, state.limit);
            drop(state);
            // Every refusal is logged, not the first or one per connection.
            // A refusal is the server silently declining to deliver a live
            // update someone asked for, and an operator who sees a stalled
            // region has no other way to find out that is what happened.
            tracing::warn!(
                requested,
                used,
                limit,
                "live update refused: subscription budget exhausted"
            );
            return Err(ProtocolError::ResourceExhausted { requested });
        }
        state.used = next;
        drop(state);
        Ok(SubscriptionLease {
            budget: self.clone(),
            amount: requested,
        })
    }

    /// Bytes currently reserved for retained subscription content.
    ///
    /// Exposed so an operator can see budget pressure before it becomes a
    /// stalled live region rather than after.
    pub(crate) fn used(&self) -> usize {
        self.state
            .lock()
            .unwrap_or_else(|error| error.into_inner())
            .used
    }

    /// The server-wide ceiling `used` is measured against.
    fn limit(&self) -> usize {
        self.state
            .lock()
            .unwrap_or_else(|error| error.into_inner())
            .limit
    }
}

#[derive(Debug)]
pub(crate) struct SubscriptionLease {
    budget: SubscriptionBudget,
    amount: usize,
}

impl SubscriptionLease {
    fn try_resize(&mut self, requested: usize) -> Result<(), ProtocolError> {
        let mut state = self
            .budget
            .state
            .lock()
            .unwrap_or_else(|error| error.into_inner());
        let without_self = state.used.saturating_sub(self.amount);
        let next = without_self
            .checked_add(requested)
            .ok_or(ProtocolError::ResourceExhausted { requested })?;
        if next > state.limit {
            return Err(ProtocolError::ResourceExhausted { requested });
        }
        state.used = next;
        self.amount = requested;
        Ok(())
    }

    fn ensure_at_least(&mut self, requested: usize) -> Result<(), ProtocolError> {
        if requested > self.amount {
            self.try_resize(requested)?;
        }
        Ok(())
    }

    pub(crate) fn shrink_to(&mut self, requested: usize) {
        debug_assert!(requested <= self.amount);
        let mut state = self
            .budget
            .state
            .lock()
            .unwrap_or_else(|error| error.into_inner());
        state.used -= self.amount - requested;
        self.amount = requested;
    }
}

impl Drop for SubscriptionLease {
    fn drop(&mut self) {
        let mut state = self
            .budget
            .state
            .lock()
            .unwrap_or_else(|error| error.into_inner());
        state.used = state.used.saturating_sub(self.amount);
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum ServerAllocationSite {
    Backing,
    Path,
    Region,
    Content,
    StaticBody,
    WatchEntry,
    WakeSlots,
}

#[cfg(test)]
struct AllocationRejectionGuard;

#[cfg(test)]
impl AllocationRejectionGuard {
    fn at(site: ServerAllocationSite, owner: u64) -> Self {
        REJECT_ALLOCATION_SITE.with(|rejected| rejected.set(Some((site, owner))));
        Self
    }
}

#[cfg(test)]
impl Drop for AllocationRejectionGuard {
    fn drop(&mut self) {
        REJECT_ALLOCATION_SITE.with(|rejected| rejected.set(None));
    }
}

#[cfg(test)]
thread_local! {
    static REJECT_ALLOCATION_SITE: std::cell::Cell<Option<(ServerAllocationSite, u64)>> = const {
        std::cell::Cell::new(None)
    };
}

#[cfg(test)]
pub(crate) fn reject_allocation_at(site: ServerAllocationSite, owner: u64) -> bool {
    REJECT_ALLOCATION_SITE.with(|rejected| rejected.get() == Some((site, owner)))
}

#[cfg(not(test))]
pub(crate) fn reject_allocation_at(_site: ServerAllocationSite, _owner: u64) -> bool {
    false
}

fn reject_subscription_backing_allocation() -> bool {
    reject_allocation_at(ServerAllocationSite::Backing, 0)
}

struct StaticSubscription {
    region: String,
    mode: SubscribeMode,
    /// This connection's last successfully sent generation.
    ///
    /// Not "the file's previous version": under `SubscribeMode::Delta` the
    /// suffix is computed against what *this* subscriber last received, and it
    /// advances only after a send succeeds. A subscriber that misses a
    /// generation therefore finds `strip_prefix` failing on the next one and
    /// falls back to a complete replace, resynchronising itself without any
    /// separate recovery path. Sharing the read must not disturb that, which is
    /// why the baseline stays per-subscription while only the text is shared.
    baseline: Arc<LiveGeneration>,
    updates: watch::Receiver<Arc<LiveGeneration>>,
    _metadata_lease: SubscriptionLease,
}

fn subscription_owner_key(path: &str, region: &str) -> u64 {
    let mut hash = 0xcbf2_9ce4_8422_2325_u64;
    for byte in path
        .bytes()
        .chain(std::iter::once(0xff))
        .chain(region.bytes())
    {
        hash ^= u64::from(byte);
        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
    }
    hash
}

fn try_subscription_storage() -> Result<Vec<StaticSubscription>, ProtocolError> {
    let requested = MAX_SUBSCRIPTIONS_PER_CONNECTION
        .checked_mul(std::mem::size_of::<StaticSubscription>())
        .ok_or(ProtocolError::ResourceExhausted {
            requested: usize::MAX,
        })?;
    if reject_subscription_backing_allocation() {
        return Err(ProtocolError::ResourceExhausted { requested });
    }
    let mut subscriptions = Vec::new();
    subscriptions
        .try_reserve_exact(MAX_SUBSCRIPTIONS_PER_CONNECTION)
        .map_err(|_| ProtocolError::ResourceExhausted { requested })?;
    Ok(subscriptions)
}

/// Configuration for a static server. Construction validates the site root.
pub struct StaticServerConfig {
    root: PathBuf,
    listener: AtpListener,
    max_connections: usize,
    max_connections_per_ip: usize,
    read_timeout: Duration,
    resolver: Option<Arc<dyn crate::include::IncludeResolver>>,
    input_handler: Option<Arc<dyn crate::input::InputHandler>>,
    session_resolver: Option<Arc<dyn crate::session::SessionResolver>>,
}

impl StaticServerConfig {
    fn new(root: PathBuf, listener: AtpListener) -> Result<Self, ProtocolError> {
        let metadata = std::fs::metadata(&root)?;
        if !metadata.is_dir() {
            return Err(ProtocolError::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidInput,
                "static site root is not a directory",
            )));
        }
        // Canonicalise once, here, rather than on every request. Blocking at
        // bind time is free; blocking on a runtime worker per GET is not.
        let root = std::fs::canonicalize(&root)?;
        Ok(Self {
            root,
            listener,
            max_connections: DEFAULT_MAX_CONNECTIONS,
            max_connections_per_ip: DEFAULT_MAX_CONNECTIONS_PER_IP,
            read_timeout: READ_TIMEOUT,
            resolver: None,
            input_handler: None,
            session_resolver: None,
        })
    }

    /// Install a resolver for `[include]` placeholders.
    ///
    /// Absent by default, and `dustnetd` never sets one: a server without a
    /// resolver serves authored AML unchanged, so an `[include]` travels to the
    /// client and renders as nothing. Setting one is what lets a page carry
    /// generated content, and it is the only way this server produces markup it
    /// did not read from a file.
    pub fn with_include_resolver(
        mut self,
        resolver: Arc<dyn crate::include::IncludeResolver>,
    ) -> Self {
        self.resolver = Some(resolver);
        self
    }

    /// Install a handler for form submissions.
    ///
    /// Absent by default, and `dustnetd` never sets one: without a handler
    /// `INPUT` is refused with 405, which is what this server did before
    /// handlers existed. Installing one is what lets a site accept a
    /// submission, and it is the only way this server changes anything on disk.
    pub fn with_input_handler(mut self, handler: Arc<dyn crate::input::InputHandler>) -> Self {
        self.input_handler = Some(handler);
        self
    }

    /// Install a resolver that turns a session token into an identity.
    ///
    /// Without one every request is anonymous, whatever token it carries.
    /// Installing one is what makes a site able to know who is asking — and the
    /// token goes no further than this resolver: handlers are told the identity.
    pub fn with_session_resolver(
        mut self,
        resolver: Arc<dyn crate::session::SessionResolver>,
    ) -> Self {
        self.session_resolver = Some(resolver);
        self
    }

    /// Bind a plaintext development server. The listener enforces loopback-only use.
    pub async fn bind_plaintext_loopback(
        root: PathBuf,
        address: &str,
        port: u16,
    ) -> Result<Self, ProtocolError> {
        Self::new(root, AtpListener::bind_plain(address, port).await?)
    }

    /// Bind a TLS 1.3 static server using PEM certificate and private-key files.
    pub async fn bind_tls(
        root: PathBuf,
        address: &str,
        port: u16,
        certificate: &str,
        private_key: &str,
    ) -> Result<Self, ProtocolError> {
        Self::new(
            root,
            AtpListener::bind_tls(address, port, certificate, private_key).await?,
        )
    }

    /// Return the listener address, including an OS-selected port when port zero was requested.
    pub fn local_addr(&self) -> Result<std::net::SocketAddr, ProtocolError> {
        self.listener.local_addr()
    }

    /// Override the idle read deadline.
    ///
    /// Exposed for tests only. The keepalive behaviour this guards is defined
    /// by a 30-second deadline, and a test that waited it out honestly would
    /// dominate the suite's runtime; shortening the deadline lets the same
    /// behaviour be proven in milliseconds.
    #[doc(hidden)]
    pub fn with_read_timeout(mut self, read_timeout: Duration) -> Self {
        self.read_timeout = read_timeout;
        self
    }

    /// Override the connection ceilings.
    ///
    /// The right ceiling depends on the operator's machine — chiefly its
    /// `RLIMIT_NOFILE`, which this process cannot raise for itself under the
    /// workspace's `forbid(unsafe_code)`. Both values are clamped to at least
    /// one, and the per-IP ceiling is clamped to the global one: a per-IP limit
    /// above the global limit does not describe a reachable state.
    pub fn with_connection_limits(mut self, global: usize, per_ip: usize) -> Self {
        self.max_connections = global.max(1);
        self.max_connections_per_ip = per_ip.max(1).min(self.max_connections);
        self
    }

    #[doc(hidden)]
    pub async fn bind_self_signed_for_tests(
        root: PathBuf,
        address: &str,
        port: u16,
    ) -> Result<Self, ProtocolError> {
        Self::new(root, AtpListener::bind_self_signed(address, port).await?)
    }
}

/// Production ATP server with no custom-handler or plugin surface.
pub struct StaticServer {
    config: Option<StaticServerConfig>,
    shutdown_tx: watch::Sender<bool>,
    shutdown_rx: watch::Receiver<bool>,
    subscription_budget: SubscriptionBudget,
}

impl StaticServer {
    pub fn new(config: StaticServerConfig) -> Self {
        let (shutdown_tx, shutdown_rx) = watch::channel(false);
        Self {
            config: Some(config),
            shutdown_tx,
            shutdown_rx,
            subscription_budget: SubscriptionBudget::new(MAX_SERVER_SUBSCRIPTION_BYTES),
        }
    }

    /// Bytes of live-region content currently retained, and the server-wide
    /// ceiling they are measured against.
    ///
    /// Budget exhaustion shows up to a user as a live region that quietly stops
    /// updating. Every refusal is logged, and this is the counter that lets an
    /// operator watch the pressure build beforehand instead of diagnosing it
    /// afterwards.
    pub fn subscription_memory(&self) -> (usize, usize) {
        (
            self.subscription_budget.used(),
            self.subscription_budget.limit(),
        )
    }

    pub fn shutdown_handle(&self) -> watch::Sender<bool> {
        self.shutdown_tx.clone()
    }

    pub async fn run(&mut self) -> Result<(), ProtocolError> {
        let config = self.config.take().ok_or_else(|| {
            ProtocolError::InvalidMessage("static server may only be run once".into())
        })?;
        let root = Arc::new(config.root);
        let resolver = config.resolver;
        let input_handler = config.input_handler;
        let session_resolver = config.session_resolver;
        let semaphore = Arc::new(tokio::sync::Semaphore::new(config.max_connections));

        // One reader for the whole server. Every connection subscribing to a
        // path shares its reads; a file changes once and is read once, however
        // many viewers are watching it.
        let (events_tx, events_rx) = mpsc::channel(256);
        let source: Box<dyn ChangeSource> = match NotifyChangeSource::new(events_tx) {
            Some(source) => Box::new(source),
            // Losing filesystem notification costs latency, not correctness:
            // the registry's reconcile sweep serves every watched file on its
            // own. Refusing to start would be a worse trade.
            None => Box::new(ManualChangeSource),
        };
        let (registry, watcher) =
            WatchRegistry::new(self.subscription_budget.clone(), source, events_rx);
        let registry_shutdown = self.shutdown_rx.clone();
        let registry_task = tokio::spawn(registry.run(registry_shutdown));
        let max_connections_per_ip = config.max_connections_per_ip;
        let read_timeout = config.read_timeout;
        let per_ip = Arc::new(Mutex::new(HashMap::<IpAddr, usize>::new()));
        let subscription_budget = self.subscription_budget.clone();
        let mut tasks = tokio::task::JoinSet::new();
        tracing::info!(
            address = %config.listener.local_addr()?,
            max_connections = config.max_connections,
            max_connections_per_ip = config.max_connections_per_ip,
            "static ATP server listening"
        );

        loop {
            tokio::select! {
                changed = self.shutdown_rx.changed() => {
                    if changed.is_err() || *self.shutdown_rx.borrow() { break; }
                }
                accepted = config.listener.accept_pending() => {
                    let pending = accepted?;
                    let Ok(permit) = semaphore.clone().try_acquire_owned() else {
                        tracing::warn!(peer = %pending.peer_addr(), "global connection limit reached");
                        continue;
                    };
                    let peer_ip = pending.peer_addr().ip();
                    {
                        let mut counts = per_ip.lock().unwrap_or_else(|p| p.into_inner());
                        let count = counts.entry(peer_ip).or_default();
                        if *count >= max_connections_per_ip {
                            tracing::warn!(peer_ip = %peer_ip, "per-IP connection limit reached");
                            continue;
                        }
                        *count += 1;
                    }
                    let root = root.clone();
                    let resolver = resolver.clone();
                    let input_handler = input_handler.clone();
                    let session_resolver = session_resolver.clone();
                    let counts = per_ip.clone();
                    let subscription_budget = subscription_budget.clone();
                    let connection_shutdown = self.shutdown_rx.clone();
                    let watcher = watcher.clone();
                    let peer = pending.peer_addr();
                    tasks.spawn(async move {
                        let _permit = permit;
                        // Logged for every connection, not only failing ones.
                        // Without this the log answers "why can nobody
                        // connect?" but not "is anyone connected?", which is
                        // the question an operator actually has first.
                        tracing::info!(peer = %peer, "connection accepted");
                        match tokio::time::timeout(HANDSHAKE_TIMEOUT, pending.handshake()).await {
                            Ok(Ok(stream)) => {
                                match serve_connection(
                                    stream,
                                    ConnectionContext {
                                        root: &root,
                                        resolver: resolver.as_deref(),
                                        input_handler: input_handler.as_deref(),
                                        session_resolver: session_resolver.as_deref(),
                                        peer: peer.ip(),
                                    },
                                    subscription_budget,
                                    watcher,
                                    read_timeout,
                                    connection_shutdown,
                                )
                                .await
                                {
                                    Ok(()) => tracing::info!(peer = %peer, "connection closed"),
                                    Err(error) => tracing::warn!(
                                        peer = %peer,
                                        error = %error,
                                        "connection closed with an error"
                                    ),
                                }
                            }
                            Ok(Err(error)) => tracing::warn!(
                                peer = %peer,
                                error = %error,
                                "handshake failed"
                            ),
                            // Previously silent: a client that connected and
                            // then said nothing left no trace at all.
                            Err(_) => tracing::warn!(
                                peer = %peer,
                                timeout = ?HANDSHAKE_TIMEOUT,
                                "handshake deadline reached"
                            ),
                        }
                        let mut counts = counts.lock().unwrap_or_else(|p| p.into_inner());
                        if let Some(count) = counts.get_mut(&peer_ip) {
                            *count = count.saturating_sub(1);
                            if *count == 0 { counts.remove(&peer_ip); }
                        }
                    });
                }
            }
        }

        let drain = async { while tasks.join_next().await.is_some() {} };
        if tokio::time::timeout(DRAIN_TIMEOUT, drain).await.is_err() {
            tasks.abort_all();
            tracing::warn!("graceful shutdown deadline reached");
        }
        // The registry observes the same shutdown signal and holds no client
        // sockets, so joining it is bounded by its own loop, not by any peer.
        registry_task.abort();
        Ok(())
    }
}

async fn serve_connection(
    mut stream: AtpServerStream,
    site: ConnectionContext<'_>,
    subscription_budget: SubscriptionBudget,
    watcher: LiveWatcher,
    read_timeout: Duration,
    mut shutdown: watch::Receiver<bool>,
) -> Result<(), ProtocolError> {
    // Retained subscription-table growth must be settled before the first response. Once an
    // initial UPDATE is on the wire, installing its matching entry is allocation-free.
    let mut subscriptions = try_subscription_storage()?;
    let hello_frame = recv(&mut stream, HANDSHAKE_TIMEOUT).await?;
    if hello_frame.msg_type != MessageType::Hello {
        return Err(ProtocolError::InvalidMessage("HELLO required".into()));
    }
    let hello_text = std::str::from_utf8(&hello_frame.body)
        .map_err(|_| ProtocolError::InvalidMessage("HELLO is not UTF-8".into()))?;
    let hello = HelloMessage::parse(hello_text)?;
    if hello.protocol_version != PROTOCOL_VERSION {
        send_error(&mut stream, 505, "unsupported ATP version").await?;
        return Ok(());
    }
    let capabilities = hello
        .capabilities
        .into_iter()
        .filter(|capability| SUPPORTED_CAPABILITIES.contains(&capability.as_str()))
        .collect();
    let welcome = WelcomeMessage {
        protocol_version: PROTOCOL_VERSION.into(),
        server: Some(format!("dustnetd/{}", env!("CARGO_PKG_VERSION"))),
        site_name: None,
        capabilities,
    };
    tracing::debug!(
        version = %hello.protocol_version,
        capabilities = ?welcome.capabilities,
        "negotiated"
    );
    send(
        &mut stream,
        RawFrame {
            msg_type: MessageType::Welcome,
            flags: 0,
            body: welcome.serialize()?.into_bytes(),
        },
    )
    .await?;

    // No per-connection timer. 2048 connections each holding a 250ms interval
    // is roughly eight thousand timer wakeups a second before any work happens;
    // the registry wakes a connection only when a file it watches has actually
    // changed. Capacity one, because a pending wake already says everything a
    // second one would.
    let (wake_tx, mut wake_rx) = mpsc::channel::<()>(1);
    let idle = tokio::time::sleep(read_timeout);
    tokio::pin!(idle);
    loop {
        tokio::select! {
            received = stream.recv_frame() => {
                let frame = received?;
                idle.as_mut().reset(tokio::time::Instant::now() + read_timeout);
                // Per-request detail sits at debug: one line per request is the
                // right amount of information when diagnosing a site and far
                // too much at two thousand connections, so the level is what
                // separates them rather than a sampling rule. Messages that
                // carry no detail worth naming are logged here; the rest log
                // themselves where their fields are already parsed.
                if matches!(
                    frame.msg_type,
                    MessageType::Ping | MessageType::Bye | MessageType::Input
                ) {
                    tracing::debug!(message = ?frame.msg_type, "request");
                }
                match frame.msg_type {
                    MessageType::Get => serve_get(&mut stream, site, frame).await?,
                    MessageType::Input => serve_input(&mut stream, site, frame).await?,
                    MessageType::Subscribe => {
                        if subscriptions.len() >= MAX_SUBSCRIPTIONS_PER_CONNECTION {
                            return Err(ProtocolError::InvalidMessage(
                                "subscription limit reached".into(),
                            ));
                        } else {
                            subscriptions.push(serve_subscription(
                                &mut stream,
                                site.root,
                                frame,
                                &watcher,
                                &wake_tx,
                                &subscription_budget,
                            ).await?);
                        }
                    }
                    MessageType::Unsubscribe => {
                        tracing::debug!(
                            released = subscriptions.len(),
                            "UNSUBSCRIBE"
                        );
                        subscriptions.clear();
                    }
                    // The idle deadline above was already reset by this frame
                    // arriving; that reset is the whole point of PING. PONG
                    // exists so the client can distinguish a live server from
                    // a black-holed socket that is silently absorbing writes.
                    MessageType::Ping => {
                        send(
                            &mut stream,
                            RawFrame {
                                msg_type: MessageType::Pong,
                                flags: 0,
                                body: Vec::new(),
                            },
                        )
                        .await?
                    }
                    MessageType::Bye => {
                        send(
                            &mut stream,
                            RawFrame {
                                msg_type: MessageType::ServerBye,
                                flags: 0,
                                body: Vec::new(),
                            },
                        )
                        .await?;
                        return Ok(());
                    }
                    _ => {
                        return Err(ProtocolError::InvalidMessage(
                            "unexpected client message".into(),
                        ));
                    }
                }
            }
            Some(()) = wake_rx.recv(), if !subscriptions.is_empty() => {
                flush_subscriptions(&mut stream, &mut subscriptions).await?;
            }
            _ = &mut idle => return Err(ProtocolError::Timeout),
            // Without this arm no connection observes shutdown, so a single
            // idle client guarantees the drain deadline expires and every task
            // is aborted. Leaving voluntarily turns DRAIN_TIMEOUT back into the
            // backstop it is meant to be — which matters far more at 2048
            // connections than at 64.
            changed = shutdown.changed() => {
                if changed.is_err() || *shutdown.borrow() {
                    let _ = send(
                        &mut stream,
                        RawFrame {
                            msg_type: MessageType::ServerBye,
                            flags: 0,
                            body: Vec::new(),
                        },
                    )
                    .await;
                    return Ok(());
                }
            }
        }
    }
}

/// What a connection needs to answer a request: where the site lives, the
/// optional hooks that let it generate content and accept submissions, and who
/// the peer is.
///
/// Bundled because they all travel together for the life of a connection. The
/// hooks are `None`-by-default policy; `peer` is the one piece of per-connection
/// state, and it is here rather than threaded separately because a submission
/// cannot be rate-limited per source without it.
#[derive(Clone, Copy)]
struct ConnectionContext<'a> {
    root: &'a Path,
    resolver: Option<&'a dyn crate::include::IncludeResolver>,
    input_handler: Option<&'a dyn crate::input::InputHandler>,
    session_resolver: Option<&'a dyn crate::session::SessionResolver>,
    /// The peer's address. Given to a submission handler for abuse control, and
    /// deliberately **not** to the include resolver: rendering a page has no
    /// business knowing where the reader is.
    peer: std::net::IpAddr,
}

async fn serve_get(
    stream: &mut AtpServerStream,
    site: ConnectionContext<'_>,
    frame: RawFrame,
) -> Result<(), ProtocolError> {
    let text = std::str::from_utf8(&frame.body)
        .map_err(|_| ProtocolError::InvalidMessage("GET is not UTF-8".into()))?;
    let get = GetMessage::parse(text)?;
    tracing::debug!(path = %get.path, "GET");
    // The token is resolved here and only the identity travels on. Nothing
    // below this line sees the token, which is the point of `crate::session`.
    let identity = resolve_identity(site.session_resolver, get.session.as_deref());
    serve_path(
        stream,
        site.root,
        site.resolver,
        &get.path,
        get.query.as_deref(),
        identity.as_deref(),
        Vec::new(),
        false,
    )
    .await
}

/// Serve one path, resolving includes if a resolver is installed.
///
/// Shared by GET and by an accepted submission, which is the point: a page
/// looks the same whether it was asked for or arrived at by submitting a form,
/// because it is produced by the same code.
/// Turn a presented token into an identity, or `None`.
///
/// `None` covers no token, no resolver, and a token the resolver did not
/// recognise. Collapsing those is deliberate: a caller that could tell them
/// apart would be an oracle for whether a token had ever existed.
fn resolve_identity(
    resolver: Option<&dyn crate::session::SessionResolver>,
    token: Option<&str>,
) -> Option<String> {
    resolver?.identity(token?)
}

#[allow(clippy::too_many_arguments)]
async fn serve_path(
    stream: &mut AtpServerStream,
    root: &Path,
    resolver: Option<&dyn crate::include::IncludeResolver>,
    request_path: &str,
    query: Option<&str>,
    identity: Option<&str>,
    session_directives: Vec<dustnet_core::session::SessionDirective>,
    // Whether the PAGE should name the path it is. Set for a submission, whose
    // answer is often a different page from the one submitted to, and unset for
    // a GET, where the client already knows.
    announce_location: bool,
) -> Result<(), ProtocolError> {
    let path = resolve_path(root, request_path).await?;
    let limit = if path
        .extension()
        .is_some_and(|extension| extension == "wasm")
    {
        MAX_WASM_MODULE_SIZE
    } else {
        MAX_PAGE_MESSAGE_SIZE
    };
    let file = match tokio::fs::File::open(&path).await {
        Ok(file) => file,
        Err(_) => {
            tracing::debug!(path = %request_path, "404 not found");
            send_error(stream, 404, "not found").await?;
            return Ok(());
        }
    };
    let metadata = match file.metadata().await {
        Ok(metadata) if metadata.is_file() && metadata.len() <= limit as u64 => metadata,
        _ => {
            send_error(stream, 404, "not found").await?;
            return Ok(());
        }
    };
    let owner_key = subscription_owner_key(request_path, "");
    let body = read_static_body(file, metadata.len() as usize, owner_key).await?;
    if path
        .extension()
        .is_some_and(|extension| extension == "wasm")
    {
        send(
            stream,
            RawFrame {
                msg_type: MessageType::Resource,
                flags: 0,
                body,
            },
        )
        .await
    } else {
        let content = String::from_utf8(body)
            .map_err(|_| ProtocolError::InvalidMessage("AML file is not UTF-8".into()))?;

        // Substitute [include] placeholders before anything reads the content.
        // `has_live_regions` in particular must see the resolved page: a
        // resolver may emit a [live] region, and a flag computed from the
        // authored source would leave the client never subscribing to it.
        let content = match resolver {
            Some(resolver) => {
                let request = crate::include::IncludeRequest {
                    path: request_path,
                    query,
                    identity,
                };
                let resolved = crate::include::resolve_page(&content, resolver, &request)?;
                // A resolver can produce more than a page may carry. Refuse
                // rather than truncate: half a page of stories is a worse
                // answer than an error naming the cause.
                if resolved.len() > MAX_PAGE_MESSAGE_SIZE {
                    tracing::warn!(
                        path = %request_path,
                        bytes = resolved.len(),
                        limit = MAX_PAGE_MESSAGE_SIZE,
                        "resolved page exceeds the page limit"
                    );
                    send_error(stream, 500, "resolved page too large").await?;
                    return Ok(());
                }
                resolved
            }
            None => content,
        };

        let has_live_regions = content.contains("[live");
        // Asked of the stream, not assumed: attaching a `Path` a client never
        // negotiated makes the frame unsendable, so an older client would get
        // no page at all instead of the page it has always got.
        let announced = (announce_location && stream.supports_page_path()).then(|| match query {
            Some(query) => format!("{request_path}?{query}"),
            None => request_path.to_string(),
        });
        let page = PageMessage {
            content,
            flags: PageFlags {
                cacheable: true,
                has_live_regions,
                ..PageFlags::default()
            },
            path: announced,
            session_directives,
        };
        let (body, flags) = page.encode_body()?;
        send(
            stream,
            RawFrame {
                msg_type: MessageType::Page,
                flags,
                body,
            },
        )
        .await
    }
}

/// Handle a form submission.
///
/// Without a handler this is the 405 it always was, so a server that installs
/// none behaves exactly as it did before submissions were possible.
///
/// An accepted submission answers with the target *page*, not a redirect: a
/// REDIRECT may carry no metadata, so it cannot also issue the session a login
/// grants, and it would cost a second round trip. The page is rendered through
/// the same `serve_path` a GET uses, so there is one path that generates a page
/// whether or not a submission preceded it.
///
/// Because the answer may be a different page from the one submitted to, it
/// names itself: the PAGE carries a `Path`, and the client adopts it as its
/// location. That is what makes a login land on the front page rather than
/// leaving the person on `/login` with the front page drawn on it, one reload
/// away from the form they just completed.
async fn serve_input(
    stream: &mut AtpServerStream,
    site: ConnectionContext<'_>,
    frame: RawFrame,
) -> Result<(), ProtocolError> {
    let Some(handler) = site.input_handler else {
        send_error(stream, 405, "server accepts no form submissions").await?;
        return Ok(());
    };

    let text = std::str::from_utf8(&frame.body)
        .map_err(|_| ProtocolError::InvalidMessage("INPUT is not UTF-8".into()))?;
    // `InputMessage::parse` enforces MAX_INPUT_MESSAGE_SIZE, so the body is
    // bounded before anything here allocates from it.
    let input = InputMessage::parse(text)?;

    let (path, query) = crate::input::split_query(&input.path);
    let fields = crate::input::FormFields::parse(&input.form_data);
    tracing::debug!(path, fields = fields.len(), "INPUT");

    let identity = resolve_identity(site.session_resolver, input.session.as_deref());
    let request = crate::input::InputRequest {
        path,
        query,
        fields: &fields,
        identity: identity.as_deref(),
        peer: site.peer,
    };

    match handler.handle(&request) {
        crate::input::InputOutcome::Render {
            path,
            query,
            session,
        } => {
            tracing::info!(%path, "submission accepted");
            // Revoke here, not in the handler: a handler is told the identity
            // and not the token, so it cannot name its own session to end it.
            // Doing it here ends exactly the session that was presented.
            if session.clears()
                && let (Some(resolver), Some(token)) =
                    (site.session_resolver, input.session.as_deref())
            {
                resolver.revoke(token);
            }
            // The response is rendered for whoever holds the session *after*
            // the handler ran, not before it. Where a handler granted one, the
            // token it issued is resolved through the same `SessionResolver` a
            // GET would use — so a login answers with the logged-in page
            // instead of showing the logged-out nav for one page, and it does
            // so without taking the handler's word about who it authenticated:
            // the resolver is still the only thing that turns a token into a
            // name, and it refuses one that is unknown, expired or revoked.
            let identity = match (site.session_resolver, session.token()) {
                (Some(resolver), Some(granted)) => resolver.identity(granted),
                _ => identity,
            };
            serve_path(
                stream,
                site.root,
                site.resolver,
                &path,
                query.as_deref(),
                identity.as_deref(),
                session.into_directives(),
                true,
            )
            .await
        }
        crate::input::InputOutcome::Rejected(reason) => {
            // Logged at the same level as an acceptance. A submission refused
            // is as much a thing an operator wants to see as one taken.
            // Logged in full, sent trimmed: the operator wants the diagnostic
            // and the reader wants a sentence they can actually see.
            tracing::info!(path, reason = %reason, "submission refused");
            send_error(stream, 400, &crate::input::short_reason(&reason)).await?;
            Ok(())
        }
    }
}

async fn read_static_body(
    mut file: tokio::fs::File,
    expected_len: usize,
    owner_key: u64,
) -> Result<Vec<u8>, ProtocolError> {
    let requested = expected_len
        .checked_add(1)
        .ok_or(ProtocolError::ResourceExhausted {
            requested: usize::MAX,
        })?;
    if reject_allocation_at(ServerAllocationSite::StaticBody, owner_key) {
        return Err(ProtocolError::ResourceExhausted { requested });
    }
    let mut body = allocate_frame_body(requested)?;
    let mut filled = 0;
    loop {
        let Some(unfilled) = body.get_mut(filled..) else {
            break;
        };
        if unfilled.is_empty() {
            break;
        }
        let read = file.read(unfilled).await?;
        if read == 0 {
            break;
        }
        filled += read;
    }
    if filled > expected_len {
        return Err(ProtocolError::InvalidMessage(
            "static file changed while it was being read".into(),
        ));
    }
    body.truncate(filled);
    Ok(body)
}

async fn serve_subscription(
    stream: &mut AtpServerStream,
    root: &Path,
    frame: RawFrame,
    watcher: &LiveWatcher,
    wake: &mpsc::Sender<()>,
    budget: &SubscriptionBudget,
) -> Result<StaticSubscription, ProtocolError> {
    let text = std::str::from_utf8(&frame.body)
        .map_err(|_| ProtocolError::InvalidMessage("SUBSCRIBE is not UTF-8".into()))?;
    let subscription = SubscribeMessage::parse(text)?;
    tracing::debug!(
        path = %subscription.path,
        region = %subscription.region,
        mode = ?subscription.mode,
        "SUBSCRIBE"
    );
    let owner_key = subscription_owner_key(&subscription.path, &subscription.region);
    let resolved_path = resolve_path(root, &subscription.path).await?;
    let metadata_bytes = resolved_path
        .as_os_str()
        .len()
        .checked_add(subscription.region.len())
        .ok_or(ProtocolError::ResourceExhausted {
            requested: usize::MAX,
        })?;
    let mut metadata_lease = budget.reserve(metadata_bytes)?;
    let path = try_owned_subscription_path(&resolved_path, owner_key)?;
    let region = try_owned_subscription_string(
        &subscription.region,
        ServerAllocationSite::Region,
        owner_key,
    )?;
    let retained_metadata_bytes =
        path.capacity()
            .checked_add(region.capacity())
            .ok_or(ProtocolError::ResourceExhausted {
                requested: usize::MAX,
            })?;
    metadata_lease.try_resize(retained_metadata_bytes)?;
    let metadata = tokio::fs::metadata(&path).await?;
    if !metadata.is_file() {
        return Err(ProtocolError::InvalidMessage(
            "invalid live update file".into(),
        ));
    }

    // Attaching reads the file only if it has moved since anyone last read it,
    // so a reconnecting subscriber is never handed a staler generation than the
    // moment it asked, and a second subscriber to a live path costs a stat.
    let attached = watcher
        .attach(
            try_owned_subscription_path(&path, owner_key)?,
            wake.clone(),
            owner_key,
        )
        .await?;

    // The initial value is always a complete replace: the subscriber has no
    // baseline to append to yet.
    UpdateMessage::validate_update_parts(&region, attached.current.text.len())?;
    let candidate = StaticSubscription {
        region,
        mode: subscription.mode,
        baseline: attached.current,
        updates: attached.updates,
        _metadata_lease: metadata_lease,
    };
    send_update(stream, &candidate.region, &candidate.baseline.text, false).await?;
    Ok(candidate)
}

/// Send every subscription whatever it has not yet seen.
///
/// Called when the registry wakes this connection. The wake carries no payload,
/// so this reconciles all of the connection's subscriptions by pointer identity
/// — which is why a dropped wake is harmless: a full wake channel already means
/// "you have unhandled work".
///
/// Every failure here is either terminal for the connection or permanent for
/// this generation. That is deliberate. The old 250ms tick let a failure be a
/// `continue` that would be retried a quarter-second later; without a tick, a
/// retryable failure skipped here would never be retried at all. Retryable
/// failures now live in the watcher's read path, where the reconcile timer is
/// the retry.
async fn flush_subscriptions(
    stream: &mut AtpServerStream,
    subscriptions: &mut [StaticSubscription],
) -> Result<(), ProtocolError> {
    for subscription in subscriptions {
        // Clone out of the guard in its own scope: holding a `watch::Ref`
        // across the await below would block the registry's `send_replace` and
        // deadlock the whole fan-out.
        let next = {
            let guard = subscription.updates.borrow();
            Arc::clone(&guard)
        };
        if Arc::ptr_eq(&next, &subscription.baseline) {
            continue;
        }
        let (wire_content, delta) = if subscription.mode == SubscribeMode::Delta {
            match next.text.strip_prefix(&subscription.baseline.text) {
                Some(suffix) => (suffix, true),
                None => (next.text.as_str(), false),
            }
        } else {
            (next.text.as_str(), false)
        };
        // Permanent for this generation, not transient: the region name is
        // fixed and the content will not shrink on a retry.
        if UpdateMessage::validate_update_parts(&subscription.region, wire_content.len()).is_err() {
            tracing::warn!(
                region = %subscription.region,
                bytes = wire_content.len(),
                "live update not sent: body exceeds the maximum update size"
            );
            subscription.baseline = next;
            continue;
        }
        send_update(stream, &subscription.region, wire_content, delta).await?;
        // Advances only after a successful send, so a subscriber that missed a
        // generation resynchronises on the next one.
        subscription.baseline = next;
    }
    Ok(())
}

fn try_owned_subscription_path(path: &Path, owner_key: u64) -> Result<PathBuf, ProtocolError> {
    let requested = path.as_os_str().len();
    if reject_allocation_at(ServerAllocationSite::Path, owner_key) {
        return Err(ProtocolError::ResourceExhausted { requested });
    }
    let mut owned = PathBuf::new();
    owned
        .try_reserve_exact(requested)
        .map_err(|_| ProtocolError::ResourceExhausted { requested })?;
    owned.push(path);
    Ok(owned)
}

fn try_owned_subscription_string(
    value: &str,
    site: ServerAllocationSite,
    owner_key: u64,
) -> Result<String, ProtocolError> {
    let requested = value.len();
    if reject_allocation_at(site, owner_key) {
        return Err(ProtocolError::ResourceExhausted { requested });
    }
    let mut owned = String::new();
    owned
        .try_reserve_exact(requested)
        .map_err(|_| ProtocolError::ResourceExhausted { requested })?;
    owned.push_str(value);
    Ok(owned)
}

pub(crate) async fn read_subscription_content(
    path: &Path,
    expected_len: usize,
    owner_key: u64,
    lease: &mut SubscriptionLease,
) -> Result<String, ProtocolError> {
    let requested = expected_len
        .checked_add(1)
        .ok_or(ProtocolError::ResourceExhausted {
            requested: usize::MAX,
        })?;
    if reject_allocation_at(ServerAllocationSite::Content, owner_key) {
        return Err(ProtocolError::ResourceExhausted { requested });
    }
    let mut bytes = Vec::new();
    bytes
        .try_reserve_exact(requested)
        .map_err(|_| ProtocolError::ResourceExhausted { requested })?;
    bytes.resize(requested, 0);
    let mut file = tokio::fs::File::open(path).await?;
    let mut filled = 0;
    loop {
        let Some(unfilled) = bytes.get_mut(filled..) else {
            break;
        };
        if unfilled.is_empty() {
            break;
        }
        let read = file.read(unfilled).await?;
        if read == 0 {
            break;
        }
        filled += read;
    }
    if filled > expected_len {
        return Err(ProtocolError::InvalidMessage(
            "live update changed while it was being read".into(),
        ));
    }
    let Some(read_bytes) = bytes.get(..filled) else {
        return Err(ProtocolError::InvalidMessage(
            "live update read past its own buffer".into(),
        ));
    };
    let text = std::str::from_utf8(read_bytes)
        .map_err(|_| ProtocolError::InvalidMessage("live update is not UTF-8".into()))?;
    let mut content = String::new();
    content
        .try_reserve_exact(filled)
        .map_err(|_| ProtocolError::ResourceExhausted { requested: filled })?;
    content.push_str(text);
    let read_peak = bytes.capacity().checked_add(content.capacity()).ok_or(
        ProtocolError::ResourceExhausted {
            requested: usize::MAX,
        },
    )?;
    lease.ensure_at_least(read_peak)?;
    Ok(content)
}

/// Map a request path onto a candidate file path without touching the disk.
///
/// Purely lexical: no syscall, so it is safe to run on a runtime worker. It
/// establishes nothing about whether the result is inside the site root —
/// symlinks are resolved by `resolve_path`, which is the only function that may
/// conclude a path is safe to serve.
fn resolve_path_lexical(root: &Path, request: &str) -> Result<PathBuf, ProtocolError> {
    let relative = request.trim_start_matches('/');
    let mut result = root.to_path_buf();
    for component in Path::new(relative).components() {
        match component {
            Component::Normal(part) => result.push(part),
            Component::CurDir => {}
            _ => return Err(ProtocolError::InvalidMessage("invalid static path".into())),
        }
    }
    if request.ends_with('/') || relative.is_empty() {
        result.push("index.aml");
    }
    if result.extension().is_none() {
        result.set_extension("aml");
    }
    Ok(result)
}

/// Resolve a request path to a file path that is proven to live inside `root`.
///
/// `root` must already be canonical; `StaticServerConfig::new` canonicalises it
/// once at bind time, where blocking costs nothing. This used to canonicalise
/// the root again on every request and probe `Path::exists` first — three
/// synchronous filesystem calls on a runtime worker thread for every GET and
/// every SUBSCRIBE, which is a hard ceiling on concurrent connections. One
/// async call replaces all three: `canonicalize` already fails for a path that
/// does not exist, so the probe was only ever telling us what it would tell us.
///
/// A path that does not resolve is returned unchanged rather than rejected. It
/// is not an escape attempt, it is a miss, and the caller's `open` turns it into
/// the 404 it always was.
async fn resolve_path(root: &Path, request: &str) -> Result<PathBuf, ProtocolError> {
    let candidate = resolve_path_lexical(root, request)?;
    let Ok(canonical) = tokio::fs::canonicalize(&candidate).await else {
        return Ok(candidate);
    };
    if !canonical.starts_with(root) {
        return Err(ProtocolError::InvalidMessage(
            "static path escapes the configured site root".into(),
        ));
    }
    Ok(canonical)
}

async fn recv(stream: &mut AtpServerStream, timeout: Duration) -> Result<RawFrame, ProtocolError> {
    tokio::time::timeout(timeout, stream.recv_frame())
        .await
        .map_err(|_| ProtocolError::Timeout)?
}

async fn send(stream: &mut AtpServerStream, frame: RawFrame) -> Result<(), ProtocolError> {
    send_with_timeout(stream, &frame, WRITE_TIMEOUT).await
}

/// Send an UPDATE from its parts under the same write deadline as any other
/// frame, so `stalled_frame_write_is_bounded` still covers the fan-out path.
async fn send_update_with_timeout(
    stream: &mut AtpServerStream,
    region: &str,
    content: &str,
    delta: bool,
    timeout: Duration,
) -> Result<(), ProtocolError> {
    tokio::time::timeout(timeout, stream.send_update_parts(region, content, delta))
        .await
        .map_err(|_| ProtocolError::Timeout)?
}

async fn send_update(
    stream: &mut AtpServerStream,
    region: &str,
    content: &str,
    delta: bool,
) -> Result<(), ProtocolError> {
    send_update_with_timeout(stream, region, content, delta, WRITE_TIMEOUT).await
}

async fn send_with_timeout(
    stream: &mut AtpServerStream,
    frame: &RawFrame,
    timeout: Duration,
) -> Result<(), ProtocolError> {
    tokio::time::timeout(timeout, stream.send_frame(frame))
        .await
        .map_err(|_| ProtocolError::Timeout)?
}

async fn send_error(
    stream: &mut AtpServerStream,
    code: u16,
    message: &str,
) -> Result<(), ProtocolError> {
    let error = ErrorMessage {
        code,
        message: Some(message.into()),
    };
    send(
        stream,
        RawFrame {
            msg_type: MessageType::Error,
            flags: 0,
            body: error.serialize()?.into_bytes(),
        },
    )
    .await
}

#[cfg(test)]
mod tests {
    use super::*;
    use dustnet_core::protocol::frame::{allocate_frame_body, decode_header, encode_frame};
    use dustnet_core::protocol::message::UpdateFlags;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::TcpStream;

    /// A subscription with no real watcher behind it, for tests that only care
    /// about the table that holds them.
    fn placeholder_subscription(region: String, budget: &SubscriptionBudget) -> StaticSubscription {
        let (updates, receiver) =
            watch::channel(live_watch::LiveGeneration::empty_for_tests(budget).unwrap());
        // The sender must outlive the receiver for `borrow` to stay valid.
        std::mem::forget(updates);
        let baseline = {
            let guard = receiver.borrow();
            Arc::clone(&guard)
        };
        StaticSubscription {
            region,
            mode: SubscribeMode::Replace,
            baseline,
            updates: receiver,
            _metadata_lease: budget.reserve(0).unwrap(),
        }
    }

    #[test]
    fn static_subscription_backing_rejection_precedes_connection_state() {
        let rejection = AllocationRejectionGuard::at(ServerAllocationSite::Backing, 0);
        assert!(matches!(
            try_subscription_storage(),
            Err(ProtocolError::ResourceExhausted { .. })
        ));
        drop(rejection);
        let mut subscriptions = try_subscription_storage().unwrap();
        assert!(subscriptions.is_empty());
        let capacity = subscriptions.capacity();
        let allocation = subscriptions.as_ptr();
        let budget = SubscriptionBudget::new(1024);
        for index in 0..MAX_SUBSCRIPTIONS_PER_CONNECTION {
            subscriptions.push(placeholder_subscription(format!("region-{index}"), &budget));
        }
        assert_eq!(subscriptions.capacity(), capacity);
        assert_eq!(subscriptions.as_ptr(), allocation);
    }

    /// Canonicalise a tempdir for use as a site root.
    ///
    /// Production canonicalises the root once in `StaticServerConfig::new`, and
    /// `resolve_path` relies on that. Tests that drive `serve_subscription` and
    /// `poll_subscriptions` directly bypass the config, so they must establish
    /// the same invariant — on macOS a tempdir is `/var/...` whose canonical
    /// form is `/private/var/...`, and comparing the two rejects every path.
    fn site_root(directory: &tempfile::TempDir) -> PathBuf {
        std::fs::canonicalize(directory.path()).unwrap()
    }

    struct RawClient(TcpStream);

    impl RawClient {
        async fn connect(address: std::net::SocketAddr) -> Self {
            Self(TcpStream::connect(address).await.unwrap())
        }

        async fn send(&mut self, frame: RawFrame) {
            self.0
                .write_all(&encode_frame(&frame).unwrap())
                .await
                .unwrap();
        }

        async fn send_fragmented(&mut self, frame: RawFrame) {
            for byte in encode_frame(&frame).unwrap() {
                self.0.write_all(&[byte]).await.unwrap();
                tokio::task::yield_now().await;
            }
        }

        async fn receive(&mut self) -> RawFrame {
            let mut header = [0_u8; dustnet_core::protocol::HEADER_SIZE];
            self.0.read_exact(&mut header).await.unwrap();
            let (length, msg_type, flags) = decode_header(&header).unwrap();
            let mut body = allocate_frame_body(length as usize).unwrap();
            self.0.read_exact(&mut body).await.unwrap();
            RawFrame {
                msg_type,
                flags,
                body,
            }
        }

        async fn handshake(&mut self) {
            self.send(RawFrame {
                msg_type: MessageType::Hello,
                flags: 0,
                body: b"HELLO/0.2\nCapabilities: live-updates\n".to_vec(),
            })
            .await;
            assert_eq!(self.receive().await.msg_type, MessageType::Welcome);
        }
    }

    fn subscription_frame(mode: SubscribeMode) -> RawFrame {
        let mode = if mode == SubscribeMode::Delta {
            "Mode: delta\n"
        } else {
            ""
        };
        RawFrame {
            msg_type: MessageType::Subscribe,
            flags: 0,
            body: format!("SUBSCRIBE /ticker.aml\nRegion: ticker\n{mode}").into_bytes(),
        }
    }

    async fn negotiated_server_pair() -> (AtpServerStream, RawClient) {
        let listener = AtpListener::bind_plain("127.0.0.1", 0).await.unwrap();
        let address = listener.local_addr().unwrap();
        let mut client = RawClient::connect(address).await;
        let pending = listener.accept_pending().await.unwrap();
        let mut server = pending.handshake().await.unwrap();
        client
            .send(RawFrame {
                msg_type: MessageType::Hello,
                flags: 0,
                body: b"HELLO/0.2\nCapabilities: live-updates\n".to_vec(),
            })
            .await;
        assert_eq!(
            server.recv_frame().await.unwrap().msg_type,
            MessageType::Hello
        );
        send(
            &mut server,
            RawFrame {
                msg_type: MessageType::Welcome,
                flags: 0,
                body: b"WELCOME/0.2\nCapabilities: live-updates\n".to_vec(),
            },
        )
        .await
        .unwrap();
        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
        (server, client)
    }

    /// A registry running in the background with intervals short enough that a
    /// file change is observed promptly.
    ///
    /// The change source observes nothing on purpose: reconciliation alone must
    /// serve every watched file, so driving these tests through it also proves
    /// the fallback path the real watcher degrades to.
    fn test_watcher(budget: &SubscriptionBudget) -> (LiveWatcher, watch::Sender<bool>) {
        let (events_tx, events_rx) = mpsc::channel(64);
        // Hold the sender open for the registry's lifetime.
        std::mem::forget(events_tx);
        let (registry, watcher) =
            WatchRegistry::new(budget.clone(), Box::new(ManualChangeSource), events_rx);
        let (shutdown_tx, shutdown_rx) = watch::channel(false);
        tokio::spawn(
            registry
                .with_intervals(Duration::from_millis(1), Duration::from_millis(5))
                .run(shutdown_rx),
        );
        (watcher, shutdown_tx)
    }

    async fn subscribe_for_test(
        server: &mut AtpServerStream,
        root: &Path,
        watcher: &LiveWatcher,
        budget: &SubscriptionBudget,
        mode: SubscribeMode,
    ) -> Result<(StaticSubscription, mpsc::Receiver<()>), ProtocolError> {
        let (wake_tx, wake_rx) = mpsc::channel(1);
        let subscription = serve_subscription(
            server,
            root,
            subscription_frame(mode),
            watcher,
            &wake_tx,
            budget,
        )
        .await?;
        Ok((subscription, wake_rx))
    }

    /// Wait for a wake, then flush. Mirrors the connection loop's own arm.
    async fn wake_and_flush(
        server: &mut AtpServerStream,
        subscriptions: &mut [StaticSubscription],
        wake: &mut mpsc::Receiver<()>,
    ) -> Result<(), ProtocolError> {
        let _ = tokio::time::timeout(Duration::from_secs(2), wake.recv()).await;
        flush_subscriptions(server, subscriptions).await
    }

    #[tokio::test]
    async fn static_subscription_complete_body_limit_and_release_are_exact() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("ticker.aml");
        let prefix = "UPDATE \n\n".len() + "ticker".len();
        let exact = "x".repeat(dustnet_core::protocol::MAX_LIVE_UPDATE_SIZE - prefix);
        std::fs::write(&path, &exact).unwrap();
        let budget = SubscriptionBudget::new(8 * dustnet_core::protocol::MAX_LIVE_UPDATE_SIZE);
        let (watcher, _shutdown) = test_watcher(&budget);
        let (mut server, mut client) = negotiated_server_pair().await;

        let (subscription, _wake) = subscribe_for_test(
            &mut server,
            &site_root(&directory),
            &watcher,
            &budget,
            SubscribeMode::Replace,
        )
        .await
        .unwrap();
        let update = client.receive().await;
        assert_eq!(
            update.body.len(),
            dustnet_core::protocol::MAX_LIVE_UPDATE_SIZE,
            "a body at exactly the limit must still be sent"
        );
        assert_eq!(subscription.baseline.text, exact);
        // The subscription itself now retains only its region; the content is
        // charged once by the generation it shares.
        assert!(
            budget.used() >= subscription.region.capacity(),
            "the subscription retains its region; the content is charged once \
             by the generation it shares"
        );
        drop(subscription);

        // A file one byte too large cannot be framed for any subscriber, so it
        // must never be published at all. Asserting that it never appears is
        // the property; asserting *when* the registry notices would be a race.
        let oversize = "x".repeat(exact.len() + 1);
        std::fs::write(&path, &oversize).unwrap();
        for _ in 0..5 {
            if let Ok((subscription, _wake)) = subscribe_for_test(
                &mut server,
                &site_root(&directory),
                &watcher,
                &budget,
                SubscribeMode::Replace,
            )
            .await
            {
                assert_ne!(
                    subscription.baseline.text, oversize,
                    "a file too large to frame must never reach a subscriber"
                );
                let _ = tokio::time::timeout(Duration::from_millis(50), client.receive()).await;
            }
            tokio::time::sleep(Duration::from_millis(20)).await;
        }
    }

    #[tokio::test]
    async fn subscription_owner_keyed_allocation_rejection_rolls_back_every_candidate() {
        let directory = tempfile::tempdir().unwrap();
        std::fs::write(directory.path().join("ticker.aml"), "first").unwrap();
        let owner = subscription_owner_key("/ticker.aml", "ticker");
        for site in [ServerAllocationSite::Path, ServerAllocationSite::Region] {
            let budget = SubscriptionBudget::new(1024 * 1024);
            let (watcher, _shutdown) = test_watcher(&budget);
            let (mut server, mut client) = negotiated_server_pair().await;
            let rejection = AllocationRejectionGuard::at(site, owner);
            assert!(
                matches!(
                    subscribe_for_test(
                        &mut server,
                        &site_root(&directory),
                        &watcher,
                        &budget,
                        SubscribeMode::Delta,
                    )
                    .await,
                    Err(ProtocolError::ResourceExhausted { .. })
                ),
                "{site:?} must refuse the subscription"
            );
            drop(rejection);
            assert_eq!(budget.used(), 0, "candidate leaked at {site:?}");
            assert!(
                tokio::time::timeout(Duration::from_millis(20), client.receive())
                    .await
                    .is_err(),
                "a refused subscription must not have sent anything"
            );
        }
    }

    #[tokio::test]
    async fn initial_subscription_send_failure_drops_complete_candidate() {
        let directory = tempfile::tempdir().unwrap();
        std::fs::write(directory.path().join("ticker.aml"), "first").unwrap();
        let budget = SubscriptionBudget::new(1024 * 1024);
        let (watcher, _shutdown) = test_watcher(&budget);
        let (mut server, _client) = negotiated_server_pair().await;
        assert!(
            server
                .send_frame(&RawFrame {
                    msg_type: MessageType::Update,
                    flags: 0,
                    body: b"invalid".to_vec(),
                })
                .await
                .is_err()
        );

        let attempt = subscribe_for_test(
            &mut server,
            &site_root(&directory),
            &watcher,
            &budget,
            SubscribeMode::Delta,
        )
        .await;
        assert!(
            attempt.is_err(),
            "a poisoned stream must fail the subscribe"
        );
        drop(attempt);
        // The per-connection lease is returned; the shared generation is
        // released once the registry reaps an entry nobody is listening to.
        let deadline = std::time::Instant::now() + Duration::from_secs(2);
        while budget.used() != 0 {
            assert!(
                std::time::Instant::now() < deadline,
                "a failed subscribe leaked {} bytes",
                budget.used()
            );
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    }

    /// The property the old polling test protected, restated for a shared read:
    /// a subscriber's delta baseline advances only on a successful send, so a
    /// missed generation resynchronises itself instead of corrupting the
    /// subscriber's view.
    #[tokio::test]
    async fn shared_generation_pressure_preserves_the_delta_baseline() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("ticker.aml");
        std::fs::write(&path, "first").unwrap();
        let budget = SubscriptionBudget::new(1024 * 1024);
        let (watcher, _shutdown) = test_watcher(&budget);
        let (mut server, mut client) = negotiated_server_pair().await;
        let (subscription, mut wake) = subscribe_for_test(
            &mut server,
            &site_root(&directory),
            &watcher,
            &budget,
            SubscribeMode::Delta,
        )
        .await
        .unwrap();
        let _ = client.receive().await;
        let mut subscriptions = vec![subscription];

        // An unsendable file must not advance anyone's baseline.
        let prefix = "UPDATE \n\n".len() + subscriptions[0].region.len();
        std::fs::write(
            &path,
            "x".repeat(dustnet_core::protocol::MAX_LIVE_UPDATE_SIZE - prefix + 1),
        )
        .unwrap();
        tokio::time::sleep(Duration::from_millis(50)).await;
        flush_subscriptions(&mut server, &mut subscriptions)
            .await
            .unwrap();
        assert_eq!(subscriptions[0].baseline.text, "first");
        assert!(
            tokio::time::timeout(Duration::from_millis(50), client.receive())
                .await
                .is_err(),
            "an unsendable generation must produce no wire traffic"
        );

        // A sendable successor resumes deltas from the preserved baseline.
        std::fs::write(&path, "first-second").unwrap();
        wake_and_flush(&mut server, &mut subscriptions, &mut wake)
            .await
            .unwrap();
        let update = client.receive().await;
        assert_eq!(update.flags, UpdateFlags { delta: true }.to_bits());
        assert_eq!(
            UpdateMessage::parse(std::str::from_utf8(&update.body).unwrap())
                .unwrap()
                .content,
            "-second",
            "the delta must be computed against what this subscriber last saw"
        );
        assert_eq!(subscriptions[0].baseline.text, "first-second");

        // A flush with nothing new sends nothing.
        flush_subscriptions(&mut server, &mut subscriptions)
            .await
            .unwrap();
        assert!(
            tokio::time::timeout(Duration::from_millis(50), client.receive())
                .await
                .is_err()
        );

        // Divergent content falls back to a complete replace.
        std::fs::write(&path, "replacement").unwrap();
        wake_and_flush(&mut server, &mut subscriptions, &mut wake)
            .await
            .unwrap();
        let update = client.receive().await;
        assert_eq!(update.flags, 0, "a divergent value is a full replace");
        assert_eq!(
            UpdateMessage::parse(std::str::from_utf8(&update.body).unwrap())
                .unwrap()
                .content,
            "replacement"
        );
        assert_eq!(subscriptions[0].baseline.text, "replacement");
    }

    /// The claim the whole change exists to make, at the connection level: two
    /// connections watching one path are served by one read, and each still
    /// gets the encoding its own subscription asked for. Sharing the read must
    /// not collapse into sharing the message.
    #[tokio::test]
    async fn two_connections_share_one_read_with_independent_modes() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("ticker.aml");
        std::fs::write(&path, "first").unwrap();
        let budget = SubscriptionBudget::new(1024 * 1024);
        let (watcher, _shutdown) = test_watcher(&budget);

        let (mut delta_server, mut delta_client) = negotiated_server_pair().await;
        let (delta_subscription, mut delta_wake) = subscribe_for_test(
            &mut delta_server,
            &site_root(&directory),
            &watcher,
            &budget,
            SubscribeMode::Delta,
        )
        .await
        .unwrap();
        let _ = delta_client.receive().await;

        let (mut replace_server, mut replace_client) = negotiated_server_pair().await;
        let (replace_subscription, mut replace_wake) = subscribe_for_test(
            &mut replace_server,
            &site_root(&directory),
            &watcher,
            &budget,
            SubscribeMode::Replace,
        )
        .await
        .unwrap();
        let _ = replace_client.receive().await;

        assert!(
            Arc::ptr_eq(&delta_subscription.baseline, &replace_subscription.baseline),
            "both connections must be looking at the very same generation"
        );
        let shared = budget.used();

        let mut delta_subscriptions = vec![delta_subscription];
        let mut replace_subscriptions = vec![replace_subscription];
        std::fs::write(&path, "first-second").unwrap();

        wake_and_flush(&mut delta_server, &mut delta_subscriptions, &mut delta_wake)
            .await
            .unwrap();
        wake_and_flush(
            &mut replace_server,
            &mut replace_subscriptions,
            &mut replace_wake,
        )
        .await
        .unwrap();

        let delta_update = delta_client.receive().await;
        assert_eq!(delta_update.flags, UpdateFlags { delta: true }.to_bits());
        assert_eq!(
            UpdateMessage::parse(std::str::from_utf8(&delta_update.body).unwrap())
                .unwrap()
                .content,
            "-second",
            "the delta subscriber gets a suffix"
        );

        let replace_update = replace_client.receive().await;
        assert_eq!(replace_update.flags, 0);
        assert_eq!(
            UpdateMessage::parse(std::str::from_utf8(&replace_update.body).unwrap())
                .unwrap()
                .content,
            "first-second",
            "the replace subscriber gets the whole value, from the same read"
        );

        assert!(
            Arc::ptr_eq(
                &delta_subscriptions[0].baseline,
                &replace_subscriptions[0].baseline
            ),
            "one read served both subscribers"
        );
        // Two subscribers of one path cost one copy of its content, so the
        // second subscriber adds only its own region.
        assert!(
            budget.used() < shared + "first-second".len() * 2,
            "content appears to have been charged per subscriber"
        );
    }

    #[tokio::test]
    async fn read_and_send_failures_preserve_the_delta_baseline() {
        let directory = tempfile::tempdir().unwrap();
        let path = directory.path().join("ticker.aml");
        std::fs::write(&path, "first").unwrap();
        let budget = SubscriptionBudget::new(1024 * 1024);
        let (watcher, _shutdown) = test_watcher(&budget);
        let (mut server, mut client) = negotiated_server_pair().await;
        let (subscription, _wake) = subscribe_for_test(
            &mut server,
            &site_root(&directory),
            &watcher,
            &budget,
            SubscribeMode::Delta,
        )
        .await
        .unwrap();
        let _ = client.receive().await;
        let mut subscriptions = vec![subscription];

        // A file that is not UTF-8 cannot be published at all.
        std::fs::write(&path, [0xff, 0xfe]).unwrap();
        tokio::time::sleep(Duration::from_millis(50)).await;
        flush_subscriptions(&mut server, &mut subscriptions)
            .await
            .unwrap();
        assert_eq!(subscriptions[0].baseline.text, "first");

        // A send failure must leave the baseline where it was, so the missed
        // generation is re-sent rather than skipped.
        std::fs::write(&path, "first-after-failure").unwrap();
        tokio::time::sleep(Duration::from_millis(50)).await;
        assert!(
            server
                .send_frame(&RawFrame {
                    msg_type: MessageType::Update,
                    flags: 0,
                    body: b"invalid".to_vec(),
                })
                .await
                .is_err()
        );
        assert!(
            flush_subscriptions(&mut server, &mut subscriptions)
                .await
                .is_err()
        );
        assert_eq!(subscriptions[0].baseline.text, "first");
        drop(client);
    }

    #[tokio::test]
    async fn static_subscription_polls_delta_and_unsubscribe_stops_updates() {
        let directory = tempfile::tempdir().unwrap();
        let live_path = directory.path().join("ticker.aml");
        std::fs::write(&live_path, "first").unwrap();
        let config = StaticServerConfig::bind_plaintext_loopback(
            directory.path().to_path_buf(),
            "127.0.0.1",
            0,
        )
        .await
        .unwrap();
        let address = config.local_addr().unwrap();
        let mut server = StaticServer::new(config);
        let shutdown = server.shutdown_handle();
        let task = tokio::spawn(async move { server.run().await });

        let mut client = RawClient::connect(address).await;
        client.handshake().await;
        client
            .send(RawFrame {
                msg_type: MessageType::Subscribe,
                flags: 0,
                body: b"SUBSCRIBE /ticker.aml\nRegion: ticker\nMode: delta\n".to_vec(),
            })
            .await;
        let initial = client.receive().await;
        assert_eq!(initial.msg_type, MessageType::Update);
        assert_eq!(initial.flags, 0);
        assert!(String::from_utf8(initial.body).unwrap().ends_with("first"));

        std::fs::write(&live_path, "first-second").unwrap();
        let changed = tokio::time::timeout(Duration::from_secs(2), client.receive())
            .await
            .unwrap();
        assert_eq!(changed.flags, 1);
        assert!(
            String::from_utf8(changed.body)
                .unwrap()
                .ends_with("-second")
        );

        client
            .send(RawFrame {
                msg_type: MessageType::Unsubscribe,
                flags: 0,
                body: Vec::new(),
            })
            .await;
        std::fs::write(&live_path, "first-second-third").unwrap();
        assert!(
            tokio::time::timeout(Duration::from_millis(700), client.receive())
                .await
                .is_err()
        );

        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
    }

    #[tokio::test]
    async fn reconnect_and_resubscribe_replays_current_content_then_resumes_deltas() {
        let directory = tempfile::tempdir().unwrap();
        let live_path = directory.path().join("ticker.aml");
        std::fs::write(&live_path, "first").unwrap();
        let config = StaticServerConfig::bind_plaintext_loopback(
            directory.path().to_path_buf(),
            "127.0.0.1",
            0,
        )
        .await
        .unwrap();
        let address = config.local_addr().unwrap();
        let mut server = StaticServer::new(config);
        let shutdown = server.shutdown_handle();
        let task = tokio::spawn(async move { server.run().await });

        let subscribe = || RawFrame {
            msg_type: MessageType::Subscribe,
            flags: 0,
            body: b"SUBSCRIBE /ticker.aml\nRegion: ticker\nMode: delta\n".to_vec(),
        };

        let mut first = RawClient::connect(address).await;
        first.handshake().await;
        first.send(subscribe()).await;
        let initial = first.receive().await;
        assert_eq!(initial.msg_type, MessageType::Update);
        assert_eq!(initial.flags, 0);
        assert_eq!(
            UpdateMessage::parse(std::str::from_utf8(&initial.body).unwrap())
                .unwrap()
                .content,
            "first"
        );
        drop(first);

        std::fs::write(&live_path, "first-while-disconnected").unwrap();
        let mut reconnected = RawClient::connect(address).await;
        reconnected.handshake().await;
        reconnected.send(subscribe()).await;
        let replay = reconnected.receive().await;
        assert_eq!(replay.msg_type, MessageType::Update);
        assert_eq!(replay.flags, 0, "a replay is a complete current value");
        assert_eq!(
            UpdateMessage::parse(std::str::from_utf8(&replay.body).unwrap())
                .unwrap()
                .content,
            "first-while-disconnected"
        );

        std::fs::write(&live_path, "first-while-disconnected-after").unwrap();
        let changed = tokio::time::timeout(Duration::from_secs(2), reconnected.receive())
            .await
            .expect("reconnected subscription did not resume polling");
        assert_eq!(changed.msg_type, MessageType::Update);
        assert_eq!(changed.flags, UpdateFlags { delta: true }.to_bits());
        assert_eq!(
            UpdateMessage::parse(std::str::from_utf8(&changed.body).unwrap())
                .unwrap()
                .content,
            "-after"
        );

        drop(reconnected);
        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
    }

    #[tokio::test]
    async fn stalled_frame_body_read_is_bounded() {
        let listener = AtpListener::bind_plain("127.0.0.1", 0).await.unwrap();
        let address = listener.local_addr().unwrap();
        let mut client = TcpStream::connect(address).await.unwrap();
        let pending = listener.accept_pending().await.unwrap();
        let mut server_stream = pending.handshake().await.unwrap();
        let encoded = encode_frame(&RawFrame {
            msg_type: MessageType::Hello,
            flags: 0,
            body: b"HELLO/0.2\n".to_vec(),
        })
        .unwrap();

        client
            .write_all(&encoded[..dustnet_core::protocol::HEADER_SIZE + 1])
            .await
            .unwrap();
        let result = recv(&mut server_stream, Duration::from_millis(50)).await;
        assert!(matches!(result, Err(ProtocolError::Timeout)));
    }

    #[tokio::test]
    async fn stalled_frame_write_is_bounded() {
        let listener = AtpListener::bind_plain("127.0.0.1", 0).await.unwrap();
        let address = listener.local_addr().unwrap();
        let mut client = TcpStream::connect(address).await.unwrap();
        let pending = listener.accept_pending().await.unwrap();
        let mut server_stream = pending.handshake().await.unwrap();

        client
            .write_all(
                &encode_frame(&RawFrame {
                    msg_type: MessageType::Hello,
                    flags: 0,
                    body: b"HELLO/0.2\nCapabilities: live-updates\n".to_vec(),
                })
                .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(
            recv(&mut server_stream, Duration::from_secs(1))
                .await
                .unwrap()
                .msg_type,
            MessageType::Hello
        );
        send_with_timeout(
            &mut server_stream,
            &RawFrame {
                msg_type: MessageType::Welcome,
                flags: 0,
                body: b"WELCOME/0.2\nCapabilities: live-updates\n".to_vec(),
            },
            Duration::from_secs(1),
        )
        .await
        .unwrap();

        // Never read from the peer. Repeated maximum-sized live updates fill
        // the kernel send window, after which the same timeout wrapper used by
        // production must bound the pending write.
        let update = UpdateMessage {
            region: "ticker".into(),
            content: "x".repeat(dustnet_core::protocol::MAX_LIVE_UPDATE_SIZE - 64),
            flags: UpdateFlags::default(),
        };
        let frame = RawFrame {
            msg_type: MessageType::Update,
            flags: 0,
            body: update.serialize().unwrap().into_bytes(),
        };
        let mut timed_out = false;
        for _ in 0..128 {
            match send_with_timeout(&mut server_stream, &frame, Duration::from_millis(50)).await {
                Err(ProtocolError::Timeout) => {
                    timed_out = true;
                    break;
                }
                Ok(()) => {}
                Err(error) => panic!("unexpected write failure: {error}"),
            }
        }
        assert!(timed_out, "peer receive window accepted more than 128 MiB");
    }

    #[tokio::test]
    async fn plaintext_configuration_rejects_non_loopback_binding() {
        let directory = tempfile::tempdir().unwrap();
        let result = StaticServerConfig::bind_plaintext_loopback(
            directory.path().to_path_buf(),
            "0.0.0.0",
            0,
        )
        .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn invalid_tls_handshake_is_closed_without_stopping_the_listener() {
        let directory = tempfile::tempdir().unwrap();
        let config = StaticServerConfig::bind_self_signed_for_tests(
            directory.path().to_path_buf(),
            "127.0.0.1",
            0,
        )
        .await
        .unwrap();
        let address = config.local_addr().unwrap();
        let mut server = StaticServer::new(config);
        let shutdown = server.shutdown_handle();
        let task = tokio::spawn(async move { server.run().await });

        let mut invalid = TcpStream::connect(address).await.unwrap();
        invalid.write_all(b"not a TLS handshake").await.unwrap();
        invalid.shutdown().await.unwrap();
        let mut alert = Vec::new();
        tokio::time::timeout(Duration::from_secs(2), invalid.read_to_end(&mut alert))
            .await
            .expect("invalid handshakes must be bounded")
            .unwrap();
        assert!(!alert.is_empty(), "rustls should return a TLS alert");

        // A rejected handshake must not poison the accept loop.
        let second = TcpStream::connect(address).await.unwrap();
        assert_eq!(second.peer_addr().unwrap(), address);
        drop(second);

        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
    }

    #[tokio::test]
    async fn silent_tls_handshake_is_closed_at_the_production_deadline() {
        let directory = tempfile::tempdir().unwrap();
        let config = StaticServerConfig::bind_self_signed_for_tests(
            directory.path().to_path_buf(),
            "127.0.0.1",
            0,
        )
        .await
        .unwrap();
        let address = config.local_addr().unwrap();
        let mut server = StaticServer::new(config);
        let shutdown = server.shutdown_handle();
        let task = tokio::spawn(async move { server.run().await });

        let started = std::time::Instant::now();
        let mut silent = TcpStream::connect(address).await.unwrap();
        let mut received = Vec::new();
        tokio::time::timeout(
            HANDSHAKE_TIMEOUT + Duration::from_secs(2),
            silent.read_to_end(&mut received),
        )
        .await
        .expect("silent TLS handshake must be closed at the configured deadline")
        .unwrap();
        assert!(
            started.elapsed() >= HANDSHAKE_TIMEOUT / 2,
            "the listener closed materially before its configured handshake timeout: {:?}",
            started.elapsed()
        );
        assert!(received.is_empty());

        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
    }

    #[tokio::test]
    async fn fragmented_frames_are_read_completely_and_missing_files_are_bounded_errors() {
        let directory = tempfile::tempdir().unwrap();
        std::fs::write(directory.path().join("index.aml"), "[page][/page]").unwrap();
        let config = StaticServerConfig::bind_plaintext_loopback(
            directory.path().to_path_buf(),
            "127.0.0.1",
            0,
        )
        .await
        .unwrap();
        let address = config.local_addr().unwrap();
        let mut server = StaticServer::new(config);
        let shutdown = server.shutdown_handle();
        let task = tokio::spawn(async move { server.run().await });

        let mut client = RawClient::connect(address).await;
        client
            .send_fragmented(RawFrame {
                msg_type: MessageType::Hello,
                flags: 0,
                body: b"HELLO/0.2\n".to_vec(),
            })
            .await;
        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);

        client
            .send_fragmented(RawFrame {
                msg_type: MessageType::Get,
                flags: 0,
                body: b"GET /missing.aml\n".to_vec(),
            })
            .await;
        let response = client.receive().await;
        assert_eq!(response.msg_type, MessageType::Error);
        assert!(response.body.len() <= dustnet_core::protocol::MAX_CONTROL_MESSAGE_SIZE);

        drop(client);
        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
    }

    fn hello_frame() -> RawFrame {
        RawFrame {
            msg_type: MessageType::Hello,
            flags: 0,
            body: b"HELLO/0.2\n".to_vec(),
        }
    }

    /// A HELLO that offers both `sessions` and `page-path`, as the reference
    /// client does — the pair a login response needs, since it both issues a
    /// session and names the page it landed on.
    fn hello_frame_with_sessions_and_page_path() -> RawFrame {
        RawFrame {
            msg_type: MessageType::Hello,
            flags: 0,
            body: b"HELLO/0.2\nCapabilities: sessions,page-path\n".to_vec(),
        }
    }

    /// A HELLO that offers the `sessions` capability.
    ///
    /// Needed by any test whose frames carry a session: the transport gates
    /// session-bearing frames on the negotiated capability, so a server cannot
    /// send `Set-Session` to a client that never said it understood sessions.
    /// A good property, and one a bare HELLO does not satisfy.
    fn hello_frame_with_sessions() -> RawFrame {
        RawFrame {
            msg_type: MessageType::Hello,
            flags: 0,
            body: b"HELLO/0.2\nCapabilities: sessions\n".to_vec(),
        }
    }

    fn ping_frame() -> RawFrame {
        RawFrame {
            msg_type: MessageType::Ping,
            flags: 0,
            body: Vec::new(),
        }
    }

    /// Spawn a server whose idle deadline is `read_timeout`, and return its
    /// address plus the handles needed to stop it.
    async fn server_with_read_timeout(
        directory: &std::path::Path,
        read_timeout: Duration,
    ) -> (
        std::net::SocketAddr,
        watch::Sender<bool>,
        tokio::task::JoinHandle<Result<(), ProtocolError>>,
    ) {
        let config =
            StaticServerConfig::bind_plaintext_loopback(directory.to_path_buf(), "127.0.0.1", 0)
                .await
                .unwrap()
                .with_read_timeout(read_timeout);
        let address = config.local_addr().unwrap();
        let mut server = StaticServer::new(config);
        let shutdown = server.shutdown_handle();
        let task = tokio::spawn(async move { server.run().await });
        (address, shutdown, task)
    }

    /// Subscribing must not wait on the platform watcher.
    ///
    /// Registering an FSEvents watch was measured at 1.7 seconds. The registry
    /// is one task shared by every connection, so a blocking registration there
    /// stalls every other subscriber behind it — which is why the platform
    /// watcher lives on its own thread. Watch registration is only ever a
    /// latency optimisation, since reconciliation serves the file regardless,
    /// so a subscriber must never be waiting on it.
    #[tokio::test]
    async fn subscribing_is_not_delayed_by_watcher_registration() {
        let directory = tempfile::tempdir().unwrap();
        let (address, shutdown, task) =
            server_with_read_timeout(directory.path(), READ_TIMEOUT).await;
        // Created after the server bound, so this is the first watch of it.
        std::fs::write(directory.path().join("ticker.aml"), "initial content").unwrap();

        let mut client = RawClient::connect(address).await;
        client.handshake().await;
        client
            .send(RawFrame {
                msg_type: MessageType::Subscribe,
                flags: 0,
                body: b"SUBSCRIBE /ticker\nRegion: my-region\n".to_vec(),
            })
            .await;

        let started = std::time::Instant::now();
        let frame = tokio::time::timeout(Duration::from_secs(3), client.receive())
            .await
            .expect("an initial UPDATE must arrive");
        let elapsed = started.elapsed();
        assert_eq!(frame.msg_type, MessageType::Update);
        assert!(
            elapsed < Duration::from_millis(500),
            "the initial UPDATE took {elapsed:?}; subscribing appears to be \
             waiting on platform watch registration again"
        );

        drop(client);
        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
    }

    #[tokio::test]
    async fn ping_is_answered_with_an_empty_pong() {
        let directory = tempfile::tempdir().unwrap();
        let (address, shutdown, task) =
            server_with_read_timeout(directory.path(), READ_TIMEOUT).await;

        let mut client = RawClient::connect(address).await;
        client.handshake().await;
        client.send(ping_frame()).await;
        let pong = tokio::time::timeout(Duration::from_secs(2), client.receive())
            .await
            .expect("PONG must arrive");
        assert_eq!(pong.msg_type, MessageType::Pong);
        assert_eq!(pong.flags, 0);
        assert!(pong.body.is_empty(), "PONG carries no body");

        drop(client);
        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
    }

    /// The control for the test below: without PING the deadline really does
    /// close the connection. Without this, a keepalive test could pass against
    /// a server that had simply stopped enforcing any deadline at all.
    #[tokio::test]
    async fn a_silent_connection_is_closed_at_the_idle_deadline() {
        let directory = tempfile::tempdir().unwrap();
        let deadline = Duration::from_millis(300);
        let (address, shutdown, task) = server_with_read_timeout(directory.path(), deadline).await;

        let mut client = RawClient::connect(address).await;
        client.handshake().await;

        let mut byte = [0_u8; 1];
        let started = std::time::Instant::now();
        let result = tokio::time::timeout(deadline * 10, client.0.read(&mut byte))
            .await
            .expect("a silent connection must be closed at the deadline");
        assert!(matches!(result, Ok(0) | Err(_)));
        assert!(
            started.elapsed() >= deadline / 2,
            "the connection closed before the deadline could have elapsed"
        );

        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
    }

    /// PING exists to reset that deadline. Pinging at a third of it keeps a
    /// connection alive well past the point where the control above dies.
    #[tokio::test]
    async fn pinging_holds_a_connection_open_past_the_idle_deadline() {
        let directory = tempfile::tempdir().unwrap();
        let deadline = Duration::from_millis(300);
        let (address, shutdown, task) = server_with_read_timeout(directory.path(), deadline).await;

        let mut client = RawClient::connect(address).await;
        client.handshake().await;

        // Four deadlines' worth of wall clock, pinged at a third of each.
        for _ in 0..12 {
            tokio::time::sleep(deadline / 3).await;
            client.send(ping_frame()).await;
            let pong = tokio::time::timeout(Duration::from_secs(2), client.receive())
                .await
                .expect("the connection must still be open");
            assert_eq!(pong.msg_type, MessageType::Pong);
        }

        drop(client);
        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
    }

    /// A PING sent while a request is outstanding must not be mistaken for the
    /// response, and must not poison the connection state machine.
    #[tokio::test]
    async fn ping_does_not_disturb_an_in_flight_request() {
        let directory = tempfile::tempdir().unwrap();
        std::fs::write(directory.path().join("index.aml"), "hello").unwrap();
        let (address, shutdown, task) =
            server_with_read_timeout(directory.path(), READ_TIMEOUT).await;

        let mut client = RawClient::connect(address).await;
        client.handshake().await;
        client
            .send(RawFrame {
                msg_type: MessageType::Get,
                flags: 0,
                body: b"GET /\n".to_vec(),
            })
            .await;
        client.send(ping_frame()).await;

        // Both replies must arrive, and the PAGE must not have been displaced.
        let mut seen_page = false;
        let mut seen_pong = false;
        for _ in 0..2 {
            let frame = tokio::time::timeout(Duration::from_secs(2), client.receive())
                .await
                .expect("both replies must arrive");
            match frame.msg_type {
                MessageType::Page => seen_page = true,
                MessageType::Pong => seen_pong = true,
                other => panic!("unexpected {other:?}"),
            }
        }
        assert!(seen_page && seen_pong);

        drop(client);
        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
    }

    #[tokio::test]
    async fn fifth_simultaneous_connection_from_one_ip_is_rejected() {
        let directory = tempfile::tempdir().unwrap();
        let config = StaticServerConfig::bind_plaintext_loopback(
            directory.path().to_path_buf(),
            "127.0.0.1",
            0,
        )
        .await
        .unwrap();
        let address = config.local_addr().unwrap();
        let mut server = StaticServer::new(config);
        let shutdown = server.shutdown_handle();
        let task = tokio::spawn(async move { server.run().await });

        let mut admitted = Vec::new();
        for _ in 0..DEFAULT_MAX_CONNECTIONS_PER_IP {
            let mut client = RawClient::connect(address).await;
            client.handshake().await;
            admitted.push(client);
        }

        let mut rejected = TcpStream::connect(address).await.unwrap();
        rejected
            .write_all(
                &encode_frame(&RawFrame {
                    msg_type: MessageType::Hello,
                    flags: 0,
                    body: b"HELLO/0.2\n".to_vec(),
                })
                .unwrap(),
            )
            .await
            .ok();
        let mut byte = [0_u8; 1];
        let result = tokio::time::timeout(Duration::from_secs(1), rejected.read(&mut byte))
            .await
            .expect("over-limit connection must be closed promptly");
        assert!(matches!(result, Ok(0) | Err(_)));

        drop(rejected);
        drop(admitted);
        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
    }

    #[tokio::test]
    async fn global_connection_limit_rejects_a_concurrent_flood() {
        let directory = tempfile::tempdir().unwrap();
        let config = StaticServerConfig::bind_plaintext_loopback(
            directory.path().to_path_buf(),
            "127.0.0.1",
            0,
        )
        .await
        .unwrap()
        .with_connection_limits(3, 4);
        let address = config.local_addr().unwrap();
        let mut server = StaticServer::new(config);
        let shutdown = server.shutdown_handle();
        let task = tokio::spawn(async move { server.run().await });

        let mut admitted = Vec::new();
        for _ in 0..3 {
            let mut client = RawClient::connect(address).await;
            client.handshake().await;
            admitted.push(client);
        }

        let mut rejected = RawClient::connect(address).await;
        rejected
            .send(RawFrame {
                msg_type: MessageType::Hello,
                flags: 0,
                body: b"HELLO/0.2\n".to_vec(),
            })
            .await;
        let mut byte = [0_u8; 1];
        let result = tokio::time::timeout(Duration::from_secs(1), rejected.0.read(&mut byte))
            .await
            .expect("globally over-limit connection must close promptly");
        assert!(matches!(result, Ok(0) | Err(_)));

        drop(rejected);
        drop(admitted);
        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
    }

    #[tokio::test]
    async fn malformed_tls_material_is_rejected_before_serving() {
        let directory = tempfile::tempdir().unwrap();
        let certificate = directory.path().join("certificate.pem");
        let private_key = directory.path().join("private-key.pem");
        std::fs::write(&certificate, "not a certificate").unwrap();
        std::fs::write(&private_key, "not a private key").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&certificate, std::fs::Permissions::from_mode(0o600)).unwrap();
            std::fs::set_permissions(&private_key, std::fs::Permissions::from_mode(0o600)).unwrap();
        }

        let result = StaticServerConfig::bind_tls(
            directory.path().to_path_buf(),
            "127.0.0.1",
            0,
            certificate.to_str().unwrap(),
            private_key.to_str().unwrap(),
        )
        .await;
        assert!(matches!(result, Err(ProtocolError::Tls(_))));
    }

    /// The test above only proves shutdown finishes inside the drain deadline —
    /// which it did even when every task had to be aborted. This one proves the
    /// connections leave voluntarily, so the deadline is a backstop rather than
    /// the normal path. That distinction is what makes 2048 connections
    /// survivable: aborting 2048 tasks is very different from joining them.
    #[tokio::test]
    async fn idle_connections_leave_voluntarily_well_inside_the_drain_deadline() {
        let directory = tempfile::tempdir().unwrap();
        let (address, shutdown, task) =
            server_with_read_timeout(directory.path(), READ_TIMEOUT).await;

        let mut clients = Vec::new();
        for _ in 0..DEFAULT_MAX_CONNECTIONS_PER_IP {
            let mut client = RawClient::connect(address).await;
            client.handshake().await;
            clients.push(client);
        }

        let started = std::time::Instant::now();
        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
        let elapsed = started.elapsed();

        assert!(
            elapsed < DRAIN_TIMEOUT / 2,
            "shutdown took {elapsed:?}, which suggests connections were aborted \
             at the drain deadline rather than leaving on their own"
        );
        drop(clients);
    }

    /// A per-IP ceiling above the global ceiling does not describe a reachable
    /// state, and zero would refuse every connection including the operator's
    /// own health check.
    #[tokio::test]
    async fn connection_limits_are_clamped_to_a_reachable_range() {
        let directory = tempfile::tempdir().unwrap();
        let config = || async {
            StaticServerConfig::bind_plaintext_loopback(
                directory.path().to_path_buf(),
                "127.0.0.1",
                0,
            )
            .await
            .unwrap()
        };

        let zeroed = config().await.with_connection_limits(0, 0);
        assert_eq!(zeroed.max_connections, 1, "zero would refuse every client");
        assert_eq!(zeroed.max_connections_per_ip, 1);

        let inverted = config().await.with_connection_limits(4, 100);
        assert_eq!(inverted.max_connections, 4);
        assert_eq!(
            inverted.max_connections_per_ip, 4,
            "a per-IP ceiling above the global ceiling is not a reachable state"
        );

        let ordinary = config().await.with_connection_limits(2048, 4);
        assert_eq!(ordinary.max_connections, 2048);
        assert_eq!(ordinary.max_connections_per_ip, 4);
    }

    #[tokio::test]
    async fn shutdown_is_bounded_with_an_idle_client() {
        let directory = tempfile::tempdir().unwrap();
        let config = StaticServerConfig::bind_plaintext_loopback(
            directory.path().to_path_buf(),
            "127.0.0.1",
            0,
        )
        .await
        .unwrap();
        let address = config.local_addr().unwrap();
        let mut server = StaticServer::new(config);
        let shutdown = server.shutdown_handle();
        let task = tokio::spawn(async move { server.run().await });

        let mut client = RawClient::connect(address).await;
        client.handshake().await;
        shutdown.send(true).unwrap();

        tokio::time::timeout(DRAIN_TIMEOUT + Duration::from_secs(2), task)
            .await
            .expect("shutdown exceeded its drain deadline")
            .unwrap()
            .unwrap();
        drop(client);
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn symlinks_cannot_escape_static_root() {
        use std::os::unix::fs::symlink;
        let root = tempfile::tempdir().unwrap();
        let canonical_root = std::fs::canonicalize(root.path()).unwrap();
        let outside = tempfile::NamedTempFile::new().unwrap();
        symlink(outside.path(), root.path().join("escape.aml")).unwrap();
        assert!(resolve_path(&canonical_root, "/escape.aml").await.is_err());
    }

    /// The lexical half must not touch the disk, so it can run on a runtime
    /// worker. A traversal attempt is rejected before any syscall.
    #[test]
    fn lexical_resolution_rejects_traversal_without_touching_the_disk() {
        let root = Path::new("/nonexistent-root");
        assert!(resolve_path_lexical(root, "/../escape.aml").is_err());
        assert_eq!(
            resolve_path_lexical(root, "/page").unwrap(),
            root.join("page.aml"),
            "a bare name gains the .aml extension"
        );
        assert_eq!(
            resolve_path_lexical(root, "/").unwrap(),
            root.join("index.aml"),
            "a directory request resolves to its index"
        );
    }

    /// A miss is a 404, not an escape. Regression guard for the removed
    /// `Path::exists` probe.
    #[tokio::test]
    async fn a_missing_file_resolves_without_error() {
        let root = tempfile::tempdir().unwrap();
        let canonical_root = std::fs::canonicalize(root.path()).unwrap();
        let resolved = resolve_path(&canonical_root, "/absent.aml").await.unwrap();
        assert_eq!(resolved, canonical_root.join("absent.aml"));
    }

    #[tokio::test]
    async fn static_resource_read_is_fallible_and_returns_only_filled_bytes() {
        let file = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(file.path(), b"wasm").unwrap();
        let opened = tokio::fs::File::open(file.path()).await.unwrap();
        let body = read_static_body(opened, 8, 41).await.unwrap();
        assert_eq!(body, b"wasm");

        let opened = tokio::fs::File::open(file.path()).await.unwrap();
        let _rejection = AllocationRejectionGuard::at(ServerAllocationSite::StaticBody, 41);
        assert!(matches!(
            read_static_body(opened, 4, 41).await,
            Err(ProtocolError::ResourceExhausted { requested: 5 })
        ));
    }

    #[tokio::test]
    async fn static_resource_growth_after_metadata_is_rejected() {
        let file = tempfile::NamedTempFile::new().unwrap();
        std::fs::write(file.path(), b"old").unwrap();
        let opened = tokio::fs::File::open(file.path()).await.unwrap();
        std::fs::write(file.path(), b"new content").unwrap();
        assert!(matches!(
            read_static_body(opened, 3, 42).await,
            Err(ProtocolError::InvalidMessage(_))
        ));
    }

    /// A resolver's content reaches the wire, and the placeholder does not.
    ///
    /// The unit tests in `include` cover substitution; this covers the wiring,
    /// which is the part that can silently not happen — a resolver configured
    /// but never consulted would leave every page looking exactly like the
    /// no-resolver case.
    #[tokio::test]
    async fn a_configured_resolver_substitutes_includes_on_the_wire() {
        struct Stories;
        impl crate::include::IncludeResolver for Stories {
            fn resolve(
                &self,
                name: &str,
                request: &crate::include::IncludeRequest<'_>,
            ) -> Option<Vec<dustnet_core::scanner::Token>> {
                assert_eq!(request.path, "/index.aml");
                (name == "links").then(|| {
                    vec![
                        dustnet_core::scanner::Token::OpenTag {
                            name: "text".into(),
                            attributes: Vec::new(),
                            self_closing: false,
                        },
                        dustnet_core::scanner::Token::Text("a generated story".into()),
                        dustnet_core::scanner::Token::CloseTag {
                            name: "text".into(),
                        },
                    ]
                })
            }
        }

        let directory = tempfile::tempdir().unwrap();
        std::fs::write(
            directory.path().join("index.aml"),
            r#"[page mode=document][include name="links" /][/page]"#,
        )
        .unwrap();
        let config = StaticServerConfig::bind_plaintext_loopback(
            directory.path().to_path_buf(),
            "127.0.0.1",
            0,
        )
        .await
        .unwrap()
        .with_include_resolver(Arc::new(Stories));
        let address = config.local_addr().unwrap();
        let mut server = StaticServer::new(config);
        let shutdown = server.shutdown_handle();
        let task = tokio::spawn(async move { server.run().await });

        let mut client = RawClient::connect(address).await;
        client
            .send(RawFrame {
                msg_type: MessageType::Hello,
                flags: 0,
                body: b"HELLO/0.2\n".to_vec(),
            })
            .await;
        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
        client
            .send(RawFrame {
                msg_type: MessageType::Get,
                flags: 0,
                body: b"GET /index.aml\n".to_vec(),
            })
            .await;

        let response = client.receive().await;
        assert_eq!(response.msg_type, MessageType::Page);
        let body = String::from_utf8(response.body).unwrap();
        assert!(body.contains("a generated story"), "{body}");
        assert!(
            !body.contains("include"),
            "the placeholder survived: {body}"
        );

        drop(client);
        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
    }

    /// Without a resolver the server is byte-for-byte what it was: the include
    /// travels to the client, which renders it as nothing. This is the
    /// assertion that `dustnetd` has not quietly become dynamic.
    #[tokio::test]
    async fn without_a_resolver_includes_are_served_verbatim() {
        let source = r#"[page mode=document][include name="links" /][/page]"#;
        let directory = tempfile::tempdir().unwrap();
        std::fs::write(directory.path().join("index.aml"), source).unwrap();
        let config = StaticServerConfig::bind_plaintext_loopback(
            directory.path().to_path_buf(),
            "127.0.0.1",
            0,
        )
        .await
        .unwrap();
        let address = config.local_addr().unwrap();
        let mut server = StaticServer::new(config);
        let shutdown = server.shutdown_handle();
        let task = tokio::spawn(async move { server.run().await });

        let mut client = RawClient::connect(address).await;
        client
            .send(RawFrame {
                msg_type: MessageType::Hello,
                flags: 0,
                body: b"HELLO/0.2\n".to_vec(),
            })
            .await;
        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
        client
            .send(RawFrame {
                msg_type: MessageType::Get,
                flags: 0,
                body: b"GET /index.aml\n".to_vec(),
            })
            .await;

        let response = client.receive().await;
        assert_eq!(response.msg_type, MessageType::Page);
        assert_eq!(String::from_utf8(response.body).unwrap(), source);

        drop(client);
        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
    }

    /// Without a handler, INPUT is refused exactly as it was before
    /// submissions were possible. This is the assertion that `dustnetd` has
    /// not quietly gained a write path.
    #[tokio::test]
    async fn without_a_handler_input_is_still_refused() {
        let directory = tempfile::tempdir().unwrap();
        std::fs::write(directory.path().join("index.aml"), "[page][/page]").unwrap();
        let config = StaticServerConfig::bind_plaintext_loopback(
            directory.path().to_path_buf(),
            "127.0.0.1",
            0,
        )
        .await
        .unwrap();
        let address = config.local_addr().unwrap();
        let mut server = StaticServer::new(config);
        let shutdown = server.shutdown_handle();
        let task = tokio::spawn(async move { server.run().await });

        let mut client = RawClient::connect(address).await;
        client.send(hello_frame()).await;
        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
        client
            .send(RawFrame {
                msg_type: MessageType::Input,
                flags: 0,
                body: b"INPUT /index\nForm: a=b\n".to_vec(),
            })
            .await;

        let response = client.receive().await;
        assert_eq!(response.msg_type, MessageType::Error);
        let body = String::from_utf8(response.body).unwrap();
        assert!(body.contains("405"), "{body}");

        drop(client);
        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
    }

    /// An accepted submission answers with the page itself, and the handler
    /// sees the fields and the action's query.
    ///
    /// A page rather than a redirect because `validate_redirect_body` requires
    /// an absolute `atp://` target — the client parses it rather than resolving
    /// it — and a server does not know its own public hostname.
    #[tokio::test]
    async fn an_accepted_submission_answers_with_the_page() {
        struct Accepts;
        impl crate::input::InputHandler for Accepts {
            fn handle(
                &self,
                request: &crate::input::InputRequest<'_>,
            ) -> crate::input::InputOutcome {
                assert_eq!(request.path, "/index");
                assert_eq!(request.query, Some("reply=7"));
                assert_eq!(request.fields.get("body"), Some("hello world"));
                crate::input::InputOutcome::render("/index")
            }
        }

        let directory = tempfile::tempdir().unwrap();
        std::fs::write(directory.path().join("index.aml"), "[page][/page]").unwrap();
        let config = StaticServerConfig::bind_plaintext_loopback(
            directory.path().to_path_buf(),
            "127.0.0.1",
            0,
        )
        .await
        .unwrap()
        .with_input_handler(Arc::new(Accepts));
        let address = config.local_addr().unwrap();
        let mut server = StaticServer::new(config);
        let shutdown = server.shutdown_handle();
        let task = tokio::spawn(async move { server.run().await });

        let mut client = RawClient::connect(address).await;
        client.send(hello_frame()).await;
        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
        client
            .send(RawFrame {
                msg_type: MessageType::Input,
                flags: 0,
                body: b"INPUT /index?reply=7\nForm: body=hello+world\n".to_vec(),
            })
            .await;

        let response = client.receive().await;
        assert_eq!(response.msg_type, MessageType::Page);
        assert_eq!(String::from_utf8(response.body).unwrap(), "[page][/page]");

        drop(client);
        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
    }

    /// A refusal reaches the person who submitted, with the handler's reason.
    #[tokio::test]
    async fn a_refused_submission_returns_the_reason() {
        struct Refuses;
        impl crate::input::InputHandler for Refuses {
            fn handle(&self, _: &crate::input::InputRequest<'_>) -> crate::input::InputOutcome {
                crate::input::InputOutcome::Rejected("a title is required".into())
            }
        }

        let directory = tempfile::tempdir().unwrap();
        std::fs::write(directory.path().join("index.aml"), "[page][/page]").unwrap();
        let config = StaticServerConfig::bind_plaintext_loopback(
            directory.path().to_path_buf(),
            "127.0.0.1",
            0,
        )
        .await
        .unwrap()
        .with_input_handler(Arc::new(Refuses));
        let address = config.local_addr().unwrap();
        let mut server = StaticServer::new(config);
        let shutdown = server.shutdown_handle();
        let task = tokio::spawn(async move { server.run().await });

        let mut client = RawClient::connect(address).await;
        client.send(hello_frame()).await;
        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
        client
            .send(RawFrame {
                msg_type: MessageType::Input,
                flags: 0,
                body: b"INPUT /index\nForm: title=\n".to_vec(),
            })
            .await;

        let response = client.receive().await;
        assert_eq!(response.msg_type, MessageType::Error);
        let body = String::from_utf8(response.body).unwrap();
        assert!(body.contains("400"), "{body}");
        assert!(body.contains("a title is required"), "{body}");

        drop(client);
        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
    }

    /// The token is resolved once and only the identity travels on. This is the
    /// property `crate::session` exists for, so it is asserted rather than
    /// described: the include resolver is handed the username and has no way to
    /// reach the token that produced it.
    #[tokio::test]
    async fn handlers_receive_an_identity_and_never_the_token() {
        use std::sync::atomic::{AtomicBool, Ordering};
        static SAW_IDENTITY: AtomicBool = AtomicBool::new(false);

        struct Sessions;
        impl crate::session::SessionResolver for Sessions {
            fn identity(&self, token: &str) -> Option<String> {
                (token == "the-secret-token").then(|| "dusty".to_string())
            }
        }

        struct Renders;
        impl crate::include::IncludeResolver for Renders {
            fn resolve(
                &self,
                _name: &str,
                request: &crate::include::IncludeRequest<'_>,
            ) -> Option<Vec<dustnet_core::scanner::Token>> {
                assert_eq!(request.identity, Some("dusty"));
                SAW_IDENTITY.store(true, Ordering::SeqCst);
                Some(vec![dustnet_core::scanner::Token::Text(
                    request.identity.unwrap_or("anonymous").to_string(),
                )])
            }
        }

        let directory = tempfile::tempdir().unwrap();
        std::fs::write(
            directory.path().join("index.aml"),
            r#"[page mode=document][include name="who" /][/page]"#,
        )
        .unwrap();
        let config = StaticServerConfig::bind_plaintext_loopback(
            directory.path().to_path_buf(),
            "127.0.0.1",
            0,
        )
        .await
        .unwrap()
        .with_include_resolver(Arc::new(Renders))
        .with_session_resolver(Arc::new(Sessions));
        let address = config.local_addr().unwrap();
        let mut server = StaticServer::new(config);
        let shutdown = server.shutdown_handle();
        let task = tokio::spawn(async move { server.run().await });

        let mut client = RawClient::connect(address).await;
        client.send(hello_frame_with_sessions()).await;
        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
        client
            .send(RawFrame {
                msg_type: MessageType::Get,
                flags: 0,
                body: b"GET /index.aml\nSession: the-secret-token\n".to_vec(),
            })
            .await;

        let response = client.receive().await;
        assert_eq!(response.msg_type, MessageType::Page);
        let body = String::from_utf8(response.body).unwrap();
        assert!(SAW_IDENTITY.load(Ordering::SeqCst), "resolver never ran");
        assert!(body.contains("dusty"), "{body}");
        assert!(
            !body.contains("the-secret-token"),
            "the token reached the page: {body}"
        );

        drop(client);
        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
    }

    /// An unrecognised token is indistinguishable from none. Anything else is
    /// an oracle for whether a token ever existed.
    #[tokio::test]
    async fn an_unrecognised_token_is_anonymous() {
        struct NoSessions;
        impl crate::session::SessionResolver for NoSessions {
            fn identity(&self, _token: &str) -> Option<String> {
                None
            }
        }

        struct Renders;
        impl crate::include::IncludeResolver for Renders {
            fn resolve(
                &self,
                _name: &str,
                request: &crate::include::IncludeRequest<'_>,
            ) -> Option<Vec<dustnet_core::scanner::Token>> {
                Some(vec![dustnet_core::scanner::Token::Text(
                    request.identity.unwrap_or("anonymous").to_string(),
                )])
            }
        }

        let directory = tempfile::tempdir().unwrap();
        std::fs::write(
            directory.path().join("index.aml"),
            r#"[page mode=document][include name="who" /][/page]"#,
        )
        .unwrap();
        let config = StaticServerConfig::bind_plaintext_loopback(
            directory.path().to_path_buf(),
            "127.0.0.1",
            0,
        )
        .await
        .unwrap()
        .with_include_resolver(Arc::new(Renders))
        .with_session_resolver(Arc::new(NoSessions));
        let address = config.local_addr().unwrap();
        let mut server = StaticServer::new(config);
        let shutdown = server.shutdown_handle();
        let task = tokio::spawn(async move { server.run().await });

        let mut client = RawClient::connect(address).await;
        client.send(hello_frame_with_sessions()).await;
        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
        client
            .send(RawFrame {
                msg_type: MessageType::Get,
                flags: 0,
                body: b"GET /index.aml\nSession: bogus\n".to_vec(),
            })
            .await;

        let body = String::from_utf8(client.receive().await.body).unwrap();
        assert!(body.contains("anonymous"), "{body}");

        drop(client);
        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
    }

    /// A handler granting a session gets its directive onto the wire, with the
    /// session flag set so the client parses the metadata block.
    #[tokio::test]
    async fn an_accepted_submission_can_issue_a_session() {
        struct Logs;
        impl crate::input::InputHandler for Logs {
            fn handle(
                &self,
                request: &crate::input::InputRequest<'_>,
            ) -> crate::input::InputOutcome {
                assert!(request.peer.is_loopback(), "peer should be loopback");
                crate::input::InputOutcome::render("/index").with_session(
                    crate::session::SessionChange::set("issued-token", "/", 1_900_000_000),
                )
            }
        }

        let directory = tempfile::tempdir().unwrap();
        std::fs::write(directory.path().join("index.aml"), "[page][/page]").unwrap();
        let config = StaticServerConfig::bind_plaintext_loopback(
            directory.path().to_path_buf(),
            "127.0.0.1",
            0,
        )
        .await
        .unwrap()
        .with_input_handler(Arc::new(Logs));
        let address = config.local_addr().unwrap();
        let mut server = StaticServer::new(config);
        let shutdown = server.shutdown_handle();
        let task = tokio::spawn(async move { server.run().await });

        let mut client = RawClient::connect(address).await;
        client.send(hello_frame_with_sessions()).await;
        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
        client
            .send(RawFrame {
                msg_type: MessageType::Input,
                flags: 0,
                body: b"INPUT /login\nForm: name=dusty\n".to_vec(),
            })
            .await;

        let response = client.receive().await;
        assert_eq!(response.msg_type, MessageType::Page);
        assert_eq!(response.flags & 0x08, 0x08, "session flag should be set");
        let body = String::from_utf8(response.body).unwrap();
        assert!(body.contains("Set-Session: issued-token"), "{body}");

        drop(client);
        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
    }

    /// The page answering a login is rendered for the identity the login just
    /// granted, not the anonymous one that asked for it. Without this the
    /// response carries `Set-Session` and a logged-out nav bar in the same
    /// frame, which reads to the person who just typed their password as a
    /// login that did not work.
    #[tokio::test]
    async fn a_granted_session_renders_the_response_for_its_new_identity() {
        struct Sessions;
        impl crate::session::SessionResolver for Sessions {
            fn identity(&self, token: &str) -> Option<String> {
                (token == "issued-token").then(|| "dusty".to_string())
            }
        }

        struct Authenticates;
        impl crate::input::InputHandler for Authenticates {
            fn handle(
                &self,
                request: &crate::input::InputRequest<'_>,
            ) -> crate::input::InputOutcome {
                // The submission itself is anonymous: nobody presents a token
                // when logging in. This is what makes the assertion below a
                // real one.
                assert_eq!(request.identity, None);
                crate::input::InputOutcome::render("/index").with_session(
                    crate::session::SessionChange::set("issued-token", "/", 1_900_000_000),
                )
            }
        }

        struct Nav;
        impl crate::include::IncludeResolver for Nav {
            fn resolve(
                &self,
                _name: &str,
                request: &crate::include::IncludeRequest<'_>,
            ) -> Option<Vec<dustnet_core::scanner::Token>> {
                Some(vec![dustnet_core::scanner::Token::Text(
                    request.identity.unwrap_or("login").to_string(),
                )])
            }
        }

        let directory = tempfile::tempdir().unwrap();
        std::fs::write(
            directory.path().join("index.aml"),
            r#"[page mode=document][include name="header" /][/page]"#,
        )
        .unwrap();
        let config = StaticServerConfig::bind_plaintext_loopback(
            directory.path().to_path_buf(),
            "127.0.0.1",
            0,
        )
        .await
        .unwrap()
        .with_include_resolver(Arc::new(Nav))
        .with_input_handler(Arc::new(Authenticates))
        .with_session_resolver(Arc::new(Sessions));
        let address = config.local_addr().unwrap();
        let mut server = StaticServer::new(config);
        let shutdown = server.shutdown_handle();
        let task = tokio::spawn(async move { server.run().await });

        let mut client = RawClient::connect(address).await;
        client.send(hello_frame_with_sessions()).await;
        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
        client
            .send(RawFrame {
                msg_type: MessageType::Input,
                flags: 0,
                body: b"INPUT /login\nForm: name=dusty&password=hunter2\n".to_vec(),
            })
            .await;

        let response = client.receive().await;
        assert_eq!(response.msg_type, MessageType::Page);
        let body = String::from_utf8(response.body).unwrap();
        assert!(body.contains("Set-Session: issued-token"), "{body}");
        assert!(
            body.contains("dusty"),
            "the login response should be rendered as dusty: {body}"
        );

        drop(client);
        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
    }

    /// A token the resolver does not recognise is anonymous even when a handler
    /// is the thing that issued it. The resolver stays the only authority on
    /// who a token belongs to — a handler cannot render a page as someone by
    /// claiming to have granted them a session.
    #[tokio::test]
    async fn a_granted_token_the_resolver_rejects_renders_anonymously() {
        struct RefusesEverything;
        impl crate::session::SessionResolver for RefusesEverything {
            fn identity(&self, _token: &str) -> Option<String> {
                None
            }
        }

        struct Claims;
        impl crate::input::InputHandler for Claims {
            fn handle(&self, _: &crate::input::InputRequest<'_>) -> crate::input::InputOutcome {
                crate::input::InputOutcome::render("/index").with_session(
                    crate::session::SessionChange::set("forged", "/", 1_900_000_000),
                )
            }
        }

        struct Nav;
        impl crate::include::IncludeResolver for Nav {
            fn resolve(
                &self,
                _name: &str,
                request: &crate::include::IncludeRequest<'_>,
            ) -> Option<Vec<dustnet_core::scanner::Token>> {
                Some(vec![dustnet_core::scanner::Token::Text(
                    request.identity.unwrap_or("anonymous").to_string(),
                )])
            }
        }

        let directory = tempfile::tempdir().unwrap();
        std::fs::write(
            directory.path().join("index.aml"),
            r#"[page mode=document][include name="header" /][/page]"#,
        )
        .unwrap();
        let config = StaticServerConfig::bind_plaintext_loopback(
            directory.path().to_path_buf(),
            "127.0.0.1",
            0,
        )
        .await
        .unwrap()
        .with_include_resolver(Arc::new(Nav))
        .with_input_handler(Arc::new(Claims))
        .with_session_resolver(Arc::new(RefusesEverything));
        let address = config.local_addr().unwrap();
        let mut server = StaticServer::new(config);
        let shutdown = server.shutdown_handle();
        let task = tokio::spawn(async move { server.run().await });

        let mut client = RawClient::connect(address).await;
        client.send(hello_frame_with_sessions()).await;
        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
        client
            .send(RawFrame {
                msg_type: MessageType::Input,
                flags: 0,
                body: b"INPUT /login\nForm: name=dusty\n".to_vec(),
            })
            .await;

        let response = client.receive().await;
        assert_eq!(response.msg_type, MessageType::Page);
        let body = String::from_utf8(response.body).unwrap();
        assert!(body.contains("anonymous"), "{body}");

        drop(client);
        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
    }

    /// A submission's answer names the page it actually is. Without this the
    /// client keeps the path it submitted to as its location, so a login shows
    /// the front page but reloads back into the login form.
    #[tokio::test]
    async fn an_accepted_submission_names_the_page_it_answers_with() {
        struct SendsElsewhere;
        impl crate::input::InputHandler for SendsElsewhere {
            fn handle(&self, _: &crate::input::InputRequest<'_>) -> crate::input::InputOutcome {
                crate::input::InputOutcome::render("/index")
            }
        }

        let directory = tempfile::tempdir().unwrap();
        std::fs::write(directory.path().join("index.aml"), "[page][/page]").unwrap();
        let config = StaticServerConfig::bind_plaintext_loopback(
            directory.path().to_path_buf(),
            "127.0.0.1",
            0,
        )
        .await
        .unwrap()
        .with_input_handler(Arc::new(SendsElsewhere));
        let address = config.local_addr().unwrap();
        let mut server = StaticServer::new(config);
        let shutdown = server.shutdown_handle();
        let task = tokio::spawn(async move { server.run().await });

        let mut client = RawClient::connect(address).await;
        client.send(hello_frame_with_sessions_and_page_path()).await;
        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
        client
            .send(RawFrame {
                msg_type: MessageType::Input,
                flags: 0,
                body: b"INPUT /login\nForm: name=dusty\n".to_vec(),
            })
            .await;

        let response = client.receive().await;
        assert_eq!(response.msg_type, MessageType::Page);
        assert_eq!(response.flags & 0x04, 0x04, "path flag should be set");
        let body = String::from_utf8(response.body).unwrap();
        assert!(body.starts_with("Path: /index\n"), "{body}");

        drop(client);
        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
    }

    /// A submission's answer carries the query too. A comment posted on a story
    /// is answered with that story, and a location that dropped the `item`
    /// would reload as the front page.
    #[tokio::test]
    async fn a_named_page_keeps_its_query() {
        struct SendsToAStory;
        impl crate::input::InputHandler for SendsToAStory {
            fn handle(&self, _: &crate::input::InputRequest<'_>) -> crate::input::InputOutcome {
                crate::input::InputOutcome::render_query("/index", "item=12")
            }
        }

        let directory = tempfile::tempdir().unwrap();
        std::fs::write(directory.path().join("index.aml"), "[page][/page]").unwrap();
        let config = StaticServerConfig::bind_plaintext_loopback(
            directory.path().to_path_buf(),
            "127.0.0.1",
            0,
        )
        .await
        .unwrap()
        .with_input_handler(Arc::new(SendsToAStory));
        let address = config.local_addr().unwrap();
        let mut server = StaticServer::new(config);
        let shutdown = server.shutdown_handle();
        let task = tokio::spawn(async move { server.run().await });

        let mut client = RawClient::connect(address).await;
        client.send(hello_frame_with_sessions_and_page_path()).await;
        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
        client
            .send(RawFrame {
                msg_type: MessageType::Input,
                flags: 0,
                body: b"INPUT /index\nForm: text=hello\n".to_vec(),
            })
            .await;

        let response = client.receive().await;
        assert_eq!(response.msg_type, MessageType::Page);
        let body = String::from_utf8(response.body).unwrap();
        assert!(body.starts_with("Path: /index?item=12\n"), "{body}");

        drop(client);
        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
    }

    /// A client that never offered `page-path` still gets its page. The
    /// capability gate refuses a frame needing a capability the peer did not
    /// negotiate, so a server that attached the field regardless would answer
    /// an older client with nothing at all.
    #[tokio::test]
    async fn a_client_without_the_capability_gets_an_unnamed_page() {
        struct SendsElsewhere;
        impl crate::input::InputHandler for SendsElsewhere {
            fn handle(&self, _: &crate::input::InputRequest<'_>) -> crate::input::InputOutcome {
                crate::input::InputOutcome::render("/index")
            }
        }

        let directory = tempfile::tempdir().unwrap();
        std::fs::write(directory.path().join("index.aml"), "[page][/page]").unwrap();
        let config = StaticServerConfig::bind_plaintext_loopback(
            directory.path().to_path_buf(),
            "127.0.0.1",
            0,
        )
        .await
        .unwrap()
        .with_input_handler(Arc::new(SendsElsewhere));
        let address = config.local_addr().unwrap();
        let mut server = StaticServer::new(config);
        let shutdown = server.shutdown_handle();
        let task = tokio::spawn(async move { server.run().await });

        let mut client = RawClient::connect(address).await;
        client.send(hello_frame()).await;
        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
        client
            .send(RawFrame {
                msg_type: MessageType::Input,
                flags: 0,
                body: b"INPUT /login\nForm: name=dusty\n".to_vec(),
            })
            .await;

        let response = client.receive().await;
        assert_eq!(response.msg_type, MessageType::Page);
        assert_eq!(response.flags & 0x04, 0, "path flag must not be set");
        let body = String::from_utf8(response.body).unwrap();
        assert!(!body.contains("Path: "), "{body}");
        assert!(body.starts_with("[page]"), "{body}");

        drop(client);
        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
    }

    /// A GET is answered without a `Path`. The client asked for that path and
    /// already knows it; spending the bytes on every page to say so again would
    /// be a field that only ever repeats the request.
    #[tokio::test]
    async fn a_get_is_not_named() {
        let directory = tempfile::tempdir().unwrap();
        std::fs::write(directory.path().join("index.aml"), "[page][/page]").unwrap();
        let config = StaticServerConfig::bind_plaintext_loopback(
            directory.path().to_path_buf(),
            "127.0.0.1",
            0,
        )
        .await
        .unwrap();
        let address = config.local_addr().unwrap();
        let mut server = StaticServer::new(config);
        let shutdown = server.shutdown_handle();
        let task = tokio::spawn(async move { server.run().await });

        let mut client = RawClient::connect(address).await;
        client.send(hello_frame_with_sessions_and_page_path()).await;
        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
        client
            .send(RawFrame {
                msg_type: MessageType::Get,
                flags: 0,
                body: b"GET /index.aml\n".to_vec(),
            })
            .await;

        let response = client.receive().await;
        assert_eq!(response.msg_type, MessageType::Page);
        assert_eq!(response.flags & 0x04, 0, "a GET needs no Path");

        drop(client);
        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
    }

    /// A resolver can produce more than a page may carry. The server refuses
    /// rather than truncating: half a page is a worse answer than an error
    /// naming the cause, and a silently truncated page is malformed AML.
    #[tokio::test]
    async fn an_oversized_resolved_page_is_refused_not_truncated() {
        struct Floods;
        impl crate::include::IncludeResolver for Floods {
            fn resolve(
                &self,
                _name: &str,
                _request: &crate::include::IncludeRequest<'_>,
            ) -> Option<Vec<dustnet_core::scanner::Token>> {
                // Comfortably past MAX_PAGE_MESSAGE_SIZE once serialized.
                Some(vec![dustnet_core::scanner::Token::Text(
                    "x".repeat(MAX_PAGE_MESSAGE_SIZE + 1024),
                )])
            }
        }

        let directory = tempfile::tempdir().unwrap();
        std::fs::write(
            directory.path().join("index.aml"),
            r#"[page mode=document][include name="flood" /][/page]"#,
        )
        .unwrap();
        let config = StaticServerConfig::bind_plaintext_loopback(
            directory.path().to_path_buf(),
            "127.0.0.1",
            0,
        )
        .await
        .unwrap()
        .with_include_resolver(Arc::new(Floods));
        let address = config.local_addr().unwrap();
        let mut server = StaticServer::new(config);
        let shutdown = server.shutdown_handle();
        let task = tokio::spawn(async move { server.run().await });

        let mut client = RawClient::connect(address).await;
        client.send(hello_frame()).await;
        assert_eq!(client.receive().await.msg_type, MessageType::Welcome);
        client
            .send(RawFrame {
                msg_type: MessageType::Get,
                flags: 0,
                body: b"GET /index.aml\n".to_vec(),
            })
            .await;

        let response = client.receive().await;
        assert_eq!(response.msg_type, MessageType::Error);
        let body = String::from_utf8(response.body).unwrap();
        assert!(body.contains("500"), "{body}");
        assert!(
            body.len() <= dustnet_core::protocol::MAX_CONTROL_MESSAGE_SIZE,
            "the refusal itself must stay bounded"
        );

        drop(client);
        shutdown.send(true).unwrap();
        task.await.unwrap().unwrap();
    }
}