use crate::common::{CompiledTest, FeatureCombination, invoke_and_capture_output};
use camino::Utf8Path;
use test_r::{test, test_dep};
#[path = "../../crates/wasm-rquickjs/skeleton/src/builtin/execution_timeout.rs"]
mod execution_timeout;
#[test]
fn timeout_sampler_uses_sparse_clock_reads() {
let started = std::time::Instant::now();
let timeout = std::time::Duration::from_secs(1);
let mut sampler =
execution_timeout::ExecutionTimeoutSampler::new(started, started + timeout, timeout);
let mut now = started;
let mut reads = 0;
for _ in 0..200_000 {
now += std::time::Duration::from_micros(10);
if sampler.expired(|| {
reads += 1;
now
}) {
assert!(now >= started + timeout);
assert!(reads <= 30, "too many clock reads: {reads}");
assert!(sampler.expired(|| panic!("expired sampler read the clock again")));
return;
}
}
panic!("continuing CPU work never observed the deadline");
}
#[test]
fn timeout_sampler_adapts_to_changed_interrupt_rate() {
let started = std::time::Instant::now();
let timeout = std::time::Duration::from_secs(1);
let mut sampler =
execution_timeout::ExecutionTimeoutSampler::new(started, started + timeout, timeout);
let mut now = started;
let mut reads = 0;
for interrupt in 0..200_000 {
now += std::time::Duration::from_micros(if interrupt < 50_000 { 10 } else { 100 });
if sampler.expired(|| {
reads += 1;
now
}) {
assert!(now >= started + timeout);
assert!(reads < 50, "too many clock reads: {reads}");
return;
}
}
panic!("continuing CPU work never observed the deadline after rate change");
}
#[test]
fn timeout_sampler_does_not_check_at_completion() {
let started = std::time::Instant::now();
let timeout = std::time::Duration::from_millis(1);
let mut sampler =
execution_timeout::ExecutionTimeoutSampler::new(started, started + timeout, timeout);
let mut reads = 0;
for _ in 0..63 {
assert!(!sampler.expired(|| {
reads += 1;
started + timeout * 2
}));
}
assert_eq!(reads, 0);
}
#[test_dep(tagged_as = "execution", scope = Cloneable)]
async fn compiled_execution() -> CompiledTest {
CompiledTest::new_with_features(
Utf8Path::new("examples/runtime/execution"),
true,
FeatureCombination::Normal,
)
.await
.expect("Failed to compile execution")
}
#[test]
async fn execution_isolation(
#[tagged_as("execution")] compiled: &CompiledTest,
) -> anyhow::Result<()> {
let (result, output) = invoke_and_capture_output(compiled.wasm_path(), None, "run", &[]).await;
let result = result?;
assert!(
output.is_empty(),
"nested output leaked to component stdio: {output}"
);
let Some(wasmtime::component::Val::String(json)) = result else {
anyhow::bail!("expected JSON string result, got {result:?}");
};
let report: serde_json::Value = serde_json::from_str(&json)?;
assert_eq!(report["liveStdout"], "live:first\nlive:last\n");
assert_eq!(report["liveStderr"], "live:warn\nlive:error\n");
assert_eq!(report["liveResult"]["value"]["label"], "live");
assert_eq!(report["liveResult"]["value"]["argv"][1], "live");
assert_eq!(
report["ordering"][0], "data",
"output was not delivered live"
);
assert_eq!(
report["ordering"].as_array().unwrap().last().unwrap(),
"result"
);
assert_eq!(report["streamedBeforeResult"], true);
assert_eq!(report["parentProgress"], true);
assert_eq!(report["left"]["value"], "left");
assert_eq!(report["left"]["stdout"], "left\n");
assert_eq!(report["right"]["value"], "right");
assert_eq!(report["right"]["stdout"], "right\n");
assert_eq!(
report["defaultEnvironment"]["value"]["keys"],
serde_json::json!([])
);
assert_eq!(
report["defaultEnvironment"]["value"]["parentSecret"],
serde_json::Value::Null
);
assert_eq!(
report["explicitEnvironment"]["value"]["keys"],
serde_json::json!(["ALLOWED"])
);
assert_eq!(report["explicitEnvironment"]["value"]["allowed"], "visible");
assert_eq!(
report["explicitEnvironment"]["value"]["parentSecret"],
serde_json::Value::Null
);
assert_eq!(report["packageCacheFirst"]["value"], "first");
assert_eq!(report["packageCacheSecond"]["value"], "second");
assert_eq!(report["timeoutSuccess"]["value"], "quick");
assert_eq!(report["timeoutError"], "execution job timed out");
assert_eq!(report["tightLoopTimeoutError"], "execution job timed out");
assert_eq!(
report["cpuBeforeSuspendTimeoutError"],
"execution job timed out"
);
assert!(
report["cpuBeforeSuspendElapsedMs"]
.as_u64()
.is_some_and(|elapsed| (300..650).contains(&elapsed)),
"timeout budget restarted after child suspension: {} ms",
report["cpuBeforeSuspendElapsedMs"]
);
assert_eq!(report["zeroTimeoutCode"], "ERR_INVALID_ARG_TYPE");
assert_eq!(report["hugeTimeoutCode"], "ERR_OUT_OF_RANGE");
for name in ["invalidEntry", "invalidSource"] {
assert_eq!(
report["invalidProgramOptions"][name], "ERR_INVALID_ARG_TYPE",
"unexpected validation result for {name}"
);
}
for name in ["invalidEntryWithSource", "invalidSourceWithEntry", "both"] {
assert_eq!(
report["invalidProgramOptions"][name], "exactly one of entry or source is required",
"unexpected exclusivity result for {name}"
);
}
assert_eq!(
report["overflowError"],
"execution output exceeded maxBytes"
);
assert_eq!(report["truncated"]["value"], "ok");
assert_eq!(report["truncated"]["stderr"], "éé");
assert_eq!(report["truncated"]["overflowed"], true);
assert_eq!(report["entry"]["value"]["kind"], "entry");
assert_eq!(
report["entry"]["value"]["argv"][0],
"wasm-rquickjs-execution"
);
assert_eq!(
report["entry"]["value"]["argv"][1],
"/tmp/execution-app/entry.mjs"
);
assert_eq!(
report["defaultArgv"]["value"],
serde_json::json!(["wasm-rquickjs-execution"])
);
assert_eq!(report["largeJavaScript"]["value"], "large-javascript");
assert_eq!(report["typescriptDisabled"], true);
assert!(
report["disabledStripError"]
.as_str()
.is_some_and(|message| message.contains("TypeScript runtime support is not enabled")),
"unexpected disabled strip error: {}",
report["disabledStripError"]
);
assert!(
report["disabledExecutionError"]
.as_str()
.is_some_and(|message| message.contains("TypeScript runtime support is not enabled")),
"unexpected disabled execution error: {}",
report["disabledExecutionError"]
);
assert_eq!(report["imports"]["value"]["local"], "local");
assert_eq!(report["imports"]["value"]["package"], "package");
assert_eq!(report["imports"]["value"]["json"], "json");
assert_eq!(report["imports"]["value"]["cjs"], "cjs");
assert_eq!(report["imports"]["value"]["afterChdir"], "local");
assert_eq!(report["imports"]["value"]["cwd"], "/tmp/execution-other");
assert_eq!(report["privateImport"]["value"], "ERR_MODULE_NOT_FOUND");
assert_eq!(
report["removedAliases"]["value"]["legacySpecifier"],
"ERR_MODULE_NOT_FOUND"
);
assert_eq!(
report["removedAliases"]["value"]["spawnJavaScript"],
"undefined"
);
for check in [
"hasUndefined",
"nan",
"infinity",
"negativeInfinity",
"negativeZero",
"zeroPairs",
"bigint",
"cycle",
"map",
"set",
"bytes",
"byteAliases",
] {
assert_eq!(report["cloneChecks"][check], true, "clone check {check}");
}
assert!(
report["resourceError"].as_str().is_some_and(
|message| message.contains("execution results cannot contain KeyObject values")
),
"unexpected resource error: {}",
report["resourceError"]
);
assert!(report["blobResultError"].as_str().is_some_and(|message| message.contains("execution results cannot contain Blob values")));
assert_eq!(report["environmentSnapshot"], true);
for kind in ["ReadableStream", "FileHandle"] {
assert!(
report["hostResultErrors"][kind]
.as_str()
.is_some_and(|message| message
.contains(&format!("execution results cannot contain {kind} values"))),
"{}",
report["hostResultErrors"]
);
}
assert_eq!(
report["clonePolicyIsolation"]["value"]["initiallyMarked"],
false
);
assert_eq!(report["clonePolicyIsolation"]["value"]["marked"], true);
assert_eq!(report["pathAliases"]["value"]["mode"], 0o611);
assert_eq!(report["pathAliases"]["value"]["link"], "./sub/../file.txt");
assert_eq!(
report["pathAliases"]["value"]["real"],
"/tmp/alias/file.txt"
);
assert_eq!(report["pathAliases"]["value"]["renamed"], "before");
assert_eq!(
report["persistentSymlinkCreated"]["value"]["absoluteError"],
"EINVAL"
);
assert_eq!(
report["persistentSymlinkCreated"]["value"]["absoluteExists"],
false
);
assert_eq!(
report["persistentSymlinkCreated"]["value"]["existingError"],
"EEXIST"
);
assert_eq!(
report["persistentSymlinkCreated"]["value"]["existingValue"],
"preserved"
);
assert_eq!(
report["persistentSymlinkCreated"]["value"]["missingParentError"],
"ENOENT"
);
assert_eq!(
report["persistentSymlinkCreated"]["value"]["parentFileError"],
"ENOTDIR"
);
assert_eq!(
report["persistentSymlinkCreated"]["value"]["relativeParentFileError"],
"ENOTDIR"
);
assert_eq!(
report["persistentSymlinkCreated"]["value"]["bareDestinationError"],
"EINVAL"
);
assert_eq!(
report["persistentSymlinkCreated"]["value"]["bareDestinationExists"],
false
);
assert_eq!(
report["persistentSymlinkRead"]["value"]["target"],
"target.txt"
);
assert_eq!(
report["persistentSymlinkRead"]["value"]["value"],
"persistent"
);
assert_eq!(
report["persistentSymlinkRead"]["value"]["realpath"],
"/tmp/persistent-link/target.txt"
);
assert_eq!(
report["persistentSymlinkRead"]["value"]["isSymbolicLink"],
true
);
assert_eq!(
report["persistentSymlinkEdges"]["value"]["brokenExists"],
false
);
assert_eq!(
report["persistentSymlinkEdges"]["value"]["brokenIsSymbolicLink"],
true
);
assert_eq!(
report["persistentSymlinkEdges"]["value"]["brokenTarget"],
"missing.txt"
);
assert_eq!(
report["persistentSymlinkEdges"]["value"]["cycleError"],
"ELOOP"
);
assert_eq!(
report["persistentSymlinkEdges"]["value"]["cycleDestinationError"],
"ELOOP"
);
assert_eq!(
report["persistentSymlinkEdges"]["value"]["recursiveNames"],
serde_json::json!([
"linked-target",
"linked-target/file.txt",
"target",
"target/file.txt"
])
);
for api in ["recursiveCallbackNames", "recursivePromiseNames"] {
assert_eq!(
report["persistentSymlinkEdges"]["value"][api],
serde_json::json!([
"linked-target",
"linked-target/file.txt",
"target",
"target/file.txt"
]),
"unexpected recursive entries for {api}"
);
}
assert_eq!(
report["persistentSymlinkEdges"]["value"]["recursiveWatcherIsFsWatcher"],
true
);
let recursive_watch_events = report["persistentSymlinkEdges"]["value"]["recursiveWatchEvents"]
.as_array()
.expect("recursive watch events should be an array");
assert!(
recursive_watch_events
.iter()
.any(|event| event == &serde_json::json!(["rename", "target/created.txt"])),
"recursive watcher should report the real nested path as a rename: {recursive_watch_events:?}"
);
assert!(
recursive_watch_events.iter().all(|event| !event
.get(1)
.and_then(serde_json::Value::as_str)
.is_some_and(|event| event.starts_with("self/"))),
"recursive watcher should not follow the self symlink: {recursive_watch_events:?}"
);
assert_eq!(
report["persistentSymlinkEdges"]["value"]["movedTarget"],
"target.txt"
);
assert_eq!(
report["persistentSymlinkEdges"]["value"]["movedExistsAfterUnlink"],
false
);
assert_eq!(report["cancellationError"], "execution job cancelled");
assert_eq!(
report["nested"]["value"],
"nested execution jobs are not supported"
);
assert_eq!(
report["capacityError"],
"execution supports at most 8 active jobs per runtime"
);
assert_eq!(report["reclaimed"]["value"], "reclaimed");
assert_eq!(
report["isolation"]["left"]["value"]["fd"],
report["isolation"]["right"]["value"]["fd"]
);
for side in ["left", "right"] {
let probe = &report["isolation"][side]["value"];
assert_eq!(probe["mode"], if side == "left" { 0o600 } else { 0o640 });
assert_eq!(probe["cwd"], format!("/tmp/execution-isolation-{side}"));
assert_eq!(probe["linkTarget"], "./target.txt");
assert_eq!(probe["linkValue"], format!("{side}:target"));
assert_eq!(probe["packageValue"], format!("{side}:package"));
assert_eq!(
report["isolation"][side]["stdout"],
format!("{side}:stdout\n")
);
assert_eq!(
report["isolation"][side]["stderr"],
format!("{side}:stderr\n")
);
}
assert_eq!(
report["isolation"]["left"]["value"]["secondFd"].as_i64(),
report["isolation"]["left"]["value"]["fd"]
.as_i64()
.map(|fd| fd + 1)
);
assert_eq!(
report["isolation"]["right"]["value"]["foreignFdError"],
"EBADF"
);
Ok(())
}