Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

ralph(M15-206): CRASH BUG: a NaN duration in http.metrics.ts kills the API process - observeHttpRequest must not hand prom-client a non-finite number

ralph8175c3f420ae
diff --git a/packages/core/src/http/context.test.ts b/packages/core/src/http/context.test.ts
index 7e765a6e3..e31e9481a 100644
--- a/packages/core/src/http/context.test.ts
+++ b/packages/core/src/http/context.test.ts
@@ -224,6 +224,35 @@ describe('requestLogging', () => {
});
});
+ // The 2026-09-08 crash class: this hook is global, so it also fires for a
+ // request that matched no route — whose `derive` never ran. Reading
+ // `ctx.logger` off that missing ctx throws out of a hook nobody awaits, so
+ // it lands on the process, not on the request.
+ test('skips a request that matched no route instead of crashing', async () => {
+ const stub = build();
+ const crashes: unknown[] = [];
+ const record = (error: unknown) => crashes.push(error);
+ // Typed as the emitter it is: bun-types augments `NodeJS.Process` with an
+ // `off(event: 'memoryPressure')` that hides the inherited `off`.
+ const processEvents: NodeJS.EventEmitter = process;
+ processEvents.on('uncaughtException', record);
+ processEvents.on('unhandledRejection', record);
+
+ try {
+ const response = await stub.app.handle(
+ new Request('http://localhost/definitely-not-a-route')
+ );
+ await settled();
+
+ expect(response.status).toBe(404);
+ expect(crashes).toEqual([]);
+ expect(lines(stub)).toHaveLength(0);
+ } finally {
+ processEvents.off('uncaughtException', record);
+ processEvents.off('unhandledRejection', record);
+ }
+ });
+
test('skips the health, metrics and misc surfaces and OPTIONS', async () => {
const stub = build();
diff --git a/packages/core/src/http/context.ts b/packages/core/src/http/context.ts
index 4173b7b90..a07b98704 100644
--- a/packages/core/src/http/context.ts
+++ b/packages/core/src/http/context.ts
@@ -94,6 +94,12 @@ export function requestLogging(
.onAfterResponse(
{ as: 'global' },
({ ctx, request, path, query, body, timestamp, clientIpHeader }) => {
+ // The same shape as `httpMetrics`' guard: this hook is global and also
+ // runs for a request that matched no route, whose `derive` never ran.
+ // There is no request logger and no arrival timestamp to log with.
+ if (!ctx) {
+ return;
+ }
if (UNLOGGED_METHODS.includes(request.method)) {
return;
}
diff --git a/packages/core/src/http/http.metrics.test.ts b/packages/core/src/http/http.metrics.test.ts
index fa222c51f..5086cefad 100644
--- a/packages/core/src/http/http.metrics.test.ts
+++ b/packages/core/src/http/http.metrics.test.ts
@@ -1,16 +1,24 @@
import { beforeEach, expect, test } from 'bun:test';
+import { Elysia } from 'elysia';
import client from 'prom-client';
import { registry } from '../metrics';
-import { observeHttpRequest } from './http.metrics';
+import { httpMetrics, observeHttpRequest } from './http.metrics';
const HISTOGRAM = 'http_request_duration_seconds';
const SUMMARY = 'http_request_summary_seconds';
+const DROPPED = 'http_request_metrics_dropped_total';
+const HOOK_SETTLE_MS = 10;
async function samples(name: string) {
const metric = await registry.getSingleMetricAsString(name);
return metric;
}
+async function dropped() {
+ const metric = await registry.getSingleMetric(DROPPED)?.get();
+ return metric?.values[0]?.value;
+}
+
beforeEach(() => {
registry.resetMetrics();
});
@@ -79,3 +87,48 @@ test('an unmatched request produces no series (registeredRoutesOnly)', async ()
expect(await samples(SUMMARY)).not.toContain('status_code="404"');
});
+
+// The 2026-09-08 crash: a global `onAfterResponse` fires for a request whose
+// `derive` never ran, `performance.now() - undefined` is NaN, prom-client
+// throws on it, and in an async hook that throw exits the process.
+test('a duration that is not a finite number >= 0 is dropped, not thrown on', async () => {
+ const unobservable = [
+ Number.NaN,
+ Number.POSITIVE_INFINITY,
+ Number.NEGATIVE_INFINITY,
+ undefined as unknown as number,
+ -1,
+ ];
+
+ for (const durationMs of unobservable) {
+ expect(() =>
+ observeHttpRequest({
+ method: 'GET',
+ route: '/some-route',
+ statusCode: 500,
+ durationMs,
+ })
+ ).not.toThrow();
+ }
+
+ expect(await samples(HISTOGRAM)).not.toContain('route="/some-route"');
+ expect(await samples(SUMMARY)).not.toContain('route="/some-route"');
+ // Dropped, but visible.
+ expect(await dropped()).toBe(unobservable.length);
+});
+
+test('the hook skips a request that matched no route, and drops nothing', async () => {
+ const app = new Elysia().use(httpMetrics()).get('/ok', () => 'ok');
+
+ await app.handle(new Request('http://localhost/ok'));
+ await app.handle(new Request('http://localhost/definitely-not-a-route'));
+ // `onAfterResponse` runs off the response's own microtask tail.
+ await new Promise((resolve) => setTimeout(resolve, HOOK_SETTLE_MS));
+
+ const text = await samples(HISTOGRAM);
+ expect(text).toContain('route="/ok"');
+ expect(text).not.toContain('definitely-not-a-route');
+ expect(text).not.toContain('status_code="404"');
+ // 0, not 1: the hook returns before it can compute a bad duration.
+ expect(await dropped()).toBe(0);
+});
diff --git a/packages/core/src/http/http.metrics.ts b/packages/core/src/http/http.metrics.ts
index 13e38d99e..2bd0f2cd6 100644
--- a/packages/core/src/http/http.metrics.ts
+++ b/packages/core/src/http/http.metrics.ts
@@ -38,6 +38,8 @@ const UNMATCHED_ROUTES = new Set(['', '/*']);
const MS_PER_SECOND = 1000;
// Elysia leaves `set.status` unset on a plain successful return.
const DEFAULT_STATUS = 200;
+const DROPPED_HELP =
+ 'http request samples dropped before observation because the measured duration was not a finite number of milliseconds >= 0';
export const httpRequestDuration = new client.Histogram({
name: 'http_request_duration_seconds',
@@ -53,20 +55,47 @@ export const httpRequestSummary = new client.Summary({
registers: [registry],
});
+// A bad sample must never take the process down, but it must not vanish
+// either: prom-client's `.observe()` throws on a non-finite value, and in an
+// async hook that throw becomes an unhandled rejection and exits the process.
+export const httpRequestSamplesDropped = new client.Counter({
+ name: 'http_request_metrics_dropped_total',
+ help: DROPPED_HELP,
+ registers: [registry],
+});
+
+/** The one shape prom-client will accept: finite, and not a negative elapsed. */
+function isMeasuredDuration(durationMs: unknown): durationMs is number {
+ return (
+ typeof durationMs === 'number' &&
+ Number.isFinite(durationMs) &&
+ durationMs >= 0
+ );
+}
+
/**
* Observes a single request. Exported so a test can assert the labels and the
* unit without standing up a server.
+ *
+ * Drops, rather than throws on, a sample it cannot observe — see
+ * `httpRequestSamplesDropped`.
*/
export function observeHttpRequest(sample: {
method: string;
- route: string;
+ // Elysia types this `string`, but hands the hook `undefined` when the
+ // request matched no route.
+ route: string | undefined;
statusCode: number;
durationMs: number;
}): void {
if (UNMEASURED_METHODS.has(sample.method)) {
return;
}
- if (UNMATCHED_ROUTES.has(sample.route)) {
+ if (!sample.route || UNMATCHED_ROUTES.has(sample.route)) {
+ return;
+ }
+ if (!isMeasuredDuration(sample.durationMs)) {
+ httpRequestSamplesDropped.inc();
return;
}
@@ -90,6 +119,12 @@ export function observeHttpRequest(sample: {
* The start time rides on a `derive`, not on `store` — `store` is app-level
* state shared by every in-flight request, so a second concurrent request
* would overwrite the first one's clock.
+ *
+ * A `derive` runs per MATCHED route; this hook is global and also runs for a
+ * request that matched nothing, where `metricsStartedAt` and `route` are both
+ * `undefined`. Such a request has no clock and no route pattern to label, and
+ * `registeredRoutesOnly` says not to observe it anyway — so the hook skips,
+ * ahead of computing an elapsed against `undefined`.
*/
export function httpMetrics() {
return new Elysia({ name: 'core/http/metrics' })
@@ -97,6 +132,9 @@ export function httpMetrics() {
.onAfterResponse(
{ as: 'global' },
({ request, route, set, metricsStartedAt }) => {
+ if (!isMeasuredDuration(metricsStartedAt)) {
+ return;
+ }
observeHttpRequest({
method: request.method,
route,