Skip to content

Lightpanda: the headless browser designed for AI and automation

webapi: sendBeacon checks its arguments, and sends with --load-resources beacon

orezraey28ba0656d062
diff --git a/src/Config.zig b/src/Config.zig
index e5fcfcb44..650dec382 100644
--- a/src/Config.zig
+++ b/src/Config.zig
@@ -231,11 +231,13 @@ pub const HttpVersion = enum {
@"1.1",
};
-pub const LoadResources = packed struct(u5) {
+pub const LoadResources = packed struct(u6) {
image: bool = false,
iframe: bool = false,
worker: bool = false,
stylesheet: bool = false,
+ // navigator.sendBeacon sends its request (otherwise it only validates).
+ beacon: bool = false,
// Only marks the option as given, so `--load-resources none` turns off a
// mode's default.
none: bool = false,
@@ -1855,18 +1857,20 @@ test "Config: parseArgs --load-resources defaults stylesheets on for mcp and age
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
- const cases = [_]struct { argv: []const [*:0]const u8, stylesheet: bool, image: bool }{
+ const cases = [_]struct { argv: []const [*:0]const u8, stylesheet: bool, image: bool, beacon: bool = false }{
.{ .argv = &.{ "lightpanda", "mcp" }, .stylesheet = true, .image = false },
.{ .argv = &.{ "lightpanda", "agent", "--no-llm" }, .stylesheet = true, .image = false },
.{ .argv = &.{ "lightpanda", "fetch", "https://example.com" }, .stylesheet = false, .image = false },
.{ .argv = &.{ "lightpanda", "mcp", "--load-resources", "none" }, .stylesheet = false, .image = false },
.{ .argv = &.{ "lightpanda", "mcp", "--load-resources", "image" }, .stylesheet = false, .image = true },
+ .{ .argv = &.{ "lightpanda", "fetch", "--load-resources", "beacon", "https://example.com" }, .stylesheet = false, .image = false, .beacon = true },
};
for (cases) |case| {
const config = try parseArgs(arena.allocator(), .{ .vector = case.argv });
const resources = config.loadResources();
try std.testing.expectEqual(case.stylesheet, resources.stylesheet);
try std.testing.expectEqual(case.image, resources.image);
+ try std.testing.expectEqual(case.beacon, resources.beacon);
}
}
diff --git a/src/browser/PageStatus.zig b/src/browser/PageStatus.zig
index 990ed25d6..e72cb27a5 100644
--- a/src/browser/PageStatus.zig
+++ b/src/browser/PageStatus.zig
@@ -36,6 +36,7 @@ pub const Skipped = enum {
worker,
image,
stylesheet,
+ beacon,
};
// The sub-resources the page itself asks for, and which we load.
@@ -118,7 +119,7 @@ pub fn noteSkipped(self: *PageStatus, what: Skipped) void {
const level: log.Level = switch (what) {
.iframe, .worker => .warn,
- .image, .stylesheet => .debug,
+ .image, .stylesheet, .beacon => .debug,
};
switch (what) {
@@ -313,5 +314,5 @@ test "PageStatus: counts serialize as an object with every tag" {
try testing.expectEqual("{\"webgl\":2,\"canvas2d\":0}", json);
const skipped = try std.json.Stringify.valueAlloc(testing.arena_allocator, status.skipped, .{});
- try testing.expectEqual("{\"iframe\":1,\"worker\":0,\"image\":0,\"stylesheet\":0}", skipped);
+ try testing.expectEqual("{\"iframe\":1,\"worker\":0,\"image\":0,\"stylesheet\":0,\"beacon\":0}", skipped);
}
diff --git a/src/browser/frame/resource_load.zig b/src/browser/frame/resource_load.zig
index 153f1f935..188856f54 100644
--- a/src/browser/frame/resource_load.zig
+++ b/src/browser/frame/resource_load.zig
@@ -28,6 +28,7 @@ const Factory = @import("../Factory.zig");
const Element = @import("../webapi/Element.zig");
const image_dimensions = @import("../image_dimensions.zig");
const HttpClient = @import("../../network/HttpClient.zig");
+const CorsGate = @import("../../network/CorsGate.zig");
const log = lp.log;
@@ -110,6 +111,87 @@ pub fn image(frame: *Frame, img: *Element.Html.Image, src: []const u8) !void {
};
}
+// A navigator.sendBeacon request: a POST whose response nobody reads. Its body
+// counts against the sending document's keepalive quota, `in_flight`, until it
+// settles.
+// https://w3c.github.io/beacon/#sec-processing-model
+//
+// A keepalive request outlives the document that made it: a beacon sent by an
+// iframe that's then removed still goes out. So the request is owned by the
+// page's main frame, not `frame`, which supplies its origin, referrer and site
+// for cookies, and `in_flight` must outlive `frame` too (it's in the page
+// arena). The owner still attributes it to the main frame in CDP events.
+pub fn beacon(frame: *Frame, in_flight: *usize, url: [:0]const u8, body: []const u8, content_type: ?[]const u8) !void {
+ const root = &frame.page.frame;
+
+ // A body with a Content-Type that isn't CORS-safelisted makes it a CORS
+ // request; anything else (no body, a Blob without a type, ...) is no-cors.
+ const cors = if (content_type) |ct| !CorsGate.isSafelistedHeader("content-type", ct) else false;
+
+ const load = try root._factory.create(BeaconLoad{
+ .root = root,
+ .in_flight = in_flight,
+ .size = body.len,
+ });
+ errdefer root._factory.destroy(load);
+
+ const transfer = try frame._session.browser.http_client.newRequest(.{
+ .ctx = load,
+ .url = url,
+ .method = .POST,
+ .body = body,
+ .origin = frame.origin,
+ .cookie_origin = frame._http_owner.siteForCookies(),
+ .request_mode = if (cors) .cors else .no_cors,
+ .credentials_mode = .include,
+ .resource_type = .beacon,
+ .done_callback = BeaconLoad.doneCallback,
+ .error_callback = BeaconLoad.errorCallback,
+ .shutdown_callback = BeaconLoad.shutdownCallback,
+ }, &root._http_owner);
+ {
+ errdefer transfer.deinit();
+ // In the request's header list, as fetch()'s headers are, so the CORS
+ // gate weighs it for a preflight.
+ if (content_type) |ct| {
+ try transfer.setHeader("Content-Type", ct, .{ .source = .author });
+ }
+ try frame.headersForRequest(transfer, .{});
+ }
+
+ in_flight.* += body.len;
+ // From here the transfer owns `load`, which gives the quota back.
+ transfer.submit() catch |err| {
+ log.debug(.http, "beacon", .{ .err = err, .url = url });
+ };
+}
+
+// One in-flight beacon. Exactly one of done/error/shutdown runs.
+const BeaconLoad = struct {
+ root: *Frame,
+ in_flight: *usize,
+ size: usize,
+
+ fn doneCallback(ctx: *anyopaque) !void {
+ settle(ctx);
+ }
+
+ fn errorCallback(ctx: *anyopaque, err: anyerror) void {
+ log.info(.http, "beacon", .{ .err = err });
+ settle(ctx);
+ }
+
+ fn shutdownCallback(ctx: *anyopaque) void {
+ settle(ctx);
+ }
+
+ fn settle(ctx: *anyopaque) void {
+ const self: *BeaconLoad = @ptrCast(@alignCast(ctx));
+ self.in_flight.* -|= self.size;
+ self.root._factory.destroy(self);
+ }
+};
+
// One in-flight image fetch. Exactly one of done/error/shutdown runs, and each
// releases the `_pending_loads` slot taken above.
const ImageLoad = struct {
diff --git a/src/browser/tests/beacon.html b/src/browser/tests/beacon.html
new file mode 100644
index 000000000..0af16dbb7
--- /dev/null
+++ b/src/browser/tests/beacon.html
@@ -0,0 +1,106 @@
+<!DOCTYPE html>
+<script src="testing.js"></script>
+<body></body>
+
+<!--
+ These run with load_resources = .{ .beacon = true, .iframe = true } (see Navigator.zig's
+ test decl), so sendBeacon really sends its POST. The test server records
+ each request to /beacon/store/<id>; /beacon/read/<id> reads it back as
+ "METHOD|content-type|body length|start of the body".
+-->
+
+<script id=beacon-sends type=module>
+ const state = await testing.async();
+ const sleep = () => new Promise((resolve) => setTimeout(resolve, 10));
+ const read = async (id) => {
+ for (let i = 0; i < 50; i++) {
+ const record = await (await fetch(`/beacon/read/${id}`)).text();
+ if (record !== "(missing)") return record;
+ await sleep();
+ }
+ return "(missing)";
+ };
+
+ // The bodies of beacons still in flight share a 64 KiB quota: a beacon that
+ // would go over it isn't sent, and sendBeacon returns false. Nothing settles
+ // between these calls, so the first is still in flight.
+ const quota = [
+ navigator.sendBeacon("/beacon/store/max", "x".repeat(65536)),
+ navigator.sendBeacon("/beacon/store/empty", ""),
+ navigator.sendBeacon("/beacon/store/over", "x"),
+ ];
+ // Once it settles, the quota is free again.
+ let freed = false;
+ for (let i = 0; i < 50 && !freed; i++) {
+ await sleep();
+ freed = navigator.sendBeacon("/beacon/store/freed", "x".repeat(65536));
+ }
+ const quotaRecords = [await read("max"), await read("over")];
+
+ // Each kind of body, with the Content-Type the spec gives it.
+ const sent = {
+ none: navigator.sendBeacon("/beacon/store/none"),
+ string: navigator.sendBeacon("/beacon/store/string", "payload"),
+ buffer: navigator.sendBeacon("/beacon/store/buffer", new TextEncoder().encode("bytes").buffer),
+ blob: navigator.sendBeacon("/beacon/store/blob", new Blob(["{}"], { type: "application/json" })),
+ untypedBlob: navigator.sendBeacon("/beacon/store/untyped-blob", new Blob(["raw"])),
+ params: navigator.sendBeacon("/beacon/store/params", new URLSearchParams("a=1&b=2")),
+ };
+ const form = new FormData();
+ form.append("field", "value");
+ sent.form = navigator.sendBeacon("/beacon/store/form", form);
+
+ const records = {};
+ for (const id of ["none", "string", "buffer", "blob", "untyped-blob", "params"]) {
+ records[id] = await read(id);
+ }
+ const formRecord = await read("form");
+
+ // Cross-origin: a CORS-safelisted Content-Type goes out as a no-cors
+ // request; another one makes it a CORS request, so it's preflighted (and
+ // this server doesn't allow it, so the POST itself never comes).
+ const cross = {
+ plain: navigator.sendBeacon("http://localhost:9582/beacon/store/cross-plain", "x"),
+ json: navigator.sendBeacon("http://localhost:9582/beacon/store/cross-json", new Blob(["{}"], { type: "application/json" })),
+ };
+ const crossRecords = { plain: await read("cross-plain"), json: await read("cross-json") };
+
+ // A beacon is a keepalive request: it still goes out when the iframe that
+ // sent it is removed right away.
+ const iframe = document.createElement("iframe");
+ document.body.appendChild(iframe);
+ const fromIframe = iframe.contentWindow.navigator.sendBeacon("/beacon/store/iframe", "bye");
+ // Each document has its own quota: the iframe can fill the rest of its own
+ // 64 KiB while this document has 60,000 bytes in flight.
+ const quotas = [
+ navigator.sendBeacon("/beacon/store/parent-big", "x".repeat(60000)),
+ iframe.contentWindow.navigator.sendBeacon("/beacon/store/iframe-max", "x".repeat(65536 - 3)),
+ iframe.contentWindow.navigator.sendBeacon("/beacon/store/iframe-over", "x"),
+ ];
+ iframe.remove();
+ const iframeRecord = await read("iframe");
+
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual([true, true, false], quota);
+ testing.expectEqual(true, freed);
+ testing.expectEqual("POST|text/plain;charset=UTF-8|65536|", quotaRecords[0].slice(0, 36));
+ testing.expectEqual("(missing)", quotaRecords[1]);
+ testing.expectEqual({ none: true, string: true, buffer: true, blob: true, untypedBlob: true, params: true, form: true }, sent);
+ testing.expectEqual({
+ none: "POST|(missing)|0|",
+ string: "POST|text/plain;charset=UTF-8|7|payload",
+ buffer: "POST|(missing)|5|bytes",
+ blob: "POST|application/json|2|{}",
+ "untyped-blob": "POST|(missing)|3|raw",
+ params: "POST|application/x-www-form-urlencoded;charset=UTF-8|7|a=1&b=2",
+ }, records);
+ testing.expectEqual(true, formRecord.startsWith("POST|multipart/form-data; boundary="));
+ testing.expectEqual({ plain: true, json: true }, cross);
+ testing.expectEqual("POST|text/plain;charset=UTF-8|1|x", crossRecords.plain);
+ testing.expectEqual("OPTIONS|", crossRecords.json.slice(0, 8));
+ testing.expectEqual([true, true, false], quotas);
+ testing.expectEqual(true, fromIframe);
+ testing.expectEqual("POST|text/plain;charset=UTF-8|3|bye", iframeRecord);
+ });
+</script>
diff --git a/src/browser/tests/navigator/navigator.html b/src/browser/tests/navigator/navigator.html
index b8c63477e..e23af85b3 100644
--- a/src/browser/tests/navigator/navigator.html
+++ b/src/browser/tests/navigator/navigator.html
@@ -182,4 +182,25 @@
testing.expectEqual(true, navigator.sendBeacon('/analytics'));
testing.expectEqual(true, navigator.sendBeacon('/analytics', 'payload'));
testing.expectEqual(true, navigator.sendBeacon('/analytics', new Blob(['x'])));
+ // The URL and data are checked even when beacons aren't sent.
+ testing.expectError('TypeError', () => navigator.sendBeacon('ftp://example.com/'));
+ testing.expectError('TypeError', () => navigator.sendBeacon('data:text/plain,hi'));
+ testing.expectError('TypeError', () => navigator.sendBeacon('http://['));
+ testing.expectError('TypeError', () => navigator.sendBeacon('/analytics', new ReadableStream()));
+ testing.expectEqual(false, navigator.sendBeacon('/analytics', 'x'.repeat(65537)));
+ testing.expectEqual(true, navigator.sendBeacon('/analytics', 'x'.repeat(65536)));
</script>
+
+<script id=sendBeacon-not-sent type=module>
+ // Without --load-resources beacon, nothing is sent.
+ const state = await testing.async();
+ const sent = navigator.sendBeacon('/beacon/store/disabled', 'payload');
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ const record = await (await fetch('/beacon/read/disabled')).text();
+ state.resolve();
+ await state.done(() => {
+ testing.expectEqual(true, sent);
+ testing.expectEqual('(missing)', record);
+ });
+</script>
+
diff --git a/src/browser/webapi/Navigator.zig b/src/browser/webapi/Navigator.zig
index 500e574e9..020e84bee 100644
--- a/src/browser/webapi/Navigator.zig
+++ b/src/browser/webapi/Navigator.zig
@@ -21,6 +21,9 @@ const builtin = @import("builtin");
const js = @import("../js/js.zig");
const Frame = @import("../Frame.zig");
+const URL = @import("../URL.zig");
+const resource_load = @import("../frame/resource_load.zig");
+const BodyInit = @import("net/body_init.zig").BodyInit;
const Execution = js.Execution;
const PluginArray = @import("PluginArray.zig");
@@ -50,6 +53,9 @@ _storage: StorageManager = .{},
_ua_data: NavigatorUAData = .{},
_service_worker: ?*ServiceWorkerContainer = null,
_locks: ?*LockManager = null,
+/// The bodies of this document's beacons still in flight, for the keepalive
+/// quota. Allocated in the page arena on the first sendBeacon.
+_beacon_bytes: ?*usize = null,
pub const init: Navigator = .{};
@@ -138,10 +144,54 @@ fn javaEnabled(_: *const Navigator) bool {
return false;
}
-/// Noop, signal that the data was successfully queued
-fn sendBeacon(_: *const Navigator, url: js.Value, data: ?js.Value) bool {
- _ = url;
- _ = data;
+/// The keepalive quota: a document's in-flight keepalive request bodies,
+/// beacons here, can't add up to more than 64 KiB (Fetch, "HTTP-network-or-cache
+/// fetch").
+const keepalive_quota = 64 * 1024;
+
+/// https://w3c.github.io/beacon/#sec-processing-model
+/// The URL and data are always checked, and the return value reflects the
+/// keepalive quota. The request is only sent with `--load-resources beacon`;
+/// otherwise this behaves as a browser with beacons disabled would, returning
+/// true without sending anything.
+fn sendBeacon(self: *Navigator, url: []const u8, data: ?BodyInit, frame: *Frame) !bool {
+ // The URL parser, not the document's encoding: the query is UTF-8.
+ const resolved = URL.resolve(frame.local_arena, frame.base(), url, .{}) catch {
+ return frame.js.typeError("sendBeacon: invalid URL");
+ };
+ if (URL.isRemoteScheme(resolved) == false) {
+ return frame.js.typeError("sendBeacon: the URL's scheme must be http or https");
+ }
+
+ var body: []const u8 = "";
+ var content_type: ?[]const u8 = null;
+ if (data) |d| {
+ // A keepalive request can't have a ReadableStream body.
+ if (d == .stream) {
+ return frame.js.typeError("sendBeacon: a ReadableStream body is not supported");
+ }
+ const extracted = try d.extract(frame.local_arena);
+ body = extracted.bytes;
+ content_type = extracted.content_type;
+ }
+
+ // In the page arena: a beacon can outlive the iframe that sent it, and it
+ // gives its bytes back when it settles.
+ const in_flight = self._beacon_bytes orelse blk: {
+ const counter = try frame.page_arena.create(usize);
+ counter.* = 0;
+ self._beacon_bytes = counter;
+ break :blk counter;
+ };
+ if (in_flight.* + body.len > keepalive_quota) {
+ return false;
+ }
+
+ if (frame._session.load_resources.beacon == false) {
+ frame.page.status.noteSkipped(.beacon);
+ return true;
+ }
+ try resource_load.beacon(frame, in_flight, resolved, body, content_type);
return true;
}
@@ -306,4 +356,5 @@ pub const JsApi = struct {
const testing = @import("../../testing.zig");
test "WebApi: Navigator" {
try testing.htmlRunner("navigator", .{});
+ try testing.htmlRunner("beacon.html", .{ .load_resources = .{ .beacon = true, .iframe = true } });
}
diff --git a/src/help.zon b/src/help.zon
index 9e20811da..959e9dc1c 100644
--- a/src/help.zon
+++ b/src/help.zon
@@ -480,6 +480,10 @@
\\ Defaults to stylesheet for mcp and agent, and to none of them
\\ otherwise. Passing it replaces the default.
\\ Allowed values:
+ \\ beacon Send navigator.sendBeacon requests. When disabled,
+ \\ sendBeacon still checks its URL and data, and
+ \\ returns true without sending anything.
+ \\
\\ iframe When enabled, <iframe> elements are fully loaded.
\\
\\ image <img> sources, so that load/error reflects the real
diff --git a/src/network/CorsGate.zig b/src/network/CorsGate.zig
index deea75928..a7fce0d38 100644
--- a/src/network/CorsGate.zig
+++ b/src/network/CorsGate.zig
@@ -142,7 +142,7 @@ fn isSafelistedLanguageValue(value: []const u8) bool {
}
// https://fetch.spec.whatwg.org/#cors-safelisted-request-header
-fn isSafelistedHeader(name: []const u8, value: []const u8) bool {
+pub fn isSafelistedHeader(name: []const u8, value: []const u8) bool {
if (value.len > 128) return false;
if (std.ascii.eqlIgnoreCase(name, "accept")) {
diff --git a/src/network/HttpClient.zig b/src/network/HttpClient.zig
index d5a466aec..a050c1d7d 100644
--- a/src/network/HttpClient.zig
+++ b/src/network/HttpClient.zig
@@ -2104,6 +2104,8 @@ pub const Request = struct {
image,
text_track,
worker,
+ // navigator.sendBeacon
+ beacon,
// Allowed Values: Document, Stylesheet, Image, Media, Font, Script,
// TextTrack, XHR, Fetch, Prefetch, EventSource, WebSocket, Manifest,
@@ -2120,6 +2122,7 @@ pub const Request = struct {
.image => "Image",
.text_track => "TextTrack",
.worker => "Script",
+ .beacon => "Ping",
};
}
};
@@ -2729,7 +2732,7 @@ pub const Transfer = struct {
return switch (self.req.resource_type) {
// The owner of a document request is the frame being navigated.
.document => if (self.owner != null and self.owner.?.parent != null) "iframe" else "document",
- .xhr, .fetch, .eventsource => "empty",
+ .xhr, .fetch, .eventsource, .beacon => "empty",
.script => "script",
.stylesheet => "style",
.image => "image",
@@ -3481,6 +3484,7 @@ pub const Transfer = struct {
.eventsource, .worker => "other",
.image => "img",
.text_track => "track",
+ .beacon => "beacon",
},
.protocol = t.protocol,
.start = t.start_time,
diff --git a/src/network/adblock/Engine.zig b/src/network/adblock/Engine.zig
index 8f91eebb4..a481e7ea2 100644
--- a/src/network/adblock/Engine.zig
+++ b/src/network/adblock/Engine.zig
@@ -150,6 +150,7 @@ pub const Request = struct {
.image => .{ .image = true },
.eventsource, .text_track => .{ .other = true },
.worker => .{ .script = true },
+ .beacon => .{ .ping = true },
};
return .init(req.url, &buffers.url, source, resource_type);
diff --git a/src/server/cdp/domains/fetch.zig b/src/server/cdp/domains/fetch.zig
index 6b085a0df..283c6b63a 100644
--- a/src/server/cdp/domains/fetch.zig
+++ b/src/server/cdp/domains/fetch.zig
@@ -688,6 +688,7 @@ pub const InterceptState = struct {
.stylesheet => .Stylesheet,
.image => .Image,
.text_track => .TextTrack,
+ .beacon => .Ping,
};
}
diff --git a/src/server/cdp/domains/network.zig b/src/server/cdp/domains/network.zig
index 3bd82ccbc..90269b84f 100644
--- a/src/server/cdp/domains/network.zig
+++ b/src/server/cdp/domains/network.zig
@@ -794,6 +794,7 @@ fn initialPriority(resource_type: HttpClient.Request.ResourceType) []const u8 {
.document, .stylesheet => "VeryHigh",
.script, .worker, .xhr, .fetch, .eventsource => "High",
.image, .text_track => "Low",
+ .beacon => "VeryLow",
};
}
diff --git a/src/test_routes.zig b/src/test_routes.zig
index 2c73df4f7..fa78ce626 100644
--- a/src/test_routes.zig
+++ b/src/test_routes.zig
@@ -43,6 +43,26 @@ var serve_counts = [_]struct { name: []const u8, count: u32 = 0 }{
.{ .name = "prescan_module" },
};
+// /beacon/store/<id> records the request it gets, /beacon/read/<id> answers
+// "METHOD|content-type|body" for it, or "(missing)". The test HTTP server runs
+// a thread per connection, so access goes through beacon_mutex.
+const BeaconRecord = struct {
+ id: [32]u8 = undefined,
+ id_len: usize = 0,
+ record: [256]u8 = undefined,
+ record_len: usize = 0,
+};
+var beacon_mutex: std.Io.Mutex = .init;
+var beacon_records: [32]BeaconRecord = @splat(.{});
+var beacon_record_count: usize = 0;
+
+fn beaconRecord(id: []const u8) ?*BeaconRecord {
+ for (beacon_records[0..beacon_record_count]) |*r| {
+ if (std.mem.eql(u8, r.id[0..r.id_len], id)) return r;
+ }
+ return null;
+}
+
fn origin(req: *std.http.Server.Request) ?[]const u8 {
var it = req.iterateHeaders();
while (it.next()) |h| {
@@ -67,6 +87,11 @@ pub fn handle(req: *std.http.Server.Request) !void {
for (&serve_counts) |*sc| sc.count = 0;
sse_flag.store(false, .release);
sse_reconnect_hits.store(0, .release);
+ {
+ beacon_mutex.lockUncancelable(lp.io);
+ defer beacon_mutex.unlock(lp.io);
+ beacon_record_count = 0;
+ }
return req.respond("", .{});
}
@@ -768,6 +793,53 @@ pub fn handle(req: *std.http.Server.Request) !void {
});
}
+ if (std.mem.startsWith(u8, path, "/beacon/store/")) {
+ // Copied: reading the body invalidates the head's strings.
+ const id = try req_allocator.dupe(u8, path["/beacon/store/".len..]);
+ var content_type: []const u8 = "(missing)";
+ var it = req.iterateHeaders();
+ while (it.next()) |h| {
+ if (std.ascii.eqlIgnoreCase(h.name, "content-type")) content_type = try req_allocator.dupe(u8, h.value);
+ }
+ var body_buf: [4096]u8 = undefined;
+ const body = if (req.head.method.requestHasBody())
+ try (try req.readerExpectContinue(&body_buf)).allocRemaining(req_allocator, .limited(128 * 1024))
+ else
+ "";
+
+ if (id.len <= 32) {
+ beacon_mutex.lockUncancelable(lp.io);
+ defer beacon_mutex.unlock(lp.io);
+ if (beacon_record_count < beacon_records.len) {
+ const r = &beacon_records[beacon_record_count];
+ beacon_record_count += 1;
+ @memcpy(r.id[0..id.len], id);
+ r.id_len = id.len;
+ const shown = body[0..@min(body.len, 64)];
+ const line = std.mem.print(&r.record, "{s}|{s}|{d}|{s}", .{ @tagName(req.head.method), content_type, body.len, shown }) catch "";
+ r.record_len = line.len;
+ }
+ }
+ return req.respond("", .{});
+ }
+
+ if (std.mem.startsWith(u8, path, "/beacon/read/")) {
+ var buf: [256]u8 = undefined;
+ const record = blk: {
+ beacon_mutex.lockUncancelable(lp.io);
+ defer beacon_mutex.unlock(lp.io);
+ const r = beaconRecord(path["/beacon/read/".len..]) orelse break :blk "(missing)";
+ const len = r.record_len;
+ @memcpy(buf[0..len], r.record[0..len]);
+ break :blk buf[0..len];
+ };
+ return req.respond(record, .{
+ .extra_headers = &.{
+ .{ .name = "Content-Type", .value = "text/plain; charset=utf-8" },
+ },
+ });
+ }
+
if (std.mem.eql(u8, path, "/echo_body")) {
// Echo the request body back verbatim, so tests can assert on the bytes
// a request actually sent rather than just on its status.