@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 @@
1
+ {"version":3,"sources":["../src/shared.ts","../src/autoInstrumentations.ts","../src/esmHookState.ts","../src/exportTarget.ts","../src/logging.ts","../src/telemetryState.ts","../src/fastifySpans.ts","../src/exemplarReservoir.ts","../src/httpBoundaries.ts","../src/httpExemplars.ts","../src/ignorePaths.ts","../src/httpInstrumentationConfig.ts","../src/ownInstrumentations.ts","../src/instrumentationSelection.ts","../src/exportProbe.ts","../src/exemplarExporter.ts","../src/instruments.ts","../src/resource.ts","../src/metrics.ts","../src/options.ts","../src/tracing.ts","../src/lifecycle.ts","../package.json","../src/fastifyInstrumentation.ts","../src/registerCore.ts","../src/register.ts"],"names":["state","DiagLogLevel","format","diag","context","trace","SpanStatusCode","isSpanContextValid","hrTimeToNanoseconds","hrTime","performance","isTracingSuppressed","OTLPMetricExporterBase","JsonMetricsSerializer","createOtlpHttpExportDelegate","getSharedConfigurationDefaults","httpAgentFactoryFromOptions","MetricsExporterMetricsHelper","AggregationTemporalityPreference","metrics","ExportResultCode","suppressTracing","defaultResource","detectResources","envDetector","resourceFromAttributes","MeterProvider","PeriodicExportingMetricReader","AggregationType","SamplingDecision","TraceIdRatioBasedSampler","ParentBasedSampler","TracerProvider","BatchSpanProcessor","OTLPTraceExporter","AsyncLocalStorageContextManager","propagation","CompositePropagator","W3CTraceContextPropagator","W3CBaggagePropagator","registerInstrumentations","InstrumentationBase","subscribe","unsubscribe","getRPCMetadata","RPCType","getNodeAutoInstrumentations"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAYA,IAAM,YAAA,mBAAe,MAAA,CAAO,GAAA,CAAI,8BAA8B,CAAA;AAI9D,SAAS,QAAA,GAAqB;AAC5B,EAAA,MAAM,MAAA,GAAS,UAAA;AACf,EAAA,IAAI,QAAA,GAAW,OAAO,YAAY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BAAA;AAAuB,GAC5B,CAAA;AAMD,EAAA,wBAAA,CAAyB,gBAAgB,CAAA;AAEzC,EAAAN,wCAAAA,CAAyB,EAAE,gBAAA,EAAkB,CAAA;AAC/C;;;ACCA,2BAAA,EAA4B;AAO5B,gBAAA,EAAiB","file":"register.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 type { Instrumentation } from '@opentelemetry/instrumentation';\nimport { shared } from './shared';\n\n// The instrumentation list `./register` installed, kept in its own\n// side-effect-free module so `start()` can read it without importing\n// `./register` — importing that patches libraries, which tests and metrics-only\n// apps must never trigger.\n//\n// With no `./register` import the list stays empty and the meter rebind in\n// `start()` is a no-op. That is the metrics-only path.\n\nconst state = shared('autoInstrumentations', () => ({\n list: [] as Instrumentation[],\n}));\n\nexport function rememberInstrumentations(instrumentations: Instrumentation[]): void {\n state.list.push(...instrumentations);\n}\n\nexport function registeredInstrumentations(): Instrumentation[] {\n return state.list;\n}\n\nexport function forgetInstrumentations(): void {\n state.list.length = 0;\n}\n","import { shared } from './shared';\n\n// What the ESM build of `./register` found about the import-in-the-middle\n// loader (see esmHook.ts), kept apart from esmHook.ts so `start()` can read it\n// without pulling `node:module` into every build.\n\nexport const esmHookState = shared('esmHook', () => ({\n installed: false,\n problem: undefined as string | undefined,\n warned: false,\n}));\n\nconst state = esmHookState;\n\n/** The one-time warning for `start()` to log, or undefined. */\nexport function takeEsmHookWarning(): string | undefined {\n if (!state.problem || state.warned) {\n return undefined;\n }\n state.warned = true;\n return `sherlock: ${state.problem}`;\n}\n\nexport function resetEsmHookForTests(): void {\n state.installed = false;\n state.problem = undefined;\n state.warned = false;\n}\n","import { shared } from './shared';\n\n// Where telemetry is sent, and how to recognise our own export requests so we\n// never instrument them. A traced export POST produces a span, which produces a\n// metric, which produces another export. Two guards cover it:\n//\n// 1. `ignoreOutgoingRequestHook` in ./register skips any outbound request whose\n// host AND port are an ingest target. In instrumentation-http 0.301.2 a true\n// here returns before the span AND before the\n// `http.client.request.duration` record, so this is the guard that stops the\n// self-metric.\n// 2. The exporters wrap their send in `suppressTracing`, which stops the span\n// for every instrumentation that goes through a Tracer.\n//\n// The port is part of the match. An in-cluster collector is commonly an IP with\n// a port (`http://10.43.0.12:4318`), and matching on host alone would silently\n// un-instrument every other service at that address — the app's own database on\n// :5432, a sidecar on :8080.\n//\n// Register-safe (state registry only). Seeded from SHERLOCK_ENDPOINT at register\n// time and topped up with the resolved endpoint by `start()`.\n\n// host (lowercased) → the ports we export to on it.\ntype Targets = Map<string, Set<string>>;\n\nconst state = shared('exportTarget', () => {\n const targets: Targets = new Map();\n addTarget(targets, process.env.SHERLOCK_ENDPOINT);\n return { targets };\n});\n\nfunction addTarget(targets: Targets, endpoint: string | undefined): void {\n if (!endpoint) {\n return;\n }\n let url: URL;\n try {\n url = new URL(endpoint);\n } catch {\n // A malformed endpoint is resolveOptions()'s problem to report, not ours.\n return;\n }\n const host = normalizeHost(url.hostname);\n // An endpoint with no explicit port still goes somewhere: fill in the protocol\n // default, because that is the port the request will actually carry.\n const port = url.port || (url.protocol === 'https:' ? '443' : '80');\n const ports = targets.get(host) ?? new Set<string>();\n ports.add(port);\n targets.set(host, ports);\n}\n\n/** Remembers an endpoint as ours, so outbound requests to it stay uninstrumented. */\nexport function registerIngestEndpoint(endpoint: string | undefined): void {\n addTarget(state.targets, endpoint);\n}\n\n/** Test and debug view: the `host:port` pairs currently treated as ours. */\nexport function ingestTargets(): string[] {\n const out: string[] = [];\n for (const [host, ports] of state.targets) {\n for (const port of ports) {\n out.push(`${host}:${port}`);\n }\n }\n return out.sort();\n}\n\n// An IPv6 literal reaches us bracketed from `new URL().hostname` and bare from\n// a hand-built request option. Store and compare the bare form so the two agree.\nfunction normalizeHost(raw: string): string {\n const host = raw.trim().toLowerCase();\n return host.startsWith('[') && host.endsWith(']') ? host.slice(1, -1) : host;\n}\n\n// `host` may carry the port (\"name:port\", \"[::1]:4318\"). A bare IPv6 literal is\n// all colons and no port, so a lone trailing colon group only counts as a port\n// when the host is bracketed or has exactly one colon.\nfunction splitHostPort(raw: string): { host: string; port: string | undefined } {\n if (raw.startsWith('[')) {\n const close = raw.indexOf(']');\n if (close === -1) {\n return { host: raw, port: undefined };\n }\n const rest = raw.slice(close + 1);\n return {\n host: raw.slice(1, close),\n port: rest.startsWith(':') ? rest.slice(1) || undefined : undefined,\n };\n }\n const at = raw.lastIndexOf(':');\n if (at === -1 || raw.indexOf(':') !== at) {\n return { host: raw, port: undefined };\n }\n return { host: raw.slice(0, at), port: raw.slice(at + 1) || undefined };\n}\n\n/**\n * True when these outgoing-request options point at a Sherlock ingest target.\n * Shaped for `ignoreOutgoingRequestHook`, which is handed a parsed\n * `RequestOptions`: a `hostname` plus a numeric `port`, or a `host` that may\n * carry the port itself. A request that names no port at all can only be\n * matched on host; instrumentation-http fills `port` from the URL before the\n * hook runs, so that is a safety net rather than the normal path.\n */\nexport function isIngestRequest(options: {\n hostname?: string | null;\n host?: string | null;\n port?: string | number | null;\n}): boolean {\n const raw = options.hostname ?? options.host;\n if (!raw) {\n return false;\n }\n const fromHost = splitHostPort(raw);\n const ports = state.targets.get(normalizeHost(fromHost.host));\n if (!ports) {\n return false;\n }\n const port =\n options.port === undefined || options.port === null || options.port === ''\n ? fromHost.port\n : String(options.port);\n if (port === undefined) {\n return true;\n }\n return ports.has(port);\n}\n","import { format } from 'node:util';\nimport { type DiagLogger, DiagLogLevel, diag } from '@opentelemetry/api';\nimport type { DistroLogger } from './types';\n\n// Bridges the OpenTelemetry SDK's own diagnostics (`diag`) to somewhere a human\n// will see them. Without this, export failures — a 401 on the ingest token, a\n// network timeout — are silent, which is the most common reason \"nothing\n// arrives at all\".\n//\n// The default sink is the console at OTEL_LOG_LEVEL (warn). An app that passes\n// a `logger` gets its own logger instead.\n\nconst LEVELS: Record<string, DiagLogLevel> = {\n none: DiagLogLevel.NONE,\n error: DiagLogLevel.ERROR,\n warn: DiagLogLevel.WARN,\n info: DiagLogLevel.INFO,\n debug: DiagLogLevel.DEBUG,\n verbose: DiagLogLevel.VERBOSE,\n all: DiagLogLevel.ALL,\n};\n\n/** Reads OTEL_LOG_LEVEL; anything unrecognised falls back to WARN. */\nfunction resolveDiagLogLevel(raw: string | undefined): DiagLogLevel {\n if (!raw) {\n return DiagLogLevel.WARN;\n }\n return LEVELS[raw.trim().toLowerCase()] ?? DiagLogLevel.WARN;\n}\n\n// Every line reaches the sink as ONE already-formatted string. The sink may be\n// a pino logger, and pino takes an optional merge object, then a message, then\n// values for `%s`-style placeholders in that message; it does not join any\n// other extra arguments. So a console-style call\n// (`logger.warn('[otel]', 'export failed', err)`) prints a bare `[otel]` and\n// loses the part that says what happened. `format` is right for pino and for a\n// console alike.\n//\n// An argument whose custom inspector throws cannot be formatted. The message\n// still goes out, marked, so the diagnostic is not lost.\nfunction line(args: unknown[]): string {\n try {\n return format('[otel]', ...args);\n } catch {\n const message = typeof args[0] === 'string' ? args[0] : 'diagnostic';\n return `[otel] ${message} (details could not be formatted)`;\n }\n}\n\nconst consoleLogger: DistroLogger = {\n debug: (...args) => console.debug(...args),\n info: (...args) => console.info(...args),\n warn: (...args) => console.warn(...args),\n error: (...args) => console.error(...args),\n};\n\n// The app's logger is outside the package's control, and diag is called from\n// places with no caller to throw back to — export callbacks, and the error\n// boundary inside start(). A logger that throws gets the line written to the\n// console instead, so a broken logger neither raises nor silences diagnostics.\n// If the console throws as well, the line is dropped: a diagnostic never\n// becomes an exception.\nfunction toDiagLogger(logger: DistroLogger): DiagLogger {\n const sink =\n (level: keyof DistroLogger) =>\n (...args: unknown[]): void => {\n const text = line(args);\n try {\n logger[level](text);\n } catch {\n try {\n consoleLogger[level](text);\n } catch {\n // Nowhere is left to report to.\n }\n }\n };\n return {\n verbose: sink('debug'),\n debug: sink('debug'),\n info: sink('info'),\n warn: sink('warn'),\n error: sink('error'),\n };\n}\n\n/**\n * Installs the diag bridge. Called first thing inside `start()` — anything that\n * logs before it is thrown away.\n */\nexport function setupDiag(logger: DistroLogger | undefined): void {\n diag.setLogger(toDiagLogger(logger ?? consoleLogger), {\n logLevel: resolveDiagLogLevel(process.env.OTEL_LOG_LEVEL),\n // A takeover legitimately re-registers a sink. Without this the API prints\n // two stack traces about it, which read like a bug and are not one.\n suppressOverrideMessage: true,\n });\n}\n\nexport function teardownDiag(): void {\n diag.disable();\n}\n\n// An app can replace the global diag logger itself, with `diag.setLogger`, and\n// then the package's own lines reach that logger outside the bridge. A throw\n// there must not escape: these lines run inside start() and its catch block,\n// where an escape either throws at the caller or tears down running pipelines.\nfunction contained(write: () => void): void {\n try {\n write();\n } catch {\n // The app's own logger failed; the line has nowhere else to go.\n }\n}\n\n/**\n * The distribution's own log lines. These go through `diag` too, so one\n * OTEL_LOG_LEVEL governs everything, and an app that never calls `start()`\n * never installs a sink at all.\n */\nexport const log = {\n debug: (message: string, ...args: unknown[]) => contained(() => diag.debug(message, ...args)),\n info: (message: string, ...args: unknown[]) => contained(() => diag.info(message, ...args)),\n warn: (message: string, ...args: unknown[]) => contained(() => diag.warn(message, ...args)),\n error: (message: string, ...args: unknown[]) => contained(() => diag.error(message, ...args)),\n};\n","import { log } from './logging';\nimport { shared } from './shared';\nimport type { TelemetryToggle } from './types';\n\n// The runtime kill switches, as two plain booleans.\n//\n// Both read sites are SYNCHRONOUS functions deep inside the SDK — `shouldSample`\n// must return its decision on the spot, and the exemplar record path runs inside\n// a 'close' listener — and a sync function cannot wait for a promise. So the\n// distribution owns the switch and reads a variable on the hot path, while the\n// app owns WHEN to flip it and does its async work (a flag poll, a config\n// watcher, an admin endpoint) wherever waiting is allowed.\n//\n// - traces off → FlagSampler (tracing.ts) drops NEW root traces; requests\n// already being traced finish whole.\n// - metrics off → the ExemplarExporter drops batches at export, stops recording\n// exemplars, and clears the reservoirs so nothing stale survives the window.\n\nexport const telemetryState = shared('telemetryState', () => ({\n tracesOn: true,\n metricsOn: true,\n // Set once the app has called setTelemetryEnabled for that pipeline. From\n // then on `start()` stops re-seeding it from the environment — an explicit\n // call by the app always outranks a boot-time env var.\n tracesSetByApp: false,\n metricsSetByApp: false,\n}));\n\n/** A true/false env value. Unset or blank is undefined, anything else unrecognised is null. */\nexport function parseEnvFlag(raw: string | undefined): boolean | undefined | null {\n if (raw === undefined || raw.trim() === '') {\n return undefined;\n }\n const normalized = raw.trim().toLowerCase();\n if (normalized === 'false' || normalized === '0' || normalized === 'no') {\n return false;\n }\n if (normalized === 'true' || normalized === '1' || normalized === 'yes') {\n return true;\n }\n return null;\n}\n\n/** A true/false env var. An unrecognised value warns and counts as unset. */\nexport function readEnvFlag(name: string, whenInvalid = 'staying enabled'): boolean | undefined {\n const value = parseEnvFlag(process.env[name]);\n if (value === null) {\n log.warn(\n `SHERLOCK: ignoring ${name}=${JSON.stringify(process.env[name])} — expected true or false, ${whenInvalid}`,\n );\n return undefined;\n }\n return value;\n}\n\n/**\n * Seeds both switches from SHERLOCK_TRACES_ENABLED / SHERLOCK_METRICS_ENABLED\n * (both default true). Called by `start()`; a pipeline the app already flipped\n * by hand is left alone.\n */\nexport function seedTelemetryStateFromEnv(): void {\n if (!telemetryState.tracesSetByApp) {\n telemetryState.tracesOn = readEnvFlag('SHERLOCK_TRACES_ENABLED') ?? true;\n }\n if (!telemetryState.metricsSetByApp) {\n telemetryState.metricsOn = readEnvFlag('SHERLOCK_METRICS_ENABLED') ?? true;\n }\n}\n\n/**\n * Turns either pipeline on or off while the process runs. An omitted field\n * leaves that pipeline as it is.\n */\nexport function setTelemetryEnabled(toggle: TelemetryToggle): void {\n if (toggle.traces !== undefined) {\n telemetryState.tracesSetByApp = true;\n if (toggle.traces !== telemetryState.tracesOn) {\n // Log transitions only. A kill-switch flip is an operational event\n // people look for on an incident timeline.\n log.warn(`sherlock telemetry kill switch: traces ${toggle.traces ? 'enabled' : 'disabled'}`);\n }\n telemetryState.tracesOn = toggle.traces;\n }\n if (toggle.metrics !== undefined) {\n telemetryState.metricsSetByApp = true;\n if (toggle.metrics !== telemetryState.metricsOn) {\n log.warn(\n `sherlock telemetry kill switch: metrics ${toggle.metrics ? 'enabled' : 'disabled'}`,\n );\n }\n telemetryState.metricsOn = toggle.metrics;\n }\n}\n\n/** Test-only reset. Not exported from the package entry point. */\nexport function resetTelemetryState(): void {\n telemetryState.tracesOn = true;\n telemetryState.metricsOn = true;\n telemetryState.tracesSetByApp = false;\n telemetryState.metricsSetByApp = false;\n}\n","import {\n type Context,\n context,\n type Span,\n SpanStatusCode,\n type Tracer,\n trace,\n} from '@opentelemetry/api';\nimport { shared } from './shared';\nimport { parseEnvFlag, readEnvFlag } from './telemetryState';\n\nconst LIFECYCLE_SPANS_ENV = 'SHERLOCK_FASTIFY_LIFECYCLE_SPANS';\n\nconst LIFECYCLE_HOOKS = [\n 'onTimeout',\n 'onRequest',\n 'preParsing',\n 'preValidation',\n 'preHandler',\n 'preSerialization',\n 'onSend',\n 'onResponse',\n 'onError',\n 'onRequestAbort',\n] as const;\ntype LifecycleHook = (typeof LIFECYCLE_HOOKS)[number];\nconst isLifecycleHook = (name: string): name is LifecycleHook =>\n (LIFECYCLE_HOOKS as readonly string[]).includes(name);\n\nexport const kLeaveUnwrapped = Symbol.for('sherlock.node.fastify.leaveUnwrapped');\n\n// Fastify adds this onSend hook itself to the HEAD route it creates for every\n// GET route (fastify/lib/head-route.js).\nconst FASTIFY_OWN_HOOKS = new Set(['headRouteOnSendHandler']);\n\n// Read when the module loads, not in start(): a Fastify instance created before\n// the deferred auto-start must already get the spans. No logger exists yet, so\n// an invalid value is reported from start() instead.\nconst state = shared('fastifyLifecycleSpans', () => ({\n enabled: parseEnvFlag(process.env[LIFECYCLE_SPANS_ENV]) === true,\n instancesCreatedWithoutSpans: 0,\n requestContexts: new WeakMap<object, Context>(),\n}));\n\n/** One per enabled `FastifyInstrumentation`, across every copy of this package. */\nexport interface EnabledCopy {\n tracer(): Tracer;\n}\n\nconst copies = shared('fastifyInstrumentationCopies', () => ({ active: new Set<EnabledCopy>() }));\n\nexport function addEnabledCopy(copy: EnabledCopy): void {\n copies.active.add(copy);\n}\n\nexport function removeEnabledCopy(copy: EnabledCopy): void {\n copies.active.delete(copy);\n}\n\nexport function anyFastifyInstrumentationEnabled(): boolean {\n return copies.active.size > 0;\n}\n\nexport function anyEnabledTracer(): Tracer | undefined {\n for (const copy of copies.active) {\n return copy.tracer();\n }\n return undefined;\n}\n\n/** Called from start(), once a logger exists: warns about an invalid env value. */\nexport function checkLifecycleSpansEnv(): void {\n readEnvFlag(LIFECYCLE_SPANS_ENV, 'leaving Fastify lifecycle spans off');\n}\n\nexport function lifecycleSpansEnabled(): boolean {\n return state.enabled;\n}\n\nexport function setLifecycleSpans(enabled: boolean | undefined): void {\n if (enabled !== undefined) {\n state.enabled = enabled;\n }\n}\n\nexport function fastifyInstancesCreatedWithoutLifecycleSpans(): number {\n return state.instancesCreatedWithoutSpans;\n}\n\nexport function noteInstanceWithoutSpans(): void {\n state.instancesCreatedWithoutSpans++;\n}\n\nexport function rememberRequestContext(request: object): void {\n if (state.enabled) {\n state.requestContexts.set(request, context.active());\n }\n}\n\ninterface RouteOptionsLike {\n url?: string;\n handler?: unknown;\n [hook: string]: unknown;\n}\n\ninterface InstanceLike {\n addHook(name: string, fn: unknown): unknown;\n}\n\ninterface RequestLike {\n routeOptions?: { url?: string };\n raw: unknown;\n}\n\ninterface ReplyLike {\n sent?: boolean;\n raw: { once(event: string, listener: () => void): unknown };\n}\n\ntype AnyFn = (this: unknown, ...args: unknown[]) => unknown;\ntype Kind = LifecycleHook | 'handler';\n\nexport function installLifecycleSpans(\n fastify: InstanceLike,\n tracer: () => Tracer | undefined,\n): void {\n const addHook = fastify.addHook;\n fastify.addHook = function addHookWithSpans(this: InstanceLike, name: string, fn: unknown) {\n const wrapped = isLifecycleHook(name) ? wrapFn(fn, tracer, name, undefined) : fn;\n return addHook.call(this, name, wrapped);\n };\n addHook.call(fastify, 'onRoute', (routeOptions: RouteOptionsLike) => {\n const route = routeOptions.url;\n for (const hook of LIFECYCLE_HOOKS) {\n const value = routeOptions[hook];\n if (value === undefined) {\n continue;\n }\n routeOptions[hook] = Array.isArray(value)\n ? value.map((fn) => wrapFn(fn, tracer, hook, route))\n : wrapFn(value, tracer, hook, route);\n }\n routeOptions.handler = wrapFn(routeOptions.handler, tracer, 'handler', route);\n });\n}\n\nfunction wrapFn(\n fn: unknown,\n tracer: () => Tracer | undefined,\n kind: Kind,\n route: string | undefined,\n): unknown {\n if (\n typeof fn !== 'function' ||\n (fn as { [kLeaveUnwrapped]?: true })[kLeaveUnwrapped] ||\n FASTIFY_OWN_HOOKS.has(fn.name)\n ) {\n return fn;\n }\n const original = fn as AnyFn;\n const run = function (this: unknown, args: unknown[]) {\n const active = state.enabled ? tracer() : undefined;\n const started = active ? startSpan(active, original, args, kind, route) : undefined;\n return started ? runInSpan(this, original, args, kind, started) : original.apply(this, args);\n };\n const wrapper =\n original.constructor.name === 'AsyncFunction'\n ? async function (this: unknown, ...args: unknown[]) {\n return run.call(this, args);\n }\n : function (this: unknown, ...args: unknown[]) {\n return run.call(this, args);\n };\n Object.defineProperty(wrapper, 'length', { value: original.length });\n Object.defineProperty(wrapper, 'name', { value: original.name });\n return wrapper;\n}\n\ninterface StartedSpan {\n span: Span;\n parent: Context;\n}\n\n/** Undefined means \"run the original untouched\": no server span to hang from, or set-up failed. */\nfunction startSpan(\n tracer: Tracer,\n original: AnyFn,\n args: unknown[],\n kind: Kind,\n route: string | undefined,\n): StartedSpan | undefined {\n try {\n const request = args.find(isRequest);\n const parent = (request && state.requestContexts.get(request)) ?? context.active();\n if (!trace.getSpan(parent)) {\n return undefined;\n }\n const httpRoute = route ?? request?.routeOptions?.url;\n const name =\n kind === 'handler'\n ? `handler - ${httpRoute ?? 'unknown'}`\n : `${kind} - ${original.name || 'anonymous'}`;\n const span = tracer.startSpan(\n name,\n {\n attributes: {\n 'fastify.type': kind === 'handler' ? 'handler' : 'hook',\n ...(kind === 'handler' ? {} : { 'fastify.hook': kind }),\n ...(httpRoute ? { 'http.route': httpRoute } : {}),\n },\n },\n parent,\n );\n return { span, parent };\n } catch {\n return undefined;\n }\n}\n\nfunction runInSpan(\n self: unknown,\n original: AnyFn,\n args: unknown[],\n kind: Kind,\n { span, parent }: StartedSpan,\n): unknown {\n let ended = false;\n const end = (err?: unknown) => {\n if (ended) {\n return;\n }\n ended = true;\n try {\n if (err) {\n recordError(span, err);\n }\n span.end();\n } catch {}\n };\n\n const last = args.length - 1;\n const done =\n typeof args[last] === 'function' && kind !== 'handler' ? (args[last] as AnyFn) : undefined;\n // Fastify runs the rest of the lifecycle inside `done`, so it continues in\n // the hook's caller's context, not in this span's.\n const entryContext = context.active();\n const callArgs = done\n ? [\n ...args.slice(0, last),\n function (this: unknown, err?: unknown, ...rest: unknown[]) {\n end(err);\n return context.with(entryContext, () => done.call(this, err, ...rest));\n },\n ]\n : args;\n\n return context.with(trace.setSpan(parent, span), () => {\n let result: unknown;\n try {\n result = original.apply(self, callArgs);\n } catch (err) {\n end(err);\n throw err;\n }\n if (isThenable(result)) {\n // Observe, never replace: a Reply is a thenable whose `then` returns\n // undefined and calls back from a stream listener.\n try {\n result.then(\n () => end(),\n (err: unknown) => end(err),\n );\n } catch {\n end();\n }\n return result;\n }\n if (kind === 'handler' && result === undefined) {\n endWhenReplied(args[1], end);\n } else if (!done) {\n end();\n }\n return result;\n });\n}\n\n// A handler that returns nothing and has not replied yet will reply later,\n// from a callback of its own.\nfunction endWhenReplied(reply: unknown, end: () => void): void {\n if (!isReply(reply) || reply.sent !== false) {\n end();\n return;\n }\n try {\n reply.raw.once('finish', end);\n reply.raw.once('close', end);\n } catch {\n end();\n }\n}\n\nfunction recordError(span: Span, err: unknown): void {\n if (err instanceof Error) {\n span.recordException(err);\n }\n const status =\n (err as { statusCode?: unknown; status?: unknown } | null)?.statusCode ??\n (err as { status?: unknown } | null)?.status;\n // A thrown 4xx is a client error. The server span leaves those unset too.\n if (typeof status === 'number' && status < 500) {\n return;\n }\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: err instanceof Error ? err.message : String(err),\n });\n}\n\nfunction isRequest(value: unknown): value is RequestLike {\n return typeof value === 'object' && value !== null && 'routeOptions' in value && 'raw' in value;\n}\n\nfunction isReply(value: unknown): value is ReplyLike {\n return typeof value === 'object' && value !== null && 'sent' in value && 'raw' in value;\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return typeof (value as { then?: unknown } | null)?.then === 'function';\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 { 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","// Type-only: a runtime import of node:http here would load it at ./register\n// time, before the patch hook exists.\nimport type * as http from 'node:http';\nimport { performance } from 'node:perf_hooks';\nimport { type Attributes, diag, type Span } from '@opentelemetry/api';\nimport type { ExemplarExporter } from './exemplarExporter';\nimport { type AttrValue, exemplarTraceFrom } from './exemplarReservoir';\nimport { httpDurationBoundaries } from './httpBoundaries';\nimport { shared } from './shared';\n\n// Exemplars for the auto-instrumented HTTP duration histograms\n// (http.server.request.duration / http.client.request.duration).\n//\n// We don't own these histograms — @opentelemetry/instrumentation-http records\n// them internally, and the OpenTelemetry JS SDK never emits exemplars. So we\n// hook the same instrumentation (requestHook/responseHook, wired in\n// ./register), time the request ourselves, and record an exemplar keyed to match\n// the metric the instrumentation just emitted.\n//\n// The fragile part is the key: an exemplar attaches to its data point only if\n// its attribute set reproduces the metric's attribute set EXACTLY. SERVER_KEYS\n// and CLIENT_KEYS below are transcribed from\n// @opentelemetry/instrumentation-http 0.301.2, which this package pins exactly\n// for that reason, and a version bump is the cue to re-check them against\n// http.js (_incomingRequestFunction / _outgoingRequestFunction\n// stableMetricAttributes) and utils.js\n// (get*StableRequestMetricAttributesOnResponse, the error paths). Values come\n// from the recorded span's attributes — the SDK derives the metric attributes\n// from that same object — so we copy keys, not logic. The reservoir's drift\n// guard warns if the lists stop matching.\n//\n// This module is loaded by ./register at process start, so it must not\n// runtime-import anything the patches still need to wrap (no node:http, no\n// logger).\n\n// The exporter is owned by the metrics pipeline, which injects it here once\n// metrics are up. It stays undefined when metrics are disabled, making the\n// whole hook path a no-op.\nconst state = shared('httpExemplars', () => ({\n exporter: undefined as ExemplarExporter | undefined,\n // performance.now() at request start, keyed by the per-request span (the\n // same Span instance flows through both hooks).\n startBySpan: new WeakMap<object, number>(),\n}));\n\nexport function setAutoHttpExemplarExporter(exporter: ExemplarExporter | undefined): void {\n state.exporter = exporter;\n}\n\n// Stable-semconv histogram names — the only ones instrumentation-http 0.301.2\n// emits. They record in SECONDS, and the exemplar value is scaled the same way\n// so it lands in the matching bucket.\nconst SERVER_METRIC = 'http.server.request.duration';\nconst CLIENT_METRIC = 'http.client.request.duration';\n\n/** The metric names the drift guard watches. */\nexport const AUTO_HTTP_METRICS = [SERVER_METRIC, CLIENT_METRIC];\n\n// The EXACT stable metric-attribute key subsets instrumentation-http 0.301.2\n// builds. Absent keys are skipped on both sides, so optional ones are safe to\n// list. error.type is special: the metric can carry it without the span having\n// it — see the derivation in recordAutoHttpExemplar.\nconst SERVER_KEYS = [\n 'http.request.method',\n 'url.scheme',\n 'network.protocol.version',\n 'http.route',\n 'http.response.status_code',\n 'error.type',\n];\nconst CLIENT_KEYS = [\n 'http.request.method',\n 'server.address',\n 'server.port',\n 'http.response.status_code',\n 'network.protocol.version',\n 'error.type',\n];\n\n// HttpInstrumentation requestHook: fires at request start for both incoming\n// (server) and outgoing (client) requests. We discriminate by duck-typing the\n// request object rather than `instanceof http.ClientRequest` (which would force\n// a runtime node:http import) or `span.kind` (which is undefined for\n// non-recording spans).\n//\n// The CLIENT exemplar is recorded here, off the request's own 'close' event,\n// rather than in the responseHook: the responseHook never fires when the request\n// fails before a response arrives (DNS failure, connection refused), while the\n// instrumentation still records the histogram on those paths. Node emits request\n// 'close' exactly once after success and after every error mode, always after\n// the SDK's own listener, so it covers the failed outbound calls too.\nexport function onHttpRequestStart(\n span: Span,\n request: http.ClientRequest | http.IncomingMessage,\n): void {\n if (!state.exporter) {\n return;\n }\n state.startBySpan.set(span, performance.now());\n if (isClientRequest(request)) {\n request.on('close', () => {\n // Mirror the instrumentation's own guard: on an aborted request it returns\n // before recording the histogram (`if (request.aborted ||\n // responseFinished) return`), so an exemplar here would be an orphan\n // series and the drift guard would cry wolf on any workload with client\n // timeouts.\n if (request.aborted) {\n return;\n }\n queueMicrotask(() => {\n recordAutoHttpExemplar(span, CLIENT_METRIC, CLIENT_KEYS);\n });\n });\n }\n}\n\n// HttpInstrumentation responseHook, used for the SERVER side only. The\n// instrumentation records the histogram on the response 'close' event, which\n// fires on success and error alike, so we listen there too.\n//\n// 'close' is safe HERE, unlike in the Express adapter (see ./express.ts). This\n// hook runs from instrumentation-http's own handling of the server's 'request'\n// event, before the app's request listener — so before Express dispatches\n// anything and before cls-rtracer patches res.on/res.removeListener. The\n// listener goes on the untouched emitter and never enters cls-rtracer's stack of\n// wrapped handlers, and a positional pop can only remove something in that\n// stack. The instrumentation's own recording listener survives for the same\n// reason, which is why the exemplars keep matching the data points.\nexport function onHttpResponse(\n span: Span,\n response: http.ServerResponse | http.IncomingMessage,\n): void {\n if (!state.exporter) {\n return;\n }\n if (isServerResponse(response)) {\n response.on('close', () => {\n queueMicrotask(() => {\n recordAutoHttpExemplar(span, SERVER_METRIC, SERVER_KEYS);\n });\n });\n }\n}\n\n// Duck-typed discrimination, robust whether or not the span is recording.\n// ClientRequest / ServerResponse both extend OutgoingMessage (getHeader /\n// writeHead); the peer IncomingMessage (a Readable) has neither.\nfunction isClientRequest(request: http.ClientRequest | http.IncomingMessage): boolean {\n return typeof (request as { getHeader?: unknown }).getHeader === 'function';\n}\nfunction isServerResponse(\n response: http.ServerResponse | http.IncomingMessage,\n): response is http.ServerResponse {\n return typeof (response as { writeHead?: unknown }).writeHead === 'function';\n}\n\n// Both listeners above reach here through queueMicrotask, and that deferral is\n// load-bearing. Node runs all 'close' listeners in one synchronous batch, in\n// registration order, and ours registers before the SDK's — so running right\n// away would read the span BEFORE the SDK wrote its final attributes (http.route,\n// the status code), and the key built from that incomplete set would match no\n// data point at export. A microtask runs right after the batch, the earliest\n// moment at which the span attributes and the histogram point are both final.\n// The duration is not what is at stake; the attribute snapshot is.\n//\n// The try/catch is the boundary: a microtask callback has no caller to throw back\n// to, so an unhandled error here is an uncaughtException on every HTTP request\n// the process serves. This is the one record path no caller's try/catch covers.\nfunction recordAutoHttpExemplar(span: Span, metric: string, keys: string[]): void {\n try {\n const exporter = state.exporter;\n if (!exporter) {\n return;\n }\n const start = state.startBySpan.get(span);\n if (start === undefined) {\n return;\n }\n // A recorded SDK Span exposes its attributes (ReadableSpan.attributes); the\n // api Span type does not declare them. An unsampled request gets a\n // NonRecordingSpan with NO attributes, so the metric's attribute key cannot\n // be rebuilt and the exemplar could never match a data point — skip it.\n //\n // This is a hard limit of the auto-HTTP path, and it is why it differs from\n // the custom-metric path, whose caller hands us the metric attributes\n // directly and so gets an exemplar at any sampling decision.\n const attrs = (span as unknown as { attributes?: Attributes }).attributes ?? {};\n if (Object.keys(attrs).length === 0) {\n return;\n }\n const picked = pick(attrs, keys);\n // instrumentation-http 0.301.2 DERIVES error.type from the status code on the\n // METRIC attributes only (utils.js get*StableRequestMetricAttributesOnResponse:\n // `metricAttributes[ATTR_ERROR_TYPE] ??= String(statusCode)`); the span never\n // gets it unless an error was thrown. Mirror that derivation or every\n // error-status data point's key misses and its exemplars vanish. The\n // thresholds differ per side: server counts only 5xx, client 4xx and up.\n if (picked['error.type'] === undefined) {\n const status = attrs['http.response.status_code'];\n const errorFloor = metric === SERVER_METRIC ? 500 : 400;\n if (typeof status === 'number' && status >= errorFloor && status < 600) {\n picked['error.type'] = String(status);\n }\n }\n // Stable histograms count in seconds.\n const valueSeconds = (performance.now() - start) / 1000;\n exporter.recordExemplar(\n metric,\n picked,\n valueSeconds,\n // No attributes of our own. The store adds `trace_flags` from the trace\n // below, and an app that wants more keys on an HTTP exemplar records its\n // own histogram with recordWithExemplar.\n {},\n httpDurationBoundaries(),\n // The HTTP request span IS the link target. A span that reaches here is\n // always sampled, so these trace_flags are always \"01\".\n exemplarTraceFrom(span.spanContext()),\n );\n } catch (err) {\n diag.warn(`sherlock: auto-HTTP exemplar for ${metric} failed`, err);\n }\n}\n\n// Copy only the metric-subset keys that are present; absent keys are skipped\n// (makeKey skips undefined too, so this reproduces the data point's exact set).\nfunction pick(attrs: Attributes, keys: string[]): Record<string, AttrValue | undefined> {\n const out: Record<string, AttrValue | undefined> = {};\n for (const key of keys) {\n const value = attrs[key];\n if (value !== undefined) {\n out[key] = value as AttrValue;\n }\n }\n return out;\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 { Instrumentation } from '@opentelemetry/instrumentation';\nimport type { HttpInstrumentationConfig } from '@opentelemetry/instrumentation-http';\nimport { isIngestRequest } from './exportTarget';\nimport { onHttpRequestStart, onHttpResponse } from './httpExemplars';\nimport { isIgnoredPath } from './ignorePaths';\nimport { log } from './logging';\n\n// The four HTTP hooks the package owns, and the merge that keeps them attached\n// however the app supplies its instrumentations.\n//\n// THE RULE: whichever http instrumentation ends up active carries these hooks.\n// One arrives from `./register`, which passes `packageHttpConfig()` into the\n// bundle on line 1, so the bundle's http instance is born with them — and\n// `{ enabled }` / `{ disabled }` only drop members of that bundle, so the\n// survivors keep what they were built with. The other arrives at `start()` as\n// part of an explicit `Instrumentation[]`, built by the app, so `start()` merges\n// the hooks into it with `setConfig` before registering the list.\n// `instrumentation-http` reads `getConfig()` per request, so a merge after\n// construction — even after `enable()` — takes effect on the next request.\n//\n// This module is loaded by `./register`, so it must stay state-only: no runtime\n// import of `node:http` or of anything else the patches still have to wrap. Both\n// imports below are type-only for that reason.\n\n/** The instrumentation the hooks belong to. */\nexport const HTTP_INSTRUMENTATION_NAME = '@opentelemetry/instrumentation-http';\n\n/** The package's own http instrumentation config. */\nexport function packageHttpConfig(): HttpInstrumentationConfig {\n return {\n // Health and liveness probes are pure noise as spans — the same path, every\n // few seconds, per pod, forever. Extend the list with SHERLOCK_IGNORE_PATHS\n // or `start({ ignorePaths })`; the set is read per request, so a later\n // addition still takes effect.\n ignoreIncomingRequestHook: (request) => isIgnoredPath(request.url),\n // The distribution never traces or meters its own export path. Returning\n // true here returns before the span AND before the\n // http.client.request.duration record (verified against\n // instrumentation-http 0.301.2), which is what stops the self-metric —\n // suppressTracing alone would only stop the span.\n ignoreOutgoingRequestHook: (options) => isIngestRequest(options),\n // Exemplars for the auto-instrumented HTTP histograms: the hooks time each\n // request and record an exemplar next to the histogram point the\n // instrumentation emits (see httpExemplars.ts). Inert until `start()` hands\n // them the exporter.\n requestHook: onHttpRequestStart,\n responseHook: onHttpResponse,\n };\n}\n\n/**\n * Merges the package hooks into the http instrumentation of an explicit list.\n * The app's own hooks are kept and run first; ours run after. An app hook that\n * throws is contained, because the self-export guard and the health-check filter\n * must run even when the app's hook fails.\n */\nexport function mergePackageHttpConfig(instrumentations: Instrumentation[]): void {\n // Matched by name, not by `instanceof`: an app that resolves its own copy of\n // `@opentelemetry/instrumentation-http` has a different class object, and an\n // `instanceof` test would silently miss it and drop all four hooks.\n const target = instrumentations.find(\n (instrumentation) => instrumentation.instrumentationName === HTTP_INSTRUMENTATION_NAME,\n ) as Instrumentation<HttpInstrumentationConfig> | undefined;\n if (!target) {\n log.debug(\n 'sherlock: the instrumentation list has no http instrumentation — the self-export guard, the ignored paths and the auto-HTTP exemplars are off',\n );\n return;\n }\n\n const app = target.getConfig();\n const ours = packageHttpConfig();\n // setConfig REPLACES the config, so everything the app set has to be carried\n // over by hand.\n target.setConfig({\n ...app,\n ignoreIncomingRequestHook: (request) =>\n safeIgnore(() => app.ignoreIncomingRequestHook?.(request)) ||\n (ours.ignoreIncomingRequestHook?.(request) ?? false),\n ignoreOutgoingRequestHook: (options) =>\n safeIgnore(() => app.ignoreOutgoingRequestHook?.(options)) ||\n (ours.ignoreOutgoingRequestHook?.(options) ?? false),\n requestHook: (span, request) => {\n safeHook(() => app.requestHook?.(span, request));\n ours.requestHook?.(span, request);\n },\n responseHook: (span, response) => {\n safeHook(() => app.responseHook?.(span, response));\n ours.responseHook?.(span, response);\n },\n });\n}\n\n/** An app ignore hook that throws means \"do not ignore\", never \"lose our guard\". */\nfunction safeIgnore(hook: () => boolean | undefined): boolean {\n try {\n return hook() === true;\n } catch (err) {\n log.warn('sherlock: an app http ignore hook threw — treating the request as not ignored', err);\n return false;\n }\n}\n\nfunction safeHook(hook: () => void): void {\n try {\n hook();\n } catch (err) {\n log.warn('sherlock: an app http hook threw', err);\n }\n}\n","export const FASTIFY_INSTRUMENTATION_NAME = '@sherlock-labs/node/fastify';\n","import type { Instrumentation } from '@opentelemetry/instrumentation';\nimport { log } from './logging';\nimport { FASTIFY_INSTRUMENTATION_NAME } from './ownInstrumentations';\nimport type { InstrumentationSelection } from './types';\n\n// `instrumentations: { enabled }` / `{ disabled }` — narrowing the bundle\n// `./register` installed, without replacing it. The names are the ones\n// OTEL_NODE_ENABLED_INSTRUMENTATIONS uses: the package suffix, so \"http\" means\n// `@opentelemetry/instrumentation-http`.\n//\n// The filter runs at `start()`, not at bundle construction, because the option\n// only reaches us there while the bundle is built on line 1 of the process. So\n// `./register` builds the WHOLE default set — it hides the two env vars from\n// `getNodeAutoInstrumentations` for exactly this reason — and the selection,\n// from the option or from the environment, is applied here. That is what lets\n// the option beat the env vars in both directions instead of only narrowing\n// what they left.\n//\n// Nothing is constructed here, so every survivor keeps the config it was built\n// with in `./register`, the http hooks included. The losers are disabled, and\n// they recorded nothing in the meantime because a dormant patch with no provider\n// behind it records nothing.\n\nconst PACKAGE_PREFIX = '@opentelemetry/instrumentation-';\n\nconst OWN_INSTRUMENTATIONS: Record<string, string> = {\n fastify: FASTIFY_INSTRUMENTATION_NAME,\n};\nconst ENABLED_ENV = 'OTEL_NODE_ENABLED_INSTRUMENTATIONS';\nconst DISABLED_ENV = 'OTEL_NODE_DISABLED_INSTRUMENTATIONS';\n\n/** True when the option is the filter form rather than an explicit list. */\nexport function isSelection(\n override: Instrumentation[] | InstrumentationSelection,\n): override is InstrumentationSelection {\n return !Array.isArray(override);\n}\n\n/**\n * Runs the bundle factory with the two instrumentation env vars hidden, so it\n * returns the full default set. `./register` is the only caller: the env vars\n * are then honoured at `start()`, where the option can outrank them.\n */\nexport function buildFullBundle<T>(build: () => T): T {\n const saved = {\n [ENABLED_ENV]: process.env[ENABLED_ENV],\n [DISABLED_ENV]: process.env[DISABLED_ENV],\n };\n delete process.env[ENABLED_ENV];\n delete process.env[DISABLED_ENV];\n try {\n return build();\n } finally {\n for (const [name, value] of Object.entries(saved)) {\n if (value === undefined) {\n delete process.env[name];\n } else {\n process.env[name] = value;\n }\n }\n }\n}\n\n/**\n * The selection the environment asks for, or undefined when it asks for\n * nothing. Read only when `start()` was given no `instrumentations` option.\n */\nexport function selectionFromEnv(): InstrumentationSelection | undefined {\n const enabled = splitEnv(ENABLED_ENV);\n const disabled = splitEnv(DISABLED_ENV);\n if (!enabled && !disabled) {\n return undefined;\n }\n return { enabled, disabled };\n}\n\nfunction splitEnv(name: string): string[] | undefined {\n const raw = process.env[name];\n if (raw === undefined) {\n return undefined;\n }\n return raw\n .split(',')\n .map((entry) => entry.trim())\n .filter((entry) => entry.length > 0);\n}\n\n/** `\"http\"` → `\"@opentelemetry/instrumentation-http\"`. */\nfunction packageName(name: string): string {\n const short = name.trim();\n return OWN_INSTRUMENTATIONS[short] ?? `${PACKAGE_PREFIX}${short}`;\n}\n\nfunction shortName(name: string): string {\n const own = Object.entries(OWN_INSTRUMENTATIONS).find(([, full]) => full === name);\n if (own) {\n return own[0];\n }\n return name.startsWith(PACKAGE_PREFIX) ? name.slice(PACKAGE_PREFIX.length) : name;\n}\n\n/**\n * Applies `{ enabled }` and `{ disabled }` to the installed bundle and returns\n * the instrumentations that stay on. The dropped ones are disabled.\n *\n * Both keys may be given, and they compose the way the env vars do: `enabled`\n * narrows the bundle, `disabled` then subtracts from what is left.\n */\nexport function selectInstrumentations(\n bundle: Instrumentation[],\n selection: InstrumentationSelection,\n): Instrumentation[] {\n const enabled = selection.enabled?.map(packageName);\n const disabled = new Set(selection.disabled?.map(packageName));\n if (!enabled && disabled.size === 0) {\n log.warn('sherlock: instrumentations needs `enabled` or `disabled` — keeping the whole bundle');\n return bundle;\n }\n if (bundle.length === 0) {\n log.warn(\n 'sherlock: instrumentations `enabled`/`disabled` filters the bundle `./register` installs, and nothing is installed — no auto-instrumentation',\n );\n return bundle;\n }\n\n const wanted = new Set(enabled);\n warnAboutUnknownNames([...wanted, ...disabled], bundle);\n\n const kept: Instrumentation[] = [];\n for (const instrumentation of bundle) {\n const name = instrumentation.instrumentationName;\n if ((!enabled || wanted.has(name)) && !disabled.has(name)) {\n kept.push(instrumentation);\n } else {\n instrumentation.disable();\n }\n }\n return kept;\n}\n\n/** A misspelt name — \"postgres\" for \"pg\" — would take pg telemetry off in silence. */\nfunction warnAboutUnknownNames(wanted: string[], bundle: Instrumentation[]): void {\n const present = new Set(bundle.map((instrumentation) => instrumentation.instrumentationName));\n for (const name of wanted) {\n if (!present.has(name)) {\n log.warn(\n `sherlock: instrumentation ${JSON.stringify(shortName(name))} is not in the bundle — check the spelling`,\n );\n }\n }\n}\n","import { context } from '@opentelemetry/api';\nimport { isTracingSuppressed } from '@opentelemetry/core';\nimport { shared } from './shared';\n\n// A self-check on the \"never trace our own export path\" principle.\n//\n// The exporters wrap their send in `suppressTracing`, but the actual POST\n// happens inside the OTLP transport, several async hops later. The metrics\n// exporter calls `probeExportContext()` from the transport's header callback,\n// so the answer is read at the real send site rather than at the call site we\n// control. `isTracingSuppressed` is the same check `Tracer.startSpan` makes, so\n// a `true` here means an instrumented POST produces a non-recording span.\n\nconst state = shared('exportProbe', () => ({\n lastSuppressed: undefined as boolean | undefined,\n}));\n\nexport function probeExportContext(): void {\n state.lastSuppressed = isTracingSuppressed(context.active());\n}\n\n/** True/false after the first export attempt; undefined before one happened. */\nexport function lastExportWasSuppressed(): boolean | undefined {\n return state.lastSuppressed;\n}\n","import { context } from '@opentelemetry/api';\nimport { type ExportResult, ExportResultCode, suppressTracing } from '@opentelemetry/core';\nimport {\n AggregationTemporalityPreference,\n OTLPMetricExporterBase,\n} from '@opentelemetry/exporter-metrics-otlp-http';\nimport { getSharedConfigurationDefaults } from '@opentelemetry/otlp-exporter-base';\nimport {\n createOtlpHttpExportDelegate,\n httpAgentFactoryFromOptions,\n} from '@opentelemetry/otlp-exporter-base/node-http';\nimport {\n type IExporterMetricsHelper,\n type ISerializer,\n JsonMetricsSerializer,\n MetricsExporterMetricsHelper,\n} from '@opentelemetry/otlp-transformer';\nimport type { ResourceMetrics } from '@opentelemetry/sdk-metrics';\nimport {\n type AttrValue,\n ExemplarReservoirStore,\n type ExemplarTrace,\n type JsonExportRequest,\n} from './exemplarReservoir';\nimport { probeExportContext } from './exportProbe';\nimport { telemetryState } from './telemetryState';\n\n// OTLP metrics exporter that adds histogram exemplars, which the OpenTelemetry\n// JS SDK cannot emit on its own. Upstream gap:\n// https://github.com/open-telemetry/opentelemetry-js/issues/5147\n//\n// It reuses the official OTLP HTTP transport (retry, gzip, keep-alive) by\n// extending OTLPMetricExporterBase; the only custom seam is the serializer,\n// which splices buffered exemplars into the payload before send.\n// `recordExemplar` buffers per-observation exemplars in an\n// ExemplarReservoirStore, and the reservoirs drain on every export.\n//\n// The transport is `node:http` / `node:https`, never fetch/undici. That is a\n// hard requirement: a custom `Host` header is what routes an in-cluster export\n// to the right tenant, and the Fetch spec makes `Host` a forbidden header that\n// undici drops silently. In otlp-exporter-base 0.301.2 `sendWithHttp` passes our\n// header object straight into `http.request`, and Node only fills in its own\n// `Host` when the caller supplied none.\n//\n// That transport also resolves `http` / `https` through a dynamic `import()` on\n// the first send, not at module load. On Node >= 24 a core module already in the\n// require cache cannot be patched, so an eager import here would silently kill\n// all http auto-instrumentation.\n\nconst DEFAULT_RESERVOIR_SIZE = 5;\n\nexport interface ExemplarExporterOptions {\n /** Full endpoint, including the /v1/metrics path. */\n url: string;\n /** Merged into every export request, after Content-Type. */\n headers?: Record<string, string>;\n /** Overrides the `Host` header on export requests. */\n host?: string;\n /** Max exemplars kept per histogram bucket per export interval. */\n reservoirSize?: number;\n /**\n * Metric names whose exemplars must always match a data point; a miss over\n * two consecutive exports triggers the store's drift warning.\n */\n driftWatchMetricNames?: string[];\n}\n\nexport class ExemplarExporter extends OTLPMetricExporterBase {\n /** The buffered exemplars. Internal; read by tests and by the kill switch. */\n readonly store: ExemplarReservoirStore;\n\n constructor(opts: ExemplarExporterOptions) {\n const store = new ExemplarReservoirStore({\n reservoirSize: opts.reservoirSize ?? DEFAULT_RESERVOIR_SIZE,\n driftWatchMetricNames: opts.driftWatchMetricNames,\n });\n\n // The official JSON serializer plus our exemplar splice — the single seam\n // OTLPMetricExporterBase exposes for extension.\n const serializer: ISerializer<ResourceMetrics, unknown> = {\n serializeRequest: (req) => {\n const bytes = JsonMetricsSerializer.serializeRequest(req);\n if (!bytes) {\n return bytes;\n }\n const payload = JSON.parse(new TextDecoder().decode(bytes)) as JsonExportRequest;\n store.inject(payload);\n return new TextEncoder().encode(JSON.stringify(payload));\n },\n deserializeResponse: (data) => JsonMetricsSerializer.deserializeResponse(data),\n };\n\n const staticHeaders: Record<string, string> = {\n 'Content-Type': 'application/json',\n ...opts.headers,\n };\n // Last, so an explicit host override always wins over a caller's headers.\n if (opts.host) {\n staticHeaders.Host = opts.host;\n }\n\n super(\n createOtlpHttpExportDelegate(\n {\n ...getSharedConfigurationDefaults(),\n // Caller passes the full endpoint incl. /v1/metrics; used as-is.\n url: opts.url,\n headers: () => {\n // Called by the transport inside send(), i.e. at the real POST site\n // — the only place worth checking that the suppression in export()\n // below survived the async hops.\n probeExportContext();\n return Promise.resolve(staticHeaders);\n },\n agentFactory: httpAgentFactoryFromOptions({ keepAlive: true }),\n },\n serializer as ISerializer<unknown, unknown>,\n // The three args below feed the delegate's otel.sdk.exporter.* self\n // metrics. The component type mirrors the stock OTLPMetricExporter,\n // whose constant is package-internal. The meter provider is undefined on\n // purpose: ExporterMetrics does `meterProvider ? getMeter(...) :\n // createNoopMeter()`, so undefined means noop rather than a fallback to\n // the global meter provider — which is ours, i.e. an export loop.\n 'otlp_http_metric_exporter',\n MetricsExporterMetricsHelper as IExporterMetricsHelper<unknown>,\n undefined,\n ),\n // Sherlock's aggregation assumes delta; cumulative inflates counts on\n // every export. Not a tunable.\n { temporalityPreference: AggregationTemporalityPreference.DELTA },\n );\n this.store = store;\n }\n\n // Two jobs here.\n //\n // 1. The metrics kill switch. Gating at export rather than at record time is\n // what covers BOTH metric families: our own instruments and the SDK-owned\n // auto-instrumented histograms all leave through this one exporter.\n // Dropping a batch is safe because temporality is DELTA — a dropped\n // interval is a gap in the chart, not a double count on the next export.\n // 2. Suppressing tracing for the export itself, so the POST that ships\n // telemetry never becomes telemetry. `suppressTracing` is what\n // `Tracer.startSpan` checks.\n override export(metrics: ResourceMetrics, resultCallback: (result: ExportResult) => void): void {\n if (!telemetryState.metricsOn) {\n // inject() only runs during serialization, which we're skipping — clear\n // the reservoirs so exemplars recorded around the flip don't sit parked\n // and get spliced, stale, into the first export after re-enable.\n this.store.clear();\n resultCallback({ code: ExportResultCode.SUCCESS });\n return;\n }\n context.with(suppressTracing(context.active()), () => {\n super.export(metrics, resultCallback);\n });\n }\n\n // Record an exemplar for a histogram observation, from the same site that\n // calls `histogram.record(value, primaryAttrs)`.\n // - primaryAttrs: the metric's aggregation labels, which match the exemplar to\n // its data point at export time.\n // - filteredAttrs: per-observation, high-cardinality keys the app owns.\n // - boundaries: the histogram's explicit bucket boundaries, so the exemplar\n // competes only within its own bucket. Pass the same array the instrument\n // was created with.\n // - trace: the trace context active at record time, exported as the exemplar's\n // top-level traceId/spanId plus a `trace_flags` filteredAttribute.\n recordExemplar(\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 // Kill switch: while metrics are off nothing drains the reservoirs, so\n // don't fill them either.\n if (!telemetryState.metricsOn) {\n return;\n }\n this.store.record(metricName, primaryAttrs, value, filteredAttrs, boundaries, trace);\n }\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 { Attributes } from '@opentelemetry/api';\nimport {\n defaultResource,\n detectResources,\n envDetector,\n type Resource,\n resourceFromAttributes,\n} from '@opentelemetry/resources';\n\n// Merge order: the SDK identity, then the environment, then the caller — so\n// `start()` options always win.\n//\n// The envDetector step is not optional. `defaultResource()` on its own does NOT\n// read OTEL_RESOURCE_ATTRIBUTES, and leaving the detector out looks like it\n// works (spans still arrive) while silently dropping the environment tag every\n// dashboard filters on. `EnvDetector.detect` reads OTEL_RESOURCE_ATTRIBUTES and\n// OTEL_SERVICE_NAME, percent-decodes each pair, and discards the whole variable\n// on a malformed entry.\nexport function buildResource(serviceName: string, extra: Attributes = {}): Resource {\n return defaultResource()\n .merge(detectResources({ detectors: [envDetector] }))\n .merge(resourceFromAttributes({ ...extra, 'service.name': serviceName }));\n}\n","import { metrics } from '@opentelemetry/api';\nimport {\n AggregationType,\n MeterProvider,\n PeriodicExportingMetricReader,\n} from '@opentelemetry/sdk-metrics';\nimport { ExemplarExporter } from './exemplarExporter';\nimport { httpDurationBoundaries, setHttpDurationBoundaries } from './httpBoundaries';\nimport { AUTO_HTTP_METRICS, setAutoHttpExemplarExporter } from './httpExemplars';\nimport { bindInstruments, unbindInstruments } from './instruments';\nimport { log } from './logging';\nimport type { StartableOptions } from './options';\nimport { buildResource } from './resource';\nimport { shared } from './shared';\n\n// The metrics pipeline: an explicitly constructed MeterProvider + a periodic\n// reader + our ExemplarExporter (OTLP/JSON to Sherlock's /v1/metrics, DELTA\n// temporality, per-bucket exemplar reservoirs).\n//\n// Providers are always constructed here, never through NodeSDK, which reads the\n// environment for signals we never configured — a process with pino\n// instrumentation and no logs endpoint quietly POSTs log records to\n// localhost:4318/v1/logs. Explicit construction makes an unconfigured signal\n// impossible to switch on by accident.\n\nconst state = shared('metricsPipeline', () => ({\n provider: undefined as MeterProvider | undefined,\n}));\n\n/** Returns the provider so `start()` can rebind it onto the instrumentations. */\nexport function startMetrics(\n options: StartableOptions,\n connection: { token: string; serviceName: string },\n): MeterProvider {\n // Applied before the exporter and the views read the list, and mutated in\n // place so instrument definitions created at module scope pick it up.\n setHttpDurationBoundaries(options.httpDurationBoundaries);\n\n const exporter = new ExemplarExporter({\n url: `${options.endpoint}/v1/metrics`,\n headers: { Authorization: `Bearer ${connection.token}`, ...options.exporter.headers },\n host: options.exporter.host,\n reservoirSize: options.exemplarsPerBucket,\n // Warn (throttled) if an auto-HTTP exemplar stops matching its data point\n // — the drift guard for the hand-mirrored attribute keys.\n driftWatchMetricNames: AUTO_HTTP_METRICS,\n });\n\n const provider = new MeterProvider({\n resource: buildResource(connection.serviceName, options.resourceAttributes),\n readers: [\n new PeriodicExportingMetricReader({\n exporter,\n exportIntervalMillis: options.exportIntervalMillis,\n }),\n ],\n // Re-bucket the auto-instrumented HTTP histograms onto the tuned\n // boundaries. A view's explicit-bucket aggregation wins over the\n // instrumentation's own `advice`; the OpenTelemetry defaults are coarse\n // exactly where web latency lives (100–500 ms). The exemplar reservoirs\n // bucket by the same list.\n views: AUTO_HTTP_METRICS.map((instrumentName) => ({\n instrumentName,\n aggregation: {\n type: AggregationType.EXPLICIT_BUCKET_HISTOGRAM,\n options: { boundaries: httpDurationBoundaries() },\n },\n })),\n });\n metrics.setGlobalMeterProvider(provider);\n // Let instrument definitions resolve real instruments and route their\n // exemplars into this exporter's reservoirs.\n bindInstruments((...args) => {\n exporter.recordExemplar(...args);\n });\n // Let the auto-instrumentation HTTP hooks (wired in ./register) record\n // exemplars into this exporter too.\n setAutoHttpExemplarExporter(exporter);\n state.provider = provider;\n\n log.info(\n `sherlock metrics started: endpoint=${options.endpoint} service=${connection.serviceName} interval=${options.exportIntervalMillis}ms`,\n );\n return provider;\n}\n\n/**\n * Unhooks the pipeline from every global it owns, synchronously, and hands back\n * the provider so the caller can flush it whenever it likes.\n *\n * The split exists for the restart case. `metrics.setGlobalMeterProvider`\n * refuses to overwrite an existing registration, so `metrics.disable()` has to\n * run BEFORE the new provider is registered, not after an awaited flush, or the\n * flush's `disable()` lands late and wipes the replacement.\n */\nexport function detachMetrics(): MeterProvider | undefined {\n const provider = state.provider;\n if (!provider) {\n return undefined;\n }\n state.provider = undefined;\n unbindInstruments();\n setAutoHttpExemplarExporter(undefined);\n metrics.disable();\n return provider;\n}\n\n/** Flushes a detached provider. Never rejects. */\nexport async function flushMetricsProvider(provider: MeterProvider): Promise<void> {\n try {\n // Runs the reader's final collect and export before the transport goes away.\n await provider.shutdown();\n } catch (err) {\n log.error('sherlock: metrics shutdown failed', err);\n }\n}\n\nexport async function stopMetrics(): Promise<void> {\n const provider = detachMetrics();\n if (provider) {\n await flushMetricsProvider(provider);\n }\n}\n","import type { Attributes } from '@opentelemetry/api';\nimport type { Instrumentation } from '@opentelemetry/instrumentation';\nimport { selectionFromEnv } from './instrumentationSelection';\nimport { log } from './logging';\nimport type { ExporterOptions, InstrumentationSelection, StartOptions } from './types';\n\n// Turns `start()` options plus the environment into one flat, already-validated\n// shape. Anything passed to `start()` wins over the environment; the\n// environment wins over the defaults.\n\nconst DEFAULT_EXPORT_INTERVAL_MS = 30_000;\nconst DEFAULT_SAMPLE_RATIO = 1;\nconst DEFAULT_EXEMPLARS_PER_BUCKET = 5;\n\nexport interface ResolvedOptions {\n accessToken: string | undefined;\n endpoint: string | undefined;\n serviceName: string | undefined;\n resourceAttributes: Attributes;\n tracingEnabled: boolean;\n sampleRatio: number;\n metricsEnabled: boolean;\n exportIntervalMillis: number;\n httpDurationBoundaries: number[] | undefined;\n exemplarsPerBucket: number;\n instrumentations: Instrumentation[] | InstrumentationSelection | undefined;\n exporter: ExporterOptions;\n ignorePaths: string[];\n fastifyLifecycleSpans: boolean | undefined;\n}\n\n/** Resolved options that passed start()'s checks: the endpoint is known. */\nexport type StartableOptions = ResolvedOptions & { endpoint: string };\n\nfunction envString(name: string): string | undefined {\n const raw = process.env[name];\n return raw && raw.trim() !== '' ? raw.trim() : undefined;\n}\n\n/**\n * Reads a 0..1 ratio. An invalid value is ignored with a warning: a typo in a\n * deployment variable must not silently kill all tracing.\n */\nexport function resolveSampleRatio(override: number | undefined): number {\n const raw = override ?? envString('OTEL_TRACES_SAMPLER_ARG');\n if (raw === undefined) {\n return DEFAULT_SAMPLE_RATIO;\n }\n const ratio = Number(raw);\n if (!Number.isFinite(ratio) || ratio < 0 || ratio > 1) {\n log.warn(\n `sherlock: invalid sample ratio ${JSON.stringify(raw)} — expected 0..1, using ${DEFAULT_SAMPLE_RATIO}`,\n );\n return DEFAULT_SAMPLE_RATIO;\n }\n return ratio;\n}\n\nfunction resolveExportInterval(override: number | undefined): number {\n const raw = override ?? envString('SHERLOCK_METRICS_EXPORT_INTERVAL');\n if (raw === undefined) {\n return DEFAULT_EXPORT_INTERVAL_MS;\n }\n const interval = Number(raw);\n if (!Number.isFinite(interval) || interval <= 0) {\n log.warn(\n `sherlock: invalid metrics export interval ${JSON.stringify(raw)} — using ${DEFAULT_EXPORT_INTERVAL_MS}ms`,\n );\n return DEFAULT_EXPORT_INTERVAL_MS;\n }\n return interval;\n}\n\n/**\n * Validates the ingest base URL. There is no default: each Sherlock tenant has\n * its own ingest endpoint, so a missing one leaves telemetry off rather than\n * sending data somewhere it does not belong. A value that `new URL()` rejects,\n * or one on a protocol the exporters cannot speak, is rejected with a warning.\n * An endpoint without a scheme passes every other check here, brings the\n * metrics pipeline up, and then throws out of the trace exporter's constructor,\n * so catching it at the edge is what keeps `start()` on its \"telemetry stays\n * off, everything else keeps running\" contract.\n */\nexport function resolveEndpoint(raw: string | undefined): string | undefined {\n if (raw === undefined || raw.trim() === '') {\n return undefined;\n }\n const trimmed = raw.replace(/\\/+$/, '');\n let parsed: URL;\n try {\n parsed = new URL(trimmed);\n } catch {\n log.warn(`sherlock: invalid endpoint ${JSON.stringify(raw)} — not a URL`);\n return undefined;\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n log.warn(`sherlock: invalid endpoint ${JSON.stringify(raw)} — expected http or https`);\n return undefined;\n }\n return trimmed;\n}\n\n/**\n * A reservoir of zero (or a fraction, or NaN) is the quietest way to lose the\n * feature this package exists for: observations still count into `seen` and\n * still consume the series budget, they are just never kept, and the drift\n * guard stays silent because the series does match its data point.\n */\nfunction resolveExemplarsPerBucket(override: number | undefined): number {\n if (override === undefined) {\n return DEFAULT_EXEMPLARS_PER_BUCKET;\n }\n if (!Number.isInteger(override) || override < 1) {\n log.warn(\n `sherlock: invalid exemplarsPerBucket ${JSON.stringify(override)} — expected a positive integer, using ${DEFAULT_EXEMPLARS_PER_BUCKET}`,\n );\n return DEFAULT_EXEMPLARS_PER_BUCKET;\n }\n return override;\n}\n\n/**\n * Boundaries must be finite, ascending and distinct, because the histogram and\n * the exemplar reservoir both index by them: a NaN or a duplicate puts an\n * exemplar in a bucket its count never lands in. Returns undefined for \"keep\n * the tuned defaults\".\n */\nfunction resolveBoundaries(override: number[] | undefined): number[] | undefined {\n if (override === undefined) {\n return undefined;\n }\n if (!Array.isArray(override) || override.some((value) => !Number.isFinite(value))) {\n log.warn(\n 'sherlock: invalid httpDurationBoundaries — expected finite numbers, using the tuned defaults',\n );\n return undefined;\n }\n const cleaned = [...new Set(override)].sort((a, b) => a - b);\n if (cleaned.length === 0) {\n log.warn('sherlock: empty httpDurationBoundaries — using the tuned defaults');\n return undefined;\n }\n if (cleaned.length !== override.length) {\n log.warn('sherlock: httpDurationBoundaries had duplicates or was unsorted — normalised');\n }\n return cleaned;\n}\n\nexport function resolveOptions(options: StartOptions = {}): ResolvedOptions {\n const tracing = options.tracing ?? true;\n const metrics = options.metrics ?? true;\n const tracingOptions = typeof tracing === 'object' ? tracing : {};\n const metricsOptions = typeof metrics === 'object' ? metrics : {};\n\n return {\n accessToken: options.accessToken ?? envString('SHERLOCK_ACCESS_TOKEN'),\n // Trailing slashes stripped so `${endpoint}/v1/metrics` never doubles up.\n endpoint: resolveEndpoint(options.endpoint ?? envString('SHERLOCK_ENDPOINT')),\n serviceName: options.serviceName ?? envString('OTEL_SERVICE_NAME'),\n resourceAttributes: options.resourceAttributes ?? {},\n tracingEnabled: tracing !== false,\n sampleRatio: resolveSampleRatio(tracingOptions.sampleRatio),\n metricsEnabled: metrics !== false,\n exportIntervalMillis: resolveExportInterval(metricsOptions.exportIntervalMillis),\n httpDurationBoundaries: resolveBoundaries(metricsOptions.httpDurationBoundaries),\n exemplarsPerBucket: resolveExemplarsPerBucket(metricsOptions.exemplarsPerBucket),\n // The option outranks the env vars entirely: when it is given, the two\n // OTEL_NODE_*_INSTRUMENTATIONS variables are not read at all.\n instrumentations: options.instrumentations ?? selectionFromEnv(),\n exporter: options.exporter ?? {},\n ignorePaths: options.ignorePaths ?? [],\n fastifyLifecycleSpans: options.fastify?.lifecycleSpans,\n };\n}\n","import { context, propagation, trace } from '@opentelemetry/api';\nimport { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';\nimport {\n CompositePropagator,\n suppressTracing,\n W3CBaggagePropagator,\n W3CTraceContextPropagator,\n} from '@opentelemetry/core';\nimport { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';\nimport {\n BatchSpanProcessor,\n ParentBasedSampler,\n type ReadableSpan,\n type Sampler,\n SamplingDecision,\n type SamplingResult,\n type SpanExporter,\n TraceIdRatioBasedSampler,\n TracerProvider,\n} from '@opentelemetry/sdk-trace';\nimport { log } from './logging';\nimport type { StartableOptions } from './options';\nimport { buildResource } from './resource';\nimport { shared } from './shared';\nimport { telemetryState } from './telemetryState';\n\n// The tracing pipeline. The library patches are installed much earlier, by\n// ./register; they stay dormant until this registers the global tracer\n// provider.\n\nconst state = shared('tracingPipeline', () => ({\n provider: undefined as TracerProvider | undefined,\n}));\n\n// The runtime kill switch for traces. It sits INSIDE ParentBased (see\n// buildSampler), and the nesting is the point: ParentBased consults the root\n// sampler only for spans with no parent and for spans with a remote parent,\n// while spans with a local parent copy their parent's decision. So a flip to\n// off stops NEW traces and lets requests already being traced finish whole.\nexport class FlagSampler implements Sampler {\n constructor(private readonly inner: Sampler) {}\n\n shouldSample(...args: Parameters<Sampler['shouldSample']>): SamplingResult {\n if (!telemetryState.tracesOn) {\n return { decision: SamplingDecision.NOT_RECORD };\n }\n return this.inner.shouldSample(...args);\n }\n\n toString(): string {\n return `FlagSampler(${this.inner.toString()})`;\n }\n}\n\n// `traceparent` is attacker-controlled input on a public API, so a remote parent\n// must not be able to force sampling or dodge it. Both remote branches take the\n// same flag+ratio decision as a new root; local parents still follow their\n// parent, so in-flight traces finish whole when the kill switch flips.\n//\n// Known limit: our spans adopt a client-sent traceId, and\n// TraceIdRatioBasedSampler decides from that traceId alone, so a client that\n// only sends trace ids passing the threshold gets all of its own requests\n// sampled at any ratio below 1. The flag cannot be bypassed — FlagSampler runs\n// first — but the RATIO only bounds clients that do not craft trace ids.\nexport function buildSampler(sampleRatio: number): Sampler {\n const rootSampler = new FlagSampler(new TraceIdRatioBasedSampler(sampleRatio));\n return new ParentBasedSampler({\n root: rootSampler,\n remoteParentSampled: rootSampler,\n remoteParentNotSampled: rootSampler,\n });\n}\n\n// Wraps the OTLP trace exporter so the export POST itself is never traced: an\n// instrumented export produces spans about exporting spans.\nclass SuppressedTraceExporter implements SpanExporter {\n constructor(private readonly inner: OTLPTraceExporter) {}\n\n export(spans: ReadableSpan[], resultCallback: Parameters<SpanExporter['export']>[1]): void {\n context.with(suppressTracing(context.active()), () => {\n this.inner.export(spans, resultCallback);\n });\n }\n\n shutdown(): Promise<void> {\n return this.inner.shutdown();\n }\n\n forceFlush(): Promise<void> {\n return this.inner.forceFlush?.() ?? Promise.resolve();\n }\n}\n\nexport function startTracing(\n options: StartableOptions,\n connection: { token: string; serviceName: string },\n): void {\n const headers: Record<string, string> = {\n Authorization: `Bearer ${connection.token}`,\n ...options.exporter.headers,\n };\n if (options.exporter.host) {\n headers.Host = options.exporter.host;\n }\n\n const provider = new TracerProvider({\n resource: buildResource(connection.serviceName, options.resourceAttributes),\n sampler: buildSampler(options.sampleRatio),\n spanProcessors: [\n new BatchSpanProcessor({\n exporter: new SuppressedTraceExporter(\n new OTLPTraceExporter({ url: `${options.endpoint}/v1/traces`, headers }),\n ),\n }),\n ],\n });\n // The three globals NodeTracerProvider.register() used to set before\n // OpenTelemetry 3 removed it: the tracer provider, an AsyncLocalStorage\n // context manager, and the W3C trace-context + baggage propagators. From this\n // point the patches ./register installed start recording spans.\n trace.setGlobalTracerProvider(provider);\n context.setGlobalContextManager(new AsyncLocalStorageContextManager().enable());\n propagation.setGlobalPropagator(\n new CompositePropagator({\n propagators: [new W3CTraceContextPropagator(), new W3CBaggagePropagator()],\n }),\n );\n state.provider = provider;\n\n log.info(\n `sherlock tracing started: endpoint=${options.endpoint} service=${connection.serviceName} sampleRatio=${options.sampleRatio}`,\n );\n}\n\n/**\n * Unhooks the pipeline from every global it owns, synchronously, and hands back\n * the provider so the caller can flush it whenever it likes.\n *\n * `startTracing()` installs three process-global registrations — tracer\n * provider, context manager, propagator — and `shutdown()` leaves all three in\n * place. Clearing them before the flush rather than after it is what lets a\n * replacement provider register instead of being refused as \"already set\".\n */\nexport function detachTracing(): TracerProvider | undefined {\n const provider = state.provider;\n if (!provider) {\n return undefined;\n }\n state.provider = undefined;\n trace.disable();\n context.disable();\n propagation.disable();\n return provider;\n}\n\n/** Flushes a detached provider. Never rejects. */\nexport async function flushTracerProvider(provider: TracerProvider): Promise<void> {\n try {\n // Flushes the pending span batch.\n await provider.shutdown();\n } catch (err) {\n log.error('sherlock: tracing shutdown failed', err);\n }\n}\n\nexport async function stopTracing(): Promise<void> {\n const provider = detachTracing();\n if (provider) {\n await flushTracerProvider(provider);\n }\n}\n","import { type Instrumentation, registerInstrumentations } from '@opentelemetry/instrumentation';\nimport {\n forgetInstrumentations,\n registeredInstrumentations,\n rememberInstrumentations,\n} from './autoInstrumentations';\nimport { takeEsmHookWarning } from './esmHookState';\nimport { registerIngestEndpoint } from './exportTarget';\nimport {\n anyFastifyInstrumentationEnabled,\n checkLifecycleSpansEnv,\n fastifyInstancesCreatedWithoutLifecycleSpans,\n lifecycleSpansEnabled,\n setLifecycleSpans,\n} from './fastifySpans';\nimport { mergePackageHttpConfig } from './httpInstrumentationConfig';\nimport { addIgnorePaths } from './ignorePaths';\nimport { isSelection, selectInstrumentations } from './instrumentationSelection';\nimport { log, setupDiag, teardownDiag } from './logging';\nimport { detachMetrics, flushMetricsProvider, startMetrics, stopMetrics } from './metrics';\nimport { resolveOptions, type StartableOptions } from './options';\nimport { shared } from './shared';\nimport { seedTelemetryStateFromEnv } from './telemetryState';\nimport { detachTracing, flushTracerProvider, startTracing, stopTracing } from './tracing';\nimport type { InstrumentationSelection, StartOptions } from './types';\n\n// Start, stop, and the one rule that governs both: an explicit `start()` always\n// wins over the `./register` auto-start.\n//\n// The winner is decided by role, not by timing. The auto-start fires on a\n// `setImmediate`, and an app that loads its token asynchronously resumes after\n// real I/O, so it loses that race every time — and losing it would silently\n// discard every option the environment cannot express (`sampleRatio`,\n// `exporter.host`, `instrumentations`, `resourceAttributes`, `logger`). So an\n// explicit call that arrives after an auto-start takes the pipelines over: the\n// auto-started providers are detached, the new ones come up in the same tick,\n// and the replaced ones flush in the background.\n\nconst state = shared('lifecycle', () => ({\n started: false,\n // The current run came from ./register rather than from app code.\n auto: false,\n // An explicit start() has been called at least once, whether or not it got\n // far enough to bring anything up. Enough to keep the auto-start from\n // stepping in behind an app that has clearly taken charge.\n explicitSeen: false,\n // Providers replaced by a takeover, still flushing. `stop()` awaits it.\n pendingFlush: undefined as Promise<void> | undefined,\n}));\n\n/**\n * Turns the pipelines on. Safe to call once config is available — the patches\n * `./register` installed record nothing until this runs, and the whole call is\n * a no-op without an access token and a service name.\n *\n * Works with no `./register` import ever having run: you get metrics and\n * exemplars with nothing monkey-patched.\n *\n * Never throws because of its own errors or a throwing `logger` option. A\n * misconfiguration that cannot be recovered from leaves telemetry off and logs\n * an error. A global diag logger the app installs itself sits outside this\n * guarantee: OpenTelemetry calls it directly.\n */\nexport function start(options: StartOptions = {}): void {\n state.explicitSeen = true;\n startPipelines(options, false);\n}\n\n/**\n * The zero-code path, called by `./register`: start from the environment alone\n * when it already holds everything needed.\n *\n * Deferred by one turn of the event loop so provider construction lands after\n * the entrypoint's module graph has loaded and been patched, and so an app that\n * calls `start()` synchronously never triggers a pointless start-then-restart.\n */\nexport function autoStartFromEnv(): void {\n if (\n !process.env.SHERLOCK_ACCESS_TOKEN?.trim() ||\n !process.env.OTEL_SERVICE_NAME?.trim() ||\n !process.env.SHERLOCK_ENDPOINT?.trim()\n ) {\n // The app is on the programmatic path. Warning about a token it is about to\n // supply itself would be noise.\n return;\n }\n const autoStart = process.env.SHERLOCK_AUTO_START?.trim().toLowerCase();\n if (autoStart === 'false' || autoStart === '0' || autoStart === 'no') {\n return;\n }\n const pending = setImmediate(() => {\n // A setImmediate callback has no caller to throw back to, so anything that\n // escapes here is an uncaughtException at boot. startPipelines has its own\n // boundary; this is the backstop for everything around it.\n try {\n if (state.started || state.explicitSeen) {\n return;\n }\n startPipelines({}, true);\n } catch (err) {\n log.error('sherlock: auto-start failed — telemetry stays off', err);\n }\n });\n // Never hold the process open just to start telemetry.\n pending.unref();\n}\n\nfunction startPipelines(options: StartOptions, auto: boolean): void {\n try {\n if (state.started && (auto || !state.auto)) {\n log.warn('sherlock: start() called twice — ignoring');\n return;\n }\n // First thing, so everything below has somewhere to log.\n setupDiag(options.logger);\n\n // `./register` cannot log when it finds the ESM hook missing or late: no\n // logger exists yet. It leaves the message here instead.\n const esmWarning = takeEsmHookWarning();\n if (esmWarning) {\n log.warn(esmWarning);\n }\n\n const resolved = resolveOptions(options);\n if (!resolved.accessToken) {\n log.warn('sherlock: no access token (SHERLOCK_ACCESS_TOKEN) — telemetry stays off');\n return;\n }\n if (!resolved.serviceName) {\n log.warn('sherlock: no service name (OTEL_SERVICE_NAME) — telemetry stays off');\n return;\n }\n if (!resolved.endpoint) {\n log.warn('sherlock: no valid endpoint (SHERLOCK_ENDPOINT) — telemetry stays off');\n return;\n }\n const startable: StartableOptions = { ...resolved, endpoint: resolved.endpoint };\n const connection = { token: resolved.accessToken, serviceName: resolved.serviceName };\n\n // Only now, with options that are known to be startable, is it safe to pull\n // down a working auto-start. Doing it any earlier would mean an explicit\n // call that turns out to have no token takes running telemetry with it.\n if (state.started) {\n log.info('sherlock: explicit start() is replacing the ./register auto-start');\n detachPipelines();\n }\n\n // Teach the outgoing-request guard about this endpoint, so our own export\n // POSTs never get instrumented.\n registerIngestEndpoint(startable.endpoint);\n addIgnorePaths(resolved.ignorePaths);\n const missedFastifyInstances = fastifyInstancesCreatedWithoutLifecycleSpans();\n if (resolved.fastifyLifecycleSpans && !lifecycleSpansEnabled() && missedFastifyInstances > 0) {\n log.warn(\n `sherlock: fastify.lifecycleSpans applies to Fastify instances created after start(); ${missedFastifyInstances} already exist without it`,\n );\n }\n if (resolved.fastifyLifecycleSpans === undefined) {\n checkLifecycleSpansEnv();\n }\n setLifecycleSpans(resolved.fastifyLifecycleSpans);\n seedTelemetryStateFromEnv();\n\n const instrumentations = applyInstrumentationOverride(resolved.instrumentations);\n if (lifecycleSpansEnabled() && !anyFastifyInstrumentationEnabled()) {\n log.warn(\n 'sherlock: fastify.lifecycleSpans is on, but the fastify instrumentation is not enabled, so there will be no lifecycle spans',\n );\n }\n\n // Order matters.\n // 1. Metrics first: registering the global MeterProvider is what lets the\n // instrument definitions resolve real instruments.\n const provider = resolved.metricsEnabled ? startMetrics(startable, connection) : undefined;\n // 2. Hand that provider to the instrumentations. They grabbed their meter at\n // process start, when no provider existed, and the OpenTelemetry metrics\n // API has no late binding — without this rebind their metrics (outbound\n // HTTP durations, runtime metrics) stay permanent no-ops. Traces don't\n // have this problem: the tracer API hands out proxies that delegate to\n // whatever provider arrives later.\n if (provider) {\n for (const instrumentation of instrumentations) {\n instrumentation.setMeterProvider(provider);\n }\n }\n // 3. Tracing last: registering the global tracer provider is what turns the\n // dormant patches on.\n if (resolved.tracingEnabled) {\n startTracing(startable, connection);\n }\n\n state.started = true;\n state.auto = auto;\n if (!provider && !resolved.tracingEnabled) {\n log.warn('sherlock: both tracing and metrics are disabled — nothing will be exported');\n }\n } catch (err) {\n // Telemetry failing is never a reason for the application to fail. The\n // realistic trigger is a misconfigured endpoint that throws inside an\n // exporter constructor after the metrics pipeline is already up, so there\n // is real state to unwind here, not just a message to log.\n log.error('sherlock: start failed — telemetry stays off', err);\n try {\n detachPipelines();\n } catch {\n // Upstream's unregister logs through a global diag logger the app\n // installed itself, which can throw. The unwind is best effort.\n }\n }\n}\n\n/**\n * Unhooks both pipelines from their globals synchronously and flushes them in\n * the background.\n *\n * Synchronous is the requirement: `start()` is a plain call, so a takeover\n * cannot await anything, and the OpenTelemetry globals refuse to be overwritten\n * while a previous registration stands. Detaching first and flushing after is\n * what lets the replacement come up in the same tick.\n */\nfunction detachPipelines(): void {\n const meterProvider = detachMetrics();\n const tracerProvider = detachTracing();\n state.started = false;\n state.auto = false;\n\n const flushes: Array<Promise<void>> = [];\n if (meterProvider) {\n flushes.push(flushMetricsProvider(meterProvider));\n }\n if (tracerProvider) {\n flushes.push(flushTracerProvider(tracerProvider));\n }\n if (flushes.length === 0) {\n return;\n }\n // Chained, not replaced: two takeovers in a row must both be awaitable from\n // stop(). Neither flush helper rejects, so this promise never does either.\n const previous = state.pendingFlush ?? Promise.resolve();\n state.pendingFlush = previous.then(async () => {\n await Promise.all(flushes);\n });\n}\n\n/**\n * Applies the `instrumentations` option, and keeps the package's http hooks\n * attached whichever form the app used.\n *\n * - Omitted keeps the bundle `./register` installed, hooks and all.\n * - `{ enabled }` / `{ disabled }` filters that bundle. Every survivor is an\n * instance `./register` built, so it already carries the hooks.\n * - An explicit list replaces the bundle: the installed one is disabled first.\n * That is clean only while the bundle has patched nothing. OpenTelemetry's\n * unwrap removes whichever wrapper is installed, not its own, and is a no-op\n * on an ES module namespace (@opentelemetry/instrumentation 0.301.2), so the\n * README says not to combine a list with `./register`. The hooks are merged into the list's own http\n * instrumentation before it is registered.\n */\nfunction applyInstrumentationOverride(\n override: Instrumentation[] | InstrumentationSelection | undefined,\n): Instrumentation[] {\n if (override === undefined) {\n return registeredInstrumentations();\n }\n if (isSelection(override)) {\n const kept = selectInstrumentations(registeredInstrumentations(), override);\n forgetInstrumentations();\n rememberInstrumentations(kept);\n return kept;\n }\n for (const installed of registeredInstrumentations()) {\n installed.disable();\n }\n forgetInstrumentations();\n if (override.length > 0) {\n mergePackageHttpConfig(override);\n registerInstrumentations({ instrumentations: override });\n }\n return override;\n}\n\n/**\n * Flushes the last metric interval and the pending span batch, then tears the\n * pipelines down. Safe to call twice, and safe to call when `start()` never\n * ran.\n */\nexport async function stop(): Promise<void> {\n // Metrics first: its shutdown runs a final flush, which must still pass\n // through the kill-switch gate in the exporter.\n await stopMetrics();\n await stopTracing();\n state.started = false;\n state.auto = false;\n // A takeover leaves the pipelines it replaced flushing in the background.\n // Waiting for them here is what makes `await stop()` mean \"nothing of ours is\n // still in flight\".\n const pending = state.pendingFlush;\n state.pendingFlush = undefined;\n await pending;\n teardownDiag();\n}\n\n/**\n * Test-only reset. `explicitSeen` survives `stop()` in production — a process\n * either has app code driving telemetry or it does not — so tests that boot\n * several times in one process need a way to forget it.\n */\nexport function resetLifecycleForTests(): void {\n state.started = false;\n state.auto = false;\n state.explicitSeen = false;\n state.pendingFlush = undefined;\n}\n","{\n \"name\": \"@sherlock-labs/node\",\n \"version\": \"0.3.0-rc.1\",\n \"private\": false,\n \"description\": \"The Sherlock Labs distribution of OpenTelemetry for Node.js — traces, metrics, and trace-linked exemplars on histograms.\",\n \"license\": \"Apache-2.0\",\n \"homepage\": \"https://github.com/sherlock-labs-dev/sherlock-node\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"git+https://github.com/sherlock-labs-dev/sherlock-node.git\"\n },\n \"engines\": {\n \"node\": \">=22.15.0\"\n },\n \"files\": [\n \"dist\",\n \"README.md\",\n \"CHANGELOG.md\",\n \"LICENSE\"\n ],\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"main\": \"./dist/index.js\",\n \"module\": \"./dist/index.mjs\",\n \"types\": \"./dist/index.d.ts\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"import\": \"./dist/index.mjs\",\n \"require\": \"./dist/index.js\"\n },\n \"./register\": {\n \"types\": \"./dist/register.d.ts\",\n \"import\": \"./dist/register.mjs\",\n \"require\": \"./dist/register.js\"\n },\n \"./koa\": {\n \"types\": \"./dist/koa.d.ts\",\n \"import\": \"./dist/koa.mjs\",\n \"require\": \"./dist/koa.js\"\n },\n \"./express\": {\n \"types\": \"./dist/express.d.ts\",\n \"import\": \"./dist/express.mjs\",\n \"require\": \"./dist/express.js\"\n },\n \"./fastify\": {\n \"types\": \"./dist/fastify.d.ts\",\n \"import\": \"./dist/fastify.mjs\",\n \"require\": \"./dist/fastify.js\"\n },\n \"./package.json\": \"./package.json\"\n },\n \"scripts\": {\n \"build\": \"rm -rf dist && tsup\",\n \"typecheck\": \"tsc --noEmit\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"test:coverage\": \"vitest run --coverage\",\n \"lint\": \"biome check .\",\n \"lint:fix\": \"biome check --write .\",\n \"format\": \"biome format --write .\",\n \"prepublishOnly\": \"npm run build\"\n },\n \"dependencies\": {\n \"@opentelemetry/auto-instrumentations-node\": \"0.83.1\",\n \"@opentelemetry/context-async-hooks\": \"3.1.1\",\n \"@opentelemetry/core\": \"3.1.1\",\n \"@opentelemetry/exporter-metrics-otlp-http\": \"0.301.2\",\n \"@opentelemetry/exporter-trace-otlp-http\": \"0.301.2\",\n \"@opentelemetry/instrumentation\": \"0.301.2\",\n \"@opentelemetry/instrumentation-http\": \"0.301.2\",\n \"@opentelemetry/otlp-exporter-base\": \"0.301.2\",\n \"@opentelemetry/otlp-transformer\": \"0.301.2\",\n \"@opentelemetry/resources\": \"3.1.1\",\n \"@opentelemetry/sdk-metrics\": \"3.1.1\",\n \"@opentelemetry/sdk-trace\": \"3.1.1\"\n },\n \"peerDependencies\": {\n \"@opentelemetry/api\": \"1.10.0\"\n },\n \"devDependencies\": {\n \"@biomejs/biome\": \"^2.6.8\",\n \"@koa/router\": \"^15.7.1\",\n \"@opentelemetry/api\": \"1.10.0\",\n \"@types/express\": \"^5.0.0\",\n \"@types/koa\": \"^3.0.0\",\n \"@types/koa__router\": \"^12.0.4\",\n \"@types/node\": \"^24.19.2\",\n \"@types/supertest\": \"^6.0.2\",\n \"cls-rtracer\": \"2.6.3\",\n \"express\": \"^5.3.0\",\n \"fastify\": \"^5.12.8\",\n \"koa\": \"^3.3.0\",\n \"supertest\": \"^7.3.2\",\n \"tsup\": \"^8.5.0\",\n \"typescript\": \"^5.9.0\",\n \"vitest\": \"^3.2.0\"\n },\n \"keywords\": [\n \"opentelemetry\",\n \"otel\",\n \"observability\",\n \"tracing\",\n \"metrics\",\n \"exemplars\",\n \"sherlock\"\n ]\n}\n","import { subscribe, unsubscribe } from 'node:diagnostics_channel';\nimport { context, diag } from '@opentelemetry/api';\nimport { getRPCMetadata, RPCType } from '@opentelemetry/core';\nimport { InstrumentationBase, type InstrumentationConfig } from '@opentelemetry/instrumentation';\nimport { version } from '../package.json';\nimport {\n addEnabledCopy,\n anyEnabledTracer,\n anyFastifyInstrumentationEnabled,\n type EnabledCopy,\n installLifecycleSpans,\n lifecycleSpansEnabled,\n noteInstanceWithoutSpans,\n rememberRequestContext,\n removeEnabledCopy,\n} from './fastifySpans';\nimport { FASTIFY_INSTRUMENTATION_NAME } from './ownInstrumentations';\n\n// instrumentation-http opens the server span below the framework, so it never\n// learns the route itself. When the response closes, it reads a route from the\n// request's RPC metadata, renames the span `GET /users/:id`, and puts\n// `http.route` on the span and the `http.server.request.duration` metric.\n\nconst CHANNEL = 'fastify.initialization';\n\nconst kRouteHookAddedByAnyCopyOfThisPackage = Symbol.for('sherlock.node.fastify.routeHook');\n\ninterface FastifyInstanceLike {\n addHook(\n name: 'onRequest',\n hook: (request: FastifyRequestLike, reply: unknown, done: () => void) => void,\n ): unknown;\n [kRouteHookAddedByAnyCopyOfThisPackage]?: true;\n}\n\ninterface FastifyRequestLike {\n /** The matched route's options; `url` is the template, `/users/:id`. */\n routeOptions?: { url?: string };\n}\n\n/**\n * Names the HTTP server span after the Fastify route template (`GET /users/:id`)\n * and puts `http.route` on the span, on `http.server.request.duration` and on\n * its exemplars. `./register` includes it as `fastify`; add it yourself only to\n * an explicit `instrumentations: [...]` list.\n *\n * It covers Fastify instances created while it is enabled. It patches nothing:\n * it listens on Fastify's `fastify.initialization` diagnostics channel and adds\n * one `onRequest` hook per instance, however many copies are enabled.\n */\nexport class FastifyInstrumentation extends InstrumentationBase<InstrumentationConfig> {\n // `declare`, not a field: InstrumentationBase calls enable() from its\n // constructor, before field initialisers run, and an initialiser would then\n // wipe the handler enable() just subscribed.\n declare private onInitialization: ((message: unknown) => void) | undefined;\n declare private enabledCopy: EnabledCopy | undefined;\n\n constructor(config: InstrumentationConfig = {}) {\n super(FASTIFY_INSTRUMENTATION_NAME, version, config);\n }\n\n protected init(): [] {\n return [];\n }\n\n override enable(): void {\n this.enabledCopy ??= { tracer: () => this.tracer };\n addEnabledCopy(this.enabledCopy);\n if (!this.onInitialization) {\n this.onInitialization = (message) => {\n // Node rethrows a subscriber's error as an uncaughtException.\n try {\n const fastify = (message as { fastify?: FastifyInstanceLike } | undefined)?.fastify;\n if (fastify) {\n addRouteHook(fastify);\n }\n } catch (err) {\n diag.warn('sherlock fastify instrumentation: could not add the route hook', err);\n }\n };\n subscribe(CHANNEL, this.onInitialization);\n }\n super.enable();\n }\n\n override disable(): void {\n if (this.enabledCopy) {\n removeEnabledCopy(this.enabledCopy);\n }\n if (this.onInitialization) {\n unsubscribe(CHANNEL, this.onInitialization);\n this.onInitialization = undefined;\n }\n super.disable();\n }\n}\n\nfunction addRouteHook(fastify: FastifyInstanceLike): void {\n if (fastify[kRouteHookAddedByAnyCopyOfThisPackage]) {\n return;\n }\n fastify[kRouteHookAddedByAnyCopyOfThisPackage] = true;\n // A hook cannot be taken off a running instance, so it asks on every request\n // whether any copy is still enabled, not only the copy that added it.\n fastify.addHook('onRequest', (request, _reply, done) => {\n if (anyFastifyInstrumentationEnabled()) {\n setRouteOnRpcMetadata(request);\n rememberRequestContext(request);\n }\n done();\n });\n if (lifecycleSpansEnabled()) {\n installLifecycleSpans(fastify, anyEnabledTracer);\n } else {\n noteInstanceWithoutSpans();\n }\n}\n\nfunction setRouteOnRpcMetadata(request: FastifyRequestLike): void {\n try {\n const route = request.routeOptions?.url;\n if (!route) {\n return;\n }\n const metadata = getRPCMetadata(context.active());\n if (metadata?.type === RPCType.HTTP) {\n metadata.route = route;\n }\n } catch {}\n}\n","import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';\nimport { registerInstrumentations } from '@opentelemetry/instrumentation';\nimport { rememberInstrumentations } from './autoInstrumentations';\nimport { FastifyInstrumentation } from './fastifyInstrumentation';\nimport { HTTP_INSTRUMENTATION_NAME, packageHttpConfig } from './httpInstrumentationConfig';\nimport { buildFullBundle } from './instrumentationSelection';\n\n// The bundle, built and enabled. Shared by both builds of `./register`:\n// register.ts (CommonJS) and register.esm.ts (ES module, which installs the\n// import-in-the-middle loader first).\nexport function installAutoInstrumentations(): void {\n // The bundle is born with the package's http hooks in its config, so the\n // zero-code path and the `{ enabled }` / `{ disabled }` filter form never have\n // to merge anything later. See httpInstrumentationConfig.ts for the rule that\n // also covers the explicit-list form.\n //\n // `buildFullBundle` hides OTEL_NODE_ENABLED_INSTRUMENTATIONS and\n // OTEL_NODE_DISABLED_INSTRUMENTATIONS from the factory, so this is the whole\n // default set. `start()` applies the narrowing, because it is the only place\n // that has seen both the env vars and the `instrumentations` option.\n const instrumentations = buildFullBundle(() => [\n ...getNodeAutoInstrumentations({\n [HTTP_INSTRUMENTATION_NAME]: packageHttpConfig(),\n }),\n new FastifyInstrumentation(),\n ]);\n\n // Remember the list so `start()` can bind the meter provider to it later. The\n // instrumentations grab their meter NOW, while no provider exists, and the\n // OpenTelemetry metrics API has no late binding — without that rebind their\n // metrics stay permanent no-ops.\n rememberInstrumentations(instrumentations);\n\n registerInstrumentations({ instrumentations });\n}\n","import { autoStartFromEnv } from './lifecycle';\nimport { installAutoInstrumentations } from './registerCore';\n\n// Auto-instrumentation registration. Import this FIRST, on line 1 of the\n// entrypoint:\n//\n// import '@sherlock-labs/node/register';\n//\n// The patches wrap libraries (http, express, koa, mongodb, ioredis, pino, …) at\n// the moment those libraries load, so this has to run before any of them does.\n// A library that loads earlier is taken un-patched and its telemetry silently\n// never appears. A file's own imports run before its body, so this must be the\n// first IMPORT, not the first statement.\n//\n// Watch this file's import graph for the same reason: everything it reaches\n// loads before the patches exist, so nothing here may touch an app library the\n// patches still have to wrap. The helpers below are state-only.\n//\n// Two measured facts about this pinned train, both on the upgrade checklist:\n// - `./index` — both exporters and both providers — loads neither `http` nor\n// `https`. They resolve lazily on the first send.\n// - `@opentelemetry/auto-instrumentations-node` DOES load both at its own\n// import. That is harmless: require-in-the-middle wraps `Module._load`, so\n// the next `require('http')` still returns a patched module. After this file\n// runs, `http.request` is the instrumentation's `outgoingRequest`.\n//\n// The patches are DORMANT — they record nothing — until the providers exist,\n// which is the auto-start at the bottom of this file, or an explicit `start()`.\n//\n// This import is optional. Skip it for metrics-only mode: call `start()` with\n// `instrumentations: []` and nothing in the process gets patched at all.\n\n// This is the CommonJS build (`require('@sherlock-labs/node/register')`,\n// `node --require`). The ES module build is register.esm.ts: an `import` or\n// `node --import` gets that one, and it also installs the ESM loader hook.\ninstallAutoInstrumentations();\n\n// The zero-code path: with the token and the service name already in the\n// environment there is nothing left for the app to tell us, so start the\n// pipelines too. It does nothing when either variable is missing, and nothing\n// when SHERLOCK_AUTO_START=false. An explicit `start()` always outranks it,\n// whenever it arrives — see lifecycle.ts.\nautoStartFromEnv();\n"]}