Skip to content

Lightpanda: the headless browser designed for AI and automation

webapi: add performance secondary buffer

Karl Seguincc20df782f29
diff --git a/src/browser/tests/performance_resource_timing_buffer_full.html b/src/browser/tests/performance_resource_timing_buffer_full.html
index 806b6a8e7..6acee14a6 100644
--- a/src/browser/tests/performance_resource_timing_buffer_full.html
+++ b/src/browser/tests/performance_resource_timing_buffer_full.html
@@ -1,6 +1,68 @@
<!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;
+ let fired = null;
+ const nextFire = () => new Promise((resolve) => fired = resolve);
+ // The event's task copies the secondary buffer back after the dispatch,
+ // and microtasks run between listeners, so give it a task to finish.
+ const nextTask = () => new Promise((resolve) => setTimeout(resolve));
+
+ performance.onresourcetimingbufferfull = (e) => {
+ event = e;
+ order.push('handler');
+ };
+ performance.addEventListener('resourcetimingbufferfull', () => {
+ order.push('listener');
+ fired();
+ });
+
+ let firing = nextFire();
+ await (await fetch(testing.ORIGIN + '/xhr')).text();
+ await firing;
+ await nextTask();
+ // The handler made no room, so the entry is dropped.
+ const dropped = performance.getEntriesByType('resource').length;
+
+ // A handler that makes room gets the overflowed entry copied in.
+ performance.onresourcetimingbufferfull = () => {
+ order.push('grow');
+ performance.setResourceTimingBufferSize(1);
+ };
+ firing = nextFire();
+ await (await fetch(testing.ORIGIN + '/xhr/json')).text();
+ await firing;
+ await nextTask();
+ const copied = performance.getEntriesByType('resource');
+ state.resolve();
+
+ await state.done(() => {
+ performance.onresourcetimingbufferfull = null;
+ testing.expectEqual(['handler', 'listener', 'grow', '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);
+ testing.expectEqual(0, dropped);
+ testing.expectEqual(1, copied.length);
+ testing.expectEqual(true, copied[0].name.endsWith('/xhr/json'));
+ });
+ }
+</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>
diff --git a/src/browser/webapi/Performance.zig b/src/browser/webapi/Performance.zig
index 076b68316..96dbf84a9 100644
--- a/src/browser/webapi/Performance.zig
+++ b/src/browser/webapi/Performance.zig
@@ -56,6 +56,9 @@ _entries: std.ArrayList(*Entry) = .empty,
// resources has its own cap, so it's split from entries (it's also potentially
// polled more)
_resources: std.ArrayList(*Entry) = .empty,
+// Entries that arrive while the buffer is full. Get copied into _resources
+// if a handler makes room.
+_secondary_resources: std.ArrayList(*Entry) = .empty,
_timing: PerformanceTiming = .{},
_navigation: PerformanceNavigation = .{},
_event_counts: EventCounts = .{},
@@ -289,10 +292,13 @@ const ResourceInfo = struct {
};
pub fn addResource(self: *Performance, info: ResourceInfo) !void {
- const buffer_full = self._resources.items.len >= self._resource_buffer_size;
- if (buffer_full) {
+ var buffer: ?*std.ArrayList(*Entry) = &self._resources;
+ if (self._buffer_full_pending or self.canAddResource() == false) {
try self.scheduleBufferFull();
- if (self.hasObserverFor(.resource) == false) {
+ buffer = if (self._buffer_full_pending) &self._secondary_resources else null;
+ if (buffer == null and self.hasObserverFor(.resource) == false) {
+ // There's no listener, so nothing can copy from our secondary, so
+ // we just drop it
return;
}
}
@@ -338,11 +344,15 @@ pub fn addResource(self: *Performance, info: ResourceInfo) !void {
rt._proto._type = .{ .resource = rt };
// 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);
+ if (buffer) |b| {
+ try self.insertOrdered(b, rt._proto);
}
}
+fn canAddResource(self: *const Performance) bool {
+ return self._resources.items.len < self._resource_buffer_size;
+}
+
fn gated(self: *const Performance, allow: bool, micros: u64) f64 {
return if (allow) self.relative(micros) else 0;
}
@@ -598,11 +608,8 @@ 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.
+// HTTP layer, with no JS on the stack.
fn scheduleBufferFull(self: *Performance) !void {
if (self._buffer_full_pending) {
return;
@@ -617,13 +624,10 @@ fn scheduleBufferFull(self: *Performance) !void {
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.bufferfull",
- });
+ // only reset _after_ the handler runs, so that entries that get
+ // added go to the secondary buffer
+ defer perf._buffer_full_pending = false;
+ try perf.fireBufferFull();
return null;
}
}.run,
@@ -632,6 +636,35 @@ fn scheduleBufferFull(self: *Performance) !void {
);
}
+// https://w3c.github.io/resource-timing/#dfn-fire-a-buffer-full-event
+fn fireBufferFull(self: *Performance) !void {
+ const secondary = &self._secondary_resources;
+ while (secondary.items.len > 0) {
+ const excess_before = secondary.items.len;
+ if (self.canAddResource() == false) {
+ const exec = self._exec;
+ const event = try Event.initTrusted(.wrap(BUFFER_FULL), .{}, exec.page);
+ try exec.dispatch(self.asEventTarget(), event, self._on_buffer_full, .{
+ .context = "Performance.bufferfull",
+ });
+ }
+ {
+ // copy the secondary buffers
+ var copied: usize = 0;
+ while (copied < secondary.items.len and self.canAddResource()) : (copied += 1) {
+ try self.insertOrdered(&self._resources, secondary.items[copied]);
+ }
+ secondary.replaceRangeAssumeCapacity(0, copied, &.{});
+ }
+
+ if (secondary.items.len >= excess_before) {
+ // The handler didn't make room for any of them, give up
+ secondary.clearRetainingCapacity();
+ return;
+ }
+ }
+}
+
// 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;