Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(contacts): make the avatar batch resilient on long sidebars (#823)
Yudhi Armyndharis7799cae4d7ae
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c19ac2fc8..8c4242190 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -77,6 +77,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- Chat-list avatars no longer stall on long sidebars: the batch endpoint caps engine lookups at a+ per-id deadline (a hanging id resolves null instead of holding the whole batch), and the request+ now resolves the sidebar's TOP 50 ids in list order so visible rows get their pictures first.++- Chat-list avatars no longer burst into HTTP 429s: profile pictures for the whole sidebar arebatch-resolved in ONE request (`GET .../contacts/profile-pictures?ids=…`, up to 50 ids, 3 enginelookups at a time) instead of one parallel fetch per row, which exhausted the per-IP throttle.diff --git a/dashboard/src/hooks/useProfilePictures.ts b/dashboard/src/hooks/useProfilePictures.tsindex 7ed66995c..3e80a1efa 100644--- a/dashboard/src/hooks/useProfilePictures.ts+++ b/dashboard/src/hooks/useProfilePictures.ts@@ -4,18 +4,22 @@ import { contactApi } from '../services/api';/*** Batch-fetch profile picture URLs for a list of chat ids in ONE request (the chat-list sidebar).* Firing one useProfilePicture per row bursts N parallel calls and exhausts the per-IP throttle- * (429s); the batch endpoint resolves up to 50 ids server-side, 3 at a time.+ * (429s); the batch endpoint resolves up to 50 ids server-side, 5 at a time with a per-id deadline.+ *+ * Ids are resolved in LIST ORDER, capped at 50 — for long sidebars the visible top rows get their+ * pictures instead of an arbitrary sorted subset (which can exclude every row on screen). The+ * query key uses the sorted id set so reordering the sidebar doesn't refetch.** Caching mirrors useProfilePicture: 1h stale (signed CDN URLs rotate), 30min gc, no retry — an- * id that comes back null just keeps the icon fallback. The query key uses the sorted id list so- * reordering the sidebar doesn't refetch.+ * id that comes back null just keeps the icon fallback.*/export function useProfilePictures(sessionId: string | undefined, contactIds: string[]) {- const sortedKey = [...contactIds].sort().join(',');+ const requestIds = contactIds.slice(0, 50); // list order: the visible top rows win the cap+ const sortedKey = [...requestIds].sort().join(',');return useQuery<Record<string, string | null>, Error>({queryKey: ['profilePictures', sessionId, sortedKey] as const,- queryFn: () => contactApi.profilePictures(sessionId!, sortedKey.split(',')).then(r => r.pictures),- enabled: Boolean(sessionId && contactIds.length > 0),+ queryFn: () => contactApi.profilePictures(sessionId!, requestIds).then(r => r.pictures),+ enabled: Boolean(sessionId && requestIds.length > 0),staleTime: 60 * 60 * 1000, // 1 hourgcTime: 30 * 60 * 1000,retry: false,diff --git a/src/modules/contact/contact.service.spec.ts b/src/modules/contact/contact.service.spec.tsindex 674fd67cd..87133066e 100644--- a/src/modules/contact/contact.service.spec.ts+++ b/src/modules/contact/contact.service.spec.ts@@ -70,7 +70,7 @@ describe('ContactService', () => {expect(getProfilePicture).toHaveBeenCalledTimes(50);});- it('runs batch lookups at most 3 concurrently', async () => {+ it('runs batch lookups at most 5 concurrently', async () => {let active = 0;let maxActive = 0;const getProfilePicture = jest.fn().mockImplementation(async () => {@@ -80,8 +80,19 @@ describe('ContactService', () => {active -= 1;return null;});- const ids = Array.from({ length: 9 }, (_, i) => `${i}@c.us`);+ const ids = Array.from({ length: 12 }, (_, i) => `${i}@c.us`);await makeService({ getProfilePicture }).getProfilePictures('s1', ids);- expect(maxActive).toBeLessThanOrEqual(3);+ expect(maxActive).toBeLessThanOrEqual(5);});++ it('yields null (not a stalled batch) when an engine lookup hangs past the per-id deadline', async () => {+ const getProfilePicture = jest+ .fn()+ .mockResolvedValueOnce('https://pps/1.jpg')+ .mockImplementationOnce(() => new Promise(() => undefined)); // never settles+ const started = Date.now();+ const out = await makeService({ getProfilePicture }).getProfilePictures('s1', ['[email protected]', '[email protected]']);+ expect(out).toEqual({ '[email protected]': 'https://pps/1.jpg', '[email protected]': null });+ expect(Date.now() - started).toBeLessThan(12_000);+ }, 15_000);});diff --git a/src/modules/contact/contact.service.ts b/src/modules/contact/contact.service.tsindex 2e8774e69..70ef26125 100644--- a/src/modules/contact/contact.service.ts+++ b/src/modules/contact/contact.service.ts@@ -54,26 +54,43 @@ export class ContactService {/** Upper bound for one batch call — keeps a huge `ids` list from pinning the engine for minutes. */private static readonly PROFILE_PICTURES_MAX_IDS = 50;+ /** Per-id engine-lookup deadline: one hanging id must not hold the whole batch hostage. */+ private static readonly PROFILE_PICTURE_LOOKUP_TIMEOUT_MS = 8000;+/*** 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 3 at a time; a per-id failure yields null for that id- * (hidden/no picture), never aborts the batch. Ids beyond PROFILE_PICTURES_MAX_IDS are ignored.+ * 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. Ids beyond+ * PROFILE_PICTURES_MAX_IDS are ignored.*/async getProfilePictures(sessionId: string, ids: string[]): Promise<Record<string, string | null>> {const engine = this.getEngine(sessionId);const capped = ids.slice(0, ContactService.PROFILE_PICTURES_MAX_IDS);const pictures: Record<string, string | null> = {};- const CHUNK = 3;+ const CHUNK = 5;for (let i = 0; i < capped.length; i += CHUNK) {const chunk = capped.slice(i, i + CHUNK);const results = await Promise.all(- chunk.map(async (id): Promise<readonly [string, string | null]> => {- try {- return [id, await engine.getProfilePicture(id)] as const;- } catch {- return [id, null] as const;- }+ 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,+ );+ engine.getProfilePicture(id).then(+ url => {+ clearTimeout(timer);+ resolve([id, url] as const);+ },+ () => {+ clearTimeout(timer);+ resolve([id, null] as const);+ },+ );+ });}),);for (const [id, url] of results) {