Skip to content

Lightpanda: the headless browser designed for AI and automation

properly use the stream body in Request

Muki Kiboigo35813ba869a6
diff --git a/src/browser/tests/net/request.html b/src/browser/tests/net/request.html
index 465f7eefc..e9f8c3756 100644
--- a/src/browser/tests/net/request.html
+++ b/src/browser/tests/net/request.html
@@ -632,3 +632,13 @@
testing.expectError('TypeError', () => new Request('https://example.com/api', { method }));
}
</script>
+
+<script id=request_body_matches_stream>
+ const open = new ReadableStream({ start(c) { c.enqueue(new TextEncoder().encode('x')); } });
+ const r1 = new Request('https://example.com', { method: 'POST', body: open, duplex: 'half' });
+ testing.expectTrue(r1.body === open)
+
+ const closed = new ReadableStream({ start(c) { c.enqueue(new TextEncoder().encode('x')); c.close(); } });
+ const r2 = new Request('https://example.com', { method: 'POST', body: closed, duplex: 'half' });
+ testing.expectTrue(r2.body === closed)
+</script>
diff --git a/src/browser/webapi/net/Request.zig b/src/browser/webapi/net/Request.zig
index 47096f963..63f4385d7 100644
--- a/src/browser/webapi/net/Request.zig
+++ b/src/browser/webapi/net/Request.zig
@@ -330,12 +330,13 @@ fn getBodyUsed(self: *const Request) bool {
}
pub fn bodyBytes(self: *Request) !?[]const u8 {
- if (self._body_stream) |stream| {
- // drain the stram on first use, TypeError if it can't.
+ if (self._body) |body| {
+ return body;
+ } else if (self._body_stream) |stream| {
self._body = try stream.collectBodyBytes(self._arena.allocator());
self._body_stream = null;
- }
- return self._body;
+ return self._body;
+ } else return null;
}
// A TypeError if the body is disturbed or its exposed `body` stream is locked.
@@ -376,10 +377,23 @@ fn consume(self: *Request, exec: *const Execution) ![]const u8 {
// https://fetch.spec.whatwg.org/#dom-body-body
pub fn getBody(self: *Request, exec: *const Execution) !?*ReadableStream {
- const body = try self.bodyBytes() orelse return null;
+ // If we already have a body, we just return that.
if (self._body_view) |stream| {
return stream;
}
+
+ // If our body is a stream, we should just return it.
+ if (self._body_stream) |stream| {
+ self._body_view = stream;
+ if (self._body_used) {
+ try lockStream(stream, exec);
+ }
+
+ return stream;
+ }
+
+ // This creates a new ReadableStream for the other types of body.
+ const body = try self.bodyBytes() orelse return null;
const stream = blk: {
if (body.len == 0) {
const stream = try ReadableStream.init(null, null, exec);