Skip to main content

hyperlane_plugin_static_files/
impl.rs

1use super::*;
2
3/// Implements [`Hasher`] for [`FxHasher`] with zero heap allocations and 8-byte word mixing.
4impl Hasher for FxHasher {
5    /// Finalizes the 64-bit hash state.
6    ///
7    /// # Returns
8    ///
9    /// - `u64` - Finalized 64-bit hash.
10    #[inline(always)]
11    fn finish(&self) -> u64 {
12        let Self { state } = *self;
13        state
14    }
15
16    /// Mixes `bytes` into the hash state 8 bytes at a time without heap allocation.
17    ///
18    /// # Arguments
19    ///
20    /// - `&[u8]` - Input byte slice.
21    #[inline(always)]
22    fn write(&mut self, bytes: &[u8]) {
23        let Self { state } = self;
24        let mut h: u64 = *state;
25        let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
26        for chunk in chunks {
27            h = (h.rotate_left(5) ^ u64::from_ne_bytes(*chunk)).wrapping_mul(FX_HASH_K);
28        }
29        let mut tail: &[u8] = rem;
30        if tail.len() >= 4 {
31            let word: u32 = u32::from_ne_bytes([tail[0], tail[1], tail[2], tail[3]]);
32            h = (h.rotate_left(5) ^ u64::from(word)).wrapping_mul(FX_HASH_K);
33            tail = &tail[4..];
34        }
35        if tail.len() >= 2 {
36            let half: u16 = u16::from_ne_bytes([tail[0], tail[1]]);
37            h = (h.rotate_left(5) ^ u64::from(half)).wrapping_mul(FX_HASH_K);
38            tail = &tail[2..];
39        }
40        if let Some(&b) = tail.first() {
41            h = (h.rotate_left(5) ^ u64::from(b)).wrapping_mul(FX_HASH_K);
42        }
43        *state = h;
44    }
45
46    /// Mixes a single `u8` byte directly into the hash state.
47    ///
48    /// # Arguments
49    ///
50    /// - `u8` - Input byte.
51    #[inline(always)]
52    fn write_u8(&mut self, i: u8) {
53        let Self { state } = self;
54        *state = (state.rotate_left(5) ^ u64::from(i)).wrapping_mul(FX_HASH_K);
55    }
56}
57
58/// Prebuilt HTTP/1.1 wire buffer helpers for [`CachedFile`].
59impl CachedFile {
60    /// Builds a complete serialized HTTP/1.1 wire buffer for this cached file with `status` and `include_body`.
61    ///
62    /// # Arguments
63    ///
64    /// - `HttpStatus` - Response HTTP status (`Ok` or `NotModified`).
65    /// - `&str` - Configured `Cache-Control` header value.
66    /// - `bool` - Whether to include file body bytes.
67    ///
68    /// # Returns
69    ///
70    /// - `Arc<[u8]>` - Immutable serialized HTTP/1.1 wire bytes.
71    fn build_wire(&self, status: HttpStatus, cache_control: &str, include_body: bool) -> Arc<[u8]> {
72        let Self {
73            bytes,
74            etag,
75            content_type,
76            content_encoding,
77            ..
78        } = self;
79        let mut resp: Response = Response::default();
80        resp.set_status_code(status.code())
81            .set_header(CONTENT_TYPE, *content_type)
82            .set_header(ETAG, etag)
83            .set_header(ACCEPT_RANGES, ACCEPT_RANGES_BYTES);
84        if !cache_control.is_empty() {
85            resp.set_header(CACHE_CONTROL, cache_control);
86        }
87        if let Some(enc) = *content_encoding {
88            resp.set_header(CONTENT_ENCODING, enc)
89                .set_header(VARY, VARY_ACCEPT_ENCODING);
90        }
91        if include_body {
92            resp.set_body(bytes.as_ref());
93        }
94        let wire: Vec<u8> = resp.build();
95        Arc::from(wire.into_boxed_slice())
96    }
97
98    /// Returns the lazily built zero-copy HTTP/1.1 `200 OK` wire response for `GET`.
99    ///
100    /// # Arguments
101    ///
102    /// - `&str` - Configured `Cache-Control` header value.
103    ///
104    /// # Returns
105    ///
106    /// - `&[u8]` - Prebuilt HTTP/1.1 wire response bytes.
107    #[inline]
108    pub(crate) fn get_wire_ok(&self, cache_control: &str) -> &[u8] {
109        let Self { wire_ok, .. } = self;
110        wire_ok
111            .get_or_init(|| self.build_wire(HttpStatus::Ok, cache_control, true))
112            .as_ref()
113    }
114
115    /// Returns the lazily built zero-copy HTTP/1.1 `200 OK` wire response for `HEAD`.
116    ///
117    /// # Arguments
118    ///
119    /// - `&str` - Configured `Cache-Control` header value.
120    ///
121    /// # Returns
122    ///
123    /// - `&[u8]` - Prebuilt HTTP/1.1 wire response bytes.
124    #[inline]
125    pub(crate) fn get_wire_head(&self, cache_control: &str) -> &[u8] {
126        let Self { wire_head, .. } = self;
127        wire_head
128            .get_or_init(|| self.build_wire(HttpStatus::Ok, cache_control, false))
129            .as_ref()
130    }
131
132    /// Returns the lazily built zero-copy HTTP/1.1 `304 Not Modified` wire response.
133    ///
134    /// # Arguments
135    ///
136    /// - `&str` - Configured `Cache-Control` header value.
137    ///
138    /// # Returns
139    ///
140    /// - `&[u8]` - Prebuilt HTTP/1.1 wire response bytes.
141    #[inline]
142    pub(crate) fn get_wire_304(&self, cache_control: &str) -> &[u8] {
143        let Self { wire_304, .. } = self;
144        wire_304
145            .get_or_init(|| self.build_wire(HttpStatus::NotModified, cache_control, false))
146            .as_ref()
147    }
148}
149
150/// Inherent constructors and builders for [`StaticFilesConfig`].
151impl StaticFilesConfig {
152    /// Creates a [`StaticFilesConfig`] serving files from `root_dir` mounted at `"/"`.
153    ///
154    /// # Arguments
155    ///
156    /// - `P` - Root directory path convertible into `PathBuf`.
157    ///
158    /// # Returns
159    ///
160    /// - `Self` - Constructed static files configuration.
161    pub fn new<P>(root_dir: P) -> Self
162    where
163        P: Into<PathBuf>,
164    {
165        Self {
166            root_dir: root_dir.into(),
167            mount_prefix: DEFAULT_STATIC_MOUNT_PREFIX.to_owned(),
168            index_file: DEFAULT_STATIC_INDEX_FILE.to_owned(),
169            spa_fallback: None,
170            cache_control: DEFAULT_STATIC_CACHE_CONTROL.to_owned(),
171            serve_precompressed: true,
172            allow_dotfiles: false,
173            max_cache_bytes: DEFAULT_STATIC_MAX_CACHE_BYTES,
174            max_file_cache_bytes: DEFAULT_STATIC_MAX_FILE_CACHE_BYTES,
175        }
176    }
177
178    /// Sets the URL mount prefix (for example `"/assets"`).
179    ///
180    /// # Arguments
181    ///
182    /// - `P` - Mount prefix convertible into `String`.
183    ///
184    /// # Returns
185    ///
186    /// - `Self` - Updated configuration.
187    pub fn with_mount_prefix<P>(mut self, prefix: P) -> Self
188    where
189        P: Into<String>,
190    {
191        self.set_mount_prefix(prefix.into());
192        self
193    }
194
195    /// Sets an SPA fallback file relative to `root_dir` (for example `"index.html"`).
196    ///
197    /// # Arguments
198    ///
199    /// - `F` - Fallback filename convertible into `String`.
200    ///
201    /// # Returns
202    ///
203    /// - `Self` - Updated configuration.
204    pub fn with_spa_fallback<F>(mut self, fallback: F) -> Self
205    where
206        F: Into<String>,
207    {
208        self.set_spa_fallback(Some(fallback.into()));
209        self
210    }
211
212    /// Sets the `Cache-Control` response header value.
213    ///
214    /// # Arguments
215    ///
216    /// - `C` - Header value convertible into `String`.
217    ///
218    /// # Returns
219    ///
220    /// - `Self` - Updated configuration.
221    pub fn with_cache_control<C>(mut self, cache_control: C) -> Self
222    where
223        C: Into<String>,
224    {
225        self.set_cache_control(cache_control.into());
226        self
227    }
228
229    /// Enables or disables `.br`/`.gz` precompressed sidecar negotiation.
230    ///
231    /// # Arguments
232    ///
233    /// - `bool` - Whether precompressed sidecars are checked.
234    ///
235    /// # Returns
236    ///
237    /// - `Self` - Updated configuration.
238    pub fn with_serve_precompressed(mut self, enabled: bool) -> Self {
239        self.set_serve_precompressed(enabled);
240        self
241    }
242}
243
244/// Inherent implementation of [`StaticFilesRuntime`].
245impl StaticFilesRuntime {
246    /// Compiles a [`StaticFilesRuntime`] by canonicalizing `config.root_dir`.
247    ///
248    /// # Arguments
249    ///
250    /// - `StaticFilesConfig` - Static file server configuration.
251    ///
252    /// # Returns
253    ///
254    /// - `Result<Self, String>` - Ready runtime or canonicalization error message.
255    pub fn new(config: StaticFilesConfig) -> Result<Self, String> {
256        let canonical_root: PathBuf =
257            canonicalize(config.get_root_dir()).map_err(|err: io::Error| err.to_string())?;
258        let trimmed: &str = config.get_mount_prefix().trim();
259        let normalized_prefix: String = if trimmed.is_empty() || trimmed == "/" {
260            "/".to_owned()
261        } else if trimmed.starts_with('/') {
262            trimmed.trim_end_matches('/').to_owned()
263        } else {
264            format!("/{}", trimmed.trim_end_matches('/'))
265        };
266        let cache_shards: Box<[StaticCacheShard; STATIC_CACHE_SHARDS]> =
267            Box::new(from_fn(|_: usize| StaticCacheShard {
268                map: RwLock::new(HashMap::default()),
269            }));
270        Ok(Self {
271            inner: Arc::new(StaticFilesRuntimeInner {
272                config,
273                canonical_root,
274                normalized_prefix,
275                cached_bytes: AtomicUsize::new(0),
276                cache_shards,
277            }),
278        })
279    }
280
281    /// Returns the active [`StaticFilesConfig`].
282    ///
283    /// # Returns
284    ///
285    /// - `&StaticFilesConfig` - Active configuration.
286    pub fn get_config(&self) -> &StaticFilesConfig {
287        let Self { inner } = self;
288        &inner.config
289    }
290
291    /// Returns current in-memory hot-file cache usage in bytes.
292    ///
293    /// # Returns
294    ///
295    /// - `usize` - Cached bytes across all 64 shards.
296    pub fn cached_bytes(&self) -> usize {
297        let Self { inner } = self;
298        inner.cached_bytes.load(Ordering::Relaxed)
299    }
300
301    /// Strips the configured mount prefix on a path-segment boundary.
302    ///
303    /// # Arguments
304    ///
305    /// - `&'a str` - Incoming request path.
306    ///
307    /// # Returns
308    ///
309    /// - `Option<&'a str>` - Relative sub-path when matched, or `None`.
310    pub(crate) fn strip_mount<'a>(&self, path: &'a str) -> Option<&'a str> {
311        let Self { inner } = self;
312        if inner.normalized_prefix == "/" {
313            return Some(path);
314        }
315        let rest: &'a str = path.strip_prefix(inner.normalized_prefix.as_str())?;
316        if rest.is_empty() || rest.starts_with('/') {
317            Some(rest)
318        } else {
319            None
320        }
321    }
322
323    /// Selects the best representation from a cached route entry for `enc_mask`.
324    ///
325    /// # Arguments
326    ///
327    /// - `&CachedRouteEntry` - Cached asset variants.
328    /// - `u8` - Client `Accept-Encoding` sidecar bitmask.
329    ///
330    /// # Returns
331    ///
332    /// - `Arc<CachedFile>` - Selected representation (`br` > `gzip` > `raw`).
333    #[inline]
334    fn select_cached_variant(entry: &CachedRouteEntry, enc_mask: u8) -> Arc<CachedFile> {
335        if (enc_mask & ENCODING_MASK_BR) != 0
336            && let Some(br_file) = &entry.br
337        {
338            return Arc::clone(br_file);
339        }
340        if (enc_mask & ENCODING_MASK_GZIP) != 0
341            && let Some(gz_file) = &entry.gz
342        {
343            return Arc::clone(gz_file);
344        }
345        Arc::clone(&entry.raw)
346    }
347
348    /// Reads one verified canonical file from disk into an immutable [`CachedFile`].
349    ///
350    /// # Arguments
351    ///
352    /// - `&Path` - Canonical file path verified inside `canonical_root`.
353    /// - `&'static str` - Resolved MIME content type.
354    /// - `Option<&'static str>` - Optional sidecar `Content-Encoding`.
355    ///
356    /// # Returns
357    ///
358    /// - `Option<Arc<CachedFile>>` - Loaded file payload, or `None` on I/O failure.
359    async fn read_disk_file(
360        disk_path: &Path,
361        content_type: &'static str,
362        content_encoding: Option<&'static str>,
363    ) -> Option<Arc<CachedFile>> {
364        let meta: Metadata = fs::metadata(disk_path).await.ok()?;
365        if !meta.is_file() {
366            return None;
367        }
368        let modified_ms: u64 = metadata_modified_ms(&meta);
369        let raw_bytes: Vec<u8> = fs::read(disk_path).await.ok()?;
370        let etag: String = compute_file_etag(raw_bytes.len() as u64, modified_ms);
371        Some(Arc::new(CachedFile {
372            bytes: Arc::from(raw_bytes),
373            etag,
374            content_type,
375            content_encoding,
376            wire_ok: OnceLock::new(),
377            wire_head: OnceLock::new(),
378            wire_304: OnceLock::new(),
379        }))
380    }
381
382    /// Probes an optional `.br` or `.gz` sidecar next to `canonical_base`, verifying containment within `canonical_root`.
383    ///
384    /// # Arguments
385    ///
386    /// - `&Path` - Canonical uncompressed file path.
387    /// - `&str` - Sidecar extension (`".br"` or `".gz"`).
388    /// - `&'static str` - Resolved base MIME content type.
389    /// - `&'static str` - Corresponding `Content-Encoding` token.
390    ///
391    /// # Returns
392    ///
393    /// - `Option<Arc<CachedFile>>` - Loaded sidecar representation if present and safe.
394    async fn load_sidecar(
395        &self,
396        canonical_base: &Path,
397        ext: &str,
398        mime: &'static str,
399        encoding: &'static str,
400    ) -> Option<Arc<CachedFile>> {
401        let Self { inner } = self;
402        let mut sidecar_os: OsString = canonical_base.as_os_str().to_os_string();
403        sidecar_os.push(ext);
404        let sidecar_path: PathBuf = PathBuf::from(sidecar_os);
405        let canon_sidecar: PathBuf = fs::canonicalize(&sidecar_path).await.ok()?;
406        if !canon_sidecar.starts_with(&inner.canonical_root) {
407            return None;
408        }
409        Self::read_disk_file(&canon_sidecar, mime, Some(encoding)).await
410    }
411
412    /// Resolves and loads a static asset on cache miss, populating the 64-shard hot cache when within budget.
413    ///
414    /// # Arguments
415    ///
416    /// - `&str` - Validated normalized relative URL path.
417    /// - `usize` - Precomputed shard index for `cache_key`.
418    /// - `u8` - Client `Accept-Encoding` sidecar bitmask.
419    ///
420    /// # Returns
421    ///
422    /// - `Option<Arc<CachedFile>>` - Resolved file representation, or `None` when not found/disallowed.
423    async fn resolve_and_cache_miss(
424        &self,
425        cache_key: &str,
426        shard_idx: usize,
427        enc_mask: u8,
428    ) -> Option<Arc<CachedFile>> {
429        let Self { inner } = self;
430        let candidate: PathBuf = resolve_safe_path(
431            &inner.canonical_root,
432            cache_key,
433            inner.config.get_allow_dotfiles(),
434        )?;
435        let resolved_base: PathBuf = match fs::metadata(&candidate).await {
436            Ok(meta) if meta.is_dir() => candidate.join(inner.config.get_index_file()),
437            Ok(meta) if meta.is_file() => candidate,
438            _ => match inner.config.get_spa_fallback() {
439                Some(fallback) => inner.canonical_root.join(fallback),
440                None => return None,
441            },
442        };
443        let canonical_base: PathBuf = fs::canonicalize(&resolved_base).await.ok()?;
444        if !canonical_base.starts_with(&inner.canonical_root) {
445            return None;
446        }
447        let mime: &'static str = mime_for_path(&canonical_base);
448        let max_cache: usize = inner.config.get_max_cache_bytes();
449        let max_file_cache: usize = inner.config.get_max_file_cache_bytes();
450        let serve_precompressed: bool = inner.config.get_serve_precompressed();
451        if max_cache == 0 {
452            if serve_precompressed
453                && (enc_mask & ENCODING_MASK_BR) != 0
454                && let Some(br_file) = self
455                    .load_sidecar(&canonical_base, SIDECAR_BR_EXT, mime, ENCODING_BR)
456                    .await
457            {
458                return Some(br_file);
459            }
460            if serve_precompressed
461                && (enc_mask & ENCODING_MASK_GZIP) != 0
462                && let Some(gz_file) = self
463                    .load_sidecar(&canonical_base, SIDECAR_GZ_EXT, mime, ENCODING_GZIP)
464                    .await
465            {
466                return Some(gz_file);
467            }
468            return Self::read_disk_file(&canonical_base, mime, None).await;
469        }
470        let raw_file: Arc<CachedFile> = Self::read_disk_file(&canonical_base, mime, None).await?;
471        let br_file: Option<Arc<CachedFile>> = if serve_precompressed {
472            self.load_sidecar(&canonical_base, SIDECAR_BR_EXT, mime, ENCODING_BR)
473                .await
474        } else {
475            None
476        };
477        let gz_file: Option<Arc<CachedFile>> = if serve_precompressed {
478            self.load_sidecar(&canonical_base, SIDECAR_GZ_EXT, mime, ENCODING_GZIP)
479                .await
480        } else {
481            None
482        };
483        let entry: Arc<CachedRouteEntry> = Arc::new(CachedRouteEntry {
484            raw: raw_file,
485            br: br_file,
486            gz: gz_file,
487        });
488        let entry_bytes: usize = entry.raw.bytes.len()
489            + entry
490                .br
491                .as_ref()
492                .map_or(0, |f: &Arc<CachedFile>| f.bytes.len())
493            + entry
494                .gz
495                .as_ref()
496                .map_or(0, |f: &Arc<CachedFile>| f.bytes.len());
497        if entry.raw.bytes.len() <= max_file_cache
498            && inner.cached_bytes.load(Ordering::Relaxed) + entry_bytes <= max_cache
499            && let Ok(mut guard) = inner.cache_shards[shard_idx].map.write()
500        {
501            if let Some(prev) = guard.insert(cache_key.to_owned(), Arc::clone(&entry)) {
502                let prev_bytes: usize = prev.raw.bytes.len()
503                    + prev
504                        .br
505                        .as_ref()
506                        .map_or(0, |f: &Arc<CachedFile>| f.bytes.len())
507                    + prev
508                        .gz
509                        .as_ref()
510                        .map_or(0, |f: &Arc<CachedFile>| f.bytes.len());
511                inner.cached_bytes.fetch_sub(prev_bytes, Ordering::Relaxed);
512            }
513            inner.cached_bytes.fetch_add(entry_bytes, Ordering::Relaxed);
514        }
515        Some(Self::select_cached_variant(&entry, enc_mask))
516    }
517
518    /// Resolves a matching [`CachedFile`] and `HEAD` flag for the incoming request context.
519    ///
520    /// # Arguments
521    ///
522    /// - `&Context` - Active Hyperlane request context.
523    ///
524    /// # Returns
525    ///
526    /// - `Option<(Arc<CachedFile>, bool)>` - Resolved file and `is_head` flag, or `None` if unmatched.
527    #[inline]
528    async fn resolve_file_for_context(&self, ctx: &Context) -> Option<(Arc<CachedFile>, bool)> {
529        let Self { inner } = self;
530        let request: &Request = ctx.get_request();
531        let is_get: bool = request.get_method().is_get();
532        let is_head: bool = !is_get && request.get_method().is_head();
533        if !is_get && !is_head {
534            return None;
535        }
536        let relative_url: &str = self.strip_mount(request.get_path())?;
537        let safe_rel: Cow<'_, str> =
538            validate_and_decode_relative(relative_url, inner.config.get_allow_dotfiles())?;
539        let cache_key: &str = safe_rel.as_ref();
540        let enc_mask: u8 = if inner.config.get_serve_precompressed() {
541            get_request_header_back_ref(request, ACCEPT_ENCODING).map_or(0, accept_encoding_mask)
542        } else {
543            0
544        };
545        let shard_idx: usize = static_cache_shard_index(cache_key);
546        let cached_hit: Option<Arc<CachedFile>> = if inner.config.get_max_cache_bytes() > 0 {
547            inner.cache_shards[shard_idx].map.read().ok().and_then(
548                |guard: RwLockReadGuard<'_, StaticCacheShardMap>| {
549                    guard.get(cache_key).map(|entry: &Arc<CachedRouteEntry>| {
550                        Self::select_cached_variant(entry, enc_mask)
551                    })
552                },
553            )
554        } else {
555            None
556        };
557        let file: Arc<CachedFile> = if let Some(hit) = cached_hit {
558            hit
559        } else {
560            self.resolve_and_cache_miss(cache_key, shard_idx, enc_mask)
561                .await?
562        };
563        Some((file, is_head))
564    }
565
566    /// Populates `ctx`'s outgoing response with status, headers, and body for `file`.
567    ///
568    /// # Arguments
569    ///
570    /// - `&mut Context` - Active Hyperlane request/response context.
571    /// - `&CachedFile` - Resolved static file representation.
572    /// - `bool` - Whether the request method is `HEAD`.
573    #[inline]
574    fn populate_response(&self, ctx: &mut Context, file: &CachedFile, is_head: bool) {
575        let Self { inner } = self;
576        let is_not_modified: bool = get_request_header_back_ref(ctx.get_request(), IF_NONE_MATCH)
577            .is_some_and(|inm: &str| if_none_match_matches(inm, &file.etag));
578        let total: usize = file.bytes.len();
579        let range_eval: Option<Option<(usize, usize)>> = if is_not_modified {
580            None
581        } else {
582            get_request_header_back_ref(ctx.get_request(), RANGE)
583                .map(|range_val: &str| parse_byte_range(range_val, total))
584        };
585        let cache_control: &str = inner.config.get_cache_control();
586        let response: &mut Response = ctx.get_mut_response();
587        response
588            .set_header(CONTENT_TYPE, file.content_type)
589            .set_header(ETAG, &file.etag)
590            .set_header(ACCEPT_RANGES, ACCEPT_RANGES_BYTES);
591        if !cache_control.is_empty() {
592            response.set_header(CACHE_CONTROL, cache_control);
593        }
594        if let Some(enc) = file.content_encoding {
595            response
596                .set_header(CONTENT_ENCODING, enc)
597                .set_header(VARY, VARY_ACCEPT_ENCODING);
598        }
599        if is_not_modified {
600            response.set_status_code(HttpStatus::NotModified.code());
601            response.get_mut_body().clear();
602            return;
603        }
604        if let Some(parsed_range) = range_eval {
605            let mut cr_buf: [u8; CONTENT_RANGE_STACK_CAP] = [0u8; CONTENT_RANGE_STACK_CAP];
606            match parsed_range {
607                Some((start, end)) => {
608                    let cr_str: &str = format_content_range_stack(start, end, total, &mut cr_buf);
609                    response
610                        .set_status_code(HttpStatus::PartialContent.code())
611                        .set_header(CONTENT_RANGE, cr_str);
612                    let body_buf: &mut Vec<u8> = response.get_mut_body();
613                    body_buf.clear();
614                    if !is_head {
615                        body_buf.extend_from_slice(&file.bytes[start..=end]);
616                    }
617                }
618                None => {
619                    let cr_str: &str = format_unsatisfiable_range_stack(total, &mut cr_buf);
620                    response
621                        .set_status_code(HttpStatus::RangeNotSatisfiable.code())
622                        .set_header(CONTENT_RANGE, cr_str);
623                    response.get_mut_body().clear();
624                }
625            }
626            return;
627        }
628        response.set_status_code(HttpStatus::Ok.code());
629        let body_buf: &mut Vec<u8> = response.get_mut_body();
630        body_buf.clear();
631        if !is_head {
632            body_buf.extend_from_slice(file.bytes.as_ref());
633        }
634    }
635
636    /// Attempts to serve a static asset for `ctx`, populating status, headers, and body.
637    ///
638    /// # Arguments
639    ///
640    /// - `&mut Context` - Incoming request and outgoing response context.
641    ///
642    /// # Returns
643    ///
644    /// - `bool` - `true` when a static file (or `304`/`206`/`416`) was served; `false` otherwise.
645    pub async fn serve_context(&self, ctx: &mut Context) -> bool {
646        let Some((file, is_head)) = self.resolve_file_for_context(ctx).await else {
647            return false;
648        };
649        self.populate_response(ctx, &file, is_head);
650        true
651    }
652
653    /// Serves a matching static asset directly to `stream` using zero-copy prebuilt HTTP/1.1 wire buffers when eligible.
654    ///
655    /// # Arguments
656    ///
657    /// - `&mut Stream` - Active client connection stream.
658    /// - `&mut Context` - Incoming request and outgoing response context.
659    ///
660    /// # Returns
661    ///
662    /// - `Status` - `Status::Reject` once a static asset was served; `Status::Continue` otherwise.
663    #[inline]
664    pub(crate) async fn serve_and_send_hook(
665        &self,
666        stream: &mut Stream,
667        ctx: &mut Context,
668    ) -> Status {
669        let Self { inner } = self;
670        let Some((file, is_head)) = self.resolve_file_for_context(ctx).await else {
671            return Status::Continue;
672        };
673        let resp: &Response = ctx.get_response();
674        let can_fast_wire: bool = ctx.get_request().get_version().is_http1_1()
675            && resp.get_version().is_http1_1()
676            && resp.get_headers().is_empty()
677            && (resp.get_reason_phrase().is_empty() || resp.get_reason_phrase().as_str() == OK);
678        if can_fast_wire {
679            let cache_control: &str = inner.config.get_cache_control();
680            let is_not_modified: bool =
681                get_request_header_back_ref(ctx.get_request(), IF_NONE_MATCH)
682                    .is_some_and(|inm: &str| if_none_match_matches(inm, &file.etag));
683            if is_not_modified {
684                let wire: &[u8] = file.get_wire_304(cache_control);
685                let _: Result<(), ResponseError> = stream.try_send(wire).await;
686                return Status::Reject;
687            }
688            if get_request_header_back_ref(ctx.get_request(), RANGE).is_none() {
689                let wire: &[u8] = if is_head {
690                    file.get_wire_head(cache_control)
691                } else {
692                    file.get_wire_ok(cache_control)
693                };
694                let _: Result<(), ResponseError> = stream.try_send(wire).await;
695                return Status::Reject;
696            }
697        }
698        self.populate_response(ctx, &file, is_head);
699        let wire: Vec<u8> = ctx.get_mut_response().build();
700        let _: Result<(), ResponseError> = stream.try_send(&wire).await;
701        Status::Reject
702    }
703}
704
705/// Inherent implementation of [`StaticFilesPlugin`].
706impl StaticFilesPlugin {
707    /// Initializes the global [`StaticFilesPlugin`] once from `config`.
708    ///
709    /// # Arguments
710    ///
711    /// - `StaticFilesConfig` - Static file server configuration.
712    ///
713    /// # Returns
714    ///
715    /// - `Result<&'static Self, String>` - Global plugin reference or canonicalization error.
716    pub fn init(config: StaticFilesConfig) -> Result<&'static Self, String> {
717        let runtime: StaticFilesRuntime = StaticFilesRuntime::new(config)?;
718        Ok(STATIC_FILES_PLUGIN.get_or_init(|| Self { runtime }))
719    }
720
721    /// Returns the initialized global [`StaticFilesPlugin`], if initialized.
722    ///
723    /// # Returns
724    ///
725    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
726    pub fn get() -> Option<&'static Self> {
727        STATIC_FILES_PLUGIN.get()
728    }
729
730    /// Returns the active [`StaticFilesRuntime`].
731    ///
732    /// # Returns
733    ///
734    /// - `&StaticFilesRuntime` - Active static file runtime.
735    pub fn get_runtime(&self) -> &StaticFilesRuntime {
736        let Self { runtime } = self;
737        runtime
738    }
739}
740
741/// Implements [`ServerHook`] for [`StaticFilesHook`].
742impl ServerHook for StaticFilesHook {
743    /// Constructs a per-request [`StaticFilesHook`].
744    ///
745    /// # Arguments
746    ///
747    /// - `&mut Stream` - Connection stream.
748    /// - `&mut Context` - Request context.
749    ///
750    /// # Returns
751    ///
752    /// - `Self` - Hook instance.
753    async fn new(_: &mut Stream, _: &mut Context) -> Self {
754        Self
755    }
756
757    /// Serves matching static files and short-circuits the pipeline once answered.
758    ///
759    /// # Arguments
760    ///
761    /// - `Self` - Hook instance.
762    /// - `&mut Stream` - Connection stream.
763    /// - `&mut Context` - Request context.
764    ///
765    /// # Returns
766    ///
767    /// - `Status` - `Status::Reject` once a static asset was served; `Status::Continue` otherwise.
768    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
769        let Some(plugin) = StaticFilesPlugin::get() else {
770            return Status::Continue;
771        };
772        plugin.get_runtime().serve_and_send_hook(stream, ctx).await
773    }
774}