Skip to content

Lightpanda: the headless browser designed for AI and automation

Simplify Inspector.Session ownership

Karl Seguin9aa748616b00
diff --git a/src/browser/js/Env.zig b/src/browser/js/Env.zig
index ef43ba993..799ed3b9f 100644
--- a/src/browser/js/Env.zig
+++ b/src/browser/js/Env.zig
@@ -245,7 +245,7 @@ pub fn deinit(self: *Env) void {
const allocator = app.allocator;
if (self.inspector) |i| {
- i.deinit();
+ i.deinit(allocator);
}
allocator.free(self.templates);
diff --git a/src/browser/js/Inspector.zig b/src/browser/js/Inspector.zig
index 22c876f7d..94d467ec8 100644
--- a/src/browser/js/Inspector.zig
+++ b/src/browser/js/Inspector.zig
@@ -17,7 +17,6 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
const std = @import("std");
-const lp = @import("lightpanda");
const js = @import("js.zig");
const v8 = js.v8;
@@ -37,29 +36,22 @@ const CLIENT_TRUST_LEVEL = 1;
// (not much at all)
const Inspector = @This();
-allocator: Allocator,
unique_id: i64,
isolate: *v8.Isolate,
handle: *v8.Inspector,
client: *v8.InspectorClientImpl,
default_context: ?v8.Global,
-/// One per CDP session attached to the page target; all connect to the same
-/// `CONTEXT_GROUP_ID`, so every session sees every context. Heap allocated
-/// because the V8 channel keeps the session's address (SET_DATA).
-sessions: std.ArrayListUnmanaged(*Session),
pub fn init(allocator: Allocator, isolate: *v8.Isolate) !*Inspector {
const self = try allocator.create(Inspector);
errdefer allocator.destroy(self);
self.* = .{
- .allocator = allocator,
.unique_id = 1,
.isolate = isolate,
.client = undefined,
.handle = undefined,
.default_context = null,
- .sessions = .empty,
};
self.client = v8.v8_inspector__Client__IMPL__CREATE();
@@ -72,39 +64,14 @@ pub fn init(allocator: Allocator, isolate: *v8.Isolate) !*Inspector {
return self;
}
-pub fn deinit(self: *Inspector) void {
+pub fn deinit(self: *const Inspector, allocator: Allocator) void {
var hs: v8.HandleScope = undefined;
v8.v8__HandleScope__CONSTRUCT(&hs, self.isolate);
defer v8.v8__HandleScope__DESTRUCT(&hs);
- for (self.sessions.items) |session| {
- session.deinit();
- self.allocator.destroy(session);
- }
- self.sessions.deinit(self.allocator);
-
v8.v8_inspector__Client__IMPL__DELETE(self.client);
v8.v8_inspector__Inspector__DELETE(self.handle);
- self.allocator.destroy(self);
-}
-
-pub fn startSession(self: *Inspector, ctx: anytype) !*Session {
- const session = try self.allocator.create(Session);
- errdefer self.allocator.destroy(session);
-
- Session.init(session, self, ctx);
- errdefer session.deinit();
-
- try self.sessions.append(self.allocator, session);
- return session;
-}
-
-pub fn stopSession(self: *Inspector, session: *Session) void {
- const index = std.mem.findScalar(*Session, self.sessions.items, session);
- lp.assert(index != null, "Inspector.stopSession unknown session", .{});
- _ = self.sessions.swapRemove(index.?);
- session.deinit();
- self.allocator.destroy(session);
+ allocator.destroy(self);
}
// From CDP docs
@@ -211,7 +178,10 @@ const RemoteObject = struct {
// Combines a v8::InspectorSession and a v8::InspectorChannelImpl. The
// InspectorSession is for zig -> v8 (sending messages to the inspector). The
// Channel is for v8 -> zig, getting events from the Inspector (that we'll pass
-// back to some opaque context, i.e the CDP BrowserContext).
+// back to some opaque context, i.e the CDP AttachedSession).
+// The channel keeps the Session's address, so the owner must not move it
+// between init and deinit. Every Session connects to the same
+// CONTEXT_GROUP_ID and so sees every context.
// The channel callbacks are defined below, as:
// pub export fn v8_inspector__Channel__IMPL__XYZ
pub const Session = struct {
@@ -224,7 +194,7 @@ pub const Session = struct {
onNotif: *const fn (ctx: *anyopaque, msg: []const u8) void,
onResp: *const fn (ctx: *anyopaque, call_id: u32, msg: []const u8) void,
- fn init(self: *Session, inspector: *Inspector, ctx: anytype) void {
+ pub fn init(self: *Session, inspector: *Inspector, ctx: anytype) void {
const Container = @typeInfo(@TypeOf(ctx)).pointer.child;
const channel = v8.v8_inspector__Channel__IMPL__CREATE(inspector.isolate);
@@ -246,11 +216,23 @@ pub const Session = struct {
};
}
- fn deinit(self: *const Session) void {
+ pub fn deinit(self: *Session) void {
+ // Deleting the V8 session fails its pending evaluations, which V8
+ // answers through the channel. The client is gone: drop them.
+ self.onResp = dropResponse;
+ self.onNotif = dropNotification;
+
+ var hs: v8.HandleScope = undefined;
+ v8.v8__HandleScope__CONSTRUCT(&hs, self.inspector.isolate);
+ defer v8.v8__HandleScope__DESTRUCT(&hs);
+
v8.v8_inspector__Session__DELETE(self.handle);
v8.v8_inspector__Channel__IMPL__DELETE(self.channel);
}
+ fn dropResponse(_: *anyopaque, _: u32, _: []const u8) void {}
+ fn dropNotification(_: *anyopaque, _: []const u8) void {}
+
pub fn send(self: *const Session, msg: []const u8) void {
const isolate = self.inspector.isolate;
var hs: v8.HandleScope = undefined;
diff --git a/src/server/cdp/CDP.zig b/src/server/cdp/CDP.zig
index 99d54f603..0a4e74cf9 100644
--- a/src/server/cdp/CDP.zig
+++ b/src/server/cdp/CDP.zig
@@ -405,7 +405,7 @@ pub const BrowserContext = struct {
id: []const u8,
parent_id: ?[]const u8,
bc: *BrowserContext,
- inspector_session: *js.Inspector.Session,
+ inspector_session: js.Inspector.Session,
/// V8 -> this session. Stamp OUR id on responses and events.
pub fn onInspectorResponse(ctx: *anyopaque, _: u32, msg: []const u8) void {
@@ -1194,15 +1194,15 @@ pub const BrowserContext = struct {
const attached = try allocator.create(AttachedSession);
errdefer allocator.destroy(attached);
- const inspector_session = try self.inspector().startSession(attached);
- errdefer self.inspector().stopSession(inspector_session);
-
attached.* = .{
.id = try self.arena.dupe(u8, session_id),
.parent_id = parent_id,
.bc = self,
- .inspector_session = inspector_session,
+ .inspector_session = undefined,
};
+ attached.inspector_session.init(self.inspector(), attached);
+ errdefer attached.inspector_session.deinit();
+
try self.attached_sessions.put(allocator, attached.id, attached);
return attached;
}
@@ -1237,14 +1237,14 @@ pub const BrowserContext = struct {
}
fn destroySession(self: *BrowserContext, attached: *AttachedSession) void {
- self.inspector().stopSession(attached.inspector_session);
+ attached.inspector_session.deinit();
self.cdp.allocator.destroy(attached);
}
pub fn inspectorSession(self: *const BrowserContext, session_id: ?[]const u8) !*js.Inspector.Session {
const id = session_id orelse self.session_id orelse return error.SessionNotAttached;
const attached = self.attached_sessions.get(id) orelse return error.SessionNotAttached;
- return attached.inspector_session;
+ return &attached.inspector_session;
}
/// Forwards `cmd`'s raw JSON to the inspector session of the session it was sent through.
diff --git a/src/server/cdp/domains/target.zig b/src/server/cdp/domains/target.zig
index c5fcc9528..1958b7d08 100644
--- a/src/server/cdp/domains/target.zig
+++ b/src/server/cdp/domains/target.zig
@@ -1061,7 +1061,6 @@ test "cdp.target: detachFromTarget releases the auxiliary session's inspector se
try ctx.expectSentEvent("Target.detachedFromTarget", .{ .sessionId = "SID-AUX" }, .{});
try ctx.expectSentResult(null, .{ .id = 11 });
try testing.expectEqual(1, bc.attached_sessions.count());
- try testing.expectEqual(1, bc.inspector().sessions.items.len);
try ctx.processMessage(.{ .id = 12, .method = "Runtime.evaluate", .sessionId = "SID-AUX", .params = .{ .expression = "1 + 1", .returnByValue = true } });
try ctx.expectSentError(-32001, "Unknown sessionId", .{ .id = 12 });
@@ -1070,6 +1069,39 @@ test "cdp.target: detachFromTarget releases the auxiliary session's inspector se
try ctx.expectSentResult(.{ .result = .{ .type = "number", .value = 4 } }, .{ .id = 13, .session_id = "SID-PRIMARY" });
}
+// Stopping an inspector session fails its pending evaluations. The client was
+// already told the session is detached, so, like Chrome, nothing more is sent.
+test "cdp.target: detachFromTarget drops the auxiliary session's pending responses" {
+ var ctx = try testing.context();
+ defer ctx.deinit();
+ const bc = try ctx.loadBrowserContext(.{
+ .id = "BID-9",
+ .url = "hi.html",
+ .session_id = "SID-PRIMARY",
+ .target_id = "TID-000000000B".*,
+ });
+ _ = try bc.attachSession("SID-AUX", null);
+
+ try ctx.processMessage(.{ .id = 10, .method = "Runtime.enable", .sessionId = "SID-AUX" });
+ try ctx.expectSentResult(null, .{ .id = 10, .session_id = "SID-AUX" });
+ try ctx.processMessage(.{ .id = 11, .method = "Runtime.evaluate", .sessionId = "SID-AUX", .params = .{ .expression = "({a: 1})" } });
+ try ctx.expectSentResult(.{ .result = .{ .type = "object" } }, .{ .id = 11, .session_id = "SID-AUX" });
+ try ctx.processMessage(.{ .id = 12, .method = "Runtime.evaluate", .sessionId = "SID-AUX", .params = .{ .expression = "new Promise(() => {})", .awaitPromise = true } });
+
+ try ctx.processMessage(.{ .id = 13, .method = "Target.detachFromTarget", .params = .{ .sessionId = "SID-AUX" } });
+ try ctx.expectSentEvent("Target.detachedFromTarget", .{ .sessionId = "SID-AUX" }, .{});
+ try ctx.expectSentResult(null, .{ .id = 13 });
+
+ var i: usize = 0;
+ while (try ctx.getSentMessage(i)) |msg| : (i += 1) {
+ const msg_id = msg.object.get("id") orelse continue;
+ try testing.expect(msg_id != .integer or msg_id.integer != 12);
+ }
+
+ try ctx.processMessage(.{ .id = 14, .method = "Runtime.evaluate", .sessionId = "SID-PRIMARY", .params = .{ .expression = "2 + 2", .returnByValue = true } });
+ try ctx.expectSentResult(.{ .result = .{ .type = "number", .value = 4 } }, .{ .id = 14, .session_id = "SID-PRIMARY" });
+}
+
test "cdp.target: detachFromTarget without session" {
var ctx = try testing.context();
defer ctx.deinit();