Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
28 changes: 28 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1034,6 +1034,34 @@ nothing for it.

</details>

<details>
<summary><strong><code>wasm-rquickjs:import-abort</code></strong></summary>

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.

</details>

<details>
<summary><strong><code>node:inspector</code></strong> (stub)</summary>

Expand Down
23 changes: 23 additions & 0 deletions crates/wasm-rquickjs/skeleton/src/builtin/import_abort.js
Original file line number Diff line number Diff line change
@@ -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 };
17 changes: 17 additions & 0 deletions crates/wasm-rquickjs/skeleton/src/builtin/import_abort.rs
Original file line number Diff line number Diff line change
@@ -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<Value<'js>> {
import_abort::enter(&ctx, signal)
}

#[rquickjs::function]
pub fn leave<'js>(ctx: Ctx<'js>, previous: Option<Value<'js>>) {
import_abort::leave(&ctx, previous)
}
}
11 changes: 10 additions & 1 deletion crates/wasm-rquickjs/skeleton/src/builtin/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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");

Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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(
Expand Down
164 changes: 164 additions & 0 deletions crates/wasm-rquickjs/skeleton/src/internal/import_abort.rs
Original file line number Diff line number Diff line change
@@ -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<Option<Value<'js>>>,
}

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::<ImportSignal>()
.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<Value<'js>> {
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<Value<'js>>) {
state(ctx).current.replace(previous);
}

fn current<'js>(ctx: &Ctx<'js>) -> Option<Value<'js>> {
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<T>>;

/// 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<Output = rquickjs::Result<T>> + '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<T>` / `stream<T>`
/// 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<rquickjs::Object<'static>>,
callback: rquickjs::Persistent<rquickjs::Function<'static>>,
}

/// 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<DeferredImportAbort<'js>> {
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<ArmedImportAbort<'js>> {
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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we recheck signal.aborted after registering the listener, as with_abort_signal does? An AbortSignal-like wrapper can abort before delegating to the real addEventListener, so this path misses the event and starts the deferred import anyway. Please remove the listener and reject with signal.reason in that case, with a regression checking that no host call starts.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8f2559b. arm_deferred_import_abort now checks signal.aborted again after addEventListener. When the signal aborted, it removes the listener and returns Aborted, so the bridge rejects with signal.reason and starts no import. The lowered stream readers are dropped, as in the existing abort-while-lowering path.

Regression: abortingOnListen in examples/p3/import-abort is a signal wrapper that aborts its inner signal before it passes the listener on. The test checks for both bridge kinds (wait and the deferred consume) that the promise rejects with the reason, no start: record exists, and no listener stays. For the deferred case it also checks that the JS source is closed. Without the fix, the deferred case recorded start:on-listen-deferred and ran the full 10 s host call.

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<Option<Value<'js>>> {
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)
}
}
}
1 change: 1 addition & 0 deletions crates/wasm-rquickjs/skeleton/src/internal/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
25 changes: 25 additions & 0 deletions crates/wasm-rquickjs/src/import_abort.d.ts
Original file line number Diff line number Diff line change
@@ -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<T>(signal: ImportSignal | undefined | null, fn: () => T): T;
}
Loading
Loading