Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(observability): exit non-zero on failed teardown and count guard rejections in RED metrics (#961)
Yudhi Armyndharis4d627d1451c4
diff --git a/src/common/interceptors/request-metrics.interceptor.spec.ts b/src/common/interceptors/request-metrics.interceptor.spec.tsindex d1850b7e0..bf10eeb91 100644--- a/src/common/interceptors/request-metrics.interceptor.spec.ts+++ b/src/common/interceptors/request-metrics.interceptor.spec.ts@@ -7,11 +7,13 @@ jest.mock('../metrics/request-metrics', () => ({import { Observable } from 'rxjs';import { RequestMetricsInterceptor } from './request-metrics.interceptor';import { recordHttpRequest } from '../metrics/request-metrics';+import { HTTP_REQUEST_METRICS_CLAIMED } from '../middleware/request-metrics.middleware';const mockedRecord = recordHttpRequest as jest.MockedFunction<typeof recordHttpRequest>;interface Ctx {ctx: Record<string, unknown>;+ req: Record<string, unknown>;listeners: { finish?: () => void; close?: () => void };}@@ -35,7 +37,7 @@ function makeContext(opts: {getClass: () => ({ name: opts.className ?? 'SessionController' }),getHandler: () => ({ name: opts.handlerName ?? 'list' }),};- return { ctx, listeners };+ return { ctx, req, listeners };}const noopHandler = { handle: (): Observable<unknown> => new Observable<unknown>() };@@ -90,4 +92,16 @@ describe('RequestMetricsInterceptor', () => {listeners.close?.();expect(mockedRecord).toHaveBeenCalledTimes(1);});++ it('claims the request so the boundary middleware does not record it a second time', () => {+ const { ctx, req } = makeContext({ routePath: '/api/sessions' });+ new RequestMetricsInterceptor().intercept(ctx as never, noopHandler as never);+ expect((req as Record<string | symbol, unknown>)[HTTP_REQUEST_METRICS_CLAIMED]).toBe(true);+ });++ it('does NOT claim skipped prefixes — nothing records those at all', () => {+ const { ctx, req } = makeContext({ routePath: '/api/health' });+ new RequestMetricsInterceptor().intercept(ctx as never, noopHandler as never);+ expect((req as Record<string | symbol, unknown>)[HTTP_REQUEST_METRICS_CLAIMED]).toBeUndefined();+ });});diff --git a/src/common/interceptors/request-metrics.interceptor.ts b/src/common/interceptors/request-metrics.interceptor.tsindex efefee269..a581ff20e 100644--- a/src/common/interceptors/request-metrics.interceptor.ts+++ b/src/common/interceptors/request-metrics.interceptor.ts@@ -2,6 +2,7 @@ import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nesimport { Observable } from 'rxjs';import type { Request, Response } from 'express';import { recordHttpRequest } from '../metrics/request-metrics';+import { claimHttpRequestMetrics } from '../middleware/request-metrics.middleware';/*** Records one HTTP RED observation per request into the in-process request-metrics store.@@ -11,6 +12,11 @@ import { recordHttpRequest } from '../metrics/request-metrics';* interceptor's observable chain — `finish`/`close` see the real status (2xx/4xx/5xx). The `recorded`* guard keeps it to one observation per request even when both events fire.*+ * Only requests that PASS the guards reach this interceptor; requests rejected earlier (throttler+ * 429, API-key guard 401/403) are recorded by requestMetricsBoundaryMiddleware instead. The request+ * is claimed here synchronously so the middleware (which runs first) skips it — exactly one+ * observation per response across the pair.+ ** Route label: the Express route pattern when available (bounded — `/api/sessions/:id`, not the raw* URL), falling back to `Controller#handler` (always available, strictly bounded).*/@@ -25,6 +31,7 @@ export class RequestMetricsInterceptor implements NestInterceptor {if (route === null || SKIPPED_PREFIXES.some(prefix => route.startsWith(prefix))) {return next.handle();}+ claimHttpRequestMetrics(req);const method = (req.method ?? 'UNKNOWN').toUpperCase();const start = process.hrtime.bigint();let recorded = false;diff --git a/src/common/middleware/request-metrics.middleware.spec.ts b/src/common/middleware/request-metrics.middleware.spec.tsnew file mode 100644index 000000000..db12f29d3--- /dev/null+++ b/src/common/middleware/request-metrics.middleware.spec.ts@@ -0,0 +1,98 @@+jest.mock('../metrics/request-metrics', () => ({+ recordHttpRequest: jest.fn(),+ renderHttpRequestMetrics: jest.fn(() => []),+ resetHttpRequestMetrics: jest.fn(),+}));++import {+ HTTP_REQUEST_METRICS_CLAIMED,+ claimHttpRequestMetrics,+ requestMetricsBoundaryMiddleware,+} from './request-metrics.middleware';+import { recordHttpRequest } from '../metrics/request-metrics';++const mockedRecord = recordHttpRequest as jest.MockedFunction<typeof recordHttpRequest>;++interface ReqRes {+ req: Record<string, unknown>;+ listeners: { finish?: () => void; close?: () => void };+ next: jest.Mock;+}++function makeReqRes(opts: { method?: string; routePath?: string; statusCode?: number }): ReqRes {+ const req: Record<string, unknown> = {+ method: opts.method ?? 'GET',+ route: opts.routePath ? { path: opts.routePath } : undefined,+ };+ const listeners: { finish?: () => void; close?: () => void } = {};+ const res = {+ statusCode: opts.statusCode ?? 200,+ on: (event: string, cb: () => void): void => {+ listeners[event as 'finish' | 'close'] = cb;+ },+ };+ const next = jest.fn();+ requestMetricsBoundaryMiddleware(req as never, res as never, next as never);+ return { req, listeners, next };+}++describe('requestMetricsBoundaryMiddleware', () => {+ beforeEach(() => mockedRecord.mockClear());++ it('calls next() immediately (never blocks the chain)', () => {+ const { next } = makeReqRes({ routePath: '/api/sessions' });+ expect(next).toHaveBeenCalledTimes(1);+ });++ it.each([401, 403, 429])(+ 'records an unclaimed request rejected by a guard with its final status (%i)',+ statusCode => {+ const { listeners } = makeReqRes({ routePath: '/api/sessions', statusCode });+ listeners.finish?.();+ expect(mockedRecord).toHaveBeenCalledTimes(1);+ const [method, route, status, seconds] = mockedRecord.mock.calls[0];+ expect(method).toBe('GET');+ expect(route).toBe('/api/sessions');+ expect(status).toBe(statusCode);+ expect(seconds).toBeGreaterThanOrEqual(0);+ },+ );++ it('skips a request claimed by the interceptor (no double-count on requests that pass the guards)', () => {+ const { req, listeners } = makeReqRes({ routePath: '/api/sessions', statusCode: 200 });+ claimHttpRequestMetrics(req as never);+ listeners.finish?.();+ expect(mockedRecord).not.toHaveBeenCalled();+ });++ it('skips /api/health and /api/metrics even when unclaimed', () => {+ for (const path of ['/api/health', '/api/health/live', '/api/metrics']) {+ const { listeners } = makeReqRes({ routePath: path });+ listeners.finish?.();+ expect(mockedRecord).not.toHaveBeenCalled();+ mockedRecord.mockClear();+ }+ });++ it('collapses unmatched routes (404) into one constant label', () => {+ const { listeners } = makeReqRes({ routePath: undefined, statusCode: 404 });+ listeners.finish?.();+ expect(mockedRecord).toHaveBeenCalledTimes(1);+ expect(mockedRecord.mock.calls[0][1]).toBe('(unmatched)');+ expect(mockedRecord.mock.calls[0][2]).toBe(404);+ });++ it('records once even if both finish and close fire', () => {+ const { listeners } = makeReqRes({ routePath: '/api/sessions', statusCode: 401 });+ listeners.finish?.();+ listeners.close?.();+ expect(mockedRecord).toHaveBeenCalledTimes(1);+ });++ it('claim marker lives on the request object under the shared symbol', () => {+ const { req } = makeReqRes({ routePath: '/api/sessions' });+ expect((req as Record<symbol, unknown>)[HTTP_REQUEST_METRICS_CLAIMED]).toBeUndefined();+ claimHttpRequestMetrics(req as never);+ expect((req as Record<symbol, unknown>)[HTTP_REQUEST_METRICS_CLAIMED]).toBe(true);+ });+});diff --git a/src/common/middleware/request-metrics.middleware.ts b/src/common/middleware/request-metrics.middleware.tsnew file mode 100644index 000000000..3f9fd3634--- /dev/null+++ b/src/common/middleware/request-metrics.middleware.ts@@ -0,0 +1,45 @@+import { Request, Response, NextFunction } from 'express';+import { recordHttpRequest } from '../metrics/request-metrics';++// Same exclusion contract as RequestMetricsInterceptor: liveness probes and the scrape endpoint+// itself are not API traffic worth a RED series.+const SKIPPED_PREFIXES = ['/api/health', '/api/metrics'];++/**+ * Per-request ownership marker for the single RED observation, shared with+ * RequestMetricsInterceptor. Nest runs middleware BEFORE guards and interceptors, so this+ * boundary middleware sees every API request — including ones the throttler (429) or the+ * API-key guard (401/403) reject before the interceptor chain ever runs. The interceptor+ * claims the requests it observes; at response time this middleware records only requests+ * left unclaimed, so every response is counted exactly once.+ */+export const HTTP_REQUEST_METRICS_CLAIMED = Symbol('openwa.httpRequestMetricsClaimed');++type MetricsRequest = Request & { [HTTP_REQUEST_METRICS_CLAIMED]?: boolean };++/** Claim the request's single RED observation (idempotent). Used by RequestMetricsInterceptor. */+export function claimHttpRequestMetrics(req: Request): void {+ (req as MetricsRequest)[HTTP_REQUEST_METRICS_CLAIMED] = true;+}++export function requestMetricsBoundaryMiddleware(req: Request, res: Response, next: NextFunction): void {+ const start = process.hrtime.bigint();+ const record = (): void => {+ const request = req as MetricsRequest;+ if (request[HTTP_REQUEST_METRICS_CLAIMED]) return;+ request[HTTP_REQUEST_METRICS_CLAIMED] = true;+ // Guard rejections happen after Express matched the route, so req.route.path carries the+ // same bounded pattern label the interceptor uses. Unmatched paths (404s) collapse into+ // one constant label — no per-URL cardinality.+ const routePath = (req as unknown as { route?: { path?: unknown } }).route?.path;+ const route = typeof routePath === 'string' ? routePath : '(unmatched)';+ if (SKIPPED_PREFIXES.some(prefix => route.startsWith(prefix))) return;+ const seconds = Number(process.hrtime.bigint() - start) / 1e9;+ recordHttpRequest((req.method ?? 'UNKNOWN').toUpperCase(), route, res.statusCode ?? 200, seconds);+ };+ // `finish` sees the status the exception filter wrote (the guard's 401/403/429); `close`+ // covers a premature client disconnect. The claim flag keeps it to one observation.+ res.on('finish', record);+ res.on('close', record);+ next();+}diff --git a/src/common/services/shutdown.service.spec.ts b/src/common/services/shutdown.service.spec.tsindex 07922684d..29b36733b 100644--- a/src/common/services/shutdown.service.spec.ts+++ b/src/common/services/shutdown.service.spec.ts@@ -110,3 +110,51 @@ describe('ShutdownService.shutdown (idempotent, bounded grace)', () => {expect(cb).toHaveBeenCalledTimes(1);});});++describe('ShutdownService exit status (teardown outcome)', () => {+ let exitSpy: jest.SpyInstance;++ beforeEach(() => {+ jest.useFakeTimers();+ exitSpy = jest.spyOn(process, 'exit').mockImplementation((): never => undefined as never);+ process.env.SHUTDOWN_DELAY_MS = '0';+ });++ afterEach(() => {+ jest.clearAllTimers();+ jest.useRealTimers();+ exitSpy.mockRestore();+ delete process.env.SHUTDOWN_DELAY_MS;+ });++ it('exits 0 after a clean teardown', async () => {+ const svc = new ShutdownService();+ svc.setShutdownCallback(jest.fn().mockResolvedValue(undefined));+ svc.shutdown();+ await jest.advanceTimersByTimeAsync(0);+ expect(exitSpy).toHaveBeenCalledTimes(1);+ expect(exitSpy).toHaveBeenCalledWith(0);+ });++ it('exits non-zero when the teardown callback rejects (a failed drain is not a clean shutdown)', async () => {+ const svc = new ShutdownService();+ svc.setShutdownCallback(jest.fn().mockRejectedValue(new Error('engine disconnect wedged')));+ svc.shutdown();+ await jest.advanceTimersByTimeAsync(0);+ expect(exitSpy).toHaveBeenCalledTimes(1);+ expect(exitSpy).toHaveBeenCalledWith(1);+ });++ it('exits non-zero when the teardown callback throws synchronously', async () => {+ const svc = new ShutdownService();+ svc.setShutdownCallback(+ jest.fn().mockImplementation(() => {+ throw new Error('sync failure');+ }),+ );+ svc.shutdown();+ await jest.advanceTimersByTimeAsync(0);+ expect(exitSpy).toHaveBeenCalledTimes(1);+ expect(exitSpy).toHaveBeenCalledWith(1);+ });+});diff --git a/src/common/services/shutdown.service.ts b/src/common/services/shutdown.service.tsindex 29b17e5ad..e3cc2e5ec 100644--- a/src/common/services/shutdown.service.ts+++ b/src/common/services/shutdown.service.ts@@ -53,14 +53,24 @@ export class ShutdownService {setTimeout(() => {this.logger.log('Initiating shutdown...');const doShutdown = async () => {+ // The exit status mirrors the teardown outcome: 0 when teardown completed, 1 when it+ // failed — an orchestrator (k8s, systemd, docker restart policies) must not read a+ // resource-leaking shutdown as a clean one. (A teardown that HANGS never reaches this+ // exit at all; that case is bounded externally by the second-signal force-exit in+ // main.ts or the orchestrator's SIGKILL deadline.)+ let exitCode = 0;try {if (this.destroyCallback) {await this.destroyCallback();}} catch (error) {- this.logger.error('Error during shutdown', error instanceof Error ? error.message : String(error));+ exitCode = 1;+ this.logger.error(+ 'Shutdown teardown failed — exiting non-zero',+ error instanceof Error ? error.message : String(error),+ );} finally {- process.exit(0);+ process.exit(exitCode);}};void doShutdown();diff --git a/src/modules/metrics/metrics.module.ts b/src/modules/metrics/metrics.module.tsindex 06cae5e01..8fc7f6704 100644--- a/src/modules/metrics/metrics.module.ts+++ b/src/modules/metrics/metrics.module.ts@@ -1,10 +1,11 @@-import { Module } from '@nestjs/common';+import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';import { APP_INTERCEPTOR } from '@nestjs/core';import { ConfigModule } from '@nestjs/config';import { MetricsController } from './metrics.controller';import { MetricsService } from './metrics.service';import { StatsModule } from '../stats/stats.module';import { RequestMetricsInterceptor } from '../../common/interceptors/request-metrics.interceptor';+import { requestMetricsBoundaryMiddleware } from '../../common/middleware/request-metrics.middleware';@Module({imports: [ConfigModule, StatsModule],@@ -15,4 +16,12 @@ import { RequestMetricsInterceptor } from '../../common/interceptors/request-met{ provide: APP_INTERCEPTOR, useClass: RequestMetricsInterceptor },],})-export class MetricsModule {}+export class MetricsModule implements NestModule {+ configure(consumer: MiddlewareConsumer): void {+ // Middleware runs BEFORE the global guards, so this boundary sees the requests the guards+ // reject (throttler 429, API-key 401/403) that never reach the interceptor. The pair+ // coordinates through a per-request claim so each response is counted exactly once.+ // '*' resolves against the global prefix, i.e. every /api route.+ consumer.apply(requestMetricsBoundaryMiddleware).forRoutes('*');+ }+}diff --git a/test/app.e2e-spec.ts b/test/app.e2e-spec.tsindex 8461192d2..51ea73ac9 100644--- a/test/app.e2e-spec.ts+++ b/test/app.e2e-spec.ts@@ -8,6 +8,9 @@ import request from 'supertest';import { App } from 'supertest/types';import { AppModule } from './../src/app.module';import { applyGlobalValidation } from './../src/config/app-validation';+import { AuthService } from './../src/modules/auth/auth.service';+import { ApiKeyRole } from './../src/modules/auth/entities/api-key.entity';+import { renderHttpRequestMetrics, resetHttpRequestMetrics } from './../src/common/metrics/request-metrics';/*** Smoke e2e: the previous test asserted a non-existent Hello-World route and failed to@@ -67,3 +70,92 @@ describe('App smoke (e2e)', () => {return request(app.getHttpServer()).post('/mcp').send({ jsonrpc: '2.0', method: 'tools/list', id: 1 }).expect(404);});});++/**+ * RED-metrics honesty e2e: requests rejected by the global guards (API-key 401/403) never reach+ * the RequestMetricsInterceptor, so the boundary middleware must count them — with the real+ * status and the matched route pattern — while requests that pass the guards are still counted+ * exactly once (by the interceptor). Runs against the live app boot so the wiring (Nest+ * middleware order, Express req.route, exception-filter status) is the production one.+ */+describe('App RED metrics (e2e)', () => {+ let app: INestApplication<App>;+ let adminKey: string;+ let viewerKey: string;++ const lines = (): string[] => renderHttpRequestMetrics();+ const counter = (method: string, route: string, status: string): number => {+ const prefix = `http_requests_total{method="${method}",route="${route}",status="${status}"} `;+ const line = lines().find(l => l.startsWith(prefix));+ return line ? Number(line.slice(prefix.length)) : 0;+ };+ const totalRequests = (): number =>+ lines()+ .filter(l => l.startsWith('http_requests_total{'))+ .reduce((sum, l) => sum + Number(l.split('} ')[1]), 0);+ const totalDurationObservations = (): number =>+ lines()+ .filter(l => l.startsWith('http_request_duration_seconds_count{'))+ .reduce((sum, l) => sum + Number(l.split('} ')[1]), 0);++ beforeAll(async () => {+ const moduleFixture: TestingModule = await Test.createTestingModule({+ imports: [AppModule],+ }).compile();++ app = moduleFixture.createNestApplication();+ applyGlobalValidation(app);+ await app.init();++ const authService = app.get(AuthService);+ adminKey = (await authService.createApiKey({ name: 'e2e-red-admin', role: ApiKeyRole.ADMIN })).rawKey;+ viewerKey = (await authService.createApiKey({ name: 'e2e-red-viewer', role: ApiKeyRole.VIEWER })).rawKey;++ // The store is process-wide; count only this suite's requests from here on.+ resetHttpRequestMetrics();+ });++ afterAll(async () => {+ try {+ await app?.close();+ } catch {+ /* ignore teardown-only multi-datasource quirk */+ }+ });++ it('records a guard-rejected request (401, no API key) with its real status and route', async () => {+ await request(app.getHttpServer()).get('/api/sessions').expect(401);+ expect(counter('GET', '/api/sessions', '401')).toBe(1);+ expect(totalRequests()).toBe(1);+ });++ it('counts a request that passes the guards exactly once (no middleware/interceptor double-count)', async () => {+ await request(app.getHttpServer()).get('/api/sessions').set('X-API-Key', adminKey).expect(200);+ expect(counter('GET', '/api/sessions', '200')).toBe(1);+ expect(counter('GET', '/api/sessions', '401')).toBe(1); // unchanged by the 200+ expect(totalRequests()).toBe(2);+ });++ it('records a role-denied request (403, viewer key on an admin route)', async () => {+ await request(app.getHttpServer()).get('/api/auth/api-keys').set('X-API-Key', viewerKey).expect(403);+ expect(counter('GET', '/api/auth/api-keys', '403')).toBe(1);+ expect(totalRequests()).toBe(3);+ });++ it('still skips /api/health entirely', async () => {+ await request(app.getHttpServer()).get('/api/health').expect(200);+ expect(lines().some(l => l.includes('/api/health'))).toBe(false);+ expect(totalRequests()).toBe(3);+ });++ it('collapses unmatched routes (404) into the constant (unmatched) label', async () => {+ await request(app.getHttpServer()).get('/api/no-such-route').expect(404);+ expect(counter('GET', '(unmatched)', '404')).toBe(1);+ expect(totalRequests()).toBe(4);+ });++ it('keeps the request counter and duration histogram consistent (same observation count)', () => {+ expect(totalRequests()).toBe(4);+ expect(totalDurationObservations()).toBe(4);+ });+});