Skip to content

Commit 725dbb9

Browse files
Yuruzuuclaude
andcommitted
perf(server): the headless browser closes after five idle minutes (517 MiB → 1.6 MiB median)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent a760f37 commit 725dbb9

3 files changed

Lines changed: 78 additions & 8 deletions

File tree

‎apps/server/src/preview/ServerBrowser.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -487,6 +487,7 @@ const make = Effect.gen(function* () {
487487

488488
const contexts = new ServerBrowserContexts({
489489
profilesDir: NodePath.join(config.stateDir, "server-browser", "profiles"),
490+
idleBrowserMs: 5 * 60_000,
490491
executable: () => runPromise(previewBrowser.executable),
491492
// An agent scope keeps Chrome out of the server's memory protection and OOM score.
492493
launcher: async (executable) => {

‎apps/server/src/preview/ServerBrowserContexts.test.ts‎

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ const makeContext = () => {
2222
return {
2323
on: vi.fn((event: string, listener: () => void) => events.on(event, listener)),
2424
pages: vi.fn(() => []),
25+
newPage: vi.fn(async () => ({ once: vi.fn() })),
26+
isClosed: () => closed,
2527
close: vi.fn(async () => {
2628
if (!closed) {
2729
closed = true;
@@ -35,7 +37,8 @@ const makeBrowser = () => {
3537
const events = new NodeEvents.EventEmitter();
3638
const contexts: ReturnType<typeof makeContext>[] = [];
3739
return {
38-
contexts,
40+
created: contexts,
41+
contexts: () => contexts.filter((context) => !context.isClosed()),
3942
on: vi.fn((event: string, listener: () => void) => events.on(event, listener)),
4043
newContext: vi.fn(async () => {
4144
const context = makeContext();
@@ -74,6 +77,37 @@ beforeEach(() => {
7477
});
7578

7679
describe("ServerBrowserContexts", () => {
80+
it("closes the shared browser only after it holds no context for the idle period", async () => {
81+
vi.useFakeTimers();
82+
try {
83+
const first = makeBrowser();
84+
const second = makeBrowser();
85+
launches.launch
86+
.mockResolvedValueOnce(first as unknown as Browser)
87+
.mockResolvedValueOnce(second as unknown as Browser);
88+
const pool = new ServerBrowserContexts({ ...options(), idleBrowserMs: 10 });
89+
const agent = await pool.contextFor("default", "agent");
90+
await pool.scratchPage();
91+
await agent.close();
92+
await vi.advanceTimersByTimeAsync(10);
93+
expect(first.close).not.toHaveBeenCalled();
94+
await first.created[1]!.close();
95+
await vi.advanceTimersByTimeAsync(9);
96+
const next = await pool.contextFor("default", "next");
97+
await vi.advanceTimersByTimeAsync(10);
98+
expect(first.close).not.toHaveBeenCalled();
99+
await next.close();
100+
await vi.advanceTimersByTimeAsync(10);
101+
expect(first.close).toHaveBeenCalledOnce();
102+
await pool.contextFor("default", "later");
103+
expect(launches.launch).toHaveBeenCalledTimes(2);
104+
expect(second.newContext).toHaveBeenCalledOnce();
105+
await pool.close();
106+
} finally {
107+
vi.useRealTimers();
108+
}
109+
});
110+
77111
it("lazily shares one browser across concurrent isolated sessions and reuses each context", async () => {
78112
const browser = makeBrowser();
79113
const launch = Promise.withResolvers<Browser>();
@@ -107,7 +141,7 @@ describe("ServerBrowserContexts", () => {
107141
});
108142
await pool.close();
109143
expect(browser.close).toHaveBeenCalledTimes(1);
110-
for (const context of browser.contexts) expect(context.close).toHaveBeenCalled();
144+
for (const context of browser.created) expect(context.close).toHaveBeenCalled();
111145
});
112146

113147
it("keeps human profiles persistent without sharing their storage with agents", async () => {
@@ -172,7 +206,7 @@ describe("ServerBrowserContexts", () => {
172206
force: true,
173207
});
174208
expect(await pool.contextFor("work/team", "agent")).toBe(agent);
175-
expect(browser.contexts[0]?.close).not.toHaveBeenCalled();
209+
expect(browser.created[0]?.close).not.toHaveBeenCalled();
176210
launches.persistent.mockResolvedValue(makeContext() as unknown as BrowserContext);
177211
expect(await pool.contextFor("work/team")).not.toBe(persistent);
178212
await pool.clearProfile("never-opened");
@@ -291,6 +325,6 @@ describe("ServerBrowserContexts", () => {
291325
await expect(pool.contextFor("default", "agent")).rejects.toThrow("closed");
292326
await pool.close();
293327
expect(browser.close).toHaveBeenCalledTimes(1);
294-
expect(browser.contexts[0]?.close).toHaveBeenCalled();
328+
expect(browser.created[0]?.close).toHaveBeenCalled();
295329
});
296330
});

‎apps/server/src/preview/ServerBrowserContexts.ts‎

Lines changed: 39 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// @effect-diagnostics nodeBuiltinImport:off - Owns Playwright resources outside the Effect runtime.
1+
// @effect-diagnostics nodeBuiltinImport:off globalTimers:off - Owns Playwright resources outside the Effect runtime.
22
import { INCOGNITO_BROWSER_PROFILE_ID } from "@t3tools/contracts";
33
import { constVoid } from "effect/Function";
44
import * as NodeFSP from "node:fs/promises";
@@ -26,6 +26,8 @@ interface Options {
2626
) => Promise<{ readonly path: string; readonly release: () => Promise<void> } | undefined>;
2727
readonly diagnose?: (executable: string, cause: unknown) => Promise<unknown>;
2828
readonly env?: NodeJS.ProcessEnv;
29+
/** Closes the shared browser once it has held no context for this long. */
30+
readonly idleBrowserMs?: number;
2931
readonly onContextClose?: (context: BrowserContext) => void;
3032
}
3133

@@ -80,6 +82,8 @@ export class ServerBrowserContexts {
8082
private readonly clearing = new Map<string, Promise<void>>();
8183
private browser: Promise<Browser> | undefined;
8284
private closing: Promise<void> | undefined;
85+
private idleTimer: ReturnType<typeof setTimeout> | undefined;
86+
private pendingSharedContexts = 0;
8387

8488
constructor(options: Options) {
8589
this.options = options;
@@ -136,6 +140,37 @@ export class ServerBrowserContexts {
136140
return this.browser;
137141
}
138142

143+
private async sharedContext(options?: Parameters<Browser["newContext"]>[0]) {
144+
clearTimeout(this.idleTimer);
145+
this.pendingSharedContexts++;
146+
const launched = this.sharedBrowser();
147+
try {
148+
const context = await (await launched).newContext(options);
149+
context.on("close", () => this.retireWhenIdle(launched));
150+
return context;
151+
} finally {
152+
this.pendingSharedContexts--;
153+
this.retireWhenIdle(launched);
154+
}
155+
}
156+
157+
private retireWhenIdle(launched: Promise<Browser>) {
158+
const delay = this.options.idleBrowserMs;
159+
if (delay === undefined || this.closing || this.pendingSharedContexts > 0) return;
160+
clearTimeout(this.idleTimer);
161+
this.idleTimer = setTimeout(() => void this.retire(launched), delay);
162+
this.idleTimer.unref();
163+
}
164+
165+
private async retire(launched: Promise<Browser>) {
166+
const browser = await launched.catch(() => undefined);
167+
if (!browser || this.browser !== launched || this.pendingSharedContexts > 0) return;
168+
if (browser.contexts().length > 0) return;
169+
// Cleared first, so a request during the close launches a fresh browser.
170+
this.browser = undefined;
171+
await browser.close().catch(constVoid);
172+
}
173+
139174
contextFor(profileId: string, isolationKey?: string): Promise<BrowserContext> {
140175
if (this.closing) return Promise.reject(new Error("The preview browser is closed."));
141176
const key = JSON.stringify([profileId, isolationKey ?? null]);
@@ -166,8 +201,7 @@ export class ServerBrowserContexts {
166201
private async createContext(profileId: string, isolationKey?: string) {
167202
const contextOptions = { viewport: { width: 1280, height: 800 }, deviceScaleFactor: 2 };
168203
if (isolationKey !== undefined || profileId === INCOGNITO_BROWSER_PROFILE_ID) {
169-
const browser = await this.sharedBrowser();
170-
return browser.newContext(contextOptions);
204+
return this.sharedContext(contextOptions);
171205
}
172206
const directory = this.profileDirectory(profileId);
173207
await NodeFSP.mkdir(directory, { recursive: true });
@@ -192,7 +226,7 @@ export class ServerBrowserContexts {
192226

193227
async scratchPage() {
194228
if (this.closing) throw new Error("The preview browser is closed.");
195-
const context = await (await this.sharedBrowser()).newContext();
229+
const context = await this.sharedContext();
196230
const page = await context.newPage();
197231
page.once("close", () => void context.close().catch(constVoid));
198232
return page;
@@ -237,6 +271,7 @@ export class ServerBrowserContexts {
237271
}
238272

239273
private async dispose() {
274+
clearTimeout(this.idleTimer);
240275
await Promise.allSettled(
241276
[...this.contexts.values()].map(async (pending) => (await pending).close()),
242277
);

0 commit comments

Comments
 (0)