Skip to content
Closed
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
23 changes: 18 additions & 5 deletions src/web/blog-refresh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -299,6 +299,19 @@ function sourceChainFor(rel: string): { name: SourceName; url: string }[] {
];
}

/** Release an unread response body, then stop the idle watchdog (fetch-util
* #552): a rejected or early-returned response is never consumed, so without
* an explicit cancel the stopped watchdog can no longer reclaim the still-open
* connection. The cancel is fire-and-forget so cleanup never delays the
* fail-soft result; cancelling an already-consumed body is a no-op, hence the
* bodyUsed guard. */
function releaseAndStop(result: { response: Response; stopIdleTimer: () => void }): void {
if (!result.response.bodyUsed) {
void result.response.body?.cancel().catch(() => {});
}
result.stopIdleTimer();
}

async function getJsonList(url: string): Promise<ContentsEntry[]> {
const result = await fetchWithTimeout(url, ghHeaders("application/json"), FETCH_TIMEOUT_MS);
try {
Expand All @@ -307,7 +320,7 @@ async function getJsonList(url: string): Promise<ContentsEntry[]> {
if (!Array.isArray(raw)) throw new Error("contents listing is not a JSON array");
return raw as ContentsEntry[];
} finally {
result.stopIdleTimer(); // body fully consumed (fetch-util #552 contract)
releaseAndStop(result);
}
}

Expand All @@ -327,7 +340,7 @@ async function fetchPlainText(url: string, account?: (bytes: number) => void): P
account?.(buf.byteLength);
return buf.toString("utf8");
} finally {
result.stopIdleTimer();
releaseAndStop(result);
}
}

Expand All @@ -352,7 +365,7 @@ async function fetchApiText(rel: string, account?: (bytes: number) => void): Pro
account?.(buf.byteLength);
return buf.toString("utf8");
} finally {
result.stopIdleTimer();
releaseAndStop(result);
}
}

Expand Down Expand Up @@ -399,7 +412,7 @@ async function fetchPlainImage(url: string, account?: (bytes: number) => void):
account?.(buf.byteLength);
return { buf, type };
} finally {
result.stopIdleTimer();
releaseAndStop(result);
}
}

Expand All @@ -425,7 +438,7 @@ async function fetchApiImage(rel: string, account?: (bytes: number) => void): Pr
account?.(buf.byteLength);
return { buf, type };
} finally {
result.stopIdleTimer();
releaseAndStop(result);
}
}

Expand Down
9 changes: 7 additions & 2 deletions src/web/changelog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,13 @@ async function runCheck(): Promise<void> {
}
state = { releases, lastCheckAt: Date.now() };
} finally {
// Fully consumed the body — stop the idle watchdog so the timer
// cannot pin the event loop (fetch-util's #552 contract).
// A rejected non-2xx body is never consumed; cancel it before
// stopping the idle watchdog, or the stopped watchdog can no longer
// reclaim the still-open connection (fetch-util #552). Fire-and-
// forget so cleanup never delays the fail-soft result.
if (!result.response.bodyUsed) {
void result.response.body?.cancel().catch(() => {});
}
result.stopIdleTimer();
}
} catch (e) {
Expand Down
14 changes: 14 additions & 0 deletions tests/web-blog-refresh.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,20 @@ test("raw AND contents-API dead (rate-limited) → the round fails soft with the
assert.ok(!hits.some((h) => !h.startsWith("https://raw.githubusercontent.com/") && !h.startsWith("https://api.github.com/")));
});

test("a non-2xx listing response releases its unread body before the idle watchdog stops (#552)", async () => {
let cancelled = 0;
const body = new ReadableStream<Uint8Array>({
start(controller) { controller.enqueue(new TextEncoder().encode("rate limited")); },
cancel() { cancelled += 1; },
});
router = (url) => url === CONTENTS_URL
? new Response(body, { status: 429 })
: new Response("nf", { status: 404 });
assert.equal((await runBlogRefreshRound({ force: true })).ok, true); // fail-soft, marker rides the feed
assert.equal(getBlogFeed().error, "offline");
assert.equal(cancelled, 1, "the rejected 429 body must not retain its transport once the watchdog stops");
});

test("healthy raw path never touches the API file endpoints (overseas unchanged)", async () => {
installGithubRouter();
await runBlogRefreshRound({ force: true });
Expand Down
96 changes: 95 additions & 1 deletion tests/web-changelog.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
*/
import { test, beforeEach, afterEach } from "node:test";
import assert from "node:assert/strict";
import type { ServerResponse } from "node:http";
import { createServer, type ServerResponse } from "node:http";
import type { AddressInfo } from "node:net";
import { once } from "node:events";
import { getChangelog, latestChangelog, _resetChangelogForTest } from "../src/web/changelog.ts";

const GH = "https://api.github.com/repos/ranxianglei/billion-context/releases?per_page=20";
Expand Down Expand Up @@ -120,6 +122,98 @@ test("HTTP 500 fails soft like a network error", async () => {
assert.deepEqual(data, { releases: [], error: "offline" });
});

for (const status of [429, 503]) {
test(`HTTP ${status} cancels an unread response and retains the last good changelog`, async () => {
globalThis.fetch = fetchStub([ghRelease(0)]);
const good = await getChangelog();
let cancelled = 0;
const body = new ReadableStream<Uint8Array>({
start(controller) { controller.enqueue(new TextEncoder().encode("upstream error")); },
cancel() { cancelled += 1; },
});
globalThis.fetch = (async () => new Response(body, { status })) as typeof fetch;
const failed = await getChangelog({ force: true });
assert.deepEqual(failed, { releases: good.releases, error: "offline" });
assert.equal(cancelled, 1, "the rejected HTTP body must not retain its transport");
});
}

test("an unread HTTP error body is closed on the actual connection", async t => {
let closed!: () => void;
const bodyClosed = new Promise<void>(resolve => { closed = resolve; });
const server = createServer((_req, res) => {
res.on("close", closed);
res.writeHead(503, { "content-type": "text/plain" });
res.write("temporarily unavailable");
});
server.listen(0, "127.0.0.1");
await once(server, "listening");
t.after(async () => {
server.closeAllConnections();
await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
});
const local = `http://127.0.0.1:${(server.address() as AddressInfo).port}/releases`;
globalThis.fetch = ((input: string | URL | Request, init?: RequestInit) => {
assert.equal(String(input), GH);
return origFetch(local, init);
}) as typeof fetch;
assert.deepEqual(await getChangelog(), { releases: [], error: "offline" });
let deadline: ReturnType<typeof setTimeout> | undefined;
try {
const ended = await Promise.race([
bodyClosed.then(() => true),
new Promise<boolean>(resolve => { deadline = setTimeout(() => resolve(false), 1_000); }),
]);
assert.equal(ended, true, "rejecting the status must close a body that never ends");
} finally {
clearTimeout(deadline);
}
});

test("a successful changelog consumes its response without cancelling it", async () => {
let cancelled = 0;
const body = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new TextEncoder().encode(JSON.stringify([ghRelease(0)])));
controller.close();
},
cancel() { cancelled += 1; },
});
globalThis.fetch = (async () => new Response(body)) as typeof fetch;
assert.equal((await getChangelog()).releases[0]?.tag, "v0.9.100");
assert.equal(cancelled, 0);
});

test("a failed cancellation cannot replace the cached offline result", async () => {
let cancelled = 0;
const body = new ReadableStream<Uint8Array>({
cancel() { cancelled += 1; throw new Error("fixture cancellation failure"); },
});
globalThis.fetch = (async () => new Response(body, { status: 429 })) as typeof fetch;
assert.deepEqual(await getChangelog(), { releases: [], error: "offline" });
assert.equal(cancelled, 1);
await new Promise<void>(resolve => setImmediate(resolve));
});

test("releasing an unread tee branch does not wait for its other consumer", async () => {
const source = new ReadableStream<Uint8Array>({
start(controller) { controller.enqueue(new TextEncoder().encode("busy")); },
});
const [body, other] = source.tee();
globalThis.fetch = (async () => new Response(body, { status: 503 })) as typeof fetch;
let deadline: ReturnType<typeof setTimeout> | undefined;
try {
const result = await Promise.race([
getChangelog(),
new Promise<undefined>(resolve => { deadline = setTimeout(() => resolve(undefined), 1_000); }),
]);
assert.deepEqual(result, { releases: [], error: "offline" }, "cleanup must not turn an HTTP rejection into a wait for a sibling stream");
} finally {
clearTimeout(deadline);
await other.cancel();
}
});

test("non-array / non-object payloads fail soft", async () => {
globalThis.fetch = fetchStub({ message: "API rate limit exceeded" });
let data = await getChangelog();
Expand Down
Loading