Skip to content
This repository was archived by the owner on Mar 13, 2025. It is now read-only.

Commit 70a7f13

Browse files
committed
Use ReadableStream for multipart/byteranges encoding
1 parent 9326118 commit 70a7f13

File tree

1 file changed

+18
-9
lines changed

1 file changed

+18
-9
lines changed

packages/cache/src/range.ts

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { ReadableStream } from "stream/web";
12
import { TextEncoder } from "util";
23
import { Response } from "@miniflare/core";
34
import { Headers } from "undici";
@@ -107,19 +108,27 @@ export function _getRangeResponse(
107108
Math.floor(Math.random() * Number.MAX_SAFE_INTEGER)
108109
.toString()
109110
.padStart(16, "0");
110-
const arrays: Uint8Array[] = [];
111-
for (const [start, end] of ranges) {
112-
const header = `--${boundary}\r\nContent-Type: ${contentType}\r\nContent-Range: bytes ${start}-${end}/${responseBody.byteLength}\r\n\r\n`;
113-
arrays.push(encoder.encode(header));
114-
arrays.push(responseBody.slice(start, end + 1));
115-
arrays.push(encoder.encode("\r\n"));
116-
}
117-
arrays.push(encoder.encode(`--${boundary}--`));
111+
const stream = new ReadableStream({
112+
type: "bytes",
113+
pull(controller) {
114+
const range = ranges.shift();
115+
if (range === undefined) {
116+
controller.enqueue(encoder.encode(`--${boundary}--`));
117+
return controller.close();
118+
}
119+
120+
const [start, end] = range;
121+
const header = `--${boundary}\r\nContent-Type: ${contentType}\r\nContent-Range: bytes ${start}-${end}/${responseBody.byteLength}\r\n\r\n`;
122+
controller.enqueue(encoder.encode(header));
123+
controller.enqueue(responseBody.slice(start, end + 1));
124+
controller.enqueue(encoder.encode("\r\n"));
125+
},
126+
});
118127
responseHeaders.set(
119128
"Content-Type",
120129
`multipart/byteranges; boundary=${boundary}`
121130
);
122-
return new Response(Buffer.concat(arrays), {
131+
return new Response(stream, {
123132
status: 206, // Partial Content
124133
headers: responseHeaders,
125134
});

0 commit comments

Comments
 (0)