mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-25 16:37:32 +00:00
fix(producer): a compile's ffmpeg runs end with it, and are bounded on their own (#8638)
A render's compile can start ffmpeg and ffprobe children (the animated GIF to VP9 and HEIC to JPEG conversions, and media probes). They now end with the compile, however it ends, and their temp output goes with them. - The compile's abort signal reaches the GIF and HEIC conversions. - The compile worker reports each child and its temp file to the parent, which kills the children still recorded and removes their temp files just before ending the thread, only inside the compile's own folders. - The conversions carry -timelimit (CPU seconds, enforced by the kernel) and -fs (output bytes); a capped output is rejected, not cached. - Temp names carry a uuid, since worker threads share process.pid. Co-authored-by: 郑润泽 <506166760@qq.com>
This commit is contained in:
@@ -480,7 +480,11 @@ export {
|
||||
FFPROBE_PATH_ENV,
|
||||
} from "./utils/ffmpegBinaries.js";
|
||||
|
||||
export { trackChildProcess, killTrackedProcesses } from "./utils/processTracker.js";
|
||||
export {
|
||||
trackChildProcess,
|
||||
killTrackedProcesses,
|
||||
onTrackedChildProcess,
|
||||
} from "./utils/processTracker.js";
|
||||
export { renameWithRetry, renameWithRetryAsync } from "@hyperframes/core/rename-retry";
|
||||
export { removeScratch, collectScratchLeftovers } from "@hyperframes/core/remove-scratch";
|
||||
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
import { spawn } from "node:child_process";
|
||||
import { trackChildProcess, killTrackedProcesses } from "./processTracker.js";
|
||||
import {
|
||||
trackChildProcess,
|
||||
killTrackedProcesses,
|
||||
onTrackedChildProcess,
|
||||
} from "./processTracker.js";
|
||||
|
||||
// Reset tracked set between tests by killing everything
|
||||
beforeEach(() => {
|
||||
@@ -92,4 +96,17 @@ describe("killTrackedProcesses", () => {
|
||||
killTrackedProcesses();
|
||||
killTrackedProcesses();
|
||||
});
|
||||
|
||||
it("tells a listener about each tracked child until it unsubscribes", () => {
|
||||
const seen: number[] = [];
|
||||
const stop = onTrackedChildProcess((proc) => seen.push(proc.pid ?? -1));
|
||||
const first = spawn("sleep", ["60"], { stdio: "ignore" });
|
||||
trackChildProcess(first);
|
||||
stop();
|
||||
const second = spawn("sleep", ["60"], { stdio: "ignore" });
|
||||
trackChildProcess(second);
|
||||
killTrackedProcesses();
|
||||
|
||||
expect(seen).toEqual([first.pid]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
import type { ChildProcess } from "node:child_process";
|
||||
|
||||
const tracked = new Set<ChildProcess>();
|
||||
const listeners = new Set<(proc: ChildProcess) => void>();
|
||||
|
||||
export function onTrackedChildProcess(listener: (proc: ChildProcess) => void): () => void {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
}
|
||||
|
||||
export function trackChildProcess(proc: ChildProcess): void {
|
||||
tracked.add(proc);
|
||||
for (const listener of listeners) listener(proc);
|
||||
const remove = () => tracked.delete(proc);
|
||||
proc.once("exit", remove);
|
||||
proc.once("close", remove);
|
||||
|
||||
@@ -1,8 +1,27 @@
|
||||
// Stands in for compileWorker.ts. workerData.projectDir picks the behaviour: "hang" spins in one
|
||||
// synchronous pass and never answers, "typed" fails with a typed producer error.
|
||||
// synchronous pass and never answers, "typed" fails with a typed producer error, "child" starts a
|
||||
// long-running child writing a temp file in downloadDir, reports both as the real worker does, then hangs.
|
||||
import { spawn } from "node:child_process";
|
||||
import { writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { parentPort, workerData } from "node:worker_threads";
|
||||
|
||||
if (workerData.projectDir === "hang") {
|
||||
if (workerData.projectDir === "child") {
|
||||
const child = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: "ignore" });
|
||||
const output = join(workerData.downloadDir, "clip.webm.tmp-1-2");
|
||||
writeFileSync(output, "partial");
|
||||
writeFileSync(join(workerData.downloadDir, "child.pid"), String(child.pid));
|
||||
parentPort.postMessage({ type: "child", pid: child.pid, output });
|
||||
// A second child names a file outside the compile's folders, which the parent must leave alone.
|
||||
const other = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: "ignore" });
|
||||
writeFileSync(join(workerData.downloadDir, "other.pid"), String(other.pid));
|
||||
const outside = join(dirname(workerData.downloadDir), "outside.webm.tmp-1-2");
|
||||
parentPort.postMessage({ type: "child", pid: other.pid, output: outside });
|
||||
// Lets the message reach the parent before this thread stops answering.
|
||||
setTimeout(() => {
|
||||
for (;;);
|
||||
}, 50);
|
||||
} else if (workerData.projectDir === "hang") {
|
||||
for (;;);
|
||||
} else if (workerData.projectDir === "typed") {
|
||||
parentPort.postMessage({
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import {
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readdirSync,
|
||||
rmSync,
|
||||
truncateSync,
|
||||
writeFileSync,
|
||||
} from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { parseHTML } from "linkedom";
|
||||
@@ -68,6 +76,21 @@ function makeProject(): string {
|
||||
}
|
||||
|
||||
describe("buildAnimatedGifTranscodeArgs", () => {
|
||||
it("bounds the transcode inside ffmpeg itself, by CPU time and output size", () => {
|
||||
const args = buildAnimatedGifTranscodeArgs({
|
||||
inputPath: "/in/reaction.gif",
|
||||
outputPath: "/out/reaction.webm.tmp-1-2",
|
||||
loopIterations: 1_000,
|
||||
padSeconds: 3_600,
|
||||
});
|
||||
// -timelimit is a global option, so it has to come before the input to apply at all.
|
||||
expect(args.indexOf("-timelimit")).toBeGreaterThan(-1);
|
||||
expect(args.indexOf("-timelimit")).toBeLessThan(args.indexOf("-i"));
|
||||
expect(Number(args[args.indexOf("-timelimit") + 1])).toBe(3_600);
|
||||
expect(Number(args[args.indexOf("-fs") + 1])).toBe(1024 * 1024 * 1024);
|
||||
expect(args.indexOf("-fs")).toBeGreaterThan(args.indexOf("-i"));
|
||||
});
|
||||
|
||||
it("builds VP9 WebM args with alpha and finite-loop expansion", () => {
|
||||
const args = buildAnimatedGifTranscodeArgs({
|
||||
inputPath: "/in/reaction.gif",
|
||||
@@ -128,6 +151,52 @@ describe("prepareAnimatedGifInputs", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it("does not cache a transcode that ffmpeg cut off at its output size limit", async () => {
|
||||
const projectDir = makeProject();
|
||||
try {
|
||||
writeFileSync(join(projectDir, "sticker.gif"), gif([...frame(5), ...frame(15)], 0));
|
||||
const cacheDir = join(projectDir, "cache");
|
||||
await expect(
|
||||
prepareAnimatedGifInputs('<img data-start="0" data-duration="2" src="sticker.gif" />', {
|
||||
projectDir,
|
||||
downloadDir: projectDir,
|
||||
cacheDir,
|
||||
// Sparse, so the test writes nothing to disk.
|
||||
transcode: async (request) => {
|
||||
writeFileSync(request.outputPath, "");
|
||||
truncateSync(request.outputPath, 1024 * 1024 * 1024);
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow(/output size limit/);
|
||||
expect(existsSync(cacheDir) ? readdirSync(cacheDir) : []).toEqual([]);
|
||||
} finally {
|
||||
rmSync(projectDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("forwards the compile abort signal to the transcode", async () => {
|
||||
const projectDir = makeProject();
|
||||
try {
|
||||
writeFileSync(join(projectDir, "sticker.gif"), gif([...frame(5), ...frame(15)], 0));
|
||||
const controller = new AbortController();
|
||||
const calls: AnimatedGifTranscodeRequest[] = [];
|
||||
|
||||
await prepareAnimatedGifInputs('<img data-start="0" data-duration="2" src="sticker.gif" />', {
|
||||
projectDir,
|
||||
downloadDir: projectDir,
|
||||
signal: controller.signal,
|
||||
transcode: async (request) => {
|
||||
calls.push(request);
|
||||
writeFileSync(request.outputPath, "webm");
|
||||
},
|
||||
});
|
||||
|
||||
expect(calls[0]?.signal).toBe(controller.signal);
|
||||
} finally {
|
||||
rmSync(projectDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("rewrites animated GIF images to muted looped videos", async () => {
|
||||
const projectDir = makeProject();
|
||||
writeFileSync(join(projectDir, "sticker.gif"), gif([...frame(5), ...frame(15)], 0));
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// fallow-ignore-file complexity
|
||||
import { createHash } from "node:crypto";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, statSync } from "node:fs";
|
||||
import { dirname, isAbsolute, join, resolve } from "node:path";
|
||||
import { parseHTML } from "linkedom";
|
||||
@@ -38,6 +38,7 @@ export interface PrepareAnimatedGifInputsOptions {
|
||||
cacheDir?: string;
|
||||
sourceAssets?: Map<string, string>;
|
||||
timeoutMs?: number;
|
||||
signal?: AbortSignal;
|
||||
transcode?: (input: AnimatedGifTranscodeRequest) => Promise<void>;
|
||||
allowOutsideFiles?: boolean;
|
||||
}
|
||||
@@ -47,6 +48,7 @@ export interface AnimatedGifTranscodeRequest {
|
||||
outputPath: string;
|
||||
args: string[];
|
||||
timeoutMs?: number;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export interface PrepareAnimatedGifInputsResult {
|
||||
@@ -159,6 +161,8 @@ function resolveLoop(metadata: AnimatedGifMetadata, override: boolean | null): b
|
||||
*/
|
||||
const MAX_LOOP_ITERATIONS = 1_000;
|
||||
const MAX_PAD_SECONDS = 3_600;
|
||||
const FFMPEG_SELF_CPU_SECONDS_CAP = 3_600;
|
||||
const FFMPEG_SELF_OUTPUT_BYTES_CAP = 1024 * 1024 * 1024;
|
||||
|
||||
function resolveCompositionDurationSeconds(document: Document): number | null {
|
||||
let max: number | null = null;
|
||||
@@ -220,7 +224,13 @@ export function buildAnimatedGifTranscodeArgs(input: {
|
||||
loopIterations: number;
|
||||
padSeconds?: number;
|
||||
}): string[] {
|
||||
const args = ["-hide_banner", "-loglevel", "error"];
|
||||
const args = [
|
||||
"-hide_banner",
|
||||
"-loglevel",
|
||||
"error",
|
||||
"-timelimit",
|
||||
String(FFMPEG_SELF_CPU_SECONDS_CAP),
|
||||
];
|
||||
if (input.loopIterations > 1) {
|
||||
args.push("-stream_loop", String(input.loopIterations - 1));
|
||||
}
|
||||
@@ -250,6 +260,8 @@ export function buildAnimatedGifTranscodeArgs(input: {
|
||||
: []),
|
||||
// Explicit muxer: the transcode writes to a `.tmp-<pid>-<ts>` path whose
|
||||
// extension ffmpeg cannot infer the container from.
|
||||
"-fs",
|
||||
String(FFMPEG_SELF_OUTPUT_BYTES_CAP),
|
||||
"-f",
|
||||
"webm",
|
||||
"-y",
|
||||
@@ -258,10 +270,17 @@ export function buildAnimatedGifTranscodeArgs(input: {
|
||||
return args;
|
||||
}
|
||||
|
||||
function abortError(): Error {
|
||||
const error = new Error("Aborted");
|
||||
error.name = "AbortError";
|
||||
return error;
|
||||
}
|
||||
|
||||
async function runAnimatedGifTranscode(request: AnimatedGifTranscodeRequest): Promise<void> {
|
||||
const timeout = request.timeoutMs ?? 300_000;
|
||||
const result = await runFfmpeg(request.args, { timeout });
|
||||
const result = await runFfmpeg(request.args, { timeout, signal: request.signal });
|
||||
if (result.success) return;
|
||||
if (request.signal?.aborted) throw abortError();
|
||||
if (result.failureReason === "external_interruption") {
|
||||
throw encoderFailureError("Animated GIF transcode failed", {
|
||||
error: `exit ${result.exitCode}: ${result.stderr.slice(-500)}`,
|
||||
@@ -284,6 +303,7 @@ async function ensurePreparedWebm(input: {
|
||||
loopIterations: number;
|
||||
padSeconds: number;
|
||||
timeoutMs?: number;
|
||||
signal?: AbortSignal;
|
||||
transcode?: (request: AnimatedGifTranscodeRequest) => Promise<void>;
|
||||
}): Promise<void> {
|
||||
if (!existsSync(dirname(input.cachePath))) {
|
||||
@@ -294,7 +314,7 @@ async function ensurePreparedWebm(input: {
|
||||
}
|
||||
|
||||
if (!isUsableFile(input.cachePath)) {
|
||||
const tmpPath = `${input.cachePath}.tmp-${process.pid}-${Date.now()}`;
|
||||
const tmpPath = `${input.cachePath}.tmp-${process.pid}-${randomUUID()}`;
|
||||
const args = buildAnimatedGifTranscodeArgs({
|
||||
inputPath: input.sourcePath,
|
||||
outputPath: tmpPath,
|
||||
@@ -308,10 +328,14 @@ async function ensurePreparedWebm(input: {
|
||||
outputPath: tmpPath,
|
||||
args,
|
||||
timeoutMs: input.timeoutMs,
|
||||
signal: input.signal,
|
||||
});
|
||||
if (!isUsableFile(tmpPath)) {
|
||||
throw new Error("Animated GIF transcode produced an empty output");
|
||||
}
|
||||
if (statSync(tmpPath).size >= FFMPEG_SELF_OUTPUT_BYTES_CAP) {
|
||||
throw new Error("Animated GIF transcode reached its output size limit");
|
||||
}
|
||||
if (!isUsableFile(input.cachePath)) {
|
||||
renameWithRetry(tmpPath, input.cachePath);
|
||||
} else {
|
||||
@@ -428,6 +452,7 @@ export async function prepareAnimatedGifInputs(
|
||||
loopIterations,
|
||||
padSeconds,
|
||||
timeoutMs: options.timeoutMs,
|
||||
signal: options.signal,
|
||||
transcode: options.transcode,
|
||||
});
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { createServer, type Server } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
@@ -6,6 +7,7 @@ import { join, resolve } from "node:path";
|
||||
import { Worker } from "node:worker_threads";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { compileForRenderInWorker } from "./compileInWorker.js";
|
||||
import { scratchOutputOf } from "./compileScratch.js";
|
||||
import { compileForRender } from "./htmlCompiler.js";
|
||||
import { extractSafeRenderErrorMetadata } from "../server.js";
|
||||
|
||||
@@ -84,6 +86,50 @@ describe("compileForRenderInWorker", () => {
|
||||
expect(performance.now() - began).toBeLessThan(3_000);
|
||||
});
|
||||
|
||||
it("ends a stopped compile's child processes and removes their temp output, only inside its folders", async () => {
|
||||
const parent = mkdtempSync(join(tmpdir(), "hf-compile-child-"));
|
||||
cleanups.push(() => rmSync(parent, { recursive: true, force: true }));
|
||||
const dir = join(parent, "downloads");
|
||||
mkdirSync(dir);
|
||||
const outside = join(parent, "outside.webm.tmp-1-2");
|
||||
writeFileSync(outside, "not this compile's");
|
||||
const error = await compileForRenderInWorker(
|
||||
"child",
|
||||
"x.html",
|
||||
dir,
|
||||
{},
|
||||
{
|
||||
entry: FAKE,
|
||||
timeoutMs: 500,
|
||||
},
|
||||
).catch((e: unknown) => e);
|
||||
expect(extractSafeRenderErrorMetadata(error)?.errorCode).toBe("COMPILE_TIMEOUT");
|
||||
// The thread never hears the abort, so the parent ends its children itself once the thread is gone.
|
||||
// Under plain node the thread's teardown then waits on them; vitest's own worker doesn't, so a zombie counts as ended.
|
||||
const running = (pidFile: string) =>
|
||||
spawnSync("ps", ["-o", "stat=", "-p", readFileSync(join(dir, pidFile), "utf8")], {
|
||||
encoding: "utf8",
|
||||
})
|
||||
.stdout.trim()
|
||||
.replace(/^Z.*/, "");
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(running("child.pid")).toBe("");
|
||||
expect(running("other.pid")).toBe("");
|
||||
expect(existsSync(join(dir, "clip.webm.tmp-1-2"))).toBe(false);
|
||||
},
|
||||
{ timeout: 6_000, interval: 200 },
|
||||
);
|
||||
expect(existsSync(outside)).toBe(true);
|
||||
}, 15_000);
|
||||
|
||||
it("counts only an ffmpeg run's own temp file as its scratch output", () => {
|
||||
const tmp = "/dl/clip.webm.tmp-42-3f2a9c1e-0b7d-4e55-9a1f-2c6d8e4b7a10";
|
||||
expect(scratchOutputOf("/usr/bin/ffmpeg", ["-i", "in.gif", tmp])).toBe(tmp);
|
||||
expect(scratchOutputOf("/opt/ffmpeg/bin/ffprobe", ["-i", tmp])).toBeUndefined();
|
||||
expect(scratchOutputOf("ffmpeg", ["-i", "in.gif", "/a.tmp-1-2/finished.webm"])).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps a typed compile error's code, owner, retryability and metadata across the thread", async () => {
|
||||
const error = await compileForRenderInWorker("typed", "x.html", "d", {}, { entry: FAKE }).catch(
|
||||
(e: unknown) => e,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { existsSync, rmSync } from "node:fs";
|
||||
import { dirname, isAbsolute, join, relative, resolve as resolvePath } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { Worker } from "node:worker_threads";
|
||||
import {
|
||||
@@ -45,6 +45,27 @@ function compileTimeoutMs(): number {
|
||||
|
||||
let warnedMissingEntry = false;
|
||||
|
||||
const endOnProcessExit = new Set<() => void>();
|
||||
let processExitHooked = false;
|
||||
function onProcessExit(end: () => void): () => void {
|
||||
if (!processExitHooked) {
|
||||
processExitHooked = true;
|
||||
process.on("exit", () => {
|
||||
for (const each of endOnProcessExit) each();
|
||||
});
|
||||
}
|
||||
endOnProcessExit.add(end);
|
||||
return () => endOnProcessExit.delete(end);
|
||||
}
|
||||
|
||||
function tryQuietly(action: () => void): void {
|
||||
try {
|
||||
action();
|
||||
} catch {
|
||||
// Best effort: one child or file that can't be ended must not stop the rest.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The published build emits the compile worker beside this module. Bundles that inline the producer
|
||||
* (the CLI, Lambda, other servers built on it) don't, so they name it with `HF_COMPILE_WORKER_ENTRY`
|
||||
@@ -102,6 +123,28 @@ export async function compileForRenderInWorker(
|
||||
const thread = new Worker(entry, {
|
||||
workerData: { projectDir, htmlPath, downloadDir, options: cloneable },
|
||||
});
|
||||
const children = new Map<number, string | undefined>();
|
||||
const scratchRoots = [downloadDir, options.animatedGifCacheDir].flatMap((dir) =>
|
||||
dir ? [resolvePath(dir)] : [],
|
||||
);
|
||||
const isScratch = (path: string) =>
|
||||
scratchRoots.some((root) => {
|
||||
const rel = relative(root, resolvePath(path));
|
||||
return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
|
||||
});
|
||||
// Only while the thread lives: an exited child it hasn't reported is still its zombie, so the pid is not reused.
|
||||
const endChildren = (signal: boolean) => {
|
||||
for (const [pid, output] of children) {
|
||||
if (signal) tryQuietly(() => process.kill(pid, "SIGKILL"));
|
||||
if (output) tryQuietly(() => rmSync(output, { force: true }));
|
||||
}
|
||||
children.clear();
|
||||
};
|
||||
const offProcessExit = onProcessExit(() => endChildren(true));
|
||||
const endThread = () => {
|
||||
endChildren(true);
|
||||
void thread.terminate();
|
||||
};
|
||||
let settled = false;
|
||||
const settle = (finish: () => void) => {
|
||||
if (settled) return;
|
||||
@@ -112,7 +155,7 @@ export async function compileForRenderInWorker(
|
||||
};
|
||||
const stop = () => {
|
||||
thread.postMessage({ type: "abort" });
|
||||
setTimeout(() => void thread.terminate(), TERMINATE_GRACE_MS).unref();
|
||||
setTimeout(endThread, TERMINATE_GRACE_MS).unref();
|
||||
};
|
||||
const timer = setTimeout(() => {
|
||||
stop();
|
||||
@@ -127,7 +170,7 @@ export async function compileForRenderInWorker(
|
||||
// and ends after the grace.
|
||||
const retire = (graceMs: number) => {
|
||||
thread.unref();
|
||||
setTimeout(() => void thread.terminate(), graceMs).unref();
|
||||
setTimeout(endThread, graceMs).unref();
|
||||
};
|
||||
|
||||
thread.on(
|
||||
@@ -154,11 +197,22 @@ export async function compileForRenderInWorker(
|
||||
}
|
||||
},
|
||||
);
|
||||
thread.on(
|
||||
"message",
|
||||
({ type, pid, output }: { type: string; pid?: number; output?: string }) => {
|
||||
if (pid === undefined) return;
|
||||
if (type === "child") children.set(pid, output && isScratch(output) ? output : undefined);
|
||||
else if (type === "childExit") children.delete(pid);
|
||||
},
|
||||
);
|
||||
thread.on("error", (error) => settle(() => reject(error)));
|
||||
thread.on("exit", (code) =>
|
||||
thread.on("exit", (code) => {
|
||||
offProcessExit();
|
||||
// Its teardown has waited on its children, so their pids may be free; ffmpeg's own limits end any left running.
|
||||
endChildren(false);
|
||||
settle(() =>
|
||||
reject(new Error(`The compile worker exited with code ${code} before answering`)),
|
||||
),
|
||||
);
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { basename } from "node:path";
|
||||
|
||||
/** The temp file an ffmpeg run writes, when its last argument is one: what to remove if the run is cut off. */
|
||||
export function scratchOutputOf(spawnfile: string, args: readonly string[]): string | undefined {
|
||||
const last = args.at(-1);
|
||||
if (!/^ffmpeg(\.exe)?$/i.test(basename(spawnfile)) || !last) return undefined;
|
||||
return /\.tmp-\d+-[\w-]+$/.test(basename(last)) ? last : undefined;
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
// Compiles workerData's project on its own thread, so a page that makes the compile run long holds up
|
||||
// this thread only: the parent keeps answering /health and other requests, and can end it at a deadline.
|
||||
import { parentPort, workerData } from "node:worker_threads";
|
||||
import { onTrackedChildProcess } from "@hyperframes/engine";
|
||||
import { scratchOutputOf } from "./compileScratch.js";
|
||||
import { compileForRender, type CompileForRenderOptions } from "./htmlCompiler.js";
|
||||
import type { ProducerLogger } from "../logger.js";
|
||||
|
||||
@@ -41,6 +43,17 @@ parentPort?.on("message", (message: { type?: string }) => {
|
||||
});
|
||||
// Fire-and-forget advisories may outlive the compile; they must not keep the parent's port open.
|
||||
parentPort?.unref();
|
||||
// This thread's ffmpeg/ffprobe timers die with it, so the parent hears of each child and ends what is left.
|
||||
onTrackedChildProcess((proc) => {
|
||||
const { pid } = proc;
|
||||
if (pid === undefined) return;
|
||||
parentPort?.postMessage({
|
||||
type: "child",
|
||||
pid,
|
||||
output: scratchOutputOf(proc.spawnfile, proc.spawnargs),
|
||||
});
|
||||
proc.once("exit", () => parentPort?.postMessage({ type: "childExit", pid }));
|
||||
});
|
||||
|
||||
try {
|
||||
const compiled = await compileForRender(projectDir, htmlPath, downloadDir, {
|
||||
|
||||
@@ -141,6 +141,26 @@ describe("prepareHeifImageInputs", () => {
|
||||
expectUprightPhoto(prepared!.outputPath);
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"forwards the abort signal to the transcode",
|
||||
async () => {
|
||||
const d = project({ "photo.heic": readFileSync(FIXTURE) });
|
||||
const controller = new AbortController();
|
||||
const calls: HeifTranscodeRequest[] = [];
|
||||
|
||||
await prepareHeifImageInputs('<img src="photo.heic">', {
|
||||
...d,
|
||||
signal: controller.signal,
|
||||
transcode: async (request) => {
|
||||
calls.push(request);
|
||||
writeFileSync(request.outputPath, "jpg");
|
||||
},
|
||||
});
|
||||
|
||||
expect(calls[0]?.signal).toBe(controller.signal);
|
||||
},
|
||||
);
|
||||
|
||||
it("converts an inline data URL", async () => {
|
||||
const d = project({});
|
||||
const uri = `data:image/heic;base64,${readFileSync(FIXTURE).toString("base64")}`;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// fallow-ignore-file complexity
|
||||
// fallow-ignore-file unused-class-member
|
||||
import { createHash } from "node:crypto";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import {
|
||||
closeSync,
|
||||
copyFileSync,
|
||||
@@ -63,6 +63,15 @@ export class HeifToolUnavailableError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
function abortError(): Error {
|
||||
const error = new Error("Aborted");
|
||||
error.name = "AbortError";
|
||||
return error;
|
||||
}
|
||||
|
||||
const FFMPEG_SELF_CPU_SECONDS_CAP = 300;
|
||||
const FFMPEG_SELF_OUTPUT_BYTES_CAP = 256 * 1024 * 1024;
|
||||
|
||||
const TOOL_FAILURE_RE =
|
||||
/(?:ffmpeg|ffprobe) not found|ENOENT|Option not found|Unrecognized option|Unknown decoder|Decoder \S+ not found/i;
|
||||
|
||||
@@ -70,6 +79,7 @@ export interface HeifTranscodeRequest {
|
||||
inputPath: string;
|
||||
outputPath: string;
|
||||
timeoutMs?: number;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export interface PrepareHeifImageInputsOptions {
|
||||
@@ -80,6 +90,7 @@ export interface PrepareHeifImageInputsOptions {
|
||||
cacheDir?: string;
|
||||
sourceAssets?: Map<string, string>;
|
||||
timeoutMs?: number;
|
||||
signal?: AbortSignal;
|
||||
transcode?: (input: HeifTranscodeRequest) => Promise<void>;
|
||||
allowOutsideFiles?: boolean;
|
||||
/** Leaves an image whose conversion failed as authored and reports it, instead of throwing. */
|
||||
@@ -196,6 +207,8 @@ export async function convertHeifToJpeg(request: HeifTranscodeRequest): Promise<
|
||||
"-hide_banner",
|
||||
"-loglevel",
|
||||
"error",
|
||||
"-timelimit",
|
||||
String(FFMPEG_SELF_CPU_SECONDS_CAP),
|
||||
...urlInputArgs(request.inputPath),
|
||||
"-i",
|
||||
request.inputPath,
|
||||
@@ -204,14 +217,17 @@ export async function convertHeifToJpeg(request: HeifTranscodeRequest): Promise<
|
||||
"1",
|
||||
"-q:v",
|
||||
"2",
|
||||
"-fs",
|
||||
String(FFMPEG_SELF_OUTPUT_BYTES_CAP),
|
||||
"-f",
|
||||
"mjpeg",
|
||||
"-y",
|
||||
request.outputPath,
|
||||
],
|
||||
{ timeout: request.timeoutMs ?? DEFAULT_TIMEOUT_MS },
|
||||
{ timeout: request.timeoutMs ?? DEFAULT_TIMEOUT_MS, signal: request.signal },
|
||||
);
|
||||
if (!result.success) {
|
||||
if (request.signal?.aborted) throw abortError();
|
||||
throw (
|
||||
result.error ?? new Error(`ffmpeg exited ${result.exitCode}: ${result.stderr.slice(-300)}`)
|
||||
);
|
||||
@@ -269,7 +285,7 @@ async function ensurePreparedJpeg(
|
||||
mkdirSync(dirname(outputPath), { recursive: true });
|
||||
|
||||
if (!isUsableFile(cachePath)) {
|
||||
const tmpPath = `${cachePath}.tmp-${process.pid}-${Date.now()}`;
|
||||
const tmpPath = `${cachePath}.tmp-${process.pid}-${randomUUID()}`;
|
||||
const inlinePath = `${tmpPath}.heic`;
|
||||
const inputPath = source.path ?? inlinePath;
|
||||
try {
|
||||
@@ -278,8 +294,12 @@ async function ensurePreparedJpeg(
|
||||
inputPath,
|
||||
outputPath: tmpPath,
|
||||
timeoutMs: options.timeoutMs,
|
||||
signal: options.signal,
|
||||
});
|
||||
if (!isUsableFile(tmpPath)) throw new Error("conversion produced an empty file");
|
||||
if (statSync(tmpPath).size >= FFMPEG_SELF_OUTPUT_BYTES_CAP) {
|
||||
throw new Error("conversion reached its output size limit");
|
||||
}
|
||||
renameWithRetry(tmpPath, cachePath);
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : String(error);
|
||||
|
||||
@@ -2908,6 +2908,7 @@ async function compileWithAssets(
|
||||
cacheDir: options.animatedGifCacheDir,
|
||||
sourceAssets: remoteImageAssets,
|
||||
timeoutMs: options.ffmpegProcessTimeout,
|
||||
signal: options.abortSignal,
|
||||
allowOutsideFiles: assetRoot === undefined,
|
||||
});
|
||||
if (preparedHeifImages.length > 0) {
|
||||
@@ -2925,6 +2926,7 @@ async function compileWithAssets(
|
||||
cacheDir: options.animatedGifCacheDir,
|
||||
sourceAssets: gifSourceAssets,
|
||||
timeoutMs: options.ffmpegProcessTimeout,
|
||||
signal: options.abortSignal,
|
||||
allowOutsideFiles: assetRoot === undefined,
|
||||
});
|
||||
if (preparedGifs.length > 0) {
|
||||
|
||||
Reference in New Issue
Block a user