fix: normalize abort signals for fetch

This commit is contained in:
Peter Steinberger
2026-01-21 17:29:39 +00:00
parent 8aca606a6f
commit 4e1806947d
8 changed files with 81 additions and 9 deletions

View File

@@ -0,0 +1,37 @@
import { describe, expect, it, vi } from "vitest";
import { resolveTelegramFetch } from "./fetch.js";
describe("resolveTelegramFetch", () => {
it("wraps proxy fetch to normalize foreign abort signals", async () => {
let seenSignal: AbortSignal | undefined;
const proxyFetch = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {
seenSignal = init?.signal as AbortSignal | undefined;
return {} as Response;
});
const fetcher = resolveTelegramFetch(proxyFetch);
expect(fetcher).toBeTypeOf("function");
let abortHandler: (() => void) | null = null;
const fakeSignal = {
aborted: false,
addEventListener: (event: string, handler: () => void) => {
if (event === "abort") abortHandler = handler;
},
removeEventListener: (event: string, handler: () => void) => {
if (event === "abort" && abortHandler === handler) abortHandler = null;
},
} as AbortSignal;
const promise = fetcher!("https://example.com", { signal: fakeSignal });
expect(proxyFetch).toHaveBeenCalledOnce();
expect(seenSignal).toBeInstanceOf(AbortSignal);
expect(seenSignal).not.toBe(fakeSignal);
abortHandler?.();
expect(seenSignal?.aborted).toBe(true);
await promise;
});
});

View File

@@ -1,13 +1,13 @@
import { wrapFetchWithAbortSignal } from "../infra/fetch.js";
import { resolveFetch } from "../infra/fetch.js";
// Bun-only: force native fetch to avoid grammY's Node shim under Bun.
export function resolveTelegramFetch(proxyFetch?: typeof fetch): typeof fetch | undefined {
if (proxyFetch) return wrapFetchWithAbortSignal(proxyFetch);
const fetchImpl = globalThis.fetch;
if (proxyFetch) return resolveFetch(proxyFetch);
const isBun = "Bun" in globalThis || Boolean(process?.versions?.bun);
if (!isBun) return undefined;
const fetchImpl = resolveFetch();
if (!fetchImpl) {
throw new Error("fetch is not available; set channels.telegram.proxy in config");
}
return wrapFetchWithAbortSignal(fetchImpl);
return fetchImpl;
}