Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session,bulk): clean up failed engine init, concurrent create, and bulk batch memory (#600)
Yudhi Armyndharisfc2b56c31632
diff --git a/src/modules/message/bulk-message.service.spec.ts b/src/modules/message/bulk-message.service.spec.tsindex a8b39e6c3..f9fc9d678 100644--- a/src/modules/message/bulk-message.service.spec.ts+++ b/src/modules/message/bulk-message.service.spec.ts@@ -142,6 +142,21 @@ describe('BulkMessageService.processBatch', () => {const inFlightMarkers = (): Map<string, boolean> =>(service as unknown as { processingBatches: Map<string, boolean> }).processingBatches;+ it('rejects a new batch (before persisting) when the concurrent in-flight cap is reached', async () => {+ const prev = process.env.BULK_MAX_CONCURRENT_BATCHES;+ process.env.BULK_MAX_CONCURRENT_BATCHES = '2';+ try {+ repo.findOne.mockResolvedValue(null); // batchId not taken+ (service as unknown as { inFlightBatches: number }).inFlightBatches = 2; // at cap+ const dto = { messages: [{ chatId: '[email protected]', type: 'text', content: { text: 'hi' } }] };+ await expect(service.createBatch('s1', dto as never)).rejects.toThrow(/too many bulk batches/i);+ expect(repo.save).not.toHaveBeenCalled(); // rejected before a PENDING row is written+ } finally {+ if (prev === undefined) delete process.env.BULK_MAX_CONCURRENT_BATCHES;+ else process.env.BULK_MAX_CONCURRENT_BATCHES = prev;+ }+ });+it('releases the in-flight marker when the engine is missing (no processingBatches leak)', async () => {repo.findOne.mockResolvedValue(makeBatch(1));sessionService.getEngine.mockReturnValue(undefined); // engine-not-found → early-return pathdiff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.tsindex b2a1d7a35..3c76f2ef3 100644--- a/src/modules/message/bulk-message.service.ts+++ b/src/modules/message/bulk-message.service.ts@@ -57,10 +57,24 @@ export function sanitizeBatchError(error: unknown): { code: string; message: strreturn { code: 'SEND_FAILED', message: error instanceof Error ? error.message : String(error) };}+/**+ * Per-process cap on concurrently-processing bulk batches. Each in-flight batch holds its full message+ * set (with base64 media) in memory and is dispatched fire-and-forget, so without a ceiling a burst of+ * batches can exhaust host memory. Env-overridable; 0 disables the cap. Default is generous — it only+ * trips a genuine runaway, not normal use. Per-process (not cluster-wide).+ */+const DEFAULT_MAX_CONCURRENT_BATCHES = 50;+export function resolveMaxConcurrentBatches(): number {+ const raw = Number(process.env.BULK_MAX_CONCURRENT_BATCHES);+ if (!Number.isFinite(raw) || raw < 0) return DEFAULT_MAX_CONCURRENT_BATCHES;+ return Math.floor(raw); // 0 = unlimited+}+@Injectable()export class BulkMessageService implements OnApplicationBootstrap {private readonly logger = new Logger(BulkMessageService.name);private readonly processingBatches = new Map<string, boolean>(); // Track active batches for cancellation+ private inFlightBatches = 0; // count of batches currently in processBatch (memory bound, see cap above)constructor(@InjectRepository(MessageBatch, 'data')@@ -115,6 +129,13 @@ export class BulkMessageService implements OnApplicationBootstrap {throw new BadRequestException(`Batch ID '${batchId}' already exists`);}+ // Reject before persisting a row when too many batches are already processing, so a burst can't+ // hold an unbounded number of full message sets (base64 media included) in memory at once.+ const maxConcurrentBatches = resolveMaxConcurrentBatches();+ if (maxConcurrentBatches > 0 && this.inFlightBatches >= maxConcurrentBatches) {+ throw new BadRequestException(`Too many bulk batches in progress (max ${maxConcurrentBatches}); retry shortly`);+ }+const options = {delayBetweenMessages: dto.options?.delayBetweenMessages ?? 3000,randomizeDelay: dto.options?.randomizeDelay ?? true,@@ -199,8 +220,10 @@ export class BulkMessageService implements OnApplicationBootstrap {// Always release the in-flight marker on every exit path (engine-not-found early return, a thrown// save/send, or normal completion) — otherwise the map leaks an entry per such batch.try {+ this.inFlightBatches++;await this.executeBatch(batch);} finally {+ this.inFlightBatches--;this.processingBatches.delete(batch.id);}}diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 2e1243976..9af3388bd 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -267,6 +267,15 @@ describe('SessionService', () => {await expect(service.create({ name: 'test-session' })).rejects.toThrow(ConflictException);});++ it('maps a name UNIQUE-violation on insert to 409 when two concurrent creates race past the pre-check', async () => {+ (repository.findOne as jest.Mock).mockResolvedValue(null); // pre-check passes (TOCTOU window)+ (repository.create as jest.Mock).mockReturnValue(createMockSession());+ const uniqueErr = Object.assign(new Error('duplicate key value'), { driverError: { code: '23505' } });+ (dataSource.transaction as jest.Mock).mockRejectedValueOnce(uniqueErr);++ await expect(service.create({ name: 'test-session' })).rejects.toThrow(ConflictException);+ });});// ── findAll / findOne / findByName ────────────────────────────────@@ -356,6 +365,19 @@ describe('SessionService', () => {expect(engineFactory.create).toHaveBeenCalledTimes(1);});+ it('evicts and tears down the engine when engine.initialize() fails (no orphan wedging the session)', async () => {+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ (engineFactory.create as jest.Mock).mockClear().mockReturnValue(mockEngine);+ mockEngine.initialize.mockRejectedValueOnce(new Error('chromium launch failed'));++ await expect(service.start('sess-uuid-1')).rejects.toThrow('chromium launch failed');++ const engines = (service as unknown as { engines: Map<string, unknown> }).engines;+ expect(engines.has('sess-uuid-1')).toBe(false); // not left orphaned → session can be started again+ expect(mockEngine.destroy).toHaveBeenCalled(); // half-built engine torn down+ });+it('allows a fresh start after the previous one completed (reservation is cleared)', async () => {(repository.findOne as jest.Mock).mockResolvedValue(createMockSession());(repository.update as jest.Mock).mockResolvedValue({ affected: 1 });diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex cfbe569ca..74115ef70 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -284,9 +284,20 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatstatus: SessionStatus.CREATED,});- const saved = await this.dataSource.transaction(async manager => {- return await manager.save(session);- });+ // The findOne pre-check above is a fast path for the common case, but it's a check-then-insert+ // TOCTOU: two concurrent same-name creates both pass it, then one hits the name UNIQUE constraint.+ // Translate that violation to a 409 (matching the pre-check) instead of leaking a raw 500.+ let saved: Session;+ try {+ saved = await this.dataSource.transaction(async manager => {+ return await manager.save(session);+ });+ } catch (err) {+ if (isUniqueConstraintError(err)) {+ throw new ConflictException(`Session with name '${dto.name}' already exists`);+ }+ throw err;+ }this.logger.log(`Session created: ${saved.name}`, {sessionId: saved.id,action: 'create',@@ -439,7 +450,22 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatconst { maxAttempts, baseDelay } = resolveReconnectConfig(session.config);this.reconnectStates.set(id, { attempts: 0, timer: null, maxAttempts, baseDelay });- await this.initializeEngine(id, session);+ try {+ await this.initializeEngine(id, session);+ } catch (err) {+ // engine.initialize() failed AFTER the engine was registered (initializeEngine sets it before+ // initializing). Evict + tear it down so the session doesn't wedge at "already started" with a+ // leaked Chromium/socket permanently holding a concurrency slot. initializingSessions serializes+ // start(), so the engine in the map here is the one this start just created.+ const orphan = this.engines.get(id);+ if (orphan) {+ this.engines.delete(id);+ this.sessionErrors.set(id, err instanceof Error ? err.message : String(err));+ await this.destroyEngineSafely(id, orphan);+ await this.updateStatus(id, SessionStatus.FAILED).catch(() => undefined);+ }+ throw err;+ }// A stop()/delete() may have landed while we awaited engine.initialize() — if so, tear down the// engine we just registered so the session isn't resurrected to READY (mirrors the post-init