Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(contact): stop avatar lookups after one times out

Yudhi Armyndharis1b5697b5692b
diff --git a/src/modules/contact/contact.controller.ts b/src/modules/contact/contact.controller.ts
index 019384199..bc235eeec 100644
--- a/src/modules/contact/contact.controller.ts
+++ b/src/modules/contact/contact.controller.ts
@@ -63,8 +63,9 @@ export class ContactController {
@ApiOperation({
summary: 'Batch-resolve profile picture URLs for up to 50 contacts',
description:
- 'One request for a whole chat sidebar — avoids the burst of parallel single fetches that ' +
- 'would exhaust the per-IP throttle. Engine lookups run 5 at a time; per-id failures return null.',
+ 'Resolve a chat sidebar in one request to avoid bursts of per-contact HTTP calls. ' +
+ 'Engine lookups run 5 at a time; per-id failures return null. After a lookup times out, ' +
+ 'later chunks are skipped and their ids are absent from the response.',
})
@ApiParam({ name: 'sessionId', description: 'Session ID' })
@ApiQuery({ name: 'ids', required: true, description: 'Comma-separated contact ids (max 50 used)' })
diff --git a/src/modules/contact/contact.service.spec.ts b/src/modules/contact/contact.service.spec.ts
index f90f9dd77..845577fe1 100644
--- a/src/modules/contact/contact.service.spec.ts
+++ b/src/modules/contact/contact.service.spec.ts
@@ -134,6 +134,69 @@ describe('ContactService', () => {
}
});
+ it.each(['resolve', 'reject'] as const)(
+ 'stops later avatar chunks after a timeout and handles a late %s',
+ async outcome => {
+ jest.useFakeTimers();
+ let active = 0;
+ let peak = 0;
+ let calls = 0;
+ const getProfilePicture = jest.fn().mockImplementation(() => {
+ active += 1;
+ peak = Math.max(peak, active);
+ const call = ++calls;
+ if (call > 5) return Promise.resolve(null).finally(() => active--);
+ return new Promise<string | null>((resolve, reject) => {
+ setTimeout(() => {
+ if (outcome === 'reject' && call === 1) reject(new Error('lookup failed'));
+ else resolve('https://pps/picture.jpg');
+ }, 9000);
+ }).finally(() => active--);
+ });
+ const ids = Array.from({ length: 6 }, (_, i) => String(628100000000 + i) + '@c.us');
+ try {
+ const result = makeService({ getProfilePicture }).getProfilePictures('s1', ids);
+ await jest.advanceTimersByTimeAsync(8000);
+ await expect(result).resolves.toEqual(Object.fromEntries(ids.slice(0, 5).map(id => [id, null])));
+ expect(active).toBe(5);
+ await jest.advanceTimersByTimeAsync(1000);
+ expect(active).toBe(0);
+ expect(getProfilePicture).toHaveBeenCalledTimes(5);
+ expect(peak).toBeLessThanOrEqual(5);
+ expect(jest.getTimerCount()).toBe(0);
+ } finally {
+ await jest.advanceTimersByTimeAsync(30000);
+ jest.clearAllTimers();
+ jest.useRealTimers();
+ }
+ },
+ );
+
+ it('preserves not-ready when other lookups in the chunk time out', async () => {
+ jest.useFakeTimers();
+ const getProfilePicture = jest
+ .fn()
+ .mockRejectedValueOnce(new EngineNotReadyError())
+ .mockImplementation(() => new Promise(resolve => setTimeout(() => resolve(null), 9000)));
+ try {
+ const result = makeService({ getProfilePicture })
+ .getProfilePictures(
+ 's1',
+ Array.from({ length: 6 }, (_, i) => String(628100000000 + i) + '@c.us'),
+ )
+ .catch((error: unknown) => error);
+ await jest.advanceTimersByTimeAsync(8000);
+ expect(await result).toBeInstanceOf(EngineNotReadyError);
+ expect(getProfilePicture).toHaveBeenCalledTimes(5);
+ await jest.advanceTimersByTimeAsync(1000);
+ expect(jest.getTimerCount()).toBe(0);
+ } finally {
+ await jest.advanceTimersByTimeAsync(30000);
+ jest.clearAllTimers();
+ jest.useRealTimers();
+ }
+ });
+
describe('block/unblock reject ids that do not name a person', () => {
// whatsapp-web.js's Contact.block()/unblock() return false for a group id (nothing blocked,
// answered 200 "blocked"). Both engines share this 400 guard.
diff --git a/src/modules/contact/contact.service.ts b/src/modules/contact/contact.service.ts
index d839b82a0..24ba6fd68 100644
--- a/src/modules/contact/contact.service.ts
+++ b/src/modules/contact/contact.service.ts
@@ -93,9 +93,11 @@ export class ContactService {
/**
* Batch-resolve profile picture URLs for a list of contact ids (the dashboard's chat-list avatars
* — one HTTP call instead of N, so the per-IP throttle isn't exhausted by a sidebar full of
- * parallel fetches). Engine lookups run 5 at a time with a per-id deadline; a per-id failure or
- * timeout yields null for that id (hidden/no picture), never aborts the batch. The exception is
- * EngineNotReadyError: it describes the session, not the id, so it fails the whole request with
+ * parallel fetches). Engine lookups run 5 at a time with a per-id deadline. A timeout yields null
+ * for that id and ends the walk: the ids of the later chunks are left out of the answer, like those
+ * past the cap, so a caller asks for them again instead of reading null as "no picture", and
+ * unfinished lookups never overlap new engine work. Ordinary per-id failures yield null and the
+ * batch continues. EngineNotReadyError describes the session, not the id, so it fails the whole request with
* 409 after the current chunk and the remaining chunks are not started. Answering 200 with every
* avatar null would be cached by the dashboard as "no pictures". Ids beyond
* PROFILE_PICTURES_MAX_IDS are ignored.
@@ -108,15 +110,16 @@ export class ContactService {
let notReady: EngineNotReadyError | undefined;
for (let i = 0; i < capped.length; i += CHUNK) {
const chunk = capped.slice(i, i + CHUNK);
+ let timedOut = false;
const results = await Promise.all(
chunk.map((id): Promise<readonly [string, string | null]> => {
// Per-id deadline: a hanging lookup (bad/unreachable id) resolves null instead of
// stalling the whole batch; the timer is cleared the moment the engine settles.
return new Promise<readonly [string, string | null]>(resolve => {
- const timer = setTimeout(
- () => resolve([id, null] as const),
- ContactService.PROFILE_PICTURE_LOOKUP_TIMEOUT_MS,
- );
+ const timer = setTimeout(() => {
+ timedOut = true;
+ resolve([id, null] as const);
+ }, ContactService.PROFILE_PICTURE_LOOKUP_TIMEOUT_MS);
engine.getProfilePicture(id).then(
url => {
clearTimeout(timer);
@@ -135,6 +138,7 @@ export class ContactService {
for (const [id, url] of results) {
pictures[id] = url;
}
+ if (timedOut) break;
}
return pictures;
}
diff --git a/src/modules/contact/dto/contact-response.dto.ts b/src/modules/contact/dto/contact-response.dto.ts
index df2aceda1..216473063 100644
--- a/src/modules/contact/dto/contact-response.dto.ts
+++ b/src/modules/contact/dto/contact-response.dto.ts
@@ -59,8 +59,8 @@ export class ProfilePicturesResponseDto {
@ApiProperty({
description:
'Map of the requested contact ids to their picture URL. An id resolves to null when the ' +
- 'contact has no picture, hides it, or its individual lookup failed — a per-id failure does ' +
- 'not fail the batch. Ids beyond the first 50 are not looked up and are absent from the map.',
+ 'contact has no picture, hides it, or its lookup failed. Ids beyond the first 50, and ids skipped ' +
+ 'after a lookup timed out, are absent from the map: ask for them again.',
example: { '[email protected]': 'https://pps.whatsapp.net/v/t61.24694-24/12345_678_910_n.jpg' },
additionalProperties: { type: 'string', nullable: true },
})