Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(metrics): keep the scrape alive when the stats query fails

Yudhi Armyndharisdd6bc6fc0d2d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0b02a2e16..8c1283359 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- `GET /api/metrics` no longer fails the whole scrape when the data database is unreachable. `render()` awaited a stats query unguarded, so a statement timeout, pool exhaustion, a `SQLITE_BUSY` under load or a genuine outage answered every scrape with a 500 once the 30-second stats memo lapsed — costing Prometheus the process, HTTP and webhook series too, and making `up` conflate a dead process with an unreachable database, during the exact incident the endpoint exists to describe. The database-derived series are now omitted rather than reported as zero (a zero would fire an alert claiming every session had dropped), and a new `openwa_stats_available` gauge says which of the two happened.
+
- An authorization denial now records WHICH credential was denied. Both post-authentication 403s — an insufficient role, and a session-scoped key on a route that forbids one — threw before the resolved key was stamped into the request context, so every such audit row carried `apiKeyId` and `apiKeyName` as null. Behind NAT or a reverse proxy without `TRUSTED_PROXIES` the recorded IP is common to every tenant, leaving an operator able to see that a key had been denied but not which one to revoke. The same stamp was added to the queue-dashboard mount, which has the same shape. A denial that happens before any key resolves is unchanged: the IP really is all there is.
- The three group-picture routes now refuse an id that does not name a group. They reuse the account's own profile-picture primitives, and Baileys omits the `target` attribute whenever the jid is the account's own — so `PUT` or `DELETE /sessions/:id/groups/<own-jid>/picture` replaced or permanently deleted the WhatsApp account's own avatar and answered `{success: true}`, while whatsapp-web.js refused the same input with a 404. Both engines now reject it with a 400 before the id reaches either adapter.
diff --git a/src/modules/metrics/metrics.service.spec.ts b/src/modules/metrics/metrics.service.spec.ts
index 3bddc5757..b5baf3efd 100644
--- a/src/modules/metrics/metrics.service.spec.ts
+++ b/src/modules/metrics/metrics.service.spec.ts
@@ -114,3 +114,51 @@ describe('MetricsService', () => {
});
});
});
+
+// The scrape had a hard runtime dependency on the data database: render() awaited
+// StatsService.getOverview() unguarded, so once the stats memo lapsed during a database problem
+// EVERY scrape answered 500 and Prometheus lost the whole target — including the process and HTTP
+// series that need no database at all, during the exact incident they exist for.
+describe('MetricsService.render survives a failing stats query', () => {
+ const healthyOverview: OverviewStats = {
+ sessions: { active: 2, total: 3, byStatus: { ready: 2, failed: 1 } },
+ messages: { sent: 100, received: 50, failed: 3, today: { sent: 10, received: 5 } },
+ };
+
+ const failing = (): MetricsService => {
+ const config = { get: () => undefined } as unknown as ConfigService;
+ const stats = {
+ getOverview: jest.fn().mockRejectedValue(new Error('SQLITE_BUSY: database is locked')),
+ } as unknown as StatsService;
+ return new MetricsService(config, stats);
+ };
+
+ it('still serves the series that need no database', async () => {
+ const text = await failing().render();
+
+ expect(text).toContain('openwa_up 1');
+ expect(text).toContain('openwa_process_uptime_seconds');
+ expect(text).toContain('openwa_process_resident_memory_bytes');
+ expect(text).toContain('openwa_webhook_delivery_failures_total');
+ });
+
+ it('signals that the database-derived series are missing rather than reporting them as zero', async () => {
+ const text = await failing().render();
+
+ expect(text).toContain('openwa_stats_available 0');
+ // A stale or invented 0 would be worse than an absent series: an alert on
+ // openwa_sessions_active would fire as if every session had dropped.
+ expect(text).not.toContain('openwa_sessions_active');
+ expect(text).not.toContain('openwa_messages_total');
+ });
+
+ // Negative twin: a healthy scrape must still carry the database-derived series and say so.
+ it('reports the stats source as available on a healthy scrape', async () => {
+ const config = { get: () => undefined } as unknown as ConfigService;
+ const stats = { getOverview: jest.fn().mockResolvedValue(healthyOverview) } as unknown as StatsService;
+ const text = await new MetricsService(config, stats).render();
+
+ expect(text).toContain('openwa_stats_available 1');
+ expect(text).toContain('openwa_sessions_active 2');
+ });
+});
diff --git a/src/modules/metrics/metrics.service.ts b/src/modules/metrics/metrics.service.ts
index 2bd6ea687..75981ebd6 100644
--- a/src/modules/metrics/metrics.service.ts
+++ b/src/modules/metrics/metrics.service.ts
@@ -10,6 +10,7 @@ import {
import { getRestrictedSessionCount } from '../../common/metrics/session-restriction-metrics';
import { getSendPacingRefusals } from '../../common/metrics/send-pacing-metrics';
import { renderHttpRequestMetrics } from '../../common/metrics/request-metrics';
+import { createLogger } from '../../common/services/logger.service';
/**
* Prometheus exposition for OpenWA. Kept dependency-free (no prom-client) — the
@@ -29,6 +30,8 @@ export const METRICS_RENDER_TTL_MS = 5000;
@Injectable()
export class MetricsService {
+ private readonly logger = createLogger('MetricsService');
+
private cachedRender: { at: number; text: string } | null = null;
constructor(
@@ -69,7 +72,21 @@ export class MetricsService {
return this.cachedRender.text;
}
- const overview = await this.statsService.getOverview();
+ // The database-derived series are best-effort. Awaiting them unguarded meant a single rejected
+ // query — a statement timeout, pool exhaustion, SQLITE_BUSY under load, or a genuine outage —
+ // answered the whole scrape with a 500, so Prometheus lost the process, HTTP and webhook series
+ // too, and `up` conflated "process dead" with "database unreachable": the exact incident this
+ // endpoint exists to describe. The series that need no database are emitted either way, and the
+ // ones that do are OMITTED rather than reported as zero, because a zero would fire an alert
+ // claiming every session had dropped.
+ let overview: Awaited<ReturnType<StatsService['getOverview']>> | null = null;
+ try {
+ overview = await this.statsService.getOverview();
+ } catch (err) {
+ this.logger.warn(
+ `Metrics scrape could not read stats; database-derived series omitted: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
const mem = process.memoryUsage();
const lines: string[] = [];
@@ -84,24 +101,32 @@ export class MetricsService {
gauge('openwa_process_resident_memory_bytes', 'Resident set size in bytes.', mem.rss);
gauge('openwa_process_heap_used_bytes', 'V8 heap used in bytes.', mem.heapUsed);
- gauge('openwa_sessions_total', 'Total number of configured sessions.', overview.sessions.total);
- gauge('openwa_sessions_active', 'Number of READY (active) sessions.', overview.sessions.active);
+ gauge(
+ 'openwa_stats_available',
+ 'Whether the database-derived series below could be read on this scrape (1) or not (0).',
+ overview ? 1 : 0,
+ );
- // Per-status session counts share one metric name with a `status` label.
- lines.push('# HELP openwa_sessions Number of sessions by status.');
- lines.push('# TYPE openwa_sessions gauge');
- for (const [status, count] of Object.entries(overview.sessions.byStatus)) {
- lines.push(`openwa_sessions{status="${this.escapeLabel(status)}"} ${count}`);
- }
+ if (overview) {
+ gauge('openwa_sessions_total', 'Total number of configured sessions.', overview.sessions.total);
+ gauge('openwa_sessions_active', 'Number of READY (active) sessions.', overview.sessions.active);
- lines.push('# HELP openwa_messages_total Current stored messages by direction.');
- lines.push('# TYPE openwa_messages_total gauge');
- lines.push(`openwa_messages_total{direction="outgoing"} ${overview.messages.sent}`);
- lines.push(`openwa_messages_total{direction="incoming"} ${overview.messages.received}`);
+ // Per-status session counts share one metric name with a `status` label.
+ lines.push('# HELP openwa_sessions Number of sessions by status.');
+ lines.push('# TYPE openwa_sessions gauge');
+ for (const [status, count] of Object.entries(overview.sessions.byStatus)) {
+ lines.push(`openwa_sessions{status="${this.escapeLabel(status)}"} ${count}`);
+ }
+
+ lines.push('# HELP openwa_messages_total Current stored messages by direction.');
+ lines.push('# TYPE openwa_messages_total gauge');
+ lines.push(`openwa_messages_total{direction="outgoing"} ${overview.messages.sent}`);
+ lines.push(`openwa_messages_total{direction="incoming"} ${overview.messages.received}`);
- lines.push('# HELP openwa_messages_failed_total Current stored messages in FAILED state.');
- lines.push('# TYPE openwa_messages_failed_total gauge');
- lines.push(`openwa_messages_failed_total ${overview.messages.failed}`);
+ lines.push('# HELP openwa_messages_failed_total Current stored messages in FAILED state.');
+ lines.push('# TYPE openwa_messages_failed_total gauge');
+ lines.push(`openwa_messages_failed_total ${overview.messages.failed}`);
+ }
lines.push(
'# HELP openwa_webhook_delivery_failures_total Webhook deliveries that terminally failed (all retries exhausted) since process start.',