Skip to content

Commit b5cab5b

Browse files
committed
fix(api): respect backpressure when streaming asset downloads
toWebReadableStream read the source with on("data") and had no cancel handler, so a slow or disconnected client caused the whole asset to be read from disk/S3 and buffered. Use Readable.toWeb, which propagates backpressure and destroys the source on cancel.
1 parent 3e22b65 commit b5cab5b

1 file changed

Lines changed: 5 additions & 9 deletions

File tree

‎packages/api/utils/upload.ts‎

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -38,15 +38,11 @@ export function webStreamToNode(
3838
export function toWebReadableStream(
3939
nodeStream: NodeJS.ReadableStream,
4040
): ReadableStream<Uint8Array> {
41-
const reader = nodeStream as unknown as Readable;
42-
43-
return new ReadableStream({
44-
start(controller) {
45-
reader.on("data", (chunk) => controller.enqueue(new Uint8Array(chunk)));
46-
reader.on("end", () => controller.close());
47-
reader.on("error", (err) => controller.error(err));
48-
},
49-
});
41+
// Readable.toWeb propagates backpressure and destroys the source on cancel,
42+
// so slow or disconnected clients don't cause the whole asset to be read.
43+
return Readable.toWeb(
44+
nodeStream as Readable,
45+
) as unknown as ReadableStream<Uint8Array>;
5046
}
5147

5248
export async function uploadAsset(

0 commit comments

Comments
 (0)