diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml
index 9f149872..ae34acdf 100644
--- a/.github/workflows/ci.yaml
+++ b/.github/workflows/ci.yaml
@@ -212,7 +212,7 @@ jobs:
suite: [generation, async-values]
include:
- suite: generation
- test_args: --test p3_generation --test p3_exported_resource
+ test_args: --test p3_generation --test p3_exported_resource --test p3_import_abort
- suite: async-values
# Each case creates its own Tokio runtime and compiles a Wasmtime
# component inside the timeout. Bound competing compiler/runtime pools.
diff --git a/README.md b/README.md
index 26218df9..bd0ba1e0 100644
--- a/README.md
+++ b/README.md
@@ -1034,6 +1034,34 @@ nothing for it.
+
+wasm-rquickjs:import-abort
+
+Lets JavaScript stop waiting for an async import and drop its component-model subtask. For worlds
+with async imports `generate-dts` also writes `wasm-rquickjs-import-abort.d.ts`. Keep the module
+external when bundling.
+
+- `withSignal(signal, fn)` makes `signal` current while `fn` runs synchronously, then restores
+ the previous signal, and returns what `fn` returns. `undefined` and `null` clear the current
+ signal. Any object with `aborted`, `reason`, `addEventListener` and `removeEventListener`, such
+ as an `AbortSignal`, works.
+
+Every async import that is called while a signal is current takes the signal with it, including
+resource methods and static resource functions. When the signal aborts before the import
+finishes, the import's promise rejects with `signal.reason`, and the runtime drops the import:
+the host cancels the call or sees that its caller stopped waiting. A signal that is already
+aborted rejects without starting the import, and the import does not start when the signal aborts
+before the runtime first polls it. The runtime still converts the other arguments from JavaScript
+when the import is called, and drops them when the import does not start: each owned resource
+passed to the import is destroyed. A `future` or `stream` argument is not lowered when the signal
+is already aborted, so its JavaScript source is not read. A `future` or `stream` argument lowered
+before the signal aborts is closed, and the runtime calls `return()` on the iterator of a
+JavaScript stream source when the host stops reading. An import that finished
+keeps its result when the signal aborts later. Imports that `fn` starts after an `await` do not
+take the signal, so pass the signal again in each continuation that starts an import.
+
+
+
node:inspector (stub)
diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/import_abort.js b/crates/wasm-rquickjs/skeleton/src/builtin/import_abort.js
new file mode 100644
index 00000000..7b94302a
--- /dev/null
+++ b/crates/wasm-rquickjs/skeleton/src/builtin/import_abort.js
@@ -0,0 +1,23 @@
+// wasm-rquickjs:import-abort
+//
+// The abort signal of generated async imports. `withSignal(signal, fn)` makes `signal` current
+// while `fn` runs synchronously. Every async import that JavaScript calls meanwhile takes the
+// signal with it: when the signal aborts before the import finishes, the import's promise rejects
+// with `signal.reason` and the runtime drops the import, which cancels its component-model
+// subtask.
+import * as native from '__wasm_rquickjs_builtin/import_abort_native';
+
+/**
+ * Calls `fn` with `signal` current, then restores the previous signal. `undefined` and `null`
+ * clear the current signal.
+ */
+export function withSignal(signal, fn) {
+ const previous = native.enter(signal);
+ try {
+ return fn();
+ } finally {
+ native.leave(previous);
+ }
+}
+
+export default { withSignal };
diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/import_abort.rs b/crates/wasm-rquickjs/skeleton/src/builtin/import_abort.rs
new file mode 100644
index 00000000..d8ee9f41
--- /dev/null
+++ b/crates/wasm-rquickjs/skeleton/src/builtin/import_abort.rs
@@ -0,0 +1,17 @@
+pub const IMPORT_ABORT_JS: &str = include_str!("import_abort.js");
+
+#[rquickjs::module]
+pub mod native_module {
+ use crate::internal::import_abort;
+ use rquickjs::{Ctx, Value};
+
+ #[rquickjs::function]
+ pub fn enter<'js>(ctx: Ctx<'js>, signal: Value<'js>) -> Option> {
+ import_abort::enter(&ctx, signal)
+ }
+
+ #[rquickjs::function]
+ pub fn leave<'js>(ctx: Ctx<'js>, previous: Option>) {
+ import_abort::leave(&ctx, previous)
+ }
+}
diff --git a/crates/wasm-rquickjs/skeleton/src/builtin/mod.rs b/crates/wasm-rquickjs/skeleton/src/builtin/mod.rs
index be67dcd0..90a94ca2 100644
--- a/crates/wasm-rquickjs/skeleton/src/builtin/mod.rs
+++ b/crates/wasm-rquickjs/skeleton/src/builtin/mod.rs
@@ -8,6 +8,7 @@ use sync_exports::SyncableBuiltinLoaderExt;
mod abort_controller;
mod abort_signal;
+pub(crate) use abort_signal::with_abort_signal;
mod assert;
mod async_hooks;
mod base64;
@@ -28,6 +29,7 @@ pub(crate) mod execution;
mod formdata_node;
mod fs;
mod gc;
+mod import_abort;
#[cfg(feature = "test-observability")]
pub(crate) use gc::install_observability as install_gc_observability;
mod http;
@@ -296,6 +298,8 @@ pub fn add_module_resolvers(
.with_module("__wasm_rquickjs_builtin/execution_native")
.with_module("__wasm_rquickjs_builtin/custom_invocation_context_native")
.with_module("wasm-rquickjs:custom-invocation-context")
+ .with_module("__wasm_rquickjs_builtin/import_abort_native")
+ .with_module("wasm-rquickjs:import-abort")
.with_module("wasm-rquickjs:execution")
.with_module("__wasm_rquickjs_builtin/typescript_native");
@@ -404,6 +408,10 @@ pub fn module_loader() -> (
.with_module(
"__wasm_rquickjs_builtin/custom_invocation_context_native",
custom_invocation_context::js_native_module,
+ )
+ .with_module(
+ "__wasm_rquickjs_builtin/import_abort_native",
+ import_abort::js_native_module,
);
let native_loader = native_loader.with_module(
"__wasm_rquickjs_builtin/typescript_native",
@@ -619,7 +627,8 @@ pub fn module_loader() -> (
.with_module(
"wasm-rquickjs:custom-invocation-context",
custom_invocation_context::CUSTOM_INVOCATION_CONTEXT_JS,
- );
+ )
+ .with_module("wasm-rquickjs:import-abort", import_abort::IMPORT_ABORT_JS);
#[cfg(feature = "golem")]
let builtin_loader = builtin_loader.with_module(
diff --git a/crates/wasm-rquickjs/skeleton/src/internal/import_abort.rs b/crates/wasm-rquickjs/skeleton/src/internal/import_abort.rs
new file mode 100644
index 00000000..7065fa84
--- /dev/null
+++ b/crates/wasm-rquickjs/skeleton/src/internal/import_abort.rs
@@ -0,0 +1,164 @@
+//! The abort signal of generated async imports (`wasm-rquickjs:import-abort`).
+//!
+//! `withSignal(signal, fn)` makes `signal` current while `fn` runs synchronously. Every generated
+//! async import bridge that JavaScript calls meanwhile takes the current signal with it. When the
+//! signal aborts before the import finishes, the import's promise rejects with `signal.reason`
+//! and the bridge drops the import future. Dropping a started import cancels its component-model
+//! subtask, so the host stops the call or learns that its caller stopped waiting.
+
+use rquickjs::{Ctx, JsLifetime, Value};
+use std::cell::RefCell;
+use std::future::Future;
+
+/// Per-runtime state: the signal that async imports called now take with them.
+#[derive(JsLifetime)]
+pub(crate) struct ImportSignal<'js> {
+ current: RefCell>>,
+}
+
+pub(crate) fn initialize(ctx: &Ctx<'_>) -> rquickjs::Result<()> {
+ ctx.store_userdata(ImportSignal {
+ current: RefCell::new(None),
+ })
+ .expect("Failed to initialize import abort state");
+ Ok(())
+}
+
+fn state<'a, 'js>(ctx: &'a Ctx<'js>) -> rquickjs::runtime::UserDataGuard<'a, ImportSignal<'js>> {
+ ctx.userdata::()
+ .expect("import abort state not initialized")
+}
+
+/// Makes `signal` current and returns the signal that was current. `undefined` and `null` clear
+/// it.
+pub(crate) fn enter<'js>(ctx: &Ctx<'js>, signal: Value<'js>) -> Option> {
+ let signal = (!signal.is_undefined() && !signal.is_null()).then_some(signal);
+ state(ctx).current.replace(signal)
+}
+
+/// Restores the signal that [`enter`] returned.
+pub(crate) fn leave<'js>(ctx: &Ctx<'js>, previous: Option>) {
+ state(ctx).current.replace(previous);
+}
+
+fn current<'js>(ctx: &Ctx<'js>) -> Option> {
+ state(ctx).current.borrow().clone()
+}
+
+/// The JavaScript promise a generated async import bridge returns.
+pub type AbortableImport<'js, T> =
+ super::custom_invocation_context::ScopedImport<'js, rquickjs::Result>;
+
+/// Builds the result of a generated async import bridge. The bridge calls it in the synchronous
+/// part of the JavaScript call, so the import runs in the scope of its caller and takes the
+/// signal that is current now. A signal that is already aborted when the import would start
+/// rejects the promise without starting the import.
+pub fn abortable_import<'js, T: 'js>(
+ ctx: &Ctx<'js>,
+ future: impl Future> + 'js,
+) -> AbortableImport<'js, T> {
+ match current(ctx) {
+ None => super::custom_invocation_context::scoped_import(future),
+ Some(signal) => {
+ let ctx = ctx.clone();
+ super::custom_invocation_context::scoped_import(async move {
+ crate::builtin::with_abort_signal(&ctx, Some(signal), future).await
+ })
+ }
+ }
+}
+
+/// The signal a deferred import bridge (an async import with `future` / `stream`
+/// parameters) takes with it. Its import runs on its own task, so the bridge registers the abort
+/// listener while a `Ctx` is available and aborts the task's import future from it.
+pub struct DeferredImportSignal {
+ signal: rquickjs::Persistent>,
+ callback: rquickjs::Persistent>,
+}
+
+/// The signal that is current when a deferred import bridge is called.
+pub enum DeferredImportAbort<'js> {
+ /// No signal is current.
+ None,
+ /// The signal already aborted: the bridge rejects with this reason, lowers no parameter and
+ /// starts no import.
+ Aborted(Value<'js>),
+ /// The bridge lowers its parameters, then arms the signal with [`arm_deferred_import_abort`].
+ Current(rquickjs::Object<'js>),
+}
+
+/// What a deferred import bridge does after it lowered its parameters.
+pub enum ArmedImportAbort<'js> {
+ /// The signal aborted while the parameters were lowered: the bridge rejects with this reason
+ /// and starts no import.
+ Aborted(Value<'js>),
+ /// The import future must run inside `futures::future::Abortable` with this registration.
+ Armed(DeferredImportSignal, futures::future::AbortRegistration),
+}
+
+/// Takes the current signal for a deferred import bridge.
+pub fn deferred_import_abort<'js>(ctx: &Ctx<'js>) -> rquickjs::Result> {
+ let Some(signal) = current(ctx) else {
+ return Ok(DeferredImportAbort::None);
+ };
+ let signal = rquickjs::Object::from_value(signal)?;
+ if signal.get::<_, bool>("aborted")? {
+ return Ok(DeferredImportAbort::Aborted(signal.get("reason")?));
+ }
+ Ok(DeferredImportAbort::Current(signal))
+}
+
+/// Registers the abort listener of a deferred import. The bridge calls it after it lowered its
+/// parameters and before it starts the import, so a lowering error leaves no listener on the
+/// signal, and an abort that arrives before the import starts still prevents the import.
+///
+/// The signal can abort while `addEventListener` runs, before the listener is registered, so
+/// `aborted` is checked again afterwards. In that case the listener is removed again.
+pub fn arm_deferred_import_abort<'js>(
+ ctx: &Ctx<'js>,
+ signal: rquickjs::Object<'js>,
+) -> rquickjs::Result> {
+ use rquickjs::function::This;
+ if signal.get::<_, bool>("aborted")? {
+ return Ok(ArmedImportAbort::Aborted(signal.get("reason")?));
+ }
+ let (handle, registration) = futures::future::AbortHandle::new_pair();
+ let callback = rquickjs::Function::new(ctx.clone(), move || handle.abort())?;
+ let options = rquickjs::Object::new(ctx.clone())?;
+ options.set("once", true)?;
+ let add: rquickjs::Function = signal.get("addEventListener")?;
+ add.call::<_, ()>((This(signal.clone()), "abort", callback.clone(), options))?;
+ if signal.get::<_, bool>("aborted")? {
+ let remove: rquickjs::Function = signal.get("removeEventListener")?;
+ let _ = remove.call::<_, ()>((This(signal.clone()), "abort", callback));
+ return Ok(ArmedImportAbort::Aborted(signal.get("reason")?));
+ }
+ Ok(ArmedImportAbort::Armed(
+ DeferredImportSignal {
+ signal: rquickjs::Persistent::save(ctx, signal),
+ callback: rquickjs::Persistent::save(ctx, callback),
+ },
+ registration,
+ ))
+}
+
+impl DeferredImportSignal {
+ /// Removes the abort listener once the import settled. Returns the signal's reason when the
+ /// import was aborted.
+ pub fn finish<'js>(
+ self,
+ ctx: &Ctx<'js>,
+ aborted: bool,
+ ) -> rquickjs::Result>> {
+ use rquickjs::function::This;
+ let signal = self.signal.restore(ctx)?;
+ let callback = self.callback.restore(ctx)?;
+ let remove: rquickjs::Function = signal.get("removeEventListener")?;
+ let _ = remove.call::<_, ()>((This(signal.clone()), "abort", callback));
+ if aborted {
+ Ok(Some(signal.get("reason")?))
+ } else {
+ Ok(None)
+ }
+ }
+}
diff --git a/crates/wasm-rquickjs/skeleton/src/internal/mod.rs b/crates/wasm-rquickjs/skeleton/src/internal/mod.rs
index 9b3e85a7..159f158b 100644
--- a/crates/wasm-rquickjs/skeleton/src/internal/mod.rs
+++ b/crates/wasm-rquickjs/skeleton/src/internal/mod.rs
@@ -7,6 +7,7 @@
pub mod custom_invocation_context;
pub(crate) mod error_formatting;
+pub mod import_abort;
pub mod invocation;
pub(crate) mod module_loading;
pub(crate) mod preinit;
diff --git a/crates/wasm-rquickjs/skeleton/src/internal/runtime_services.rs b/crates/wasm-rquickjs/skeleton/src/internal/runtime_services.rs
index 55b94073..d0c063fc 100644
--- a/crates/wasm-rquickjs/skeleton/src/internal/runtime_services.rs
+++ b/crates/wasm-rquickjs/skeleton/src/internal/runtime_services.rs
@@ -755,6 +755,7 @@ impl OwnedJsRuntime {
super::error_formatting::initialize(&ctx)?;
super::promise_hook::initialize(&ctx);
super::custom_invocation_context::initialize(&ctx)?;
+ super::import_abort::initialize(&ctx)?;
// The invocation whose work runs now, for queues kept in JavaScript such as
// `process.nextTick`.
ctx.globals().set(
diff --git a/crates/wasm-rquickjs/src/import_abort.d.ts b/crates/wasm-rquickjs/src/import_abort.d.ts
new file mode 100644
index 00000000..b2d011c2
--- /dev/null
+++ b/crates/wasm-rquickjs/src/import_abort.d.ts
@@ -0,0 +1,25 @@
+/**
+ * The abort signal of generated async imports.
+ *
+ * `withSignal(signal, fn)` makes `signal` current while `fn` runs synchronously. Every async
+ * import that is called meanwhile takes the signal with it. When the signal aborts before the
+ * import finishes, the import's promise rejects with `signal.reason` and the runtime drops the
+ * import, which cancels its component-model subtask: the host stops the call or learns that its
+ * caller stopped waiting. A signal that is already aborted rejects without starting the import.
+ * Imports that `fn` starts after an `await` do not take the signal.
+ */
+declare module 'wasm-rquickjs:import-abort' {
+ /** The part of `AbortSignal` the runtime uses. */
+ export interface ImportSignal {
+ readonly aborted: boolean;
+ readonly reason: unknown;
+ addEventListener(type: 'abort', listener: () => void, options?: { once?: boolean }): void;
+ removeEventListener(type: 'abort', listener: () => void): void;
+ }
+
+ /**
+ * Calls `fn` with `signal` current, then restores the previous signal. `undefined` and `null`
+ * clear the current signal.
+ */
+ export function withSignal(signal: ImportSignal | undefined | null, fn: () => T): T;
+}
diff --git a/crates/wasm-rquickjs/src/imports.rs b/crates/wasm-rquickjs/src/imports.rs
index 6538ec8a..01e6dff6 100644
--- a/crates/wasm-rquickjs/src/imports.rs
+++ b/crates/wasm-rquickjs/src/imports.rs
@@ -247,23 +247,42 @@ fn build_freestanding_import_bridge(
}
// An async bridge is a synchronous JS function that returns a promise. It builds the import
- // future during the JS call, so the import runs in the caller's custom invocation context
- // (see `crate::internal::custom_invocation_context::scoped_import`).
+ // future during the JS call, so the import runs in the caller's custom invocation context and
+ // takes the current import signal (see `crate::internal::import_abort::abortable_import`).
let maybe_await = if is_async {
quote! { .await }
} else {
quote! {}
};
- let returns = |ty: TokenStream| {
+ // An async bridge returns `AbortableImport<'js, T>` for a body that evaluates to
+ // `rquickjs::Result`; a synchronous bridge returns the body's own type.
+ let returns_result = |ty: TokenStream| {
if is_async {
- quote! { crate::internal::custom_invocation_context::ScopedImport<'js, #ty> }
+ quote! { crate::internal::import_abort::AbortableImport<'js, #ty> }
+ } else {
+ quote! { rquickjs::Result<#ty> }
+ }
+ };
+ let returns_plain = |ty: TokenStream| {
+ if is_async {
+ quote! { crate::internal::import_abort::AbortableImport<'js, #ty> }
} else {
ty
}
};
+ let plain_body = |value: TokenStream| {
+ if is_async {
+ quote! { Ok(#value) }
+ } else {
+ value
+ }
+ };
let body = |body: TokenStream| {
if is_async {
- quote! { crate::internal::custom_invocation_context::scoped_import(async move { #body }) }
+ quote! {
+ let __import_ctx = ctx.clone();
+ crate::internal::import_abort::abortable_import(&__import_ctx, async move { #body })
+ }
} else {
body
}
@@ -273,7 +292,7 @@ fn build_freestanding_import_bridge(
let reader_type = crate::async_values::reader_type(context, &async_value)?;
let reader_to_js =
crate::async_values::reader_to_js_expr(context, &async_value, quote! { result })?;
- let ret = returns(quote! { rquickjs::Result> });
+ let ret = returns_result(quote! { rquickjs::Value<'js> });
let body = body(quote! {
let result: #reader_type = #bindgen_path(#(#param_refs),*) #maybe_await;
rquickjs::IntoJs::into_js(#reader_to_js, &ctx)
@@ -294,7 +313,7 @@ fn build_freestanding_import_bridge(
if let Some(exception) = &return_types.expected_exception {
let wrapped_exception = &exception.wrapped_type_ref;
let wrap_exception = exception.wrap.run(quote! { error });
- let ret = returns(quote! { rquickjs::Result<#wrapped_result> });
+ let ret = returns_result(quote! { #wrapped_result });
let body = body(quote! {
let result: #original_result = #bindgen_path(#(#param_refs),*) #maybe_await;
match result {
@@ -314,25 +333,19 @@ fn build_freestanding_import_bridge(
}
}
} else {
- let ret = returns(quote! { #wrapped_result });
+ let ret = returns_plain(quote! { #wrapped_result });
+ let value = plain_body(wrap_result);
let body = body(quote! {
let result: #original_result = #bindgen_path(#(#param_refs),*) #maybe_await;
- #wrap_result
+ #value
});
- if needs_ctx {
+ if needs_ctx || is_async {
quote! {
#[rquickjs::function]
fn #rust_function_ident<'js>(ctx: rquickjs::Ctx<'js>, #(#param_list),*) -> #ret {
#body
}
}
- } else if is_async {
- quote! {
- #[rquickjs::function]
- fn #rust_function_ident<'js>(#(#param_list),*) -> #ret {
- #body
- }
- }
} else {
quote! {
#[rquickjs::function]
@@ -504,13 +517,46 @@ fn build_deferred_import_bridge(
#[rquickjs::function]
fn #rust_function_ident<'js>(ctx: rquickjs::Ctx<'js>, #(#param_list),*) -> rquickjs::Result> {
let (__promise, __resolve, __reject) = rquickjs::Promise::new(&ctx)?;
+ // The current import signal. An already aborted signal rejects before any parameter
+ // is lowered, so no import starts and no JS source is read.
+ let __abort_signal = match crate::internal::import_abort::deferred_import_abort(&ctx)? {
+ crate::internal::import_abort::DeferredImportAbort::None => None,
+ crate::internal::import_abort::DeferredImportAbort::Aborted(__reason) => {
+ __reject.call::<_, ()>((__reason,))?;
+ return Ok(__promise);
+ }
+ crate::internal::import_abort::DeferredImportAbort::Current(__signal) => Some(__signal),
+ };
// Lower each `future` / `stream` parameter into a component reader here, while a
// `Ctx` is available. The writers are fed from JS (promise callbacks / a JS pump) and
// pure component-model tasks, so they keep running correctly after the import returns.
#(#arg_bindings)*
+ // The abort listener is registered only after every parameter is lowered, so a
+ // lowering error leaves no listener on the signal. A signal that aborted meanwhile
+ // rejects without starting the import; dropping the lowered readers closes them.
+ let (__abort_signal, __abort_registration) = match __abort_signal {
+ None => (None, None),
+ Some(__signal) => match crate::internal::import_abort::arm_deferred_import_abort(&ctx, __signal)? {
+ crate::internal::import_abort::ArmedImportAbort::Aborted(__reason) => {
+ __reject.call::<_, ()>((__reason,))?;
+ return Ok(__promise);
+ }
+ crate::internal::import_abort::ArmedImportAbort::Armed(__signal, __registration) => {
+ (Some(__signal), Some(__registration))
+ }
+ },
+ };
let (__result_tx, __result_rx) = futures::channel::oneshot::channel();
crate::internal::spawn_local(crate::internal::custom_invocation_context::scoped(async move {
- let __result: #result_ty = #bindgen_path(#(#arg_exprs),*).await;
+ let __import = #bindgen_path(#(#arg_exprs),*);
+ // `None` when the signal aborted: the import future is dropped, which cancels its
+ // subtask.
+ let __result: Option<#result_ty> = match __abort_registration {
+ None => Some(__import.await),
+ Some(__registration) => {
+ futures::future::Abortable::new(__import, __registration).await.ok()
+ }
+ };
// The receiver is dropped if the originating JavaScript runtime shuts down.
let _ = __result_tx.send(__result);
}));
@@ -522,7 +568,15 @@ fn build_deferred_import_bridge(
&__settle_ctx,
__resolve,
__reject,
- move |__ctx| { #produce_body },
+ move |__ctx| {
+ if let Some(__signal) = __abort_signal
+ && let Some(__reason) = __signal.finish(__ctx, __result.is_none())?
+ {
+ return Ok(crate::internal::PromiseOutcome::Reject(__reason));
+ }
+ let __result = __result.expect("an import without an aborted signal has a result");
+ #produce_body
+ },
);
});
Ok(__promise)
@@ -820,6 +874,11 @@ fn generate_import_module(
let rust_fn = RustWitFunction::new(context, &name, function);
let rust_method_name_ident = rust_fn.function_name_ident();
+ // The TypeScript declarations name the method the same way.
+ let js_method_name_lit = LitStr::new(
+ &escape_js_ident(name.to_lower_camel_case()),
+ Span::call_site(),
+ );
let parameters = function
.params
@@ -866,18 +925,40 @@ fn generate_import_module(
} else {
quote! {}
};
- let returns = |ty: TokenStream| {
+ // An async bridge returns `AbortableImport<'js, T>` for a body that evaluates to
+ // `rquickjs::Result`, and takes a `Ctx` to read the current import signal.
+ let returns_result = |ty: TokenStream| {
if is_async {
- quote! { crate::internal::custom_invocation_context::ScopedImport<'js, #ty> }
+ quote! { crate::internal::import_abort::AbortableImport<'js, #ty> }
+ } else {
+ quote! { rquickjs::Result<#ty> }
+ }
+ };
+ let returns_plain = |ty: TokenStream| {
+ if is_async {
+ quote! { crate::internal::import_abort::AbortableImport<'js, #ty> }
} else {
ty
}
};
+ let plain_body = |value: TokenStream| {
+ if is_async {
+ quote! { Ok(#value) }
+ } else {
+ value
+ }
+ };
+ let ctx_param = if is_async {
+ quote! { ctx: rquickjs::Ctx<'js>, }
+ } else {
+ quote! {}
+ };
let body = |prelude: TokenStream, body: TokenStream| {
if is_async {
quote! {
#prelude
- crate::internal::custom_invocation_context::scoped_import(async move { #body })
+ let __import_ctx = ctx.clone();
+ crate::internal::import_abort::abortable_import(&__import_ctx, async move { #body })
}
} else {
quote! { #prelude #body }
@@ -916,7 +997,7 @@ fn generate_import_module(
let wrapped_exception = &exception.wrapped_type_ref;
let wrap_exception = exception.wrap.run(quote! { error });
- let ret = returns(quote! { rquickjs::Result<#wrapped_result> });
+ let ret = returns_result(quote! { #wrapped_result });
let body = body(
method_prelude,
quote! {
@@ -934,23 +1015,26 @@ fn generate_import_module(
},
);
methods.push(quote! {
+ #[qjs(rename = #js_method_name_lit)]
pub fn #rust_method_name_ident #lifetime (&self, ctx: #ctx_type, #(#param_list),*) -> #ret {
#body
}
});
} else {
- let ret = returns(quote! { #wrapped_result });
+ let ret = returns_plain(quote! { #wrapped_result });
+ let value = plain_body(wrap_result);
let body = body(
method_prelude,
quote! {
let result: #original_result = #method_target
.#rust_method_name_ident(#(#param_refs),*)
#maybe_await;
- #wrap_result
+ #value
},
);
methods.push(quote! {
- pub fn #rust_method_name_ident #lifetime (&self, #(#param_list),*) -> #ret {
+ #[qjs(rename = #js_method_name_lit)]
+ pub fn #rust_method_name_ident #lifetime (&self, #ctx_param #(#param_list),*) -> #ret {
#body
}
});
@@ -961,7 +1045,7 @@ fn generate_import_module(
let wrapped_exception = &exception.wrapped_type_ref;
let wrap_exception = exception.wrap.run(quote! { error });
- let ret = returns(quote! { rquickjs::Result<#wrapped_result> });
+ let ret = returns_result(quote! { #wrapped_result });
let body = body(
quote! {},
quote! {
@@ -977,23 +1061,24 @@ fn generate_import_module(
},
);
methods.push(quote! {
- #[qjs(static)]
+ #[qjs(static, rename = #js_method_name_lit)]
pub fn #rust_method_name_ident #lifetime (ctx: #ctx_type, #(#param_list),*) -> #ret {
#body
}
});
} else {
- let ret = returns(quote! { #wrapped_result });
+ let ret = returns_plain(quote! { #wrapped_result });
+ let value = plain_body(wrap_result);
let body = body(
quote! {},
quote! {
let result: #original_result = #bindgen_path::#rust_method_name_ident(#(#param_refs),*) #maybe_await;
- #wrap_result
+ #value
},
);
methods.push(quote! {
- #[qjs(static)]
- pub fn #rust_method_name_ident #lifetime (#(#param_list),*) -> #ret {
+ #[qjs(static, rename = #js_method_name_lit)]
+ pub fn #rust_method_name_ident #lifetime (#ctx_param #(#param_list),*) -> #ret {
#body
}
});
diff --git a/crates/wasm-rquickjs/src/typescript.rs b/crates/wasm-rquickjs/src/typescript.rs
index e16129d2..22294d0d 100644
--- a/crates/wasm-rquickjs/src/typescript.rs
+++ b/crates/wasm-rquickjs/src/typescript.rs
@@ -116,10 +116,11 @@ pub fn generate_export_module(context: &GeneratorContext) -> anyhow::Result anyhow::Result> {
let mut results = Vec::new();
- let (_global, interfaces) = crate::imports::collect_imported_interfaces(context)?;
+ let (global, interfaces) = crate::imports::collect_imported_interfaces(context)?;
if crate::imports::custom_invocation_context_interface(&interfaces).is_some() {
let target = context
@@ -130,6 +131,30 @@ pub fn generate_import_modules(context: &GeneratorContext) -> anyhow::Result setTimeout(resolve, ms));
+}
+
+async function settle(promise) {
+ try {
+ return { value: await promise };
+ } catch (error) {
+ return { error: error instanceof Error ? error.message : String(error) };
+ }
+}
+
+// Starts `call` with a fresh signal current, aborts the signal after `ms` and settles the call.
+async function abortAfter(label, ms, call) {
+ const controller = new AbortController();
+ const promise = withSignal(controller.signal, call);
+ await sleep(ms);
+ controller.abort(new Error(`stop-${label}`));
+ return settle(promise);
+}
+
+async function* bytes() {
+ yield 1;
+ yield 2;
+ yield 3;
+}
+
+// A JS stream source that records how many items the runtime pulled from it, whether it ran to
+// its end, and whether its `finally` block ran (on its end or on `return()`).
+function source() {
+ const state = { pulled: 0, exhausted: false, closed: false };
+ state.iterable = (async function* () {
+ try {
+ for (let item = 1; item <= 3; item++) {
+ state.pulled = item;
+ yield item;
+ }
+ state.exhausted = true;
+ } finally {
+ state.closed = true;
+ }
+ })();
+ return state;
+}
+
+function sourceOutcome(outcome, state) {
+ return { ...outcome, pulled: state.pulled, exhausted: state.exhausted, closed: state.closed };
+}
+
+// An AbortSignal-like object that counts its abort listeners. `abort` removes the listeners
+// registered with `once`, as `AbortSignal` does.
+function countingSignal() {
+ const listeners = new Set();
+ const signal = {
+ aborted: false,
+ reason: undefined,
+ addEventListener(type, listener, options) {
+ if (type === 'abort') {
+ listeners.add({ listener, once: Boolean(options && options.once) });
+ }
+ },
+ removeEventListener(type, listener) {
+ for (const entry of listeners) {
+ if (type === 'abort' && entry.listener === listener) {
+ listeners.delete(entry);
+ }
+ }
+ },
+ abort(reason) {
+ signal.aborted = true;
+ signal.reason = reason;
+ for (const entry of [...listeners]) {
+ if (entry.once) {
+ listeners.delete(entry);
+ }
+ entry.listener();
+ }
+ },
+ count() {
+ return listeners.size;
+ },
+ };
+ return signal;
+}
+
+// A wrapper around a counting signal that aborts it when a listener is added, before it passes
+// the listener on.
+function abortingOnListen(label) {
+ const inner = countingSignal();
+ return {
+ get aborted() {
+ return inner.aborted;
+ },
+ get reason() {
+ return inner.reason;
+ },
+ addEventListener(type, listener, options) {
+ inner.abort(new Error(`stop-${label}`));
+ inner.addEventListener(type, listener, options);
+ },
+ removeEventListener(type, listener) {
+ inner.removeEventListener(type, listener);
+ },
+ count() {
+ return inner.count();
+ },
+ };
+}
+
+// Calls `call` with a counting signal current. It reports the listener count once the import
+// runs and after the import settled. With `abortAfterMs` the signal aborts after that delay.
+async function countListeners(label, call, abortAfterMs) {
+ const signal = countingSignal();
+ const promise = withSignal(signal, call);
+ await sleep(5);
+ const during = signal.count();
+ if (abortAfterMs !== undefined) {
+ await sleep(abortAfterMs);
+ signal.abort(new Error(`stop-${label}`));
+ }
+ const outcome = await settle(promise);
+ return { ...outcome, during, after: signal.count() };
+}
+
+export async function run() {
+ const outcomes = {};
+
+ outcomes.free = await abortAfter('free', 20, () => wait('free', 10000));
+ outcomes.result = await abortAfter('result', 20, () => waitResult('result', 10000));
+ const timer = new Timer();
+ outcomes.method = await abortAfter('method', 20, () => timer.wait('method', 10000));
+ outcomes.static = await abortAfter('static', 20, () => Timer.waitStatic('static', 10000));
+ outcomes.keyword = await settle(timer.await_('keyword', 1));
+ outcomes.deferred = await abortAfter('deferred', 20, () => consume('deferred', bytes(), 10000));
+
+ // An aborted signal rejects without starting the import.
+ const aborted = new AbortController();
+ aborted.abort(new Error('stop-pre'));
+ outcomes.pre = await settle(withSignal(aborted.signal, () => wait('pre', 0)));
+ const preDeferredSource = source();
+ outcomes.preDeferred = sourceOutcome(
+ await settle(
+ withSignal(aborted.signal, () => consume('pre-deferred', preDeferredSource.iterable, 0)),
+ ),
+ preDeferredSource,
+ );
+
+ // A JS stream source that the host keeps without reading is closed when the abort cancels
+ // the import.
+ const heldSource = source();
+ const held = await abortAfter('held', 20, () => hold('held', heldSource.iterable, 10000));
+ await sleep(50);
+ outcomes.held = sourceOutcome(held, heldSource);
+
+ // A signal that aborts after the parameters were lowered but before the runtime first polls
+ // the import starts no host call, and the lowered stream is closed.
+ const prePoll = new AbortController();
+ const prePollSource = source();
+ const prePollCall = withSignal(prePoll.signal, () =>
+ hold('pre-poll', prePollSource.iterable, 10000),
+ );
+ prePoll.abort(new Error('stop-pre-poll'));
+ const prePollOutcome = await settle(prePollCall);
+ await sleep(50);
+ outcomes.prePoll = sourceOutcome(prePollOutcome, prePollSource);
+
+ // A signal that aborts while the parameters are lowered starts no host call. The `then`
+ // getter runs synchronously when the runtime lowers the stream source.
+ const lowering = new AbortController();
+ const loweringSource = source();
+ const loweringValue = {
+ get then() {
+ lowering.abort(new Error('stop-lowering'));
+ return undefined;
+ },
+ [Symbol.asyncIterator]() {
+ return loweringSource.iterable;
+ },
+ };
+ const loweringOutcome = await settle(
+ withSignal(lowering.signal, () => hold('lowering', loweringValue, 10000)),
+ );
+ await sleep(50);
+ outcomes.lowering = sourceOutcome(loweringOutcome, loweringSource);
+
+ // An import that finishes first is not affected by a later abort.
+ const late = new AbortController();
+ outcomes.finished = await settle(withSignal(late.signal, () => wait('finished', 1)));
+ outcomes.finishedDeferred = await settle(
+ withSignal(late.signal, () => consume('finished-deferred', bytes(), 1)),
+ );
+ late.abort(new Error('stop-late'));
+
+ // Only imports called synchronously inside `withSignal` take the signal, and an inner
+ // `withSignal` restores the outer signal when it returns.
+ const outer = new AbortController();
+ const inner = new AbortController();
+ let nestedInner;
+ let nestedOuter;
+ let afterAwait;
+ withSignal(outer.signal, () => {
+ withSignal(inner.signal, () => {
+ nestedInner = wait('nested-inner', 30);
+ });
+ nestedOuter = wait('nested-outer', 10000);
+ afterAwait = (async () => {
+ await Promise.resolve();
+ return wait('after-await', 30);
+ })();
+ });
+ const unsignalled = wait('unsignalled', 30);
+ await sleep(10);
+ outer.abort(new Error('stop-outer'));
+ outcomes.nestedInner = await settle(nestedInner);
+ outcomes.nestedOuter = await settle(nestedOuter);
+ outcomes.afterAwait = await settle(afterAwait);
+ outcomes.unsignalled = await settle(unsignalled);
+
+ // An exception from `fn` propagates out of `withSignal` and restores the signal that was
+ // current before.
+ const throwOuter = new AbortController();
+ let thrownInner;
+ let throwOuterCall;
+ withSignal(throwOuter.signal, () => {
+ try {
+ withSignal(new AbortController().signal, () => {
+ throw new Error('boom-inner');
+ });
+ } catch (error) {
+ thrownInner = error.message;
+ }
+ throwOuterCall = wait('throw-outer', 10000);
+ });
+ const throwTop = new AbortController();
+ let thrownTop;
+ try {
+ withSignal(throwTop.signal, () => {
+ throw new Error('boom-top');
+ });
+ } catch (error) {
+ thrownTop = error.message;
+ }
+ const afterThrow = wait('after-throw', 30);
+ await sleep(10);
+ throwOuter.abort(new Error('stop-throw-outer'));
+ throwTop.abort(new Error('stop-throw-top'));
+ outcomes.thrownInner = thrownInner;
+ outcomes.throwOuter = await settle(throwOuterCall);
+ outcomes.thrownTop = thrownTop;
+ outcomes.afterThrow = await settle(afterThrow);
+
+ // No abort listener stays on the signal after the import settled, for both bridge kinds,
+ // whether the import finished or was aborted, and when a parameter fails to convert.
+ outcomes.listeners = {
+ freeFinished: await countListeners('count-free-finished', () =>
+ wait('count-free-finished', 30),
+ ),
+ freeAborted: await countListeners(
+ 'count-free-aborted',
+ () => wait('count-free-aborted', 10000),
+ 10,
+ ),
+ deferredFinished: await countListeners('count-deferred-finished', () =>
+ consume('count-deferred-finished', bytes(), 30),
+ ),
+ deferredAborted: await countListeners(
+ 'count-deferred-aborted',
+ () => consume('count-deferred-aborted', bytes(), 10000),
+ 10,
+ ),
+ };
+ const badSignal = countingSignal();
+ const badFuture = {
+ get then() {
+ throw new Error('bad-future');
+ },
+ };
+ let badError;
+ try {
+ withSignal(badSignal, () => takeFuture('count-bad-future', badFuture, 0));
+ } catch (error) {
+ badError = error instanceof Error ? error.message : String(error);
+ }
+ outcomes.listeners.conversionError = { error: badError, after: badSignal.count() };
+
+ // A signal that aborts inside `addEventListener`, before it registers the listener, starts
+ // no host call and keeps no listener, for both bridge kinds.
+ const freeOnListen = abortingOnListen('on-listen-free');
+ outcomes.onListenFree = {
+ ...(await settle(withSignal(freeOnListen, () => wait('on-listen-free', 10000)))),
+ after: freeOnListen.count(),
+ };
+ const deferredOnListen = abortingOnListen('on-listen-deferred');
+ const onListenSource = source();
+ const onListenOutcome = await settle(
+ withSignal(deferredOnListen, () =>
+ consume('on-listen-deferred', onListenSource.iterable, 10000),
+ ),
+ );
+ await sleep(50);
+ outcomes.onListenDeferred = {
+ ...sourceOutcome(onListenOutcome, onListenSource),
+ after: deferredOnListen.count(),
+ };
+
+ return JSON.stringify(outcomes);
+}
+
+// The signals of pending `overlapping` calls, by label.
+const overlappingSignals = new Map();
+
+export async function overlapping(label, delayMs) {
+ const controller = new AbortController();
+ overlappingSignals.set(label, controller);
+ try {
+ const call = withSignal(controller.signal, () => wait(label, delayMs));
+ return JSON.stringify(await settle(call));
+ } finally {
+ overlappingSignals.delete(label);
+ }
+}
+
+export async function abortOverlapping(label) {
+ const controller = overlappingSignals.get(label);
+ if (controller === undefined) {
+ return false;
+ }
+ controller.abort(new Error(`stop-${label}`));
+ return true;
+}
diff --git a/examples/p3/import-abort/wit/world.wit b/examples/p3/import-abort/wit/world.wit
new file mode 100644
index 00000000..3fae1de3
--- /dev/null
+++ b/examples/p3/import-abort/wit/world.wit
@@ -0,0 +1,31 @@
+package test:import-abort;
+
+// Host calls that record when they start, finish and are cancelled, for the abort signal of
+// generated async imports (`wasm-rquickjs:import-abort`).
+interface host {
+ wait: async func(label: string, delay-ms: u32) -> string;
+ wait-result: async func(label: string, delay-ms: u32) -> result;
+ consume: async func(label: string, data: stream, delay-ms: u32) -> u32;
+ // Keeps `data` without reading it; closes it when the call ends or is cancelled.
+ hold: async func(label: string, data: stream, delay-ms: u32) -> u32;
+ take-future: async func(label: string, value: future>, delay-ms: u32) -> u32;
+
+ resource timer {
+ constructor();
+ wait: async func(label: string, delay-ms: u32) -> string;
+ wait-static: static async func(label: string, delay-ms: u32) -> string;
+ // A keyword-named method keeps the escaped name of the TypeScript declarations.
+ %await: async func(label: string, delay-ms: u32) -> string;
+ }
+}
+
+world import-abort {
+ import host;
+
+ export run: async func() -> string;
+ // Calls `wait(label, delay-ms)` with a signal of its own and returns its outcome as JSON.
+ // Calls can overlap; `abort-overlapping` aborts the signal of one of them.
+ export overlapping: async func(label: string, delay-ms: u32) -> string;
+ // Aborts the signal of the pending `overlapping` call with `label`; false when there is none.
+ export abort-overlapping: async func(label: string) -> bool;
+}
diff --git a/tests/goldenfiles/generated_types_all-golem-imports_wasm-rquickjs-import-abort.d.ts b/tests/goldenfiles/generated_types_all-golem-imports_wasm-rquickjs-import-abort.d.ts
new file mode 100644
index 00000000..b2d011c2
--- /dev/null
+++ b/tests/goldenfiles/generated_types_all-golem-imports_wasm-rquickjs-import-abort.d.ts
@@ -0,0 +1,25 @@
+/**
+ * The abort signal of generated async imports.
+ *
+ * `withSignal(signal, fn)` makes `signal` current while `fn` runs synchronously. Every async
+ * import that is called meanwhile takes the signal with it. When the signal aborts before the
+ * import finishes, the import's promise rejects with `signal.reason` and the runtime drops the
+ * import, which cancels its component-model subtask: the host stops the call or learns that its
+ * caller stopped waiting. A signal that is already aborted rejects without starting the import.
+ * Imports that `fn` starts after an `await` do not take the signal.
+ */
+declare module 'wasm-rquickjs:import-abort' {
+ /** The part of `AbortSignal` the runtime uses. */
+ export interface ImportSignal {
+ readonly aborted: boolean;
+ readonly reason: unknown;
+ addEventListener(type: 'abort', listener: () => void, options?: { once?: boolean }): void;
+ removeEventListener(type: 'abort', listener: () => void): void;
+ }
+
+ /**
+ * Calls `fn` with `signal` current, then restores the previous signal. `undefined` and `null`
+ * clear the current signal.
+ */
+ export function withSignal(signal: ImportSignal | undefined | null, fn: () => T): T;
+}
diff --git a/tests/p3_import_abort.rs b/tests/p3_import_abort.rs
new file mode 100644
index 00000000..7371c127
--- /dev/null
+++ b/tests/p3_import_abort.rs
@@ -0,0 +1,611 @@
+//! End-to-end tests for `wasm-rquickjs:import-abort` on WASI Preview 3.
+//!
+//! The component under test is generated from `examples/p3/import-abort`. Every host call records
+//! when it starts and when it finishes. A host call that the guest cancels is dropped by Wasmtime
+//! before it finishes, which records its cancellation.
+
+use camino::Utf8PathBuf;
+use camino_tempfile::Utf8TempDir;
+use std::process::Command;
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+use wasm_rquickjs::{
+ EmbeddingMode, GenerationTarget, JsModuleSpec, generate_wrapper_crate_with_target,
+};
+use wasmtime::component::{
+ Accessor, Component, FutureReader, HasSelf, Linker, Resource, StreamReader, bindgen,
+};
+use wasmtime::{Config, Engine, Result, Store};
+use wasmtime_wasi::p2::pipe::MemoryOutputPipe;
+use wasmtime_wasi::{ResourceTable, WasiCtxBuilder, WasiCtxView};
+use wasmtime_wasi_http::{WasiHttpCtx, WasiHttpCtxView, WasiHttpView};
+
+mod p3_build;
+
+pub struct Timer;
+
+bindgen!({
+ world: "import-abort",
+ path: "examples/p3/import-abort/wit",
+ with: {
+ "test:import-abort/host.timer": Timer,
+ },
+});
+
+use test::import_abort::host as host_api;
+
+type Records = Arc>>;
+
+struct Host {
+ wasi: wasmtime_wasi::WasiCtx,
+ http: WasiHttpCtx,
+ table: ResourceTable,
+ stderr: MemoryOutputPipe,
+ #[cfg(feature = "use-golem-wasmtime")]
+ io_ctx: wasmtime_wasi::IoCtx,
+ records: Records,
+}
+
+impl wasmtime_wasi::WasiView for Host {
+ fn ctx(&mut self) -> WasiCtxView<'_> {
+ WasiCtxView {
+ ctx: &mut self.wasi,
+ table: &mut self.table,
+ #[cfg(feature = "use-golem-wasmtime")]
+ io_ctx: &mut self.io_ctx,
+ }
+ }
+}
+
+impl WasiHttpView for Host {
+ fn http(&mut self) -> WasiHttpCtxView<'_> {
+ WasiHttpCtxView {
+ ctx: &mut self.http,
+ table: &mut self.table,
+ hooks: wasmtime_wasi_http::default_hooks(),
+ }
+ }
+}
+
+/// Records `cancelled:` when dropped before [`Call::finish`].
+struct Call {
+ label: String,
+ records: Records,
+ finished: bool,
+}
+
+impl Call {
+ fn start(records: Records, label: &str) -> Self {
+ records.lock().unwrap().push(format!("start:{label}"));
+ Self {
+ label: label.to_string(),
+ records,
+ finished: false,
+ }
+ }
+
+ async fn sleep_and_finish(mut self, delay_ms: u32) -> String {
+ tokio::time::sleep(Duration::from_millis(delay_ms.into())).await;
+ self.finished = true;
+ self.records
+ .lock()
+ .unwrap()
+ .push(format!("done:{}", self.label));
+ self.label.clone()
+ }
+}
+
+impl Drop for Call {
+ fn drop(&mut self) {
+ if !self.finished {
+ self.records
+ .lock()
+ .unwrap()
+ .push(format!("cancelled:{}", self.label));
+ }
+ }
+}
+
+fn records(accessor: &Accessor>) -> Records {
+ accessor.with(|mut access| access.get().records.clone())
+}
+
+impl host_api::Host for Host {}
+
+impl host_api::HostTimer for Host {
+ fn new(&mut self) -> Resource {
+ self.table.push(Timer).expect("failed to store timer")
+ }
+
+ fn drop(&mut self, rep: Resource) -> Result<()> {
+ self.table.delete(rep)?;
+ Ok(())
+ }
+}
+
+impl host_api::HostWithStore for HasSelf {
+ async fn wait(accessor: &Accessor, label: String, delay_ms: u32) -> String {
+ Call::start(records(accessor), &label)
+ .sleep_and_finish(delay_ms)
+ .await
+ }
+
+ async fn wait_result(
+ accessor: &Accessor,
+ label: String,
+ delay_ms: u32,
+ ) -> std::result::Result {
+ Ok(Call::start(records(accessor), &label)
+ .sleep_and_finish(delay_ms)
+ .await)
+ }
+
+ async fn consume(
+ accessor: &Accessor,
+ label: String,
+ mut data: StreamReader,
+ delay_ms: u32,
+ ) -> u32 {
+ let call = Call::start(records(accessor), &label);
+ let _ = accessor.with(|access| data.close(access));
+ call.sleep_and_finish(delay_ms).await;
+ 0
+ }
+
+ async fn hold(
+ accessor: &Accessor,
+ label: String,
+ data: StreamReader,
+ delay_ms: u32,
+ ) -> u32 {
+ let call = Call::start(records(accessor), &label);
+ // Closes the stream when the call finishes or is cancelled, without reading it.
+ let _data = data.guard(accessor);
+ call.sleep_and_finish(delay_ms).await;
+ 0
+ }
+
+ async fn take_future(
+ accessor: &Accessor,
+ label: String,
+ mut value: FutureReader>,
+ delay_ms: u32,
+ ) -> u32 {
+ let call = Call::start(records(accessor), &label);
+ let _ = accessor.with(|access| value.close(access));
+ call.sleep_and_finish(delay_ms).await;
+ 0
+ }
+}
+
+impl host_api::HostTimerWithStore for HasSelf {
+ async fn await_(
+ accessor: &Accessor,
+ _self: Resource,
+ label: String,
+ delay_ms: u32,
+ ) -> String {
+ Call::start(records(accessor), &label)
+ .sleep_and_finish(delay_ms)
+ .await
+ }
+
+ async fn wait(
+ accessor: &Accessor,
+ _self: Resource,
+ label: String,
+ delay_ms: u32,
+ ) -> String {
+ Call::start(records(accessor), &label)
+ .sleep_and_finish(delay_ms)
+ .await
+ }
+
+ async fn wait_static(accessor: &Accessor, label: String, delay_ms: u32) -> String {
+ Call::start(records(accessor), &label)
+ .sleep_and_finish(delay_ms)
+ .await
+ }
+}
+
+fn build_component(temp: &Utf8TempDir) -> anyhow::Result {
+ let example_dir = Utf8PathBuf::from(env!("CARGO_MANIFEST_DIR"))
+ .join("examples")
+ .join("p3")
+ .join("import-abort");
+ let out = temp.path().join("out");
+ generate_wrapper_crate_with_target(
+ &example_dir.join("wit"),
+ &[JsModuleSpec {
+ name: "module".to_string(),
+ mode: EmbeddingMode::EmbedFile(example_dir.join("src").join("import-abort.js")),
+ }],
+ &out,
+ None,
+ GenerationTarget::WasiP3,
+ )?;
+
+ let cache = p3_build::BuildCache::new()?;
+ let mut build_cmd = Command::new("cargo");
+ cache.configure(&mut build_cmd);
+ let build = build_cmd
+ .arg("build")
+ .arg("--manifest-path")
+ .arg(out.join("Cargo.toml"))
+ .arg("--no-default-features")
+ .arg("--features")
+ .arg("p3,crypto,zlib,encoding")
+ .arg("--target")
+ .arg("wasm32-wasip2")
+ .output()?;
+ assert!(
+ build.status.success(),
+ "generated P3 crate should build; stderr:\n{}",
+ String::from_utf8_lossy(&build.stderr)
+ );
+
+ let mut metadata_cmd = Command::new("cargo");
+ cache.configure(&mut metadata_cmd);
+ let metadata = metadata_cmd
+ .args([
+ "metadata",
+ "--no-deps",
+ "--format-version",
+ "1",
+ "--manifest-path",
+ ])
+ .arg(out.join("Cargo.toml"))
+ .output()?;
+ let metadata: serde_json::Value = serde_json::from_slice(&metadata.stdout)?;
+ let wasm = Utf8PathBuf::from(metadata["target_directory"].as_str().unwrap())
+ .join("wasm32-wasip2")
+ .join("debug")
+ .join("import_abort.wasm");
+ Ok(
+ Utf8PathBuf::from_path_buf(cache.finish(wasm.as_std_path(), out.as_std_path())?)
+ .expect("generated paths are UTF-8"),
+ )
+}
+
+async fn run(
+ component_path: &camino::Utf8Path,
+ records: Records,
+) -> Result<(serde_json::Value, Vec, String)> {
+ let mut config = Config::new();
+ config.wasm_component_model(true);
+ config.wasm_component_model_async(true);
+ let engine = Engine::new(&config)?;
+ let component = Component::from_file(&engine, component_path)?;
+ let mut linker = Linker::::new(&engine);
+ wasmtime_wasi::p2::add_to_linker_async(&mut linker)?;
+ wasmtime_wasi::p3::add_to_linker(&mut linker)?;
+ wasmtime_wasi_http::p3::add_to_linker(&mut linker)?;
+ // Timer sleeps run on the host's tokio runtime, as in the custom invocation context test.
+ linker.allow_shadowing(true);
+ linker
+ .instance("wasi:clocks/monotonic-clock@0.3.0")?
+ .func_wrap_concurrent(
+ "wait-for",
+ |_accessor: &Accessor, (how_long,): (u64,)| {
+ Box::pin(async move {
+ tokio::time::sleep(Duration::from_nanos(how_long)).await;
+ Ok(())
+ })
+ },
+ )?;
+ linker.allow_shadowing(false);
+ host_api::add_to_linker::>(&mut linker, |host| host)?;
+
+ let stderr = MemoryOutputPipe::new(1024 * 1024);
+ let mut builder = WasiCtxBuilder::new();
+ builder.inherit_stdout().stderr(stderr.clone());
+ #[cfg(feature = "use-golem-wasmtime")]
+ let (wasi, io_ctx) = builder.build();
+ #[cfg(not(feature = "use-golem-wasmtime"))]
+ let wasi = builder.build();
+ let mut store = Store::new(
+ &engine,
+ Host {
+ wasi,
+ http: WasiHttpCtx::new(),
+ table: ResourceTable::new(),
+ stderr,
+ #[cfg(feature = "use-golem-wasmtime")]
+ io_ctx,
+ records: records.clone(),
+ },
+ );
+ let bindings = ImportAbort::instantiate_async(&mut store, &component, &linker).await?;
+ let started = std::time::Instant::now();
+ let (result, overlapping) = store
+ .run_concurrent(async |accessor| -> Result<_> {
+ let result = bindings.call_run(accessor).await?;
+ // Three overlapping exported calls, each with its own signal. The second signal
+ // aborts once all three host calls are in flight.
+ let (first, second, third, aborted) = futures::join!(
+ bindings.call_overlapping(accessor, "overlap-first".into(), 1000),
+ bindings.call_overlapping(accessor, "overlap-second".into(), 10000),
+ bindings.call_overlapping(accessor, "overlap-third".into(), 1000),
+ async {
+ wait_for_records(
+ &records,
+ &[
+ "start:overlap-first",
+ "start:overlap-second",
+ "start:overlap-third",
+ ],
+ )
+ .await;
+ bindings
+ .call_abort_overlapping(accessor, "overlap-second".into())
+ .await
+ },
+ );
+ let overlapping = serde_json::json!({
+ "overlap-first": serde_json::from_str::(&first?)?,
+ "overlap-second": serde_json::from_str::(&second?)?,
+ "overlap-third": serde_json::from_str::(&third?)?,
+ "aborted": aborted?,
+ });
+ Ok((result, overlapping))
+ })
+ .await??;
+ // Each aborted import would otherwise wait 10 seconds.
+ let elapsed = started.elapsed();
+ assert!(
+ elapsed < Duration::from_secs(8),
+ "aborted imports did not end early: {elapsed:?}; records: {:#?}",
+ records.lock().unwrap()
+ );
+ let stderr = String::from_utf8_lossy(&store.data().stderr.contents()).into_owned();
+ let records = records.lock().unwrap().clone();
+ let mut outcomes: serde_json::Value = serde_json::from_str(&result)?;
+ outcomes["overlapping"] = overlapping;
+ Ok((outcomes, records, stderr))
+}
+
+/// Waits until the host recorded every record in `expected`.
+async fn wait_for_records(records: &Records, expected: &[&str]) {
+ let deadline = std::time::Instant::now() + Duration::from_secs(30);
+ loop {
+ let found = {
+ let records = records.lock().unwrap();
+ expected
+ .iter()
+ .all(|record| records.iter().any(|candidate| candidate == record))
+ };
+ if found {
+ return;
+ }
+ assert!(
+ std::time::Instant::now() < deadline,
+ "{expected:?} were not recorded: {:#?}",
+ records.lock().unwrap()
+ );
+ tokio::time::sleep(Duration::from_millis(5)).await;
+ }
+}
+
+#[test]
+fn p3_import_abort_cancels_the_signalled_imports() {
+ let temp = Utf8TempDir::new().expect("temp dir");
+ let wasm = build_component(&temp).expect("generate + build");
+ let rt = tokio::runtime::Builder::new_multi_thread()
+ .enable_all()
+ .build()
+ .expect("failed to build tokio runtime");
+ let shared = Records::default();
+ let (outcomes, records, stderr) = rt.block_on(async {
+ tokio::time::timeout(Duration::from_secs(120), run(&wasm, shared.clone()))
+ .await
+ .unwrap_or_else(|_| {
+ panic!(
+ "guest call did not complete within 120s; records: {:#?}",
+ shared.lock().unwrap()
+ )
+ })
+ .expect("guest call failed")
+ });
+ let context = format!("outcomes: {outcomes:#}\nrecords: {records:#?}\nstderr: {stderr}");
+ let has = |record: &str| records.iter().any(|candidate| candidate == record);
+
+ // An abort rejects with the signal's reason and cancels the started host call, for every
+ // bridge shape: freestanding, `result`, resource method, resource static and deferred.
+ for label in ["free", "result", "method", "static", "deferred"] {
+ assert_eq!(
+ outcomes[label]["error"],
+ format!("stop-{label}"),
+ "{label}\n{context}"
+ );
+ assert!(has(&format!("start:{label}")), "{label}\n{context}");
+ assert!(has(&format!("cancelled:{label}")), "{label}\n{context}");
+ assert!(!has(&format!("done:{label}")), "{label}\n{context}");
+ }
+
+ // A method whose WIT name is a JavaScript keyword is callable under the escaped name its
+ // TypeScript declaration uses.
+ assert_eq!(
+ outcomes["keyword"]["value"], "keyword",
+ "keyword\n{context}"
+ );
+ assert!(has("done:keyword"), "keyword\n{context}");
+
+ // An already aborted signal starts no host call.
+ for (outcome, label) in [("pre", "pre"), ("preDeferred", "pre-deferred")] {
+ assert_eq!(outcomes[outcome]["error"], "stop-pre", "{label}\n{context}");
+ assert!(!has(&format!("start:{label}")), "{label}\n{context}");
+ }
+ // ... and does not lower a stream argument, so its JS source is not read.
+ assert_eq!(outcomes["preDeferred"]["pulled"], 0, "{context}");
+ assert_eq!(outcomes["preDeferred"]["closed"], false, "{context}");
+
+ // A lowered JS stream source is closed (its iterator's `return()` runs) and not read to its
+ // end when the signal aborts: after the host took the stream without reading it, after the
+ // parameters were lowered but before the import was first polled, and while the parameters
+ // were lowered.
+ for (outcome, label, started) in [
+ ("held", "held", true),
+ ("prePoll", "pre-poll", false),
+ ("lowering", "lowering", false),
+ ] {
+ assert_eq!(
+ outcomes[outcome]["error"],
+ format!("stop-{label}"),
+ "{label}\n{context}"
+ );
+ assert_eq!(
+ has(&format!("start:{label}")),
+ started,
+ "{label}\n{context}"
+ );
+ assert!(!has(&format!("done:{label}")), "{label}\n{context}");
+ assert_eq!(outcomes[outcome]["closed"], true, "{label}\n{context}");
+ assert_eq!(outcomes[outcome]["exhausted"], false, "{label}\n{context}");
+ }
+ assert!(has("cancelled:held"), "{context}");
+
+ // A finished import keeps its result when the signal aborts later.
+ assert_eq!(outcomes["finished"]["value"], "finished", "{context}");
+ assert_eq!(outcomes["finishedDeferred"]["value"], 0, "{context}");
+ assert!(
+ has("done:finished") && has("done:finished-deferred"),
+ "{context}"
+ );
+
+ // The outer signal reaches only the import called synchronously after the inner
+ // `withSignal` returned.
+ assert_eq!(outcomes["nestedOuter"]["error"], "stop-outer", "{context}");
+ assert!(has("cancelled:nested-outer"), "{context}");
+ for (outcome, label) in [
+ ("nestedInner", "nested-inner"),
+ ("afterAwait", "after-await"),
+ ("unsignalled", "unsignalled"),
+ ] {
+ assert_eq!(outcomes[outcome]["value"], label, "{context}");
+ assert!(has(&format!("done:{label}")), "{context}");
+ assert!(!has(&format!("cancelled:{label}")), "{context}");
+ }
+
+ // An exception from `fn` propagates out of `withSignal` and restores the previous signal:
+ // the outer signal after a nested `withSignal`, and no signal after a top-level one.
+ assert_eq!(outcomes["thrownInner"], "boom-inner", "{context}");
+ assert_eq!(
+ outcomes["throwOuter"]["error"], "stop-throw-outer",
+ "{context}"
+ );
+ assert!(has("cancelled:throw-outer"), "{context}");
+ assert_eq!(outcomes["thrownTop"], "boom-top", "{context}");
+ assert_eq!(outcomes["afterThrow"]["value"], "after-throw", "{context}");
+ assert!(has("done:after-throw"), "{context}");
+
+ // The bridge registers one abort listener while the import runs and none stays once the
+ // import settled.
+ let listeners = &outcomes["listeners"];
+ for (outcome, label, expected) in [
+ (
+ "freeFinished",
+ "count-free-finished",
+ Some(serde_json::json!("count-free-finished")),
+ ),
+ ("freeAborted", "count-free-aborted", None),
+ (
+ "deferredFinished",
+ "count-deferred-finished",
+ Some(serde_json::json!(0)),
+ ),
+ ("deferredAborted", "count-deferred-aborted", None),
+ ] {
+ let outcome = &listeners[outcome];
+ match expected {
+ Some(value) => assert_eq!(outcome["value"], value, "{label}\n{context}"),
+ None => assert_eq!(
+ outcome["error"],
+ format!("stop-{label}"),
+ "{label}\n{context}"
+ ),
+ }
+ assert_eq!(outcome["during"], 1, "{label}\n{context}");
+ assert_eq!(outcome["after"], 0, "{label}\n{context}");
+ }
+ // A parameter that fails to convert throws from the call and leaves no listener.
+ let conversion_error = &listeners["conversionError"];
+ assert!(
+ conversion_error["error"]
+ .as_str()
+ .is_some_and(|error| error.contains("bad-future")),
+ "{context}"
+ );
+ assert_eq!(conversion_error["after"], 0, "{context}");
+ assert!(!has("start:count-bad-future"), "{context}");
+
+ // A signal that aborts inside `addEventListener` starts no host call and keeps no listener.
+ for (outcome, label) in [
+ ("onListenFree", "on-listen-free"),
+ ("onListenDeferred", "on-listen-deferred"),
+ ] {
+ assert_eq!(
+ outcomes[outcome]["error"],
+ format!("stop-{label}"),
+ "{label}\n{context}"
+ );
+ assert!(!has(&format!("start:{label}")), "{label}\n{context}");
+ assert_eq!(outcomes[outcome]["after"], 0, "{label}\n{context}");
+ }
+ // The lowered JS stream source is closed without being read to its end.
+ assert_eq!(outcomes["onListenDeferred"]["closed"], true, "{context}");
+ assert_eq!(
+ outcomes["onListenDeferred"]["exhausted"], false,
+ "{context}"
+ );
+
+ // Overlapping exported calls each keep the signal they passed to `withSignal`, though the
+ // other calls made their own signals current before and after it: aborting the signal of
+ // the second call cancels only its host call, while the other two are still in flight.
+ let overlapping = &outcomes["overlapping"];
+ assert_eq!(overlapping["aborted"], true, "{context}");
+ assert_eq!(
+ overlapping["overlap-second"]["error"], "stop-overlap-second",
+ "{context}"
+ );
+ assert!(has("cancelled:overlap-second"), "{context}");
+ assert!(!has("done:overlap-second"), "{context}");
+ let position = |record: &str| records.iter().position(|candidate| candidate == record);
+ for label in ["overlap-first", "overlap-third"] {
+ assert_eq!(overlapping[label]["value"], label, "{label}\n{context}");
+ assert!(!has(&format!("cancelled:{label}")), "{label}\n{context}");
+ assert!(
+ position("cancelled:overlap-second") < position(&format!("done:{label}")),
+ "{label} finished before the abort\n{context}"
+ );
+ }
+}
+
+#[test]
+fn p3_import_abort_declarations_are_generated_only_for_worlds_with_async_imports() {
+ let declarations = |example: &str| {
+ let temp = Utf8TempDir::new().expect("temp dir");
+ let wit = Utf8PathBuf::from("examples/p3").join(example).join("wit");
+ let generated =
+ wasm_rquickjs::generate_dts(&wit, temp.path(), None).expect("generate d.ts");
+ let abort = generated
+ .iter()
+ .find(|path| path.file_name() == Some("wasm-rquickjs-import-abort.d.ts"))
+ .map(|path| std::fs::read_to_string(path).expect("read d.ts"));
+ (abort, temp)
+ };
+
+ let (abort, _temp) = declarations("import-abort");
+ let abort = abort.expect("a world with async imports declares the import-abort module");
+ assert!(
+ abort.contains("declare module 'wasm-rquickjs:import-abort'"),
+ "{abort}"
+ );
+ assert!(
+ abort.contains("export function withSignal(signal: ImportSignal | undefined | null, fn: () => T): T;"),
+ "{abort}"
+ );
+
+ // Async exports alone do not make the module available.
+ let (abort, _temp) = declarations("async-export");
+ assert_eq!(abort, None);
+}