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 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 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 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
390impl StaticFilesPlugin {
392 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 pub fn get() -> Option<&'static Self> {
412 STATIC_FILES_PLUGIN.get()
413 }
414
415 pub fn get_runtime(&self) -> &StaticFilesRuntime {
421 &self.runtime
422 }
423}
424
425impl ServerHook for StaticFilesHook {
427 async fn new(_: &mut Stream, _: &mut Context) -> Self {
438 Self
439 }
440
441 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}