Repository navigation
Add wasm-rquickjs:import-abort and name imported resource methods explicitly - #241
Conversation
…licitly 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 <amp@ampcode.com>
Three overlapping exported calls each pass their own signal to withSignal and wait in a host call. Aborting the signal of the second call cancels only its host call; the first and third finish afterwards. Co-authored-by: Amp <amp@ampcode.com> Amp-Thread-ID: https://ampcode.com/threads/T-01a20968-e35a-756a-a2f3-deaba79311e3
| options.set("once", true)?; | ||
| let add: rquickjs::Function = signal.get("addEventListener")?; | ||
| add.call::<_, ()>((This(signal.clone()), "abort", callback.clone(), options))?; | ||
| Ok(ArmedImportAbort::Armed( |
There was a problem hiding this comment.
Could we recheck
signal.abortedafter registering the listener, aswith_abort_signaldoes? An AbortSignal-like wrapper can abort before delegating to the realaddEventListener, so this path misses the event and starts the deferred import anyway. Please remove the listener and reject withsignal.reasonin that case, with a regression checking that no host call starts.
There was a problem hiding this comment.
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.
| } | ||
|
|
||
| #[test] | ||
| fn p3_import_abort_cancels_the_signalled_imports() { |
There was a problem hiding this comment.
Could we add
--test p3_import_abortto a P3 CI lane? The current explicit test lists omit this target, so the new cancellation and overlapping-call regressions are not exercised by the green CI run.
There was a problem hiding this comment.
Done in 8f2559b: the generation suite of test-p3 now runs --test p3_generation --test p3_exported_resource --test p3_import_abort. The test needs no fork-only fix, so it runs on the stock wasmtime like the other P3 tests in that lane.
…abort in CI A signal-like wrapper can abort inside addEventListener before it registers the listener. The deferred import bridge now checks aborted again after it added the listener; when the signal aborted, it removes the listener and rejects without starting the import, as with_abort_signal already does for the other bridges. The test-p3 generation lane now runs p3_import_abort. Co-authored-by: Amp <amp@ampcode.com> Amp-Thread-ID: https://ampcode.com/threads/T-01a20968-e35a-756a-a2f3-deaba79311e3
noise64
left a comment
There was a problem hiding this comment.
Both earlier findings are verified fixed in source and the exact-head CI regression tests. Looks good.
This adds the built-in module
wasm-rquickjs:import-abort. Its functionwithSignal(signal, fn)lets JavaScript cancel the async imports thatfnstarts. This change also gives each imported resource method an explicit JavaScript name, so the runtime name matches the name in the generated declarations.Why. In Golem (GOL-1053), an agent-to-agent call is now one async
invoke-and-awaitimport. When a TypeScript caller aborts the call with anAbortSignal, or an Effect fiber is interrupted, the call must be withdrawn on a best-effort basis. To withdraw an async import, the guest must drop its subtask. Before this change, JavaScript had no way to do that: a promise cannot be cancelled, and the generated bridges kept the import future until it completed.Walkthrough: how cancellation works
The problem
An async import returns a promise. A promise has no "stop" button: once JavaScript calls the import, the runtime keeps the import running until it completes, even if nobody waits for the result any more. The host never learns that the caller gave up.
The idea: a "current signal"
withSignal(signal, fn)makessignalthe current signal whilefnruns. Every async import that is called during that time picks up the current signal. When the signal aborts, each import that picked it up stops:signal.reason, andAny object with
aborted,reason,addEventListenerandremoveEventListenerworks as the signal, so a plainAbortSignalis enough.What happens, step by step
If the import finishes first, steps 5 and 6 never happen: the bridge removes the listener and the promise resolves with the result. The listener is removed in every case, so a signal that is used for many imports does not collect listeners.
When the abort comes, and what you get
signal.abortedis alreadytrue)signal.reasonsignal.reasonsignal.reasonOnly the synchronous part of
fncountsThe signal is current only while
fnruns synchronously. Anasyncfunction runs synchronously up to its firstawait, so only the imports before thatawaitpick up the signal:To cover every import, wrap each one:
Nesting
An inner
withSignalreplaces the signal only for its ownfn. When it returns or throws, the outer signal is current again.nullorundefinedmeans "no signal".Overlapping invocations
The current signal is one value per JavaScript runtime. With overlapping invocations, one runtime runs several invocations at the same time, and each of them can make an agent call with its own signal. So why can't the signals get mixed up?
The answer: the current signal lives only for a moment, but each import remembers its own copy for as long as it runs.
fnruns synchronously: microsecondsThe bridge reads the current signal once, when JavaScript calls the import. It never reads the current signal again for that import. Each import also gets its own abort listener, which cancels only that import.
Here are two invocations that overlap:
withSignal(a.signal, …)makesacurrent, the bridge of A's import remembersa, andwithSignalmakes the previous signal current again before it returns.withSignalsetsb. A's import does not see this, because it already hasa.a.abort()calls only the listener of A's import. B's import has no listener ona.This is safe because JavaScript runs one piece of code at a time. While
fnruns, no other invocation's code can run, so no other invocation can see or change the current signal. Invocation B can only run after A reached anawait, and by thenwithSignalalready restored the previous signal. The custom invocation context uses the same rule: each import is attributed to the scope that is current when JavaScript calls it.The test
p3_import_abort_cancels_the_signalled_importschecks this with real overlapping export calls on one component instance. It starts threeoverlappingcalls at the same time. Each call uses its own signal and waits in a host call. When all three host calls run, it aborts the signal of the second call. The second host call is cancelled. The first and third finish afterwards with their results. A runtime that cancels the wrong import fails this case, for example one where an abort cancels the import that started last.Arguments
streamandfuturearguments. With an already aborted signal, the runtime does not read the JavaScript source at all. If the abort comes later, the runtime closes the stream and callsreturn()on the source's iterator, so afinallyblock in a generator runs:How Golem uses it
The Golem TypeScript SDK makes an agent-to-agent call with one async import. It passes the caller's
AbortSignalthroughwithSignal:Awaiting the result of an invocation handle (
handle.awaitResult({ signal })) uses the same mechanism on the handle'sawait_()method. There, dropping the import only stops the wait; the invocation itself goes on. The Effect SDK aborts the signal when the fiber is interrupted, so interrupting an Effect cancels the call in the same way.Where the code is
withSignal(JavaScript)skeleton/src/builtin/import_abort.jsenter/leave, and the bridge helpersskeleton/src/internal/import_abort.rsAbortablearound the import future (the existing helperfetchalso uses)skeleton/src/builtin/abort_signal.rs(with_abort_signal)src/imports.rssrc/import_abort.d.tstests/p3_import_abort.rs,examples/p3/import-abortReference: the changes in detail
withSignal(skeleton/src/builtin/import_abort.{js,rs},skeleton/src/internal/import_abort.rs,builtin/mod.rs,internal/runtime_services.rs)withSignal(signal, fn)callsfnand returns its result. Whilefnruns synchronously,signalis the current signal. Each async import that starts in that time takes the signal.signal.reason, and the bridge drops the import future. Dropping the future cancels the subtask.fncalls rejects at once and does not start.awaitinsidefndoes not take the signal, because the signal is current only during the synchronous part offn.withSignalrestores the outer signal when it returns or throws. A top-level call restores "no signal".Generator (
src/imports.rs)futureorstreamparameters.futureandstreamparameters, the bridge checks for an already aborted signal before it lowers any argument, so it reads nothing from the JavaScript source. It adds the abort listener only after all arguments are converted, so a conversion error leaves no listener on the signal. After it adds the listener, it checkssignal.abortedagain, because a signal-like wrapper can abort insideaddEventListenerbefore it registers the listener. In that case it removes the listener and rejects without starting the import, as the other bridges already do.Resource method names (
src/imports.rs). This is a breaking change for plain JavaScript callers.rename_all = "camelCase"named the methods of imported resources. The.d.tsgenerator usesescape_js_ident(to_lower_camel_case(name)). The two rules gave different names for some methods. For example, the method%awaitwasawaitat runtime butawait_in the.d.ts, so a TypeScript call ofawait_()failed with "not a function".#[qjs(rename = ...)]with the.d.tsrule. The names that change:delete_,new_,await_.sha256Sumbecomessha256sum.TypeScript declarations (
src/typescript.rs,src/import_abort.d.ts)generate-dtswriteswasm-rquickjs-import-abort.d.tsfor a world with async imports.Tests
examples/p3/import-abortand testtests/p3_import_abort.rs. They cover:futureorstreamargument, and while the host runs the import;return()called) when the host has not read it yet, and it is not read at all when the signal is already aborted;fnthrowing, at the top level and nested;addEventListener: no host call starts and no listener stays, for both bridge kinds;%await, called asawait_(). This case fails without the rename fix.tests/goldenfiles/generated_types_all-golem-imports_wasm-rquickjs-import-abort.d.ts.wasm-rquickjs:import-abort.Checks
generationsuite oftest-p3now also runs--test p3_import_abort.cargo test --test p3_import_abort --test dts(3 and 87 tests pass),cargo fmt --check,cargo clippy --all-targets -- -Dwarnings, andtools/check-skeleton-clippy.sh(default and maximal lanes).p3_async_values,p3_generation,p3_custom_invocation_contextandp3_exported_resourcepass.p3_invocation_tasks(fork lane), the fullruntimesuite andnode_compat.skeleton/src/builtin/mod.rsstill has threerustfmtdifferences that are also on main. This change does not touch them.The Golem side, which uses
withSignalin the TypeScript and Effect SDKs and callsawait_()in the Scala SDK, waits for a release with this change.