use std::sync::Arc;
use std::time::{Duration, Instant};
use serde_json::{Value, json};
use super::{Backend, CodeCache};
use crate::execution::Interrupt;
use crate::{Error, Limits, Module, Requirements, Result};
pub(crate) struct Startup<'a> {
source: &'a str,
check: Check,
code_cache: Option<Arc<CodeCache>>,
busy_timeout: Option<Duration>,
startup_timeout: Option<Duration>,
heap_bytes: Option<usize>,
}
impl<'a> Startup<'a> {
pub fn new(
module: &'a Module,
backend: &Backend,
code_cache: Arc<CodeCache>,
limits: &Limits,
) -> Self {
let requirements = module.requirements();
Self {
source: module.source(),
check: Check {
unmet: static_unmet(requirements, backend),
engine: backend.engine_name(),
probe: probe_script(requirements),
},
code_cache: Some(code_cache),
busy_timeout: limits.busy_timeout,
startup_timeout: limits.startup_timeout,
heap_bytes: limits.heap_bytes,
}
}
pub fn unchecked(source: &'a str) -> Self {
Self {
source,
check: Check {
unmet: Vec::new(),
engine: "",
probe: None,
},
code_cache: None,
busy_timeout: None,
startup_timeout: None,
heap_bytes: None,
}
}
pub fn source(&self) -> &'a str {
self.source
}
pub fn check(&self) -> &Check {
&self.check
}
pub fn interrupt(&self) -> Interrupt {
Interrupt::new(self.busy_timeout)
}
pub fn deadline(&self) -> Option<Instant> {
self.startup_timeout
.and_then(|timeout| Instant::now().checked_add(timeout))
}
#[cfg_attr(not(feature = "v8"), allow(dead_code))]
pub fn startup_timeout(&self) -> Option<Duration> {
self.startup_timeout
}
#[cfg_attr(not(any(feature = "quickjs", feature = "v8")), allow(dead_code))]
pub fn heap_bytes(&self) -> Option<usize> {
self.heap_bytes
}
#[cfg_attr(not(any(feature = "quickjs", feature = "v8")), allow(dead_code))]
pub fn code_cache(&self) -> Option<&Arc<CodeCache>> {
self.code_cache.as_ref()
}
}
#[derive(Clone)]
pub(crate) struct Check {
unmet: Vec<String>,
engine: &'static str,
probe: Option<String>,
}
impl Check {
pub fn probe(&self) -> Option<&str> {
self.probe.as_deref()
}
pub fn admit(&self, report: Option<&str>) -> Result<()> {
let mut missing = Vec::new();
if let Some(report) = report {
let engine: Vec<String> = serde_json::from_str(report).map_err(|_| {
Error::JavaScript("the engine probe returned an invalid report".into())
})?;
missing.extend(engine.into_iter().map(|api| format!("native {api}")));
}
missing.extend(self.unmet.iter().cloned());
if missing.is_empty() {
return Ok(());
}
let hint = if missing.iter().any(|item| item == "native WebAssembly") {
"enable the `v8` feature on `fetchlet` and run on `Backend::v8()` for WebAssembly, or remove the WebAssembly dependency"
} else {
"build the artifact for this engine, or change the host's engine or features"
};
Err(Error::Configuration(format!(
"the module needs {}, which this host's {} engine does not provide; {hint}",
list(&missing),
self.engine
)))
}
}
fn static_unmet(requirements: &Requirements, backend: &Backend) -> Vec<String> {
let mut unmet = Vec::new();
if requirements.needs_async_context() && !backend.has_async_context() {
unmet.push("async context".to_owned());
}
if requirements.needs_preemption()
&& let Err(gap) = backend.preemption()
{
unmet.push(format!("preemption ({gap})"));
}
let capabilities = fetchlet_web::capabilities();
let served: Vec<&str> = capabilities["apis"]
.as_array()
.map(|apis| apis.iter().filter_map(Value::as_str).collect())
.unwrap_or_default();
if let Some(version) = requirements.protocol()
&& version != fetchlet_web::PROTOCOL_VERSION
{
unmet.push(format!(
"fetchlet-web protocol {version} (this host speaks {})",
fetchlet_web::PROTOCOL_VERSION
));
}
for api in requirements.host_apis() {
if !served.contains(&api) {
unmet.push(format!("the {api} Web API"));
}
}
unmet
}
fn probe_script(requirements: &Requirements) -> Option<String> {
let apis: Vec<&str> = requirements.engine_apis().collect();
if apis.is_empty() {
return None;
}
let input = json!({ "apis": apis, "locales": requirements.locale_list() });
Some(format!(
r#"((input) => {{
const missing = [];
for (const api of input.apis) {{
let value = globalThis;
for (const key of api.split(".")) {{
value = value === undefined || value === null ? undefined : value[key];
}}
if (value === undefined || value === null) {{
missing.push(api);
continue;
}}
if (typeof value.supportedLocalesOf === "function") {{
const absent = input.locales.filter((locale) => value.supportedLocalesOf([locale]).length === 0);
if (absent.length > 0) {{
missing.push(api + " (" + absent.join(", ") + ")");
}}
}}
}}
return JSON.stringify(missing);
}})({input})"#
))
}
fn list(items: &[String]) -> String {
match items {
[] => String::new(),
[only] => only.clone(),
[rest @ .., last] => format!("{} and {last}", rest.join(", ")),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn lists_read_as_english() {
let items = |items: &[&str]| {
items
.iter()
.map(|item| (*item).to_owned())
.collect::<Vec<_>>()
};
assert_eq!(list(&items(&["a"])), "a");
assert_eq!(list(&items(&["a", "b"])), "a and b");
assert_eq!(list(&items(&["a", "b", "c"])), "a, b and c");
}
#[test]
fn a_module_without_requirements_needs_no_probe() {
let module = Module::new("");
let startup = Startup::unchecked(module.source());
assert!(startup.check().probe().is_none());
assert!(startup.check().admit(None).is_ok());
}
#[test]
fn missing_webassembly_mentions_v8_backend() {
let check = Check {
unmet: Vec::new(),
engine: "quickjs",
probe: None,
};
let error = check.admit(Some(r#"["WebAssembly"]"#)).unwrap_err();
let message = error.to_string();
assert!(message.contains("native WebAssembly"), "{message}");
assert!(message.contains("Backend::v8()"), "{message}");
}
}