@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/CHANGELOG.md +85 -0
- package/LICENSE +202 -0
- package/README.md +680 -2
- package/dist/express.d.mts +18 -0
- package/dist/express.d.ts +18 -0
- package/dist/express.js +320 -0
- package/dist/express.js.map +1 -0
- package/dist/express.mjs +318 -0
- package/dist/express.mjs.map +1 -0
- package/dist/fastify.d.mts +62 -0
- package/dist/fastify.d.ts +62 -0
- package/dist/fastify.js +659 -0
- package/dist/fastify.js.map +1 -0
- package/dist/fastify.mjs +656 -0
- package/dist/fastify.mjs.map +1 -0
- package/dist/httpServerMetrics-BfVoFAxd.d.mts +15 -0
- package/dist/httpServerMetrics-BfVoFAxd.d.ts +15 -0
- package/dist/index.d.mts +198 -0
- package/dist/index.d.ts +198 -0
- package/dist/index.js +1552 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +1527 -0
- package/dist/index.mjs.map +1 -0
- package/dist/koa.d.mts +14 -0
- package/dist/koa.d.ts +14 -0
- package/dist/koa.js +309 -0
- package/dist/koa.js.map +1 -0
- package/dist/koa.mjs +307 -0
- package/dist/koa.mjs.map +1 -0
- package/dist/register.d.mts +2 -0
- package/dist/register.d.ts +2 -0
- package/dist/register.js +1641 -0
- package/dist/register.js.map +1 -0
- package/dist/register.mjs +1691 -0
- package/dist/register.mjs.map +1 -0
- package/package.json +108 -4
package/dist/fastify.mjs
ADDED
|
@@ -0,0 +1,656 @@
|
|
|
1
|
+
import { performance } from 'perf_hooks';
|
|
2
|
+
import { DiagLogLevel, diag, context, metrics, trace, isSpanContextValid, SpanStatusCode } from '@opentelemetry/api';
|
|
3
|
+
import 'util';
|
|
4
|
+
import { getRPCMetadata, RPCType } from '@opentelemetry/core';
|
|
5
|
+
import { subscribe, unsubscribe } from 'diagnostics_channel';
|
|
6
|
+
import { InstrumentationBase } from '@opentelemetry/instrumentation';
|
|
7
|
+
|
|
8
|
+
// src/fastify.ts
|
|
9
|
+
|
|
10
|
+
// src/shared.ts
|
|
11
|
+
var REGISTRY_KEY = /* @__PURE__ */ Symbol.for("@sherlock-labs/node:state:v1");
|
|
12
|
+
function registry() {
|
|
13
|
+
const holder = globalThis;
|
|
14
|
+
let existing = holder[REGISTRY_KEY];
|
|
15
|
+
if (!existing) {
|
|
16
|
+
existing = /* @__PURE__ */ new Map();
|
|
17
|
+
holder[REGISTRY_KEY] = existing;
|
|
18
|
+
}
|
|
19
|
+
return existing;
|
|
20
|
+
}
|
|
21
|
+
function shared(name, create) {
|
|
22
|
+
const store = registry();
|
|
23
|
+
const existing = store.get(name);
|
|
24
|
+
if (existing) {
|
|
25
|
+
return existing;
|
|
26
|
+
}
|
|
27
|
+
const created = create();
|
|
28
|
+
store.set(name, created);
|
|
29
|
+
return created;
|
|
30
|
+
}
|
|
31
|
+
({
|
|
32
|
+
none: DiagLogLevel.NONE,
|
|
33
|
+
error: DiagLogLevel.ERROR,
|
|
34
|
+
warn: DiagLogLevel.WARN,
|
|
35
|
+
info: DiagLogLevel.INFO,
|
|
36
|
+
debug: DiagLogLevel.DEBUG,
|
|
37
|
+
verbose: DiagLogLevel.VERBOSE,
|
|
38
|
+
all: DiagLogLevel.ALL
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
// src/telemetryState.ts
|
|
42
|
+
shared("telemetryState", () => ({
|
|
43
|
+
tracesOn: true,
|
|
44
|
+
metricsOn: true,
|
|
45
|
+
// Set once the app has called setTelemetryEnabled for that pipeline. From
|
|
46
|
+
// then on `start()` stops re-seeding it from the environment — an explicit
|
|
47
|
+
// call by the app always outranks a boot-time env var.
|
|
48
|
+
tracesSetByApp: false,
|
|
49
|
+
metricsSetByApp: false
|
|
50
|
+
}));
|
|
51
|
+
function parseEnvFlag(raw) {
|
|
52
|
+
if (raw === void 0 || raw.trim() === "") {
|
|
53
|
+
return void 0;
|
|
54
|
+
}
|
|
55
|
+
const normalized = raw.trim().toLowerCase();
|
|
56
|
+
if (normalized === "false" || normalized === "0" || normalized === "no") {
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
if (normalized === "true" || normalized === "1" || normalized === "yes") {
|
|
60
|
+
return true;
|
|
61
|
+
}
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// src/fastifySpans.ts
|
|
66
|
+
var LIFECYCLE_SPANS_ENV = "SHERLOCK_FASTIFY_LIFECYCLE_SPANS";
|
|
67
|
+
var LIFECYCLE_HOOKS = [
|
|
68
|
+
"onTimeout",
|
|
69
|
+
"onRequest",
|
|
70
|
+
"preParsing",
|
|
71
|
+
"preValidation",
|
|
72
|
+
"preHandler",
|
|
73
|
+
"preSerialization",
|
|
74
|
+
"onSend",
|
|
75
|
+
"onResponse",
|
|
76
|
+
"onError",
|
|
77
|
+
"onRequestAbort"
|
|
78
|
+
];
|
|
79
|
+
var isLifecycleHook = (name) => LIFECYCLE_HOOKS.includes(name);
|
|
80
|
+
var kLeaveUnwrapped = /* @__PURE__ */ Symbol.for("sherlock.node.fastify.leaveUnwrapped");
|
|
81
|
+
var FASTIFY_OWN_HOOKS = /* @__PURE__ */ new Set(["headRouteOnSendHandler"]);
|
|
82
|
+
var state = shared("fastifyLifecycleSpans", () => ({
|
|
83
|
+
enabled: parseEnvFlag(process.env[LIFECYCLE_SPANS_ENV]) === true,
|
|
84
|
+
instancesCreatedWithoutSpans: 0,
|
|
85
|
+
requestContexts: /* @__PURE__ */ new WeakMap()
|
|
86
|
+
}));
|
|
87
|
+
var copies = shared("fastifyInstrumentationCopies", () => ({ active: /* @__PURE__ */ new Set() }));
|
|
88
|
+
function addEnabledCopy(copy) {
|
|
89
|
+
copies.active.add(copy);
|
|
90
|
+
}
|
|
91
|
+
function removeEnabledCopy(copy) {
|
|
92
|
+
copies.active.delete(copy);
|
|
93
|
+
}
|
|
94
|
+
function anyFastifyInstrumentationEnabled() {
|
|
95
|
+
return copies.active.size > 0;
|
|
96
|
+
}
|
|
97
|
+
function anyEnabledTracer() {
|
|
98
|
+
for (const copy of copies.active) {
|
|
99
|
+
return copy.tracer();
|
|
100
|
+
}
|
|
101
|
+
return void 0;
|
|
102
|
+
}
|
|
103
|
+
function lifecycleSpansEnabled() {
|
|
104
|
+
return state.enabled;
|
|
105
|
+
}
|
|
106
|
+
function noteInstanceWithoutSpans() {
|
|
107
|
+
state.instancesCreatedWithoutSpans++;
|
|
108
|
+
}
|
|
109
|
+
function rememberRequestContext(request) {
|
|
110
|
+
if (state.enabled) {
|
|
111
|
+
state.requestContexts.set(request, context.active());
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
function installLifecycleSpans(fastify, tracer) {
|
|
115
|
+
const addHook = fastify.addHook;
|
|
116
|
+
fastify.addHook = function addHookWithSpans(name, fn) {
|
|
117
|
+
const wrapped = isLifecycleHook(name) ? wrapFn(fn, tracer, name, void 0) : fn;
|
|
118
|
+
return addHook.call(this, name, wrapped);
|
|
119
|
+
};
|
|
120
|
+
addHook.call(fastify, "onRoute", (routeOptions) => {
|
|
121
|
+
const route = routeOptions.url;
|
|
122
|
+
for (const hook of LIFECYCLE_HOOKS) {
|
|
123
|
+
const value = routeOptions[hook];
|
|
124
|
+
if (value === void 0) {
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
routeOptions[hook] = Array.isArray(value) ? value.map((fn) => wrapFn(fn, tracer, hook, route)) : wrapFn(value, tracer, hook, route);
|
|
128
|
+
}
|
|
129
|
+
routeOptions.handler = wrapFn(routeOptions.handler, tracer, "handler", route);
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
function wrapFn(fn, tracer, kind, route) {
|
|
133
|
+
if (typeof fn !== "function" || fn[kLeaveUnwrapped] || FASTIFY_OWN_HOOKS.has(fn.name)) {
|
|
134
|
+
return fn;
|
|
135
|
+
}
|
|
136
|
+
const original = fn;
|
|
137
|
+
const run = function(args) {
|
|
138
|
+
const active = state.enabled ? tracer() : void 0;
|
|
139
|
+
const started = active ? startSpan(active, original, args, kind, route) : void 0;
|
|
140
|
+
return started ? runInSpan(this, original, args, kind, started) : original.apply(this, args);
|
|
141
|
+
};
|
|
142
|
+
const wrapper = original.constructor.name === "AsyncFunction" ? async function(...args) {
|
|
143
|
+
return run.call(this, args);
|
|
144
|
+
} : function(...args) {
|
|
145
|
+
return run.call(this, args);
|
|
146
|
+
};
|
|
147
|
+
Object.defineProperty(wrapper, "length", { value: original.length });
|
|
148
|
+
Object.defineProperty(wrapper, "name", { value: original.name });
|
|
149
|
+
return wrapper;
|
|
150
|
+
}
|
|
151
|
+
function startSpan(tracer, original, args, kind, route) {
|
|
152
|
+
try {
|
|
153
|
+
const request = args.find(isRequest);
|
|
154
|
+
const parent = (request && state.requestContexts.get(request)) ?? context.active();
|
|
155
|
+
if (!trace.getSpan(parent)) {
|
|
156
|
+
return void 0;
|
|
157
|
+
}
|
|
158
|
+
const httpRoute = route ?? request?.routeOptions?.url;
|
|
159
|
+
const name = kind === "handler" ? `handler - ${httpRoute ?? "unknown"}` : `${kind} - ${original.name || "anonymous"}`;
|
|
160
|
+
const span = tracer.startSpan(
|
|
161
|
+
name,
|
|
162
|
+
{
|
|
163
|
+
attributes: {
|
|
164
|
+
"fastify.type": kind === "handler" ? "handler" : "hook",
|
|
165
|
+
...kind === "handler" ? {} : { "fastify.hook": kind },
|
|
166
|
+
...httpRoute ? { "http.route": httpRoute } : {}
|
|
167
|
+
}
|
|
168
|
+
},
|
|
169
|
+
parent
|
|
170
|
+
);
|
|
171
|
+
return { span, parent };
|
|
172
|
+
} catch {
|
|
173
|
+
return void 0;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
function runInSpan(self, original, args, kind, { span, parent }) {
|
|
177
|
+
let ended = false;
|
|
178
|
+
const end = (err) => {
|
|
179
|
+
if (ended) {
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
ended = true;
|
|
183
|
+
try {
|
|
184
|
+
if (err) {
|
|
185
|
+
recordError(span, err);
|
|
186
|
+
}
|
|
187
|
+
span.end();
|
|
188
|
+
} catch {
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
const last = args.length - 1;
|
|
192
|
+
const done = typeof args[last] === "function" && kind !== "handler" ? args[last] : void 0;
|
|
193
|
+
const entryContext = context.active();
|
|
194
|
+
const callArgs = done ? [
|
|
195
|
+
...args.slice(0, last),
|
|
196
|
+
function(err, ...rest) {
|
|
197
|
+
end(err);
|
|
198
|
+
return context.with(entryContext, () => done.call(this, err, ...rest));
|
|
199
|
+
}
|
|
200
|
+
] : args;
|
|
201
|
+
return context.with(trace.setSpan(parent, span), () => {
|
|
202
|
+
let result;
|
|
203
|
+
try {
|
|
204
|
+
result = original.apply(self, callArgs);
|
|
205
|
+
} catch (err) {
|
|
206
|
+
end(err);
|
|
207
|
+
throw err;
|
|
208
|
+
}
|
|
209
|
+
if (isThenable(result)) {
|
|
210
|
+
try {
|
|
211
|
+
result.then(
|
|
212
|
+
() => end(),
|
|
213
|
+
(err) => end(err)
|
|
214
|
+
);
|
|
215
|
+
} catch {
|
|
216
|
+
end();
|
|
217
|
+
}
|
|
218
|
+
return result;
|
|
219
|
+
}
|
|
220
|
+
if (kind === "handler" && result === void 0) {
|
|
221
|
+
endWhenReplied(args[1], end);
|
|
222
|
+
} else if (!done) {
|
|
223
|
+
end();
|
|
224
|
+
}
|
|
225
|
+
return result;
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
function endWhenReplied(reply, end) {
|
|
229
|
+
if (!isReply(reply) || reply.sent !== false) {
|
|
230
|
+
end();
|
|
231
|
+
return;
|
|
232
|
+
}
|
|
233
|
+
try {
|
|
234
|
+
reply.raw.once("finish", end);
|
|
235
|
+
reply.raw.once("close", end);
|
|
236
|
+
} catch {
|
|
237
|
+
end();
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
function recordError(span, err) {
|
|
241
|
+
if (err instanceof Error) {
|
|
242
|
+
span.recordException(err);
|
|
243
|
+
}
|
|
244
|
+
const status = err?.statusCode ?? err?.status;
|
|
245
|
+
if (typeof status === "number" && status < 500) {
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
span.setStatus({
|
|
249
|
+
code: SpanStatusCode.ERROR,
|
|
250
|
+
message: err instanceof Error ? err.message : String(err)
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
function isRequest(value) {
|
|
254
|
+
return typeof value === "object" && value !== null && "routeOptions" in value && "raw" in value;
|
|
255
|
+
}
|
|
256
|
+
function isReply(value) {
|
|
257
|
+
return typeof value === "object" && value !== null && "sent" in value && "raw" in value;
|
|
258
|
+
}
|
|
259
|
+
function isThenable(value) {
|
|
260
|
+
return typeof value?.then === "function";
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// src/httpBoundaries.ts
|
|
264
|
+
var DEFAULT_DURATION_BOUNDARIES_S = Object.freeze([
|
|
265
|
+
5e-3,
|
|
266
|
+
0.01,
|
|
267
|
+
0.025,
|
|
268
|
+
0.05,
|
|
269
|
+
0.075,
|
|
270
|
+
0.1,
|
|
271
|
+
0.15,
|
|
272
|
+
0.2,
|
|
273
|
+
0.25,
|
|
274
|
+
0.3,
|
|
275
|
+
0.35,
|
|
276
|
+
0.4,
|
|
277
|
+
0.45,
|
|
278
|
+
0.5,
|
|
279
|
+
0.75,
|
|
280
|
+
1,
|
|
281
|
+
2.5,
|
|
282
|
+
5,
|
|
283
|
+
7.5,
|
|
284
|
+
10
|
|
285
|
+
]);
|
|
286
|
+
var state2 = shared("httpBoundaries", () => ({
|
|
287
|
+
list: [...DEFAULT_DURATION_BOUNDARIES_S]
|
|
288
|
+
}));
|
|
289
|
+
function httpDurationBoundaries() {
|
|
290
|
+
return state2.list;
|
|
291
|
+
}
|
|
292
|
+
function exemplarTraceFrom(spanContext) {
|
|
293
|
+
if (!spanContext || !isSpanContextValid(spanContext)) {
|
|
294
|
+
return void 0;
|
|
295
|
+
}
|
|
296
|
+
return {
|
|
297
|
+
traceId: spanContext.traceId,
|
|
298
|
+
spanId: spanContext.spanId,
|
|
299
|
+
// The trace-flags byte as two lowercase hex digits, e.g. 1 → "01".
|
|
300
|
+
traceFlags: (spanContext.traceFlags & 255).toString(16).padStart(2, "0")
|
|
301
|
+
};
|
|
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 state3 = shared("instruments", () => ({
|
|
323
|
+
enabled: false,
|
|
324
|
+
epoch: 0,
|
|
325
|
+
recorder: void 0
|
|
326
|
+
}));
|
|
327
|
+
var CounterDef = class {
|
|
328
|
+
constructor(name, opts) {
|
|
329
|
+
this.name = name;
|
|
330
|
+
this.opts = opts;
|
|
331
|
+
}
|
|
332
|
+
name;
|
|
333
|
+
opts;
|
|
334
|
+
counter;
|
|
335
|
+
counterEpoch = -1;
|
|
336
|
+
add(value, attrs = {}) {
|
|
337
|
+
if (!state3.enabled) {
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
try {
|
|
341
|
+
if (this.counterEpoch !== state3.epoch) {
|
|
342
|
+
this.counter = metrics.getMeter(this.opts.meterName ?? "app").createCounter(this.name, { description: this.opts.description, unit: this.opts.unit });
|
|
343
|
+
this.counterEpoch = state3.epoch;
|
|
344
|
+
}
|
|
345
|
+
this.counter?.add(value, attrs);
|
|
346
|
+
} catch (err) {
|
|
347
|
+
diag.warn(`counter ${this.name}: record failed`, err);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
};
|
|
351
|
+
var HistogramDef = class {
|
|
352
|
+
constructor(name, opts) {
|
|
353
|
+
this.name = name;
|
|
354
|
+
this.opts = opts;
|
|
355
|
+
this.unit = opts.unit ?? "s";
|
|
356
|
+
this.boundaries = opts.boundaries ?? defaultBoundariesFor(this.unit);
|
|
357
|
+
}
|
|
358
|
+
name;
|
|
359
|
+
opts;
|
|
360
|
+
histogram;
|
|
361
|
+
histogramEpoch = -1;
|
|
362
|
+
// The unit on the wire, and the bucket list the histogram advice and the
|
|
363
|
+
// exemplar reservoir share. The list is held by reference, never copied:
|
|
364
|
+
// `start({ metrics: { httpDurationBoundaries } })` mutates the shared list in
|
|
365
|
+
// place, and a definition created at module scope has to see that.
|
|
366
|
+
unit;
|
|
367
|
+
boundaries;
|
|
368
|
+
record(value, attrs = {}) {
|
|
369
|
+
if (!state3.enabled) {
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
try {
|
|
373
|
+
if (this.histogramEpoch !== state3.epoch) {
|
|
374
|
+
this.histogram = metrics.getMeter(this.opts.meterName ?? "app").createHistogram(this.name, {
|
|
375
|
+
description: this.opts.description,
|
|
376
|
+
unit: this.unit,
|
|
377
|
+
advice: { explicitBucketBoundaries: [...this.boundaries] }
|
|
378
|
+
});
|
|
379
|
+
this.histogramEpoch = state3.epoch;
|
|
380
|
+
}
|
|
381
|
+
this.histogram?.record(value, attrs);
|
|
382
|
+
} catch (err) {
|
|
383
|
+
diag.warn(`histogram ${this.name}: record failed`, err);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
// record() plus an exemplar. `exemplarAttrs` are the per-observation,
|
|
387
|
+
// high-cardinality keys the app owns (an order id, a customer id); the
|
|
388
|
+
// distribution adds none of its own.
|
|
389
|
+
//
|
|
390
|
+
// Whenever a span with a valid context is active, its ids go onto the exemplar
|
|
391
|
+
// and its trace-flags byte lands in filteredAttributes as `trace_flags` — "01"
|
|
392
|
+
// when the span was sampled, "00" when it was not. That is the
|
|
393
|
+
// same trio instrumentation-pino writes on log lines, so a chart, an exemplar
|
|
394
|
+
// and a log line all join on trace_id.
|
|
395
|
+
recordWithExemplar(value, attrs = {}, exemplarAttrs = {}) {
|
|
396
|
+
this.record(value, attrs);
|
|
397
|
+
const recorder = state3.recorder;
|
|
398
|
+
if (!recorder) {
|
|
399
|
+
return;
|
|
400
|
+
}
|
|
401
|
+
try {
|
|
402
|
+
recorder(
|
|
403
|
+
this.name,
|
|
404
|
+
attrs,
|
|
405
|
+
value,
|
|
406
|
+
exemplarAttrs,
|
|
407
|
+
this.boundaries,
|
|
408
|
+
exemplarTraceFrom(trace.getActiveSpan()?.spanContext())
|
|
409
|
+
);
|
|
410
|
+
} catch (err) {
|
|
411
|
+
diag.warn(`histogram ${this.name}: exemplar record failed`, err);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
};
|
|
415
|
+
function defaultBoundariesFor(unit) {
|
|
416
|
+
return unit === "s" ? DEFAULT_DURATION_BOUNDARIES_S : DEFAULT_HISTOGRAM_BOUNDARIES;
|
|
417
|
+
}
|
|
418
|
+
function defineCounter(name, opts = {}) {
|
|
419
|
+
return new CounterDef(name, opts);
|
|
420
|
+
}
|
|
421
|
+
function defineHistogram(name, opts = {}) {
|
|
422
|
+
return new HistogramDef(name, opts);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// src/httpServerMetrics.ts
|
|
426
|
+
var NO_ROUTE = "<no_route>";
|
|
427
|
+
var MAX_DISTINCT_ROUTES = 1e3;
|
|
428
|
+
var instruments = shared("httpServerInstruments", () => ({
|
|
429
|
+
count: defineCounter("app.http.server.count", {
|
|
430
|
+
description: "HTTP request count",
|
|
431
|
+
meterName: "app.http.server"
|
|
432
|
+
}),
|
|
433
|
+
errors: defineCounter("app.http.server.errors", {
|
|
434
|
+
description: "HTTP request errors",
|
|
435
|
+
meterName: "app.http.server"
|
|
436
|
+
}),
|
|
437
|
+
duration: defineHistogram("app.http.server.duration", {
|
|
438
|
+
description: "HTTP request duration",
|
|
439
|
+
unit: "s",
|
|
440
|
+
boundaries: httpDurationBoundaries(),
|
|
441
|
+
meterName: "app.http.server"
|
|
442
|
+
}),
|
|
443
|
+
seenRoutes: /* @__PURE__ */ new Set()
|
|
444
|
+
}));
|
|
445
|
+
function capRoute(route) {
|
|
446
|
+
if (!route) {
|
|
447
|
+
return NO_ROUTE;
|
|
448
|
+
}
|
|
449
|
+
if (instruments.seenRoutes.has(route)) {
|
|
450
|
+
return route;
|
|
451
|
+
}
|
|
452
|
+
if (instruments.seenRoutes.size >= MAX_DISTINCT_ROUTES) {
|
|
453
|
+
return NO_ROUTE;
|
|
454
|
+
}
|
|
455
|
+
instruments.seenRoutes.add(route);
|
|
456
|
+
return route;
|
|
457
|
+
}
|
|
458
|
+
function shouldIgnoreRequest(predicate, req) {
|
|
459
|
+
if (!predicate) {
|
|
460
|
+
return false;
|
|
461
|
+
}
|
|
462
|
+
try {
|
|
463
|
+
return predicate(req) === true;
|
|
464
|
+
} catch (err) {
|
|
465
|
+
diag.warn("sherlock: ignoreRequest predicate threw \u2014 measuring the request anyway", err);
|
|
466
|
+
return false;
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
var CLIENT_CLOSED_REQUEST = 499;
|
|
470
|
+
function recordedStatusCode(res, finished) {
|
|
471
|
+
return finished || res.headersSent ? res.statusCode ?? 0 : CLIENT_CLOSED_REQUEST;
|
|
472
|
+
}
|
|
473
|
+
function recordHttpRequest(attrs, durationSeconds, recordExemplars) {
|
|
474
|
+
instruments.count.add(1, attrs);
|
|
475
|
+
if (attrs.status === "error") {
|
|
476
|
+
instruments.errors.add(1, attrs);
|
|
477
|
+
}
|
|
478
|
+
if (!recordExemplars) {
|
|
479
|
+
instruments.duration.record(durationSeconds, attrs);
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
instruments.duration.recordWithExemplar(durationSeconds, attrs);
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
// src/ignorePaths.ts
|
|
486
|
+
var DEFAULT_IGNORE_PATHS = ["/healthz", "/livez", "/healthcheck"];
|
|
487
|
+
var state4 = shared("ignorePaths", () => ({
|
|
488
|
+
paths: /* @__PURE__ */ new Set([...DEFAULT_IGNORE_PATHS, ...readEnvPaths()])
|
|
489
|
+
}));
|
|
490
|
+
function readEnvPaths() {
|
|
491
|
+
return (process.env.SHERLOCK_IGNORE_PATHS ?? "").split(",").map((path) => path.trim()).filter((path) => path.length > 0);
|
|
492
|
+
}
|
|
493
|
+
function isIgnoredPath(url) {
|
|
494
|
+
if (!url) {
|
|
495
|
+
return false;
|
|
496
|
+
}
|
|
497
|
+
const queryAt = url.indexOf("?");
|
|
498
|
+
const path = queryAt === -1 ? url : url.slice(0, queryAt);
|
|
499
|
+
return state4.paths.has(path);
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
// package.json
|
|
503
|
+
var version = "0.3.0-rc.1";
|
|
504
|
+
|
|
505
|
+
// src/ownInstrumentations.ts
|
|
506
|
+
var FASTIFY_INSTRUMENTATION_NAME = "@sherlock-labs/node/fastify";
|
|
507
|
+
|
|
508
|
+
// src/fastifyInstrumentation.ts
|
|
509
|
+
var CHANNEL = "fastify.initialization";
|
|
510
|
+
var kRouteHookAddedByAnyCopyOfThisPackage = /* @__PURE__ */ Symbol.for("sherlock.node.fastify.routeHook");
|
|
511
|
+
var FastifyInstrumentation = class extends InstrumentationBase {
|
|
512
|
+
constructor(config = {}) {
|
|
513
|
+
super(FASTIFY_INSTRUMENTATION_NAME, version, config);
|
|
514
|
+
}
|
|
515
|
+
init() {
|
|
516
|
+
return [];
|
|
517
|
+
}
|
|
518
|
+
enable() {
|
|
519
|
+
this.enabledCopy ??= { tracer: () => this.tracer };
|
|
520
|
+
addEnabledCopy(this.enabledCopy);
|
|
521
|
+
if (!this.onInitialization) {
|
|
522
|
+
this.onInitialization = (message) => {
|
|
523
|
+
try {
|
|
524
|
+
const fastify = message?.fastify;
|
|
525
|
+
if (fastify) {
|
|
526
|
+
addRouteHook(fastify);
|
|
527
|
+
}
|
|
528
|
+
} catch (err) {
|
|
529
|
+
diag.warn("sherlock fastify instrumentation: could not add the route hook", err);
|
|
530
|
+
}
|
|
531
|
+
};
|
|
532
|
+
subscribe(CHANNEL, this.onInitialization);
|
|
533
|
+
}
|
|
534
|
+
super.enable();
|
|
535
|
+
}
|
|
536
|
+
disable() {
|
|
537
|
+
if (this.enabledCopy) {
|
|
538
|
+
removeEnabledCopy(this.enabledCopy);
|
|
539
|
+
}
|
|
540
|
+
if (this.onInitialization) {
|
|
541
|
+
unsubscribe(CHANNEL, this.onInitialization);
|
|
542
|
+
this.onInitialization = void 0;
|
|
543
|
+
}
|
|
544
|
+
super.disable();
|
|
545
|
+
}
|
|
546
|
+
};
|
|
547
|
+
function addRouteHook(fastify) {
|
|
548
|
+
if (fastify[kRouteHookAddedByAnyCopyOfThisPackage]) {
|
|
549
|
+
return;
|
|
550
|
+
}
|
|
551
|
+
fastify[kRouteHookAddedByAnyCopyOfThisPackage] = true;
|
|
552
|
+
fastify.addHook("onRequest", (request, _reply, done) => {
|
|
553
|
+
if (anyFastifyInstrumentationEnabled()) {
|
|
554
|
+
setRouteOnRpcMetadata(request);
|
|
555
|
+
rememberRequestContext(request);
|
|
556
|
+
}
|
|
557
|
+
done();
|
|
558
|
+
});
|
|
559
|
+
if (lifecycleSpansEnabled()) {
|
|
560
|
+
installLifecycleSpans(fastify, anyEnabledTracer);
|
|
561
|
+
} else {
|
|
562
|
+
noteInstanceWithoutSpans();
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
function setRouteOnRpcMetadata(request) {
|
|
566
|
+
try {
|
|
567
|
+
const route = request.routeOptions?.url;
|
|
568
|
+
if (!route) {
|
|
569
|
+
return;
|
|
570
|
+
}
|
|
571
|
+
const metadata = getRPCMetadata(context.active());
|
|
572
|
+
if (metadata?.type === RPCType.HTTP) {
|
|
573
|
+
metadata.route = route;
|
|
574
|
+
}
|
|
575
|
+
} catch {
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
// src/fastify.ts
|
|
580
|
+
var kMetricsPluginRegistered = /* @__PURE__ */ Symbol.for("sherlock.node.fastify.metricsPlugin");
|
|
581
|
+
function metricsPlugin(options = {}) {
|
|
582
|
+
const plugin = (instance, _opts, done) => {
|
|
583
|
+
if (instance[kMetricsPluginRegistered]) {
|
|
584
|
+
diag.warn("sherlock fastify adapter: metricsPlugin is already registered; ignoring this one");
|
|
585
|
+
done();
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
instance[kMetricsPluginRegistered] = true;
|
|
589
|
+
const watchRequest = (rawRequest, rawReply, hookDone) => {
|
|
590
|
+
const request = rawRequest;
|
|
591
|
+
const reply = rawReply;
|
|
592
|
+
try {
|
|
593
|
+
if (!isIgnoredPath(request.originalUrl ?? request.url) && !shouldIgnoreRequest(options.ignoreRequest, request)) {
|
|
594
|
+
watchResponse(request, reply, options);
|
|
595
|
+
}
|
|
596
|
+
} catch (err) {
|
|
597
|
+
diag.warn("sherlock fastify adapter: could not watch the request", err);
|
|
598
|
+
}
|
|
599
|
+
hookDone();
|
|
600
|
+
};
|
|
601
|
+
instance.addHook("onRequest", Object.assign(watchRequest, { [kLeaveUnwrapped]: true }));
|
|
602
|
+
done();
|
|
603
|
+
};
|
|
604
|
+
return Object.assign(plugin, {
|
|
605
|
+
[/* @__PURE__ */ Symbol.for("skip-override")]: true,
|
|
606
|
+
[/* @__PURE__ */ Symbol.for("fastify.display-name")]: "@sherlock-labs/node/fastify"
|
|
607
|
+
});
|
|
608
|
+
}
|
|
609
|
+
function watchResponse(request, reply, options) {
|
|
610
|
+
const res = reply.raw;
|
|
611
|
+
const startedAt = performance.now();
|
|
612
|
+
let recorded = false;
|
|
613
|
+
const record = (finished) => {
|
|
614
|
+
if (recorded) {
|
|
615
|
+
return;
|
|
616
|
+
}
|
|
617
|
+
recorded = true;
|
|
618
|
+
try {
|
|
619
|
+
const durationSeconds = (performance.now() - startedAt) / 1e3;
|
|
620
|
+
if (ignoredByResponse(options.ignoreResponse, request, reply)) {
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
const route = capRoute(options.routeName?.(request) ?? request.routeOptions?.url);
|
|
624
|
+
const statusCode = recordedStatusCode(res, finished);
|
|
625
|
+
recordHttpRequest(
|
|
626
|
+
{
|
|
627
|
+
route,
|
|
628
|
+
method: request.method ?? "UNKNOWN",
|
|
629
|
+
status_code: statusCode,
|
|
630
|
+
status: statusCode >= 500 ? "error" : "ok"
|
|
631
|
+
},
|
|
632
|
+
durationSeconds,
|
|
633
|
+
options.recordExemplars !== false
|
|
634
|
+
);
|
|
635
|
+
} catch (err) {
|
|
636
|
+
diag.warn("sherlock fastify adapter: metrics recording failed", err);
|
|
637
|
+
}
|
|
638
|
+
};
|
|
639
|
+
res.on("finish", () => record(true));
|
|
640
|
+
res.on("close", () => record(false));
|
|
641
|
+
}
|
|
642
|
+
function ignoredByResponse(predicate, request, reply) {
|
|
643
|
+
if (!predicate) {
|
|
644
|
+
return false;
|
|
645
|
+
}
|
|
646
|
+
try {
|
|
647
|
+
return predicate(request, reply) === true;
|
|
648
|
+
} catch (err) {
|
|
649
|
+
diag.warn("sherlock: ignoreResponse predicate threw \u2014 recording the request anyway", err);
|
|
650
|
+
return false;
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
export { FastifyInstrumentation, metricsPlugin };
|
|
655
|
+
//# sourceMappingURL=fastify.mjs.map
|
|
656
|
+
//# sourceMappingURL=fastify.mjs.map
|