hyperlane-plugin-static-files 23.0.0

A high-performance static file server plugin for the Hyperlane framework with canonicalized path-traversal protection, built-in FileExtension MIME detection, 64-way sharded hot-file cache, precompressed .br/.gz sidecars, ETag/304 conditional validation, RFC 9110 Range 206/416 support, and SPA fallback.
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
use super::*;

/// Implements [`Hasher`] for [`FxHasher`] with zero heap allocations and 8-byte word mixing.
impl Hasher for FxHasher {
    /// Finalizes the 64-bit hash state.
    ///
    /// # Returns
    ///
    /// - `u64` - Finalized 64-bit hash.
    #[inline(always)]
    fn finish(&self) -> u64 {
        let Self { state } = *self;
        state
    }

    /// Mixes `bytes` into the hash state 8 bytes at a time without heap allocation.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - Input byte slice.
    #[inline(always)]
    fn write(&mut self, bytes: &[u8]) {
        let Self { state } = self;
        let mut h: u64 = *state;
        let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
        for chunk in chunks {
            h = (h.rotate_left(5) ^ u64::from_ne_bytes(*chunk)).wrapping_mul(FX_HASH_K);
        }
        let mut tail: &[u8] = rem;
        if tail.len() >= 4 {
            let word: u32 = u32::from_ne_bytes([tail[0], tail[1], tail[2], tail[3]]);
            h = (h.rotate_left(5) ^ u64::from(word)).wrapping_mul(FX_HASH_K);
            tail = &tail[4..];
        }
        if tail.len() >= 2 {
            let half: u16 = u16::from_ne_bytes([tail[0], tail[1]]);
            h = (h.rotate_left(5) ^ u64::from(half)).wrapping_mul(FX_HASH_K);
            tail = &tail[2..];
        }
        if let Some(&b) = tail.first() {
            h = (h.rotate_left(5) ^ u64::from(b)).wrapping_mul(FX_HASH_K);
        }
        *state = h;
    }

    /// Mixes a single `u8` byte directly into the hash state.
    ///
    /// # Arguments
    ///
    /// - `u8` - Input byte.
    #[inline(always)]
    fn write_u8(&mut self, i: u8) {
        let Self { state } = self;
        *state = (state.rotate_left(5) ^ u64::from(i)).wrapping_mul(FX_HASH_K);
    }
}

/// Prebuilt HTTP/1.1 wire buffer helpers for [`CachedFile`].
impl CachedFile {
    /// Builds a complete serialized HTTP/1.1 wire buffer for this cached file with `status` and `include_body`.
    ///
    /// # Arguments
    ///
    /// - `HttpStatus` - Response HTTP status (`Ok` or `NotModified`).
    /// - `&str` - Configured `Cache-Control` header value.
    /// - `bool` - Whether to include file body bytes.
    ///
    /// # Returns
    ///
    /// - `Arc<[u8]>` - Immutable serialized HTTP/1.1 wire bytes.
    fn build_wire(&self, status: HttpStatus, cache_control: &str, include_body: bool) -> Arc<[u8]> {
        let Self {
            bytes,
            etag,
            content_type,
            content_encoding,
            ..
        } = self;
        let mut resp: Response = Response::default();
        resp.set_status_code(status.code())
            .set_header(CONTENT_TYPE, *content_type)
            .set_header(ETAG, etag)
            .set_header(ACCEPT_RANGES, ACCEPT_RANGES_BYTES);
        if !cache_control.is_empty() {
            resp.set_header(CACHE_CONTROL, cache_control);
        }
        if let Some(enc) = *content_encoding {
            resp.set_header(CONTENT_ENCODING, enc)
                .set_header(VARY, VARY_ACCEPT_ENCODING);
        }
        if include_body {
            resp.set_body(bytes.as_ref());
        }
        let wire: Vec<u8> = resp.build();
        Arc::from(wire.into_boxed_slice())
    }

    /// Returns the lazily built zero-copy HTTP/1.1 `200 OK` wire response for `GET`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Configured `Cache-Control` header value.
    ///
    /// # Returns
    ///
    /// - `&[u8]` - Prebuilt HTTP/1.1 wire response bytes.
    #[inline]
    pub(crate) fn get_wire_ok(&self, cache_control: &str) -> &[u8] {
        let Self { wire_ok, .. } = self;
        wire_ok
            .get_or_init(|| self.build_wire(HttpStatus::Ok, cache_control, true))
            .as_ref()
    }

    /// Returns the lazily built zero-copy HTTP/1.1 `200 OK` wire response for `HEAD`.
    ///
    /// # Arguments
    ///
    /// - `&str` - Configured `Cache-Control` header value.
    ///
    /// # Returns
    ///
    /// - `&[u8]` - Prebuilt HTTP/1.1 wire response bytes.
    #[inline]
    pub(crate) fn get_wire_head(&self, cache_control: &str) -> &[u8] {
        let Self { wire_head, .. } = self;
        wire_head
            .get_or_init(|| self.build_wire(HttpStatus::Ok, cache_control, false))
            .as_ref()
    }

    /// Returns the lazily built zero-copy HTTP/1.1 `304 Not Modified` wire response.
    ///
    /// # Arguments
    ///
    /// - `&str` - Configured `Cache-Control` header value.
    ///
    /// # Returns
    ///
    /// - `&[u8]` - Prebuilt HTTP/1.1 wire response bytes.
    #[inline]
    pub(crate) fn get_wire_304(&self, cache_control: &str) -> &[u8] {
        let Self { wire_304, .. } = self;
        wire_304
            .get_or_init(|| self.build_wire(HttpStatus::NotModified, cache_control, false))
            .as_ref()
    }
}

/// Inherent constructors and builders for [`StaticFilesConfig`].
impl StaticFilesConfig {
    /// Creates a [`StaticFilesConfig`] serving files from `root_dir` mounted at `"/"`.
    ///
    /// # Arguments
    ///
    /// - `P` - Root directory path convertible into `PathBuf`.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed static files configuration.
    pub fn new<P>(root_dir: P) -> Self
    where
        P: Into<PathBuf>,
    {
        Self {
            root_dir: root_dir.into(),
            mount_prefix: DEFAULT_STATIC_MOUNT_PREFIX.to_owned(),
            index_file: DEFAULT_STATIC_INDEX_FILE.to_owned(),
            spa_fallback: None,
            cache_control: DEFAULT_STATIC_CACHE_CONTROL.to_owned(),
            serve_precompressed: true,
            allow_dotfiles: false,
            max_cache_bytes: DEFAULT_STATIC_MAX_CACHE_BYTES,
            max_file_cache_bytes: DEFAULT_STATIC_MAX_FILE_CACHE_BYTES,
        }
    }

    /// Sets the URL mount prefix (for example `"/assets"`).
    ///
    /// # Arguments
    ///
    /// - `P` - Mount prefix convertible into `String`.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_mount_prefix<P>(mut self, prefix: P) -> Self
    where
        P: Into<String>,
    {
        self.set_mount_prefix(prefix.into());
        self
    }

    /// Sets an SPA fallback file relative to `root_dir` (for example `"index.html"`).
    ///
    /// # Arguments
    ///
    /// - `F` - Fallback filename convertible into `String`.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_spa_fallback<F>(mut self, fallback: F) -> Self
    where
        F: Into<String>,
    {
        self.set_spa_fallback(Some(fallback.into()));
        self
    }

    /// Sets the `Cache-Control` response header value.
    ///
    /// # Arguments
    ///
    /// - `C` - Header value convertible into `String`.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_cache_control<C>(mut self, cache_control: C) -> Self
    where
        C: Into<String>,
    {
        self.set_cache_control(cache_control.into());
        self
    }

    /// Enables or disables `.br`/`.gz` precompressed sidecar negotiation.
    ///
    /// # Arguments
    ///
    /// - `bool` - Whether precompressed sidecars are checked.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_serve_precompressed(mut self, enabled: bool) -> Self {
        self.set_serve_precompressed(enabled);
        self
    }
}

/// Inherent implementation of [`StaticFilesRuntime`].
impl StaticFilesRuntime {
    /// Compiles a [`StaticFilesRuntime`] by canonicalizing `config.root_dir`.
    ///
    /// # Arguments
    ///
    /// - `StaticFilesConfig` - Static file server configuration.
    ///
    /// # Returns
    ///
    /// - `Result<Self, String>` - Ready runtime or canonicalization error message.
    pub fn new(config: StaticFilesConfig) -> Result<Self, String> {
        let canonical_root: PathBuf =
            canonicalize(config.get_root_dir()).map_err(|err: io::Error| err.to_string())?;
        let trimmed: &str = config.get_mount_prefix().trim();
        let normalized_prefix: String = if trimmed.is_empty() || trimmed == "/" {
            "/".to_owned()
        } else if trimmed.starts_with('/') {
            trimmed.trim_end_matches('/').to_owned()
        } else {
            format!("/{}", trimmed.trim_end_matches('/'))
        };
        let cache_shards: Box<[StaticCacheShard; STATIC_CACHE_SHARDS]> =
            Box::new(from_fn(|_: usize| StaticCacheShard {
                map: RwLock::new(HashMap::default()),
            }));
        Ok(Self {
            inner: Arc::new(StaticFilesRuntimeInner {
                config,
                canonical_root,
                normalized_prefix,
                cached_bytes: AtomicUsize::new(0),
                cache_shards,
            }),
        })
    }

    /// Returns the active [`StaticFilesConfig`].
    ///
    /// # Returns
    ///
    /// - `&StaticFilesConfig` - Active configuration.
    pub fn get_config(&self) -> &StaticFilesConfig {
        let Self { inner } = self;
        &inner.config
    }

    /// Returns current in-memory hot-file cache usage in bytes.
    ///
    /// # Returns
    ///
    /// - `usize` - Cached bytes across all 64 shards.
    pub fn cached_bytes(&self) -> usize {
        let Self { inner } = self;
        inner.cached_bytes.load(Ordering::Relaxed)
    }

    /// Strips the configured mount prefix on a path-segment boundary.
    ///
    /// # Arguments
    ///
    /// - `&'a str` - Incoming request path.
    ///
    /// # Returns
    ///
    /// - `Option<&'a str>` - Relative sub-path when matched, or `None`.
    pub(crate) fn strip_mount<'a>(&self, path: &'a str) -> Option<&'a str> {
        let Self { inner } = self;
        if inner.normalized_prefix == "/" {
            return Some(path);
        }
        let rest: &'a str = path.strip_prefix(inner.normalized_prefix.as_str())?;
        if rest.is_empty() || rest.starts_with('/') {
            Some(rest)
        } else {
            None
        }
    }

    /// Selects the best representation from a cached route entry for `enc_mask`.
    ///
    /// # Arguments
    ///
    /// - `&CachedRouteEntry` - Cached asset variants.
    /// - `u8` - Client `Accept-Encoding` sidecar bitmask.
    ///
    /// # Returns
    ///
    /// - `Arc<CachedFile>` - Selected representation (`br` > `gzip` > `raw`).
    #[inline]
    fn select_cached_variant(entry: &CachedRouteEntry, enc_mask: u8) -> Arc<CachedFile> {
        if (enc_mask & ENCODING_MASK_BR) != 0
            && let Some(br_file) = &entry.br
        {
            return Arc::clone(br_file);
        }
        if (enc_mask & ENCODING_MASK_GZIP) != 0
            && let Some(gz_file) = &entry.gz
        {
            return Arc::clone(gz_file);
        }
        Arc::clone(&entry.raw)
    }

    /// Reads one verified canonical file from disk into an immutable [`CachedFile`].
    ///
    /// # Arguments
    ///
    /// - `&Path` - Canonical file path verified inside `canonical_root`.
    /// - `&'static str` - Resolved MIME content type.
    /// - `Option<&'static str>` - Optional sidecar `Content-Encoding`.
    ///
    /// # Returns
    ///
    /// - `Option<Arc<CachedFile>>` - Loaded file payload, or `None` on I/O failure.
    async fn read_disk_file(
        disk_path: &Path,
        content_type: &'static str,
        content_encoding: Option<&'static str>,
    ) -> Option<Arc<CachedFile>> {
        let meta: Metadata = fs::metadata(disk_path).await.ok()?;
        if !meta.is_file() {
            return None;
        }
        let modified_ms: u64 = metadata_modified_ms(&meta);
        let raw_bytes: Vec<u8> = fs::read(disk_path).await.ok()?;
        let etag: String = compute_file_etag(raw_bytes.len() as u64, modified_ms);
        Some(Arc::new(CachedFile {
            bytes: Arc::from(raw_bytes),
            etag,
            content_type,
            content_encoding,
            wire_ok: OnceLock::new(),
            wire_head: OnceLock::new(),
            wire_304: OnceLock::new(),
        }))
    }

    /// Probes an optional `.br` or `.gz` sidecar next to `canonical_base`, verifying containment within `canonical_root`.
    ///
    /// # Arguments
    ///
    /// - `&Path` - Canonical uncompressed file path.
    /// - `&str` - Sidecar extension (`".br"` or `".gz"`).
    /// - `&'static str` - Resolved base MIME content type.
    /// - `&'static str` - Corresponding `Content-Encoding` token.
    ///
    /// # Returns
    ///
    /// - `Option<Arc<CachedFile>>` - Loaded sidecar representation if present and safe.
    async fn load_sidecar(
        &self,
        canonical_base: &Path,
        ext: &str,
        mime: &'static str,
        encoding: &'static str,
    ) -> Option<Arc<CachedFile>> {
        let Self { inner } = self;
        let mut sidecar_os: OsString = canonical_base.as_os_str().to_os_string();
        sidecar_os.push(ext);
        let sidecar_path: PathBuf = PathBuf::from(sidecar_os);
        let canon_sidecar: PathBuf = fs::canonicalize(&sidecar_path).await.ok()?;
        if !canon_sidecar.starts_with(&inner.canonical_root) {
            return None;
        }
        Self::read_disk_file(&canon_sidecar, mime, Some(encoding)).await
    }

    /// Resolves and loads a static asset on cache miss, populating the 64-shard hot cache when within budget.
    ///
    /// # Arguments
    ///
    /// - `&str` - Validated normalized relative URL path.
    /// - `usize` - Precomputed shard index for `cache_key`.
    /// - `u8` - Client `Accept-Encoding` sidecar bitmask.
    ///
    /// # Returns
    ///
    /// - `Option<Arc<CachedFile>>` - Resolved file representation, or `None` when not found/disallowed.
    async fn resolve_and_cache_miss(
        &self,
        cache_key: &str,
        shard_idx: usize,
        enc_mask: u8,
    ) -> Option<Arc<CachedFile>> {
        let Self { inner } = self;
        let candidate: PathBuf = resolve_safe_path(
            &inner.canonical_root,
            cache_key,
            inner.config.get_allow_dotfiles(),
        )?;
        let resolved_base: PathBuf = match fs::metadata(&candidate).await {
            Ok(meta) if meta.is_dir() => candidate.join(inner.config.get_index_file()),
            Ok(meta) if meta.is_file() => candidate,
            _ => match inner.config.get_spa_fallback() {
                Some(fallback) => inner.canonical_root.join(fallback),
                None => return None,
            },
        };
        let canonical_base: PathBuf = fs::canonicalize(&resolved_base).await.ok()?;
        if !canonical_base.starts_with(&inner.canonical_root) {
            return None;
        }
        let mime: &'static str = mime_for_path(&canonical_base);
        let max_cache: usize = inner.config.get_max_cache_bytes();
        let max_file_cache: usize = inner.config.get_max_file_cache_bytes();
        let serve_precompressed: bool = inner.config.get_serve_precompressed();
        if max_cache == 0 {
            if serve_precompressed
                && (enc_mask & ENCODING_MASK_BR) != 0
                && let Some(br_file) = self
                    .load_sidecar(&canonical_base, SIDECAR_BR_EXT, mime, ENCODING_BR)
                    .await
            {
                return Some(br_file);
            }
            if serve_precompressed
                && (enc_mask & ENCODING_MASK_GZIP) != 0
                && let Some(gz_file) = self
                    .load_sidecar(&canonical_base, SIDECAR_GZ_EXT, mime, ENCODING_GZIP)
                    .await
            {
                return Some(gz_file);
            }
            return Self::read_disk_file(&canonical_base, mime, None).await;
        }
        let raw_file: Arc<CachedFile> = Self::read_disk_file(&canonical_base, mime, None).await?;
        let br_file: Option<Arc<CachedFile>> = if serve_precompressed {
            self.load_sidecar(&canonical_base, SIDECAR_BR_EXT, mime, ENCODING_BR)
                .await
        } else {
            None
        };
        let gz_file: Option<Arc<CachedFile>> = if serve_precompressed {
            self.load_sidecar(&canonical_base, SIDECAR_GZ_EXT, mime, ENCODING_GZIP)
                .await
        } else {
            None
        };
        let entry: Arc<CachedRouteEntry> = Arc::new(CachedRouteEntry {
            raw: raw_file,
            br: br_file,
            gz: gz_file,
        });
        let entry_bytes: usize = entry.raw.bytes.len()
            + entry
                .br
                .as_ref()
                .map_or(0, |f: &Arc<CachedFile>| f.bytes.len())
            + entry
                .gz
                .as_ref()
                .map_or(0, |f: &Arc<CachedFile>| f.bytes.len());
        if entry.raw.bytes.len() <= max_file_cache
            && inner.cached_bytes.load(Ordering::Relaxed) + entry_bytes <= max_cache
            && let Ok(mut guard) = inner.cache_shards[shard_idx].map.write()
        {
            if let Some(prev) = guard.insert(cache_key.to_owned(), Arc::clone(&entry)) {
                let prev_bytes: usize = prev.raw.bytes.len()
                    + prev
                        .br
                        .as_ref()
                        .map_or(0, |f: &Arc<CachedFile>| f.bytes.len())
                    + prev
                        .gz
                        .as_ref()
                        .map_or(0, |f: &Arc<CachedFile>| f.bytes.len());
                inner.cached_bytes.fetch_sub(prev_bytes, Ordering::Relaxed);
            }
            inner.cached_bytes.fetch_add(entry_bytes, Ordering::Relaxed);
        }
        Some(Self::select_cached_variant(&entry, enc_mask))
    }

    /// Resolves a matching [`CachedFile`] and `HEAD` flag for the incoming request context.
    ///
    /// # Arguments
    ///
    /// - `&Context` - Active Hyperlane request context.
    ///
    /// # Returns
    ///
    /// - `Option<(Arc<CachedFile>, bool)>` - Resolved file and `is_head` flag, or `None` if unmatched.
    #[inline]
    async fn resolve_file_for_context(&self, ctx: &Context) -> Option<(Arc<CachedFile>, bool)> {
        let Self { inner } = self;
        let request: &Request = ctx.get_request();
        let is_get: bool = request.get_method().is_get();
        let is_head: bool = !is_get && request.get_method().is_head();
        if !is_get && !is_head {
            return None;
        }
        let relative_url: &str = self.strip_mount(request.get_path())?;
        let safe_rel: Cow<'_, str> =
            validate_and_decode_relative(relative_url, inner.config.get_allow_dotfiles())?;
        let cache_key: &str = safe_rel.as_ref();
        let enc_mask: u8 = if inner.config.get_serve_precompressed() {
            get_request_header_back_ref(request, ACCEPT_ENCODING).map_or(0, accept_encoding_mask)
        } else {
            0
        };
        let shard_idx: usize = static_cache_shard_index(cache_key);
        let cached_hit: Option<Arc<CachedFile>> = if inner.config.get_max_cache_bytes() > 0 {
            inner.cache_shards[shard_idx].map.read().ok().and_then(
                |guard: RwLockReadGuard<'_, StaticCacheShardMap>| {
                    guard.get(cache_key).map(|entry: &Arc<CachedRouteEntry>| {
                        Self::select_cached_variant(entry, enc_mask)
                    })
                },
            )
        } else {
            None
        };
        let file: Arc<CachedFile> = if let Some(hit) = cached_hit {
            hit
        } else {
            self.resolve_and_cache_miss(cache_key, shard_idx, enc_mask)
                .await?
        };
        Some((file, is_head))
    }

    /// Populates `ctx`'s outgoing response with status, headers, and body for `file`.
    ///
    /// # Arguments
    ///
    /// - `&mut Context` - Active Hyperlane request/response context.
    /// - `&CachedFile` - Resolved static file representation.
    /// - `bool` - Whether the request method is `HEAD`.
    #[inline]
    fn populate_response(&self, ctx: &mut Context, file: &CachedFile, is_head: bool) {
        let Self { inner } = self;
        let is_not_modified: bool = get_request_header_back_ref(ctx.get_request(), IF_NONE_MATCH)
            .is_some_and(|inm: &str| if_none_match_matches(inm, &file.etag));
        let total: usize = file.bytes.len();
        let range_eval: Option<Option<(usize, usize)>> = if is_not_modified {
            None
        } else {
            get_request_header_back_ref(ctx.get_request(), RANGE)
                .map(|range_val: &str| parse_byte_range(range_val, total))
        };
        let cache_control: &str = inner.config.get_cache_control();
        let response: &mut Response = ctx.get_mut_response();
        response
            .set_header(CONTENT_TYPE, file.content_type)
            .set_header(ETAG, &file.etag)
            .set_header(ACCEPT_RANGES, ACCEPT_RANGES_BYTES);
        if !cache_control.is_empty() {
            response.set_header(CACHE_CONTROL, cache_control);
        }
        if let Some(enc) = file.content_encoding {
            response
                .set_header(CONTENT_ENCODING, enc)
                .set_header(VARY, VARY_ACCEPT_ENCODING);
        }
        if is_not_modified {
            response.set_status_code(HttpStatus::NotModified.code());
            response.get_mut_body().clear();
            return;
        }
        if let Some(parsed_range) = range_eval {
            let mut cr_buf: [u8; CONTENT_RANGE_STACK_CAP] = [0u8; CONTENT_RANGE_STACK_CAP];
            match parsed_range {
                Some((start, end)) => {
                    let cr_str: &str = format_content_range_stack(start, end, total, &mut cr_buf);
                    response
                        .set_status_code(HttpStatus::PartialContent.code())
                        .set_header(CONTENT_RANGE, cr_str);
                    let body_buf: &mut Vec<u8> = response.get_mut_body();
                    body_buf.clear();
                    if !is_head {
                        body_buf.extend_from_slice(&file.bytes[start..=end]);
                    }
                }
                None => {
                    let cr_str: &str = format_unsatisfiable_range_stack(total, &mut cr_buf);
                    response
                        .set_status_code(HttpStatus::RangeNotSatisfiable.code())
                        .set_header(CONTENT_RANGE, cr_str);
                    response.get_mut_body().clear();
                }
            }
            return;
        }
        response.set_status_code(HttpStatus::Ok.code());
        let body_buf: &mut Vec<u8> = response.get_mut_body();
        body_buf.clear();
        if !is_head {
            body_buf.extend_from_slice(file.bytes.as_ref());
        }
    }

    /// Attempts to serve a static asset for `ctx`, populating status, headers, and body.
    ///
    /// # Arguments
    ///
    /// - `&mut Context` - Incoming request and outgoing response context.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when a static file (or `304`/`206`/`416`) was served; `false` otherwise.
    pub async fn serve_context(&self, ctx: &mut Context) -> bool {
        let Some((file, is_head)) = self.resolve_file_for_context(ctx).await else {
            return false;
        };
        self.populate_response(ctx, &file, is_head);
        true
    }

    /// Serves a matching static asset directly to `stream` using zero-copy prebuilt HTTP/1.1 wire buffers when eligible.
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Active client connection stream.
    /// - `&mut Context` - Incoming request and outgoing response context.
    ///
    /// # Returns
    ///
    /// - `Status` - `Status::Reject` once a static asset was served; `Status::Continue` otherwise.
    #[inline]
    pub(crate) async fn serve_and_send_hook(
        &self,
        stream: &mut Stream,
        ctx: &mut Context,
    ) -> Status {
        let Self { inner } = self;
        let Some((file, is_head)) = self.resolve_file_for_context(ctx).await else {
            return Status::Continue;
        };
        let resp: &Response = ctx.get_response();
        let can_fast_wire: bool = ctx.get_request().get_version().is_http1_1()
            && resp.get_version().is_http1_1()
            && resp.get_headers().is_empty()
            && (resp.get_reason_phrase().is_empty() || resp.get_reason_phrase().as_str() == OK);
        if can_fast_wire {
            let cache_control: &str = inner.config.get_cache_control();
            let is_not_modified: bool =
                get_request_header_back_ref(ctx.get_request(), IF_NONE_MATCH)
                    .is_some_and(|inm: &str| if_none_match_matches(inm, &file.etag));
            if is_not_modified {
                let wire: &[u8] = file.get_wire_304(cache_control);
                let _: Result<(), ResponseError> = stream.try_send(wire).await;
                return Status::Reject;
            }
            if get_request_header_back_ref(ctx.get_request(), RANGE).is_none() {
                let wire: &[u8] = if is_head {
                    file.get_wire_head(cache_control)
                } else {
                    file.get_wire_ok(cache_control)
                };
                let _: Result<(), ResponseError> = stream.try_send(wire).await;
                return Status::Reject;
            }
        }
        self.populate_response(ctx, &file, is_head);
        let wire: Vec<u8> = ctx.get_mut_response().build();
        let _: Result<(), ResponseError> = stream.try_send(&wire).await;
        Status::Reject
    }
}

/// Inherent implementation of [`StaticFilesPlugin`].
impl StaticFilesPlugin {
    /// Initializes the global [`StaticFilesPlugin`] once from `config`.
    ///
    /// # Arguments
    ///
    /// - `StaticFilesConfig` - Static file server configuration.
    ///
    /// # Returns
    ///
    /// - `Result<&'static Self, String>` - Global plugin reference or canonicalization error.
    pub fn init(config: StaticFilesConfig) -> Result<&'static Self, String> {
        let runtime: StaticFilesRuntime = StaticFilesRuntime::new(config)?;
        Ok(STATIC_FILES_PLUGIN.get_or_init(|| Self { runtime }))
    }

    /// Returns the initialized global [`StaticFilesPlugin`], if initialized.
    ///
    /// # Returns
    ///
    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
    pub fn get() -> Option<&'static Self> {
        STATIC_FILES_PLUGIN.get()
    }

    /// Returns the active [`StaticFilesRuntime`].
    ///
    /// # Returns
    ///
    /// - `&StaticFilesRuntime` - Active static file runtime.
    pub fn get_runtime(&self) -> &StaticFilesRuntime {
        let Self { runtime } = self;
        runtime
    }
}

/// Implements [`ServerHook`] for [`StaticFilesHook`].
impl ServerHook for StaticFilesHook {
    /// Constructs a per-request [`StaticFilesHook`].
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Self` - Hook instance.
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Serves matching static files and short-circuits the pipeline once answered.
    ///
    /// # Arguments
    ///
    /// - `Self` - Hook instance.
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Status` - `Status::Reject` once a static asset was served; `Status::Continue` otherwise.
    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
        let Some(plugin) = StaticFilesPlugin::get() else {
            return Status::Continue;
        };
        plugin.get_runtime().serve_and_send_hook(stream, ctx).await
    }
}