Skip to content

Commit 92aaa70

Browse files
fix(cli): guard process snapshot capture
Co-authored-by: miguel.sierra <[email protected]>
1 parent edf6e4b commit 92aaa70

29 files changed

Lines changed: 2099 additions & 231 deletions

‎packages/cli/README.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,9 @@ npx hyperframes render -o output.mp4
7171
npx hyperframes render -c ./my-composition.html -o output.mp4
7272
```
7373

74+
Set `HYPERFRAMES_RENDER_DETACHED=1` when starting a render with `nohup` or
75+
`disown` so it keeps running after the invoking shell exits.
76+
7477
### `publish`
7578

7679
Upload a project directory and get a hosted URL that keeps working after the CLI exits.

‎packages/cli/src/browser/ffmpeg.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { execFileSync } from "node:child_process";
22
import { findFfBinary } from "@hyperframes/parsers/ff-binaries";
33
import { detectLinuxDistro, ffmpegInstallCommand } from "./linuxDeps.js";
4+
import { runCancellableProcess } from "../utils/cancellableProcess.js";
45

56
export { FFMPEG_PATH_ENV, FFPROBE_PATH_ENV } from "@hyperframes/parsers/ff-binaries";
67

@@ -40,6 +41,18 @@ export function detectH264EncoderMode(ffmpegPath: string, gpuRequested: boolean)
4041
return resolveH264EncoderMode(encoders, gpuRequested);
4142
}
4243

44+
export async function detectH264EncoderModeForRender(
45+
ffmpegPath: string,
46+
gpuRequested: boolean,
47+
signal: AbortSignal,
48+
): Promise<H264EncoderMode> {
49+
const result = await runCancellableProcess(ffmpegPath, ["-hide_banner", "-encoders"], {
50+
signal,
51+
timeoutMs: 5000,
52+
});
53+
return resolveH264EncoderMode(result.stdout, gpuRequested);
54+
}
55+
4356
// `configuredMustExist`: the CLI surfaces an install hint when a binary is
4457
// missing, so an env override pointing at a nonexistent file reports as
4558
// not-found instead of being handed to spawn.

‎packages/cli/src/browser/manager.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ function installFsMocks({ existing, dirs, touchError, initialMtimeMs = 0 }: FsMo
7070
// assert the lock dir doesn't leak after ensureBrowser resolves.
7171
const paths = new Set(existing);
7272
const mtimes = new Map([...existing].map((p) => [p, initialMtimeMs]));
73+
const contents = new Map<string, string>();
7374
vi.doMock("node:fs", () => ({
7475
existsSync: (p: string) => paths.has(p),
7576
readdirSync: (p: string) => {
@@ -94,6 +95,7 @@ function installFsMocks({ existing, dirs, touchError, initialMtimeMs = 0 }: FsMo
9495
if (existingPath === p || existingPath.startsWith(p + sep)) {
9596
paths.delete(existingPath);
9697
mtimes.delete(existingPath);
98+
contents.delete(existingPath);
9799
}
98100
}
99101
},
@@ -114,6 +116,19 @@ function installFsMocks({ existing, dirs, touchError, initialMtimeMs = 0 }: FsMo
114116
}
115117
mtimes.set(p, mtime.getTime());
116118
},
119+
writeFileSync: (p: string, value: string) => {
120+
paths.add(p);
121+
contents.set(p, value);
122+
},
123+
readFileSync: (p: string) => {
124+
const value = contents.get(p);
125+
if (value === undefined) {
126+
const err = new Error(`ENOENT: no such file or directory, read '${p}'`);
127+
(err as NodeJS.ErrnoException).code = "ENOENT";
128+
throw err;
129+
}
130+
return value;
131+
},
117132
}));
118133
vi.doMock("node:os", () => ({
119134
homedir: () => FAKE_HOME,

‎packages/cli/src/browser/manager.ts‎

Lines changed: 71 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,21 @@
11
// fallow-ignore-file code-duplication
22
import { execSync, spawnSync } from "node:child_process";
3-
import { existsSync, mkdirSync, readdirSync, rmSync, statSync, utimesSync } from "node:fs";
3+
import { randomUUID } from "node:crypto";
4+
import {
5+
existsSync,
6+
mkdirSync,
7+
readFileSync,
8+
readdirSync,
9+
rmSync,
10+
statSync,
11+
utimesSync,
12+
writeFileSync,
13+
} from "node:fs";
414
import { basename } from "node:path";
515
import { homedir } from "node:os";
616
import { join } from "node:path";
717
import { normalizeErrorMessage } from "../utils/errorMessage.js";
18+
import { runRenderSetupWorker } from "../utils/cancellableProcess.js";
819

920
type PuppeteerBrowsers = typeof import("@puppeteer/browsers");
1021

@@ -57,6 +68,9 @@ const PUPPETEER_CACHE_DIR = join(homedir(), ".cache", "puppeteer", "chrome-headl
5768
// doubles as a zero-dependency cross-process mutex — no lockfile library needed.
5869
const INSTALL_LOCK_DIR = join(CACHE_ROOT_DIR, ".chrome.install.lock");
5970
const INSTALL_RECLAIM_LOCK_DIR = join(CACHE_ROOT_DIR, ".chrome.install.reclaim.lock");
71+
const INSTALL_LOCK_OWNER_FILE = join(INSTALL_LOCK_DIR, "owner");
72+
const INSTALL_LOCK_OWNER_ENV = "HYPERFRAMES_BROWSER_LOCK_OWNER";
73+
let ownedInstallLockToken: string | undefined;
6074
const INSTALL_LOCK_TIMINGS = {
6175
staleMs: 120_000,
6276
pollMs: 200,
@@ -134,6 +148,7 @@ function touchInstallLock(): void {
134148
}
135149
}
136150

151+
// fallow-ignore-next-line complexity
137152
export async function withInstallLock<T>(
138153
fn: () => Promise<T>,
139154
timings: InstallLockTimings = INSTALL_LOCK_TIMINGS,
@@ -156,6 +171,14 @@ export async function withInstallLock<T>(
156171
continue;
157172
}
158173
if (tryAcquireDirLock(INSTALL_LOCK_DIR)) {
174+
ownedInstallLockToken = process.env[INSTALL_LOCK_OWNER_ENV] ?? randomUUID();
175+
try {
176+
writeFileSync(INSTALL_LOCK_OWNER_FILE, ownedInstallLockToken);
177+
} catch (error) {
178+
ownedInstallLockToken = undefined;
179+
rmSync(INSTALL_LOCK_DIR, { recursive: true, force: true });
180+
throw error;
181+
}
159182
rmSync(INSTALL_RECLAIM_LOCK_DIR, { recursive: true, force: true });
160183
break;
161184
}
@@ -184,10 +207,25 @@ export async function withInstallLock<T>(
184207
return await fn();
185208
} finally {
186209
clearInterval(heartbeat);
187-
rmSync(INSTALL_LOCK_DIR, { recursive: true, force: true });
210+
releaseOwnedBrowserInstallLock();
188211
}
189212
}
190213

214+
export function releaseOwnedBrowserInstallLock(): void {
215+
if (!ownedInstallLockToken) return;
216+
releaseBrowserInstallLock(ownedInstallLockToken);
217+
}
218+
219+
function releaseBrowserInstallLock(ownerToken: string): void {
220+
if (ownedInstallLockToken === ownerToken) ownedInstallLockToken = undefined;
221+
try {
222+
if (readFileSync(INSTALL_LOCK_OWNER_FILE, "utf8") !== ownerToken) return;
223+
} catch {
224+
return;
225+
}
226+
rmSync(INSTALL_LOCK_DIR, { recursive: true, force: true });
227+
}
228+
191229
export type BrowserSource = "env" | "cache" | "system" | "download";
192230

193231
export interface BrowserResult {
@@ -211,6 +249,7 @@ export interface EnsureBrowserOptions {
211249
// eligible renders outright; HF#2060). `HYPERFRAMES_BROWSER_PATH` still
212250
// wins over this — an explicit override is still an explicit override.
213251
preferManagedChrome?: boolean;
252+
signal?: AbortSignal;
214253
}
215254

216255
interface CacheLookupResult {
@@ -614,6 +653,14 @@ async function ensureLinuxArmBrowser(options?: EnsureBrowserOptions): Promise<Br
614653
* (puppeteer-cache preference and system Chrome are both skipped).
615654
*/
616655
export async function ensureBrowser(options?: EnsureBrowserOptions): Promise<BrowserResult> {
656+
if (options?.signal) return ensureBrowserInOwnedProcess(options);
657+
return ensureBrowserInCurrentProcess(options);
658+
}
659+
660+
// fallow-ignore-next-line complexity
661+
async function ensureBrowserInCurrentProcess(
662+
options?: EnsureBrowserOptions,
663+
): Promise<BrowserResult> {
617664
const fromEnv = findFromEnv();
618665
if (fromEnv) return fromEnv;
619666

@@ -665,6 +712,28 @@ export async function ensureBrowser(options?: EnsureBrowserOptions): Promise<Bro
665712
});
666713
}
667714

715+
async function ensureBrowserInOwnedProcess(options: EnsureBrowserOptions): Promise<BrowserResult> {
716+
const signal = options.signal;
717+
signal?.throwIfAborted();
718+
const lockOwner = randomUUID();
719+
try {
720+
return await runRenderSetupWorker<BrowserResult>(
721+
"browser",
722+
{
723+
force: options.force,
724+
preferManagedChrome: options.preferManagedChrome,
725+
},
726+
{
727+
signal,
728+
maxBufferBytes: 4 * 1024 * 1024,
729+
env: { [INSTALL_LOCK_OWNER_ENV]: lockOwner },
730+
},
731+
);
732+
} finally {
733+
releaseBrowserInstallLock(lockOwner);
734+
}
735+
}
736+
668737
/**
669738
* True when `err` is a corrupt/truncated-archive extraction failure, as opposed
670739
* to a network error or a genuine platform problem. A partially-downloaded or

0 commit comments

Comments
 (0)