Truly independent web browser
LibJS: Finish promise reactions before running the next job
Timothy Flynn544b9b9c2db2
diff --git a/Libraries/LibJS/Rust/src/interpreter/vm.rs b/Libraries/LibJS/Rust/src/interpreter/vm.rsindex 0219a75080d..ed0195f1df1 100644--- a/Libraries/LibJS/Rust/src/interpreter/vm.rs+++ b/Libraries/LibJS/Rust/src/interpreter/vm.rs@@ -561,6 +561,7 @@ pub struct Vm {job_queues: OnceCell<Gc<JobQueues>>,/// How many run_executable() calls are running: the outermost one runs the promise jobs its code queued.run_executable_depth: Cell<u32>,+ running_promise_jobs: Cell<bool>,/// The cells that hold others weakly, LibGC's list of weak containers. The list is weak: the sweep callback drops/// the containers that die, and has the others forget the cells that died.weak_containers: RefCell<Vec<WeakContainer>>,@@ -711,6 +712,7 @@ impl Vm {on_promise_rejection_handled: Cell::new(None),job_queues: OnceCell::new(),run_executable_depth: Cell::new(0),+ running_promise_jobs: Cell::new(false),weak_containers: RefCell::new(Vec::new()),finalization_registries_with_dead_cells: GcRefCell::new(Vec::new()),host_resize_array_buffer: Cell::new(default_host_resize_array_buffer),@@ -1543,20 +1545,30 @@ impl Vm {}pub fn run_queued_promise_jobs(&self) {- if self.job_queues().promise_jobs.borrow().is_empty() {+ // A reaction must finish settling its result promise before another job starts, even if its callback runs+ // bytecode that would otherwise trigger another checkpoint.+ if self.running_promise_jobs.get() || self.job_queues().promise_jobs.borrow().is_empty() {return;}- self.run_queued_promise_jobs_impl();+ self.run_queued_promise_jobs_impl(|| false);}- fn run_queued_promise_jobs_impl(&self) {+ /// The native Await shim cannot suspend its Rust stack, so it must be able to drive an already-running queue+ /// while waiting for its promise to settle. Leave later jobs queued once the await can resume.+ pub(crate) fn run_queued_promise_jobs_for_await(&self, is_settled: impl Fn() -> bool) {+ self.run_queued_promise_jobs_impl(is_settled);+ }++ fn run_queued_promise_jobs_impl(&self, should_stop: impl Fn() -> bool) {+ let was_running_promise_jobs = self.running_promise_jobs.replace(true);let job_queues = self.job_queues();- loop {+ while !should_stop() {let Some(job) = job_queues.promise_jobs.borrow_mut(self).pop_front() else {break;};let _ = HeapFunction::call(job, self);}+ self.running_promise_jobs.set(was_running_promise_jobs);}// 9.5.4 HostEnqueuePromiseJob ( job, realm ), https://tc39.es/ecma262/#sec-hostenqueuepromisejobdiff --git a/Libraries/LibJS/Rust/src/runtime/completion.rs b/Libraries/LibJS/Rust/src/runtime/completion.rsindex 5e2687b1492..1049d25dcc8 100644--- a/Libraries/LibJS/Rust/src/runtime/completion.rs+++ b/Libraries/LibJS/Rust/src/runtime/completion.rs@@ -209,7 +209,7 @@ pub fn r#await(vm: &Vm, value: Value) -> ThrowCompletionOr<Value> {);// FIXME: Since we don't support context suspension, we attempt to "wait" for the promise to resolve- // by synchronously running all queued promise jobs.+ // by synchronously running queued promise jobs until it settles.if let Some(agent) = vm.agent().embedder_agent {// Embedder case (i.e. LibWeb). Runs all promise jobs by performing a microtask checkpoint.// NB: The goal condition reads the outcome itself, as a copy taken before the promise settles would never@@ -217,7 +217,7 @@ pub fn r#await(vm: &Vm, value: Value) -> ThrowCompletionOr<Value> {agent.spin_event_loop_until(vm, &|| awaited_completion.success.get().is_some());} else {// No embedder, standalone LibJS implementation- vm.run_queued_promise_jobs();+ vm.run_queued_promise_jobs_for_await(|| awaited_completion.success.get().is_some());}// 8. Remove asyncContext from the execution context stack and restore the execution context that is at the top of the execution context stack as the running execution context.diff --git a/Tests/LibJS/Runtime/modules/basic-modules.js b/Tests/LibJS/Runtime/modules/basic-modules.jsindex f9b9bb99f20..419d99b8715 100644--- a/Tests/LibJS/Runtime/modules/basic-modules.js+++ b/Tests/LibJS/Runtime/modules/basic-modules.js@@ -344,6 +344,24 @@ describe("scoping in modules", () => {});describe("top-level await", () => {+ test("await continuations interleave with chained promise reactions", () => {+ const result = expectModulePassed("./top-level-await-job-order.mjs");+ const ticksFirst = ["tick 1", "await 1", "tick 2", "await 2", "tick 3", "await 3", "tick 4", "await 4"];+ for (const order of result.ordersAfterAwait) {+ expect(order).toEqual(ticksFirst);+ }+ expect(result.orderBeforeAwait).toEqual([+ "await 1",+ "tick 1",+ "await 2",+ "tick 2",+ "await 3",+ "tick 3",+ "await 4",+ "tick 4",+ ]);+ });+test("for await at the top level", () => {const result = expectModulePassed("./top-level-for-await.mjs");expect(result.result).toEqual([1, 2, "a", "b", "closed", "first", "iterator failed", "1x", "2x"]);diff --git a/Tests/LibJS/Runtime/modules/top-level-await-job-order.mjs b/Tests/LibJS/Runtime/modules/top-level-await-job-order.mjsnew file mode 100644index 00000000000..39cf4f5a364--- /dev/null+++ b/Tests/LibJS/Runtime/modules/top-level-await-job-order.mjs@@ -0,0 +1,29 @@+export const ordersAfterAwait = [];++for (const usePromise of [false, true]) {+ const order = [];+ Promise.resolve()+ .then(() => order.push("tick 1"))+ .then(() => order.push("tick 2"))+ .then(() => order.push("tick 3"))+ .then(() => order.push("tick 4"));++ for (let i = 1; i <= 4; ++i) {+ await (usePromise ? Promise.resolve(i) : i);+ order.push(`await ${i}`);+ }+ ordersAfterAwait.push(order);+}++export const orderBeforeAwait = [];+Promise.resolve()+ .then(() => orderBeforeAwait.push("tick 1"))+ .then(() => orderBeforeAwait.push("tick 2"))+ .then(() => orderBeforeAwait.push("tick 3"))+ .then(() => orderBeforeAwait.push("tick 4"));++for (let i = 1; i <= 4; ++i) {+ await orderBeforeAwait.push(`await ${i}`);+}++export const passed = true;diff --git a/Tests/LibJS/Runtime/regress/promise-job-queue-reentrancy.js b/Tests/LibJS/Runtime/regress/promise-job-queue-reentrancy.jsnew file mode 100644index 00000000000..03dff5a112e--- /dev/null+++ b/Tests/LibJS/Runtime/regress/promise-job-queue-reentrancy.js@@ -0,0 +1,50 @@+test("nested promise job checkpoints wait for the current reaction to finish", () => {+ const order = [];+ Promise.resolve()+ .then(() => {+ order.push("reaction start");+ Promise.resolve().then(() => order.push("queued reaction"));+ runQueuedPromiseJobs();+ order.push("reaction end");+ })+ .then(() => order.push("chained reaction"));++ runQueuedPromiseJobs();+ expect(order).toEqual(["reaction start", "reaction end", "queued reaction", "chained reaction"]);+});++test("native awaits resume disposal before draining later promise jobs", () => {+ for (const reject of [false, true]) {+ const order = [];+ Promise.resolve().then(() => {+ const stack = new AsyncDisposableStack();+ stack.defer(() => {+ order.push("second dispose");+ });+ stack.defer(() => {+ order.push("first dispose");+ Promise.resolve()+ .then(() => order.push("tick 1"))+ .then(() => order.push("tick 2"))+ .then(() => order.push("tick 3"));+ return reject ? Promise.reject("disposal failed") : Promise.resolve();+ });+ stack.disposeAsync().then(+ () => order.push("fulfilled"),+ () => order.push("rejected")+ );+ order.push("dispose returned");+ });++ runQueuedPromiseJobs();+ expect(order).toEqual([+ "first dispose",+ "tick 1",+ "second dispose",+ "tick 2",+ "dispose returned",+ "tick 3",+ reject ? "rejected" : "fulfilled",+ ]);+ }+});