Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(media): 404 for a status media miss on S3, and bound concurrent ffmpeg conversions

Yudhi Armyndharis0538e04f39be
diff --git a/.env.example b/.env.example
index f36dbc9d2..f5afd9a92 100644
--- a/.env.example
+++ b/.env.example
@@ -408,6 +408,8 @@ WEBHOOK_SSRF_PROTECT=true
# FFMPEG_PATH=ffmpeg # absolute path, for a binary outside PATH
# MEDIA_CONVERSION_TIMEOUT_MS=60000 # kill one conversion after this long (default 60s)
# MEDIA_CONVERSION_MAX_OUTPUT_BYTES=52428800 # cap the CONVERTED bytes (default 50 MiB)
+# MEDIA_CONVERSION_CONCURRENCY=2 # max concurrent ffmpeg processes; a short queue
+# # absorbs bursts, beyond it the endpoint answers 503
# Aggregate base64 budget for media inlined by ONE GET .../messages/:chatId/history?includeMedia=true
# call. Once the running total crosses it, remaining media messages return the declared-only `omitted`
# marker instead of a download, so a media-heavy history can't stack ~100 × the per-message cap into a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8f3b550b1..a1b02a7a7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -35,6 +35,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- A media-storage root the app cannot write to is caught at boot with a clear error, instead of failing on the first write (#1066).
- The bundled `docker-compose.yml` now forwards the `SEND_PACING_*`, `MEDIA_CONVERSION_*`/`FFMPEG_PATH` and session-ownership (`NODE_ID`, `NODE_URL`, lease/sweep) variables — previously these features could not be enabled from `.env` in a compose deployment at all.
- The four label write tools (`LabelUpsert`, `LabelDelete`, `LabelAddToChat`, `LabelRemoveFromChat`) answered `Internal error` over MCP even though the write had succeeded on WhatsApp, prompting agents to retry a completed operation; they now return `{ success: true }`.
+- Fetching a status's media that S3 retention already removed answers 404 instead of 500 (the local-storage miss already did), and server-side media conversion is bounded to `MEDIA_CONVERSION_CONCURRENCY` (default 2) concurrent `ffmpeg` processes with a short queue — saturation answers 503 instead of stacking processes.
- **Baileys message-action targeting:** star/pin/unpin/react/delete now verify the stored message belongs to the requested chat (a mismatched pair answered success while writing under the wrong conversation), pin/unpin/react/delete resolve LID-migrated contacts like every other send, and tagging/untagging a chat's label folds the neutral id to the engine form so the write lands on the real chat instead of a phantom index.
- **whatsapp-web.js raw-id extraction hardening:** listing a label's chats no longer 500s when a labelled chat was deleted, and the channel list, channel creation and group-invite preview now read the `$1` fallback for the WA Web property rename — previously a renamed build returned channel ids as the literal string `"undefined"` and turned every valid invite preview into a false 404.
- **Baileys refusals now answer their documented statuses instead of 500:** an invalid/expired group invite previews as 404, admin-refused group writes (subject, description, announce/locked, picture, member-add mode) and refused channel writes (create/delete/mute) answer 403 — matching the whatsapp-web.js engine. Transport failures still propagate unchanged.
diff --git a/docker-compose.yml b/docker-compose.yml
index 9d84c3003..28a5ec925 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -201,6 +201,7 @@ services:
- FFMPEG_PATH=${FFMPEG_PATH:-}
- MEDIA_CONVERSION_TIMEOUT_MS=${MEDIA_CONVERSION_TIMEOUT_MS:-}
- MEDIA_CONVERSION_MAX_OUTPUT_BYTES=${MEDIA_CONVERSION_MAX_OUTPUT_BYTES:-}
+ - MEDIA_CONVERSION_CONCURRENCY=${MEDIA_CONVERSION_CONCURRENCY:-}
# Redis. Blank-forwarded (see Database note) so a dashboard enable/disable applies; a real host
# value pins.
- REDIS_ENABLED=${REDIS_ENABLED:-}
diff --git a/src/common/storage/storage.service.ts b/src/common/storage/storage.service.ts
index 9a354b111..617379e59 100644
--- a/src/common/storage/storage.service.ts
+++ b/src/common/storage/storage.service.ts
@@ -28,6 +28,22 @@ interface S3Config {
/** How often an S3-configured service re-probes a bucket that was unreachable at boot. */
export const DEFAULT_S3_REPROBE_INTERVAL_MS = 60_000;
+/**
+ * True when a storage read failed because the object is simply not there.
+ *
+ * Both backends must be covered, and they report it differently: the local backend raises a POSIX
+ * `ENOENT` (a `.code`), while S3 raises `NoSuchKey`/`NotFound`, which carries a `.name` and no
+ * `.code` at all — `getS3File` below rethrows that original error when the local read-through also
+ * misses. Checking only `.code` turns a missing S3 object into a 500 on the one backend where
+ * retention and bucket lifecycle rules make a miss most likely.
+ */
+export function isMissingObjectError(error: unknown): boolean {
+ const e = error as { code?: string; name?: string; $metadata?: { httpStatusCode?: number } };
+ return (
+ e?.code === 'ENOENT' || e?.name === 'NoSuchKey' || e?.name === 'NotFound' || e?.$metadata?.httpStatusCode === 404
+ );
+}
+
function positiveIntFromEnv(name: string, fallback: number): number {
const parsed = Number.parseInt(process.env[name] ?? '', 10);
return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
diff --git a/src/config/configuration.ts b/src/config/configuration.ts
index 9272ebaa9..5b54d32fe 100644
--- a/src/config/configuration.ts
+++ b/src/config/configuration.ts
@@ -460,6 +460,14 @@ export default () => ({
const n = parseInt(process.env.MEDIA_CONVERSION_MAX_OUTPUT_BYTES ?? '', 10);
return Number.isFinite(n) && n > 0 ? n : 50 * 1024 * 1024;
})(),
+ // At most this many ffmpeg processes at once (default 2). Each conversion spawns an external
+ // process and holds its input in heap; without a bound, requests inside the rate-limit window
+ // can stack processes for as long as each one runs. A short queue absorbs bursts; beyond it
+ // the endpoint answers 503 rather than piling on.
+ concurrency: (() => {
+ const n = parseInt(process.env.MEDIA_CONVERSION_CONCURRENCY ?? '', 10);
+ return Number.isFinite(n) && n > 0 ? n : 2;
+ })(),
},
// Message-template rendering
diff --git a/src/config/env-precedence.ts b/src/config/env-precedence.ts
index baaa534bf..13eb3a3f0 100644
--- a/src/config/env-precedence.ts
+++ b/src/config/env-precedence.ts
@@ -63,6 +63,7 @@ export const BLANK_SHADOWED_ENV_KEYS: string[] = [
'FFMPEG_PATH',
'MEDIA_CONVERSION_TIMEOUT_MS',
'MEDIA_CONVERSION_MAX_OUTPUT_BYTES',
+ 'MEDIA_CONVERSION_CONCURRENCY',
// Session ownership / multi-node routing (docs/13). Blank-forwarded so the single-node default
// stays untouched while .env / data/.env.generated can supply real values.
'NODE_ID',
diff --git a/src/modules/media/media-conversion.service.spec.ts b/src/modules/media/media-conversion.service.spec.ts
index fa4b5b145..08f23205d 100644
--- a/src/modules/media/media-conversion.service.spec.ts
+++ b/src/modules/media/media-conversion.service.spec.ts
@@ -156,4 +156,34 @@ describe('MediaConversionService', () => {
await expect(service.convertToVoice({ base64: 'AAAA' })).rejects.toBeInstanceOf(TypeError);
});
});
+
+ describe('concurrency gate', () => {
+ // The rate limiter caps admission per second, not how many long-running ffmpeg processes stack
+ // up while each runs toward its timeout — that bound lives here.
+ it('bounds concurrent ffmpeg runs and answers 503 past the queue instead of stacking processes', async () => {
+ // concurrency 1 → queue depth 4: five simultaneous requests fill the gate, the sixth is refused.
+ const service = new MediaConversionService(config({ 'mediaConversion.concurrency': 1 }));
+ let release!: () => void;
+ runFfmpeg.mockImplementation(
+ () =>
+ new Promise<Buffer>(resolve => {
+ release = () => resolve(Buffer.from('x'));
+ }),
+ );
+
+ const inflight = Array.from({ length: 5 }, () => service.convertToVoice({ base64: 'AAAA' }));
+ await new Promise(resolve => setImmediate(resolve));
+ expect(runFfmpeg).toHaveBeenCalledTimes(1);
+
+ await expect(service.convertToVoice({ base64: 'AAAA' })).rejects.toBeInstanceOf(ServiceUnavailableException);
+
+ // Drain: release each run in turn so every parked task completes and nothing leaks.
+ for (let i = 0; i < 5; i++) {
+ release();
+ await new Promise(resolve => setImmediate(resolve));
+ }
+ await Promise.all(inflight);
+ expect(runFfmpeg).toHaveBeenCalledTimes(5);
+ });
+ });
});
diff --git a/src/modules/media/media-conversion.service.ts b/src/modules/media/media-conversion.service.ts
index 036884ae9..adb972364 100644
--- a/src/modules/media/media-conversion.service.ts
+++ b/src/modules/media/media-conversion.service.ts
@@ -2,6 +2,7 @@ import { BadRequestException, Injectable, ServiceUnavailableException } from '@n
import { ConfigService } from '@nestjs/config';
import { createLogger } from '../../common/services/logger.service';
import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';
+import { ConcurrencyLimiter } from '../../common/utils/concurrency-limiter';
import { assertBase64WithinMediaCap, stripBase64DataUri } from '../message/media-cap.util';
import { FfmpegConversionError, probeFfmpeg, runFfmpeg, videoEncodeArgs, voiceEncodeArgs } from './ffmpeg';
import type { ConvertMediaDto } from './dto/convert-media.dto';
@@ -21,8 +22,18 @@ export class MediaConversionService {
private readonly logger = createLogger('MediaConversionService');
/** Result of the binary probe. Cached because it cannot change without a restart. */
private binaryAvailable?: Promise<boolean>;
+ /**
+ * Bounds concurrent ffmpeg processes (the rate limiter caps admission per second, not how many
+ * long-running processes stack up while each runs toward its timeout). Queue depth is a small
+ * multiple of the cap: each parked task holds its input buffer in heap, so anything beyond it
+ * answers 503 instead of accumulating.
+ */
+ private readonly ffmpegGate: ConcurrencyLimiter;
- constructor(private readonly configService: ConfigService) {}
+ constructor(private readonly configService: ConfigService) {
+ const concurrency = this.configService.get<number>('mediaConversion.concurrency', 2);
+ this.ffmpegGate = new ConcurrencyLimiter(concurrency, concurrency * 4);
+ }
/**
* Convert to a WhatsApp voice note: Ogg/Opus, which is what produces a playable mic bubble.
@@ -57,14 +68,19 @@ export class MediaConversionService {
const input = await this.resolveInput(dto);
try {
- const output = await runFfmpeg(input, 'bin', outputExtension, encodeArgs, {
- 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),
- });
+ const output = await this.ffmpegGate.run(() =>
+ runFfmpeg(input, 'bin', outputExtension, encodeArgs, {
+ 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),
+ }),
+ );
this.logger.log('Media converted', { inputBytes: input.length, outputBytes: output.length, outputMimetype });
return { base64: output.toString('base64'), mimetype: outputMimetype, bytes: output.length };
} catch (error) {
+ if (error instanceof Error && error.message === 'ConcurrencyLimiter queue full') {
+ throw new ServiceUnavailableException('Media conversion is busy — retry shortly');
+ }
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
diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.ts
index ba211d5f9..87b644af8 100644
--- a/src/modules/message/message.service.ts
+++ b/src/modules/message/message.service.ts
@@ -22,7 +22,7 @@ import { resolveFeatureFlags } from '../../config/feature-flags';
import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';
import { ChatMediaArchiveService } from '../chat-media/chat-media-archive.service';
-import { StorageService } from '../../common/storage/storage.service';
+import { StorageService, isMissingObjectError } from '../../common/storage/storage.service';
export interface GetMessagesOptions {
chatId?: string;
@@ -51,22 +51,6 @@ function inertMimetype(mimetype: string): string {
return INERT_MEDIA_MIMETYPE.test(mimetype) ? mimetype : 'application/octet-stream';
}
-/**
- * True when a storage read failed because the object is simply not there.
- *
- * Both backends must be covered, and they report it differently: the local backend raises a POSIX
- * `ENOENT` (a `.code`), while S3 raises `NoSuchKey`/`NotFound`, which carries a `.name` and no
- * `.code` at all — `getS3File` rethrows that original error when the local read-through also misses
- * (storage.service.ts:448-459). Checking only `.code` therefore turned a missing S3 object into a
- * 500 on the one backend where retention and bucket lifecycle rules make it most likely.
- */
-function isMissingObjectError(error: unknown): boolean {
- const e = error as { code?: string; name?: string; $metadata?: { httpStatusCode?: number } };
- return (
- e?.code === 'ENOENT' || e?.name === 'NoSuchKey' || e?.name === 'NotFound' || e?.$metadata?.httpStatusCode === 404
- );
-}
-
/**
* Outbound sends are executed directly against the WhatsApp engine, not via a BullMQ queue.
*
diff --git a/src/modules/status/status.service.spec.ts b/src/modules/status/status.service.spec.ts
index 9b74c7a8c..749574d51 100644
--- a/src/modules/status/status.service.spec.ts
+++ b/src/modules/status/status.service.spec.ts
@@ -111,7 +111,17 @@ describe('StatusService media validation and selection', () => {
await expect(service.getStatusMedia('sess', 'w1')).rejects.toBeInstanceOf(NotFoundException);
});
- it('rethrows non-ENOENT storage errors unchanged', async () => {
+ it('maps an S3 NoSuchKey (codeless, name-only) to NotFoundException like the local ENOENT', async () => {
+ // The S3 backend reports a miss with a `.name` and no `.code` at all — retention/lifecycle
+ // rules make the row-outlived-file race most likely exactly there.
+ store.getMedia.mockResolvedValue({ path: 'statuses/sess/gone.jpg', mimetype: 'image/jpeg' });
+ const noSuchKey = Object.assign(new Error('The specified key does not exist.'), { name: 'NoSuchKey' });
+ storageService.getFile.mockRejectedValue(noSuchKey);
+
+ await expect(service.getStatusMedia('sess', 'w1')).rejects.toBeInstanceOf(NotFoundException);
+ });
+
+ it('rethrows non-missing-object storage errors unchanged', async () => {
store.getMedia.mockResolvedValue({ path: 'statuses/sess/x.jpg', mimetype: 'image/jpeg' });
storageService.getFile.mockRejectedValue(new Error('S3 unavailable'));
diff --git a/src/modules/status/status.service.ts b/src/modules/status/status.service.ts
index d8024b6b2..360fada13 100644
--- a/src/modules/status/status.service.ts
+++ b/src/modules/status/status.service.ts
@@ -1,7 +1,7 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { EngineRegistry } from '../../engine/engine-registry.service';
import { StatusStoreService } from '../status-store/status-store.service';
-import { StorageService } from '../../common/storage/storage.service';
+import { StorageService, isMissingObjectError } from '../../common/storage/storage.service';
import type { Status, StatusResult, StatusPostOptions } from '../../engine/interfaces/whatsapp-engine.interface';
import { assertBase64WithinMediaCap, stripBase64DataUri } from '../message/media-cap.util';
import { HookManager, applySendingGate } from '../../core/hooks';
@@ -79,8 +79,9 @@ export class StatusService {
return { buffer, mimetype };
} catch (error) {
// The row outlived its file: purgeExpired (or a concurrent delete) removed it between the
- // DB read and this read. That's "gone", not a server fault — surface a 404.
- if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
+ // DB read and this read. That's "gone", not a server fault — surface a 404. The helper covers
+ // both backends: the local ENOENT and the codeless NoSuchKey/NotFound an S3 miss raises.
+ if (isMissingObjectError(error)) {
throw new NotFoundException('Status media not found or expired');
}
throw error;