Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(engine): bound the wait for an inbound media slot

Yudhi Armyndharis1b242674dd8e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4b7231a5c..e7fa25a40 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -35,7 +35,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `check:sdk-coverage` no longer passes when a client drops a route entirely: a wildcard the client built for a path parameter — `contacts/${contactId}` — was read as a one-builder family and stood in for every concrete sibling under it, so removing `contacts/blocked` from a client left the gate green. A wildcard now counts as a family only where the contract publishes no route of that shape.
- The Go SDK no longer approves or rejects every pending join request when handed an empty participant list: `omitempty` dropped the empty slice, so `[]string{}` reached the gateway as the bodyless "act on every request" rather than the `400` the other four clients receive. A nil slice still means every request.
- Approving or rejecting a join request by bare phone number works on the whatsapp-web.js engine instead of answering `500`: the participant guard accepts a bare number and the three other participant writes qualify it, but these two routes handed it to the engine unqualified, so it reached the page as an unaddressable id. The same request already worked on Baileys. Refs #1220.
-- A burst of inbound media on the whatsapp-web.js engine no longer loses the media of everything past the eighth, which the Baileys repair in this release left in place on the other engine: its download queue was capped at its active slots too, making admission a constant 8 whatever the batch size. A burst now parks rather than shedding, and only the download waits — a text message never enters the limiter.
+- A burst of inbound media on the whatsapp-web.js engine no longer loses the media of everything past the eighth, which the Baileys repair in this release left in place on the other engine: its download queue was capped at its active slots too, making admission a constant 8 whatever the batch size. A burst now parks rather than shedding, and only the download waits — a text message never enters the limiter. The wait for a slot is bounded by `MEDIA_DOWNLOAD_TIMEOUT_MS`, so a burst queued behind a hung page still emits its messages without media rather than waiting on a slot that never frees.
- The chart's optional ServiceMonitor now selects on a new `openwa.io/scrape-target` label, so it scrapes one target per pod instead of two; series previously collected through the headless target stop appearing, so check anything keyed on the `service` label.
- The Helm chart's new startup probe stops the kubelet killing a pod that is still booting, allowing 295s (`periodSeconds: 5`, `failureThreshold: 60`) where the liveness settings allowed 50. It fires immediately, so a fast boot goes live sooner than before, not later — and it is not limited to auto-start, since the database connect retry alone can consume 30 of the old 50 seconds.
- A Helm upgrade that changes only `env` or `secretEnv` now restarts the pod through ConfigMap and Secret checksums, so the new configuration reaches the running container. With `existingSecret` set the chart renders no Secret, so that path still needs `kubectl rollout restart`; `values.yaml` notes what publishing the Secret checksum as a pod annotation means.
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 72828b760..e3d1a673b 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -392,23 +392,32 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
() => undefined,
);
});
- // The slot-holder runs in the background. With an unbounded queue the only rejection left is the
- // limiter CLOSING at teardown — in which case the download task never ran and boundedReady would
- // hang. Resolve null so the caller unblocks and emits the message without media, matching the
- // timeout/byte-cap no-media path. Never let it surface as an unhandled rejection either.
- // Naming the teardown as saturation sent operators to look at concurrency settings for a problem
- // that was never there, so say which one happened.
+ // Defensive only, and deliberately kept. `run()` rejects on a full queue (gone — the queue is
+ // unbounded) or on close(), which nothing calls on this limiter; the task itself swallows both
+ // download outcomes. So nothing is expected here — but an unhandled rejection from a
+ // fire-and-forget promise is not an acceptable way to find that out.
void slotHeld.catch((error: unknown) => {
- const closed = error instanceof Error && error.message.startsWith('ConcurrencyLimiter closed');
- this.logger.warn(
- closed
- ? 'Inbound media limiter closed during teardown; emitting message without media'
- : 'Inbound media download could not be admitted; emitting message without media',
- { msgId: msg.id._serialized, ...(closed ? {} : { error: String(error) }) },
- );
+ this.logger.warn('Inbound media slot holder rejected unexpectedly; emitting message without media', {
+ msgId: msg.id._serialized,
+ error: String(error),
+ });
resolveBounded(null);
});
- const media = await boundedReady;
+ // The caller's wait spans the QUEUE as well as the download, and BOTH are unbounded: the queue by
+ // design now, and the wait for a slot because a slot is held until its download really settles —
+ // which a hung page never does. The inner race only starts once this message is admitted, so it
+ // cannot cover the waiting. Without a bound here, a burst behind stuck slots parks forever and
+ // those messages are never emitted AT ALL — strictly worse than the media loss this change set
+ // out to fix. The old queue cap provided that degradation by rejecting; this restores it without
+ // shedding at a fixed batch size.
+ const media = await withInboundDownloadTimeout(boundedReady, inboundMediaTimeoutMs(), () =>
+ this.logger.warn(
+ 'Inbound media did not arrive within MEDIA_DOWNLOAD_TIMEOUT_MS; emitting message without media',
+ {
+ msgId: msg.id._serialized,
+ },
+ ),
+ );
if (!media) {
return declaredOnlyMedia(msg);
}
diff --git a/src/engine/adapters/wwebjs-inbound-burst.spec.ts b/src/engine/adapters/wwebjs-inbound-burst.spec.ts
index 741d923ca..90600727e 100644
--- a/src/engine/adapters/wwebjs-inbound-burst.spec.ts
+++ b/src/engine/adapters/wwebjs-inbound-burst.spec.ts
@@ -1,5 +1,7 @@
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
+import { ConcurrencyLimiter } from '../../common/utils/concurrency-limiter';
+import { withInboundDownloadTimeout } from './inbound-media-cap';
/**
* The whatsapp-web.js half of the inbound-media burst bound.
@@ -7,13 +9,18 @@ import { join } from 'node:path';
* `baileys-inbound-burst.spec.ts` pins the same property on the other engine, where a queue cap
* equal to the active slots made admission a constant 8 whatever the batch size, so a burst lost
* the media of everything past the eighth. The whatsapp-web.js adapter carried the identical
- * construction — `new ConcurrencyLimiter(inboundMediaConcurrency(), inboundMediaConcurrency())` —
- * and kept losing media in exactly the same way after the Baileys side was repaired.
+ * construction and kept losing media the same way after the Baileys side was repaired.
*
* Unbounding the queue is safe here for a reason that does not hold on Baileys: only the DOWNLOAD
* runs inside the limiter, not the whole message pipeline, and each message awaits its own
- * `capInboundMediaFor`. A parked download therefore delays that message alone — a text message
- * never enters the limiter at all.
+ * `capInboundMediaFor`, so a parked download delays that message alone.
+ *
+ * But removing the cap removes a degradation as well as a defect, and the second test below is the
+ * one that matters. A slot is held until its download REALLY settles — deliberately, so an
+ * abandoned download cannot let a fresh one exceed the concurrency bound — and a hung page never
+ * settles. The rejected-on-full-queue path used to unblock everyone behind it; with no cap and no
+ * bound on the wait, a burst behind stuck slots would park forever and those messages would never
+ * be emitted at all, which is strictly worse than emitting them without media.
*/
describe('whatsapp-web.js inbound media burst', () => {
it('gives the inbound limiter an unbounded queue, so a burst parks instead of shedding', () => {
@@ -29,4 +36,32 @@ describe('whatsapp-web.js inbound media burst', () => {
.filter(Boolean);
expect(args).toEqual(['inboundMediaConcurrency()']);
});
+
+ it('bounds the caller wait, so a message behind permanently stuck slots still resolves', async () => {
+ // The real composition: a limiter whose slots never free, and a caller awaiting admission.
+ const limiter = new ConcurrencyLimiter(1);
+ const wedged = new Promise<never>(() => undefined); // a download that never settles
+ void limiter.run(() => wedged); // takes the only slot and keeps it
+
+ let admitted = false;
+ const boundedReady = limiter.run(() => {
+ admitted = true;
+ return Promise.resolve({ data: 'QUJD', mimetype: 'image/jpeg' });
+ });
+
+ const media = await withInboundDownloadTimeout(boundedReady, 25);
+
+ expect(admitted).toBe(false); // it never got a slot...
+ expect(media).toBeNull(); // ...and the caller still unblocked, to emit without media
+ });
+
+ it('wraps the caller wait in the timeout rather than only the admitted download', () => {
+ // Structural, because the behaviour above is composition-level: the inner race starts once the
+ // task is ADMITTED, so it cannot cover the queue wait. Awaiting boundedReady bare is the shape
+ // that reintroduces the unbounded wait.
+ const source = readFileSync(join(__dirname, 'whatsapp-web-js.adapter.ts'), 'utf8');
+
+ expect(source).toMatch(/await\s+withInboundDownloadTimeout\(\s*boundedReady\s*,/);
+ expect(source).not.toMatch(/const\s+media\s*=\s*await\s+boundedReady\s*;/);
+ });
});