Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session,message): reclaim leaked slot on reconnect exhaustion; protect FAILED batches (#912)

Yudhi Armyndharis29d16064e366
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a3955edb1..bdb337bb7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- **A session that exhausts its reconnect budget no longer leaks a concurrency slot or wedge its
+ restart.** When a session with a finite `config.maxReconnectAttempts` reached the terminal FAILED
+ branch of `scheduleReconnect`, it wrote FAILED but left the dead engine in the in-process map —
+ unlike the sister terminal path in `onError`, which evicts for the explicit reason that a leftover
+ engine holds a concurrency slot and makes the next `start()` reject the session as "already started".
+ The reconnect-exhaustion path now evicts the dead engine the same way `onError` does (guarded on
+ the engine being present, since the `executeReconnect`-catch caller already evicted its half-built
+ engine). Only affects sessions with an explicit finite `maxReconnectAttempts` (the default is
+ unlimited).
+
+- **`cancelBatch` no longer overwrites a terminally FAILED batch to CANCELLED.** The cancel guard
+ checked only COMPLETED and CANCELLED, so a post-completion cancel on a `stopOnError`-failed batch
+ (or any batch that resolved to FAILED) relabelled it CANCELLED, rewrote `progress.cancelled`/
+ `pending`, and masked the real delivery failures and the `message:failed` events that had already
+ fired. FAILED is now in the terminal-status guard, so each terminal status stays exclusive.
+
### Security
- **Secret comparisons on the `/api/metrics` Bearer and ingress `shared-secret` auth surfaces no
diff --git a/openapi.json b/openapi.json
index 1330fbb9d..6cc285e44 100644
--- a/openapi.json
+++ b/openapi.json
@@ -2193,7 +2193,7 @@
"description": "Batch cancelled"
},
"400": {
- "description": "Batch already completed or cancelled"
+ "description": "Batch already completed, cancelled, or failed (terminal statuses are exclusive)"
},
"404": {
"description": "Batch not found"
diff --git a/src/modules/message/bulk-message.service.spec.ts b/src/modules/message/bulk-message.service.spec.ts
index 85ba8a8f1..2d88e05bf 100644
--- a/src/modules/message/bulk-message.service.spec.ts
+++ b/src/modules/message/bulk-message.service.spec.ts
@@ -388,6 +388,67 @@ describe('BulkMessageService.processBatch', () => {
});
});
+describe('BulkMessageService.cancelBatch', () => {
+ let service: BulkMessageService;
+ let repo: { findOne: jest.Mock; save: jest.Mock };
+
+ const batchWithStatus = (status: BatchStatus): MessageBatch =>
+ ({
+ id: 'b1',
+ batchId: 'bx',
+ sessionId: 's1',
+ status,
+ messages: [],
+ options: {},
+ progress: { total: 2, sent: 0, failed: 0, pending: 2, cancelled: 0 },
+ results: [],
+ }) as unknown as MessageBatch;
+
+ beforeEach(async () => {
+ repo = { findOne: jest.fn(), save: jest.fn().mockImplementation(b => Promise.resolve(b)) };
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ BulkMessageService,
+ { provide: getRepositoryToken(MessageBatch, 'data'), useValue: repo },
+ { provide: SessionService, useValue: {} },
+ { provide: MessageService, useValue: {} },
+ { provide: HookManager, useValue: { execute: jest.fn() } },
+ ],
+ }).compile();
+ service = module.get(BulkMessageService);
+ });
+
+ it('rejects a cancel on a terminally FAILED batch (does not overwrite the failure to CANCELLED)', async () => {
+ // A FAILED batch reached its terminal state because real sends failed (stopOnError, or all sends
+ // failed). Overwriting it to CANCELLED would mask the delivery failure and the message:failed
+ // 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();
+ });
+
+ 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();
+ });
+
+ 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();
+ });
+
+ it('cancels a PENDING batch (the supported case) and moves pending items to cancelled', async () => {
+ const batch = batchWithStatus(BatchStatus.PENDING);
+ repo.findOne.mockResolvedValue(batch);
+ const result = await service.cancelBatch('s1', 'bx');
+ expect(result.status).toBe(BatchStatus.CANCELLED);
+ expect(result.progress.cancelled).toBe(2);
+ expect(result.progress.pending).toBe(0);
+ });
+});
+
describe('BulkMessageService.createBatch base64 media cap', () => {
let service: BulkMessageService;
let repo: { findOne: jest.Mock; save: jest.Mock; create: jest.Mock };
diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.ts
index cecb120da..1efda562d 100644
--- a/src/modules/message/bulk-message.service.ts
+++ b/src/modules/message/bulk-message.service.ts
@@ -206,7 +206,14 @@ export class BulkMessageService implements OnApplicationBootstrap {
throw new NotFoundException(`Batch '${batchId}' not found`);
}
- if (batch.status === BatchStatus.COMPLETED || batch.status === BatchStatus.CANCELLED) {
+ // A terminal batch (COMPLETED, CANCELLED, or FAILED) cannot be cancelled — cancelling a FAILED
+ // batch would overwrite the failure outcome to CANCELLED, masking the real delivery failures and
+ // the `message:failed` events that already fired. Each terminal status is exclusive.
+ if (
+ batch.status === BatchStatus.COMPLETED ||
+ batch.status === BatchStatus.CANCELLED ||
+ batch.status === BatchStatus.FAILED
+ ) {
throw new BadRequestException(`Batch '${batchId}' is already ${batch.status}`);
}
diff --git a/src/modules/message/message.controller.ts b/src/modules/message/message.controller.ts
index 633d2152a..61eb433dd 100644
--- a/src/modules/message/message.controller.ts
+++ b/src/modules/message/message.controller.ts
@@ -456,7 +456,7 @@ export class MessageController {
})
@ApiResponse({
status: 400,
- description: 'Batch already completed or cancelled',
+ description: 'Batch already completed, cancelled, or failed (terminal statuses are exclusive)',
})
@ApiResponse({
status: 404,
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 34c05e3b1..64c54be6b 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -826,6 +826,48 @@ describe('SessionService', () => {
// maxAttempts:0 means auto-reconnect is OFF, not that 0 attempts were tried and failed.
expect(i.sessionErrors.get('sess-uuid-1')).toMatch(/auto-reconnect is disabled/i);
});
+
+ it('evicts the dead engine when the max-attempts budget is exhausted (no leaked slot, restart works)', async () => {
+ // A terminal FAILED session must not hold an engine entry — otherwise isActive() stays true,
+ // the concurrency cap leaks a slot, and a later start() rejects the session as "already started".
+ // This mirrors onError's terminal path, which evicts for exactly that reason.
+ const i = service as unknown as {
+ reconnectStates: Map<string, { attempts: number; timer: null; maxAttempts: number; baseDelay: number }>;
+ sessionErrors: Map<string, string>;
+ engines: Map<string, { forceDestroy: jest.Mock }>;
+ scheduleReconnect: (id: string, session: Session) => void;
+ };
+ const deadEngine = { forceDestroy: jest.fn().mockResolvedValue(undefined) };
+ i.engines.set('sess-uuid-1', deadEngine);
+ i.reconnectStates.set('sess-uuid-1', { attempts: 2, timer: null, maxAttempts: 2, baseDelay: 5000 });
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+
+ expect(service.isActive('sess-uuid-1')).toBe(true);
+
+ i.scheduleReconnect('sess-uuid-1', createMockSession());
+ await new Promise(resolve => setImmediate(resolve));
+
+ // The dead engine is evicted and force-destroyed; the session no longer counts as active.
+ expect(service.isActive('sess-uuid-1')).toBe(false);
+ expect(deadEngine.forceDestroy).toHaveBeenCalledTimes(1);
+ expect(i.sessionErrors.get('sess-uuid-1')).toMatch(/reconnection failed after 2 attempts/i);
+ });
+
+ it('does not throw when the engine was already evicted (executeReconnect-catch path)', () => {
+ // executeReconnect evicts the half-built engine before scheduling a reconnect, so by the time
+ // the maxAttempts branch runs there the engine is gone. The eviction guard must handle that.
+ const i = service as unknown as {
+ reconnectStates: Map<string, { attempts: number; timer: null; maxAttempts: number; baseDelay: number }>;
+ sessionErrors: Map<string, string>;
+ engines: Map<string, unknown>;
+ scheduleReconnect: (id: string, session: Session) => void;
+ };
+ i.reconnectStates.set('sess-uuid-1', { attempts: 0, timer: null, maxAttempts: 0, baseDelay: 5000 });
+ expect(i.engines.has('sess-uuid-1')).toBe(false);
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+
+ expect(() => i.scheduleReconnect('sess-uuid-1', createMockSession())).not.toThrow();
+ });
});
describe('scheduleReconnect (reconnect policy)', () => {
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 2e9e59165..1a8150912 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -1919,6 +1919,15 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
: `Reconnection failed after ${state.attempts} attempts — restart the session.`,
);
void this.updateStatus(id, SessionStatus.FAILED);
+ // Terminal path — evict the dead engine so it neither holds a concurrency slot nor makes a
+ // subsequent start() reject the session as "already started". This mirrors onError's terminal
+ // path (the same rationale: leaving the engine in the map wedges the session). The engine may
+ // already be gone in the executeReconnect-catch path (it evicts the half-built engine before
+ // scheduling a reconnect), so guard on its presence — evictAndForceDestroy takes a non-null engine.
+ const deadEngine = this.engines.get(id);
+ if (deadEngine) {
+ this.evictAndForceDestroy(id, deadEngine);
+ }
return;
}