Files
hyperframes/packages/engine/src/services/browserLeasePool.test.ts
T
Miguel Ángel 1b8f8a43d4 fix(cli): stopping the preview server no longer leaves a Chrome running (#4183)
* fix(cli): stop the preview server's browser when the server exits

Cancel in-flight renders and thumbnail launches before draining the
browser pool on shutdown, instead of only closing whatever browser was
already registered. A render whose Chrome died from the shutdown signal
itself was being misclassified as a transient failure and retried with a
fresh, untracked browser that outlived the process. Reject new render and
thumbnail requests once shutdown has begun, and await an in-flight
thumbnail launch before closing it.

* fix(cli): close preview browsers before a hung render, keep SIGINT armed

shutdown() awaited renders before closing browsers, so a render slower
than preview.ts 3s exit watchdog left Chrome running when it fired.
Close the thumbnail browser and drain the pool concurrently with, not
after, the render wait, and bound the wait under that watchdog.

A second Ctrl+C/SIGTERM during shutdown removed the one-shot signal
handlers, so it hit the OS default and killed the process before
cleanup ran. Use persistent handlers guarded by the existing
shuttingDown flag instead.

Also: getThumbnailBrowser could still hand a live lease to a request
that lands after shuttingDown flips true; trim a comment over budget;
replace a fixed-sleep test race with a drain-signal barrier.

* fix(engine): make browser pool shutdown terminal, not just draining

drain() resets its drainPromise to null once it settles, so acquire()
only waits for an in-flight drain -- a render still unwinding after
shutdown could relaunch Chrome the instant that drain resolved
(probeStage.ts:449-465 has exactly this gap between an abort check
and a later acquireBrowser call). No non-shutdown caller reuses the
pool after draining it (checked every drainBrowserPool()/drain()
call site), but added a separate terminal close() rather than
changing drain()'s own semantics, so a future reuse caller stays
safe by default.

BrowserLeasePool.close() sets a permanent closed flag before
draining, and acquire() checks it both before and after its one
await point, so a request already mid-await when close() lands still
sees it once that await resolves. studioServer's shutdown() now
calls the new closeBrowserPool() instead of drainBrowserPool().

Also bounds drain()'s own wait: a close() that hangs past 1s now
gets escalated to a force-close instead of blocking the caller
indefinitely, keeping total shutdown time under preview.ts's 3s exit
watchdog alongside the existing render-wait bound.

* fix(engine): trim closeBrowserPool JSDoc to house comment length
2026-09-22 22:49:44 -04:00

210 lines
7.4 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import type { Browser } from "puppeteer-core";
import { BrowserLeasePool, type BrowserLaunchFingerprint } from "./browserLeasePool.js";
function browser(name: string): Browser {
return {
connected: true,
close: vi.fn().mockResolvedValue(undefined),
disconnect: vi.fn(),
process: () => null,
version: vi.fn().mockResolvedValue(name),
} as unknown as Browser;
}
function fingerprint(args: string[] = ["--one"]): BrowserLaunchFingerprint {
return {
args,
executablePath: "/chrome",
browserTimeoutMs: 1_000,
protocolTimeoutMs: 2_000,
requestedCaptureMode: "screenshot",
};
}
describe("BrowserLeasePool", () => {
it("shares only an exact immutable launch fingerprint", async () => {
const firstBrowser = browser("first");
const secondBrowser = browser("second");
const launch = vi
.fn()
.mockResolvedValueOnce({ browser: firstBrowser, captureMode: "screenshot" as const })
.mockResolvedValueOnce({ browser: secondBrowser, captureMode: "screenshot" as const });
const pool = new BrowserLeasePool({
launch,
close: async (value) => value.close(),
forceClose: vi.fn(),
});
const mutableArgs = ["--one"];
const first = await pool.acquire(fingerprint(mutableArgs), true);
mutableArgs.push("--mutated-after-acquire");
const shared = await pool.acquire(fingerprint(), true);
const isolated = await pool.acquire(fingerprint(["--two"]), true);
expect(shared.browser).toBe(first.browser);
expect(isolated.browser).toBe(secondBrowser);
expect(first.fingerprint.args).toEqual(["--one"]);
expect(Object.isFrozen(first.fingerprint)).toBe(true);
expect(Object.isFrozen(first.fingerprint.args)).toBe(true);
await Promise.all([first.release(), shared.release(), isolated.release()]);
});
it("removes a final lease from availability before awaiting close", async () => {
const firstBrowser = browser("first");
const secondBrowser = browser("second");
let finishFirstClose!: () => void;
const firstClose = new Promise<void>((resolve) => {
finishFirstClose = resolve;
});
const launch = vi
.fn()
.mockResolvedValueOnce({ browser: firstBrowser, captureMode: "screenshot" as const })
.mockResolvedValueOnce({ browser: secondBrowser, captureMode: "screenshot" as const });
const close = vi.fn((value: Browser) =>
value === firstBrowser ? firstClose : Promise.resolve(),
);
const pool = new BrowserLeasePool({ launch, close, forceClose: vi.fn() });
const first = await pool.acquire(fingerprint(), true);
const releasing = first.release();
const replacement = await pool.acquire(fingerprint(), true);
expect(replacement.browser).toBe(secondBrowser);
expect(launch).toHaveBeenCalledTimes(2);
finishFirstClose();
await releasing;
await replacement.release();
});
it("makes lease release idempotent", async () => {
const value = browser("only");
const close = vi.fn().mockResolvedValue(undefined);
const pool = new BrowserLeasePool({
launch: vi.fn().mockResolvedValue({ browser: value, captureMode: "screenshot" }),
close,
forceClose: vi.fn(),
});
const lease = await pool.acquire(fingerprint(), true);
await Promise.all([lease.release(), lease.release(), lease.release()]);
expect(close).toHaveBeenCalledTimes(1);
});
it("rejects ambiguous release through the shared browser handle", async () => {
const value = browser("shared");
const close = vi.fn().mockResolvedValue(undefined);
const forceClose = vi.fn();
const pool = new BrowserLeasePool({
launch: vi.fn().mockResolvedValue({ browser: value, captureMode: "screenshot" }),
close,
forceClose,
});
const renderLease = await pool.acquire(fingerprint(), true);
const thumbnailLease = await pool.acquire(fingerprint(), true);
await expect(pool.releaseByBrowser(value)).rejects.toThrow(
"Cannot release a pooled browser by handle while 2 leases are active",
);
pool.forceReleaseByBrowser(value);
expect(close).not.toHaveBeenCalled();
expect(forceClose).not.toHaveBeenCalled();
await thumbnailLease.release();
expect(close).not.toHaveBeenCalled();
await renderLease.release();
expect(close).toHaveBeenCalledTimes(1);
});
it("evicts a failed launch so the next acquire can recover", async () => {
const recovered = browser("recovered");
const launch = vi
.fn()
.mockRejectedValueOnce(new Error("launch failed"))
.mockResolvedValueOnce({ browser: recovered, captureMode: "screenshot" as const });
const pool = new BrowserLeasePool({
launch,
close: async (value) => value.close(),
forceClose: vi.fn(),
});
await expect(pool.acquire(fingerprint(), true)).rejects.toThrow("launch failed");
const lease = await pool.acquire(fingerprint(), true);
expect(lease.browser).toBe(recovered);
expect(launch).toHaveBeenCalledTimes(2);
await lease.release();
});
it("drains an in-flight launch without returning the closing browser", async () => {
const value = browser("pending");
let finishLaunch!: () => void;
const pendingLaunch = new Promise<{ browser: Browser; captureMode: "screenshot" }>(
(resolve) => {
finishLaunch = () => resolve({ browser: value, captureMode: "screenshot" });
},
);
const close = vi.fn().mockResolvedValue(undefined);
const pool = new BrowserLeasePool({
launch: vi.fn().mockReturnValue(pendingLaunch),
close,
forceClose: vi.fn(),
});
const acquiring = pool.acquire(fingerprint(), true);
const draining = pool.drain();
finishLaunch();
await expect(acquiring).rejects.toThrow("drained during acquisition");
await draining;
expect(close).toHaveBeenCalledWith(value);
});
it("refuses acquire after close, even once the drain it started has resolved", async () => {
const value = browser("only");
const launch = vi.fn().mockResolvedValue({ browser: value, captureMode: "screenshot" });
const pool = new BrowserLeasePool({
launch,
close: async (v) => v.close(),
forceClose: vi.fn(),
});
const first = await pool.acquire(fingerprint(), true);
const releasing = first.release();
// drain()'s own drainPromise resets to null once it settles -- close()
// must still refuse a request that arrives after that, not just a
// request that raced the drain while it was in flight.
await pool.close();
await releasing;
launch.mockClear();
await expect(pool.acquire(fingerprint(), true)).rejects.toThrow(/pool is closed/i);
expect(launch).not.toHaveBeenCalled();
});
it("force-closes an entry whose graceful close hangs past drain's bound", async () => {
vi.useFakeTimers();
try {
const value = browser("stuck");
const forceClose = vi.fn();
const pool = new BrowserLeasePool({
launch: vi.fn().mockResolvedValue({ browser: value, captureMode: "screenshot" }),
close: () => new Promise<void>(() => {}), // never resolves
forceClose,
});
const lease = await pool.acquire(fingerprint(), true);
const releasing = lease.release();
const draining = pool.drain();
await vi.advanceTimersByTimeAsync(1_100);
await draining;
await releasing;
expect(forceClose).toHaveBeenCalledWith(value);
} finally {
vi.useRealTimers();
}
});
});