Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(metrics): let the restricted-sessions gauge follow expiry

Yudhi Armyndharis59b7d7c49522
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9e6ed745e..be5dafc07 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
+- The `openwa_sessions_restricted` gauge now follows a restriction that lapses on its own. It was republished only when a restriction was recorded or cleared, and an expiry is neither — so after a reachout timelock passed its stated end, the gauge kept reporting the pre-expiry count while every read path already reported the session as unrestricted, leaving an alert on `> 0` firing indefinitely and disagreeing with `GET /api/sessions`.
+
- Both compose files now forward the inbound-media knobs — `MEDIA_DOWNLOAD_ENABLED`, `MEDIA_DOWNLOAD_MAX_BYTES`, `MEDIA_DOWNLOAD_TIMEOUT_MS` and `INBOUND_MEDIA_CONCURRENCY`. None of the four reached the container, so an operator running the bundled stack who set `MEDIA_DOWNLOAD_ENABLED=false` in `.env` got no error and no log line while the gateway kept decrypting every inbound media blob and base64-inlining it into every message row at up to 50 MiB apiece. The cap and the timeout were equally unreachable. A gate now binds all four, in both files.
- `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.
diff --git a/src/common/metrics/session-restriction-metrics.ts b/src/common/metrics/session-restriction-metrics.ts
index 856dbf3c2..96dd6b004 100644
--- a/src/common/metrics/session-restriction-metrics.ts
+++ b/src/common/metrics/session-restriction-metrics.ts
@@ -9,12 +9,26 @@
*/
let restrictedSessions = 0;
+/**
+ * A live recount, registered by the store. The mirrored value above is refreshed on every mutation,
+ * but a restriction that lapses by its own `expiresAt` is not a mutation — nothing fires, and the
+ * gauge kept reporting the pre-expiry count while every read path already reported the session as
+ * unrestricted. Registering a function rather than importing the store keeps the dependency pointing
+ * one way: the session module knows about metrics, not the reverse.
+ */
+let recount: (() => number) | null = null;
+
/** Publish the current number of restricted sessions (called by SessionRestrictionStore). */
export function setRestrictedSessionCount(count: number): void {
restrictedSessions = count;
}
+/** Register the store's live recount. Called once, when the store is constructed. */
+export function registerRestrictedSessionRecount(fn: () => number): void {
+ recount = fn;
+}
+
/** Sessions under a WhatsApp-imposed restriction at this moment. */
export function getRestrictedSessionCount(): number {
- return restrictedSessions;
+ return recount ? recount() : restrictedSessions;
}
diff --git a/src/modules/session/session-restriction-store.service.spec.ts b/src/modules/session/session-restriction-store.service.spec.ts
index 90fcfb666..e02d6b7ba 100644
--- a/src/modules/session/session-restriction-store.service.spec.ts
+++ b/src/modules/session/session-restriction-store.service.spec.ts
@@ -179,3 +179,31 @@ describe('SessionRestrictionStore', () => {
);
});
});
+
+describe('the restricted-sessions gauge follows expiry, not just mutations', () => {
+ const timelock = (expiresAt: number): AccountRestriction =>
+ ({ kind: 'timelock', code: 'reachout', expiresAt }) as unknown as AccountRestriction;
+
+ it('drops to zero once the only restriction lapses, with no further mutation', () => {
+ const store = new SessionRestrictionStore();
+ store.set('s1', timelock(Date.now() + 60_000));
+ expect(getRestrictedSessionCount()).toBe(1);
+
+ // The clock passes the stated end. Nothing calls set() or clear().
+ jest.spyOn(Date, 'now').mockReturnValue(Date.now() + 120_000);
+ try {
+ expect(store.get('s1')).toBeUndefined(); // the read path already agrees it has lapsed
+ expect(getRestrictedSessionCount()).toBe(0);
+ } finally {
+ jest.spyOn(Date, 'now').mockRestore();
+ }
+ });
+
+ // Negative twin: a restriction still in force must keep being counted, or the fix would just
+ // zero the gauge.
+ it('keeps counting a restriction that is still in force', () => {
+ const store = new SessionRestrictionStore();
+ store.set('s2', timelock(Date.now() + 60_000));
+ expect(getRestrictedSessionCount()).toBe(1);
+ });
+});
diff --git a/src/modules/session/session-restriction-store.service.ts b/src/modules/session/session-restriction-store.service.ts
index 8c0276f03..f10fb6ac5 100644
--- a/src/modules/session/session-restriction-store.service.ts
+++ b/src/modules/session/session-restriction-store.service.ts
@@ -1,6 +1,9 @@
import { Injectable } from '@nestjs/common';
import type { AccountRestriction } from '../../engine/interfaces/whatsapp-engine.interface';
-import { setRestrictedSessionCount } from '../../common/metrics/session-restriction-metrics';
+import {
+ setRestrictedSessionCount,
+ registerRestrictedSessionRecount,
+} from '../../common/metrics/session-restriction-metrics';
import { Session } from './entities/session.entity';
/**
@@ -20,6 +23,22 @@ import { Session } from './entities/session.entity';
export class SessionRestrictionStore {
private readonly restrictions = new Map<string, AccountRestriction>();
+ constructor() {
+ // The mirrored gauge is refreshed on every mutation, but an expiry is not a mutation: a timelock
+ // that lapses on its own left the gauge claiming a session was restricted while get/size/attachTo
+ // all reported it was not. Registering the recount makes the gauge read what the API would say.
+ registerRestrictedSessionRecount(() => this.countInForce());
+ }
+
+ /** How many stored restrictions are still in force right now. */
+ private countInForce(): number {
+ let inForce = 0;
+ for (const sessionId of this.restrictions.keys()) {
+ if (this.inForce(sessionId)) inForce++;
+ }
+ return inForce;
+ }
+
/**
* Record a restriction the engine reported.
*
@@ -44,11 +63,7 @@ export class SessionRestrictionStore {
* read says it is not.
*/
private publishCount(): void {
- let inForce = 0;
- for (const sessionId of this.restrictions.keys()) {
- if (this.inForce(sessionId)) inForce++;
- }
- setRestrictedSessionCount(inForce);
+ setRestrictedSessionCount(this.countInForce());
}
/** The restriction in force, if any. `attachTo` is the projection; this is the raw read. */