Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

test(message): pin the write lifetime guards of a single send

Yudhi Armyndharis8901c8f309f7
diff --git a/src/modules/message/message-send-pacing.spec.ts b/src/modules/message/message-send-pacing.spec.ts
index 2725c34b4..2ace1a49c 100644
--- a/src/modules/message/message-send-pacing.spec.ts
+++ b/src/modules/message/message-send-pacing.spec.ts
@@ -351,6 +351,55 @@ describe('MessageSendService preparation pacing', () => {
expect(engine.sendTextMessage).toHaveBeenCalledTimes(1);
});
+ // The delete transaction must not start while the insert of a pending row is in flight: the row would
+ // land after the delete, for a session that no longer exists and with nothing left to settle it.
+ it('drains its pending insert before the session content is deleted', async () => {
+ const entered = deferred();
+ const finish = deferred();
+ const save = messages.save.bind(messages);
+ jest.spyOn(messages, 'save').mockImplementationOnce(async message => {
+ entered.resolve();
+ await finish.promise;
+ return save(message);
+ });
+ const old = send().catch((error: unknown) => error);
+ await entered.promise;
+ let deleted = false;
+ const deletion = replaceSession().then(() => {
+ deleted = true;
+ });
+ await new Promise<void>(setImmediate);
+ const deletedBeforeInsert = deleted;
+ finish.resolve();
+ await Promise.all([deletion, old]);
+
+ expect(deletedBeforeInsert).toBe(false);
+ expect(await old).toMatchObject({ status: 404 });
+ expect(await messages.count()).toBe(0);
+ });
+
+ // Told apart by the status the caller gets: a deleted session is a 404, where continuing to the engine
+ // lookup would answer a 400 telling them to start a session that is gone.
+ it('answers 404, not a missing engine, when its session is deleted during the sending hook', async () => {
+ const entered = deferred();
+ const finish = deferred();
+ hooks.register('moderation', 'message:sending', async context => {
+ entered.resolve();
+ await finish.promise;
+ return { continue: true, data: context.data };
+ });
+ const old = send().catch((error: unknown) => error);
+ await entered.promise;
+ const deletion = closeSessionWrites(ds, 's1');
+ engines.delete('s1');
+ await deletion.drain();
+ deletion.release();
+ finish.resolve();
+
+ expect(await old).toMatchObject({ status: 404 });
+ expect(engine.sendTextMessage).not.toHaveBeenCalled();
+ });
+
it('cannot dispatch or settle successfully after its pending write lifetime retires', async () => {
const entered = deferred();
const finish = deferred();
diff --git a/src/modules/message/message-send.service.spec.ts b/src/modules/message/message-send.service.spec.ts
index 3fd7441c1..282b03d86 100644
--- a/src/modules/message/message-send.service.spec.ts
+++ b/src/modules/message/message-send.service.spec.ts
@@ -22,6 +22,10 @@ import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error'
import { SendIdempotencyKey } from './entities/send-idempotency-key.entity';
import { SendIdempotencyService } from './idempotency/send-idempotency.service';
import { SendIdempotencyInterceptor } from './idempotency/send-idempotency.interceptor';
+import * as sessionWriteScope from '../../common/utils/session-write-scope';
+
+// The real function, held before any test spies on the module export.
+const realCaptureSessionWrites = sessionWriteScope.captureSessionWrites;
/** Pacing is off by default in these tests; the governor's own spec covers its behaviour. */
const inertPacing = (): SendPacingService =>
@@ -355,6 +359,36 @@ describe('MessageSendService', () => {
expect(calls[1][1]).toMatchObject({ message: { status: MessageStatus.FAILED } });
});
+ // The row went with its session between the PENDING insert and this write: a provider must not be
+ // handed a terminal state for a row that no longer exists, or it would index a ghost document.
+ it.each([
+ [
+ 'FAILED',
+ async () => {
+ mockEngine.sendTextMessage.mockRejectedValueOnce(new Error('engine down'));
+ await expect(service.sendText('sess-1', { chatId: '[email protected]', text: 'hi' })).rejects.toThrow();
+ },
+ ],
+ [
+ 'SENT',
+ async () => {
+ await expect(service.sendText('sess-1', { chatId: '[email protected]', text: 'hi' })).resolves.toMatchObject({
+ messageId: 'wa-msg-1',
+ });
+ },
+ ],
+ ])('does not re-emit message:persisted with %s when the update matched no row', async (_state, run) => {
+ (repository.update as jest.Mock).mockResolvedValueOnce({ affected: 0 });
+
+ await run();
+
+ const calls = (hookManager.execute as jest.Mock).mock.calls.filter(
+ ([ev]: unknown[]) => ev === 'message:persisted',
+ ) as unknown[][];
+ expect(calls).toHaveLength(1);
+ expect(calls[0][1]).toMatchObject({ message: { status: MessageStatus.PENDING } });
+ });
+
it('logs an engine-side send failure with the session, chat and type', async () => {
const warn = jest.spyOn(
(service as unknown as { logger: { warn: (...args: unknown[]) => void } }).logger,
@@ -836,6 +870,13 @@ describe('MessageSendService', () => {
expect(media?.data).toBeUndefined();
expect(media?.mimetype).toBe('image/png');
expect(media?.filename).toBe('pic.png');
+ // `saved` is the entity handed to save() and mutated afterwards, so it proves nothing about what
+ // was written: the UPDATE is what has to carry the stripped metadata.
+ const [, patch] = (repository.update as jest.Mock).mock.calls.at(-1) as [unknown, Record<string, unknown>];
+ expect(patch).toEqual({
+ status: MessageStatus.FAILED,
+ metadata: { media: { mimetype: 'image/png', filename: 'pic.png' } },
+ });
});
});
@@ -1547,6 +1588,57 @@ describe('MessageSendService', () => {
expect(release).toHaveBeenCalledTimes(1);
expect(release).toHaveBeenCalledWith(true);
});
+
+ // Retiring a session settles every admission whose send still holds a subscription. A send that has
+ // finished must hold none, or each one leaves a closure in the session's generation for good.
+ it('leaves no retire subscription behind once the send settles', async () => {
+ await service.sendText('sess-1', { chatId: '[email protected]', text: 'hi' });
+ expect(release).toHaveBeenCalledTimes(1);
+
+ sessionWriteScope.closeSessionWrites(repository, 'sess-1').release();
+
+ expect(release).toHaveBeenCalledTimes(1);
+ });
+ });
+
+ describe('write scopes', () => {
+ afterEach(() => jest.restoreAllMocks());
+
+ const closeSpies = () => {
+ const closes: jest.SpyInstance[] = [];
+ jest.spyOn(sessionWriteScope, 'captureSessionWrites').mockImplementation((...args) => {
+ const scope = realCaptureSessionWrites(...args);
+ closes.push(jest.spyOn(scope, 'close'));
+ return scope;
+ });
+ return closes;
+ };
+
+ // Left open, a scope keeps its session's write state from ever being released.
+ it('closes the scope a direct row save captures for itself', async () => {
+ const closes = closeSpies();
+
+ await service.saveOutgoingMessage('sess-1', { chatId: '[email protected]', type: 'text', body: 'x' });
+
+ expect(closes).toHaveLength(1);
+ expect(closes[0]).toHaveBeenCalled();
+ });
+
+ it.each([
+ ['succeeds', () => undefined],
+ [
+ 'is refused by the engine',
+ () => mockEngine.sendTextMessage.mockRejectedValueOnce(new BadRequestException('refused')),
+ ],
+ ])('closes the scope of a send that %s', async (_outcome, arrange) => {
+ const closes = closeSpies();
+ arrange();
+
+ await service.sendText('sess-1', { chatId: '[email protected]', text: 'hi' }).catch(() => undefined);
+
+ expect(closes).toHaveLength(1);
+ expect(closes[0]).toHaveBeenCalled();
+ });
});
// ── buildMediaInput (via sendImage) ───────────────────────────────
@@ -1925,6 +2017,16 @@ describe('MessageSendService', () => {
expect(archive.archive).not.toHaveBeenCalled();
});
+ it('archives nothing for a SENT update that matched no row, whose row went with its session', async () => {
+ const archive = { archive: jest.fn() };
+ const svc = withFlag(true, archive);
+ (repository.update as jest.Mock).mockResolvedValueOnce({ affected: 0 });
+
+ await svc.sendImage('sess-1', { chatId: '[email protected]', base64: 'QUJD', mimetype: 'image/png' });
+
+ expect(archive.archive).not.toHaveBeenCalled();
+ });
+
it('never archives a PENDING row — the merge may delete it and the reaper may rewrite it', async () => {
const archive = { archive: jest.fn() };
const svc = withFlag(true, archive);
diff --git a/src/modules/status-store/status-store.service.spec.ts b/src/modules/status-store/status-store.service.spec.ts
index 6288464f9..da67981f0 100644
--- a/src/modules/status-store/status-store.service.spec.ts
+++ b/src/modules/status-store/status-store.service.spec.ts
@@ -81,6 +81,33 @@ describe('StatusStoreService (ingest / list / getMedia)', () => {
expect(stored).toEqual(['dup', 'other']);
});
+ // Left open, the scope an ingest captures for itself keeps its session's write state from ever being released.
+ it('closes the scope it captures for itself, for a new status and for one already stored', async () => {
+ const closes: jest.SpyInstance[] = [];
+ const capture = service.captureWrites.bind(service);
+ const spy = jest.spyOn(service, 'captureWrites').mockImplementation(sessionId => {
+ const scope = capture(sessionId);
+ closes.push(jest.spyOn(scope, 'close'));
+ return scope;
+ });
+ const status = {
+ waStatusId: 'scope-close',
+ contactJid: '[email protected]',
+ type: 'text' as const,
+ caption: 'hi',
+ postedAt: Date.now(),
+ };
+ try {
+ expect((await service.ingest('sess-scope', status)).created).toBe(true);
+ expect((await service.ingest('sess-scope', status)).created).toBe(false);
+ } finally {
+ spy.mockRestore();
+ }
+
+ expect(closes).toHaveLength(2);
+ for (const close of closes) expect(close).toHaveBeenCalled();
+ });
+
it('ingest writes a text row with expiresAt = postedAt + 24h, flagged as created', async () => {
const postedAt = Date.now();
const { row, created } = await service.ingest('sess', {