Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(media): answer 503 when ffmpeg cannot be started
Yudhi Armyndharis1939cae96adf
diff --git a/src/modules/media/ffmpeg-run.spec.ts b/src/modules/media/ffmpeg-run.spec.tsindex 9a24a649c..257bf9cc7 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, killRunningConversions, probeFfmpeg, runFfmpeg } from './ffmpeg';+import { FfmpegConversionError, FfmpegSpawnError, killRunningConversions, probeFfmpeg, runFfmpeg } from './ffmpeg';// The real spawn, wrapped so a test can reach the child process it created.jest.mock('node:child_process', () => {@@ -231,7 +231,7 @@ esacit('says plainly when the binary cannot be executed at all', async () => {await expect(runFfmpeg(Buffer.from('input'), 'bin', 'ogg', [], options({ ffmpegPath: join(workDir, 'not-here') })),- ).rejects.toBeInstanceOf(FfmpegConversionError);+ ).rejects.toBeInstanceOf(FfmpegSpawnError);await expect(runFfmpeg(Buffer.from('input'), 'bin', 'ogg', [], options({ ffmpegPath: join(workDir, 'not-here') })),).rejects.toThrow(/Could not run ffmpeg/);diff --git a/src/modules/media/ffmpeg.ts b/src/modules/media/ffmpeg.tsindex a8c0f14da..f87ff4439 100644--- a/src/modules/media/ffmpeg.ts+++ b/src/modules/media/ffmpeg.ts@@ -15,6 +15,14 @@ export class FfmpegConversionError extends Error {}}+/** ffmpeg could not be started at all: a host fault (missing binary, EAGAIN, EMFILE), not the input's. */+export class FfmpegSpawnError extends FfmpegConversionError {+ constructor(message: string) {+ super(message);+ this.name = 'FfmpegSpawnError';+ }+}+export interface FfmpegRunOptions {/** Binary to execute. Resolved through PATH unless absolute. */ffmpegPath: string;@@ -266,7 +274,7 @@ function execute(args: string[], options: FfmpegRunOptions): Promise<void> {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)}`));+ reject(new FfmpegSpawnError(`Could not run ffmpeg: ${err instanceof Error ? err.message : String(err)}`));});child.on('close', code => {diff --git a/src/modules/media/media-conversion.service.spec.ts b/src/modules/media/media-conversion.service.spec.tsindex 4bf69153c..1335e331a 100644--- a/src/modules/media/media-conversion.service.spec.ts+++ b/src/modules/media/media-conversion.service.spec.ts@@ -292,6 +292,19 @@ describe('MediaConversionService', () => {await expect(service.convertToVoice(SESSION, { base64: 'AAAA' })).rejects.toThrow(/Invalid data found/);});+ // A spawn that fails (EAGAIN, EMFILE, a binary removed by an upgrade) is the host's fault, not the+ // caller's, so it answers the documented 503 and the binary is probed again on the next call.+ it('answers 503, not 400, when ffmpeg cannot be started, and probes again', async () => {+ runFfmpeg.mockRejectedValue(new ffmpeg.FfmpegSpawnError('Could not run ffmpeg: spawn ffmpeg EAGAIN'));+ const service = makeService(config());++ await expect(service.convertToVoice(SESSION, { base64: 'AAAA' })).rejects.toBeInstanceOf(+ ServiceUnavailableException,+ );+ await service.isAvailable();+ expect(probeFfmpeg).toHaveBeenCalledTimes(2);+ });+// A programming error must not be relabelled as the caller's fault.it('lets an unexpected error through rather than reporting it as a bad request', async () => {runFfmpeg.mockRejectedValue(new TypeError('boom'));diff --git a/src/modules/media/media-conversion.service.ts b/src/modules/media/media-conversion.service.tsindex 9cb383f64..677c2f7a8 100644--- a/src/modules/media/media-conversion.service.ts+++ b/src/modules/media/media-conversion.service.ts@@ -10,7 +10,14 @@ import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';import { SsrfBlockedError, SSRF_BLOCKED_CLIENT_MESSAGE } from '../../common/security/ssrf-guard';import { ConcurrencyLimiter } from '../../common/utils/concurrency-limiter';import { assertBase64WithinMediaCap, stripBase64DataUri } from '../message/media-cap.util';-import { FfmpegConversionError, probeFfmpeg, runFfmpeg, videoEncodeArgs, voiceEncodeArgs } from './ffmpeg';+import {+ FfmpegConversionError,+ FfmpegSpawnError,+ probeFfmpeg,+ runFfmpeg,+ videoEncodeArgs,+ voiceEncodeArgs,+} from './ffmpeg';import type { ConvertMediaDto } from './dto/convert-media.dto';/** What a conversion produced, in the same url-or-base64 vocabulary the send endpoints speak. */@@ -96,6 +103,15 @@ export class MediaConversionService {if (error instanceof Error && error.message === 'ConcurrencyLimiter queue full') {throw new ServiceUnavailableException('Media conversion is busy — retry shortly');}+ if (error instanceof FfmpegSpawnError) {+ // The host could not start ffmpeg (a binary removed since the probe, or a process, memory or+ // descriptor limit), which is no fault of the input. Probe again on the next call.+ this.binaryAvailable = undefined;+ this.logger.warn('Media conversion could not start ffmpeg', { reason: error.message });+ throw new ServiceUnavailableException(+ 'Media conversion could not start the ffmpeg binary. Retry shortly, or check FFMPEG_PATH.',+ );+ }if (error instanceof FfmpegConversionError) {// ffmpeg's stderr is about the caller's own bytes, so returning it is what makes a rejection// actionable. It never names a path the caller did not supply: the only paths in the command