Lightpanda: the headless browser designed for AI and automation
Performance capture schedule and notify when full
Karl Seguin1034ed873265
diff --git a/src/browser/Frame.zig b/src/browser/Frame.zigindex 47396a5a5..dff8f8bd5 100644--- a/src/browser/Frame.zig+++ b/src/browser/Frame.zig@@ -474,6 +474,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;const location = try Location.init("about:blank", self);// We're holding a reference in Zig-side.diff --git a/src/browser/tests/performance_observer/performance_observer.html b/src/browser/tests/performance_observer/performance_observer.htmlindex 82708e947..477e2666e 100644--- a/src/browser/tests/performance_observer/performance_observer.html+++ b/src/browser/tests/performance_observer/performance_observer.html@@ -174,3 +174,36 @@});}</script>++<script id="observe_mode_is_fixed">+{+ const observer = new PerformanceObserver(() => {});+ observer.observe({ entryTypes: ["mark"] });+ testing.expectError("InvalidModificationError", () => observer.observe({ type: "mark" }));+ observer.disconnect();++ const single = new PerformanceObserver(() => {});+ single.observe({ type: "mark" });+ testing.expectError("InvalidModificationError", () => single.observe({ entryTypes: ["mark"] }));+ testing.expectError("TypeError", () => single.observe({ type: "mark", entryTypes: ["mark"] }));+ testing.expectError("TypeError", () => single.observe({}));+ single.disconnect();+}+</script>++<script id="buffered_ignored_with_entry_types" type=module>+{+ const state = await testing.async();+ performance.mark("before_observer");+ // Like every engine (and unlike the spec's TypeError), buffered is+ // ignored alongside entryTypes: no past entry is delivered.+ let delivered = 0;+ const observer = new PerformanceObserver((list) => { delivered += list.getEntries().length; });+ observer.observe({ entryTypes: ["mark"], buffered: true });+ setTimeout(() => state.resolve(), 20);+ await state.done(() => {+ observer.disconnect();+ testing.expectEqual(0, delivered);+ });+}+</script>diff --git a/src/browser/tests/performance_resource_timing_buffer.html b/src/browser/tests/performance_resource_timing_buffer.htmlindex 0a9d24f83..ce34783e7 100644--- a/src/browser/tests/performance_resource_timing_buffer.html+++ b/src/browser/tests/performance_resource_timing_buffer.html@@ -10,14 +10,22 @@testing.expectEqual(0, performance.getEntriesByType('resource').length);performance.setResourceTimingBufferSize(1);+ const observed = [];+ const observer = new PerformanceObserver((list) => {+ for (const e of list.getEntries()) observed.push(e.name);+ if (observed.length === 2) state.resolve();+ });+ observer.observe({ type: 'resource' });await (await fetch(testing.ORIGIN + '/xhr')).text();await (await fetch(testing.ORIGIN + '/xhr/json')).text();- state.resolve();await state.done(() => {- // The buffer was full: the second fetch's entry is dropped.+ observer.disconnect();+ // The buffer was full: the second fetch's entry is dropped from the+ // buffer, but the observer still sees it.const list = performance.getEntriesByType('resource');testing.expectEqual(1, list.length);testing.expectEqual(testing.ORIGIN + '/xhr', list[0].name);+ testing.expectEqual([testing.ORIGIN + '/xhr', testing.ORIGIN + '/xhr/json'], observed);testing.expectEqual(0, performance.getEntries().filter((e) => e.entryType !== 'resource').length);// getEntries merges marks and resources in startTime order.diff --git a/src/browser/webapi/Performance.zig b/src/browser/webapi/Performance.zigindex 692d69438..6d6ed008b 100644--- a/src/browser/webapi/Performance.zig+++ b/src/browser/webapi/Performance.zig@@ -21,6 +21,7 @@ const lp = @import("lightpanda");const js = @import("../js/js.zig");const Factory = @import("../Factory.zig");+const Scheduler = @import("../js/Scheduler.zig");const EventCounts = @import("EventCounts.zig");const PerformanceObserver = @import("PerformanceObserver.zig");@@ -51,9 +52,11 @@ _navigation: PerformanceNavigation = .{},_event_counts: EventCounts = .{},_resource_buffer_size: u32 = DEFAULT_RESOURCE_BUFFER_SIZE,-// Captured when the first observer registers. Entries created outside of-// JS (resource timing, from the HTTP client) need it to notify observers.-_exec: ?*const Execution = null,+// 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.+_scheduler: *Scheduler = undefined,// PerformanceObserver infrastructure. Lives here (rather than on the owning// Frame/WorkerGlobalScope) so that both contexts get observers for free.@@ -112,7 +115,7 @@ pub fn mark(const start_time = opts.startTime orelse self.now();const m = try Mark.init(name, opts.detail, start_time, exec);try self.insertOrdered(&self._entries, m._proto);- try self.notifyObservers(m._proto, exec);+ try self.notifyObservers(m._proto);return m;}@@ -163,7 +166,7 @@ pub fn measure(exec,);try self.insertOrdered(&self._entries, m._proto);- try self.notifyObservers(m._proto, exec);+ try self.notifyObservers(m._proto);return m;},.start_mark => |start_mark| {@@ -187,14 +190,14 @@ pub fn measure(exec,);try self.insertOrdered(&self._entries, m._proto);- try self.notifyObservers(m._proto, exec);+ try self.notifyObservers(m._proto);return m;},};const m = try Measure.init(name, null, 0.0, self.now(), null, exec);try self.insertOrdered(&self._entries, m._proto);- try self.notifyObservers(m._proto, exec);+ try self.notifyObservers(m._proto);return m;}@@ -260,9 +263,10 @@ pub const ResourceInfo = struct {};pub fn addResource(self: *Performance, info: ResourceInfo) !void {- if (self._resources.items.len >= self._resource_buffer_size) {- // TODO: Perfomance should be an EventTarget and it should fire- // a resourcetimingbufferfull event+ // 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;}@@ -305,10 +309,10 @@ pub fn addResource(self: *Performance, info: ResourceInfo) !void {},});rt._proto._type = .{ .resource = rt };- try self.insertOrdered(&self._resources, rt._proto);-- if (self._exec) |exec| {- try self.notifyObservers(rt._proto, exec);+ // Observers see every entry; only the buffer has a cap.+ try self.notifyObservers(rt._proto);+ if (!buffer_full) {+ try self.insertOrdered(&self._resources, rt._proto);}}@@ -519,8 +523,7 @@ fn getMarkTime(self: *const Performance, mark_name: []const u8) !f64 {return error.SyntaxError; // Mark not found}-pub fn registerObserver(self: *Performance, observer: *PerformanceObserver, exec: *const Execution) !void {- self._exec = exec;+pub fn registerObserver(self: *Performance, observer: *PerformanceObserver) !void {for (self._observers.items) |o| {if (o == observer) {return;@@ -544,28 +547,37 @@ pub fn unregisterObserver(self: *Performance, observer: *PerformanceObserver) vo/// Append the entry to every interested observer's queue and schedule async/// delivery. Does NOT fire the callbacks synchronously — that happens later/// via the scheduled task.-pub fn notifyObservers(self: *Performance, entry: *Entry, exec: *const Execution) !void {+fn notifyObservers(self: *Performance, entry: *Entry) !void {if (self._observers.items.len == 0) {return;}for (self._observers.items) |observer| {if (observer.interested(entry)) {- observer._entries.append(exec.arena, entry) catch |err| {+ observer._entries.append(observer._arena, entry) catch |err| {lp.log.err(.frame, "Performance.notifyObservers", .{ .err = err });};}}- try self.scheduleDelivery(exec);+ try self.scheduleDelivery();+}++fn hasObserverFor(self: *const Performance, kind: Entry.Type.Enum) bool {+ for (self._observers.items) |observer| {+ if (observer.interestedIn(kind)) {+ return true;+ }+ }+ return false;}-pub fn scheduleDelivery(self: *Performance, exec: *const Execution) !void {+pub fn scheduleDelivery(self: *Performance) !void {if (self._delivery_scheduled) {return;}self._delivery_scheduled = true;- return exec._scheduler.add(+ return self._scheduler.add(self,struct {fn run(_self: *anyopaque) anyerror!?u32 {diff --git a/src/browser/webapi/PerformanceObserver.zig b/src/browser/webapi/PerformanceObserver.zigindex b3e64db1c..58fce5392 100644--- a/src/browser/webapi/PerformanceObserver.zig+++ b/src/browser/webapi/PerformanceObserver.zig@@ -39,6 +39,9 @@ _callback: js.Function.Global,_duration_threshold: f64,/// Entry types we're looking for are encoded as bit flags._interests: u16,+/// Fixed by the first observe(): a `type` observer can't later observe+/// `entryTypes`, nor the reverse.+_mode: enum { unset, single, multiple } = .unset,/// Entries this observer hold./// Don't mutate these; other observers may hold pointers to them._entries: std.ArrayList(*Performance.Entry),@@ -73,7 +76,7 @@ const ObserveOptions = struct {type: ?[]const u8 = null,};-pub fn observe(self: *PerformanceObserver, maybe_options: ?ObserveOptions, exec: *const Execution) !void {+pub fn observe(self: *PerformanceObserver, maybe_options: ?ObserveOptions) !void {const options: ObserveOptions = maybe_options orelse .{};// Update threshold.self._duration_threshold = @max(@floor(options.durationThreshold / 8) * 8, 16);@@ -85,11 +88,21 @@ pub fn observe(self: *PerformanceObserver, maybe_options: ?ObserveOptions, exec:if (options.entryTypes != null) {return error.TypeError;}-+ if (self._mode == .multiple) {+ return error.InvalidModification;+ }+ self._mode = .single;break :blk &.{entry_type};}if (options.entryTypes) |entry_types| {+ // The spec wants a TypeError when `buffered` (or+ // `durationThreshold`) is used with entryTypes. But neither firefox+ // nor Chrome throw (Chrome does log an warning). They ignore it.+ if (self._mode == .single) {+ return error.InvalidModification;+ }+ self._mode = .multiple;break :blk entry_types;}@@ -116,15 +129,14 @@ pub fn observe(self: *PerformanceObserver, maybe_options: ?ObserveOptions, exec:// If we had no interests before, it means the Performance is not aware// of this observer.if (self._interests == 0) {- try self._performance.registerObserver(self, exec);+ try self._performance.registerObserver(self);}// Update interests.self._interests = interests;- // Deliver existing entries if buffered option is set.- // Per spec, buffered is only valid with the type option, not entryTypes.- // Delivery is async via a queued task, not synchronous.+ // Deliver existing entries if buffered option is set (only honoured+ // with `type`, see above). Delivery is async via a queued task.if (options.buffered and options.type != null and !self.hasRecords()) {for ([_][]const *Performance.Entry{ self._performance._entries.items, self._performance._resources.items }) |list| {for (list) |entry| {@@ -134,7 +146,7 @@ pub fn observe(self: *PerformanceObserver, maybe_options: ?ObserveOptions, exec:}}if (self.hasRecords()) {- try self._performance.scheduleDelivery(exec);+ try self._performance.scheduleDelivery();}}}@@ -166,7 +178,11 @@ pub fn interested(self: *const PerformanceObserver,entry: *const Performance.Entry,) bool {- const flag = @as(u16, 1) << @intCast(@intFromEnum(entry._type));+ return self.interestedIn(entry._type);+}++pub fn interestedIn(self: *const PerformanceObserver, kind: Performance.Entry.Type.Enum) bool {+ const flag = @as(u16, 1) << @intCast(@intFromEnum(kind));return self._interests & flag != 0;}diff --git a/src/browser/webapi/WorkerGlobalScope.zig b/src/browser/webapi/WorkerGlobalScope.zigindex 9db3df817..c789d16e7 100644--- a/src/browser/webapi/WorkerGlobalScope.zig+++ b/src/browser/webapi/WorkerGlobalScope.zig@@ -199,6 +199,7 @@ pub fn init(.identity_arena = arena,.identity = &self._identity,});+ self._performance._scheduler = &self.js.scheduler;// 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