diff --git a/e2e/console/workers-answers.ts b/e2e/console/workers-answers.ts new file mode 100644 index 000000000..6c4853c34 --- /dev/null +++ b/e2e/console/workers-answers.ts @@ -0,0 +1,77 @@ +import type { Page, Route } from "@playwright/test"; + +interface WorkerPayload { + load?: + | { + memory?: { availableBytes?: number; pressure?: string; totalBytes?: number } | undefined; + } + | undefined; +} + +// why: the page re-reads the list every second, so a re-read can be intercepted just as the test's +// `finally` stops the gateway; the refused connect it gets is the fleet going away, not a failure of +// the test, and Playwright would otherwise charge the rejection to it. Only connect-level errors are +// dropped: any other error is a real fault and must still kill the test. +const CONNECT_ERROR = /ECONNREFUSED|ECONNRESET|socket hang up/i; + +async function fetchOrDrop(route: Route): Promise> | undefined> { + try { + return await route.fetch(); + } catch (error) { + if (!(error instanceof Error) || !CONNECT_ERROR.test(error.message)) throw error; + await route.abort().catch(() => undefined); + return undefined; + } +} + +// why: the two fields a colour case has to state; everything else in the reading stays the +// daemon's. +export interface MemoryClaim { + readonly pressure?: string; + readonly usedPercent: number; +} + +/** + * why: only macOS reports a memory pressure, and how full a CI machine's memory happens to be is + * nobody's to predict — so the colour test states the memory reading it wants and this writes just + * those fields into the daemon's own answer, leaving every other field, its headers and its `Date` + * real. The route is asked again per request, so the reading stays as fresh as the daemon's own. + */ +export async function answerMemory(page: Page, claim: () => MemoryClaim): Promise { + await page.route( + (url) => url.pathname === "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/v1/workers", + async (route: Route) => { + const response = await fetchOrDrop(route); + if (response === undefined) return; + const listed = (await response.json()) as { workers: WorkerPayload[] }; + for (const worker of listed.workers) { + const memory = worker.load?.memory; + const total = memory?.totalBytes; + if (memory === undefined || typeof total !== "number" || total <= 0) continue; + const wanted = claim(); + memory.availableBytes = Math.round((total * (100 - wanted.usedPercent)) / 100); + if (wanted.pressure === undefined) delete memory.pressure; + else memory.pressure = wanted.pressure; + } + await route.fulfill({ json: listed, response }); + }, + ); +} + +/** + * why: a machine's own disk or CPU may already be over a threshold, which would turn every square + * the page draws and hide the state a test is about (a drain, a lost link). A test about squares + * answers the page's read of the worker list without the load reading, so only the states are left. + */ +export async function answerWithoutLoad(page: Page): Promise { + await page.route( + (url) => url.pathname === "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/v1/workers", + async (route: Route) => { + const response = await fetchOrDrop(route); + if (response === undefined) return; + const listed = (await response.json()) as { workers: WorkerPayload[] }; + for (const worker of listed.workers) delete worker.load; + await route.fulfill({ json: listed, response }); + }, + ); +} diff --git a/e2e/console/workers-gateway-stops-mid-fetch.spec.ts b/e2e/console/workers-gateway-stops-mid-fetch.spec.ts new file mode 100644 index 000000000..33c884d73 --- /dev/null +++ b/e2e/console/workers-gateway-stops-mid-fetch.spec.ts @@ -0,0 +1,171 @@ +import type { Locator, Page, Route } from "@playwright/test"; + +import { waitFor } from "../helpers/wait.js"; +import { answerMemory, answerWithoutLoad } from "./workers-answers.js"; +import { disposeFleet, expect, type RunningDaemon, signIn, startFleet, test } from "./fixtures.js"; + +/** + * why: reproduces #642. The workers page's response helpers (`answerWithoutLoad`, `answerMemory`) + * answer the page's re-reads of `/v1/workers` by fetching them from the gateway through + * `route.fetch()`, and the page re-reads every second. A re-read intercepted but not yet fetched + * when the test's `finally` disposes the fleet gets a refused connect — a listener destroyed + * mid-request reads the same way as a socket hang up — and Playwright attributes the handler's + * rejection to the test, so the spec dies on the helper's `route.fetch()` line although every + * assertion it made had passed. The lane races that window by accident; this holds it open: the + * next re-read is parked inside the handler before it fetches, the gateway's listener is confirmed + * gone, and only then is the parked fetch let go. The park is the injection; every other line is + * the lane's own. + */ + +const IOS = { availableOsVersions: ["18.4"], knownModels: ["iPhone 16"] }; + +async function openConsole(page: Page, daemon: RunningDaemon): Promise { + await page.goto(daemon.url); + await signIn(page, daemon.tokens.operator); + await page.getByRole("link", { name: "Workers", exact: true }).click(); + await expect(page.getByRole("heading", { level: 1, name: "Workers" })).toBeVisible(); +} + +function workerRows(page: Page): Locator { + return page.getByRole("list", { name: "Workers", exact: true }).getByRole("listitem"); +} + +async function askForWorkerList(page: Page, daemon: RunningDaemon): Promise { + return page.evaluate( + (bearer) => + fetch("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/v1/workers", { headers: { authorization: bearer } }).then( + (response) => response.status, + () => 0, + ), + `Bearer ${daemon.tokens.operator}`, + ); +} + +async function listenerIsGone(daemon: RunningDaemon): Promise { + try { + return (await fetch(new URL("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/v1/healthz", daemon.url))).status >= 400; + } catch { + return true; + } +} + +test.describe("the workers page response helper against a gateway whose listener stops", () => { + test("the re-read whose gateway listener stops between its interception and the helper's fetch is dropped by the helper instead of escaping it", async ({ + page, + }) => { + const fleet = await startFleet([ + { driverScript: { ios: IOS }, label: "worker-a" }, + { driverScript: { ios: IOS }, label: "worker-b" }, + ]); + let parkNext = false; + let parkedSeen = false; + let parkedArrived = { resolve: () => {} }; + let releaseParked = { resolve: () => {} }; + const arrived = new Promise((resolve) => { + parkedArrived = { resolve }; + }); + const released = new Promise((resolve) => { + releaseParked = { resolve }; + }); + await answerWithoutLoad(page); + // why: Playwright runs the latest-registered route first, so this one parks the next re-read + // before the lane's real helper above sees it, then hands it on with `fallback()`: the helper's + // `route.fetch()` is the only line that meets the dead listener, as in the lane. + await page.route( + (url) => url.pathname === "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/v1/workers", + async (route: Route) => { + if (parkNext && !parkedSeen) { + parkedSeen = true; + parkNext = false; + parkedArrived.resolve(); + await released; + } + await route.fallback(); + }, + ); + + try { + await openConsole(page, fleet.gateway); + await expect(workerRows(page)).toHaveCount(2); + + // why: the same helper answers through this gateway while it is up, so a refusal below is the + // listener being gone and not a route that never worked (testing rule 2). + expect(await askForWorkerList(page, fleet.gateway)).toBe(200); + + parkNext = true; + const asked = askForWorkerList(page, fleet.gateway); + await arrived; + await disposeFleet(fleet); + await waitFor(() => listenerIsGone(fleet.gateway), { + interval: 50, + label: "the gateway's HTTP listener stopped", + timeout: 10_000, + }); + releaseParked.resolve(); + + // why: once the helper drops the re-read the page's own promise settles (0 when aborted); + // a rejection escaping the helper fails the test at its `route.fetch()` line instead. + await asked; + await expect(page.getByRole("heading", { level: 1, name: "Workers" })).toBeVisible(); + } finally { + await disposeFleet(fleet).catch(() => undefined); + } + }); +}); + +type Handler = (route: Route) => Promise; + +function captureHandler(answer: (page: Page) => Promise): Promise { + return new Promise((resolve) => { + const page = { route: async (_match: unknown, handler: Handler) => resolve(handler) }; + void answer(page as unknown as Page); + }); +} + +test.describe("what the workers page response helper drops and what it lets through", () => { + test("a fetch that fails for a reason other than the connection going away still rejects out of the helper", async () => { + const handler = await captureHandler(answerWithoutLoad); + let aborted = false; + const route = { + abort: async () => { + aborted = true; + }, + fetch: async () => { + throw new Error("getaddrinfo ENOTFOUND gateway.invalid"); + }, + } as unknown as Route; + + await expect(handler(route)).rejects.toThrow("ENOTFOUND"); + expect(aborted).toBe(false); + }); + + const helpers = [ + ["answerWithoutLoad", answerWithoutLoad], + ["answerMemory", (page: Page) => answerMemory(page, () => ({ usedPercent: 50 }))], + ] as const; + const goneAway = [ + ["refused at connect", "connect ECONNREFUSED 127.0.0.1:1"], + ["destroyed mid-request (socket hang up)", "socket hang up"], + ["reset by the peer", "read ECONNRESET"], + ] as const; + + for (const [helperName, helper] of helpers) { + for (const [how, message] of goneAway) { + test(`${helperName}: a fetch ${how} is aborted and resolves quietly`, async () => { + const handler = await captureHandler(helper); + let aborted = false; + const route = { + abort: async () => { + aborted = true; + }, + fetch: async () => { + throw new Error(message); + }, + } as unknown as Route; + + await handler(route); + expect(aborted).toBe(true); + }); + } + } +}); diff --git a/e2e/console/workers.spec.ts b/e2e/console/workers.spec.ts index 0e6b8b648..3a819fc8a 100644 --- a/e2e/console/workers.spec.ts +++ b/e2e/console/workers.spec.ts @@ -1,6 +1,7 @@ -import type { Locator, Page, Route } from "@playwright/test"; +import type { Locator, Page } from "@playwright/test"; import { waitFor } from "../helpers/wait.js"; +import { answerMemory, answerWithoutLoad, type MemoryClaim } from "./workers-answers.js"; import { disposeFleet, expect, @@ -42,64 +43,6 @@ interface WorkerView { }; } -interface WorkerPayload { - load?: - | { - memory?: { availableBytes?: number; pressure?: string; totalBytes?: number } | undefined; - } - | undefined; -} - -// why: the two fields a colour case has to state; everything else in the reading stays the -// daemon's. -interface MemoryClaim { - readonly pressure?: string; - readonly usedPercent: number; -} - -/** - * why: only macOS reports a memory pressure, and how full a CI machine's memory happens to be is - * nobody's to predict — so the colour test states the memory reading it wants and this writes just - * those fields into the daemon's own answer, leaving every other field, its headers and its `Date` - * real. The route is asked again per request, so the reading stays as fresh as the daemon's own. - */ -async function answerMemory(page: Page, claim: () => MemoryClaim): Promise { - await page.route( - (url) => url.pathname === "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/v1/workers", - async (route: Route) => { - const response = await route.fetch(); - const listed = (await response.json()) as { workers: WorkerPayload[] }; - for (const worker of listed.workers) { - const memory = worker.load?.memory; - const total = memory?.totalBytes; - if (memory === undefined || typeof total !== "number" || total <= 0) continue; - const wanted = claim(); - memory.availableBytes = Math.round((total * (100 - wanted.usedPercent)) / 100); - if (wanted.pressure === undefined) delete memory.pressure; - else memory.pressure = wanted.pressure; - } - await route.fulfill({ json: listed, response }); - }, - ); -} - -/** - * why: a machine's own disk or CPU may already be over a threshold, which would turn every square - * the page draws and hide the state a test is about (a drain, a lost link). A test about squares - * answers the page's read of the worker list without the load reading, so only the states are left. - */ -async function answerWithoutLoad(page: Page): Promise { - await page.route( - (url) => url.pathname === "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/v1/workers", - async (route: Route) => { - const response = await route.fetch(); - const listed = (await response.json()) as { workers: WorkerPayload[] }; - for (const worker of listed.workers) delete worker.load; - await route.fulfill({ json: listed, response }); - }, - ); -} - interface Status { readonly devices: readonly { readonly id: string;