Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
test(wwebjs): pin the start diagnostics, the slot hold and the cap edge
Yudhi Armyndharis8f5039063b4b
diff --git a/src/engine/adapters/inbound-hold.spec.ts b/src/engine/adapters/inbound-hold.spec.tsindex 9b57995a0..24567b08f 100644--- a/src/engine/adapters/inbound-hold.spec.ts+++ b/src/engine/adapters/inbound-hold.spec.ts@@ -680,6 +680,63 @@ describe('whatsapp-web.js inbound messages held for storage', () => {},);+ it('keeps its slot while the processing of a downloaded message is parked, across a reconnect', async () => {+ process.env.MEDIA_DOWNLOAD_TIMEOUT_MS = '5000';+ const h = heldProjector();+ const { client } = build(h.callbacks);+ const quoted = deferred<{ id: { _serialized: string }; body: string }>();+ const first = jest.fn().mockResolvedValue({ mimetype: 'image/png', data: 'QUJD' });+ client.emit('message', {+ ...incoming('m1', '[email protected]', first),+ hasQuotedMsg: true,+ getQuotedMessage: jest.fn(() => quoted.promise),+ });+ await flush();+ // The payload is downloaded; the processing waits for the quoted message, which a held message bounds+ // only by MEDIA_DOWNLOAD_TIMEOUT_MS.+ expect(first).toHaveBeenCalledTimes(1);++ // The engine is retired and its pending turn dropped, so only the hold on the processing keeps the slot.+ const fresh = {} as IWhatsAppEngine;+ h.engines.set('s1', fresh);+ const next = build(h.callbacksFor(fresh));+ const second = jest.fn().mockResolvedValue({ mimetype: 'image/png', data: 'QUJD' });+ next.client.emit('message', incoming('m2', '[email protected]', second));+ await flush();+ expect(second).not.toHaveBeenCalled();++ quoted.resolve({ id: { _serialized: 'q' }, body: 'quoted' });+ await flush();+ expect(second).toHaveBeenCalledTimes(1);+ });++ it('plans the download of a declared size at the cap, and of none above it', () => {+ process.env.MEDIA_DOWNLOAD_MAX_BYTES = '1000';+ process.env.MEDIA_DOWNLOAD_ENABLED = 'true';+ const declared = (size: number): WwebjsMessage => ({ hasMedia: true, _data: { size } }) as unknown as WwebjsMessage;++ expect(plannedInboundDownload(declared(1000))).toBe(true);+ expect(plannedInboundDownload(declared(1001))).toBe(false);+ });++ it('ignores message_create for a message the account did not send, which has its own message event', async () => {+ const h = heldProjector();+ const callbacks = {+ ...h.callbacks,+ admitInbound: jest.fn(h.callbacks.admitInbound),+ onMessageCreate: jest.fn(),+ };+ const { client } = build(callbacks);+ const page = jest.fn().mockResolvedValue({ mimetype: 'image/png', data: 'QUJD' });++ client.emit('message_create', incoming('m1', '[email protected]', page));+ await flush();++ expect(callbacks.admitInbound).not.toHaveBeenCalled();+ expect(callbacks.onMessageCreate).not.toHaveBeenCalled();+ expect(page).not.toHaveBeenCalled();+ });+it('keeps the slot of a timed-out page download until the page settles', async () => {process.env.MEDIA_DOWNLOAD_TIMEOUT_MS = '100';// The adapter's limiter gets a spare slot, so only the room (one slot) can hold the second download.diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex aa3e9b1a3..2780d557d 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -5872,6 +5872,24 @@ describe('WhatsAppWebJsAdapter inbound media measured in the page', () => {});});+ // The comparison in the page and the one that plans the download are each one character from the wrong one.+ it('inlines a payload of exactly the cap and drops one a byte over it', async () => {+ pageServing(1000);+ await expect(cap(understated(runInPage))).resolves.toEqual({+ mimetype: 'video/mp4',+ filename: 'clip.mp4',+ data: Buffer.alloc(1000).toString('base64'),+ });++ pageServing(1001);+ await expect(cap(understated(runInPage))).resolves.toEqual({+ mimetype: 'video/mp4',+ filename: 'clip.mp4',+ omitted: true,+ sizeBytes: 1001,+ });+ });+it('drops a payload over the cap by its received length even when the page reports it small', async () => {const data = Buffer.alloc(2000).toString('base64');const page = jest.fn().mockResolvedValue({ mimetype: 'video/mp4', data, sizeBytes: 10 });@@ -5918,24 +5936,6 @@ describe('WhatsAppWebJsAdapter inbound media measured in the page', () => {);});- // puppeteer ships downloadMediaInPage into the page as Function#toString(), so it can reach nothing of this- // module: a constant or helper it closes over resolves in Node, where every test above runs it, and throws- // ReferenceError in the page, where every download then fails. The source is compiled from the file with the- // project's compiler options and run in a context holding only the page's window and AbortController. The- // loaded copy is not used: coverage instruments it with counters the page does not have.- function shippedToPage(): typeof downloadMediaInPage {- const root = path.join(__dirname, '..', '..', '..');- const { config } = ts.readConfigFile(path.join(root, 'tsconfig.json'), name => fs.readFileSync(name, 'utf8')) as {- config: { compilerOptions: Record<string, unknown> };- };- const { options } = ts.convertCompilerOptionsFromJson({ ...config.compilerOptions, module: 'CommonJS' }, root);- const file = fs.readFileSync(path.join(__dirname, 'wwebjs-messaging.ts'), 'utf8');- const start = file.indexOf('async function downloadMediaInPage');- expect(start).toBeGreaterThan(-1);- const compiled = ts.transpileModule(file.slice(start, file.indexOf('\n}\n', start) + 2), {- compilerOptions: options,- }).outputText;- // Declared alongside whatever helpers the compiler hoisted, then sent as its own text, as puppeteer does.// WhatsApp Web rejects with more than errors: a bare string, or an object that carries only a status// (upstream reads e.status === 404), and the operator reads the warning that names it.it.each([@@ -5955,6 +5955,24 @@ describe('WhatsAppWebJsAdapter inbound media measured in the page', () => {await expect(downloadMediaInPage({ msgId: 'M1', maxBytes: 1000 })).rejects.toThrow(expected);});+ // puppeteer ships downloadMediaInPage into the page as Function#toString(), so it can reach nothing of this+ // module: a constant or helper it closes over resolves in Node, where every test above runs it, and throws+ // ReferenceError in the page, where every download then fails. The source is compiled from the file with the+ // project's compiler options and run in a context holding only the page's window and AbortController. The+ // loaded copy is not used: coverage instruments it with counters the page does not have.+ function shippedToPage(): typeof downloadMediaInPage {+ const root = path.join(__dirname, '..', '..', '..');+ const { config } = ts.readConfigFile(path.join(root, 'tsconfig.json'), name => fs.readFileSync(name, 'utf8')) as {+ config: { compilerOptions: Record<string, unknown> };+ };+ const { options } = ts.convertCompilerOptionsFromJson({ ...config.compilerOptions, module: 'CommonJS' }, root);+ const file = fs.readFileSync(path.join(__dirname, 'wwebjs-messaging.ts'), 'utf8');+ const start = file.indexOf('async function downloadMediaInPage');+ expect(start).toBeGreaterThan(-1);+ const compiled = ts.transpileModule(file.slice(start, file.indexOf('\n}\n', start) + 2), {+ compilerOptions: options,+ }).outputText;+ // Declared alongside whatever helpers the compiler hoisted, then sent as its own text, as puppeteer does.const declared = vm.runInNewContext(`${compiled}\n;downloadMediaInPage`) as { toString(): string };return vm.runInNewContext(`(${declared.toString()})`, {window: (globalThis as unknown as { window: unknown }).window,@@ -6030,6 +6048,7 @@ describe('WhatsAppWebJsAdapter inbound media measured in the page', () => {'sizeBytes','name','message',+ 'constructor','Debug','VERSION',].sort(),@@ -6048,7 +6067,6 @@ describe('WhatsAppWebJsAdapter inbound media measured in the page', () => {* into one value (`Client.js:1558`), and its typings claim `Promise<Message>` — so nothing upstream of* these tests catches a regression here.*/- 'constructor',describe('WhatsAppWebJsAdapter send-result contract', () => {const readyAdapter = (client: unknown): WhatsAppWebJsAdapter => {const adapter = new WhatsAppWebJsAdapter({ sessionId: 's', sessionDataPath: './data/sessions', puppeteer: {} });diff --git a/src/engine/adapters/wwebjs-startup-diagnostics.spec.ts b/src/engine/adapters/wwebjs-startup-diagnostics.spec.tsnew file mode 100644index 000000000..28e9f3883--- /dev/null+++ b/src/engine/adapters/wwebjs-startup-diagnostics.spec.ts@@ -0,0 +1,85 @@+import { Client } from 'whatsapp-web.js';+import { WwebjsLifecycle, type WwebjsLifecycleHost } from './wwebjs-lifecycle';+import { backportProblem } from './wwebjs-backport-check';+import { unappliedPatches, unappliedPatchesMessage } from './engine-patch-status';++jest.mock('./wwebjs-backport-check', () => ({ backportProblem: jest.fn() }));+jest.mock('./engine-patch-status', () => ({+ unappliedPatches: jest.fn().mockReturnValue([]),+ unappliedPatchesMessage: jest.fn(),+}));+jest.mock('./wwebjs-running-build', () => ({ reportRunningWebBuild: jest.fn() }));+jest.mock('./wwebjs-call-hook-check', () => ({ reportMissingCallHook: jest.fn().mockResolvedValue(undefined) }));+jest.mock('./chromium-profile-hygiene', () => ({+ killOrphanedChromiumProcesses: jest.fn().mockResolvedValue(undefined),+ removeStaleSingletonFiles: jest.fn().mockResolvedValue(undefined),+}));++const problem = backportProblem as jest.Mock;+const unapplied = unappliedPatches as jest.Mock;+const unappliedText = unappliedPatchesMessage as jest.Mock;++/**+ * An install whose patches did not land fails later with errors that name no cause, so the engine says+ * so at the start, where the operator is looking at the logs. The checks are pure functions with their+ * own specs; this is the call that makes them reach anyone.+ */+describe('the patch diagnostics at whatsapp-web.js start', () => {+ let clientInitSpy: jest.SpyInstance;+ let logger: { log: jest.Mock; warn: jest.Mock; error: jest.Mock; debug: jest.Mock };++ const initialize = async (): Promise<void> => {+ const host = {+ logger,+ config: { sessionId: 'sess', sessionDataPath: './data/sessions' },+ getCallbacks: () => ({}),+ emitState: jest.fn(),+ scheduleReadyReconcile: jest.fn(),+ clearReadyReconcile: jest.fn(),+ startOnboardingWatcher: jest.fn(),+ clearOnboardingWatcher: jest.fn(),+ clearLiveCalls: jest.fn(),+ clearLocalAuth: jest.fn().mockResolvedValue(undefined),+ attachDomainEvents: jest.fn(),+ } as unknown as WwebjsLifecycleHost;+ await new WwebjsLifecycle(host).initialize();+ };++ beforeEach(() => {+ logger = { log: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn() };+ problem.mockReset().mockReturnValue(undefined);+ unapplied.mockReset().mockReturnValue([]);+ unappliedText.mockReset().mockReturnValue('patch text');+ clientInitSpy = jest+ .spyOn(Client.prototype as unknown as { initialize: () => Promise<void> }, 'initialize')+ .mockResolvedValue(undefined);+ });++ afterEach(() => {+ clientInitSpy.mockRestore();+ });++ it('logs the message-id backport problem as an error', async () => {+ problem.mockReturnValue('the backport is missing');++ await initialize();++ expect(logger.error).toHaveBeenCalledWith('the backport is missing');+ });++ it('logs the patches that did not land as an error', async () => {+ unapplied.mockReturnValue(['status']);+ unappliedText.mockReturnValue('the status patch is not applied');++ await initialize();++ expect(unappliedText).toHaveBeenCalledWith('wwebjs', ['status']);+ expect(logger.error).toHaveBeenCalledWith('the status patch is not applied');+ });++ it('says nothing when every patch landed', async () => {+ await initialize();++ expect(logger.error).not.toHaveBeenCalled();+ });+});