@zaisma/cli 0.33.0 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/chrome.mjs +152 -8
  2. package/package.json +1 -1
package/chrome.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  // Headless Chrome, for `zaisma check` on a shader's folder and Zaisma's own scripts that look at pages in a real browser
2
2
  // (scripts/chrome.mjs), driven over its DevTools protocol with Node's own WebSocket (Node 22 or newer), so it needs no dependency and
3
3
  // never downloads a browser. Chrome is the one in CHROME_PATH, the system's, or one Playwright or @puppeteer/browsers downloaded.
4
- import { spawn } from "node:child_process";
5
- import { existsSync, mkdtempSync, readdirSync, rmSync } from "node:fs";
4
+ import { spawn, spawnSync } from "node:child_process";
5
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6
6
  import { homedir, tmpdir } from "node:os";
7
7
  import { join } from "node:path";
8
8
 
@@ -54,9 +54,31 @@ function playwrightChromes() {
54
54
  * sessionId), listen(sessionId, onEvent) and close().
55
55
  */
56
56
  export async function openChrome(path, profilePrefix, { isGpu = false } = {}) {
57
- const profile = mkdtempSync(join(tmpdir(), profilePrefix));
57
+ await sweepOrphans();
58
+ // A folder for each Chrome: OWNER_FILE, which says whose it is, and Chrome's profile inside, removed before the folder so a profile
59
+ // that can't be removed yet keeps its owner for the next sweep.
60
+ const folder = mkdtempSync(join(tmpdir(), profilePrefix));
61
+ const profile = join(folder, "profile");
62
+ mkdirSync(profile);
58
63
  const webgl = isGpu ? ["--enable-gpu", "--ignore-gpu-blocklist", ...(process.platform === "darwin" ? ["--use-angle=metal"] : [])] : ["--use-angle=swiftshader", "--enable-unsafe-swiftshader"];
59
- const child = spawn(path, ["--headless=new", "--remote-debugging-port=0", `--user-data-dir=${profile}`, "--no-first-run", "--no-default-browser-check", ...webgl, "--autoplay-policy=no-user-gesture-required", "--hide-scrollbars", "--disable-renderer-backgrounding", "--disable-background-timer-throttling", "--disable-backgrounding-occluded-windows", "about:blank"], { stdio: ["ignore", "ignore", "pipe"] });
64
+ let child;
65
+ try {
66
+ child = spawn(path, ["--headless=new", "--remote-debugging-port=0", `--user-data-dir=${profile}`, "--no-first-run", "--no-default-browser-check", ...webgl, "--autoplay-policy=no-user-gesture-required", "--hide-scrollbars", "--disable-renderer-backgrounding", "--disable-background-timer-throttling", "--disable-backgrounding-occluded-windows", "about:blank"], { stdio: ["ignore", "ignore", "pipe"] });
67
+ } catch (error) {
68
+ rmSync(folder, { recursive: true, force: true });
69
+ throw error;
70
+ }
71
+ const running = { child, folder, profile };
72
+ if (child.pid) {
73
+ writeFileSync(join(folder, OWNER_FILE), JSON.stringify({ owner_process_id: process.pid, chrome_process_id: child.pid }));
74
+ keepUntilExit(running);
75
+ }
76
+ const giveUp = (error) => {
77
+ child.kill("SIGKILL");
78
+ removeFolder(running);
79
+ letGo(running);
80
+ throw error;
81
+ };
60
82
  const address = await new Promise((resolve, reject) => {
61
83
  let output = "";
62
84
  child.stderr.on("data", (chunk) => {
@@ -66,9 +88,9 @@ export async function openChrome(path, profilePrefix, { isGpu = false } = {}) {
66
88
  });
67
89
  child.on("error", (error) => reject(error));
68
90
  child.on("exit", (code) => reject(new Error(`Chrome stopped (${code}): ${output.slice(-500)}`)));
69
- });
91
+ }).catch(giveUp);
70
92
  const socket = new WebSocket(address);
71
- await new Promise((resolve, reject) => ((socket.onopen = resolve), (socket.onerror = reject)));
93
+ await new Promise((resolve, reject) => ((socket.onopen = resolve), (socket.onerror = reject))).catch(giveUp);
72
94
  let nextMessageNumber = 1;
73
95
  const waiting = new Map();
74
96
  const listeners = new Set();
@@ -96,10 +118,132 @@ export async function openChrome(path, profilePrefix, { isGpu = false } = {}) {
96
118
  // Chrome writes to its profile until it has exited, so it goes after.
97
119
  close: async () => {
98
120
  socket.close();
99
- const exited = new Promise((resolve) => child.once("exit", resolve));
121
+ const exited = new Promise((resolve) => (child.exitCode !== null || child.signalCode !== null ? resolve() : child.once("exit", resolve)));
100
122
  child.kill();
101
123
  await exited;
102
- rmSync(profile, { recursive: true, force: true, maxRetries: 5 });
124
+ await endAndRemove([running]);
125
+ letGo(running);
103
126
  },
104
127
  };
105
128
  }
129
+
130
+ /** The file in each Chrome's folder that says whose it is: { owner_process_id, chrome_process_id }. */
131
+ const OWNER_FILE = "zaisma-chrome-owner.json";
132
+ const STOP_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
133
+ /** The Chromes this process started and hasn't closed. */
134
+ const runningChromes = new Set();
135
+
136
+ // Chrome outlives the node process that started it unless something stops it: a script that exits without close(), or is stopped by a
137
+ // signal that skips its finally, would leave Chrome and its helpers running. So each one is killed when this process exits, and on
138
+ // SIGINT, SIGTERM and SIGHUP, which then end the process as they would have (a script with a handler of its own keeps its say).
139
+ function stopAll() {
140
+ const runnings = [...runningChromes];
141
+ runningChromes.clear();
142
+ // Nothing can be awaited on exit, so this waits in place, only as long as Chrome's processes take to end.
143
+ const deadlineMs = Date.now() + EXIT_TIME_LIMIT_MS;
144
+ const pause = new Int32Array(new SharedArrayBuffer(4));
145
+ while (killAll(runnings) && Date.now() < deadlineMs) Atomics.wait(pause, 0, 0, 50);
146
+ for (const running of runnings) removeFolder(running);
147
+ }
148
+ async function onSignal(signal) {
149
+ if (process.listenerCount(signal) > 1) return;
150
+ removeHandlers();
151
+ const runnings = [...runningChromes];
152
+ runningChromes.clear();
153
+ await endAndRemove(runnings);
154
+ process.kill(process.pid, signal);
155
+ }
156
+ function addHandlers() {
157
+ process.on("exit", stopAll);
158
+ for (const signal of STOP_SIGNALS) process.on(signal, onSignal);
159
+ }
160
+ function removeHandlers() {
161
+ process.off("exit", stopAll);
162
+ for (const signal of STOP_SIGNALS) process.off(signal, onSignal);
163
+ }
164
+ function keepUntilExit(running) {
165
+ if (!runningChromes.size) addHandlers();
166
+ runningChromes.add(running);
167
+ }
168
+ function letGo(running) {
169
+ if (runningChromes.delete(running) && !runningChromes.size) removeHandlers();
170
+ }
171
+
172
+ /** How long Chrome's processes get to end after SIGKILL before their folders are removed anyway: on exit, which holds the process up, and otherwise. */
173
+ const EXIT_TIME_LIMIT_MS = 2_000;
174
+ const END_TIME_LIMIT_MS = 5_000;
175
+
176
+ /**
177
+ * Sends SIGKILL to every process of these Chromes still running (the one started here, and each whose command line names its profile:
178
+ * the helpers, or a dead owner's Chrome), and says whether there were any. Chrome's helpers write to the profile until they've exited,
179
+ * so a folder is removed only once this finds none.
180
+ */
181
+ function killAll(runnings) {
182
+ const children = runnings.flatMap(({ child }) => (child && child.exitCode === null && child.signalCode === null ? [child] : []));
183
+ const processNumbers = profileProcessNumbers(runnings.map(({ profile }) => profile));
184
+ for (const child of children) child.kill("SIGKILL");
185
+ for (const processNumber of processNumbers) {
186
+ try {
187
+ process.kill(processNumber, "SIGKILL");
188
+ } catch {}
189
+ }
190
+ return children.length > 0 || processNumbers.length > 0;
191
+ }
192
+
193
+ /** Kills these Chromes and removes their folders once their processes have ended. */
194
+ async function endAndRemove(runnings) {
195
+ const deadlineMs = Date.now() + END_TIME_LIMIT_MS;
196
+ while (killAll(runnings) && Date.now() < deadlineMs) await new Promise((resolve) => setTimeout(resolve, 50));
197
+ for (const running of runnings) removeFolder(running);
198
+ }
199
+
200
+ /** The processes whose command line names one of these profiles; Windows has no ps, so none there. */
201
+ function profileProcessNumbers(profiles) {
202
+ if (process.platform === "win32" || !profiles.length) return [];
203
+ const listed = spawnSync("ps", ["-A", "-o", "pid=,command="], { encoding: "utf8" }).stdout ?? "";
204
+ return listed.split("\n").flatMap((line) => {
205
+ const [, processNumber, command] = line.match(/^\s*(\d+)\s+(.*)$/) ?? [];
206
+ return processNumber && profiles.some((profile) => command.includes(`--user-data-dir=${profile}`)) ? [Number(processNumber)] : [];
207
+ });
208
+ }
209
+
210
+ /** Removes a Chrome's profile, then its folder; one that can't be removed yet stays, with its owner, for the next sweep. */
211
+ function removeFolder({ folder, profile }) {
212
+ try {
213
+ rmSync(profile, { recursive: true, force: true, maxRetries: 5 });
214
+ rmSync(folder, { recursive: true, force: true });
215
+ } catch {}
216
+ }
217
+
218
+ const isAlive = (processNumber) => {
219
+ try {
220
+ process.kill(processNumber, 0);
221
+ return true;
222
+ } catch (error) {
223
+ return error.code === "EPERM";
224
+ }
225
+ };
226
+
227
+ /**
228
+ * Kills the Chromes, and removes the folders, of owners that died without closing them (SIGKILL, a crash), so the next openChrome
229
+ * cleans up after them; another run's Chrome, whose owner is alive, is left alone. A process is only killed when its command line names
230
+ * the dead owner's profile, so a reused process id is never hit; on Windows only the folder is removed.
231
+ */
232
+ async function sweepOrphans() {
233
+ let names;
234
+ try {
235
+ names = readdirSync(tmpdir());
236
+ } catch {
237
+ return;
238
+ }
239
+ const orphans = names.flatMap((name) => {
240
+ const folder = join(tmpdir(), name);
241
+ try {
242
+ const owner = JSON.parse(readFileSync(join(folder, OWNER_FILE), "utf8"));
243
+ return isAlive(owner.owner_process_id) ? [] : [{ child: null, folder, profile: join(folder, "profile") }];
244
+ } catch {
245
+ return [];
246
+ }
247
+ });
248
+ if (orphans.length) await endAndRemove(orphans);
249
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zaisma/cli",
3
- "version": "0.33.0",
3
+ "version": "0.34.0",
4
4
  "description": "Upload and publish browser games on Zaisma from the command line.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://zaisma.com",