mini-static 0.29.0

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
use std::convert::Infallible;
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::body::Incoming;
use hyper::header::{self, HeaderName, HeaderValue};
use hyper::http::response::Builder;
use hyper::server::conn::http1;
use hyper::service::service_fn;
use hyper::{HeaderMap, Method, Request, Response, StatusCode};
use hyper_util::rt::{TokioIo, TokioTimer};
use tokio::fs::File;
use tokio::io::{AsyncReadExt, AsyncSeekExt};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
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};

const ACCEPT_BACKOFF_INITIAL: Duration = Duration::from_millis(10);
const ACCEPT_BACKOFF_MAX: Duration = Duration::from_secs(1);

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

/// A source of accepted TCP connections. Abstracted so the accept-error backoff below
/// can be exercised against a listener that fails on demand, without needing to provoke
/// real OS-level accept errors (e.g. EMFILE) in tests.
trait TcpAccept {
    async fn accept(&self) -> std::io::Result<(TcpStream, SocketAddr)>;
}

impl TcpAccept for TcpListener {
    async fn accept(&self) -> std::io::Result<(TcpStream, SocketAddr)> {
        TcpListener::accept(self).await
    }
}

/// Accept a connection and reserve it a connection-limit permit.
///
/// `backoff` retries a failed `accept()` after an exponentially growing delay (reset on
/// the next success, capped at `ACCEPT_BACKOFF_MAX`) instead of ending the accept loop,
/// so a sustained failure — the process being out of file descriptors, say — degrades
/// into periodic retries rather than a CPU-bound busy spin or a permanently dead server.
///
/// Returns `None` only if the semaphore itself has been closed (never happens in normal
/// operation, since nothing ever calls `close()` on it — handled so a caller can still
/// fail safely rather than panic).
async fn accept_and_permit<L: TcpAccept>(
    listener: &L,
    backoff: &mut Duration,
    semaphore: &Arc<Semaphore>,
    log: Option<&Server>,
) -> Option<(TcpStream, OwnedSemaphorePermit)> {
    loop {
        let stream = match listener.accept().await {
            Ok((stream, _)) => {
                *backoff = ACCEPT_BACKOFF_INITIAL;
                stream
            }
            Err(error) => {
                // Logged rather than swallowed: sustained accept failure (out of file
                // descriptors, most often) degrades into an ever-slower retry loop that
                // is otherwise indistinguishable from an idle server.
                if let Some(server) = log {
                    server.log(format_args!(
                        "accept error: {error}; retrying in {backoff:?}"
                    ));
                }
                tokio::time::sleep(*backoff).await;
                *backoff = (*backoff * 2).min(ACCEPT_BACKOFF_MAX);
                continue;
            }
        };
        return semaphore
            .clone()
            .acquire_owned()
            .await
            .ok()
            .map(|permit| (stream, permit));
    }
}

/// 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,
    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,
            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 [`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
    }

    /// 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,
        )
    }

    /// 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.
    /// - `Err(StaticError::PipelineSetup)` if a configured [`CssTool`]/[`JsTool`]'s binary
    ///   is not found on `PATH`. Checked before the listener binds: a deployment whose
    ///   configured pipeline can never run should fail visibly at boot, not be discovered
    ///   later as a missing/stale asset.
    pub async fn run_on(
        &self,
        addr: SocketAddr,
        header_timeout: Duration,
    ) -> Result<(u16, ServerHandle), StaticError> {
        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 semaphore = Arc::new(Semaphore::new(server.max_connections));
        let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel();

        let accept_task = tokio::spawn(async move {
            let mut backoff = ACCEPT_BACKOFF_INITIAL;
            let mut join_set: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
            let mut shutdown_pin = std::pin::pin!(shutdown_rx);
            let mut shutting_down = false;

            loop {
                if !shutting_down {
                    // The accept-and-permit step and the shutdown signal race in a single
                    // `select!` so shutdown can preempt a pending accept or a permit wait
                    // cleanly, at any point — not just between loop iterations.
                    tokio::select! {
                        accepted = accept_and_permit(&listener, &mut backoff, &semaphore, Some(&server)) => {
                            match accepted {
                                Some((stream, permit)) => {
                                    let server = server.clone();
                                    join_set.spawn(async move {
                                        let _permit = permit;
                                        serve_connection(stream, server, header_timeout).await;
                                    });
                                }
                                None => shutting_down = true,
                            }
                        }
                        _ = shutdown_pin.as_mut() => {
                            shutting_down = true;
                        }
                    }
                    continue;
                }

                // Stop accepting; drain already-spawned connections before returning.
                match join_set.join_next().await {
                    Some(_) => continue,
                    None => break,
                }
            }
        });

        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(([127, 0, 0, 1], 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`). It never blocks the calling task — path resolution runs on Tokio's
    /// blocking-thread pool via `spawn_blocking`, and the file is read via async I/O.
    ///
    /// 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> {
        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()))),
                );
            }
        }

        // `resolve()` does blocking filesystem syscalls (`canonicalize()`, up to two per
        // request). Running those directly in this `async fn` would block whichever
        // Tokio worker thread happens to be driving it, stalling every other task
        // scheduled on that thread for the duration of the syscalls. `spawn_blocking`
        // moves the work onto Tokio's dedicated blocking thread pool instead.
        let server = self.clone();
        let owned_request_path = request_path.to_string();
        let resolved =
            tokio::task::spawn_blocking(move || server.resolve(&owned_request_path)).await;
        let path = match resolved {
            Err(_) => return internal_error_response(),
            Ok(Err(e)) => return self.not_found_response(e.user_message()).await,
            Ok(Ok(path)) => path,
        };

        // 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.
        let decoded_request_path = resolve::decode_request_path(request_path);
        if path.file_name().is_some_and(|name| name == "index.html")
            && !decoded_request_path.ends_with('/')
            && !decoded_request_path.ends_with("index.html")
        {
            // `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 Ok(file) = File::open(&path).await else {
            return internal_error_response();
        };
        let Ok(metadata) = file.metadata().await else {
            return internal_error_response();
        };

        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 sidecar = if html_injection || range_header.is_some() {
            None
        } else {
            select_precompressed_sidecar(&path, accept_encoding).await
        };
        let (mut file, metadata, content_encoding) = match sidecar {
            Some((sidecar_file, sidecar_metadata, encoding)) => {
                (sidecar_file, sidecar_metadata, Some(encoding))
            }
            None => (file, metadata, None),
        };

        // 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()))),
            );
        }

        // `Some` when the served representation differs from the file's raw bytes and had
        // to be built in memory; `None` means stream the open file as-is. Computed 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.
        let transformed: Option<Bytes> = if html_injection {
            let mut html = Vec::with_capacity(metadata.len() as usize);
            if file.read_to_end(&mut html).await.is_err() {
                return internal_error_response();
            }
            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);
            }
            Some(Bytes::from(html))
        } else {
            None
        };

        let file_size = transformed
            .as_ref()
            .map_or(metadata.len(), |bytes| bytes.len() as u64);

        // 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;

                // Seek to start position; if sidecar, we already skipped it above.
                if transformed.is_none()
                    && file.seek(std::io::SeekFrom::Start(*start)).await.is_err()
                {
                    return internal_error_response();
                }

                // HEAD must not return a body (RFC 9110).
                let body = if *method == Method::HEAD {
                    ResponseBody::Buffered(Full::new(Bytes::new()))
                } else {
                    match transformed {
                        Some(ref bytes) => ResponseBody::Buffered(Full::new(
                            bytes.slice(*start as usize..(*end as usize + 1)),
                        )),
                        None => ResponseBody::Streamed(FileBody::new_ranged(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 transformed {
                Some(bytes) => ResponseBody::Buffered(Full::new(bytes)),
                None => ResponseBody::Streamed(FileBody::new(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;

/// Wires an accepted connection up to the hyper HTTP/1.1 service.
///
/// HTTP/1.1 is the whole surface, deliberately. An earlier implementation used
/// `hyper_util`'s auto builder, whose `server-auto` feature transitively enables
/// `hyper/http2` — so a prior-knowledge h2c client negotiated HTTP/2 against a server
/// that documented, tested, and tuned only HTTP/1: no stream-concurrency limit, no
/// frame-size bound, and a header pre-read whose `\r\n\r\n` scan the HTTP/2 preface
/// satisfies without being an HTTP/1 request at all. Serving a protocol nobody
/// configured is worse than not serving it; browsers reach h2 over TLS only, which this
/// crate does not terminate.
///
/// `header_timeout` and `MAX_HEADER_BYTES` are enforced by hyper itself, per request.
/// They were previously enforced by a hand-rolled pre-read that ran once, before the
/// connection was handed to hyper — which meant the first request on a connection was
/// bounded and every subsequent keep-alive request on that same connection was not:
/// a client could complete one cheap request and then trickle headers forever, or send
/// an unbounded header block, with neither the timeout nor the size ceiling in play.
/// Delegating to hyper applies both bounds to every request, and deletes ~100 lines of
/// socket plumbing (`read_header_prefix`, `PrefixedIo`) whose only job was to hand the
/// already-read bytes back to hyper.
///
/// Only the *header* phase is bounded. A response body may legitimately outlive
/// `header_timeout` by design — the live-reload SSE stream stays open until a watched
/// file changes, possibly hours later — and `header_read_timeout` does not apply once a
/// request's headers are complete. The connection-count ceiling
/// (`Server::with_max_connections`) is what bounds resource use from connections held
/// open indefinitely.
///
/// `.timer(TokioTimer::new())` is load-bearing, not boilerplate: hyper resolves
/// `header_read_timeout` against an installed timer and panics with "timeout set, but no
/// timer set" if there isn't one (`hyper::common::time`). The failure is loud rather than
/// silent, but it happens per connection inside a spawned task — where a panic takes out
/// the connection, not the server — so it is the keep-alive tests, not a startup check,
/// that hold this wiring in place.
async fn serve_connection(stream: TcpStream, server: Server, header_timeout: Duration) {
    let io = TokioIo::new(stream);
    let log_server = server.clone();
    let svc = service_fn(move |req: Request<Incoming>| {
        let server = server.clone();
        async move {
            let started = Instant::now();
            let method = req.method().clone();
            let path = req.uri().path().to_string();

            let resp = server
                .handle_request(req.method(), req.uri().path(), req.headers())
                .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::<_, Infallible>(resp)
        }
    });
    if let Err(error) = http1::Builder::new()
        .timer(TokioTimer::new())
        .header_read_timeout(header_timeout)
        .max_buf_size(MAX_HEADER_BYTES)
        .serve_connection(io, svc)
        .await
    {
        log_server.log(format_args!("connection error: {error}"));
    }
}

/// 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.
async fn select_precompressed_sidecar(
    path: &Path,
    accept_encoding: Option<&str>,
) -> Option<(File, fs::Metadata, &'static str)> {
    // 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.
    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));

    for (encoding, ext, _) in candidates {
        let mut sidecar = path.as_os_str().to_os_string();
        sidecar.push(ext);
        let sidecar_path = PathBuf::from(sidecar);

        // Tripwire for the traversal boundary: a sidecar path built by appending a suffix
        // must stay in the same directory as `path` (which `resolve()` already proved is
        // inside root). `ext` is always one of the two static literals in
        // `SIDECAR_ENCODINGS`, never derived from request input, so this can only fire if
        // a future change starts deriving `sidecar` some other way.
        debug_assert_eq!(
            sidecar_path.parent(),
            path.parent(),
            "sidecar path must stay in the same directory as the already-resolved path"
        );

        if let Ok(sidecar_file) = File::open(&sidecar_path).await {
            if let Ok(sidecar_metadata) = sidecar_file.metadata().await {
                return Some((sidecar_file, sidecar_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()
    )
}

/// 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)]
#[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/accept.rs"]
mod accept_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;