From 9267573e75f5b58f10908bdde7b02e4dcb5ab20e Mon Sep 17 00:00:00 2001 From: Daniel Vigovszky Date: Thu, 26 Nov 2026 07:53:50 +0000 Subject: [PATCH 1/3] Add wasm-rquickjs:import-abort and name imported resource methods explicitly withSignal(signal, fn) lets JavaScript cancel the async imports that fn starts: an abort rejects the import and drops it, which cancels its subtask. Imported resource methods now get an explicit JavaScript name from the same rule as the generated declarations, so %await is await_. Amp-Thread-ID: https://ampcode.com/threads/T-01a20968-e35a-756a-a2f3-deaba79311e3 Co-authored-by: Amp --- README.md | 28 + .../skeleton/src/builtin/import_abort.js | 23 + .../skeleton/src/builtin/import_abort.rs | 17 + .../wasm-rquickjs/skeleton/src/builtin/mod.rs | 11 +- .../skeleton/src/internal/import_abort.rs | 156 ++++++ .../skeleton/src/internal/mod.rs | 1 + .../skeleton/src/internal/runtime_services.rs | 1 + crates/wasm-rquickjs/src/import_abort.d.ts | 25 + crates/wasm-rquickjs/src/imports.rs | 149 +++-- crates/wasm-rquickjs/src/typescript.rs | 27 +- examples/p3/import-abort/src/import-abort.js | 266 +++++++++ examples/p3/import-abort/wit/world.wit | 26 + ...em-imports_wasm-rquickjs-import-abort.d.ts | 25 + tests/p3_import_abort.rs | 516 ++++++++++++++++++ 14 files changed, 1237 insertions(+), 34 deletions(-) create mode 100644 crates/wasm-rquickjs/skeleton/src/builtin/import_abort.js create mode 100644 crates/wasm-rquickjs/skeleton/src/builtin/import_abort.rs create mode 100644 crates/wasm-rquickjs/skeleton/src/internal/import_abort.rs create mode 100644 crates/wasm-rquickjs/src/import_abort.d.ts create mode 100644 examples/p3/import-abort/src/import-abort.js create mode 100644 examples/p3/import-abort/wit/world.wit create mode 100644 tests/goldenfiles/generated_types_all-golem-imports_wasm-rquickjs-import-abort.d.ts create mode 100644 tests/p3_import_abort.rs diff --git a/README.md b/README.md index 26218df95..bd0ba1e08 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 000000000..7b94302aa --- /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 000000000..d8ee9f41f --- /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 be67dcd09..90a94ca2f 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 000000000..c3a63542f --- /dev/null +++ b/crates/wasm-rquickjs/skeleton/src/internal/import_abort.rs @@ -0,0 +1,156 @@ +//! 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. +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))?; + 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 9b3e85a7c..159f158bb 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 55b940730..d0c063fc2 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 000000000..b2d011c2c --- /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 6538ec8a7..01e6dff69 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 e16129d28..22294d0d2 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; +} + +// 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() }; + + return JSON.stringify(outcomes); +} diff --git a/examples/p3/import-abort/wit/world.wit b/examples/p3/import-abort/wit/world.wit new file mode 100644 index 000000000..ad5b3ddb9 --- /dev/null +++ b/examples/p3/import-abort/wit/world.wit @@ -0,0 +1,26 @@ +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; +} 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 000000000..b2d011c2c --- /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 000000000..10b53009e --- /dev/null +++ b/tests/p3_import_abort.rs @@ -0,0 +1,516 @@ +//! 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: