Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): pace the media fetches of a contact's statuses
Yudhi Armyndharis93a7bf825b2b
diff --git a/dashboard/src/components/chats/StatusMedia.test.ts b/dashboard/src/components/chats/StatusMedia.test.tsnew file mode 100644index 000000000..cf4abb298--- /dev/null+++ b/dashboard/src/components/chats/StatusMedia.test.ts@@ -0,0 +1,64 @@+// A contact's status items all mount at once. The gateway answers a route ten times a second per IP and+// refuses the rest with a 429, so fetching every item together left the newest ones as "Media unavailable"+// for good; they take their turns now, and a refusal that still arrives is retried.+import '../../test-helpers/register-hooks.ts';+import { test, before, afterEach } from 'node:test';+import assert from 'node:assert/strict';+import { createElement } from 'react';++type RTL = typeof import('@testing-library/react');++let rtl: RTL;+let StatusMedia: typeof import('./StatusMedia.tsx').default;+let sessionApi: typeof import('../../services/api.ts').sessionApi;++before(async () => {+ const { installJsdomGlobals } = await import('../../test-helpers/jsdom.ts');+ await installJsdomGlobals();+ const { i18nReady } = await import('../../i18n/index.ts');+ await i18nReady;+ rtl = await import('@testing-library/react');+ ({ default: StatusMedia } = await import('./StatusMedia.tsx'));+ ({ sessionApi } = await import('../../services/api.ts'));+ URL.createObjectURL = (): string => 'blob:status';+ URL.revokeObjectURL = (): void => undefined;+});++afterEach(() => rtl.cleanup());++test('twelve status items mounted together all end up with their media when the gateway refuses past ten a second', async () => {+ const startedAt: number[] = [];+ const api = sessionApi as unknown as {+ getStatusMediaBlob: (id: string, statusId: string, signal?: AbortSignal) => Promise<Blob>;+ };+ const original = api.getStatusMediaBlob;+ api.getStatusMediaBlob = () => {+ const now = Date.now();+ startedAt.push(now);+ const inWindow = startedAt.filter(t => now - t < 1000).length;+ return inWindow > 10+ ? Promise.reject(Object.assign(new Error('Too Many Requests'), { status: 429 }))+ : Promise.resolve(new Blob(['x'], { type: 'image/jpeg' }));+ };+ try {+ const { container } = rtl.render(+ createElement(+ 'div',+ null,+ Array.from({ length: 12 }, (_, i) =>+ createElement(StatusMedia, { key: i, sessionId: 's1', statusId: `st-${i}`, type: 'image' as const }),+ ),+ ),+ );++ await rtl.waitFor(+ () => {+ assert.equal(container.querySelectorAll('img.channel-media').length, 12);+ },+ { timeout: 6000 },+ );+ assert.equal(container.querySelectorAll('.status-media-placeholder').length, 0);+ } finally {+ api.getStatusMediaBlob = original;+ }+});diff --git a/dashboard/src/components/chats/StatusMedia.tsx b/dashboard/src/components/chats/StatusMedia.tsxindex 10d30a1f7..35187dcba 100644--- a/dashboard/src/components/chats/StatusMedia.tsx+++ b/dashboard/src/components/chats/StatusMedia.tsx@@ -1,10 +1,13 @@import { useEffect, useState } from 'react';import { useTranslation } from 'react-i18next';import { sessionApi } from '../../services/api';+import { loadArchivedMedia } from '../../utils/archivedMediaLoad';// Status image item. <img src="/api/..."> can't carry the X-API-Key header, so the bytes are// fetched via sessionApi (which does) and re-exposed as a local object URL. The URL is revoked on-// unmount/statusId change to avoid leaking blob memory as the viewer browses items.+// unmount/statusId change to avoid leaking blob memory as the viewer browses items. Every item of the+// open contact mounts at once, so the fetches take their turns a gap apart and a refusal for rate is+// retried, as the previews of archived chat media do.function StatusMedia({sessionId,statusId,@@ -22,10 +25,10 @@ function StatusMedia({if (!sessionId) return undefined;let objectUrl: string | null = null;let cancelled = false;+ const controller = new AbortController();setSrc(null);setError(false);- sessionApi- .getStatusMediaBlob(sessionId, statusId)+ loadArchivedMedia(controller.signal, () => sessionApi.getStatusMediaBlob(sessionId, statusId, controller.signal)).then(blob => {if (cancelled) return;objectUrl = URL.createObjectURL(blob);@@ -36,6 +39,7 @@ function StatusMedia({});return () => {cancelled = true;+ controller.abort();if (objectUrl) URL.revokeObjectURL(objectUrl);};}, [sessionId, statusId]);diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex 3182ba493..56289f90c 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -916,8 +916,8 @@ export const sessionApi = {getChannelMessages: (id: string, channelId: string, limit = 50) =>request<ChannelMessage[]>(`/sessions/${id}/channels/${encodeURIComponent(channelId)}/messages?limit=${limit}`),getContactStatuses: (id: string) => request<{ statuses: StatusUpdate[] }>(`/sessions/${id}/status`),- getStatusMediaBlob: (id: string, statusId: string) =>- requestBlob(`/sessions/${id}/status/${encodeURIComponent(statusId)}/media`),+ getStatusMediaBlob: (id: string, statusId: string, signal?: AbortSignal) =>+ requestBlob(`/sessions/${id}/status/${encodeURIComponent(statusId)}/media`, signal),postTextStatus: (id: string,text: string,