1use std::borrow::Cow;
2use std::io;
3#[cfg(fetchlet_engine)]
4use std::num::NonZeroUsize;
5use std::path::{Component, Path, PathBuf};
6use std::sync::Arc;
7#[cfg(fetchlet_engine)]
8use std::time::Duration;
9
10use bytes::Bytes;
11use fetchlet::Requirements;
12#[cfg(fetchlet_engine)]
13use fetchlet::{App, AppBuilder, Backend, Limits, Module, WorkerOptions};
14use serde::Deserialize;
15
16use crate::assets::{AssetArchive, AssetArchiveError};
17
18#[cfg(fetchlet_engine)]
20pub(crate) const DEFAULT_QUEUE_CAPACITY: NonZeroUsize = NonZeroUsize::new(8).unwrap();
21
22#[cfg(fetchlet_engine)]
26pub(crate) const DEFAULT_WORKER_STACK_BYTES: NonZeroUsize =
27 NonZeroUsize::new(64 * 1024 * 1024).unwrap();
28
29#[cfg(fetchlet_engine)]
32pub(crate) const MINIMUM_STACK_FOR_DEFAULT_LIMITS: NonZeroUsize =
33 NonZeroUsize::new(8 * 1024 * 1024).unwrap();
34
35#[cfg(fetchlet_engine)]
37pub(crate) const DEFAULT_QUICKJS_STACK_BYTES: usize = 4 * 1024 * 1024;
38
39#[cfg(fetchlet_engine)]
41pub(crate) const DEFAULT_HEAP_BYTES: usize = 64 * 1024 * 1024;
42
43#[cfg(fetchlet_engine)]
45pub(crate) const DEFAULT_BUSY_TIMEOUT: Duration = Duration::from_secs(10);
46
47#[cfg(fetchlet_engine)]
49pub(crate) const DEFAULT_STARTUP_TIMEOUT: Duration = Duration::from_secs(60);
50
51#[cfg(fetchlet_engine)]
53pub(crate) const DEFAULT_BOA_STACK_SLOTS: usize = 128 * 1024;
54
55#[cfg(fetchlet_engine)]
57pub(crate) const DEFAULT_BOA_RECURSION: usize = 10_000;
58
59const FORMAT: &str = "fetchlet-iife";
61const FORMAT_VERSION: u32 = 1;
62
63#[derive(Clone, Debug)]
73pub struct Artifact {
74 source: Source,
75 manifest: Manifest,
76 assets: Option<Arc<AssetArchive>>,
77}
78
79#[derive(Clone, Debug)]
80enum Source {
81 Directory(PathBuf),
82 Embedded { server: Cow<'static, str> },
83}
84
85#[derive(Clone, Debug, Deserialize)]
86#[serde(rename_all = "camelCase")]
87struct Manifest {
88 format: String,
89 format_version: u32,
90 handler: Option<String>,
91 functions: Option<Vec<String>>,
92 server: String,
93 client: Option<String>,
94 assets: Option<String>,
95 backend: Option<String>,
96 needs: Option<Needs>,
98 #[serde(default)]
100 native_requirements: Vec<String>,
101 intl: Option<Intl>,
102 async_context: Option<String>,
103}
104
105#[derive(Clone, Debug, Default, Deserialize)]
107#[serde(rename_all = "camelCase", default)]
108struct Needs {
109 engine_apis: Vec<String>,
110 locales: Vec<String>,
111 async_context: bool,
112 host_apis: Vec<String>,
113 host_protocol: Option<u32>,
114}
115
116#[derive(Clone, Debug, Default, Deserialize)]
117#[serde(default)]
118struct Intl {
119 locales: Vec<String>,
120}
121
122#[derive(Debug, thiserror::Error)]
124pub enum ArtifactError {
125 #[error("could not read {path}: {source}")]
126 Read { path: PathBuf, source: io::Error },
127 #[error("invalid manifest {path}: {source}")]
128 Manifest {
129 path: PathBuf,
130 source: serde_json::Error,
131 },
132 #[error("unsupported artifact {path}: {reason}")]
133 Unsupported { path: PathBuf, reason: String },
134 #[error("invalid asset archive {path}: {source}")]
135 Assets {
136 path: PathBuf,
137 source: AssetArchiveError,
138 },
139 #[cfg(fetchlet_engine)]
140 #[error("could not configure backend: {0}")]
141 Backend(#[from] fetchlet::Error),
142}
143
144const EMBEDDED: &str = "<embedded>";
146
147impl Artifact {
148 pub fn open(directory: impl Into<PathBuf>) -> Result<Self, ArtifactError> {
150 let directory = directory.into();
151 let path = directory.join("fetchlet.json");
152 let source = std::fs::read(&path).map_err(|source| ArtifactError::Read {
153 path: path.clone(),
154 source,
155 })?;
156 let manifest = parse_manifest(&source, &path)?;
157 let assets = match &manifest.assets {
158 Some(file) => {
159 let path = directory.join(file);
160 let archive = AssetArchive::open(&path)
161 .map_err(|source| ArtifactError::Assets { path, source })?;
162 Some(Arc::new(archive))
163 }
164 None => None,
165 };
166 Ok(Self {
167 source: Source::Directory(directory),
168 manifest,
169 assets,
170 })
171 }
172
173 pub fn embedded(
178 manifest: &[u8],
179 server: impl Into<Cow<'static, str>>,
180 assets: Option<Bytes>,
181 ) -> Result<Self, ArtifactError> {
182 let path = Path::new(EMBEDDED).join("fetchlet.json");
183 let manifest = parse_manifest(manifest, &path)?;
184 let assets = match (&manifest.assets, assets) {
185 (Some(file), Some(bytes)) => {
186 let archive = AssetArchive::new(bytes).map_err(|source| ArtifactError::Assets {
187 path: Path::new(EMBEDDED).join(file),
188 source,
189 })?;
190 Some(Arc::new(archive))
191 }
192 (Some(file), None) => {
193 return Err(ArtifactError::Unsupported {
194 path,
195 reason: format!("the manifest names {file}, which was not embedded"),
196 });
197 }
198 (None, _) => None,
199 };
200 Ok(Self {
201 source: Source::Embedded {
202 server: server.into(),
203 },
204 manifest,
205 assets,
206 })
207 }
208
209 pub fn directory(&self) -> Option<&Path> {
211 match &self.source {
212 Source::Directory(directory) => Some(directory),
213 Source::Embedded { .. } => None,
214 }
215 }
216
217 pub fn handler(&self) -> Option<&str> {
221 self.manifest.handler.as_deref()
222 }
223
224 pub fn functions(&self) -> Option<&[String]> {
227 self.manifest.functions.as_deref()
228 }
229
230 pub fn backend(&self) -> Option<&str> {
232 self.manifest.backend.as_deref()
233 }
234
235 pub fn requirements(&self) -> Requirements {
248 let manifest = &self.manifest;
249 let needs = match &manifest.needs {
250 Some(needs) => needs.clone(),
251 None => Needs {
252 engine_apis: manifest.native_requirements.clone(),
253 locales: manifest
254 .intl
255 .as_ref()
256 .map(|intl| intl.locales.clone())
257 .unwrap_or_default(),
258 async_context: manifest.async_context.as_deref() == Some("propagated"),
259 ..Needs::default()
260 },
261 };
262 let mut requirements = Requirements::new().locales(needs.locales);
263 for api in needs.engine_apis {
264 requirements = requirements.engine_api(api);
265 }
266 if needs.async_context {
267 requirements = requirements.async_context();
268 }
269 for api in needs.host_apis {
270 requirements = requirements.host_api(api);
271 }
272 if let Some(version) = needs.host_protocol {
273 requirements = requirements.host_protocol(version);
274 }
275 requirements
276 }
277
278 pub fn server_path(&self) -> Option<PathBuf> {
280 self.directory()
281 .map(|directory| directory.join(&self.manifest.server))
282 }
283
284 pub fn server_source(&self) -> Result<String, ArtifactError> {
286 match &self.source {
287 Source::Directory(directory) => {
288 let path = directory.join(&self.manifest.server);
289 std::fs::read_to_string(&path)
290 .map_err(|source| ArtifactError::Read { path, source })
291 }
292 Source::Embedded { server } => Ok(server.clone().into_owned()),
293 }
294 }
295
296 pub fn client_directory(&self) -> Option<PathBuf> {
299 let client = self.manifest.client.as_ref()?;
300 self.directory().map(|directory| directory.join(client))
301 }
302
303 pub fn asset_archive(&self) -> Option<&Arc<AssetArchive>> {
306 self.assets.as_ref()
307 }
308
309 #[cfg(fetchlet_engine)]
312 pub fn default_worker_options() -> WorkerOptions {
313 let mut worker = WorkerOptions::new(DEFAULT_QUEUE_CAPACITY);
314 worker.stack_size_bytes = Some(DEFAULT_WORKER_STACK_BYTES);
315 worker
316 }
317
318 #[cfg(fetchlet_engine)]
321 pub fn default_limits() -> Limits {
322 Limits {
323 busy_timeout: Some(DEFAULT_BUSY_TIMEOUT),
324 startup_timeout: Some(DEFAULT_STARTUP_TIMEOUT),
325 ..Limits::default()
326 }
327 }
328
329 #[cfg(fetchlet_engine)]
333 pub fn default_backend(&self) -> fetchlet::Result<Backend> {
334 let backend = Backend::for_target(self.backend().unwrap_or("portable"))?;
335 Ok(backend
336 .with_default_quickjs_stack(DEFAULT_QUICKJS_STACK_BYTES)
337 .with_default_boa_stack(DEFAULT_BOA_STACK_SLOTS, DEFAULT_BOA_RECURSION))
338 }
339
340 #[cfg(fetchlet_engine)]
349 pub fn app_builder(&self) -> Result<AppBuilder, ArtifactError> {
350 let backend = self.default_backend()?;
351 self.app_builder_with(backend)
352 }
353
354 #[cfg(fetchlet_engine)]
358 pub fn app_builder_with(&self, backend: Backend) -> Result<AppBuilder, ArtifactError> {
359 let mut limits = Self::default_limits();
360 if backend.bounds_heap() {
361 limits.heap_bytes = Some(DEFAULT_HEAP_BYTES);
362 }
363 let mut builder = App::builder(backend)
364 .module(Module::new(self.server_source()?).requires(self.requirements()))
365 .fetch_handler(self.handler())
366 .limits(limits);
367 #[cfg(any(
368 feature = "axum",
369 feature = "actix",
370 feature = "dev-reload",
371 feature = "vite-dev"
372 ))]
373 if let Ok(runtime) = tokio::runtime::Handle::try_current()
374 && runtime.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread
375 {
376 builder = builder.host_runtime(runtime);
377 }
378 Ok(builder)
379 }
380}
381
382fn parse_manifest(source: &[u8], path: &Path) -> Result<Manifest, ArtifactError> {
383 let manifest: Manifest =
384 serde_json::from_slice(source).map_err(|source| ArtifactError::Manifest {
385 path: path.to_owned(),
386 source,
387 })?;
388 let unsupported = |reason: String| ArtifactError::Unsupported {
389 path: path.to_owned(),
390 reason,
391 };
392 if manifest.format != FORMAT || manifest.format_version != FORMAT_VERSION {
393 return Err(unsupported(format!(
394 "format {} version {}; expected {FORMAT} version {FORMAT_VERSION}",
395 manifest.format, manifest.format_version
396 )));
397 }
398 for file in std::iter::once(&manifest.server)
399 .chain(&manifest.client)
400 .chain(&manifest.assets)
401 {
402 if !is_contained(Path::new(file)) {
403 return Err(unsupported(format!("{file} is outside the artifact")));
404 }
405 }
406 Ok(manifest)
407}
408
409fn is_contained(path: &Path) -> bool {
411 path.components()
412 .all(|component| matches!(component, Component::Normal(_) | Component::CurDir))
413}
414
415#[macro_export]
425macro_rules! include_artifact {
426 ($directory:expr) => {
427 $crate::Artifact::embedded(
428 ::core::include_bytes!(::core::concat!($directory, "/fetchlet.json")),
429 ::core::include_str!(::core::concat!($directory, "/server.js")),
430 ::core::option::Option::Some($crate::__private::Bytes::from_static(
431 ::core::include_bytes!(::core::concat!($directory, "/assets.flpk")),
432 )),
433 )
434 };
435}
436
437#[cfg(test)]
438mod tests {
439 use super::*;
440
441 fn manifest(fields: &str) -> Vec<u8> {
442 format!(r#"{{"format":"fetchlet-iife","formatVersion":1,"handler":"handle",{fields}}}"#)
443 .into_bytes()
444 }
445
446 fn reason(source: &[u8]) -> String {
447 match parse_manifest(source, Path::new("fetchlet.json")) {
448 Err(ArtifactError::Unsupported { reason, .. }) => reason,
449 other => panic!("expected an unsupported manifest, got {other:?}"),
450 }
451 }
452
453 #[test]
454 fn manifest_paths_stay_inside_the_artifact() {
455 for path in ["server.js", "./server.js", "nested/server.js", "a/./b"] {
456 assert!(is_contained(Path::new(path)), "{path}");
457 }
458 for path in ["../server.js", "a/../b", "/server.js"] {
459 assert!(!is_contained(Path::new(path)), "{path}");
460 }
461 #[cfg(windows)]
462 for path in [r"C:\server.js", r"\\host\share\server.js", r"C:server.js"] {
463 assert!(!is_contained(Path::new(path)), "{path}");
464 }
465 }
466
467 #[test]
468 fn every_named_file_is_checked() {
469 assert_eq!(
470 reason(&manifest(
471 r#""server":"server.js","assets":"../assets.flpk""#
472 )),
473 "../assets.flpk is outside the artifact"
474 );
475 assert_eq!(
476 reason(&manifest(r#""server":"server.js","client":"/srv/public""#)),
477 "/srv/public is outside the artifact"
478 );
479 }
480
481 #[test]
482 fn the_format_and_its_version_must_match() {
483 let other = br#"{"format":"esm","formatVersion":1,"handler":"handle","server":"s.js"}"#;
484 assert_eq!(
485 reason(other),
486 "format esm version 1; expected fetchlet-iife version 1"
487 );
488 }
489
490 #[test]
491 fn required_fields_are_checked_and_optional_ones_may_be_absent() {
492 assert!(matches!(
493 parse_manifest(
494 &manifest(r#""client":"client""#),
495 Path::new("fetchlet.json")
496 ),
497 Err(ArtifactError::Manifest { .. })
498 ));
499 let parsed = parse_manifest(
500 &manifest(r#""server":"server.js","framework":"astro""#),
501 Path::new("fetchlet.json"),
502 )
503 .unwrap();
504 assert_eq!(parsed.server, "server.js");
505 assert!(parsed.client.is_none() && parsed.assets.is_none() && parsed.backend.is_none());
506 }
507
508 #[test]
509 fn an_artifact_of_functions_only_has_no_handler() {
510 let source = br#"{"format":"fetchlet-iife","formatVersion":1,"handler":null,"functions":["greet"],"server":"server.js"}"#;
511 let artifact = Artifact::embedded(source, "", None).unwrap();
512 assert_eq!(artifact.handler(), None);
513 assert_eq!(artifact.functions(), Some(&["greet".to_owned()][..]));
514 let older = Artifact::embedded(&manifest(r#""server":"server.js""#), "", None).unwrap();
515 assert_eq!(older.handler(), Some("handle"));
516 assert_eq!(older.functions(), None);
517 }
518
519 fn requirements(fields: &str) -> Requirements {
520 Artifact::embedded(
521 &manifest(&format!(r#""server":"server.js"{fields}"#)),
522 "",
523 None,
524 )
525 .unwrap()
526 .requirements()
527 }
528
529 #[test]
530 fn requirements_come_from_needs_or_the_older_fields() {
531 assert!(requirements("").is_empty());
532 assert_eq!(
533 requirements(
534 r#","nativeRequirements":["Intl.DateTimeFormat"],"intl":{"locales":["en","ja"],"timeZoneData":"utc"},"asyncContext":"propagated""#
535 ),
536 Requirements::new()
537 .engine_api("Intl.DateTimeFormat")
538 .locales(["en", "ja"])
539 .async_context()
540 );
541 assert!(requirements(r#","nativeRequirements":[],"asyncContext":"serialized""#).is_empty());
542 assert_eq!(
544 requirements(
545 r#","nativeRequirements":["Intl.Locale"],"needs":{"engineApis":["Intl.NumberFormat"],"locales":["en"],"asyncContext":false,"hostApis":["crypto"],"hostProtocol":3}"#
546 ),
547 Requirements::new()
548 .engine_api("Intl.NumberFormat")
549 .locales(["en"])
550 .host_api("crypto")
551 .host_protocol(3)
552 );
553 }
554
555 #[test]
556 fn an_embedded_artifact_needs_the_archive_its_manifest_names() {
557 let source = manifest(r#""server":"server.js","assets":"assets.flpk""#);
558 match Artifact::embedded(&source, "export const handle = 1;", None) {
559 Err(ArtifactError::Unsupported { reason, .. }) => {
560 assert_eq!(
561 reason,
562 "the manifest names assets.flpk, which was not embedded"
563 );
564 }
565 other => panic!("expected a missing archive, got {other:?}"),
566 }
567 let artifact = Artifact::embedded(
568 &manifest(r#""server":"server.js","client":"client""#),
569 "export const handle = 1;",
570 Some(Bytes::from_static(b"ignored without a manifest entry")),
571 )
572 .unwrap();
573 assert!(artifact.asset_archive().is_none());
574 assert!(artifact.directory().is_none());
575 assert!(artifact.client_directory().is_none());
576 assert!(artifact.server_path().is_none());
577 assert_eq!(
578 artifact.server_source().unwrap(),
579 "export const handle = 1;"
580 );
581 }
582}