Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(message): re-validate rendered bulk payloads and make batch cancellation terminal (#955)

Yudhi Armyndharisf3fba8d9244f
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index aaa7bac63..0d6c7811c 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -1387,13 +1387,15 @@ Send messages to multiple recipients as an async batch — returns immediately a
| Field | Type | Required | Constraints | Description |
| --- | --- | --- | --- | --- |
| batchId | string | No | string | Auto-generated `batch_<hex>` if omitted; a duplicate id returns `400` |
-| messages | BulkMessageItemDto[] | Yes | array, max 100, nested-validated | The batch items (see below) |
+| messages | BulkMessageItemDto[] | Yes | array, max 100, nested-validated | The batch items (see below); duplicate `chatId`s are collapsed before processing — first occurrence wins, order preserved |
| options | BulkMessageOptionsDto | No | nested-validated | Pacing/error options (see below) |
Each `BulkMessageItemDto`: `{ chatId: string, type: 'text'|'image'|'video'|'audio'|'document', content: BulkMessageContentDto, variables?: Record<string,string> }`. `content` (all fields optional, nested-validated): `text?: string`, `image?`/`video?`/`audio?`/`document?`: `{ url?, base64?, mimetype?, filename? }`, `caption?: string`.
`BulkMessageOptionsDto`: `{ delayBetweenMessages?: number (1000–60000, default 3000), randomizeDelay?: boolean (default true), stopOnError?: boolean (default false) }`.
+Each item's base64 media is checked against the media byte cap (`MEDIA_DOWNLOAD_MAX_BYTES`) twice: at batch creation, and again per item after `variables` and the `message:sending` plugin gate are applied. An item that outgrows the cap only after rendering fails individually (`failed` in `results`, with `message:failed` fired) instead of being sent. `totalMessages` in the response reflects the de-duplicated item count.
+
```json
{
"messages": [
diff --git a/docs/07-api-collection.md b/docs/07-api-collection.md
index ab7e44126..36017f98f 100644
--- a/docs/07-api-collection.md
+++ b/docs/07-api-collection.md
@@ -399,7 +399,7 @@ curl -X POST "$BASE/api/sessions/my-session/messages/delete" \
#### POST /api/sessions/:sessionId/messages/send-bulk
-Send to multiple recipients as an async batch (max 100 messages).
+Send to multiple recipients as an async batch (max 100 messages; duplicate `chatId`s are collapsed — first occurrence wins).
```bash
curl -X POST "$BASE/api/sessions/my-session/messages/send-bulk" \
diff --git a/openapi.json b/openapi.json
index 3da9d509c..9699399a7 100644
--- a/openapi.json
+++ b/openapi.json
@@ -7140,7 +7140,7 @@
"description": "Custom batch ID (auto-generated if not provided)"
},
"messages": {
- "description": "Array of messages (max 100 per request)",
+ "description": "Array of messages (max 100 per request; duplicate chatIds are collapsed — first occurrence wins)",
"type": "array",
"items": {
"$ref": "#/components/schemas/BulkMessageItemDto"
diff --git a/src/modules/message/bulk-message.service.spec.ts b/src/modules/message/bulk-message.service.spec.ts
index 2d88e05bf..936ae8eaf 100644
--- a/src/modules/message/bulk-message.service.spec.ts
+++ b/src/modules/message/bulk-message.service.spec.ts
@@ -1,8 +1,9 @@
import { Test, TestingModule } from '@nestjs/testing';
import { PayloadTooLargeException } from '@nestjs/common';
import { getRepositoryToken } from '@nestjs/typeorm';
+import { In, Not } from 'typeorm';
import { BulkMessageService, resolveFinalBatchStatus, sanitizeBatchError } from './bulk-message.service';
-import { MessageBatch, BatchStatus } from './entities/message-batch.entity';
+import { MessageBatch, BatchStatus, BatchMessageStatus, BatchMessageResult } from './entities/message-batch.entity';
import { MessageStatus } from './entities/message.entity';
import { SendBulkMessageDto } from './dto/bulk-message.dto';
import { SessionService } from '../session/session.service';
@@ -99,7 +100,7 @@ describe('sanitizeBatchError', () => {
describe('BulkMessageService.processBatch', () => {
let service: BulkMessageService;
- let repo: { findOne: jest.Mock; save: jest.Mock };
+ let repo: { findOne: jest.Mock; save: jest.Mock; update: jest.Mock };
let messageService: { saveOutgoingMessage: jest.Mock };
let engine: {
sendTextMessage: jest.Mock;
@@ -137,7 +138,12 @@ describe('BulkMessageService.processBatch', () => {
hookManager = {
execute: jest.fn().mockImplementation((_e: string, data: unknown) => Promise.resolve({ continue: true, data })),
};
- repo = { findOne: jest.fn(), save: jest.fn().mockImplementation(b => Promise.resolve(b)) };
+ repo = {
+ findOne: jest.fn(),
+ save: jest.fn().mockImplementation(b => Promise.resolve(b)),
+ // Guarded status writes: default to "the row matched" (1 affected), as when no cancel committed.
+ update: jest.fn().mockResolvedValue({ affected: 1 }),
+ };
const module: TestingModule = await Test.createTestingModule({
providers: [
BulkMessageService,
@@ -182,7 +188,7 @@ describe('BulkMessageService.processBatch', () => {
it('releases the in-flight marker when processing throws (no processingBatches leak)', async () => {
repo.findOne.mockResolvedValue(makeBatch(1));
- repo.save.mockRejectedValueOnce(new Error('db down')); // the first save (→ PROCESSING) throws
+ repo.update.mockRejectedValueOnce(new Error('db down')); // the first guarded write (→ PROCESSING) throws
await runProcessBatch().catch(() => undefined);
@@ -298,9 +304,12 @@ describe('BulkMessageService.processBatch', () => {
);
// A completed batch is terminal (never resumed), so the persisted message_batches.messages must not
- // retain the (often multi-MB) base64 — only the descriptive fields are kept.
- const savedBatch = (repo.save.mock.calls as [MessageBatch][]).at(-1)![0];
- const img = (savedBatch.messages[0].content as { image?: { base64?: unknown; mimetype?: string } }).image;
+ // retain the (often multi-MB) base64 — only the descriptive fields are kept. The terminal write is
+ // the last guarded UPDATE (start transition and cadence writes carry no messages payload).
+ const finalPartial = (repo.update.mock.calls as Array<[unknown, { messages: MessageBatch['messages'] }]>).at(
+ -1,
+ )![1];
+ const img = (finalPartial.messages[0].content as { image?: { base64?: unknown; mimetype?: string } }).image;
expect(img?.base64).toBeUndefined();
expect(img?.mimetype).toBe('image/png');
});
@@ -343,26 +352,94 @@ describe('BulkMessageService.processBatch', () => {
});
it('stops sending when the batch is cancelled in the DB by another instance/restart', async () => {
- // First load is the running batch; the cadence re-read reports a CANCELLED status.
- repo.findOne.mockResolvedValueOnce(makeBatch(3)).mockResolvedValue({ status: BatchStatus.CANCELLED });
+ repo.findOne.mockResolvedValue(makeBatch(3));
+ repo.update
+ .mockResolvedValueOnce({ affected: 1 }) // start transition → PROCESSING
+ .mockResolvedValueOnce({ affected: 0 }) // cadence write at i=0 loses to the committed CANCELLED
+ .mockResolvedValue({ affected: 1 });
await runProcessBatch();
- // Only the first message (before the cadence re-read saw CANCELLED) was sent.
+ // Only the first message (before the guarded cadence write saw the cancel) was sent.
expect(engine.sendTextMessage).toHaveBeenCalledTimes(1);
+ // The terminal write persists CANCELLED with reconciled counters — never a PROCESSING rewrite.
+ const savedBatch = (repo.save.mock.calls as [MessageBatch][]).at(-1)![0];
+ expect(savedBatch.status).toBe(BatchStatus.CANCELLED);
+ });
+
+ it('sends nothing when the batch row is already CANCELLED at pickup (cancel-before-start)', async () => {
+ const batch = makeBatch(3);
+ batch.status = BatchStatus.CANCELLED; // cancelBatch committed before this process picked the batch up
+ repo.findOne.mockResolvedValue(batch);
+
+ await runProcessBatch();
+
+ expect(engine.sendTextMessage).not.toHaveBeenCalled();
+ expect(repo.update).not.toHaveBeenCalled(); // no PROCESSING transition is even attempted
+ expect(repo.save).not.toHaveBeenCalled();
+ });
+
+ it('sends nothing when the in-memory cancel flag was set before pickup (same-process cancel-before-start)', async () => {
+ repo.findOne.mockResolvedValue(makeBatch(3));
+ inFlightMarkers().set('b1', false); // cancelBatch ran before processBatch got to the batch
+
+ await runProcessBatch();
+
+ expect(engine.sendTextMessage).not.toHaveBeenCalled();
+ expect(repo.update).not.toHaveBeenCalled();
+ expect(inFlightMarkers().has('b1')).toBe(false); // marker still released
+ });
+
+ it('sends nothing when a cancel commits between pickup and the guarded start transition', async () => {
+ repo.findOne.mockResolvedValue(makeBatch(3));
+ repo.update.mockResolvedValueOnce({ affected: 0 }); // CANCELLED won the race to the first write
+
+ await runProcessBatch();
+
+ expect(engine.sendTextMessage).not.toHaveBeenCalled();
+ expect(repo.update).toHaveBeenCalledTimes(1); // the guarded start transition only
+ expect(repo.update).toHaveBeenCalledWith(
+ { id: 'b1', status: Not(BatchStatus.CANCELLED) },
+ expect.objectContaining({ status: BatchStatus.PROCESSING }),
+ );
+ expect(repo.save).not.toHaveBeenCalled(); // nothing is written after losing to the cancel
+ });
+
+ it('stops after the in-flight item when cancelled mid-batch, and no write resurrects the batch', async () => {
+ repo.findOne.mockResolvedValue(makeBatch(3));
+ engine.sendTextMessage.mockImplementationOnce(() => {
+ inFlightMarkers().set('b1', false); // cancelBatch lands while the first send is in flight
+ return Promise.resolve({ id: 'wa1', timestamp: 111 });
+ });
+
+ await runProcessBatch();
+
+ expect(engine.sendTextMessage).toHaveBeenCalledTimes(1); // the remaining two items were not sent
+ const savedBatch = (repo.save.mock.calls as [MessageBatch][]).at(-1)![0];
+ expect(savedBatch.status).toBe(BatchStatus.CANCELLED);
+ // No guarded write ever carried a non-cancelled terminal status back to the row.
+ for (const [, partial] of repo.update.mock.calls as Array<[unknown, { status?: BatchStatus }]>) {
+ expect(partial.status).not.toBe(BatchStatus.COMPLETED);
+ expect(partial.status).not.toBe(BatchStatus.FAILED);
+ }
});
- it('does not clobber a CANCELLED that landed after the last cadence read (final status stays CANCELLED)', async () => {
+ it('does not clobber a CANCELLED that landed after the last guarded write (final write is guarded too)', async () => {
const batch = makeBatch(1);
repo.findOne
.mockResolvedValueOnce(batch) // processBatch initial load
- .mockResolvedValueOnce(batch) // cadence re-read (i=0) — still PROCESSING
- .mockResolvedValue({ status: BatchStatus.CANCELLED }); // FINAL pre-save re-read — cancel landed late
+ .mockResolvedValueOnce({ status: BatchStatus.PROCESSING }); // pre-final re-read — cancel not visible yet
+ repo.update
+ .mockResolvedValueOnce({ affected: 1 }) // start transition → PROCESSING
+ .mockResolvedValueOnce({ affected: 1 }) // cadence write (i=0, also the last item)
+ .mockResolvedValueOnce({ affected: 0 }); // final write loses the race to a committed CANCELLED
await runProcessBatch();
- const savedStatuses = (repo.save.mock.calls as [MessageBatch][]).map(c => c[0].status);
- expect(savedStatuses[savedStatuses.length - 1]).toBe(BatchStatus.CANCELLED);
+ expect(batch.status).toBe(BatchStatus.CANCELLED); // terminal state follows the DB, not the runner
+ expect(repo.save).not.toHaveBeenCalled(); // no unguarded terminal write happened
+ const finalCriteria = (repo.update.mock.calls as Array<[unknown, unknown]>).at(-1)![0];
+ expect(finalCriteria).toEqual({ id: 'b1', status: Not(BatchStatus.CANCELLED) });
});
it('substitutes canonical {{name}} placeholders in bulk content', async () => {
@@ -386,11 +463,80 @@ describe('BulkMessageService.processBatch', () => {
expect(engine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'Hi Sam');
});
+
+ it('fails an item whose rendered variables grow its base64 media past the cap (no send, explicit failure)', async () => {
+ process.env.MEDIA_DOWNLOAD_MAX_BYTES = '16';
+ try {
+ engine.sendImageMessage = jest.fn().mockResolvedValue({ id: 'waimg', timestamp: 222 });
+ const batch = makeBatch(1);
+ // The raw placeholder passes the create-time cap check; the rendered value does not.
+ batch.messages = [
+ {
+ chatId: '[email protected]',
+ type: 'image',
+ content: { image: { base64: '{{payload}}', mimetype: 'image/png' } },
+ variables: { payload: Buffer.alloc(32).toString('base64') },
+ },
+ ];
+ repo.findOne.mockResolvedValue(batch);
+
+ await runProcessBatch();
+
+ expect(engine.sendImageMessage).not.toHaveBeenCalled(); // the oversized media was NOT sent
+ const failedCall = (
+ hookManager.execute.mock.calls as Array<[string, { type: string; error: string }, unknown]>
+ ).find(([event]) => event === 'message:failed');
+ expect(failedCall?.[1].type).toBe('image');
+ expect(failedCall?.[1].error).toContain('exceeds the maximum allowed size');
+ const finalPartial = (
+ repo.update.mock.calls as Array<[unknown, { status: BatchStatus; results: BatchMessageResult[] }]>
+ ).at(-1)![1];
+ expect(finalPartial.status).toBe(BatchStatus.FAILED); // the only item failed → batch FAILED
+ expect(finalPartial.results[0].status).toBe(BatchMessageStatus.FAILED);
+ expect(finalPartial.results[0].error?.message).toContain('exceeds the maximum allowed size');
+ } finally {
+ delete process.env.MEDIA_DOWNLOAD_MAX_BYTES;
+ }
+ });
+
+ it('fails an item the message:sending gate rewrote past the media cap (gate output is re-validated)', async () => {
+ process.env.MEDIA_DOWNLOAD_MAX_BYTES = '16';
+ try {
+ engine.sendImageMessage = jest.fn().mockResolvedValue({ id: 'waimg', timestamp: 222 });
+ const batch = makeBatch(1);
+ batch.messages = [
+ {
+ chatId: '[email protected]',
+ type: 'image',
+ content: { image: { base64: Buffer.alloc(4).toString('base64'), mimetype: 'image/png' } },
+ },
+ ];
+ repo.findOne.mockResolvedValue(batch);
+ // The gate allows the send but swaps in a payload that exceeds the cap.
+ hookManager.execute.mockImplementationOnce(() =>
+ Promise.resolve({
+ continue: true,
+ data: { input: { image: { base64: Buffer.alloc(32).toString('base64'), mimetype: 'image/png' } } },
+ }),
+ );
+
+ await runProcessBatch();
+
+ expect(engine.sendImageMessage).not.toHaveBeenCalled();
+ const finalPartial = (
+ repo.update.mock.calls as Array<[unknown, { status: BatchStatus; results: BatchMessageResult[] }]>
+ ).at(-1)![1];
+ expect(finalPartial.results[0].status).toBe(BatchMessageStatus.FAILED);
+ expect(finalPartial.results[0].error?.message).toContain('exceeds the maximum allowed size');
+ } finally {
+ delete process.env.MEDIA_DOWNLOAD_MAX_BYTES;
+ }
+ });
});
describe('BulkMessageService.cancelBatch', () => {
let service: BulkMessageService;
- let repo: { findOne: jest.Mock; save: jest.Mock };
+ let repo: { findOne: jest.Mock; save: jest.Mock; update: jest.Mock };
const batchWithStatus = (status: BatchStatus): MessageBatch =>
({
@@ -405,7 +551,11 @@ describe('BulkMessageService.cancelBatch', () => {
}) as unknown as MessageBatch;
beforeEach(async () => {
- repo = { findOne: jest.fn(), save: jest.fn().mockImplementation(b => Promise.resolve(b)) };
+ repo = {
+ findOne: jest.fn(),
+ save: jest.fn().mockImplementation(b => Promise.resolve(b)),
+ update: jest.fn().mockResolvedValue({ affected: 1 }),
+ };
const module: TestingModule = await Test.createTestingModule({
providers: [
BulkMessageService,
@@ -424,19 +574,19 @@ describe('BulkMessageService.cancelBatch', () => {
// events that already fired. FAILED is terminal, like COMPLETED/CANCELLED.
repo.findOne.mockResolvedValue(batchWithStatus(BatchStatus.FAILED));
await expect(service.cancelBatch('s1', 'bx')).rejects.toThrow(/already failed/i);
- expect(repo.save).not.toHaveBeenCalled();
+ expect(repo.update).not.toHaveBeenCalled();
});
it('rejects a cancel on an already-COMPLETED batch', async () => {
repo.findOne.mockResolvedValue(batchWithStatus(BatchStatus.COMPLETED));
await expect(service.cancelBatch('s1', 'bx')).rejects.toThrow(/already completed/i);
- expect(repo.save).not.toHaveBeenCalled();
+ expect(repo.update).not.toHaveBeenCalled();
});
it('rejects a cancel on an already-CANCELLED batch', async () => {
repo.findOne.mockResolvedValue(batchWithStatus(BatchStatus.CANCELLED));
await expect(service.cancelBatch('s1', 'bx')).rejects.toThrow(/already cancelled/i);
- expect(repo.save).not.toHaveBeenCalled();
+ expect(repo.update).not.toHaveBeenCalled();
});
it('cancels a PENDING batch (the supported case) and moves pending items to cancelled', async () => {
@@ -446,25 +596,44 @@ describe('BulkMessageService.cancelBatch', () => {
expect(result.status).toBe(BatchStatus.CANCELLED);
expect(result.progress.cancelled).toBe(2);
expect(result.progress.pending).toBe(0);
+ // The write is guarded to the non-terminal statuses inside the UPDATE itself.
+ expect(repo.update).toHaveBeenCalledWith(
+ { id: 'b1', status: In([BatchStatus.PENDING, BatchStatus.PROCESSING]) },
+ expect.objectContaining({ status: BatchStatus.CANCELLED }),
+ );
+ });
+
+ it('rejects when the batch turns terminal between the read and the guarded write (no relabelling)', async () => {
+ repo.findOne
+ .mockResolvedValueOnce(batchWithStatus(BatchStatus.PROCESSING)) // upfront read — still running
+ .mockResolvedValueOnce({ status: BatchStatus.COMPLETED }); // re-read after the write matched nothing
+ repo.update.mockResolvedValueOnce({ affected: 0 }); // the batch completed in between
+
+ await expect(service.cancelBatch('s1', 'bx')).rejects.toThrow(/already completed/i);
});
});
describe('BulkMessageService.createBatch base64 media cap', () => {
let service: BulkMessageService;
- let repo: { findOne: jest.Mock; save: jest.Mock; create: jest.Mock };
+ let repo: { findOne: jest.Mock; save: jest.Mock; create: jest.Mock; update: jest.Mock };
+ let sessionService: { getEngine: jest.Mock };
+ let messageService: { saveOutgoingMessage: jest.Mock };
beforeEach(async () => {
repo = {
findOne: jest.fn().mockResolvedValue(undefined),
save: jest.fn().mockImplementation(b => Promise.resolve(b)),
- create: jest.fn().mockImplementation((b: MessageBatch) => b),
+ create: jest.fn().mockImplementation((b: MessageBatch) => Object.assign({ id: 'b1' }, b)),
+ update: jest.fn().mockResolvedValue({ affected: 1 }),
};
+ sessionService = { getEngine: jest.fn().mockReturnValue({}) };
+ messageService = { saveOutgoingMessage: jest.fn().mockResolvedValue(undefined) };
const module: TestingModule = await Test.createTestingModule({
providers: [
BulkMessageService,
{ provide: getRepositoryToken(MessageBatch, 'data'), useValue: repo },
- { provide: SessionService, useValue: { getEngine: jest.fn().mockReturnValue({}) } },
- { provide: MessageService, useValue: { saveOutgoingMessage: jest.fn() } },
+ { provide: SessionService, useValue: sessionService },
+ { provide: MessageService, useValue: messageService },
{
provide: HookManager,
useValue: {
@@ -564,4 +733,44 @@ describe('BulkMessageService.createBatch base64 media cap', () => {
expect(repo.findOne).toHaveBeenCalledWith({ where: { batchId: 'dup', sessionId: 's2' } });
});
+
+ it('collapses duplicate chatIds before persisting (first occurrence wins, order preserved)', async () => {
+ const dto = {
+ messages: [
+ { chatId: '[email protected]', type: 'text' as const, content: { text: 'first' } },
+ { chatId: '[email protected]', type: 'text' as const, content: { text: 'second' } },
+ { chatId: '[email protected]', type: 'text' as const, content: { text: 'duplicate — dropped' } },
+ ],
+ } as unknown as SendBulkMessageDto;
+
+ const batch = await service.createBatch('s1', dto);
+
+ expect(batch.messages.map(m => m.chatId)).toEqual(['[email protected]', '[email protected]']);
+ expect(batch.messages[0].content).toEqual({ text: 'first' }); // the first entry for an id wins
+ expect(batch.progress.total).toBe(2);
+ expect(batch.progress.pending).toBe(2);
+ });
+
+ it('runs the engine once per unique chatId across the full create→process path', async () => {
+ const engine = { sendTextMessage: jest.fn().mockResolvedValue({ id: 'wa', timestamp: 1 }) };
+ sessionService.getEngine.mockReturnValue(engine);
+ const dto = {
+ messages: [
+ { chatId: '[email protected]', type: 'text' as const, content: { text: 'first' } },
+ { chatId: '[email protected]', type: 'text' as const, content: { text: 'second' } },
+ { chatId: '[email protected]', type: 'text' as const, content: { text: 'duplicate — dropped' } },
+ ],
+ options: { delayBetweenMessages: 0, randomizeDelay: false, stopOnError: false },
+ } as unknown as SendBulkMessageDto;
+
+ const batch = await service.createBatch('s1', dto);
+ // createBatch's own fire-and-forget processBatch saw no persisted row (findOne → undefined);
+ // drive the processing explicitly with the created batch now "in the DB".
+ repo.findOne.mockResolvedValue(batch);
+ await (service as unknown as { processBatch: (id: string) => Promise<void> }).processBatch(batch.id);
+
+ expect(engine.sendTextMessage).toHaveBeenCalledTimes(2);
+ expect(engine.sendTextMessage).toHaveBeenNthCalledWith(1, '[email protected]', 'first');
+ expect(engine.sendTextMessage).toHaveBeenNthCalledWith(2, '[email protected]', 'second');
+ });
});
diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.ts
index 1efda562d..5401a5db0 100644
--- a/src/modules/message/bulk-message.service.ts
+++ b/src/modules/message/bulk-message.service.ts
@@ -1,6 +1,6 @@
import { Injectable, Logger, BadRequestException, NotFoundException, OnApplicationBootstrap } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
-import { Repository } from 'typeorm';
+import { In, Not, QueryDeepPartialEntity, Repository } from 'typeorm';
import { randomUUID } from 'crypto';
import {
MessageBatch,
@@ -112,17 +112,23 @@ export class BulkMessageService implements OnApplicationBootstrap {
throw new BadRequestException(`Session '${sessionId}' is not active`);
}
+ // Collapse duplicate chatIds — first occurrence wins, order preserved — so a recipient gets at
+ // most one message per batch. Repeats would only re-run the engine (and the moderation gate)
+ // for an id already covered by the first entry.
+ const seenChatIds = new Set<string>();
+ const messages: SendBulkMessageDto['messages'] = [];
+ for (const message of dto.messages) {
+ if (seenChatIds.has(message.chatId)) continue;
+ seenChatIds.add(message.chatId);
+ messages.push(message);
+ }
+
// Bound every outbound base64 blob to the media byte cap before the whole messages array (with
// its base64 payloads) is persisted into the batch row. Mirrors the single-send cap in
- // MessageService.buildMediaInput.
- for (const { content } of dto.messages) {
- for (const media of [content?.image, content?.video, content?.audio, content?.document]) {
- const base64 = stripBase64DataUri(media?.base64);
- if (media?.base64 !== undefined && !base64 && !media.url) {
- throw new BadRequestException('Either url or base64 must be provided for bulk media');
- }
- assertBase64WithinMediaCap(base64);
- }
+ // MessageService.buildMediaInput. The same check runs again per item after variables and the
+ // message:sending gate are applied (see executeBatch).
+ for (const { content } of messages) {
+ this.assertContentMediaWithinCap(content);
}
const batchId = dto.batchId || `batch_${randomUUID().split('-')[0]}`;
@@ -148,10 +154,10 @@ export class BulkMessageService implements OnApplicationBootstrap {
};
const progress: BatchProgress = {
- total: dto.messages.length,
+ total: messages.length,
sent: 0,
failed: 0,
- pending: dto.messages.length,
+ pending: messages.length,
cancelled: 0,
};
@@ -159,7 +165,7 @@ export class BulkMessageService implements OnApplicationBootstrap {
batchId,
sessionId,
status: BatchStatus.PENDING,
- messages: dto.messages as MessageBatch['messages'],
+ messages: messages as MessageBatch['messages'],
options,
progress,
results: [],
@@ -175,7 +181,12 @@ export class BulkMessageService implements OnApplicationBootstrap {
this.inFlightBatches--;
throw error;
}
- this.logger.log(`Created batch ${batchId} with ${dto.messages.length} messages`);
+ this.logger.log(
+ `Created batch ${batchId} with ${messages.length} messages` +
+ (messages.length === dto.messages.length
+ ? ''
+ : ` (${dto.messages.length - messages.length} duplicate chatId entr${dto.messages.length - messages.length === 1 ? 'y' : 'ies'} dropped)`),
+ );
// Start processing asynchronously
this.processBatch(batch.id, true).catch(err => {
@@ -220,14 +231,28 @@ export class BulkMessageService implements OnApplicationBootstrap {
// Signal cancellation
this.processingBatches.set(batch.id, false);
- // Update status
+ // Update status — guarded to the non-terminal statuses IN the UPDATE, so a batch that reached a
+ // terminal state between the read above and this write is not relabelled CANCELLED after the
+ // fact (same exclusivity the upfront check enforces, but race-safe).
batch.status = BatchStatus.CANCELLED;
batch.progress.cancelled = batch.progress.pending;
batch.progress.pending = 0;
batch.completedAt = new Date();
this.stripBatchMediaPayloads(batch.messages);
- await this.batchRepository.save(batch);
+ const cancelledRows = await this.batchRepository.update(
+ { id: batch.id, status: In([BatchStatus.PENDING, BatchStatus.PROCESSING]) },
+ {
+ status: batch.status,
+ progress: batch.progress,
+ completedAt: batch.completedAt,
+ messages: batch.messages,
+ } as QueryDeepPartialEntity<MessageBatch>,
+ );
+ if (!cancelledRows.affected) {
+ const fresh = await this.batchRepository.findOne({ where: { id: batch.id }, select: { status: true } });
+ throw new BadRequestException(`Batch '${batchId}' is already ${fresh?.status ?? 'gone'}`);
+ }
this.logger.log(`Cancelled batch ${batchId}`);
return batch;
@@ -240,6 +265,13 @@ export class BulkMessageService implements OnApplicationBootstrap {
try {
batch = await this.batchRepository.findOne({ where: { id: batchDbId } });
if (!batch) return;
+ // A cancel that landed before this run picked the batch up must not be revived — neither the
+ // in-memory flag nor a persisted CANCELLED may be flipped back. The guarded status UPDATE in
+ // executeBatch closes the remaining race (a cancel committing after this read).
+ if (this.processingBatches.get(batch.id) === false || batch.status === BatchStatus.CANCELLED) {
+ this.logger.log(`Batch ${batch.batchId} was cancelled before processing started; nothing was sent`);
+ return;
+ }
this.processingBatches.set(batch.id, true);
await this.executeBatch(batch);
} finally {
@@ -249,17 +281,30 @@ export class BulkMessageService implements OnApplicationBootstrap {
}
private async executeBatch(batch: MessageBatch): Promise<void> {
- // Update status to processing
+ // Transition to PROCESSING with the guard IN the UPDATE: it only lands while the stored status
+ // is not CANCELLED, so a cancel that already committed (any process) can never be overwritten
+ // back to PROCESSING. Zero affected rows = cancel-before-start won; send nothing.
batch.status = BatchStatus.PROCESSING;
batch.startedAt = new Date();
- await this.batchRepository.save(batch);
+ const started = await this.batchRepository.update(
+ { id: batch.id, status: Not(BatchStatus.CANCELLED) },
+ { status: BatchStatus.PROCESSING, startedAt: batch.startedAt },
+ );
+ if (!started.affected) {
+ this.logger.log(`Batch ${batch.batchId} was cancelled before processing started; nothing was sent`);
+ return;
+ }
const engine = this.sessionService.getEngine(batch.sessionId);
if (!engine) {
batch.status = BatchStatus.FAILED;
batch.completedAt = new Date();
this.stripBatchMediaPayloads(batch.messages);
- await this.batchRepository.save(batch);
+ await this.batchRepository.update({ id: batch.id, status: Not(BatchStatus.CANCELLED) }, {
+ status: BatchStatus.FAILED,
+ completedAt: batch.completedAt,
+ messages: batch.messages,
+ } as QueryDeepPartialEntity<MessageBatch>);
return;
}
@@ -305,6 +350,11 @@ export class BulkMessageService implements OnApplicationBootstrap {
}
content = (gate.data as { input: BulkMessageContent }).input;
+ // Re-validate the ACTUAL outbound payload against the media cap: template variables and a
+ // gate rewrite can grow base64 media past the limit createBatch verified on the raw input.
+ // A violation fails just this item (honouring stopOnError) instead of sending it.
+ this.assertContentMediaWithinCap(content);
+
// Send message based on type
const messageResult = await this.sendMessage(engine, msg.chatId, msg.type, content);
@@ -355,16 +405,19 @@ export class BulkMessageService implements OnApplicationBootstrap {
// Save progress periodically (every 10 messages or last message)
if (i % 10 === 0 || i === batch.messages.length - 1) {
- // Honor a cancellation issued by ANOTHER instance / after a restart — the in-memory Map only
- // sees same-process cancels. Re-read the status BEFORE saving so we don't clobber a CANCELLED
- // back to PROCESSING.
- const fresh = await this.batchRepository.findOne({ where: { id: batch.id }, select: { status: true } });
- if (fresh?.status === BatchStatus.CANCELLED) {
+ // Honor a cancellation issued by ANY process — the in-memory Map only sees same-process
+ // cancels. The guard lives IN the UPDATE (not a read-then-write), so a CANCELLED that
+ // committed first can never be clobbered back to PROCESSING: zero affected rows means the
+ // cancel won and the loop stops.
+ const progressSaved = await this.batchRepository.update(
+ { id: batch.id, status: Not(BatchStatus.CANCELLED) },
+ { progress: batch.progress, results, currentIndex: batch.currentIndex },
+ );
+ if (!progressSaved.affected) {
cancelledByDb = true;
this.logger.log(`Batch ${batch.batchId} cancelled (DB) at index ${i}`);
break;
}
- await this.batchRepository.save(batch);
}
// Delay before next message (except for last)
@@ -374,11 +427,10 @@ export class BulkMessageService implements OnApplicationBootstrap {
}
}
- // Final update. NOTE: `batch` still holds the in-memory PROCESSING status from the start, so a
- // cancellation persisted by cancelBatch would be overwritten if we saved without re-deriving it.
- // A cancel may also have landed AFTER the last cadence re-read (multi-replica / post-restart); the
- // unconditional save below would clobber it back to a terminal non-cancelled status, so re-read
- // once more here unless we already know the batch was cancelled.
+ // Final update. `batch` still holds the in-memory PROCESSING status from the start, so the
+ // terminal status is re-derived from the cancellation signals (DB + in-memory flag) rather than
+ // saved blindly. The re-read below narrows the race window so the reconciled counters stay
+ // consistent in the common case; the guarded write after it closes what remains.
if (!cancelledByDb) {
const fresh = await this.batchRepository.findOne({ where: { id: batch.id }, select: { status: true } });
if (fresh?.status === BatchStatus.CANCELLED) {
@@ -398,11 +450,46 @@ export class BulkMessageService implements OnApplicationBootstrap {
// otherwise the message_batches row retains multi-MB media forever. Intermediate (cadence) saves
// above keep the payload so a batch interrupted mid-run can still resume from currentIndex.
this.stripBatchMediaPayloads(batch.messages);
- await this.batchRepository.save(batch);
+ if (batch.status === BatchStatus.CANCELLED) {
+ // Persisting CANCELLED can never resurrect a finished batch — save the reconciled counters
+ // over cancelBatch's own (possibly earlier, staler) write.
+ await this.batchRepository.save(batch);
+ } else {
+ // A cancel may have committed after the re-read above; the guard IN the UPDATE makes this
+ // terminal write unable to flip a CANCELLED batch back to COMPLETED/FAILED. Zero affected
+ // rows means the cancel won the final race — the batch stays exactly as cancelBatch left it.
+ const finalized = await this.batchRepository.update({ id: batch.id, status: Not(BatchStatus.CANCELLED) }, {
+ status: batch.status,
+ progress: batch.progress,
+ results,
+ currentIndex: batch.currentIndex,
+ completedAt: batch.completedAt,
+ messages: batch.messages,
+ } as QueryDeepPartialEntity<MessageBatch>);
+ if (!finalized.affected) {
+ batch.status = BatchStatus.CANCELLED;
+ this.logger.log(`Batch ${batch.batchId} was cancelled just before completion; keeping CANCELLED`);
+ }
+ }
this.logger.log(`Batch ${batch.batchId} completed: ${batch.progress.sent} sent, ${batch.progress.failed} failed`);
}
+ /**
+ * Bound one content payload's base64 media to the shared media byte cap. Runs at batch creation
+ * and again per item after template variables and the message:sending gate are applied — both
+ * can grow (or empty out) a payload relative to what was verified at create time.
+ */
+ private assertContentMediaWithinCap(content: BulkMessageContent): void {
+ for (const media of [content?.image, content?.video, content?.audio, content?.document]) {
+ const base64 = stripBase64DataUri(media?.base64);
+ if (media?.base64 !== undefined && !base64 && !media.url) {
+ throw new BadRequestException('Either url or base64 must be provided for bulk media');
+ }
+ assertBase64WithinMediaCap(base64);
+ }
+ }
+
/**
* Drop base64 payloads from a finished batch's stored message list. A completed/cancelled batch is
* terminal (never resumed), so the (often multi-MB) base64 in `message_batches.messages` is dead
diff --git a/src/modules/message/dto/bulk-message.dto.ts b/src/modules/message/dto/bulk-message.dto.ts
index 17a34f8ee..32a98b0c0 100644
--- a/src/modules/message/dto/bulk-message.dto.ts
+++ b/src/modules/message/dto/bulk-message.dto.ts
@@ -132,7 +132,10 @@ export class SendBulkMessageDto {
@IsString()
batchId?: string;
- @ApiProperty({ description: 'Array of messages (max 100 per request)', type: [BulkMessageItemDto] })
+ @ApiProperty({
+ description: 'Array of messages (max 100 per request; duplicate chatIds are collapsed — first occurrence wins)',
+ type: [BulkMessageItemDto],
+ })
@IsArray()
@ArrayMaxSize(100)
@ValidateNested({ each: true })