autumn-web 0.9.0

An opinionated, convention-over-configuration web framework for Rust
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
//! Middleware for serving statically generated files.
//!
//! This module contains the `StaticFileLayer`, which intercepts requests and serves
//! pre-rendered HTML files from the `dist/` directory if they exist. It acts as a
//! lightning-fast cache layer in front of your dynamic routes.

// autumn-determinism-gate: production code in this module must read time and
// mint identifiers through the framework's injected seams (ClockSource /
// Entropy), never `Instant::now()` / `Utc::now()` / `SystemTime::now()` /
// `Uuid::new_v4()` directly. See CONTRIBUTING.md "Determinism seam gate"
// (issue #1797). Justify exceptions with
// #[allow(clippy::disallowed_methods, reason = "…")] at the narrowest scope.
#![cfg_attr(not(test), deny(clippy::disallowed_methods))]

use std::borrow::Cow;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::SystemTime;

use super::isr_coordinator::{IsrCoordinator, LocalIsrCoordinator, isr_window_key};
use super::{ManifestEntry, StaticManifest};

/// Per-route ISR state, tracking whether a regeneration is in flight
/// and when the last regeneration attempt occurred.
struct IsrRouteState {
    /// `true` when a background regeneration task is running for this route.
    in_flight: AtomicBool,
    /// Unix timestamp of the last regeneration attempt. Used for backoff:
    /// after a failed regeneration, wait at least `REGEN_COOLDOWN_SECS`
    /// before trying again.
    last_attempt: AtomicU64,
}

/// Minimum seconds between regeneration attempts for the same route.
/// Prevents tight retry loops when the handler is failing.
const REGEN_COOLDOWN_SECS: u64 = 30;

/// Layer that resolves incoming request paths against a pre-built static
/// manifest and the corresponding `dist/` directory on disk.
///
/// Created via [`StaticFileLayer::new`], which returns `None` when the
/// expected `manifest.json` is missing or unparseable -- this makes it
/// safe to attempt construction unconditionally and simply skip static
/// serving when no build output exists.
///
/// ## ISR (Incremental Static Regeneration)
///
/// Routes with a `revalidate` interval are served from disk but checked
/// for staleness on each request. When the file on disk is older than
/// `revalidate` seconds, a background Tokio task is spawned to re-render
/// the page. The stale page continues to be served until the fresh one
/// is ready (stale-while-revalidate pattern).
#[derive(Clone)]
pub struct StaticFileLayer {
    dist_dir: PathBuf,
    manifest: Arc<StaticManifest>,
    /// Per-route ISR state, keyed by URL path. Only populated for routes
    /// that have `revalidate` set.
    isr_state: Arc<HashMap<String, IsrRouteState>>,
    /// The Axum router used for ISR regeneration. Cloned from the app
    /// router at construction time. `None` if ISR is not needed.
    isr_router: Option<Arc<axum::Router>>,
    /// Coordination backend that prevents duplicate regeneration.
    /// Defaults to [`LocalIsrCoordinator`] (in-process only).
    /// Use [`with_isr_coordinator`](Self::with_isr_coordinator) to supply
    /// a distributed backend such as `PostgresIsrCoordinator` for
    /// multi-replica deployments.
    isr_coordinator: Arc<dyn IsrCoordinator>,
}

/// A manifest hit: the file to serve and the `Content-Type` to serve it as
/// (#1832).
///
/// Returned by [`StaticFileLayer::resolve_entry`]. The type is already decided
/// — the manifest's recorded value when there is a usable one, otherwise the
/// legacy derivation — so the caller has nothing left to infer. See
/// [`resolved_content_type`] for the ordering.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ResolvedStatic {
    /// Absolute path of the generated file inside `dist/`.
    pub file_path: PathBuf,
    /// The `Content-Type` header to serve, ready to attach to the response.
    pub content_type: http::HeaderValue,
}

/// A byte a recorded `Content-Type` may contain: visible ASCII (`0x20`-`0x7e`),
/// or a horizontal tab.
///
/// HTAB is legal OWS around media-type parameters (RFC 9110), so
/// `application/rss+xml;\tprofile="x"` is a perfectly good header — both
/// `HeaderValue::to_str` and `HeaderValue::from_str` accept it — and rejecting
/// it would send an extensionless `/feed` back to the `feed/index.html`
/// derivation and serve it as `text/html`. Tab is also not part of the hazard
/// this predicate exists for: the compression layer matches its exclusions on
/// `to_str().ok().unwrap_or_default()`, and `to_str` *succeeds* on tab, so a
/// tab-bearing type is matched against the carve-outs in full. What must stay
/// rejected is a value `to_str` fails on (any byte from `0x80` up), or one that
/// is blank after trimming — both read as an empty `Content-Type` there, which
/// silently bypasses the image/audio/video and octet-stream carve-outs and
/// gzips a binary body.
///
/// A tab-*only* value is still rejected: `str::trim` strips it, leaving the
/// empty string the caller refuses.
#[must_use]
fn is_legal_content_type_byte(b: u8) -> bool {
    b == b'\t' || (0x20..0x7f).contains(&b)
}

/// The `Content-Type` values axum attaches only because of a handler's Rust
/// return type: `String`/`&str` give the first, `Vec<u8>`/`Bytes` the second.
/// They state no intent about the page.
const GENERIC_RETURN_TYPE_DEFAULTS: [&str; 2] =
    ["text/plain; charset=utf-8", "application/octet-stream"];

/// Return the `Content-Type` to record or compare for `route_path` (#2409).
///
/// A generic return-type default becomes the route's asset-extension type.
/// Any other value stays as it is. Build records the result. ISR applies it
/// to the expected and the fresh type before comparing.
///
/// Axum's `String` header is the same as a hand-written
/// `text/plain; charset=utf-8`. The two look equal, so the extension wins:
/// `nosniff` blocks a stylesheet served as `text/plain`. To opt out, write
/// bare `text/plain`, or `application/octet-stream` with a parameter.
pub(super) fn effective_content_type<'a>(declared: &'a str, route_path: &str) -> &'a str {
    if GENERIC_RETURN_TYPE_DEFAULTS.contains(&declared)
        && let Some(from_extension) = crate::assets::content_type_for_opt(route_path)
    {
        return from_extension;
    }
    declared
}

/// The recorded `Content-Type` a manifest entry can actually be served with, or
/// `None` when the stored value is unusable (#1832).
///
/// The single validation the whole static path shares. A value is usable when,
/// after trimming, it is non-empty and every byte is
/// [legal](is_legal_content_type_byte) — visible ASCII or a tab.
/// `HeaderValue::from_str` alone is not a sufficient filter: it accepts any byte
/// `>= 0x20` except DEL, so `"   "` and `"text/htmlé"` pass it — and either would produce a
/// `Content-Type` the compression layer reads as empty (it matches its
/// exclusions on `to_str().ok().unwrap_or_default()`), silently bypassing the
/// image/audio/video and octet-stream carve-outs and gzipping a binary body.
/// CR/LF and NUL are rejected by both checks, so header injection is impossible
/// either way.
///
/// Serving, ISR **and generation** must agree on this, which is why it is one
/// function. The serve path ignores an unusable value and derives instead; if
/// the ISR check still treated that same value as authoritative, no handler
/// response could ever match it and every regeneration would be refused forever
/// — a hand-written or tampered manifest would freeze the route rather than
/// merely having its bad value ignored. Generation
/// ([`build::recorded_content_type`](super::build)) screens through the same
/// function so the manifest can never carry a value the serve path will
/// discard — a recorded-then-ignored value is worse than none, because the
/// route silently falls back to the very derivation the recorded value existed
/// to replace.
#[must_use]
pub(super) fn usable_recorded_content_type(recorded: Option<&str>) -> Option<&str> {
    recorded
        .map(str::trim)
        .filter(|value| !value.is_empty() && value.bytes().all(is_legal_content_type_byte))
}

/// The `Content-Type` to serve for a manifest-backed response (#1832).
///
/// The single decision point for the static-first serve path:
///
/// 1. **The type recorded in the manifest**, when there is one and it is a legal
///    header value. This is the intended type, captured at generation time from
///    the handler's own response, so nothing has to be inferred.
/// 2. Otherwise the **route extension**, but only when the final path segment
///    ends in an extension the crate's asset table recognizes.
///    This is what keeps a generated `/robots.txt` (stored as
///    `robots.txt/index.html`) from being mislabeled `text/html`, while a page
///    whose slug merely *contains* a dot (`/posts/release.v1`,
///    `/users/alice@example.com`) is left to step 3 rather than being mislabeled
///    `application/octet-stream`.
/// 3. Otherwise the **served file name**, which resolves every extensionless
///    page (`/about` → `about/index.html` → `text/html`) and any hand-written
///    manifest that maps a route straight at an extensioned file (`/logo` →
///    `logo.png`).
/// 4. Otherwise `application/octet-stream`.
///
/// Steps 2–4 are the pre-#1832 derivation, kept verbatim so an existing `dist/`
/// keeps serving exactly as before until it is rebuilt.
///
/// Returns an `http::HeaderValue` — reachable from downstream code as
/// `autumn_web::reexports::http::HeaderValue`, since `autumn_web::http` is the
/// HTTP *client* module — rather than a string, so the caller cannot fail to
/// build the response.
///
/// A recorded value is used only if, after trimming, it is non-empty and every
/// byte is visible ASCII (`0x20`–`0x7e`) or a horizontal tab — tab is legal OWS
/// around media-type parameters, so rejecting it would send a declared
/// `application/rss+xml;\tprofile="x"` back to the derivation.
/// `HeaderValue::from_str` alone is not a sufficient filter: it accepts any byte
/// `>= 0x20` except DEL, so `"   "` and
/// `"text/htmlé"` pass it. Either would produce a `Content-Type` the compression
/// layer reads as empty (it matches its exclusions on
/// `to_str().ok().unwrap_or_default()`), silently bypassing the image/audio/video
/// and octet-stream carve-outs and gzipping a binary body. CR/LF and NUL are
/// rejected by both checks, so header injection is impossible either way.
/// Anything that fails falls through to the derivation, so a bad manifest can
/// neither panic the request path nor inject a header.
///
/// The URL path is always `/`-delimited, so inspecting its last segment is
/// unaffected by platform path separators.
#[must_use]
pub fn resolved_content_type(
    recorded: Option<&str>,
    route_path: &str,
    file_path: &Path,
) -> http::HeaderValue {
    if let Some(recorded) = usable_recorded_content_type(recorded)
        && let Ok(value) = http::HeaderValue::from_str(effective_content_type(recorded, route_path))
    {
        return value;
    }

    let derived = crate::assets::content_type_for_opt(route_path).unwrap_or_else(|| {
        file_path
            .file_name()
            .and_then(|name| name.to_str())
            .map_or("application/octet-stream", |name| {
                crate::assets::content_type_for(name)
            })
    });
    http::HeaderValue::from_static(derived)
}

/// The `Content-Type` to serve for a manifest `entry` (#2403).
///
/// A declared type is served as is. An inferred one goes through
/// [`resolved_content_type`]. An app that serves `dist/` itself must use this
/// function to match Autumn.
#[must_use]
pub fn resolved_entry_content_type(
    entry: &ManifestEntry,
    route_path: &str,
    file_path: &Path,
) -> http::HeaderValue {
    if entry.content_type_explicit
        && let Some(declared) = usable_recorded_content_type(entry.content_type.as_deref())
        && let Ok(value) = http::HeaderValue::from_str(declared)
    {
        return value;
    }
    resolved_content_type(entry.content_type.as_deref(), route_path, file_path)
}

/// The type ISR must see in a fresh response for `entry`, or `None` for no check.
///
/// A usable declared type is pinned by the route attribute, so the handler
/// header cannot desync from it and needs no guard.
fn isr_expected_content_type(
    entry: &ManifestEntry,
    route_path: &str,
    file_path: &Path,
) -> Option<String> {
    let usable = usable_recorded_content_type(entry.content_type.as_deref());
    if entry.content_type_explicit {
        // An unusable declared value is ignored when serving, so guard the
        // type that is served instead.
        return match usable {
            Some(_) => None,
            None => resolved_content_type(None, route_path, file_path)
                .to_str()
                .ok()
                .map(str::to_owned),
        };
    }
    usable.map(|recorded| effective_content_type(recorded, route_path).to_owned())
}

impl StaticFileLayer {
    /// Try to load a `StaticFileLayer` from a `dist/` directory.
    ///
    /// Looks for `<dist_dir>/manifest.json`. Returns `None` if the file
    /// does not exist or cannot be parsed as a valid [`StaticManifest`].
    ///
    /// ISR routes are detected from the manifest but no regeneration
    /// router is configured. Use [`with_router`](Self::with_router) to
    /// enable ISR regeneration.
    pub fn new(dist_dir: impl Into<PathBuf>) -> Option<Self> {
        let dist_dir = dist_dir.into();
        let manifest_path = dist_dir.join("manifest.json");
        // A manifest that is *present but unparseable* used to disable static
        // serving with no trace at all — every pre-rendered page silently fell
        // through to the dynamic router. Absent is the normal "this app has no
        // static build" case and stays quiet; malformed is a misconfiguration
        // and says so.
        let manifest = match StaticManifest::load(&manifest_path) {
            Ok(manifest) => manifest,
            Err(error) => {
                if manifest_path.exists() {
                    tracing::warn!(
                        manifest = %manifest_path.display(),
                        %error,
                        "static manifest could not be parsed; serving every route \
                         dynamically — re-run `autumn build`"
                    );
                }
                return None;
            }
        };

        let isr_state = build_isr_state(&manifest);

        Some(Self {
            dist_dir,
            manifest: Arc::new(manifest),
            isr_state: Arc::new(isr_state),
            isr_router: None,
            isr_coordinator: Arc::new(LocalIsrCoordinator::new()),
        })
    }

    /// Attach an Axum router for ISR background regeneration.
    ///
    /// Without a router, ISR staleness is detected but pages are never
    /// re-rendered. This method enables the full ISR cycle.
    #[must_use]
    pub fn with_router(mut self, router: axum::Router) -> Self {
        self.isr_router = Some(Arc::new(router));
        self
    }

    /// Set the ISR coordination backend.
    ///
    /// The default is [`LocalIsrCoordinator`], which is suitable for
    /// single-replica and development deployments. For multi-replica
    /// deployments sharing a writable `dist/` volume, supply a distributed
    /// backend such as `PostgresIsrCoordinator` (feature `postgres`) to prevent
    /// stampede writes.
    ///
    /// # Example (production multi-replica)
    ///
    /// ```rust,ignore
    /// use std::sync::Arc;
    /// use autumn_web::static_gen::{StaticFileLayer, PostgresIsrCoordinator};
    ///
    /// let layer = StaticFileLayer::new("dist")
    ///     .unwrap()
    ///     .with_router(app_router)
    ///     .with_isr_coordinator(Arc::new(PostgresIsrCoordinator::new(pool)));
    /// ```
    #[must_use]
    pub fn with_isr_coordinator(mut self, coordinator: Arc<dyn IsrCoordinator>) -> Self {
        self.isr_coordinator = coordinator;
        self
    }

    /// Reference to the loaded manifest.
    #[must_use]
    pub fn manifest(&self) -> &StaticManifest {
        &self.manifest
    }

    /// The `dist/` directory this layer serves files from.
    #[must_use]
    pub fn dist_dir(&self) -> &Path {
        &self.dist_dir
    }

    /// Map a request path (e.g. `"/about"`) to its filesystem path
    /// within `dist/`, based on the manifest.
    ///
    /// Returns `None` if the path is not in the manifest. Does **not**
    /// check whether the file exists on disk -- callers (e.g. `ServeDir`)
    /// handle missing files gracefully.
    ///
    /// If the route has ISR enabled and the file is stale, this method
    /// triggers a background regeneration task (at most one at a time
    /// per route) and still returns the stale file path. The caller
    /// serves the stale content while regeneration happens.
    ///
    /// This is the file-path-only shorthand over
    /// [`resolve_entry`](Self::resolve_entry); use that one when you also need
    /// the `Content-Type` recorded for the route.
    #[must_use]
    pub fn resolve(&self, request_path: &str) -> Option<PathBuf> {
        self.resolve_entry(request_path).map(|hit| hit.file_path)
    }

    /// Resolve a request path to the file to serve **and** the `Content-Type`
    /// recorded for it at generation time (#1832).
    ///
    /// Same lookup and same ISR side effect as [`resolve`](Self::resolve); the
    /// difference is that the recorded MIME type comes back with the path
    /// instead of being thrown away, so the serve path never has to
    /// reverse-engineer it from the route slug and the served file name.
    ///
    /// [`ResolvedStatic::content_type`] is the final header value: the recorded
    /// type when the manifest has a usable one, otherwise the legacy derivation
    /// (see [`resolved_content_type`]). The recorded value is read as a `&str`
    /// borrowed from the shared manifest rather than cloned; a recorded type
    /// still costs the one `HeaderValue` allocation the response needs either
    /// way, and a derived one is `HeaderValue::from_static` and allocates
    /// nothing.
    #[must_use]
    pub fn resolve_entry(&self, request_path: &str) -> Option<ResolvedStatic> {
        let entry = self.manifest.routes.get(request_path)?;
        let file_path = self.dist_dir.join(&entry.file);

        // Check ISR staleness
        if let Some(revalidate) = entry.revalidate {
            self.maybe_trigger_isr(
                request_path,
                &file_path,
                revalidate,
                // Only a value the serve path would actually honour: an
                // unusable one is ignored there, so treating it as the ISR
                // expectation would refuse every regeneration forever.
                isr_expected_content_type(entry, request_path, &file_path).as_deref(),
            );
        }

        let content_type = resolved_entry_content_type(entry, request_path, &file_path);

        Some(ResolvedStatic {
            file_path,
            content_type,
        })
    }

    /// Check if a file is stale and trigger background regeneration if needed.
    fn maybe_trigger_isr(
        &self,
        url_path: &str,
        file_path: &Path,
        revalidate_secs: u64,
        recorded_content_type: Option<&str>,
    ) {
        // Check file age
        let is_stale = file_mtime_age_secs(file_path).is_none_or(|age| age > revalidate_secs);

        if !is_stale {
            return;
        }

        let Some(route_state) = self.isr_state.get(url_path) else {
            return;
        };

        let Some(router) = &self.isr_router else {
            // No router configured -- ISR detection only, no regeneration
            return;
        };

        // Check cooldown -- don't retry too fast after a failure
        let now = unix_now();
        let last = route_state.last_attempt.load(Ordering::Relaxed);
        if last > 0 && now.saturating_sub(last) < REGEN_COOLDOWN_SECS {
            return;
        }

        // Try to claim the in-flight flag (CAS: false -> true).
        // This prevents this process from spawning more than one task per route.
        if route_state
            .in_flight
            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Relaxed)
            .is_err()
        {
            // Another task is already regenerating this route in this process
            return;
        }

        // Record attempt time
        route_state.last_attempt.store(now, Ordering::Relaxed);

        // Compute the revalidation window key for distributed coordination
        let window_key = isr_window_key(url_path, revalidate_secs, now);

        // Spawn background regeneration
        let router = Arc::clone(router);
        let url = url_path.to_owned();
        let dest = file_path.to_owned();
        let in_flight = Arc::clone(&self.isr_state);
        let coordinator = Arc::clone(&self.isr_coordinator);
        let expected_content_type = recorded_content_type.map(str::to_owned);

        tokio::spawn(async move {
            // RAII guard: clears the in_flight flag when this scope exits,
            // including on panic, so ISR is never permanently disabled for
            // a route after a handler crash.
            let _guard = InFlightReset {
                state: &in_flight,
                url: &url,
            };

            // Distributed coordination: prevents multiple replicas from
            // regenerating the same route in the same revalidation window.
            let acquired = coordinator.try_acquire(&url, &window_key).await;
            if !acquired {
                tracing::debug!(
                    "ISR: another replica holds the lock for this window, skipping (route: {}, backend: {})",
                    url,
                    coordinator.backend()
                );
                return; // _guard drops here, resetting in_flight
            }

            let result =
                regenerate_page(&router, &url, &dest, expected_content_type.as_deref()).await;

            // Release distributed lock before the guard drops.
            coordinator.release(&url, &window_key).await;

            match result {
                Ok(()) => {
                    tracing::info!("ISR: page regenerated for route: {}", url);
                }
                Err(e) => {
                    tracing::warn!("ISR: regeneration failed for route: {}, error: {}", url, e);
                }
            }
            // _guard drops here, resetting in_flight
        });
    }
}

/// RAII guard that resets the per-route `in_flight` flag when dropped.
///
/// Placed at the top of every ISR background task so the flag is always
/// cleared on normal exit, early return, or panic.
struct InFlightReset<'a> {
    state: &'a HashMap<String, IsrRouteState>,
    url: &'a str,
}

impl Drop for InFlightReset<'_> {
    fn drop(&mut self) {
        if let Some(s) = self.state.get(self.url) {
            s.in_flight.store(false, Ordering::Release);
        }
    }
}

/// Build per-route ISR state from the manifest. Only routes with
/// `revalidate` set get entries.
fn build_isr_state(manifest: &StaticManifest) -> HashMap<String, IsrRouteState> {
    let mut state = HashMap::new();
    for (path, entry) in &manifest.routes {
        if entry.revalidate.is_some() {
            state.insert(
                path.clone(),
                IsrRouteState {
                    in_flight: AtomicBool::new(false),
                    last_attempt: AtomicU64::new(0),
                },
            );
        }
    }
    state
}

/// Whether two `Content-Type` header values mean the same thing.
///
/// The ISR refusal compares the regenerated response's type against the string
/// the build recorded, and a false mismatch there freezes the route until the
/// next `autumn build`. `text/html;charset=utf-8` and `text/html; charset=utf-8`
/// are one type spelled two ways, and a layer that reconstructs the header can
/// easily change the spacing — so compare on meaning rather than on bytes.
///
/// "Meaning" follows RFC 9110 §8.3 rather than being a blanket
/// lowercase-and-strip: the **media type** and **parameter names** are
/// case-insensitive, and parameter order is not significant, but a parameter
/// **value** is case-sensitive and its interior spacing is its own. Flattening
/// values would be a correctness bug in the safety-critical direction: a
/// `multipart/…; boundary=Aa` recorded at build time would compare equal to a
/// regenerated `boundary=aa`, so ISR would overwrite the body while every
/// request still advertised the old boundary — exactly the undecodable-response
/// desync this check exists to prevent. The exceptions are the parameters
/// whose *values* their own specifications define as case-insensitive: `charset`
/// (RFC 2046 §4.1.2) and the parameters whose value is itself a media type —
/// `type` on `multipart/related` (RFC 2387 §3.1), `protocol` on
/// `multipart/signed` and `multipart/encrypted` (RFC 1847 §§2.1, 2.2). See
/// [`parameter_value_case_insensitive`].
///
/// Quoted values are unquoted (decoding quoted-pairs, so `boundary="a\b"` and
/// `boundary=ab` agree), and `;` inside quotes does not split a parameter.
fn content_type_equivalent(a: &str, b: &str) -> bool {
    normalize_content_type(a) == normalize_content_type(b)
}

/// Split a header value on `;`, ignoring separators inside a quoted string.
fn split_unquoted_semicolons(value: &str) -> Vec<&str> {
    let mut parts = Vec::new();
    let mut start = 0;
    let mut in_quotes = false;
    let mut escaped = false;
    for (index, byte) in value.bytes().enumerate() {
        if escaped {
            escaped = false;
        } else if byte == b'\\' && in_quotes {
            escaped = true;
        } else if byte == b'"' {
            in_quotes = !in_quotes;
        } else if byte == b';' && !in_quotes {
            parts.push(&value[start..index]);
            start = index + 1;
        }
    }
    parts.push(&value[start..]);
    parts
}

/// Decode quoted-pairs inside a quoted MIME parameter value (RFC 9110 §5.6.4).
///
/// Inside a quoted-string, `\` followed by any character denotes that
/// character alone, so `boundary="a\b"` and `boundary="ab"` are the *same*
/// value. Decoding here keeps the normalizer from letting the escape
/// backslash make two spellings of one value compare unequal — an ISR
/// freeze on a route whose header was merely reserialized between
/// `autumn build` and regeneration.
///
/// Only quoted values are touched; an unquoted value is returned as-is so a
/// backslash that is genuinely part of a token never gets rewritten. A lone
/// trailing `\` escapes nothing and is dropped; it must neither panic nor
/// discard the rest of the value.
fn decode_quoted_pairs(raw_value: &str) -> Cow<'_, str> {
    let Some(inner) = raw_value
        .strip_prefix('"')
        .and_then(|v| v.strip_suffix('"'))
    else {
        return Cow::Borrowed(raw_value);
    };
    if !inner.contains('\\') {
        return Cow::Borrowed(inner);
    }
    let mut decoded = String::with_capacity(inner.len());
    let mut chars = inner.chars();
    while let Some(c) = chars.next() {
        if c == '\\' {
            if let Some(escaped) = chars.next() {
                decoded.push(escaped);
            }
        } else {
            decoded.push(c);
        }
    }
    Cow::Owned(decoded)
}

/// Whether a MIME parameter's *value* is case-insensitive per its own
/// specification.
///
/// Parameter-value case sensitivity is defined per parameter by its own
/// specification, not by a single well-known name. This is the whitelist
/// `normalize_content_type` applies when canonicalizing:
///
/// - `charset` — case-insensitive on every media type (RFC 2046 §4.1.2);
/// - `type` on `multipart/related` (RFC 2387 §3.1) and `protocol` on
///   `multipart/signed` / `multipart/encrypted` (RFC 1847 §§2.1, 2.2) — the
///   parameters whose value is itself a media type. Media types are
///   case-insensitive (RFC 9110 §8.3), so `type="TEXT/HTML"` and
///   `type="text/html"` denote the same thing there.
///
/// Everything else keeps its value byte-verbatim. `boundary` in particular
/// stays case-sensitive: a build-time `boundary=Aa` matching a regenerated
/// `boundary=aa` would let ISR overwrite a body whose advertised boundary no
/// longer decodes it. `type` and `protocol` on any other media type are
/// likewise verbatim — no specification gives them media-type semantics there.
fn parameter_value_case_insensitive(media_type: &str, name: &str) -> bool {
    if name == "charset" {
        return true;
    }
    match name {
        "type" => media_type == "multipart/related",
        "protocol" => matches!(media_type, "multipart/signed" | "multipart/encrypted"),
        _ => false,
    }
}

/// Canonical form of a `Content-Type` for comparison: the lowercased media type
/// followed by its parameters as sorted `name=value` pairs, names lowercased,
/// and values left alone apart from unquoting — except parameters whose value
/// is case-insensitive per its own specification (see
/// [`parameter_value_case_insensitive`]), which are lowercased too.
/// See [`content_type_equivalent`].
fn normalize_content_type(value: &str) -> Vec<String> {
    let mut segments = split_unquoted_semicolons(value).into_iter();
    let media_type = segments.next().unwrap_or("").trim().to_ascii_lowercase();

    let mut parameters: Vec<String> = segments
        // An empty segment carries no meaning, so a trailing or doubled `;`
        // must not make two otherwise-identical types compare unequal. Without
        // this, a handler that re-emits `text/html; charset=utf-8;` would be
        // refused by the ISR check forever against a recorded
        // `text/html; charset=utf-8`, freezing the route until the next build.
        .filter(|segment| !segment.trim().is_empty())
        .map(|segment| {
            let segment = segment.trim();
            let Some((name, raw_value)) = segment.split_once('=') else {
                // A malformed segment with no `=` has no value to protect.
                return segment.to_ascii_lowercase();
            };
            let name = name.trim().to_ascii_lowercase();
            let raw_value = raw_value.trim();
            // Unquote quoted values, decoding quoted-pairs so e.g.
            // `boundary="a\b"` and `boundary="ab"` normalize the same.
            let unquoted = decode_quoted_pairs(raw_value);
            if parameter_value_case_insensitive(&media_type, &name) {
                format!("{name}={}", unquoted.to_ascii_lowercase())
            } else {
                format!("{name}={unquoted}")
            }
        })
        .collect();
    // Parameter order carries no meaning.
    parameters.sort();

    let mut normalized = Vec::with_capacity(parameters.len() + 1);
    normalized.push(media_type);
    normalized.extend(parameters);
    normalized
}

/// Re-render a single page by sending a request through the router.
async fn regenerate_page(
    router: &axum::Router,
    url: &str,
    dest: &Path,
    expected_content_type: Option<&str>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    use axum::body::Body;
    use axum::http::Request;
    use tower::ServiceExt;

    let response = router
        .clone()
        .oneshot(
            Request::builder()
                .uri(url)
                // Internal ISR regeneration render: exempt from the inbound
                // request-timeout deadline (no client connection).
                .extension(super::RenderDeadlineExempt)
                .body(Body::empty())
                .expect("valid request"),
        )
        .await
        .expect("router infallible");

    if !response.status().is_success() {
        return Err(format!("Handler returned HTTP {} for {}", response.status(), url).into());
    }

    // #1832: the manifest's recorded Content-Type is a build-time property, and
    // ISR deliberately does not rewrite the manifest (the design keeps it
    // immutable behind an `Arc` and uses file mtime for staleness, avoiding
    // write contention). So the header served for this route is fixed for the
    // process lifetime while the *body* on disk is not.
    //
    // That makes a type change during regeneration a body/header desync waiting
    // to happen: writing bytes the handler now calls `application/json` into a
    // file still advertised as `text/html` would serve undecodable content. A
    // handler that stops declaring a type at all is the same hazard — the
    // recorded type would keep being asserted over bytes nothing vouches for.
    //
    // Refuse the regeneration instead. The previous file stays on disk and
    // keeps matching its recorded type, so the route degrades to stale-but-
    // correct rather than fresh-but-mislabeled. The error propagates to the
    // caller's existing `warn!`, and the ISR cooldown throttles the retries; a
    // rebuild (`autumn build`) is what re-records the type.
    if let Some(expected) = expected_content_type {
        // Same normalization as build, so a generic default compares equal to
        // the extension type it was recorded as (#2409).
        let actual = response
            .headers()
            .get(axum::http::header::CONTENT_TYPE)
            .and_then(|v| v.to_str().ok())
            .map(|v| effective_content_type(v.trim(), url));
        if !actual.is_some_and(|actual| content_type_equivalent(actual, expected)) {
            // Logged here as well as by the caller: an ordinary regeneration
            // failure is transient, but this one repeats every cooldown until
            // someone rebuilds, so it needs to be greppable on its own.
            tracing::error!(
                route = url,
                manifest_content_type = expected,
                handler_content_type = actual.unwrap_or("<none>"),
                "ISR: refusing to regenerate — the handler's Content-Type no longer matches \
                 the one recorded in the manifest, and the manifest is not rewritten at \
                 runtime, so the new body would be served under the old header. The existing \
                 page is still served. Re-run `autumn build` to refresh the manifest."
            );
            return Err(format!(
                "Content-Type changed for {url}: manifest records {expected:?} but the handler \
                 now declares {actual:?}; refusing to write a body the recorded type would \
                 mislabel — re-run `autumn build` to refresh the manifest"
            )
            .into());
        }
    }

    let body_bytes = axum::body::to_bytes(response.into_body(), usize::MAX).await?;

    // Write to a temp file, then atomically rename to avoid serving partial content
    let temp_path = dest.with_extension("tmp");
    std::fs::write(&temp_path, &body_bytes)?;
    std::fs::rename(&temp_path, dest)?;

    Ok(())
}

/// Get the age of a file in seconds based on its modification time.
/// Returns `None` if the file doesn't exist or metadata can't be read.
#[allow(
    clippy::disallowed_methods,
    reason = "the OS stamps the file mtime with real time, so compare it with real time"
)]
fn file_mtime_age_secs(path: &Path) -> Option<u64> {
    let metadata = std::fs::metadata(path).ok()?;
    let mtime = metadata.modified().ok()?;
    let elapsed = SystemTime::now().duration_since(mtime).ok()?;
    Some(elapsed.as_secs())
}

/// Current Unix timestamp in seconds.
fn unix_now() -> u64 {
    crate::time::clock_unix_secs(&crate::time::AmbientClock)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::static_gen::{ManifestEntry, StaticManifest};
    use std::collections::HashMap;

    /// Helper: create a temp dist dir with manifest.json and some HTML files.
    fn create_test_dist() -> tempfile::TempDir {
        let dir = tempfile::tempdir().expect("tempdir");
        let dist = dir.path().join("dist");

        // Create directories
        std::fs::create_dir_all(dist.join("about")).expect("mkdir about");

        // Create HTML files
        std::fs::write(dist.join("index.html"), "<h1>Home</h1>").expect("write index");
        std::fs::write(dist.join("about/index.html"), "<h1>About</h1>").expect("write about");

        // Build and write manifest
        let mut routes = HashMap::new();
        routes.insert("/".to_owned(), ManifestEntry::new("index.html".to_owned()));
        routes.insert(
            "/about".to_owned(),
            ManifestEntry::new("about/index.html".to_owned()).with_revalidate(Some(3600)),
        );

        let manifest = StaticManifest {
            generated_at: "2026-03-27T12:00:00Z".to_owned(),
            autumn_version: "0.3.0".to_owned(),
            routes,
        };

        let json = serde_json::to_string(&manifest).expect("serialize manifest");
        std::fs::write(dist.join("manifest.json"), json).expect("write manifest");

        dir
    }

    /// Helper: create a dist dir with parameterized routes in the manifest.
    fn create_parameterized_dist() -> tempfile::TempDir {
        let dir = tempfile::tempdir().expect("tempdir");
        let dist = dir.path().join("dist");

        // Create directories
        std::fs::create_dir_all(dist.join("posts/hello")).expect("mkdir posts/hello");
        std::fs::create_dir_all(dist.join("posts/world")).expect("mkdir posts/world");

        // Create HTML files
        std::fs::write(dist.join("posts/hello/index.html"), "<h1>Hello</h1>").expect("write hello");
        std::fs::write(dist.join("posts/world/index.html"), "<h1>World</h1>").expect("write world");

        // Build and write manifest
        let mut routes = HashMap::new();
        routes.insert(
            "/posts/hello".to_owned(),
            ManifestEntry::new("posts/hello/index.html".to_owned()),
        );
        routes.insert(
            "/posts/world".to_owned(),
            ManifestEntry::new("posts/world/index.html".to_owned()),
        );

        let manifest = StaticManifest {
            generated_at: "2026-03-29T12:00:00Z".to_owned(),
            autumn_version: "0.3.0".to_owned(),
            routes,
        };

        let json = serde_json::to_string(&manifest).expect("serialize manifest");
        std::fs::write(dist.join("manifest.json"), json).expect("write manifest");

        dir
    }

    /// Helper: create a dist dir with ISR routes.
    fn create_isr_dist(revalidate: u64) -> tempfile::TempDir {
        let dir = tempfile::tempdir().expect("tempdir");
        let dist = dir.path().join("dist");

        std::fs::create_dir_all(dist.join("about")).expect("mkdir about");
        std::fs::write(dist.join("about/index.html"), "<h1>About (stale)</h1>")
            .expect("write about");

        let mut routes = HashMap::new();
        routes.insert(
            "/about".to_owned(),
            ManifestEntry::new("about/index.html".to_owned()).with_revalidate(Some(revalidate)),
        );

        let manifest = StaticManifest {
            generated_at: "2026-03-29T12:00:00Z".to_owned(),
            autumn_version: "0.3.0".to_owned(),
            routes,
        };

        let json = serde_json::to_string(&manifest).expect("serialize manifest");
        std::fs::write(dist.join("manifest.json"), json).expect("write manifest");

        dir
    }

    #[test]
    fn layer_loads_from_valid_dist() {
        let tmp = create_test_dist();
        let dist = tmp.path().join("dist");
        let layer = StaticFileLayer::new(&dist);
        assert!(layer.is_some(), "should load from valid dist dir");
    }

    #[test]
    fn layer_returns_none_without_manifest() {
        let tmp = tempfile::tempdir().expect("tempdir");
        // No manifest.json at all
        let layer = StaticFileLayer::new(tmp.path());
        assert!(layer.is_none(), "should return None without manifest.json");
    }

    /// A manifest that is *present but unparseable* also disables static
    /// serving — but unlike the absent case it is a misconfiguration, so
    /// `StaticFileLayer::new` warns rather than failing silently. Absent stays
    /// quiet: that is simply an app with no static build.
    #[test]
    fn layer_returns_none_for_an_unparseable_manifest() {
        let tmp = tempfile::tempdir().expect("tempdir");
        std::fs::write(tmp.path().join("manifest.json"), "{ not json").expect("write");
        assert!(
            StaticFileLayer::new(tmp.path()).is_none(),
            "an unparseable manifest must disable static serving, not panic"
        );

        // A manifest carrying a key this runtime does not know still loads —
        // the forward-compatibility STABILITY.md promises for an older runtime
        // reading a manifest written by a newer Autumn.
        std::fs::write(
            tmp.path().join("manifest.json"),
            r#"{"generated_at":"1","autumn_version":"0.0.0","routes":{
                "/about":{"file":"about/index.html","revalidate":null,
                          "content_type":"text/html","future_field":42}}}"#,
        )
        .expect("write");
        let layer = StaticFileLayer::new(tmp.path()).expect("unknown keys must be ignored");
        assert_eq!(
            layer
                .resolve_entry("/about")
                .expect("resolves")
                .content_type,
            "text/html"
        );
    }

    #[test]
    fn resolve_finds_known_route() {
        let tmp = create_test_dist();
        let dist = tmp.path().join("dist");
        let layer = StaticFileLayer::new(&dist).expect("layer");

        let resolved = layer.resolve("/about");
        assert!(resolved.is_some(), "/about should resolve");
        assert!(
            resolved.unwrap().ends_with("about/index.html"),
            "should point to about/index.html"
        );
    }

    #[test]
    fn resolve_finds_root() {
        let tmp = create_test_dist();
        let dist = tmp.path().join("dist");
        let layer = StaticFileLayer::new(&dist).expect("layer");

        let resolved = layer.resolve("/");
        assert!(resolved.is_some(), "/ should resolve");
        assert!(
            resolved.unwrap().ends_with("index.html"),
            "should point to index.html"
        );
    }

    #[test]
    fn resolve_returns_none_for_unknown_route() {
        let tmp = create_test_dist();
        let dist = tmp.path().join("dist");
        let layer = StaticFileLayer::new(&dist).expect("layer");

        let resolved = layer.resolve("/admin");
        assert!(resolved.is_none(), "/admin should not resolve");
    }

    #[test]
    fn manifest_accessor() {
        let tmp = create_test_dist();
        let dist = tmp.path().join("dist");
        let layer = StaticFileLayer::new(&dist).expect("layer");

        assert_eq!(layer.manifest().routes.len(), 2);
    }

    // --- Parameterized route middleware tests ---

    #[test]
    fn resolve_finds_parameterized_routes() {
        let tmp = create_parameterized_dist();
        let dist = tmp.path().join("dist");
        let layer = StaticFileLayer::new(&dist).expect("layer");

        let hello = layer.resolve("/posts/hello");
        assert!(hello.is_some(), "/posts/hello should resolve");
        assert!(hello.unwrap().ends_with("posts/hello/index.html"));

        let world = layer.resolve("/posts/world");
        assert!(world.is_some(), "/posts/world should resolve");
        assert!(world.unwrap().ends_with("posts/world/index.html"));
    }

    #[test]
    fn resolve_returns_none_for_non_generated_param() {
        let tmp = create_parameterized_dist();
        let dist = tmp.path().join("dist");
        let layer = StaticFileLayer::new(&dist).expect("layer");

        // This slug was not in the params list, so not in the manifest
        let resolved = layer.resolve("/posts/unknown");
        assert!(
            resolved.is_none(),
            "/posts/unknown should not resolve (not pre-rendered)"
        );
    }

    // --- ISR tests ---

    #[test]
    fn isr_state_built_for_revalidate_routes() {
        let tmp = create_test_dist();
        let dist = tmp.path().join("dist");
        let layer = StaticFileLayer::new(&dist).expect("layer");

        // /about has revalidate=3600, / does not
        assert!(layer.isr_state.contains_key("/about"));
        assert!(!layer.isr_state.contains_key("/"));
    }

    #[test]
    fn file_mtime_age_fresh_file() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let file = tmp.path().join("test.html");
        std::fs::write(&file, "test").expect("write");

        // File just created, age should be very small
        let age = file_mtime_age_secs(&file).expect("mtime");
        assert!(age < 5, "Fresh file should be < 5 seconds old, got {age}");
    }

    #[test]
    fn file_mtime_age_missing_file() {
        let age = file_mtime_age_secs(Path::new("/nonexistent/file.html"));
        assert!(age.is_none(), "Missing file should return None");
    }

    #[tokio::test]
    async fn isr_triggers_regeneration_for_stale_page() {
        // Create a dist dir with a very short revalidate (1 second)
        let tmp = create_isr_dist(1);
        let dist = tmp.path().join("dist");

        // Make the file old by setting mtime to the past
        let file = dist.join("about/index.html");
        let old_time = std::time::SystemTime::now() - std::time::Duration::from_secs(100);
        filetime::set_file_mtime(&file, filetime::FileTime::from_system_time(old_time))
            .unwrap_or(());

        // Create a router that returns fresh content
        let router =
            axum::Router::new().fallback(axum::routing::get(|| async { "<h1>About (fresh)</h1>" }));

        let layer = StaticFileLayer::new(&dist)
            .expect("layer")
            .with_router(router);

        // Resolve should return the stale file path but trigger ISR
        let resolved = layer.resolve("/about");
        assert!(resolved.is_some());

        // Give the background task time to complete
        tokio::time::sleep(std::time::Duration::from_millis(200)).await;

        // Check if file was updated (only if mtime was successfully set)
        let content = std::fs::read_to_string(&file).unwrap();
        // The content should be updated if ISR fired, or remain stale
        // if filetime wasn't available. Either way, resolve works.
        assert!(
            content == "<h1>About (fresh)</h1>" || content == "<h1>About (stale)</h1>",
            "unexpected content: {content}"
        );
    }

    #[tokio::test]
    async fn isr_does_not_retrigger_while_in_flight() {
        let tmp = create_isr_dist(1);
        let dist = tmp.path().join("dist");

        let router = axum::Router::new().fallback(axum::routing::get(|| async {
            // Simulate slow handler
            tokio::time::sleep(std::time::Duration::from_millis(500)).await;
            "<h1>Slow</h1>"
        }));

        let layer = StaticFileLayer::new(&dist)
            .expect("layer")
            .with_router(router);

        // Make file stale
        let file = dist.join("about/index.html");
        let old_time = std::time::SystemTime::now() - std::time::Duration::from_secs(100);
        let _ = filetime::set_file_mtime(&file, filetime::FileTime::from_system_time(old_time));

        // First resolve triggers ISR
        let _ = layer.resolve("/about");

        // Check in-flight flag
        let state = layer.isr_state.get("/about").expect("isr state");
        // May or may not be true depending on timing, but second resolve
        // should not panic or double-trigger
        let _ = layer.resolve("/about");

        // Wait for background task
        tokio::time::sleep(std::time::Duration::from_millis(700)).await;

        // Flag should be cleared
        assert!(
            !state.in_flight.load(Ordering::Relaxed),
            "in_flight should be cleared after regeneration"
        );
    }

    #[tokio::test]
    async fn regenerate_page_writes_atomically() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let dest = tmp.path().join("page.html");
        std::fs::write(&dest, "old content").expect("write old");

        let router = axum::Router::new().fallback(axum::routing::get(|| async { "new content" }));

        let result = regenerate_page(&router, "/test", &dest, None).await;
        assert!(result.is_ok(), "regeneration failed: {:?}", result.err());

        let content = std::fs::read_to_string(&dest).unwrap();
        assert_eq!(content, "new content");

        // Temp file should be cleaned up
        assert!(!dest.with_extension("tmp").exists());
    }

    #[tokio::test]
    async fn regenerate_page_fails_on_non_2xx() {
        let tmp = tempfile::tempdir().expect("tempdir");
        let dest = tmp.path().join("page.html");
        std::fs::write(&dest, "old content").expect("write old");

        let router = axum::Router::new()
            .fallback(|| async { (axum::http::StatusCode::INTERNAL_SERVER_ERROR, "error") });

        let result = regenerate_page(&router, "/test", &dest, None).await;
        assert!(result.is_err());

        // Original file should be untouched
        let content = std::fs::read_to_string(&dest).unwrap();
        assert_eq!(content, "old content");
    }

    #[tokio::test]
    async fn isr_coordinator_deny_clears_in_flight_and_skips_regen() {
        use crate::static_gen::isr_coordinator::IsrFuture;

        // A coordinator that always denies acquisition — exercises the
        // `if !acquired { return; }` branch in the spawned ISR task.
        struct DenyCoordinator;
        impl IsrCoordinator for DenyCoordinator {
            fn backend(&self) -> &'static str {
                "deny"
            }

            fn try_acquire<'a>(&'a self, _: &'a str, _: &'a str) -> IsrFuture<'a, bool> {
                Box::pin(async { false })
            }

            fn release<'a>(&'a self, _: &'a str, _: &'a str) -> IsrFuture<'a, ()> {
                Box::pin(async {})
            }
        }

        let tmp = create_isr_dist(1);
        let dist = tmp.path().join("dist");
        let file = dist.join("about/index.html");

        let old_time = std::time::SystemTime::now() - std::time::Duration::from_secs(100);
        let _ = filetime::set_file_mtime(&file, filetime::FileTime::from_system_time(old_time));

        let router =
            axum::Router::new().fallback(axum::routing::get(|| async { "should not appear" }));
        let layer = StaticFileLayer::new(&dist)
            .expect("layer")
            .with_router(router)
            .with_isr_coordinator(Arc::new(DenyCoordinator));

        // Trigger the ISR background task.
        let _ = layer.resolve("/about");

        // Wait for the spawned task to run the deny branch and exit.
        tokio::time::sleep(std::time::Duration::from_millis(200)).await;

        // InFlightReset guard must have cleared the flag despite early return.
        let state = layer.isr_state.get("/about").unwrap();
        assert!(
            !state.in_flight.load(Ordering::Relaxed),
            "in_flight must be cleared when coordinator denies acquisition"
        );

        // File must be unchanged — regeneration was skipped.
        assert_eq!(
            std::fs::read_to_string(&file).unwrap(),
            "<h1>About (stale)</h1>"
        );
    }

    // ── #1832: Content-Type recorded at generation time ─────────────────────

    /// The recorded type wins outright — including a type the serve-time
    /// extension heuristic can never produce from an extensionless route.
    #[test]
    fn resolved_content_type_prefers_recorded_value() {
        let ct = resolved_content_type(
            Some("application/rss+xml"),
            "/feed",
            Path::new("feed/index.html"),
        );
        assert_eq!(ct, "application/rss+xml");
    }

    /// A recorded type overrides what the route extension would have said, so a
    /// route may be generated with a type its slug does not advertise.
    #[test]
    fn resolved_content_type_recorded_overrides_route_extension() {
        let ct = resolved_content_type(
            Some("application/manifest+json"),
            "/feed.xml",
            Path::new("feed.xml/index.html"),
        );
        assert_eq!(
            ct, "application/manifest+json",
            "`.xml` is a recognized asset extension deriving `application/xml`; \
             the recorded value must beat it"
        );
    }

    /// An empty recorded value is not a `Content-Type`; it must not produce an
    /// empty header.
    #[test]
    fn resolved_content_type_ignores_empty_recorded_value() {
        let ct = resolved_content_type(Some(""), "/about", Path::new("about/index.html"));
        assert_eq!(ct, "text/html; charset=utf-8");
    }

    /// A recorded value that `HeaderValue::from_str` would *accept* but that is
    /// not a usable `Content-Type` must still fall back. `from_str` only rejects
    /// bytes below 0x20 (except tab) and DEL, so blanks, tabs and any byte from
    /// 0x80 up sail through it — and the compression layer reads such a header
    /// as empty, bypassing its binary carve-outs and gzipping the body.
    #[test]
    fn resolved_content_type_rejects_blank_and_non_ascii_recorded_values() {
        for bad in ["   ", "\t", "text/htmlé", "text/html\u{80}"] {
            assert!(
                http::HeaderValue::from_str(bad).is_ok(),
                "{bad:?} is supposed to be a value from_str accepts — otherwise \
                 this test is not exercising the extra check"
            );
            assert_eq!(
                resolved_content_type(Some(bad), "/about", Path::new("about/index.html")),
                "text/html; charset=utf-8",
                "{bad:?} must fall back rather than becoming a Content-Type"
            );
        }
    }

    /// Surrounding whitespace is trimmed rather than treated as a rejection —
    /// `" text/css "` is still `text/css`.
    #[test]
    fn resolved_content_type_trims_recorded_value() {
        assert_eq!(
            resolved_content_type(
                Some("  application/rss+xml  "),
                "/feed",
                Path::new("f.html")
            ),
            "application/rss+xml"
        );
    }

    #[test]
    fn content_type_equivalent_ignores_spacing_and_media_type_case() {
        assert!(content_type_equivalent(
            "text/html;charset=utf-8",
            "text/html; charset=utf-8"
        ));
        assert!(content_type_equivalent("TEXT/HTML", "  text/html  "));
        // Parameter names are case-insensitive; order carries no meaning.
        assert!(content_type_equivalent(
            "multipart/mixed; BOUNDARY=xyz; charset=utf-8",
            "multipart/mixed; charset=utf-8; boundary=xyz"
        ));
        // `charset` values are case-insensitive (RFC 2046 §4.1.2).
        assert!(content_type_equivalent(
            "text/html; charset=UTF-8",
            "text/html; charset=utf-8"
        ));
        // Quoting a value does not change it.
        assert!(content_type_equivalent(
            r#"multipart/mixed; boundary="xyz""#,
            "multipart/mixed; boundary=xyz"
        ));

        // A different media type or a different parameter value is a real
        // change and must still be caught.
        assert!(!content_type_equivalent("text/html", "application/json"));
        assert!(!content_type_equivalent(
            "text/html; charset=utf-8",
            "text/html; charset=iso-8859-1"
        ));
    }

    /// A parameter whose value is itself a media type is case-insensitive:
    /// `type` on `multipart/related` (RFC 2387 §3.1), `protocol` on
    /// `multipart/signed` and `multipart/encrypted` (RFC 1847 §§2.1, 2.2). A harmless
    /// reserialization between `autumn build` and regeneration — a layer that
    /// rewrites the header, a library that normalizes media-type case — must
    /// not freeze the route the way a raw byte comparison would.
    #[test]
    fn content_type_equivalent_treats_media_type_valued_type_parameter_case_insensitively() {
        // The bug: these denote the same thing but normalized differently.
        assert!(content_type_equivalent(
            r#"multipart/related; type="TEXT/HTML""#,
            r#"multipart/related; type="text/html""#
        ));
        assert!(content_type_equivalent(
            "multipart/related; TYPE=Text/Html",
            "multipart/related; type=text/html"
        ));
        // Same rule for the RFC 1847 types, whose media-type-valued parameter
        // is `protocol` (§§2.1, 2.2).
        assert!(content_type_equivalent(
            r#"multipart/signed; protocol="APPLICATION/PKCS7-SIGNATURE""#,
            r#"multipart/signed; protocol="application/pkcs7-signature""#
        ));
        assert!(content_type_equivalent(
            r#"multipart/encrypted; protocol="APPLICATION/PGP-ENCRYPTED""#,
            r#"multipart/encrypted; protocol="application/pgp-encrypted""#
        ));
        // …and there `type` has no media-type semantics, so it stays verbatim,
        // as does `protocol` on `multipart/related`.
        assert!(!content_type_equivalent(
            "multipart/signed; type=BAR",
            "multipart/signed; type=bar"
        ));
        assert!(!content_type_equivalent(
            "multipart/related; protocol=BAR",
            "multipart/related; protocol=bar"
        ));

        // Must not regress: a genuinely different media type value still
        // compares unequal.
        assert!(!content_type_equivalent(
            r#"multipart/related; type="text/html""#,
            r#"multipart/related; type="application/json""#
        ));
        // `type` on a media type where no specification gives it media-type
        // semantics keeps its value verbatim.
        assert!(!content_type_equivalent(
            "application/example; type=BAR",
            "application/example; type=bar"
        ));
        // And `boundary` stays case-sensitive on multipart types too.
        assert!(!content_type_equivalent(
            "multipart/related; type=text/html; boundary=Aa",
            "multipart/related; type=text/html; boundary=aa"
        ));
    }

    /// Parameter values are case-sensitive except where their own specification
    /// says otherwise (`charset` everywhere; `type`/`protocol` where the value is
    /// a media type — see [`parameter_value_case_insensitive`]), and their interior
    /// spacing is their own. Flattening them would be a bug in the
    /// dangerous direction: a recorded `boundary=Aa` matching a regenerated
    /// `boundary=aa` lets ISR overwrite the body while every request still
    /// advertises the old boundary, making the multipart response undecodable.
    /// An empty parameter segment carries no meaning. Treating one as a real
    /// parameter would make a handler that re-emits `text/html; charset=utf-8;`
    /// compare unequal to the recorded `text/html; charset=utf-8`, so
    /// `regenerate_page` would refuse every regeneration and the route would
    /// serve stale content until the next `autumn build` — the frozen-route
    /// failure this comparison exists to avoid.
    #[test]
    fn content_type_equivalent_ignores_empty_parameter_segments() {
        assert!(content_type_equivalent(
            "text/html; charset=utf-8",
            "text/html; charset=utf-8;"
        ));
        assert!(content_type_equivalent(
            "text/html; charset=utf-8",
            "text/html;;charset=utf-8"
        ));
        assert!(content_type_equivalent("text/html", "text/html; "));

        // Still not a licence to ignore a real parameter.
        assert!(!content_type_equivalent(
            "text/html;",
            "text/html; charset=utf-8"
        ));
    }

    #[test]
    fn content_type_equivalent_preserves_parameter_value_case_and_spacing() {
        assert!(!content_type_equivalent(
            "multipart/form-data; boundary=Aa",
            "multipart/form-data; boundary=aa"
        ));
        assert!(!content_type_equivalent(
            r#"multipart/form-data; boundary="a b""#,
            r#"multipart/form-data; boundary="ab""#
        ));
        // A `;` inside quotes is part of the value, not a parameter separator.
        assert!(!content_type_equivalent(
            r#"multipart/form-data; boundary="a;b""#,
            r#"multipart/form-data; boundary="a;c""#
        ));
        assert!(content_type_equivalent(
            r#"multipart/form-data; boundary="a;b""#,
            r#"MULTIPART/FORM-DATA;  boundary="a;b""#
        ));
    }

    /// Bites the quote/escape tracking in `split_unquoted_semicolons`
    /// specifically. Without it, `boundary="a;b"` splits into `boundary="a` and
    /// the tail `b"`, which has no `=` and is therefore *lowercased* as a
    /// malformed segment — so `…"a;b"` and `…"a;B"` would compare **equal** and
    /// ISR would overwrite a multipart body while every request still
    /// advertised the old boundary.
    #[test]
    fn content_type_equivalent_tracks_quotes_and_escapes_in_parameter_values() {
        assert!(
            !content_type_equivalent(
                r#"multipart/mixed; boundary="a;b""#,
                r#"multipart/mixed; boundary="a;B""#
            ),
            "case inside a quoted value is significant even across a quoted `;`"
        );
        assert!(
            !content_type_equivalent(
                r#"multipart/mixed; boundary="a\";c""#,
                r#"multipart/mixed; boundary="a\";C""#
            ),
            "an escaped quote does not end the quoted string, so the `;` after \
             it is still part of the value"
        );

        // A malformed segment with no `=` has no value to protect, so it *is*
        // case-folded — the branch the quoted cases above must not reach.
        assert!(content_type_equivalent("text/html; FOO", "text/html; foo"));
    }

    /// Quoted-pairs decode when a parameter value is unquoted (RFC 9110 §5.6.4),
    /// so a header that merely gets reserialized — `boundary="a\b"` becoming
    /// `boundary="ab"` — between `autumn build` and ISR regeneration does not
    /// make `regenerate_page` refuse the refresh. The decoder only removes
    /// escape backslashes: it must not fold case or interior spacing, which
    /// `content_type_equivalent_preserves_parameter_value_case_and_spacing`
    /// covers.
    #[test]
    fn content_type_equivalent_decodes_quoted_pairs_in_parameter_values() {
        // `\"` and `\b` inside quotes denote the character alone, so `"a\b"`
        // is the same value as `ab`.
        assert!(content_type_equivalent(
            r#"multipart/mixed; boundary="a\b""#,
            "multipart/mixed; boundary=ab"
        ));
        // An escaped quote is really a quote: it must not make the value
        // compare equal to one without it.
        assert!(!content_type_equivalent(
            r#"multipart/mixed; boundary="a\"b""#,
            "multipart/mixed; boundary=ab"
        ));
        // An escaped backslash is a literal backslash, so `boundary="a\\b"` is
        // the value `a\b`, not `ab`.
        assert!(!content_type_equivalent(
            r#"multipart/mixed; boundary="a\\b""#,
            "multipart/mixed; boundary=ab"
        ));
        // A trailing lone `\` escapes nothing: it is dropped without panicking
        // and without discarding the rest of the value.
        assert!(content_type_equivalent(
            r#"multipart/mixed; boundary="abc\""#,
            "multipart/mixed; boundary=abc"
        ));
    }

    /// A manifest whose recorded type the serve path refuses to honour must not
    /// become the ISR expectation: the handler's perfectly good type could never
    /// match it, so every regeneration would be refused forever and the route
    /// would freeze — a strictly worse outcome than the bad value being ignored.
    #[tokio::test]
    async fn isr_ignores_unusable_recorded_content_type_and_still_regenerates() {
        let dir = tempfile::tempdir().expect("tempdir");
        let dist = dir.path().join("dist");
        std::fs::create_dir_all(dist.join("about")).expect("mkdir");
        let file = dist.join("about/index.html");
        std::fs::write(&file, "<h1>stale</h1>").expect("write");

        let mut routes = HashMap::new();
        routes.insert(
            "/about".to_owned(),
            ManifestEntry::new("about/index.html")
                .with_revalidate(Some(1))
                // Blank: `resolved_content_type` ignores it and derives
                // text/html from `index.html`.
                .with_content_type(Some("   ".to_owned())),
        );
        std::fs::write(
            dist.join("manifest.json"),
            serde_json::to_string(&StaticManifest::new(routes)).expect("serialize"),
        )
        .expect("write manifest");

        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(100);
        let _ = filetime::set_file_mtime(&file, filetime::FileTime::from_system_time(old));

        let fresh = axum::Router::new().fallback(axum::routing::get(|| async {
            axum::response::Html("<h1>fresh</h1>")
        }));
        let layer = StaticFileLayer::new(&dist)
            .expect("layer")
            .with_router(fresh);

        // The serve path ignores the unusable value and derives instead.
        let hit = layer.resolve_entry("/about").expect("resolves");
        assert_eq!(hit.content_type, "text/html; charset=utf-8");

        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
        assert_eq!(
            std::fs::read_to_string(&file).unwrap(),
            "<h1>fresh</h1>",
            "an unusable recorded type must not freeze regeneration"
        );
    }

    #[test]
    fn usable_recorded_content_type_matches_what_the_serve_path_honours() {
        assert_eq!(
            usable_recorded_content_type(Some("  application/rss+xml  ")),
            Some("application/rss+xml")
        );
        // A horizontal tab is legal OWS around media-type parameters, so a value
        // carrying one is usable — rejecting it would send an extensionless
        // `/feed` back to the `feed/index.html` derivation and serve RSS as
        // `text/html`. `to_str` succeeds on tab, so the compression layer still
        // matches such a type against its carve-outs in full; the hazard this
        // screen exists for is a value that reads as *empty* there.
        assert_eq!(
            usable_recorded_content_type(Some("application/rss+xml;\tprofile=\"x\"")),
            Some("application/rss+xml;\tprofile=\"x\"")
        );
        assert_eq!(
            resolved_content_type(
                Some("application/rss+xml;\tprofile=\"x\""),
                "/feed",
                Path::new("feed/index.html"),
            ),
            "application/rss+xml;\tprofile=\"x\"",
            "a tab-bearing type must be served, not derived around"
        );

        // A tab-*only* value is still nothing: trimming leaves the empty string.
        for unusable in [None, Some(""), Some("   "), Some("\t"), Some("text/htmlé")] {
            assert!(
                usable_recorded_content_type(unusable).is_none(),
                "{unusable:?} must be treated as nothing recorded"
            );
        }
    }

    /// A spelling difference must not freeze ISR: the regenerated response is
    /// the same type, written differently, so regeneration proceeds.
    #[tokio::test]
    async fn regenerate_page_accepts_equivalent_content_type_spelling() {
        let dir = tempfile::tempdir().expect("tempdir");
        let dest = dir.path().join("page.html");
        std::fs::write(&dest, "<h1>original</h1>").expect("write");

        let router = axum::Router::new().fallback(axum::routing::get(|| async {
            (
                [(axum::http::header::CONTENT_TYPE, "TEXT/HTML;charset=UTF-8")],
                "<h1>fresh</h1>",
            )
        }));

        regenerate_page(&router, "/page", &dest, Some("text/html; charset=utf-8"))
            .await
            .expect("an equivalent spelling must not freeze the route");

        assert_eq!(std::fs::read_to_string(&dest).unwrap(), "<h1>fresh</h1>");
    }

    /// A hand-edited manifest carrying CR/LF must never reach the response:
    /// it falls back rather than injecting a header (and never panics).
    #[test]
    fn resolved_content_type_rejects_header_illegal_recorded_value() {
        for bad in [
            "text/html\r\nX-Injected: yes",
            "text/html\nX-Injected: yes",
            "text/html\u{7f}",
            "text/html\0",
        ] {
            let ct = resolved_content_type(Some(bad), "/about", Path::new("about/index.html"));
            assert_eq!(
                ct, "text/html; charset=utf-8",
                "header-illegal recorded value {bad:?} must fall back"
            );
        }
    }

    /// With nothing recorded, the legacy derivation still applies — these are
    /// the three edge cases #1819 needed three rounds to get right, and they
    /// must keep working for manifests built before #1832.
    #[test]
    fn resolved_content_type_falls_back_to_route_extension() {
        assert_eq!(
            resolved_content_type(None, "/robots.txt", Path::new("robots.txt/index.html")),
            "text/plain; charset=utf-8"
        );
        assert_eq!(
            resolved_content_type(None, "/sitemap.xml", Path::new("sitemap.xml/index.html")),
            "application/xml"
        );
    }

    #[test]
    fn resolved_content_type_falls_back_to_file_name_for_dotted_slugs() {
        assert_eq!(
            resolved_content_type(
                None,
                "/posts/release.v1",
                Path::new("posts/release.v1/index.html")
            ),
            "text/html; charset=utf-8"
        );
        assert_eq!(
            resolved_content_type(
                None,
                "/users/alice@example.com",
                Path::new("users/alice@example.com/index.html")
            ),
            "text/html; charset=utf-8"
        );
    }

    #[test]
    fn resolved_content_type_falls_back_to_file_name_for_extensionless_routes() {
        assert_eq!(
            resolved_content_type(None, "/about", Path::new("about/index.html")),
            "text/html; charset=utf-8"
        );
        assert_eq!(
            resolved_content_type(None, "/inter", Path::new("fonts/inter.woff2")),
            "font/woff2"
        );
    }

    #[test]
    fn resolved_content_type_last_resort_is_octet_stream() {
        assert_eq!(
            resolved_content_type(None, "/data", Path::new("data.bin")),
            "application/octet-stream"
        );
        assert_eq!(
            resolved_content_type(None, "/data", Path::new("")),
            "application/octet-stream"
        );
    }

    /// `resolve_entry` decides the type once — recorded when the manifest has
    /// one, derived otherwise — so the serve path never has to.
    #[test]
    fn resolve_entry_decides_content_type() {
        let dir = tempfile::tempdir().expect("tempdir");
        let dist = dir.path().join("dist");
        std::fs::create_dir_all(&dist).expect("mkdir");
        std::fs::write(dist.join("index.html"), "<h1>Home</h1>").expect("write");

        let mut routes = HashMap::new();
        routes.insert(
            "/".to_owned(),
            ManifestEntry::new("index.html").with_content_type(Some("text/html".to_owned())),
        );
        routes.insert("/bare".to_owned(), ManifestEntry::new("bare/index.html"));
        let manifest = StaticManifest {
            generated_at: "2026-09-01T00:00:00Z".to_owned(),
            autumn_version: "0.6.0".to_owned(),
            routes,
        };
        std::fs::write(
            dist.join("manifest.json"),
            serde_json::to_string(&manifest).expect("serialize"),
        )
        .expect("write manifest");

        let layer = StaticFileLayer::new(&dist).expect("layer");

        // The recorded type is served verbatim...
        let hit = layer.resolve_entry("/").expect("root resolves");
        assert_eq!(hit.file_path, dist.join("index.html"));
        assert_eq!(hit.content_type, "text/html");

        // ...and a route that records nothing gets the legacy derivation, so
        // callers never see an undecided type.
        let bare = layer.resolve_entry("/bare").expect("bare resolves");
        assert_eq!(bare.content_type, "text/html; charset=utf-8");

        assert!(layer.resolve_entry("/missing").is_none());
    }

    // ── #1832: ISR must not desync a regenerated body from the recorded type ──

    /// The manifest is immutable at runtime, so a handler that starts declaring
    /// a *different* `Content-Type` would have its new bytes served under the
    /// old recorded type. Regeneration is refused instead, leaving the previous
    /// file — which still matches its recorded type — in place.
    #[tokio::test]
    async fn regenerate_page_refuses_when_content_type_changed() {
        let dir = tempfile::tempdir().expect("tempdir");
        let dest = dir.path().join("page.html");
        std::fs::write(&dest, "<h1>original</h1>").expect("write");

        let router = axum::Router::new().fallback(axum::routing::get(|| async {
            (
                [(axum::http::header::CONTENT_TYPE, "application/json")],
                r#"{"now":"json"}"#,
            )
        }));

        let result =
            regenerate_page(&router, "/page", &dest, Some("text/html; charset=utf-8")).await;

        let err = result.expect_err("a changed Content-Type must fail regeneration");
        assert!(
            err.to_string().contains("Content-Type changed"),
            "unexpected error: {err}"
        );
        assert_eq!(
            std::fs::read_to_string(&dest).unwrap(),
            "<h1>original</h1>",
            "the stale-but-correctly-typed file must survive a refused regeneration"
        );
    }

    /// A handler that stops declaring a type at all is the same hazard: the
    /// recorded type would keep being asserted over bytes nothing vouches for.
    #[tokio::test]
    async fn regenerate_page_refuses_when_content_type_disappears() {
        let dir = tempfile::tempdir().expect("tempdir");
        let dest = dir.path().join("page.html");
        std::fs::write(&dest, "<h1>original</h1>").expect("write");

        let router = axum::Router::new().fallback(axum::routing::get(|| async {
            axum::response::Response::builder()
                .status(axum::http::StatusCode::OK)
                .body(axum::body::Body::from("bare"))
                .unwrap()
        }));

        let result =
            regenerate_page(&router, "/page", &dest, Some("text/html; charset=utf-8")).await;

        let err = result.expect_err("a vanished Content-Type must fail regeneration");
        assert!(
            err.to_string().contains("Content-Type changed"),
            "unexpected error: {err}"
        );
        assert_eq!(std::fs::read_to_string(&dest).unwrap(), "<h1>original</h1>");
    }

    /// The matching case still regenerates normally.
    #[tokio::test]
    async fn regenerate_page_writes_when_content_type_matches() {
        let dir = tempfile::tempdir().expect("tempdir");
        let dest = dir.path().join("page.html");
        std::fs::write(&dest, "<h1>original</h1>").expect("write");

        let router = axum::Router::new().fallback(axum::routing::get(|| async {
            axum::response::Html("<h1>fresh</h1>")
        }));

        regenerate_page(&router, "/page", &dest, Some("text/html; charset=utf-8"))
            .await
            .expect("matching Content-Type regenerates");

        assert_eq!(std::fs::read_to_string(&dest).unwrap(), "<h1>fresh</h1>");
    }

    /// #2409: a `String` handler on `/theme.css` records `text/css`. Its fresh
    /// `text/plain` default must normalize to the same type, not freeze the route.
    #[tokio::test]
    async fn regenerate_page_accepts_generic_default_normalized_to_extension_type() {
        let dir = tempfile::tempdir().expect("tempdir");
        let dest = dir.path().join("theme.css");
        std::fs::write(&dest, "a{}").expect("write");

        let router =
            axum::Router::new().fallback(axum::routing::get(|| async { "b{}".to_owned() }));

        regenerate_page(
            &router,
            "/theme.css",
            &dest,
            Some("text/css; charset=utf-8"),
        )
        .await
        .expect("generic default normalizes to the recorded extension type");

        assert_eq!(std::fs::read_to_string(&dest).unwrap(), "b{}");
    }

    /// #2409: a JSON response must not overwrite a recorded `text/css` file.
    #[tokio::test]
    async fn regenerate_page_refuses_json_over_recorded_extension_type() {
        let dir = tempfile::tempdir().expect("tempdir");
        let dest = dir.path().join("theme.css");
        std::fs::write(&dest, "a{}").expect("write");

        let router = axum::Router::new().fallback(axum::routing::get(|| async {
            (
                [(axum::http::header::CONTENT_TYPE, "application/json")],
                r#"{"x":1}"#,
            )
        }));

        let err = regenerate_page(
            &router,
            "/theme.css",
            &dest,
            Some("text/css; charset=utf-8"),
        )
        .await
        .expect_err("JSON must not replace a text/css file");
        assert!(err.to_string().contains("Content-Type changed"), "{err}");
        assert_eq!(std::fs::read_to_string(&dest).unwrap(), "a{}");
    }

    /// #2409: an old or edited manifest holding a generic default on an
    /// extensioned route serves the extension type.
    #[test]
    fn resolved_content_type_normalizes_recorded_generic_default() {
        let value = resolved_content_type(
            Some("text/plain; charset=utf-8"),
            "/theme.css",
            Path::new("theme.css/index.html"),
        );
        assert_eq!(value, "text/css; charset=utf-8");
    }

    /// #2409: ISR must not freeze on a recorded generic default.
    #[tokio::test]
    async fn regenerate_page_accepts_trimmed_generic_default_header() {
        let dir = tempfile::tempdir().expect("tempdir");
        let dest = dir.path().join("theme.css");
        std::fs::write(&dest, "a{}").expect("write");
        let router = axum::Router::new().fallback(axum::routing::get(|| async {
            (
                [(
                    axum::http::header::CONTENT_TYPE,
                    " text/plain; charset=utf-8",
                )],
                "b{}",
            )
        }));
        regenerate_page(
            &router,
            "/theme.css",
            &dest,
            Some("text/css; charset=utf-8"),
        )
        .await
        .expect("padded generic default normalizes");
    }

    /// #2409 end to end: build a `String` route on `/theme.css`, then ISR it.
    #[tokio::test]
    async fn isr_guards_extensioned_string_route_built_by_render_static_routes() {
        let dir = tempfile::tempdir().expect("tempdir");
        let dist_dir = dir.path().join("dist");
        let string_router =
            || axum::Router::new().fallback(axum::routing::get(|| async { "a{}".to_owned() }));
        let meta = crate::static_gen::StaticRouteMeta {
            path: "/theme.css",
            name: "theme",
            revalidate: Some(1),
            params_fn: None,
            seo: crate::seo::SeoRouteDefaults::EMPTY,
            content_type: None,
        };
        crate::static_gen::render_static_routes(string_router(), &[meta], &dist_dir)
            .await
            .expect("render");
        let manifest = StaticManifest::load(&dist_dir.join("manifest.json")).expect("manifest");
        let recorded = manifest.routes["/theme.css"].content_type.clone();
        assert_eq!(recorded.as_deref(), Some("text/css; charset=utf-8"));

        let dest = dist_dir.join(&manifest.routes["/theme.css"].file);
        regenerate_page(&string_router(), "/theme.css", &dest, recorded.as_deref())
            .await
            .expect("String handler still regenerates");

        let json_router = axum::Router::new().fallback(axum::routing::get(|| async {
            (
                [(axum::http::header::CONTENT_TYPE, "application/json")],
                "{}",
            )
        }));
        regenerate_page(&json_router, "/theme.css", &dest, recorded.as_deref())
            .await
            .expect_err("JSON must not overwrite the stylesheet");
    }

    // ── #2403: an explicit entry is served and guarded as declared ───────────

    fn explicit_entry(content_type: &str, revalidate: Option<u64>) -> ManifestEntry {
        ManifestEntry::new("logo.png/index.html")
            .with_revalidate(revalidate)
            .with_content_type(Some(content_type.to_owned()))
            .with_content_type_explicit(true)
    }

    #[test]
    fn explicit_generic_type_is_served_as_declared() {
        let entry = explicit_entry("application/octet-stream", None);
        let value =
            resolved_entry_content_type(&entry, "/logo.png", Path::new("logo.png/index.html"));
        assert_eq!(value, "application/octet-stream");
    }

    #[test]
    fn explicit_entry_with_an_unusable_type_still_falls_back() {
        let entry = explicit_entry("   ", None);
        let value =
            resolved_entry_content_type(&entry, "/logo.png", Path::new("logo.png/index.html"));
        assert_eq!(value, "image/png");
    }

    #[test]
    fn explicit_entry_with_a_non_ascii_type_falls_back() {
        let entry = explicit_entry("image/p\u{e9}ng", None);
        let value =
            resolved_entry_content_type(&entry, "/logo.png", Path::new("logo.png/index.html"));
        assert_eq!(value, "image/png");
    }

    /// The runtime byte rule the macro copies: tab and `0x20..0x7f`.
    #[test]
    fn legal_content_type_bytes_match_the_macro_rule() {
        for b in 0..=255u8 {
            let expected = b == b'\t' || (0x20..0x7f).contains(&b);
            assert_eq!(is_legal_content_type_byte(b), expected, "byte {b:#x}");
        }
    }

    /// Whole path: build with a declared type, serve through the layer, then
    /// ISR with a handler that sets another header.
    #[tokio::test]
    async fn declared_type_survives_serving_and_isr() {
        let dir = tempfile::tempdir().expect("tempdir");
        let dist_dir = dir.path().join("dist");
        let router = axum::Router::new().fallback(axum::routing::get(|| async {
            ([(axum::http::header::CONTENT_TYPE, "text/plain")], "b")
        }));
        let meta = crate::static_gen::StaticRouteMeta {
            path: "/logo.png",
            name: "logo",
            revalidate: Some(3600),
            params_fn: None,
            seo: crate::seo::SeoRouteDefaults::EMPTY,
            content_type: Some("application/octet-stream"),
        };
        crate::static_gen::render_static_routes(router.clone(), &[meta], &dist_dir)
            .await
            .expect("render");

        let layer = StaticFileLayer::new(&dist_dir).expect("layer");
        let hit = layer.resolve_entry("/logo.png").expect("hit");
        assert_eq!(hit.content_type, "application/octet-stream");

        let manifest = StaticManifest::load(&dist_dir.join("manifest.json")).expect("manifest");
        let entry = &manifest.routes["/logo.png"];
        let expected = isr_expected_content_type(entry, "/logo.png", &hit.file_path);
        regenerate_page(&router, "/logo.png", &hit.file_path, expected.as_deref())
            .await
            .expect("an explicit entry regenerates whatever the handler header says");
    }

    #[test]
    fn inferred_generic_type_is_still_remapped() {
        let value = resolved_content_type(
            Some("application/octet-stream"),
            "/logo.png",
            Path::new("logo.png/index.html"),
        );
        assert_eq!(value, "image/png");
    }

    /// ISR skips the type guard for an explicit entry: the route attribute
    /// pins the header, so the handler's own header is irrelevant.
    #[test]
    fn isr_does_not_guard_the_type_of_an_explicit_entry() {
        let entry = explicit_entry("application/octet-stream", Some(1));
        let file = Path::new("logo.png/index.html");
        assert_eq!(isr_expected_content_type(&entry, "/logo.png", file), None);
    }

    /// An explicit flag with no usable type serves the derived type, so ISR
    /// must guard that same type.
    #[test]
    fn isr_guards_the_fallback_type_of_an_unusable_explicit_entry() {
        let file = Path::new("logo.png/index.html");
        for bad in [None, Some(""), Some("   "), Some("image/p\u{e9}ng")] {
            let entry = ManifestEntry::new("logo.png/index.html")
                .with_content_type(bad.map(str::to_owned))
                .with_content_type_explicit(true);
            assert_eq!(
                isr_expected_content_type(&entry, "/logo.png", file).as_deref(),
                Some("image/png"),
                "{bad:?}"
            );
        }
    }

    #[test]
    fn isr_still_guards_the_type_of_an_inferred_entry() {
        let entry = ManifestEntry::new("theme.css/index.html")
            .with_content_type(Some("text/plain; charset=utf-8".to_owned()));
        assert_eq!(
            isr_expected_content_type(&entry, "/theme.css", Path::new("theme.css/index.html"))
                .as_deref(),
            Some("text/css; charset=utf-8")
        );
    }

    #[test]
    fn effective_content_type_maps_generic_default_to_extension_type() {
        assert_eq!(
            effective_content_type("text/plain; charset=utf-8", "/theme.css"),
            "text/css; charset=utf-8"
        );
        assert_eq!(
            effective_content_type("application/octet-stream", "/logo.png"),
            "image/png"
        );
        // Explicit, agreeing, or unknown-extension types stay as declared.
        assert_eq!(
            effective_content_type("application/json", "/n.txt"),
            "application/json"
        );
        assert_eq!(
            effective_content_type("text/plain; charset=utf-8", "/n.txt"),
            "text/plain; charset=utf-8"
        );
        assert_eq!(
            effective_content_type("application/octet-stream", "/r.pdf"),
            "application/octet-stream"
        );
        assert_eq!(
            effective_content_type("text/plain", "/theme.css"),
            "text/plain"
        );
    }

    /// A route that records no type has nothing to desync, so regeneration is
    /// unconstrained — this is the pre-#1832 behaviour for legacy manifests.
    #[tokio::test]
    async fn regenerate_page_unconstrained_when_nothing_recorded() {
        let dir = tempfile::tempdir().expect("tempdir");
        let dest = dir.path().join("page.html");
        std::fs::write(&dest, "<h1>original</h1>").expect("write");

        let router = axum::Router::new().fallback(axum::routing::get(|| async {
            (
                [(axum::http::header::CONTENT_TYPE, "application/json")],
                r#"{"any":"type"}"#,
            )
        }));

        regenerate_page(&router, "/page", &dest, None)
            .await
            .expect("no recorded type means no constraint");

        assert_eq!(std::fs::read_to_string(&dest).unwrap(), r#"{"any":"type"}"#);
    }

    /// M4: an ISR route with a recorded type keeps it while the stale page is
    /// served. `resolve_entry` triggers regeneration *before* it builds the
    /// hit, so this pins that the staleness branch does not disturb the type.
    #[tokio::test]
    async fn resolve_entry_keeps_recorded_content_type_for_isr_route() {
        let dir = tempfile::tempdir().expect("tempdir");
        let dist = dir.path().join("dist");
        std::fs::create_dir_all(dist.join("feed")).expect("mkdir");
        let file = dist.join("feed/index.html");
        std::fs::write(&file, "<rss/>").expect("write");

        let mut routes = HashMap::new();
        routes.insert(
            "/feed".to_owned(),
            ManifestEntry::new("feed/index.html")
                .with_revalidate(Some(1))
                .with_content_type(Some("application/rss+xml".to_owned())),
        );
        let manifest = StaticManifest {
            generated_at: "2026-09-01T00:00:00Z".to_owned(),
            autumn_version: "0.7.0".to_owned(),
            routes,
        };
        std::fs::write(
            dist.join("manifest.json"),
            serde_json::to_string(&manifest).expect("serialize"),
        )
        .expect("write manifest");

        // Age the file so the ISR staleness branch runs on this resolve.
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(100);
        let _ = filetime::set_file_mtime(&file, filetime::FileTime::from_system_time(old));

        let layer = StaticFileLayer::new(&dist).expect("layer");
        let hit = layer.resolve_entry("/feed").expect("resolves");
        assert_eq!(hit.content_type, "application/rss+xml");
    }

    /// M6: a refused regeneration must leave the route usable — the stale file
    /// stays and the in-flight flag clears, so the next stale request can try
    /// again after the cooldown rather than the route wedging forever.
    #[tokio::test]
    async fn isr_refused_regeneration_keeps_file_and_clears_in_flight() {
        let dir = tempfile::tempdir().expect("tempdir");
        let dist = dir.path().join("dist");
        std::fs::create_dir_all(dist.join("about")).expect("mkdir");
        let file = dist.join("about/index.html");
        std::fs::write(&file, "<h1>About (stale)</h1>").expect("write");

        let mut routes = HashMap::new();
        routes.insert(
            "/about".to_owned(),
            ManifestEntry::new("about/index.html")
                .with_revalidate(Some(1))
                .with_content_type(Some("text/html; charset=utf-8".to_owned())),
        );
        let manifest = StaticManifest {
            generated_at: "2026-09-01T00:00:00Z".to_owned(),
            autumn_version: "0.7.0".to_owned(),
            routes,
        };
        std::fs::write(
            dist.join("manifest.json"),
            serde_json::to_string(&manifest).expect("serialize"),
        )
        .expect("write manifest");

        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(100);
        let _ = filetime::set_file_mtime(&file, filetime::FileTime::from_system_time(old));

        // The handler now declares a different type than the manifest records.
        let drifted_handler = axum::Router::new().fallback(axum::routing::get(|| async {
            (
                [(axum::http::header::CONTENT_TYPE, "application/json")],
                r#"{"drifted":true}"#,
            )
        }));
        let layer = StaticFileLayer::new(&dist)
            .expect("layer")
            .with_router(drifted_handler);

        let _ = layer.resolve("/about");
        tokio::time::sleep(std::time::Duration::from_millis(200)).await;

        assert_eq!(
            std::fs::read_to_string(&file).unwrap(),
            "<h1>About (stale)</h1>",
            "a refused regeneration must not overwrite the correctly-typed file"
        );
        let state = layer.isr_state.get("/about").expect("isr state");
        assert!(
            !state.in_flight.load(Ordering::Relaxed),
            "a refused regeneration must clear in_flight, not wedge the route"
        );
    }

    /// M5 — the load-bearing test for the refusal above.
    ///
    /// The refusal compares the regenerated response's `Content-Type` against
    /// the manifest's recorded string exactly. If the framework's own build
    /// path and ISR path ever disagreed on that string — a charset spelling, a
    /// layer applied on one path but not the other — every route built after
    /// #1832 would refuse to regenerate *forever*, silently, until the next
    /// `autumn build`. This drives both real paths end to end and asserts the
    /// page actually refreshes, so such a divergence fails CI instead of
    /// freezing ISR in production.
    ///
    /// (The asymmetry this note used to document — `autumn build` rendering
    /// through the app's custom Tower layers while ISR regeneration did not —
    /// is closed by #2405: the build renders through the pre-layer router too.
    /// `isr_accepts_regeneration_when_a_user_layer_rewrites_content_type`
    /// covers the rewriting-layer shape directly.)
    #[tokio::test]
    async fn isr_regenerates_page_built_by_render_static_routes() {
        let router = axum::Router::new().route(
            "/about",
            axum::routing::get(|| async { axum::response::Html("<h1>fresh</h1>") }),
        );

        let tmp = tempfile::tempdir().expect("tempdir");
        let dist = tmp.path().join("dist");
        crate::static_gen::render_static_routes(
            router.clone(),
            &[crate::static_gen::StaticRouteMeta {
                path: "/about",
                name: "about",
                revalidate: Some(1),
                params_fn: None,
                seo: crate::seo::SeoRouteDefaults::EMPTY,
                content_type: None,
            }],
            &dist,
        )
        .await
        .expect("static build");

        // The build must have recorded the type that regeneration will declare.
        let manifest = StaticManifest::load(&dist.join("manifest.json")).expect("manifest");
        assert_eq!(
            manifest.routes["/about"].content_type.as_deref(),
            Some("text/html; charset=utf-8")
        );

        // Overwrite and age the generated page so regeneration has something
        // observable to do.
        let file = dist.join("about/index.html");
        std::fs::write(&file, "<h1>stale</h1>").expect("write");
        let old = std::time::SystemTime::now() - std::time::Duration::from_secs(100);
        let _ = filetime::set_file_mtime(&file, filetime::FileTime::from_system_time(old));

        let layer = StaticFileLayer::new(&dist)
            .expect("layer")
            .with_router(router);
        let _ = layer.resolve("/about");
        tokio::time::sleep(std::time::Duration::from_millis(300)).await;

        assert_eq!(
            std::fs::read_to_string(&file).unwrap(),
            "<h1>fresh</h1>",
            "a page built by render_static_routes must still be regenerable by ISR — \
             a build/ISR disagreement on the recorded Content-Type would freeze it"
        );
    }

    /// #2405: `autumn build` used to render through the app's custom Tower
    /// layers while ISR regeneration deliberately did not. For an app with a
    /// `Content-Type`-rewriting layer the build recorded the post-layer type,
    /// ISR saw the pre-layer one, and the #2400 guard refused every refresh —
    /// freezing the route until the next build.
    ///
    /// The build now renders through the pre-layer router (user layers drained
    /// in `run_build_mode` via
    /// [`crate::router::partition_custom_layers_for_static_render`], the same
    /// partition the SSG serve path applies), so the manifest records the
    /// handler's type and the body on disk is the handler's body. This drives
    /// the real `render_static_routes` into the real `regenerate_page` with a
    /// rewriting layer in the picture and asserts the refresh is accepted —
    /// the exact shape that used to freeze.
    #[tokio::test]
    async fn isr_accepts_regeneration_when_a_user_layer_rewrites_content_type() {
        use axum::http::header::{CONTENT_TYPE, HeaderValue};

        // The offending shape: a user layer that rewrites Content-Type on the
        // way out.
        let rewrite = axum::middleware::from_fn(
            |req: axum::extract::Request, next: axum::middleware::Next| async move {
                let mut response = next.run(req).await;
                response.headers_mut().insert(
                    CONTENT_TYPE,
                    HeaderValue::from_static("application/x-rewritten"),
                );
                response
            },
        );
        let registration = crate::app::CustomLayerRegistration {
            type_id: std::any::TypeId::of::<()>(),
            type_name: "content_type_rewrite",
            layer: tower::util::BoxCloneSyncServiceLayer::new(rewrite.clone()),
        };

        // What `run_build_mode` does before rendering: drain the user layers.
        let (pre_layer, drained) =
            crate::router::partition_custom_layers_for_static_render(vec![registration]);
        assert!(
            pre_layer.is_empty(),
            "a plain user layer must not survive the build-time drain"
        );
        assert_eq!(
            drained.len(),
            1,
            "the drained set carries the rewriting layer"
        );

        let base = axum::Router::new().route(
            "/page",
            axum::routing::get(|| async { axum::response::Html("<h1>v1</h1>") }),
        );
        // The old build composition, for contrast: the layer applied at
        // render time.
        let layered = base.clone().layer(rewrite);

        let meta = || crate::static_gen::StaticRouteMeta {
            path: "/page",
            name: "page",
            revalidate: Some(1),
            params_fn: None,
            seo: crate::seo::SeoRouteDefaults::EMPTY,
            content_type: None,
        };

        // Old behavior: the build records the post-layer type ...
        let tmp_old = tempfile::tempdir().expect("tempdir");
        let dist_old = tmp_old.path().join("dist");
        crate::static_gen::render_static_routes(layered, &[meta()], &dist_old)
            .await
            .expect("static build");
        let manifest_old = StaticManifest::load(&dist_old.join("manifest.json")).expect("manifest");
        assert_eq!(
            manifest_old.routes["/page"].content_type.as_deref(),
            Some("application/x-rewritten"),
            "rendering through the layer records the rewritten type"
        );
        // ... which ISR (pre-layer view) then refuses: the freeze.
        let refused = regenerate_page(
            &base,
            "/page",
            &dist_old.join("page/index.html"),
            manifest_old.routes["/page"].content_type.as_deref(),
        )
        .await;
        assert!(
            refused.is_err(),
            "the old build/ISR asymmetry must refuse the refresh — this is the freeze #2405 fixes"
        );

        // New behavior: the build renders through the pre-layer router, so
        // the manifest records the handler's type ...
        let tmp_new = tempfile::tempdir().expect("tempdir");
        let dist_new = tmp_new.path().join("dist");
        crate::static_gen::render_static_routes(base.clone(), &[meta()], &dist_new)
            .await
            .expect("static build");
        let manifest_new = StaticManifest::load(&dist_new.join("manifest.json")).expect("manifest");
        assert_eq!(
            manifest_new.routes["/page"].content_type.as_deref(),
            Some("text/html; charset=utf-8"),
            "the build must record the handler's pre-layer type, not the layer's rewrite"
        );
        // ... and ISR accepts the refresh, writing the handler's body.
        let page_new = dist_new.join("page/index.html");
        std::fs::write(&page_new, "<h1>stale</h1>").expect("write stale");
        regenerate_page(
            &base,
            "/page",
            &page_new,
            manifest_new.routes["/page"].content_type.as_deref(),
        )
        .await
        .expect("ISR regeneration must accept the pre-layer recording");
        assert_eq!(
            std::fs::read_to_string(&page_new).unwrap(),
            "<h1>v1</h1>",
            "the regenerated body is the handler's output"
        );
    }
}