Repository navigation
Add wasm-rquickjs:import-abort and name imported resource methods explicitly #241
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
164 changes: 164 additions & 0 deletions
164
crates/wasm-rquickjs/skeleton/src/internal/import_abort.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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( | ||
| 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) | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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; | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
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_abortnow checkssignal.abortedagain afteraddEventListener. When the signal aborted, it removes the listener and returnsAborted, so the bridge rejects withsignal.reasonand starts no import. The lowered stream readers are dropped, as in the existing abort-while-lowering path.Regression:
abortingOnListeninexamples/p3/import-abortis a signal wrapper that aborts its inner signal before it passes the listener on. The test checks for both bridge kinds (waitand the deferredconsume) that the promise rejects with the reason, nostart: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 recordedstart:on-listen-deferredand ran the full 10 s host call.