Файли
openidea/perf/lib/lifecycle.ts
T
Mr0Bread 34cb4ad5e0 fix(bench): preserve failed trials and bound cleanup (#4489)
Failed warmups and repetitions were dropped from benchmark summaries, a failed startup, build or cleanup could leave an earlier success report in place, and a hung renderer or child process could block a run. Every attempt now keeps its status, metrics and error so summaries have the complete denominator; failures replace stale reports; browser and child-process lifecycles are bounded with cleanup of owned resources; and each criterion execution gets its own artifact directory.

Co-authored-by: Mr0Bread <[email protected]>
2026-11-19 19:38:34 +08:00

60 рядки
2.0 KiB
TypeScript

import { chromium, type Browser, type LaunchOptions } from "@playwright/test";
import type { Server } from "node:http";
export class DeadlineError extends Error {
constructor(label: string, timeoutMs: number) {
super(`${label} timed out after ${timeoutMs} ms (wall clock)`);
this.name = "DeadlineError";
}
}
/** Runs on Node's clock even if the renderer, rAF, or an RPC never answers. */
export async function withDeadline<T>(operation: Promise<T>, timeoutMs: number, label: string): Promise<T> {
const { promise, reject } = Promise.withResolvers<never>();
const timer = setTimeout(() => reject(new DeadlineError(label, timeoutMs)), timeoutMs);
try {
return await Promise.race([operation, promise]);
} finally {
clearTimeout(timer);
}
}
export interface BrowserSession {
browser: Browser;
close(): Promise<void>;
}
export async function launchBrowser(options: LaunchOptions, cleanupMs = 5000): Promise<BrowserSession> {
const server = await chromium.launchServer({ ...options, timeout: 30_000 });
const close = async () => {
try {
await withDeadline(server.close(), cleanupMs, "browser close");
} catch (error) {
try {
await withDeadline(server.kill(), cleanupMs, "browser kill");
} catch (killError) {
throw new AggregateError([error, killError], "Browser cleanup failed", { cause: killError });
}
throw error;
}
};
try {
const browser = await chromium.connect(server.wsEndpoint(), { timeout: 30_000 });
return { browser, close };
} catch (error) {
try {
await close();
} catch (cleanup) {
throw new AggregateError([error, cleanup], "Browser startup failed", { cause: cleanup });
}
throw error;
}
}
export async function closeServer(server: Server) {
server.closeAllConnections();
const { promise, resolve, reject } = Promise.withResolvers<void>();
server.close((error) => (error ? reject(error) : resolve()));
await withDeadline(promise, 5000, "HTTP server close");
}