Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(metrics): bound how long a statistics read can pin its answer

Yudhi Armyndharis5e476b284957
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index a4d725b93..2d3a2aa9f 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -5284,8 +5284,8 @@ When the data database cannot be read the database-derived series (`openwa_sessi
`openwa_messages*`) are OMITTED rather than reported as zero — a zero would fire an alert
claiming every session had dropped. `openwa_stats_available` is what tells the two cases apart,
so alert on it rather than reading a missing series as zero. A scrape waits at most 2 seconds for
-that read and serves the last result it kept, up to 5 minutes old, when it is late; the series are omitted when
-the read failed or no result is that recent, so a database that stalls costs those series and not the
+that read and serves the last result it kept, up to 5 minutes after that read started, when it is late; the series are omitted when
+the read failed (which also discards the kept result) or no result is that recent, so a database that stalls costs those series and not the
rest of the scrape. `docs/10` lists every series.
```
@@ -5314,7 +5314,7 @@ openwa_messages_total{direction="incoming"} 940
openwa_messages_failed_total 4
```
-Values come from `StatsService.getOverview()` plus `process.memoryUsage()`/`process.uptime()`. The render is memoized for 5000 ms to avoid re-running the overview query on every scrape, and `getOverview()` is itself memoized for `STATS_CACHE_TTL_MS` (default 30 s), so the database-derived series and `openwa_stats_available` can trail the data database by up to `STATS_CACHE_TTL_MS` + 5 s plus the time the overview query takes (the memo TTL counts from when the query completes).
+Values come from `StatsService.getOverview()` plus `process.memoryUsage()`/`process.uptime()`. The render is memoized for 5000 ms to avoid re-running the overview query on every scrape, and `getOverview()` is itself memoized for `STATS_CACHE_TTL_MS` (default 30 s), so the database-derived series and `openwa_stats_available` can trail the data database by up to `STATS_CACHE_TTL_MS` + 5 s plus the time the overview query takes (the memo TTL counts from when the query completes), or by up to 5 minutes when the database stops answering and the last kept result stands in for the late read.
**Errors:** `401` — `METRICS_TOKEN` is configured but the bearer is missing or does not match (`{ "statusCode": 401, "message": "Invalid metrics token", "error": "Unauthorized" }`) · `404` — `METRICS_TOKEN` is unset/blank, so the endpoint is disabled (`{ "statusCode": 404, "message": "Metrics endpoint is disabled (set METRICS_TOKEN to enable)", "error": "Not Found" }`) · `429`: 10 failed token attempts from one client within a minute; only failures count, and the block lifts as the window slides (`{ "statusCode": 429, "message": "Too many failed metrics token attempts" }`).
diff --git a/docs/10-devops-infrastructure.md b/docs/10-devops-infrastructure.md
index 1f3176d75..466f47867 100644
--- a/docs/10-devops-infrastructure.md
+++ b/docs/10-devops-infrastructure.md
@@ -931,10 +931,12 @@ short TTL (~5s, so back-to-back scrapes don't repeat the DB scan), and exposes i
`GET /api/metrics`.
A scrape waits at most 2 seconds for that overview. When the read fails, the database-derived series are
-left out and `openwa_stats_available` reads 0. When it is still pending after that, the scrape serves the last
-result it kept, up to 5 minutes old, and `openwa_stats_available` stays 1; the late result fills the memo for the
-next scrape. With no result that recent, such as the first scrape after start, the series are left out and the
-gauge reads 0. The process, HTTP, webhook and queue series are served as usual. A read still pending is shared by the scrapes that arrive
+left out and `openwa_stats_available` reads 0, and the result the last good read kept is discarded. When it is
+still pending after that, the scrape serves the last result it kept, up to 5 minutes after that read started, and
+`openwa_stats_available` stays 1; the late result fills the memo and is kept for the next scrape. With no result
+that recent, such as the first scrape after start, or a read that has hung for more than 5 minutes after the last
+good one, the series are left out and the gauge reads 0. A read still pending after 5 minutes is given up on and the
+next scrape starts a new one. The process, HTTP, webhook and queue series are served as usual. A read still pending is shared by the scrapes that arrive
meanwhile, so they answer without waiting again and add no query of their own, whatever
`STATS_CACHE_TTL_MS` is. The 2 seconds bound the wait, not the query: nothing cancels it in the database.
@@ -995,7 +997,7 @@ export class MetricsService {
| `openwa_event_loop_delay_max_seconds` | gauge | none | Maximum event-loop delay since the previous uncached scrape |
| `openwa_unhandled_rejections_total` | counter | `kind` | Unhandled promise rejections since process start (`other` or `page_context_lost`) |
| `openwa_queue_jobs` | gauge | `queue`, `state` | BullMQ jobs per queue in `wait`/`active`/`delayed`/`failed` (cluster-wide, from Redis) |
-| `openwa_stats_available` | gauge | — | 1 when the last overview read of the database-derived series below succeeded, or is served from a late read (5 min), 0 if it failed |
+| `openwa_stats_available` | gauge | — | 1 when the last overview read of the database-derived series below succeeded or a kept result under 5 minutes old stands in, else 0 |
| `openwa_sessions_total` | gauge | — | Configured sessions |
| `openwa_sessions_active` | gauge | — | READY (active) sessions |
| `openwa_sessions` | gauge | `status` | Session count per status |
@@ -1041,8 +1043,10 @@ seen, so keep new renderers on that composition.
> and still means "the process is alive". Alert on `openwa_stats_available == 0` for the degradation itself;
> an alert written as `openwa_sessions_active == 0` would never fire for it, and one written with `absent()`
> would. Because of the two caches, `openwa_stats_available` can keep reporting 1, and the series their last
-> values, for up to `STATS_CACHE_TTL_MS` + 5 s after the data database fails, so expect an alert on it to fire
-> up to that much later; a `for:` adds to that delay rather than offsetting it. `STATS_CACHE_TTL_MS=0` makes
+> values, for up to `STATS_CACHE_TTL_MS` + 5 s after the data database fails. When the database stops answering
+> instead of failing, the last kept result stands in for the late read, so it can keep reporting 1 for up to 5
+> minutes after the last good read started. Expect an alert on it to fire up to that much later; a `for:` adds to
+> that delay rather than offsetting it. `STATS_CACHE_TTL_MS=0` makes
> the signal live at the cost of a full overview query per render.
### Grafana Dashboard Definition
diff --git a/src/modules/metrics/metrics-render-budget.spec.ts b/src/modules/metrics/metrics-render-budget.spec.ts
index 7aa93b4fe..38adffa89 100644
--- a/src/modules/metrics/metrics-render-budget.spec.ts
+++ b/src/modules/metrics/metrics-render-budget.spec.ts
@@ -137,6 +137,38 @@ describe('MetricsService bounded degraded renders', () => {
}
});
+ it('keeps the numbers of a newer read when a read given up on settles afterwards', async () => {
+ const abandoned = deferred<OverviewStats>();
+ const hung = deferred<OverviewStats>();
+ const newer: OverviewStats = { ...overview, sessions: { ...overview.sessions, active: 7 } };
+ const f = fixture(() => abandoned.promise);
+ f.stats.getOverview.mockImplementationOnce(() => abandoned.promise);
+ f.stats.getOverview.mockImplementationOnce(() => Promise.resolve(newer));
+ f.stats.getOverview.mockImplementationOnce(() => hung.promise);
+ const calls = [observe(f.scrape())];
+ try {
+ await jest.advanceTimersByTimeAsync(STATS_BUDGET_MS);
+ degraded(calls[0].result);
+ await jest.advanceTimersByTimeAsync(STATS_STALE_MAX_MS);
+ const second = await f.scrape();
+ expect(f.stats.getOverview).toHaveBeenCalledTimes(2);
+ expect(second).toContain('openwa_sessions_active 7');
+
+ abandoned.resolve(overview);
+ await jest.advanceTimersByTimeAsync(METRICS_RENDER_TTL_MS + 1);
+ const third = observe(f.scrape());
+ calls.push(third);
+ await jest.advanceTimersByTimeAsync(STATS_BUDGET_MS);
+ expect(f.stats.getOverview).toHaveBeenCalledTimes(3);
+ expect(third.result.text).toContain('openwa_stats_available 1');
+ expect(third.result.text).toContain('openwa_sessions_active 7');
+ } finally {
+ abandoned.resolve(overview);
+ hung.resolve(overview);
+ await Promise.all(calls.map(call => call.done));
+ }
+ });
+
it('retains healthy values and serves the completed render from cache', async () => {
const f = fixture(() => Promise.resolve(overview));
const first = await f.scrape();
@@ -207,17 +239,32 @@ describe('MetricsService statistics slower than its budget, with the real stats
const SCAN_MS = 3000;
const later = <T>(value: T, delay = SCAN_MS) => new Promise<T>(resolve => setTimeout(() => resolve(value), delay));
function slowDatabase() {
- const state = { fail: false };
+ const state: { fail: boolean; delay: number; hang?: { promise: Promise<unknown[]>; release: () => void } } = {
+ fail: false,
+ delay: SCAN_MS,
+ };
+ const hold = () => {
+ let release!: () => void;
+ const promise = new Promise<unknown[]>(resolve => {
+ release = () => resolve([{ status: 'ready' }]);
+ });
+ state.hang = { promise, release };
+ };
const query = (): Record<string, unknown> => {
const chain: Record<string, unknown> = {};
for (const step of ['select', 'addSelect', 'where', 'groupBy']) chain[step] = () => chain;
- chain.getRawMany = () => later([{ direction: 'outgoing', count: '4' }]);
+ chain.getRawMany = () => later([{ direction: 'outgoing', count: '4' }], state.delay);
return chain;
};
const sessions = {
- find: () => (state.fail ? Promise.reject(new Error('pool exhausted')) : later([{ status: 'ready' }])),
+ find: () =>
+ state.hang
+ ? state.hang.promise
+ : state.fail
+ ? Promise.reject(new Error('pool exhausted'))
+ : later([{ status: 'ready' }], state.delay),
};
- const messages = { createQueryBuilder: query, count: () => later(1) };
+ const messages = { createQueryBuilder: query, count: () => later(1, state.delay) };
const stats = new StatsService(
sessions as never,
messages as never,
@@ -234,7 +281,7 @@ describe('MetricsService statistics slower than its budget, with the real stats
service.assertScrapeAuthorized('Bearer fixture-token', { headers: {}, socket: { remoteAddress: '192.0.2.1' } });
return service.render();
};
- return { state, scrape };
+ return { state, hold, scrape };
}
const scrapeAfter = async (scrape: () => Promise<string>, interval: number): Promise<string> => {
const pending = scrape();
@@ -263,18 +310,47 @@ describe('MetricsService statistics slower than its budget, with the real stats
}
});
- it('drops the series once the last result is older than the stale bound', async () => {
+ it('stops serving the kept result 5 minutes after its read started while a read hangs, then recovers', async () => {
const db = slowDatabase();
- await scrapeAfter(db.scrape, SCAN_MS);
- expect(await scrapeAfter(db.scrape, STATS_STALE_MAX_MS)).toContain('openwa_stats_available 0');
+ db.state.delay = 0;
+ expect(await scrapeAfter(db.scrape, 60_000)).toContain('openwa_stats_available 1');
+ db.hold();
+
+ const flags: string[] = [];
+ // Scrapes at 60 s steps from the good read: ages 62 s to 242 s are served from the kept result.
+ for (let i = 0; i < 4; i++) flags.push(await scrapeAfter(db.scrape, 60_000));
+ for (const text of flags) {
+ expect(text).toContain('openwa_stats_available 1');
+ expect(text).toContain('openwa_messages_total{direction="outgoing"} 4');
+ }
+ // At 5 minutes the kept result is too old, and so is the read: it is given up on and a new one starts.
+ for (let i = 0; i < 2; i++) {
+ const text = await scrapeAfter(db.scrape, 60_000);
+ expect(text).toContain('openwa_stats_available 0');
+ expect(text).not.toContain('openwa_sessions_active');
+ }
+
+ db.state.hang!.release();
+ await jest.advanceTimersByTimeAsync(METRICS_RENDER_TTL_MS + 1);
+ const recovered = await scrapeAfter(db.scrape, 1);
+ expect(recovered).toContain('openwa_stats_available 1');
+ expect(recovered).toContain('openwa_messages_total{direction="outgoing"} 4');
});
- it('does not stand in for a read that failed', async () => {
+ it('does not serve numbers from before a failed read when a later read is late', async () => {
const db = slowDatabase();
+ db.state.delay = 0;
await scrapeAfter(db.scrape, 60_000);
db.state.fail = true;
const failed = await scrapeAfter(db.scrape, 60_000);
expect(failed).toContain('openwa_stats_available 0');
- expect(failed).not.toContain('openwa_sessions_active');
+ db.state.fail = false;
+ db.state.delay = SCAN_MS;
+ const late = await scrapeAfter(db.scrape, 60_000);
+ expect(late).toContain('openwa_stats_available 0');
+ expect(late).not.toContain('openwa_sessions_active');
+ // The late read completed, so it is what the next late read falls back to.
+ const next = await scrapeAfter(db.scrape, 60_000);
+ expect(next).toContain('openwa_stats_available 1');
});
});
diff --git a/src/modules/metrics/metrics.service.ts b/src/modules/metrics/metrics.service.ts
index 9d898e1d5..e3860e3a4 100644
--- a/src/modules/metrics/metrics.service.ts
+++ b/src/modules/metrics/metrics.service.ts
@@ -51,9 +51,10 @@ export const QUEUE_READ_TIMEOUT_MS = 2000;
export const STATS_READ_TIMEOUT_MS = 2000;
/**
- * How long the last overview read stands in for one that is slower than the budget. A read that outlasts the
- * budget still completes, and the stats memo it fills expires before a scrape interval of a minute comes round
- * again, so without this every such scrape would meet a cold memo and drop the series.
+ * How long the last overview read stands in for one that is slower than the budget, counted from when that read
+ * started. A read that outlasts the budget still completes, and the stats memo it fills expires before a scrape
+ * interval of a minute comes round again, so without this every such scrape would meet a cold memo and drop the
+ * series. A read still pending after this long is given up on and a new one starts.
*/
export const STATS_STALE_MAX_MS = 5 * 60_000;
@@ -73,7 +74,11 @@ export class MetricsService implements OnModuleDestroy {
private cachedRender: { at: number; text: string } | null = null;
private pendingOverview: Promise<OverviewStats | null> | null = null;
+ private pendingSince = 0;
+ /** What the newest read to finish kept: its result and when it started, or nothing after a failure. */
private lastOverview: { overview: OverviewStats; at: number } | null = null;
+ private readSeq = 0;
+ private keptSeq = 0;
/**
* The route skips the shared throttler so a scrape interval costs no request budget, which left
@@ -199,7 +204,7 @@ export class MetricsService implements OnModuleDestroy {
gauge(
'openwa_stats_available',
- 'Whether the database-derived series below could be read (1) or not (0); cached up to STATS_CACHE_TTL_MS + 5 s.',
+ 'Whether the database-derived series below could be read (1) or not (0); they can trail the database by STATS_CACHE_TTL_MS + 5 s, or up to 5 min while a read runs late.',
overview ? 1 : 0,
);
@@ -266,12 +271,21 @@ export class MetricsService implements OnModuleDestroy {
/**
* The overview, or null when it failed or did not settle within STATS_READ_TIMEOUT_MS and no recent one is
- * known. The wait is shared until the read itself settles, so scrapes arriving behind a stuck read neither
- * queue up nor each start a deadline of their own. A read that only runs late is kept when it completes, and
- * stands in for the next scrape that finds it late again (STATS_STALE_MAX_MS); a failed read never does.
+ * kept. Scrapes arriving inside that wait share it, so they neither queue up nor start a deadline of their own.
+ * Once it has run out, scrapes behind the same read do not wait again: they get the kept result while it is
+ * younger than STATS_STALE_MAX_MS, else nothing, and past that age the read is given up on and a new one starts.
+ * A read that only runs late is kept when it completes; a failed one discards what an earlier read kept.
*/
private readOverviewOrNull(): Promise<OverviewStats | null> {
- if (this.pendingOverview) return this.pendingOverview;
+ const now = Date.now();
+ if (this.pendingOverview) {
+ const waited = now - this.pendingSince;
+ if (waited < STATS_READ_TIMEOUT_MS) return this.pendingOverview;
+ if (waited < STATS_STALE_MAX_MS) return Promise.resolve(this.recentOverview());
+ this.logger.warn('Metrics scrape gave up on a statistics read that never settled; starting a new one');
+ }
+ this.pendingSince = now;
+ const seq = ++this.readSeq;
const work = Promise.resolve().then(() => this.statsService.getOverview());
const late = new Error('statistics read timed out');
let timer: ReturnType<typeof setTimeout> | undefined;
@@ -296,13 +310,19 @@ export class MetricsService implements OnModuleDestroy {
},
);
this.pendingOverview = waiting;
- const settled = (): void => {
+ // Only a read newer than the one the kept result came from may replace it, so an abandoned read that
+ // settles after its successor changes nothing.
+ const settled = (kept: { overview: OverviewStats; at: number } | null): void => {
+ if (seq > this.keptSeq) {
+ this.keptSeq = seq;
+ this.lastOverview = kept;
+ }
if (this.pendingOverview === waiting) this.pendingOverview = null;
};
- void work.then(overview => {
- this.lastOverview = { overview, at: Date.now() };
- settled();
- }, settled);
+ void work.then(
+ overview => settled({ overview, at: now }),
+ () => settled(null),
+ );
return waiting;
}