@sentry/node 9.19.0 → 9.21.0
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/build/cjs/integrations/anr/index.js +1 -1
- package/build/cjs/integrations/http/SentryHttpInstrumentation.js +93 -76
- package/build/cjs/integrations/http/SentryHttpInstrumentation.js.map +1 -1
- package/build/cjs/integrations/http/index.js.map +1 -1
- package/build/cjs/integrations/local-variables/local-variables-async.js +1 -1
- package/build/cjs/integrations/node-fetch/SentryNodeFetchInstrumentation.js +29 -10
- package/build/cjs/integrations/node-fetch/SentryNodeFetchInstrumentation.js.map +1 -1
- package/build/cjs/integrations/tracing/fastify/fastify-otel/index.js +489 -0
- package/build/cjs/integrations/tracing/fastify/fastify-otel/index.js.map +1 -0
- package/build/cjs/integrations/tracing/fastify/index.js +2 -2
- package/build/cjs/integrations/tracing/fastify/index.js.map +1 -1
- package/build/esm/integrations/anr/index.js +1 -1
- package/build/esm/integrations/anr/worker-script.js +2 -2
- package/build/esm/integrations/http/SentryHttpInstrumentation.js +94 -77
- package/build/esm/integrations/http/SentryHttpInstrumentation.js.map +1 -1
- package/build/esm/integrations/http/index.js.map +1 -1
- package/build/esm/integrations/local-variables/local-variables-async.js +1 -1
- package/build/esm/integrations/local-variables/worker-script.js +2 -2
- package/build/esm/integrations/node-fetch/SentryNodeFetchInstrumentation.js +30 -11
- package/build/esm/integrations/node-fetch/SentryNodeFetchInstrumentation.js.map +1 -1
- package/build/esm/integrations/tracing/fastify/fastify-otel/index.js +487 -0
- package/build/esm/integrations/tracing/fastify/fastify-otel/index.js.map +1 -0
- package/build/esm/integrations/tracing/fastify/index.js +1 -1
- package/build/esm/integrations/tracing/fastify/index.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/types/integrations/http/SentryHttpInstrumentation.d.ts +20 -0
- package/build/types/integrations/http/SentryHttpInstrumentation.d.ts.map +1 -1
- package/build/types/integrations/http/index.d.ts +15 -0
- package/build/types/integrations/http/index.d.ts.map +1 -1
- package/build/types/integrations/node-fetch/SentryNodeFetchInstrumentation.d.ts +5 -0
- package/build/types/integrations/node-fetch/SentryNodeFetchInstrumentation.d.ts.map +1 -1
- package/build/types/integrations/tracing/fastify/index.d.ts.map +1 -1
- package/build/types-ts3.8/integrations/http/SentryHttpInstrumentation.d.ts +20 -0
- package/build/types-ts3.8/integrations/http/index.d.ts +15 -0
- package/build/types-ts3.8/integrations/node-fetch/SentryNodeFetchInstrumentation.d.ts +5 -0
- package/package.json +5 -5
- package/build/types/integrations/http/utils.d.ts +0 -14
- package/build/types/integrations/http/utils.d.ts.map +0 -1
- package/build/types-ts3.8/integrations/http/utils.d.ts +0 -14
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { context } from '@opentelemetry/api';
|
|
2
|
+
import { VERSION, isTracingSuppressed } from '@opentelemetry/core';
|
|
2
3
|
import { InstrumentationBase } from '@opentelemetry/instrumentation';
|
|
3
4
|
import { LRUMap, getClient, getTraceData, getBreadcrumbLogLevelFromHttpStatusCode, addBreadcrumb, parseUrl, getSanitizedUrlString } from '@sentry/core';
|
|
4
5
|
import { shouldPropagateTraceForUrl } from '@sentry/opentelemetry';
|
|
@@ -30,6 +31,7 @@ class SentryNodeFetchInstrumentation extends InstrumentationBase {
|
|
|
30
31
|
super('@sentry/instrumentation-node-fetch', VERSION, config);
|
|
31
32
|
this._channelSubs = [];
|
|
32
33
|
this._propagationDecisionMap = new LRUMap(100);
|
|
34
|
+
this._ignoreOutgoingRequestsMap = new WeakMap();
|
|
33
35
|
}
|
|
34
36
|
|
|
35
37
|
/** No need to instrument files/modules. */
|
|
@@ -82,15 +84,17 @@ class SentryNodeFetchInstrumentation extends InstrumentationBase {
|
|
|
82
84
|
return;
|
|
83
85
|
}
|
|
84
86
|
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
87
|
+
const shouldIgnore = this._shouldIgnoreOutgoingRequest(request);
|
|
88
|
+
// We store this decisision for later so we do not need to re-evaluate it
|
|
89
|
+
// Additionally, the active context is not correct in _onResponseHeaders, so we need to make sure it is evaluated here
|
|
90
|
+
this._ignoreOutgoingRequestsMap.set(request, shouldIgnore);
|
|
89
91
|
|
|
90
92
|
if (shouldIgnore) {
|
|
91
93
|
return;
|
|
92
94
|
}
|
|
93
95
|
|
|
96
|
+
const url = getAbsoluteUrl(request.origin, request.path);
|
|
97
|
+
|
|
94
98
|
// Manually add the trace headers, if it applies
|
|
95
99
|
// Note: We do not use `propagation.inject()` here, because our propagator relies on an active span
|
|
96
100
|
// Which we do not have in this case
|
|
@@ -161,13 +165,9 @@ class SentryNodeFetchInstrumentation extends InstrumentationBase {
|
|
|
161
165
|
const _breadcrumbs = config.breadcrumbs;
|
|
162
166
|
const breadCrumbsEnabled = typeof _breadcrumbs === 'undefined' ? true : _breadcrumbs;
|
|
163
167
|
|
|
164
|
-
const
|
|
165
|
-
const shouldCreateBreadcrumb =
|
|
166
|
-
typeof _ignoreOutgoingRequests === 'function'
|
|
167
|
-
? !_ignoreOutgoingRequests(getAbsoluteUrl(request.origin, request.path))
|
|
168
|
-
: true;
|
|
168
|
+
const shouldIgnore = this._ignoreOutgoingRequestsMap.get(request);
|
|
169
169
|
|
|
170
|
-
if (breadCrumbsEnabled &&
|
|
170
|
+
if (breadCrumbsEnabled && !shouldIgnore) {
|
|
171
171
|
addRequestBreadcrumb(request, response);
|
|
172
172
|
}
|
|
173
173
|
}
|
|
@@ -196,6 +196,25 @@ class SentryNodeFetchInstrumentation extends InstrumentationBase {
|
|
|
196
196
|
unsubscribe,
|
|
197
197
|
});
|
|
198
198
|
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Check if the given outgoing request should be ignored.
|
|
202
|
+
*/
|
|
203
|
+
_shouldIgnoreOutgoingRequest(request) {
|
|
204
|
+
if (isTracingSuppressed(context.active())) {
|
|
205
|
+
return true;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// Add trace propagation headers
|
|
209
|
+
const url = getAbsoluteUrl(request.origin, request.path);
|
|
210
|
+
const ignoreOutgoingRequests = this.getConfig().ignoreOutgoingRequests;
|
|
211
|
+
|
|
212
|
+
if (typeof ignoreOutgoingRequests !== 'function' || !url) {
|
|
213
|
+
return false;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
return ignoreOutgoingRequests(url);
|
|
217
|
+
}
|
|
199
218
|
}
|
|
200
219
|
|
|
201
220
|
/** Add a breadcrumb for outgoing requests. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SentryNodeFetchInstrumentation.js","sources":["../../../../src/integrations/node-fetch/SentryNodeFetchInstrumentation.ts"],"sourcesContent":["import { VERSION } from '@opentelemetry/core';\nimport type { InstrumentationConfig } from '@opentelemetry/instrumentation';\nimport { InstrumentationBase } from '@opentelemetry/instrumentation';\nimport type { SanitizedRequestData } from '@sentry/core';\nimport {\n addBreadcrumb,\n getBreadcrumbLogLevelFromHttpStatusCode,\n getClient,\n getSanitizedUrlString,\n getTraceData,\n LRUMap,\n parseUrl,\n} from '@sentry/core';\nimport { shouldPropagateTraceForUrl } from '@sentry/opentelemetry';\nimport * as diagch from 'diagnostics_channel';\nimport { NODE_MAJOR, NODE_MINOR } from '../../nodeVersion';\nimport { mergeBaggageHeaders } from '../../utils/baggage';\nimport type { UndiciRequest, UndiciResponse } from './types';\n\nconst SENTRY_TRACE_HEADER = 'sentry-trace';\nconst SENTRY_BAGGAGE_HEADER = 'baggage';\n\n// For baggage, we make sure to merge this into a possibly existing header\nconst BAGGAGE_HEADER_REGEX = /baggage: (.*)\\r\\n/;\n\nexport type SentryNodeFetchInstrumentationOptions = InstrumentationConfig & {\n /**\n * Whether breadcrumbs should be recorded for requests.\n *\n * @default `true`\n */\n breadcrumbs?: boolean;\n\n /**\n * Do not capture breadcrumbs or inject headers for outgoing fetch requests to URLs where the given callback returns `true`.\n * The same option can be passed to the top-level httpIntegration where it controls both, breadcrumb and\n * span creation.\n *\n * @param url Contains the entire URL, including query string (if any), protocol, host, etc. of the outgoing request.\n */\n ignoreOutgoingRequests?: (url: string) => boolean;\n};\n\ninterface ListenerRecord {\n name: string;\n unsubscribe: () => void;\n}\n\n/**\n * This custom node-fetch instrumentation is used to instrument outgoing fetch requests.\n * It does not emit any spans.\n *\n * The reason this is isolated from the OpenTelemetry instrumentation is that users may overwrite this,\n * which would lead to Sentry not working as expected.\n *\n * This is heavily inspired & adapted from:\n * https://github.com/open-telemetry/opentelemetry-js-contrib/blob/28e209a9da36bc4e1f8c2b0db7360170ed46cb80/plugins/node/instrumentation-undici/src/undici.ts\n */\nexport class SentryNodeFetchInstrumentation extends InstrumentationBase<SentryNodeFetchInstrumentationOptions> {\n // Keep ref to avoid https://github.com/nodejs/node/issues/42170 bug and for\n // unsubscribing.\n private _channelSubs: Array<ListenerRecord>;\n private _propagationDecisionMap: LRUMap<string, boolean>;\n\n public constructor(config: SentryNodeFetchInstrumentationOptions = {}) {\n super('@sentry/instrumentation-node-fetch', VERSION, config);\n this._channelSubs = [];\n this._propagationDecisionMap = new LRUMap<string, boolean>(100);\n }\n\n /** No need to instrument files/modules. */\n public init(): void {\n return undefined;\n }\n\n /** Disable the instrumentation. */\n public disable(): void {\n super.disable();\n this._channelSubs.forEach(sub => sub.unsubscribe());\n this._channelSubs = [];\n }\n\n /** Enable the instrumentation. */\n public enable(): void {\n // \"enabled\" handling is currently a bit messy with InstrumentationBase.\n // If constructed with `{enabled: false}`, this `.enable()` is still called,\n // and `this.getConfig().enabled !== this.isEnabled()`, creating confusion.\n //\n // For now, this class will setup for instrumenting if `.enable()` is\n // called, but use `this.getConfig().enabled` to determine if\n // instrumentation should be generated. This covers the more likely common\n // case of config being given a construction time, rather than later via\n // `instance.enable()`, `.disable()`, or `.setConfig()` calls.\n super.enable();\n\n // This method is called by the super-class constructor before ours is\n // called. So we need to ensure the property is initalized.\n this._channelSubs = this._channelSubs || [];\n\n // Avoid to duplicate subscriptions\n if (this._channelSubs.length > 0) {\n return;\n }\n\n this._subscribeToChannel('undici:request:create', this._onRequestCreated.bind(this));\n this._subscribeToChannel('undici:request:headers', this._onResponseHeaders.bind(this));\n }\n\n /**\n * This method is called when a request is created.\n * You can still mutate the request here before it is sent.\n */\n private _onRequestCreated({ request }: { request: UndiciRequest }): void {\n const config = this.getConfig();\n const enabled = config.enabled !== false;\n\n if (!enabled) {\n return;\n }\n\n // Add trace propagation headers\n const url = getAbsoluteUrl(request.origin, request.path);\n const _ignoreOutgoingRequests = config.ignoreOutgoingRequests;\n const shouldIgnore = _ignoreOutgoingRequests && url && _ignoreOutgoingRequests(url);\n\n if (shouldIgnore) {\n return;\n }\n\n // Manually add the trace headers, if it applies\n // Note: We do not use `propagation.inject()` here, because our propagator relies on an active span\n // Which we do not have in this case\n // The propagator _may_ overwrite this, but this should be fine as it is the same data\n const tracePropagationTargets = getClient()?.getOptions().tracePropagationTargets;\n const addedHeaders = shouldPropagateTraceForUrl(url, tracePropagationTargets, this._propagationDecisionMap)\n ? getTraceData()\n : undefined;\n\n if (!addedHeaders) {\n return;\n }\n\n const { 'sentry-trace': sentryTrace, baggage } = addedHeaders;\n\n // We do not want to overwrite existing headers here\n // If the core UndiciInstrumentation is registered, it will already have set the headers\n // We do not want to add any then\n if (Array.isArray(request.headers)) {\n const requestHeaders = request.headers;\n\n // We do not want to overwrite existing header here, if it was already set\n if (sentryTrace && !requestHeaders.includes(SENTRY_TRACE_HEADER)) {\n requestHeaders.push(SENTRY_TRACE_HEADER, sentryTrace);\n }\n\n // For baggage, we make sure to merge this into a possibly existing header\n const existingBaggagePos = requestHeaders.findIndex(header => header === SENTRY_BAGGAGE_HEADER);\n if (baggage && existingBaggagePos === -1) {\n requestHeaders.push(SENTRY_BAGGAGE_HEADER, baggage);\n } else if (baggage) {\n const existingBaggage = requestHeaders[existingBaggagePos + 1];\n const merged = mergeBaggageHeaders(existingBaggage, baggage);\n if (merged) {\n requestHeaders[existingBaggagePos + 1] = merged;\n }\n }\n } else {\n const requestHeaders = request.headers;\n // We do not want to overwrite existing header here, if it was already set\n if (sentryTrace && !requestHeaders.includes(`${SENTRY_TRACE_HEADER}:`)) {\n request.headers += `${SENTRY_TRACE_HEADER}: ${sentryTrace}\\r\\n`;\n }\n\n const existingBaggage = request.headers.match(BAGGAGE_HEADER_REGEX)?.[1];\n if (baggage && !existingBaggage) {\n request.headers += `${SENTRY_BAGGAGE_HEADER}: ${baggage}\\r\\n`;\n } else if (baggage) {\n const merged = mergeBaggageHeaders(existingBaggage, baggage);\n if (merged) {\n request.headers = request.headers.replace(BAGGAGE_HEADER_REGEX, `baggage: ${merged}\\r\\n`);\n }\n }\n }\n }\n\n /**\n * This method is called when a response is received.\n */\n private _onResponseHeaders({ request, response }: { request: UndiciRequest; response: UndiciResponse }): void {\n const config = this.getConfig();\n const enabled = config.enabled !== false;\n\n if (!enabled) {\n return;\n }\n\n const _breadcrumbs = config.breadcrumbs;\n const breadCrumbsEnabled = typeof _breadcrumbs === 'undefined' ? true : _breadcrumbs;\n\n const _ignoreOutgoingRequests = config.ignoreOutgoingRequests;\n const shouldCreateBreadcrumb =\n typeof _ignoreOutgoingRequests === 'function'\n ? !_ignoreOutgoingRequests(getAbsoluteUrl(request.origin, request.path))\n : true;\n\n if (breadCrumbsEnabled && shouldCreateBreadcrumb) {\n addRequestBreadcrumb(request, response);\n }\n }\n\n /** Subscribe to a diagnostics channel. */\n private _subscribeToChannel(\n diagnosticChannel: string,\n onMessage: (message: unknown, name: string | symbol) => void,\n ): void {\n // `diagnostics_channel` had a ref counting bug until v18.19.0.\n // https://github.com/nodejs/node/pull/47520\n const useNewSubscribe = NODE_MAJOR > 18 || (NODE_MAJOR === 18 && NODE_MINOR >= 19);\n\n let unsubscribe: () => void;\n if (useNewSubscribe) {\n diagch.subscribe?.(diagnosticChannel, onMessage);\n unsubscribe = () => diagch.unsubscribe?.(diagnosticChannel, onMessage);\n } else {\n const channel = diagch.channel(diagnosticChannel);\n channel.subscribe(onMessage);\n unsubscribe = () => channel.unsubscribe(onMessage);\n }\n\n this._channelSubs.push({\n name: diagnosticChannel,\n unsubscribe,\n });\n }\n}\n\n/** Add a breadcrumb for outgoing requests. */\nfunction addRequestBreadcrumb(request: UndiciRequest, response: UndiciResponse): void {\n const data = getBreadcrumbData(request);\n\n const statusCode = response.statusCode;\n const level = getBreadcrumbLogLevelFromHttpStatusCode(statusCode);\n\n addBreadcrumb(\n {\n category: 'http',\n data: {\n status_code: statusCode,\n ...data,\n },\n type: 'http',\n level,\n },\n {\n event: 'response',\n request,\n response,\n },\n );\n}\n\nfunction getBreadcrumbData(request: UndiciRequest): Partial<SanitizedRequestData> {\n try {\n const url = getAbsoluteUrl(request.origin, request.path);\n const parsedUrl = parseUrl(url);\n\n const data: Partial<SanitizedRequestData> = {\n url: getSanitizedUrlString(parsedUrl),\n 'http.method': request.method || 'GET',\n };\n\n if (parsedUrl.search) {\n data['http.query'] = parsedUrl.search;\n }\n if (parsedUrl.hash) {\n data['http.fragment'] = parsedUrl.hash;\n }\n\n return data;\n } catch {\n return {};\n }\n}\n\nfunction getAbsoluteUrl(origin: string, path: string = '/'): string {\n try {\n const url = new URL(path, origin);\n return url.toString();\n } catch {\n // fallback: Construct it on our own\n const url = `${origin}`;\n\n if (url.endsWith('/') && path.startsWith('/')) {\n return `${url}${path.slice(1)}`;\n }\n\n if (!url.endsWith('/') && !path.startsWith('/')) {\n return `${url}/${path.slice(1)}`;\n }\n\n return `${url}${path}`;\n }\n}\n"],"names":[],"mappings":";;;;;;;;AAmBA,MAAM,mBAAA,GAAsB,cAAc;AAC1C,MAAM,qBAAA,GAAwB,SAAS;;AAEvC;AACA,MAAM,oBAAA,GAAuB,mBAAmB;;AAyBhD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,8BAAA,SAAuC,mBAAmB,CAAwC;AAC/G;AACA;;AAIA,GAAS,WAAW,CAAC,MAAM,GAA0C,EAAE,EAAE;AACzE,IAAI,KAAK,CAAC,oCAAoC,EAAE,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AAA,EAAA,MAAA,CAAA,CAAA;;AAEA,IAAA,IAAA,GAAA,CAAA,QAAA,CAAA,GAAA,CAAA,IAAA,IAAA,CAAA,UAAA,CAAA,GAAA,CAAA,EAAA;AACA,MAAA,OAAA,CAAA,EAAA,GAAA,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AACA;;AAEA,IAAA,IAAA,CAAA,GAAA,CAAA,QAAA,CAAA,GAAA,CAAA,IAAA,CAAA,IAAA,CAAA,UAAA,CAAA,GAAA,CAAA,EAAA;AACA,MAAA,OAAA,CAAA,EAAA,GAAA,CAAA,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AACA;;AAEA,IAAA,OAAA,CAAA,EAAA,GAAA,CAAA,EAAA,IAAA,CAAA,CAAA;AACA;AACA;;;;"}
|
|
1
|
+
{"version":3,"file":"SentryNodeFetchInstrumentation.js","sources":["../../../../src/integrations/node-fetch/SentryNodeFetchInstrumentation.ts"],"sourcesContent":["import { context } from '@opentelemetry/api';\nimport { isTracingSuppressed, VERSION } from '@opentelemetry/core';\nimport type { InstrumentationConfig } from '@opentelemetry/instrumentation';\nimport { InstrumentationBase } from '@opentelemetry/instrumentation';\nimport type { SanitizedRequestData } from '@sentry/core';\nimport {\n addBreadcrumb,\n getBreadcrumbLogLevelFromHttpStatusCode,\n getClient,\n getSanitizedUrlString,\n getTraceData,\n LRUMap,\n parseUrl,\n} from '@sentry/core';\nimport { shouldPropagateTraceForUrl } from '@sentry/opentelemetry';\nimport * as diagch from 'diagnostics_channel';\nimport { NODE_MAJOR, NODE_MINOR } from '../../nodeVersion';\nimport { mergeBaggageHeaders } from '../../utils/baggage';\nimport type { UndiciRequest, UndiciResponse } from './types';\n\nconst SENTRY_TRACE_HEADER = 'sentry-trace';\nconst SENTRY_BAGGAGE_HEADER = 'baggage';\n\n// For baggage, we make sure to merge this into a possibly existing header\nconst BAGGAGE_HEADER_REGEX = /baggage: (.*)\\r\\n/;\n\nexport type SentryNodeFetchInstrumentationOptions = InstrumentationConfig & {\n /**\n * Whether breadcrumbs should be recorded for requests.\n *\n * @default `true`\n */\n breadcrumbs?: boolean;\n\n /**\n * Do not capture breadcrumbs or inject headers for outgoing fetch requests to URLs where the given callback returns `true`.\n * The same option can be passed to the top-level httpIntegration where it controls both, breadcrumb and\n * span creation.\n *\n * @param url Contains the entire URL, including query string (if any), protocol, host, etc. of the outgoing request.\n */\n ignoreOutgoingRequests?: (url: string) => boolean;\n};\n\ninterface ListenerRecord {\n name: string;\n unsubscribe: () => void;\n}\n\n/**\n * This custom node-fetch instrumentation is used to instrument outgoing fetch requests.\n * It does not emit any spans.\n *\n * The reason this is isolated from the OpenTelemetry instrumentation is that users may overwrite this,\n * which would lead to Sentry not working as expected.\n *\n * This is heavily inspired & adapted from:\n * https://github.com/open-telemetry/opentelemetry-js-contrib/blob/28e209a9da36bc4e1f8c2b0db7360170ed46cb80/plugins/node/instrumentation-undici/src/undici.ts\n */\nexport class SentryNodeFetchInstrumentation extends InstrumentationBase<SentryNodeFetchInstrumentationOptions> {\n // Keep ref to avoid https://github.com/nodejs/node/issues/42170 bug and for\n // unsubscribing.\n private _channelSubs: Array<ListenerRecord>;\n private _propagationDecisionMap: LRUMap<string, boolean>;\n private _ignoreOutgoingRequestsMap: WeakMap<UndiciRequest, boolean>;\n\n public constructor(config: SentryNodeFetchInstrumentationOptions = {}) {\n super('@sentry/instrumentation-node-fetch', VERSION, config);\n this._channelSubs = [];\n this._propagationDecisionMap = new LRUMap<string, boolean>(100);\n this._ignoreOutgoingRequestsMap = new WeakMap<UndiciRequest, boolean>();\n }\n\n /** No need to instrument files/modules. */\n public init(): void {\n return undefined;\n }\n\n /** Disable the instrumentation. */\n public disable(): void {\n super.disable();\n this._channelSubs.forEach(sub => sub.unsubscribe());\n this._channelSubs = [];\n }\n\n /** Enable the instrumentation. */\n public enable(): void {\n // \"enabled\" handling is currently a bit messy with InstrumentationBase.\n // If constructed with `{enabled: false}`, this `.enable()` is still called,\n // and `this.getConfig().enabled !== this.isEnabled()`, creating confusion.\n //\n // For now, this class will setup for instrumenting if `.enable()` is\n // called, but use `this.getConfig().enabled` to determine if\n // instrumentation should be generated. This covers the more likely common\n // case of config being given a construction time, rather than later via\n // `instance.enable()`, `.disable()`, or `.setConfig()` calls.\n super.enable();\n\n // This method is called by the super-class constructor before ours is\n // called. So we need to ensure the property is initalized.\n this._channelSubs = this._channelSubs || [];\n\n // Avoid to duplicate subscriptions\n if (this._channelSubs.length > 0) {\n return;\n }\n\n this._subscribeToChannel('undici:request:create', this._onRequestCreated.bind(this));\n this._subscribeToChannel('undici:request:headers', this._onResponseHeaders.bind(this));\n }\n\n /**\n * This method is called when a request is created.\n * You can still mutate the request here before it is sent.\n */\n private _onRequestCreated({ request }: { request: UndiciRequest }): void {\n const config = this.getConfig();\n const enabled = config.enabled !== false;\n\n if (!enabled) {\n return;\n }\n\n const shouldIgnore = this._shouldIgnoreOutgoingRequest(request);\n // We store this decisision for later so we do not need to re-evaluate it\n // Additionally, the active context is not correct in _onResponseHeaders, so we need to make sure it is evaluated here\n this._ignoreOutgoingRequestsMap.set(request, shouldIgnore);\n\n if (shouldIgnore) {\n return;\n }\n\n const url = getAbsoluteUrl(request.origin, request.path);\n\n // Manually add the trace headers, if it applies\n // Note: We do not use `propagation.inject()` here, because our propagator relies on an active span\n // Which we do not have in this case\n // The propagator _may_ overwrite this, but this should be fine as it is the same data\n const tracePropagationTargets = getClient()?.getOptions().tracePropagationTargets;\n const addedHeaders = shouldPropagateTraceForUrl(url, tracePropagationTargets, this._propagationDecisionMap)\n ? getTraceData()\n : undefined;\n\n if (!addedHeaders) {\n return;\n }\n\n const { 'sentry-trace': sentryTrace, baggage } = addedHeaders;\n\n // We do not want to overwrite existing headers here\n // If the core UndiciInstrumentation is registered, it will already have set the headers\n // We do not want to add any then\n if (Array.isArray(request.headers)) {\n const requestHeaders = request.headers;\n\n // We do not want to overwrite existing header here, if it was already set\n if (sentryTrace && !requestHeaders.includes(SENTRY_TRACE_HEADER)) {\n requestHeaders.push(SENTRY_TRACE_HEADER, sentryTrace);\n }\n\n // For baggage, we make sure to merge this into a possibly existing header\n const existingBaggagePos = requestHeaders.findIndex(header => header === SENTRY_BAGGAGE_HEADER);\n if (baggage && existingBaggagePos === -1) {\n requestHeaders.push(SENTRY_BAGGAGE_HEADER, baggage);\n } else if (baggage) {\n const existingBaggage = requestHeaders[existingBaggagePos + 1];\n const merged = mergeBaggageHeaders(existingBaggage, baggage);\n if (merged) {\n requestHeaders[existingBaggagePos + 1] = merged;\n }\n }\n } else {\n const requestHeaders = request.headers;\n // We do not want to overwrite existing header here, if it was already set\n if (sentryTrace && !requestHeaders.includes(`${SENTRY_TRACE_HEADER}:`)) {\n request.headers += `${SENTRY_TRACE_HEADER}: ${sentryTrace}\\r\\n`;\n }\n\n const existingBaggage = request.headers.match(BAGGAGE_HEADER_REGEX)?.[1];\n if (baggage && !existingBaggage) {\n request.headers += `${SENTRY_BAGGAGE_HEADER}: ${baggage}\\r\\n`;\n } else if (baggage) {\n const merged = mergeBaggageHeaders(existingBaggage, baggage);\n if (merged) {\n request.headers = request.headers.replace(BAGGAGE_HEADER_REGEX, `baggage: ${merged}\\r\\n`);\n }\n }\n }\n }\n\n /**\n * This method is called when a response is received.\n */\n private _onResponseHeaders({ request, response }: { request: UndiciRequest; response: UndiciResponse }): void {\n const config = this.getConfig();\n const enabled = config.enabled !== false;\n\n if (!enabled) {\n return;\n }\n\n const _breadcrumbs = config.breadcrumbs;\n const breadCrumbsEnabled = typeof _breadcrumbs === 'undefined' ? true : _breadcrumbs;\n\n const shouldIgnore = this._ignoreOutgoingRequestsMap.get(request);\n\n if (breadCrumbsEnabled && !shouldIgnore) {\n addRequestBreadcrumb(request, response);\n }\n }\n\n /** Subscribe to a diagnostics channel. */\n private _subscribeToChannel(\n diagnosticChannel: string,\n onMessage: (message: unknown, name: string | symbol) => void,\n ): void {\n // `diagnostics_channel` had a ref counting bug until v18.19.0.\n // https://github.com/nodejs/node/pull/47520\n const useNewSubscribe = NODE_MAJOR > 18 || (NODE_MAJOR === 18 && NODE_MINOR >= 19);\n\n let unsubscribe: () => void;\n if (useNewSubscribe) {\n diagch.subscribe?.(diagnosticChannel, onMessage);\n unsubscribe = () => diagch.unsubscribe?.(diagnosticChannel, onMessage);\n } else {\n const channel = diagch.channel(diagnosticChannel);\n channel.subscribe(onMessage);\n unsubscribe = () => channel.unsubscribe(onMessage);\n }\n\n this._channelSubs.push({\n name: diagnosticChannel,\n unsubscribe,\n });\n }\n\n /**\n * Check if the given outgoing request should be ignored.\n */\n private _shouldIgnoreOutgoingRequest(request: UndiciRequest): boolean {\n if (isTracingSuppressed(context.active())) {\n return true;\n }\n\n // Add trace propagation headers\n const url = getAbsoluteUrl(request.origin, request.path);\n const ignoreOutgoingRequests = this.getConfig().ignoreOutgoingRequests;\n\n if (typeof ignoreOutgoingRequests !== 'function' || !url) {\n return false;\n }\n\n return ignoreOutgoingRequests(url);\n }\n}\n\n/** Add a breadcrumb for outgoing requests. */\nfunction addRequestBreadcrumb(request: UndiciRequest, response: UndiciResponse): void {\n const data = getBreadcrumbData(request);\n\n const statusCode = response.statusCode;\n const level = getBreadcrumbLogLevelFromHttpStatusCode(statusCode);\n\n addBreadcrumb(\n {\n category: 'http',\n data: {\n status_code: statusCode,\n ...data,\n },\n type: 'http',\n level,\n },\n {\n event: 'response',\n request,\n response,\n },\n );\n}\n\nfunction getBreadcrumbData(request: UndiciRequest): Partial<SanitizedRequestData> {\n try {\n const url = getAbsoluteUrl(request.origin, request.path);\n const parsedUrl = parseUrl(url);\n\n const data: Partial<SanitizedRequestData> = {\n url: getSanitizedUrlString(parsedUrl),\n 'http.method': request.method || 'GET',\n };\n\n if (parsedUrl.search) {\n data['http.query'] = parsedUrl.search;\n }\n if (parsedUrl.hash) {\n data['http.fragment'] = parsedUrl.hash;\n }\n\n return data;\n } catch {\n return {};\n }\n}\n\nfunction getAbsoluteUrl(origin: string, path: string = '/'): string {\n try {\n const url = new URL(path, origin);\n return url.toString();\n } catch {\n // fallback: Construct it on our own\n const url = `${origin}`;\n\n if (url.endsWith('/') && path.startsWith('/')) {\n return `${url}${path.slice(1)}`;\n }\n\n if (!url.endsWith('/') && !path.startsWith('/')) {\n return `${url}/${path.slice(1)}`;\n }\n\n return `${url}${path}`;\n }\n}\n"],"names":[],"mappings":";;;;;;;;;AAoBA,MAAM,mBAAA,GAAsB,cAAc;AAC1C,MAAM,qBAAA,GAAwB,SAAS;;AAEvC;AACA,MAAM,oBAAA,GAAuB,mBAAmB;;AAyBhD;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAM,8BAAA,SAAuC,mBAAmB,CAAwC;AAC/G;AACA;;AAKA,GAAS,WAAW,CAAC,MAAM,GAA0C,EAAE,EAAE;AACzE,IAAI,KAAK,CAAC,oCAAoC,EAAE,OAAO,EAAE,MAAM,CAAC;AAChE,IAAI,IAAI,CAAC,YAAa,GAAE,EAAE;AAC1B,IAAI,IAAI,CAAC,uBAAwB,GAAE,IAAI,MAAM,CAAkB,GAAG,CAAC;AACnE,IAAI,IAAI,CAAC,0BAAA,GAA6B,IAAI,OAAO,EAA0B;AAC3E;;AAEA;AACA,GAAS,IAAI,GAAS;AACtB,IAAI,OAAO,SAAS;AACpB;;AAEA;AACA,GAAS,OAAO,GAAS;AACzB,IAAI,KAAK,CAAC,OAAO,EAAE;AACnB,IAAI,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,GAAI,IAAG,GAAG,CAAC,WAAW,EAAE,CAAC;AACvD,IAAI,IAAI,CAAC,YAAa,GAAE,EAAE;AAC1B;;AAEA;AACA,GAAS,MAAM,GAAS;AACxB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,IAAI,KAAK,CAAC,MAAM,EAAE;;AAElB;AACA;AACA,IAAI,IAAI,CAAC,YAAa,GAAE,IAAI,CAAC,YAAA,IAAgB,EAAE;;AAE/C;AACA,I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QAAA,CAAA,GAAA,CAAA,IAAA,CAAA,IAAA,CAAA,UAAA,CAAA,GAAA,CAAA,EAAA;AACA,MAAA,OAAA,CAAA,EAAA,GAAA,CAAA,CAAA,EAAA,IAAA,CAAA,KAAA,CAAA,CAAA,CAAA,CAAA,CAAA;AACA;;AAEA,IAAA,OAAA,CAAA,EAAA,GAAA,CAAA,EAAA,IAAA,CAAA,CAAA;AACA;AACA;;;;"}
|
|
@@ -0,0 +1,487 @@
|
|
|
1
|
+
import diagnosticsChannel__default from 'node:diagnostics_channel';
|
|
2
|
+
import { diag, propagation, context, trace, SpanStatusCode } from '@opentelemetry/api';
|
|
3
|
+
import { getRPCMetadata, RPCType } from '@opentelemetry/core';
|
|
4
|
+
import { InstrumentationBase } from '@opentelemetry/instrumentation';
|
|
5
|
+
import { ATTR_HTTP_ROUTE, ATTR_SERVICE_NAME, ATTR_HTTP_REQUEST_METHOD, ATTR_HTTP_RESPONSE_STATUS_CODE } from '@opentelemetry/semantic-conventions';
|
|
6
|
+
|
|
7
|
+
/*
|
|
8
|
+
Vendored in and modified from @fastify/otel version 0.8.0
|
|
9
|
+
https://github.com/fastify/otel/releases/tag/v0.8.0
|
|
10
|
+
|
|
11
|
+
Tried not to modify the original code too much keeping it as a JavaScript CJS module to make it easier to update when required
|
|
12
|
+
|
|
13
|
+
Modifications include:
|
|
14
|
+
- Removed reading of package.json to get the version and package name
|
|
15
|
+
|
|
16
|
+
MIT License
|
|
17
|
+
|
|
18
|
+
Copyright (c) 2024 Fastify
|
|
19
|
+
|
|
20
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
21
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
22
|
+
in the Software without restriction, including without limitation the rights
|
|
23
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
24
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
25
|
+
furnished to do so, subject to the following conditions:
|
|
26
|
+
|
|
27
|
+
The above copyright notice and this permission notice shall be included in all
|
|
28
|
+
copies or substantial portions of the Software.
|
|
29
|
+
|
|
30
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
31
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
32
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
33
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
34
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
35
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
36
|
+
SOFTWARE.
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
// SENTRY VENDOR NOTE
|
|
41
|
+
// Instead of using the package.json file, we hard code the package name and version here.
|
|
42
|
+
const PACKAGE_NAME = '@fastify/otel';
|
|
43
|
+
const PACKAGE_VERSION = '0.8.0';
|
|
44
|
+
|
|
45
|
+
// Constants
|
|
46
|
+
const SUPPORTED_VERSIONS = '>=4.0.0 <6';
|
|
47
|
+
const FASTIFY_HOOKS = [
|
|
48
|
+
'onRequest',
|
|
49
|
+
'preParsing',
|
|
50
|
+
'preValidation',
|
|
51
|
+
'preHandler',
|
|
52
|
+
'preSerialization',
|
|
53
|
+
'onSend',
|
|
54
|
+
'onResponse',
|
|
55
|
+
'onError',
|
|
56
|
+
];
|
|
57
|
+
const ATTRIBUTE_NAMES = {
|
|
58
|
+
HOOK_NAME: 'hook.name',
|
|
59
|
+
FASTIFY_TYPE: 'fastify.type',
|
|
60
|
+
HOOK_CALLBACK_NAME: 'hook.callback.name',
|
|
61
|
+
ROOT: 'fastify.root',
|
|
62
|
+
};
|
|
63
|
+
const HOOK_TYPES = {
|
|
64
|
+
ROUTE: 'route-hook',
|
|
65
|
+
INSTANCE: 'hook',
|
|
66
|
+
HANDLER: 'request-handler',
|
|
67
|
+
};
|
|
68
|
+
const ANONYMOUS_FUNCTION_NAME = 'anonymous';
|
|
69
|
+
|
|
70
|
+
// Symbols
|
|
71
|
+
const kInstrumentation = Symbol('fastify otel instance');
|
|
72
|
+
const kRequestSpan = Symbol('fastify otel request spans');
|
|
73
|
+
const kRequestContext = Symbol('fastify otel request context');
|
|
74
|
+
const kAddHookOriginal = Symbol('fastify otel addhook original');
|
|
75
|
+
const kSetNotFoundOriginal = Symbol('fastify otel setnotfound original');
|
|
76
|
+
const kIgnorePaths = Symbol('fastify otel ignore path');
|
|
77
|
+
|
|
78
|
+
class FastifyOtelInstrumentation extends InstrumentationBase {
|
|
79
|
+
constructor(config) {
|
|
80
|
+
super(PACKAGE_NAME, PACKAGE_VERSION, config);
|
|
81
|
+
this.servername = config?.servername ?? process.env.OTEL_SERVICE_NAME ?? 'fastify';
|
|
82
|
+
this[kIgnorePaths] = null;
|
|
83
|
+
this._logger = diag.createComponentLogger({ namespace: PACKAGE_NAME });
|
|
84
|
+
|
|
85
|
+
if (config?.ignorePaths != null || process.env.OTEL_FASTIFY_IGNORE_PATHS != null) {
|
|
86
|
+
const ignorePaths = config?.ignorePaths ?? process.env.OTEL_FASTIFY_IGNORE_PATHS;
|
|
87
|
+
|
|
88
|
+
if ((typeof ignorePaths !== 'string' || ignorePaths.length === 0) && typeof ignorePaths !== 'function') {
|
|
89
|
+
throw new TypeError('ignorePaths must be a string or a function');
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
let globMatcher = null;
|
|
93
|
+
|
|
94
|
+
this[kIgnorePaths] = routeOptions => {
|
|
95
|
+
if (typeof ignorePaths === 'function') {
|
|
96
|
+
return ignorePaths(routeOptions);
|
|
97
|
+
} else {
|
|
98
|
+
// Using minimatch to match the path until path.matchesGlob is out of experimental
|
|
99
|
+
// path.matchesGlob uses minimatch internally
|
|
100
|
+
if (globMatcher == null) {
|
|
101
|
+
globMatcher = require('minimatch').minimatch;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return globMatcher(routeOptions.url, ignorePaths);
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
enable() {
|
|
111
|
+
if (this._handleInitialization === undefined && this.getConfig().registerOnInitialization) {
|
|
112
|
+
const FastifyInstrumentationPlugin = this.plugin();
|
|
113
|
+
this._handleInitialization = message => {
|
|
114
|
+
message.fastify.register(FastifyInstrumentationPlugin);
|
|
115
|
+
};
|
|
116
|
+
diagnosticsChannel__default.subscribe('fastify.initialization', this._handleInitialization);
|
|
117
|
+
}
|
|
118
|
+
return super.enable();
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
disable() {
|
|
122
|
+
if (this._handleInitialization) {
|
|
123
|
+
diagnosticsChannel__default.unsubscribe('fastify.initialization', this._handleInitialization);
|
|
124
|
+
this._handleInitialization = undefined;
|
|
125
|
+
}
|
|
126
|
+
return super.disable();
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// We do not do patching in this instrumentation
|
|
130
|
+
init() {
|
|
131
|
+
return [];
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
plugin() {
|
|
135
|
+
const instrumentation = this;
|
|
136
|
+
|
|
137
|
+
FastifyInstrumentationPlugin[Symbol.for('skip-override')] = true;
|
|
138
|
+
FastifyInstrumentationPlugin[Symbol.for('fastify.display-name')] = '@fastify/otel';
|
|
139
|
+
FastifyInstrumentationPlugin[Symbol.for('plugin-meta')] = {
|
|
140
|
+
fastify: SUPPORTED_VERSIONS,
|
|
141
|
+
name: '@fastify/otel',
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
return FastifyInstrumentationPlugin;
|
|
145
|
+
|
|
146
|
+
function FastifyInstrumentationPlugin(instance, opts, done) {
|
|
147
|
+
instance.decorate(kInstrumentation, instrumentation);
|
|
148
|
+
// addHook and notfoundHandler are essentially inherited from the prototype
|
|
149
|
+
// what is important is to bound it to the right instance
|
|
150
|
+
instance.decorate(kAddHookOriginal, instance.addHook);
|
|
151
|
+
instance.decorate(kSetNotFoundOriginal, instance.setNotFoundHandler);
|
|
152
|
+
instance.decorateRequest('opentelemetry', function openetelemetry() {
|
|
153
|
+
const ctx = this[kRequestContext];
|
|
154
|
+
const span = this[kRequestSpan];
|
|
155
|
+
return {
|
|
156
|
+
span,
|
|
157
|
+
tracer: instrumentation.tracer,
|
|
158
|
+
context: ctx,
|
|
159
|
+
inject: (carrier, setter) => {
|
|
160
|
+
return propagation.inject(ctx, carrier, setter);
|
|
161
|
+
},
|
|
162
|
+
extract: (carrier, getter) => {
|
|
163
|
+
return propagation.extract(ctx, carrier, getter);
|
|
164
|
+
},
|
|
165
|
+
};
|
|
166
|
+
});
|
|
167
|
+
instance.decorateRequest(kRequestSpan, null);
|
|
168
|
+
instance.decorateRequest(kRequestContext, null);
|
|
169
|
+
|
|
170
|
+
instance.addHook('onRoute', function (routeOptions) {
|
|
171
|
+
if (instrumentation[kIgnorePaths]?.(routeOptions) === true) {
|
|
172
|
+
instrumentation._logger.debug(
|
|
173
|
+
`Ignoring route instrumentation ${routeOptions.method} ${routeOptions.url} because it matches the ignore path`,
|
|
174
|
+
);
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
for (const hook of FASTIFY_HOOKS) {
|
|
179
|
+
if (routeOptions[hook] != null) {
|
|
180
|
+
const handlerLike = routeOptions[hook];
|
|
181
|
+
|
|
182
|
+
if (typeof handlerLike === 'function') {
|
|
183
|
+
routeOptions[hook] = handlerWrapper(handlerLike, {
|
|
184
|
+
[ATTR_SERVICE_NAME]: instance[kInstrumentation].servername,
|
|
185
|
+
[ATTRIBUTE_NAMES.HOOK_NAME]: `${this.pluginName} - route -> ${hook}`,
|
|
186
|
+
[ATTRIBUTE_NAMES.FASTIFY_TYPE]: HOOK_TYPES.ROUTE,
|
|
187
|
+
[ATTR_HTTP_ROUTE]: routeOptions.url,
|
|
188
|
+
[ATTRIBUTE_NAMES.HOOK_CALLBACK_NAME]:
|
|
189
|
+
handlerLike.name?.length > 0 ? handlerLike.name : ANONYMOUS_FUNCTION_NAME /* c8 ignore next */,
|
|
190
|
+
});
|
|
191
|
+
} else if (Array.isArray(handlerLike)) {
|
|
192
|
+
const wrappedHandlers = [];
|
|
193
|
+
|
|
194
|
+
for (const handler of handlerLike) {
|
|
195
|
+
wrappedHandlers.push(
|
|
196
|
+
handlerWrapper(handler, {
|
|
197
|
+
[ATTR_SERVICE_NAME]: instance[kInstrumentation].servername,
|
|
198
|
+
[ATTRIBUTE_NAMES.HOOK_NAME]: `${this.pluginName} - route -> ${hook}`,
|
|
199
|
+
[ATTRIBUTE_NAMES.FASTIFY_TYPE]: HOOK_TYPES.ROUTE,
|
|
200
|
+
[ATTR_HTTP_ROUTE]: routeOptions.url,
|
|
201
|
+
[ATTRIBUTE_NAMES.HOOK_CALLBACK_NAME]:
|
|
202
|
+
handler.name?.length > 0 ? handler.name : ANONYMOUS_FUNCTION_NAME,
|
|
203
|
+
}),
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
routeOptions[hook] = wrappedHandlers;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// We always want to add the onSend hook to the route to be executed last
|
|
213
|
+
if (routeOptions.onSend != null) {
|
|
214
|
+
routeOptions.onSend = Array.isArray(routeOptions.onSend)
|
|
215
|
+
? [...routeOptions.onSend, onSendHook]
|
|
216
|
+
: [routeOptions.onSend, onSendHook];
|
|
217
|
+
} else {
|
|
218
|
+
routeOptions.onSend = onSendHook;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// We always want to add the onError hook to the route to be executed last
|
|
222
|
+
if (routeOptions.onError != null) {
|
|
223
|
+
routeOptions.onError = Array.isArray(routeOptions.onError)
|
|
224
|
+
? [...routeOptions.onError, onErrorHook]
|
|
225
|
+
: [routeOptions.onError, onErrorHook];
|
|
226
|
+
} else {
|
|
227
|
+
routeOptions.onError = onErrorHook;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
routeOptions.handler = handlerWrapper(routeOptions.handler, {
|
|
231
|
+
[ATTR_SERVICE_NAME]: instance[kInstrumentation].servername,
|
|
232
|
+
[ATTRIBUTE_NAMES.HOOK_NAME]: `${this.pluginName} - route-handler`,
|
|
233
|
+
[ATTRIBUTE_NAMES.FASTIFY_TYPE]: HOOK_TYPES.HANDLER,
|
|
234
|
+
[ATTR_HTTP_ROUTE]: routeOptions.url,
|
|
235
|
+
[ATTRIBUTE_NAMES.HOOK_CALLBACK_NAME]:
|
|
236
|
+
routeOptions.handler.name.length > 0 ? routeOptions.handler.name : ANONYMOUS_FUNCTION_NAME,
|
|
237
|
+
});
|
|
238
|
+
});
|
|
239
|
+
|
|
240
|
+
instance.addHook('onRequest', function (request, _reply, hookDone) {
|
|
241
|
+
if (this[kInstrumentation].isEnabled() === false) {
|
|
242
|
+
return hookDone();
|
|
243
|
+
} else if (
|
|
244
|
+
this[kInstrumentation][kIgnorePaths]?.({
|
|
245
|
+
url: request.url,
|
|
246
|
+
method: request.method,
|
|
247
|
+
}) === true
|
|
248
|
+
) {
|
|
249
|
+
this[kInstrumentation]._logger.debug(
|
|
250
|
+
`Ignoring request ${request.method} ${request.url} because it matches the ignore path`,
|
|
251
|
+
);
|
|
252
|
+
return hookDone();
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
let ctx = context.active();
|
|
256
|
+
|
|
257
|
+
if (trace.getSpan(ctx) == null) {
|
|
258
|
+
ctx = propagation.extract(ctx, request.headers);
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const rpcMetadata = getRPCMetadata(ctx);
|
|
262
|
+
|
|
263
|
+
if (request.routeOptions.url != null && rpcMetadata?.type === RPCType.HTTP) {
|
|
264
|
+
rpcMetadata.route = request.routeOptions.url;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** @type {import('@opentelemetry/api').Span} */
|
|
268
|
+
const span = this[kInstrumentation].tracer.startSpan(
|
|
269
|
+
'request',
|
|
270
|
+
{
|
|
271
|
+
attributes: {
|
|
272
|
+
[ATTR_SERVICE_NAME]: instance[kInstrumentation].servername,
|
|
273
|
+
[ATTRIBUTE_NAMES.ROOT]: '@fastify/otel',
|
|
274
|
+
[ATTR_HTTP_ROUTE]: request.url,
|
|
275
|
+
[ATTR_HTTP_REQUEST_METHOD]: request.method,
|
|
276
|
+
},
|
|
277
|
+
},
|
|
278
|
+
ctx,
|
|
279
|
+
);
|
|
280
|
+
|
|
281
|
+
request[kRequestContext] = trace.setSpan(ctx, span);
|
|
282
|
+
request[kRequestSpan] = span;
|
|
283
|
+
|
|
284
|
+
context.with(request[kRequestContext], () => {
|
|
285
|
+
hookDone();
|
|
286
|
+
});
|
|
287
|
+
});
|
|
288
|
+
|
|
289
|
+
// onResponse is the last hook to be executed, only added for 404 handlers
|
|
290
|
+
instance.addHook('onResponse', function (request, reply, hookDone) {
|
|
291
|
+
const span = request[kRequestSpan];
|
|
292
|
+
|
|
293
|
+
if (span != null) {
|
|
294
|
+
span.setStatus({
|
|
295
|
+
code: SpanStatusCode.OK,
|
|
296
|
+
message: 'OK',
|
|
297
|
+
});
|
|
298
|
+
span.setAttributes({
|
|
299
|
+
[ATTR_HTTP_RESPONSE_STATUS_CODE]: 404,
|
|
300
|
+
});
|
|
301
|
+
span.end();
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
request[kRequestSpan] = null;
|
|
305
|
+
|
|
306
|
+
hookDone();
|
|
307
|
+
});
|
|
308
|
+
|
|
309
|
+
instance.addHook = addHookPatched;
|
|
310
|
+
instance.setNotFoundHandler = setNotFoundHandlerPatched;
|
|
311
|
+
|
|
312
|
+
done();
|
|
313
|
+
|
|
314
|
+
function onSendHook(request, reply, payload, hookDone) {
|
|
315
|
+
/** @type {import('@opentelemetry/api').Span} */
|
|
316
|
+
const span = request[kRequestSpan];
|
|
317
|
+
|
|
318
|
+
if (span != null) {
|
|
319
|
+
if (reply.statusCode < 500) {
|
|
320
|
+
span.setStatus({
|
|
321
|
+
code: SpanStatusCode.OK,
|
|
322
|
+
message: 'OK',
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
span.setAttributes({
|
|
327
|
+
[ATTR_HTTP_RESPONSE_STATUS_CODE]: reply.statusCode,
|
|
328
|
+
});
|
|
329
|
+
span.end();
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
request[kRequestSpan] = null;
|
|
333
|
+
|
|
334
|
+
hookDone(null, payload);
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function onErrorHook(request, reply, error, hookDone) {
|
|
338
|
+
/** @type {Span} */
|
|
339
|
+
const span = request[kRequestSpan];
|
|
340
|
+
|
|
341
|
+
if (span != null) {
|
|
342
|
+
span.setStatus({
|
|
343
|
+
code: SpanStatusCode.ERROR,
|
|
344
|
+
message: error.message,
|
|
345
|
+
});
|
|
346
|
+
span.recordException(error);
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
hookDone();
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
function addHookPatched(name, hook) {
|
|
353
|
+
const addHookOriginal = this[kAddHookOriginal];
|
|
354
|
+
|
|
355
|
+
if (FASTIFY_HOOKS.includes(name)) {
|
|
356
|
+
return addHookOriginal.call(
|
|
357
|
+
this,
|
|
358
|
+
name,
|
|
359
|
+
handlerWrapper(hook, {
|
|
360
|
+
[ATTR_SERVICE_NAME]: instance[kInstrumentation].servername,
|
|
361
|
+
[ATTRIBUTE_NAMES.HOOK_NAME]: `${this.pluginName} - ${name}`,
|
|
362
|
+
[ATTRIBUTE_NAMES.FASTIFY_TYPE]: HOOK_TYPES.INSTANCE,
|
|
363
|
+
[ATTRIBUTE_NAMES.HOOK_CALLBACK_NAME]:
|
|
364
|
+
hook.name?.length > 0 ? hook.name : ANONYMOUS_FUNCTION_NAME /* c8 ignore next */,
|
|
365
|
+
}),
|
|
366
|
+
);
|
|
367
|
+
} else {
|
|
368
|
+
return addHookOriginal.call(this, name, hook);
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function setNotFoundHandlerPatched(hooks, handler) {
|
|
373
|
+
const setNotFoundHandlerOriginal = this[kSetNotFoundOriginal];
|
|
374
|
+
if (typeof hooks === 'function') {
|
|
375
|
+
handler = handlerWrapper(hooks, {
|
|
376
|
+
[ATTR_SERVICE_NAME]: instance[kInstrumentation].servername,
|
|
377
|
+
[ATTRIBUTE_NAMES.HOOK_NAME]: `${this.pluginName} - not-found-handler`,
|
|
378
|
+
[ATTRIBUTE_NAMES.FASTIFY_TYPE]: HOOK_TYPES.INSTANCE,
|
|
379
|
+
[ATTRIBUTE_NAMES.HOOK_CALLBACK_NAME]:
|
|
380
|
+
hooks.name?.length > 0 ? hooks.name : ANONYMOUS_FUNCTION_NAME /* c8 ignore next */,
|
|
381
|
+
});
|
|
382
|
+
setNotFoundHandlerOriginal.call(this, handler);
|
|
383
|
+
} else {
|
|
384
|
+
if (hooks.preValidation != null) {
|
|
385
|
+
hooks.preValidation = handlerWrapper(hooks.preValidation, {
|
|
386
|
+
[ATTR_SERVICE_NAME]: instance[kInstrumentation].servername,
|
|
387
|
+
[ATTRIBUTE_NAMES.HOOK_NAME]: `${this.pluginName} - not-found-handler - preValidation`,
|
|
388
|
+
[ATTRIBUTE_NAMES.FASTIFY_TYPE]: HOOK_TYPES.INSTANCE,
|
|
389
|
+
[ATTRIBUTE_NAMES.HOOK_CALLBACK_NAME]:
|
|
390
|
+
hooks.preValidation.name?.length > 0
|
|
391
|
+
? hooks.preValidation.name
|
|
392
|
+
: ANONYMOUS_FUNCTION_NAME /* c8 ignore next */,
|
|
393
|
+
});
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
if (hooks.preHandler != null) {
|
|
397
|
+
hooks.preHandler = handlerWrapper(hooks.preHandler, {
|
|
398
|
+
[ATTR_SERVICE_NAME]: instance[kInstrumentation].servername,
|
|
399
|
+
[ATTRIBUTE_NAMES.HOOK_NAME]: `${this.pluginName} - not-found-handler - preHandler`,
|
|
400
|
+
[ATTRIBUTE_NAMES.FASTIFY_TYPE]: HOOK_TYPES.INSTANCE,
|
|
401
|
+
[ATTRIBUTE_NAMES.HOOK_CALLBACK_NAME]:
|
|
402
|
+
hooks.preHandler.name?.length > 0
|
|
403
|
+
? hooks.preHandler.name
|
|
404
|
+
: ANONYMOUS_FUNCTION_NAME /* c8 ignore next */,
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
handler = handlerWrapper(handler, {
|
|
409
|
+
[ATTR_SERVICE_NAME]: instance[kInstrumentation].servername,
|
|
410
|
+
[ATTRIBUTE_NAMES.HOOK_NAME]: `${this.pluginName} - not-found-handler`,
|
|
411
|
+
[ATTRIBUTE_NAMES.FASTIFY_TYPE]: HOOK_TYPES.INSTANCE,
|
|
412
|
+
[ATTRIBUTE_NAMES.HOOK_CALLBACK_NAME]:
|
|
413
|
+
handler.name?.length > 0 ? handler.name : ANONYMOUS_FUNCTION_NAME /* c8 ignore next */,
|
|
414
|
+
});
|
|
415
|
+
setNotFoundHandlerOriginal.call(this, hooks, handler);
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
function handlerWrapper(handler, spanAttributes = {}) {
|
|
420
|
+
return function handlerWrapped(...args) {
|
|
421
|
+
/** @type {FastifyOtelInstrumentation} */
|
|
422
|
+
const instrumentation = this[kInstrumentation];
|
|
423
|
+
const [request] = args;
|
|
424
|
+
|
|
425
|
+
if (instrumentation.isEnabled() === false) {
|
|
426
|
+
return handler.call(this, ...args);
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
const ctx = request[kRequestContext] ?? context.active();
|
|
430
|
+
const span = instrumentation.tracer.startSpan(
|
|
431
|
+
`handler - ${
|
|
432
|
+
handler.name?.length > 0
|
|
433
|
+
? handler.name
|
|
434
|
+
: this.pluginName /* c8 ignore next */ ?? ANONYMOUS_FUNCTION_NAME /* c8 ignore next */
|
|
435
|
+
}`,
|
|
436
|
+
{
|
|
437
|
+
attributes: spanAttributes,
|
|
438
|
+
},
|
|
439
|
+
ctx,
|
|
440
|
+
);
|
|
441
|
+
|
|
442
|
+
return context.with(
|
|
443
|
+
trace.setSpan(ctx, span),
|
|
444
|
+
function () {
|
|
445
|
+
try {
|
|
446
|
+
const res = handler.call(this, ...args);
|
|
447
|
+
|
|
448
|
+
if (typeof res?.then === 'function') {
|
|
449
|
+
return res.then(
|
|
450
|
+
result => {
|
|
451
|
+
span.end();
|
|
452
|
+
return result;
|
|
453
|
+
},
|
|
454
|
+
error => {
|
|
455
|
+
span.setStatus({
|
|
456
|
+
code: SpanStatusCode.ERROR,
|
|
457
|
+
message: error.message,
|
|
458
|
+
});
|
|
459
|
+
span.recordException(error);
|
|
460
|
+
span.end();
|
|
461
|
+
return Promise.reject(error);
|
|
462
|
+
},
|
|
463
|
+
);
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
span.end();
|
|
467
|
+
return res;
|
|
468
|
+
} catch (error) {
|
|
469
|
+
span.setStatus({
|
|
470
|
+
code: SpanStatusCode.ERROR,
|
|
471
|
+
message: error.message,
|
|
472
|
+
});
|
|
473
|
+
span.recordException(error);
|
|
474
|
+
span.end();
|
|
475
|
+
throw error;
|
|
476
|
+
}
|
|
477
|
+
},
|
|
478
|
+
this,
|
|
479
|
+
);
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
export { FastifyOtelInstrumentation };
|
|
487
|
+
//# sourceMappingURL=index.js.map
|