Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(media): stop queued conversions once shutdown starts
Yudhi Armyndharis153861870df1
diff --git a/src/modules/media/ffmpeg.ts b/src/modules/media/ffmpeg.tsindex 3ab4c175a..8f367e824 100644--- a/src/modules/media/ffmpeg.ts+++ b/src/modules/media/ffmpeg.ts@@ -30,6 +30,8 @@ export interface FfmpegRunOptions {timeoutMs: number;/** Ceiling on the produced bytes. */maxOutputBytes: number;+ /** Cancellation checked immediately before a process can be started. */+ signal?: AbortSignal;}/**@@ -266,6 +268,7 @@ function execute(args: string[], options: FfmpegRunOptions): Promise<void> {// filename with a space or a quote is data rather than syntax.// `detached` puts the child at the head of its own process group, so the timeout can kill// everything under it (see below).+ options.signal?.throwIfAborted();const child = spawn(options.ffmpegPath, args, {stdio: ['ignore', 'ignore', 'pipe'],detached: true,diff --git a/src/modules/media/media-conversion.service.ts b/src/modules/media/media-conversion.service.tsindex 5dde475bf..66aa6f923 100644--- a/src/modules/media/media-conversion.service.ts+++ b/src/modules/media/media-conversion.service.ts@@ -46,6 +46,7 @@ export class MediaConversionService implements OnApplicationShutdown {* request holds only its own body, and at most the cap's worth of inputs sit in heap at once.*/private readonly ffmpegGate: ConcurrencyLimiter;+ private readonly shutdown = new AbortController();constructor(private readonly configService: ConfigService,@@ -63,6 +64,8 @@ export class MediaConversionService implements OnApplicationShutdown {* on that path and on `app.close()`.*/onApplicationShutdown(): void {+ this.shutdown.abort();+ this.ffmpegGate.close();killRunningConversions();}@@ -85,8 +88,10 @@ export class MediaConversionService implements OnApplicationShutdown {/** Whether conversion is both switched on and actually runnable on this host. */async isAvailable(): Promise<boolean> {- if (!this.configService.get<boolean>('mediaConversion.enabled', false)) return false;- return this.probeOnce();+ if (this.shutdown.signal.aborted || !this.configService.get<boolean>('mediaConversion.enabled', false))+ return false;+ const available = await this.probeOnce();+ return available && !this.shutdown.signal.aborted;}private async convert(@@ -96,6 +101,7 @@ export class MediaConversionService implements OnApplicationShutdown {encodeArgs: string[],outputMimetype: string,): Promise<ConvertedMedia> {+ this.assertRunning();await this.assertAvailable();try {@@ -103,8 +109,11 @@ export class MediaConversionService implements OnApplicationShutdown {// base64 body, held for each request that had not yet reached a slot, would stack 50 MiB a request// in heap while the gate answers 503 only after the downloads finished.const { input, output } = await this.ffmpegGate.run(async () => {+ this.assertRunning();const loaded = await this.resolveInput(sessionId, dto);+ this.assertRunning();const converted = await runFfmpeg(loaded, 'bin', outputExtension, encodeArgs, {+ signal: this.shutdown.signal,ffmpegPath: this.configService.get<string>('mediaConversion.ffmpegPath', 'ffmpeg'),timeoutMs: this.configService.get<number>('mediaConversion.timeoutMs', 60_000),maxOutputBytes: this.configService.get<number>('mediaConversion.maxOutputBytes', 50 * 1024 * 1024),@@ -114,6 +123,7 @@ export class MediaConversionService implements OnApplicationShutdown {this.logger.log('Media converted', { inputBytes: input.length, outputBytes: output.length, outputMimetype });return { base64: output.toString('base64'), mimetype: outputMimetype, bytes: output.length };} catch (error) {+ this.assertRunning();if (error instanceof Error && error.message === 'ConcurrencyLimiter queue full') {throw new ServiceUnavailableException('Media conversion is busy — retry shortly');}@@ -195,6 +205,12 @@ export class MediaConversionService implements OnApplicationShutdown {throw new BadRequestException('Either url or base64 must be provided');}+ private assertRunning(): void {+ if (this.shutdown.signal.aborted) {+ throw new ServiceUnavailableException('Media conversion is shutting down');+ }+ }+private async assertAvailable(): Promise<void> {if (!this.configService.get<boolean>('mediaConversion.enabled', false)) {throw new ServiceUnavailableException(diff --git a/src/modules/media/media-shutdown.spec.ts b/src/modules/media/media-shutdown.spec.tsnew file mode 100644index 000000000..eb1c08612--- /dev/null+++ b/src/modules/media/media-shutdown.spec.ts@@ -0,0 +1,119 @@+import childProcess from 'node:child_process';+import files from 'node:fs/promises';+import { ConfigService } from '@nestjs/config';+import { Repository } from 'typeorm';+import { MediaConversionService } from './media-conversion.service';+import * as ffmpeg from './ffmpeg';+import * as remoteMedia from '../../common/media/load-remote-media';+import { EngineRegistry } from '../../engine/engine-registry.service';+import { Session } from '../session/entities/session.entity';++const deferred = <T>() => {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>(done => {+ resolve = done;+ });+ return { promise, resolve };+};+const tick = () => new Promise<void>(done => setImmediate(done));++describe('media conversion shutdown', () => {+ const input = Buffer.from('tiny');+ let service: MediaConversionService;+ let run: jest.SpyInstance;+ let probe: jest.SpyInstance;++ beforeEach(() => {+ probe = jest.spyOn(ffmpeg, 'probeFfmpeg').mockResolvedValue(true);+ run = jest.spyOn(ffmpeg, 'runFfmpeg').mockResolvedValue(input);+ jest.spyOn(ffmpeg, 'killRunningConversions').mockImplementation(() => undefined);+ const config = {+ get: (key: string, fallback: unknown) =>+ key === 'mediaConversion.enabled' ? true : key === 'mediaConversion.concurrency' ? 1 : fallback,+ };+ service = new MediaConversionService(config as ConfigService, new EngineRegistry(), {+ findOne: jest.fn().mockResolvedValue(null),+ } as unknown as Repository<Session>);+ });+ afterEach(() => jest.restoreAllMocks());++ for (const method of ['convertToVoice', 'convertToVideo'] as const) {+ it(`${method} rejects parked work without invoking another runner`, async () => {+ const active = deferred<Buffer>();+ run.mockImplementationOnce(() => active.promise);+ const first = service[method]('session', { base64: input.toString('base64') });+ const second = service[method]('session', { base64: input.toString('base64') });+ const rejected = second.catch(error => error as { status: number });+ await tick();+ expect(run).toHaveBeenCalledTimes(1);+ service.onApplicationShutdown();+ expect(await rejected).toMatchObject({ status: 503 });+ active.resolve(input);+ await first;+ expect(run).toHaveBeenCalledTimes(1);+ await expect(service[method]('session', { base64: input.toString('base64') })).rejects.toMatchObject({+ status: 503,+ });+ });++ it(`${method} refuses an input that finishes loading after shutdown`, async () => {+ const loaded = deferred<{ data: Buffer; mimetype: string }>();+ const load = jest.spyOn(remoteMedia, 'loadRemoteMediaBuffer').mockReturnValue(loaded.promise);+ const pending = service[method]('session', { url: 'https://media.invalid/tiny.wav' });+ const rejected = pending.catch(error => error as { status: number });+ await tick();+ expect(load).toHaveBeenCalledTimes(1);+ service.onApplicationShutdown();+ loaded.resolve({ data: input, mimetype: 'audio/wav' });+ expect(await rejected).toMatchObject({ status: 503 });+ expect(run).not.toHaveBeenCalled();+ });++ it(`${method} refuses a successful availability probe that settles after shutdown`, async () => {+ const ready = deferred<boolean>();+ probe.mockReturnValue(ready.promise);+ const pending = service[method]('session', { base64: input.toString('base64') });+ const rejected = pending.catch(error => error as { status: number });+ service.onApplicationShutdown();+ ready.resolve(true);+ expect(await rejected).toMatchObject({ status: 503 });+ expect(run).not.toHaveBeenCalled();+ });+ }++ it('reports unavailable when the probe succeeds after shutdown', async () => {+ const ready = deferred<boolean>();+ probe.mockReturnValue(ready.promise);+ const pending = service.isAvailable();+ service.onApplicationShutdown();+ ready.resolve(true);+ expect(await pending).toBe(false);+ expect(await service.isAvailable()).toBe(false);+ expect(probe).toHaveBeenCalledTimes(1);+ });+});++describe('conversion process cancellation', () => {+ afterEach(() => jest.restoreAllMocks());++ it('checks cancellation after input preparation and before spawning', async () => {+ const cancellation = new AbortController();+ const write = files.writeFile;+ jest.spyOn(files, 'writeFile').mockImplementation(async (...args) => {+ await write(...args);+ cancellation.abort();+ });+ const spawn = jest.spyOn(childProcess, 'spawn').mockImplementation(() => {+ throw new Error('A cancelled conversion must not spawn');+ });+ await expect(+ ffmpeg.runFfmpeg(Buffer.from('tiny'), 'bin', 'raw', [], {+ signal: cancellation.signal,+ ffmpegPath: 'unused',+ timeoutMs: 1000,+ maxOutputBytes: 1024,+ }),+ ).rejects.toMatchObject({ name: 'AbortError' });+ expect(spawn).not.toHaveBeenCalled();+ });+});