@sentry/server-utils 10.61.0 → 10.63.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.
Files changed (95) hide show
  1. package/build/cjs/index.js +6 -0
  2. package/build/cjs/index.js.map +1 -1
  3. package/build/cjs/integrations/tracing-channel/fastify/errors.js +42 -0
  4. package/build/cjs/integrations/tracing-channel/fastify/errors.js.map +1 -0
  5. package/build/cjs/integrations/tracing-channel/fastify/index.js +34 -0
  6. package/build/cjs/integrations/tracing-channel/fastify/index.js.map +1 -0
  7. package/build/cjs/integrations/tracing-channel/fastify/instrumentation.js +279 -0
  8. package/build/cjs/integrations/tracing-channel/fastify/instrumentation.js.map +1 -0
  9. package/build/cjs/integrations/tracing-channel/fastify/utils.js +11 -0
  10. package/build/cjs/integrations/tracing-channel/fastify/utils.js.map +1 -0
  11. package/build/cjs/integrations/tracing-channel/lru-memoizer.js +31 -0
  12. package/build/cjs/integrations/tracing-channel/lru-memoizer.js.map +1 -0
  13. package/build/cjs/integrations/tracing-channel/mysql.js +44 -82
  14. package/build/cjs/integrations/tracing-channel/mysql.js.map +1 -1
  15. package/build/cjs/orchestrion/channels.js +2 -1
  16. package/build/cjs/orchestrion/channels.js.map +1 -1
  17. package/build/cjs/orchestrion/config.js +6 -0
  18. package/build/cjs/orchestrion/config.js.map +1 -1
  19. package/build/cjs/orchestrion/index.js +2 -0
  20. package/build/cjs/orchestrion/index.js.map +1 -1
  21. package/build/cjs/tracing-channel.js +50 -11
  22. package/build/cjs/tracing-channel.js.map +1 -1
  23. package/build/cjs/vercel-ai/index.js +23 -0
  24. package/build/cjs/vercel-ai/index.js.map +1 -0
  25. package/build/cjs/vercel-ai/vercel-ai-dc-subscriber.js +362 -0
  26. package/build/cjs/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -0
  27. package/build/esm/index.js +2 -0
  28. package/build/esm/index.js.map +1 -1
  29. package/build/esm/integrations/tracing-channel/fastify/errors.js +39 -0
  30. package/build/esm/integrations/tracing-channel/fastify/errors.js.map +1 -0
  31. package/build/esm/integrations/tracing-channel/fastify/index.js +30 -0
  32. package/build/esm/integrations/tracing-channel/fastify/index.js.map +1 -0
  33. package/build/esm/integrations/tracing-channel/fastify/instrumentation.js +277 -0
  34. package/build/esm/integrations/tracing-channel/fastify/instrumentation.js.map +1 -0
  35. package/build/esm/integrations/tracing-channel/fastify/utils.js +8 -0
  36. package/build/esm/integrations/tracing-channel/fastify/utils.js.map +1 -0
  37. package/build/esm/integrations/tracing-channel/lru-memoizer.js +29 -0
  38. package/build/esm/integrations/tracing-channel/lru-memoizer.js.map +1 -0
  39. package/build/esm/integrations/tracing-channel/mysql.js +45 -83
  40. package/build/esm/integrations/tracing-channel/mysql.js.map +1 -1
  41. package/build/esm/orchestrion/channels.js +2 -1
  42. package/build/esm/orchestrion/channels.js.map +1 -1
  43. package/build/esm/orchestrion/config.js +6 -0
  44. package/build/esm/orchestrion/config.js.map +1 -1
  45. package/build/esm/orchestrion/index.js +1 -0
  46. package/build/esm/orchestrion/index.js.map +1 -1
  47. package/build/esm/package.json +1 -1
  48. package/build/esm/tracing-channel.js +51 -12
  49. package/build/esm/tracing-channel.js.map +1 -1
  50. package/build/esm/vercel-ai/index.js +21 -0
  51. package/build/esm/vercel-ai/index.js.map +1 -0
  52. package/build/esm/vercel-ai/vercel-ai-dc-subscriber.js +357 -0
  53. package/build/esm/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -0
  54. package/build/types/index.d.ts +2 -0
  55. package/build/types/index.d.ts.map +1 -1
  56. package/build/types/integrations/tracing-channel/fastify/errors.d.ts +12 -0
  57. package/build/types/integrations/tracing-channel/fastify/errors.d.ts.map +1 -0
  58. package/build/types/integrations/tracing-channel/fastify/index.d.ts +66 -0
  59. package/build/types/integrations/tracing-channel/fastify/index.d.ts.map +1 -0
  60. package/build/types/integrations/tracing-channel/fastify/instrumentation.d.ts +10 -0
  61. package/build/types/integrations/tracing-channel/fastify/instrumentation.d.ts.map +1 -0
  62. package/build/types/integrations/tracing-channel/fastify/types.d.ts +32 -0
  63. package/build/types/integrations/tracing-channel/fastify/types.d.ts.map +1 -0
  64. package/build/types/integrations/tracing-channel/fastify/utils.d.ts +9 -0
  65. package/build/types/integrations/tracing-channel/fastify/utils.d.ts.map +1 -0
  66. package/build/types/integrations/tracing-channel/lru-memoizer.d.ts +10 -0
  67. package/build/types/integrations/tracing-channel/lru-memoizer.d.ts.map +1 -0
  68. package/build/types/integrations/tracing-channel/mysql.d.ts +3 -1
  69. package/build/types/integrations/tracing-channel/mysql.d.ts.map +1 -1
  70. package/build/types/orchestrion/channels.d.ts +1 -0
  71. package/build/types/orchestrion/channels.d.ts.map +1 -1
  72. package/build/types/orchestrion/config.d.ts.map +1 -1
  73. package/build/types/orchestrion/index.d.ts +1 -0
  74. package/build/types/orchestrion/index.d.ts.map +1 -1
  75. package/build/types/tracing-channel.d.ts +22 -0
  76. package/build/types/tracing-channel.d.ts.map +1 -1
  77. package/build/types/vercel-ai/index.d.ts +27 -0
  78. package/build/types/vercel-ai/index.d.ts.map +1 -0
  79. package/build/types/vercel-ai/vercel-ai-dc-subscriber.d.ts +62 -0
  80. package/build/types/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -0
  81. package/build/types-ts3.8/index.d.ts +3 -0
  82. package/build/types-ts3.8/integrations/tracing-channel/fastify/errors.d.ts +12 -0
  83. package/build/types-ts3.8/integrations/tracing-channel/fastify/index.d.ts +66 -0
  84. package/build/types-ts3.8/integrations/tracing-channel/fastify/instrumentation.d.ts +10 -0
  85. package/build/types-ts3.8/integrations/tracing-channel/fastify/types.d.ts +32 -0
  86. package/build/types-ts3.8/integrations/tracing-channel/fastify/utils.d.ts +9 -0
  87. package/build/types-ts3.8/integrations/tracing-channel/lru-memoizer.d.ts +10 -0
  88. package/build/types-ts3.8/integrations/tracing-channel/mysql.d.ts +3 -1
  89. package/build/types-ts3.8/node-diagnostics-channel.d.ts +19 -0
  90. package/build/types-ts3.8/orchestrion/channels.d.ts +1 -0
  91. package/build/types-ts3.8/orchestrion/index.d.ts +1 -0
  92. package/build/types-ts3.8/tracing-channel.d.ts +22 -0
  93. package/build/types-ts3.8/vercel-ai/index.d.ts +27 -0
  94. package/build/types-ts3.8/vercel-ai/vercel-ai-dc-subscriber.d.ts +62 -0
  95. package/package.json +3 -3
@@ -0,0 +1,277 @@
1
+ import * as diagnosticsChannel from 'node:diagnostics_channel';
2
+ import { HTTP_ROUTE, URL_PATH, HTTP_REQUEST_METHOD, HTTP_RESPONSE_STATUS_CODE } from '@sentry/conventions/attributes';
3
+ import { debug, getIsolationScope, getActiveSpan, getRootSpan, spanToJSON, SEMANTIC_ATTRIBUTE_SENTRY_OP, startInactiveSpan, withActiveSpan, startSpan, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SPAN_STATUS_ERROR } from '@sentry/core';
4
+ import { DEBUG_BUILD } from '../../../debug-build.js';
5
+
6
+ const PACKAGE_NAME = "@sentry/instrumentation-fastify";
7
+ const SUPPORTED_VERSIONS = ">=3.21.0 <6";
8
+ const ORIGIN = "auto.http.otel.fastify";
9
+ const HOOK_OP = "hook.fastify";
10
+ const REQUEST_HANDLER_OP = "request_handler.fastify";
11
+ const FASTIFY_HOOKS = [
12
+ "onRequest",
13
+ "preParsing",
14
+ "preValidation",
15
+ "preHandler",
16
+ "preSerialization",
17
+ "onSend",
18
+ "onResponse",
19
+ "onError"
20
+ ];
21
+ const ATTRIBUTE_HOOK_NAME = "hook.name";
22
+ const ATTRIBUTE_FASTIFY_TYPE = "fastify.type";
23
+ const ATTRIBUTE_HOOK_CALLBACK_NAME = "hook.callback.name";
24
+ const ATTRIBUTE_FASTIFY_ROOT = "fastify.root";
25
+ const HOOK_TYPE_ROUTE = "route-hook";
26
+ const HOOK_TYPE_INSTANCE = "hook";
27
+ const HOOK_TYPE_HANDLER = "request-handler";
28
+ const ANONYMOUS_FUNCTION_NAME = "anonymous";
29
+ const kRequestSpan = /* @__PURE__ */ Symbol("sentry fastify request span");
30
+ const kAddHookOriginal = /* @__PURE__ */ Symbol("sentry fastify addHook original");
31
+ const kSetNotFoundOriginal = /* @__PURE__ */ Symbol("sentry fastify setNotFoundHandler original");
32
+ function getRequestRouteUrl(request) {
33
+ return request.routeOptions?.url ?? request.routerPath;
34
+ }
35
+ function getRequestRouteConfig(request) {
36
+ return request.routeOptions?.config ?? request.routeConfig;
37
+ }
38
+ function isFastifyRequest(arg) {
39
+ return !!arg && typeof arg === "object" && !!arg.method && !!arg.url && (!!arg.routeOptions || "routerPath" in arg);
40
+ }
41
+ function fastifyOtelPlugin(instance, _opts, done) {
42
+ instance.decorate(kAddHookOriginal, instance.addHook);
43
+ instance.decorate(kSetNotFoundOriginal, instance.setNotFoundHandler);
44
+ instance.decorateRequest("opentelemetry", function opentelemetry() {
45
+ return { span: this[kRequestSpan] };
46
+ });
47
+ instance.decorateRequest(kRequestSpan, null);
48
+ instance.addHook("onRoute", otelWireRoute);
49
+ instance.addHook("onRequest", startRequestSpanHook);
50
+ instance.addHook("onResponse", finalizeNotFoundSpanHook);
51
+ instance.addHook = addHookPatched;
52
+ instance.setNotFoundHandler = setNotFoundHandlerPatched;
53
+ done();
54
+ }
55
+ const pluginSymbols = fastifyOtelPlugin;
56
+ pluginSymbols[/* @__PURE__ */ Symbol.for("skip-override")] = true;
57
+ pluginSymbols[/* @__PURE__ */ Symbol.for("fastify.display-name")] = PACKAGE_NAME;
58
+ pluginSymbols[/* @__PURE__ */ Symbol.for("plugin-meta")] = {
59
+ fastify: SUPPORTED_VERSIONS,
60
+ name: PACKAGE_NAME
61
+ };
62
+ function otelWireRoute(routeOptions) {
63
+ if (routeOptions.config?.otel === false) {
64
+ return;
65
+ }
66
+ for (const hook of FASTIFY_HOOKS) {
67
+ const handlerLike = routeOptions[hook];
68
+ if (typeof handlerLike === "function") {
69
+ routeOptions[hook] = handlerWrapper(
70
+ handlerLike,
71
+ hook,
72
+ routeHookAttributes(this.pluginName, hook, handlerLike, routeOptions.url)
73
+ );
74
+ } else if (Array.isArray(handlerLike)) {
75
+ routeOptions[hook] = handlerLike.map(
76
+ (handler) => handlerWrapper(handler, hook, routeHookAttributes(this.pluginName, hook, handler, routeOptions.url))
77
+ );
78
+ }
79
+ }
80
+ routeOptions.onSend = appendRouteHook(routeOptions.onSend, finalizeResponseSpanHook);
81
+ routeOptions.onError = appendRouteHook(routeOptions.onError, recordErrorInSpanHook);
82
+ routeOptions.handler = handlerWrapper(routeOptions.handler, "handler", {
83
+ [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - route-handler`,
84
+ [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_HANDLER,
85
+ [HTTP_ROUTE]: routeOptions.url,
86
+ [ATTRIBUTE_HOOK_CALLBACK_NAME]: routeOptions.handler.name.length > 0 ? routeOptions.handler.name : ANONYMOUS_FUNCTION_NAME
87
+ });
88
+ }
89
+ function routeHookAttributes(pluginName, hook, handler, url) {
90
+ return {
91
+ [ATTRIBUTE_HOOK_NAME]: `${pluginName} - route -> ${hook}`,
92
+ [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_ROUTE,
93
+ [HTTP_ROUTE]: url,
94
+ [ATTRIBUTE_HOOK_CALLBACK_NAME]: handler.name?.length > 0 ? handler.name : ANONYMOUS_FUNCTION_NAME
95
+ };
96
+ }
97
+ function appendRouteHook(existing, hook) {
98
+ if (existing == null) {
99
+ return hook;
100
+ }
101
+ return Array.isArray(existing) ? [...existing, hook] : [existing, hook];
102
+ }
103
+ function startRequestSpanHook(request, _reply, hookDone) {
104
+ if (getRequestRouteConfig(request)?.otel === false) {
105
+ return hookDone();
106
+ }
107
+ const attributes = {
108
+ [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: ORIGIN,
109
+ [ATTRIBUTE_FASTIFY_ROOT]: PACKAGE_NAME,
110
+ [HTTP_REQUEST_METHOD]: request.method,
111
+ [URL_PATH]: request.url
112
+ };
113
+ const route = getRequestRouteUrl(request);
114
+ if (route != null) {
115
+ attributes[HTTP_ROUTE] = route;
116
+ const activeSpan = getActiveSpan();
117
+ const rootSpan = activeSpan && getRootSpan(activeSpan);
118
+ if (rootSpan && spanToJSON(rootSpan).data[SEMANTIC_ATTRIBUTE_SENTRY_OP] === "http.server") {
119
+ rootSpan.setAttribute(HTTP_ROUTE, route);
120
+ }
121
+ }
122
+ const requestSpan = startInactiveSpan({ name: "request", op: REQUEST_HANDLER_OP, attributes });
123
+ request[kRequestSpan] = requestSpan;
124
+ withActiveSpan(requestSpan, () => {
125
+ hookDone();
126
+ });
127
+ }
128
+ function finalizeNotFoundSpanHook(request, reply, hookDone) {
129
+ const span = request[kRequestSpan];
130
+ if (span != null) {
131
+ span.setAttributes({ [HTTP_RESPONSE_STATUS_CODE]: reply.statusCode });
132
+ span.end();
133
+ }
134
+ request[kRequestSpan] = null;
135
+ hookDone();
136
+ }
137
+ function finalizeResponseSpanHook(request, reply, payload, hookDone) {
138
+ const span = request[kRequestSpan];
139
+ if (span != null) {
140
+ if (reply.statusCode >= 500) {
141
+ span.setStatus({ code: SPAN_STATUS_ERROR });
142
+ }
143
+ span.setAttributes({ [HTTP_RESPONSE_STATUS_CODE]: reply.statusCode });
144
+ span.end();
145
+ }
146
+ request[kRequestSpan] = null;
147
+ hookDone(null, payload);
148
+ }
149
+ function recordErrorInSpanHook(request, _reply, error, hookDone) {
150
+ const span = request[kRequestSpan];
151
+ if (span != null) {
152
+ span.setStatus({ code: SPAN_STATUS_ERROR, message: error.message });
153
+ }
154
+ hookDone();
155
+ }
156
+ function addHookPatched(name, hook) {
157
+ const addHookOriginal = this[kAddHookOriginal];
158
+ if (FASTIFY_HOOKS.includes(name)) {
159
+ return addHookOriginal.call(
160
+ this,
161
+ name,
162
+ handlerWrapper(hook, name, {
163
+ [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - ${name}`,
164
+ [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,
165
+ [ATTRIBUTE_HOOK_CALLBACK_NAME]: hook.name?.length > 0 ? hook.name : ANONYMOUS_FUNCTION_NAME
166
+ })
167
+ );
168
+ }
169
+ return addHookOriginal.call(this, name, hook);
170
+ }
171
+ function setNotFoundHandlerPatched(hooks, handler) {
172
+ const setNotFoundHandlerOriginal = this[kSetNotFoundOriginal];
173
+ if (typeof hooks === "function") {
174
+ setNotFoundHandlerOriginal.call(
175
+ this,
176
+ handlerWrapper(hooks, "notFoundHandler", {
177
+ [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler`,
178
+ [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,
179
+ [ATTRIBUTE_HOOK_CALLBACK_NAME]: hooks.name?.length > 0 ? hooks.name : ANONYMOUS_FUNCTION_NAME
180
+ })
181
+ );
182
+ return;
183
+ }
184
+ if (hooks.preValidation != null) {
185
+ hooks.preValidation = handlerWrapper(hooks.preValidation, "notFoundHandler - preValidation", {
186
+ [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler - preValidation`,
187
+ [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,
188
+ [ATTRIBUTE_HOOK_CALLBACK_NAME]: hooks.preValidation.name?.length > 0 ? hooks.preValidation.name : ANONYMOUS_FUNCTION_NAME
189
+ });
190
+ }
191
+ if (hooks.preHandler != null) {
192
+ hooks.preHandler = handlerWrapper(hooks.preHandler, "notFoundHandler - preHandler", {
193
+ [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler - preHandler`,
194
+ [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,
195
+ [ATTRIBUTE_HOOK_CALLBACK_NAME]: hooks.preHandler.name?.length > 0 ? hooks.preHandler.name : ANONYMOUS_FUNCTION_NAME
196
+ });
197
+ }
198
+ if (handler == null) {
199
+ setNotFoundHandlerOriginal.call(this, hooks);
200
+ return;
201
+ }
202
+ setNotFoundHandlerOriginal.call(
203
+ this,
204
+ hooks,
205
+ handlerWrapper(handler, "notFoundHandler", {
206
+ [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler`,
207
+ [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,
208
+ [ATTRIBUTE_HOOK_CALLBACK_NAME]: handler.name?.length > 0 ? handler.name : ANONYMOUS_FUNCTION_NAME
209
+ })
210
+ );
211
+ }
212
+ function getRequestFromArgs(args) {
213
+ for (const arg of args) {
214
+ if (isFastifyRequest(arg)) {
215
+ return arg;
216
+ }
217
+ }
218
+ return null;
219
+ }
220
+ function handlerWrapper(handler, hookName, spanAttributes = {}) {
221
+ return function handlerWrapped(...args) {
222
+ const request = getRequestFromArgs(args);
223
+ if (request === null || getRequestRouteConfig(request)?.otel === false) {
224
+ return handler.call(this, ...args);
225
+ }
226
+ const parentSpan = request[kRequestSpan] ?? void 0;
227
+ const handlerName = handler.name?.length > 0 ? handler.name : this.pluginName ?? ANONYMOUS_FUNCTION_NAME;
228
+ const hookType = spanAttributes[ATTRIBUTE_FASTIFY_TYPE];
229
+ const op = hookType === HOOK_TYPE_INSTANCE ? HOOK_OP : hookType === HOOK_TYPE_HANDLER ? REQUEST_HANDLER_OP : void 0;
230
+ const name = op ? stripFastifyPrefix(spanAttributes[ATTRIBUTE_HOOK_NAME]) : `${hookName} - ${handlerName}`;
231
+ return startSpan(
232
+ {
233
+ name,
234
+ op,
235
+ attributes: {
236
+ ...spanAttributes,
237
+ [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: ORIGIN
238
+ },
239
+ parentSpan
240
+ },
241
+ () => handler.call(this, ...args)
242
+ );
243
+ };
244
+ }
245
+ function stripFastifyPrefix(hookName = "") {
246
+ return hookName.replace(/^fastify -> /, "").replace(/^@fastify\/otel -> /, "").replace(/^@sentry\/instrumentation-fastify -> /, "");
247
+ }
248
+ function instrumentOnRequest(fastify) {
249
+ fastify.addHook("onRequest", async (request, _reply) => {
250
+ const routeName = getRequestRouteUrl(request);
251
+ const method = request.method || "GET";
252
+ getIsolationScope().setTransactionName(`${method} ${routeName}`);
253
+ });
254
+ }
255
+ let _isInstrumented = false;
256
+ const instrumentFastify = Object.assign(
257
+ function instrumentFastify2() {
258
+ if (_isInstrumented) {
259
+ return;
260
+ }
261
+ _isInstrumented = true;
262
+ diagnosticsChannel.subscribe("fastify.initialization", (message) => {
263
+ const fastifyInstance = message.fastify;
264
+ fastifyInstance?.register(fastifyOtelPlugin).after((err) => {
265
+ if (err) {
266
+ DEBUG_BUILD && debug.error("Failed to setup Fastify instrumentation", err);
267
+ } else if (fastifyInstance) {
268
+ instrumentOnRequest(fastifyInstance);
269
+ }
270
+ });
271
+ });
272
+ },
273
+ { id: "Fastify.v5" }
274
+ );
275
+
276
+ export { instrumentFastify };
277
+ //# sourceMappingURL=instrumentation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"instrumentation.js","sources":["../../../../../src/integrations/tracing-channel/fastify/instrumentation.ts"],"sourcesContent":["/*\n * Copyright (c) 2024-present The Fastify team <https://github.com/fastify/fastify#team>\n * SPDX-License-Identifier: MIT\n *\n * NOTICE from the Sentry authors:\n * - Based on: https://github.com/fastify/otel/tree/bae80d6caef4287e7f01ff3c8dc753243706ea86 (@fastify/otel@0.18.1)\n * - Streamlined to the Sentry SDK's needs: dropped the `InstrumentationBase` wrapper, the unused\n * request/lifecycle hooks, `ignorePaths`/`minimatch` support and the OpenTelemetry tracer/context\n * APIs in favor of the Sentry span API.\n */\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n/* eslint-disable @typescript-eslint/no-unsafe-member-access */\n/* eslint-disable @typescript-eslint/no-this-alias */\n/* eslint-disable max-lines */\n\nimport * as diagnosticsChannel from 'node:diagnostics_channel';\nimport { HTTP_REQUEST_METHOD, HTTP_RESPONSE_STATUS_CODE, HTTP_ROUTE, URL_PATH } from '@sentry/conventions/attributes';\nimport type { Span } from '@sentry/core';\nimport {\n debug,\n getActiveSpan,\n getIsolationScope,\n getRootSpan,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SPAN_STATUS_ERROR,\n spanToJSON,\n startInactiveSpan,\n startSpan,\n withActiveSpan,\n} from '@sentry/core';\nimport type { FastifyInstance, FastifyRequest } from './types';\nimport { DEBUG_BUILD } from '../../../debug-build';\n\nconst PACKAGE_NAME = '@sentry/instrumentation-fastify';\nconst SUPPORTED_VERSIONS = '>=3.21.0 <6';\n\nconst ORIGIN = 'auto.http.otel.fastify';\nconst HOOK_OP = 'hook.fastify';\nconst REQUEST_HANDLER_OP = 'request_handler.fastify';\n\nconst FASTIFY_HOOKS = [\n 'onRequest',\n 'preParsing',\n 'preValidation',\n 'preHandler',\n 'preSerialization',\n 'onSend',\n 'onResponse',\n 'onError',\n];\nconst ATTRIBUTE_HOOK_NAME = 'hook.name' as const;\nconst ATTRIBUTE_FASTIFY_TYPE = 'fastify.type' as const;\nconst ATTRIBUTE_HOOK_CALLBACK_NAME = 'hook.callback.name' as const;\nconst ATTRIBUTE_FASTIFY_ROOT = 'fastify.root' as const;\n\nconst HOOK_TYPE_ROUTE = 'route-hook' as const;\nconst HOOK_TYPE_INSTANCE = 'hook' as const;\nconst HOOK_TYPE_HANDLER = 'request-handler' as const;\nconst ANONYMOUS_FUNCTION_NAME = 'anonymous';\n\nconst kRequestSpan = Symbol('sentry fastify request span');\nconst kAddHookOriginal = Symbol('sentry fastify addHook original');\nconst kSetNotFoundOriginal = Symbol('sentry fastify setNotFoundHandler original');\n\ntype AnyFn = (...args: any[]) => any;\n\n/**\n * Read the matched route URL off a request. Fastify >=4 exposes it on `request.routeOptions.url`,\n * while v3 only has the (since-removed-in-v5) `request.routerPath`.\n */\nfunction getRequestRouteUrl(request: any): string | undefined {\n return request.routeOptions?.url ?? request.routerPath;\n}\n\n/**\n * Read the per-route config off a request. Fastify >=4 exposes it on `request.routeOptions.config`,\n * while v3 uses `request.routeConfig`. Used to honor the `{ config: { otel: false } }` opt-out.\n */\nfunction getRequestRouteConfig(request: any): { otel?: boolean } | undefined {\n return request.routeOptions?.config ?? request.routeConfig;\n}\n\n/**\n * Detect whether one of a wrapped handler's arguments is the Fastify request. We can't rely on a\n * single property since the route metadata moved from `routerPath` (v3) to `routeOptions` (>=4),\n * so we accept either shape.\n */\nfunction isFastifyRequest(arg: any): boolean {\n return !!arg && typeof arg === 'object' && !!arg.method && !!arg.url && (!!arg.routeOptions || 'routerPath' in arg);\n}\n\n/**\n * The Fastify plugin that wires up the request/hook/handler spans. It is registered on every Fastify\n * instance via the `fastify.initialization` diagnostics channel.\n */\nfunction fastifyOtelPlugin(this: unknown, instance: any, _opts: unknown, done: () => void): void {\n instance.decorate(kAddHookOriginal, instance.addHook);\n instance.decorate(kSetNotFoundOriginal, instance.setNotFoundHandler);\n instance.decorateRequest('opentelemetry', function opentelemetry(this: any) {\n return { span: this[kRequestSpan] as Span | null };\n });\n instance.decorateRequest(kRequestSpan, null);\n\n instance.addHook('onRoute', otelWireRoute);\n instance.addHook('onRequest', startRequestSpanHook);\n instance.addHook('onResponse', finalizeNotFoundSpanHook);\n\n instance.addHook = addHookPatched;\n instance.setNotFoundHandler = setNotFoundHandlerPatched;\n\n done();\n}\n\nconst pluginSymbols = fastifyOtelPlugin as unknown as Record<symbol, unknown>;\npluginSymbols[Symbol.for('skip-override')] = true;\npluginSymbols[Symbol.for('fastify.display-name')] = PACKAGE_NAME;\npluginSymbols[Symbol.for('plugin-meta')] = {\n fastify: SUPPORTED_VERSIONS,\n name: PACKAGE_NAME,\n};\n\nfunction otelWireRoute(this: any, routeOptions: any): void {\n if (routeOptions.config?.otel === false) {\n return;\n }\n\n for (const hook of FASTIFY_HOOKS) {\n const handlerLike = routeOptions[hook];\n\n if (typeof handlerLike === 'function') {\n routeOptions[hook] = handlerWrapper(\n handlerLike,\n hook,\n routeHookAttributes(this.pluginName, hook, handlerLike, routeOptions.url),\n );\n } else if (Array.isArray(handlerLike)) {\n routeOptions[hook] = handlerLike.map((handler: AnyFn) =>\n handlerWrapper(handler, hook, routeHookAttributes(this.pluginName, hook, handler, routeOptions.url)),\n );\n }\n }\n\n routeOptions.onSend = appendRouteHook(routeOptions.onSend, finalizeResponseSpanHook);\n routeOptions.onError = appendRouteHook(routeOptions.onError, recordErrorInSpanHook);\n\n routeOptions.handler = handlerWrapper(routeOptions.handler, 'handler', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - route-handler`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_HANDLER,\n [HTTP_ROUTE]: routeOptions.url,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]:\n routeOptions.handler.name.length > 0 ? routeOptions.handler.name : ANONYMOUS_FUNCTION_NAME,\n });\n}\n\nfunction routeHookAttributes(pluginName: string, hook: string, handler: AnyFn, url: string): Record<string, string> {\n return {\n [ATTRIBUTE_HOOK_NAME]: `${pluginName} - route -> ${hook}`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_ROUTE,\n [HTTP_ROUTE]: url,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]: handler.name?.length > 0 ? handler.name : ANONYMOUS_FUNCTION_NAME,\n };\n}\n\nfunction appendRouteHook(existing: AnyFn | AnyFn[] | undefined, hook: AnyFn): AnyFn | AnyFn[] {\n if (existing == null) {\n return hook;\n }\n return Array.isArray(existing) ? [...existing, hook] : [existing, hook];\n}\n\nfunction startRequestSpanHook(this: any, request: any, _reply: any, hookDone: () => void): void {\n if (getRequestRouteConfig(request)?.otel === false) {\n return hookDone();\n }\n\n const attributes: Record<string, string> = {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: ORIGIN,\n [ATTRIBUTE_FASTIFY_ROOT]: PACKAGE_NAME,\n [HTTP_REQUEST_METHOD]: request.method,\n [URL_PATH]: request.url,\n };\n\n const route = getRequestRouteUrl(request);\n if (route != null) {\n attributes[HTTP_ROUTE] = route;\n\n // Update the route of the request on the root span, if it is a http.server span\n const activeSpan = getActiveSpan();\n const rootSpan = activeSpan && getRootSpan(activeSpan);\n if (rootSpan && spanToJSON(rootSpan).data[SEMANTIC_ATTRIBUTE_SENTRY_OP] === 'http.server') {\n rootSpan.setAttribute(HTTP_ROUTE, route);\n }\n }\n\n const requestSpan = startInactiveSpan({ name: 'request', op: REQUEST_HANDLER_OP, attributes });\n request[kRequestSpan] = requestSpan;\n\n // Set the request span as the active span for the remainder of the request lifecycle, so that\n // downstream hooks/handlers as well as errors captured via the error diagnostics channel are\n // parented to it (otherwise they would attach to the root `http.server` span instead).\n withActiveSpan(requestSpan, () => {\n hookDone();\n });\n}\n\nfunction finalizeNotFoundSpanHook(request: any, reply: any, hookDone: () => void): void {\n const span = request[kRequestSpan] as Span | null;\n\n if (span != null) {\n span.setAttributes({ [HTTP_RESPONSE_STATUS_CODE]: reply.statusCode });\n span.end();\n }\n\n request[kRequestSpan] = null;\n\n hookDone();\n}\n\nfunction finalizeResponseSpanHook(\n request: any,\n reply: any,\n payload: any,\n hookDone: (err: null, payload: any) => void,\n): void {\n const span = request[kRequestSpan] as Span | null;\n\n if (span != null) {\n if (reply.statusCode >= 500) {\n span.setStatus({ code: SPAN_STATUS_ERROR });\n }\n span.setAttributes({ [HTTP_RESPONSE_STATUS_CODE]: reply.statusCode });\n span.end();\n }\n\n request[kRequestSpan] = null;\n\n hookDone(null, payload);\n}\n\nfunction recordErrorInSpanHook(request: any, _reply: any, error: any, hookDone: () => void): void {\n const span = request[kRequestSpan] as Span | null;\n\n if (span != null) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: error.message });\n }\n\n hookDone();\n}\n\nfunction addHookPatched(this: any, name: string, hook: AnyFn): unknown {\n const addHookOriginal = this[kAddHookOriginal];\n\n if (FASTIFY_HOOKS.includes(name)) {\n return addHookOriginal.call(\n this,\n name,\n handlerWrapper(hook, name, {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - ${name}`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]: hook.name?.length > 0 ? hook.name : ANONYMOUS_FUNCTION_NAME,\n }),\n );\n }\n\n return addHookOriginal.call(this, name, hook);\n}\n\nfunction setNotFoundHandlerPatched(this: any, hooks: any, handler?: any): void {\n const setNotFoundHandlerOriginal = this[kSetNotFoundOriginal];\n\n if (typeof hooks === 'function') {\n setNotFoundHandlerOriginal.call(\n this,\n handlerWrapper(hooks, 'notFoundHandler', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]: hooks.name?.length > 0 ? hooks.name : ANONYMOUS_FUNCTION_NAME,\n }),\n );\n return;\n }\n\n if (hooks.preValidation != null) {\n hooks.preValidation = handlerWrapper(hooks.preValidation, 'notFoundHandler - preValidation', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler - preValidation`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]:\n hooks.preValidation.name?.length > 0 ? hooks.preValidation.name : ANONYMOUS_FUNCTION_NAME,\n });\n }\n\n if (hooks.preHandler != null) {\n hooks.preHandler = handlerWrapper(hooks.preHandler, 'notFoundHandler - preHandler', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler - preHandler`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]:\n hooks.preHandler.name?.length > 0 ? hooks.preHandler.name : ANONYMOUS_FUNCTION_NAME,\n });\n }\n\n // Fastify allows `setNotFoundHandler(opts)` without a handler, falling back to its built-in 404\n // handler. Forward the (already-wrapped) hooks unchanged so that fallback still applies.\n if (handler == null) {\n setNotFoundHandlerOriginal.call(this, hooks);\n return;\n }\n\n setNotFoundHandlerOriginal.call(\n this,\n hooks,\n handlerWrapper(handler, 'notFoundHandler', {\n [ATTRIBUTE_HOOK_NAME]: `${this.pluginName} - not-found-handler`,\n [ATTRIBUTE_FASTIFY_TYPE]: HOOK_TYPE_INSTANCE,\n [ATTRIBUTE_HOOK_CALLBACK_NAME]: handler.name?.length > 0 ? handler.name : ANONYMOUS_FUNCTION_NAME,\n }),\n );\n}\n\nfunction getRequestFromArgs(args: any[]): any | null {\n for (const arg of args) {\n if (isFastifyRequest(arg)) {\n return arg;\n }\n }\n return null;\n}\n\nfunction handlerWrapper(handler: AnyFn, hookName: string, spanAttributes: Record<string, string> = {}): AnyFn {\n return function handlerWrapped(this: any, ...args: any[]) {\n const request = getRequestFromArgs(args);\n\n if (request === null || getRequestRouteConfig(request)?.otel === false) {\n return handler.call(this, ...args);\n }\n\n const parentSpan = (request[kRequestSpan] as Span | null) ?? undefined;\n const handlerName = handler.name?.length > 0 ? handler.name : (this.pluginName ?? ANONYMOUS_FUNCTION_NAME);\n\n const hookType = spanAttributes[ATTRIBUTE_FASTIFY_TYPE];\n const op =\n hookType === HOOK_TYPE_INSTANCE ? HOOK_OP : hookType === HOOK_TYPE_HANDLER ? REQUEST_HANDLER_OP : undefined;\n\n const name = op ? stripFastifyPrefix(spanAttributes[ATTRIBUTE_HOOK_NAME]) : `${hookName} - ${handlerName}`;\n\n return startSpan(\n {\n name,\n op,\n attributes: {\n ...spanAttributes,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: ORIGIN,\n },\n parentSpan,\n },\n () => handler.call(this, ...args),\n );\n };\n}\n\n/**\n * Strip the framework/plugin prefixes from a Fastify `hook.name` to derive a readable span name.\n * This is a bit of a hack and does not always work for all spans, but it's the best we can do without a proper API.\n */\nfunction stripFastifyPrefix(hookName = ''): string {\n return hookName\n .replace(/^fastify -> /, '')\n .replace(/^@fastify\\/otel -> /, '')\n .replace(/^@sentry\\/instrumentation-fastify -> /, '');\n}\n\nfunction instrumentOnRequest(fastify: FastifyInstance): void {\n fastify.addHook('onRequest', async (request: FastifyRequest, _reply) => {\n const routeName = getRequestRouteUrl(request);\n const method = request.method || 'GET';\n\n getIsolationScope().setTransactionName(`${method} ${routeName}`);\n });\n}\n\nlet _isInstrumented = false;\n\n/**\n * Set up the Fastify (>= 3.21.0 < 6) instrumentation by subscribing to the `fastify.initialization`\n * diagnostics channel and registering the span-creating plugin on every Fastify instance.\n *\n * Idempotent and exposes an `id` so it can participate in the OpenTelemetry preload list.\n */\nexport const instrumentFastify = Object.assign(\n function instrumentFastify(): void {\n if (_isInstrumented) {\n return;\n }\n _isInstrumented = true;\n\n diagnosticsChannel.subscribe('fastify.initialization', message => {\n const fastifyInstance = (message as { fastify?: FastifyInstance }).fastify;\n\n fastifyInstance?.register(fastifyOtelPlugin).after(err => {\n if (err) {\n DEBUG_BUILD && debug.error('Failed to setup Fastify instrumentation', err);\n } else if (fastifyInstance) {\n instrumentOnRequest(fastifyInstance);\n }\n });\n });\n },\n { id: 'Fastify.v5' },\n);\n"],"names":["instrumentFastify"],"mappings":";;;;;AAmCA,MAAM,YAAA,GAAe,iCAAA;AACrB,MAAM,kBAAA,GAAqB,aAAA;AAE3B,MAAM,MAAA,GAAS,wBAAA;AACf,MAAM,OAAA,GAAU,cAAA;AAChB,MAAM,kBAAA,GAAqB,yBAAA;AAE3B,MAAM,aAAA,GAAgB;AAAA,EACpB,WAAA;AAAA,EACA,YAAA;AAAA,EACA,eAAA;AAAA,EACA,YAAA;AAAA,EACA,kBAAA;AAAA,EACA,QAAA;AAAA,EACA,YAAA;AAAA,EACA;AACF,CAAA;AACA,MAAM,mBAAA,GAAsB,WAAA;AAC5B,MAAM,sBAAA,GAAyB,cAAA;AAC/B,MAAM,4BAAA,GAA+B,oBAAA;AACrC,MAAM,sBAAA,GAAyB,cAAA;AAE/B,MAAM,eAAA,GAAkB,YAAA;AACxB,MAAM,kBAAA,GAAqB,MAAA;AAC3B,MAAM,iBAAA,GAAoB,iBAAA;AAC1B,MAAM,uBAAA,GAA0B,WAAA;AAEhC,MAAM,YA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O,CAAA;AAC5C,IAAA,MAAM,MAAA,GAAS,QAAQ,MAAA,IAAU,KAAA;AAEjC,IAAA,iBAAA,GAAoB,kBAAA,CAAmB,CAAA,EAAG,MAAM,CAAA,CAAA,EAAI,SAAS,CAAA,CAAE,CAAA;AAAA,EACjE,CAAC,CAAA;AACH;AAEA,IAAI,eAAA,GAAkB,KAAA;AAQf,MAAM,oBAAoB,MAAA,CAAO,MAAA;AAAA,EACtC,SAASA,kBAAAA,GAA0B;AACjC,IAAA,IAAI,eAAA,EAAiB;AACnB,MAAA;AAAA,IACF;AACA,IAAA,eAAA,GAAkB,IAAA;AAElB,IAAA,kBAAA,CAAmB,SAAA,CAAU,0BAA0B,CAAA,OAAA,KAAW;AAChE,MAAA,MAAM,kBAAmB,OAAA,CAA0C,OAAA;AAEnE,MAAA,eAAA,EAAiB,QAAA,CAAS,iBAAiB,CAAA,CAAE,KAAA,CAAM,CAAA,GAAA,KAAO;AACxD,QAAA,IAAI,GAAA,EAAK;AACP,UAAA,WAAA,IAAe,KAAA,CAAM,KAAA,CAAM,yCAAA,EAA2C,GAAG,CAAA;AAAA,QAC3E,WAAW,eAAA,EAAiB;AAC1B,UAAA,mBAAA,CAAoB,eAAe,CAAA;AAAA,QACrC;AAAA,MACF,CAAC,CAAA;AAAA,IACH,CAAC,CAAA;AAAA,EACH,CAAA;AAAA,EACA,EAAE,IAAI,YAAA;AACR;;;;"}
@@ -0,0 +1,8 @@
1
+ const INTEGRATION_NAME = "Fastify";
2
+ function defaultShouldHandleError(_error, _request, reply) {
3
+ const statusCode = reply.statusCode;
4
+ return statusCode >= 500 || statusCode <= 299;
5
+ }
6
+
7
+ export { INTEGRATION_NAME, defaultShouldHandleError };
8
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sources":["../../../../../src/integrations/tracing-channel/fastify/utils.ts"],"sourcesContent":["import type { FastifyReply, FastifyRequest } from './types';\n\nexport const INTEGRATION_NAME = 'Fastify';\n\n/**\n * Default function to determine if an error should be sent to Sentry\n *\n * 3xx and 4xx errors are not sent by default.\n */\nexport function defaultShouldHandleError(_error: Error, _request: FastifyRequest, reply: FastifyReply): boolean {\n const statusCode = reply.statusCode;\n // 3xx and 4xx errors are not sent by default.\n return statusCode >= 500 || statusCode <= 299;\n}\n"],"names":[],"mappings":"AAEO,MAAM,gBAAA,GAAmB;AAOzB,SAAS,wBAAA,CAAyB,MAAA,EAAe,QAAA,EAA0B,KAAA,EAA8B;AAC9G,EAAA,MAAM,aAAa,KAAA,CAAM,UAAA;AAEzB,EAAA,OAAO,UAAA,IAAc,OAAO,UAAA,IAAc,GAAA;AAC5C;;;;"}
@@ -0,0 +1,29 @@
1
+ import * as diagnosticsChannel from 'node:diagnostics_channel';
2
+ import { defineIntegration, debug, waitForTracingChannelBinding } from '@sentry/core';
3
+ import { DEBUG_BUILD } from '../../debug-build.js';
4
+ import { CHANNELS } from '../../orchestrion/channels.js';
5
+ import { bindTracingChannelToSpan } from '../../tracing-channel.js';
6
+
7
+ const INTEGRATION_NAME = "LruMemoizer";
8
+ const _lruMemoizerChannelIntegration = (() => {
9
+ return {
10
+ name: INTEGRATION_NAME,
11
+ setupOnce() {
12
+ if (!diagnosticsChannel.tracingChannel) {
13
+ return;
14
+ }
15
+ DEBUG_BUILD && debug.log(`[orchestrion:lru-memoizer] subscribing to channel "${CHANNELS.LRU_MEMOIZER_LOAD}"`);
16
+ waitForTracingChannelBinding(() => {
17
+ bindTracingChannelToSpan(
18
+ diagnosticsChannel.tracingChannel(CHANNELS.LRU_MEMOIZER_LOAD),
19
+ // We only want the helper's caller-context restore for the callback lru-memoizer fires from a detached `setImmediate`.
20
+ () => void 0
21
+ );
22
+ });
23
+ }
24
+ };
25
+ });
26
+ const lruMemoizerChannelIntegration = defineIntegration(_lruMemoizerChannelIntegration);
27
+
28
+ export { lruMemoizerChannelIntegration };
29
+ //# sourceMappingURL=lru-memoizer.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lru-memoizer.js","sources":["../../../../src/integrations/tracing-channel/lru-memoizer.ts"],"sourcesContent":["import * as diagnosticsChannel from 'node:diagnostics_channel';\nimport type { IntegrationFn } from '@sentry/core';\nimport { debug, defineIntegration, waitForTracingChannelBinding } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\n\n// Same name as the OTel integration by design — when enabled, the OTel\n// 'LruMemoizer' integration is omitted from the default set.\nconst INTEGRATION_NAME = 'LruMemoizer' as const;\n\ninterface LruMemoizerLoadContext {\n arguments: unknown[];\n}\n\nconst _lruMemoizerChannelIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n // `tracingChannel` is unavailable before Node 18.19 so do nothing in that case.\n if (!diagnosticsChannel.tracingChannel) {\n return;\n }\n\n DEBUG_BUILD && debug.log(`[orchestrion:lru-memoizer] subscribing to channel \"${CHANNELS.LRU_MEMOIZER_LOAD}\"`);\n\n waitForTracingChannelBinding(() => {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<LruMemoizerLoadContext>(CHANNELS.LRU_MEMOIZER_LOAD),\n // We only want the helper's caller-context restore for the callback lru-memoizer fires from a detached `setImmediate`.\n () => undefined,\n );\n });\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * EXPERIMENTAL — orchestrion-driven lru-memoizer integration. Subscribes to\n * `orchestrion:lru-memoizer:load` (injected into `lru-memoizer/lib/async.js`'s\n * `memoizedFunction`). Creates no spans; only re-runs the memoized callback with the\n * caller's scope. Requires the orchestrion runtime hook or bundler plugin.\n */\nexport const lruMemoizerChannelIntegration = defineIntegration(_lruMemoizerChannelIntegration);\n"],"names":[],"mappings":";;;;;;AASA,MAAM,gBAAA,GAAmB,aAAA;AAMzB,MAAM,kCAAkC,MAAM;AAC5C,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,SAAA,GAAY;AAEV,MAAA,IAAI,CAAC,mBAAmB,cAAA,EAAgB;AACtC,QAAA;AAAA,MACF;AAEA,MAAA,WAAA,IAAe,KAAA,CAAM,GAAA,CAAI,CAAA,mDAAA,EAAsD,QAAA,CAAS,iBAAiB,CAAA,CAAA,CAAG,CAAA;AAE5G,MAAA,4BAAA,CAA6B,MAAM;AACjC,QAAA,wBAAA;AAAA,UACE,kBAAA,CAAmB,cAAA,CAAuC,QAAA,CAAS,iBAAiB,CAAA;AAAA;AAAA,UAEpF,MAAM;AAAA,SACR;AAAA,MACF,CAAC,CAAA;AAAA,IACH;AAAA,GACF;AACF,CAAA,CAAA;AAQO,MAAM,6BAAA,GAAgC,kBAAkB,8BAA8B;;;;"}
@@ -1,7 +1,8 @@
1
1
  import * as diagnosticsChannel from 'node:diagnostics_channel';
2
- import { defineIntegration, debug, SPAN_STATUS_ERROR, bindScopeToEmitter, startInactiveSpan, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, getCurrentScope, withScope } from '@sentry/core';
2
+ import { defineIntegration, debug, waitForTracingChannelBinding, bindScopeToEmitter, getCurrentScope, startInactiveSpan, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '@sentry/core';
3
3
  import { DEBUG_BUILD } from '../../debug-build.js';
4
4
  import { CHANNELS } from '../../orchestrion/channels.js';
5
+ import { bindTracingChannelToSpan } from '../../tracing-channel.js';
5
6
 
6
7
  const INTEGRATION_NAME = "Mysql";
7
8
  const ATTR_DB_SYSTEM = "db.system";
@@ -15,92 +16,53 @@ const _mysqlChannelIntegration = (() => {
15
16
  return {
16
17
  name: INTEGRATION_NAME,
17
18
  setupOnce() {
19
+ if (!diagnosticsChannel.tracingChannel) {
20
+ return;
21
+ }
18
22
  DEBUG_BUILD && debug.log(`[orchestrion:mysql] subscribing to channel "${CHANNELS.MYSQL_QUERY}"`);
19
- const queryCh = diagnosticsChannel.tracingChannel(CHANNELS.MYSQL_QUERY);
20
- const spans = /* @__PURE__ */ new WeakMap();
21
- const parentScopes = /* @__PURE__ */ new WeakMap();
22
- queryCh.subscribe({
23
- start(rawCtx) {
24
- const ctx = rawCtx;
25
- const sql = extractSql(ctx.arguments[0]);
26
- const { host, port, database, user } = getConnectionConfig(ctx.self);
27
- const portNumber = typeof port === "string" ? parseInt(port, 10) : port;
28
- const portIsNumber = typeof portNumber === "number" && !isNaN(portNumber);
29
- const span = startInactiveSpan({
30
- name: sql ?? "mysql.query",
31
- op: "db",
32
- attributes: {
33
- [ATTR_DB_SYSTEM]: "mysql",
34
- [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.db.orchestrion.mysql",
35
- [ATTR_DB_CONNECTION_STRING]: getJDBCString(host, portIsNumber ? portNumber : void 0, database),
36
- ...database ? { [ATTR_DB_NAME]: database } : {},
37
- ...user ? { [ATTR_DB_USER]: user } : {},
38
- ...sql ? { [ATTR_DB_STATEMENT]: sql } : {},
39
- ...host ? { [ATTR_NET_PEER_NAME]: host } : {},
40
- ...portIsNumber ? { [ATTR_NET_PEER_PORT]: portNumber } : {}
41
- }
42
- });
43
- spans.set(rawCtx, span);
44
- const scope = getCurrentScope();
45
- parentScopes.set(rawCtx, scope);
46
- if (ctx.arguments.length > 0) {
47
- const cbIdx = ctx.arguments.length - 1;
48
- const orchestrionWrappedCb = ctx.arguments[cbIdx];
49
- if (typeof orchestrionWrappedCb === "function") {
50
- const wrapped = orchestrionWrappedCb;
51
- ctx.arguments[cbIdx] = function(...args) {
52
- return withScope(scope, () => wrapped.apply(this, args));
53
- };
54
- }
55
- }
56
- },
57
- end(rawCtx) {
58
- const ctx = rawCtx;
59
- if (ctx.error !== void 0) {
60
- finishSpan(rawCtx);
61
- return;
62
- }
63
- const result = ctx.result;
64
- if (result && typeof result === "object" && hasOnMethod(result)) {
65
- const span = spans.get(rawCtx);
66
- if (!span) return;
67
- const parentScope = parentScopes.get(rawCtx);
68
- if (parentScope) {
69
- bindScopeToEmitter(result, parentScope);
70
- }
71
- result.on("error", (err) => {
72
- span.setStatus({
73
- code: SPAN_STATUS_ERROR,
74
- message: err instanceof Error ? err.message : "unknown_error"
75
- });
76
- finishSpan(rawCtx);
23
+ waitForTracingChannelBinding(() => {
24
+ bindTracingChannelToSpan(
25
+ diagnosticsChannel.tracingChannel(CHANNELS.MYSQL_QUERY),
26
+ (data) => {
27
+ const sql = extractSql(data.arguments[0]);
28
+ const { host, port, database, user } = getConnectionConfig(data.self);
29
+ const portNumber = typeof port === "string" ? parseInt(port, 10) : port;
30
+ const portIsNumber = typeof portNumber === "number" && !isNaN(portNumber);
31
+ data._sentryCallerScope = getCurrentScope();
32
+ return startInactiveSpan({
33
+ name: sql ?? "mysql.query",
34
+ op: "db",
35
+ attributes: {
36
+ [ATTR_DB_SYSTEM]: "mysql",
37
+ [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.db.orchestrion.mysql",
38
+ [ATTR_DB_CONNECTION_STRING]: getJDBCString(host, portIsNumber ? portNumber : void 0, database),
39
+ ...database ? { [ATTR_DB_NAME]: database } : {},
40
+ ...user ? { [ATTR_DB_USER]: user } : {},
41
+ ...sql ? { [ATTR_DB_STATEMENT]: sql } : {},
42
+ ...host ? { [ATTR_NET_PEER_NAME]: host } : {},
43
+ ...portIsNumber ? { [ATTR_NET_PEER_PORT]: portNumber } : {}
44
+ }
77
45
  });
78
- result.on("end", () => finishSpan(rawCtx));
79
- return;
46
+ },
47
+ {
48
+ // No-callback `query(sql)` returns a streamable `Query` emitter as `result`; it settles on the
49
+ // emitter's `'end'`/`'error'`, not the channel, so defer ending to those.
50
+ deferSpanEnd({ data, end }) {
51
+ const result = data.result;
52
+ if (!result || typeof result !== "object" || !hasOnMethod(result)) {
53
+ return false;
54
+ }
55
+ const callerScope = data._sentryCallerScope;
56
+ if (callerScope) {
57
+ bindScopeToEmitter(result, callerScope);
58
+ }
59
+ result.on("error", (err) => end(err));
60
+ result.on("end", () => end());
61
+ return true;
62
+ }
80
63
  }
81
- },
82
- error(rawCtx) {
83
- const ctx = rawCtx;
84
- const span = spans.get(rawCtx);
85
- if (!span) return;
86
- span.setStatus({
87
- code: SPAN_STATUS_ERROR,
88
- message: ctx.error instanceof Error ? ctx.error.message : "unknown_error"
89
- });
90
- },
91
- asyncStart() {
92
- },
93
- asyncEnd(rawCtx) {
94
- finishSpan(rawCtx);
95
- }
64
+ );
96
65
  });
97
- function finishSpan(rawCtx) {
98
- const span = spans.get(rawCtx);
99
- if (!span) return;
100
- span.end();
101
- spans.delete(rawCtx);
102
- parentScopes.delete(rawCtx);
103
- }
104
66
  }
105
67
  };
106
68
  });
@@ -1 +1 @@
1
- {"version":3,"file":"mysql.js","sources":["../../../../src/integrations/tracing-channel/mysql.ts"],"sourcesContent":["import * as diagnosticsChannel from 'node:diagnostics_channel';\nimport type { IntegrationFn, Scope, Span } from '@sentry/core';\nimport {\n bindScopeToEmitter,\n debug,\n defineIntegration,\n getCurrentScope,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n withScope,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { CHANNELS } from '../../orchestrion/channels';\n\n// NOTE: this uses the same name as the OTel integration by design.\n// When enabled, OTel 'Mysql' integration is omitted from the default set.\nconst INTEGRATION_NAME = 'Mysql';\n\n// OpenTelemetry \"OLD\" db/net semantic-conventions. We inline them rather than\n// importing `@opentelemetry/semantic-conventions` to keep this integration's\n// dependency surface free of OTel — orchestrion's whole point is to step away\n// from the OTel auto-instrumentation stack.\n//\n// We emit the OLD conventions to match `@opentelemetry/instrumentation-mysql`'s\n// default (it only emits the stable `db.system.name` / `db.query.text` set when\n// `OTEL_SEMCONV_STABILITY_OPT_IN=database` is opted into) and the rest of the\n// Sentry JS SDK, whose `inferDbSpanData` processor renames spans based on\n// `db.statement`.\nconst ATTR_DB_SYSTEM = 'db.system';\nconst ATTR_DB_CONNECTION_STRING = 'db.connection_string';\nconst ATTR_DB_NAME = 'db.name';\nconst ATTR_DB_USER = 'db.user';\nconst ATTR_DB_STATEMENT = 'db.statement';\nconst ATTR_NET_PEER_NAME = 'net.peer.name';\nconst ATTR_NET_PEER_PORT = 'net.peer.port';\n\n/**\n * The shape orchestrion's wrapCallback transform attaches to the tracing-channel\n * `context` object. Documented here rather than imported because orchestrion's\n * runtime doesn't export it — see `node_modules/@apm-js-collab/code-transformer/lib/transforms.js`.\n *\n * `arguments` is the *live* args array passed to the wrapped function: orchestrion\n * splices the user's callback out and inserts its own wrapper at the same index\n * before publishing `start`. The `start` hook re-wraps that entry to restore the\n * caller's scope across mysql's async callback dispatch (see below).\n */\ninterface MysqlQueryChannelContext {\n arguments: unknown[];\n self?: MysqlConnection;\n moduleVersion?: string;\n result?: unknown;\n error?: unknown;\n}\n\ninterface MysqlConnectionConfig {\n host?: string;\n port?: number | string;\n database?: string;\n user?: string;\n // Pool connections nest the real config one level deeper.\n connectionConfig?: MysqlConnectionConfig;\n}\n\ninterface MysqlConnection {\n config?: MysqlConnectionConfig;\n}\n\nconst _mysqlChannelIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n DEBUG_BUILD && debug.log(`[orchestrion:mysql] subscribing to channel \"${CHANNELS.MYSQL_QUERY}\"`);\n const queryCh = diagnosticsChannel.tracingChannel(CHANNELS.MYSQL_QUERY);\n\n // Orchestrion creates one `context` object per call, shared across all\n // lifecycle hooks. We key both maps off that identity; `WeakMap` so an\n // unfinished path can't leak its entries.\n const spans = new WeakMap<object, Span>();\n // The scope active when the query was issued, consumed in `end` to bind\n // the streamed `Query` emitter's listeners to it.\n const parentScopes = new WeakMap<object, Scope>();\n\n // `subscribe()` requires all five lifecycle hooks. The orchestrion\n // `wrapAuto` transform fires events in one of four orders depending on\n // call shape:\n // - sync throw : start → error → end\n // (NO asyncEnd)\n // - async-callback error : start → end → error →\n // asyncStart → asyncEnd\n // - async-callback success : start → end → asyncStart →\n // asyncEnd\n // - no-callback (streamable Query) : start → end\n // (ctx.result is the Query\n // emitter, no async events)\n //\n // Where the span closes depends on the path: `asyncEnd` for callbacks (so\n // it spans the full round-trip + callback), or `end` for the sync-throw\n // and streamable paths. The `end` hook tells those apart via `ctx.error`\n // / `ctx.result` — see there.\n queryCh.subscribe({\n start(rawCtx) {\n const ctx = rawCtx as MysqlQueryChannelContext;\n const sql = extractSql(ctx.arguments[0]);\n const { host, port, database, user } = getConnectionConfig(ctx.self);\n const portNumber = typeof port === 'string' ? parseInt(port, 10) : port;\n const portIsNumber = typeof portNumber === 'number' && !isNaN(portNumber);\n\n const span = startInactiveSpan({\n name: sql ?? 'mysql.query',\n op: 'db',\n attributes: {\n [ATTR_DB_SYSTEM]: 'mysql',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.orchestrion.mysql',\n [ATTR_DB_CONNECTION_STRING]: getJDBCString(host, portIsNumber ? portNumber : undefined, database),\n ...(database ? { [ATTR_DB_NAME]: database } : {}),\n ...(user ? { [ATTR_DB_USER]: user } : {}),\n ...(sql ? { [ATTR_DB_STATEMENT]: sql } : {}),\n ...(host ? { [ATTR_NET_PEER_NAME]: host } : {}),\n ...(portIsNumber ? { [ATTR_NET_PEER_PORT]: portNumber } : {}),\n },\n });\n spans.set(rawCtx, span);\n\n // Capture the scope while we're still synchronously inside the\n // caller's `connection.query` call. mysql v2 drains callbacks and\n // emits streamed-query events from its socket data handler, where the\n // AsyncLocalStorage store backing the active span no longer reflects\n // the caller's context — and `asyncStart`/`asyncEnd` fire from that\n // same lost context, so capturing has to happen now.\n const scope = getCurrentScope();\n parentScopes.set(rawCtx, scope);\n\n // Callback path: orchestrion has spliced the user's callback out of\n // `ctx.arguments` and put its own wrapper (`__apm$wrappedCb`) at the\n // same index. Re-wrap it so the callback — and any nested\n // `connection.query(...)` — runs with the captured scope active.\n if (ctx.arguments.length > 0) {\n const cbIdx = ctx.arguments.length - 1;\n const orchestrionWrappedCb = ctx.arguments[cbIdx];\n if (typeof orchestrionWrappedCb === 'function') {\n const wrapped = orchestrionWrappedCb as (...a: unknown[]) => unknown;\n ctx.arguments[cbIdx] = function (this: unknown, ...args: unknown[]): unknown {\n return withScope(scope, () => wrapped.apply(this, args));\n };\n }\n }\n },\n\n end(rawCtx) {\n const ctx = rawCtx as MysqlQueryChannelContext;\n\n // Sync throw: `end` fires AFTER `error` (both inside the wrapper's\n // `try/catch/finally`), so `ctx.error` is already set. Close the\n // span now since no `asyncEnd` will fire.\n if (ctx.error !== undefined) {\n finishSpan(rawCtx);\n return;\n }\n\n // No-callback (streamable Query) path: orchestrion's `wrapPromise`\n // stores the synchronous return value on `ctx.result` and never\n // fires `asyncStart`/`asyncEnd`. The returned `Query` is an\n // `EventEmitter` that emits `'end'` on success and `'error'` on\n // failure — hook those to close the span.\n // Note: a streamed span never finishes if the connection is destroyed\n // mid-flight — mysql then emits neither `'end'` nor `'error'`, so the\n // span is dropped (the `WeakMap` still prevents a leak). Closing this\n // needs connection-level hooks the per-query context doesn't expose.\n const result = ctx.result;\n if (result && typeof result === 'object' && hasOnMethod(result)) {\n const span = spans.get(rawCtx);\n if (!span) return;\n\n // Bind the captured scope to the streamed `Query` emitter: its\n // `'end'`/`'error'`/`'fields'`/… events fire from mysql's socket\n // handler with the caller's context lost, so without this a span\n // started in a user's stream listener would begin a fresh root trace\n // instead of nesting under the parent. `bindScopeToEmitter` patches\n // `on`/`addListener`/… so listeners added after `query()` returns\n // inherit the scope (like OTel's `context.bind`).\n const parentScope = parentScopes.get(rawCtx);\n if (parentScope) {\n bindScopeToEmitter(result, parentScope);\n }\n\n result.on('error', err => {\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message: err instanceof Error ? err.message : 'unknown_error',\n });\n // Defensive: end the span here too in case `'end'` never fires\n // (e.g. abrupt socket destruction). `finishSpan` is idempotent —\n // `spans.delete` makes the subsequent `'end'` listener a no-op.\n finishSpan(rawCtx);\n });\n result.on('end', () => finishSpan(rawCtx));\n return;\n }\n\n // Callback path: `asyncEnd` will close the span. Nothing to do here.\n },\n\n error(rawCtx) {\n const ctx = rawCtx as MysqlQueryChannelContext;\n const span = spans.get(rawCtx);\n if (!span) return;\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message: ctx.error instanceof Error ? ctx.error.message : 'unknown_error',\n });\n },\n\n asyncStart() {\n // No-op: we end on `asyncEnd` so the span covers the full callback duration.\n },\n\n asyncEnd(rawCtx) {\n finishSpan(rawCtx);\n },\n });\n\n function finishSpan(rawCtx: object): void {\n const span = spans.get(rawCtx);\n if (!span) return;\n span.end();\n spans.delete(rawCtx);\n parentScopes.delete(rawCtx);\n }\n },\n };\n}) satisfies IntegrationFn;\n\nfunction hasOnMethod(obj: object): obj is { on: (event: string, listener: (arg?: unknown) => void) => unknown } {\n return 'on' in obj && typeof (obj as { on?: unknown }).on === 'function';\n}\n\nfunction extractSql(firstArg: unknown): string | undefined {\n if (typeof firstArg === 'string') {\n return firstArg;\n }\n if (firstArg && typeof firstArg === 'object' && 'sql' in firstArg) {\n const sql = (firstArg as { sql?: unknown }).sql;\n return typeof sql === 'string' ? sql : undefined;\n }\n return undefined;\n}\n\nfunction getConnectionConfig(connection: MysqlConnection | undefined): {\n host?: string;\n port?: number | string;\n database?: string;\n user?: string;\n} {\n // Pool connections nest the real config under `.connectionConfig`; single\n // connections expose it directly. Matches `@opentelemetry/instrumentation-mysql`.\n const config = connection?.config?.connectionConfig ?? connection?.config ?? {};\n return {\n host: config.host,\n port: config.port,\n database: config.database,\n user: config.user,\n };\n}\n\nfunction getJDBCString(host: string | undefined, port: number | undefined, database: string | undefined): string {\n let s = `jdbc:mysql://${host || 'localhost'}`;\n if (typeof port === 'number') {\n s += `:${port}`;\n }\n if (database) {\n s += `/${database}`;\n }\n return s;\n}\n\n/**\n * EXPERIMENTAL — orchestrion-driven mysql integration.\n *\n * Subscribes to the `orchestrion:mysql:query` diagnostics_channel that the\n * orchestrion code transform injects into `mysql/lib/Connection.js`'s\n * `Connection.prototype.query`. Requires the orchestrion runtime hook or\n * bundler plugin to be active — wire that up via `_experimentalSetup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ACb,MAAM,MAAA,CAAO,IAAA;AAAA,IACb,UAAU,MAAA,CAAO,QAAA;AAAA,IACjB,MAAM,MAAA,CAAO;AAAA,GACf;AACF;AAEA,SAAS,aAAA,CAAc,IAAA,EAA0B,IAAA,EAA0B,QAAA,EAAsC;AAC/G,EAAA,IAAI,CAAA,GAAI,CAAA,aAAA,EAAgB,IAAA,IAAQ,WAAW,CAAA,CAAA;AAC3C,EAAA,IAAI,OAAO,SAAS,QAAA,EAAU;AAC5B,IAAA,CAAA,IAAK,IAAI,IAAI,CAAA,CAAA;AAAA,EACf;AACA,EAAA,IAAI,QAAA,EAAU;AACZ,IAAA,CAAA,IAAK,IAAI,QAAQ,CAAA,CAAA;AAAA,EACnB;AACA,EAAA,OAAO,CAAA;AACT;AAUO,MAAM,uBAAA,GAA0B,kBAAkB,wBAAwB;;;;"}
1
+ {"version":3,"file":"mysql.js","sources":["../../../../src/integrations/tracing-channel/mysql.ts"],"sourcesContent":["import * as diagnosticsChannel from 'node:diagnostics_channel';\nimport type { IntegrationFn, Scope } from '@sentry/core';\nimport {\n bindScopeToEmitter,\n debug,\n defineIntegration,\n getCurrentScope,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n startInactiveSpan,\n waitForTracingChannelBinding,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\n\n// NOTE: this uses the same name as the OTel integration by design.\n// When enabled, OTel 'Mysql' integration is omitted from the default set.\nconst INTEGRATION_NAME = 'Mysql' as const;\n\n// OTel \"OLD\" db/net semantic-conventions, inlined to keep this integration free of OTel deps. Matches\n// `@opentelemetry/instrumentation-mysql`'s default and the SDK's `inferDbSpanData` (which renames spans\n// off `db.statement`).\nconst ATTR_DB_SYSTEM = 'db.system';\nconst ATTR_DB_CONNECTION_STRING = 'db.connection_string';\nconst ATTR_DB_NAME = 'db.name';\nconst ATTR_DB_USER = 'db.user';\nconst ATTR_DB_STATEMENT = 'db.statement';\nconst ATTR_NET_PEER_NAME = 'net.peer.name';\nconst ATTR_NET_PEER_PORT = 'net.peer.port';\n\n/**\n * The shape orchestrion's transform attaches to the tracing-channel `context` object. Documented here\n * rather than imported because orchestrion's runtime doesn't export it.\n */\ninterface MysqlQueryChannelContext {\n // The live args array passed to the wrapped `connection.query` call; `arguments[0]` is the SQL.\n arguments: unknown[];\n self?: MysqlConnection;\n moduleVersion?: string;\n result?: unknown;\n error?: unknown;\n // The caller's scope, captured at `start` and replayed onto the streamed `Query` emitter (see below).\n _sentryCallerScope?: Scope;\n}\n\ninterface MysqlConnectionConfig {\n host?: string;\n port?: number | string;\n database?: string;\n user?: string;\n // Pool connections nest the real config one level deeper.\n connectionConfig?: MysqlConnectionConfig;\n}\n\ninterface MysqlConnection {\n config?: MysqlConnectionConfig;\n}\n\nconst _mysqlChannelIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n // `tracingChannel` is unavailable before Node 18.19 so do nothing in that case.\n if (!diagnosticsChannel.tracingChannel) {\n return;\n }\n\n DEBUG_BUILD && debug.log(`[orchestrion:mysql] subscribing to channel \"${CHANNELS.MYSQL_QUERY}\"`);\n\n waitForTracingChannelBinding(() => {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<MysqlQueryChannelContext>(CHANNELS.MYSQL_QUERY),\n data => {\n const sql = extractSql(data.arguments[0]);\n const { host, port, database, user } = getConnectionConfig(data.self);\n const portNumber = typeof port === 'string' ? parseInt(port, 10) : port;\n const portIsNumber = typeof portNumber === 'number' && !isNaN(portNumber);\n\n // For the streamed path: mysql emits the `Query` emitter's events from its socket data\n // handler with the caller's context lost. `deferSpanEnd` replays this scope onto the emitter.\n data._sentryCallerScope = getCurrentScope();\n\n return startInactiveSpan({\n name: sql ?? 'mysql.query',\n op: 'db',\n attributes: {\n [ATTR_DB_SYSTEM]: 'mysql',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.orchestrion.mysql',\n [ATTR_DB_CONNECTION_STRING]: getJDBCString(host, portIsNumber ? portNumber : undefined, database),\n ...(database ? { [ATTR_DB_NAME]: database } : {}),\n ...(user ? { [ATTR_DB_USER]: user } : {}),\n ...(sql ? { [ATTR_DB_STATEMENT]: sql } : {}),\n ...(host ? { [ATTR_NET_PEER_NAME]: host } : {}),\n ...(portIsNumber ? { [ATTR_NET_PEER_PORT]: portNumber } : {}),\n },\n });\n },\n {\n // No-callback `query(sql)` returns a streamable `Query` emitter as `result`; it settles on the\n // emitter's `'end'`/`'error'`, not the channel, so defer ending to those.\n deferSpanEnd({ data, end }) {\n const result = data.result;\n if (!result || typeof result !== 'object' || !hasOnMethod(result)) {\n return false;\n }\n\n // Replay the caller's scope so user listeners on the emitter nest under it, not a new trace.\n const callerScope = data._sentryCallerScope;\n if (callerScope) {\n bindScopeToEmitter(result, callerScope);\n }\n\n result.on('error', err => end(err));\n result.on('end', () => end());\n\n return true;\n },\n },\n );\n });\n },\n };\n}) satisfies IntegrationFn;\n\nfunction hasOnMethod(obj: object): obj is { on: (event: string, listener: (arg?: unknown) => void) => unknown } {\n return 'on' in obj && typeof (obj as { on?: unknown }).on === 'function';\n}\n\nfunction extractSql(firstArg: unknown): string | undefined {\n if (typeof firstArg === 'string') {\n return firstArg;\n }\n if (firstArg && typeof firstArg === 'object' && 'sql' in firstArg) {\n const sql = (firstArg as { sql?: unknown }).sql;\n return typeof sql === 'string' ? sql : undefined;\n }\n return undefined;\n}\n\nfunction getConnectionConfig(connection: MysqlConnection | undefined): {\n host?: string;\n port?: number | string;\n database?: string;\n user?: string;\n} {\n // Pool connections nest the real config under `.connectionConfig`; single\n // connections expose it directly. Matches `@opentelemetry/instrumentation-mysql`.\n const config = connection?.config?.connectionConfig ?? connection?.config ?? {};\n return {\n host: config.host,\n port: config.port,\n database: config.database,\n user: config.user,\n };\n}\n\nfunction getJDBCString(host: string | undefined, port: number | undefined, database: string | undefined): string {\n let s = `jdbc:mysql://${host || 'localhost'}`;\n if (typeof port === 'number') {\n s += `:${port}`;\n }\n if (database) {\n s += `/${database}`;\n }\n return s;\n}\n\n/**\n * EXPERIMENTAL — orchestrion-driven mysql integration.\n *\n * Subscribes to the `orchestrion:mysql:query` diagnostics_channel that the\n * orchestrion code transform injects into `mysql/lib/Connection.js`'s\n * `Connection.prototype.query`. Requires the orchestrion runtime hook or\n * bundler plugin to be active — wire that up via `_experimentalSetupOrchestrion`.\n */\nexport const mysqlChannelIntegration = defineIntegration(_mysqlChannelIntegration);\n"],"names":[],"mappings":";;;;;;AAiBA,MAAM,gBAAA,GAAmB,OAAA;AAKzB,MAAM,cAAA,GAAiB,WAAA;AACvB,MAAM,yBAAA,GAA4B,sBAAA;AAClC,MAAM,YAAA,GAAe,SAAA;AACrB,MAAM,YAAA,GAAe,SAAA;AACrB,MAAM,iBAAA,GAAoB,cAAA;AAC1B,MAAM,kBAAA,GAAqB,eAAA;AAC3B,MAAM,kBAAA,GAAqB,eAAA;AA8B3B,MAAM,4BAA4B,MAAM;AACtC,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,SAAA,GAAY;AAEV,MAAA,IAAI,CAAC,mBAAmB,cAAA,EAAgB;AACtC,QAAA;AAAA,MACF;AAEA,MAAA,WAAA,IAAe,KAAA,CAAM,GAAA,CAAI,CAAA,4CAAA,EAA+C,QAAA,CAAS,WAAW,CAAA,CAAA,CAAG,CAAA;AAE/F,MAAA,4BAAA,CAA6B,MAAM;AACjC,QAAA,wBAAA;AAAA,UACE,kBAAA,CAAmB,cAAA,CAAyC,QAAA,CAAS,WAAW,CAAA;AAAA,UAChF,CAAA,IAAA,KAAQ;AACN,YAAA,MAAM,GAAA,GAAM,UAAA,CAAW,IAAA,CAAK,SAAA,CAAU,CAAC,CAAC,CAAA;AACxC,YAAA,MAAM,EAAE,MAAM,IAAA,EAAM,QAAA,EAAU,MAAK,GAAI,mBAAA,CAAoB,KAAK,IAAI,CAAA;AACpE,YA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IAAI,OAAO,SAAS,QAAA,EAAU;AAC5B,IAAA,CAAA,IAAK,IAAI,IAAI,CAAA,CAAA;AAAA,EACf;AACA,EAAA,IAAI,QAAA,EAAU;AACZ,IAAA,CAAA,IAAK,IAAI,QAAQ,CAAA,CAAA;AAAA,EACnB;AACA,EAAA,OAAO,CAAA;AACT;AAUO,MAAM,uBAAA,GAA0B,kBAAkB,wBAAwB;;;;"}
@@ -1,5 +1,6 @@
1
1
  const CHANNELS = {
2
- MYSQL_QUERY: "orchestrion:mysql:query"
2
+ MYSQL_QUERY: "orchestrion:mysql:query",
3
+ LRU_MEMOIZER_LOAD: "orchestrion:lru-memoizer:load"
3
4
  };
4
5
 
5
6
  export { CHANNELS };
@@ -1 +1 @@
1
- {"version":3,"file":"channels.js","sources":["../../../src/orchestrion/channels.ts"],"sourcesContent":["/**\n * Fully-qualified `diagnostics_channel` names that orchestrion publishes to.\n *\n * Orchestrion's transform always prefixes the configured `channelName` with\n * `orchestrion:${module.name}:`. So a config of\n * `{ channelName: 'query', module: { name: 'mysql' } }`\n * publishes to `orchestrion:mysql:query`.\n *\n * Subscribers (`integrations/<lib>/tracing-channel.ts`) consume the full\n * prefixed string from this map; the config files set only the unprefixed\n * suffix in `channelName`. Keeping both pieces in one file is what guarantees\n * they don't drift apart and silently stop firing.\n */\nexport const CHANNELS = {\n MYSQL_QUERY: 'orchestrion:mysql:query',\n} as const;\n\nexport type ChannelName = (typeof CHANNELS)[keyof typeof CHANNELS];\n"],"names":[],"mappings":"AAaO,MAAM,QAAA,GAAW;AAAA,EACtB,WAAA,EAAa;AACf;;;;"}
1
+ {"version":3,"file":"channels.js","sources":["../../../src/orchestrion/channels.ts"],"sourcesContent":["/**\n * Fully-qualified `diagnostics_channel` names that orchestrion publishes to.\n *\n * Orchestrion's transform always prefixes the configured `channelName` with\n * `orchestrion:${module.name}:`. So a config of\n * `{ channelName: 'query', module: { name: 'mysql' } }`\n * publishes to `orchestrion:mysql:query`.\n *\n * Subscribers (`integrations/<lib>/tracing-channel.ts`) consume the full\n * prefixed string from this map; the config files set only the unprefixed\n * suffix in `channelName`. Keeping both pieces in one file is what guarantees\n * they don't drift apart and silently stop firing.\n */\nexport const CHANNELS = {\n MYSQL_QUERY: 'orchestrion:mysql:query',\n LRU_MEMOIZER_LOAD: 'orchestrion:lru-memoizer:load',\n} as const;\n\nexport type ChannelName = (typeof CHANNELS)[keyof typeof CHANNELS];\n"],"names":[],"mappings":"AAaO,MAAM,QAAA,GAAW;AAAA,EACtB,WAAA,EAAa,yBAAA;AAAA,EACb,iBAAA,EAAmB;AACrB;;;;"}
@@ -18,6 +18,12 @@ const SENTRY_INSTRUMENTATIONS = [
18
18
  // returned `Query` emitter on `ctx.result`, which the integration uses to
19
19
  // attach `'end'`/`'error'` listeners that finish the span.
20
20
  functionQuery: { expressionName: "query", kind: "Auto" }
21
+ },
22
+ {
23
+ channelName: "load",
24
+ // `>=2.1.0` only: the named `function memoizedFunction()` the selector targets exists from 2.1.0
25
+ module: { name: "lru-memoizer", versionRange: ">=2.1.0 <4", filePath: "lib/async.js" },
26
+ functionQuery: { functionName: "memoizedFunction", kind: "Callback" }
21
27
  }
22
28
  ];
23
29
  const INSTRUMENTED_MODULE_NAMES = Array.from(new Set(SENTRY_INSTRUMENTATIONS.map((i) => i.module.name)));