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
use super::*;

/// Configuration for [`StaticFilesRuntime`] and [`StaticFilesPlugin`].
#[derive(Clone, Data, Debug, Eq, PartialEq)]
pub struct StaticFilesConfig {
    /// Filesystem root directory from which assets are served.
    pub(crate) root_dir: PathBuf,
    /// URL mount prefix (for example `"/static"` or `"/"`).
    pub(crate) mount_prefix: String,
    /// Default directory index filename (default `"index.html"`).
    pub(crate) index_file: String,
    /// Optional SPA fallback file relative to `root_dir` (for example `"index.html"`).
    #[get(type(clone))]
    pub(crate) spa_fallback: Option<String>,
    /// `Cache-Control` header value applied to served files.
    pub(crate) cache_control: String,
    /// Enables serving precompressed `.br` and `.gz` sidecar files when accepted by the client.
    #[get(type(copy))]
    pub(crate) serve_precompressed: bool,
    /// Permits serving dotfiles (`.well-known`, etc.) when `true` (default `false`).
    #[get(type(copy))]
    pub(crate) allow_dotfiles: bool,
    /// Total memory budget in bytes for the 64-way sharded hot-file cache (`0` disables caching).
    #[get(type(copy))]
    pub(crate) max_cache_bytes: usize,
    /// Maximum single file size eligible for in-memory hot caching.
    #[get(type(copy))]
    pub(crate) max_file_cache_bytes: usize,
}

/// Zero-allocation multiplicative 64-bit hasher for hot-file cache lookup.
#[derive(Clone, Copy, Default)]
pub(crate) struct FxHasher {
    /// Running 64-bit hash accumulator.
    pub(crate) state: u64,
}

/// Cache-line-aligned hot-file cache shard avoiding cross-thread false sharing.
#[repr(align(64))]
pub(crate) struct StaticCacheShard {
    /// Per-shard read-write lock guarding cached route entries.
    pub(crate) map: RwLock<StaticCacheShardMap>,
}

/// Immutable cached static file payload stored inside [`StaticFilesRuntime`].
#[derive(Debug)]
pub(crate) struct CachedFile {
    /// Shared zero-copy file contents bytes.
    pub(crate) bytes: Arc<[u8]>,
    /// Precomputed strong `ETag`.
    pub(crate) etag: String,
    /// Resolved MIME `Content-Type`.
    pub(crate) content_type: &'static str,
    /// Optional precompressed `Content-Encoding` (`"br"` or `"gzip"`).
    pub(crate) content_encoding: Option<&'static str>,
    /// Lazily built HTTP/1.1 `200 OK` full wire response (headers + body).
    pub(crate) wire_ok: OnceLock<Arc<[u8]>>,
    /// Lazily built HTTP/1.1 `200 OK` `HEAD` wire response (headers only).
    pub(crate) wire_head: OnceLock<Arc<[u8]>>,
    /// Lazily built HTTP/1.1 `304 Not Modified` wire response.
    pub(crate) wire_304: OnceLock<Arc<[u8]>>,
}

/// Cached asset entry holding the uncompressed representation plus optional `.br` and `.gz` sidecars.
#[derive(Clone, Debug)]
pub(crate) struct CachedRouteEntry {
    /// Uncompressed file representation.
    pub(crate) raw: Arc<CachedFile>,
    /// Optional Brotli precompressed sidecar representation.
    pub(crate) br: Option<Arc<CachedFile>>,
    /// Optional Gzip precompressed sidecar representation.
    pub(crate) gz: Option<Arc<CachedFile>>,
}

/// Shared interior state of [`StaticFilesRuntime`].
pub(crate) struct StaticFilesRuntimeInner {
    /// Original static file configuration.
    pub(crate) config: StaticFilesConfig,
    /// Canonicalized root directory path for symlink-escape verification.
    pub(crate) canonical_root: PathBuf,
    /// Normalized mount prefix (without trailing slash unless `"/"`).
    pub(crate) normalized_prefix: String,
    /// Current cached byte usage across all 64 shards.
    pub(crate) cached_bytes: AtomicUsize,
    /// 64-way sharded hot-file memory cache.
    pub(crate) cache_shards: Box<[StaticCacheShard; STATIC_CACHE_SHARDS]>,
}

/// Thread-safe static asset engine with 64-way sharded hot-file caching and security checks.
#[derive(Clone)]
pub struct StaticFilesRuntime {
    /// Shared runtime state.
    pub(crate) inner: Arc<StaticFilesRuntimeInner>,
}

/// Process-wide [`StaticFilesPlugin`] singleton storing [`StaticFilesRuntime`].
#[derive(Clone)]
pub struct StaticFilesPlugin {
    /// Compiled static-file serving engine.
    pub(crate) runtime: StaticFilesRuntime,
}

/// Opt-in [`ServerHook`] serving static assets on `GET` / `HEAD` requests under the configured mount prefix.
#[derive(Clone, Copy, Debug, Default)]
#[hyperlane::request_middleware(-55)]
pub struct StaticFilesHook;