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