Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(media): kill in-flight ffmpeg runs when the gateway exits
Yudhi Armyndharise9165c547634
diff --git a/src/modules/media/ffmpeg-run.spec.ts b/src/modules/media/ffmpeg-run.spec.tsindex 6af591880..b09e4589f 100644--- a/src/modules/media/ffmpeg-run.spec.ts+++ b/src/modules/media/ffmpeg-run.spec.ts@@ -2,7 +2,7 @@ import { spawn, type ChildProcess } from 'node:child_process';import { chmod, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';-import { FfmpegConversionError, probeFfmpeg, runFfmpeg } from './ffmpeg';+import { FfmpegConversionError, killRunningConversions, probeFfmpeg, runFfmpeg } from './ffmpeg';// The real spawn, wrapped so a test can reach the child process it created.jest.mock('node:child_process', () => {@@ -157,6 +157,38 @@ esac}}, 15_000);+ // Each run sits in its own process group, so a signal to the gateway's group never reaches it and its+ // timeout dies with the gateway. Whatever is still running has to be killed on the way out.+ it('kills every running conversion group when the gateway exits', async () => {+ expect(process.listeners('exit')).toContain(killRunningConversions);+ const pidFile = `${stubPath}.pid`;+ await rm(pidFile, { force: true });+ const run = runFfmpeg(Buffer.from('input'), 'bin', 'ogg', mode('orphan'), options({ timeoutMs: 10_000 }));+ const settled = run.catch((error: unknown) => error);++ let grandchild = 0;+ for (let i = 0; i < 40 && !grandchild; i++) {+ await new Promise(r => setTimeout(r, 50));+ grandchild = Number((await readFile(pidFile, 'utf8').catch(() => '')).trim());+ }+ const alive = (): boolean => {+ try {+ process.kill(grandchild, 0);+ return true;+ } catch {+ return false;+ }+ };+ try {+ killRunningConversions();+ expect(await settled).toBeInstanceOf(FfmpegConversionError);+ for (let i = 0; i < 40 && alive(); i++) await new Promise(r => setTimeout(r, 50));+ expect(alive()).toBe(false);+ } finally {+ if (alive()) process.kill(grandchild, 'SIGKILL');+ }+ }, 15_000);+// Transcoding can inflate as well as shrink, so the output needs a ceiling of its own.it('refuses output above the cap, and says what it measured', async () => {await expect(diff --git a/src/modules/media/ffmpeg.ts b/src/modules/media/ffmpeg.tsindex 080a2494d..88a2f6e23 100644--- a/src/modules/media/ffmpeg.ts+++ b/src/modules/media/ffmpeg.ts@@ -190,6 +190,27 @@ export async function runFfmpeg(}}+/** Process groups of the ffmpeg runs still in flight, so they can be killed when the gateway exits. */+const runningGroups = new Set<number>();++/**+ * SIGKILL every ffmpeg process group still running. Each run is detached into its own group, so a+ * Ctrl-C or a signal to the gateway's group no longer reaches it, and its timeout dies with this+ * process. Registered on `exit`, which every shutdown path reaches; `process.kill` is synchronous, so+ * it still runs there.+ */+export function killRunningConversions(): void {+ for (const pid of runningGroups) {+ try {+ process.kill(-pid, 'SIGKILL');+ } catch {+ // Already gone.+ }+ }+ runningGroups.clear();+}+process.on('exit', killRunningConversions);+/** Spawn ffmpeg and resolve when it exits 0, else reject with whatever it wrote to stderr. */function execute(args: string[], options: FfmpegRunOptions): Promise<void> {return new Promise((resolve, reject) => {@@ -198,6 +219,8 @@ function execute(args: string[], options: FfmpegRunOptions): Promise<void> {// `detached` puts the child at the head of its own process group, so the timeout can kill// everything under it (see below).const child = spawn(options.ffmpegPath, args, { stdio: ['ignore', 'ignore', 'pipe'], detached: true });+ const pid = child.pid;+ if (pid !== undefined) runningGroups.add(pid);let stderr = '';let timedOut = false;@@ -223,6 +246,7 @@ function execute(args: string[], options: FfmpegRunOptions): Promise<void> {// wrapper script) can still hold the inherited stderr, and the open pipe would keep this// process alive until that descendant exits.child.stderr.destroy();+ if (pid !== undefined) runningGroups.delete(pid);// Reject as soon as the signal is sent rather than waiting for `close`. `close` fires when the// stdio pipes close, not when the process dies, so anything still holding the inherited stderr// keeps it pending — which would leave the timeout bounding nothing at all.@@ -231,12 +255,14 @@ function execute(args: string[], options: FfmpegRunOptions): Promise<void> {child.on('error', err => {clearTimeout(timer);+ if (pid !== undefined) runningGroups.delete(pid);// Spawn itself failed — almost always a missing binary, which is worth saying plainly.reject(new FfmpegConversionError(`Could not run ffmpeg: ${err instanceof Error ? err.message : String(err)}`));});child.on('close', code => {clearTimeout(timer);+ if (pid !== undefined) runningGroups.delete(pid);// Already rejected by the timer; a late close has nothing left to report.if (timedOut) return;if (code !== 0) {