@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,1691 @@
1
+ import { createRequire, register } from 'module';
2
+ import { registerInstrumentations, InstrumentationBase } from '@opentelemetry/instrumentation';
3
+ import { DiagLogLevel, diag, metrics, trace, context, propagation, isSpanContextValid, SpanStatusCode } from '@opentelemetry/api';
4
+ import { format } from 'util';
5
+ import { performance } from 'perf_hooks';
6
+ import { CompositePropagator, W3CTraceContextPropagator, W3CBaggagePropagator, ExportResultCode, suppressTracing, getRPCMetadata, RPCType, hrTimeToNanoseconds, hrTime, isTracingSuppressed } from '@opentelemetry/core';
7
+ import { MeterProvider, PeriodicExportingMetricReader, AggregationType } from '@opentelemetry/sdk-metrics';
8
+ import { OTLPMetricExporterBase, AggregationTemporalityPreference } from '@opentelemetry/exporter-metrics-otlp-http';
9
+ import { getSharedConfigurationDefaults } from '@opentelemetry/otlp-exporter-base';
10
+ import { createOtlpHttpExportDelegate, httpAgentFactoryFromOptions } from '@opentelemetry/otlp-exporter-base/node-http';
11
+ import { MetricsExporterMetricsHelper, JsonMetricsSerializer } from '@opentelemetry/otlp-transformer';
12
+ import { defaultResource, detectResources, envDetector, resourceFromAttributes } from '@opentelemetry/resources';
13
+ import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';
14
+ import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
15
+ import { TracerProvider, BatchSpanProcessor, TraceIdRatioBasedSampler, ParentBasedSampler, SamplingDecision } from '@opentelemetry/sdk-trace';
16
+ import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
17
+ import { subscribe, unsubscribe } from 'diagnostics_channel';
18
+
19
+ // src/esmHook.ts
20
+
21
+ // src/shared.ts
22
+ var REGISTRY_KEY = /* @__PURE__ */ Symbol.for("@sherlock-labs/node:state:v1");
23
+ function registry() {
24
+ const holder = globalThis;
25
+ let existing = holder[REGISTRY_KEY];
26
+ if (!existing) {
27
+ existing = /* @__PURE__ */ new Map();
28
+ holder[REGISTRY_KEY] = existing;
29
+ }
30
+ return existing;
31
+ }
32
+ function shared(name, create) {
33
+ const store = registry();
34
+ const existing = store.get(name);
35
+ if (existing) {
36
+ return existing;
37
+ }
38
+ const created = create();
39
+ store.set(name, created);
40
+ return created;
41
+ }
42
+
43
+ // src/esmHookState.ts
44
+ var esmHookState = shared("esmHook", () => ({
45
+ installed: false,
46
+ problem: void 0,
47
+ warned: false
48
+ }));
49
+ var state = esmHookState;
50
+ function takeEsmHookWarning() {
51
+ if (!state.problem || state.warned) {
52
+ return void 0;
53
+ }
54
+ state.warned = true;
55
+ return `sherlock: ${state.problem}`;
56
+ }
57
+
58
+ // src/esmHook.ts
59
+ var ACK_TIMEOUT_MS = 2e3;
60
+ function installEsmHook(parentUrl) {
61
+ if (esmHookState.installed) {
62
+ return async () => {
63
+ };
64
+ }
65
+ try {
66
+ const fromHere = createRequire(parentUrl);
67
+ const instrumentationEntry = fromHere.resolve("@opentelemetry/instrumentation");
68
+ const iitm = createRequire(instrumentationEntry)("import-in-the-middle");
69
+ const channel = iitm.createAddHookMessageChannel();
70
+ register(
71
+ "@opentelemetry/instrumentation/hook.mjs",
72
+ parentUrl,
73
+ channel.registerOptions
74
+ );
75
+ esmHookState.installed = true;
76
+ return () => waitWithTimeout(channel.waitForAllMessagesAcknowledged(), ACK_TIMEOUT_MS);
77
+ } catch (err) {
78
+ esmHookState.problem = `the ESM loader hook could not be registered (${String(err)}); libraries loaded with import are not instrumented`;
79
+ return async () => {
80
+ };
81
+ }
82
+ }
83
+ async function waitWithTimeout(acknowledged2, timeoutMs = ACK_TIMEOUT_MS) {
84
+ let timer;
85
+ const timedOut = new Promise((resolve) => {
86
+ timer = setTimeout(() => resolve("timeout"), timeoutMs);
87
+ });
88
+ try {
89
+ if (await Promise.race([acknowledged2, timedOut]) === "timeout") {
90
+ esmHookState.problem = `the ESM loader hook did not acknowledge within ${timeoutMs} ms; libraries loaded with import may not be instrumented`;
91
+ }
92
+ } finally {
93
+ clearTimeout(timer);
94
+ }
95
+ }
96
+ function noteIfLate(execArgv = process.execArgv, nodeOptions = process.env.NODE_OPTIONS) {
97
+ const flags = [...execArgv, ...(nodeOptions ?? "").split(/\s+/)];
98
+ const preloaded = flags.some((f) => /^--(import|loader|experimental-loader)(=|$)/.test(f));
99
+ if (!preloaded && !esmHookState.problem) {
100
+ esmHookState.problem = "@sherlock-labs/node/register ran inside the app's ES module graph, after its static imports had loaded, so libraries those imports bring in (ioredis, pg, \u2026) are not instrumented. Start the app with `node --import @sherlock-labs/node/register <entry>`";
101
+ }
102
+ }
103
+
104
+ // src/autoInstrumentations.ts
105
+ var state2 = shared("autoInstrumentations", () => ({
106
+ list: []
107
+ }));
108
+ function rememberInstrumentations(instrumentations) {
109
+ state2.list.push(...instrumentations);
110
+ }
111
+ function registeredInstrumentations() {
112
+ return state2.list;
113
+ }
114
+ function forgetInstrumentations() {
115
+ state2.list.length = 0;
116
+ }
117
+
118
+ // src/exportTarget.ts
119
+ var state3 = shared("exportTarget", () => {
120
+ const targets = /* @__PURE__ */ new Map();
121
+ addTarget(targets, process.env.SHERLOCK_ENDPOINT);
122
+ return { targets };
123
+ });
124
+ function addTarget(targets, endpoint) {
125
+ if (!endpoint) {
126
+ return;
127
+ }
128
+ let url;
129
+ try {
130
+ url = new URL(endpoint);
131
+ } catch {
132
+ return;
133
+ }
134
+ const host = normalizeHost(url.hostname);
135
+ const port = url.port || (url.protocol === "https:" ? "443" : "80");
136
+ const ports = targets.get(host) ?? /* @__PURE__ */ new Set();
137
+ ports.add(port);
138
+ targets.set(host, ports);
139
+ }
140
+ function registerIngestEndpoint(endpoint) {
141
+ addTarget(state3.targets, endpoint);
142
+ }
143
+ function normalizeHost(raw) {
144
+ const host = raw.trim().toLowerCase();
145
+ return host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
146
+ }
147
+ function splitHostPort(raw) {
148
+ if (raw.startsWith("[")) {
149
+ const close = raw.indexOf("]");
150
+ if (close === -1) {
151
+ return { host: raw, port: void 0 };
152
+ }
153
+ const rest = raw.slice(close + 1);
154
+ return {
155
+ host: raw.slice(1, close),
156
+ port: rest.startsWith(":") ? rest.slice(1) || void 0 : void 0
157
+ };
158
+ }
159
+ const at = raw.lastIndexOf(":");
160
+ if (at === -1 || raw.indexOf(":") !== at) {
161
+ return { host: raw, port: void 0 };
162
+ }
163
+ return { host: raw.slice(0, at), port: raw.slice(at + 1) || void 0 };
164
+ }
165
+ function isIngestRequest(options) {
166
+ const raw = options.hostname ?? options.host;
167
+ if (!raw) {
168
+ return false;
169
+ }
170
+ const fromHost = splitHostPort(raw);
171
+ const ports = state3.targets.get(normalizeHost(fromHost.host));
172
+ if (!ports) {
173
+ return false;
174
+ }
175
+ const port = options.port === void 0 || options.port === null || options.port === "" ? fromHost.port : String(options.port);
176
+ if (port === void 0) {
177
+ return true;
178
+ }
179
+ return ports.has(port);
180
+ }
181
+ var LEVELS = {
182
+ none: DiagLogLevel.NONE,
183
+ error: DiagLogLevel.ERROR,
184
+ warn: DiagLogLevel.WARN,
185
+ info: DiagLogLevel.INFO,
186
+ debug: DiagLogLevel.DEBUG,
187
+ verbose: DiagLogLevel.VERBOSE,
188
+ all: DiagLogLevel.ALL
189
+ };
190
+ function resolveDiagLogLevel(raw) {
191
+ if (!raw) {
192
+ return DiagLogLevel.WARN;
193
+ }
194
+ return LEVELS[raw.trim().toLowerCase()] ?? DiagLogLevel.WARN;
195
+ }
196
+ function line(args) {
197
+ try {
198
+ return format("[otel]", ...args);
199
+ } catch {
200
+ const message = typeof args[0] === "string" ? args[0] : "diagnostic";
201
+ return `[otel] ${message} (details could not be formatted)`;
202
+ }
203
+ }
204
+ var consoleLogger = {
205
+ debug: (...args) => console.debug(...args),
206
+ info: (...args) => console.info(...args),
207
+ warn: (...args) => console.warn(...args),
208
+ error: (...args) => console.error(...args)
209
+ };
210
+ function toDiagLogger(logger) {
211
+ const sink = (level) => (...args) => {
212
+ const text = line(args);
213
+ try {
214
+ logger[level](text);
215
+ } catch {
216
+ try {
217
+ consoleLogger[level](text);
218
+ } catch {
219
+ }
220
+ }
221
+ };
222
+ return {
223
+ verbose: sink("debug"),
224
+ debug: sink("debug"),
225
+ info: sink("info"),
226
+ warn: sink("warn"),
227
+ error: sink("error")
228
+ };
229
+ }
230
+ function setupDiag(logger) {
231
+ diag.setLogger(toDiagLogger(logger ?? consoleLogger), {
232
+ logLevel: resolveDiagLogLevel(process.env.OTEL_LOG_LEVEL),
233
+ // A takeover legitimately re-registers a sink. Without this the API prints
234
+ // two stack traces about it, which read like a bug and are not one.
235
+ suppressOverrideMessage: true
236
+ });
237
+ }
238
+ function contained(write) {
239
+ try {
240
+ write();
241
+ } catch {
242
+ }
243
+ }
244
+ var log = {
245
+ debug: (message, ...args) => contained(() => diag.debug(message, ...args)),
246
+ info: (message, ...args) => contained(() => diag.info(message, ...args)),
247
+ warn: (message, ...args) => contained(() => diag.warn(message, ...args)),
248
+ error: (message, ...args) => contained(() => diag.error(message, ...args))
249
+ };
250
+
251
+ // src/telemetryState.ts
252
+ var telemetryState = shared("telemetryState", () => ({
253
+ tracesOn: true,
254
+ metricsOn: true,
255
+ // Set once the app has called setTelemetryEnabled for that pipeline. From
256
+ // then on `start()` stops re-seeding it from the environment — an explicit
257
+ // call by the app always outranks a boot-time env var.
258
+ tracesSetByApp: false,
259
+ metricsSetByApp: false
260
+ }));
261
+ function parseEnvFlag(raw) {
262
+ if (raw === void 0 || raw.trim() === "") {
263
+ return void 0;
264
+ }
265
+ const normalized = raw.trim().toLowerCase();
266
+ if (normalized === "false" || normalized === "0" || normalized === "no") {
267
+ return false;
268
+ }
269
+ if (normalized === "true" || normalized === "1" || normalized === "yes") {
270
+ return true;
271
+ }
272
+ return null;
273
+ }
274
+ function readEnvFlag(name, whenInvalid = "staying enabled") {
275
+ const value = parseEnvFlag(process.env[name]);
276
+ if (value === null) {
277
+ log.warn(
278
+ `SHERLOCK: ignoring ${name}=${JSON.stringify(process.env[name])} \u2014 expected true or false, ${whenInvalid}`
279
+ );
280
+ return void 0;
281
+ }
282
+ return value;
283
+ }
284
+ function seedTelemetryStateFromEnv() {
285
+ if (!telemetryState.tracesSetByApp) {
286
+ telemetryState.tracesOn = readEnvFlag("SHERLOCK_TRACES_ENABLED") ?? true;
287
+ }
288
+ if (!telemetryState.metricsSetByApp) {
289
+ telemetryState.metricsOn = readEnvFlag("SHERLOCK_METRICS_ENABLED") ?? true;
290
+ }
291
+ }
292
+
293
+ // src/fastifySpans.ts
294
+ var LIFECYCLE_SPANS_ENV = "SHERLOCK_FASTIFY_LIFECYCLE_SPANS";
295
+ var LIFECYCLE_HOOKS = [
296
+ "onTimeout",
297
+ "onRequest",
298
+ "preParsing",
299
+ "preValidation",
300
+ "preHandler",
301
+ "preSerialization",
302
+ "onSend",
303
+ "onResponse",
304
+ "onError",
305
+ "onRequestAbort"
306
+ ];
307
+ var isLifecycleHook = (name) => LIFECYCLE_HOOKS.includes(name);
308
+ var kLeaveUnwrapped = /* @__PURE__ */ Symbol.for("sherlock.node.fastify.leaveUnwrapped");
309
+ var FASTIFY_OWN_HOOKS = /* @__PURE__ */ new Set(["headRouteOnSendHandler"]);
310
+ var state4 = shared("fastifyLifecycleSpans", () => ({
311
+ enabled: parseEnvFlag(process.env[LIFECYCLE_SPANS_ENV]) === true,
312
+ instancesCreatedWithoutSpans: 0,
313
+ requestContexts: /* @__PURE__ */ new WeakMap()
314
+ }));
315
+ var copies = shared("fastifyInstrumentationCopies", () => ({ active: /* @__PURE__ */ new Set() }));
316
+ function addEnabledCopy(copy) {
317
+ copies.active.add(copy);
318
+ }
319
+ function removeEnabledCopy(copy) {
320
+ copies.active.delete(copy);
321
+ }
322
+ function anyFastifyInstrumentationEnabled() {
323
+ return copies.active.size > 0;
324
+ }
325
+ function anyEnabledTracer() {
326
+ for (const copy of copies.active) {
327
+ return copy.tracer();
328
+ }
329
+ return void 0;
330
+ }
331
+ function checkLifecycleSpansEnv() {
332
+ readEnvFlag(LIFECYCLE_SPANS_ENV, "leaving Fastify lifecycle spans off");
333
+ }
334
+ function lifecycleSpansEnabled() {
335
+ return state4.enabled;
336
+ }
337
+ function setLifecycleSpans(enabled) {
338
+ if (enabled !== void 0) {
339
+ state4.enabled = enabled;
340
+ }
341
+ }
342
+ function fastifyInstancesCreatedWithoutLifecycleSpans() {
343
+ return state4.instancesCreatedWithoutSpans;
344
+ }
345
+ function noteInstanceWithoutSpans() {
346
+ state4.instancesCreatedWithoutSpans++;
347
+ }
348
+ function rememberRequestContext(request) {
349
+ if (state4.enabled) {
350
+ state4.requestContexts.set(request, context.active());
351
+ }
352
+ }
353
+ function installLifecycleSpans(fastify, tracer) {
354
+ const addHook = fastify.addHook;
355
+ fastify.addHook = function addHookWithSpans(name, fn) {
356
+ const wrapped = isLifecycleHook(name) ? wrapFn(fn, tracer, name, void 0) : fn;
357
+ return addHook.call(this, name, wrapped);
358
+ };
359
+ addHook.call(fastify, "onRoute", (routeOptions) => {
360
+ const route = routeOptions.url;
361
+ for (const hook of LIFECYCLE_HOOKS) {
362
+ const value = routeOptions[hook];
363
+ if (value === void 0) {
364
+ continue;
365
+ }
366
+ routeOptions[hook] = Array.isArray(value) ? value.map((fn) => wrapFn(fn, tracer, hook, route)) : wrapFn(value, tracer, hook, route);
367
+ }
368
+ routeOptions.handler = wrapFn(routeOptions.handler, tracer, "handler", route);
369
+ });
370
+ }
371
+ function wrapFn(fn, tracer, kind, route) {
372
+ if (typeof fn !== "function" || fn[kLeaveUnwrapped] || FASTIFY_OWN_HOOKS.has(fn.name)) {
373
+ return fn;
374
+ }
375
+ const original = fn;
376
+ const run = function(args) {
377
+ const active = state4.enabled ? tracer() : void 0;
378
+ const started = active ? startSpan(active, original, args, kind, route) : void 0;
379
+ return started ? runInSpan(this, original, args, kind, started) : original.apply(this, args);
380
+ };
381
+ const wrapper = original.constructor.name === "AsyncFunction" ? async function(...args) {
382
+ return run.call(this, args);
383
+ } : function(...args) {
384
+ return run.call(this, args);
385
+ };
386
+ Object.defineProperty(wrapper, "length", { value: original.length });
387
+ Object.defineProperty(wrapper, "name", { value: original.name });
388
+ return wrapper;
389
+ }
390
+ function startSpan(tracer, original, args, kind, route) {
391
+ try {
392
+ const request = args.find(isRequest);
393
+ const parent = (request && state4.requestContexts.get(request)) ?? context.active();
394
+ if (!trace.getSpan(parent)) {
395
+ return void 0;
396
+ }
397
+ const httpRoute = route ?? request?.routeOptions?.url;
398
+ const name = kind === "handler" ? `handler - ${httpRoute ?? "unknown"}` : `${kind} - ${original.name || "anonymous"}`;
399
+ const span = tracer.startSpan(
400
+ name,
401
+ {
402
+ attributes: {
403
+ "fastify.type": kind === "handler" ? "handler" : "hook",
404
+ ...kind === "handler" ? {} : { "fastify.hook": kind },
405
+ ...httpRoute ? { "http.route": httpRoute } : {}
406
+ }
407
+ },
408
+ parent
409
+ );
410
+ return { span, parent };
411
+ } catch {
412
+ return void 0;
413
+ }
414
+ }
415
+ function runInSpan(self, original, args, kind, { span, parent }) {
416
+ let ended = false;
417
+ const end = (err) => {
418
+ if (ended) {
419
+ return;
420
+ }
421
+ ended = true;
422
+ try {
423
+ if (err) {
424
+ recordError(span, err);
425
+ }
426
+ span.end();
427
+ } catch {
428
+ }
429
+ };
430
+ const last = args.length - 1;
431
+ const done = typeof args[last] === "function" && kind !== "handler" ? args[last] : void 0;
432
+ const entryContext = context.active();
433
+ const callArgs = done ? [
434
+ ...args.slice(0, last),
435
+ function(err, ...rest) {
436
+ end(err);
437
+ return context.with(entryContext, () => done.call(this, err, ...rest));
438
+ }
439
+ ] : args;
440
+ return context.with(trace.setSpan(parent, span), () => {
441
+ let result;
442
+ try {
443
+ result = original.apply(self, callArgs);
444
+ } catch (err) {
445
+ end(err);
446
+ throw err;
447
+ }
448
+ if (isThenable(result)) {
449
+ try {
450
+ result.then(
451
+ () => end(),
452
+ (err) => end(err)
453
+ );
454
+ } catch {
455
+ end();
456
+ }
457
+ return result;
458
+ }
459
+ if (kind === "handler" && result === void 0) {
460
+ endWhenReplied(args[1], end);
461
+ } else if (!done) {
462
+ end();
463
+ }
464
+ return result;
465
+ });
466
+ }
467
+ function endWhenReplied(reply, end) {
468
+ if (!isReply(reply) || reply.sent !== false) {
469
+ end();
470
+ return;
471
+ }
472
+ try {
473
+ reply.raw.once("finish", end);
474
+ reply.raw.once("close", end);
475
+ } catch {
476
+ end();
477
+ }
478
+ }
479
+ function recordError(span, err) {
480
+ if (err instanceof Error) {
481
+ span.recordException(err);
482
+ }
483
+ const status = err?.statusCode ?? err?.status;
484
+ if (typeof status === "number" && status < 500) {
485
+ return;
486
+ }
487
+ span.setStatus({
488
+ code: SpanStatusCode.ERROR,
489
+ message: err instanceof Error ? err.message : String(err)
490
+ });
491
+ }
492
+ function isRequest(value) {
493
+ return typeof value === "object" && value !== null && "routeOptions" in value && "raw" in value;
494
+ }
495
+ function isReply(value) {
496
+ return typeof value === "object" && value !== null && "sent" in value && "raw" in value;
497
+ }
498
+ function isThenable(value) {
499
+ return typeof value?.then === "function";
500
+ }
501
+ var DEFAULT_MAX_SERIES_KEYS = 5e3;
502
+ var DEFAULT_MAX_KEYS_PER_METRIC = 1e3;
503
+ var DRIFT_WARN_THROTTLE_MS = 5 * 6e4;
504
+ var MAX_MISSED_INJECTS = 2;
505
+ var TRACE_FLAGS_ATTR = "trace_flags";
506
+ function exemplarTraceFrom(spanContext) {
507
+ if (!spanContext || !isSpanContextValid(spanContext)) {
508
+ return void 0;
509
+ }
510
+ return {
511
+ traceId: spanContext.traceId,
512
+ spanId: spanContext.spanId,
513
+ // The trace-flags byte as two lowercase hex digits, e.g. 1 → "01".
514
+ traceFlags: (spanContext.traceFlags & 255).toString(16).padStart(2, "0")
515
+ };
516
+ }
517
+ var ExemplarReservoirStore = class {
518
+ seriesMap = /* @__PURE__ */ new Map();
519
+ keysPerMetric = /* @__PURE__ */ new Map();
520
+ lastDriftWarnAt = 0;
521
+ reservoirSize;
522
+ driftWatchMetricNames;
523
+ maxSeriesKeys;
524
+ maxKeysPerMetric;
525
+ onDrift;
526
+ constructor(options = {}) {
527
+ this.reservoirSize = options.reservoirSize ?? 5;
528
+ this.driftWatchMetricNames = new Set(options.driftWatchMetricNames ?? []);
529
+ this.maxSeriesKeys = options.maxSeriesKeys ?? DEFAULT_MAX_SERIES_KEYS;
530
+ this.maxKeysPerMetric = options.maxKeysPerMetric ?? DEFAULT_MAX_KEYS_PER_METRIC;
531
+ this.onDrift = options.onDrift;
532
+ }
533
+ record(metricName, primaryAttrs, value, filteredAttrs, boundaries = [], trace4) {
534
+ if (Object.keys(filteredAttrs).length === 0 && !trace4) {
535
+ return;
536
+ }
537
+ const key = makeKey(metricName, primaryAttrs);
538
+ let series = this.seriesMap.get(key);
539
+ if (!series) {
540
+ const metricKeys = this.keysPerMetric.get(metricName) ?? 0;
541
+ if (this.seriesMap.size >= this.maxSeriesKeys || metricKeys >= this.maxKeysPerMetric) {
542
+ return;
543
+ }
544
+ series = { metricName, buckets: /* @__PURE__ */ new Map(), missedInjects: 0 };
545
+ this.seriesMap.set(key, series);
546
+ this.keysPerMetric.set(metricName, metricKeys + 1);
547
+ }
548
+ const bucket = bucketIndex(value, boundaries);
549
+ let reservoir = series.buckets.get(bucket);
550
+ if (!reservoir) {
551
+ reservoir = { exemplars: [], seen: 0 };
552
+ series.buckets.set(bucket, reservoir);
553
+ }
554
+ const exemplar = {
555
+ value,
556
+ timeUnixNano: String(hrTimeToNanoseconds(hrTime())),
557
+ // trace_flags rides in filteredAttributes because the OTLP exemplar has
558
+ // no field for it — only traceId and spanId. The app's own keys win, so a
559
+ // caller that already stamps one keeps its value.
560
+ filteredAttributes: trace4 ? { [TRACE_FLAGS_ATTR]: trace4.traceFlags, ...filteredAttrs } : filteredAttrs,
561
+ trace: trace4
562
+ };
563
+ reservoir.seen += 1;
564
+ if (reservoir.exemplars.length < this.reservoirSize) {
565
+ reservoir.exemplars.push(exemplar);
566
+ } else {
567
+ const idx = Math.floor(Math.random() * reservoir.seen);
568
+ if (idx < this.reservoirSize) {
569
+ reservoir.exemplars[idx] = exemplar;
570
+ }
571
+ }
572
+ }
573
+ // Merges our exemplars into the SDK's histogram payload at export time. The
574
+ // SDK serializes data points with bucket counts and no exemplars (the JS SDK
575
+ // cannot attach any); we keep our reservoirs separate from its aggregation so
576
+ // we can sample per bucket, which is what stops the slow-tail requests being
577
+ // crowded out by the dense fast buckets.
578
+ //
579
+ // This walks the payload, matches each histogram data point back to its series
580
+ // by re-keying the data point's attributes, flattens that series' buckets into
581
+ // one exemplar list, and splices it onto `dp.exemplars`. Matched series are
582
+ // then drained.
583
+ inject(payload) {
584
+ for (const rm of payload.resourceMetrics ?? []) {
585
+ for (const sm of rm.scopeMetrics ?? []) {
586
+ for (const m of sm.metrics ?? []) {
587
+ if (!m.histogram) {
588
+ continue;
589
+ }
590
+ for (const dp of m.histogram.dataPoints ?? []) {
591
+ const attrs = decodeKeyValueList(dp.attributes);
592
+ const key = makeKey(m.name, attrs);
593
+ const series = this.seriesMap.get(key);
594
+ if (!series) {
595
+ continue;
596
+ }
597
+ const exemplars = [];
598
+ for (const reservoir of series.buckets.values()) {
599
+ exemplars.push(...reservoir.exemplars);
600
+ }
601
+ if (exemplars.length === 0) {
602
+ continue;
603
+ }
604
+ dp.exemplars = exemplars.map((exemplar) => ({
605
+ timeUnixNano: exemplar.timeUnixNano,
606
+ asDouble: exemplar.value,
607
+ // traceId/spanId are top-level exemplar fields on the wire —
608
+ // that link is what turns a chart spike into an open-the-trace
609
+ // button, so they must not go into filteredAttributes.
610
+ traceId: exemplar.trace?.traceId,
611
+ spanId: exemplar.trace?.spanId,
612
+ filteredAttributes: Object.entries(exemplar.filteredAttributes).map(([k, v]) => ({
613
+ key: k,
614
+ value: { stringValue: v }
615
+ }))
616
+ }));
617
+ this.deleteSeries(key);
618
+ }
619
+ }
620
+ }
621
+ }
622
+ const staleKeys = [];
623
+ for (const [key, series] of this.seriesMap) {
624
+ series.missedInjects += 1;
625
+ if (series.missedInjects >= MAX_MISSED_INJECTS) {
626
+ staleKeys.push(key);
627
+ }
628
+ }
629
+ this.warnOnDrift();
630
+ for (const key of staleKeys) {
631
+ this.deleteSeries(key);
632
+ }
633
+ }
634
+ // Drop every buffered exemplar. Used by the metrics kill switch: while exports
635
+ // are dropped nothing drains the reservoirs, so exemplars recorded before the
636
+ // flip would otherwise be spliced, hours stale, into the first export after
637
+ // re-enable.
638
+ clear() {
639
+ this.seriesMap.clear();
640
+ this.keysPerMetric.clear();
641
+ }
642
+ /** Number of live series. Used by tests and by the kill-switch assertions. */
643
+ get size() {
644
+ return this.seriesMap.size;
645
+ }
646
+ deleteSeries(key) {
647
+ const series = this.seriesMap.get(key);
648
+ if (!series) {
649
+ return;
650
+ }
651
+ this.seriesMap.delete(key);
652
+ const metricKeys = this.keysPerMetric.get(series.metricName) ?? 0;
653
+ if (metricKeys <= 1) {
654
+ this.keysPerMetric.delete(series.metricName);
655
+ } else {
656
+ this.keysPerMetric.set(series.metricName, metricKeys - 1);
657
+ }
658
+ }
659
+ // The drift guard: a leftover series for a watched metric means an exemplar
660
+ // matched no data point in the export, so the hand-mirrored attribute lists in
661
+ // httpExemplars.ts have likely drifted from what the instrumentation records.
662
+ // Without this warning that failure mode is invisible — charts stay normal and
663
+ // exemplars just stop appearing.
664
+ warnOnDrift() {
665
+ if (this.driftWatchMetricNames.size === 0) {
666
+ return;
667
+ }
668
+ const unmatched = /* @__PURE__ */ new Set();
669
+ for (const series of this.seriesMap.values()) {
670
+ if (this.driftWatchMetricNames.has(series.metricName) && series.missedInjects >= MAX_MISSED_INJECTS) {
671
+ unmatched.add(series.metricName);
672
+ }
673
+ }
674
+ if (unmatched.size === 0) {
675
+ return;
676
+ }
677
+ this.onDrift?.([...unmatched]);
678
+ const now = Date.now();
679
+ if (now - this.lastDriftWarnAt < DRIFT_WARN_THROTTLE_MS) {
680
+ return;
681
+ }
682
+ this.lastDriftWarnAt = now;
683
+ diag.warn(
684
+ `exemplars recorded for ${[...unmatched].join(", ")} matched no histogram data point \u2014 the mirrored attribute keys in httpExemplars.ts may have drifted from what @opentelemetry/instrumentation-http records (check after upgrades)`
685
+ );
686
+ }
687
+ };
688
+ function bucketIndex(value, boundaries) {
689
+ for (let i = 0; i < boundaries.length; i++) {
690
+ if (value <= boundaries[i]) {
691
+ return i;
692
+ }
693
+ }
694
+ return boundaries.length;
695
+ }
696
+ function makeKey(metricName, attrs) {
697
+ const parts = [];
698
+ for (const k of Object.keys(attrs).sort()) {
699
+ const v = attrs[k];
700
+ if (v === void 0) {
701
+ continue;
702
+ }
703
+ parts.push(`${k}=${String(v)}`);
704
+ }
705
+ return `${metricName} ${parts.join("|")}`;
706
+ }
707
+ function decodeKeyValueList(kvs) {
708
+ const out = {};
709
+ for (const kv of kvs ?? []) {
710
+ const v = kv.value;
711
+ if (v == null) {
712
+ continue;
713
+ }
714
+ if (typeof v.stringValue === "string") {
715
+ out[kv.key] = v.stringValue;
716
+ } else if (typeof v.intValue === "number" || typeof v.intValue === "string") {
717
+ out[kv.key] = Number(v.intValue);
718
+ } else if (typeof v.doubleValue === "number") {
719
+ out[kv.key] = v.doubleValue;
720
+ } else if (typeof v.boolValue === "boolean") {
721
+ out[kv.key] = v.boolValue;
722
+ }
723
+ }
724
+ return out;
725
+ }
726
+
727
+ // src/httpBoundaries.ts
728
+ var DEFAULT_DURATION_BOUNDARIES_S = Object.freeze([
729
+ 5e-3,
730
+ 0.01,
731
+ 0.025,
732
+ 0.05,
733
+ 0.075,
734
+ 0.1,
735
+ 0.15,
736
+ 0.2,
737
+ 0.25,
738
+ 0.3,
739
+ 0.35,
740
+ 0.4,
741
+ 0.45,
742
+ 0.5,
743
+ 0.75,
744
+ 1,
745
+ 2.5,
746
+ 5,
747
+ 7.5,
748
+ 10
749
+ ]);
750
+ var state5 = shared("httpBoundaries", () => ({
751
+ list: [...DEFAULT_DURATION_BOUNDARIES_S]
752
+ }));
753
+ function httpDurationBoundaries() {
754
+ return state5.list;
755
+ }
756
+ function setHttpDurationBoundaries(boundaries) {
757
+ if (!boundaries || boundaries.length === 0) {
758
+ return;
759
+ }
760
+ state5.list.length = 0;
761
+ state5.list.push(...[...boundaries].sort((a, b) => a - b));
762
+ }
763
+
764
+ // src/httpExemplars.ts
765
+ var state6 = shared("httpExemplars", () => ({
766
+ exporter: void 0,
767
+ // performance.now() at request start, keyed by the per-request span (the
768
+ // same Span instance flows through both hooks).
769
+ startBySpan: /* @__PURE__ */ new WeakMap()
770
+ }));
771
+ function setAutoHttpExemplarExporter(exporter) {
772
+ state6.exporter = exporter;
773
+ }
774
+ var SERVER_METRIC = "http.server.request.duration";
775
+ var CLIENT_METRIC = "http.client.request.duration";
776
+ var AUTO_HTTP_METRICS = [SERVER_METRIC, CLIENT_METRIC];
777
+ var SERVER_KEYS = [
778
+ "http.request.method",
779
+ "url.scheme",
780
+ "network.protocol.version",
781
+ "http.route",
782
+ "http.response.status_code",
783
+ "error.type"
784
+ ];
785
+ var CLIENT_KEYS = [
786
+ "http.request.method",
787
+ "server.address",
788
+ "server.port",
789
+ "http.response.status_code",
790
+ "network.protocol.version",
791
+ "error.type"
792
+ ];
793
+ function onHttpRequestStart(span, request) {
794
+ if (!state6.exporter) {
795
+ return;
796
+ }
797
+ state6.startBySpan.set(span, performance.now());
798
+ if (isClientRequest(request)) {
799
+ request.on("close", () => {
800
+ if (request.aborted) {
801
+ return;
802
+ }
803
+ queueMicrotask(() => {
804
+ recordAutoHttpExemplar(span, CLIENT_METRIC, CLIENT_KEYS);
805
+ });
806
+ });
807
+ }
808
+ }
809
+ function onHttpResponse(span, response) {
810
+ if (!state6.exporter) {
811
+ return;
812
+ }
813
+ if (isServerResponse(response)) {
814
+ response.on("close", () => {
815
+ queueMicrotask(() => {
816
+ recordAutoHttpExemplar(span, SERVER_METRIC, SERVER_KEYS);
817
+ });
818
+ });
819
+ }
820
+ }
821
+ function isClientRequest(request) {
822
+ return typeof request.getHeader === "function";
823
+ }
824
+ function isServerResponse(response) {
825
+ return typeof response.writeHead === "function";
826
+ }
827
+ function recordAutoHttpExemplar(span, metric, keys) {
828
+ try {
829
+ const exporter = state6.exporter;
830
+ if (!exporter) {
831
+ return;
832
+ }
833
+ const start = state6.startBySpan.get(span);
834
+ if (start === void 0) {
835
+ return;
836
+ }
837
+ const attrs = span.attributes ?? {};
838
+ if (Object.keys(attrs).length === 0) {
839
+ return;
840
+ }
841
+ const picked = pick(attrs, keys);
842
+ if (picked["error.type"] === void 0) {
843
+ const status = attrs["http.response.status_code"];
844
+ const errorFloor = metric === SERVER_METRIC ? 500 : 400;
845
+ if (typeof status === "number" && status >= errorFloor && status < 600) {
846
+ picked["error.type"] = String(status);
847
+ }
848
+ }
849
+ const valueSeconds = (performance.now() - start) / 1e3;
850
+ exporter.recordExemplar(
851
+ metric,
852
+ picked,
853
+ valueSeconds,
854
+ // No attributes of our own. The store adds `trace_flags` from the trace
855
+ // below, and an app that wants more keys on an HTTP exemplar records its
856
+ // own histogram with recordWithExemplar.
857
+ {},
858
+ httpDurationBoundaries(),
859
+ // The HTTP request span IS the link target. A span that reaches here is
860
+ // always sampled, so these trace_flags are always "01".
861
+ exemplarTraceFrom(span.spanContext())
862
+ );
863
+ } catch (err) {
864
+ diag.warn(`sherlock: auto-HTTP exemplar for ${metric} failed`, err);
865
+ }
866
+ }
867
+ function pick(attrs, keys) {
868
+ const out = {};
869
+ for (const key of keys) {
870
+ const value = attrs[key];
871
+ if (value !== void 0) {
872
+ out[key] = value;
873
+ }
874
+ }
875
+ return out;
876
+ }
877
+
878
+ // src/ignorePaths.ts
879
+ var DEFAULT_IGNORE_PATHS = ["/healthz", "/livez", "/healthcheck"];
880
+ var state7 = shared("ignorePaths", () => ({
881
+ paths: /* @__PURE__ */ new Set([...DEFAULT_IGNORE_PATHS, ...readEnvPaths()])
882
+ }));
883
+ function readEnvPaths() {
884
+ return (process.env.SHERLOCK_IGNORE_PATHS ?? "").split(",").map((path) => path.trim()).filter((path) => path.length > 0);
885
+ }
886
+ function addIgnorePaths(paths) {
887
+ for (const path of paths ?? []) {
888
+ if (path.trim()) {
889
+ state7.paths.add(path.trim());
890
+ }
891
+ }
892
+ }
893
+ function isIgnoredPath(url) {
894
+ if (!url) {
895
+ return false;
896
+ }
897
+ const queryAt = url.indexOf("?");
898
+ const path = queryAt === -1 ? url : url.slice(0, queryAt);
899
+ return state7.paths.has(path);
900
+ }
901
+
902
+ // src/httpInstrumentationConfig.ts
903
+ var HTTP_INSTRUMENTATION_NAME = "@opentelemetry/instrumentation-http";
904
+ function packageHttpConfig() {
905
+ return {
906
+ // Health and liveness probes are pure noise as spans — the same path, every
907
+ // few seconds, per pod, forever. Extend the list with SHERLOCK_IGNORE_PATHS
908
+ // or `start({ ignorePaths })`; the set is read per request, so a later
909
+ // addition still takes effect.
910
+ ignoreIncomingRequestHook: (request) => isIgnoredPath(request.url),
911
+ // The distribution never traces or meters its own export path. Returning
912
+ // true here returns before the span AND before the
913
+ // http.client.request.duration record (verified against
914
+ // instrumentation-http 0.301.2), which is what stops the self-metric —
915
+ // suppressTracing alone would only stop the span.
916
+ ignoreOutgoingRequestHook: (options) => isIngestRequest(options),
917
+ // Exemplars for the auto-instrumented HTTP histograms: the hooks time each
918
+ // request and record an exemplar next to the histogram point the
919
+ // instrumentation emits (see httpExemplars.ts). Inert until `start()` hands
920
+ // them the exporter.
921
+ requestHook: onHttpRequestStart,
922
+ responseHook: onHttpResponse
923
+ };
924
+ }
925
+ function mergePackageHttpConfig(instrumentations) {
926
+ const target = instrumentations.find(
927
+ (instrumentation) => instrumentation.instrumentationName === HTTP_INSTRUMENTATION_NAME
928
+ );
929
+ if (!target) {
930
+ log.debug(
931
+ "sherlock: the instrumentation list has no http instrumentation \u2014 the self-export guard, the ignored paths and the auto-HTTP exemplars are off"
932
+ );
933
+ return;
934
+ }
935
+ const app = target.getConfig();
936
+ const ours = packageHttpConfig();
937
+ target.setConfig({
938
+ ...app,
939
+ ignoreIncomingRequestHook: (request) => safeIgnore(() => app.ignoreIncomingRequestHook?.(request)) || (ours.ignoreIncomingRequestHook?.(request) ?? false),
940
+ ignoreOutgoingRequestHook: (options) => safeIgnore(() => app.ignoreOutgoingRequestHook?.(options)) || (ours.ignoreOutgoingRequestHook?.(options) ?? false),
941
+ requestHook: (span, request) => {
942
+ safeHook(() => app.requestHook?.(span, request));
943
+ ours.requestHook?.(span, request);
944
+ },
945
+ responseHook: (span, response) => {
946
+ safeHook(() => app.responseHook?.(span, response));
947
+ ours.responseHook?.(span, response);
948
+ }
949
+ });
950
+ }
951
+ function safeIgnore(hook) {
952
+ try {
953
+ return hook() === true;
954
+ } catch (err) {
955
+ log.warn("sherlock: an app http ignore hook threw \u2014 treating the request as not ignored", err);
956
+ return false;
957
+ }
958
+ }
959
+ function safeHook(hook) {
960
+ try {
961
+ hook();
962
+ } catch (err) {
963
+ log.warn("sherlock: an app http hook threw", err);
964
+ }
965
+ }
966
+
967
+ // src/ownInstrumentations.ts
968
+ var FASTIFY_INSTRUMENTATION_NAME = "@sherlock-labs/node/fastify";
969
+
970
+ // src/instrumentationSelection.ts
971
+ var PACKAGE_PREFIX = "@opentelemetry/instrumentation-";
972
+ var OWN_INSTRUMENTATIONS = {
973
+ fastify: FASTIFY_INSTRUMENTATION_NAME
974
+ };
975
+ var ENABLED_ENV = "OTEL_NODE_ENABLED_INSTRUMENTATIONS";
976
+ var DISABLED_ENV = "OTEL_NODE_DISABLED_INSTRUMENTATIONS";
977
+ function isSelection(override) {
978
+ return !Array.isArray(override);
979
+ }
980
+ function buildFullBundle(build) {
981
+ const saved = {
982
+ [ENABLED_ENV]: process.env[ENABLED_ENV],
983
+ [DISABLED_ENV]: process.env[DISABLED_ENV]
984
+ };
985
+ delete process.env[ENABLED_ENV];
986
+ delete process.env[DISABLED_ENV];
987
+ try {
988
+ return build();
989
+ } finally {
990
+ for (const [name, value] of Object.entries(saved)) {
991
+ if (value === void 0) {
992
+ delete process.env[name];
993
+ } else {
994
+ process.env[name] = value;
995
+ }
996
+ }
997
+ }
998
+ }
999
+ function selectionFromEnv() {
1000
+ const enabled = splitEnv(ENABLED_ENV);
1001
+ const disabled = splitEnv(DISABLED_ENV);
1002
+ if (!enabled && !disabled) {
1003
+ return void 0;
1004
+ }
1005
+ return { enabled, disabled };
1006
+ }
1007
+ function splitEnv(name) {
1008
+ const raw = process.env[name];
1009
+ if (raw === void 0) {
1010
+ return void 0;
1011
+ }
1012
+ return raw.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0);
1013
+ }
1014
+ function packageName(name) {
1015
+ const short = name.trim();
1016
+ return OWN_INSTRUMENTATIONS[short] ?? `${PACKAGE_PREFIX}${short}`;
1017
+ }
1018
+ function shortName(name) {
1019
+ const own = Object.entries(OWN_INSTRUMENTATIONS).find(([, full]) => full === name);
1020
+ if (own) {
1021
+ return own[0];
1022
+ }
1023
+ return name.startsWith(PACKAGE_PREFIX) ? name.slice(PACKAGE_PREFIX.length) : name;
1024
+ }
1025
+ function selectInstrumentations(bundle, selection) {
1026
+ const enabled = selection.enabled?.map(packageName);
1027
+ const disabled = new Set(selection.disabled?.map(packageName));
1028
+ if (!enabled && disabled.size === 0) {
1029
+ log.warn("sherlock: instrumentations needs `enabled` or `disabled` \u2014 keeping the whole bundle");
1030
+ return bundle;
1031
+ }
1032
+ if (bundle.length === 0) {
1033
+ log.warn(
1034
+ "sherlock: instrumentations `enabled`/`disabled` filters the bundle `./register` installs, and nothing is installed \u2014 no auto-instrumentation"
1035
+ );
1036
+ return bundle;
1037
+ }
1038
+ const wanted = new Set(enabled);
1039
+ warnAboutUnknownNames([...wanted, ...disabled], bundle);
1040
+ const kept = [];
1041
+ for (const instrumentation of bundle) {
1042
+ const name = instrumentation.instrumentationName;
1043
+ if ((!enabled || wanted.has(name)) && !disabled.has(name)) {
1044
+ kept.push(instrumentation);
1045
+ } else {
1046
+ instrumentation.disable();
1047
+ }
1048
+ }
1049
+ return kept;
1050
+ }
1051
+ function warnAboutUnknownNames(wanted, bundle) {
1052
+ const present = new Set(bundle.map((instrumentation) => instrumentation.instrumentationName));
1053
+ for (const name of wanted) {
1054
+ if (!present.has(name)) {
1055
+ log.warn(
1056
+ `sherlock: instrumentation ${JSON.stringify(shortName(name))} is not in the bundle \u2014 check the spelling`
1057
+ );
1058
+ }
1059
+ }
1060
+ }
1061
+ var state8 = shared("exportProbe", () => ({
1062
+ lastSuppressed: void 0
1063
+ }));
1064
+ function probeExportContext() {
1065
+ state8.lastSuppressed = isTracingSuppressed(context.active());
1066
+ }
1067
+
1068
+ // src/exemplarExporter.ts
1069
+ var DEFAULT_RESERVOIR_SIZE = 5;
1070
+ var ExemplarExporter = class extends OTLPMetricExporterBase {
1071
+ /** The buffered exemplars. Internal; read by tests and by the kill switch. */
1072
+ store;
1073
+ constructor(opts) {
1074
+ const store = new ExemplarReservoirStore({
1075
+ reservoirSize: opts.reservoirSize ?? DEFAULT_RESERVOIR_SIZE,
1076
+ driftWatchMetricNames: opts.driftWatchMetricNames
1077
+ });
1078
+ const serializer = {
1079
+ serializeRequest: (req) => {
1080
+ const bytes = JsonMetricsSerializer.serializeRequest(req);
1081
+ if (!bytes) {
1082
+ return bytes;
1083
+ }
1084
+ const payload = JSON.parse(new TextDecoder().decode(bytes));
1085
+ store.inject(payload);
1086
+ return new TextEncoder().encode(JSON.stringify(payload));
1087
+ },
1088
+ deserializeResponse: (data) => JsonMetricsSerializer.deserializeResponse(data)
1089
+ };
1090
+ const staticHeaders = {
1091
+ "Content-Type": "application/json",
1092
+ ...opts.headers
1093
+ };
1094
+ if (opts.host) {
1095
+ staticHeaders.Host = opts.host;
1096
+ }
1097
+ super(
1098
+ createOtlpHttpExportDelegate(
1099
+ {
1100
+ ...getSharedConfigurationDefaults(),
1101
+ // Caller passes the full endpoint incl. /v1/metrics; used as-is.
1102
+ url: opts.url,
1103
+ headers: () => {
1104
+ probeExportContext();
1105
+ return Promise.resolve(staticHeaders);
1106
+ },
1107
+ agentFactory: httpAgentFactoryFromOptions({ keepAlive: true })
1108
+ },
1109
+ serializer,
1110
+ // The three args below feed the delegate's otel.sdk.exporter.* self
1111
+ // metrics. The component type mirrors the stock OTLPMetricExporter,
1112
+ // whose constant is package-internal. The meter provider is undefined on
1113
+ // purpose: ExporterMetrics does `meterProvider ? getMeter(...) :
1114
+ // createNoopMeter()`, so undefined means noop rather than a fallback to
1115
+ // the global meter provider — which is ours, i.e. an export loop.
1116
+ "otlp_http_metric_exporter",
1117
+ MetricsExporterMetricsHelper,
1118
+ void 0
1119
+ ),
1120
+ // Sherlock's aggregation assumes delta; cumulative inflates counts on
1121
+ // every export. Not a tunable.
1122
+ { temporalityPreference: AggregationTemporalityPreference.DELTA }
1123
+ );
1124
+ this.store = store;
1125
+ }
1126
+ // Two jobs here.
1127
+ //
1128
+ // 1. The metrics kill switch. Gating at export rather than at record time is
1129
+ // what covers BOTH metric families: our own instruments and the SDK-owned
1130
+ // auto-instrumented histograms all leave through this one exporter.
1131
+ // Dropping a batch is safe because temporality is DELTA — a dropped
1132
+ // interval is a gap in the chart, not a double count on the next export.
1133
+ // 2. Suppressing tracing for the export itself, so the POST that ships
1134
+ // telemetry never becomes telemetry. `suppressTracing` is what
1135
+ // `Tracer.startSpan` checks.
1136
+ export(metrics3, resultCallback) {
1137
+ if (!telemetryState.metricsOn) {
1138
+ this.store.clear();
1139
+ resultCallback({ code: ExportResultCode.SUCCESS });
1140
+ return;
1141
+ }
1142
+ context.with(suppressTracing(context.active()), () => {
1143
+ super.export(metrics3, resultCallback);
1144
+ });
1145
+ }
1146
+ // Record an exemplar for a histogram observation, from the same site that
1147
+ // calls `histogram.record(value, primaryAttrs)`.
1148
+ // - primaryAttrs: the metric's aggregation labels, which match the exemplar to
1149
+ // its data point at export time.
1150
+ // - filteredAttrs: per-observation, high-cardinality keys the app owns.
1151
+ // - boundaries: the histogram's explicit bucket boundaries, so the exemplar
1152
+ // competes only within its own bucket. Pass the same array the instrument
1153
+ // was created with.
1154
+ // - trace: the trace context active at record time, exported as the exemplar's
1155
+ // top-level traceId/spanId plus a `trace_flags` filteredAttribute.
1156
+ recordExemplar(metricName, primaryAttrs, value, filteredAttrs, boundaries, trace4) {
1157
+ if (!telemetryState.metricsOn) {
1158
+ return;
1159
+ }
1160
+ this.store.record(metricName, primaryAttrs, value, filteredAttrs, boundaries, trace4);
1161
+ }
1162
+ };
1163
+ var state9 = shared("instruments", () => ({
1164
+ enabled: false,
1165
+ epoch: 0,
1166
+ recorder: void 0
1167
+ }));
1168
+ function bindInstruments(recorder) {
1169
+ state9.enabled = true;
1170
+ state9.epoch += 1;
1171
+ state9.recorder = recorder;
1172
+ }
1173
+ function unbindInstruments() {
1174
+ state9.enabled = false;
1175
+ state9.epoch += 1;
1176
+ state9.recorder = void 0;
1177
+ }
1178
+ function buildResource(serviceName, extra = {}) {
1179
+ return defaultResource().merge(detectResources({ detectors: [envDetector] })).merge(resourceFromAttributes({ ...extra, "service.name": serviceName }));
1180
+ }
1181
+
1182
+ // src/metrics.ts
1183
+ var state10 = shared("metricsPipeline", () => ({
1184
+ provider: void 0
1185
+ }));
1186
+ function startMetrics(options, connection) {
1187
+ setHttpDurationBoundaries(options.httpDurationBoundaries);
1188
+ const exporter = new ExemplarExporter({
1189
+ url: `${options.endpoint}/v1/metrics`,
1190
+ headers: { Authorization: `Bearer ${connection.token}`, ...options.exporter.headers },
1191
+ host: options.exporter.host,
1192
+ reservoirSize: options.exemplarsPerBucket,
1193
+ // Warn (throttled) if an auto-HTTP exemplar stops matching its data point
1194
+ // — the drift guard for the hand-mirrored attribute keys.
1195
+ driftWatchMetricNames: AUTO_HTTP_METRICS
1196
+ });
1197
+ const provider = new MeterProvider({
1198
+ resource: buildResource(connection.serviceName, options.resourceAttributes),
1199
+ readers: [
1200
+ new PeriodicExportingMetricReader({
1201
+ exporter,
1202
+ exportIntervalMillis: options.exportIntervalMillis
1203
+ })
1204
+ ],
1205
+ // Re-bucket the auto-instrumented HTTP histograms onto the tuned
1206
+ // boundaries. A view's explicit-bucket aggregation wins over the
1207
+ // instrumentation's own `advice`; the OpenTelemetry defaults are coarse
1208
+ // exactly where web latency lives (100–500 ms). The exemplar reservoirs
1209
+ // bucket by the same list.
1210
+ views: AUTO_HTTP_METRICS.map((instrumentName) => ({
1211
+ instrumentName,
1212
+ aggregation: {
1213
+ type: AggregationType.EXPLICIT_BUCKET_HISTOGRAM,
1214
+ options: { boundaries: httpDurationBoundaries() }
1215
+ }
1216
+ }))
1217
+ });
1218
+ metrics.setGlobalMeterProvider(provider);
1219
+ bindInstruments((...args) => {
1220
+ exporter.recordExemplar(...args);
1221
+ });
1222
+ setAutoHttpExemplarExporter(exporter);
1223
+ state10.provider = provider;
1224
+ log.info(
1225
+ `sherlock metrics started: endpoint=${options.endpoint} service=${connection.serviceName} interval=${options.exportIntervalMillis}ms`
1226
+ );
1227
+ return provider;
1228
+ }
1229
+ function detachMetrics() {
1230
+ const provider = state10.provider;
1231
+ if (!provider) {
1232
+ return void 0;
1233
+ }
1234
+ state10.provider = void 0;
1235
+ unbindInstruments();
1236
+ setAutoHttpExemplarExporter(void 0);
1237
+ metrics.disable();
1238
+ return provider;
1239
+ }
1240
+ async function flushMetricsProvider(provider) {
1241
+ try {
1242
+ await provider.shutdown();
1243
+ } catch (err) {
1244
+ log.error("sherlock: metrics shutdown failed", err);
1245
+ }
1246
+ }
1247
+
1248
+ // src/options.ts
1249
+ var DEFAULT_EXPORT_INTERVAL_MS = 3e4;
1250
+ var DEFAULT_SAMPLE_RATIO = 1;
1251
+ var DEFAULT_EXEMPLARS_PER_BUCKET = 5;
1252
+ function envString(name) {
1253
+ const raw = process.env[name];
1254
+ return raw && raw.trim() !== "" ? raw.trim() : void 0;
1255
+ }
1256
+ function resolveSampleRatio(override) {
1257
+ const raw = override ?? envString("OTEL_TRACES_SAMPLER_ARG");
1258
+ if (raw === void 0) {
1259
+ return DEFAULT_SAMPLE_RATIO;
1260
+ }
1261
+ const ratio = Number(raw);
1262
+ if (!Number.isFinite(ratio) || ratio < 0 || ratio > 1) {
1263
+ log.warn(
1264
+ `sherlock: invalid sample ratio ${JSON.stringify(raw)} \u2014 expected 0..1, using ${DEFAULT_SAMPLE_RATIO}`
1265
+ );
1266
+ return DEFAULT_SAMPLE_RATIO;
1267
+ }
1268
+ return ratio;
1269
+ }
1270
+ function resolveExportInterval(override) {
1271
+ const raw = override ?? envString("SHERLOCK_METRICS_EXPORT_INTERVAL");
1272
+ if (raw === void 0) {
1273
+ return DEFAULT_EXPORT_INTERVAL_MS;
1274
+ }
1275
+ const interval = Number(raw);
1276
+ if (!Number.isFinite(interval) || interval <= 0) {
1277
+ log.warn(
1278
+ `sherlock: invalid metrics export interval ${JSON.stringify(raw)} \u2014 using ${DEFAULT_EXPORT_INTERVAL_MS}ms`
1279
+ );
1280
+ return DEFAULT_EXPORT_INTERVAL_MS;
1281
+ }
1282
+ return interval;
1283
+ }
1284
+ function resolveEndpoint(raw) {
1285
+ if (raw === void 0 || raw.trim() === "") {
1286
+ return void 0;
1287
+ }
1288
+ const trimmed = raw.replace(/\/+$/, "");
1289
+ let parsed;
1290
+ try {
1291
+ parsed = new URL(trimmed);
1292
+ } catch {
1293
+ log.warn(`sherlock: invalid endpoint ${JSON.stringify(raw)} \u2014 not a URL`);
1294
+ return void 0;
1295
+ }
1296
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
1297
+ log.warn(`sherlock: invalid endpoint ${JSON.stringify(raw)} \u2014 expected http or https`);
1298
+ return void 0;
1299
+ }
1300
+ return trimmed;
1301
+ }
1302
+ function resolveExemplarsPerBucket(override) {
1303
+ if (override === void 0) {
1304
+ return DEFAULT_EXEMPLARS_PER_BUCKET;
1305
+ }
1306
+ if (!Number.isInteger(override) || override < 1) {
1307
+ log.warn(
1308
+ `sherlock: invalid exemplarsPerBucket ${JSON.stringify(override)} \u2014 expected a positive integer, using ${DEFAULT_EXEMPLARS_PER_BUCKET}`
1309
+ );
1310
+ return DEFAULT_EXEMPLARS_PER_BUCKET;
1311
+ }
1312
+ return override;
1313
+ }
1314
+ function resolveBoundaries(override) {
1315
+ if (override === void 0) {
1316
+ return void 0;
1317
+ }
1318
+ if (!Array.isArray(override) || override.some((value) => !Number.isFinite(value))) {
1319
+ log.warn(
1320
+ "sherlock: invalid httpDurationBoundaries \u2014 expected finite numbers, using the tuned defaults"
1321
+ );
1322
+ return void 0;
1323
+ }
1324
+ const cleaned = [...new Set(override)].sort((a, b) => a - b);
1325
+ if (cleaned.length === 0) {
1326
+ log.warn("sherlock: empty httpDurationBoundaries \u2014 using the tuned defaults");
1327
+ return void 0;
1328
+ }
1329
+ if (cleaned.length !== override.length) {
1330
+ log.warn("sherlock: httpDurationBoundaries had duplicates or was unsorted \u2014 normalised");
1331
+ }
1332
+ return cleaned;
1333
+ }
1334
+ function resolveOptions(options = {}) {
1335
+ const tracing = options.tracing ?? true;
1336
+ const metrics3 = options.metrics ?? true;
1337
+ const tracingOptions = typeof tracing === "object" ? tracing : {};
1338
+ const metricsOptions = typeof metrics3 === "object" ? metrics3 : {};
1339
+ return {
1340
+ accessToken: options.accessToken ?? envString("SHERLOCK_ACCESS_TOKEN"),
1341
+ // Trailing slashes stripped so `${endpoint}/v1/metrics` never doubles up.
1342
+ endpoint: resolveEndpoint(options.endpoint ?? envString("SHERLOCK_ENDPOINT")),
1343
+ serviceName: options.serviceName ?? envString("OTEL_SERVICE_NAME"),
1344
+ resourceAttributes: options.resourceAttributes ?? {},
1345
+ tracingEnabled: tracing !== false,
1346
+ sampleRatio: resolveSampleRatio(tracingOptions.sampleRatio),
1347
+ metricsEnabled: metrics3 !== false,
1348
+ exportIntervalMillis: resolveExportInterval(metricsOptions.exportIntervalMillis),
1349
+ httpDurationBoundaries: resolveBoundaries(metricsOptions.httpDurationBoundaries),
1350
+ exemplarsPerBucket: resolveExemplarsPerBucket(metricsOptions.exemplarsPerBucket),
1351
+ // The option outranks the env vars entirely: when it is given, the two
1352
+ // OTEL_NODE_*_INSTRUMENTATIONS variables are not read at all.
1353
+ instrumentations: options.instrumentations ?? selectionFromEnv(),
1354
+ exporter: options.exporter ?? {},
1355
+ ignorePaths: options.ignorePaths ?? [],
1356
+ fastifyLifecycleSpans: options.fastify?.lifecycleSpans
1357
+ };
1358
+ }
1359
+ var state11 = shared("tracingPipeline", () => ({
1360
+ provider: void 0
1361
+ }));
1362
+ var FlagSampler = class {
1363
+ constructor(inner) {
1364
+ this.inner = inner;
1365
+ }
1366
+ inner;
1367
+ shouldSample(...args) {
1368
+ if (!telemetryState.tracesOn) {
1369
+ return { decision: SamplingDecision.NOT_RECORD };
1370
+ }
1371
+ return this.inner.shouldSample(...args);
1372
+ }
1373
+ toString() {
1374
+ return `FlagSampler(${this.inner.toString()})`;
1375
+ }
1376
+ };
1377
+ function buildSampler(sampleRatio) {
1378
+ const rootSampler = new FlagSampler(new TraceIdRatioBasedSampler(sampleRatio));
1379
+ return new ParentBasedSampler({
1380
+ root: rootSampler,
1381
+ remoteParentSampled: rootSampler,
1382
+ remoteParentNotSampled: rootSampler
1383
+ });
1384
+ }
1385
+ var SuppressedTraceExporter = class {
1386
+ constructor(inner) {
1387
+ this.inner = inner;
1388
+ }
1389
+ inner;
1390
+ export(spans, resultCallback) {
1391
+ context.with(suppressTracing(context.active()), () => {
1392
+ this.inner.export(spans, resultCallback);
1393
+ });
1394
+ }
1395
+ shutdown() {
1396
+ return this.inner.shutdown();
1397
+ }
1398
+ forceFlush() {
1399
+ return this.inner.forceFlush?.() ?? Promise.resolve();
1400
+ }
1401
+ };
1402
+ function startTracing(options, connection) {
1403
+ const headers = {
1404
+ Authorization: `Bearer ${connection.token}`,
1405
+ ...options.exporter.headers
1406
+ };
1407
+ if (options.exporter.host) {
1408
+ headers.Host = options.exporter.host;
1409
+ }
1410
+ const provider = new TracerProvider({
1411
+ resource: buildResource(connection.serviceName, options.resourceAttributes),
1412
+ sampler: buildSampler(options.sampleRatio),
1413
+ spanProcessors: [
1414
+ new BatchSpanProcessor({
1415
+ exporter: new SuppressedTraceExporter(
1416
+ new OTLPTraceExporter({ url: `${options.endpoint}/v1/traces`, headers })
1417
+ )
1418
+ })
1419
+ ]
1420
+ });
1421
+ trace.setGlobalTracerProvider(provider);
1422
+ context.setGlobalContextManager(new AsyncLocalStorageContextManager().enable());
1423
+ propagation.setGlobalPropagator(
1424
+ new CompositePropagator({
1425
+ propagators: [new W3CTraceContextPropagator(), new W3CBaggagePropagator()]
1426
+ })
1427
+ );
1428
+ state11.provider = provider;
1429
+ log.info(
1430
+ `sherlock tracing started: endpoint=${options.endpoint} service=${connection.serviceName} sampleRatio=${options.sampleRatio}`
1431
+ );
1432
+ }
1433
+ function detachTracing() {
1434
+ const provider = state11.provider;
1435
+ if (!provider) {
1436
+ return void 0;
1437
+ }
1438
+ state11.provider = void 0;
1439
+ trace.disable();
1440
+ context.disable();
1441
+ propagation.disable();
1442
+ return provider;
1443
+ }
1444
+ async function flushTracerProvider(provider) {
1445
+ try {
1446
+ await provider.shutdown();
1447
+ } catch (err) {
1448
+ log.error("sherlock: tracing shutdown failed", err);
1449
+ }
1450
+ }
1451
+
1452
+ // src/lifecycle.ts
1453
+ var state12 = shared("lifecycle", () => ({
1454
+ started: false,
1455
+ // The current run came from ./register rather than from app code.
1456
+ auto: false,
1457
+ // An explicit start() has been called at least once, whether or not it got
1458
+ // far enough to bring anything up. Enough to keep the auto-start from
1459
+ // stepping in behind an app that has clearly taken charge.
1460
+ explicitSeen: false,
1461
+ // Providers replaced by a takeover, still flushing. `stop()` awaits it.
1462
+ pendingFlush: void 0
1463
+ }));
1464
+ function autoStartFromEnv() {
1465
+ if (!process.env.SHERLOCK_ACCESS_TOKEN?.trim() || !process.env.OTEL_SERVICE_NAME?.trim() || !process.env.SHERLOCK_ENDPOINT?.trim()) {
1466
+ return;
1467
+ }
1468
+ const autoStart = process.env.SHERLOCK_AUTO_START?.trim().toLowerCase();
1469
+ if (autoStart === "false" || autoStart === "0" || autoStart === "no") {
1470
+ return;
1471
+ }
1472
+ const pending = setImmediate(() => {
1473
+ try {
1474
+ if (state12.started || state12.explicitSeen) {
1475
+ return;
1476
+ }
1477
+ startPipelines({}, true);
1478
+ } catch (err) {
1479
+ log.error("sherlock: auto-start failed \u2014 telemetry stays off", err);
1480
+ }
1481
+ });
1482
+ pending.unref();
1483
+ }
1484
+ function startPipelines(options, auto) {
1485
+ try {
1486
+ if (state12.started && (auto || !state12.auto)) {
1487
+ log.warn("sherlock: start() called twice \u2014 ignoring");
1488
+ return;
1489
+ }
1490
+ setupDiag(options.logger);
1491
+ const esmWarning = takeEsmHookWarning();
1492
+ if (esmWarning) {
1493
+ log.warn(esmWarning);
1494
+ }
1495
+ const resolved = resolveOptions(options);
1496
+ if (!resolved.accessToken) {
1497
+ log.warn("sherlock: no access token (SHERLOCK_ACCESS_TOKEN) \u2014 telemetry stays off");
1498
+ return;
1499
+ }
1500
+ if (!resolved.serviceName) {
1501
+ log.warn("sherlock: no service name (OTEL_SERVICE_NAME) \u2014 telemetry stays off");
1502
+ return;
1503
+ }
1504
+ if (!resolved.endpoint) {
1505
+ log.warn("sherlock: no valid endpoint (SHERLOCK_ENDPOINT) \u2014 telemetry stays off");
1506
+ return;
1507
+ }
1508
+ const startable = { ...resolved, endpoint: resolved.endpoint };
1509
+ const connection = { token: resolved.accessToken, serviceName: resolved.serviceName };
1510
+ if (state12.started) {
1511
+ log.info("sherlock: explicit start() is replacing the ./register auto-start");
1512
+ detachPipelines();
1513
+ }
1514
+ registerIngestEndpoint(startable.endpoint);
1515
+ addIgnorePaths(resolved.ignorePaths);
1516
+ const missedFastifyInstances = fastifyInstancesCreatedWithoutLifecycleSpans();
1517
+ if (resolved.fastifyLifecycleSpans && !lifecycleSpansEnabled() && missedFastifyInstances > 0) {
1518
+ log.warn(
1519
+ `sherlock: fastify.lifecycleSpans applies to Fastify instances created after start(); ${missedFastifyInstances} already exist without it`
1520
+ );
1521
+ }
1522
+ if (resolved.fastifyLifecycleSpans === void 0) {
1523
+ checkLifecycleSpansEnv();
1524
+ }
1525
+ setLifecycleSpans(resolved.fastifyLifecycleSpans);
1526
+ seedTelemetryStateFromEnv();
1527
+ const instrumentations = applyInstrumentationOverride(resolved.instrumentations);
1528
+ if (lifecycleSpansEnabled() && !anyFastifyInstrumentationEnabled()) {
1529
+ log.warn(
1530
+ "sherlock: fastify.lifecycleSpans is on, but the fastify instrumentation is not enabled, so there will be no lifecycle spans"
1531
+ );
1532
+ }
1533
+ const provider = resolved.metricsEnabled ? startMetrics(startable, connection) : void 0;
1534
+ if (provider) {
1535
+ for (const instrumentation of instrumentations) {
1536
+ instrumentation.setMeterProvider(provider);
1537
+ }
1538
+ }
1539
+ if (resolved.tracingEnabled) {
1540
+ startTracing(startable, connection);
1541
+ }
1542
+ state12.started = true;
1543
+ state12.auto = auto;
1544
+ if (!provider && !resolved.tracingEnabled) {
1545
+ log.warn("sherlock: both tracing and metrics are disabled \u2014 nothing will be exported");
1546
+ }
1547
+ } catch (err) {
1548
+ log.error("sherlock: start failed \u2014 telemetry stays off", err);
1549
+ try {
1550
+ detachPipelines();
1551
+ } catch {
1552
+ }
1553
+ }
1554
+ }
1555
+ function detachPipelines() {
1556
+ const meterProvider = detachMetrics();
1557
+ const tracerProvider = detachTracing();
1558
+ state12.started = false;
1559
+ state12.auto = false;
1560
+ const flushes = [];
1561
+ if (meterProvider) {
1562
+ flushes.push(flushMetricsProvider(meterProvider));
1563
+ }
1564
+ if (tracerProvider) {
1565
+ flushes.push(flushTracerProvider(tracerProvider));
1566
+ }
1567
+ if (flushes.length === 0) {
1568
+ return;
1569
+ }
1570
+ const previous = state12.pendingFlush ?? Promise.resolve();
1571
+ state12.pendingFlush = previous.then(async () => {
1572
+ await Promise.all(flushes);
1573
+ });
1574
+ }
1575
+ function applyInstrumentationOverride(override) {
1576
+ if (override === void 0) {
1577
+ return registeredInstrumentations();
1578
+ }
1579
+ if (isSelection(override)) {
1580
+ const kept = selectInstrumentations(registeredInstrumentations(), override);
1581
+ forgetInstrumentations();
1582
+ rememberInstrumentations(kept);
1583
+ return kept;
1584
+ }
1585
+ for (const installed of registeredInstrumentations()) {
1586
+ installed.disable();
1587
+ }
1588
+ forgetInstrumentations();
1589
+ if (override.length > 0) {
1590
+ mergePackageHttpConfig(override);
1591
+ registerInstrumentations({ instrumentations: override });
1592
+ }
1593
+ return override;
1594
+ }
1595
+
1596
+ // package.json
1597
+ var version = "0.3.0-rc.1";
1598
+
1599
+ // src/fastifyInstrumentation.ts
1600
+ var CHANNEL = "fastify.initialization";
1601
+ var kRouteHookAddedByAnyCopyOfThisPackage = /* @__PURE__ */ Symbol.for("sherlock.node.fastify.routeHook");
1602
+ var FastifyInstrumentation = class extends InstrumentationBase {
1603
+ constructor(config = {}) {
1604
+ super(FASTIFY_INSTRUMENTATION_NAME, version, config);
1605
+ }
1606
+ init() {
1607
+ return [];
1608
+ }
1609
+ enable() {
1610
+ this.enabledCopy ??= { tracer: () => this.tracer };
1611
+ addEnabledCopy(this.enabledCopy);
1612
+ if (!this.onInitialization) {
1613
+ this.onInitialization = (message) => {
1614
+ try {
1615
+ const fastify = message?.fastify;
1616
+ if (fastify) {
1617
+ addRouteHook(fastify);
1618
+ }
1619
+ } catch (err) {
1620
+ diag.warn("sherlock fastify instrumentation: could not add the route hook", err);
1621
+ }
1622
+ };
1623
+ subscribe(CHANNEL, this.onInitialization);
1624
+ }
1625
+ super.enable();
1626
+ }
1627
+ disable() {
1628
+ if (this.enabledCopy) {
1629
+ removeEnabledCopy(this.enabledCopy);
1630
+ }
1631
+ if (this.onInitialization) {
1632
+ unsubscribe(CHANNEL, this.onInitialization);
1633
+ this.onInitialization = void 0;
1634
+ }
1635
+ super.disable();
1636
+ }
1637
+ };
1638
+ function addRouteHook(fastify) {
1639
+ if (fastify[kRouteHookAddedByAnyCopyOfThisPackage]) {
1640
+ return;
1641
+ }
1642
+ fastify[kRouteHookAddedByAnyCopyOfThisPackage] = true;
1643
+ fastify.addHook("onRequest", (request, _reply, done) => {
1644
+ if (anyFastifyInstrumentationEnabled()) {
1645
+ setRouteOnRpcMetadata(request);
1646
+ rememberRequestContext(request);
1647
+ }
1648
+ done();
1649
+ });
1650
+ if (lifecycleSpansEnabled()) {
1651
+ installLifecycleSpans(fastify, anyEnabledTracer);
1652
+ } else {
1653
+ noteInstanceWithoutSpans();
1654
+ }
1655
+ }
1656
+ function setRouteOnRpcMetadata(request) {
1657
+ try {
1658
+ const route = request.routeOptions?.url;
1659
+ if (!route) {
1660
+ return;
1661
+ }
1662
+ const metadata = getRPCMetadata(context.active());
1663
+ if (metadata?.type === RPCType.HTTP) {
1664
+ metadata.route = route;
1665
+ }
1666
+ } catch {
1667
+ }
1668
+ }
1669
+
1670
+ // src/registerCore.ts
1671
+ function installAutoInstrumentations() {
1672
+ const instrumentations = buildFullBundle(() => [
1673
+ ...getNodeAutoInstrumentations({
1674
+ [HTTP_INSTRUMENTATION_NAME]: packageHttpConfig()
1675
+ }),
1676
+ new FastifyInstrumentation()
1677
+ ]);
1678
+ rememberInstrumentations(instrumentations);
1679
+ registerInstrumentations({ instrumentations });
1680
+ }
1681
+
1682
+ // src/register.esm.ts
1683
+ var acknowledged = installEsmHook(import.meta.url);
1684
+ noteIfLate();
1685
+ installAutoInstrumentations();
1686
+ await acknowledged();
1687
+ await import('http');
1688
+ await import('https');
1689
+ autoStartFromEnv();
1690
+ //# sourceMappingURL=register.mjs.map
1691
+ //# sourceMappingURL=register.mjs.map