mini-static 0.38.5

A secure, async static file server with streaming, traversal protection, and connection limits.
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
use std::fs;
use std::io::Write;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime};

use bytes::Bytes;
use http_body_util::Full;
use hyper::header::{self, HeaderName, HeaderValue};
use hyper::http::response::Builder;
use hyper::{HeaderMap, Method, Request, Response, StatusCode};
use tokio::fs::File;
use tokio::net::TcpListener;
use tokio::time::timeout;

use crate::error::StaticError;
use crate::handler::{FileBody, ResponseBody};
use crate::reload::{self, SseBody};
use crate::resolve;
use crate::resolve::HiddenFiles;
use crate::spa::{self, SpaTransition};
use crate::watcher::{start_watching, Broadcaster};


/// Default maximum concurrent connections, overridable via `Server::with_max_connections`.
const DEFAULT_MAX_CONNECTIONS: usize = 1024;

/// A predicate deciding whether a resolved file path should get an immutable cache
/// policy; see [`Server::with_immutable_assets`].
type ImmutablePredicate = Arc<dyn Fn(&Path) -> bool + Send + Sync>;

/// A static file server for serving files securely from a root directory.
///
/// `Server` canonicalizes the root directory once at creation time and uses the
/// canonical form for all subsequent requests, avoiding repeated filesystem calls.
///
/// # Security
///
/// The server protects against:
/// - Path traversal attacks (e.g., `../../etc/passwd`)
/// - Accessing files outside the root via symlinks
/// - Disclosing filesystem structure (traversal and missing files both return 404)
///
/// # Cloning
///
/// `Server` is cheap to clone: a `PathBuf`, a couple of primitives, and an `Arc`'d
/// predicate closure. Multiple clones can be used concurrently in async tasks without
/// synchronization overhead.
///
/// # Example
///
/// ```no_run
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// use mini_static::Server;
/// use std::path::Path;
/// use std::time::Duration;
///
/// let server = Server::new(Path::new("./public"))?;
/// let (port, _handle) = server.run(Duration::from_secs(30)).await?;
/// println!("Server running on port {}", port);
/// # Ok(())
/// # }
/// ```
/// Headers this server derives from the response it is building, and therefore refuses
/// as fixed values via [`Server::with_response_header`]. A fixed value would be either
/// silently overridden or silently duplicated depending on the response — and a wrong
/// `Content-Length` or `ETag` is a correctness bug, not a policy choice.
const SERVER_COMPUTED_HEADERS: [HeaderName; 13] = [
    header::CONTENT_LENGTH,
    header::CONTENT_TYPE,
    header::CONTENT_ENCODING,
    header::CONTENT_RANGE,
    header::ETAG,
    header::CACHE_CONTROL,
    header::VARY,
    header::ACCEPT_RANGES,
    header::ALLOW,
    header::LOCATION,
    header::CONNECTION,
    header::TRANSFER_ENCODING,
    header::X_CONTENT_TYPE_OPTIONS,
];

/// Where request and connection log lines go.
///
/// A `Server` is cloned per request, so the sink is shared rather than duplicated. The
/// mutex serializes writes from concurrent connections — without it, two responses
/// finishing at once would interleave mid-line and produce log entries belonging to
/// neither request.
type RequestLog = Arc<Mutex<Box<dyn Write + Send>>>;

#[derive(Clone)]
pub struct Server {
    root_canon: PathBuf,
    max_connections: usize,
    live_reload: bool,
    broadcaster: Option<Broadcaster>,
    spa_mode: bool,
    spa_root: Option<String>,
    spa_transition: SpaTransition,
    not_found_page: Option<PathBuf>,
    hidden_files: HiddenFiles,
    /// Whether to look for `.br`/`.gz` siblings. On by default; see
    /// [`Server::without_precompressed`] for what it costs and why the default stands.
    precompressed: bool,
    /// Files read into memory at construction, if [`Server::with_content_cache`] was called.
    ///
    /// `Arc` because `Server` is cloned per connection today and the map is read-only after
    /// construction — there is no lock, no eviction and no invalidation, which is the whole
    /// reason an eager cache is simpler than a general one.
    content_cache: Option<Arc<crate::cache::ContentCache>>,
    request_log: Option<RequestLog>,
    extra_headers: Arc<Vec<(HeaderName, HeaderValue)>>,
    immutable_predicate: Option<ImmutablePredicate>,
}

impl Server {
    /// Create a new server with the given root directory.
    ///
    /// Canonicalizes the root once at startup. All subsequent requests use the
    /// canonical root without re-canonicalizing it, making this suitable for long-lived servers.
    ///
    /// # Errors
    ///
    /// Returns `Err(StaticError::Io)` if the root cannot be canonicalized (e.g., doesn't exist,
    /// no read permissions).
    pub fn new(root: &Path) -> Result<Self, StaticError> {
        let root_canon = root.canonicalize().map_err(StaticError::Io)?;
        Ok(Server {
            root_canon,
            max_connections: DEFAULT_MAX_CONNECTIONS,
            live_reload: false,
            broadcaster: None,
            spa_mode: false,
            spa_root: None,
            spa_transition: SpaTransition::default(),
            not_found_page: None,
            hidden_files: HiddenFiles::Deny,
            precompressed: true,
            content_cache: None,
            request_log: None,
            extra_headers: Arc::new(Vec::new()),
            immutable_predicate: None,
        })
    }

    /// Set the maximum number of connections served concurrently (default 1024).
    ///
    /// Once this many connections are in flight, `run()`'s accept loop stops accepting
    /// new ones — without pausing the accept loop, a client that opens a connection and
    /// sends nothing (see the header-read timeout docs on [`Server::run_on`]) could
    /// otherwise be used, in enough parallel copies, to exhaust the process's file
    /// descriptors or memory with no bound at all.
    pub fn with_max_connections(mut self, max: usize) -> Self {
        self.max_connections = max;
        self
    }

    /// Enable live-reload for this server (disabled by default).
    ///
    /// Once enabled, the `run*` methods start a background watcher (mtime polling,
    /// bounded 500ms interval — see [`crate::start_watching`]) the first time the server
    /// actually starts accepting connections. It watches the served root; when a build
    /// pipeline is configured it watches that pipeline's source folders instead, because
    /// the pipeline broadcasts its own outputs once they are written. Then it will:
    ///
    /// - serve a live-reload SSE stream at [`crate::LIVE_RELOAD_PATH`], broadcasting a
    ///   change event (with [`crate::ChangeType`]) whenever a served file is added,
    ///   modified, or removed;
    /// - inject a small `<script>` into every served `text/html` response that connects
    ///   to that stream and reloads the page (or hot-swaps stylesheet `<link>`s, for CSS
    ///   changes) — no manual client wiring required.
    ///
    /// This is meant for local development, not production: leave it disabled (the
    /// default) for any server serving real traffic. A typical call site gates it behind
    /// `#[cfg(debug_assertions)]` so a release build never pays for the watcher or the
    /// injected script.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// use mini_static::Server;
    /// use std::path::Path;
    ///
    /// let server = Server::new(Path::new("./public"))?;
    /// #[cfg(debug_assertions)]
    /// let server = server.with_live_reload();
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_live_reload(mut self) -> Self {
        self.live_reload = true;
        self
    }

    /// Enable spa-mode navigation for this server, swapping `document.body` on
    /// each navigation (disabled by default).
    ///
    /// Once enabled, every served `text/html` response gets a small `<script>`
    /// injected (see [`Server::with_spa_root`] for what it does) that treats
    /// `document.body` as the swap target. Calling this after
    /// [`Server::with_spa_root`] does not clear a previously configured root
    /// selector — the two methods set independent fields, so
    /// `.with_spa_root(sel).with_spa_mode()` and
    /// `.with_spa_mode().with_spa_root(sel)` both end up with spa-mode on and
    /// root `sel`. Use this one alone when there's no persistent chrome to
    /// preserve across navigations.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// use mini_static::Server;
    /// use std::path::Path;
    ///
    /// let server = Server::new(Path::new("./public"))?.with_spa_mode();
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_spa_mode(mut self) -> Self {
        self.spa_mode = true;
        self
    }

    /// Enable spa-mode navigation for this server, swapping only the element
    /// matched by the CSS `selector` on each navigation (disabled by default;
    /// also enables spa-mode the same as [`Server::with_spa_mode`]).
    ///
    /// Once enabled, every served `text/html` response gets a small `<script>`
    /// injected that intercepts left-clicks on same-origin `<a href>`
    /// elements (skipping links with a non-`_self` `target`, a `download`
    /// attribute, `rel="external"`, a `data-no-spa` attribute, or a same-page
    /// hash-only href) and, instead of a normal navigation:
    ///
    /// - fetches the target URL;
    /// - on a non-OK or non-`text/html` response (or a fetch error), falls
    ///   back to a real `location.href` navigation — spa-mode never renders a
    ///   broken page;
    /// - otherwise replaces the matched element's `innerHTML` with the
    ///   corresponding content from the fetched document, updates the page
    ///   title, and pushes the new URL via `history.pushState`, animating the
    ///   swap with `document.startViewTransition()` where supported;
    /// - dispatches a `mini-static:navigate` `CustomEvent` on `window` after
    ///   every client-side navigation, so page scripts can re-run any
    ///   per-page initialization that would otherwise only execute once
    ///   (content swapped in via `innerHTML` never executes its own
    ///   `<script>` tags);
    /// - handles browser back/forward by re-fetching and swapping to the new
    ///   `location.href`.
    ///
    /// `selector` is matched against both the current page and the fetched
    /// page; a link click where the selector matches neither falls back to a
    /// real navigation, same as a fetch failure. Choose a `selector` that
    /// wraps only the content that varies between pages, leaving persistent
    /// chrome (nav/header/footer) outside it so it survives navigation
    /// untouched.
    ///
    /// This is meant to be usable in production, not just local development
    /// (unlike [`Server::with_live_reload`]): a click on a link mini-static
    /// doesn't intercept, or on a browser without JS or View Transitions
    /// support, still works as a normal navigation.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// use mini_static::Server;
    /// use std::path::Path;
    ///
    /// let server = Server::new(Path::new("./public"))?.with_spa_root("#app");
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_spa_root(mut self, selector: &str) -> Self {
        self.spa_mode = true;
        self.spa_root = Some(selector.to_string());
        self
    }

    /// Set how spa-mode animates the swap between pages (also enables
    /// spa-mode the same as [`Server::with_spa_mode`]; default
    /// [`SpaTransition::Fade`] when spa-mode is enabled without calling this).
    ///
    /// [`SpaTransition::Slide`] injects its own `<style>` tag alongside the
    /// spa-mode `<script>` — no site CSS is required. See [`SpaTransition`]
    /// and [`crate::SlideOptions`] for what each variant does and how to
    /// configure the slide's duration, direction, and easing.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// use mini_static::{Server, SlideOptions, SpaTransition};
    /// use std::path::Path;
    ///
    /// let server = Server::new(Path::new("./public"))?
    ///     .with_spa_root("#app")
    ///     .with_spa_transition(SpaTransition::Slide(
    ///         SlideOptions::default().duration_ms(500),
    ///     ));
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_spa_transition(mut self, transition: SpaTransition) -> Self {
        self.spa_mode = true;
        self.spa_transition = transition;
        self
    }

    /// Serves `path` as the body of every `404`, instead of the default plain-text
    /// `not found`.
    ///
    /// `path` is resolved relative to the served root and must exist when this is
    /// called: a missing 404 page is a deployment mistake, and finding out on the first
    /// broken link — the one moment the page exists to handle — is too late. It is read
    /// from disk per response rather than cached, so editing it during a live-reload
    /// session takes effect without a restart.
    ///
    /// The response keeps its `404` status. Serving a custom page with `200` is a soft
    /// 404: search engines index it, and monitoring stops seeing the failures. It also
    /// carries `Cache-Control: no-store`, so a client never holds this page as though it
    /// were the resource that was actually requested.
    ///
    /// Nothing about the failed request reaches the page — no path, no reason. A
    /// traversal attempt and an ordinary miss are deliberately indistinguishable
    /// (`StaticError::user_message`), and templating the requested path into the
    /// response would undo that and hand back a reflected-content vector besides.
    ///
    /// # Errors
    ///
    /// Returns `Err(StaticError::Io)` if `path` cannot be canonicalized (typically:
    /// it does not exist), or `Err(StaticError::Traversal)` if it lies outside the
    /// served root.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// use mini_static::Server;
    /// use std::path::Path;
    ///
    /// let server = Server::new(Path::new("./public"))?
    ///     .with_not_found_page(Path::new("404.html"))?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_not_found_page(mut self, path: &Path) -> Result<Self, StaticError> {
        let joined = self.root_canon.join(path);
        let canon = joined.canonicalize().map_err(StaticError::Io)?;

        if !canon.starts_with(&self.root_canon) {
            return Err(StaticError::Traversal(format!(
                "404 page {} lies outside the served root {}",
                canon.display(),
                self.root_canon.display()
            )));
        }

        self.not_found_page = Some(canon);
        Ok(self)
    }

    /// Serve dot-prefixed paths (`.env`, `.git/config`) instead of answering them as a
    /// miss.
    ///
    /// Hidden files are denied by default. A served root is routinely a build output
    /// directory, a repository working copy, or a folder someone dropped a `.env` into,
    /// and the traversal guard cannot help: those files are legitimately *inside* the
    /// root, so anyone who guesses the name gets them. The default trades a rarely-wanted
    /// capability for not leaking credentials by accident.
    ///
    /// `/.well-known/` is served either way — it is where the web puts resources that
    /// are meant to be fetched (ACME challenges for certificate issuance,
    /// `security.txt`), and denying it would break certificate renewal. The exception is
    /// the first segment only: `/.well-known/.hidden` is still denied.
    ///
    /// Call this when the served root is a curated directory whose dotfiles are content
    /// — a static site that publishes a `.htaccess` for a downstream server, say.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// use mini_static::Server;
    /// use std::path::Path;
    ///
    /// let server = Server::new(Path::new("./public"))?.with_hidden_files();
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_hidden_files(mut self) -> Self {
        self.hidden_files = HiddenFiles::Serve;
        self
    }

    /// A cached sidecar for `relative`, honouring the client's stated encoding preference.
    ///
    /// The variants are already in the map: a `.br` file is a regular file and was enumerated
    /// under its own name, so this is a second lookup rather than extra storage. A cached root
    /// therefore serves precompressed assets with **no `open()` at all**, where the disk path
    /// spends up to two.
    ///
    /// Negotiation comes from `preferred_encodings`, the same function the disk probe uses, so
    /// the two cannot disagree about which encoding a client wanted.
    fn cached_sidecar(
        &self,
        relative: &Path,
        accept_encoding: Option<&str>,
    ) -> Option<(&crate::cache::CachedFile, &'static str)> {
        let cache = self.content_cache.as_ref()?;
        for (encoding, ext) in preferred_encodings(accept_encoding) {
            let mut sibling = relative.as_os_str().to_os_string();
            sibling.push(ext);
            if let Some(entry) = cache.get(Path::new(&sibling)) {
                return Some((entry, encoding));
            }
        }
        None
    }

    /// The cached entry for a request's segments, if one is held and usable.
    ///
    /// Retries with `index.html` appended, because the disk path resolves a directory to its
    /// index and a cache keyed on files would otherwise miss `/` — the most common request any
    /// site receives. The returned path is relative to the root; the caller joins it, so the
    /// trailing-slash redirect downstream sees exactly the path it would have seen from disk.
    ///
    /// Does **not** decline an entry that has a precompressed sibling, though an earlier draft
    /// did. The sidecar probe runs after this and replaces the body when the client accepts an
    /// encoding, so declining changed nothing a client could see — a mutation removing the
    /// decline left every test green, which is how the code was found to be inert. Dropping it
    /// is also faster: a client that sends no `Accept-Encoding` now gets such a file from
    /// memory instead of from disk.
    fn cached_entry<S: AsRef<str>>(
        &self,
        segments: Option<&[S]>,
        request_path: &str,
    ) -> Option<(PathBuf, &crate::cache::CachedFile)> {
        let cache = self.content_cache.as_ref()?;

        // `handle_request` supplies no segments, so decode them here. The disk path would do
        // the same work; nothing is duplicated by doing it before the lookup instead of after.
        let decoded = match segments {
            Some(_) => None,
            None => Some(resolve::decode_segments(request_path).ok()?),
        };

        // The same refusals the disk path makes, from the same function. Skipping them served
        // `/.env` from memory while the disk path refused it; a cache must not be a way around
        // a policy.
        let key: PathBuf = match (segments, &decoded) {
            (Some(given), _) => resolve::servable_segments(given, request_path, self.hidden_files)
                .ok()?
                .iter()
                .map(|segment| segment.as_ref())
                .collect(),
            (None, Some(own)) => {
                resolve::servable_segments(own, request_path, self.hidden_files).ok()?;
                own.iter().map(|segment| segment.as_ref()).collect()
            }
            (None, None) => return None,
        };

        let direct = self.content_cache.as_ref().and_then(|c| c.get(&key)).map(|entry| (key.clone(), entry));
        let found = match direct {
            Some(found) => found,
            None => {
                let index = key.join(resolve::INDEX_FILE_NAME);
                let entry = cache.get(&index)?;
                (index, entry)
            }
        };
        Some(found)
    }

    /// The conflict between a content cache and live-reload, decided in one place.
    ///
    /// Live-reload exists because files under the root change while the server runs; the cache
    /// exists because they do not. Holding both is not a preference to resolve at serve time —
    /// it is a contradiction, and serving stale content while a watcher announces changes is
    /// the worst of the available outcomes.
    ///
    /// Consulted from all three entry points rather than checked at each: `with_content_cache`
    /// catches the conflict when the cache is added second, `run_on` catches it when
    /// live-reload is, and `into_fallback` catches it for a composed deployment that never
    /// calls `run_on` at all. One condition, three callers — the alternative is three copies of
    /// a rule that must agree.
    fn cache_conflict(&self) -> Option<StaticError> {
        (self.live_reload && self.content_cache.is_some()).then(|| {
            StaticError::Config(
                "a content cache and live-reload cannot both be enabled: live-reload watches \
                 the served root for changes, and the cache is never invalidated, so every \
                 change it reported would be a change the server did not serve. Drop \
                 with_content_cache for development, or with_live_reload for production."
                    .to_string(),
            )
        })
    }

    /// Read the served root into memory now, and answer from memory thereafter.
    ///
    /// **This reads the filesystem when called**, walking the root and holding up to
    /// `max_bytes` of file contents. That is unusual for a builder and is the point: the cost
    /// is paid once, at construction, so no request pays it.
    ///
    /// # The promise you are making
    ///
    /// The cache is never invalidated. **A file changed under the root after this call is
    /// served in its old form until the process restarts.** That suits the deployment this
    /// crate targets — a baked image, built then served — and does not suit a root that is
    /// written while running, which is why a server configured with both this and
    /// [`Server::with_live_reload`] refuses to start rather than serving stale content.
    ///
    /// # What is cached
    ///
    /// Real regular files only. Symlinks, FIFOs, sockets and devices are refused, and the walk
    /// does not follow a symlinked directory — so every cached path is inside the root by
    /// construction, with no containment check of its own. Anything not cached, including
    /// everything past `max_bytes`, is served from disk exactly as before.
    ///
    /// Exceeding `max_bytes` truncates rather than failing: enumeration is sorted, so the
    /// cached set is a deterministic prefix, and the shortfall is logged.
    /// # Errors
    ///
    /// Returns `Err` if [`Server::with_live_reload`] was already called: live-reload watches
    /// the served root for changes and this cache is never invalidated, so the two contradict
    /// each other. Fallible in the builder rather than only at start-up
    /// because catching a contradiction at the call site that created it beats catching it
    /// later; `with_live_reload` cannot do the same, since it returns `Self`.
    pub fn with_content_cache(mut self, max_bytes: usize) -> Result<Self, StaticError> {
        let cache = crate::cache::populate(&self.root_canon, max_bytes);
        self.log(format_args!(
            "content cache: {} files, {} bytes, {} with precompressed siblings{}",
            cache.len(),
            cache.bytes_held(),
            cache.with_siblings(),
            if cache.truncated() {
                format!(" (truncated at the {max_bytes}-byte ceiling; the rest serves from disk)")
            } else {
                String::new()
            }
        ));
        self.content_cache = Some(Arc::new(cache));
        match self.cache_conflict() {
            Some(conflict) => Err(conflict),
            None => Ok(self),
        }
    }

    /// Stop looking for precompressed `.br`/`.gz` siblings.
    ///
    /// Serving a sidecar costs **two `open()` calls per request that finds none**, because
    /// browsers send `Accept-Encoding` on every request: one attempt for `<path>.br`, one
    /// for `<path>.gz`. Measured on a 484-byte file that is **12.7% of throughput**
    /// (58,638 → 66,077 req/s), which makes it the largest single cost this crate pays for
    /// a feature many deployments never use — nothing in this ecosystem generates sidecars,
    /// so a root without them pays the whole 12.7% for a lookup that cannot succeed.
    ///
    /// Left **on by default** deliberately. Inferring the answer from a directory scan would
    /// be behaviour a reader has to know to look for, and defaulting it off would silently
    /// stop serving precompressed assets for anyone who does ship them — a failure visible
    /// only as a bandwidth bill. So it is a decision made at the call site.
    ///
    /// Call this when the served root contains no `.br` or `.gz` siblings. If one appears
    /// later it will not be served, which is the whole of what this trades away.
    pub fn without_precompressed(mut self) -> Self {
        self.precompressed = false;
        self
    }

    /// Log one line per request to stderr, plus connection-level errors.
    ///
    /// Off by default: a library that writes to a process's stderr uninvited is a
    /// surprise, and an embedder with its own logging wants the lines somewhere else.
    /// See [`Server::with_request_logging_to`] to choose the destination.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// use mini_static::Server;
    /// use std::path::Path;
    ///
    /// let server = Server::new(Path::new("./public"))?.with_request_logging();
    /// # Ok(())
    /// # }
    /// ```
    /// Send `name: value` on every response.
    ///
    /// Call repeatedly to add several. Intended for the policy headers a static site
    /// wants applied uniformly — `Strict-Transport-Security`, `Content-Security-Policy`,
    /// `Referrer-Policy` — which this crate has no business choosing on an embedder's
    /// behalf but every business making expressible.
    ///
    /// Both name and value are validated here, at configuration time, so a malformed
    /// header fails when the server is built rather than on a request months later.
    ///
    /// # Errors
    ///
    /// - `StaticError::Config` if `name` or `value` is not a valid HTTP header.
    /// - `StaticError::Config` if `name` is one this server computes per response
    ///   (`Content-Length`, `Content-Type`, `Content-Encoding`, `Content-Range`, `ETag`,
    ///   `Cache-Control`, `Vary`, `Accept-Ranges`, `Allow`, `Location`, `Connection`,
    ///   `Transfer-Encoding`, `X-Content-Type-Options`). A fixed value would either be
    ///   silently overridden or silently duplicated depending on the response — a
    ///   configuration mistake worth surfacing at startup rather than a behavior worth
    ///   supporting. Use [`Server::with_immutable_assets`] for cache policy.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// use mini_static::Server;
    /// use std::path::Path;
    ///
    /// let server = Server::new(Path::new("./public"))?
    ///     .with_response_header("Strict-Transport-Security", "max-age=63072000")?
    ///     .with_response_header("Referrer-Policy", "strict-origin-when-cross-origin")?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_response_header(mut self, name: &str, value: &str) -> Result<Self, StaticError> {
        let name = HeaderName::from_bytes(name.as_bytes())
            .map_err(|_| StaticError::Config(format!("invalid header name: {name}")))?;
        let value = HeaderValue::from_str(value).map_err(|_| {
            StaticError::Config(format!("invalid value for header {name}: {value}"))
        })?;

        if SERVER_COMPUTED_HEADERS.contains(&name) {
            return Err(StaticError::Config(format!(
                "{name} is computed per response and cannot be set as a fixed header"
            )));
        }

        Arc::make_mut(&mut self.extra_headers).push((name, value));
        Ok(self)
    }

    pub fn with_request_logging(self) -> Self {
        self.with_request_logging_to(Box::new(std::io::stderr()))
    }

    /// Log one line per request to `writer`, plus connection-level errors.
    ///
    /// Each served request writes one line:
    ///
    /// ```text
    /// GET /index.html 200 512 0.421ms
    /// ```
    ///
    /// — method, requested path exactly as received, status, response body bytes (`-`
    /// when the length isn't known, as on a live-reload SSE stream), and how long
    /// handling took. Connection-level failures — a malformed request, a client
    /// vanishing mid-response — write `connection error: <cause>`; before this they were
    /// discarded entirely, so a server that was refusing every request looked exactly
    /// like one nobody was talking to.
    ///
    /// The path is logged as received, *not* decoded: it is attacker-controlled input,
    /// and a log reader deserves to see the bytes that actually arrived rather than a
    /// normalized rendering of them.
    ///
    /// Writes are serialized across connections and write errors are ignored — a
    /// failing log sink must not take down request serving.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// use mini_static::Server;
    /// use std::fs::File;
    /// use std::path::Path;
    ///
    /// let log = File::create("access.log")?;
    /// let server = Server::new(Path::new("./public"))?.with_request_logging_to(Box::new(log));
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_request_logging_to(mut self, writer: Box<dyn Write + Send>) -> Self {
        self.request_log = Some(Arc::new(Mutex::new(writer)));
        self
    }

    /// Start a response carrying the baseline security header plus every header the
    /// embedder configured via [`Server::with_response_header`].
    ///
    /// Every response this server builds for a request goes through here, so a
    /// configured policy header cannot be missing from one status and present on
    /// another. The sole exception is the `400` that `finish` falls back to when a
    /// builder produced an invalid header — no `Server` is in scope there, and a
    /// response that exists only because header construction already failed is the wrong
    /// place to add more headers.
    fn response(&self, status: StatusCode) -> Builder {
        let mut builder = response(status);
        for (name, value) in self.extra_headers.iter() {
            builder = builder.header(name, value);
        }
        builder
    }

    /// Write `line` to the configured log sink, if there is one.
    ///
    /// A poisoned mutex (some earlier writer panicked mid-write) and a failed write are
    /// both ignored: neither is a reason to fail a request that was otherwise served
    /// correctly.
    fn log(&self, line: std::fmt::Arguments<'_>) {
        let Some(log) = &self.request_log else {
            return;
        };
        if let Ok(mut sink) = log.lock() {
            let _ = writeln!(sink, "{line}");
            let _ = sink.flush();
        }
    }

    /// Serve files matching `predicate` with a long-lived, immutable cache policy
    /// instead of the default `Cache-Control: no-cache`.
    ///
    /// `predicate` is evaluated against each resolved file's path; a match sends
    /// `Cache-Control: public, max-age=31536000, immutable` on that file's 200 and 304
    /// responses. This is correct only for fingerprinted assets (e.g.
    /// `main.a1b2c3.js`) where a content change always produces a new filename —
    /// caching a mutable filename indefinitely would serve stale content to every
    /// client that already has it cached.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// use mini_static::Server;
    /// use std::path::Path;
    ///
    /// let server = Server::new(Path::new("./public"))?
    ///     .with_immutable_assets(|path| {
    ///         path.file_name()
    ///             .and_then(|name| name.to_str())
    ///             .is_some_and(|name| name.contains(".fingerprint."))
    ///     });
    /// # Ok(())
    /// # }
    /// ```
    pub fn with_immutable_assets<F>(mut self, predicate: F) -> Self
    where
        F: Fn(&Path) -> bool + Send + Sync + 'static,
    {
        self.immutable_predicate = Some(Arc::new(predicate));
        self
    }

    /// The `Cache-Control` header value for a resolved file path: the immutable policy
    /// if `with_immutable_assets`'s predicate matches, `no-cache` otherwise.
    fn cache_control_for(&self, path: &Path) -> &'static str {
        match &self.immutable_predicate {
            Some(predicate) if predicate(path) => "public, max-age=31536000, immutable",
            _ => "no-cache",
        }
    }

    /// The directories the live-reload watcher polls: the served root, and only that.
    ///
    /// Until 0.29.0 this also returned the build pipeline's source folders, and the
    /// served root was excluded whenever a pipeline was configured — watching the output
    /// dir would have fed each pipeline its own writes back into its own trigger. The
    /// pipeline now lives in `mini-build`, in a separate process, so nothing this server
    /// watches is written by this server and the exclusion has nothing left to prevent.
    fn watch_targets(&self) -> Vec<PathBuf> {
        vec![self.root_canon.clone()]
    }

    /// Resolve a request path under the server's root.
    ///
    /// This is a lower-level API for resolving paths without generating HTTP responses.
    /// For most use cases, prefer [`Server::handle_request`] or the `run*` methods.
    ///
    /// # Returns
    ///
    /// - `Ok(PathBuf)` if the path resolves to a file within root.
    /// - `Err(StaticError)` if the path is invalid, missing, or attempts traversal.
    pub fn resolve(&self, request_path: &str) -> Result<PathBuf, StaticError> {
        resolve::resolve_with_policy(&self.root_canon, request_path, self.hidden_files)
    }

    /// Builds the `404` response: the configured page when there is one and it can be
    /// read, and `fallback` as plain text otherwise.
    ///
    /// `fallback` is the caller's already-sanitized message (see
    /// `StaticError::user_message`) — never the requested path, so an ordinary miss and
    /// a rejected traversal stay indistinguishable to whoever is probing.
    ///
    /// A page that vanished after `with_not_found_page` validated it degrades to that
    /// text rather than to a `500`: the request was still a miss, and answering a
    /// missing page with the wrong status would be a second bug wearing the first one's
    /// clothes.
    async fn not_found_response(&self, fallback: &'static str) -> Response<ResponseBody> {
        let builder = self
            .response(StatusCode::NOT_FOUND)
            .header("Cache-Control", "no-store");

        let Some(page) = &self.not_found_page else {
            return text(builder, format!("{fallback}\n"));
        };
        let Ok(body) = tokio::fs::read(page).await else {
            return text(builder, format!("{fallback}\n"));
        };

        text(
            builder.header("Content-Type", "text/html; charset=utf-8"),
            body,
        )
    }

    /// This root as a `mini-serve` fallback handler.
    ///
    /// The composed deployment: register API routes, then hand everything they do not
    /// match to the files.
    ///
    /// ```no_run
    /// # fn example(files: mini_static::Server, api: mini_serve::Handler<()>) -> mini_serve::App<()> {
    /// mini_serve::RouteBuilder::stateless()
    ///     .get("/api/users", api)
    ///     .with_fallback(files.into_fallback())
    ///     .seal()
    /// # }
    /// ```
    ///
    /// This is what `mini-unified` existed to provide. That crate had to wrap this one's
    /// handler for `mini-serve` because this crate shipped a whole server, when the
    /// composed case only ever wanted the handler out of it.
    pub fn into_fallback<S: Send + Sync + 'static>(self) -> mini_serve::Handler<S> {
        // The composed path never calls `run_on`, so this is where the cache/live-reload
        // contradiction has to be caught for it. Returning a `Handler` leaves no way to report
        // an error, so every request fails loudly instead: a `500` naming the misconfiguration
        // is a bug found in the first minute of testing, where serving stale content while a
        // watcher announces changes is a bug found in production, by a reader, weeks later.
        if let Some(conflict) = self.cache_conflict() {
            let message = conflict.to_string();
            self.log(format_args!("refusing to serve: {message}"));
            return mini_serve::handler(move |_req, _state| {
                let message = message.clone();
                async move { Err(mini_serve::ServeError::new(500, message)) }
            });
        }
        let server = Arc::new(self);
        mini_serve::handler(move |req, _state| {
                let server = Arc::clone(&server);
                async move {
                    // The router already split and decoded this path; taking its answer is
                    // the point. `unwrap_or_default` covers a caller who wired the handler
                    // up without the seam — an empty segment list resolves to the root's
                    // index, which is the same answer a bare `/` gets.
                    // Taken, not cloned. Cloning cost a `Vec<String>` and one allocation
                    // per segment on every request; nothing downstream reads the extension
                    // again, so moving it out is free.
                    let mut req = req;
                    let segments = req
                        .extensions_mut()
                        .remove::<mini_serve::PathSegments>()
                        .map(|s| s.0)
                        .unwrap_or_default();
                    // Logged here rather than in the connection layer, which this crate no
                    // longer owns. The format is unchanged — `mini-serve`'s own line omits
                    // the byte count, and changing either crate's format to unify them is
                    // a user-visible change worth making on its own, not inside a
                    // migration.
                    let started = Instant::now();
                    let method = req.method().clone();
                    let path = req.uri().path().to_string();

                    let resp = server.respond(&req, &segments).await;

                    let bytes = header_str(resp.headers(), "content-length").unwrap_or("-");
                    server.log(format_args!(
                        "{method} {path} {} {bytes} {:.3}ms",
                        resp.status().as_u16(),
                        started.elapsed().as_secs_f64() * 1000.0,
                    ));
                    Ok(bridge_body(resp))
                }
        })
    }

    /// Build the `mini-serve` app that serves this root, and nothing else.
    ///
    /// The whole crate as one fallback: with no routes registered, every request is a file
    /// request. The same app with routes in front is the composed deployment, which is what
    /// [`Server::into_fallback`] is for.
    fn into_app(self, header_timeout: Duration) -> mini_serve::App<()> {
        let max_connections = self.max_connections;
        mini_serve::RouteBuilder::stateless()
            .with_header_read_timeout(header_timeout)
            .with_max_connections(max_connections)
            // This crate's own 64 KiB ceiling, passed through rather than dropped. It
            // predates mini-serve having one at all — the migration is what surfaced that.
            .with_max_header_bytes(MAX_HEADER_BYTES)
            .with_fallback(self.into_fallback())
            .seal()
    }

    /// Run the server on a specific address with a configurable header-read timeout.
    ///
    /// Spawns the server in a background Tokio task and returns immediately with the
    /// assigned port number and a [`ServerHandle`]. Call `handle.shutdown().await` to
    /// stop accepting new connections and wait for in-flight connections to finish.
    /// Dropping the handle instead leaves the server running for the life of the process.
    ///
    /// # Header-Read Timeout
    ///
    /// Connections that don't send complete HTTP headers within `header_timeout` are closed.
    /// This prevents slowloris attacks and resource exhaustion from incomplete requests. The
    /// timeout applies only to the header-read phase — once a complete header block has been
    /// read, the connection is handed off with no further time bound, so long-lived response
    /// bodies (e.g. the live-reload SSE stream from [`Server::with_live_reload`]) are not cut
    /// off mid-stream.
    ///
    /// # Precompressed Sidecars
    ///
    /// If a request's `Accept-Encoding` allows `br` or `gzip` (preferring `br`) and a
    /// sibling `<path>.br`/`<path>.gz` exists next to the resolved file, its bytes are
    /// served instead with a matching `Content-Encoding`. Every file response carries
    /// `Vary: Accept-Encoding` so intermediate caches don't serve the wrong variant to a
    /// differently-capable client.
    ///
    /// # Arguments
    ///
    /// * `addr` - Socket address to bind to (e.g., `127.0.0.1:0` for loopback ephemeral,
    ///   or `0.0.0.0:8080` to bind all interfaces on a fixed port).
    /// * `header_timeout` - Maximum time to wait for complete HTTP headers on each connection.
    ///
    /// # Returns
    ///
    /// - `Ok((u16, ServerHandle))` with the assigned port number and a handle for graceful shutdown.
    /// - `Err(StaticError::Io)` if binding to the socket fails. This is the only error
    ///   this function returns.
    pub async fn run_on(
        &self,
        addr: SocketAddr,
        header_timeout: Duration,
    ) -> Result<(u16, ServerHandle), StaticError> {
        if let Some(conflict) = self.cache_conflict() {
            return Err(conflict);
        }
        let listener = TcpListener::bind(addr).await.map_err(StaticError::Io)?;
        let port = listener.local_addr().map_err(StaticError::Io)?.port();

        let mut server = self.clone();
        if server.live_reload {
            // The served root is the only watch target now that nothing writes into it.
            // While the build pipeline lived here the output dir was deliberately never
            // watched, because watching it fed each pipeline its own writes back into its
            // trigger; with the builder in a separate process that loop cannot happen.
            let broadcaster = Broadcaster::new();
            for dir in server.watch_targets() {
                start_watching(Arc::new(dir), broadcaster.clone());
            }
            server.broadcaster = Some(broadcaster);
        }

        let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel();
        let app = server.into_app(header_timeout);
        let accept_task = tokio::spawn(async move {
            // `mini-serve` owns the accept loop, the connection ceiling, the header-read
            // timeout and the bounded drain — all of them mutation-verified there. This
            // crate used to carry a second implementation of each; keeping two was how the
            // two came to disagree about what a path segment is.
            let _ = app
                .run(listener, async move {
                    let _ = shutdown_rx.await;
                })
                .await;
        });

        Ok((
            port,
            ServerHandle {
                shutdown_tx: Some(shutdown_tx),
                accept_task,
            },
        ))
    }

    /// Run the server on loopback (127.0.0.1), binding an ephemeral port.
    ///
    /// Thin wrapper around [`Server::run_on`] — see it for the header-read timeout and
    /// sidecar semantics, and for what the returned [`ServerHandle`] does.
    pub async fn run(&self, header_timeout: Duration) -> Result<(u16, ServerHandle), StaticError> {
        self.run_on((EPHEMERAL_BIND_IP, 0).into(), header_timeout).await
    }

    /// Run the server on all interfaces (0.0.0.0) at `port` (0 for an ephemeral port).
    ///
    /// Useful for containerized deployments and reverse-proxy setups. Thin wrapper
    /// around [`Server::run_on`] — see it for the header-read timeout and sidecar
    /// semantics, and for what the returned [`ServerHandle`] does.
    pub async fn run_all(
        &self,
        port: u16,
        header_timeout: Duration,
    ) -> Result<(u16, ServerHandle), StaticError> {
        self.run_on(([0, 0, 0, 0], port).into(), header_timeout)
            .await
    }

    /// Run the server on loopback with the default 30-second header-read timeout.
    ///
    /// The recommended entry point for tests and lightweight services that don't need a
    /// custom timeout. Thin wrapper around [`Server::run`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// use mini_static::Server;
    /// use std::path::Path;
    ///
    /// let server = Server::new(Path::new("./public"))?;
    /// let (port, handle) = server.run_ephemeral().await?;
    /// println!("Server ready on http://127.0.0.1:{}", port);
    /// handle.shutdown().await;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn run_ephemeral(&self) -> Result<(u16, ServerHandle), StaticError> {
        self.run(DEFAULT_HEADER_TIMEOUT).await
    }

    /// Produce the HTTP response for a request, streaming file bodies to the client.
    ///
    /// This is the crate's single request-handling path: the `run*` accept loop calls it,
    /// and so should any async server embedding `mini-static` as a fallback route (e.g.
    /// `mini-unified`).
    ///
    /// Filesystem metadata work (path resolution, `open`, `stat`) runs *inline* on the
    /// calling task, deliberately. Until 0.30.0 it was dispatched to Tokio's blocking
    /// pool so a slow filesystem could not stall co-scheduled tasks — measured under
    /// load, that dispatch cost roughly three times the syscalls it sheltered, and a
    /// one-worker server burned nearly four cores on pool handoff. On the local-disk
    /// deployments this crate targets these calls are single-digit microseconds; an
    /// embedder serving from a filesystem with unbounded latency (a network mount)
    /// should use a multi-threaded runtime, which bounds the blast radius of a stall
    /// to one worker.
    ///
    /// File responses are backed by `FileBody`, which hands hyper one 64 KB chunk at a
    /// time as `poll_frame` is driven: memory use stays bounded to one chunk per in-flight
    /// response regardless of file size.
    ///
    /// `headers` are the request's headers; `If-None-Match` (304 on a matching ETag) and
    /// `Accept-Encoding` (precompressed sidecar selection, see [`Server::run_on`]) are the
    /// ones read today. Only `GET` and `HEAD` are allowed; anything else gets a 405 with an
    /// `Allow` header. Missing files and traversal attempts both get an identical 404, so a
    /// response never discloses whether a path exists outside the root.
    pub async fn handle_request(
        &self,
        method: &Method,
        request_path: &str,
        headers: &HeaderMap,
    ) -> Response<ResponseBody> {
        self.serve(method, request_path, headers, None::<&[String]>).await
    }

    /// Serve a request whose path a router has already split and decoded.
    ///
    /// The engine, without a server around it. Every type here belongs to `http`/`hyper`,
    /// so this drops into any stack that speaks them — it is not a `mini-serve` adapter.
    ///
    /// `segments` decide **which file is opened**; the request's raw path is used only to
    /// echo back into a `Location` redirect, and never to resolve anything. That division
    /// is the point: a redirect must preserve the client's own encoding (`/my%20docs` →
    /// `/my%20docs/`, since re-encoding is not a safe round-trip — `%41` would return as
    /// `A`), while resolution must use exactly the segments the router matched on. Two
    /// crates deriving path segments independently is what let `/admin%2Fconfig` reach a
    /// nested file while the router in front saw one segment and matched no route.
    ///
    /// Segments are still checked before they touch the filesystem. Where they came from
    /// is the caller's business; whether they can escape the root is this crate's.
    pub async fn respond<B>(
        &self,
        req: &Request<B>,
        segments: &[String],
    ) -> Response<ResponseBody> {
        self.serve(req.method(), req.uri().path(), req.headers(), Some(segments))
            .await
    }

    /// One implementation behind both entry points. `segments` is `None` when this crate
    /// owns the path and `Some` when a router already decided it.
    async fn serve<S: AsRef<str>>(
        &self,
        method: &Method,
        request_path: &str,
        headers: &HeaderMap,
        segments: Option<&[S]>,
    ) -> Response<ResponseBody> {
        if method != Method::GET && method != Method::HEAD {
            return text(
                self.response(StatusCode::METHOD_NOT_ALLOWED)
                    .header("Allow", "GET, HEAD"),
                "method not allowed\n",
            );
        }

        // Live-reload SSE stream — only reachable when `with_live_reload()` was called
        // and the server was started via a `run*` method (those are the only paths that
        // populate `broadcaster`).
        if *method == Method::GET && request_path == reload::LIVE_RELOAD_PATH {
            if let Some(broadcaster) = &self.broadcaster {
                return finish(
                    self.response(StatusCode::OK)
                        .header("Content-Type", "text/event-stream")
                        .header("Cache-Control", "no-cache")
                        .header("Connection", "keep-alive")
                        .body(ResponseBody::Sse(SseBody::new(broadcaster.subscribe()))),
                );
            }
        }

        // Inline on purpose — see this function's doc comment for the measured case
        // against the old `spawn_blocking` dispatch. One call opens the file and proves
        // containment on the opened fd, so there is no separate open to fail later and
        // no window between the check and the handle that gets served.
        // The cache is consulted before the open, because avoiding the open — and the `fstat`
        // behind it — is the entire reason the cache exists. A miss falls through to exactly
        // the resolution that has always run, including its refusals.
        let cached = self.cached_entry(segments, request_path);
        let (source, metadata, path, cached_key) = match cached {
            Some((relative, entry)) => (
                BodySource::Memory(entry.bytes.clone()),
                entry.metadata.clone(),
                self.root_canon.join(&relative),
                Some(relative),
            ),
            None => {
                let opened = match segments {
                    Some(segments) => resolve::open_segments(
                        &self.root_canon,
                        segments,
                        request_path,
                        self.hidden_files,
                    ),
                    None => {
                        resolve::open_with_policy(&self.root_canon, request_path, self.hidden_files)
                    }
                };
                let resolved = match opened {
                    Err(e) => return self.not_found_response(e.user_message()).await,
                    Ok(resolved) => resolved,
                };
                (
                    BodySource::Descriptor(resolved.file),
                    resolved.metadata,
                    resolved.path,
                    None,
                )
            }
        };

        // A directory served via its `index.html` needs a trailing slash to establish the
        // correct base for the page's relative links. Compare against the *decoded*
        // request path so a percent-encoded explicit request for index.html (e.g.
        // `/docs/index.htm%6c`) is recognized as such instead of producing a redirect to a
        // still-encoded, broken Location.
        // Compared segment-wise through the same decoder resolution used, so a
        // percent-encoded explicit request for index.html (e.g. `/docs/index.htm%6c`) is
        // recognised as such instead of redirecting to a still-encoded, broken Location.
        // A trailing slash is read from the raw path: `%2F` is no longer a separator, so
        // a real trailing slash is the only thing that can produce one.
        let last_segment = resolve::decode_segments(request_path)
            .ok()
            .and_then(|segments| segments.last().cloned())
            .unwrap_or_default();
        if path.file_name().is_some_and(|name| name == resolve::INDEX_FILE_NAME)
            && !request_path.ends_with('/')
            && last_segment != resolve::INDEX_FILE_NAME
        {
            // `location` is built from the (attacker-controlled) request path; `finish()`
            // degrades to 400 instead of panicking if it ever contains bytes invalid in a
            // header value.
            let location = format!("{}/", request_path.trim_end_matches('/'));
            return text(
                self.response(StatusCode::MOVED_PERMANENTLY)
                    .header("Location", location),
                "moved\n",
            );
        }

        let content_type = mime_type_for_path(&path);
        // Live-reload and spa-mode HTML injection both need the original, uncompressed
        // bytes to splice their script into — never substitute a precompressed sidecar on
        // this path. `broadcaster` is only `Some` when live-reload is enabled (see
        // `Server::with_live_reload`); `spa_mode` is independent of it (see
        // `Server::with_spa_mode`/`with_spa_root`) — either alone is enough to trigger
        // injection.
        // Injection reads the whole file into memory, so it is also gated on size. Every
        // decision keyed off `html_injection` — the sidecar skip below, the range skip,
        // the full read itself — inherits the cap from this one boolean, so an over-cap
        // page takes the ordinary streamed path with no second decision point.
        let wants_injection =
            (self.broadcaster.is_some() || self.spa_mode) && content_type.starts_with("text/html");
        let html_injection = wants_injection && metadata.len() <= MAX_INJECTABLE_HTML_BYTES;

        if wants_injection && !html_injection {
            self.log(format_args!(
                "html injection skipped for {request_path}: {} bytes exceeds the \
                 {MAX_INJECTABLE_HTML_BYTES}-byte limit; serving unmodified",
                metadata.len(),
            ));
        }

        let range_header = header_str(headers, "range");
        let if_range_header = header_str(headers, "if-range");

        let accept_encoding = header_str(headers, "accept-encoding");
        // Skip precompressed sidecars when Range is requested (serve original file instead).
        let wants_sidecar = self.precompressed && !html_injection && range_header.is_none();

        // A cached body looks for a cached variant, so a cached root spends no `open()` on
        // content negotiation at all — where the disk path spends up to two per request, on
        // files that usually do not exist. The disk probe is reached only when the body itself
        // came from disk.
        let cached_variant = match (wants_sidecar, &cached_key) {
            (true, Some(relative)) => self.cached_sidecar(relative, accept_encoding),
            _ => None,
        };
        let (source, metadata, content_encoding) = match cached_variant {
            Some((entry, encoding)) => (
                BodySource::Memory(entry.bytes.clone()),
                entry.metadata.clone(),
                Some(encoding),
            ),
            // Reached when the body came from disk, *and* when it came from memory but no
            // cached variant was found — budget truncation can hold `app.css` without holding
            // `app.css.br`, and a cached hit must still find that variant on disk or it would
            // serve an unencoded body where the disk path serves a compressed one. An earlier
            // draft guarded this with `cached_key.is_none()` and had exactly that divergence.
            None if wants_sidecar => {
                match select_precompressed_sidecar(&self.root_canon, &path, accept_encoding) {
                    Some((sidecar_file, sidecar_metadata, encoding)) => (
                        BodySource::Descriptor(sidecar_file),
                        sidecar_metadata,
                        Some(encoding),
                    ),
                    None => (source, metadata, None),
                }
            }
            None => (source, metadata, None),
        };
        // The handle stays synchronous until a body actually streams: every whole-file
        // read below (HTML injection, small bodies) is cheaper inline than as a
        // blocking-pool round trip, and only `FileBody` needs an async `File`.

        // HTML injection is skipped for a served precompressed sidecar (already final
        // bytes from a build step) — see `html_injection`'s definition above.
        let etag = generate_etag(&metadata);
        let cache_control = self.cache_control_for(&path);

        if header_str(headers, "if-none-match").is_some_and(|value| is_etag_match(value, &etag)) {
            return finish(
                self.response(StatusCode::NOT_MODIFIED)
                    .header("Cache-Control", cache_control)
                    .header("Vary", "Accept-Encoding")
                    .header("ETag", etag)
                    .header("Accept-Ranges", "bytes")
                    .body(ResponseBody::Buffered(Full::new(Bytes::new()))),
            );
        }

        // Built before the HEAD check below because RFC 9110 requires a HEAD response's
        // headers — `Content-Length` included — to match what a GET would send, even though
        // the body itself is dropped. Built once, so the descriptor is moved into exactly one
        // branch and there is no state where the source is both in memory and on disk.
        let source = if html_injection {
            use std::io::Read as _;
            let mut html = match source {
                // A cached page is injected from memory rather than re-read: the bytes are the
                // same bytes, so the served result is identical and the open is still avoided.
                BodySource::Memory(bytes) => bytes.to_vec(),
                BodySource::Descriptor(mut file) => {
                    let mut buffer = Vec::with_capacity(metadata.len() as usize);
                    if file.read_to_end(&mut buffer).is_err() {
                        return internal_error_response();
                    }
                    buffer
                }
            };
            if self.broadcaster.is_some() {
                reload::inject_reload_script(&mut html);
            }
            if self.spa_mode {
                spa::inject_spa_script(&mut html, self.spa_root.as_deref(), &self.spa_transition);
            }
            BodySource::Memory(Bytes::from(html))
        } else {
            source
        };

        let file_size = match &source {
            BodySource::Memory(bytes) => bytes.len() as u64,
            BodySource::Descriptor(_) => metadata.len(),
        };

        // Handle Range requests.
        let range_outcome = range_header.map(|h| parse_range_header(h, file_size));
        let range_check = if let Some(outcome) = &range_outcome {
            match outcome {
                RangeOutcome::Satisfiable(start, end) => {
                    // If-Range validation: stale If-Range ignores Range, serves full 200.
                    if let Some(if_range) = if_range_header {
                        if !if_range_valid(if_range, &etag) {
                            RangeCheck::IgnoreRange
                        } else {
                            RangeCheck::Satisfiable(*start, *end)
                        }
                    } else {
                        RangeCheck::Satisfiable(*start, *end)
                    }
                }
                RangeOutcome::MultiRangeIgnored => RangeCheck::IgnoreRange,
                RangeOutcome::Unsatisfiable => RangeCheck::Unsatisfiable,
                RangeOutcome::NoRange => RangeCheck::IgnoreRange,
            }
        } else {
            RangeCheck::IgnoreRange
        };

        match &range_check {
            RangeCheck::Unsatisfiable => {
                return finish(
                    Response::builder()
                        .status(StatusCode::RANGE_NOT_SATISFIABLE)
                        .header("Content-Range", format!("bytes */{}", file_size))
                        .header("Accept-Ranges", "bytes")
                        .body(ResponseBody::Buffered(Full::new(Bytes::new()))),
                );
            }
            RangeCheck::Satisfiable(start, end) => {
                let range_len = end - start + 1;

                // HEAD must not return a body (RFC 9110).
                let body = if *method == Method::HEAD {
                    ResponseBody::Buffered(Full::new(Bytes::new()))
                } else {
                    match source {
                        BodySource::Memory(bytes) => ResponseBody::Buffered(Full::new(
                            bytes.slice(*start as usize..(*end as usize + 1)),
                        )),
                        // The seek lives here rather than behind a guard above: only a
                        // descriptor can be sought, and now only the descriptor arm reaches it.
                        BodySource::Descriptor(mut file) => {
                            if std::io::Seek::seek(&mut file, std::io::SeekFrom::Start(*start))
                                .is_err()
                            {
                                return internal_error_response();
                            }
                            ResponseBody::Streamed(FileBody::new_ranged(
                                File::from_std(file),
                                range_len,
                            ))
                        }
                    }
                };

                let mut builder = Response::builder()
                    .status(StatusCode::PARTIAL_CONTENT)
                    .header("Content-Type", content_type)
                    .header("Content-Length", range_len.to_string())
                    .header(
                        "Content-Range",
                        format!("bytes {}-{}/{}", start, end, file_size),
                    )
                    .header("Cache-Control", cache_control)
                    .header("Vary", "Accept-Encoding")
                    .header("ETag", etag)
                    .header("Accept-Ranges", "bytes");
                if let Some(encoding) = content_encoding {
                    builder = builder.header("Content-Encoding", encoding);
                }
                return finish(builder.body(body));
            }
            RangeCheck::IgnoreRange => {}
        }

        // HEAD must not return a body (RFC 9110).
        let body = if *method == Method::HEAD {
            ResponseBody::Buffered(Full::new(Bytes::new()))
        } else {
            match source {
                BodySource::Memory(bytes) => ResponseBody::Buffered(Full::new(bytes)),
                BodySource::Descriptor(mut file) if metadata.len() <= INLINE_BODY_BYTES => {
                    // From the handle opened above — never by re-opening the path — so
                    // the bytes served are provably the file that was probed and
                    // stat'd, sidecars included, with no reopen window in between.
                    let mut bytes = Vec::with_capacity(metadata.len() as usize);
                    use std::io::Read as _;
                    if file.read_to_end(&mut bytes).is_err() {
                        return internal_error_response();
                    }
                    ResponseBody::Buffered(Full::new(Bytes::from(bytes)))
                }
                BodySource::Descriptor(file) => {
                    ResponseBody::Streamed(FileBody::new(File::from_std(file)))
                }
            }
        };

        let mut builder = self
            .response(StatusCode::OK)
            .header("Content-Type", content_type)
            .header("Content-Length", file_size.to_string())
            .header("Cache-Control", cache_control)
            .header("Vary", "Accept-Encoding")
            .header("ETag", etag)
            .header("Accept-Ranges", "bytes");
        if let Some(encoding) = content_encoding {
            builder = builder.header("Content-Encoding", encoding);
        }
        finish(builder.body(body))
    }
}

/// Ceiling on how many bytes hyper buffers for a single request's header block before
/// rejecting it. Without this, a client that trickles bytes forever without ever sending
/// the terminating blank line could grow the buffer without limit — the header-read
/// timeout alone doesn't bound memory, only wall-clock time, and a sufficiently patient
/// sender could still send unbounded data before the deadline fires.
const MAX_HEADER_BYTES: usize = 64 * 1024;

/// Ceiling on the size of an HTML file this server will buffer in memory to splice a
/// live-reload or spa-mode `<script>` into.
///
/// Injection is the one code path that reads a whole file into memory rather than
/// streaming it in bounded chunks, and it does so *per request* — so without a cap, a
/// single large HTML file turns every concurrent request for it into another full copy
/// in memory, and spa-mode is a production feature, not a development-only one. An
/// over-cap page is served unmodified (and streamed) instead: losing a client-side
/// navigation enhancement on an 8 MiB document is a far smaller failure than an
/// allocation proportional to file size times concurrency.
///
/// 8 MiB is comfortably above any hand-written HTML page and any realistic
/// static-site-generator output, so the cap should never fire on content this feature
/// was designed for.
const MAX_INJECTABLE_HTML_BYTES: u64 = 8 * 1024 * 1024;

/// Bodies at or below this size are read synchronously and served from memory; larger
/// ones stream through `FileBody`. Equal to `FileBody`'s chunk size on purpose: at or
/// under one chunk the streaming path performed exactly one read anyway, so buffering
/// changes only *where* that read runs (inline, instead of a blocking-pool round trip
/// per chunk) — never how much memory a response can hold.
const INLINE_BODY_BYTES: u64 = 64 * 1024;

/// The address [`Server::run`] and [`Server::run_ephemeral`] bind to.
///
/// Loopback, deliberately: a convenience entry point must not put a server on the LAN
/// because the caller did not think to say otherwise. Exposing the service is
/// [`Server::run_on`]'s job, where the address is written at the call site and visible in
/// review. Named rather than inlined so a test can assert the choice — the previous test
/// only checked that loopback *reached* the server, which is equally true of `0.0.0.0`.
const EPHEMERAL_BIND_IP: std::net::Ipv4Addr = std::net::Ipv4Addr::LOCALHOST;

/// Bridge this crate's response body to `mini-serve`'s.
///
/// `ResponseBody` stays a concrete enum so the streaming paths keep their own types; this
/// is the single place it is type-erased. The error remap matters as much as the erasure:
/// a mid-stream disk failure must abort the connection rather than being dropped, which
/// would send a truncated body under a `200`.
fn bridge_body(response: Response<ResponseBody>) -> Response<mini_serve::ResponseBody> {
    let (parts, body) = response.into_parts();
    let erased = http_body_util::BodyExt::map_err(body, mini_serve::BodyError::new);
    Response::from_parts(parts, http_body_util::BodyExt::boxed(erased))
}

/// Default header-read timeout used by [`Server::run_ephemeral`].
const DEFAULT_HEADER_TIMEOUT: Duration = Duration::from_secs(30);

/// Default grace period `ServerHandle::shutdown()` waits for in-flight connections to
/// finish on their own before aborting whatever is left. A connection with no
/// self-imposed end — an open live-reload SSE stream, or any keep-alive connection whose
/// peer simply never closes it — would otherwise let `shutdown()` hang forever waiting
/// for it to finish naturally. Every wait in this crate has a stated upper bound;
/// shutdown is no exception.
const DEFAULT_SHUTDOWN_DRAIN_TIMEOUT: Duration = Duration::from_secs(5);

/// A handle to a server started by one of the `Server::run*` methods.
///
/// Dropping this handle without calling `shutdown()` leaves the server running in the
/// background for the life of the process. Call `shutdown()` to stop accepting new
/// connections and wait for already-accepted connections to finish before returning.
pub struct ServerHandle {
    shutdown_tx: Option<tokio::sync::oneshot::Sender<()>>,
    accept_task: tokio::task::JoinHandle<()>,
}

impl ServerHandle {
    /// Stop accepting new connections and wait up to `DEFAULT_SHUTDOWN_DRAIN_TIMEOUT`
    /// (5s) for in-flight connections to finish on their own. Equivalent to
    /// `shutdown_with_timeout(DEFAULT_SHUTDOWN_DRAIN_TIMEOUT)` — see that method for what
    /// happens to connections still open once the grace period elapses.
    pub async fn shutdown(self) {
        self.shutdown_with_timeout(DEFAULT_SHUTDOWN_DRAIN_TIMEOUT)
            .await;
    }

    /// Stop accepting new connections and wait up to `drain_timeout` for in-flight
    /// connections to finish on their own.
    ///
    /// Connections still open once `drain_timeout` elapses are aborted rather than
    /// waited on further: dropping the accept task drops its `JoinSet`, which aborts
    /// every task still tracked in it (see `tokio::task::JoinSet`'s own drop behavior) —
    /// which in turn drops each connection's socket, closing it. This is what bounds
    /// shutdown when a connection has no natural end of its own (the live-reload SSE
    /// stream is the motivating case: it stays open until a watched file changes, which
    /// may never happen before the process needs to exit).
    pub async fn shutdown_with_timeout(mut self, drain_timeout: Duration) {
        if let Some(tx) = self.shutdown_tx.take() {
            let _ = tx.send(());
        }
        if timeout(drain_timeout, &mut self.accept_task).await.is_err() {
            self.accept_task.abort();
        }
    }
}

/// Read a request header as a `&str`, or `None` if it's absent or not valid ASCII.
fn header_str<'h>(headers: &'h HeaderMap, name: &str) -> Option<&'h str> {
    headers.get(name).and_then(|value| value.to_str().ok())
}

/// Start a response carrying the baseline security header every response in this crate
/// sends — 304s included. A 304 otherwise repeats only the caching validators, which is
/// why it once built its own builder and was the single response able to arrive without
/// `nosniff`; a client that caches the header set alongside the representation would
/// then hold a copy missing it.
///
/// Prefer [`Server::response`], which also applies the embedder's configured headers.
/// This bare form exists for `bad_request_response`, which is reachable from `finish`
/// where no `Server` is in scope.
fn response(status: StatusCode) -> Builder {
    Response::builder()
        .status(status)
        .header("X-Content-Type-Options", "nosniff")
}

/// Finish `builder` with a plain-text body. `&'static str` bodies borrow rather than
/// allocate; owned bodies are moved in.
fn text(builder: Builder, body: impl Into<Bytes>) -> Response<ResponseBody> {
    finish(builder.body(ResponseBody::Buffered(Full::new(body.into()))))
}

/// Finishes building a response, degrading to a generic 400 instead of panicking if any
/// header value turns out to be invalid for use as an HTTP header value.
///
/// Every header value that reaches `Response::builder()` in this module is either a
/// static string or formatted from internal, already-validated data (a byte count, an
/// mtime, a fixed method list) — none of it can actually fail today. But `.unwrap()`
/// on that assumption is exactly the kind of thing that turns "can't happen" into a
/// production panic the day someone adds a header built from new input without
/// re-deriving that guarantee. Routing every response through this one fallible path
/// means that mistake fails safe instead of panicking.
fn finish(built: Result<Response<ResponseBody>, hyper::http::Error>) -> Response<ResponseBody> {
    built.unwrap_or_else(|_| bad_request_response())
}

// `internal_error_response()` and `bad_request_response()` are the fallback responses
// `finish()` itself degrades to — every header and body here is a fixed string with no
// external input, so `.body(...)` cannot fail. They can't be routed through `finish()`
// without it degrading to itself on failure.
fn internal_error_response() -> Response<ResponseBody> {
    response(StatusCode::INTERNAL_SERVER_ERROR)
        .body(ResponseBody::Buffered(Full::new(Bytes::from_static(
            b"internal server error\n",
        ))))
        .unwrap()
}

fn bad_request_response() -> Response<ResponseBody> {
    response(StatusCode::BAD_REQUEST)
        .body(ResponseBody::Buffered(Full::new(Bytes::from_static(
            b"bad request\n",
        ))))
        .unwrap()
}

/// `Content-Encoding` name and sidecar file extension for each supported precompressed
/// variant, in preference order — brotli wins when a client accepts both and both
/// sidecars exist.
const SIDECAR_ENCODINGS: [(&str, &str); 2] = [("br", ".br"), ("gzip", ".gz")];

/// `q`-values are carried in thousandths — RFC 9110 allows at most three decimal places
/// — so weights compare exactly as integers instead of through float equality.
const QVALUE_SCALE: f32 = 1000.0;

/// An `Accept-Encoding` entry with no explicit `q` parameter has weight 1.
const DEFAULT_QVALUE: u16 = 1000;

/// The weight `accept_encoding` gives `encoding`, or `None` if it does not list it.
///
/// Entries are matched as whole tokens, case-insensitively, per RFC 9110 — not by
/// substring. The substring form this replaces got two things wrong that a client can
/// trigger: `Accept-Encoding: gzip;q=0` selected gzip, because the header *contains*
/// "gzip" while explicitly refusing it, and a token like `brotli` matched `br`.
///
/// `*` is deliberately not honored: treating the wildcard as matching nothing can only
/// cost a bandwidth optimization, while treating it as matching everything risks sending
/// an encoding the client did not ask for. The conservative reading is the safe one when
/// the payoff is choosing between two static files.
fn encoding_quality(accept_encoding: &str, encoding: &str) -> Option<u16> {
    accept_encoding.split(',').find_map(|entry| {
        let mut parts = entry.split(';');
        if !parts.next()?.trim().eq_ignore_ascii_case(encoding) {
            return None;
        }

        let quality = parts
            .find_map(|parameter| {
                let (key, value) = parameter.split_once('=')?;
                key.trim().eq_ignore_ascii_case("q").then(|| value.trim())
            })
            .and_then(|value| value.parse::<f32>().ok())
            .map(|value| (value.clamp(0.0, 1.0) * QVALUE_SCALE).round() as u16)
            .unwrap_or(DEFAULT_QVALUE);

        Some(quality)
    })
}

/// Look for a precompressed sidecar (`<path>.br` / `<path>.gz`) matching the client's
/// `Accept-Encoding`, and return its open file, metadata, and encoding name if found.
///
/// `path` must already be the fully resolved, canonicalized path `resolve()` produced.
/// The sidecar path is built by appending an extension to it — never by re-resolving a
/// modified request path — so this lookup can't become a second traversal surface: any
/// path this function reads is provably a sibling of a path `resolve()` already cleared.
/// The encodings a client will accept, best first, as `(encoding, file extension)`.
///
/// Highest `q` first; ties keep `SIDECAR_ENCODINGS` order (brotli over gzip) because the sort
/// is stable. Without this, `br;q=0.5, gzip` would serve brotli purely because it is listed
/// first here, ignoring the preference the client stated.
///
/// Extracted so that finding a sidecar on disk and finding one in the content cache share one
/// negotiation. Two copies of "which encoding does this client want" is the shape that let a
/// router and a file server disagree about `%2F`; content negotiation is no safer a place for it.
fn preferred_encodings(accept_encoding: Option<&str>) -> Vec<(&'static str, &'static str)> {
    let mut candidates: Vec<(&'static str, &'static str, u16)> = SIDECAR_ENCODINGS
        .iter()
        .filter_map(|(encoding, ext)| {
            let quality = accept_encoding.and_then(|header| encoding_quality(header, encoding))?;
            (quality > 0).then_some((*encoding, *ext, quality))
        })
        .collect();
    candidates.sort_by_key(|(_, _, quality)| std::cmp::Reverse(*quality));
    candidates
        .into_iter()
        .map(|(encoding, ext, _)| (encoding, ext))
        .collect()
}

fn select_precompressed_sidecar(
    root_canon: &Path,
    path: &Path,
    accept_encoding: Option<&str>,
) -> Option<(std::fs::File, fs::Metadata, &'static str)> {
    for (encoding, ext) in preferred_encodings(accept_encoding) {
        let mut sidecar = path.as_os_str().to_os_string();
        sidecar.push(ext);
        let sidecar_path = PathBuf::from(sidecar);

        // Containment is proven on the sidecar's **own** descriptor, by
        // `resolve::open_sidecar_verified`, and not inferred from `path` having been
        // verified. Inferring it is what this function did from 0.9.0 until the fix: the
        // constructed path sits beside an already-verified file, so the sidecar was opened
        // with a bare `File::open` and served. A symlink at that name escaped the root —
        // `GET /styles.css.br` returned 404 while `GET /styles.css` with
        // `Accept-Encoding: br` served the link's target. A `debug_assert_eq!` on parent
        // equality stood here and could not have caught it: it compared constructed paths,
        // not what the descriptor pointed at, and was compiled out of release builds
        // anyway.
        //
        // It stays an *open* rather than a cheaper `stat`: handing back an already-open,
        // already-verified file is what keeps there being no gap between probing the
        // sidecar and serving it. Browsers send `Accept-Encoding` on every request, so this
        // probe is the common path — as `tokio::fs` opens, two misses per request kept the
        // blocking pool hot for files that do not exist.
        if let Some(resolved) = resolve::open_sidecar_verified(root_canon, &sidecar_path) {
            return Some((resolved.file, resolved.metadata, encoding));
        }
    }
    None
}

/// Generate an ETag for a file based on modification time and size.
///
/// Format: `"<size>-<mtime_secs>.<mtime_nanos>"`.
///
/// The sub-second component is what makes this crate's choice to serve an ETag *instead*
/// of `Last-Modified`/`If-Modified-Since` sound. That choice rests on an ETag being able
/// to distinguish representations a whole-second timestamp cannot — two writes inside the
/// same second — which a whole-second ETag plainly cannot do either: rewriting a file
/// within a second of its last write, without changing its length, reproduced the
/// previous ETag exactly and every revalidating client was told `304 Not Modified` while
/// holding stale bytes. Build pipelines that rewrite generated assets are the realistic
/// way to hit that, and this crate ships one.
///
/// A filesystem whose timestamps are only second-granular gives `subsec_nanos() == 0`
/// and the same behavior as before — no worse, and no false confidence beyond what the
/// filesystem actually provides.
fn generate_etag(metadata: &fs::Metadata) -> String {
    let mtime = metadata
        .modified()
        .ok()
        .and_then(|t| t.duration_since(SystemTime::UNIX_EPOCH).ok())
        .unwrap_or_default();
    format!(
        "\"{}-{}.{}\"",
        metadata.len(),
        mtime.as_secs(),
        mtime.subsec_nanos()
    )
}

/// Where a response body's bytes come from.
///
/// Replaces a `(Option<Bytes>, File)` pair whose invariant — exactly one of them is the real
/// source — was carried by convention and by a `transformed.is_none()` guard on the seek. As an
/// enum the invariant is the type: there is no state where both or neither is present, and the
/// seek cannot be reached without the descriptor it seeks.
///
/// `Memory` covers an injected HTML page today and a cached file from commit 5 of
/// `PLAN-cache.md`; nothing downstream needs to know which.
enum BodySource {
    Memory(Bytes),
    Descriptor(std::fs::File),
}

/// Determine MIME type from file path extension.
fn mime_type_for_path(path: &Path) -> &'static str {
    let ext = path
        .extension()
        .and_then(|ext| ext.to_str())
        .unwrap_or_default()
        .to_lowercase();

    match ext.as_str() {
        "html" | "htm" => "text/html; charset=utf-8",
        "css" => "text/css; charset=utf-8",
        "js" => "application/javascript; charset=utf-8",
        "json" => "application/json; charset=utf-8",
        "svg" => "image/svg+xml",
        "png" => "image/png",
        "jpg" | "jpeg" => "image/jpeg",
        "gif" => "image/gif",
        "webp" => "image/webp",
        "ico" => "image/x-icon",
        "woff" => "font/woff",
        "woff2" => "font/woff2",
        "ttf" => "font/ttf",
        "md" | "markdown" => "text/markdown; charset=utf-8",
        "txt" => "text/plain; charset=utf-8",
        "xml" => "application/xml",
        "pdf" => "application/pdf",
        "zip" => "application/zip",
        _ => "application/octet-stream",
    }
}

/// Check if the If-None-Match header matches the current ETag.
/// Handles both exact match and wildcard (*) comparison per RFC 9110.
fn is_etag_match(if_none_match: &str, etag: &str) -> bool {
    if if_none_match == "*" {
        return true;
    }
    if_none_match.split(',').any(|tag| tag.trim() == etag)
}

#[derive(Debug)]
enum RangeOutcome {
    NoRange,
    Satisfiable(u64, u64),
    Unsatisfiable,
    MultiRangeIgnored,
}

enum RangeCheck {
    IgnoreRange,
    Satisfiable(u64, u64),
    Unsatisfiable,
}

fn parse_range_header(header: &str, file_size: u64) -> RangeOutcome {
    let header = header.trim();
    if !header.starts_with("bytes=") {
        return RangeOutcome::NoRange;
    }

    let range_spec = &header[6..];

    if range_spec.contains(',') {
        return RangeOutcome::MultiRangeIgnored;
    }

    if let Some(suffix_pos) = range_spec.find('-') {
        if suffix_pos == 0 {
            let suffix_len_str = &range_spec[1..];
            if let Ok(suffix_len) = suffix_len_str.parse::<u64>() {
                if suffix_len == 0 {
                    return RangeOutcome::Unsatisfiable;
                }
                if suffix_len >= file_size {
                    return RangeOutcome::Satisfiable(0, file_size - 1);
                }
                return RangeOutcome::Satisfiable(file_size - suffix_len, file_size - 1);
            }
            return RangeOutcome::Unsatisfiable;
        }

        let start_str = &range_spec[..suffix_pos];
        let end_str = &range_spec[suffix_pos + 1..];

        if let Ok(start) = start_str.parse::<u64>() {
            if start >= file_size {
                return RangeOutcome::Unsatisfiable;
            }

            if end_str.is_empty() {
                return RangeOutcome::Satisfiable(start, file_size - 1);
            }

            if let Ok(end) = end_str.parse::<u64>() {
                if end < start {
                    return RangeOutcome::Unsatisfiable;
                }
                let clamped_end = (end + 1).min(file_size) - 1;
                if start > clamped_end {
                    return RangeOutcome::Unsatisfiable;
                }
                return RangeOutcome::Satisfiable(start, clamped_end);
            }
        }
    }

    RangeOutcome::Unsatisfiable
}

fn if_range_valid(if_range_header: &str, current_etag: &str) -> bool {
    if_range_header.trim() == current_etag
}

#[cfg(test)]
mod bind_address_tests {
    use super::EPHEMERAL_BIND_IP;

    /// `run`/`run_ephemeral` must never expose the server beyond loopback.
    #[test]
    fn the_ephemeral_bind_address_is_loopback() {
        assert!(
            EPHEMERAL_BIND_IP.is_loopback(),
            "run_ephemeral would expose the server on {EPHEMERAL_BIND_IP}"
        );
    }
}

#[cfg(test)]
#[path = "../tests/unit/server/precompressed_sidecar.rs"]
mod precompressed_sidecar_tests;

#[cfg(test)]
#[path = "../tests/unit/server/file_body.rs"]
mod file_body_tests;

#[cfg(test)]
#[path = "../tests/unit/server/finish.rs"]
mod finish_tests;

#[cfg(test)]
#[path = "../tests/unit/server/etag.rs"]
mod etag_tests;

#[cfg(test)]
#[path = "../tests/unit/server/range_header.rs"]
mod range_header_tests;