Skip to content

Commit a980447

Browse files
authored
perf(cloudflare): optimize readable/writable piping (#1005)
1 parent e8f5e66 commit a980447

File tree

2 files changed

+45
-6
lines changed

2 files changed

+45
-6
lines changed

.changeset/sour-socks-rescue.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@opennextjs/aws": patch
3+
---
4+
5+
perf(cloudflare): optimize readable/writable piping

packages/open-next/src/overrides/wrappers/cloudflare-node.ts

Lines changed: 40 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -52,19 +52,53 @@ const handler: WrapperHandler<InternalEvent, InternalResult> =
5252
responseHeaders.set("Content-Encoding", "identity");
5353
}
5454

55-
const { readable, writable } = new TransformStream({
56-
transform(chunk, controller) {
57-
controller.enqueue(Uint8Array.from(chunk.chunk ?? chunk));
55+
// Optimize: skip ReadableStream creation for null body statuses
56+
if (NULL_BODY_STATUSES.has(statusCode)) {
57+
const response = new Response(null, {
58+
status: statusCode,
59+
headers: responseHeaders,
60+
});
61+
resolveResponse(response);
62+
63+
// Return a no-op Writable that discards all data
64+
return new Writable({
65+
write(chunk, encoding, callback) {
66+
callback();
67+
},
68+
});
69+
}
70+
71+
let controller: ReadableStreamDefaultController<Uint8Array>;
72+
const readable = new ReadableStream({
73+
start(c) {
74+
controller = c;
5875
},
5976
});
60-
const body = NULL_BODY_STATUSES.has(statusCode) ? null : readable;
61-
const response = new Response(body, {
77+
78+
const response = new Response(readable, {
6279
status: statusCode,
6380
headers: responseHeaders,
6481
});
6582
resolveResponse(response);
6683

67-
return Writable.fromWeb(writable);
84+
return new Writable({
85+
write(chunk, encoding, callback) {
86+
controller.enqueue(chunk);
87+
callback();
88+
},
89+
final(callback) {
90+
controller.close();
91+
callback();
92+
},
93+
destroy(error, callback) {
94+
if (error) {
95+
controller.error(error);
96+
} else {
97+
controller.close();
98+
}
99+
callback(error);
100+
},
101+
});
68102
},
69103
// This is for passing along the original abort signal from the initial Request you retrieve in your worker
70104
// Ensures that the response we pass to NextServer is aborted if the request is aborted

0 commit comments

Comments
 (0)