Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(reliability): harden shutdown, reconnect, logging, queue + audit retention

rmyndharis8914f20b8c16
diff --git a/.env.example b/.env.example
index bd750e210..7e79beede 100644
--- a/.env.example
+++ b/.env.example
@@ -91,6 +91,10 @@ PUPPETEER_ARGS=--no-sandbox,--disable-setuid-sandbox,--disable-dev-shm-usage,--d
# Disabled by default; set a token to enable. Scrapers must send `Authorization: Bearer <token>`.
# METRICS_TOKEN=change-me-to-a-long-random-string
+# Audit-log retention. Logs older than this many days are pruned daily (and once at startup).
+# Default 90; set to 0 to keep audit logs forever (disable pruning).
+# AUDIT_RETENTION_DAYS=90
+
# =============================================================================
# DATABASE
# =============================================================================
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ffcb7a747..a56aaa062 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,26 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [Unreleased]
+
+### Added
+
+- **`LOG_LEVEL` is now honored.** It was read into config/compose but never applied (logging was hardcoded
+ to `info`); the level (`error`/`warn`/`info`/`debug`/`verbose`) is now set at bootstrap.
+- **Automatic audit-log retention.** Audit logs older than `AUDIT_RETENTION_DAYS` (default 90; `0` disables)
+ are pruned daily and once at startup — the existing `cleanup()` was never scheduled, so `audit_logs` grew
+ without bound.
+
+### Fixed
+
+- **Graceful shutdown is now robust.** `onModuleDestroy` clears reconnect timers first and destroys engines
+ in parallel, each isolated and time-bounded — so one hung/throwing Chromium can no longer abort teardown
+ of the other sessions or stall shutdown.
+- **A session that exhausts its reconnect attempts is now marked `FAILED` with a reason** (surfaced via
+ `lastError`) instead of sitting silently `DISCONNECTED` forever.
+- **BullMQ webhook jobs are auto-evicted** (`removeOnComplete`/`removeOnFail` retention) so completed/failed
+ job payloads no longer accumulate unbounded in Redis (audit M19).
+
## [0.2.8] - 2026-06-17
The engine-pluggability release: the whatsapp-web.js delivery-ack, message-type, and JID specifics are
diff --git a/src/main.ts b/src/main.ts
index 061ef4cb3..8b688b648 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -4,6 +4,7 @@ import { SwaggerModule } from '@nestjs/swagger';
import helmet from 'helmet';
import { AppModule } from './app.module';
import { ShutdownService } from './common/services/shutdown.service';
+import { LoggerService, LogLevel } from './common/services/logger.service';
import { createSwaggerConfig } from './config/swagger.config';
import {
resolveCorsPolicy,
@@ -75,6 +76,12 @@ STORAGE_PATH=./data/media
}
async function bootstrap() {
+ // Apply the operator-configured log verbosity (LOG_LEVEL) before anything logs. Unset/invalid → INFO.
+ const requestedLevel = process.env.LOG_LEVEL?.trim().toLowerCase();
+ if (requestedLevel && (Object.values(LogLevel) as string[]).includes(requestedLevel)) {
+ LoggerService.setLogLevel(requestedLevel as LogLevel);
+ }
+
// Fail fast: never start production with default/placeholder secrets.
assertNoDefaultSecretsInProduction({
nodeEnv: process.env.NODE_ENV,
diff --git a/src/modules/audit/audit.service.ts b/src/modules/audit/audit.service.ts
index cc4a85cb1..38610e08a 100644
--- a/src/modules/audit/audit.service.ts
+++ b/src/modules/audit/audit.service.ts
@@ -1,8 +1,9 @@
-import { Injectable } from '@nestjs/common';
+import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Between, LessThan } from 'typeorm';
import { AuditLog, AuditAction, AuditSeverity } from './entities/audit-log.entity';
import { ApiKey } from '../auth/entities/api-key.entity';
+import { createLogger } from '../../common/services/logger.service';
interface AuditContext {
apiKey?: ApiKey;
@@ -29,12 +30,45 @@ export interface AuditQueryOptions {
}
@Injectable()
-export class AuditService {
+export class AuditService implements OnModuleInit, OnModuleDestroy {
+ private readonly logger = createLogger('AuditService');
+ private cleanupTimer?: ReturnType<typeof setInterval>;
+
constructor(
@InjectRepository(AuditLog, 'main')
private readonly auditRepository: Repository<AuditLog>,
) {}
+ /**
+ * Periodically prune audit logs older than AUDIT_RETENTION_DAYS (default 90; set <= 0 to disable).
+ * Runs once at startup, then daily. Without this the audit_logs table grows without bound — the
+ * existing cleanup() method was never scheduled or called anywhere.
+ */
+ onModuleInit(): void {
+ const parsed = Number.parseInt(process.env.AUDIT_RETENTION_DAYS ?? '', 10);
+ const retentionDays = Number.isInteger(parsed) ? Math.max(0, parsed) : 90;
+ if (retentionDays <= 0) {
+ this.logger.log('Audit-log retention disabled (AUDIT_RETENTION_DAYS <= 0)');
+ return;
+ }
+ const runCleanup = (): void => {
+ this.cleanup(retentionDays)
+ .then(n => {
+ if (n > 0) this.logger.log(`Pruned ${n} audit log(s) older than ${retentionDays} day(s)`);
+ })
+ .catch(err => this.logger.error('Audit-log cleanup failed', err instanceof Error ? err.stack : String(err)));
+ };
+ runCleanup(); // prune once at startup
+ this.cleanupTimer = setInterval(runCleanup, 24 * 60 * 60 * 1000);
+ this.cleanupTimer.unref?.();
+ }
+
+ onModuleDestroy(): void {
+ if (this.cleanupTimer) {
+ clearInterval(this.cleanupTimer);
+ }
+ }
+
async log(
action: AuditAction,
context: AuditContext = {},
diff --git a/src/modules/queue/queue.module.ts b/src/modules/queue/queue.module.ts
index 3990cce58..b13f2c661 100644
--- a/src/modules/queue/queue.module.ts
+++ b/src/modules/queue/queue.module.ts
@@ -30,7 +30,15 @@ export { QUEUE_NAMES } from './queue-names';
},
}),
}),
- BullModule.registerQueue({ name: QUEUE_NAMES.WEBHOOK }),
+ BullModule.registerQueue({
+ name: QUEUE_NAMES.WEBHOOK,
+ // Auto-evict finished jobs so completed/failed webhook payloads don't accumulate in Redis
+ // unbounded (M19). Keep a small recent window for debugging; cap age too.
+ defaultJobOptions: {
+ removeOnComplete: { age: 3600, count: 1000 },
+ removeOnFail: { age: 86400, count: 5000 },
+ },
+ }),
BullBoardModule.forRoot({
route: '/admin/queues',
adapter: ExpressAdapter,
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index a650b7304..921bb9998 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -128,6 +128,24 @@ describe('SessionService', () => {
service = module.get<SessionService>(SessionService);
});
+ // ── shutdown ──────────────────────────────────────────────────────
+
+ describe('onModuleDestroy', () => {
+ it('destroys every engine even if one destroy() throws, and clears the map', async () => {
+ const good = { destroy: jest.fn().mockResolvedValue(undefined) };
+ const bad = { destroy: jest.fn().mockRejectedValue(new Error('stuck chromium')) };
+ const engines = (service as unknown as { engines: Map<string, unknown> }).engines;
+ engines.set('s-good', good);
+ engines.set('s-bad', bad);
+
+ await expect(service.onModuleDestroy()).resolves.toBeUndefined();
+
+ expect(good.destroy).toHaveBeenCalledTimes(1);
+ expect(bad.destroy).toHaveBeenCalledTimes(1);
+ expect(engines.size).toBe(0);
+ });
+ });
+
// ── create ────────────────────────────────────────────────────────
describe('create', () => {
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index af7d4aa06..4075e95aa 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -138,23 +138,42 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
}
async onModuleDestroy(): Promise<void> {
- // Clean up all engines on shutdown
- for (const [sessionId, engine] of this.engines) {
- this.logger.log(`Destroying engine for session ${sessionId}`, {
- sessionId,
- action: 'shutdown',
- });
- await engine.destroy();
- }
- this.engines.clear();
-
- // Clear all reconnect timers
+ // Stop reconnect timers FIRST so nothing reschedules mid-teardown, and so this always runs even
+ // if an engine.destroy() below hangs or throws.
for (const [, state] of this.reconnectStates) {
if (state.timer) {
clearTimeout(state.timer);
}
}
this.reconnectStates.clear();
+
+ // Destroy engines in parallel, each isolated + time-bounded, so one stuck Chromium can neither
+ // stall the shutdown nor abort teardown of the other sessions.
+ await Promise.allSettled(
+ [...this.engines].map(([sessionId, engine]) => this.destroyEngineSafely(sessionId, engine)),
+ );
+ this.engines.clear();
+ }
+
+ /** Destroy one engine, isolating + time-bounding failures so shutdown can't be stalled or aborted. */
+ private async destroyEngineSafely(sessionId: string, engine: IWhatsAppEngine): Promise<void> {
+ this.logger.log(`Destroying engine for session ${sessionId}`, { sessionId, action: 'shutdown' });
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ await Promise.race([
+ engine.destroy(),
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(new Error('engine.destroy() timed out')), 10_000);
+ }),
+ ]);
+ } catch (err) {
+ this.logger.error(`Failed to destroy engine for session ${sessionId} during shutdown`, String(err), {
+ sessionId,
+ action: 'shutdown_destroy_failed',
+ });
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
}
async create(dto: CreateSessionDto): Promise<Session> {
@@ -665,6 +684,10 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
attempts: state.attempts,
action: 'reconnect_failed',
});
+ // Don't leave the session silently stuck DISCONNECTED — mark it terminally FAILED with a reason
+ // so findOne/findAll surface it via `lastError` and the dashboard shows it needs a restart.
+ this.sessionErrors.set(id, `Reconnection failed after ${state.attempts} attempts — restart the session.`);
+ void this.updateStatus(id, SessionStatus.FAILED);
return;
}