Skip to content

Commit c809580

Browse files
committed
fix(telegram): cancel unread response body on media fetch error
1 parent e2e394e commit c809580

2 files changed

Lines changed: 24 additions & 1 deletion

File tree

‎extensions/telegram/src/bot.media.e2e-harness.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ async function defaultReadRemoteMediaBuffer(
4343
}
4444
const response = await params.fetchImpl(params.url, { redirect: "manual" });
4545
if (!response.ok) {
46+
await response.body?.cancel().catch(() => undefined);
4647
throw new Error(
4748
`Failed to fetch media from ${params.url}: HTTP ${response.status} ${response.statusText}`,
4849
);

‎extensions/telegram/src/bot.media.stickers-and-fragments.e2e.test.ts‎

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,11 @@ import { mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";
33
import os from "node:os";
44
import path from "node:path";
55
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
6-
import { readRemoteMediaBufferSpy, telegramBotDepsForTest } from "./bot.media.e2e-harness.js";
6+
import {
7+
readRemoteMediaBufferSpy,
8+
resetReadRemoteMediaBufferMock,
9+
telegramBotDepsForTest,
10+
} from "./bot.media.e2e-harness.js";
711
import {
812
TELEGRAM_TEST_TIMINGS,
913
cacheStickerSpy,
@@ -270,6 +274,24 @@ describe("telegram local Bot API media", () => {
270274
await rm(tempRoot, { recursive: true, force: true });
271275
}
272276
});
277+
278+
it("cancels response body on non-ok status before throwing", async () => {
279+
const cancel = vi.fn();
280+
const body = new ReadableStream<Uint8Array>({ cancel });
281+
const response = new Response(body, { status: 404, statusText: "Not Found" });
282+
const fetchImpl = vi.fn().mockResolvedValue(response);
283+
284+
resetReadRemoteMediaBufferMock();
285+
286+
await expect(
287+
readRemoteMediaBufferSpy({
288+
url: "https://example.com/file.jpg",
289+
fetchImpl: fetchImpl as unknown as typeof fetch,
290+
}),
291+
).rejects.toThrow("Failed to fetch media from https://example.com/file.jpg");
292+
293+
expect(cancel).toHaveBeenCalledOnce();
294+
});
273295
});
274296

275297
describe("telegram text fragments", () => {

0 commit comments

Comments
 (0)