kernel / core / itx / src / context / answer-body.test.tsmain at 949894f
import { afterEach, beforeEach, expect, test, vi } from "vitest";
import { ANSWER_BODY_UNREAD_AFTER_MS, untilBodyEnds, type BodyEnd } from "./answer-body.ts";
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
const encoder = new TextEncoder();
/** A body of `lines` lines, one each `everyMs`, and whether its reader cancelled it. */
function slowBody(lines: number, everyMs: number) {
const seen = { cancelled: false };
let line = 0;
const body = new ReadableStream<Uint8Array>({
async pull(controller) {
if (line === lines) return controller.close();
await new Promise((resolve) => setTimeout(resolve, everyMs));
controller.enqueue(encoder.encode(`${line++}\n`));
},
cancel() {
seen.cancelled = true;
},
});
return { body, seen };
}
function watchedAnswer(answer: unknown) {
const ends: (BodyEnd | null)[] = [];
return { answer: untilBodyEnds(answer, (how) => ends.push(how)), ends };
}
test("an answer with no body has ended at once, and is handed on as it is", () => {
const data = { some: "data" };
const empty = new Response(null, { status: 204 });
expect(watchedAnswer(data)).toEqual({ answer: data, ends: [null] });
expect(watchedAnswer(empty)).toEqual({ answer: empty, ends: [null] });
});
test("a body that takes two minutes arrives whole, and ends once, when it closes", async () => {
const { body } = slowBody(240, 500);
const { answer, ends } = watchedAnswer(
new Response(body, { status: 201, headers: { "content-type": "text/event-stream" } }),
);
const response = answer as Response;
expect([response.status, response.headers.get("content-type")]).toEqual([
201,
"text/event-stream",
]);
const text = response.text();
await vi.advanceTimersByTimeAsync(119_000);
expect(ends).toEqual([]);
await vi.advanceTimersByTimeAsync(1_000);
expect(await text).toBe(Array.from({ length: 240 }, (_, line) => `${line}\n`).join(""));
expect(ends).toEqual(["closed"]);
});
test("a chunk that is slow to come is not an unread body: its reader waits for it", async () => {
const { body } = slowBody(1, 5 * ANSWER_BODY_UNREAD_AFTER_MS);
const { answer, ends } = watchedAnswer(body);
const text = new Response(answer as ReadableStream).text();
await vi.advanceTimersByTimeAsync(5 * ANSWER_BODY_UNREAD_AFTER_MS - 1);
expect(ends).toEqual([]);
await vi.advanceTimersByTimeAsync(1);
expect(await text).toBe("0\n");
expect(ends).toEqual(["closed"]);
});
test("a watched body is a byte stream, and an empty chunk of its source is passed over", async () => {
const chunks = ["a", "", "b"].map((text) => encoder.encode(text));
const body = new ReadableStream<Uint8Array>({
pull(controller) {
const chunk = chunks.shift();
if (chunk) controller.enqueue(chunk);
else controller.close();
},
});
const { answer, ends } = watchedAnswer(body);
// only a byte stream gives a reader of this kind
const reader = (answer as ReadableStream<Uint8Array>).getReader({ mode: "byob" });
reader.releaseLock();
expect(await new Response(answer as ReadableStream).text()).toBe("ab");
expect(ends).toEqual(["closed"]);
});
test("a body that its reader drops ends as cancelled, and its source is cancelled", async () => {
const { body, seen } = slowBody(1000, 100);
const { answer, ends } = watchedAnswer(new Response(body));
const reader = (answer as Response).body!.getReader();
const first = reader.read();
await vi.advanceTimersByTimeAsync(100);
expect(new TextDecoder().decode((await first).value)).toBe("0\n");
await reader.cancel("the reader left");
expect(ends).toEqual(["cancelled"]);
expect(seen.cancelled).toBe(true);
});
test("a body whose source fails ends as errored, and its reader gets the error", async () => {
let fail: (error: Error) => void = () => {};
const body = new ReadableStream<Uint8Array>({
start(controller) {
fail = (error) => controller.error(error);
},
});
const { answer, ends } = watchedAnswer(body);
const read = (answer as ReadableStream<Uint8Array>).getReader().read();
fail(new Error("the far end hung up"));
await expect(read).rejects.toThrow("the far end hung up");
expect(ends).toEqual(["errored"]);
});
test("a body that nobody reads ends as unread after the bound, once", async () => {
const { body } = slowBody(10, 100);
const { answer, ends } = watchedAnswer(new Response(body));
await vi.advanceTimersByTimeAsync(ANSWER_BODY_UNREAD_AFTER_MS - 1);
expect(ends).toEqual([]);
await vi.advanceTimersByTimeAsync(1);
expect(ends).toEqual(["unread"]);
// the body is left as it is: a reader that comes back gets it, and no second end is said
const text = (answer as Response).text();
await vi.advanceTimersByTimeAsync(1_000);
expect(await text).toBe(Array.from({ length: 10 }, (_, line) => `${line}\n`).join(""));
expect(ends).toEqual(["unread"]);
});
test("a reader that stops asking mid-body ends it as unread", async () => {
const { body } = slowBody(10, 100);
const { answer, ends } = watchedAnswer(body);
const reader = (answer as ReadableStream<Uint8Array>).getReader();
const first = reader.read();
await vi.advanceTimersByTimeAsync(100);
await first;
await vi.advanceTimersByTimeAsync(ANSWER_BODY_UNREAD_AFTER_MS);
expect(ends).toEqual(["unread"]);
});