server, cdp: improve logging

Signed-off-by: Francis Bouvier <francis@lightpanda.io>
This commit is contained in:
Francis Bouvier
2024-10-15 22:57:56 +02:00
parent 84c49fbe34
commit 8e05f09fc8
12 changed files with 180 additions and 45 deletions

View File

@@ -24,6 +24,8 @@ const cdp = @import("cdp.zig");
const result = cdp.result; const result = cdp.result;
const getMsg = cdp.getMsg; const getMsg = cdp.getMsg;
const log = std.log.scoped(.cdp);
const Methods = enum { const Methods = enum {
getVersion, getVersion,
setDownloadBehavior, setDownloadBehavior,
@@ -64,6 +66,7 @@ fn getVersion(
// input // input
const msg = try getMsg(alloc, _id, void, scanner); const msg = try getMsg(alloc, _id, void, scanner);
log.debug("Req > id {d}, method {s}", .{ msg.id, "browser.getVersion" });
// ouput // ouput
const Res = struct { const Res = struct {
@@ -92,6 +95,7 @@ fn setDownloadBehavior(
eventsEnabled: ?bool = null, eventsEnabled: ?bool = null,
}; };
const msg = try getMsg(alloc, _id, Params, scanner); const msg = try getMsg(alloc, _id, Params, scanner);
log.debug("REQ > id {d}, method {s}", .{ msg.id, "browser.setDownloadBehavior" });
// output // output
return result(alloc, msg.id, null, null, null); return result(alloc, msg.id, null, null, null);
@@ -113,6 +117,7 @@ fn getWindowForTarget(
}; };
const msg = try cdp.getMsg(alloc, _id, ?Params, scanner); const msg = try cdp.getMsg(alloc, _id, ?Params, scanner);
std.debug.assert(msg.sessionID != null); std.debug.assert(msg.sessionID != null);
log.debug("Req > id {d}, method {s}", .{ msg.id, "browser.getWindowForTarget" });
// output // output
const Resp = struct { const Resp = struct {
@@ -138,6 +143,7 @@ fn setWindowBounds(
// input // input
const msg = try cdp.getMsg(alloc, _id, void, scanner); const msg = try cdp.getMsg(alloc, _id, void, scanner);
log.debug("Req > id {d}, method {s}", .{ msg.id, "browser.setWindowBounds" });
// output // output
return result(alloc, msg.id, null, null, msg.sessionID); return result(alloc, msg.id, null, null, msg.sessionID);

View File

@@ -31,6 +31,8 @@ const emulation = @import("emulation.zig").emulation;
const fetch = @import("fetch.zig").fetch; const fetch = @import("fetch.zig").fetch;
const performance = @import("performance.zig").performance; const performance = @import("performance.zig").performance;
const log_cdp = std.log.scoped(.cdp);
pub const Error = error{ pub const Error = error{
UnknonwDomain, UnknonwDomain,
UnknownMethod, UnknownMethod,
@@ -95,7 +97,6 @@ pub fn do(
return error.WrongTokenType; return error.WrongTokenType;
} }
const method_name = method_token.string; const method_name = method_token.string;
std.log.debug("cmd: method {s}, id {any}", .{ method_name, id });
// retrieve domain from method // retrieve domain from method
var iter = std.mem.splitScalar(u8, method_name, '.'); var iter = std.mem.splitScalar(u8, method_name, '.');
@@ -154,7 +155,6 @@ pub fn dumpFile(
std.debug.assert(nb == script.len); std.debug.assert(nb == script.len);
const p = try dir.realpathAlloc(alloc, name); const p = try dir.realpathAlloc(alloc, name);
defer alloc.free(p); defer alloc.free(p);
std.log.debug("Script {d} saved at {s}", .{ id, p });
} }
fn checkKey(key: []const u8, token: []const u8) !void { fn checkKey(key: []const u8, token: []const u8) !void {
@@ -186,6 +186,10 @@ pub fn result(
res: anytype, res: anytype,
sessionID: ?[]const u8, sessionID: ?[]const u8,
) ![]const u8 { ) ![]const u8 {
log_cdp.debug(
"Res > id {d}, sessionID {?s}, result {any}",
.{ id, sessionID, res },
);
if (T == null) { if (T == null) {
// No need to stringify a custom JSON msg, just use string templates // No need to stringify a custom JSON msg, just use string templates
if (sessionID) |sID| { if (sessionID) |sID| {
@@ -212,6 +216,7 @@ pub fn sendEvent(
params: T, params: T,
sessionID: ?[]const u8, sessionID: ?[]const u8,
) !void { ) !void {
log_cdp.debug("Event > method {s}, sessionID {?s}", .{ name, sessionID });
const Resp = struct { const Resp = struct {
method: []const u8, method: []const u8,
params: T, params: T,
@@ -221,7 +226,6 @@ pub fn sendEvent(
const event_msg = try stringify(alloc, resp); const event_msg = try stringify(alloc, resp);
defer alloc.free(event_msg); defer alloc.free(event_msg);
std.log.debug("event {s}", .{event_msg});
try server.sendSync(ctx, event_msg); try server.sendSync(ctx, event_msg);
} }
@@ -307,10 +311,6 @@ pub fn getMsg(
} }
// end // end
std.log.debug(
"id {any}, params {any}, sessionID: {any}, token {any}",
.{ id, params, sessionID, t },
);
t = try scanner.next(); t = try scanner.next();
if (t != .end_of_document) return error.CDPMsgEnd; if (t != .end_of_document) return error.CDPMsgEnd;

View File

@@ -25,6 +25,8 @@ const result = cdp.result;
const getMsg = cdp.getMsg; const getMsg = cdp.getMsg;
const stringify = cdp.stringify; const stringify = cdp.stringify;
const log = std.log.scoped(.cdp);
const Methods = enum { const Methods = enum {
setEmulatedMedia, setEmulatedMedia,
setFocusEmulationEnabled, setFocusEmulationEnabled,
@@ -68,6 +70,7 @@ fn setEmulatedMedia(
features: ?[]MediaFeature = null, features: ?[]MediaFeature = null,
}; };
const msg = try getMsg(alloc, _id, Params, scanner); const msg = try getMsg(alloc, _id, Params, scanner);
log.debug("Req > id {d}, method {s}", .{ msg.id, "emulation.setEmulatedMedia" });
// output // output
return result(alloc, msg.id, null, null, msg.sessionID); return result(alloc, msg.id, null, null, msg.sessionID);
@@ -86,6 +89,7 @@ fn setFocusEmulationEnabled(
enabled: bool, enabled: bool,
}; };
const msg = try getMsg(alloc, _id, Params, scanner); const msg = try getMsg(alloc, _id, Params, scanner);
log.debug("Req > id {d}, method {s}", .{ msg.id, "emulation.setFocusEmulationEnabled" });
// output // output
return result(alloc, msg.id, null, null, msg.sessionID); return result(alloc, msg.id, null, null, msg.sessionID);
@@ -101,6 +105,7 @@ fn setDeviceMetricsOverride(
// input // input
const msg = try cdp.getMsg(alloc, _id, void, scanner); const msg = try cdp.getMsg(alloc, _id, void, scanner);
log.debug("Req > id {d}, method {s}", .{ msg.id, "emulation.setDeviceMetricsOverride" });
// output // output
return result(alloc, msg.id, null, null, msg.sessionID); return result(alloc, msg.id, null, null, msg.sessionID);
@@ -114,6 +119,7 @@ fn setTouchEmulationEnabled(
_: *Ctx, _: *Ctx,
) ![]const u8 { ) ![]const u8 {
const msg = try cdp.getMsg(alloc, _id, void, scanner); const msg = try cdp.getMsg(alloc, _id, void, scanner);
log.debug("Req > id {d}, method {s}", .{ msg.id, "emulation.setTouchEmulationEnabled" });
return result(alloc, msg.id, null, null, msg.sessionID); return result(alloc, msg.id, null, null, msg.sessionID);
} }

View File

@@ -24,6 +24,8 @@ const cdp = @import("cdp.zig");
const result = cdp.result; const result = cdp.result;
const getMsg = cdp.getMsg; const getMsg = cdp.getMsg;
const log = std.log.scoped(.cdp);
const Methods = enum { const Methods = enum {
disable, disable,
}; };
@@ -51,6 +53,7 @@ fn disable(
_: *Ctx, _: *Ctx,
) ![]const u8 { ) ![]const u8 {
const msg = try getMsg(alloc, _id, void, scanner); const msg = try getMsg(alloc, _id, void, scanner);
log.debug("Req > id {d}, method {s}", .{ msg.id, "fetch.disable" });
return result(alloc, msg.id, null, null, msg.sessionID); return result(alloc, msg.id, null, null, msg.sessionID);
} }

View File

@@ -25,6 +25,8 @@ const result = cdp.result;
const getMsg = cdp.getMsg; const getMsg = cdp.getMsg;
const stringify = cdp.stringify; const stringify = cdp.stringify;
const log_cdp = std.log.scoped(.cdp);
const Methods = enum { const Methods = enum {
enable, enable,
}; };
@@ -51,6 +53,7 @@ fn enable(
_: *Ctx, _: *Ctx,
) ![]const u8 { ) ![]const u8 {
const msg = try getMsg(alloc, _id, void, scanner); const msg = try getMsg(alloc, _id, void, scanner);
log_cdp.debug("Req > id {d}, method {s}", .{ msg.id, "log.enable" });
return result(alloc, msg.id, null, null, msg.sessionID); return result(alloc, msg.id, null, null, msg.sessionID);
} }

View File

@@ -24,6 +24,8 @@ const cdp = @import("cdp.zig");
const result = cdp.result; const result = cdp.result;
const getMsg = cdp.getMsg; const getMsg = cdp.getMsg;
const log = std.log.scoped(.cdp);
const Methods = enum { const Methods = enum {
enable, enable,
setCacheDisabled, setCacheDisabled,
@@ -51,7 +53,10 @@ fn enable(
scanner: *std.json.Scanner, scanner: *std.json.Scanner,
_: *Ctx, _: *Ctx,
) ![]const u8 { ) ![]const u8 {
// input
const msg = try getMsg(alloc, _id, void, scanner); const msg = try getMsg(alloc, _id, void, scanner);
log.debug("Req > id {d}, method {s}", .{ msg.id, "network.enable" });
return result(alloc, msg.id, null, null, msg.sessionID); return result(alloc, msg.id, null, null, msg.sessionID);
} }
@@ -63,7 +68,10 @@ fn setCacheDisabled(
scanner: *std.json.Scanner, scanner: *std.json.Scanner,
_: *Ctx, _: *Ctx,
) ![]const u8 { ) ![]const u8 {
// input
const msg = try getMsg(alloc, _id, void, scanner); const msg = try getMsg(alloc, _id, void, scanner);
log.debug("Req > id {d}, method {s}", .{ msg.id, "network.setCacheDisabled" });
return result(alloc, msg.id, null, null, msg.sessionID); return result(alloc, msg.id, null, null, msg.sessionID);
} }

View File

@@ -26,6 +26,8 @@ const getMsg = cdp.getMsg;
const stringify = cdp.stringify; const stringify = cdp.stringify;
const sendEvent = cdp.sendEvent; const sendEvent = cdp.sendEvent;
const log = std.log.scoped(.cdp);
const Runtime = @import("runtime.zig"); const Runtime = @import("runtime.zig");
const Methods = enum { const Methods = enum {
@@ -62,7 +64,11 @@ fn enable(
scanner: *std.json.Scanner, scanner: *std.json.Scanner,
_: *Ctx, _: *Ctx,
) ![]const u8 { ) ![]const u8 {
// input
const msg = try getMsg(alloc, _id, void, scanner); const msg = try getMsg(alloc, _id, void, scanner);
log.debug("Req > id {d}, method {s}", .{ msg.id, "page.enable" });
return result(alloc, msg.id, null, null, msg.sessionID); return result(alloc, msg.id, null, null, msg.sessionID);
} }
@@ -87,13 +93,36 @@ fn getFrameTree(
scanner: *std.json.Scanner, scanner: *std.json.Scanner,
ctx: *Ctx, ctx: *Ctx,
) ![]const u8 { ) ![]const u8 {
const msg = try cdp.getMsg(alloc, _id, void, scanner);
// input
const msg = try cdp.getMsg(alloc, _id, void, scanner);
log.debug("Req > id {d}, method {s}", .{ msg.id, "page.getFrameTree" });
// output
const FrameTree = struct { const FrameTree = struct {
frameTree: struct { frameTree: struct {
frame: Frame, frame: Frame,
}, },
childFrames: ?[]@This() = null, childFrames: ?[]@This() = null,
pub fn format(
self: @This(),
comptime _: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
try writer.writeAll("cdp.page.getFrameTree { ");
try writer.writeAll(".frameTree = { ");
try writer.writeAll(".frame = { ");
const frame = self.frameTree.frame;
try writer.writeAll(".id = ");
try std.fmt.formatText(frame.id, "s", options, writer);
try writer.writeAll(", .loaderId = ");
try std.fmt.formatText(frame.loaderId, "s", options, writer);
try writer.writeAll(", .url = ");
try std.fmt.formatText(frame.url, "s", options, writer);
try writer.writeAll(" } } }");
}
}; };
const frameTree = FrameTree{ const frameTree = FrameTree{
.frameTree = .{ .frameTree = .{
@@ -121,6 +150,7 @@ fn setLifecycleEventsEnabled(
enabled: bool, enabled: bool,
}; };
const msg = try getMsg(alloc, _id, Params, scanner); const msg = try getMsg(alloc, _id, Params, scanner);
log.debug("Req > id {d}, method {s}", .{ msg.id, "page.setLifecycleEventsEnabled" });
ctx.state.page_life_cycle_events = true; ctx.state.page_life_cycle_events = true;
@@ -151,10 +181,23 @@ fn addScriptToEvaluateOnNewDocument(
runImmediately: bool = false, runImmediately: bool = false,
}; };
const msg = try getMsg(alloc, _id, Params, scanner); const msg = try getMsg(alloc, _id, Params, scanner);
log.debug("Req > id {d}, method {s}", .{ msg.id, "page.addScriptToEvaluateOnNewDocument" });
// output // output
const Res = struct { const Res = struct {
identifier: []const u8 = "1", identifier: []const u8 = "1",
pub fn format(
self: @This(),
comptime _: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
try writer.writeAll("cdp.page.addScriptToEvaluateOnNewDocument { ");
try writer.writeAll(".identifier = ");
try std.fmt.formatText(self.identifier, "s", options, writer);
try writer.writeAll(" }");
}
}; };
return result(alloc, msg.id, Res, Res{}, msg.sessionID); return result(alloc, msg.id, Res, Res{}, msg.sessionID);
} }
@@ -175,6 +218,7 @@ fn createIsolatedWorld(
}; };
const msg = try getMsg(alloc, _id, Params, scanner); const msg = try getMsg(alloc, _id, Params, scanner);
std.debug.assert(msg.sessionID != null); std.debug.assert(msg.sessionID != null);
log.debug("Req > id {d}, method {s}", .{ msg.id, "page.createIsolatedWorld" });
const params = msg.params.?; const params = msg.params.?;
// noop executionContextCreated event // noop executionContextCreated event
@@ -219,6 +263,7 @@ fn navigate(
}; };
const msg = try getMsg(alloc, _id, Params, scanner); const msg = try getMsg(alloc, _id, Params, scanner);
std.debug.assert(msg.sessionID != null); std.debug.assert(msg.sessionID != null);
log.debug("Req > id {d}, method {s}", .{ msg.id, "page.navigate" });
const params = msg.params.?; const params = msg.params.?;
// change state // change state
@@ -264,6 +309,22 @@ fn navigate(
frameId: []const u8, frameId: []const u8,
loaderId: ?[]const u8, loaderId: ?[]const u8,
errorText: ?[]const u8 = null, errorText: ?[]const u8 = null,
pub fn format(
self: @This(),
comptime _: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
try writer.writeAll("cdp.page.navigate.Resp { ");
try writer.writeAll(".frameId = ");
try std.fmt.formatText(self.frameId, "s", options, writer);
if (self.loaderId) |loaderId| {
try writer.writeAll(", .loaderId = '");
try std.fmt.formatText(loaderId, "s", options, writer);
}
try writer.writeAll(" }");
}
}; };
const resp = Resp{ const resp = Resp{
.frameId = ctx.state.frameID, .frameId = ctx.state.frameID,
@@ -271,7 +332,6 @@ fn navigate(
}; };
const res = try result(alloc, msg.id, Resp, resp, msg.sessionID); const res = try result(alloc, msg.id, Resp, resp, msg.sessionID);
defer alloc.free(res); defer alloc.free(res);
std.log.debug("res {s}", .{res});
try server.sendSync(ctx, res); try server.sendSync(ctx, res);
// TODO: at this point do we need async the following actions to be async? // TODO: at this point do we need async the following actions to be async?

View File

@@ -24,6 +24,8 @@ const cdp = @import("cdp.zig");
const result = cdp.result; const result = cdp.result;
const getMsg = cdp.getMsg; const getMsg = cdp.getMsg;
const log = std.log.scoped(.cdp);
const Methods = enum { const Methods = enum {
enable, enable,
}; };
@@ -49,7 +51,10 @@ fn enable(
scanner: *std.json.Scanner, scanner: *std.json.Scanner,
_: *Ctx, _: *Ctx,
) ![]const u8 { ) ![]const u8 {
// input
const msg = try getMsg(alloc, _id, void, scanner); const msg = try getMsg(alloc, _id, void, scanner);
log.debug("Req > id {d}, method {s}", .{ msg.id, "performance.enable" });
return result(alloc, msg.id, null, null, msg.sessionID); return result(alloc, msg.id, null, null, msg.sessionID);
} }

View File

@@ -28,6 +28,8 @@ const result = cdp.result;
const getMsg = cdp.getMsg; const getMsg = cdp.getMsg;
const stringify = cdp.stringify; const stringify = cdp.stringify;
const log = std.log.scoped(.cdp);
const Methods = enum { const Methods = enum {
enable, enable,
runIfWaitingForDebugger, runIfWaitingForDebugger,
@@ -80,6 +82,7 @@ fn sendInspector(
}; };
const msg = try getMsg(alloc, _id, Params, scanner); const msg = try getMsg(alloc, _id, Params, scanner);
log.debug("Req > id {d}, method {s} (script saved on cache)", .{ msg.id, "runtime.evaluate" });
const params = msg.params.?; const params = msg.params.?;
script = params.expression; script = params.expression;
id = msg.id; id = msg.id;
@@ -98,6 +101,7 @@ fn sendInspector(
}; };
const msg = try getMsg(alloc, _id, Params, scanner); const msg = try getMsg(alloc, _id, Params, scanner);
log.debug("Req > id {d}, method {s} (script saved on cache)", .{ msg.id, "runtime.callFunctionOn" });
const params = msg.params.?; const params = msg.params.?;
script = params.functionDeclaration; script = params.functionDeclaration;
id = msg.id; id = msg.id;
@@ -166,7 +170,10 @@ fn runIfWaitingForDebugger(
scanner: *std.json.Scanner, scanner: *std.json.Scanner,
_: *Ctx, _: *Ctx,
) ![]const u8 { ) ![]const u8 {
// input
const msg = try getMsg(alloc, _id, void, scanner); const msg = try getMsg(alloc, _id, void, scanner);
log.debug("Req > id {d}, method {s}", .{ msg.id, "runtime.runIfWaitingForDebugger" });
return result(alloc, msg.id, null, null, msg.sessionID); return result(alloc, msg.id, null, null, msg.sessionID);
} }

View File

@@ -25,6 +25,8 @@ const result = cdp.result;
const getMsg = cdp.getMsg; const getMsg = cdp.getMsg;
const stringify = cdp.stringify; const stringify = cdp.stringify;
const log = std.log.scoped(.cdp);
const Methods = enum { const Methods = enum {
setDiscoverTargets, setDiscoverTargets,
setAutoAttach, setAutoAttach,
@@ -72,6 +74,7 @@ fn setDiscoverTargets(
// input // input
const msg = try getMsg(alloc, _id, void, scanner); const msg = try getMsg(alloc, _id, void, scanner);
log.debug("Req > id {d}, method {s}", .{ msg.id, "target.setDiscoverTargets" });
// output // output
return result(alloc, msg.id, null, null, msg.sessionID); return result(alloc, msg.id, null, null, msg.sessionID);
@@ -112,7 +115,7 @@ fn setAutoAttach(
filter: ?[]TargetFilter = null, filter: ?[]TargetFilter = null,
}; };
const msg = try getMsg(alloc, _id, Params, scanner); const msg = try getMsg(alloc, _id, Params, scanner);
std.log.debug("params {any}", .{msg.params}); log.debug("Req > id {d}, method {s}", .{ msg.id, "target.setAutoAttach" });
// attachedToTarget event // attachedToTarget event
if (msg.sessionID == null) { if (msg.sessionID == null) {
@@ -144,6 +147,7 @@ fn getTargetInfo(
targetId: ?[]const u8 = null, targetId: ?[]const u8 = null,
}; };
const msg = try getMsg(alloc, _id, Params, scanner); const msg = try getMsg(alloc, _id, Params, scanner);
log.debug("Req > id {d}, method {s}", .{ msg.id, "target.getTargetInfo" });
// output // output
const TargetInfo = struct { const TargetInfo = struct {
@@ -178,6 +182,7 @@ fn getBrowserContexts(
// input // input
const msg = try getMsg(alloc, _id, void, scanner); const msg = try getMsg(alloc, _id, void, scanner);
log.debug("Req > id {d}, method {s}", .{ msg.id, "target.getBrowserContexts" });
// ouptut // ouptut
const Resp = struct { const Resp = struct {
@@ -212,12 +217,25 @@ fn createBrowserContext(
originsWithUniversalNetworkAccess: ?[][]const u8 = null, originsWithUniversalNetworkAccess: ?[][]const u8 = null,
}; };
const msg = try getMsg(alloc, _id, Params, scanner); const msg = try getMsg(alloc, _id, Params, scanner);
log.debug("Req > id {d}, method {s}", .{ msg.id, "target.createBrowserContext" });
ctx.state.contextID = ContextID; ctx.state.contextID = ContextID;
// output // output
const Resp = struct { const Resp = struct {
browserContextId: []const u8 = ContextID, browserContextId: []const u8 = ContextID,
pub fn format(
self: @This(),
comptime _: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
try writer.writeAll("cdp.target.createBrowserContext { ");
try writer.writeAll(".browserContextId = ");
try std.fmt.formatText(self.browserContextId, "s", options, writer);
try writer.writeAll(" }");
}
}; };
return result(alloc, msg.id, Resp, Resp{}, msg.sessionID); return result(alloc, msg.id, Resp, Resp{}, msg.sessionID);
} }
@@ -234,6 +252,7 @@ fn disposeBrowserContext(
browserContextId: []const u8, browserContextId: []const u8,
}; };
const msg = try getMsg(alloc, _id, Params, scanner); const msg = try getMsg(alloc, _id, Params, scanner);
log.debug("Req > id {d}, method {s}", .{ msg.id, "target.disposeBrowserContext" });
// output // output
const res = try result(alloc, msg.id, null, .{}, null); const res = try result(alloc, msg.id, null, .{}, null);
@@ -266,6 +285,7 @@ fn createTarget(
forTab: ?bool = null, forTab: ?bool = null,
}; };
const msg = try getMsg(alloc, _id, Params, scanner); const msg = try getMsg(alloc, _id, Params, scanner);
log.debug("Req > id {d}, method {s}", .{ msg.id, "target.createTarget" });
// change CDP state // change CDP state
ctx.state.frameID = TargetID; ctx.state.frameID = TargetID;
@@ -290,6 +310,18 @@ fn createTarget(
// output // output
const Resp = struct { const Resp = struct {
targetId: []const u8 = TargetID, targetId: []const u8 = TargetID,
pub fn format(
self: @This(),
comptime _: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
try writer.writeAll("cdp.target.createTarget { ");
try writer.writeAll(".targetId = ");
try std.fmt.formatText(self.targetId, "s", options, writer);
try writer.writeAll(" }");
}
}; };
return result(alloc, msg.id, Resp, Resp{}, msg.sessionID); return result(alloc, msg.id, Resp, Resp{}, msg.sessionID);
} }
@@ -306,6 +338,7 @@ fn closeTarget(
targetId: []const u8, targetId: []const u8,
}; };
const msg = try getMsg(alloc, _id, Params, scanner); const msg = try getMsg(alloc, _id, Params, scanner);
log.debug("Req > id {d}, method {s}", .{ msg.id, "target.closeTarget" });
// output // output
const Resp = struct { const Resp = struct {

View File

@@ -27,6 +27,8 @@ const server = @import("server.zig");
const parser = @import("netsurf"); const parser = @import("netsurf");
const apiweb = @import("apiweb.zig"); const apiweb = @import("apiweb.zig");
const log = std.log.scoped(.server);
pub const Types = jsruntime.reflect(apiweb.Interfaces); pub const Types = jsruntime.reflect(apiweb.Interfaces);
pub const UserContext = apiweb.UserContext; pub const UserContext = apiweb.UserContext;
@@ -144,7 +146,7 @@ pub const StreamServer = struct {
fn printUsageExit(execname: []const u8, res: u8) void { fn printUsageExit(execname: []const u8, res: u8) void {
std.io.getStdErr().writer().print(usage, .{execname}) catch |err| { std.io.getStdErr().writer().print(usage, .{execname}) catch |err| {
std.log.err("Print usage error: {any}", .{err}); log.err("Print usage error: {any}", .{err});
std.posix.exit(1); std.posix.exit(1);
}; };
std.posix.exit(res); std.posix.exit(res);
@@ -175,37 +177,37 @@ pub fn main() !void {
host = arg; host = arg;
continue; continue;
} else { } else {
std.log.err("--host not provided\n", .{}); log.err("--host not provided\n", .{});
return printUsageExit(execname, 1); return printUsageExit(execname, 1);
} }
} }
if (std.mem.eql(u8, "--port", opt)) { if (std.mem.eql(u8, "--port", opt)) {
if (args.next()) |arg| { if (args.next()) |arg| {
port = std.fmt.parseInt(u16, arg, 10) catch |err| { port = std.fmt.parseInt(u16, arg, 10) catch |err| {
std.log.err("--port {any}\n", .{err}); log.err("--port {any}\n", .{err});
return printUsageExit(execname, 1); return printUsageExit(execname, 1);
}; };
continue; continue;
} else { } else {
std.log.err("--port not provided\n", .{}); log.err("--port not provided\n", .{});
return printUsageExit(execname, 1); return printUsageExit(execname, 1);
} }
} }
if (std.mem.eql(u8, "--timeout", opt)) { if (std.mem.eql(u8, "--timeout", opt)) {
if (args.next()) |arg| { if (args.next()) |arg| {
timeout = std.fmt.parseInt(u8, arg, 10) catch |err| { timeout = std.fmt.parseInt(u8, arg, 10) catch |err| {
std.log.err("--timeout {any}\n", .{err}); log.err("--timeout {any}\n", .{err});
return printUsageExit(execname, 1); return printUsageExit(execname, 1);
}; };
continue; continue;
} else { } else {
std.log.err("--timeout not provided\n", .{}); log.err("--timeout not provided\n", .{});
return printUsageExit(execname, 1); return printUsageExit(execname, 1);
} }
} }
} }
addr = std.net.Address.parseIp4(host, port) catch |err| { addr = std.net.Address.parseIp4(host, port) catch |err| {
std.log.err("address (host:port) {any}\n", .{err}); log.err("address (host:port) {any}\n", .{err});
return printUsageExit(execname, 1); return printUsageExit(execname, 1);
}; };
@@ -218,11 +220,11 @@ pub fn main() !void {
defer srv.deinit(); defer srv.deinit();
srv.listen(addr) catch |err| { srv.listen(addr) catch |err| {
std.log.err("address (host:port) {any}\n", .{err}); log.err("address (host:port) {any}\n", .{err});
return printUsageExit(execname, 1); return printUsageExit(execname, 1);
}; };
defer srv.close(); defer srv.close();
std.log.info("Listening on: {s}:{d}...", .{ host, port }); log.info("Listening on: {s}:{d}...", .{ host, port });
// loop // loop
var loop = try jsruntime.Loop.init(arena.allocator()); var loop = try jsruntime.Loop.init(arena.allocator());

View File

@@ -36,6 +36,8 @@ const Error = IOError || std.fmt.ParseIntError || cdp.Error || NoError;
const TimeoutCheck = std.time.ns_per_ms * 100; const TimeoutCheck = std.time.ns_per_ms * 100;
const log = std.log.scoped(.server);
// I/O Main // I/O Main
// -------- // --------
@@ -83,7 +85,7 @@ pub const Ctx = struct {
// set connection timestamp and timeout // set connection timestamp and timeout
self.last_active = std.time.Instant.now() catch |err| { self.last_active = std.time.Instant.now() catch |err| {
std.log.err("accept timestamp error: {any}", .{err}); log.err("accept timestamp error: {any}", .{err});
return; return;
}; };
self.loop.io.timeout( self.loop.io.timeout(
@@ -127,23 +129,19 @@ pub const Ctx = struct {
} }
// input // input
if (std.log.defaultLogEnabled(.debug)) {
const content = input[0..@min(MaxStdOutSize, size)];
std.debug.print("\ninput size: {d}, content: {s}\n", .{ size, content });
}
const input = self.read_buf[0..size]; const input = self.read_buf[0..size];
// read and execute input // read and execute input
self.msg_buf.read(self.alloc(), input, self, Ctx.do) catch |err| { self.msg_buf.read(self.alloc(), input, self, Ctx.do) catch |err| {
if (err != error.Closed) { if (err != error.Closed) {
std.log.err("do error: {any}", .{err}); log.err("do error: {any}", .{err});
} }
return; return;
}; };
// set connection timestamp // set connection timestamp
self.last_active = std.time.Instant.now() catch |err| { self.last_active = std.time.Instant.now() catch |err| {
std.log.err("read timestamp error: {any}", .{err}); log.err("read timestamp error: {any}", .{err});
return; return;
}; };
@@ -173,13 +171,13 @@ pub const Ctx = struct {
// check time since last read // check time since last read
const now = std.time.Instant.now() catch |err| { const now = std.time.Instant.now() catch |err| {
std.log.err("timeout timestamp error: {any}", .{err}); log.err("timeout timestamp error: {any}", .{err});
return; return;
}; };
if (now.since(self.last_active.?) > self.timeout) { if (now.since(self.last_active.?) > self.timeout) {
// closing // closing
std.log.debug("conn timeout, closing...", .{}); log.debug("conn timeout, closing...", .{});
// NOTE: we should cancel the current read // NOTE: we should cancel the current read
// but it seems that's just closing the connection is enough // but it seems that's just closing the connection is enough
@@ -221,13 +219,12 @@ pub const Ctx = struct {
// restart a new browser session in case of re-connect // restart a new browser session in case of re-connect
if (!self.sessionNew) { if (!self.sessionNew) {
self.newSession() catch |err| { self.newSession() catch |err| {
std.log.err("new session error: {any}", .{err}); log.err("new session error: {any}", .{err});
return; return;
}; };
} }
std.log.debug("conn closed", .{}); log.info("accepting new conn...", .{});
std.log.debug("accepting new conn...", .{});
// continue accepting incoming requests // continue accepting incoming requests
self.loop.io.accept( self.loop.io.accept(
@@ -265,7 +262,7 @@ pub const Ctx = struct {
// close cmd // close cmd
if (std.mem.eql(u8, cmd, "close")) { if (std.mem.eql(u8, cmd, "close")) {
// close connection // close connection
std.log.debug("close cmd, closing...", .{}); log.info("close cmd, closing conn...", .{});
self.loop.io.close( self.loop.io.close(
*Ctx, *Ctx,
self, self,
@@ -283,7 +280,7 @@ pub const Ctx = struct {
// cdp end cmd // cdp end cmd
if (err == error.DisposeBrowserContext) { if (err == error.DisposeBrowserContext) {
// restart a new browser session // restart a new browser session
std.log.debug("cdp end cmd", .{}); std.log.scoped(.cdp).debug("end cmd, restarting a new session...", .{});
try self.newSession(); try self.newSession();
return; return;
} }
@@ -293,7 +290,6 @@ pub const Ctx = struct {
// send result // send result
if (!std.mem.eql(u8, res, "")) { if (!std.mem.eql(u8, res, "")) {
std.log.debug("res {s}", .{res});
return sendAsync(self, res); return sendAsync(self, res);
} }
} }
@@ -306,7 +302,6 @@ pub const Ctx = struct {
Ctx.onInspectorNotif, Ctx.onInspectorNotif,
); );
self.sessionNew = true; self.sessionNew = true;
std.log.debug("new session", .{});
} }
// inspector // inspector
@@ -338,13 +333,23 @@ pub const Ctx = struct {
} }
pub fn onInspectorResp(ctx_opaque: *anyopaque, _: u32, msg: []const u8) void { pub fn onInspectorResp(ctx_opaque: *anyopaque, _: u32, msg: []const u8) void {
std.log.debug("inspector resp: {s}", .{msg}); if (std.log.defaultLogEnabled(.debug)) {
// msg should be {"id":<id>,...
const id_end = std.mem.indexOfScalar(u8, msg, ',') orelse unreachable;
const id = msg[6..id_end];
std.log.scoped(.cdp).debug("Res (inspector) > id {s}", .{id});
}
const ctx = inspectorCtx(ctx_opaque); const ctx = inspectorCtx(ctx_opaque);
inspectorMsg(ctx.alloc(), ctx, msg) catch unreachable; inspectorMsg(ctx.alloc(), ctx, msg) catch unreachable;
} }
pub fn onInspectorNotif(ctx_opaque: *anyopaque, msg: []const u8) void { pub fn onInspectorNotif(ctx_opaque: *anyopaque, msg: []const u8) void {
std.log.debug("inspector event: {s}", .{msg}); if (std.log.defaultLogEnabled(.debug)) {
// msg should be {"method":<method>,...
const method_end = std.mem.indexOfScalar(u8, msg, ',') orelse unreachable;
const method = msg[10..method_end];
std.log.scoped(.cdp).debug("Event (inspector) > method {s}", .{method});
}
const ctx = inspectorCtx(ctx_opaque); const ctx = inspectorCtx(ctx_opaque);
inspectorMsg(ctx.alloc(), ctx, msg) catch unreachable; inspectorMsg(ctx.alloc(), ctx, msg) catch unreachable;
} }
@@ -374,12 +379,10 @@ const Send = struct {
} }
fn asyncCbk(self: *Send, _: *Completion, result: SendError!usize) void { fn asyncCbk(self: *Send, _: *Completion, result: SendError!usize) void {
const size = result catch |err| { _ = result catch |err| {
self.ctx.err = err; self.ctx.err = err;
return; return;
}; };
std.log.debug("send async {d} bytes", .{size});
self.deinit(); self.deinit();
} }
}; };
@@ -390,8 +393,7 @@ pub fn sendAsync(ctx: *Ctx, msg: []const u8) !void {
} }
pub fn sendSync(ctx: *Ctx, msg: []const u8) !void { pub fn sendSync(ctx: *Ctx, msg: []const u8) !void {
const s = try std.posix.write(ctx.conn_socket, msg); _ = try std.posix.write(ctx.conn_socket, msg);
std.log.debug("send sync {d} bytes", .{s});
} }
// Listen // Listen
@@ -442,7 +444,7 @@ pub fn listen(
); );
// accepting connection asynchronously on internal server // accepting connection asynchronously on internal server
std.log.debug("accepting new conn...", .{}); log.info("accepting new conn...", .{});
loop.io.accept(*Ctx, &ctx, Ctx.acceptCbk, ctx.conn_completion, ctx.accept_socket); loop.io.accept(*Ctx, &ctx, Ctx.acceptCbk, ctx.conn_completion, ctx.accept_socket);
// infinite loop on I/O events, either: // infinite loop on I/O events, either:
@@ -451,7 +453,7 @@ pub fn listen(
while (true) { while (true) {
try loop.io.tick(); try loop.io.tick();
if (loop.cbk_error) { if (loop.cbk_error) {
std.log.err("JS error", .{}); log.err("JS error", .{});
// if (try try_catch.exception(alloc, js_env.*)) |msg| { // if (try try_catch.exception(alloc, js_env.*)) |msg| {
// std.debug.print("\n\rUncaught {s}\n\r", .{msg}); // std.debug.print("\n\rUncaught {s}\n\r", .{msg});
// alloc.free(msg); // alloc.free(msg);
@@ -459,7 +461,7 @@ pub fn listen(
// loop.cbk_error = false; // loop.cbk_error = false;
} }
if (ctx.err) |err| { if (ctx.err) |err| {
if (err != error.NoError) std.log.err("Server error: {any}", .{err}); if (err != error.NoError) log.err("Server error: {any}", .{err});
break; break;
} }
} }