hyperlane-plugin-static-files 22.14.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
use super::*;

/// 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: StaticCacheShardArray =
            Box::new(from_fn(|_: usize| RwLock::new(hash_map_xx_hash3_64())));
        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,
        }))
    }

    /// 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].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))
    }

    /// 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 Self { inner } = self;
        let is_get: bool = ctx.get_request().get_method().is_get();
        let is_head: bool = ctx.get_request().get_method().is_head();
        if !is_get && !is_head {
            return false;
        }
        let file: Arc<CachedFile> = {
            let request: &Request = ctx.get_request();
            let Some(relative_url) = self.strip_mount(request.get_path()) else {
                return false;
            };
            let Some(safe_rel) =
                validate_and_decode_relative(relative_url, inner.config.get_allow_dotfiles())
            else {
                return false;
            };
            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].read().ok().and_then(
                    |guard: RwLockReadGuard<
                        '_,
                        HashMapXxHash3_64<String, Arc<CachedRouteEntry>>,
                    >| {
                        guard.get(cache_key).map(|entry: &Arc<CachedRouteEntry>| {
                            Self::select_cached_variant(entry, enc_mask)
                        })
                    },
                )
            } else {
                None
            };
            if let Some(hit) = cached_hit {
                hit
            } else {
                let Some(loaded) = self
                    .resolve_and_cache_miss(cache_key, shard_idx, enc_mask)
                    .await
                else {
                    return false;
                };
                loaded
            }
        };
        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())
                .set_body(EMPTY_STR);
            return true;
        }
        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);
                    if is_head {
                        response.set_body(EMPTY_STR);
                    } else {
                        response.set_body(&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)
                        .set_body(EMPTY_STR);
                }
            }
            return true;
        }
        response.set_status_code(HttpStatus::Ok.code());
        if is_head {
            response.set_body(EMPTY_STR);
        } else {
            response.set_body(file.bytes.as_ref());
        }
        true
    }
}

/// 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 {
        &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;
        };
        if plugin.get_runtime().serve_context(ctx).await {
            let wire: ResponseData = ctx.get_mut_response().build();
            let _: Result<(), ResponseError> = stream.try_send(&wire).await;
            return Status::Reject;
        }
        Status::Continue
    }
}