Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): stop an inbound media burst shedding everything past the eighth

Yudhi Armyndharis65bf856bc9d0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 416a5d83a..6aa47325d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -40,6 +40,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `.env.example` and the troubleshooting FAQ no longer name a specific WhatsApp Web build to pin with `WWEBJS_WEB_VERSION`. The build they named has since been withdrawn from the registry, and a build the registry no longer serves is fetched, missed and silently ignored — so an operator following the FAQ's own workaround got the default behaviour while the log claimed the pin had been applied. Both now point at the registry's `html/` folder for a build that is currently served.
- A WhatsApp Web build that cannot be resolved from the wa-version registry is now reported (`web_version_resolve_failed`) with the reason, the registry URL and the remedy. A host that cannot reach the registry — a proxy, a firewalled VPS, regional blocking — silently continued without a pin and let whatsapp-web.js pick the build itself, which is the "authenticates then never reaches ready" class the pin exists to prevent; nothing was logged, so there was nothing to grep for. The existing one-minute backoff already bounds how often the warning can repeat.
- `POST /sessions/:id/pairing-code` answers `409` while a whatsapp-web.js session is still starting up, instead of a `500` carrying a raw `TypeError`. The engine stored its client before launching Chromium, so for the whole launch — seconds on a modest host — the route passed its only guard and reached into a browser page that did not exist yet. Requesting a code straight after `POST /start`, which is what the dashboard's linking modal invites, landed in exactly that window. The request is now accepted only once the session reaches `qr_ready`, the state the pairing flow needs anyway.
+- A burst of inbound media messages no longer loses the media of everything past the eighth. The Baileys adapter capped the download queue at its active slots, and an upsert is submitted in one synchronous pass, so admission was a constant 8 whatever the batch size — a 40-message upsert arrived with 32 of its files replaced by an omitted-media marker. The queue is now unbounded and a burst parks instead of shedding; the concurrent-download bound is unchanged.
### Security
diff --git a/src/engine/adapters/baileys-events.spec.ts b/src/engine/adapters/baileys-events.spec.ts
index 7c07ace13..190930e4e 100644
--- a/src/engine/adapters/baileys-events.spec.ts
+++ b/src/engine/adapters/baileys-events.spec.ts
@@ -1,6 +1,7 @@
import { BaileysEvents, type BaileysEventsHost } from './baileys-events';
import { createLogger } from '../../common/services/logger.service';
import { ConcurrencyLimiter } from '../../common/utils/concurrency-limiter';
+import { inboundMediaConcurrency } from './inbound-media-cap';
import type { WAMessage, WASocket } from '@whiskeysockets/baileys';
/**
@@ -96,7 +97,7 @@ function makeHost(overrides: Partial<BaileysEventsHost> = {}): BaileysEventsHost
// connectedAt only gates handleMessagesUpsert's history-replay skip; mapMessage itself never
// reads it.
connectedAt: 0,
- inboundLimiter: new ConcurrencyLimiter(1),
+ inboundLimiter: new ConcurrencyLimiter(inboundMediaConcurrency()),
recordKeyLidMappings: noop,
recordMessage: noop,
recordMessageEdit: noop,
diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.ts
index ceb3159f7..db39fb121 100644
--- a/src/engine/adapters/baileys-events.ts
+++ b/src/engine/adapters/baileys-events.ts
@@ -159,15 +159,23 @@ export class BaileysEvents {
}
// Throttle through the limiter so a burst of media messages can't run unbounded parallel
// downloads (each a full decrypted buffer in heap). Ordering stays correct — the message store
- // keeps the newest by timestamp. When the waiter queue is saturated we REJECT instead of parking
- // forever, and re-process the message WITHOUT media: the message (body + metadata) is still
- // emitted, but we skip the heap-heavy download that the limiter exists to bound.
+ // keeps the newest by timestamp. The queue is unbounded, so a burst parks rather than shedding
+ // and the message keeps its media either way; on any rejection we still re-process WITHOUT
+ // media, so the body and metadata are emitted rather than lost.
void this.host.inboundLimiter
.run(() => this.processInboundMessage(msg))
- .catch(() => {
- this.host.logger.warn('Inbound media limiter saturated; emitting message without media', {
- msgId: msg.key?.id ?? 'unknown',
- });
+ .catch((error: unknown) => {
+ // Two different failures land here and they are not the same event. The limiter closing is
+ // an orderly teardown; anything else is a real download failure, and reporting it as
+ // "saturated" sent operators to look at concurrency settings for a problem that was never
+ // there. Say which one happened.
+ const closed = error instanceof Error && error.message.startsWith('ConcurrencyLimiter closed');
+ this.host.logger.warn(
+ closed
+ ? 'Inbound media limiter closed during teardown; emitting message without media'
+ : 'Inbound media download failed; emitting message without media',
+ { msgId: msg.key?.id ?? 'unknown', ...(closed ? {} : { error: String(error) }) },
+ );
return this.processInboundMessage(msg, { skipMedia: true });
});
}
diff --git a/src/engine/adapters/baileys-inbound-burst.spec.ts b/src/engine/adapters/baileys-inbound-burst.spec.ts
new file mode 100644
index 000000000..0b14df378
--- /dev/null
+++ b/src/engine/adapters/baileys-inbound-burst.spec.ts
@@ -0,0 +1,144 @@
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { BaileysEvents } from './baileys-events';
+import { ConcurrencyLimiter } from '../../common/utils/concurrency-limiter';
+import { createLogger } from '../../common/services/logger.service';
+import type { WASocket, WAMessage } from '@whiskeysockets/baileys';
+
+/**
+ * A burst of inbound media messages must all keep their media.
+ *
+ * `handleMessagesUpsert` submits every message in an upsert to the inbound limiter synchronously,
+ * so admission is decided before any download finishes. With a queue cap equal to the active slots
+ * the ninth message onward was rejected and re-processed with `skipMedia`, losing the file for
+ * every message past the eighth — one upsert of 40 lost 32.
+ *
+ * No spec exercised this path at all, and the one fixture that built a limiter used
+ * `new ConcurrencyLimiter(1)`, whose unbounded queue cannot shed at any batch size. The whole suite
+ * was green in the presence of the defect, and equally green under a "fix" that removed the
+ * concurrency bound instead — so this asserts the bound as well as the outcome.
+ */
+
+const CONCURRENCY = 4;
+const CONNECTED_AT = 1_700_000_000;
+
+function mediaMessage(index: number): WAMessage {
+ return {
+ key: { id: `m${index}`, remoteJid: '[email protected]', fromMe: false },
+ messageTimestamp: CONNECTED_AT + 60,
+ message: { imageMessage: { mimetype: 'image/jpeg', fileLength: 1024 } },
+ };
+}
+
+/** Drain the microtask queue until every submitted task has settled. */
+const settle = async (): Promise<void> => {
+ for (let i = 0; i < 50; i++) await Promise.resolve();
+};
+
+describe('BaileysEvents inbound media burst', () => {
+ const build = (batch: number) => {
+ const downloaded: string[] = [];
+ let inFlight = 0;
+ let maxInFlight = 0;
+ const warns: string[] = [];
+
+ const events = new BaileysEvents({
+ getSocket: () => ({ updateMediaMessage: jest.fn() }) as unknown as WASocket,
+ getSocketOrNull: () => null,
+ logger: { ...createLogger('BurstSpec'), warn: (m: string) => warns.push(m) },
+ toNeutralJid: (jid: string) => jid,
+ normalizedSelfJid: () => '[email protected]',
+ connectedAt: CONNECTED_AT,
+ // The production wiring, not a test-only limiter — the point of this spec.
+ inboundLimiter: new ConcurrencyLimiter(CONCURRENCY),
+ recordKeyLidMappings: () => undefined,
+ recordMessage: () => undefined,
+ recordMessageEdit: () => undefined,
+ putStoredMessage: () => undefined,
+ getOnMessage: () => undefined,
+ getOnMessageCreate: () => undefined,
+ getOnMessageRevoked: () => undefined,
+ getOnMessageEdited: () => undefined,
+ getOnMessageReaction: () => undefined,
+ getOnMessageAck: () => undefined,
+ getOnGroupEvent: () => undefined,
+ getOnCall: () => undefined,
+ getOnPresenceUpdate: () => undefined,
+ getOnCallOutcome: () => undefined,
+ } as never);
+
+ // Stand in for the download: records that media was fetched, and tracks concurrency while it runs.
+ (events as unknown as { processInboundMessage: unknown }).processInboundMessage = async (
+ msg: WAMessage,
+ opts?: { skipMedia?: boolean },
+ ): Promise<void> => {
+ if (opts?.skipMedia) return;
+ inFlight++;
+ maxInFlight = Math.max(maxInFlight, inFlight);
+ await Promise.resolve();
+ downloaded.push(msg.key?.id ?? '?');
+ inFlight--;
+ };
+
+ const messages = Array.from({ length: batch }, (_, i) => mediaMessage(i + 1));
+ return { events, messages, downloaded, warns, peak: () => maxInFlight };
+ };
+
+ it.each([12, 40])('keeps the media of every message in a batch of %i', async batch => {
+ const h = build(batch);
+ h.events.handleMessagesUpsert({ messages: h.messages, type: 'notify' });
+ await settle();
+
+ expect(h.downloaded.length).toBe(batch);
+ expect(h.warns).toEqual([]);
+ });
+
+ it('never exceeds the configured concurrency while doing so', async () => {
+ const h = build(40);
+ h.events.handleMessagesUpsert({ messages: h.messages, type: 'notify' });
+ await settle();
+
+ // Guard the guard: a peak of 0 would mean nothing ran and the assertion above is vacuous.
+ expect(h.peak()).toBeGreaterThan(0);
+ // Removing the bound instead of the queue cap also makes the test above pass. This is what
+ // separates the two.
+ expect(h.peak()).toBeLessThanOrEqual(CONCURRENCY);
+ });
+
+ // Two different failures reach the rejection handler and they are not the same event. Reporting a
+ // failed download as "limiter saturated" sends an operator to look at concurrency settings for a
+ // problem that was never there.
+ it.each([
+ ['ConcurrencyLimiter closed', 'closed during teardown'],
+ ['socket hung up', 'download failed'],
+ ])('says which failure happened when a submission rejects with "%s"', async (message, expected) => {
+ const h = build(1);
+ (h.events as unknown as { processInboundMessage: unknown }).processInboundMessage = (
+ _msg: WAMessage,
+ opts?: { skipMedia?: boolean },
+ ): Promise<void> => (opts?.skipMedia ? Promise.resolve() : Promise.reject(new Error(message)));
+
+ h.events.handleMessagesUpsert({ messages: h.messages, type: 'notify' });
+ await settle();
+
+ expect(h.warns).toHaveLength(1);
+ expect(h.warns[0]).toContain(expected);
+ });
+
+ // The tests above build their own limiter, so they cannot see how the adapter builds its one.
+ // This is the assertion that actually guards production: re-adding the queue cap is the
+ // regression, and it is a second constructor argument.
+ it('builds the adapter limiter without a queue cap', () => {
+ const source = readFileSync(join(__dirname, 'baileys.adapter.ts'), 'utf8');
+ const construction = source.match(/new ConcurrencyLimiter\(([\s\S]*?)\);/);
+
+ // Guard the parser: a renamed limiter would make this vacuous.
+ expect(construction).not.toBeNull();
+
+ const args = (construction?.[1] ?? '')
+ .split(',')
+ .map(arg => arg.replace(/\/\/[^\n]*/g, '').trim())
+ .filter(Boolean);
+ expect(args).toEqual(['inboundMediaConcurrency()']);
+ });
+});
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 6cc88dd7d..ba2c9a6e7 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -61,12 +61,14 @@ export class BaileysAdapter implements IWhatsAppEngine {
private readonly logger = createLogger('BaileysAdapter');
// Bound concurrent inbound media downloads: each materialises a full decrypted buffer in heap, so an
// unbounded fire-and-forget loop lets a sender flood the gateway with N parallel multi-MB allocations.
- private readonly inboundLimiter = new ConcurrencyLimiter(
- inboundMediaConcurrency(),
- // Queue cap == active slots: beyond (active + queued) concurrent media messages, reject instead of
- // parking, so a burst can't grow heap without bound (each parked closure holds the message).
- inboundMediaConcurrency(),
- );
+ //
+ // The QUEUE is deliberately unbounded. handleMessagesUpsert submits a whole upsert synchronously,
+ // so admission is decided before any download finishes: a queue capped at the active slots admitted
+ // a constant 2n regardless of batch size, and everything past it was re-processed with skipMedia —
+ // a 40-message upsert lost the media of 32. A parked closure holds the message, not the file, and
+ // inbound-media-cap.ts bounds what any one download may allocate, so capping the queue again needs
+ // a threshold an ordinary burst does not reach. That is its own question.
+ private readonly inboundLimiter = new ConcurrencyLimiter(inboundMediaConcurrency());
private readonly authPath: string;
private readonly sessionStore: BaileysSessionStore;
private readonly groups: BaileysGroups;