Skip to main content

hyperlane_plugin_static_files/
impl.rs

1use super::*;
2
3/// Inherent constructors and builders for [`StaticFilesConfig`].
4impl StaticFilesConfig {
5    /// Creates a [`StaticFilesConfig`] serving files from `root_dir` mounted at `"/"`.
6    ///
7    /// # Arguments
8    ///
9    /// - `P` - Root directory path convertible into `PathBuf`.
10    ///
11    /// # Returns
12    ///
13    /// - `Self` - Constructed static files configuration.
14    pub fn new<P>(root_dir: P) -> Self
15    where
16        P: Into<PathBuf>,
17    {
18        Self {
19            root_dir: root_dir.into(),
20            mount_prefix: DEFAULT_STATIC_MOUNT_PREFIX.to_owned(),
21            index_file: DEFAULT_STATIC_INDEX_FILE.to_owned(),
22            spa_fallback: None,
23            cache_control: DEFAULT_STATIC_CACHE_CONTROL.to_owned(),
24            serve_precompressed: true,
25            allow_dotfiles: false,
26            max_cache_bytes: DEFAULT_STATIC_MAX_CACHE_BYTES,
27            max_file_cache_bytes: DEFAULT_STATIC_MAX_FILE_CACHE_BYTES,
28        }
29    }
30
31    /// Sets the URL mount prefix (for example `"/assets"`).
32    ///
33    /// # Arguments
34    ///
35    /// - `P` - Mount prefix convertible into `String`.
36    ///
37    /// # Returns
38    ///
39    /// - `Self` - Updated configuration.
40    pub fn with_mount_prefix<P>(mut self, prefix: P) -> Self
41    where
42        P: Into<String>,
43    {
44        self.set_mount_prefix(prefix.into());
45        self
46    }
47
48    /// Sets an SPA fallback file relative to `root_dir` (for example `"index.html"`).
49    ///
50    /// # Arguments
51    ///
52    /// - `F` - Fallback filename convertible into `String`.
53    ///
54    /// # Returns
55    ///
56    /// - `Self` - Updated configuration.
57    pub fn with_spa_fallback<F>(mut self, fallback: F) -> Self
58    where
59        F: Into<String>,
60    {
61        self.set_spa_fallback(Some(fallback.into()));
62        self
63    }
64
65    /// Sets the `Cache-Control` response header value.
66    ///
67    /// # Arguments
68    ///
69    /// - `C` - Header value convertible into `String`.
70    ///
71    /// # Returns
72    ///
73    /// - `Self` - Updated configuration.
74    pub fn with_cache_control<C>(mut self, cache_control: C) -> Self
75    where
76        C: Into<String>,
77    {
78        self.set_cache_control(cache_control.into());
79        self
80    }
81
82    /// Enables or disables `.br`/`.gz` precompressed sidecar negotiation.
83    ///
84    /// # Arguments
85    ///
86    /// - `bool` - Whether precompressed sidecars are checked.
87    ///
88    /// # Returns
89    ///
90    /// - `Self` - Updated configuration.
91    pub fn with_serve_precompressed(mut self, enabled: bool) -> Self {
92        self.set_serve_precompressed(enabled);
93        self
94    }
95}
96
97/// Inherent implementation of [`StaticFilesRuntime`].
98impl StaticFilesRuntime {
99    /// Compiles a [`StaticFilesRuntime`] by canonicalizing `config.root_dir`.
100    ///
101    /// # Arguments
102    ///
103    /// - `StaticFilesConfig` - Static file server configuration.
104    ///
105    /// # Returns
106    ///
107    /// - `Result<Self, String>` - Ready runtime or canonicalization error message.
108    pub fn new(config: StaticFilesConfig) -> Result<Self, String> {
109        let canonical_root: PathBuf =
110            canonicalize(config.get_root_dir()).map_err(|err: io::Error| err.to_string())?;
111        let trimmed: &str = config.get_mount_prefix().trim();
112        let normalized_prefix: String = if trimmed.is_empty() || trimmed == "/" {
113            "/".to_owned()
114        } else if trimmed.starts_with('/') {
115            trimmed.trim_end_matches('/').to_owned()
116        } else {
117            format!("/{}", trimmed.trim_end_matches('/'))
118        };
119        let cache_shards: StaticCacheShardArray =
120            Box::new(from_fn(|_: usize| RwLock::new(hash_map_xx_hash3_64())));
121        Ok(Self {
122            inner: Arc::new(StaticFilesRuntimeInner {
123                config,
124                canonical_root,
125                normalized_prefix,
126                cached_bytes: AtomicUsize::new(0),
127                cache_shards,
128            }),
129        })
130    }
131
132    /// Returns the active [`StaticFilesConfig`].
133    ///
134    /// # Returns
135    ///
136    /// - `&StaticFilesConfig` - Active configuration.
137    pub fn get_config(&self) -> &StaticFilesConfig {
138        let Self { inner } = self;
139        &inner.config
140    }
141
142    /// Returns current in-memory hot-file cache usage in bytes.
143    ///
144    /// # Returns
145    ///
146    /// - `usize` - Cached bytes across all 64 shards.
147    pub fn cached_bytes(&self) -> usize {
148        let Self { inner } = self;
149        inner.cached_bytes.load(Ordering::Relaxed)
150    }
151
152    /// Strips the configured mount prefix on a path-segment boundary.
153    ///
154    /// # Arguments
155    ///
156    /// - `&'a str` - Incoming request path.
157    ///
158    /// # Returns
159    ///
160    /// - `Option<&'a str>` - Relative sub-path when matched, or `None`.
161    pub(crate) fn strip_mount<'a>(&self, path: &'a str) -> Option<&'a str> {
162        let Self { inner } = self;
163        if inner.normalized_prefix == "/" {
164            return Some(path);
165        }
166        let rest: &'a str = path.strip_prefix(inner.normalized_prefix.as_str())?;
167        if rest.is_empty() || rest.starts_with('/') {
168            Some(rest)
169        } else {
170            None
171        }
172    }
173
174    /// Resolves a verified canonical file path inside `canonical_root`, applying directory index and sidecar selection.
175    ///
176    /// # Arguments
177    ///
178    /// - `&str` - Relative URL path under mount prefix.
179    /// - `Option<&str>` - Optional `Accept-Encoding` header value.
180    ///
181    /// # Returns
182    ///
183    /// - `Option<(PathBuf, &'static str, Option<&'static str>)>` - `(disk_path, content_type, content_encoding)`.
184    async fn resolve_target_file(
185        &self,
186        relative_url: &str,
187        accept_encoding: Option<&str>,
188    ) -> Option<(PathBuf, &'static str, Option<&'static str>)> {
189        let Self { inner } = self;
190        let candidate: PathBuf = resolve_safe_path(
191            &inner.canonical_root,
192            relative_url,
193            inner.config.get_allow_dotfiles(),
194        )?;
195        let resolved_base: PathBuf = match fs::metadata(&candidate).await {
196            Ok(meta) if meta.is_dir() => candidate.join(inner.config.get_index_file()),
197            Ok(meta) if meta.is_file() => candidate,
198            _ => match inner.config.get_spa_fallback() {
199                Some(fallback) => inner.canonical_root.join(fallback),
200                None => return None,
201            },
202        };
203        let canonical_base: PathBuf = fs::canonicalize(&resolved_base).await.ok()?;
204        if !canonical_base.starts_with(&inner.canonical_root) {
205            return None;
206        }
207        let mime: &'static str = mime_for_path(&canonical_base);
208        if inner.config.get_serve_precompressed()
209            && let Some(ae) = accept_encoding
210        {
211            if accepts_encoding(ae, ENCODING_BR) {
212                let mut br_os: OsString = canonical_base.as_os_str().to_os_string();
213                br_os.push(SIDECAR_BR_EXT);
214                let br_path: PathBuf = PathBuf::from(br_os);
215                if let Ok(canon_br) = fs::canonicalize(&br_path).await
216                    && canon_br.starts_with(&inner.canonical_root)
217                    && fs::metadata(&canon_br)
218                        .await
219                        .is_ok_and(|m: Metadata| m.is_file())
220                {
221                    return Some((canon_br, mime, Some(ENCODING_BR)));
222                }
223            }
224            if accepts_encoding(ae, ENCODING_GZIP) {
225                let mut gz_os: OsString = canonical_base.as_os_str().to_os_string();
226                gz_os.push(SIDECAR_GZ_EXT);
227                let gz_path: PathBuf = PathBuf::from(gz_os);
228                if let Ok(canon_gz) = fs::canonicalize(&gz_path).await
229                    && canon_gz.starts_with(&inner.canonical_root)
230                    && fs::metadata(&canon_gz)
231                        .await
232                        .is_ok_and(|m: Metadata| m.is_file())
233                {
234                    return Some((canon_gz, mime, Some(ENCODING_GZIP)));
235                }
236            }
237        }
238        Some((canonical_base, mime, None))
239    }
240
241    /// Loads `disk_path` from the 64-shard hot-file cache (revalidating mtime+size) or disk.
242    ///
243    /// # Arguments
244    ///
245    /// - `&Path` - Canonical target file path.
246    /// - `&'static str` - Resolved MIME content type.
247    /// - `Option<&'static str>` - Optional sidecar `Content-Encoding`.
248    ///
249    /// # Returns
250    ///
251    /// - `Option<Arc<CachedFile>>` - Loaded file entry, or `None` on I/O failure.
252    async fn load_file(
253        &self,
254        disk_path: &Path,
255        content_type: &'static str,
256        content_encoding: Option<&'static str>,
257    ) -> Option<Arc<CachedFile>> {
258        let Self { inner } = self;
259        let meta: Metadata = fs::metadata(disk_path).await.ok()?;
260        if !meta.is_file() {
261            return None;
262        }
263        let file_len: u64 = meta.len();
264        let modified_ms: u64 = metadata_modified_ms(&meta);
265        let shard_idx: usize = static_cache_shard_index(disk_path);
266        let max_cache: usize = inner.config.get_max_cache_bytes();
267        let max_file_cache: usize = inner.config.get_max_file_cache_bytes();
268        if max_cache > 0
269            && (file_len as usize) <= max_file_cache
270            && let Ok(guard) = inner.cache_shards[shard_idx].read()
271            && let Some(cached) = guard.get(disk_path)
272            && cached.modified_ms == modified_ms
273            && cached.bytes.len() as u64 == file_len
274        {
275            return Some(Arc::clone(cached));
276        }
277        let bytes: Vec<u8> = fs::read(disk_path).await.ok()?;
278        let etag: String = compute_file_etag(bytes.len() as u64, modified_ms);
279        let file: Arc<CachedFile> = Arc::new(CachedFile {
280            bytes,
281            etag,
282            content_type,
283            content_encoding,
284            modified_ms,
285        });
286        if max_cache > 0 && file.bytes.len() <= max_file_cache {
287            let size: usize = file.bytes.len();
288            if inner.cached_bytes.load(Ordering::Relaxed) + size <= max_cache
289                && let Ok(mut guard) = inner.cache_shards[shard_idx].write()
290            {
291                if let Some(prev) = guard.insert(disk_path.to_path_buf(), Arc::clone(&file)) {
292                    inner
293                        .cached_bytes
294                        .fetch_sub(prev.bytes.len(), Ordering::Relaxed);
295                }
296                inner.cached_bytes.fetch_add(size, Ordering::Relaxed);
297            }
298        }
299        Some(file)
300    }
301
302    /// Attempts to serve a static asset for `ctx`, populating status, headers, and body.
303    ///
304    /// # Arguments
305    ///
306    /// - `&mut Context` - Incoming request and outgoing response context.
307    ///
308    /// # Returns
309    ///
310    /// - `bool` - `true` when a static file (or `304`/`206`/`416`) was served; `false` otherwise.
311    pub async fn serve_context(&self, ctx: &mut Context) -> bool {
312        let is_get: bool = ctx.get_request().get_method().is_get();
313        let is_head: bool = ctx.get_request().get_method().is_head();
314        if !is_get && !is_head {
315            return false;
316        }
317        let req_path: String = ctx.get_request().get_path().clone();
318        let Some(relative_url) = self.strip_mount(&req_path) else {
319            return false;
320        };
321        let accept_encoding: Option<String> =
322            ctx.get_request().try_get_header_back(ACCEPT_ENCODING);
323        let Some((disk_path, mime, encoding)) = self
324            .resolve_target_file(relative_url, accept_encoding.as_deref())
325            .await
326        else {
327            return false;
328        };
329        let Some(file) = self.load_file(&disk_path, mime, encoding).await else {
330            return false;
331        };
332        let if_none_match: Option<String> = ctx.get_request().try_get_header_back(IF_NONE_MATCH);
333        let range_header: Option<String> = ctx.get_request().try_get_header_back(RANGE);
334        let cache_control: &str = self.get_config().get_cache_control();
335        let response: &mut Response = ctx.get_mut_response();
336        response
337            .set_header(CONTENT_TYPE, file.content_type)
338            .set_header(ETAG, &file.etag)
339            .set_header(ACCEPT_RANGES, ACCEPT_RANGES_BYTES);
340        if !cache_control.is_empty() {
341            response.set_header(CACHE_CONTROL, cache_control);
342        }
343        if let Some(enc) = file.content_encoding {
344            response
345                .set_header(CONTENT_ENCODING, enc)
346                .set_header(VARY, VARY_ACCEPT_ENCODING);
347        }
348        if let Some(inm) = if_none_match
349            && if_none_match_matches(&inm, &file.etag)
350        {
351            response
352                .set_status_code(HttpStatus::NotModified.code())
353                .set_body(Vec::new());
354            return true;
355        }
356        let total: usize = file.bytes.len();
357        if let Some(range_val) = range_header {
358            match parse_byte_range(&range_val, total) {
359                Some((start, end)) => {
360                    let content_range: String = format!("bytes {start}-{end}/{total}");
361                    response
362                        .set_status_code(HttpStatus::PartialContent.code())
363                        .set_header(CONTENT_RANGE, content_range);
364                    if is_head {
365                        response.set_body(Vec::new());
366                    } else {
367                        response.set_body(&file.bytes[start..=end]);
368                    }
369                }
370                None => {
371                    let content_range: String = format!("bytes */{total}");
372                    response
373                        .set_status_code(HttpStatus::RangeNotSatisfiable.code())
374                        .set_header(CONTENT_RANGE, content_range)
375                        .set_body(Vec::new());
376                }
377            }
378            return true;
379        }
380        response.set_status_code(HttpStatus::Ok.code());
381        if is_head {
382            response.set_body(Vec::new());
383        } else {
384            response.set_body(file.bytes.clone());
385        }
386        true
387    }
388}
389
390/// Inherent implementation of [`StaticFilesPlugin`].
391impl StaticFilesPlugin {
392    /// Initializes the global [`StaticFilesPlugin`] once from `config`.
393    ///
394    /// # Arguments
395    ///
396    /// - `StaticFilesConfig` - Static file server configuration.
397    ///
398    /// # Returns
399    ///
400    /// - `Result<&'static Self, String>` - Global plugin reference or canonicalization error.
401    pub fn init(config: StaticFilesConfig) -> Result<&'static Self, String> {
402        let runtime: StaticFilesRuntime = StaticFilesRuntime::new(config)?;
403        Ok(STATIC_FILES_PLUGIN.get_or_init(|| Self { runtime }))
404    }
405
406    /// Returns the initialized global [`StaticFilesPlugin`], if initialized.
407    ///
408    /// # Returns
409    ///
410    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
411    pub fn get() -> Option<&'static Self> {
412        STATIC_FILES_PLUGIN.get()
413    }
414
415    /// Returns the active [`StaticFilesRuntime`].
416    ///
417    /// # Returns
418    ///
419    /// - `&StaticFilesRuntime` - Active static file runtime.
420    pub fn get_runtime(&self) -> &StaticFilesRuntime {
421        &self.runtime
422    }
423}
424
425/// Implements [`ServerHook`] for [`StaticFilesHook`].
426impl ServerHook for StaticFilesHook {
427    /// Constructs a per-request [`StaticFilesHook`].
428    ///
429    /// # Arguments
430    ///
431    /// - `&mut Stream` - Connection stream.
432    /// - `&mut Context` - Request context.
433    ///
434    /// # Returns
435    ///
436    /// - `Self` - Hook instance.
437    async fn new(_: &mut Stream, _: &mut Context) -> Self {
438        Self
439    }
440
441    /// Serves matching static files and short-circuits the pipeline once answered.
442    ///
443    /// # Arguments
444    ///
445    /// - `Self` - Hook instance.
446    /// - `&mut Stream` - Connection stream.
447    /// - `&mut Context` - Request context.
448    ///
449    /// # Returns
450    ///
451    /// - `Status` - `Status::Reject` once a static asset was served; `Status::Continue` otherwise.
452    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
453        let Some(plugin) = StaticFilesPlugin::get() else {
454            return Status::Continue;
455        };
456        if plugin.get_runtime().serve_context(ctx).await {
457            let wire: ResponseData = ctx.get_mut_response().build();
458            let _: Result<(), ResponseError> = stream.try_send(&wire).await;
459            return Status::Reject;
460        }
461        Status::Continue
462    }
463}