Skip to content

Lightpanda: the headless browser designed for AI and automation

webapi: Performance is an EventTarget

Karl Seguin1c9ec1b2c7a5
diff --git a/src/browser/EventManager.zig b/src/browser/EventManager.zig
index 142c1e23a..69ecfde8d 100644
--- a/src/browser/EventManager.zig
+++ b/src/browser/EventManager.zig
@@ -26,11 +26,12 @@ const EventManagerBase = @import("EventManagerBase.zig");
const Node = @import("webapi/Node.zig");
const Event = @import("webapi/Event.zig");
const Window = @import("webapi/Window.zig");
-const EventTarget = @import("webapi/EventTarget.zig");
const Element = @import("webapi/Element.zig");
const ShadowRoot = @import("webapi/ShadowRoot.zig");
-const XMLHttpRequestEventTarget = @import("webapi/net/XMLHttpRequestEventTarget.zig");
+const Performance = @import("webapi/Performance.zig");
+const EventTarget = @import("webapi/EventTarget.zig");
const MediaQueryList = @import("webapi/css/MediaQueryList.zig");
+const XMLHttpRequestEventTarget = @import("webapi/net/XMLHttpRequestEventTarget.zig");
const log = lp.log;
const Allocator = std.mem.Allocator;
@@ -89,6 +90,7 @@ pub fn dispatch(self: *EventManager, target: *EventTarget, event: *Event) Dispat
.node => try self.dispatchNode(target.subtype(Node), event),
.xhr => try self.dispatchDirect(target, event, target.subtype(XMLHttpRequestEventTarget).inlineHandler(event._type_string), .{ .context = "dispatch" }),
.media_query_list => try self.dispatchDirect(target, event, target.subtype(MediaQueryList).inlineHandler(event._type_string), .{ .context = "dispatch" }),
+ .performance => try self.dispatchDirect(target, event, target.subtype(Performance).inlineHandler(event._type_string), .{ .context = "dispatch" }),
.window => try self.dispatchDirect(target, event, windowInlineHandler(target.subtype(Window), event._type_string), .{ .context = "dispatch" }),
else => try self.dispatchDirect(target, event, null, .{ .context = "dispatch" }),
}
diff --git a/src/browser/Frame.zig b/src/browser/Frame.zig
index c168ca8ad..f85a4e121 100644
--- a/src/browser/Frame.zig
+++ b/src/browser/Frame.zig
@@ -444,7 +444,7 @@ pub fn init(self: *Frame, frame_id: u32, page: *Page, opts: InitOpts) !void {
._proto = undefined,
._document = self.document,
._location = undefined,
- ._performance = .init(factory, arena),
+ ._performance = try .init(factory, arena),
._screen = screen,
._visual_viewport = visual_viewport,
._cross_origin_wrapper = undefined,
@@ -470,7 +470,7 @@ pub fn init(self: *Frame, frame_id: u32, page: *Page, opts: InitOpts) !void {
.loader_id = self._loader_id,
.cookie_jar = &session.cookie_jar,
.notification = session.notification,
- .performance = &self.window._performance,
+ .performance = self.window._performance,
};
self._style_manager = try StyleManager.init(self);
@@ -487,7 +487,7 @@ pub fn init(self: *Frame, frame_id: u32, page: *Page, opts: InitOpts) !void {
.local_arena = self.local_arena,
});
errdefer browser.env.destroyContext(self.js);
- self.window._performance._scheduler = &self.js.scheduler;
+ self.window._performance.attach(self.js);
const location = try Location.init("about:blank", self);
// We're holding a reference in Zig-side.
@@ -2284,7 +2284,7 @@ pub fn getElementByIdFromNode(self: *Frame, node: *Node, id: []const u8) ?*Eleme
}
pub fn performance(self: *Frame) *Performance {
- return &self.window._performance;
+ return self.window._performance;
}
// Tracks a file input's FileList so its File refs are released at teardown.
diff --git a/src/browser/tests/performance_resource_timing_buffer_full.html b/src/browser/tests/performance_resource_timing_buffer_full.html
new file mode 100644
index 000000000..806b6a8e7
--- /dev/null
+++ b/src/browser/tests/performance_resource_timing_buffer_full.html
@@ -0,0 +1,39 @@
+<!DOCTYPE html>
+<script src="testing.js"></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/webapi/EventTarget.zig b/src/browser/webapi/EventTarget.zig
index 5f0d83e93..9148b7b43 100644
--- a/src/browser/webapi/EventTarget.zig
+++ b/src/browser/webapi/EventTarget.zig
@@ -18,8 +18,8 @@
const std = @import("std");
const lp = @import("lightpanda");
-const js = @import("../js/js.zig");
+const js = @import("../js/js.zig");
const Page = @import("../Page.zig");
const Factory = @import("../Factory.zig");
const EventManager = @import("../EventManager.zig");
@@ -29,24 +29,29 @@ const Event = @import("Event.zig");
const Screen = @import("Screen.zig");
const Worker = @import("Worker.zig");
const Window = @import("Window.zig");
+const FileReader = @import("FileReader.zig");
const AbortSignal = @import("AbortSignal.zig");
const MessagePort = @import("MessagePort.zig");
-const FileReader = @import("FileReader.zig");
-const WebSocket = @import("net/WebSocket.zig");
-const Navigation = @import("navigation/Navigation.zig");
+const Performance = @import("Performance.zig");
const Notification = @import("Notification.zig");
+const SharedWorker = @import("SharedWorker.zig");
+const VisualViewport = @import("VisualViewport.zig");
+const BroadcastChannel = @import("BroadcastChannel.zig");
+const WorkerGlobalScope = @import("WorkerGlobalScope.zig");
+
+const WebSocket = @import("net/WebSocket.zig");
const EventSource = @import("net/EventSource.zig");
const CookieStore = @import("storage/CookieStore.zig");
const IDBRequest = @import("storage/idb/IDBRequest.zig");
-const SharedWorker = @import("SharedWorker.zig");
-const FontFaceSet = @import("css/FontFaceSet.zig");
const IDBDatabase = @import("storage/idb/IDBDatabase.zig");
-const TextTrackCue = @import("media/TextTrackCue.zig");
-const VisualViewport = @import("VisualViewport.zig");
-const MediaQueryList = @import("css/MediaQueryList.zig");
const IDBTransaction = @import("storage/idb/IDBTransaction.zig");
-const BroadcastChannel = @import("BroadcastChannel.zig");
-const WorkerGlobalScope = @import("WorkerGlobalScope.zig");
+
+const FontFaceSet = @import("css/FontFaceSet.zig");
+const MediaQueryList = @import("css/MediaQueryList.zig");
+
+const TextTrackCue = @import("media/TextTrackCue.zig");
+
+const Navigation = @import("navigation/Navigation.zig");
const NavigationHistoryEntry = @import("navigation/NavigationHistoryEntry.zig");
const XMLHttpRequestEventTarget = @import("net/XMLHttpRequestEventTarget.zig");
@@ -63,64 +68,66 @@ pub const _prototype_root = true;
_type: Type align(8),
pub const Type = enum(u8) {
- generic,
- node,
- window,
- worker,
- shared_worker,
- worker_global_scope,
- xhr,
abort_signal,
+ broadcast_channel,
+ cookie_store,
+ event_source,
+ file_reader,
+ font_face_set,
+ generic,
+ idb_database,
+ idb_request,
+ idb_transaction,
media_query_list,
message_port,
- broadcast_channel,
- text_track_cue,
navigation,
navigation_history_entry,
+ node,
+ notification,
+ performance,
screen,
screen_orientation,
+ shared_worker,
+ text_track_cue,
visual_viewport,
- file_reader,
- font_face_set,
websocket,
- event_source,
- cookie_store,
- idb_request,
- idb_database,
- idb_transaction,
- notification,
+ window,
+ worker,
+ worker_global_scope,
+ xhr,
};
// `.generic` maps to EventTarget itself: a standalone `new EventTarget()` has
// no chain member of its own.
pub fn Subtype(comptime tag: Type) type {
return switch (tag) {
- .generic => EventTarget,
- .node => Node,
- .window => Window,
- .worker => Worker,
- .shared_worker => SharedWorker,
- .worker_global_scope => WorkerGlobalScope,
- .xhr => XMLHttpRequestEventTarget,
.abort_signal => AbortSignal,
+ .broadcast_channel => BroadcastChannel,
+ .cookie_store => CookieStore,
+ .event_source => EventSource,
+ .file_reader => FileReader,
+ .font_face_set => FontFaceSet,
+ .generic => EventTarget,
+ .idb_database => IDBDatabase,
+ .idb_request => IDBRequest,
+ .idb_transaction => IDBTransaction,
.media_query_list => MediaQueryList,
.message_port => MessagePort,
- .broadcast_channel => BroadcastChannel,
- .text_track_cue => TextTrackCue,
.navigation => Navigation,
.navigation_history_entry => NavigationHistoryEntry,
+ .node => Node,
+ .notification => Notification,
+ .performance => Performance,
.screen => Screen,
.screen_orientation => Screen.Orientation,
+ .shared_worker => SharedWorker,
+ .text_track_cue => TextTrackCue,
.visual_viewport => VisualViewport,
- .file_reader => FileReader,
- .font_face_set => FontFaceSet,
.websocket => WebSocket,
- .event_source => EventSource,
- .cookie_store => CookieStore,
- .idb_request => IDBRequest,
- .idb_database => IDBDatabase,
- .idb_transaction => IDBTransaction,
- .notification => Notification,
+ .window => Window,
+ .worker => Worker,
+ .worker_global_scope => WorkerGlobalScope,
+ .xhr => XMLHttpRequestEventTarget,
};
}
@@ -336,32 +343,33 @@ pub fn format(self: *EventTarget, writer: *std.Io.Writer) !void {
pub fn toString(self: *EventTarget) []const u8 {
return switch (self._type) {
- .node => return "[object Node]",
- .generic => return "[object EventTarget]",
- .window => return "[object Window]",
- .worker => return "[object Worker]",
- .shared_worker => return "[object SharedWorker]",
- .worker_global_scope => return "[object WorkerGlobalScope]",
- .xhr => return "[object XMLHttpRequestEventTarget]",
.abort_signal => return "[object AbortSignal]",
+ .broadcast_channel => return "[object BroadcastChannel]",
+ .cookie_store => return "[object CookieStore]",
+ .event_source => return "[object EventSource]",
+ .file_reader => return "[object FileReader]",
+ .font_face_set => return "[object FontFaceSet]",
+ .generic => return "[object EventTarget]",
+ .idb_database => return "[object IDBDatabase]",
+ .idb_request => return "[object IDBRequest]",
+ .idb_transaction => return "[object IDBTransaction]",
.media_query_list => return "[object MediaQueryList]",
.message_port => return "[object MessagePort]",
- .broadcast_channel => return "[object BroadcastChannel]",
- .text_track_cue => return "[object TextTrackCue]",
.navigation => return "[object Navigation]",
+ .navigation_history_entry => return "[object NavigationHistoryEntry]",
+ .node => return "[object Node]",
+ .notification => return "[object Notification]",
+ .performance => return "[object Performance]",
.screen => return "[object Screen]",
.screen_orientation => return "[object ScreenOrientation]",
+ .shared_worker => return "[object SharedWorker]",
+ .text_track_cue => return "[object TextTrackCue]",
.visual_viewport => return "[object VisualViewport]",
- .file_reader => return "[object FileReader]",
- .font_face_set => return "[object FontFaceSet]",
.websocket => return "[object WebSocket]",
- .event_source => return "[object EventSource]",
- .cookie_store => return "[object CookieStore]",
- .idb_request => return "[object IDBRequest]",
- .idb_database => return "[object IDBDatabase]",
- .idb_transaction => return "[object IDBTransaction]",
- .notification => return "[object Notification]",
- .navigation_history_entry => return "[object NavigationHistoryEntry]",
+ .window => return "[object Window]",
+ .worker => return "[object Worker]",
+ .worker_global_scope => return "[object WorkerGlobalScope]",
+ .xhr => return "[object XMLHttpRequestEventTarget]",
};
}
diff --git a/src/browser/webapi/Performance.zig b/src/browser/webapi/Performance.zig
index 6d6ed008b..d1d1f7c35 100644
--- a/src/browser/webapi/Performance.zig
+++ b/src/browser/webapi/Performance.zig
@@ -23,6 +23,8 @@ const js = @import("../js/js.zig");
const Factory = @import("../Factory.zig");
const Scheduler = @import("../js/Scheduler.zig");
+const Event = @import("Event.zig");
+const EventTarget = @import("EventTarget.zig");
const EventCounts = @import("EventCounts.zig");
const PerformanceObserver = @import("PerformanceObserver.zig");
@@ -32,12 +34,17 @@ const Allocator = std.mem.Allocator;
// https://w3c.github.io/resource-timing/#dfn-resource-timing-buffer-size-limit
const DEFAULT_RESOURCE_BUFFER_SIZE = 250;
+const BUFFER_FULL = "resourcetimingbufferfull";
+
pub fn registerTypes() []const type {
return &.{ Performance, Entry, Mark, Measure, ResourceTiming, PerformanceTiming, PerformanceNavigation };
}
const Performance = @This();
+pub const Proto = EventTarget;
+
+_proto: *EventTarget,
_time_origin: u64,
_arena: Allocator,
_factory: *Factory,
@@ -51,11 +58,15 @@ _timing: PerformanceTiming = .{},
_navigation: PerformanceNavigation = .{},
_event_counts: EventCounts = .{},
_resource_buffer_size: u32 = DEFAULT_RESOURCE_BUFFER_SIZE,
-
-// The owner's task scheduler, set by the owner once its JS context exists
-// (Frame builds the Window, and thus this, before the context). Never taken
-// from a caller's Execution: an isolated-world or cross-frame caller's
-// context can be destroyed while we live on.
+_buffer_full_pending: bool = false,
+_on_buffer_full: ?js.Function.Global = null,
+
+// The owner's task scheduler and its main-world Execution, both set by the
+// owner once its JS context exists (Frame builds the Window, and thus this,
+// before the context) - see attach. Never taken from a caller's Execution: an
+// isolated-world or cross-frame caller's context can be destroyed while we
+// live on.
+_exec: *Execution = undefined,
_scheduler: *Scheduler = undefined,
// PerformanceObserver infrastructure. Lives here (rather than on the owning
@@ -73,12 +84,22 @@ pub fn highResTimestamp() u64 {
return rounded;
}
-pub fn init(factory: *Factory, arena: Allocator) Performance {
- return .{
+pub fn init(factory: *Factory, arena: Allocator) !*Performance {
+ return factory.eventTarget(Performance{
+ ._proto = undefined,
._arena = arena,
._factory = factory,
._time_origin = highResTimestamp(),
- };
+ });
+}
+
+pub fn attach(self: *Performance, ctx: *js.Context) void {
+ self._exec = &ctx.execution;
+ self._scheduler = &ctx.scheduler;
+}
+
+pub fn asEventTarget(self: *Performance) *EventTarget {
+ return self._proto;
}
pub fn getTiming(self: *Performance) *PerformanceTiming {
@@ -263,11 +284,12 @@ pub const ResourceInfo = struct {
};
pub fn addResource(self: *Performance, info: ResourceInfo) !void {
- // TODO: Perfomance should be an EventTarget and it should fire
- // a resourcetimingbufferfull event
const buffer_full = self._resources.items.len >= self._resource_buffer_size;
- if (buffer_full and !self.hasObserverFor(.resource)) {
- return;
+ if (buffer_full) {
+ try self.scheduleBufferFull();
+ if (self.hasObserverFor(.resource) == false) {
+ return;
+ }
}
const arena = self._arena;
@@ -571,6 +593,54 @@ fn hasObserverFor(self: *const Performance, kind: Entry.Type.Enum) bool {
return false;
}
+// https://w3c.github.io/resource-timing/#dfn-fire-a-buffer-full-event
+// The event is queued rather than fired inline: addResource runs from the
+// HTTP layer, with no JS on the stack. We have no secondary buffer, so an
+// entry that overflows is dropped instead of being copied back in by a
+// handler that calls clearResourceTimings.
+fn scheduleBufferFull(self: *Performance) !void {
+ if (self._buffer_full_pending) {
+ return;
+ }
+ if (self._exec.hasDirectListeners(self.asEventTarget(), BUFFER_FULL, self._on_buffer_full) == false) {
+ return;
+ }
+ self._buffer_full_pending = true;
+
+ return self._scheduler.add(
+ self,
+ struct {
+ fn run(_self: *anyopaque) anyerror!?u32 {
+ const perf: *Performance = @ptrCast(@alignCast(_self));
+ perf._buffer_full_pending = false;
+
+ const exec = perf._exec;
+ const event = try Event.initTrusted(.wrap(BUFFER_FULL), .{}, exec.page);
+ try exec.dispatch(perf.asEventTarget(), event, perf._on_buffer_full, .{
+ .context = "Performance.resourcetimingbufferfull",
+ });
+ return null;
+ }
+ }.run,
+ 0,
+ .{ .name = "Performance.bufferFull" },
+ );
+}
+
+// The property handler for a JS-side dispatchEvent (see EventManager.dispatch).
+pub fn inlineHandler(self: *const Performance, typ: lp.String) ?js.Function.Global {
+ if (typ.eql(.wrap(BUFFER_FULL))) return self._on_buffer_full;
+ return null;
+}
+
+pub fn getOnResourceTimingBufferFull(self: *const Performance) ?js.Function.Global {
+ return self._on_buffer_full;
+}
+
+pub fn setOnResourceTimingBufferFull(self: *Performance, cb: ?js.Function.Global) void {
+ self._on_buffer_full = cb;
+}
+
pub fn scheduleDelivery(self: *Performance) !void {
if (self._delivery_scheduled) {
return;
@@ -684,6 +754,7 @@ pub const JsApi = struct {
pub const timing = bridge.accessor(Performance.getTiming, null, .{ .exposed = .window });
pub const navigation = bridge.accessor(Performance.getNavigation, null, .{ .exposed = .window });
pub const eventCounts = bridge.accessor(Performance.getEventCounts, null, .{ .exposed = .window });
+ pub const onresourcetimingbufferfull = bridge.accessor(Performance.getOnResourceTimingBufferFull, Performance.setOnResourceTimingBufferFull, .{});
};
pub const Entry = struct {
@@ -1184,6 +1255,7 @@ test "WebApi: Performance" {
test "WebApi: Performance.resource_timing" {
try testing.htmlRunner("performance_resource_timing.html", .{});
try testing.htmlRunner("performance_resource_timing_buffer.html", .{});
+ try testing.htmlRunner("performance_resource_timing_buffer_full.html", .{});
}
test "Performance: minimizeMimeType" {
diff --git a/src/browser/webapi/Window.zig b/src/browser/webapi/Window.zig
index b3af3c0e4..992282d1d 100644
--- a/src/browser/webapi/Window.zig
+++ b/src/browser/webapi/Window.zig
@@ -74,7 +74,7 @@ _navigator: Navigator = .init,
_model_context: ModelContext = .init,
_screen: *Screen,
_visual_viewport: *VisualViewport,
-_performance: Performance,
+_performance: *Performance,
_cookie_store: ?*CookieStore = null,
_idb_factory: ?*idb.IDBFactory = null,
_on_load: ?js.Function.Global = null,
@@ -279,7 +279,7 @@ pub fn getCSS(self: *Window) *CSS {
}
pub fn getPerformance(self: *Window) *Performance {
- return &self._performance;
+ return self._performance;
}
pub fn setPerformance(self: *Window, value: js.Value) void {
diff --git a/src/browser/webapi/WorkerGlobalScope.zig b/src/browser/webapi/WorkerGlobalScope.zig
index 8bcf7f25b..a6ca4331d 100644
--- a/src/browser/webapi/WorkerGlobalScope.zig
+++ b/src/browser/webapi/WorkerGlobalScope.zig
@@ -106,7 +106,7 @@ _proto: *EventTarget,
_console: Console = .init,
_crypto: Crypto = .init,
_navigator: WorkerNavigator = .init,
-_performance: Performance,
+_performance: *Performance,
_idb_factory: ?*idb.IDBFactory = null,
_on_error: ?JS.Function.Global = null,
_on_rejection_handled: ?JS.Function.Global = null,
@@ -166,7 +166,7 @@ pub fn init(
._event_manager = .init(arena),
._script_manager = undefined,
._location = .{ ._url = url },
- ._performance = .init(factory, arena),
+ ._performance = try .init(factory, arena),
._http_owner = undefined,
},
leaf_value,
@@ -184,7 +184,7 @@ pub fn init(
.loader_id = loader_id,
.cookie_jar = &session.cookie_jar,
.notification = session.notification,
- .performance = &self._performance,
+ .performance = self._performance,
};
self._script_manager = ScriptManagerBase.init(
@@ -199,7 +199,7 @@ pub fn init(
.identity_arena = arena,
.identity = &self._identity,
});
- self._performance._scheduler = &self.js.scheduler;
+ self._performance.attach(self.js);
// A dedicated worker is in the same agent cluster and inherits its creator's
// origin. Adopt the parent frame's origin (shared *Origin + v8 security
@@ -319,7 +319,7 @@ pub fn getScheduler(self: *WorkerGlobalScope) *Scheduler {
}
pub fn performance(self: *WorkerGlobalScope) *Performance {
- return &self._performance;
+ return self._performance;
}
pub fn getLocation(self: *WorkerGlobalScope) *WorkerLocation {