// THE BROWSER THAT HOLDS A PROFILE, BY PID (lane x-trending-2) — for ending a // browser that no longer answers. // // Playwright gives a persistent context no process handle (only // `launchServer` has `process()`), and closing a context that has stopped // answering closes nothing: the browser keeps the profile, and every later // read, capture, Refresh and Connect fails on Chromium's profile lock until // somebody kills it by hand. So the pid is read where Chromium itself writes // it: `/SingletonLock`, a symlink to `-`. // // A PID IS ONLY EVER KILLED WHEN IT IS THIS PROFILE'S BROWSER, and every one // of these holds: // - the lock was written on THIS machine (its host is os.hostname(): a // profile on a shared disk can carry another machine's pid); // - the process's command line (`/proc//cmdline`) names this exact // profile directory, `--user-data-dir=` as one argument; // - its first argument looks like a Chromium binary (chrome, chromium, // headless_shell, …); // - it is the BROWSER process, not one of its children: no `--type=` // argument (renderers, the GPU process and the rest carry one). // The check is made once, by killProfileBrowser, immediately before the // signal — nothing else runs between reading the command line and signalling. // A stale lock whose pid now belongs to another process, a lock of another // profile, another program that merely mentions the directory: none is // signalled. Linux only (it reads /proc); anywhere else, and whenever the // check does not hold, nothing is killed and the caller is told why — it falls // back to closing, and says so in the job's log. // // `process.kill(pid)` on a checked pid, never a child's `.kill()` and never a // process group. import { readFile, readlink } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; export type ProfileBrowserPidDeps = { platform?: string; readlink?: (file: string) => Promise; // /proc//cmdline, raw (arguments separated by NUL). cmdline?: (pid: number) => Promise; kill?: (pid: number, signal: NodeJS.Signals) => void; selfPid?: number; hostname?: string; }; const CHROMIUM_BINARY = /^(chrome|chromium|chromium-browser|chrome-headless-shell|headless_shell|google-chrome(-[a-z]+)?|brave(-browser)?|msedge|microsoft-edge(-[a-z]+)?)$/i; export type ProfileBrowserPid = { pid: number } | { pid: null; why: string }; const realCmdline = (pid: number) => readFile(`/proc/${pid}/cmdline`, "utf8"); // The pid of the browser holding `profileDir`, checked against its command // line — or why there is none to name. export async function profileBrowserPid(profileDir: string, deps: ProfileBrowserPidDeps = {}): Promise { if ((deps.platform ?? process.platform) !== "linux") { return { pid: null, why: "finding the browser's process is Linux-only" }; } const dir = path.resolve(profileDir); let target: string; try { target = await (deps.readlink ?? readlink)(path.join(dir, "SingletonLock")); } catch { return { pid: null, why: "the profile has no browser lock (no browser holds it)" }; } const m = /^(.*)-(\d{1,10})$/.exec(target); const pid = m ? Number(m[2]) : NaN; if (m && m[1] !== (deps.hostname ?? os.hostname())) { return { pid: null, why: "the profile's lock was written on another machine: its process is not looked for here" }; } if (!Number.isInteger(pid) || pid <= 1 || pid === (deps.selfPid ?? process.pid)) { return { pid: null, why: "the profile's lock names no browser process" }; } let cmdline: string; try { cmdline = await (deps.cmdline ?? realCmdline)(pid); } catch { return { pid: null, why: `the process the profile's lock names (${pid}) is gone` }; } const args = cmdline.split("\0"); // The exact directory, as one argument: never a prefix of another profile's path. const names = args.some((a) => a.startsWith("--user-data-dir=") && path.resolve(a.slice("--user-data-dir=".length)) === dir); if (!names) { return { pid: null, why: `process ${pid} does not name this profile on its command line (a stale lock): it is left alone` }; } if (!CHROMIUM_BINARY.test(path.basename(args[0] ?? ""))) { return { pid: null, why: `process ${pid} is not a Chromium browser (${path.basename(args[0] ?? "") || "no name"}): it is left alone` }; } if (args.some((a) => a.startsWith("--type="))) { return { pid: null, why: `process ${pid} is one of a browser's child processes, not the browser: it is left alone` }; } return { pid }; } export type KilledProfileBrowser = { killed: true; pid: number } | { killed: false; why: string }; // SIGKILL to the browser holding `profileDir` — only to a pid that passes the // check above, made here, immediately before the signal. export async function killProfileBrowser(profileDir: string, deps: ProfileBrowserPidDeps = {}): Promise { const found = await profileBrowserPid(profileDir, deps); if (found.pid === null) return { killed: false, why: found.why }; try { (deps.kill ?? ((pid, signal) => void process.kill(pid, signal)))(found.pid, "SIGKILL"); } catch (err) { return { killed: false, why: `process ${found.pid} could not be signalled (${(err as Error).message.split("\n")[0]})` }; } return { killed: true, pid: found.pid }; }