@sentry/node 10.54.0 → 10.56.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 (166) hide show
  1. package/build/cjs/integrations/node-fetch/vendored/undici.js +2 -3
  2. package/build/cjs/integrations/node-fetch/vendored/undici.js.map +1 -1
  3. package/build/cjs/integrations/tracing/InstrumentationNodeModuleFile.js +15 -0
  4. package/build/cjs/integrations/tracing/InstrumentationNodeModuleFile.js.map +1 -0
  5. package/build/cjs/integrations/tracing/amqplib/vendored/amqplib.js +9 -9
  6. package/build/cjs/integrations/tracing/amqplib/vendored/amqplib.js.map +1 -1
  7. package/build/cjs/integrations/tracing/amqplib/vendored/utils.js.map +1 -1
  8. package/build/cjs/integrations/tracing/anthropic-ai/index.js.map +1 -1
  9. package/build/cjs/integrations/tracing/connect/vendored/instrumentation.js +3 -5
  10. package/build/cjs/integrations/tracing/connect/vendored/instrumentation.js.map +1 -1
  11. package/build/cjs/integrations/tracing/express.js +3 -5
  12. package/build/cjs/integrations/tracing/express.js.map +1 -1
  13. package/build/cjs/integrations/tracing/fastify/v3/instrumentation.js +10 -11
  14. package/build/cjs/integrations/tracing/fastify/v3/instrumentation.js.map +1 -1
  15. package/build/cjs/integrations/tracing/fastify/vendored/instrumentation.js +3 -4
  16. package/build/cjs/integrations/tracing/fastify/vendored/instrumentation.js.map +1 -1
  17. package/build/cjs/integrations/tracing/firebase/otel/patches/firestore.js +2 -1
  18. package/build/cjs/integrations/tracing/firebase/otel/patches/firestore.js.map +1 -1
  19. package/build/cjs/integrations/tracing/firebase/otel/patches/functions.js +2 -1
  20. package/build/cjs/integrations/tracing/firebase/otel/patches/functions.js.map +1 -1
  21. package/build/cjs/integrations/tracing/google-genai/instrumentation.js +2 -1
  22. package/build/cjs/integrations/tracing/google-genai/instrumentation.js.map +1 -1
  23. package/build/cjs/integrations/tracing/graphql/vendored/instrumentation.js +4 -3
  24. package/build/cjs/integrations/tracing/graphql/vendored/instrumentation.js.map +1 -1
  25. package/build/cjs/integrations/tracing/hapi/vendored/instrumentation.js +2 -5
  26. package/build/cjs/integrations/tracing/hapi/vendored/instrumentation.js.map +1 -1
  27. package/build/cjs/integrations/tracing/hono/index.js.map +1 -1
  28. package/build/cjs/integrations/tracing/knex/vendored/instrumentation.js +3 -2
  29. package/build/cjs/integrations/tracing/knex/vendored/instrumentation.js.map +1 -1
  30. package/build/cjs/integrations/tracing/koa/vendored/instrumentation.js +3 -4
  31. package/build/cjs/integrations/tracing/koa/vendored/instrumentation.js.map +1 -1
  32. package/build/cjs/integrations/tracing/langchain/instrumentation.js +3 -2
  33. package/build/cjs/integrations/tracing/langchain/instrumentation.js.map +1 -1
  34. package/build/cjs/integrations/tracing/langgraph/index.js.map +1 -1
  35. package/build/cjs/integrations/tracing/langgraph/instrumentation.js +7 -5
  36. package/build/cjs/integrations/tracing/langgraph/instrumentation.js.map +1 -1
  37. package/build/cjs/integrations/tracing/mongo/vendored/instrumentation.js +7 -6
  38. package/build/cjs/integrations/tracing/mongo/vendored/instrumentation.js.map +1 -1
  39. package/build/cjs/integrations/tracing/mysql2/vendored/instrumentation.js +3 -2
  40. package/build/cjs/integrations/tracing/mysql2/vendored/instrumentation.js.map +1 -1
  41. package/build/cjs/integrations/tracing/openai/index.js.map +1 -1
  42. package/build/cjs/integrations/tracing/postgres/vendored/instrumentation.js +5 -5
  43. package/build/cjs/integrations/tracing/postgres/vendored/instrumentation.js.map +1 -1
  44. package/build/cjs/integrations/tracing/postgresjs.js +2 -1
  45. package/build/cjs/integrations/tracing/postgresjs.js.map +1 -1
  46. package/build/cjs/integrations/tracing/redis/index.js +3 -2
  47. package/build/cjs/integrations/tracing/redis/index.js.map +1 -1
  48. package/build/cjs/integrations/tracing/redis/vendored/ioredis-instrumentation.js +1 -1
  49. package/build/cjs/integrations/tracing/redis/vendored/ioredis-instrumentation.js.map +1 -1
  50. package/build/cjs/integrations/tracing/redis/vendored/redis-instrumentation.js +4 -3
  51. package/build/cjs/integrations/tracing/redis/vendored/redis-instrumentation.js.map +1 -1
  52. package/build/cjs/integrations/tracing/vercelai/instrumentation.js +6 -5
  53. package/build/cjs/integrations/tracing/vercelai/instrumentation.js.map +1 -1
  54. package/build/cjs/utils/setHttpServerSpanRouteAttribute.js +21 -0
  55. package/build/cjs/utils/setHttpServerSpanRouteAttribute.js.map +1 -0
  56. package/build/esm/integrations/node-fetch/vendored/undici.js +3 -4
  57. package/build/esm/integrations/node-fetch/vendored/undici.js.map +1 -1
  58. package/build/esm/integrations/tracing/InstrumentationNodeModuleFile.js +13 -0
  59. package/build/esm/integrations/tracing/InstrumentationNodeModuleFile.js.map +1 -0
  60. package/build/esm/integrations/tracing/amqplib/vendored/amqplib.js +7 -7
  61. package/build/esm/integrations/tracing/amqplib/vendored/amqplib.js.map +1 -1
  62. package/build/esm/integrations/tracing/amqplib/vendored/utils.js.map +1 -1
  63. package/build/esm/integrations/tracing/anthropic-ai/index.js.map +1 -1
  64. package/build/esm/integrations/tracing/connect/vendored/instrumentation.js +3 -5
  65. package/build/esm/integrations/tracing/connect/vendored/instrumentation.js.map +1 -1
  66. package/build/esm/integrations/tracing/express.js +3 -5
  67. package/build/esm/integrations/tracing/express.js.map +1 -1
  68. package/build/esm/integrations/tracing/fastify/v3/instrumentation.js +3 -4
  69. package/build/esm/integrations/tracing/fastify/v3/instrumentation.js.map +1 -1
  70. package/build/esm/integrations/tracing/fastify/vendored/instrumentation.js +3 -4
  71. package/build/esm/integrations/tracing/fastify/vendored/instrumentation.js.map +1 -1
  72. package/build/esm/integrations/tracing/firebase/otel/patches/firestore.js +2 -1
  73. package/build/esm/integrations/tracing/firebase/otel/patches/firestore.js.map +1 -1
  74. package/build/esm/integrations/tracing/firebase/otel/patches/functions.js +2 -1
  75. package/build/esm/integrations/tracing/firebase/otel/patches/functions.js.map +1 -1
  76. package/build/esm/integrations/tracing/google-genai/instrumentation.js +2 -1
  77. package/build/esm/integrations/tracing/google-genai/instrumentation.js.map +1 -1
  78. package/build/esm/integrations/tracing/graphql/vendored/instrumentation.js +2 -1
  79. package/build/esm/integrations/tracing/graphql/vendored/instrumentation.js.map +1 -1
  80. package/build/esm/integrations/tracing/hapi/vendored/instrumentation.js +2 -5
  81. package/build/esm/integrations/tracing/hapi/vendored/instrumentation.js.map +1 -1
  82. package/build/esm/integrations/tracing/hono/index.js.map +1 -1
  83. package/build/esm/integrations/tracing/knex/vendored/instrumentation.js +2 -1
  84. package/build/esm/integrations/tracing/knex/vendored/instrumentation.js.map +1 -1
  85. package/build/esm/integrations/tracing/koa/vendored/instrumentation.js +3 -4
  86. package/build/esm/integrations/tracing/koa/vendored/instrumentation.js.map +1 -1
  87. package/build/esm/integrations/tracing/langchain/instrumentation.js +2 -1
  88. package/build/esm/integrations/tracing/langchain/instrumentation.js.map +1 -1
  89. package/build/esm/integrations/tracing/langgraph/index.js.map +1 -1
  90. package/build/esm/integrations/tracing/langgraph/instrumentation.js +5 -3
  91. package/build/esm/integrations/tracing/langgraph/instrumentation.js.map +1 -1
  92. package/build/esm/integrations/tracing/mongo/vendored/instrumentation.js +2 -1
  93. package/build/esm/integrations/tracing/mongo/vendored/instrumentation.js.map +1 -1
  94. package/build/esm/integrations/tracing/mysql2/vendored/instrumentation.js +2 -1
  95. package/build/esm/integrations/tracing/mysql2/vendored/instrumentation.js.map +1 -1
  96. package/build/esm/integrations/tracing/openai/index.js.map +1 -1
  97. package/build/esm/integrations/tracing/postgres/vendored/instrumentation.js +5 -5
  98. package/build/esm/integrations/tracing/postgres/vendored/instrumentation.js.map +1 -1
  99. package/build/esm/integrations/tracing/postgresjs.js +2 -1
  100. package/build/esm/integrations/tracing/postgresjs.js.map +1 -1
  101. package/build/esm/integrations/tracing/redis/index.js +3 -2
  102. package/build/esm/integrations/tracing/redis/index.js.map +1 -1
  103. package/build/esm/integrations/tracing/redis/vendored/ioredis-instrumentation.js +1 -1
  104. package/build/esm/integrations/tracing/redis/vendored/ioredis-instrumentation.js.map +1 -1
  105. package/build/esm/integrations/tracing/redis/vendored/redis-instrumentation.js +2 -1
  106. package/build/esm/integrations/tracing/redis/vendored/redis-instrumentation.js.map +1 -1
  107. package/build/esm/integrations/tracing/vercelai/instrumentation.js +6 -5
  108. package/build/esm/integrations/tracing/vercelai/instrumentation.js.map +1 -1
  109. package/build/esm/package.json +1 -1
  110. package/build/esm/utils/setHttpServerSpanRouteAttribute.js +19 -0
  111. package/build/esm/utils/setHttpServerSpanRouteAttribute.js.map +1 -0
  112. package/build/types/integrations/node-fetch/vendored/undici.d.ts.map +1 -1
  113. package/build/types/integrations/tracing/InstrumentationNodeModuleFile.d.ts +9 -0
  114. package/build/types/integrations/tracing/InstrumentationNodeModuleFile.d.ts.map +1 -0
  115. package/build/types/integrations/tracing/amqplib/vendored/amqplib.d.ts.map +1 -1
  116. package/build/types/integrations/tracing/amqplib/vendored/utils.d.ts +2 -2
  117. package/build/types/integrations/tracing/amqplib/vendored/utils.d.ts.map +1 -1
  118. package/build/types/integrations/tracing/anthropic-ai/index.d.ts +7 -7
  119. package/build/types/integrations/tracing/connect/vendored/instrumentation.d.ts.map +1 -1
  120. package/build/types/integrations/tracing/express.d.ts.map +1 -1
  121. package/build/types/integrations/tracing/fastify/v3/instrumentation.d.ts.map +1 -1
  122. package/build/types/integrations/tracing/fastify/vendored/instrumentation.d.ts.map +1 -1
  123. package/build/types/integrations/tracing/firebase/otel/patches/firestore.d.ts.map +1 -1
  124. package/build/types/integrations/tracing/firebase/otel/patches/functions.d.ts.map +1 -1
  125. package/build/types/integrations/tracing/google-genai/instrumentation.d.ts.map +1 -1
  126. package/build/types/integrations/tracing/graphql/vendored/instrumentation.d.ts.map +1 -1
  127. package/build/types/integrations/tracing/hapi/vendored/instrumentation.d.ts.map +1 -1
  128. package/build/types/integrations/tracing/hono/index.d.ts +6 -0
  129. package/build/types/integrations/tracing/hono/index.d.ts.map +1 -1
  130. package/build/types/integrations/tracing/knex/vendored/instrumentation.d.ts.map +1 -1
  131. package/build/types/integrations/tracing/koa/vendored/instrumentation.d.ts.map +1 -1
  132. package/build/types/integrations/tracing/langchain/instrumentation.d.ts.map +1 -1
  133. package/build/types/integrations/tracing/langgraph/index.d.ts +7 -7
  134. package/build/types/integrations/tracing/langgraph/instrumentation.d.ts.map +1 -1
  135. package/build/types/integrations/tracing/mongo/vendored/instrumentation.d.ts.map +1 -1
  136. package/build/types/integrations/tracing/mysql2/vendored/instrumentation.d.ts.map +1 -1
  137. package/build/types/integrations/tracing/openai/index.d.ts +7 -7
  138. package/build/types/integrations/tracing/postgres/vendored/instrumentation.d.ts.map +1 -1
  139. package/build/types/integrations/tracing/postgresjs.d.ts.map +1 -1
  140. package/build/types/integrations/tracing/redis/index.d.ts +4 -1
  141. package/build/types/integrations/tracing/redis/index.d.ts.map +1 -1
  142. package/build/types/integrations/tracing/redis/vendored/redis-instrumentation.d.ts.map +1 -1
  143. package/build/types/integrations/tracing/vercelai/instrumentation.d.ts +2 -2
  144. package/build/types/integrations/tracing/vercelai/instrumentation.d.ts.map +1 -1
  145. package/build/types/integrations/tracing/vercelai/types.d.ts +6 -4
  146. package/build/types/integrations/tracing/vercelai/types.d.ts.map +1 -1
  147. package/build/types/utils/setHttpServerSpanRouteAttribute.d.ts +9 -0
  148. package/build/types/utils/setHttpServerSpanRouteAttribute.d.ts.map +1 -0
  149. package/build/types-ts3.8/integrations/tracing/InstrumentationNodeModuleFile.d.ts +9 -0
  150. package/build/types-ts3.8/integrations/tracing/amqplib/vendored/utils.d.ts +2 -2
  151. package/build/types-ts3.8/integrations/tracing/anthropic-ai/index.d.ts +7 -7
  152. package/build/types-ts3.8/integrations/tracing/hono/index.d.ts +6 -0
  153. package/build/types-ts3.8/integrations/tracing/langgraph/index.d.ts +7 -7
  154. package/build/types-ts3.8/integrations/tracing/openai/index.d.ts +7 -7
  155. package/build/types-ts3.8/integrations/tracing/redis/index.d.ts +4 -1
  156. package/build/types-ts3.8/integrations/tracing/vercelai/instrumentation.d.ts +2 -2
  157. package/build/types-ts3.8/integrations/tracing/vercelai/types.d.ts +6 -4
  158. package/build/types-ts3.8/utils/setHttpServerSpanRouteAttribute.d.ts +9 -0
  159. package/package.json +5 -4
  160. package/build/cjs/integrations/tracing/redis/redis-dc-subscriber.js +0 -151
  161. package/build/cjs/integrations/tracing/redis/redis-dc-subscriber.js.map +0 -1
  162. package/build/esm/integrations/tracing/redis/redis-dc-subscriber.js +0 -149
  163. package/build/esm/integrations/tracing/redis/redis-dc-subscriber.js.map +0 -1
  164. package/build/types/integrations/tracing/redis/redis-dc-subscriber.d.ts +0 -17
  165. package/build/types/integrations/tracing/redis/redis-dc-subscriber.d.ts.map +0 -1
  166. package/build/types-ts3.8/integrations/tracing/redis/redis-dc-subscriber.d.ts +0 -17
@@ -3,6 +3,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3
3
  const api = require('@opentelemetry/api');
4
4
  const core = require('@sentry/core');
5
5
  const instrumentation = require('@opentelemetry/instrumentation');
6
+ const InstrumentationNodeModuleFile = require('../../InstrumentationNodeModuleFile.js');
6
7
  const semconv = require('./semconv.js');
7
8
  const sqlCommon = require('../../utils/sql-common.js');
8
9
  const utils = require('./utils.js');
@@ -51,7 +52,7 @@ class MySQL2Instrumentation extends instrumentation.InstrumentationBase {
51
52
  () => {
52
53
  },
53
54
  [
54
- new instrumentation.InstrumentationNodeModuleFile(
55
+ new InstrumentationNodeModuleFile.InstrumentationNodeModuleFile(
55
56
  "mysql2/promise.js",
56
57
  supportedVersions,
57
58
  (moduleExports) => {
@@ -61,7 +62,7 @@ class MySQL2Instrumentation extends instrumentation.InstrumentationBase {
61
62
  () => {
62
63
  }
63
64
  ),
64
- new instrumentation.InstrumentationNodeModuleFile(
65
+ new InstrumentationNodeModuleFile.InstrumentationNodeModuleFile(
65
66
  "mysql2/lib/connection.js",
66
67
  supportedVersions,
67
68
  (moduleExports) => {
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentation.js","sources":["../../../../../../src/integrations/tracing/mysql2/vendored/instrumentation.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * NOTICE from the Sentry authors:\n * - Vendored from: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/15ef7506553f631ea4181391e0c5725a56f0d082/packages/instrumentation-mysql2\n * - Upstream version: @opentelemetry/instrumentation-mysql2@0.64.0\n * - Types from 'mysql2' inlined as simplified interfaces\n * - Minor TypeScript strictness adjustments for this repository's compiler settings\n */\n/* eslint-disable */\n\nimport * as api from '@opentelemetry/api';\nimport { SDK_VERSION } from '@sentry/core';\nimport {\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n InstrumentationNodeModuleFile,\n isWrapped,\n safeExecuteInTheMiddle,\n SemconvStability,\n semconvStabilityFromStr,\n} from '@opentelemetry/instrumentation';\nimport { DB_SYSTEM_VALUE_MYSQL, ATTR_DB_STATEMENT, ATTR_DB_SYSTEM } from './semconv';\nimport { addSqlCommenterComment } from '../../utils/sql-common';\nimport type { Connection, Query, QueryOptions, QueryError, FieldPacket, FormatFunction } from './mysql2-types';\nimport { MySQL2InstrumentationConfig } from './types';\nimport { getConnectionAttributes, getConnectionPrototypeToInstrument, getQueryText, getSpanName, once } from './utils';\nimport {\n ATTR_DB_QUERY_TEXT,\n ATTR_DB_SYSTEM_NAME,\n DB_SYSTEM_NAME_VALUE_MYSQL,\n} from '@opentelemetry/semantic-conventions';\n\nconst PACKAGE_NAME = '@sentry/instrumentation-mysql2';\n\nconst supportedVersions = ['>=1.4.2 <4'];\n\nexport class MySQL2Instrumentation extends InstrumentationBase<MySQL2InstrumentationConfig> {\n private _netSemconvStability!: SemconvStability;\n private _dbSemconvStability!: SemconvStability;\n\n constructor(config: MySQL2InstrumentationConfig = {}) {\n super(PACKAGE_NAME, SDK_VERSION, config);\n this._setSemconvStabilityFromEnv();\n }\n\n private _setSemconvStabilityFromEnv() {\n this._netSemconvStability = semconvStabilityFromStr('http', process.env.OTEL_SEMCONV_STABILITY_OPT_IN);\n this._dbSemconvStability = semconvStabilityFromStr('database', process.env.OTEL_SEMCONV_STABILITY_OPT_IN);\n }\n\n protected init() {\n let format: FormatFunction | undefined;\n function setFormatFunction(moduleExports: any) {\n if (!format && moduleExports.format) {\n format = moduleExports.format;\n }\n }\n const patch = (ConnectionPrototype: Connection) => {\n if (isWrapped(ConnectionPrototype.query)) {\n this._unwrap(ConnectionPrototype, 'query');\n }\n this._wrap(ConnectionPrototype, 'query', this._patchQuery(format, false) as any);\n if (isWrapped(ConnectionPrototype.execute)) {\n this._unwrap(ConnectionPrototype, 'execute');\n }\n this._wrap(ConnectionPrototype, 'execute', this._patchQuery(format, true) as any);\n };\n const unpatch = (ConnectionPrototype: Connection) => {\n this._unwrap(ConnectionPrototype, 'query');\n this._unwrap(ConnectionPrototype, 'execute');\n };\n return [\n new InstrumentationNodeModuleDefinition(\n 'mysql2',\n supportedVersions,\n (moduleExports: any) => {\n setFormatFunction(moduleExports);\n return moduleExports;\n },\n () => {},\n [\n new InstrumentationNodeModuleFile(\n 'mysql2/promise.js',\n supportedVersions,\n (moduleExports: any) => {\n setFormatFunction(moduleExports);\n return moduleExports;\n },\n () => {},\n ),\n new InstrumentationNodeModuleFile(\n 'mysql2/lib/connection.js',\n supportedVersions,\n (moduleExports: any) => {\n const ConnectionPrototype: Connection = getConnectionPrototypeToInstrument(moduleExports);\n patch(ConnectionPrototype);\n return moduleExports;\n },\n (moduleExports: any) => {\n if (moduleExports === undefined) return;\n const ConnectionPrototype: Connection = getConnectionPrototypeToInstrument(moduleExports);\n unpatch(ConnectionPrototype);\n },\n ),\n ],\n ),\n ];\n }\n\n private _patchQuery(format: FormatFunction | undefined, isPrepared: boolean) {\n return (originalQuery: Function): Function => {\n const thisPlugin = this;\n return function query(\n this: Connection,\n query: string | Query | QueryOptions,\n _valuesOrCallback?: unknown[] | Function,\n _callback?: Function,\n ) {\n let values;\n if (Array.isArray(_valuesOrCallback)) {\n values = _valuesOrCallback;\n } else if (arguments[2]) {\n values = [_valuesOrCallback];\n }\n const { maskStatement, maskStatementHook, responseHook } = thisPlugin.getConfig();\n\n const attributes: api.Attributes = getConnectionAttributes(\n this.config,\n thisPlugin._dbSemconvStability,\n thisPlugin._netSemconvStability,\n );\n const dbQueryText = getQueryText(query, format, values, maskStatement, maskStatementHook);\n if (thisPlugin._dbSemconvStability & SemconvStability.OLD) {\n attributes[ATTR_DB_SYSTEM] = DB_SYSTEM_VALUE_MYSQL;\n attributes[ATTR_DB_STATEMENT] = dbQueryText;\n }\n if (thisPlugin._dbSemconvStability & SemconvStability.STABLE) {\n attributes[ATTR_DB_SYSTEM_NAME] = DB_SYSTEM_NAME_VALUE_MYSQL;\n attributes[ATTR_DB_QUERY_TEXT] = dbQueryText;\n }\n\n const span = thisPlugin.tracer.startSpan(getSpanName(query), {\n kind: api.SpanKind.CLIENT,\n attributes,\n });\n\n if (!isPrepared && thisPlugin.getConfig().addSqlCommenterCommentToQueries) {\n arguments[0] = query =\n typeof query === 'string'\n ? addSqlCommenterComment(span, query)\n : Object.assign(query, {\n sql: addSqlCommenterComment(span, query.sql),\n });\n }\n\n const endSpan = once((err?: any, results?: any) => {\n if (err) {\n span.setStatus({\n code: api.SpanStatusCode.ERROR,\n message: err.message,\n });\n } else {\n if (typeof responseHook === 'function') {\n safeExecuteInTheMiddle(\n () => {\n responseHook(span, {\n queryResults: results,\n });\n },\n err => {\n if (err) {\n thisPlugin._diag.warn('Failed executing responseHook', err);\n }\n },\n true,\n );\n }\n }\n\n span.end();\n });\n\n if (arguments.length === 1) {\n if (typeof (query as any).onResult === 'function') {\n thisPlugin._wrap(query as any, 'onResult', thisPlugin._patchCallbackQuery(endSpan));\n }\n\n const streamableQuery: Query = originalQuery.apply(this, arguments);\n\n streamableQuery\n .once('error', (err: any) => {\n endSpan(err);\n })\n .once('result', (results: any) => {\n endSpan(undefined, results);\n });\n\n return streamableQuery;\n }\n\n if (typeof arguments[1] === 'function') {\n thisPlugin._wrap(arguments, 1, thisPlugin._patchCallbackQuery(endSpan));\n } else if (typeof arguments[2] === 'function') {\n thisPlugin._wrap(arguments, 2, thisPlugin._patchCallbackQuery(endSpan));\n }\n\n return originalQuery.apply(this, arguments);\n };\n };\n }\n\n private _patchCallbackQuery(endSpan: Function) {\n return (originalCallback: Function) => {\n return function (err: QueryError | null, results?: any, _fields?: FieldPacket[]) {\n endSpan(err, results);\n return originalCallback(...arguments);\n };\n };\n }\n}\n"],"names":["InstrumentationBase","SDK_VERSION","semconvStabilityFromStr","isWrapped","InstrumentationNodeModuleDefinition","InstrumentationNodeModuleFile","getConnectionPrototypeToInstrument","getConnectionAttributes","getQueryText","SemconvStability","ATTR_DB_SYSTEM","DB_SYSTEM_VALUE_MYSQL","ATTR_DB_STATEMENT","ATTR_DB_SYSTEM_NAME","DB_SYSTEM_NAME_VALUE_MYSQL","ATTR_DB_QUERY_TEXT","getSpanName","addSqlCommenterComment","once","safeExecuteInTheMiddle","err"],"mappings":";;;;;;;;;;AA6CA,MAAM,YAAA,GAAe,gCAAA;AAErB,MAAM,iBAAA,GAAoB,CAAC,YAAY,CAAA;AAEhC,MAAM,8BAA8BA,mCAAA,CAAiD;AAAA,EAI1F,WAAA,CAAY,MAAA,GAAsC,EAAC,EAAG;AACpD,IAAA,KAAA,CAAM,YAAA,EAAcC,kBAAa,MAAM,CAAA;AACvC,IAAA,IAAA,CAAK,2BAAA,EAA4B;AAAA,EACnC;AAAA,EAEQ,2BAAA,GAA8B;AACpC,IAAA,IAAA,CAAK,oBAAA,GAAuBC,uCAAA,CAAwB,MAAA,EAAQ,OAAA,CAAQ,IAAI,6BAA6B,CAAA;AACrG,IAAA,I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,UAAA,UAAA,CAAW,MAAM,SAAA,EAAW,CAAA,EAAG,UAAA,CAAW,mBAAA,CAAoB,OAAO,CAAC,CAAA;AAAA,QACxE,CAAA,MAAA,IAAW,OAAO,SAAA,CAAU,CAAC,MAAM,UAAA,EAAY;AAC7C,UAAA,UAAA,CAAW,MAAM,SAAA,EAAW,CAAA,EAAG,UAAA,CAAW,mBAAA,CAAoB,OAAO,CAAC,CAAA;AAAA,QACxE;AAEA,QAAA,OAAO,aAAA,CAAc,KAAA,CAAM,IAAA,EAAM,SAAS,CAAA;AAAA,MAC5C,CAAA;AAAA,IACF,CAAA;AAAA,EACF;AAAA,EAEQ,oBAAoB,OAAA,EAAmB;AAC7C,IAAA,OAAO,CAAC,gBAAA,KAA+B;AACrC,MAAA,OAAO,SAAU,GAAA,EAAwB,OAAA,EAAe,OAAA,EAAyB;AAC/E,QAAA,OAAA,CAAQ,KAAK,OAAO,CAAA;AACpB,QAAA,OAAO,gBAAA,CAAiB,GAAG,SAAS,CAAA;AAAA,MACtC,CAAA;AAAA,IACF,CAAA;AAAA,EACF;AACF;;;;"}
1
+ {"version":3,"file":"instrumentation.js","sources":["../../../../../../src/integrations/tracing/mysql2/vendored/instrumentation.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * NOTICE from the Sentry authors:\n * - Vendored from: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/15ef7506553f631ea4181391e0c5725a56f0d082/packages/instrumentation-mysql2\n * - Upstream version: @opentelemetry/instrumentation-mysql2@0.64.0\n * - Types from 'mysql2' inlined as simplified interfaces\n * - Minor TypeScript strictness adjustments for this repository's compiler settings\n */\n/* eslint-disable */\n\nimport * as api from '@opentelemetry/api';\nimport { SDK_VERSION } from '@sentry/core';\nimport {\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n isWrapped,\n safeExecuteInTheMiddle,\n SemconvStability,\n semconvStabilityFromStr,\n} from '@opentelemetry/instrumentation';\nimport { InstrumentationNodeModuleFile } from '../../InstrumentationNodeModuleFile';\nimport { DB_SYSTEM_VALUE_MYSQL, ATTR_DB_STATEMENT, ATTR_DB_SYSTEM } from './semconv';\nimport { addSqlCommenterComment } from '../../utils/sql-common';\nimport type { Connection, Query, QueryOptions, QueryError, FieldPacket, FormatFunction } from './mysql2-types';\nimport { MySQL2InstrumentationConfig } from './types';\nimport { getConnectionAttributes, getConnectionPrototypeToInstrument, getQueryText, getSpanName, once } from './utils';\nimport {\n ATTR_DB_QUERY_TEXT,\n ATTR_DB_SYSTEM_NAME,\n DB_SYSTEM_NAME_VALUE_MYSQL,\n} from '@opentelemetry/semantic-conventions';\n\nconst PACKAGE_NAME = '@sentry/instrumentation-mysql2';\n\nconst supportedVersions = ['>=1.4.2 <4'];\n\nexport class MySQL2Instrumentation extends InstrumentationBase<MySQL2InstrumentationConfig> {\n private _netSemconvStability!: SemconvStability;\n private _dbSemconvStability!: SemconvStability;\n\n constructor(config: MySQL2InstrumentationConfig = {}) {\n super(PACKAGE_NAME, SDK_VERSION, config);\n this._setSemconvStabilityFromEnv();\n }\n\n private _setSemconvStabilityFromEnv() {\n this._netSemconvStability = semconvStabilityFromStr('http', process.env.OTEL_SEMCONV_STABILITY_OPT_IN);\n this._dbSemconvStability = semconvStabilityFromStr('database', process.env.OTEL_SEMCONV_STABILITY_OPT_IN);\n }\n\n protected init() {\n let format: FormatFunction | undefined;\n function setFormatFunction(moduleExports: any) {\n if (!format && moduleExports.format) {\n format = moduleExports.format;\n }\n }\n const patch = (ConnectionPrototype: Connection) => {\n if (isWrapped(ConnectionPrototype.query)) {\n this._unwrap(ConnectionPrototype, 'query');\n }\n this._wrap(ConnectionPrototype, 'query', this._patchQuery(format, false) as any);\n if (isWrapped(ConnectionPrototype.execute)) {\n this._unwrap(ConnectionPrototype, 'execute');\n }\n this._wrap(ConnectionPrototype, 'execute', this._patchQuery(format, true) as any);\n };\n const unpatch = (ConnectionPrototype: Connection) => {\n this._unwrap(ConnectionPrototype, 'query');\n this._unwrap(ConnectionPrototype, 'execute');\n };\n return [\n new InstrumentationNodeModuleDefinition(\n 'mysql2',\n supportedVersions,\n (moduleExports: any) => {\n setFormatFunction(moduleExports);\n return moduleExports;\n },\n () => {},\n [\n new InstrumentationNodeModuleFile(\n 'mysql2/promise.js',\n supportedVersions,\n (moduleExports: any) => {\n setFormatFunction(moduleExports);\n return moduleExports;\n },\n () => {},\n ),\n new InstrumentationNodeModuleFile(\n 'mysql2/lib/connection.js',\n supportedVersions,\n (moduleExports: any) => {\n const ConnectionPrototype: Connection = getConnectionPrototypeToInstrument(moduleExports);\n patch(ConnectionPrototype);\n return moduleExports;\n },\n (moduleExports: any) => {\n if (moduleExports === undefined) return;\n const ConnectionPrototype: Connection = getConnectionPrototypeToInstrument(moduleExports);\n unpatch(ConnectionPrototype);\n },\n ),\n ],\n ),\n ];\n }\n\n private _patchQuery(format: FormatFunction | undefined, isPrepared: boolean) {\n return (originalQuery: Function): Function => {\n const thisPlugin = this;\n return function query(\n this: Connection,\n query: string | Query | QueryOptions,\n _valuesOrCallback?: unknown[] | Function,\n _callback?: Function,\n ) {\n let values;\n if (Array.isArray(_valuesOrCallback)) {\n values = _valuesOrCallback;\n } else if (arguments[2]) {\n values = [_valuesOrCallback];\n }\n const { maskStatement, maskStatementHook, responseHook } = thisPlugin.getConfig();\n\n const attributes: api.Attributes = getConnectionAttributes(\n this.config,\n thisPlugin._dbSemconvStability,\n thisPlugin._netSemconvStability,\n );\n const dbQueryText = getQueryText(query, format, values, maskStatement, maskStatementHook);\n if (thisPlugin._dbSemconvStability & SemconvStability.OLD) {\n attributes[ATTR_DB_SYSTEM] = DB_SYSTEM_VALUE_MYSQL;\n attributes[ATTR_DB_STATEMENT] = dbQueryText;\n }\n if (thisPlugin._dbSemconvStability & SemconvStability.STABLE) {\n attributes[ATTR_DB_SYSTEM_NAME] = DB_SYSTEM_NAME_VALUE_MYSQL;\n attributes[ATTR_DB_QUERY_TEXT] = dbQueryText;\n }\n\n const span = thisPlugin.tracer.startSpan(getSpanName(query), {\n kind: api.SpanKind.CLIENT,\n attributes,\n });\n\n if (!isPrepared && thisPlugin.getConfig().addSqlCommenterCommentToQueries) {\n arguments[0] = query =\n typeof query === 'string'\n ? addSqlCommenterComment(span, query)\n : Object.assign(query, {\n sql: addSqlCommenterComment(span, query.sql),\n });\n }\n\n const endSpan = once((err?: any, results?: any) => {\n if (err) {\n span.setStatus({\n code: api.SpanStatusCode.ERROR,\n message: err.message,\n });\n } else {\n if (typeof responseHook === 'function') {\n safeExecuteInTheMiddle(\n () => {\n responseHook(span, {\n queryResults: results,\n });\n },\n err => {\n if (err) {\n thisPlugin._diag.warn('Failed executing responseHook', err);\n }\n },\n true,\n );\n }\n }\n\n span.end();\n });\n\n if (arguments.length === 1) {\n if (typeof (query as any).onResult === 'function') {\n thisPlugin._wrap(query as any, 'onResult', thisPlugin._patchCallbackQuery(endSpan));\n }\n\n const streamableQuery: Query = originalQuery.apply(this, arguments);\n\n streamableQuery\n .once('error', (err: any) => {\n endSpan(err);\n })\n .once('result', (results: any) => {\n endSpan(undefined, results);\n });\n\n return streamableQuery;\n }\n\n if (typeof arguments[1] === 'function') {\n thisPlugin._wrap(arguments, 1, thisPlugin._patchCallbackQuery(endSpan));\n } else if (typeof arguments[2] === 'function') {\n thisPlugin._wrap(arguments, 2, thisPlugin._patchCallbackQuery(endSpan));\n }\n\n return originalQuery.apply(this, arguments);\n };\n };\n }\n\n private _patchCallbackQuery(endSpan: Function) {\n return (originalCallback: Function) => {\n return function (err: QueryError | null, results?: any, _fields?: FieldPacket[]) {\n endSpan(err, results);\n return originalCallback(...arguments);\n };\n };\n }\n}\n"],"names":["InstrumentationBase","SDK_VERSION","semconvStabilityFromStr","isWrapped","InstrumentationNodeModuleDefinition","InstrumentationNodeModuleFile","getConnectionPrototypeToInstrument","getConnectionAttributes","getQueryText","SemconvStability","ATTR_DB_SYSTEM","DB_SYSTEM_VALUE_MYSQL","ATTR_DB_STATEMENT","ATTR_DB_SYSTEM_NAME","DB_SYSTEM_NAME_VALUE_MYSQL","ATTR_DB_QUERY_TEXT","getSpanName","addSqlCommenterComment","once","safeExecuteInTheMiddle","err"],"mappings":";;;;;;;;;;;AA6CA,MAAM,YAAA,GAAe,gCAAA;AAErB,MAAM,iBAAA,GAAoB,CAAC,YAAY,CAAA;AAEhC,MAAM,8BAA8BA,mCAAA,CAAiD;AAAA,EAI1F,WAAA,CAAY,MAAA,GAAsC,EAAC,EAAG;AACpD,IAAA,KAAA,CAAM,YAAA,EAAcC,kBAAa,MAAM,CAAA;AACvC,IAAA,IAAA,CAAK,2BAAA,EAA4B;AAAA,EACnC;AAAA,EAEQ,2BAAA,GAA8B;AACpC,IAAA,IAAA,CAAK,oBAAA,GAAuBC,uCAAA,CAAwB,MAAA,EAAQ,OAAA,CAAQ,IAAI,6BAA6B,CAAA;AACrG,IAAA,IAAA,CAAK,mBAAA,GAAsBA,uCAAA,CAAwB,UAAA,EAAY,OAAA,CAAQ,IAAI,6BAA6B,CAAA;AAAA,EAC1G;AAAA,EAEU,IAAA,GAAO;AACf,IAAA,IAAI,MAAA;AACJ,IAAA,SAAS,kBAAkB,aAAA,EAAoB;AAC7C,MAAA,IAAI,CAAC,MAAA,IAAU,aAAA,CAAc,MAAA,EAAQ;AACnC,QAAA,MAAA,GAAS,aAAA,CAAc,MAAA;AAAA,MACzB;AAAA,IACF;AACA,IAAA,MAAM,KAAA,GAAQ,CAAC,mBAAA,KAAoC;AACjD,MAAA,IAAIC,yBAAA,CAAU,mBAAA,CAAoB,KAAK,CAAA,EAAG;AACxC,QAAA,IAAA,CAAK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BAAA,KAA+B;AACrC,MAAA,OAAO,SAAU,GAAA,EAAwB,OAAA,EAAe,OAAA,EAAyB;AAC/E,QAAA,OAAA,CAAQ,KAAK,OAAO,CAAA;AACpB,QAAA,OAAO,gBAAA,CAAiB,GAAG,SAAS,CAAA;AAAA,MACtC,CAAA;AAAA,IACF,CAAA;AAAA,EACF;AACF;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../../../src/integrations/tracing/openai/index.ts"],"sourcesContent":["import type { IntegrationFn, OpenAiOptions } from '@sentry/core';\nimport { defineIntegration, OPENAI_INTEGRATION_NAME } from '@sentry/core';\nimport { generateInstrumentOnce } from '@sentry/node-core';\nimport { SentryOpenAiInstrumentation } from './instrumentation';\n\nexport const instrumentOpenAi = generateInstrumentOnce<OpenAiOptions>(\n OPENAI_INTEGRATION_NAME,\n options => new SentryOpenAiInstrumentation(options),\n);\n\nconst _openAiIntegration = ((options: OpenAiOptions = {}) => {\n return {\n name: OPENAI_INTEGRATION_NAME,\n setupOnce() {\n instrumentOpenAi(options);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Adds Sentry tracing instrumentation for the OpenAI SDK.\n *\n * This integration is enabled by default.\n *\n * When configured, this integration automatically instruments OpenAI SDK client instances\n * to capture telemetry data following OpenTelemetry Semantic Conventions for Generative AI.\n *\n * @example\n * ```javascript\n * import * as Sentry from '@sentry/node';\n *\n * Sentry.init({\n * integrations: [Sentry.openAIIntegration()],\n * });\n * ```\n *\n * ## Options\n *\n * - `recordInputs`: Whether to record prompt messages (default: respects `sendDefaultPii` client option)\n * - `recordOutputs`: Whether to record response text (default: respects `sendDefaultPii` client option)\n *\n * ### Default Behavior\n *\n * By default, the integration will:\n * - Record inputs and outputs ONLY if `sendDefaultPii` is set to `true` in your Sentry client options\n * - Otherwise, inputs and outputs are NOT recorded unless explicitly enabled\n *\n * @example\n * ```javascript\n * // Record inputs and outputs when sendDefaultPii is false\n * Sentry.init({\n * integrations: [\n * Sentry.openAIIntegration({\n * recordInputs: true,\n * recordOutputs: true\n * })\n * ],\n * });\n *\n * // Never record inputs/outputs regardless of sendDefaultPii\n * Sentry.init({\n * sendDefaultPii: true,\n * integrations: [\n * Sentry.openAIIntegration({\n * recordInputs: false,\n * recordOutputs: false\n * })\n * ],\n * });\n * ```\n *\n */\nexport const openAIIntegration = defineIntegration(_openAiIntegration);\n"],"names":["generateInstrumentOnce","OPENAI_INTEGRATION_NAME","SentryOpenAiInstrumentation","defineIntegration"],"mappings":";;;;;;AAKO,MAAM,gBAAA,GAAmBA,+BAAA;AAAA,EAC9BC,4BAAA;AAAA,EACA,CAAA,OAAA,KAAW,IAAIC,2CAAA,CAA4B,OAAO;AACpD;AAEA,MAAM,kBAAA,IAAsB,CAAC,OAAA,GAAyB,EAAC,KAAM;AAC3D,EAAA,OAAO;AAAA,IACL,IAAA,EAAMD,4BAAA;AAAA,IACN,SAAA,GAAY;AACV,MAAA,gBAAA,CAAiB,OAAO,CAAA;AAAA,IAC1B;AAAA,GACF;AACF,CAAA,CAAA;AAuDO,MAAM,iBAAA,GAAoBE,uBAAkB,kBAAkB;;;;;"}
1
+ {"version":3,"file":"index.js","sources":["../../../../../src/integrations/tracing/openai/index.ts"],"sourcesContent":["import type { IntegrationFn, OpenAiOptions } from '@sentry/core';\nimport { defineIntegration, OPENAI_INTEGRATION_NAME } from '@sentry/core';\nimport { generateInstrumentOnce } from '@sentry/node-core';\nimport { SentryOpenAiInstrumentation } from './instrumentation';\n\nexport const instrumentOpenAi = generateInstrumentOnce<OpenAiOptions>(\n OPENAI_INTEGRATION_NAME,\n options => new SentryOpenAiInstrumentation(options),\n);\n\nconst _openAiIntegration = ((options: OpenAiOptions = {}) => {\n return {\n name: OPENAI_INTEGRATION_NAME,\n setupOnce() {\n instrumentOpenAi(options);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Adds Sentry tracing instrumentation for the OpenAI SDK.\n *\n * This integration is enabled by default.\n *\n * When configured, this integration automatically instruments OpenAI SDK client instances\n * to capture telemetry data following OpenTelemetry Semantic Conventions for Generative AI.\n *\n * @example\n * ```javascript\n * import * as Sentry from '@sentry/node';\n *\n * Sentry.init({\n * integrations: [Sentry.openAIIntegration()],\n * });\n * ```\n *\n * ## Options\n *\n * - `recordInputs`: Whether to record prompt messages (default: follows `sendDefaultPii` or `dataCollection.genAI.inputs`)\n * - `recordOutputs`: Whether to record response text (default: follows `sendDefaultPii` or `dataCollection.genAI.outputs`)\n *\n * ### Default Behavior\n *\n * By default, the integration will:\n * - Record inputs and outputs based on `sendDefaultPii` or `dataCollection.genAI` in your Sentry client options\n * - Integration-level `recordInputs`/`recordOutputs` options take precedence over global config\n *\n * @example\n * ```javascript\n * // Always record inputs and outputs regardless of global dataCollection config\n * Sentry.init({\n * integrations: [\n * Sentry.openAIIntegration({\n * recordInputs: true,\n * recordOutputs: true\n * })\n * ],\n * });\n *\n * // Never record inputs/outputs regardless of global dataCollection config\n * Sentry.init({\n * dataCollection: { genAI: { inputs: true, outputs: true } },\n * integrations: [\n * Sentry.openAIIntegration({\n * recordInputs: false,\n * recordOutputs: false\n * })\n * ],\n * });\n * ```\n *\n */\nexport const openAIIntegration = defineIntegration(_openAiIntegration);\n"],"names":["generateInstrumentOnce","OPENAI_INTEGRATION_NAME","SentryOpenAiInstrumentation","defineIntegration"],"mappings":";;;;;;AAKO,MAAM,gBAAA,GAAmBA,+BAAA;AAAA,EAC9BC,4BAAA;AAAA,EACA,CAAA,OAAA,KAAW,IAAIC,2CAAA,CAA4B,OAAO;AACpD;AAEA,MAAM,kBAAA,IAAsB,CAAC,OAAA,GAAyB,EAAC,KAAM;AAC3D,EAAA,OAAO;AAAA,IACL,IAAA,EAAMD,4BAAA;AAAA,IACN,SAAA,GAAY;AACV,MAAA,gBAAA,CAAiB,OAAO,CAAA;AAAA,IAC1B;AAAA,GACF;AACF,CAAA,CAAA;AAuDO,MAAM,iBAAA,GAAoBE,uBAAkB,kBAAkB;;;;;"}
@@ -1,13 +1,13 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
 
3
3
  const instrumentation = require('@opentelemetry/instrumentation');
4
+ const InstrumentationNodeModuleFile = require('../../InstrumentationNodeModuleFile.js');
4
5
  const api = require('@opentelemetry/api');
5
6
  const internalTypes = require('./internal-types.js');
6
7
  const utils = require('./utils.js');
7
8
  const sqlCommon = require('../../utils/sql-common.js');
8
9
  const core = require('@sentry/core');
9
10
  const SpanNames = require('./enums/SpanNames.js');
10
- const core$1 = require('@opentelemetry/core');
11
11
  const semanticConventions = require('@opentelemetry/semantic-conventions');
12
12
  const semconv = require('./semconv.js');
13
13
 
@@ -56,13 +56,13 @@ class PgInstrumentation extends instrumentation.InstrumentationBase {
56
56
  init() {
57
57
  const SUPPORTED_PG_VERSIONS = [">=8.0.3 <9"];
58
58
  const SUPPORTED_PG_POOL_VERSIONS = [">=2.0.0 <4"];
59
- const modulePgNativeClient = new instrumentation.InstrumentationNodeModuleFile(
59
+ const modulePgNativeClient = new InstrumentationNodeModuleFile.InstrumentationNodeModuleFile(
60
60
  "pg/lib/native/client.js",
61
61
  SUPPORTED_PG_VERSIONS,
62
62
  this._patchPgClient.bind(this),
63
63
  this._unpatchPgClient.bind(this)
64
64
  );
65
- const modulePgClient = new instrumentation.InstrumentationNodeModuleFile(
65
+ const modulePgClient = new InstrumentationNodeModuleFile.InstrumentationNodeModuleFile(
66
66
  "pg/lib/client.js",
67
67
  SUPPORTED_PG_VERSIONS,
68
68
  this._patchPgClient.bind(this),
@@ -174,7 +174,7 @@ class PgInstrumentation extends instrumentation.InstrumentationBase {
174
174
  metricsAttributes[key] = attributes[key];
175
175
  }
176
176
  });
177
- const durationSeconds = core$1.hrTimeToMilliseconds(core$1.hrTimeDuration(startTime, core$1.hrTime())) / 1e3;
177
+ const durationSeconds = core.timestampInSeconds() - startTime;
178
178
  this._operationDuration.record(durationSeconds, metricsAttributes);
179
179
  }
180
180
  _getClientQueryPatch() {
@@ -185,7 +185,7 @@ class PgInstrumentation extends instrumentation.InstrumentationBase {
185
185
  if (utils.shouldSkipInstrumentation(plugin.getConfig())) {
186
186
  return original.apply(this, args);
187
187
  }
188
- const startTime = core$1.hrTime();
188
+ const startTime = core.timestampInSeconds();
189
189
  const arg0 = args[0];
190
190
  const firstArgIsString = typeof arg0 === "string";
191
191
  const firstArgIsQueryObjectWithText = utils.isObjectWithTextString(arg0);
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentation.js","sources":["../../../../../../src/integrations/tracing/postgres/vendored/instrumentation.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * NOTICE from the Sentry authors:\n * - Vendored from: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/15ef7506553f631ea4181391e0c5725a56f0d082/packages/instrumentation-pg\n * - Upstream version: @opentelemetry/instrumentation-pg@0.70.0\n * - Types from `pg` and `pg-pool` packages inlined as simplified interfaces\n * - Minor TypeScript strictness adjustments\n */\n/* eslint-disable */\n\nimport {\n isWrapped,\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n safeExecuteInTheMiddle,\n InstrumentationNodeModuleFile,\n SemconvStability,\n semconvStabilityFromStr,\n} from '@opentelemetry/instrumentation';\nimport {\n context,\n trace,\n Span,\n SpanStatusCode,\n SpanKind,\n Histogram,\n ValueType,\n Attributes,\n HrTime,\n UpDownCounter,\n} from '@opentelemetry/api';\nimport type { PgClient } from './pg-types';\nimport {\n PgClientConnect,\n PgClientExtended,\n PostgresCallback,\n PgPoolExtended,\n PgPoolCallback,\n EVENT_LISTENERS_SET,\n} from './internal-types';\nimport { PgInstrumentationConfig } from './types';\nimport * as utils from './utils';\nimport { addSqlCommenterComment } from '../../utils/sql-common';\nimport { SDK_VERSION } from '@sentry/core';\nconst PACKAGE_NAME = '@sentry/instrumentation-pg';\nimport { SpanNames } from './enums/SpanNames';\nimport { hrTime, hrTimeDuration, hrTimeToMilliseconds } from '@opentelemetry/core';\nimport {\n ATTR_ERROR_TYPE,\n ATTR_SERVER_PORT,\n ATTR_SERVER_ADDRESS,\n ATTR_DB_NAMESPACE,\n ATTR_DB_OPERATION_NAME,\n ATTR_DB_SYSTEM_NAME,\n METRIC_DB_CLIENT_OPERATION_DURATION,\n} from '@opentelemetry/semantic-conventions';\nimport {\n METRIC_DB_CLIENT_CONNECTION_COUNT,\n METRIC_DB_CLIENT_CONNECTION_PENDING_REQUESTS,\n ATTR_DB_SYSTEM,\n DB_SYSTEM_VALUE_POSTGRESQL,\n} from './semconv';\n\nfunction extractModuleExports(module: any) {\n return module[Symbol.toStringTag] === 'Module'\n ? module.default // ESM\n : module; // CommonJS\n}\n\nexport class PgInstrumentation extends InstrumentationBase<PgInstrumentationConfig> {\n declare private _operationDuration: Histogram;\n declare private _connectionsCount: UpDownCounter;\n declare private _connectionPendingRequests: UpDownCounter;\n // Pool events connect, acquire, release and remove can be called\n // multiple times without changing the values of total, idle and waiting\n // connections. The _connectionsCounter is used to keep track of latest\n // values and only update the metrics _connectionsCount and _connectionPendingRequests\n // when the value change.\n private _connectionsCounter: utils.poolConnectionsCounter = {\n used: 0,\n idle: 0,\n pending: 0,\n };\n private _semconvStability: SemconvStability;\n\n constructor(config: PgInstrumentationConfig = {}) {\n super(PACKAGE_NAME, SDK_VERSION, config);\n this._semconvStability = semconvStabilityFromStr('database', process.env.OTEL_SEMCONV_STABILITY_OPT_IN);\n }\n\n override _updateMetricInstruments() {\n this._operationDuration = this.meter.createHistogram(METRIC_DB_CLIENT_OPERATION_DURATION, {\n description: 'Duration of database client operations.',\n unit: 's',\n valueType: ValueType.DOUBLE,\n advice: {\n explicitBucketBoundaries: [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10],\n },\n });\n\n this._connectionsCounter = {\n idle: 0,\n pending: 0,\n used: 0,\n };\n this._connectionsCount = this.meter.createUpDownCounter(METRIC_DB_CLIENT_CONNECTION_COUNT, {\n description: 'The number of connections that are currently in state described by the state attribute.',\n unit: '{connection}',\n });\n this._connectionPendingRequests = this.meter.createUpDownCounter(METRIC_DB_CLIENT_CONNECTION_PENDING_REQUESTS, {\n description: 'The number of current pending requests for an open connection.',\n unit: '{connection}',\n });\n }\n\n protected init() {\n const SUPPORTED_PG_VERSIONS = ['>=8.0.3 <9'];\n const SUPPORTED_PG_POOL_VERSIONS = ['>=2.0.0 <4'];\n\n const modulePgNativeClient = new InstrumentationNodeModuleFile(\n 'pg/lib/native/client.js',\n SUPPORTED_PG_VERSIONS,\n this._patchPgClient.bind(this),\n this._unpatchPgClient.bind(this),\n );\n\n const modulePgClient = new InstrumentationNodeModuleFile(\n 'pg/lib/client.js',\n SUPPORTED_PG_VERSIONS,\n this._patchPgClient.bind(this),\n this._unpatchPgClient.bind(this),\n );\n\n const modulePG = new InstrumentationNodeModuleDefinition(\n 'pg',\n SUPPORTED_PG_VERSIONS,\n (module: any) => {\n const moduleExports = extractModuleExports(module);\n\n this._patchPgClient(moduleExports.Client);\n return module;\n },\n (module: any) => {\n const moduleExports = extractModuleExports(module);\n\n this._unpatchPgClient(moduleExports.Client);\n return module;\n },\n [modulePgClient, modulePgNativeClient],\n );\n\n const modulePGPool = new InstrumentationNodeModuleDefinition(\n 'pg-pool',\n SUPPORTED_PG_POOL_VERSIONS,\n (module: any) => {\n const moduleExports = extractModuleExports(module);\n if (isWrapped(moduleExports.prototype.connect)) {\n this._unwrap(moduleExports.prototype, 'connect');\n }\n this._wrap(moduleExports.prototype, 'connect', this._getPoolConnectPatch() as any);\n return moduleExports;\n },\n (module: any) => {\n const moduleExports = extractModuleExports(module);\n if (isWrapped(moduleExports.prototype.connect)) {\n this._unwrap(moduleExports.prototype, 'connect');\n }\n },\n );\n\n return [modulePG, modulePGPool];\n }\n\n private _patchPgClient(module: any) {\n if (!module) {\n return;\n }\n\n const moduleExports = extractModuleExports(module);\n\n if (isWrapped(moduleExports.prototype.query)) {\n this._unwrap(moduleExports.prototype, 'query');\n }\n\n if (isWrapped(moduleExports.prototype.connect)) {\n this._unwrap(moduleExports.prototype, 'connect');\n }\n\n this._wrap(moduleExports.prototype, 'query', this._getClientQueryPatch() as any);\n\n this._wrap(moduleExports.prototype, 'connect', this._getClientConnectPatch() as any);\n\n return module;\n }\n\n private _unpatchPgClient(module: any) {\n const moduleExports = extractModuleExports(module);\n\n if (isWrapped(moduleExports.prototype.query)) {\n this._unwrap(moduleExports.prototype, 'query');\n }\n\n if (isWrapped(moduleExports.prototype.connect)) {\n this._unwrap(moduleExports.prototype, 'connect');\n }\n\n return module;\n }\n\n private _getClientConnectPatch() {\n const plugin = this;\n return (original: PgClientConnect) => {\n return function connect(this: PgClient, callback?: Function) {\n const config = plugin.getConfig();\n\n if (utils.shouldSkipInstrumentation(config) || config.ignoreConnectSpans) {\n return original.call(this, callback);\n }\n\n const span = plugin.tracer.startSpan(SpanNames.CONNECT, {\n kind: SpanKind.CLIENT,\n attributes: utils.getSemanticAttributesFromConnection(this, plugin._semconvStability),\n });\n\n if (callback) {\n const parentSpan = trace.getSpan(context.active());\n callback = utils.patchClientConnectCallback(span, callback);\n if (parentSpan) {\n callback = context.bind(context.active(), callback);\n }\n }\n\n const connectResult: unknown = context.with(trace.setSpan(context.active(), span), () => {\n return original.call(this, callback);\n });\n\n return handleConnectResult(span, connectResult);\n };\n };\n }\n\n private recordOperationDuration(attributes: Attributes, startTime: HrTime) {\n const metricsAttributes: Attributes = {};\n const keysToCopy: string[] = [\n ATTR_DB_NAMESPACE,\n ATTR_ERROR_TYPE,\n ATTR_SERVER_PORT,\n ATTR_SERVER_ADDRESS,\n ATTR_DB_OPERATION_NAME,\n ];\n if (this._semconvStability & SemconvStability.OLD) {\n keysToCopy.push(ATTR_DB_SYSTEM);\n }\n if (this._semconvStability & SemconvStability.STABLE) {\n keysToCopy.push(ATTR_DB_SYSTEM_NAME);\n }\n\n keysToCopy.forEach(key => {\n if (key in attributes) {\n metricsAttributes[key] = attributes[key];\n }\n });\n\n const durationSeconds = hrTimeToMilliseconds(hrTimeDuration(startTime, hrTime())) / 1000;\n this._operationDuration.record(durationSeconds, metricsAttributes);\n }\n\n private _getClientQueryPatch() {\n const plugin = this;\n return (original: (...args: any[]) => any) => {\n this._diag.debug('Patching pg.Client.prototype.query');\n return function query(this: PgClientExtended, ...args: unknown[]) {\n if (utils.shouldSkipInstrumentation(plugin.getConfig())) {\n return original.apply(this, args as never);\n }\n const startTime = hrTime();\n\n // client.query(text, cb?), client.query(text, values, cb?), and\n // client.query(configObj, cb?) are all valid signatures. We construct\n // a queryConfig obj from all (valid) signatures to build the span in a\n // unified way. We verify that we at least have query text, and code\n // defensively when dealing with `queryConfig` after that (to handle all\n // the other invalid cases, like a non-array for values being provided).\n // The type casts here reflect only what we've actually validated.\n const arg0 = args[0];\n const firstArgIsString = typeof arg0 === 'string';\n const firstArgIsQueryObjectWithText = utils.isObjectWithTextString(arg0);\n\n // TODO: remove the `as ...` casts below when the TS version is upgraded.\n // Newer TS versions will use the result of firstArgIsQueryObjectWithText\n // to properly narrow arg0, but TS 4.3.5 does not.\n const queryConfig = firstArgIsString\n ? {\n text: arg0 as string,\n values: Array.isArray(args[1]) ? args[1] : undefined,\n }\n : firstArgIsQueryObjectWithText\n ? {\n ...(arg0 as any),\n name: arg0.name,\n text: arg0.text,\n values: (arg0 as any).values ?? (Array.isArray(args[1]) ? args[1] : undefined),\n }\n : undefined;\n\n const attributes: Attributes = {\n [ATTR_DB_SYSTEM]: DB_SYSTEM_VALUE_POSTGRESQL,\n [ATTR_DB_NAMESPACE]: this.database,\n [ATTR_SERVER_PORT]: this.connectionParameters.port,\n [ATTR_SERVER_ADDRESS]: this.connectionParameters.host,\n };\n\n if (queryConfig?.text) {\n attributes[ATTR_DB_OPERATION_NAME] = utils.parseNormalizedOperationName(queryConfig?.text);\n }\n\n const recordDuration = () => {\n plugin.recordOperationDuration(attributes, startTime);\n };\n\n const instrumentationConfig = plugin.getConfig();\n\n const span = utils.handleConfigQuery.call(\n this,\n plugin.tracer,\n instrumentationConfig,\n plugin._semconvStability,\n queryConfig,\n );\n\n // Modify query text w/ a tracing comment before invoking original for\n // tracing, but only if args[0] has one of our expected shapes.\n if (instrumentationConfig.addSqlCommenterCommentToQueries) {\n if (firstArgIsString) {\n args[0] = addSqlCommenterComment(span, arg0);\n } else if (firstArgIsQueryObjectWithText && !('name' in arg0)) {\n // In the case of a query object, we need to ensure there's no name field\n // as this indicates a prepared query, where the comment would remain the same\n // for every invocation and contain an outdated trace context.\n args[0] = {\n ...arg0,\n text: addSqlCommenterComment(span, arg0.text),\n };\n }\n }\n\n // Bind callback (if any) to parent span (if any)\n if (args.length > 0) {\n const parentSpan = trace.getSpan(context.active());\n if (typeof args[args.length - 1] === 'function') {\n // Patch ParameterQuery callback\n args[args.length - 1] = utils.patchCallback(\n instrumentationConfig,\n span,\n args[args.length - 1] as PostgresCallback, // nb: not type safe.\n attributes,\n recordDuration,\n );\n\n // If a parent span exists, bind the callback\n if (parentSpan) {\n args[args.length - 1] = context.bind(context.active(), args[args.length - 1]);\n }\n } else if (typeof queryConfig?.callback === 'function') {\n // Patch ConfigQuery callback\n let callback = utils.patchCallback(\n plugin.getConfig(),\n span,\n queryConfig.callback as PostgresCallback, // nb: not type safe.\n attributes,\n recordDuration,\n );\n\n // If a parent span existed, bind the callback\n if (parentSpan) {\n callback = context.bind(context.active(), callback);\n }\n\n (args[0] as { callback?: PostgresCallback }).callback = callback;\n }\n }\n\n const { requestHook } = instrumentationConfig;\n if (typeof requestHook === 'function' && queryConfig) {\n safeExecuteInTheMiddle(\n () => {\n // pick keys to expose explicitly, so we're not leaking pg package\n // internals that are subject to change\n const { database, host, port, user } = this.connectionParameters;\n const connection = { database, host, port, user };\n\n requestHook(span, {\n connection,\n query: {\n text: queryConfig.text,\n // nb: if `client.query` is called with illegal arguments\n // (e.g., if `queryConfig.values` is passed explicitly, but a\n // non-array is given), then the type casts will be wrong. But\n // we leave it up to the queryHook to handle that, and we\n // catch and swallow any errors it throws. The other options\n // are all worse. E.g., we could leave `queryConfig.values`\n // and `queryConfig.name` as `unknown`, but then the hook body\n // would be forced to validate (or cast) them before using\n // them, which seems incredibly cumbersome given that these\n // casts will be correct 99.9% of the time -- and pg.query\n // will immediately throw during development in the other .1%\n // of cases. Alternatively, we could simply skip calling the\n // hook when `values` or `name` don't have the expected type,\n // but that would add unnecessary validation overhead to every\n // hook invocation and possibly be even more confusing/unexpected.\n values: queryConfig.values as unknown[],\n name: queryConfig.name as string | undefined,\n },\n });\n },\n err => {\n if (err) {\n plugin._diag.error('Error running query hook', err);\n }\n },\n true,\n );\n }\n\n let result: unknown;\n try {\n result = original.apply(this, args as never);\n } catch (e: unknown) {\n if (e instanceof Error) {\n span.recordException(utils.sanitizedErrorMessage(e));\n }\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: utils.getErrorMessage(e),\n });\n span.end();\n throw e;\n }\n\n // Bind promise to parent span and end the span\n if (result instanceof Promise) {\n return result\n .then((result: unknown) => {\n // Return a pass-along promise which ends the span and then goes to user's orig resolvers\n return new Promise(resolve => {\n utils.handleExecutionResult(plugin.getConfig(), span, result);\n recordDuration();\n span.end();\n resolve(result);\n });\n })\n .catch((error: Error) => {\n return new Promise((_, reject) => {\n if (error instanceof Error) {\n span.recordException(utils.sanitizedErrorMessage(error));\n }\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n recordDuration();\n span.end();\n reject(error);\n });\n });\n }\n\n // else returns void\n return result; // void\n };\n };\n }\n\n private _setPoolConnectEventListeners(pgPool: PgPoolExtended) {\n if (pgPool[EVENT_LISTENERS_SET]) return;\n const poolName = utils.getPoolName(pgPool.options);\n\n pgPool.on('connect', () => {\n this._connectionsCounter = utils.updateCounter(\n poolName,\n pgPool,\n this._connectionsCount,\n this._connectionPendingRequests,\n this._connectionsCounter,\n );\n });\n\n pgPool.on('acquire', () => {\n this._connectionsCounter = utils.updateCounter(\n poolName,\n pgPool,\n this._connectionsCount,\n this._connectionPendingRequests,\n this._connectionsCounter,\n );\n });\n\n pgPool.on('remove', () => {\n this._connectionsCounter = utils.updateCounter(\n poolName,\n pgPool,\n this._connectionsCount,\n this._connectionPendingRequests,\n this._connectionsCounter,\n );\n });\n\n pgPool.on('release' as any, () => {\n this._connectionsCounter = utils.updateCounter(\n poolName,\n pgPool,\n this._connectionsCount,\n this._connectionPendingRequests,\n this._connectionsCounter,\n );\n });\n pgPool[EVENT_LISTENERS_SET] = true;\n }\n\n private _getPoolConnectPatch() {\n const plugin = this;\n return (originalConnect: (...args: any[]) => any) => {\n return function connect(this: PgPoolExtended, callback?: PgPoolCallback) {\n const config = plugin.getConfig();\n\n if (utils.shouldSkipInstrumentation(config)) {\n return originalConnect.call(this, callback as any);\n }\n\n // Still set up event listeners for metrics even when skipping spans\n plugin._setPoolConnectEventListeners(this);\n\n if (config.ignoreConnectSpans) {\n return originalConnect.call(this, callback as any);\n }\n\n // setup span\n const span = plugin.tracer.startSpan(SpanNames.POOL_CONNECT, {\n kind: SpanKind.CLIENT,\n attributes: utils.getSemanticAttributesFromPoolConnection(this.options, plugin._semconvStability),\n });\n\n if (callback) {\n const parentSpan = trace.getSpan(context.active());\n callback = utils.patchCallbackPGPool(span, callback) as PgPoolCallback;\n // If a parent span exists, bind the callback\n if (parentSpan) {\n callback = context.bind(context.active(), callback);\n }\n }\n\n const connectResult: unknown = context.with(trace.setSpan(context.active(), span), () => {\n return originalConnect.call(this, callback as any);\n });\n\n return handleConnectResult(span, connectResult);\n };\n };\n }\n}\n\nfunction handleConnectResult(span: Span, connectResult: unknown) {\n if (!(connectResult instanceof Promise)) {\n return connectResult;\n }\n\n const connectResultPromise = connectResult as Promise<unknown>;\n return context.bind(\n context.active(),\n connectResultPromise\n .then(result => {\n span.end();\n return result;\n })\n .catch((error: unknown) => {\n if (error instanceof Error) {\n span.recordException(utils.sanitizedErrorMessage(error));\n }\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: utils.getErrorMessage(error),\n });\n span.end();\n return Promise.reject(error);\n }),\n );\n}\n"],"names":["InstrumentationBase","SDK_VERSION","semconvStabilityFromStr","METRIC_DB_CLIENT_OPERATION_DURATION","ValueType","METRIC_DB_CLIENT_CONNECTION_COUNT","METRIC_DB_CLIENT_CONNECTION_PENDING_REQUESTS","InstrumentationNodeModuleFile","InstrumentationNodeModuleDefinition","isWrapped","utils.shouldSkipInstrumentation","SpanNames","SpanKind","utils.getSemanticAttributesFromConnection","trace","context","utils.patchClientConnectCallback","ATTR_DB_NAMESPACE","ATTR_ERROR_TYPE","ATTR_SERVER_PORT","ATTR_SERVER_ADDRESS","ATTR_DB_OPERATION_NAME","SemconvStability","ATTR_DB_SYSTEM","ATTR_DB_SYSTEM_NAME","hrTimeToMilliseconds","hrTimeDuration","hrTime","utils.isObjectWithTextString","DB_SYSTEM_VALUE_POSTGRESQL","utils.parseNormalizedOperationName","utils.handleConfigQuery","addSqlCommenterComment","utils.patchCallback","safeExecuteInTheMiddle","utils.sanitizedErrorMessage","SpanStatusCode","utils.getErrorMessage","result","utils.handleExecutionResult","EVENT_LISTENERS_SET","utils.getPoolName","utils.updateCounter","utils.getSemanticAttributesFromPoolConnection","utils.patchCallbackPGPool"],"mappings":";;;;;;;;;;;;;AAyDA,MAAM,YAAA,GAAe,4BAAA;AAmBrB,SAAS,qBAAqB,MAAA,EAAa;AACzC,EAAA,OAAO,OAAO,MAAA,CAAO,WAAW,CAAA,KAAM,QAAA,GAClC,OAAO,OAAA,GACP,MAAA;AACN;AAEO,MAAM,0BAA0BA,mCAAA,CAA6C;AAAA,EAgBlF,WAAA,CAAY,MAAA,GAAkC,EAAC,EAAG;AAChD,IAAA,KAAA,CAAM,YAAA,EAAcC,kBAAa,MAAM,C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C,CAAA;AACD,MAAA,IAAA,CAAK,GAAA,EAAI;AACT,MAAA,OAAO,OAAA,CAAQ,OAAO,KAAK,CAAA;AAAA,IAC7B,CAAC;AAAA,GACL;AACF;;;;"}
1
+ {"version":3,"file":"instrumentation.js","sources":["../../../../../../src/integrations/tracing/postgres/vendored/instrumentation.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * NOTICE from the Sentry authors:\n * - Vendored from: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/15ef7506553f631ea4181391e0c5725a56f0d082/packages/instrumentation-pg\n * - Upstream version: @opentelemetry/instrumentation-pg@0.70.0\n * - Types from `pg` and `pg-pool` packages inlined as simplified interfaces\n * - Minor TypeScript strictness adjustments\n */\n/* eslint-disable */\n\nimport {\n isWrapped,\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n safeExecuteInTheMiddle,\n SemconvStability,\n semconvStabilityFromStr,\n} from '@opentelemetry/instrumentation';\nimport { InstrumentationNodeModuleFile } from '../../InstrumentationNodeModuleFile';\nimport {\n context,\n trace,\n Span,\n SpanStatusCode,\n SpanKind,\n Histogram,\n ValueType,\n Attributes,\n UpDownCounter,\n} from '@opentelemetry/api';\nimport type { PgClient } from './pg-types';\nimport {\n PgClientConnect,\n PgClientExtended,\n PostgresCallback,\n PgPoolExtended,\n PgPoolCallback,\n EVENT_LISTENERS_SET,\n} from './internal-types';\nimport { PgInstrumentationConfig } from './types';\nimport * as utils from './utils';\nimport { addSqlCommenterComment } from '../../utils/sql-common';\nimport { SDK_VERSION, timestampInSeconds } from '@sentry/core';\nconst PACKAGE_NAME = '@sentry/instrumentation-pg';\nimport { SpanNames } from './enums/SpanNames';\nimport {\n ATTR_ERROR_TYPE,\n ATTR_SERVER_PORT,\n ATTR_SERVER_ADDRESS,\n ATTR_DB_NAMESPACE,\n ATTR_DB_OPERATION_NAME,\n ATTR_DB_SYSTEM_NAME,\n METRIC_DB_CLIENT_OPERATION_DURATION,\n} from '@opentelemetry/semantic-conventions';\nimport {\n METRIC_DB_CLIENT_CONNECTION_COUNT,\n METRIC_DB_CLIENT_CONNECTION_PENDING_REQUESTS,\n ATTR_DB_SYSTEM,\n DB_SYSTEM_VALUE_POSTGRESQL,\n} from './semconv';\n\nfunction extractModuleExports(module: any) {\n return module[Symbol.toStringTag] === 'Module'\n ? module.default // ESM\n : module; // CommonJS\n}\n\nexport class PgInstrumentation extends InstrumentationBase<PgInstrumentationConfig> {\n declare private _operationDuration: Histogram;\n declare private _connectionsCount: UpDownCounter;\n declare private _connectionPendingRequests: UpDownCounter;\n // Pool events connect, acquire, release and remove can be called\n // multiple times without changing the values of total, idle and waiting\n // connections. The _connectionsCounter is used to keep track of latest\n // values and only update the metrics _connectionsCount and _connectionPendingRequests\n // when the value change.\n private _connectionsCounter: utils.poolConnectionsCounter = {\n used: 0,\n idle: 0,\n pending: 0,\n };\n private _semconvStability: SemconvStability;\n\n constructor(config: PgInstrumentationConfig = {}) {\n super(PACKAGE_NAME, SDK_VERSION, config);\n this._semconvStability = semconvStabilityFromStr('database', process.env.OTEL_SEMCONV_STABILITY_OPT_IN);\n }\n\n override _updateMetricInstruments() {\n this._operationDuration = this.meter.createHistogram(METRIC_DB_CLIENT_OPERATION_DURATION, {\n description: 'Duration of database client operations.',\n unit: 's',\n valueType: ValueType.DOUBLE,\n advice: {\n explicitBucketBoundaries: [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10],\n },\n });\n\n this._connectionsCounter = {\n idle: 0,\n pending: 0,\n used: 0,\n };\n this._connectionsCount = this.meter.createUpDownCounter(METRIC_DB_CLIENT_CONNECTION_COUNT, {\n description: 'The number of connections that are currently in state described by the state attribute.',\n unit: '{connection}',\n });\n this._connectionPendingRequests = this.meter.createUpDownCounter(METRIC_DB_CLIENT_CONNECTION_PENDING_REQUESTS, {\n description: 'The number of current pending requests for an open connection.',\n unit: '{connection}',\n });\n }\n\n protected init() {\n const SUPPORTED_PG_VERSIONS = ['>=8.0.3 <9'];\n const SUPPORTED_PG_POOL_VERSIONS = ['>=2.0.0 <4'];\n\n const modulePgNativeClient = new InstrumentationNodeModuleFile(\n 'pg/lib/native/client.js',\n SUPPORTED_PG_VERSIONS,\n this._patchPgClient.bind(this),\n this._unpatchPgClient.bind(this),\n );\n\n const modulePgClient = new InstrumentationNodeModuleFile(\n 'pg/lib/client.js',\n SUPPORTED_PG_VERSIONS,\n this._patchPgClient.bind(this),\n this._unpatchPgClient.bind(this),\n );\n\n const modulePG = new InstrumentationNodeModuleDefinition(\n 'pg',\n SUPPORTED_PG_VERSIONS,\n (module: any) => {\n const moduleExports = extractModuleExports(module);\n\n this._patchPgClient(moduleExports.Client);\n return module;\n },\n (module: any) => {\n const moduleExports = extractModuleExports(module);\n\n this._unpatchPgClient(moduleExports.Client);\n return module;\n },\n [modulePgClient, modulePgNativeClient],\n );\n\n const modulePGPool = new InstrumentationNodeModuleDefinition(\n 'pg-pool',\n SUPPORTED_PG_POOL_VERSIONS,\n (module: any) => {\n const moduleExports = extractModuleExports(module);\n if (isWrapped(moduleExports.prototype.connect)) {\n this._unwrap(moduleExports.prototype, 'connect');\n }\n this._wrap(moduleExports.prototype, 'connect', this._getPoolConnectPatch() as any);\n return moduleExports;\n },\n (module: any) => {\n const moduleExports = extractModuleExports(module);\n if (isWrapped(moduleExports.prototype.connect)) {\n this._unwrap(moduleExports.prototype, 'connect');\n }\n },\n );\n\n return [modulePG, modulePGPool];\n }\n\n private _patchPgClient(module: any) {\n if (!module) {\n return;\n }\n\n const moduleExports = extractModuleExports(module);\n\n if (isWrapped(moduleExports.prototype.query)) {\n this._unwrap(moduleExports.prototype, 'query');\n }\n\n if (isWrapped(moduleExports.prototype.connect)) {\n this._unwrap(moduleExports.prototype, 'connect');\n }\n\n this._wrap(moduleExports.prototype, 'query', this._getClientQueryPatch() as any);\n\n this._wrap(moduleExports.prototype, 'connect', this._getClientConnectPatch() as any);\n\n return module;\n }\n\n private _unpatchPgClient(module: any) {\n const moduleExports = extractModuleExports(module);\n\n if (isWrapped(moduleExports.prototype.query)) {\n this._unwrap(moduleExports.prototype, 'query');\n }\n\n if (isWrapped(moduleExports.prototype.connect)) {\n this._unwrap(moduleExports.prototype, 'connect');\n }\n\n return module;\n }\n\n private _getClientConnectPatch() {\n const plugin = this;\n return (original: PgClientConnect) => {\n return function connect(this: PgClient, callback?: Function) {\n const config = plugin.getConfig();\n\n if (utils.shouldSkipInstrumentation(config) || config.ignoreConnectSpans) {\n return original.call(this, callback);\n }\n\n const span = plugin.tracer.startSpan(SpanNames.CONNECT, {\n kind: SpanKind.CLIENT,\n attributes: utils.getSemanticAttributesFromConnection(this, plugin._semconvStability),\n });\n\n if (callback) {\n const parentSpan = trace.getSpan(context.active());\n callback = utils.patchClientConnectCallback(span, callback);\n if (parentSpan) {\n callback = context.bind(context.active(), callback);\n }\n }\n\n const connectResult: unknown = context.with(trace.setSpan(context.active(), span), () => {\n return original.call(this, callback);\n });\n\n return handleConnectResult(span, connectResult);\n };\n };\n }\n\n private recordOperationDuration(attributes: Attributes, startTime: number) {\n const metricsAttributes: Attributes = {};\n const keysToCopy: string[] = [\n ATTR_DB_NAMESPACE,\n ATTR_ERROR_TYPE,\n ATTR_SERVER_PORT,\n ATTR_SERVER_ADDRESS,\n ATTR_DB_OPERATION_NAME,\n ];\n if (this._semconvStability & SemconvStability.OLD) {\n keysToCopy.push(ATTR_DB_SYSTEM);\n }\n if (this._semconvStability & SemconvStability.STABLE) {\n keysToCopy.push(ATTR_DB_SYSTEM_NAME);\n }\n\n keysToCopy.forEach(key => {\n if (key in attributes) {\n metricsAttributes[key] = attributes[key];\n }\n });\n\n const durationSeconds = timestampInSeconds() - startTime;\n this._operationDuration.record(durationSeconds, metricsAttributes);\n }\n\n private _getClientQueryPatch() {\n const plugin = this;\n return (original: (...args: any[]) => any) => {\n this._diag.debug('Patching pg.Client.prototype.query');\n return function query(this: PgClientExtended, ...args: unknown[]) {\n if (utils.shouldSkipInstrumentation(plugin.getConfig())) {\n return original.apply(this, args as never);\n }\n const startTime = timestampInSeconds();\n\n // client.query(text, cb?), client.query(text, values, cb?), and\n // client.query(configObj, cb?) are all valid signatures. We construct\n // a queryConfig obj from all (valid) signatures to build the span in a\n // unified way. We verify that we at least have query text, and code\n // defensively when dealing with `queryConfig` after that (to handle all\n // the other invalid cases, like a non-array for values being provided).\n // The type casts here reflect only what we've actually validated.\n const arg0 = args[0];\n const firstArgIsString = typeof arg0 === 'string';\n const firstArgIsQueryObjectWithText = utils.isObjectWithTextString(arg0);\n\n // TODO: remove the `as ...` casts below when the TS version is upgraded.\n // Newer TS versions will use the result of firstArgIsQueryObjectWithText\n // to properly narrow arg0, but TS 4.3.5 does not.\n const queryConfig = firstArgIsString\n ? {\n text: arg0 as string,\n values: Array.isArray(args[1]) ? args[1] : undefined,\n }\n : firstArgIsQueryObjectWithText\n ? {\n ...(arg0 as any),\n name: arg0.name,\n text: arg0.text,\n values: (arg0 as any).values ?? (Array.isArray(args[1]) ? args[1] : undefined),\n }\n : undefined;\n\n const attributes: Attributes = {\n [ATTR_DB_SYSTEM]: DB_SYSTEM_VALUE_POSTGRESQL,\n [ATTR_DB_NAMESPACE]: this.database,\n [ATTR_SERVER_PORT]: this.connectionParameters.port,\n [ATTR_SERVER_ADDRESS]: this.connectionParameters.host,\n };\n\n if (queryConfig?.text) {\n attributes[ATTR_DB_OPERATION_NAME] = utils.parseNormalizedOperationName(queryConfig?.text);\n }\n\n const recordDuration = () => {\n plugin.recordOperationDuration(attributes, startTime);\n };\n\n const instrumentationConfig = plugin.getConfig();\n\n const span = utils.handleConfigQuery.call(\n this,\n plugin.tracer,\n instrumentationConfig,\n plugin._semconvStability,\n queryConfig,\n );\n\n // Modify query text w/ a tracing comment before invoking original for\n // tracing, but only if args[0] has one of our expected shapes.\n if (instrumentationConfig.addSqlCommenterCommentToQueries) {\n if (firstArgIsString) {\n args[0] = addSqlCommenterComment(span, arg0);\n } else if (firstArgIsQueryObjectWithText && !('name' in arg0)) {\n // In the case of a query object, we need to ensure there's no name field\n // as this indicates a prepared query, where the comment would remain the same\n // for every invocation and contain an outdated trace context.\n args[0] = {\n ...arg0,\n text: addSqlCommenterComment(span, arg0.text),\n };\n }\n }\n\n // Bind callback (if any) to parent span (if any)\n if (args.length > 0) {\n const parentSpan = trace.getSpan(context.active());\n if (typeof args[args.length - 1] === 'function') {\n // Patch ParameterQuery callback\n args[args.length - 1] = utils.patchCallback(\n instrumentationConfig,\n span,\n args[args.length - 1] as PostgresCallback, // nb: not type safe.\n attributes,\n recordDuration,\n );\n\n // If a parent span exists, bind the callback\n if (parentSpan) {\n args[args.length - 1] = context.bind(context.active(), args[args.length - 1]);\n }\n } else if (typeof queryConfig?.callback === 'function') {\n // Patch ConfigQuery callback\n let callback = utils.patchCallback(\n plugin.getConfig(),\n span,\n queryConfig.callback as PostgresCallback, // nb: not type safe.\n attributes,\n recordDuration,\n );\n\n // If a parent span existed, bind the callback\n if (parentSpan) {\n callback = context.bind(context.active(), callback);\n }\n\n (args[0] as { callback?: PostgresCallback }).callback = callback;\n }\n }\n\n const { requestHook } = instrumentationConfig;\n if (typeof requestHook === 'function' && queryConfig) {\n safeExecuteInTheMiddle(\n () => {\n // pick keys to expose explicitly, so we're not leaking pg package\n // internals that are subject to change\n const { database, host, port, user } = this.connectionParameters;\n const connection = { database, host, port, user };\n\n requestHook(span, {\n connection,\n query: {\n text: queryConfig.text,\n // nb: if `client.query` is called with illegal arguments\n // (e.g., if `queryConfig.values` is passed explicitly, but a\n // non-array is given), then the type casts will be wrong. But\n // we leave it up to the queryHook to handle that, and we\n // catch and swallow any errors it throws. The other options\n // are all worse. E.g., we could leave `queryConfig.values`\n // and `queryConfig.name` as `unknown`, but then the hook body\n // would be forced to validate (or cast) them before using\n // them, which seems incredibly cumbersome given that these\n // casts will be correct 99.9% of the time -- and pg.query\n // will immediately throw during development in the other .1%\n // of cases. Alternatively, we could simply skip calling the\n // hook when `values` or `name` don't have the expected type,\n // but that would add unnecessary validation overhead to every\n // hook invocation and possibly be even more confusing/unexpected.\n values: queryConfig.values as unknown[],\n name: queryConfig.name as string | undefined,\n },\n });\n },\n err => {\n if (err) {\n plugin._diag.error('Error running query hook', err);\n }\n },\n true,\n );\n }\n\n let result: unknown;\n try {\n result = original.apply(this, args as never);\n } catch (e: unknown) {\n if (e instanceof Error) {\n span.recordException(utils.sanitizedErrorMessage(e));\n }\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: utils.getErrorMessage(e),\n });\n span.end();\n throw e;\n }\n\n // Bind promise to parent span and end the span\n if (result instanceof Promise) {\n return result\n .then((result: unknown) => {\n // Return a pass-along promise which ends the span and then goes to user's orig resolvers\n return new Promise(resolve => {\n utils.handleExecutionResult(plugin.getConfig(), span, result);\n recordDuration();\n span.end();\n resolve(result);\n });\n })\n .catch((error: Error) => {\n return new Promise((_, reject) => {\n if (error instanceof Error) {\n span.recordException(utils.sanitizedErrorMessage(error));\n }\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error.message,\n });\n recordDuration();\n span.end();\n reject(error);\n });\n });\n }\n\n // else returns void\n return result; // void\n };\n };\n }\n\n private _setPoolConnectEventListeners(pgPool: PgPoolExtended) {\n if (pgPool[EVENT_LISTENERS_SET]) return;\n const poolName = utils.getPoolName(pgPool.options);\n\n pgPool.on('connect', () => {\n this._connectionsCounter = utils.updateCounter(\n poolName,\n pgPool,\n this._connectionsCount,\n this._connectionPendingRequests,\n this._connectionsCounter,\n );\n });\n\n pgPool.on('acquire', () => {\n this._connectionsCounter = utils.updateCounter(\n poolName,\n pgPool,\n this._connectionsCount,\n this._connectionPendingRequests,\n this._connectionsCounter,\n );\n });\n\n pgPool.on('remove', () => {\n this._connectionsCounter = utils.updateCounter(\n poolName,\n pgPool,\n this._connectionsCount,\n this._connectionPendingRequests,\n this._connectionsCounter,\n );\n });\n\n pgPool.on('release' as any, () => {\n this._connectionsCounter = utils.updateCounter(\n poolName,\n pgPool,\n this._connectionsCount,\n this._connectionPendingRequests,\n this._connectionsCounter,\n );\n });\n pgPool[EVENT_LISTENERS_SET] = true;\n }\n\n private _getPoolConnectPatch() {\n const plugin = this;\n return (originalConnect: (...args: any[]) => any) => {\n return function connect(this: PgPoolExtended, callback?: PgPoolCallback) {\n const config = plugin.getConfig();\n\n if (utils.shouldSkipInstrumentation(config)) {\n return originalConnect.call(this, callback as any);\n }\n\n // Still set up event listeners for metrics even when skipping spans\n plugin._setPoolConnectEventListeners(this);\n\n if (config.ignoreConnectSpans) {\n return originalConnect.call(this, callback as any);\n }\n\n // setup span\n const span = plugin.tracer.startSpan(SpanNames.POOL_CONNECT, {\n kind: SpanKind.CLIENT,\n attributes: utils.getSemanticAttributesFromPoolConnection(this.options, plugin._semconvStability),\n });\n\n if (callback) {\n const parentSpan = trace.getSpan(context.active());\n callback = utils.patchCallbackPGPool(span, callback) as PgPoolCallback;\n // If a parent span exists, bind the callback\n if (parentSpan) {\n callback = context.bind(context.active(), callback);\n }\n }\n\n const connectResult: unknown = context.with(trace.setSpan(context.active(), span), () => {\n return originalConnect.call(this, callback as any);\n });\n\n return handleConnectResult(span, connectResult);\n };\n };\n }\n}\n\nfunction handleConnectResult(span: Span, connectResult: unknown) {\n if (!(connectResult instanceof Promise)) {\n return connectResult;\n }\n\n const connectResultPromise = connectResult as Promise<unknown>;\n return context.bind(\n context.active(),\n connectResultPromise\n .then(result => {\n span.end();\n return result;\n })\n .catch((error: unknown) => {\n if (error instanceof Error) {\n span.recordException(utils.sanitizedErrorMessage(error));\n }\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: utils.getErrorMessage(error),\n });\n span.end();\n return Promise.reject(error);\n }),\n );\n}\n"],"names":["InstrumentationBase","SDK_VERSION","semconvStabilityFromStr","METRIC_DB_CLIENT_OPERATION_DURATION","ValueType","METRIC_DB_CLIENT_CONNECTION_COUNT","METRIC_DB_CLIENT_CONNECTION_PENDING_REQUESTS","InstrumentationNodeModuleFile","InstrumentationNodeModuleDefinition","isWrapped","utils.shouldSkipInstrumentation","SpanNames","SpanKind","utils.getSemanticAttributesFromConnection","trace","context","utils.patchClientConnectCallback","ATTR_DB_NAMESPACE","ATTR_ERROR_TYPE","ATTR_SERVER_PORT","ATTR_SERVER_ADDRESS","ATTR_DB_OPERATION_NAME","SemconvStability","ATTR_DB_SYSTEM","ATTR_DB_SYSTEM_NAME","timestampInSeconds","utils.isObjectWithTextString","DB_SYSTEM_VALUE_POSTGRESQL","utils.parseNormalizedOperationName","utils.handleConfigQuery","addSqlCommenterComment","utils.patchCallback","safeExecuteInTheMiddle","utils.sanitizedErrorMessage","SpanStatusCode","utils.getErrorMessage","result","utils.handleExecutionResult","EVENT_LISTENERS_SET","utils.getPoolName","utils.updateCounter","utils.getSemanticAttributesFromPoolConnection","utils.patchCallbackPGPool"],"mappings":";;;;;;;;;;;;;AAwDA,MAAM,YAAA,GAAe,4BAAA;AAkBrB,SAAS,qBAAqB,MAAA,EAAa;AACzC,EAAA,OAAO,OAAO,MAAA,CAAO,WAAW,CAAA,KAAM,QAAA,GAClC,OAAO,OAAA,GACP,MAAA;AACN;AAEO,MAAM,0BAA0BA,mCAAA,CAA6C;AAAA,EAgBlF,WAAA,CAAY,MAAA,GAAkC,EAAC,EAAG;AAChD,IAAA,KAAA,CAAM,YAAA,EAAcC,kBAAa,MAAM,CAAA;AARzC;AAAA;AAAA;AAAA;AAAA;AAAA,IAAA,IAAA,CAAQ,mBAAA,GAAoD;AAAA,MAC1D,IAAA,EAAM,CAAA;AAAA,MACN,IAAA,EAAM,CAAA;AAAA,MACN,OAAA,EAAS;AAAA,KACX;AAKE,IAAA,IAAA,CAAK,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AAAA,QACF;AAEA,QAAA,MAAM,aAAA,GAAyBA,WAAA,CAAQ,IAAA,CAAKD,SAAA,CAAM,OAAA,CAAQC,YAAQ,MAAA,EAAO,EAAG,IAAI,CAAA,EAAG,MAAM;AACvF,UAAA,OAAO,eAAA,CAAgB,IAAA,CAAK,IAAA,EAAM,QAAe,CAAA;AAAA,QACnD,CAAC,CAAA;AAED,QAAA,OAAO,mBAAA,CAAoB,MAAM,aAAa,CAAA;AAAA,MAChD,CAAA;AAAA,IACF,CAAA;AAAA,EACF;AACF;AAEA,SAAS,mBAAA,CAAoB,MAAY,aAAA,EAAwB;AAC/D,EAAA,IAAI,EAAE,yBAAyB,OAAA,CAAA,EAAU;AACvC,IAAA,OAAO,aAAA;AAAA,EACT;AAEA,EAAA,MAAM,oBAAA,GAAuB,aAAA;AAC7B,EAAA,OAAOA,WAAA,CAAQ,IAAA;AAAA,IACbA,YAAQ,MAAA,EAAO;AAAA,IACf,oBAAA,CACG,KAAK,CAAA,MAAA,KAAU;AACd,MAAA,IAAA,CAAK,GAAA,EAAI;AACT,MAAA,OAAO,MAAA;AAAA,IACT,CAAC,CAAA,CACA,KAAA,CAAM,CAAC,KAAA,KAAmB;AACzB,MAAA,IAAI,iBAAiB,KAAA,EAAO;AAC1B,QAAA,IAAA,CAAK,eAAA,CAAgBkB,2BAAM,CAAsB,KAAK,CAAC,CAAA;AAAA,MACzD;AACA,MAAA,IAAA,CAAK,SAAA,CAAU;AAAA,QACb,MAAMC,kBAAA,CAAe,KAAA;AAAA,QACrB,OAAA,EAASC,qBAAM,CAAgB,KAAK;AAAA,OACrC,CAAA;AACD,MAAA,IAAA,CAAK,GAAA,EAAI;AACT,MAAA,OAAO,OAAA,CAAQ,OAAO,KAAK,CAAA;AAAA,IAC7B,CAAC;AAAA,GACL;AACF;;;;"}
@@ -2,6 +2,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
 
3
3
  const api = require('@opentelemetry/api');
4
4
  const instrumentation = require('@opentelemetry/instrumentation');
5
+ const InstrumentationNodeModuleFile = require('./InstrumentationNodeModuleFile.js');
5
6
  const semanticConventions = require('@opentelemetry/semantic-conventions');
6
7
  const core = require('@sentry/core');
7
8
  const nodeCore = require('@sentry/node-core');
@@ -44,7 +45,7 @@ class PostgresJsInstrumentation extends instrumentation.InstrumentationBase {
44
45
  );
45
46
  ["src", "cf/src", "cjs/src"].forEach((path) => {
46
47
  module.files.push(
47
- new instrumentation.InstrumentationNodeModuleFile(
48
+ new InstrumentationNodeModuleFile.InstrumentationNodeModuleFile(
48
49
  `postgres/${path}/query.js`,
49
50
  SUPPORTED_VERSIONS,
50
51
  this._patchQueryPrototype.bind(this),
@@ -1 +1 @@
1
- {"version":3,"file":"postgresjs.js","sources":["../../../../src/integrations/tracing/postgresjs.ts"],"sourcesContent":["// Instrumentation for https://github.com/porsager/postgres\n\nimport { context, trace } from '@opentelemetry/api';\nimport type { InstrumentationConfig } from '@opentelemetry/instrumentation';\nimport {\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n InstrumentationNodeModuleFile,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport {\n ATTR_DB_OPERATION_NAME,\n ATTR_DB_QUERY_TEXT,\n ATTR_DB_RESPONSE_STATUS_CODE,\n ATTR_DB_SYSTEM_NAME,\n ATTR_ERROR_TYPE,\n} from '@opentelemetry/semantic-conventions';\nimport type { IntegrationFn, Span } from '@sentry/core';\nimport {\n debug,\n defineIntegration,\n instrumentPostgresJsSql,\n replaceExports,\n SDK_VERSION,\n SPAN_STATUS_ERROR,\n startSpanManual,\n} from '@sentry/core';\nimport { addOriginToSpan, generateInstrumentOnce } from '@sentry/node-core';\nimport { DEBUG_BUILD } from '../../debug-build';\n\nconst INTEGRATION_NAME = 'PostgresJs';\nconst SUPPORTED_VERSIONS = ['>=3.0.0 <4'];\nconst SQL_OPERATION_REGEX = /^(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER)/i;\n\ntype PostgresConnectionContext = {\n ATTR_DB_NAMESPACE?: string; // Database name\n ATTR_SERVER_ADDRESS?: string; // Hostname or IP address of the database server\n ATTR_SERVER_PORT?: string; // Port number of the database server\n};\n\n// Marker to track if a query was created from an instrumented sql instance\n// This prevents double-spanning when both wrapper and prototype patches are active\nconst QUERY_FROM_INSTRUMENTED_SQL = Symbol.for('sentry.query.from.instrumented.sql');\n\ntype PostgresJsInstrumentationConfig = InstrumentationConfig & {\n /**\n * Whether to require a parent span for the instrumentation.\n * If set to true, the instrumentation will only create spans if there is a parent span\n * available in the current scope.\n * @default true\n */\n requireParentSpan?: boolean;\n /**\n * Hook to modify the span before it is started.\n * This can be used to set additional attributes or modify the span in any way.\n */\n requestHook?: (span: Span, sanitizedSqlQuery: string, postgresConnectionContext?: PostgresConnectionContext) => void;\n};\n\nexport const instrumentPostgresJs = generateInstrumentOnce(\n INTEGRATION_NAME,\n (options?: PostgresJsInstrumentationConfig) =>\n new PostgresJsInstrumentation({\n requireParentSpan: options?.requireParentSpan ?? true,\n requestHook: options?.requestHook,\n }),\n);\n\n/**\n * Instrumentation for the [postgres](https://www.npmjs.com/package/postgres) library.\n * This instrumentation captures postgresjs queries and their attributes.\n *\n * Uses internal Sentry patching patterns to support both CommonJS and ESM environments.\n */\nexport class PostgresJsInstrumentation extends InstrumentationBase<PostgresJsInstrumentationConfig> {\n public constructor(config: PostgresJsInstrumentationConfig) {\n super('sentry-postgres-js', SDK_VERSION, config);\n }\n\n /**\n * Initializes the instrumentation by patching the postgres module.\n * Uses two complementary approaches:\n * 1. Main function wrapper: instruments sql instances created AFTER instrumentation is set up (CJS + ESM)\n * 2. Query.prototype patch: fallback for sql instances created BEFORE instrumentation (CJS only)\n */\n public init(): InstrumentationNodeModuleDefinition {\n const module = new InstrumentationNodeModuleDefinition(\n 'postgres',\n SUPPORTED_VERSIONS,\n exports => {\n try {\n return this._patchPostgres(exports);\n } catch (e) {\n DEBUG_BUILD && debug.error('Failed to patch postgres module:', e);\n return exports;\n }\n },\n exports => exports,\n );\n\n // Add fallback Query.prototype patching for pre-existing sql instances (CJS only)\n // This catches queries from sql instances created before Sentry was initialized\n ['src', 'cf/src', 'cjs/src'].forEach(path => {\n module.files.push(\n new InstrumentationNodeModuleFile(\n `postgres/${path}/query.js`,\n SUPPORTED_VERSIONS,\n this._patchQueryPrototype.bind(this),\n this._unpatchQueryPrototype.bind(this),\n ),\n );\n });\n\n return module;\n }\n\n /**\n * Patches the postgres module by wrapping the main export function.\n * This intercepts the creation of sql instances and instruments them.\n */\n private _patchPostgres(exports: { [key: string]: unknown }): { [key: string]: unknown } {\n // In CJS: exports is the function itself\n // In ESM: exports.default is the function\n const isFunction = typeof exports === 'function';\n const Original = isFunction ? exports : exports.default;\n\n if (typeof Original !== 'function') {\n DEBUG_BUILD && debug.warn('postgres module does not export a function. Skipping instrumentation.');\n return exports;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this;\n\n const WrappedPostgres = function (this: unknown, ...args: unknown[]): unknown {\n const sql = Reflect.construct(Original as (...args: unknown[]) => unknown, args);\n\n // Validate that construction succeeded and returned a valid function object\n if (!sql || typeof sql !== 'function') {\n DEBUG_BUILD && debug.warn('postgres() did not return a valid instance');\n return sql;\n }\n\n // Delegate to the portable instrumentation from @sentry/core\n const config = self.getConfig();\n return instrumentPostgresJsSql(sql, {\n requireParentSpan: config.requireParentSpan,\n requestHook: config.requestHook,\n });\n };\n\n Object.setPrototypeOf(WrappedPostgres, Original);\n Object.setPrototypeOf(WrappedPostgres.prototype, (Original as { prototype: object }).prototype);\n\n for (const key of Object.getOwnPropertyNames(Original)) {\n if (!['length', 'name', 'prototype'].includes(key)) {\n const descriptor = Object.getOwnPropertyDescriptor(Original, key);\n if (descriptor) {\n Object.defineProperty(WrappedPostgres, key, descriptor);\n }\n }\n }\n\n // For CJS: the exports object IS the function, so return the wrapped function\n // For ESM: replace the default export\n if (isFunction) {\n return WrappedPostgres as unknown as { [key: string]: unknown };\n } else {\n replaceExports(exports, 'default', WrappedPostgres);\n return exports;\n }\n }\n\n /**\n * Determines whether a span should be created based on the current context.\n * If `requireParentSpan` is set to true in the configuration, a span will\n * only be created if there is a parent span available.\n */\n private _shouldCreateSpans(): boolean {\n const config = this.getConfig();\n const hasParentSpan = trace.getSpan(context.active()) !== undefined;\n return hasParentSpan || !config.requireParentSpan;\n }\n\n /**\n * Extracts DB operation name from SQL query and sets it on the span.\n */\n private _setOperationName(span: Span, sanitizedQuery: string | undefined, command?: string): void {\n if (command) {\n span.setAttribute(ATTR_DB_OPERATION_NAME, command);\n return;\n }\n // Fallback: extract operation from the SQL query\n const operationMatch = sanitizedQuery?.match(SQL_OPERATION_REGEX);\n if (operationMatch?.[1]) {\n span.setAttribute(ATTR_DB_OPERATION_NAME, operationMatch[1].toUpperCase());\n }\n }\n\n /**\n * Reconstructs the full SQL query from template strings with PostgreSQL placeholders.\n *\n * For sql`SELECT * FROM users WHERE id = ${123} AND name = ${'foo'}`:\n * strings = [\"SELECT * FROM users WHERE id = \", \" AND name = \", \"\"]\n * returns: \"SELECT * FROM users WHERE id = $1 AND name = $2\"\n */\n private _reconstructQuery(strings: string[] | undefined): string | undefined {\n if (!strings?.length) {\n return undefined;\n }\n if (strings.length === 1) {\n return strings[0] || undefined;\n }\n // Join template parts with PostgreSQL placeholders ($1, $2, etc.)\n return strings.reduce((acc, str, i) => (i === 0 ? str : `${acc}$${i}${str}`), '');\n }\n\n /**\n * Sanitize SQL query as per the OTEL semantic conventions\n * https://opentelemetry.io/docs/specs/semconv/database/database-spans/#sanitization-of-dbquerytext\n *\n * PostgreSQL $n placeholders are preserved per OTEL spec - they're parameterized queries,\n * not sensitive literals. Only actual values (strings, numbers, booleans) are sanitized.\n */\n private _sanitizeSqlQuery(sqlQuery: string | undefined): string {\n if (!sqlQuery) {\n return 'Unknown SQL Query';\n }\n\n return (\n sqlQuery\n // Remove comments first (they may contain newlines and extra spaces)\n .replace(/--.*$/gm, '') // Single line comments (multiline mode)\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, '') // Multi-line comments\n .replace(/;\\s*$/, '') // Remove trailing semicolons\n // Collapse whitespace to a single space (after removing comments)\n .replace(/\\s+/g, ' ')\n .trim() // Remove extra spaces and trim\n // Sanitize hex/binary literals before string literals\n .replace(/\\bX'[0-9A-Fa-f]*'/gi, '?') // Hex string literals\n .replace(/\\bB'[01]*'/gi, '?') // Binary string literals\n // Sanitize string literals (handles escaped quotes)\n .replace(/'(?:[^']|'')*'/g, '?')\n // Sanitize hex numbers\n .replace(/\\b0x[0-9A-Fa-f]+/gi, '?')\n // Sanitize boolean literals\n .replace(/\\b(?:TRUE|FALSE)\\b/gi, '?')\n // Sanitize numeric literals (preserve $n placeholders via negative lookbehind)\n .replace(/-?\\b\\d+\\.?\\d*[eE][+-]?\\d+\\b/g, '?') // Scientific notation\n .replace(/-?\\b\\d+\\.\\d+\\b/g, '?') // Decimals\n .replace(/-?\\.\\d+\\b/g, '?') // Decimals starting with dot\n .replace(/(?<!\\$)-?\\b\\d+\\b/g, '?') // Integers (NOT $n placeholders)\n // Collapse IN clauses for cardinality (both ? and $n variants)\n .replace(/\\bIN\\b\\s*\\(\\s*\\?(?:\\s*,\\s*\\?)*\\s*\\)/gi, 'IN (?)')\n .replace(/\\bIN\\b\\s*\\(\\s*\\$\\d+(?:\\s*,\\s*\\$\\d+)*\\s*\\)/gi, 'IN ($?)')\n );\n }\n\n /**\n * Fallback patch for Query.prototype.handle to instrument queries from pre-existing sql instances.\n * This catches queries from sql instances created BEFORE Sentry was initialized (CJS only).\n *\n * Note: Queries from pre-existing instances won't have connection context (database, host, port)\n * because the sql instance wasn't created through our instrumented wrapper.\n */\n private _patchQueryPrototype(moduleExports: {\n Query: {\n prototype: {\n handle: ((...args: unknown[]) => Promise<unknown>) & {\n __sentry_original__?: (...args: unknown[]) => Promise<unknown>;\n };\n };\n };\n }): typeof moduleExports {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this;\n const originalHandle = moduleExports.Query.prototype.handle;\n\n moduleExports.Query.prototype.handle = async function (\n this: {\n resolve: unknown;\n reject: unknown;\n strings?: string[];\n },\n ...args: unknown[]\n ): Promise<unknown> {\n // Skip if this query came from an instrumented sql instance (already handled by wrapper)\n if ((this as Record<symbol, unknown>)[QUERY_FROM_INSTRUMENTED_SQL]) {\n return originalHandle.apply(this, args);\n }\n\n // Skip if we shouldn't create spans\n if (!self._shouldCreateSpans()) {\n return originalHandle.apply(this, args);\n }\n\n const fullQuery = self._reconstructQuery(this.strings);\n const sanitizedSqlQuery = self._sanitizeSqlQuery(fullQuery);\n\n return startSpanManual(\n {\n name: sanitizedSqlQuery || 'postgresjs.query',\n op: 'db',\n },\n (span: Span) => {\n addOriginToSpan(span, 'auto.db.postgresjs');\n\n span.setAttributes({\n [ATTR_DB_SYSTEM_NAME]: 'postgres',\n [ATTR_DB_QUERY_TEXT]: sanitizedSqlQuery,\n });\n\n // Note: No connection context available for pre-existing instances\n // because the sql instance wasn't created through our instrumented wrapper\n\n const config = self.getConfig();\n const { requestHook } = config;\n if (requestHook) {\n safeExecuteInTheMiddle(\n () => requestHook(span, sanitizedSqlQuery, undefined),\n e => {\n if (e) {\n span.setAttribute('sentry.hook.error', 'requestHook failed');\n DEBUG_BUILD && debug.error(`Error in requestHook for ${INTEGRATION_NAME} integration:`, e);\n }\n },\n true,\n );\n }\n\n // Wrap resolve to end span on success\n const originalResolve = this.resolve;\n this.resolve = new Proxy(originalResolve as (...args: unknown[]) => unknown, {\n apply: (resolveTarget, resolveThisArg, resolveArgs: [{ command?: string }]) => {\n try {\n self._setOperationName(span, sanitizedSqlQuery, resolveArgs?.[0]?.command);\n span.end();\n } catch (e) {\n DEBUG_BUILD && debug.error('Error ending span in resolve callback:', e);\n }\n return Reflect.apply(resolveTarget, resolveThisArg, resolveArgs);\n },\n });\n\n // Wrap reject to end span on error\n const originalReject = this.reject;\n this.reject = new Proxy(originalReject as (...args: unknown[]) => unknown, {\n apply: (rejectTarget, rejectThisArg, rejectArgs: { message?: string; code?: string; name?: string }[]) => {\n try {\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message: rejectArgs?.[0]?.message || 'unknown_error',\n });\n span.setAttribute(ATTR_DB_RESPONSE_STATUS_CODE, rejectArgs?.[0]?.code || 'unknown');\n span.setAttribute(ATTR_ERROR_TYPE, rejectArgs?.[0]?.name || 'unknown');\n self._setOperationName(span, sanitizedSqlQuery);\n span.end();\n } catch (e) {\n DEBUG_BUILD && debug.error('Error ending span in reject callback:', e);\n }\n return Reflect.apply(rejectTarget, rejectThisArg, rejectArgs);\n },\n });\n\n try {\n return originalHandle.apply(this, args);\n } catch (e) {\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message: e instanceof Error ? e.message : 'unknown_error',\n });\n span.end();\n throw e;\n }\n },\n );\n };\n\n // Store original for unpatch - must be set on the NEW patched function\n moduleExports.Query.prototype.handle.__sentry_original__ = originalHandle;\n\n return moduleExports;\n }\n\n /**\n * Restores the original Query.prototype.handle method.\n */\n private _unpatchQueryPrototype(moduleExports: {\n Query: {\n prototype: {\n handle: ((...args: unknown[]) => Promise<unknown>) & {\n __sentry_original__?: (...args: unknown[]) => Promise<unknown>;\n };\n };\n };\n }): typeof moduleExports {\n if (moduleExports.Query.prototype.handle.__sentry_original__) {\n moduleExports.Query.prototype.handle = moduleExports.Query.prototype.handle.__sentry_original__;\n }\n return moduleExports;\n }\n}\n\nconst _postgresJsIntegration = ((options?: PostgresJsInstrumentationConfig) => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n instrumentPostgresJs(options);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Adds Sentry tracing instrumentation for the [postgres](https://www.npmjs.com/package/postgres) library.\n *\n * For more information, see the [`postgresIntegration` documentation](https://docs.sentry.io/platforms/javascript/guides/node/configuration/integrations/postgres/).\n *\n * @example\n * ```javascript\n * const Sentry = require('@sentry/node');\n *\n * Sentry.init({\n * integrations: [Sentry.postgresJsIntegration()],\n * });\n * ```\n */\n\nexport const postgresJsIntegration = defineIntegration(_postgresJsIntegration);\n"],"names":["generateInstrumentOnce","InstrumentationBase","SDK_VERSION","InstrumentationNodeModuleDefinition","DEBUG_BUILD","debug","InstrumentationNodeModuleFile","instrumentPostgresJsSql","replaceExports","trace","context","ATTR_DB_OPERATION_NAME","startSpanManual","addOriginToSpan","ATTR_DB_SYSTEM_NAME","ATTR_DB_QUERY_TEXT","safeExecuteInTheMiddle","SPAN_STATUS_ERROR","ATTR_DB_RESPONSE_STATUS_CODE","ATTR_ERROR_TYPE","defineIntegration"],"mappings":";;;;;;;;;AA8BA,MAAM,gBAAA,GAAmB,YAAA;AACzB,MAAM,kBAAA,GAAqB,CAAC,YAAY,CAAA;AACxC,MAAM,mBAAA,GAAsB,mDAAA;AAU5B,MAAM,2BAAA,mBAA8B,MAAA,CAAO,GAAA,CAAI,oCAAoC,CAAA;AAiB5E,MAAM,oBAAA,GAAuBA,+BAAA;AAAA,EAClC,gBAAA;AAAA,EACA,CAAC,OAAA,KACC,IAAI,yBAAA,CAA0B;AAAA,IAC5B,iBAAA,EAAmB,SAAS,iBAAA,IAAqB,IAAA;AAAA,IACjD,aAAa,OAAA,EAAS;AAAA,GACvB;AACL;AAQO,MAAM,kCAAkCC,mCAAA,CAAqD;AAAA,EAC3F,YAAY,MAAA,EAAyC;AAC1D,IAAA,KAAA,CAAM,oBAAA,EAAsBC,kBAAa,MAAM,CAAA;AAAA,EACjD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQO,IAAA,GAA4C;AACjD,IAAA,MAAM,SAAS,IAAIC,mDAAA;AAAA,MACjB,UAAA;AAAA,MACA,kBAAA;AAAA,MACA,CAAA,OAAA,KAAW;AACT,QAAA,IAAI;AACF,UAAA,OAAO,IAAA,CAAK,eAAe,OAAO,CAAA;AAAA,QACpC,SAAS,CAAA,EAAG;AACV,UAAAC,sBAAA,IAAeC,UAAA,CAAM,KAAA,CAAM,kCAAA,EAAoC,CAAC,CAAA;AAChE,UAA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A,QACF;AAAA,OACF;AAAA,IACF,CAAA;AAGA,IAAA,aAAA,CAAc,KAAA,CAAM,SAAA,CAAU,MAAA,CAAO,mBAAA,GAAsB,cAAA;AAE3D,IAAA,OAAO,aAAA;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKQ,uBAAuB,aAAA,EAQN;AACvB,IAAA,IAAI,aAAA,CAAc,KAAA,CAAM,SAAA,CAAU,MAAA,CAAO,mBAAA,EAAqB;AAC5D,MAAA,aAAA,CAAc,MAAM,SAAA,CAAU,MAAA,GAAS,aAAA,CAAc,KAAA,CAAM,UAAU,MAAA,CAAO,mBAAA;AAAA,IAC9E;AACA,IAAA,OAAO,aAAA;AAAA,EACT;AACF;AAEA,MAAM,sBAAA,IAA0B,CAAC,OAAA,KAA8C;AAC7E,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,SAAA,GAAY;AACV,MAAA,oBAAA,CAAqB,OAAO,CAAA;AAAA,IAC9B;AAAA,GACF;AACF,CAAA,CAAA;AAiBO,MAAM,qBAAA,GAAwBG,uBAAkB,sBAAsB;;;;;;"}
1
+ {"version":3,"file":"postgresjs.js","sources":["../../../../src/integrations/tracing/postgresjs.ts"],"sourcesContent":["// Instrumentation for https://github.com/porsager/postgres\n\nimport { context, trace } from '@opentelemetry/api';\nimport type { InstrumentationConfig } from '@opentelemetry/instrumentation';\nimport {\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport { InstrumentationNodeModuleFile } from './InstrumentationNodeModuleFile';\nimport {\n ATTR_DB_OPERATION_NAME,\n ATTR_DB_QUERY_TEXT,\n ATTR_DB_RESPONSE_STATUS_CODE,\n ATTR_DB_SYSTEM_NAME,\n ATTR_ERROR_TYPE,\n} from '@opentelemetry/semantic-conventions';\nimport type { IntegrationFn, Span } from '@sentry/core';\nimport {\n debug,\n defineIntegration,\n instrumentPostgresJsSql,\n replaceExports,\n SDK_VERSION,\n SPAN_STATUS_ERROR,\n startSpanManual,\n} from '@sentry/core';\nimport { addOriginToSpan, generateInstrumentOnce } from '@sentry/node-core';\nimport { DEBUG_BUILD } from '../../debug-build';\n\nconst INTEGRATION_NAME = 'PostgresJs';\nconst SUPPORTED_VERSIONS = ['>=3.0.0 <4'];\nconst SQL_OPERATION_REGEX = /^(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER)/i;\n\ntype PostgresConnectionContext = {\n ATTR_DB_NAMESPACE?: string; // Database name\n ATTR_SERVER_ADDRESS?: string; // Hostname or IP address of the database server\n ATTR_SERVER_PORT?: string; // Port number of the database server\n};\n\n// Marker to track if a query was created from an instrumented sql instance\n// This prevents double-spanning when both wrapper and prototype patches are active\nconst QUERY_FROM_INSTRUMENTED_SQL = Symbol.for('sentry.query.from.instrumented.sql');\n\ntype PostgresJsInstrumentationConfig = InstrumentationConfig & {\n /**\n * Whether to require a parent span for the instrumentation.\n * If set to true, the instrumentation will only create spans if there is a parent span\n * available in the current scope.\n * @default true\n */\n requireParentSpan?: boolean;\n /**\n * Hook to modify the span before it is started.\n * This can be used to set additional attributes or modify the span in any way.\n */\n requestHook?: (span: Span, sanitizedSqlQuery: string, postgresConnectionContext?: PostgresConnectionContext) => void;\n};\n\nexport const instrumentPostgresJs = generateInstrumentOnce(\n INTEGRATION_NAME,\n (options?: PostgresJsInstrumentationConfig) =>\n new PostgresJsInstrumentation({\n requireParentSpan: options?.requireParentSpan ?? true,\n requestHook: options?.requestHook,\n }),\n);\n\n/**\n * Instrumentation for the [postgres](https://www.npmjs.com/package/postgres) library.\n * This instrumentation captures postgresjs queries and their attributes.\n *\n * Uses internal Sentry patching patterns to support both CommonJS and ESM environments.\n */\nexport class PostgresJsInstrumentation extends InstrumentationBase<PostgresJsInstrumentationConfig> {\n public constructor(config: PostgresJsInstrumentationConfig) {\n super('sentry-postgres-js', SDK_VERSION, config);\n }\n\n /**\n * Initializes the instrumentation by patching the postgres module.\n * Uses two complementary approaches:\n * 1. Main function wrapper: instruments sql instances created AFTER instrumentation is set up (CJS + ESM)\n * 2. Query.prototype patch: fallback for sql instances created BEFORE instrumentation (CJS only)\n */\n public init(): InstrumentationNodeModuleDefinition {\n const module = new InstrumentationNodeModuleDefinition(\n 'postgres',\n SUPPORTED_VERSIONS,\n exports => {\n try {\n return this._patchPostgres(exports);\n } catch (e) {\n DEBUG_BUILD && debug.error('Failed to patch postgres module:', e);\n return exports;\n }\n },\n exports => exports,\n );\n\n // Add fallback Query.prototype patching for pre-existing sql instances (CJS only)\n // This catches queries from sql instances created before Sentry was initialized\n ['src', 'cf/src', 'cjs/src'].forEach(path => {\n module.files.push(\n new InstrumentationNodeModuleFile(\n `postgres/${path}/query.js`,\n SUPPORTED_VERSIONS,\n this._patchQueryPrototype.bind(this),\n this._unpatchQueryPrototype.bind(this),\n ),\n );\n });\n\n return module;\n }\n\n /**\n * Patches the postgres module by wrapping the main export function.\n * This intercepts the creation of sql instances and instruments them.\n */\n private _patchPostgres(exports: { [key: string]: unknown }): { [key: string]: unknown } {\n // In CJS: exports is the function itself\n // In ESM: exports.default is the function\n const isFunction = typeof exports === 'function';\n const Original = isFunction ? exports : exports.default;\n\n if (typeof Original !== 'function') {\n DEBUG_BUILD && debug.warn('postgres module does not export a function. Skipping instrumentation.');\n return exports;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this;\n\n const WrappedPostgres = function (this: unknown, ...args: unknown[]): unknown {\n const sql = Reflect.construct(Original as (...args: unknown[]) => unknown, args);\n\n // Validate that construction succeeded and returned a valid function object\n if (!sql || typeof sql !== 'function') {\n DEBUG_BUILD && debug.warn('postgres() did not return a valid instance');\n return sql;\n }\n\n // Delegate to the portable instrumentation from @sentry/core\n const config = self.getConfig();\n return instrumentPostgresJsSql(sql, {\n requireParentSpan: config.requireParentSpan,\n requestHook: config.requestHook,\n });\n };\n\n Object.setPrototypeOf(WrappedPostgres, Original);\n Object.setPrototypeOf(WrappedPostgres.prototype, (Original as { prototype: object }).prototype);\n\n for (const key of Object.getOwnPropertyNames(Original)) {\n if (!['length', 'name', 'prototype'].includes(key)) {\n const descriptor = Object.getOwnPropertyDescriptor(Original, key);\n if (descriptor) {\n Object.defineProperty(WrappedPostgres, key, descriptor);\n }\n }\n }\n\n // For CJS: the exports object IS the function, so return the wrapped function\n // For ESM: replace the default export\n if (isFunction) {\n return WrappedPostgres as unknown as { [key: string]: unknown };\n } else {\n replaceExports(exports, 'default', WrappedPostgres);\n return exports;\n }\n }\n\n /**\n * Determines whether a span should be created based on the current context.\n * If `requireParentSpan` is set to true in the configuration, a span will\n * only be created if there is a parent span available.\n */\n private _shouldCreateSpans(): boolean {\n const config = this.getConfig();\n const hasParentSpan = trace.getSpan(context.active()) !== undefined;\n return hasParentSpan || !config.requireParentSpan;\n }\n\n /**\n * Extracts DB operation name from SQL query and sets it on the span.\n */\n private _setOperationName(span: Span, sanitizedQuery: string | undefined, command?: string): void {\n if (command) {\n span.setAttribute(ATTR_DB_OPERATION_NAME, command);\n return;\n }\n // Fallback: extract operation from the SQL query\n const operationMatch = sanitizedQuery?.match(SQL_OPERATION_REGEX);\n if (operationMatch?.[1]) {\n span.setAttribute(ATTR_DB_OPERATION_NAME, operationMatch[1].toUpperCase());\n }\n }\n\n /**\n * Reconstructs the full SQL query from template strings with PostgreSQL placeholders.\n *\n * For sql`SELECT * FROM users WHERE id = ${123} AND name = ${'foo'}`:\n * strings = [\"SELECT * FROM users WHERE id = \", \" AND name = \", \"\"]\n * returns: \"SELECT * FROM users WHERE id = $1 AND name = $2\"\n */\n private _reconstructQuery(strings: string[] | undefined): string | undefined {\n if (!strings?.length) {\n return undefined;\n }\n if (strings.length === 1) {\n return strings[0] || undefined;\n }\n // Join template parts with PostgreSQL placeholders ($1, $2, etc.)\n return strings.reduce((acc, str, i) => (i === 0 ? str : `${acc}$${i}${str}`), '');\n }\n\n /**\n * Sanitize SQL query as per the OTEL semantic conventions\n * https://opentelemetry.io/docs/specs/semconv/database/database-spans/#sanitization-of-dbquerytext\n *\n * PostgreSQL $n placeholders are preserved per OTEL spec - they're parameterized queries,\n * not sensitive literals. Only actual values (strings, numbers, booleans) are sanitized.\n */\n private _sanitizeSqlQuery(sqlQuery: string | undefined): string {\n if (!sqlQuery) {\n return 'Unknown SQL Query';\n }\n\n return (\n sqlQuery\n // Remove comments first (they may contain newlines and extra spaces)\n .replace(/--.*$/gm, '') // Single line comments (multiline mode)\n .replace(/\\/\\*[\\s\\S]*?\\*\\//g, '') // Multi-line comments\n .replace(/;\\s*$/, '') // Remove trailing semicolons\n // Collapse whitespace to a single space (after removing comments)\n .replace(/\\s+/g, ' ')\n .trim() // Remove extra spaces and trim\n // Sanitize hex/binary literals before string literals\n .replace(/\\bX'[0-9A-Fa-f]*'/gi, '?') // Hex string literals\n .replace(/\\bB'[01]*'/gi, '?') // Binary string literals\n // Sanitize string literals (handles escaped quotes)\n .replace(/'(?:[^']|'')*'/g, '?')\n // Sanitize hex numbers\n .replace(/\\b0x[0-9A-Fa-f]+/gi, '?')\n // Sanitize boolean literals\n .replace(/\\b(?:TRUE|FALSE)\\b/gi, '?')\n // Sanitize numeric literals (preserve $n placeholders via negative lookbehind)\n .replace(/-?\\b\\d+\\.?\\d*[eE][+-]?\\d+\\b/g, '?') // Scientific notation\n .replace(/-?\\b\\d+\\.\\d+\\b/g, '?') // Decimals\n .replace(/-?\\.\\d+\\b/g, '?') // Decimals starting with dot\n .replace(/(?<!\\$)-?\\b\\d+\\b/g, '?') // Integers (NOT $n placeholders)\n // Collapse IN clauses for cardinality (both ? and $n variants)\n .replace(/\\bIN\\b\\s*\\(\\s*\\?(?:\\s*,\\s*\\?)*\\s*\\)/gi, 'IN (?)')\n .replace(/\\bIN\\b\\s*\\(\\s*\\$\\d+(?:\\s*,\\s*\\$\\d+)*\\s*\\)/gi, 'IN ($?)')\n );\n }\n\n /**\n * Fallback patch for Query.prototype.handle to instrument queries from pre-existing sql instances.\n * This catches queries from sql instances created BEFORE Sentry was initialized (CJS only).\n *\n * Note: Queries from pre-existing instances won't have connection context (database, host, port)\n * because the sql instance wasn't created through our instrumented wrapper.\n */\n private _patchQueryPrototype(moduleExports: {\n Query: {\n prototype: {\n handle: ((...args: unknown[]) => Promise<unknown>) & {\n __sentry_original__?: (...args: unknown[]) => Promise<unknown>;\n };\n };\n };\n }): typeof moduleExports {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const self = this;\n const originalHandle = moduleExports.Query.prototype.handle;\n\n moduleExports.Query.prototype.handle = async function (\n this: {\n resolve: unknown;\n reject: unknown;\n strings?: string[];\n },\n ...args: unknown[]\n ): Promise<unknown> {\n // Skip if this query came from an instrumented sql instance (already handled by wrapper)\n if ((this as Record<symbol, unknown>)[QUERY_FROM_INSTRUMENTED_SQL]) {\n return originalHandle.apply(this, args);\n }\n\n // Skip if we shouldn't create spans\n if (!self._shouldCreateSpans()) {\n return originalHandle.apply(this, args);\n }\n\n const fullQuery = self._reconstructQuery(this.strings);\n const sanitizedSqlQuery = self._sanitizeSqlQuery(fullQuery);\n\n return startSpanManual(\n {\n name: sanitizedSqlQuery || 'postgresjs.query',\n op: 'db',\n },\n (span: Span) => {\n addOriginToSpan(span, 'auto.db.postgresjs');\n\n span.setAttributes({\n [ATTR_DB_SYSTEM_NAME]: 'postgres',\n [ATTR_DB_QUERY_TEXT]: sanitizedSqlQuery,\n });\n\n // Note: No connection context available for pre-existing instances\n // because the sql instance wasn't created through our instrumented wrapper\n\n const config = self.getConfig();\n const { requestHook } = config;\n if (requestHook) {\n safeExecuteInTheMiddle(\n () => requestHook(span, sanitizedSqlQuery, undefined),\n e => {\n if (e) {\n span.setAttribute('sentry.hook.error', 'requestHook failed');\n DEBUG_BUILD && debug.error(`Error in requestHook for ${INTEGRATION_NAME} integration:`, e);\n }\n },\n true,\n );\n }\n\n // Wrap resolve to end span on success\n const originalResolve = this.resolve;\n this.resolve = new Proxy(originalResolve as (...args: unknown[]) => unknown, {\n apply: (resolveTarget, resolveThisArg, resolveArgs: [{ command?: string }]) => {\n try {\n self._setOperationName(span, sanitizedSqlQuery, resolveArgs?.[0]?.command);\n span.end();\n } catch (e) {\n DEBUG_BUILD && debug.error('Error ending span in resolve callback:', e);\n }\n return Reflect.apply(resolveTarget, resolveThisArg, resolveArgs);\n },\n });\n\n // Wrap reject to end span on error\n const originalReject = this.reject;\n this.reject = new Proxy(originalReject as (...args: unknown[]) => unknown, {\n apply: (rejectTarget, rejectThisArg, rejectArgs: { message?: string; code?: string; name?: string }[]) => {\n try {\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message: rejectArgs?.[0]?.message || 'unknown_error',\n });\n span.setAttribute(ATTR_DB_RESPONSE_STATUS_CODE, rejectArgs?.[0]?.code || 'unknown');\n span.setAttribute(ATTR_ERROR_TYPE, rejectArgs?.[0]?.name || 'unknown');\n self._setOperationName(span, sanitizedSqlQuery);\n span.end();\n } catch (e) {\n DEBUG_BUILD && debug.error('Error ending span in reject callback:', e);\n }\n return Reflect.apply(rejectTarget, rejectThisArg, rejectArgs);\n },\n });\n\n try {\n return originalHandle.apply(this, args);\n } catch (e) {\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message: e instanceof Error ? e.message : 'unknown_error',\n });\n span.end();\n throw e;\n }\n },\n );\n };\n\n // Store original for unpatch - must be set on the NEW patched function\n moduleExports.Query.prototype.handle.__sentry_original__ = originalHandle;\n\n return moduleExports;\n }\n\n /**\n * Restores the original Query.prototype.handle method.\n */\n private _unpatchQueryPrototype(moduleExports: {\n Query: {\n prototype: {\n handle: ((...args: unknown[]) => Promise<unknown>) & {\n __sentry_original__?: (...args: unknown[]) => Promise<unknown>;\n };\n };\n };\n }): typeof moduleExports {\n if (moduleExports.Query.prototype.handle.__sentry_original__) {\n moduleExports.Query.prototype.handle = moduleExports.Query.prototype.handle.__sentry_original__;\n }\n return moduleExports;\n }\n}\n\nconst _postgresJsIntegration = ((options?: PostgresJsInstrumentationConfig) => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n instrumentPostgresJs(options);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Adds Sentry tracing instrumentation for the [postgres](https://www.npmjs.com/package/postgres) library.\n *\n * For more information, see the [`postgresIntegration` documentation](https://docs.sentry.io/platforms/javascript/guides/node/configuration/integrations/postgres/).\n *\n * @example\n * ```javascript\n * const Sentry = require('@sentry/node');\n *\n * Sentry.init({\n * integrations: [Sentry.postgresJsIntegration()],\n * });\n * ```\n */\n\nexport const postgresJsIntegration = defineIntegration(_postgresJsIntegration);\n"],"names":["generateInstrumentOnce","InstrumentationBase","SDK_VERSION","InstrumentationNodeModuleDefinition","DEBUG_BUILD","debug","InstrumentationNodeModuleFile","instrumentPostgresJsSql","replaceExports","trace","context","ATTR_DB_OPERATION_NAME","startSpanManual","addOriginToSpan","ATTR_DB_SYSTEM_NAME","ATTR_DB_QUERY_TEXT","safeExecuteInTheMiddle","SPAN_STATUS_ERROR","ATTR_DB_RESPONSE_STATUS_CODE","ATTR_ERROR_TYPE","defineIntegration"],"mappings":";;;;;;;;;;AA8BA,MAAM,gBAAA,GAAmB,YAAA;AACzB,MAAM,kBAAA,GAAqB,CAAC,YAAY,CAAA;AACxC,MAAM,mBAAA,GAAsB,mDAAA;AAU5B,MAAM,2BAAA,mBAA8B,MAAA,CAAO,GAAA,CAAI,oCAAoC,CAAA;AAiB5E,MAAM,oBAAA,GAAuBA,+BAAA;AAAA,EAClC,gBAAA;AAAA,EACA,CAAC,OAAA,KACC,IAAI,yBAAA,CAA0B;AAAA,IAC5B,iBAAA,EAAmB,SAAS,iBAAA,IAAqB,IAAA;AAAA,IACjD,aAAa,OAAA,EAAS;AAAA,GACvB;AACL;AAQO,MAAM,kCAAkCC,mCAAA,CAAqD;AAAA,EAC3F,YAAY,MAAA,EAAyC;AAC1D,IAAA,KAAA,CAAM,oBAAA,EAAsBC,kBAAa,MAAM,CAAA;AAAA,EACjD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQO,IAAA,GAA4C;AACjD,I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AAM,IAAI,CAAA;AAAA,UACxC,SAAS,CAAA,EAAG;AACV,YAAA,IAAA,CAAK,SAAA,CAAU;AAAA,cACb,IAAA,EAAMY,sBAAA;AAAA,cACN,OAAA,EAAS,CAAA,YAAa,KAAA,GAAQ,CAAA,CAAE,OAAA,GAAU;AAAA,aAC3C,CAAA;AACD,YAAA,IAAA,CAAK,GAAA,EAAI;AACT,YAAA,MAAM,CAAA;AAAA,UACR;AAAA,QACF;AAAA,OACF;AAAA,IACF,CAAA;AAGA,IAAA,aAAA,CAAc,KAAA,CAAM,SAAA,CAAU,MAAA,CAAO,mBAAA,GAAsB,cAAA;AAE3D,IAAA,OAAO,aAAA;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKQ,uBAAuB,aAAA,EAQN;AACvB,IAAA,IAAI,aAAA,CAAc,KAAA,CAAM,SAAA,CAAU,MAAA,CAAO,mBAAA,EAAqB;AAC5D,MAAA,aAAA,CAAc,MAAM,SAAA,CAAU,MAAA,GAAS,aAAA,CAAc,KAAA,CAAM,UAAU,MAAA,CAAO,mBAAA;AAAA,IAC9E;AACA,IAAA,OAAO,aAAA;AAAA,EACT;AACF;AAEA,MAAM,sBAAA,IAA0B,CAAC,OAAA,KAA8C;AAC7E,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,SAAA,GAAY;AACV,MAAA,oBAAA,CAAqB,OAAO,CAAA;AAAA,IAC9B;AAAA,GACF;AACF,CAAA,CAAA;AAiBO,MAAM,qBAAA,GAAwBG,uBAAkB,sBAAsB;;;;;;"}
@@ -1,11 +1,12 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
 
3
3
  const core = require('@sentry/core');
4
+ const serverUtils = require('@sentry-internal/server-utils');
4
5
  const nodeCore = require('@sentry/node-core');
6
+ const tracingChannel = require('@sentry/opentelemetry/tracing-channel');
5
7
  const redisCache = require('../../../utils/redisCache.js');
6
8
  const ioredisInstrumentation = require('./vendored/ioredis-instrumentation.js');
7
9
  const redisInstrumentation = require('./vendored/redis-instrumentation.js');
8
- const redisDcSubscriber = require('./redis-dc-subscriber.js');
9
10
 
10
11
  const INTEGRATION_NAME = "Redis";
11
12
  exports._redisOptions = {};
@@ -51,7 +52,7 @@ const instrumentRedis = Object.assign(
51
52
  () => {
52
53
  instrumentIORedis();
53
54
  instrumentRedisModule();
54
- void Promise.resolve().then(() => redisDcSubscriber.subscribeRedisDiagnosticChannels(cacheResponseHook));
55
+ void Promise.resolve().then(() => serverUtils.subscribeRedisDiagnosticChannels(tracingChannel.tracingChannel, cacheResponseHook));
55
56
  },
56
57
  { id: INTEGRATION_NAME }
57
58
  );
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../../../../src/integrations/tracing/redis/index.ts"],"sourcesContent":["import type { Span } from '@opentelemetry/api';\nimport type { IntegrationFn } from '@sentry/core';\nimport {\n defineIntegration,\n SEMANTIC_ATTRIBUTE_CACHE_HIT,\n SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE,\n SEMANTIC_ATTRIBUTE_CACHE_KEY,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n spanToJSON,\n truncate,\n} from '@sentry/core';\nimport { generateInstrumentOnce } from '@sentry/node-core';\nimport type { IORedisCommandArgs } from '../../../utils/redisCache';\nimport {\n calculateCacheItemSize,\n GET_COMMANDS,\n getCacheKeySafely,\n getCacheOperation,\n isInCommands,\n shouldConsiderForCache,\n} from '../../../utils/redisCache';\nimport type { IORedisResponseCustomAttributeFunction } from './vendored/types';\nimport { IORedisInstrumentation } from './vendored/ioredis-instrumentation';\nimport { RedisInstrumentation } from './vendored/redis-instrumentation';\nimport { subscribeRedisDiagnosticChannels } from './redis-dc-subscriber';\n\ninterface RedisOptions {\n /**\n * Define cache prefixes for cache keys that should be captured as a cache span.\n *\n * Setting this to, for example, `['user:']` will capture cache keys that start with `user:`.\n */\n cachePrefixes?: string[];\n /**\n * Maximum length of the cache key added to the span description. If the key exceeds this length, it will be truncated.\n *\n * Passing `0` will use the full cache key without truncation.\n *\n * By default, the full cache key is used.\n */\n maxCacheKeyLength?: number;\n}\n\nconst INTEGRATION_NAME = 'Redis';\n\n/* Only exported for testing purposes */\nexport let _redisOptions: RedisOptions = {};\n\n/* Only exported for testing purposes */\nexport const cacheResponseHook: IORedisResponseCustomAttributeFunction = (\n span: Span,\n redisCommand: string,\n cmdArgs: IORedisCommandArgs,\n response: unknown,\n) => {\n const safeKey = getCacheKeySafely(redisCommand, cmdArgs);\n const cacheOperation = getCacheOperation(redisCommand);\n\n if (\n !safeKey ||\n !cacheOperation ||\n !_redisOptions.cachePrefixes ||\n !shouldConsiderForCache(redisCommand, safeKey, _redisOptions.cachePrefixes)\n ) {\n // not relevant for cache\n return;\n }\n\n // otel/ioredis seems to be using the old standard, as there was a change to those params: https://github.com/open-telemetry/opentelemetry-specification/issues/3199\n // We are using params based on the docs: https://opentelemetry.io/docs/specs/semconv/attributes-registry/network/\n // Fall back to stable semconv attributes (server.address/server.port) when\n // old-semconv ones are absent, eg OTEL_SEMCONV_STABILITY_OPT_IN=database\n // set for node-redis v4/v5.\n const spanData = spanToJSON(span).data;\n const networkPeerAddress = spanData['net.peer.name'] ?? spanData['server.address'];\n const networkPeerPort = spanData['net.peer.port'] ?? spanData['server.port'];\n if (networkPeerPort && networkPeerAddress) {\n span.setAttributes({ 'network.peer.address': networkPeerAddress, 'network.peer.port': networkPeerPort });\n }\n\n const cacheItemSize = calculateCacheItemSize(response);\n\n if (cacheItemSize) {\n span.setAttribute(SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE, cacheItemSize);\n }\n\n if (isInCommands(GET_COMMANDS, redisCommand) && cacheItemSize !== undefined) {\n span.setAttribute(SEMANTIC_ATTRIBUTE_CACHE_HIT, cacheItemSize > 0);\n }\n\n span.setAttributes({\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: cacheOperation,\n [SEMANTIC_ATTRIBUTE_CACHE_KEY]: safeKey,\n });\n\n // todo: change to string[] once EAP supports it\n const spanDescription = safeKey.join(', ');\n\n span.updateName(\n _redisOptions.maxCacheKeyLength ? truncate(spanDescription, _redisOptions.maxCacheKeyLength) : spanDescription,\n );\n};\n\nconst instrumentIORedis = generateInstrumentOnce(`${INTEGRATION_NAME}.IORedis`, () => {\n return new IORedisInstrumentation({\n responseHook: cacheResponseHook,\n });\n});\n\nconst instrumentRedisModule = generateInstrumentOnce(`${INTEGRATION_NAME}.Redis`, () => {\n return new RedisInstrumentation({\n responseHook: cacheResponseHook,\n });\n});\n\n/** To be able to preload all Redis OTel instrumentations with just one ID (\"Redis\"), all the instrumentations are generated in this one function */\nexport const instrumentRedis = Object.assign(\n (): void => {\n instrumentIORedis();\n instrumentRedisModule();\n // node-redis >= 5.12.0 publishes via diagnostics_channel. The subscriber uses\n // `@sentry/opentelemetry/tracing-channel`, which needs the Sentry OTel context manager\n // to be registered before it can `bindStore`. `initOpenTelemetry()` runs after integration\n // `setupOnce`, so defer to the next tick.\n void Promise.resolve().then(() => subscribeRedisDiagnosticChannels(cacheResponseHook));\n\n // todo: implement them gradually\n // new LegacyRedisInstrumentation({}),\n },\n { id: INTEGRATION_NAME },\n);\n\nconst _redisIntegration = ((options: RedisOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n _redisOptions = options;\n instrumentRedis();\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Adds Sentry tracing instrumentation for the [redis](https://www.npmjs.com/package/redis) and\n * [ioredis](https://www.npmjs.com/package/ioredis) libraries.\n *\n * For more information, see the [`redisIntegration` documentation](https://docs.sentry.io/platforms/javascript/guides/node/configuration/integrations/redis/).\n *\n * @example\n * ```javascript\n * const Sentry = require('@sentry/node');\n *\n * Sentry.init({\n * integrations: [Sentry.redisIntegration()],\n * });\n * ```\n */\nexport const redisIntegration = defineIntegration(_redisIntegration);\n"],"names":["_redisOptions","getCacheKeySafely","getCacheOperation","shouldConsiderForCache","spanToJSON","calculateCacheItemSize","SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE","isInCommands","GET_COMMANDS","SEMANTIC_ATTRIBUTE_CACHE_HIT","SEMANTIC_ATTRIBUTE_SENTRY_OP","SEMANTIC_ATTRIBUTE_CACHE_KEY","truncate","generateInstrumentOnce","IORedisInstrumentation","RedisInstrumentation","subscribeRedisDiagnosticChannels","defineIntegration"],"mappings":";;;;;;;;;AA2CA,MAAM,gBAAA,GAAmB,OAAA;AAGdA,wBAA8B;AAGlC,MAAM,iBAAA,GAA4D,CACvE,IAAA,EACA,YAAA,EACA,SACA,QAAA,KACG;AACH,EAAA,MAAM,OAAA,GAAUC,4BAAA,CAAkB,YAAA,EAAc,OAAO,CAAA;AACvD,EAAA,MAAM,cAAA,GAAiBC,6BAAkB,YAAY,CAAA;AAErD,EAAA,IACE,CAAC,OAAA,IACD,CAAC,cAAA,IACD,CAACF,qBAAA,CAAc,aAAA,IACf,CAACG,iCAAA,CAAuB,YAAA,EAAc,OAAA,EAASH,qBAAA,CAAc,aAAa,CAAA,EAC1E;AAEA,IAAA;AAAA,EACF;AAOA,EAAA,MAAM,QAAA,GAAWI,eAAA,CAAW,IAAI,CAAA,CAAE,IAAA;AAClC,EAAA,MAAM,kBAAA,GAAqB,QAAA,CAAS,eAAe,CAAA,IAAK,SAAS,gBAAgB,CAAA;AACjF,EAAA,MAAM,eAAA,GAAkB,QAAA,CAAS,eAAe,CAAA,IAAK,SAAS,aAAa,CAAA;AAC3E,EAAA,IAAI,mBAAmB,kBAAA,EAAoB;AACzC,IAAA,IAAA,CAAK,cAAc,EAAE,sBAAA,EAAwB,kBAAA,EAAoB,mBAAA,EAAqB,iBAAiB,CAAA;AAAA,EACzG;AAEA,EAAA,MAAM,aAAA,GAAgBC,kCAAuB,QAAQ,CAAA;AAErD,EAAA,IAAI,aAAA,EAAe;AACjB,IAAA,IAAA,CAAK,YAAA,CAAaC,yCAAoC,aAAa,CAAA;AAAA,EACrE;AAEA,EAAA,IAAIC,uBAAA,CAAaC,uBAAA,EAA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AAChB,MAAA,eAAA,EAAgB;AAAA,IAClB;AAAA,GACF;AACF,CAAA,CAAA;AAiBO,MAAM,gBAAA,GAAmBiB,uBAAkB,iBAAiB;;;;;;"}
1
+ {"version":3,"file":"index.js","sources":["../../../../../src/integrations/tracing/redis/index.ts"],"sourcesContent":["import type { Span } from '@opentelemetry/api';\nimport type { IntegrationFn } from '@sentry/core';\nimport {\n defineIntegration,\n SEMANTIC_ATTRIBUTE_CACHE_HIT,\n SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE,\n SEMANTIC_ATTRIBUTE_CACHE_KEY,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n spanToJSON,\n truncate,\n} from '@sentry/core';\nimport { subscribeRedisDiagnosticChannels } from '@sentry-internal/server-utils';\nimport { generateInstrumentOnce } from '@sentry/node-core';\nimport { tracingChannel as otelTracingChannel } from '@sentry/opentelemetry/tracing-channel';\nimport type { IORedisCommandArgs } from '../../../utils/redisCache';\nimport {\n calculateCacheItemSize,\n GET_COMMANDS,\n getCacheKeySafely,\n getCacheOperation,\n isInCommands,\n shouldConsiderForCache,\n} from '../../../utils/redisCache';\nimport type { IORedisResponseCustomAttributeFunction } from './vendored/types';\nimport { IORedisInstrumentation } from './vendored/ioredis-instrumentation';\nimport { RedisInstrumentation } from './vendored/redis-instrumentation';\n\ninterface RedisOptions {\n /**\n * Define cache prefixes for cache keys that should be captured as a cache span.\n *\n * Setting this to, for example, `['user:']` will capture cache keys that start with `user:`.\n */\n cachePrefixes?: string[];\n /**\n * Maximum length of the cache key added to the span description. If the key exceeds this length, it will be truncated.\n *\n * Passing `0` will use the full cache key without truncation.\n *\n * By default, the full cache key is used.\n */\n maxCacheKeyLength?: number;\n}\n\nconst INTEGRATION_NAME = 'Redis';\n\n/* Only exported for testing purposes */\nexport let _redisOptions: RedisOptions = {};\n\n/* Only exported for testing purposes */\nexport const cacheResponseHook: IORedisResponseCustomAttributeFunction = (\n span: Span,\n redisCommand: string,\n cmdArgs: IORedisCommandArgs,\n response: unknown,\n) => {\n const safeKey = getCacheKeySafely(redisCommand, cmdArgs);\n const cacheOperation = getCacheOperation(redisCommand);\n\n if (\n !safeKey ||\n !cacheOperation ||\n !_redisOptions.cachePrefixes ||\n !shouldConsiderForCache(redisCommand, safeKey, _redisOptions.cachePrefixes)\n ) {\n // not relevant for cache\n return;\n }\n\n // otel/ioredis seems to be using the old standard, as there was a change to those params: https://github.com/open-telemetry/opentelemetry-specification/issues/3199\n // We are using params based on the docs: https://opentelemetry.io/docs/specs/semconv/attributes-registry/network/\n // Fall back to stable semconv attributes (server.address/server.port) when\n // old-semconv ones are absent, eg OTEL_SEMCONV_STABILITY_OPT_IN=database\n // set for node-redis v4/v5.\n const spanData = spanToJSON(span).data;\n const networkPeerAddress = spanData['net.peer.name'] ?? spanData['server.address'];\n const networkPeerPort = spanData['net.peer.port'] ?? spanData['server.port'];\n if (networkPeerPort && networkPeerAddress) {\n span.setAttributes({ 'network.peer.address': networkPeerAddress, 'network.peer.port': networkPeerPort });\n }\n\n const cacheItemSize = calculateCacheItemSize(response);\n\n if (cacheItemSize) {\n span.setAttribute(SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE, cacheItemSize);\n }\n\n if (isInCommands(GET_COMMANDS, redisCommand) && cacheItemSize !== undefined) {\n span.setAttribute(SEMANTIC_ATTRIBUTE_CACHE_HIT, cacheItemSize > 0);\n }\n\n span.setAttributes({\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: cacheOperation,\n [SEMANTIC_ATTRIBUTE_CACHE_KEY]: safeKey,\n });\n\n // todo: change to string[] once EAP supports it\n const spanDescription = safeKey.join(', ');\n\n span.updateName(\n _redisOptions.maxCacheKeyLength ? truncate(spanDescription, _redisOptions.maxCacheKeyLength) : spanDescription,\n );\n};\n\nconst instrumentIORedis = generateInstrumentOnce(`${INTEGRATION_NAME}.IORedis`, () => {\n return new IORedisInstrumentation({\n responseHook: cacheResponseHook,\n });\n});\n\nconst instrumentRedisModule = generateInstrumentOnce(`${INTEGRATION_NAME}.Redis`, () => {\n return new RedisInstrumentation({\n responseHook: cacheResponseHook,\n });\n});\n\n/**\n * To be able to preload all Redis OTel instrumentations with just one ID\n * (\"Redis\"), all the instrumentations are generated in this one function\n */\nexport const instrumentRedis = Object.assign(\n (): void => {\n instrumentIORedis();\n instrumentRedisModule();\n // node-redis >= 5.12.0 and ioredis >= 5.11.0 publish via diagnostics_channel.\n // We pass `@sentry/opentelemetry/tracing-channel` as the factory so the span\n // becomes the active OTel context via `bindStore`. That factory needs the\n // Sentry OTel context manager to be registered, which `initOpenTelemetry()`\n // does after integration `setupOnce`, so defer to the next tick.\n void Promise.resolve().then(() => subscribeRedisDiagnosticChannels(otelTracingChannel, cacheResponseHook));\n\n // todo: implement them gradually\n // new LegacyRedisInstrumentation({}),\n },\n { id: INTEGRATION_NAME },\n);\n\nconst _redisIntegration = ((options: RedisOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n _redisOptions = options;\n instrumentRedis();\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Adds Sentry tracing instrumentation for the [redis](https://www.npmjs.com/package/redis) and\n * [ioredis](https://www.npmjs.com/package/ioredis) libraries.\n *\n * For more information, see the [`redisIntegration` documentation](https://docs.sentry.io/platforms/javascript/guides/node/configuration/integrations/redis/).\n *\n * @example\n * ```javascript\n * const Sentry = require('@sentry/node');\n *\n * Sentry.init({\n * integrations: [Sentry.redisIntegration()],\n * });\n * ```\n */\nexport const redisIntegration = defineIntegration(_redisIntegration);\n"],"names":["_redisOptions","getCacheKeySafely","getCacheOperation","shouldConsiderForCache","spanToJSON","calculateCacheItemSize","SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE","isInCommands","GET_COMMANDS","SEMANTIC_ATTRIBUTE_CACHE_HIT","SEMANTIC_ATTRIBUTE_SENTRY_OP","SEMANTIC_ATTRIBUTE_CACHE_KEY","truncate","generateInstrumentOnce","IORedisInstrumentation","RedisInstrumentation","subscribeRedisDiagn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rumentationBase {
38
38
  return [
39
39
  new instrumentation.InstrumentationNodeModuleDefinition(
40
40
  "ioredis",
41
- [">=2.0.0 <6"],
41
+ [">=2.0.0 <5.11.0"],
42
42
  (module, moduleVersion) => {
43
43
  const moduleExports = module[Symbol.toStringTag] === "Module" ? module.default : module;
44
44
  if (instrumentation.isWrapped(moduleExports.prototype.sendCommand)) {