Skip to content

Lightpanda: the headless browser designed for AI and automation

Simplify unhandled rejection tracking

Karl Seguin186e96283f2a
diff --git a/src/browser/PageStatus.zig b/src/browser/PageStatus.zig
index 5619c46b6..bc6b193cf 100644
--- a/src/browser/PageStatus.zig
+++ b/src/browser/PageStatus.zig
@@ -182,7 +182,7 @@ fn Counts(comptime E: type) type {
const testing = @import("../testing.zig");
test "PageStatus: missing globals from uncaught ReferenceErrors" {
- testing.expectLog(&.{ .page_error, .page_error, .page_error, .page_error });
+ testing.expectLog(&.{ .page_error, .page_error, .page_error, .page_error, .page_error });
const page = try testing.pageTest("page_missing_global.html", .{});
defer page.close();
diff --git a/src/browser/js/Context.zig b/src/browser/js/Context.zig
index 31b84dd95..1e64fb9d3 100644
--- a/src/browser/js/Context.zig
+++ b/src/browser/js/Context.zig
@@ -128,7 +128,7 @@ scheduler: Scheduler,
// Promises rejected without a handler since the last microtask checkpoint. A
// handler attached before the checkpoint ends withdraws the promise: it was
// never unhandled. What is left is reported by Env.runMicrotasks.
-rejected_promises: std.ArrayList(RejectedPromise) = .empty,
+rejected_promises: std.ArrayList(js.Promise.Global) = .empty,
// Execution context for worker-compatible APIs. This provides a common
// interface that works in both Page and Worker contexts.
@@ -136,16 +136,6 @@ execution: Execution,
unknown_properties: (if (lp.IS_DEBUG) std.StringHashMapUnmanaged(UnknownPropertyStat) else void) = if (lp.IS_DEBUG) .{} else {},
-pub const RejectedPromise = struct {
- promise: js.Promise.Global,
- reason: js.Value.Global,
-
- pub fn release(self: RejectedPromise) void {
- self.promise.release();
- self.reason.release();
- }
-};
-
const ModuleEntry = struct {
// Can be null if we're asynchronously loading the module, in
// which case resolver_promise cannot be null.
@@ -217,8 +207,8 @@ pub fn deinit(self: *Context) void {
// this can release objects
self.scheduler.deinit();
- for (self.rejected_promises.items) |rejected| {
- rejected.release();
+ for (self.rejected_promises.items) |promise| {
+ promise.release();
}
self.rejected_promises.deinit(env.allocator);
@@ -429,12 +419,10 @@ fn evaluateModule(self: *Context, comptime want_result: bool, mod: js.Module, ur
// get the error from the module itself.
const exception = mod.getException();
- // A module script that throws while it evaluates rejects its
- // evaluation promise rather than throwing. That promise is ours, not
- // the page's: like a classic script's, the exception is reported as
- // uncaught, not as an unhandled rejection.
+ // Like a classic script's, the exception is reported as uncaught.
+ // (Module.evaluate marked the rejected evaluation promise handled.)
if (comptime want_result == false) {
- if (self.withdrawRejectedReason(exception)) {
+ if (self.env.terminatePending() == false) {
self.global.reportError(exception) catch |report_err| {
log.debug(.js, "report module error", .{ .specifier = url, .err = report_err });
};
@@ -1231,23 +1219,17 @@ fn enqueueMicrotask(self: *Context, callback: anytype) void {
// A promise rejected with no handler. It is reported at the end of the
// microtask checkpoint if it still has none.
-pub fn addRejectedPromise(self: *Context, promise: js.Promise, reason: js.Value) !void {
- const promise_global = try promise.persist();
- errdefer promise_global.release();
- const reason_global = try reason.persist();
- errdefer reason_global.release();
-
- try self.rejected_promises.append(self.env.allocator, .{
- .promise = promise_global,
- .reason = reason_global,
- });
+pub fn addRejectedPromise(self: *Context, promise: js.Promise) !void {
+ const global = try promise.persist();
+ errdefer global.release();
+ try self.rejected_promises.append(self.env.allocator, global);
}
// A handler was attached to `promise`. False when it wasn't waiting to be
// reported (it was already reported, or rejected in another context).
pub fn withdrawRejectedPromise(self: *Context, promise: js.Promise) bool {
for (self.rejected_promises.items, 0..) |rejected, i| {
- if (rejected.promise.isEqual(promise)) {
+ if (rejected.isEqual(promise)) {
rejected.release();
_ = self.rejected_promises.orderedRemove(i);
return true;
@@ -1256,24 +1238,6 @@ pub fn withdrawRejectedPromise(self: *Context, promise: js.Promise) bool {
return false;
}
-// Drops the rejections waiting with `reason`, for a caller that reports it
-// itself. True when there was one.
-fn withdrawRejectedReason(self: *Context, reason: js.Value) bool {
- var found = false;
- var i: usize = 0;
- while (i < self.rejected_promises.items.len) {
- const rejected = self.rejected_promises.items[i];
- if (rejected.reason.isEqual(reason)) {
- rejected.release();
- _ = self.rejected_promises.orderedRemove(i);
- found = true;
- } else {
- i += 1;
- }
- }
- return found;
-}
-
// There's an assumption here: the js.Function will be alive when microtasks are
// run. If we're Env.runMicrotasks in all the places that we're supposed to, then
// this should be safe (I think). In whatever HandleScope a microtask is enqueued,
diff --git a/src/browser/js/Env.zig b/src/browser/js/Env.zig
index ca721cfcc..69ec063e2 100644
--- a/src/browser/js/Env.zig
+++ b/src/browser/js/Env.zig
@@ -548,9 +548,9 @@ fn reportRejectedPromises(self: *Env, ctx: *Context) bool {
var batch = ctx.rejected_promises;
ctx.rejected_promises = .empty;
defer batch.deinit(self.allocator);
- defer for (batch.items) |rejected| rejected.release();
+ defer for (batch.items) |promise| promise.release();
- for (batch.items) |rejected| {
+ for (batch.items) |global| {
if (self.terminatePending()) {
break;
}
@@ -563,7 +563,8 @@ fn reportRejectedPromises(self: *Env, ctx: *Context) bool {
ctx.localScope(&ls);
defer ls.deinit();
- reportRejectedPromise(ctx, rejected.promise.local(&ls.local), rejected.reason.local(&ls.local));
+ const promise = global.local(&ls.local);
+ reportRejectedPromise(ctx, promise, promise.result());
}
return true;
}
@@ -923,8 +924,7 @@ fn promiseRejectCallback(message_handle: v8.PromiseRejectMessage) callconv(.c) v
if (promise_event == v8.kPromiseRejectWithNoHandler) {
// Not unhandled yet: a handler can still come before the end of the
// microtask checkpoint (see reportRejectedPromises).
- const reason = rejection.reason() orelse return;
- ctx.addRejectedPromise(promise, reason) catch |err| {
+ ctx.addRejectedPromise(promise) catch |err| {
log.debug(.browser, "queue rejected promise", .{ .err = err });
};
return;
diff --git a/src/browser/js/Module.zig b/src/browser/js/Module.zig
index a7ce4e4e2..27c628ac1 100644
--- a/src/browser/js/Module.zig
+++ b/src/browser/js/Module.zig
@@ -87,6 +87,11 @@ pub fn evaluate(self: Module) !js.Value {
const res = v8.v8__Module__Evaluate(self.handle, self.local.handle) orelse return error.JsException;
if (self.getStatus() == .kErrored) {
+ // `res` is the evaluation promise, already rejected. It never reaches
+ // the page, so it isn't an unhandled rejection: the caller reports
+ // the exception itself.
+ const promise: js.Promise = .{ .local = self.local, .handle = @ptrCast(res) };
+ promise.markAsHandled();
return error.JsException;
}
diff --git a/src/browser/tests/frames/cross_realm_webcodecs_flush.html b/src/browser/tests/frames/cross_realm_webcodecs_flush.html
index 7273e244c..4992533ae 100644
--- a/src/browser/tests/frames/cross_realm_webcodecs_flush.html
+++ b/src/browser/tests/frames/cross_realm_webcodecs_flush.html
@@ -25,10 +25,11 @@ local scope at that point.
decoder.configure({codec: 'opus', sampleRate: 48000, numberOfChannels: 2});
const flush = iframe.contentWindow.AudioDecoder.prototype.flush.call(decoder);
const unconfigured = iframe.contentWindow.VideoEncoder.prototype.flush.call(new VideoEncoder({output: () => {}, error: () => {}}));
- state.resolve([
- await flush.then(() => 'resolved', (e) => e.name),
- await unconfigured.then(() => 'resolved', (e) => e.name),
- ]);
+ // Both handled now: awaiting one leaves the other unhandled meanwhile.
+ state.resolve(await Promise.all([
+ flush.then(() => 'resolved', (e) => e.name),
+ unconfigured.then(() => 'resolved', (e) => e.name),
+ ]));
await state.done((names) => {
// the codec is unsupported, so the pending configure closes it
diff --git a/src/browser/tests/frames/srcdoc.html b/src/browser/tests/frames/srcdoc.html
index be6092149..2aa1c3fd2 100644
--- a/src/browser/tests/frames/srcdoc.html
+++ b/src/browser/tests/frames/srcdoc.html
@@ -192,19 +192,25 @@
"var h=document.createElement('span');var r=h.attachShadow({mode:'open'});fb.appendChild(h);r.appendChild(ca)",
"var t=document.createElement('template');fb.appendChild(t);t.content.appendChild(ca)",
];
+ const state = await testing.async();
+ const frames = [];
for (const move of moves) {
- const state = await testing.async();
const f = document.createElement('iframe');
f.srcdoc = `<div id=ca><b><p id=fb><script>var fb=document.getElementById('fb');var ca=document.getElementById('ca');document.body.appendChild(fb);${move}<\/script></b></div>`;
- f.onload = () => state.resolve(f);
+ const loaded = new Promise((resolve) => f.onload = resolve);
document.body.appendChild(f);
+ await loaded;
+ frames.push(f);
+ }
+ state.resolve(frames);
- await state.done((f) => {
+ await state.done((frames) => {
+ for (const f of frames) {
const w = f.contentWindow;
testing.expectEqual(0, f.contentDocument.body.childNodes.length);
testing.expectEqual(null, w.fb.parentNode);
testing.expectEqual(false, w.ca.contains(w.fb));
- });
- }
+ }
+ });
}
</script>
diff --git a/src/browser/tests/net/xhr.html b/src/browser/tests/net/xhr.html
index b67881e14..2dbd7f3bd 100644
--- a/src/browser/tests/net/xhr.html
+++ b/src/browser/tests/net/xhr.html
@@ -585,22 +585,27 @@
// at teardown (the "release overflow" UAF).
const state = await testing.async();
const req = new XMLHttpRequest();
- req.onload = () => state.resolve();
+ const load = () => new Promise((resolve) => req.onload = resolve);
+
+ let loaded = load();
req.open('GET', 'http://127.0.0.1:9582/xhr');
req.send();
testing.expectError('InvalidStateError', () => req.send());
-
- await state.done(() => {
- // the first request was unaffected by the rejected second send()
- testing.expectEqual(200, req.status);
- });
+ await loaded;
+ // the first request was unaffected by the rejected second send()
+ const first_status = req.status;
// a fresh open() clears the flag, so the object is reusable
- const state2 = await testing.async();
- req.onload = () => state2.resolve();
+ loaded = load();
req.open('GET', 'http://127.0.0.1:9582/xhr');
req.send();
- await state2.done(() => testing.expectEqual(200, req.status));
+ await loaded;
+ state.resolve();
+
+ await state.done(() => {
+ testing.expectEqual(200, first_status);
+ testing.expectEqual(200, req.status);
+ });
}
</script>
@@ -762,26 +767,31 @@ handler runs, abort() cancels the re-send and no load is delivered.
// acquire (or a double release) frees the arena out from under `first`.
const state = await testing.async();
const req = new XMLHttpRequest();
- req.onload = () => { state.resolve() };
+ const load = () => new Promise((resolve) => req.onload = resolve);
+
+ let loaded = load();
req.open('GET', 'http://127.0.0.1:9582/xhr/binary');
req.responseType = 'blob';
req.send();
- await state.done(() => testing.expectEqual(200, req.status));
-
+ await loaded;
+ const first_status = req.status;
const first = req.response;
- const state2 = await testing.async();
- req.onload = () => { state2.resolve() };
+ loaded = load();
req.open('GET', 'http://127.0.0.1:9582/xhr/binary');
req.send();
- await state2.done(() => {
+ await loaded;
+ const first_bytes = new Int8Array(await first.arrayBuffer());
+ state.resolve();
+
+ await state.done(() => {
+ testing.expectEqual(200, first_status);
testing.expectEqual(true, req.response instanceof Blob);
// the second request parses a fresh blob, not the discarded one
testing.expectEqual(false, req.response === first);
+ testing.expectEqual(7, first.size);
+ testing.expectEqual([0, 0, 1, 2, 0, 0, 9], first_bytes);
});
-
- testing.expectEqual(7, first.size);
- testing.expectEqual([0, 0, 1, 2, 0, 0, 9], new Int8Array(await first.arrayBuffer()));
}
</script>
diff --git a/src/browser/tests/page/module_throw.html b/src/browser/tests/page/module_throw.html
index 2c79e568c..21a447a95 100644
--- a/src/browser/tests/page/module_throw.html
+++ b/src/browser/tests/page/module_throw.html
@@ -22,3 +22,20 @@
<script id=module_throw>
testing.onload(() => testing.expectEqual(['error:module-throw'], reported));
</script>
+
+<script id=dynamic_import_throw type=module>
+ // A module that throws under import() rejects the import() promise. The
+ // module's own evaluation promise isn't the page's: no unhandledrejection.
+ const state = await testing.async();
+ let outcome = 'resolved';
+ try {
+ await import('./modules/throws.js');
+ } catch (e) {
+ outcome = 'rejected';
+ }
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual('rejected', outcome);
+ testing.expectEqual(['error:module-throw'], reported);
+ });
+</script>
diff --git a/src/browser/tests/page/modules/throws.js b/src/browser/tests/page/modules/throws.js
new file mode 100644
index 000000000..bee43591e
--- /dev/null
+++ b/src/browser/tests/page/modules/throws.js
@@ -0,0 +1 @@
+throw new Error('dynamic-throw');
diff --git a/src/browser/tests/performance_resource_timing_buffer_full.html b/src/browser/tests/performance_resource_timing_buffer_full.html
index 6acee14a6..4f77e916d 100644
--- a/src/browser/tests/performance_resource_timing_buffer_full.html
+++ b/src/browser/tests/performance_resource_timing_buffer_full.html
@@ -62,40 +62,3 @@
});
}
</script>
-
-<!-- Its own file: script blocks run concurrently, so a fetch here would show
- up in the other resource tests' observers. -->
-<script id=buffer_full type=module>
- {
- const state = await testing.async();
- performance.clearResourceTimings();
- // Every resource overflows a zero-length buffer.
- performance.setResourceTimingBufferSize(0);
-
- const order = [];
- let event = null;
- performance.onresourcetimingbufferfull = (e) => {
- event = e;
- order.push('handler');
- };
- performance.addEventListener('resourcetimingbufferfull', () => {
- order.push('listener');
- state.resolve();
- });
-
- await (await fetch(testing.ORIGIN + '/xhr')).text();
- await state.done(() => {
- performance.onresourcetimingbufferfull = null;
- testing.expectEqual(['handler', 'listener'], order);
- testing.expectEqual('resourcetimingbufferfull', event.type);
- testing.expectEqual(true, event.isTrusted);
- // Non-bubbling per spec, Chrome, and WPT
- // (resource-timing/buffer-full-when-populate-entries.html). Firefox
- // fires it bubbling, so this one assertion fails there.
- testing.expectEqual(false, event.bubbles);
- testing.expectEqual(true, event.target === performance);
- // The event fires, but the entry that triggered it is still dropped.
- testing.expectEqual(0, performance.getEntriesByType('resource').length);
- });
- }
-</script>
diff --git a/src/browser/tests/weblocks.html b/src/browser/tests/weblocks.html
index f3c9ec1c5..86e01f7db 100644
--- a/src/browser/tests/weblocks.html
+++ b/src/browser/tests/weblocks.html
@@ -195,6 +195,8 @@
order.push('holder-start');
releaseStolen = resolve;
}));
+ // stolen below: its request rejects with AbortError
+ holder.catch(() => {});
await new Promise((r) => setTimeout(r, 0));
diff --git a/src/browser/tests/window/window.html b/src/browser/tests/window/window.html
index 5f7136cae..ff7b0b06c 100644
--- a/src/browser/tests/window/window.html
+++ b/src/browser/tests/window/window.html
@@ -429,6 +429,8 @@
testing.expectEqual(window, e.srcElement);
testing.expectEqual(window, e.currentTarget);
unhandledCalled += 1;
+ // expected: not reported as uncaught
+ e.preventDefault();
});
Promise.reject({x: 'Fail'});
testing.onload(() => testing.expectEqual(2, unhandledCalled));