@sherlock-labs/node 0.0.0-stage → 0.3.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,18 @@
1
+ import { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { A as AdapterOptions } from './httpServerMetrics-BfVoFAxd.mjs';
3
+
4
+ interface ExpressRequest extends IncomingMessage {
5
+ /** The URL as it arrived, before a mounted router rewrote `url`. */
6
+ originalUrl?: string;
7
+ /** Mount path of the router that handled the request, '' at the top level. */
8
+ baseUrl?: string;
9
+ /** Set by Express once a route matched; `path` is the template, not the URL. */
10
+ route?: {
11
+ path?: string | RegExp | Array<string | RegExp>;
12
+ };
13
+ }
14
+ type ExpressNext = (err?: unknown) => void;
15
+ type ExpressMiddleware = (req: ExpressRequest, res: ServerResponse, next: ExpressNext) => void;
16
+ declare function applyMetricsMiddleware(options?: AdapterOptions<ExpressRequest>): ExpressMiddleware;
17
+
18
+ export { type ExpressRequest, applyMetricsMiddleware };
@@ -0,0 +1,18 @@
1
+ import { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { A as AdapterOptions } from './httpServerMetrics-BfVoFAxd.js';
3
+
4
+ interface ExpressRequest extends IncomingMessage {
5
+ /** The URL as it arrived, before a mounted router rewrote `url`. */
6
+ originalUrl?: string;
7
+ /** Mount path of the router that handled the request, '' at the top level. */
8
+ baseUrl?: string;
9
+ /** Set by Express once a route matched; `path` is the template, not the URL. */
10
+ route?: {
11
+ path?: string | RegExp | Array<string | RegExp>;
12
+ };
13
+ }
14
+ type ExpressNext = (err?: unknown) => void;
15
+ type ExpressMiddleware = (req: ExpressRequest, res: ServerResponse, next: ExpressNext) => void;
16
+ declare function applyMetricsMiddleware(options?: AdapterOptions<ExpressRequest>): ExpressMiddleware;
17
+
18
+ export { type ExpressRequest, applyMetricsMiddleware };
@@ -0,0 +1,320 @@
1
+ 'use strict';
2
+
3
+ var perf_hooks = require('perf_hooks');
4
+ var api = require('@opentelemetry/api');
5
+ require('@opentelemetry/core');
6
+
7
+ // src/express.ts
8
+
9
+ // src/shared.ts
10
+ var REGISTRY_KEY = /* @__PURE__ */ Symbol.for("@sherlock-labs/node:state:v1");
11
+ function registry() {
12
+ const holder = globalThis;
13
+ let existing = holder[REGISTRY_KEY];
14
+ if (!existing) {
15
+ existing = /* @__PURE__ */ new Map();
16
+ holder[REGISTRY_KEY] = existing;
17
+ }
18
+ return existing;
19
+ }
20
+ function shared(name, create) {
21
+ const store = registry();
22
+ const existing = store.get(name);
23
+ if (existing) {
24
+ return existing;
25
+ }
26
+ const created = create();
27
+ store.set(name, created);
28
+ return created;
29
+ }
30
+
31
+ // src/httpBoundaries.ts
32
+ var DEFAULT_DURATION_BOUNDARIES_S = Object.freeze([
33
+ 5e-3,
34
+ 0.01,
35
+ 0.025,
36
+ 0.05,
37
+ 0.075,
38
+ 0.1,
39
+ 0.15,
40
+ 0.2,
41
+ 0.25,
42
+ 0.3,
43
+ 0.35,
44
+ 0.4,
45
+ 0.45,
46
+ 0.5,
47
+ 0.75,
48
+ 1,
49
+ 2.5,
50
+ 5,
51
+ 7.5,
52
+ 10
53
+ ]);
54
+ var state = shared("httpBoundaries", () => ({
55
+ list: [...DEFAULT_DURATION_BOUNDARIES_S]
56
+ }));
57
+ function httpDurationBoundaries() {
58
+ return state.list;
59
+ }
60
+ function exemplarTraceFrom(spanContext) {
61
+ if (!spanContext || !api.isSpanContextValid(spanContext)) {
62
+ return void 0;
63
+ }
64
+ return {
65
+ traceId: spanContext.traceId,
66
+ spanId: spanContext.spanId,
67
+ // The trace-flags byte as two lowercase hex digits, e.g. 1 → "01".
68
+ traceFlags: (spanContext.traceFlags & 255).toString(16).padStart(2, "0")
69
+ };
70
+ }
71
+
72
+ // src/instruments.ts
73
+ var DEFAULT_HISTOGRAM_BOUNDARIES = Object.freeze([
74
+ 0,
75
+ 5,
76
+ 10,
77
+ 25,
78
+ 50,
79
+ 75,
80
+ 100,
81
+ 250,
82
+ 500,
83
+ 750,
84
+ 1e3,
85
+ 2500,
86
+ 5e3,
87
+ 7500,
88
+ 1e4
89
+ ]);
90
+ var state2 = shared("instruments", () => ({
91
+ enabled: false,
92
+ epoch: 0,
93
+ recorder: void 0
94
+ }));
95
+ var CounterDef = class {
96
+ constructor(name, opts) {
97
+ this.name = name;
98
+ this.opts = opts;
99
+ }
100
+ name;
101
+ opts;
102
+ counter;
103
+ counterEpoch = -1;
104
+ add(value, attrs = {}) {
105
+ if (!state2.enabled) {
106
+ return;
107
+ }
108
+ try {
109
+ if (this.counterEpoch !== state2.epoch) {
110
+ this.counter = api.metrics.getMeter(this.opts.meterName ?? "app").createCounter(this.name, { description: this.opts.description, unit: this.opts.unit });
111
+ this.counterEpoch = state2.epoch;
112
+ }
113
+ this.counter?.add(value, attrs);
114
+ } catch (err) {
115
+ api.diag.warn(`counter ${this.name}: record failed`, err);
116
+ }
117
+ }
118
+ };
119
+ var HistogramDef = class {
120
+ constructor(name, opts) {
121
+ this.name = name;
122
+ this.opts = opts;
123
+ this.unit = opts.unit ?? "s";
124
+ this.boundaries = opts.boundaries ?? defaultBoundariesFor(this.unit);
125
+ }
126
+ name;
127
+ opts;
128
+ histogram;
129
+ histogramEpoch = -1;
130
+ // The unit on the wire, and the bucket list the histogram advice and the
131
+ // exemplar reservoir share. The list is held by reference, never copied:
132
+ // `start({ metrics: { httpDurationBoundaries } })` mutates the shared list in
133
+ // place, and a definition created at module scope has to see that.
134
+ unit;
135
+ boundaries;
136
+ record(value, attrs = {}) {
137
+ if (!state2.enabled) {
138
+ return;
139
+ }
140
+ try {
141
+ if (this.histogramEpoch !== state2.epoch) {
142
+ this.histogram = api.metrics.getMeter(this.opts.meterName ?? "app").createHistogram(this.name, {
143
+ description: this.opts.description,
144
+ unit: this.unit,
145
+ advice: { explicitBucketBoundaries: [...this.boundaries] }
146
+ });
147
+ this.histogramEpoch = state2.epoch;
148
+ }
149
+ this.histogram?.record(value, attrs);
150
+ } catch (err) {
151
+ api.diag.warn(`histogram ${this.name}: record failed`, err);
152
+ }
153
+ }
154
+ // record() plus an exemplar. `exemplarAttrs` are the per-observation,
155
+ // high-cardinality keys the app owns (an order id, a customer id); the
156
+ // distribution adds none of its own.
157
+ //
158
+ // Whenever a span with a valid context is active, its ids go onto the exemplar
159
+ // and its trace-flags byte lands in filteredAttributes as `trace_flags` — "01"
160
+ // when the span was sampled, "00" when it was not. That is the
161
+ // same trio instrumentation-pino writes on log lines, so a chart, an exemplar
162
+ // and a log line all join on trace_id.
163
+ recordWithExemplar(value, attrs = {}, exemplarAttrs = {}) {
164
+ this.record(value, attrs);
165
+ const recorder = state2.recorder;
166
+ if (!recorder) {
167
+ return;
168
+ }
169
+ try {
170
+ recorder(
171
+ this.name,
172
+ attrs,
173
+ value,
174
+ exemplarAttrs,
175
+ this.boundaries,
176
+ exemplarTraceFrom(api.trace.getActiveSpan()?.spanContext())
177
+ );
178
+ } catch (err) {
179
+ api.diag.warn(`histogram ${this.name}: exemplar record failed`, err);
180
+ }
181
+ }
182
+ };
183
+ function defaultBoundariesFor(unit) {
184
+ return unit === "s" ? DEFAULT_DURATION_BOUNDARIES_S : DEFAULT_HISTOGRAM_BOUNDARIES;
185
+ }
186
+ function defineCounter(name, opts = {}) {
187
+ return new CounterDef(name, opts);
188
+ }
189
+ function defineHistogram(name, opts = {}) {
190
+ return new HistogramDef(name, opts);
191
+ }
192
+
193
+ // src/httpServerMetrics.ts
194
+ var NO_ROUTE = "<no_route>";
195
+ var MAX_DISTINCT_ROUTES = 1e3;
196
+ var instruments = shared("httpServerInstruments", () => ({
197
+ count: defineCounter("app.http.server.count", {
198
+ description: "HTTP request count",
199
+ meterName: "app.http.server"
200
+ }),
201
+ errors: defineCounter("app.http.server.errors", {
202
+ description: "HTTP request errors",
203
+ meterName: "app.http.server"
204
+ }),
205
+ duration: defineHistogram("app.http.server.duration", {
206
+ description: "HTTP request duration",
207
+ unit: "s",
208
+ boundaries: httpDurationBoundaries(),
209
+ meterName: "app.http.server"
210
+ }),
211
+ seenRoutes: /* @__PURE__ */ new Set()
212
+ }));
213
+ function capRoute(route) {
214
+ if (!route) {
215
+ return NO_ROUTE;
216
+ }
217
+ if (instruments.seenRoutes.has(route)) {
218
+ return route;
219
+ }
220
+ if (instruments.seenRoutes.size >= MAX_DISTINCT_ROUTES) {
221
+ return NO_ROUTE;
222
+ }
223
+ instruments.seenRoutes.add(route);
224
+ return route;
225
+ }
226
+ function shouldIgnoreRequest(predicate, req) {
227
+ if (!predicate) {
228
+ return false;
229
+ }
230
+ try {
231
+ return predicate(req) === true;
232
+ } catch (err) {
233
+ api.diag.warn("sherlock: ignoreRequest predicate threw \u2014 measuring the request anyway", err);
234
+ return false;
235
+ }
236
+ }
237
+ var CLIENT_CLOSED_REQUEST = 499;
238
+ function recordedStatusCode(res, finished) {
239
+ return finished || res.headersSent ? res.statusCode ?? 0 : CLIENT_CLOSED_REQUEST;
240
+ }
241
+ function recordHttpRequest(attrs, durationSeconds, recordExemplars) {
242
+ instruments.count.add(1, attrs);
243
+ if (attrs.status === "error") {
244
+ instruments.errors.add(1, attrs);
245
+ }
246
+ if (!recordExemplars) {
247
+ instruments.duration.record(durationSeconds, attrs);
248
+ return;
249
+ }
250
+ instruments.duration.recordWithExemplar(durationSeconds, attrs);
251
+ }
252
+
253
+ // src/ignorePaths.ts
254
+ var DEFAULT_IGNORE_PATHS = ["/healthz", "/livez", "/healthcheck"];
255
+ var state3 = shared("ignorePaths", () => ({
256
+ paths: /* @__PURE__ */ new Set([...DEFAULT_IGNORE_PATHS, ...readEnvPaths()])
257
+ }));
258
+ function readEnvPaths() {
259
+ return (process.env.SHERLOCK_IGNORE_PATHS ?? "").split(",").map((path) => path.trim()).filter((path) => path.length > 0);
260
+ }
261
+ function isIgnoredPath(url) {
262
+ if (!url) {
263
+ return false;
264
+ }
265
+ const queryAt = url.indexOf("?");
266
+ const path = queryAt === -1 ? url : url.slice(0, queryAt);
267
+ return state3.paths.has(path);
268
+ }
269
+
270
+ // src/express.ts
271
+ function routeTemplate(req) {
272
+ const path = req.route?.path;
273
+ if (typeof path !== "string") {
274
+ return void 0;
275
+ }
276
+ const base = req.baseUrl ?? "";
277
+ const full = `${base}${path}`;
278
+ return full.length > 1 ? full.replace(/\/$/, "") : full;
279
+ }
280
+ function applyMetricsMiddleware(options = {}) {
281
+ return (req, res, next) => {
282
+ if (isIgnoredPath(req.originalUrl ?? req.url) || shouldIgnoreRequest(options.ignoreRequest, req)) {
283
+ next();
284
+ return;
285
+ }
286
+ const startedAt = perf_hooks.performance.now();
287
+ let recorded = false;
288
+ const record = (finished) => {
289
+ if (recorded) {
290
+ return;
291
+ }
292
+ recorded = true;
293
+ try {
294
+ const durationSeconds = (perf_hooks.performance.now() - startedAt) / 1e3;
295
+ const route = capRoute(options.routeName?.(req) ?? routeTemplate(req));
296
+ const statusCode = recordedStatusCode(res, finished);
297
+ const isError = statusCode >= 500;
298
+ recordHttpRequest(
299
+ {
300
+ route,
301
+ method: req.method ?? "UNKNOWN",
302
+ status_code: statusCode,
303
+ status: isError ? "error" : "ok"
304
+ },
305
+ durationSeconds,
306
+ options.recordExemplars !== false
307
+ );
308
+ } catch (recordErr) {
309
+ api.diag.warn("sherlock express adapter: metrics recording failed", recordErr);
310
+ }
311
+ };
312
+ res.on("finish", () => record(true));
313
+ res.on("close", () => record(false));
314
+ next();
315
+ };
316
+ }
317
+
318
+ exports.applyMetricsMiddleware = applyMetricsMiddleware;
319
+ //# sourceMappingURL=express.js.map
320
+ //# sourceMappingURL=express.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/shared.ts","../src/httpBoundaries.ts","../src/exemplarReservoir.ts","../src/instruments.ts","../src/httpServerMetrics.ts","../src/ignorePaths.ts","../src/express.ts"],"names":["isSpanContextValid","state","metrics","diag","trace","performance"],"mappings":";;;;;;;;;AAYA,IAAM,YAAA,mBAAe,MAAA,CAAO,GAAA,CAAI,8BAA8B,CAAA;AAI9D,SAAS,QAAA,GAAqB;AAC5B,E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AAK,CAAC,CAAA;AACnC,IAAA,IAAA,EAAK;AAAA,EACP,CAAA;AACF","file":"express.js","sourcesContent":["// The process-global registry for every piece of mutable state the\n// distribution keeps between modules.\n//\n// This package ships four entry points (`.`, `./register`, `./koa`,\n// `./express`), each bundled on its own, in both ESM and CJS, so a consumer can\n// end up with more than one copy of the same module in one process. Anchoring\n// the state on a symbol key on `globalThis` makes every copy share one object,\n// which is also what removes the dual-package hazard.\n//\n// The key carries a version suffix: two different MAJOR versions of this\n// package in one tree must NOT share state, because the shapes may differ.\n\nconst REGISTRY_KEY = Symbol.for('@sherlock-labs/node:state:v1');\n\ntype Registry = Map<string, unknown>;\n\nfunction registry(): Registry {\n const holder = globalThis as typeof globalThis & { [REGISTRY_KEY]?: Registry };\n let existing = holder[REGISTRY_KEY];\n if (!existing) {\n existing = new Map<string, unknown>();\n holder[REGISTRY_KEY] = existing;\n }\n return existing;\n}\n\n/**\n * Returns the one shared instance of `name`, creating it on first use. Call\n * this once at module scope and keep the returned object — never re-assign its\n * identity, only mutate its fields.\n */\nexport function shared<T extends object>(name: string, create: () => T): T {\n const store = registry();\n const existing = store.get(name);\n if (existing) {\n return existing as T;\n }\n const created = create();\n store.set(name, created);\n return created;\n}\n","import { shared } from './shared';\n\n// The duration buckets (5 ms → 10 s): the semantic-convention list with finer\n// 100–500 ms steps.\n//\n// In SECONDS, because the auto-instrumented histograms record seconds (stable\n// semantic conventions) and a view can change an instrument's buckets but never\n// rescale its values. This one list serves:\n// - `app.http.server.duration`, created with these as advice;\n// - the two auto-instrumented HTTP histograms, via views in metrics.ts;\n// - every custom histogram with `unit: 's'` and no `boundaries` of its own;\n// - the exemplar reservoirs for all of them, so an exemplar always competes in\n// the same bucket its histogram count lands in.\n//\n// `setHttpDurationBoundaries` mutates the list IN PLACE rather than replacing\n// it, because instrument definitions hold a reference to the array and an app\n// may call `start({ metrics: { httpDurationBoundaries } })` after those\n// definitions were created at module scope.\n//\n// Register-safe (state registry only): the exemplar hooks need it and they load\n// on line 1.\n\n/** The default bucket boundaries, in seconds, of a duration histogram. */\nexport const DEFAULT_DURATION_BOUNDARIES_S: readonly number[] = Object.freeze([\n 0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5, 0.75, 1, 2.5, 5,\n 7.5, 10,\n]);\n\nconst state = shared('httpBoundaries', () => ({\n list: [...DEFAULT_DURATION_BOUNDARIES_S],\n}));\n\n/** The live boundary list. Same array object every call — do not copy it. */\nexport function httpDurationBoundaries(): number[] {\n return state.list;\n}\n\nexport function setHttpDurationBoundaries(boundaries: number[] | undefined): void {\n if (!boundaries || boundaries.length === 0) {\n return;\n }\n state.list.length = 0;\n state.list.push(...[...boundaries].sort((a, b) => a - b));\n}\n\nexport function resetHttpDurationBoundaries(): void {\n state.list.length = 0;\n state.list.push(...DEFAULT_DURATION_BOUNDARIES_S);\n}\n","import { diag, isSpanContextValid, type SpanContext } from '@opentelemetry/api';\nimport { hrTime, hrTimeToNanoseconds } from '@opentelemetry/core';\n\n// Holds per-(metric, attrs) exemplars and splices them into an OTLP/JSON payload\n// at export time. Pure logic (no transport, no exporter wiring).\n//\n// A \"series\" is a metric name plus a full attribute set; each distinct\n// combination is tracked on its own. The store is a two-level map — series, then\n// bucket index — and each bucket holds one reservoir. With an HTTP latency\n// histogram (reservoirSize 3, boundaries [0.05, 0.5], seconds):\n//\n// series (Map keyed by metric name + attrs)\n// └─ \"app.http.server.duration route=/api/v2/quote\"\n// └─ buckets (Map keyed by bucket index)\n// ├─ 0 → reservoir { seen: 51200, exemplars: [ 3 kept, ≤50ms ] }\n// ├─ 1 → reservoir { seen: 2000, exemplars: [ 3 kept, 50–500ms ] }\n// └─ 2 → reservoir { seen: 40, exemplars: [ 3 kept, >500ms ] }\n//\n// `seen` counts every observation that hit the bucket; `exemplars` keeps up to\n// `reservoirSize` of them. Each bucket samples independently, so every occupied\n// bucket keeps a few of its own and the slow-tail buckets you most want to click\n// into always have some. Per-series capacity is bounded at\n// `reservoirSize × (boundaries.length + 1)`.\n//\n// `record` and `inject` below document how exemplars get in and out.\n\n// Two tiers of cardinality guard, because they fail differently:\n// - the global cap bounds total memory across every metric in the process;\n// - the per-metric budget stops ONE high-cardinality metric (the client HTTP\n// histogram, keyed by server.address × port × status) from eating the whole\n// global pool and starving a low-cardinality one.\nconst DEFAULT_MAX_SERIES_KEYS = 5_000;\nconst DEFAULT_MAX_KEYS_PER_METRIC = 1_000;\n// Throttle the drift warning so a persistent mismatch can't spam the log.\nconst DRIFT_WARN_THROTTLE_MS = 5 * 60_000;\n// One missed inject can be a benign race (an exemplar recorded between the\n// reader's collect and our inject lands in the NEXT interval's data point);\n// two in a row cannot — the next export would have carried the data point.\n// Shared by the drift warning and stale-series eviction.\nconst MAX_MISSED_INJECTS = 2;\n\nexport type AttrValue =\n | string\n | number\n | boolean\n | Array<string | number | boolean | null | undefined>;\n\n// The trace behind an exemplar. OTLP/JSON encodes both ids as lowercase hex\n// strings — exactly what span.spanContext() returns, so they pass through as-is.\n// `traceFlags` is the W3C trace-flags byte as two hex digits, the same text\n// @opentelemetry/instrumentation-pino stamps on every log line.\nexport interface ExemplarTrace {\n traceId: string;\n spanId: string;\n traceFlags: string;\n}\n\n/** The filteredAttribute that carries the trace-flags byte. */\nconst TRACE_FLAGS_ATTR = 'trace_flags';\n\n// Builds the trace link for an exemplar, or undefined when there is no valid\n// span context to link to.\n//\n// The ids are attached at ANY sampling decision. That is the same vocabulary\n// instrumentation-pino writes on log lines — trace_id, span_id and trace_flags —\n// so a log line and an exemplar from the same request always agree, and one join\n// key works for both. `trace_flags` is the span context's sampling flag at\n// record time — \"01\" sampled, \"00\" not — not export status.\nexport function exemplarTraceFrom(spanContext: SpanContext | undefined): ExemplarTrace | undefined {\n if (!spanContext || !isSpanContextValid(spanContext)) {\n return undefined;\n }\n return {\n traceId: spanContext.traceId,\n spanId: spanContext.spanId,\n // The trace-flags byte as two lowercase hex digits, e.g. 1 → \"01\".\n traceFlags: (spanContext.traceFlags & 0xff).toString(16).padStart(2, '0'),\n };\n}\n\ninterface PendingExemplar {\n value: number;\n // proto3/OTLP-JSON encodes uint64 as a decimal string (matching what\n // JsonMetricsSerializer emits for the surrounding data point timestamps).\n // Note the precision is already float64-limited before we stringify —\n // hrTimeToNanoseconds() returns a JS number, and epoch nanos sit past\n // MAX_SAFE_INTEGER. Sub-microsecond loss; harmless for exemplars.\n timeUnixNano: string;\n filteredAttributes: Record<string, string>;\n // Set when a valid span context was active at record time; lets the UI jump\n // from the exemplar straight to that trace. Its `traceFlags` also lands in\n // filteredAttributes as `trace_flags`.\n trace?: ExemplarTrace;\n}\n\ninterface Reservoir {\n exemplars: PendingExemplar[];\n seen: number;\n}\n\n// A series (metric name + aggregation attrs) holds one reservoir per bucket\n// index. The index isn't sent on the wire; it only governs which sub-reservoir\n// an exemplar competes in.\ninterface Series {\n metricName: string;\n buckets: Map<number, Reservoir>;\n // How many injects this series has survived without matching a data point.\n // Drives two things at MAX_MISSED_INJECTS: the drift warning, and eviction\n // (an unmatchable series must not occupy the per-metric key budget forever).\n missedInjects: number;\n}\n\nexport interface ExemplarReservoirStoreOptions {\n /** Exemplars kept per histogram bucket. Not per series. */\n reservoirSize?: number;\n /**\n * Metric names we KNOW should always match a data point (the\n * auto-instrumented HTTP histograms, whose attribute sets we mirror by hand\n * — see httpExemplars.ts). A recorded exemplar for one of them that matches\n * nothing means the mirrored attribute list has drifted, e.g. after an\n * instrumentation upgrade. That failure is otherwise completely silent.\n */\n driftWatchMetricNames?: Iterable<string>;\n /** Total series across all metrics. Defaults to 5000. */\n maxSeriesKeys?: number;\n /** Series per metric name. Defaults to 1000. */\n maxKeysPerMetric?: number;\n /**\n * Called (un-throttled) with the watched metric names whose exemplars\n * matched no data point across two consecutive exports. Production leaves\n * this unset and reads the throttled warning instead; tests use it to assert\n * the guard fired.\n */\n onDrift?: (metricNames: string[]) => void;\n}\n\nexport class ExemplarReservoirStore {\n private readonly seriesMap = new Map<string, Series>();\n private readonly keysPerMetric = new Map<string, number>();\n private lastDriftWarnAt = 0;\n private readonly reservoirSize: number;\n private readonly driftWatchMetricNames: Set<string>;\n private readonly maxSeriesKeys: number;\n private readonly maxKeysPerMetric: number;\n private readonly onDrift: ((metricNames: string[]) => void) | undefined;\n\n constructor(options: ExemplarReservoirStoreOptions = {}) {\n this.reservoirSize = options.reservoirSize ?? 5;\n this.driftWatchMetricNames = new Set(options.driftWatchMetricNames ?? []);\n this.maxSeriesKeys = options.maxSeriesKeys ?? DEFAULT_MAX_SERIES_KEYS;\n this.maxKeysPerMetric = options.maxKeysPerMetric ?? DEFAULT_MAX_KEYS_PER_METRIC;\n this.onDrift = options.onDrift;\n }\n\n record(\n metricName: string,\n primaryAttrs: Record<string, AttrValue | undefined>,\n value: number,\n filteredAttrs: Record<string, string>,\n boundaries: readonly number[] = [],\n trace?: ExemplarTrace,\n ): void {\n // An exemplar with neither a drill-down attribute nor a trace context is\n // useless, so we don't store it.\n if (Object.keys(filteredAttrs).length === 0 && !trace) {\n return;\n }\n\n const key = makeKey(metricName, primaryAttrs);\n let series = this.seriesMap.get(key);\n if (!series) {\n const metricKeys = this.keysPerMetric.get(metricName) ?? 0;\n if (this.seriesMap.size >= this.maxSeriesKeys || metricKeys >= this.maxKeysPerMetric) {\n return;\n }\n series = { metricName, buckets: new Map(), missedInjects: 0 };\n this.seriesMap.set(key, series);\n this.keysPerMetric.set(metricName, metricKeys + 1);\n }\n const bucket = bucketIndex(value, boundaries);\n let reservoir = series.buckets.get(bucket);\n if (!reservoir) {\n reservoir = { exemplars: [], seen: 0 };\n series.buckets.set(bucket, reservoir);\n }\n const exemplar: PendingExemplar = {\n value,\n timeUnixNano: String(hrTimeToNanoseconds(hrTime())),\n // trace_flags rides in filteredAttributes because the OTLP exemplar has\n // no field for it — only traceId and spanId. The app's own keys win, so a\n // caller that already stamps one keeps its value.\n filteredAttributes: trace\n ? { [TRACE_FLAGS_ATTR]: trace.traceFlags, ...filteredAttrs }\n : filteredAttrs,\n trace,\n };\n // Keep-or-drop via Algorithm R reservoir sampling: the kept exemplars stay\n // a uniform random sample of the bucket, never storing more than\n // reservoirSize.\n // - not full yet → always keep;\n // - full → replace a random slot with probability reservoirSize/seen, a\n // chance that shrinks as `seen` grows, so early and late exemplars have\n // an equal shot at surviving.\n // https://en.wikipedia.org/wiki/Reservoir_sampling#Simple:_Algorithm_R\n reservoir.seen += 1;\n if (reservoir.exemplars.length < this.reservoirSize) {\n reservoir.exemplars.push(exemplar);\n } else {\n const idx = Math.floor(Math.random() * reservoir.seen);\n if (idx < this.reservoirSize) {\n reservoir.exemplars[idx] = exemplar;\n }\n }\n }\n\n // Merges our exemplars into the SDK's histogram payload at export time. The\n // SDK serializes data points with bucket counts and no exemplars (the JS SDK\n // cannot attach any); we keep our reservoirs separate from its aggregation so\n // we can sample per bucket, which is what stops the slow-tail requests being\n // crowded out by the dense fast buckets.\n //\n // This walks the payload, matches each histogram data point back to its series\n // by re-keying the data point's attributes, flattens that series' buckets into\n // one exemplar list, and splices it onto `dp.exemplars`. Matched series are\n // then drained.\n inject(payload: JsonExportRequest): void {\n for (const rm of payload.resourceMetrics ?? []) {\n for (const sm of rm.scopeMetrics ?? []) {\n for (const m of sm.metrics ?? []) {\n if (!m.histogram) {\n continue;\n }\n for (const dp of m.histogram.dataPoints ?? []) {\n const attrs = decodeKeyValueList(dp.attributes);\n const key = makeKey(m.name, attrs);\n const series = this.seriesMap.get(key);\n if (!series) {\n continue;\n }\n // Flatten every bucket's reservoir into one exemplar list.\n const exemplars: PendingExemplar[] = [];\n for (const reservoir of series.buckets.values()) {\n exemplars.push(...reservoir.exemplars);\n }\n if (exemplars.length === 0) {\n continue;\n }\n dp.exemplars = exemplars.map((exemplar) => ({\n timeUnixNano: exemplar.timeUnixNano,\n asDouble: exemplar.value,\n // traceId/spanId are top-level exemplar fields on the wire —\n // that link is what turns a chart spike into an open-the-trace\n // button, so they must not go into filteredAttributes.\n traceId: exemplar.trace?.traceId,\n spanId: exemplar.trace?.spanId,\n filteredAttributes: Object.entries(exemplar.filteredAttributes).map(([k, v]) => ({\n key: k,\n value: { stringValue: v },\n })),\n }));\n // Drained here, inside the walk, not in a sweep afterwards. Two data\n // points in one payload CAN share a series key — the same instrument\n // name on two meters — and a series left in the map until the end of\n // the walk would have its exemplars spliced onto both.\n this.deleteSeries(key);\n }\n }\n }\n }\n // An unmatched series gets one grace inject (the benign record-vs-collect\n // race); on the second miss it is evicted, because a key that can never\n // match would otherwise eat the per-metric budget until the metric stopped\n // accepting new exemplar series for the life of the process. A later record\n // recreates it.\n const staleKeys: string[] = [];\n for (const [key, series] of this.seriesMap) {\n series.missedInjects += 1;\n if (series.missedInjects >= MAX_MISSED_INJECTS) {\n staleKeys.push(key);\n }\n }\n // Warn BEFORE evicting — the drift guard reads the stale series.\n this.warnOnDrift();\n for (const key of staleKeys) {\n this.deleteSeries(key);\n }\n }\n\n // Drop every buffered exemplar. Used by the metrics kill switch: while exports\n // are dropped nothing drains the reservoirs, so exemplars recorded before the\n // flip would otherwise be spliced, hours stale, into the first export after\n // re-enable.\n clear(): void {\n this.seriesMap.clear();\n this.keysPerMetric.clear();\n }\n\n /** Number of live series. Used by tests and by the kill-switch assertions. */\n get size(): number {\n return this.seriesMap.size;\n }\n\n private deleteSeries(key: string): void {\n const series = this.seriesMap.get(key);\n if (!series) {\n return;\n }\n this.seriesMap.delete(key);\n const metricKeys = this.keysPerMetric.get(series.metricName) ?? 0;\n if (metricKeys <= 1) {\n this.keysPerMetric.delete(series.metricName);\n } else {\n this.keysPerMetric.set(series.metricName, metricKeys - 1);\n }\n }\n\n // The drift guard: a leftover series for a watched metric means an exemplar\n // matched no data point in the export, so the hand-mirrored attribute lists in\n // httpExemplars.ts have likely drifted from what the instrumentation records.\n // Without this warning that failure mode is invisible — charts stay normal and\n // exemplars just stop appearing.\n private warnOnDrift(): void {\n if (this.driftWatchMetricNames.size === 0) {\n return;\n }\n const unmatched = new Set<string>();\n for (const series of this.seriesMap.values()) {\n if (\n this.driftWatchMetricNames.has(series.metricName) &&\n series.missedInjects >= MAX_MISSED_INJECTS\n ) {\n unmatched.add(series.metricName);\n }\n }\n if (unmatched.size === 0) {\n return;\n }\n // The callback is un-throttled on purpose: it feeds an alert or a test,\n // both of which want every occurrence. Only the log line is throttled.\n this.onDrift?.([...unmatched]);\n const now = Date.now();\n if (now - this.lastDriftWarnAt < DRIFT_WARN_THROTTLE_MS) {\n return;\n }\n this.lastDriftWarnAt = now;\n diag.warn(\n `exemplars recorded for ${[...unmatched].join(', ')} matched no histogram data point — ` +\n 'the mirrored attribute keys in httpExemplars.ts may have drifted from what ' +\n '@opentelemetry/instrumentation-http records (check after upgrades)',\n );\n }\n}\n\n// Returns the histogram bucket index for `value` given ascending upper-bound\n// boundaries, matching the OTel SDK's (lowerBound, upperBound] convention so an\n// exemplar lands in the same bucket the histogram count is attributed to.\n// Values above the last boundary fall in the overflow bucket\n// (boundaries.length); empty boundaries collapse everything into bucket 0.\nfunction bucketIndex(value: number, boundaries: readonly number[]): number {\n for (let i = 0; i < boundaries.length; i++) {\n if (value <= boundaries[i]) {\n return i;\n }\n }\n return boundaries.length;\n}\n\n// Flattens (metric name + attrs) into the string used to key `this.seriesMap`.\n// This is a one-way fingerprint, never parsed back: both sides re-run makeKey\n// and match by string equality. `record` keys the incoming observation, and\n// `inject` decodes a data point's attributes and re-keys them to find the same\n// entry. For that round trip to line up the key must be deterministic — keys\n// sorted, undefined values skipped, values stringified and joined with '|':\n//\n// makeKey(\"app.http.server.duration\",\n// { status_code: 200, route: \"/api/v2/quote\", method: undefined })\n// → \"app.http.server.duration route=/api/v2/quote|status_code=200\"\n//\n// So the attrs passed to `record` must serialize IDENTICALLY to the data point's\n// attributes at export: exactly the histogram's aggregation attrs, no more, no\n// less. Any mismatch means the lookup misses and the exemplars silently vanish.\n//\n// Do not use array-valued attributes on histograms that carry exemplars: the\n// record side stringifies them (String(['a','b']) === 'a,b') while the inject\n// side (decodeKeyValueList) drops arrayValue entirely, so the keys can never\n// match.\nfunction makeKey(metricName: string, attrs: Record<string, AttrValue | undefined>): string {\n const parts: string[] = [];\n for (const k of Object.keys(attrs).sort()) {\n const v = attrs[k];\n if (v === undefined) {\n continue;\n }\n parts.push(`${k}=${String(v)}`);\n }\n return `${metricName} ${parts.join('|')}`;\n}\n\nfunction decodeKeyValueList(kvs: JsonKeyValue[] | undefined): Record<string, AttrValue> {\n const out: Record<string, AttrValue> = {};\n for (const kv of kvs ?? []) {\n const v = kv.value;\n if (v == null) {\n continue;\n }\n if (typeof v.stringValue === 'string') {\n out[kv.key] = v.stringValue;\n } else if (typeof v.intValue === 'number' || typeof v.intValue === 'string') {\n out[kv.key] = Number(v.intValue);\n } else if (typeof v.doubleValue === 'number') {\n out[kv.key] = v.doubleValue;\n } else if (typeof v.boolValue === 'boolean') {\n out[kv.key] = v.boolValue;\n }\n }\n return out;\n}\n\n// Minimal types for the slice of the OTLP/JSON payload we walk. The real shape\n// is much richer; this mirrors otlp-transformer's serialized layout only as far\n// as `inject` reads and writes it.\ninterface JsonKeyValue {\n key: string;\n value?: {\n stringValue?: string;\n intValue?: number | string;\n doubleValue?: number;\n boolValue?: boolean;\n };\n}\ninterface JsonHistogramDataPoint {\n attributes?: JsonKeyValue[];\n exemplars?: Array<{\n // proto3/OTLP-JSON encodes uint64 as a decimal string, matching the\n // surrounding data point timestamps emitted by JsonMetricsSerializer.\n timeUnixNano: string;\n asDouble: number;\n // Lowercase-hex trace/span ids, present when the exemplar links to a trace.\n traceId?: string;\n spanId?: string;\n filteredAttributes: JsonKeyValue[];\n }>;\n}\ninterface JsonMetric {\n name: string;\n histogram?: { dataPoints?: JsonHistogramDataPoint[] };\n}\ninterface JsonScopeMetrics {\n metrics?: JsonMetric[];\n}\ninterface JsonResourceMetrics {\n scopeMetrics?: JsonScopeMetrics[];\n}\nexport interface JsonExportRequest {\n resourceMetrics?: JsonResourceMetrics[];\n}\n","import {\n type Attributes,\n type Counter,\n diag,\n type Gauge,\n type Histogram,\n metrics,\n trace,\n} from '@opentelemetry/api';\nimport { type AttrValue, type ExemplarTrace, exemplarTraceFrom } from './exemplarReservoir';\nimport { DEFAULT_DURATION_BOUNDARIES_S } from './httpBoundaries';\nimport { shared } from './shared';\n\n// Custom metric instruments, safe to define anywhere — module scope included.\n//\n// Do NOT call metrics.getMeter().createHistogram(...) yourself at module load.\n// Before a MeterProvider is registered, the OpenTelemetry metrics API hands out\n// permanent no-op instruments: the metric compiles, runs, and silently records\n// nothing, forever, because the metrics API has no late binding (unlike traces).\n// A definition avoids that trap — it stores only the definition, and resolves\n// the real instrument lazily on the first record after `start()`. Records before\n// `start()`, after `stop()`, and in a process that never starts telemetry are\n// dropped, not broken.\n//\n// A histogram's unit defaults to 's': the semantic conventions record durations\n// in seconds, and app histograms are overwhelmingly durations. A histogram that\n// measures something else declares its unit. A histogram definition carries its\n// own bucket boundaries, so the exemplar reservoir always buckets an exemplar\n// into the same bucket as the histogram count:\n//\n// const settlementDuration = defineHistogram('app.order.settlement.duration');\n// settlementDuration.recordWithExemplar(elapsedSeconds, { provider }, { orderId });\n//\n// A histogram defined without `boundaries` gets a default list that depends on\n// its unit, passed to both the histogram and the reservoir:\n// - unit 's', explicit or default → DEFAULT_DURATION_BOUNDARIES_S, the seconds\n// list the HTTP histograms use;\n// - any other unit → DEFAULT_HISTOGRAM_BOUNDARIES, a unitless list whose\n// numbers fit millisecond-scale values.\n//\n// A gauge keeps the LAST value recorded per attribute set (the synchronous\n// OpenTelemetry Gauge, `@opentelemetry/api` 1.9+). It has no exemplar variant,\n// because exemplars only exist on histograms:\n//\n// const queueDepth = defineGauge('app.queue.depth', { unit: '{job}' });\n// queueDepth.record(jobs.length, { queue: 'orders' });\n//\n// `defineMeter(name)` binds the instrumentation scope once for a file of\n// definitions, so `meterName` is not repeated per instrument:\n//\n// const m = defineMeter('app.billing');\n// const settlements = m.counter('app.order.settlements', { unit: '{order}' });\n// const settlementDuration = m.histogram('app.order.settlement.duration', { unit: 's' });\n// const queueDepth = m.gauge('app.queue.depth', { unit: '{job}' });\n\n/**\n * The default bucket boundaries of a histogram defined without `boundaries`\n * whose unit is not `'s'`. Same numbers as the fallback `@opentelemetry/sdk-metrics`\n * applies to a histogram created without boundaries\n * (`HistogramAggregation.DEFAULT_INSTANCE`, private). Upstream changes do not\n * propagate; the upgrade checklist re-compares.\n */\nexport const DEFAULT_HISTOGRAM_BOUNDARIES: readonly number[] = Object.freeze([\n 0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000,\n]);\n\nexport interface CounterOptions {\n description?: string;\n unit?: string;\n /** Instrumentation scope name; defaults to 'app'. */\n meterName?: string;\n}\n\nexport type GaugeOptions = CounterOptions;\n\nexport interface HistogramOptions extends CounterOptions {\n /** Defaults to 's' — durations record in seconds. */\n unit?: string;\n /**\n * Explicit bucket boundaries, ascending. Shared with the exemplar reservoir.\n * Defaults to DEFAULT_DURATION_BOUNDARIES_S when the unit is 's', else to\n * DEFAULT_HISTOGRAM_BOUNDARIES.\n */\n boundaries?: readonly number[];\n}\n\ntype ExemplarRecorder = (\n metricName: string,\n primaryAttrs: Record<string, AttrValue | undefined>,\n value: number,\n filteredAttrs: Record<string, string>,\n boundaries: readonly number[],\n exemplarTrace?: ExemplarTrace,\n) => void;\n\n// Flipped on by the metrics pipeline once the global MeterProvider is\n// registered, and off again on shutdown. The epoch invalidates an instrument a\n// definition cached against a provider that is gone, so a restart re-resolves.\nconst state = shared('instruments', () => ({\n enabled: false,\n epoch: 0,\n recorder: undefined as ExemplarRecorder | undefined,\n}));\n\nexport function bindInstruments(recorder: ExemplarRecorder): void {\n state.enabled = true;\n state.epoch += 1;\n state.recorder = recorder;\n}\n\nexport function unbindInstruments(): void {\n state.enabled = false;\n state.epoch += 1;\n state.recorder = undefined;\n}\n\nexport class CounterDef {\n private counter: Counter | undefined;\n private counterEpoch = -1;\n\n constructor(\n readonly name: string,\n private readonly opts: CounterOptions,\n ) {}\n\n add(value: number, attrs: Attributes = {}): void {\n if (!state.enabled) {\n return;\n }\n // Definitions are safe to call from anywhere, so a throw here must never\n // reach the caller's business logic.\n try {\n if (this.counterEpoch !== state.epoch) {\n this.counter = metrics\n .getMeter(this.opts.meterName ?? 'app')\n .createCounter(this.name, { description: this.opts.description, unit: this.opts.unit });\n this.counterEpoch = state.epoch;\n }\n this.counter?.add(value, attrs);\n } catch (err) {\n diag.warn(`counter ${this.name}: record failed`, err);\n }\n }\n}\n\nexport class GaugeDef {\n private gauge: Gauge | undefined;\n private gaugeEpoch = -1;\n\n constructor(\n readonly name: string,\n private readonly opts: GaugeOptions,\n ) {}\n\n /** Records the current value; the export carries the last one per attribute set. */\n record(value: number, attrs: Attributes = {}): void {\n if (!state.enabled) {\n return;\n }\n // Same error boundary as CounterDef.add: telemetry must never throw.\n try {\n if (this.gaugeEpoch !== state.epoch) {\n this.gauge = metrics.getMeter(this.opts.meterName ?? 'app').createGauge(this.name, {\n description: this.opts.description,\n unit: this.opts.unit,\n });\n this.gaugeEpoch = state.epoch;\n }\n this.gauge?.record(value, attrs);\n } catch (err) {\n diag.warn(`gauge ${this.name}: record failed`, err);\n }\n }\n}\n\nexport class HistogramDef {\n private histogram: Histogram | undefined;\n private histogramEpoch = -1;\n // The unit on the wire, and the bucket list the histogram advice and the\n // exemplar reservoir share. The list is held by reference, never copied:\n // `start({ metrics: { httpDurationBoundaries } })` mutates the shared list in\n // place, and a definition created at module scope has to see that.\n private readonly unit: string;\n private readonly boundaries: readonly number[];\n\n constructor(\n readonly name: string,\n private readonly opts: HistogramOptions,\n ) {\n this.unit = opts.unit ?? 's';\n this.boundaries = opts.boundaries ?? defaultBoundariesFor(this.unit);\n }\n\n record(value: number, attrs: Attributes = {}): void {\n if (!state.enabled) {\n return;\n }\n // Same error boundary as CounterDef.add: telemetry must never throw.\n try {\n if (this.histogramEpoch !== state.epoch) {\n this.histogram = metrics.getMeter(this.opts.meterName ?? 'app').createHistogram(this.name, {\n description: this.opts.description,\n unit: this.unit,\n advice: { explicitBucketBoundaries: [...this.boundaries] },\n });\n this.histogramEpoch = state.epoch;\n }\n this.histogram?.record(value, attrs);\n } catch (err) {\n diag.warn(`histogram ${this.name}: record failed`, err);\n }\n }\n\n // record() plus an exemplar. `exemplarAttrs` are the per-observation,\n // high-cardinality keys the app owns (an order id, a customer id); the\n // distribution adds none of its own.\n //\n // Whenever a span with a valid context is active, its ids go onto the exemplar\n // and its trace-flags byte lands in filteredAttributes as `trace_flags` — \"01\"\n // when the span was sampled, \"00\" when it was not. That is the\n // same trio instrumentation-pino writes on log lines, so a chart, an exemplar\n // and a log line all join on trace_id.\n recordWithExemplar(\n value: number,\n attrs: Attributes = {},\n exemplarAttrs: Record<string, string> = {},\n ): void {\n this.record(value, attrs);\n const recorder = state.recorder;\n if (!recorder) {\n return;\n }\n try {\n recorder(\n this.name,\n attrs as Record<string, AttrValue | undefined>,\n value,\n exemplarAttrs,\n this.boundaries,\n exemplarTraceFrom(trace.getActiveSpan()?.spanContext()),\n );\n } catch (err) {\n diag.warn(`histogram ${this.name}: exemplar record failed`, err);\n }\n }\n}\n\nfunction defaultBoundariesFor(unit: string): readonly number[] {\n return unit === 's' ? DEFAULT_DURATION_BOUNDARIES_S : DEFAULT_HISTOGRAM_BOUNDARIES;\n}\n\nexport function defineCounter(name: string, opts: CounterOptions = {}): CounterDef {\n return new CounterDef(name, opts);\n}\n\nexport function defineGauge(name: string, opts: GaugeOptions = {}): GaugeDef {\n return new GaugeDef(name, opts);\n}\n\nexport function defineHistogram(name: string, opts: HistogramOptions = {}): HistogramDef {\n return new HistogramDef(name, opts);\n}\n\n/** Definition factories bound to one instrumentation scope. */\nexport interface MeterDef {\n counter(name: string, opts?: Omit<CounterOptions, 'meterName'>): CounterDef;\n gauge(name: string, opts?: Omit<GaugeOptions, 'meterName'>): GaugeDef;\n histogram(name: string, opts?: Omit<HistogramOptions, 'meterName'>): HistogramDef;\n}\n\nexport function defineMeter(meterName: string): MeterDef {\n return {\n counter: (name, opts) => defineCounter(name, { ...opts, meterName }),\n gauge: (name, opts) => defineGauge(name, { ...opts, meterName }),\n histogram: (name, opts) => defineHistogram(name, { ...opts, meterName }),\n };\n}\n","import type { ServerResponse } from 'node:http';\nimport { type Attributes, diag } from '@opentelemetry/api';\nimport { httpDurationBoundaries } from './httpBoundaries';\nimport { defineCounter, defineHistogram } from './instruments';\nimport { shared } from './shared';\n\n// The three application-level HTTP instruments every framework adapter drives.\n// They sit alongside the auto-instrumented `http.server.request.duration` on\n// purpose: these are measured from inside the app's own request pipeline, so\n// they exist in metrics-only mode, where nothing is patched at all.\n//\n// They are ordinary instrument definitions, so they no-op until `start()` binds\n// them, and they use the same tuned boundary list as every other HTTP duration\n// histogram.\n\n/** Route template used when the framework matched no route. */\nconst NO_ROUTE = '<no_route>';\n\n// A ceiling on distinct route templates. A mounted sub-app, a catch-all, or a\n// framework that hands back the raw path can turn `route` into a per-URL label\n// and blow up the series count. Past the cap, new routes collapse into NO_ROUTE\n// rather than being dropped, so the request is still counted.\nconst MAX_DISTINCT_ROUTES = 1_000;\n\nconst instruments = shared('httpServerInstruments', () => ({\n count: defineCounter('app.http.server.count', {\n description: 'HTTP request count',\n meterName: 'app.http.server',\n }),\n errors: defineCounter('app.http.server.errors', {\n description: 'HTTP request errors',\n meterName: 'app.http.server',\n }),\n duration: defineHistogram('app.http.server.duration', {\n description: 'HTTP request duration',\n unit: 's',\n boundaries: httpDurationBoundaries(),\n meterName: 'app.http.server',\n }),\n seenRoutes: new Set<string>(),\n}));\n\ninterface HttpRequestAttrs extends Attributes {\n route: string;\n method: string;\n status_code: number;\n status: 'ok' | 'error';\n}\n\n/**\n * Caps route cardinality. An unknown route, and any route past\n * MAX_DISTINCT_ROUTES, becomes `<no_route>`.\n */\nexport function capRoute(route: string | undefined | null): string {\n if (!route) {\n return NO_ROUTE;\n }\n if (instruments.seenRoutes.has(route)) {\n return route;\n }\n if (instruments.seenRoutes.size >= MAX_DISTINCT_ROUTES) {\n return NO_ROUTE;\n }\n instruments.seenRoutes.add(route);\n return route;\n}\n\n/**\n * Options every framework adapter accepts. Every adapter also skips the paths\n * the HTTP instrumentation ignores: `/healthz`, `/livez`, `/healthcheck`, and\n * anything added with `start({ ignorePaths })` or `SHERLOCK_IGNORE_PATHS`.\n */\nexport interface AdapterOptions<Req> {\n /** Skip a request entirely. Use it for websockets, long polls and SSE-only routes. */\n ignoreRequest?: (req: Req) => boolean;\n /** Override how the route template is derived. */\n routeName?: (req: Req) => string | undefined;\n /** Defaults to true. */\n recordExemplars?: boolean;\n}\n\n/**\n * Runs an app-supplied `ignoreRequest` predicate without letting it reach the\n * request. It runs OUTSIDE the adapters' recording try/catch, at the top of the\n * middleware, so an unguarded throw here would not lose a metric — it would 500\n * the request. A throwing predicate therefore means \"don't ignore\".\n */\nexport function shouldIgnoreRequest<Req>(\n predicate: ((req: Req) => boolean) | undefined,\n req: Req,\n): boolean {\n if (!predicate) {\n return false;\n }\n try {\n return predicate(req) === true;\n } catch (err) {\n diag.warn('sherlock: ignoreRequest predicate threw — measuring the request anyway', err);\n return false;\n }\n}\n\n/**\n * The status code recorded for a request that closed before the app sent any\n * response: nginx's \"client closed request\". Without it a client timeout would\n * be recorded with the status the app had not sent yet, usually 200.\n */\nexport const CLIENT_CLOSED_REQUEST = 499;\n\n/**\n * The status code to record once `finish` or `close` fired, whichever came\n * first. A response whose headers went out keeps its own status, so a stream\n * the client ends after reading it is recorded as the 200 it was.\n */\nexport function recordedStatusCode(res: ServerResponse, finished: boolean): number {\n return finished || res.headersSent ? (res.statusCode ?? 0) : CLIENT_CLOSED_REQUEST;\n}\n\n/** Records one finished request. `durationSeconds`, to match every other HTTP histogram. */\nexport function recordHttpRequest(\n attrs: HttpRequestAttrs,\n durationSeconds: number,\n recordExemplars: boolean,\n): void {\n instruments.count.add(1, attrs);\n if (attrs.status === 'error') {\n instruments.errors.add(1, attrs);\n }\n if (!recordExemplars) {\n instruments.duration.record(durationSeconds, attrs);\n return;\n }\n // The exemplar carries the active request span's trace context, so a slow\n // latency bucket links straight to that request's trace and, through the\n // shared trace_id, to its log lines. The adapter adds no attributes of its\n // own: an app that wants extra keys records its own histogram with\n // recordWithExemplar.\n instruments.duration.recordWithExemplar(durationSeconds, attrs);\n}\n\n/** Test-only: forget the route cardinality set. */\nexport function resetRouteCardinality(): void {\n instruments.seenRoutes.clear();\n}\n","import { shared } from './shared';\n\n// Request paths the HTTP instrumentation skips entirely — no span, no SDK\n// metric, no exemplar hooks. Health and liveness probes are the reason: a\n// kubernetes probe hits the same path every few seconds per pod forever, which\n// is pure noise as a trace and drags the latency histogram toward zero.\n//\n// Register-safe (state registry only): `./register` reads this on line 1,\n// before `start()` exists. The set is seeded from the environment there and\n// `start({ ignorePaths })` can add to it later — the hook reads the live set on\n// every request, so a late addition still takes effect.\n\nconst DEFAULT_IGNORE_PATHS = ['/healthz', '/livez', '/healthcheck'];\n\nconst state = shared('ignorePaths', () => ({\n paths: new Set<string>([...DEFAULT_IGNORE_PATHS, ...readEnvPaths()]),\n}));\n\nfunction readEnvPaths(): string[] {\n return (process.env.SHERLOCK_IGNORE_PATHS ?? '')\n .split(',')\n .map((path) => path.trim())\n .filter((path) => path.length > 0);\n}\n\nexport function addIgnorePaths(paths: string[] | undefined): void {\n for (const path of paths ?? []) {\n if (path.trim()) {\n state.paths.add(path.trim());\n }\n }\n}\n\n/** True when this request path must not be instrumented. Query strings are ignored. */\nexport function isIgnoredPath(url: string | undefined): boolean {\n if (!url) {\n return false;\n }\n const queryAt = url.indexOf('?');\n const path = queryAt === -1 ? url : url.slice(0, queryAt);\n return state.paths.has(path);\n}\n\n/** Test-only view of the current set. */\nexport function ignoredPaths(): string[] {\n return [...state.paths];\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http';\nimport { performance } from 'node:perf_hooks';\nimport { diag } from '@opentelemetry/api';\nimport {\n type AdapterOptions,\n capRoute,\n recordedStatusCode,\n recordHttpRequest,\n shouldIgnoreRequest,\n} from './httpServerMetrics';\nimport { isIgnoredPath } from './ignorePaths';\n\n// Express adapter: application-level HTTP metrics with exemplars. Mount it early\n// — before the routers — so it sees every request.\n//\n// Structural types below, so this file does not depend on Express at build time.\n// An app using the Express subpath already has Express; one that doesn't should\n// not be made to install it.\n\nexport interface ExpressRequest extends IncomingMessage {\n /** The URL as it arrived, before a mounted router rewrote `url`. */\n originalUrl?: string;\n /** Mount path of the router that handled the request, '' at the top level. */\n baseUrl?: string;\n /** Set by Express once a route matched; `path` is the template, not the URL. */\n route?: { path?: string | RegExp | Array<string | RegExp> };\n}\ntype ExpressNext = (err?: unknown) => void;\ntype ExpressMiddleware = (req: ExpressRequest, res: ServerResponse, next: ExpressNext) => void;\n\n// The route template is only known AFTER routing, so it is read at response\n// end, not at entry. `req.route.path` is the template ('/users/:id') and\n// `baseUrl` is where its router was mounted; together they rebuild the path a\n// human recognises while keeping one series per route instead of one per id.\nfunction routeTemplate(req: ExpressRequest): string | undefined {\n const path = req.route?.path;\n if (typeof path !== 'string') {\n // A regex or array route has no readable template; capRoute turns the\n // undefined into <no_route>.\n return undefined;\n }\n const base = req.baseUrl ?? '';\n const full = `${base}${path}`;\n // A router mounted at /api with a route of '/' gives '/api/' — trim the\n // trailing slash so it doesn't become a second series next to '/api'.\n return full.length > 1 ? full.replace(/\\/$/, '') : full;\n}\n\nexport function applyMetricsMiddleware(\n options: AdapterOptions<ExpressRequest> = {},\n): ExpressMiddleware {\n return (req, res, next) => {\n if (\n isIgnoredPath(req.originalUrl ?? req.url) ||\n shouldIgnoreRequest(options.ignoreRequest, req)\n ) {\n next();\n return;\n }\n const startedAt = performance.now();\n // Express dispatches downstream layers itself and catches their throws, so\n // this middleware never sees the error object. It reads the outcome from\n // the status code instead: an unhandled throw reaches Express's default\n // error handler, which sets 500, and an app that maps a thrown error to a\n // 4xx is telling us it was a client error.\n let recorded = false;\n const record = (finished: boolean) => {\n // 'finish' and 'close' both fire on a normal response, in that order, and\n // only 'close' fires on an aborted one. Record on whichever comes first.\n if (recorded) {\n return;\n }\n recorded = true;\n try {\n const durationSeconds = (performance.now() - startedAt) / 1000;\n const route = capRoute(options.routeName?.(req) ?? routeTemplate(req));\n const statusCode = recordedStatusCode(res, finished);\n const isError = statusCode >= 500;\n recordHttpRequest(\n {\n route,\n method: req.method ?? 'UNKNOWN',\n status_code: statusCode,\n status: isError ? 'error' : 'ok',\n },\n durationSeconds,\n options.recordExemplars !== false,\n );\n } catch (recordErr) {\n // Never let metrics break the request.\n diag.warn('sherlock express adapter: metrics recording failed', recordErr);\n }\n };\n // Record on 'finish' with 'close' as the fallback, never on 'close' alone.\n //\n // cls-rtracer's express middleware patches res.on/addListener/\n // prependListener AND res.off/removeListener, and its removal side is\n // POSITIONAL: it keeps a stack of wrapped handlers per event name and pops\n // the most recent one, whatever function was passed.\n // @opentelemetry/instrumentation-express then calls\n // req.res.removeListener('close', onResponseEnded) from its wrapped next(),\n // once per layer that calls next() — including layers that never registered\n // that listener. Together they strip every 'close' listener registered after\n // cls-rtracer, ours included, and a 'close'-only adapter records nothing at\n // all in such an app.\n //\n // Nothing removes 'finish' listeners, so 'finish' is the primary and 'close'\n // stays as the fallback for an aborted response, which never emits 'finish'.\n // Registering 'close' immediately before next() also makes the adapter\n // absorb the pop its own next() triggers, instead of another middleware's.\n //\n // The exemplar hooks in ./httpExemplars are NOT exposed to this: their\n // res.on('close') runs from instrumentation-http's responseHook, which fires\n // on the server's 'request' event — before Express, and so before\n // cls-rtracer patches the response. Those listeners never enter the wrapped\n // stack, and a pop can only remove something that is in it.\n res.on('finish', () => record(true));\n res.on('close', () => record(false));\n next();\n };\n}\n"]}