Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: cancel stalled source probes before encoding

Richie McIlroyde48abc5e5ad
diff --git a/apps/render-farm/src/worker.test.ts b/apps/render-farm/src/worker.test.ts
new file mode 100644
index 000000000..8038a359e
--- /dev/null
+++ b/apps/render-farm/src/worker.test.ts
@@ -0,0 +1,162 @@
+import { describe, expect, test } from "bun:test";
+import { randomUUID } from "node:crypto";
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import type { TranscodeTask, WorkItem } from "./protocol";
+import * as transcode from "./transcode";
+
+function harness(
+ options: { presignGate?: Promise<void>; probeStalls?: boolean } = {},
+) {
+ const spawned: string[] = [];
+ const killed: string[] = [];
+ const removed: string[] = [];
+ const intervals: (() => void)[] = [];
+ let uploads = 0;
+ const source = readFileSync(
+ new URL("./worker.ts", import.meta.url),
+ "utf8",
+ ).replace(/^import[\s\S]*?from "[^"]+";\n/gm, "");
+ const deps = {
+ randomUUID,
+ join,
+ ...transcode,
+ availableParallelism: () => 1,
+ hostname: () => "worker-test",
+ mkdirSync: () => {},
+ rmSync: (path: string) => removed.push(path),
+ mediaS3ConfigFromEnv: () => ({}),
+ S3: class {
+ async presignFresh() {
+ await options.presignGate;
+ return "https://media.test/source";
+ }
+ async uploadFile() {
+ uploads++;
+ return 42;
+ }
+ },
+ process: {
+ env: { RF_SLOTS: "0", RF_AUDIO_SLOTS: "0" },
+ on: () => {},
+ },
+ setInterval: (callback: () => void) => intervals.push(callback),
+ console: { log() {}, warn() {}, error() {} },
+ Bun: {
+ spawn: ([command]: string[]) => {
+ const name = command ?? "";
+ spawned.push(name);
+ const exit = Promise.withResolvers<number>();
+ let output: ReadableStreamDefaultController<Uint8Array>;
+ let exitCode: number | null = null;
+ const stdout = new ReadableStream<Uint8Array>({
+ start(controller) {
+ output = controller;
+ if (name !== "ffprobe" || options.probeStalls === false) {
+ controller.close();
+ exitCode = 0;
+ exit.resolve(0);
+ }
+ },
+ });
+ return {
+ stdout,
+ stderr: new Response("").body,
+ exited: exit.promise,
+ get exitCode() {
+ return exitCode;
+ },
+ kill(signal: string) {
+ killed.push(`${name}:${signal}`);
+ if (exitCode === null) {
+ exitCode = 137;
+ output.close();
+ exit.resolve(exitCode);
+ }
+ },
+ };
+ },
+ },
+ };
+ const compiled = new Bun.Transpiler({ loader: "ts" }).transformSync(source);
+ const worker = new Function(
+ ...Object.keys(deps),
+ `${compiled}\nreturn {runTranscode, cancel, busy, progress, transcoders};`,
+ )(...Object.values(deps)) as {
+ runTranscode: (task: TranscodeTask, slot: number) => Promise<number>;
+ cancel: (taskIds: string[]) => void;
+ busy: Map<number, WorkItem>;
+ progress: Map<number, { lastProgressAt: number }>;
+ transcoders: Map<number, unknown>;
+ };
+ return {
+ ...worker,
+ spawned,
+ killed,
+ removed,
+ intervals,
+ uploads: () => uploads,
+ };
+}
+
+const task: TranscodeTask = {
+ kind: "transcode",
+ taskId: "tc:test",
+ source: "source.webm",
+ output: "source.mp4",
+ keyframeSeconds: 1,
+};
+
+describe("transcode cancellation", () => {
+ test("cancelling a stalled probe kills it and prevents the encoder from starting", async () => {
+ const h = harness();
+ h.busy.set(0, task);
+ const pending = h.runTranscode(task, 0);
+ for (let i = 0; i < 20; i++) await Promise.resolve();
+ expect(h.spawned).toEqual(["ffprobe"]);
+ h.cancel([task.taskId]);
+ await expect(pending).rejects.toThrow("transcode cancelled");
+ expect(h.killed).toEqual(["ffprobe:SIGKILL"]);
+ expect(h.spawned).toEqual(["ffprobe"]);
+ expect(h.transcoders.size).toBe(0);
+ expect(h.progress.size).toBe(0);
+ expect(h.removed).toHaveLength(1);
+ expect(h.uploads()).toBe(0);
+ });
+
+ test("the watchdog releases a stalled probe without waiting for cancellation", async () => {
+ const h = harness();
+ const pending = h.runTranscode(task, 0);
+ for (let i = 0; i < 20; i++) await Promise.resolve();
+ const progress = h.progress.get(0);
+ if (!progress) throw new Error("missing progress");
+ progress.lastProgressAt = 0;
+ h.intervals[0]?.();
+ await expect(pending).rejects.toThrow("transcode cancelled");
+ expect(h.killed).toEqual(["ffprobe:SIGKILL"]);
+ expect(h.spawned).toEqual(["ffprobe"]);
+ expect(h.transcoders.size).toBe(0);
+ });
+
+ test("cancellation while obtaining credentials prevents a later probe", async () => {
+ const gate = Promise.withResolvers<void>();
+ const h = harness({ presignGate: gate.promise });
+ h.busy.set(0, task);
+ const pending = h.runTranscode(task, 0);
+ h.cancel([task.taskId]);
+ gate.resolve();
+ await expect(pending).rejects.toThrow("transcode cancelled");
+ expect(h.spawned).toEqual([]);
+ expect(h.transcoders.size).toBe(0);
+ });
+
+ test("an uncancelled source still encodes, uploads and releases its process", async () => {
+ const h = harness({ probeStalls: false });
+ expect(await h.runTranscode(task, 0)).toBe(42);
+ expect(h.spawned).toEqual(["ffprobe", "ffmpeg"]);
+ expect(h.killed).toEqual([]);
+ expect(h.uploads()).toBe(1);
+ expect(h.transcoders.size).toBe(0);
+ expect(h.progress.size).toBe(0);
+ });
+});
diff --git a/apps/render-farm/src/worker.ts b/apps/render-farm/src/worker.ts
index e0c7d2f88..84ac88a4b 100644
--- a/apps/render-farm/src/worker.ts
+++ b/apps/render-farm/src/worker.ts
@@ -115,8 +115,18 @@ function dropJobs(finished: string[]) {
}
const busy = new Map<number, WorkItem>();
-// Running ffmpeg transcodes, by slot, so cancels and the watchdog can stop them.
-const transcoders = new Map<number, Bun.Subprocess>();
+type TranscodeRun = {
+ controller: AbortController;
+ process?: Bun.Subprocess;
+};
+const transcoders = new Map<number, TranscodeRun>();
+
+function stopTranscode(slot: number) {
+ const run = transcoders.get(slot);
+ if (!run) return;
+ run.controller.abort(new Error("transcode cancelled"));
+ run.process?.kill("SIGKILL");
+}
const progress = new Map<
number,
{
@@ -676,17 +686,27 @@ async function runTranscode(task: TranscodeTask, slot: number) {
lastProgressAt: Date.now(),
};
progress.set(slot, entry);
+ const run: TranscodeRun = { controller: new AbortController() };
+ transcoders.set(slot, run);
try {
const output = join(dir, "output.mp4");
const input = await s3.presignFresh("GET", task.source, 6 * 3600);
+ run.controller.signal.throwIfAborted();
const probe = Bun.spawn(["ffprobe", ...probeArgs(input)], {
stdout: "pipe",
stderr: "ignore",
});
- const probed = await new Response(probe.stdout).text();
- // H.264 with frequent keyframes (Chrome, Edge and Safari recordings)
- // only needs its container rewritten; anything else is re-encoded.
+ run.process = probe;
+ const probeDecoder = new TextDecoder();
+ let probed = "";
+ for await (const bytes of probe.stdout) {
+ probed += probeDecoder.decode(bytes, { stream: true });
+ entry.lastProgressAt = Date.now();
+ }
+ probed += probeDecoder.decode();
const remux = (await probe.exited) === 0 && canRemux(probed);
+ run.controller.signal.throwIfAborted();
+ entry.lastProgressAt = Date.now();
console.log(`${task.taskId}: ${remux ? "remuxing" : "transcoding"}`);
const ffmpeg = Bun.spawn(
[
@@ -702,7 +722,7 @@ async function runTranscode(task: TranscodeTask, slot: number) {
],
{ stdout: "pipe", stderr: "pipe" },
);
- transcoders.set(slot, ffmpeg);
+ run.process = ffmpeg;
const stderr = new Response(ffmpeg.stderr).text();
const decoder = new TextDecoder();
let buffered = "";
@@ -719,6 +739,7 @@ async function runTranscode(task: TranscodeTask, slot: number) {
}
}
const code = await ffmpeg.exited;
+ run.controller.signal.throwIfAborted();
if (code !== 0) {
throw new Error(
`ffmpeg exited ${code}: ${(await stderr).trim().slice(-500)}`,
@@ -728,6 +749,10 @@ async function runTranscode(task: TranscodeTask, slot: number) {
ifNoneMatch: true,
});
} finally {
+ if (run.process?.exitCode === null) {
+ run.process.kill("SIGKILL");
+ await run.process.exited;
+ }
transcoders.delete(slot);
progress.delete(slot);
rmSync(dir, { recursive: true, force: true });
@@ -963,7 +988,7 @@ function cancel(taskIds: string[]) {
if (!taskIds.includes(task.taskId)) continue;
console.log(`cancelling ${task.taskId}`);
if (task.kind === "transcode") {
- transcoders.get(slot)?.kill("SIGKILL");
+ stopTranscode(slot);
continue;
}
// SIGKILL: a stopped or wedged engine never acts on SIGTERM and would
@@ -979,9 +1004,9 @@ setInterval(() => {
// Decoding a long source can start slowly; a minute without any
// output means a wedged ffmpeg.
if (now - entry.lastProgressAt >= Math.max(STALL_MS, 60_000)) {
- console.error(`${entry.taskId}: no progress, killing ffmpeg`);
+ console.error(`${entry.taskId}: no progress, stopping transcode`);
entry.lastProgressAt = now;
- transcoders.get(slot)?.kill("SIGKILL");
+ stopTranscode(slot);
}
continue;
}