Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/ResponseHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,12 @@ export class ResponseHelper {
body: ReadableStream,
expressResponse: express.Response,
): Promise<void> {
const source = Readable.fromWeb(body);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
source.on("error", () => undefined);
try {
await pipeline(Readable.fromWeb(body), expressResponse);
await pipeline(source, expressResponse);
} catch (err) {
source.destroy();
logger.error("Stream error piping response from upstream:", err);
if (!expressResponse.writableEnded) {
expressResponse.end();
Expand Down
37 changes: 37 additions & 0 deletions test/unit/ResponseHelper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,43 @@ describe("ResponseHelper", () => {
await responseHelper.pipe(erroring, dest as unknown as Response);
expect(endSpy).toHaveBeenCalledTimes(1);
});

test("pipe: cancels the upstream body when the response is already destroyed", async () => {
const dest = new PassThrough();
dest.destroy();

const cancel = jest.fn();
const body = new ReadableStream({
pull(controller) {
controller.enqueue("chunk");
},
cancel,
});

await responseHelper.pipe(body, dest as unknown as Response);
expect(cancel).toHaveBeenCalledTimes(1);
});

test("pipe: handles an already-errored body when the response is already destroyed", async () => {
const dest = new PassThrough();
dest.destroy();

const errored = new ReadableStream({
start(controller) {
controller.error(new Error("upstream error"));
},
});

const uncaught = jest.fn();
process.on("uncaughtException", uncaught);
try {
await responseHelper.pipe(errored, dest as unknown as Response);
await new Promise((resolve) => setImmediate(resolve));
} finally {
process.off("uncaughtException", uncaught);
}
expect(uncaught).not.toHaveBeenCalled();
});
});

describe("ResponseHelper getRemoteImagePromise tests", () => {
Expand Down
Loading