hyperlane_plugin_static_files/
impl.rs1use super::*;
2
3impl StaticFilesConfig {
5 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 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 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 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 pub fn with_serve_precompressed(mut self, enabled: bool) -> Self {
92 self.set_serve_precompressed(enabled);
93 self
94 }
95}
96
97impl StaticFilesRuntime {
99 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 pub fn get_config(&self) -> &StaticFilesConfig {
138 let Self { inner } = self;
139 &inner.config
140 }
141
142 pub fn cached_bytes(&self) -> usize {
148 let Self { inner } = self;
149 inner.cached_bytes.load(Ordering::Relaxed)
150 }
151
152 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 #[inline]
185 fn select_cached_variant(entry: &CachedRouteEntry, enc_mask: u8) -> Arc<CachedFile> {
186 if (enc_mask & ENCODING_MASK_BR) != 0
187 && let Some(br_file) = &entry.br
188 {
189 return Arc::clone(br_file);
190 }
191 if (enc_mask & ENCODING_MASK_GZIP) != 0
192 && let Some(gz_file) = &entry.gz
193 {
194 return Arc::clone(gz_file);
195 }
196 Arc::clone(&entry.raw)
197 }
198
199 async fn read_disk_file(
211 disk_path: &Path,
212 content_type: &'static str,
213 content_encoding: Option<&'static str>,
214 ) -> Option<Arc<CachedFile>> {
215 let meta: Metadata = fs::metadata(disk_path).await.ok()?;
216 if !meta.is_file() {
217 return None;
218 }
219 let modified_ms: u64 = metadata_modified_ms(&meta);
220 let raw_bytes: Vec<u8> = fs::read(disk_path).await.ok()?;
221 let etag: String = compute_file_etag(raw_bytes.len() as u64, modified_ms);
222 Some(Arc::new(CachedFile {
223 bytes: Arc::from(raw_bytes),
224 etag,
225 content_type,
226 content_encoding,
227 }))
228 }
229
230 async fn load_sidecar(
243 &self,
244 canonical_base: &Path,
245 ext: &str,
246 mime: &'static str,
247 encoding: &'static str,
248 ) -> Option<Arc<CachedFile>> {
249 let Self { inner } = self;
250 let mut sidecar_os: OsString = canonical_base.as_os_str().to_os_string();
251 sidecar_os.push(ext);
252 let sidecar_path: PathBuf = PathBuf::from(sidecar_os);
253 let canon_sidecar: PathBuf = fs::canonicalize(&sidecar_path).await.ok()?;
254 if !canon_sidecar.starts_with(&inner.canonical_root) {
255 return None;
256 }
257 Self::read_disk_file(&canon_sidecar, mime, Some(encoding)).await
258 }
259
260 async fn resolve_and_cache_miss(
272 &self,
273 cache_key: &str,
274 shard_idx: usize,
275 enc_mask: u8,
276 ) -> Option<Arc<CachedFile>> {
277 let Self { inner } = self;
278 let candidate: PathBuf = resolve_safe_path(
279 &inner.canonical_root,
280 cache_key,
281 inner.config.get_allow_dotfiles(),
282 )?;
283 let resolved_base: PathBuf = match fs::metadata(&candidate).await {
284 Ok(meta) if meta.is_dir() => candidate.join(inner.config.get_index_file()),
285 Ok(meta) if meta.is_file() => candidate,
286 _ => match inner.config.get_spa_fallback() {
287 Some(fallback) => inner.canonical_root.join(fallback),
288 None => return None,
289 },
290 };
291 let canonical_base: PathBuf = fs::canonicalize(&resolved_base).await.ok()?;
292 if !canonical_base.starts_with(&inner.canonical_root) {
293 return None;
294 }
295 let mime: &'static str = mime_for_path(&canonical_base);
296 let max_cache: usize = inner.config.get_max_cache_bytes();
297 let max_file_cache: usize = inner.config.get_max_file_cache_bytes();
298 let serve_precompressed: bool = inner.config.get_serve_precompressed();
299 if max_cache == 0 {
300 if serve_precompressed
301 && (enc_mask & ENCODING_MASK_BR) != 0
302 && let Some(br_file) = self
303 .load_sidecar(&canonical_base, SIDECAR_BR_EXT, mime, ENCODING_BR)
304 .await
305 {
306 return Some(br_file);
307 }
308 if serve_precompressed
309 && (enc_mask & ENCODING_MASK_GZIP) != 0
310 && let Some(gz_file) = self
311 .load_sidecar(&canonical_base, SIDECAR_GZ_EXT, mime, ENCODING_GZIP)
312 .await
313 {
314 return Some(gz_file);
315 }
316 return Self::read_disk_file(&canonical_base, mime, None).await;
317 }
318 let raw_file: Arc<CachedFile> = Self::read_disk_file(&canonical_base, mime, None).await?;
319 let br_file: Option<Arc<CachedFile>> = if serve_precompressed {
320 self.load_sidecar(&canonical_base, SIDECAR_BR_EXT, mime, ENCODING_BR)
321 .await
322 } else {
323 None
324 };
325 let gz_file: Option<Arc<CachedFile>> = if serve_precompressed {
326 self.load_sidecar(&canonical_base, SIDECAR_GZ_EXT, mime, ENCODING_GZIP)
327 .await
328 } else {
329 None
330 };
331 let entry: Arc<CachedRouteEntry> = Arc::new(CachedRouteEntry {
332 raw: raw_file,
333 br: br_file,
334 gz: gz_file,
335 });
336 let entry_bytes: usize = entry.raw.bytes.len()
337 + entry
338 .br
339 .as_ref()
340 .map_or(0, |f: &Arc<CachedFile>| f.bytes.len())
341 + entry
342 .gz
343 .as_ref()
344 .map_or(0, |f: &Arc<CachedFile>| f.bytes.len());
345 if entry.raw.bytes.len() <= max_file_cache
346 && inner.cached_bytes.load(Ordering::Relaxed) + entry_bytes <= max_cache
347 && let Ok(mut guard) = inner.cache_shards[shard_idx].write()
348 {
349 if let Some(prev) = guard.insert(cache_key.to_owned(), Arc::clone(&entry)) {
350 let prev_bytes: usize = prev.raw.bytes.len()
351 + prev
352 .br
353 .as_ref()
354 .map_or(0, |f: &Arc<CachedFile>| f.bytes.len())
355 + prev
356 .gz
357 .as_ref()
358 .map_or(0, |f: &Arc<CachedFile>| f.bytes.len());
359 inner.cached_bytes.fetch_sub(prev_bytes, Ordering::Relaxed);
360 }
361 inner.cached_bytes.fetch_add(entry_bytes, Ordering::Relaxed);
362 }
363 Some(Self::select_cached_variant(&entry, enc_mask))
364 }
365
366 pub async fn serve_context(&self, ctx: &mut Context) -> bool {
376 let Self { inner } = self;
377 let is_get: bool = ctx.get_request().get_method().is_get();
378 let is_head: bool = ctx.get_request().get_method().is_head();
379 if !is_get && !is_head {
380 return false;
381 }
382 let file: Arc<CachedFile> = {
383 let request: &Request = ctx.get_request();
384 let Some(relative_url) = self.strip_mount(request.get_path()) else {
385 return false;
386 };
387 let Some(safe_rel) =
388 validate_and_decode_relative(relative_url, inner.config.get_allow_dotfiles())
389 else {
390 return false;
391 };
392 let cache_key: &str = safe_rel.as_ref();
393 let enc_mask: u8 = if inner.config.get_serve_precompressed() {
394 get_request_header_back_ref(request, ACCEPT_ENCODING)
395 .map_or(0, accept_encoding_mask)
396 } else {
397 0
398 };
399 let shard_idx: usize = static_cache_shard_index(cache_key);
400 let cached_hit: Option<Arc<CachedFile>> = if inner.config.get_max_cache_bytes() > 0 {
401 inner.cache_shards[shard_idx].read().ok().and_then(
402 |guard: RwLockReadGuard<
403 '_,
404 HashMapXxHash3_64<String, Arc<CachedRouteEntry>>,
405 >| {
406 guard.get(cache_key).map(|entry: &Arc<CachedRouteEntry>| {
407 Self::select_cached_variant(entry, enc_mask)
408 })
409 },
410 )
411 } else {
412 None
413 };
414 if let Some(hit) = cached_hit {
415 hit
416 } else {
417 let Some(loaded) = self
418 .resolve_and_cache_miss(cache_key, shard_idx, enc_mask)
419 .await
420 else {
421 return false;
422 };
423 loaded
424 }
425 };
426 let is_not_modified: bool = get_request_header_back_ref(ctx.get_request(), IF_NONE_MATCH)
427 .is_some_and(|inm: &str| if_none_match_matches(inm, &file.etag));
428 let total: usize = file.bytes.len();
429 let range_eval: Option<Option<(usize, usize)>> = if is_not_modified {
430 None
431 } else {
432 get_request_header_back_ref(ctx.get_request(), RANGE)
433 .map(|range_val: &str| parse_byte_range(range_val, total))
434 };
435 let cache_control: &str = inner.config.get_cache_control();
436 let response: &mut Response = ctx.get_mut_response();
437 response
438 .set_header(CONTENT_TYPE, file.content_type)
439 .set_header(ETAG, &file.etag)
440 .set_header(ACCEPT_RANGES, ACCEPT_RANGES_BYTES);
441 if !cache_control.is_empty() {
442 response.set_header(CACHE_CONTROL, cache_control);
443 }
444 if let Some(enc) = file.content_encoding {
445 response
446 .set_header(CONTENT_ENCODING, enc)
447 .set_header(VARY, VARY_ACCEPT_ENCODING);
448 }
449 if is_not_modified {
450 response
451 .set_status_code(HttpStatus::NotModified.code())
452 .set_body(EMPTY_STR);
453 return true;
454 }
455 if let Some(parsed_range) = range_eval {
456 let mut cr_buf: [u8; CONTENT_RANGE_STACK_CAP] = [0u8; CONTENT_RANGE_STACK_CAP];
457 match parsed_range {
458 Some((start, end)) => {
459 let cr_str: &str = format_content_range_stack(start, end, total, &mut cr_buf);
460 response
461 .set_status_code(HttpStatus::PartialContent.code())
462 .set_header(CONTENT_RANGE, cr_str);
463 if is_head {
464 response.set_body(EMPTY_STR);
465 } else {
466 response.set_body(&file.bytes[start..=end]);
467 }
468 }
469 None => {
470 let cr_str: &str = format_unsatisfiable_range_stack(total, &mut cr_buf);
471 response
472 .set_status_code(HttpStatus::RangeNotSatisfiable.code())
473 .set_header(CONTENT_RANGE, cr_str)
474 .set_body(EMPTY_STR);
475 }
476 }
477 return true;
478 }
479 response.set_status_code(HttpStatus::Ok.code());
480 if is_head {
481 response.set_body(EMPTY_STR);
482 } else {
483 response.set_body(file.bytes.as_ref());
484 }
485 true
486 }
487}
488
489impl StaticFilesPlugin {
491 pub fn init(config: StaticFilesConfig) -> Result<&'static Self, String> {
501 let runtime: StaticFilesRuntime = StaticFilesRuntime::new(config)?;
502 Ok(STATIC_FILES_PLUGIN.get_or_init(|| Self { runtime }))
503 }
504
505 pub fn get() -> Option<&'static Self> {
511 STATIC_FILES_PLUGIN.get()
512 }
513
514 pub fn get_runtime(&self) -> &StaticFilesRuntime {
520 &self.runtime
521 }
522}
523
524impl ServerHook for StaticFilesHook {
526 async fn new(_: &mut Stream, _: &mut Context) -> Self {
537 Self
538 }
539
540 async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
552 let Some(plugin) = StaticFilesPlugin::get() else {
553 return Status::Continue;
554 };
555 if plugin.get_runtime().serve_context(ctx).await {
556 let wire: ResponseData = ctx.get_mut_response().build();
557 let _: Result<(), ResponseError> = stream.try_send(&wire).await;
558 return Status::Reject;
559 }
560 Status::Continue
561 }
562}