@sentry/node 10.63.0 → 10.64.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/cjs/index.js +15 -14
- package/build/cjs/index.js.map +1 -1
- package/build/cjs/integrations/node-fetch.js +24 -0
- package/build/cjs/integrations/node-fetch.js.map +1 -0
- package/build/cjs/integrations/tracing/amqplib/vendored/semconv.js +0 -6
- package/build/cjs/integrations/tracing/amqplib/vendored/semconv.js.map +1 -1
- package/build/cjs/integrations/tracing/amqplib/vendored/utils.js +11 -10
- package/build/cjs/integrations/tracing/amqplib/vendored/utils.js.map +1 -1
- package/build/cjs/integrations/tracing/connect/vendored/instrumentation.js +2 -2
- package/build/cjs/integrations/tracing/connect/vendored/instrumentation.js.map +1 -1
- package/build/cjs/integrations/tracing/fastify/v3/instrumentation.js +2 -2
- package/build/cjs/integrations/tracing/fastify/v3/instrumentation.js.map +1 -1
- package/build/cjs/integrations/tracing/firebase/otel/patches/firestore.js +9 -9
- package/build/cjs/integrations/tracing/firebase/otel/patches/firestore.js.map +1 -1
- package/build/cjs/integrations/tracing/hapi/vendored/utils.js +8 -9
- package/build/cjs/integrations/tracing/hapi/vendored/utils.js.map +1 -1
- package/build/cjs/integrations/tracing/hono/index.js +7 -7
- package/build/cjs/integrations/tracing/hono/index.js.map +1 -1
- package/build/cjs/integrations/tracing/kafka/vendored/instrumentation.js +2 -1
- package/build/cjs/integrations/tracing/kafka/vendored/instrumentation.js.map +1 -1
- package/build/cjs/integrations/tracing/kafka/vendored/semconv.js +0 -12
- package/build/cjs/integrations/tracing/kafka/vendored/semconv.js.map +1 -1
- package/build/cjs/integrations/tracing/kafka/vendored/utils.js +12 -11
- package/build/cjs/integrations/tracing/kafka/vendored/utils.js.map +1 -1
- package/build/cjs/integrations/tracing/knex/vendored/instrumentation.js +11 -10
- package/build/cjs/integrations/tracing/knex/vendored/instrumentation.js.map +1 -1
- package/build/cjs/integrations/tracing/knex/vendored/semconv.js +0 -16
- package/build/cjs/integrations/tracing/knex/vendored/semconv.js.map +1 -1
- package/build/cjs/integrations/tracing/koa/vendored/instrumentation.js +2 -2
- package/build/cjs/integrations/tracing/koa/vendored/instrumentation.js.map +1 -1
- package/build/cjs/integrations/tracing/koa/vendored/utils.js +2 -2
- package/build/cjs/integrations/tracing/koa/vendored/utils.js.map +1 -1
- package/build/cjs/integrations/tracing/mongo/vendored/semconv.js +0 -12
- package/build/cjs/integrations/tracing/mongo/vendored/semconv.js.map +1 -1
- package/build/cjs/integrations/tracing/mongo/vendored/utils.js +12 -11
- package/build/cjs/integrations/tracing/mongo/vendored/utils.js.map +1 -1
- package/build/cjs/integrations/tracing/mongoose/index.js +3 -2
- package/build/cjs/integrations/tracing/mongoose/index.js.map +1 -1
- package/build/cjs/integrations/tracing/mongoose/vendored/mongoose.js +11 -8
- package/build/cjs/integrations/tracing/mongoose/vendored/mongoose.js.map +1 -1
- package/build/cjs/integrations/tracing/mongoose/vendored/semconv.js +0 -12
- package/build/cjs/integrations/tracing/mongoose/vendored/semconv.js.map +1 -1
- package/build/cjs/integrations/tracing/mongoose/vendored/utils.js +9 -9
- package/build/cjs/integrations/tracing/mongoose/vendored/utils.js.map +1 -1
- package/build/cjs/integrations/tracing/mysql/vendored/instrumentation.js +9 -8
- package/build/cjs/integrations/tracing/mysql/vendored/instrumentation.js.map +1 -1
- package/build/cjs/integrations/tracing/mysql/vendored/semconv.js +0 -12
- package/build/cjs/integrations/tracing/mysql/vendored/semconv.js.map +1 -1
- package/build/cjs/integrations/tracing/mysql2/vendored/instrumentation.js +7 -4
- package/build/cjs/integrations/tracing/mysql2/vendored/instrumentation.js.map +1 -1
- package/build/cjs/integrations/tracing/mysql2/vendored/semconv.js +0 -12
- package/build/cjs/integrations/tracing/mysql2/vendored/semconv.js.map +1 -1
- package/build/cjs/integrations/tracing/mysql2/vendored/utils.js +7 -4
- package/build/cjs/integrations/tracing/mysql2/vendored/utils.js.map +1 -1
- package/build/cjs/integrations/tracing/postgres/vendored/semconv.js +0 -12
- package/build/cjs/integrations/tracing/postgres/vendored/semconv.js.map +1 -1
- package/build/cjs/integrations/tracing/postgres/vendored/utils.js +12 -11
- package/build/cjs/integrations/tracing/postgres/vendored/utils.js.map +1 -1
- package/build/cjs/integrations/tracing/postgresjs.js +8 -7
- package/build/cjs/integrations/tracing/postgresjs.js.map +1 -1
- package/build/cjs/integrations/tracing/prisma/index.js +48 -53
- package/build/cjs/integrations/tracing/prisma/index.js.map +1 -1
- package/build/cjs/integrations/tracing/redis/cache.js +41 -0
- package/build/cjs/integrations/tracing/redis/cache.js.map +1 -0
- package/build/cjs/integrations/tracing/redis/index.js +14 -36
- package/build/cjs/integrations/tracing/redis/index.js.map +1 -1
- package/build/cjs/integrations/tracing/redis/vendored/ioredis-instrumentation.js +22 -13
- package/build/cjs/integrations/tracing/redis/vendored/ioredis-instrumentation.js.map +1 -1
- package/build/cjs/integrations/tracing/redis/vendored/redis-instrumentation.js +21 -15
- package/build/cjs/integrations/tracing/redis/vendored/redis-instrumentation.js.map +1 -1
- package/build/cjs/integrations/tracing/redis/vendored/semconv.js +0 -8
- package/build/cjs/integrations/tracing/redis/vendored/semconv.js.map +1 -1
- package/build/cjs/integrations/tracing/tedious/vendored/instrumentation.js +9 -8
- package/build/cjs/integrations/tracing/tedious/vendored/instrumentation.js.map +1 -1
- package/build/cjs/integrations/tracing/tedious/vendored/semconv.js +0 -12
- package/build/cjs/integrations/tracing/tedious/vendored/semconv.js.map +1 -1
- package/build/cjs/sdk/experimentalUseDiagnosticsChannelInjection.js +12 -2
- package/build/cjs/sdk/experimentalUseDiagnosticsChannelInjection.js.map +1 -1
- package/build/cjs/sdk/index.js +2 -2
- package/build/cjs/sdk/index.js.map +1 -1
- package/build/cjs/sdk/initOtel.js +36 -0
- package/build/cjs/sdk/initOtel.js.map +1 -1
- package/build/esm/index.js +2 -2
- package/build/esm/integrations/node-fetch.js +22 -0
- package/build/esm/integrations/node-fetch.js.map +1 -0
- package/build/esm/integrations/tracing/amqplib/vendored/semconv.js +1 -4
- package/build/esm/integrations/tracing/amqplib/vendored/semconv.js.map +1 -1
- package/build/esm/integrations/tracing/amqplib/vendored/utils.js +7 -6
- package/build/esm/integrations/tracing/amqplib/vendored/utils.js.map +1 -1
- package/build/esm/integrations/tracing/connect/vendored/instrumentation.js +2 -2
- package/build/esm/integrations/tracing/connect/vendored/instrumentation.js.map +1 -1
- package/build/esm/integrations/tracing/fastify/v3/instrumentation.js +2 -2
- package/build/esm/integrations/tracing/fastify/v3/instrumentation.js.map +1 -1
- package/build/esm/integrations/tracing/firebase/otel/patches/firestore.js +7 -7
- package/build/esm/integrations/tracing/firebase/otel/patches/firestore.js.map +1 -1
- package/build/esm/integrations/tracing/hapi/vendored/utils.js +3 -4
- package/build/esm/integrations/tracing/hapi/vendored/utils.js.map +1 -1
- package/build/esm/integrations/tracing/hono/index.js +3 -3
- package/build/esm/integrations/tracing/hono/index.js.map +1 -1
- package/build/esm/integrations/tracing/kafka/vendored/instrumentation.js +3 -2
- package/build/esm/integrations/tracing/kafka/vendored/instrumentation.js.map +1 -1
- package/build/esm/integrations/tracing/kafka/vendored/semconv.js +1 -7
- package/build/esm/integrations/tracing/kafka/vendored/semconv.js.map +1 -1
- package/build/esm/integrations/tracing/kafka/vendored/utils.js +11 -10
- package/build/esm/integrations/tracing/kafka/vendored/utils.js.map +1 -1
- package/build/esm/integrations/tracing/knex/vendored/instrumentation.js +10 -9
- package/build/esm/integrations/tracing/knex/vendored/instrumentation.js.map +1 -1
- package/build/esm/integrations/tracing/knex/vendored/semconv.js +1 -9
- package/build/esm/integrations/tracing/knex/vendored/semconv.js.map +1 -1
- package/build/esm/integrations/tracing/koa/vendored/instrumentation.js +2 -2
- package/build/esm/integrations/tracing/koa/vendored/instrumentation.js.map +1 -1
- package/build/esm/integrations/tracing/koa/vendored/utils.js +2 -2
- package/build/esm/integrations/tracing/koa/vendored/utils.js.map +1 -1
- package/build/esm/integrations/tracing/mongo/vendored/semconv.js +1 -7
- package/build/esm/integrations/tracing/mongo/vendored/semconv.js.map +1 -1
- package/build/esm/integrations/tracing/mongo/vendored/utils.js +9 -8
- package/build/esm/integrations/tracing/mongo/vendored/utils.js.map +1 -1
- package/build/esm/integrations/tracing/mongoose/index.js +4 -3
- package/build/esm/integrations/tracing/mongoose/index.js.map +1 -1
- package/build/esm/integrations/tracing/mongoose/vendored/mongoose.js +9 -6
- package/build/esm/integrations/tracing/mongoose/vendored/mongoose.js.map +1 -1
- package/build/esm/integrations/tracing/mongoose/vendored/semconv.js +1 -7
- package/build/esm/integrations/tracing/mongoose/vendored/semconv.js.map +1 -1
- package/build/esm/integrations/tracing/mongoose/vendored/utils.js +10 -10
- package/build/esm/integrations/tracing/mongoose/vendored/utils.js.map +1 -1
- package/build/esm/integrations/tracing/mysql/vendored/instrumentation.js +8 -7
- package/build/esm/integrations/tracing/mysql/vendored/instrumentation.js.map +1 -1
- package/build/esm/integrations/tracing/mysql/vendored/semconv.js +1 -7
- package/build/esm/integrations/tracing/mysql/vendored/semconv.js.map +1 -1
- package/build/esm/integrations/tracing/mysql2/vendored/instrumentation.js +6 -3
- package/build/esm/integrations/tracing/mysql2/vendored/instrumentation.js.map +1 -1
- package/build/esm/integrations/tracing/mysql2/vendored/semconv.js +1 -7
- package/build/esm/integrations/tracing/mysql2/vendored/semconv.js.map +1 -1
- package/build/esm/integrations/tracing/mysql2/vendored/utils.js +8 -5
- package/build/esm/integrations/tracing/mysql2/vendored/utils.js.map +1 -1
- package/build/esm/integrations/tracing/postgres/vendored/semconv.js +1 -7
- package/build/esm/integrations/tracing/postgres/vendored/semconv.js.map +1 -1
- package/build/esm/integrations/tracing/postgres/vendored/utils.js +13 -12
- package/build/esm/integrations/tracing/postgres/vendored/utils.js.map +1 -1
- package/build/esm/integrations/tracing/postgresjs.js +7 -6
- package/build/esm/integrations/tracing/postgresjs.js.map +1 -1
- package/build/esm/integrations/tracing/prisma/index.js +49 -54
- package/build/esm/integrations/tracing/prisma/index.js.map +1 -1
- package/build/esm/integrations/tracing/redis/cache.js +38 -0
- package/build/esm/integrations/tracing/redis/cache.js.map +1 -0
- package/build/esm/integrations/tracing/redis/index.js +9 -34
- package/build/esm/integrations/tracing/redis/index.js.map +1 -1
- package/build/esm/integrations/tracing/redis/vendored/ioredis-instrumentation.js +19 -10
- package/build/esm/integrations/tracing/redis/vendored/ioredis-instrumentation.js.map +1 -1
- package/build/esm/integrations/tracing/redis/vendored/redis-instrumentation.js +16 -10
- package/build/esm/integrations/tracing/redis/vendored/redis-instrumentation.js.map +1 -1
- package/build/esm/integrations/tracing/redis/vendored/semconv.js +1 -5
- package/build/esm/integrations/tracing/redis/vendored/semconv.js.map +1 -1
- package/build/esm/integrations/tracing/tedious/vendored/instrumentation.js +8 -7
- package/build/esm/integrations/tracing/tedious/vendored/instrumentation.js.map +1 -1
- package/build/esm/integrations/tracing/tedious/vendored/semconv.js +1 -7
- package/build/esm/integrations/tracing/tedious/vendored/semconv.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/esm/sdk/experimentalUseDiagnosticsChannelInjection.js +13 -4
- package/build/esm/sdk/experimentalUseDiagnosticsChannelInjection.js.map +1 -1
- package/build/esm/sdk/index.js +1 -1
- package/build/esm/sdk/initOtel.js +38 -2
- package/build/esm/sdk/initOtel.js.map +1 -1
- package/build/types/index.d.ts +1 -1
- package/build/types/index.d.ts.map +1 -1
- package/build/types/integrations/node-fetch.d.ts +9 -0
- package/build/types/integrations/node-fetch.d.ts.map +1 -0
- package/build/types/integrations/tracing/amqplib/vendored/semconv.d.ts +0 -6
- package/build/types/integrations/tracing/amqplib/vendored/semconv.d.ts.map +1 -1
- package/build/types/integrations/tracing/amqplib/vendored/utils.d.ts.map +1 -1
- package/build/types/integrations/tracing/hapi/vendored/utils.d.ts.map +1 -1
- package/build/types/integrations/tracing/kafka/vendored/semconv.d.ts +5 -63
- package/build/types/integrations/tracing/kafka/vendored/semconv.d.ts.map +1 -1
- package/build/types/integrations/tracing/kafka/vendored/utils.d.ts.map +1 -1
- package/build/types/integrations/tracing/knex/vendored/semconv.d.ts +0 -32
- package/build/types/integrations/tracing/knex/vendored/semconv.d.ts.map +1 -1
- package/build/types/integrations/tracing/mongo/vendored/semconv.d.ts +1 -37
- package/build/types/integrations/tracing/mongo/vendored/semconv.d.ts.map +1 -1
- package/build/types/integrations/tracing/mongo/vendored/utils.d.ts.map +1 -1
- package/build/types/integrations/tracing/mongoose/index.d.ts.map +1 -1
- package/build/types/integrations/tracing/mongoose/vendored/mongoose.d.ts.map +1 -1
- package/build/types/integrations/tracing/mongoose/vendored/semconv.d.ts +0 -48
- package/build/types/integrations/tracing/mongoose/vendored/semconv.d.ts.map +1 -1
- package/build/types/integrations/tracing/mongoose/vendored/utils.d.ts.map +1 -1
- package/build/types/integrations/tracing/mysql/vendored/instrumentation.d.ts.map +1 -1
- package/build/types/integrations/tracing/mysql/vendored/semconv.d.ts +1 -62
- package/build/types/integrations/tracing/mysql/vendored/semconv.d.ts.map +1 -1
- package/build/types/integrations/tracing/mysql2/vendored/instrumentation.d.ts.map +1 -1
- package/build/types/integrations/tracing/mysql2/vendored/semconv.d.ts +0 -6
- package/build/types/integrations/tracing/mysql2/vendored/semconv.d.ts.map +1 -1
- package/build/types/integrations/tracing/mysql2/vendored/utils.d.ts.map +1 -1
- package/build/types/integrations/tracing/postgres/vendored/semconv.d.ts +1 -50
- package/build/types/integrations/tracing/postgres/vendored/semconv.d.ts.map +1 -1
- package/build/types/integrations/tracing/postgres/vendored/utils.d.ts.map +1 -1
- package/build/types/integrations/tracing/postgresjs.d.ts.map +1 -1
- package/build/types/integrations/tracing/prisma/index.d.ts.map +1 -1
- package/build/types/integrations/tracing/redis/cache.d.ts +22 -0
- package/build/types/integrations/tracing/redis/cache.d.ts.map +1 -0
- package/build/types/integrations/tracing/redis/index.d.ts +2 -20
- package/build/types/integrations/tracing/redis/index.d.ts.map +1 -1
- package/build/types/integrations/tracing/redis/vendored/ioredis-instrumentation.d.ts.map +1 -1
- package/build/types/integrations/tracing/redis/vendored/redis-instrumentation.d.ts.map +1 -1
- package/build/types/integrations/tracing/redis/vendored/semconv.d.ts +0 -4
- package/build/types/integrations/tracing/redis/vendored/semconv.d.ts.map +1 -1
- package/build/types/integrations/tracing/tedious/vendored/instrumentation.d.ts.map +1 -1
- package/build/types/integrations/tracing/tedious/vendored/semconv.d.ts +1 -62
- package/build/types/integrations/tracing/tedious/vendored/semconv.d.ts.map +1 -1
- package/build/types/sdk/experimentalUseDiagnosticsChannelInjection.d.ts +2 -0
- package/build/types/sdk/experimentalUseDiagnosticsChannelInjection.d.ts.map +1 -1
- package/build/types/sdk/initOtel.d.ts +2 -3
- package/build/types/sdk/initOtel.d.ts.map +1 -1
- package/build/types-ts3.8/index.d.ts +1 -1
- package/build/types-ts3.8/integrations/node-fetch.d.ts +9 -0
- package/build/types-ts3.8/integrations/tracing/amqplib/vendored/semconv.d.ts +0 -6
- package/build/types-ts3.8/integrations/tracing/kafka/vendored/semconv.d.ts +5 -63
- package/build/types-ts3.8/integrations/tracing/knex/vendored/semconv.d.ts +0 -32
- package/build/types-ts3.8/integrations/tracing/mongo/vendored/semconv.d.ts +1 -37
- package/build/types-ts3.8/integrations/tracing/mongoose/vendored/semconv.d.ts +0 -48
- package/build/types-ts3.8/integrations/tracing/mysql/vendored/semconv.d.ts +1 -62
- package/build/types-ts3.8/integrations/tracing/mysql2/vendored/semconv.d.ts +0 -6
- package/build/types-ts3.8/integrations/tracing/postgres/vendored/semconv.d.ts +1 -50
- package/build/types-ts3.8/integrations/tracing/redis/cache.d.ts +22 -0
- package/build/types-ts3.8/integrations/tracing/redis/index.d.ts +2 -20
- package/build/types-ts3.8/integrations/tracing/redis/vendored/semconv.d.ts +0 -4
- package/build/types-ts3.8/integrations/tracing/tedious/vendored/semconv.d.ts +1 -62
- package/build/types-ts3.8/sdk/experimentalUseDiagnosticsChannelInjection.d.ts +2 -0
- package/build/types-ts3.8/sdk/initOtel.d.ts +3 -4
- package/package.json +8 -9
- package/build/cjs/integrations/node-fetch/index.js +0 -38
- package/build/cjs/integrations/node-fetch/index.js.map +0 -1
- package/build/cjs/integrations/node-fetch/undici-instrumentation.js +0 -266
- package/build/cjs/integrations/node-fetch/undici-instrumentation.js.map +0 -1
- package/build/cjs/integrations/tracing/hapi/vendored/semconv.js +0 -6
- package/build/cjs/integrations/tracing/hapi/vendored/semconv.js.map +0 -1
- package/build/cjs/integrations/tracing/redis/vendored/redis-common.js +0 -34
- package/build/cjs/integrations/tracing/redis/vendored/redis-common.js.map +0 -1
- package/build/esm/integrations/node-fetch/index.js +0 -36
- package/build/esm/integrations/node-fetch/index.js.map +0 -1
- package/build/esm/integrations/node-fetch/undici-instrumentation.js +0 -264
- package/build/esm/integrations/node-fetch/undici-instrumentation.js.map +0 -1
- package/build/esm/integrations/tracing/hapi/vendored/semconv.js +0 -4
- package/build/esm/integrations/tracing/hapi/vendored/semconv.js.map +0 -1
- package/build/esm/integrations/tracing/redis/vendored/redis-common.js +0 -32
- package/build/esm/integrations/tracing/redis/vendored/redis-common.js.map +0 -1
- package/build/types/integrations/node-fetch/index.d.ts +0 -5
- package/build/types/integrations/node-fetch/index.d.ts.map +0 -1
- package/build/types/integrations/node-fetch/types.d.ts +0 -96
- package/build/types/integrations/node-fetch/types.d.ts.map +0 -1
- package/build/types/integrations/node-fetch/undici-instrumentation.d.ts +0 -14
- package/build/types/integrations/node-fetch/undici-instrumentation.d.ts.map +0 -1
- package/build/types/integrations/tracing/hapi/vendored/semconv.d.ts +0 -13
- package/build/types/integrations/tracing/hapi/vendored/semconv.d.ts.map +0 -1
- package/build/types/integrations/tracing/redis/vendored/redis-common.d.ts +0 -6
- package/build/types/integrations/tracing/redis/vendored/redis-common.d.ts.map +0 -1
- package/build/types-ts3.8/integrations/node-fetch/index.d.ts +0 -5
- package/build/types-ts3.8/integrations/node-fetch/types.d.ts +0 -96
- package/build/types-ts3.8/integrations/node-fetch/undici-instrumentation.d.ts +0 -14
- package/build/types-ts3.8/integrations/tracing/hapi/vendored/semconv.d.ts +0 -13
- package/build/types-ts3.8/integrations/tracing/redis/vendored/redis-common.d.ts +0 -6
|
@@ -3,13 +3,14 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
3
3
|
const api = require('@opentelemetry/api');
|
|
4
4
|
const instrumentation = require('@opentelemetry/instrumentation');
|
|
5
5
|
const InstrumentationNodeModuleFile = require('./InstrumentationNodeModuleFile.js');
|
|
6
|
-
const
|
|
6
|
+
const attributes = require('@sentry/conventions/attributes');
|
|
7
7
|
const core = require('@sentry/core');
|
|
8
8
|
const nodeCore = require('@sentry/node-core');
|
|
9
9
|
const debugBuild = require('../../debug-build.js');
|
|
10
10
|
|
|
11
11
|
const INTEGRATION_NAME = "PostgresJs";
|
|
12
12
|
const SUPPORTED_VERSIONS = [">=3.0.0 <4"];
|
|
13
|
+
const ATTR_DB_RESPONSE_STATUS_CODE = "db.response.status_code";
|
|
13
14
|
const SQL_OPERATION_REGEX = /^(SELECT|INSERT|UPDATE|DELETE|CREATE|DROP|ALTER)/i;
|
|
14
15
|
const QUERY_FROM_INSTRUMENTED_SQL = /* @__PURE__ */ Symbol.for("sentry.query.from.instrumented.sql");
|
|
15
16
|
const instrumentPostgresJs = nodeCore.generateInstrumentOnce(
|
|
@@ -111,12 +112,12 @@ class PostgresJsInstrumentation extends instrumentation.InstrumentationBase {
|
|
|
111
112
|
*/
|
|
112
113
|
_setOperationName(span, sanitizedQuery, command) {
|
|
113
114
|
if (command) {
|
|
114
|
-
span.setAttribute(
|
|
115
|
+
span.setAttribute(attributes.DB_OPERATION_NAME, command);
|
|
115
116
|
return;
|
|
116
117
|
}
|
|
117
118
|
const operationMatch = sanitizedQuery?.match(SQL_OPERATION_REGEX);
|
|
118
119
|
if (operationMatch?.[1]) {
|
|
119
|
-
span.setAttribute(
|
|
120
|
+
span.setAttribute(attributes.DB_OPERATION_NAME, operationMatch[1].toUpperCase());
|
|
120
121
|
}
|
|
121
122
|
}
|
|
122
123
|
/**
|
|
@@ -175,8 +176,8 @@ class PostgresJsInstrumentation extends instrumentation.InstrumentationBase {
|
|
|
175
176
|
(span) => {
|
|
176
177
|
nodeCore.addOriginToSpan(span, "auto.db.postgresjs");
|
|
177
178
|
span.setAttributes({
|
|
178
|
-
[
|
|
179
|
-
[
|
|
179
|
+
[attributes.DB_SYSTEM_NAME]: "postgres",
|
|
180
|
+
[attributes.DB_QUERY_TEXT]: sanitizedSqlQuery
|
|
180
181
|
});
|
|
181
182
|
const config = self.getConfig();
|
|
182
183
|
const { requestHook } = config;
|
|
@@ -212,8 +213,8 @@ class PostgresJsInstrumentation extends instrumentation.InstrumentationBase {
|
|
|
212
213
|
code: core.SPAN_STATUS_ERROR,
|
|
213
214
|
message: rejectArgs?.[0]?.message || "unknown_error"
|
|
214
215
|
});
|
|
215
|
-
span.setAttribute(
|
|
216
|
-
span.setAttribute(
|
|
216
|
+
span.setAttribute(ATTR_DB_RESPONSE_STATUS_CODE, rejectArgs?.[0]?.code || "unknown");
|
|
217
|
+
span.setAttribute(attributes.ERROR_TYPE, rejectArgs?.[0]?.name || "unknown");
|
|
217
218
|
self._setOperationName(span, sanitizedSqlQuery);
|
|
218
219
|
span.end();
|
|
219
220
|
} catch (e) {
|
|
@@ -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 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' as const;\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 executed?: boolean;\n },\n ...args: unknown[]\n ): Promise<unknown> {\n // Skip if this query came from an instrumented sql instance (already handled by wrapper),\n // or if handle() was already called (postgres.js calls handle() from then/catch/finally —\n // only the first call executes SQL, subsequent calls are no-ops).\n if (this.executed || (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,kCA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/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 { DB_OPERATION_NAME, DB_QUERY_TEXT, DB_SYSTEM_NAME, ERROR_TYPE } from '@sentry/conventions/attributes';\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' as const;\nconst SUPPORTED_VERSIONS = ['>=3.0.0 <4'];\n// Not part of `@sentry/conventions`, so we keep it inline.\nconst ATTR_DB_RESPONSE_STATUS_CODE = 'db.response.status_code';\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(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(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 executed?: boolean;\n },\n ...args: unknown[]\n ): Promise<unknown> {\n // Skip if this query came from an instrumented sql instance (already handled by wrapper),\n // or if handle() was already called (postgres.js calls handle() from then/catch/finally —\n // only the first call executes SQL, subsequent calls are no-ops).\n if (this.executed || (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 [DB_SYSTEM_NAME]: 'postgres',\n [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(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","DB_OPERATION_NAME","startSpanManual","addOriginToSpan","DB_SYSTEM_NAME","DB_QUERY_TEXT","safeExecuteInTheMiddle","SPAN_STATUS_ERROR","ERROR_TYPE","defineIntegration"],"mappings":";;;;;;;;;;AAwBA,MAAM,gBAAA,GAAmB,YAAA;AACzB,MAAM,kBAAA,GAAqB,CAAC,YAAY,CAAA;AA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;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,GAAwBE,uBAAkB,sBAAsB;;;;;;"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
2
|
|
|
3
|
-
const api = require('@opentelemetry/api');
|
|
4
3
|
const core = require('@sentry/core');
|
|
5
4
|
const nodeCore = require('@sentry/node-core');
|
|
5
|
+
const debugBuild = require('../../../debug-build.js');
|
|
6
6
|
const instrumentation = require('./vendored/instrumentation.js');
|
|
7
7
|
|
|
8
8
|
const INTEGRATION_NAME = "Prisma";
|
|
@@ -14,6 +14,44 @@ function getPrismaTracingHelper() {
|
|
|
14
14
|
const prismaTracingHelper = prismaInstrumentationObject && typeof prismaInstrumentationObject === "object" && "helper" in prismaInstrumentationObject ? prismaInstrumentationObject.helper : void 0;
|
|
15
15
|
return prismaTracingHelper;
|
|
16
16
|
}
|
|
17
|
+
const MAX_TRACKED_PRISMA_SPANS = 1e3;
|
|
18
|
+
const prismaSpanRegistry = new core.LRUMap(MAX_TRACKED_PRISMA_SPANS);
|
|
19
|
+
const pendingEngineSpans = [];
|
|
20
|
+
function registerPrismaSpan(id, span) {
|
|
21
|
+
prismaSpanRegistry.set(id, span);
|
|
22
|
+
}
|
|
23
|
+
function createResolvedEngineSpans() {
|
|
24
|
+
let createdSpan = true;
|
|
25
|
+
while (createdSpan) {
|
|
26
|
+
createdSpan = false;
|
|
27
|
+
for (let i = pendingEngineSpans.length - 1; i >= 0; i--) {
|
|
28
|
+
const engineSpan = pendingEngineSpans[i];
|
|
29
|
+
const parentSpan = prismaSpanRegistry.get(engineSpan.parent_span_id);
|
|
30
|
+
if (!parentSpan) {
|
|
31
|
+
continue;
|
|
32
|
+
}
|
|
33
|
+
const span = core.startInactiveSpan({
|
|
34
|
+
name: engineSpan.name,
|
|
35
|
+
attributes: engineSpan.attributes,
|
|
36
|
+
kind: engineSpan.kind === "client" ? core.SPAN_KIND.CLIENT : core.SPAN_KIND.INTERNAL,
|
|
37
|
+
startTime: engineSpan.start_time,
|
|
38
|
+
parentSpan
|
|
39
|
+
});
|
|
40
|
+
registerPrismaSpan(engineSpan.span_id, span);
|
|
41
|
+
if (engineSpan.links) {
|
|
42
|
+
span.addLinks(
|
|
43
|
+
engineSpan.links.flatMap((link) => {
|
|
44
|
+
const linkedSpan = prismaSpanRegistry.get(link.span_id);
|
|
45
|
+
return linkedSpan ? [{ context: linkedSpan.spanContext() }] : [];
|
|
46
|
+
})
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
span.end(engineSpan.end_time);
|
|
50
|
+
pendingEngineSpans.splice(i, 1);
|
|
51
|
+
createdSpan = true;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
17
55
|
class SentryPrismaInteropInstrumentation extends instrumentation.PrismaInstrumentation {
|
|
18
56
|
constructor(options) {
|
|
19
57
|
super(options?.instrumentationConfig);
|
|
@@ -23,58 +61,12 @@ class SentryPrismaInteropInstrumentation extends instrumentation.PrismaInstrumen
|
|
|
23
61
|
const prismaTracingHelper = getPrismaTracingHelper();
|
|
24
62
|
if (isPrismaV6TracingHelper(prismaTracingHelper)) {
|
|
25
63
|
prismaTracingHelper.createEngineSpan = (engineSpanEvent) => {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
);
|
|
33
|
-
});
|
|
34
|
-
return;
|
|
35
|
-
}
|
|
36
|
-
try {
|
|
37
|
-
engineSpanEvent.spans.forEach((engineSpan) => {
|
|
38
|
-
const kind = engineSpan.kind === "client" ? api.SpanKind.CLIENT : api.SpanKind.INTERNAL;
|
|
39
|
-
const parentSpanId = engineSpan.parent_span_id;
|
|
40
|
-
const spanId = engineSpan.span_id;
|
|
41
|
-
const traceId = engineSpan.trace_id;
|
|
42
|
-
const links = engineSpan.links?.map((link) => {
|
|
43
|
-
return {
|
|
44
|
-
context: {
|
|
45
|
-
traceId: link.trace_id,
|
|
46
|
-
spanId: link.span_id,
|
|
47
|
-
traceFlags: api.TraceFlags.SAMPLED
|
|
48
|
-
}
|
|
49
|
-
};
|
|
50
|
-
});
|
|
51
|
-
const ctx = api.trace.setSpanContext(api.context.active(), {
|
|
52
|
-
traceId,
|
|
53
|
-
spanId: parentSpanId,
|
|
54
|
-
traceFlags: api.TraceFlags.SAMPLED
|
|
55
|
-
});
|
|
56
|
-
api.context.with(ctx, () => {
|
|
57
|
-
const temporaryIdGenerator = {
|
|
58
|
-
generateTraceId: () => {
|
|
59
|
-
return traceId;
|
|
60
|
-
},
|
|
61
|
-
generateSpanId: () => {
|
|
62
|
-
return spanId;
|
|
63
|
-
}
|
|
64
|
-
};
|
|
65
|
-
tracer._idGenerator = temporaryIdGenerator;
|
|
66
|
-
const span = tracer.startSpan(engineSpan.name, {
|
|
67
|
-
kind,
|
|
68
|
-
links,
|
|
69
|
-
startTime: engineSpan.start_time,
|
|
70
|
-
attributes: engineSpan.attributes
|
|
71
|
-
});
|
|
72
|
-
span.end(engineSpan.end_time);
|
|
73
|
-
tracer._idGenerator = initialIdGenerator;
|
|
74
|
-
});
|
|
75
|
-
});
|
|
76
|
-
} finally {
|
|
77
|
-
tracer._idGenerator = initialIdGenerator;
|
|
64
|
+
pendingEngineSpans.push(...engineSpanEvent.spans);
|
|
65
|
+
createResolvedEngineSpans();
|
|
66
|
+
const overflow = pendingEngineSpans.length - MAX_TRACKED_PRISMA_SPANS;
|
|
67
|
+
if (overflow > 0) {
|
|
68
|
+
debugBuild.DEBUG_BUILD && core.debug.log(`[Prisma] Dropping ${overflow} unresolved v5 engine span(s) whose parent was never registered.`);
|
|
69
|
+
pendingEngineSpans.splice(0, overflow);
|
|
78
70
|
}
|
|
79
71
|
};
|
|
80
72
|
}
|
|
@@ -97,6 +89,9 @@ const prismaIntegration = core.defineIntegration((options) => {
|
|
|
97
89
|
const spanJSON = core.spanToJSON(span);
|
|
98
90
|
if (spanJSON.description?.startsWith("prisma:")) {
|
|
99
91
|
span.setAttribute(core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, "auto.db.otel.prisma");
|
|
92
|
+
if (spanJSON.description.startsWith("prisma:client:")) {
|
|
93
|
+
registerPrismaSpan(span.spanContext().spanId, span);
|
|
94
|
+
}
|
|
100
95
|
}
|
|
101
96
|
if ((spanJSON.description === "prisma:engine:db_query" || spanJSON.description === "prisma:client:db_query") && spanJSON.data["db.query.text"]) {
|
|
102
97
|
span.updateName(spanJSON.data["db.query.text"]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../../../src/integrations/tracing/prisma/index.ts"],"sourcesContent":["import type { Link, Tracer } from '@opentelemetry/api';\nimport { context, SpanKind, trace, TraceFlags } from '@opentelemetry/api';\nimport type { Instrumentation } from '@opentelemetry/instrumentation';\nimport type { IdGenerator } from '@opentelemetry/sdk-trace-base';\nimport { consoleSandbox, defineIntegration, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, spanToJSON } from '@sentry/core';\nimport { generateInstrumentOnce } from '@sentry/node-core';\nimport { PrismaInstrumentation } from './vendored/instrumentation';\nimport type { PrismaV5TracingHelper } from './vendored/v5-tracing-helper';\nimport type { PrismaV6TracingHelper } from './vendored/v6-tracing-helper';\n\nconst INTEGRATION_NAME = 'Prisma' as const;\n\ntype CompatibilityLayerTraceHelper = PrismaV5TracingHelper & PrismaV6TracingHelper;\n\n// Vendored in from @prisma/instrumentation v5:\ntype V5EngineSpanEvent = {\n span: boolean;\n spans: V5EngineSpan[];\n};\n\ntype V5EngineSpanKind = 'client' | 'internal';\n\ntype V5EngineSpan = {\n span: boolean;\n name: string;\n trace_id: string;\n span_id: string;\n parent_span_id: string;\n start_time: [number, number];\n end_time: [number, number];\n attributes?: Record<string, string>;\n links?: { trace_id: string; span_id: string }[];\n kind: V5EngineSpanKind;\n};\n\nfunction isPrismaV6TracingHelper(helper: unknown): helper is PrismaV6TracingHelper {\n return !!helper && typeof helper === 'object' && 'dispatchEngineSpans' in helper;\n}\n\nfunction getPrismaTracingHelper(): unknown | undefined {\n const prismaInstrumentationObject = (globalThis as Record<string, unknown>).PRISMA_INSTRUMENTATION;\n const prismaTracingHelper =\n prismaInstrumentationObject &&\n typeof prismaInstrumentationObject === 'object' &&\n 'helper' in prismaInstrumentationObject\n ? prismaInstrumentationObject.helper\n : undefined;\n\n return prismaTracingHelper;\n}\n\ntype TracerWithIdGenerator = Tracer & {\n _idGenerator?: IdGenerator;\n};\n\ninterface PrismaOptions {\n /**\n * @deprecated This is no longer used, v5 works out of the box.\n */\n prismaInstrumentation?: Instrumentation;\n /**\n * Configuration passed through to the {@link PrismaInstrumentation} constructor.\n */\n instrumentationConfig?: ConstructorParameters<typeof PrismaInstrumentation>[0];\n}\n\nclass SentryPrismaInteropInstrumentation extends PrismaInstrumentation {\n public constructor(options?: PrismaOptions) {\n super(options?.instrumentationConfig);\n }\n\n public enable(): void {\n super.enable();\n\n // The PrismaIntegration (super class) defines a global variable `global[\"PRISMA_INSTRUMENTATION\"]` when `enable()` is called. This global variable holds a \"TracingHelper\" which Prisma uses internally to create tracing data. It's their way of not depending on OTEL with their main package. The sucky thing is, prisma broke the interface of the tracing helper with the v6 major update. This means that if you use Prisma 5 with the v6 instrumentation (or vice versa) Prisma just blows up, because tries to call methods on the helper that no longer exist.\n // Because we actually want to use the v6 instrumentation and not blow up in Prisma 5 user's faces, what we're doing here is backfilling the v5 method (`createEngineSpan`) with a noop so that no longer crashes when it attempts to call that function.\n const prismaTracingHelper = getPrismaTracingHelper();\n\n if (isPrismaV6TracingHelper(prismaTracingHelper)) {\n // Inspired & adjusted from https://github.com/prisma/prisma/tree/5.22.0/packages/instrumentation\n (prismaTracingHelper as CompatibilityLayerTraceHelper).createEngineSpan = (\n engineSpanEvent: V5EngineSpanEvent,\n ) => {\n const tracer = trace.getTracer('prismaV5Compatibility') as TracerWithIdGenerator;\n\n // Prisma v5 relies on being able to create spans with a specific span & trace ID\n // this is no longer possible in OTEL v2, there is no public API to do this anymore\n // So in order to kind of hack this possibility, we rely on the internal `_idGenerator` property\n // This is used to generate the random IDs, and we overwrite this temporarily to generate static IDs\n // This is flawed and may not work, e.g. if the code is bundled and the private property is renamed\n // in such cases, these spans will not be captured and some Prisma spans will be missing\n const initialIdGenerator = tracer._idGenerator;\n\n if (!initialIdGenerator) {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n '[Sentry] Could not find _idGenerator on tracer, skipping Prisma v5 compatibility - some Prisma spans may be missing!',\n );\n });\n\n return;\n }\n\n try {\n engineSpanEvent.spans.forEach(engineSpan => {\n const kind = engineSpan.kind === 'client' ? SpanKind.CLIENT : SpanKind.INTERNAL;\n\n const parentSpanId = engineSpan.parent_span_id;\n const spanId = engineSpan.span_id;\n const traceId = engineSpan.trace_id;\n\n const links: Link[] | undefined = engineSpan.links?.map(link => {\n return {\n context: {\n traceId: link.trace_id,\n spanId: link.span_id,\n traceFlags: TraceFlags.SAMPLED,\n },\n };\n });\n\n const ctx = trace.setSpanContext(context.active(), {\n traceId,\n spanId: parentSpanId,\n traceFlags: TraceFlags.SAMPLED,\n });\n\n context.with(ctx, () => {\n const temporaryIdGenerator: IdGenerator = {\n generateTraceId: () => {\n return traceId;\n },\n generateSpanId: () => {\n return spanId;\n },\n };\n\n tracer._idGenerator = temporaryIdGenerator;\n\n const span = tracer.startSpan(engineSpan.name, {\n kind,\n links,\n startTime: engineSpan.start_time,\n attributes: engineSpan.attributes,\n });\n\n span.end(engineSpan.end_time);\n\n tracer._idGenerator = initialIdGenerator;\n });\n });\n } finally {\n // Ensure we always restore this at the end, even if something errors\n tracer._idGenerator = initialIdGenerator;\n }\n };\n }\n }\n}\n\nexport const instrumentPrisma = generateInstrumentOnce<PrismaOptions>(INTEGRATION_NAME, options => {\n return new SentryPrismaInteropInstrumentation(options);\n});\n\n/**\n * Adds Sentry tracing instrumentation for the [prisma](https://www.npmjs.com/package/prisma) library.\n * For more information, see the [`prismaIntegration` documentation](https://docs.sentry.io/platforms/javascript/guides/node/configuration/integrations/prisma/).\n *\n * NOTE: This integration works out of the box with Prisma v6, and v7.\n * On Prisma versions prior to v6, add `previewFeatures = [\"tracing\"]` to the client generator block of your Prisma schema:\n *\n * ```\n * generator client {\n * provider = \"prisma-client-js\"\n * previewFeatures = [\"tracing\"]\n * }\n * ```\n */\nexport const prismaIntegration = defineIntegration((options?: PrismaOptions) => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n instrumentPrisma(options);\n },\n setup(client) {\n // If no tracing helper exists, we skip any work here\n // this means that prisma is not being used\n if (!getPrismaTracingHelper()) {\n return;\n }\n\n // Prisma v5 engine spans are created via the `createEngineSpan` path above, which bypasses the\n // tracing helper, so this hook applies origin, the db_query rename, and the db.system backfill to\n // them. v6/v7 spans already get these from the helper; the guards are idempotent, so it's a no-op there.\n client.on('spanStart', span => {\n const spanJSON = spanToJSON(span);\n if (spanJSON.description?.startsWith('prisma:')) {\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, 'auto.db.otel.prisma');\n }\n\n // Make sure we use the query text as the span name, for ex. SELECT * FROM \"User\" WHERE \"id\" = $1.\n // v5/v6 emit `prisma:engine:db_query`; v7 inlined the engine and emits `prisma:client:db_query`.\n if (\n (spanJSON.description === 'prisma:engine:db_query' || spanJSON.description === 'prisma:client:db_query') &&\n spanJSON.data['db.query.text']\n ) {\n span.updateName(spanJSON.data['db.query.text'] as string);\n }\n\n // In Prisma v5.22+, the `db.system` attribute is automatically set\n // On older versions, this is missing, so we add it here\n if (spanJSON.description === 'prisma:engine:db_query' && !spanJSON.data['db.system']) {\n span.setAttribute('db.system', 'prisma');\n }\n });\n },\n };\n});\n"],"names":["PrismaInstrumentation","trace","consoleSandbox","SpanKind","TraceFlags","context","generateInstrumentOnce","defineIntegration","spanToJSON","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN"],"mappings":";;;;;;;AAUA,MAAM,gBAAA,GAAmB,QAAA;AAyBzB,SAAS,wBAAwB,MAAA,EAAkD;AACjF,EAAA,OAAO,CAAC,CAAC,MAAA,IAAU,OAAO,MAAA,KAAW,YAAY,qBAAA,IAAyB,MAAA;AAC5E;AAEA,SAAS,sBAAA,GAA8C;AACrD,EAAA,MAAM,8BAA+B,UAAA,CAAuC,sBAAA;AAC5E,EAAA,MAAM,mBAAA,GACJ,+BACA,OAAO,2BAAA,KAAgC,YACvC,QAAA,IAAY,2BAAA,GACR,4BAA4B,MAAA,GAC5B,MAAA;AAEN,EAAA,OAAO,mBAAA;AACT;AAiBA,MAAM,2CAA2CA,qCAAA,CAAsB;AAAA,EAC9D,YAAY,OAAA,EAAyB;AAC1C,IAAA,KAAA,CAAM,SAAS,qBAAqB,CAAA;AAAA,EACtC;AAAA,EAEO,MAAA,GAAe;AACpB,IAAA,KAAA,CAAM,MAAA,EAAO;AAIb,IAAA,MAAM,sBAAsB,sBAAA,EAAuB;AAEnD,IAAA,IAAI,uBAAA,CAAwB,mBAAmB,CAAA,EAAG;AAEhD,MAAC,mBAAA,CAAsD,gBAAA,GAAmB,CACxE,eAAA,KACG;AACH,QAAA,MAAM,MAAA,GAASC,SAAA,CAAM,SAAA,CAAU,uBAAuB,CAAA;AAQtD,QAAA,MAAM,qBAAqB,MAAA,CAAO,YAAA;AAElC,QAAA,IAAI,CAAC,kBAAA,EAAoB;AACvB,UAAAC,mBAAA,CAAe,MAAM;AAEnB,YAAA,OAAA,CAAQ,IAAA;AAAA,cACN;AAAA,aACF;AAAA,UACF,CAAC,CAAA;AAED,UAAA;AAAA,QACF;AAEA,QAAA,IAAI;AACF,UAAA,eAAA,CA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;AACpF,UAAA,IAAA,CAAK,YAAA,CAAa,aAAa,QAAQ,CAAA;AAAA,QACzC;AAAA,MACF,CAAC,CAAA;AAAA,IACH;AAAA,GACF;AACF,CAAC;;;;;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../../../src/integrations/tracing/prisma/index.ts"],"sourcesContent":["import type { Instrumentation } from '@opentelemetry/instrumentation';\nimport type { Span } from '@sentry/core';\nimport {\n debug,\n defineIntegration,\n LRUMap,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SPAN_KIND,\n spanToJSON,\n startInactiveSpan,\n} from '@sentry/core';\nimport { generateInstrumentOnce } from '@sentry/node-core';\nimport { DEBUG_BUILD } from '../../../debug-build';\nimport { PrismaInstrumentation } from './vendored/instrumentation';\nimport type { PrismaV5TracingHelper } from './vendored/v5-tracing-helper';\nimport type { PrismaV6TracingHelper } from './vendored/v6-tracing-helper';\n\nconst INTEGRATION_NAME = 'Prisma' as const;\n\ntype CompatibilityLayerTraceHelper = PrismaV5TracingHelper & PrismaV6TracingHelper;\n\n// Vendored in from @prisma/instrumentation v5:\ntype V5EngineSpanEvent = {\n span: boolean;\n spans: V5EngineSpan[];\n};\n\ntype V5EngineSpanKind = 'client' | 'internal';\n\ntype V5EngineSpan = {\n span: boolean;\n name: string;\n trace_id: string;\n span_id: string;\n parent_span_id: string;\n start_time: [number, number];\n end_time: [number, number];\n attributes?: Record<string, string>;\n links?: { trace_id: string; span_id: string }[];\n kind: V5EngineSpanKind;\n};\n\nfunction isPrismaV6TracingHelper(helper: unknown): helper is PrismaV6TracingHelper {\n return !!helper && typeof helper === 'object' && 'dispatchEngineSpans' in helper;\n}\n\nfunction getPrismaTracingHelper(): unknown | undefined {\n const prismaInstrumentationObject = (globalThis as Record<string, unknown>).PRISMA_INSTRUMENTATION;\n const prismaTracingHelper =\n prismaInstrumentationObject &&\n typeof prismaInstrumentationObject === 'object' &&\n 'helper' in prismaInstrumentationObject\n ? prismaInstrumentationObject.helper\n : undefined;\n\n return prismaTracingHelper;\n}\n\n// Prisma v5 dispatches engine spans (`prisma:engine:*`, which carry the SQL `db.statement`) one batch\n// at a time, out of order, and detached from the active span, naming their parent only by id: a span\n// references either a client span (by the Sentry span id Prisma learned via `getTraceParent`) or a\n// sibling engine span (by the engine's own id), and a batch may not contain the parent it references.\n// By the time the engine reports them the client span may already have ended, so `getActiveSpan()`\n// can't be used to find it. `prismaSpanRegistry` maps span ids to their Sentry span, and an engine\n// span whose parent isn't registered yet waits in `pendingEngineSpans` until a later batch registers it.\nconst MAX_TRACKED_PRISMA_SPANS = 1000;\nconst prismaSpanRegistry = new LRUMap<string, Span>(MAX_TRACKED_PRISMA_SPANS);\nconst pendingEngineSpans: V5EngineSpan[] = [];\n\n/** Register a span so v5 engine spans can later resolve it as a parent by the id Prisma reports it under. */\nfunction registerPrismaSpan(id: string, span: Span): void {\n prismaSpanRegistry.set(id, span);\n}\n\n/**\n * Create every pending v5 engine span whose parent is now registered, repeating until no further span\n * resolves (so a child queued before its parent is created once the parent arrives in a later batch).\n * Each span is created under its resolved parent and registered by its engine id so its own children\n * can find it; origin, the `prisma:engine:db_query` to SQL rename, and the `db.system` backfill are\n * applied by the `spanStart` hook, exactly as for v6/v7 engine spans.\n */\nfunction createResolvedEngineSpans(): void {\n // Terminates: `createdSpan` is only set true right after a `splice`, so every pass that keeps the\n // loop going strictly shrinks the finite `pendingEngineSpans`; a pass that resolves nothing exits.\n let createdSpan = true;\n while (createdSpan) {\n createdSpan = false;\n for (let i = pendingEngineSpans.length - 1; i >= 0; i--) {\n const engineSpan = pendingEngineSpans[i]!;\n const parentSpan = prismaSpanRegistry.get(engineSpan.parent_span_id);\n if (!parentSpan) {\n continue;\n }\n\n const span = startInactiveSpan({\n name: engineSpan.name,\n attributes: engineSpan.attributes,\n kind: engineSpan.kind === 'client' ? SPAN_KIND.CLIENT : SPAN_KIND.INTERNAL,\n startTime: engineSpan.start_time,\n parentSpan,\n });\n registerPrismaSpan(engineSpan.span_id, span);\n\n // Engine links reference other engine spans by their engine id; re-point them at the Sentry spans\n // we minted (mirroring v6/v7's `dispatchEngineSpan`). Links must be added before the span ends,\n // since the SentryTracerProvider seals spans on end. Links to spans we haven't created are dropped.\n if (engineSpan.links) {\n span.addLinks(\n engineSpan.links.flatMap(link => {\n const linkedSpan = prismaSpanRegistry.get(link.span_id);\n return linkedSpan ? [{ context: linkedSpan.spanContext() }] : [];\n }),\n );\n }\n\n span.end(engineSpan.end_time);\n\n pendingEngineSpans.splice(i, 1);\n createdSpan = true;\n }\n }\n}\n\ninterface PrismaOptions {\n /**\n * @deprecated This is no longer used, v5 works out of the box.\n */\n prismaInstrumentation?: Instrumentation;\n /**\n * Configuration passed through to the {@link PrismaInstrumentation} constructor.\n */\n instrumentationConfig?: ConstructorParameters<typeof PrismaInstrumentation>[0];\n}\n\nclass SentryPrismaInteropInstrumentation extends PrismaInstrumentation {\n public constructor(options?: PrismaOptions) {\n super(options?.instrumentationConfig);\n }\n\n public enable(): void {\n super.enable();\n\n // The PrismaIntegration (super class) defines a global variable `global[\"PRISMA_INSTRUMENTATION\"]` when `enable()` is called. This global variable holds a \"TracingHelper\" which Prisma uses internally to create tracing data. It's their way of not depending on OTEL with their main package. The sucky thing is, prisma broke the interface of the tracing helper with the v6 major update. This means that if you use Prisma 5 with the v6 instrumentation (or vice versa) Prisma just blows up, because tries to call methods on the helper that no longer exist.\n // Because we actually want to use the v6/v7 instrumentation and not blow up in Prisma 5 users' faces, we backfill the v5-only `createEngineSpan` method so v5 engine spans are minted through Sentry's span APIs instead of crashing.\n const prismaTracingHelper = getPrismaTracingHelper();\n\n if (isPrismaV6TracingHelper(prismaTracingHelper)) {\n (prismaTracingHelper as CompatibilityLayerTraceHelper).createEngineSpan = (\n engineSpanEvent: V5EngineSpanEvent,\n ) => {\n pendingEngineSpans.push(...engineSpanEvent.spans);\n\n // Resolve before capping so a span is only ever dropped after a full resolution attempt, never\n // before it had a chance to find its parent. What remains are orphans whose parent was never\n // registered (e.g. evicted from the registry under sustained load); cap that backlog so it can't\n // grow without bound.\n createResolvedEngineSpans();\n\n const overflow = pendingEngineSpans.length - MAX_TRACKED_PRISMA_SPANS;\n if (overflow > 0) {\n DEBUG_BUILD &&\n debug.log(`[Prisma] Dropping ${overflow} unresolved v5 engine span(s) whose parent was never registered.`);\n pendingEngineSpans.splice(0, overflow);\n }\n };\n }\n }\n}\n\nexport const instrumentPrisma = generateInstrumentOnce<PrismaOptions>(INTEGRATION_NAME, options => {\n return new SentryPrismaInteropInstrumentation(options);\n});\n\n/**\n * Adds Sentry tracing instrumentation for the [prisma](https://www.npmjs.com/package/prisma) library.\n * For more information, see the [`prismaIntegration` documentation](https://docs.sentry.io/platforms/javascript/guides/node/configuration/integrations/prisma/).\n *\n * NOTE: This integration works out of the box with Prisma v6, and v7.\n * On Prisma versions prior to v6, add `previewFeatures = [\"tracing\"]` to the client generator block of your Prisma schema:\n *\n * ```\n * generator client {\n * provider = \"prisma-client-js\"\n * previewFeatures = [\"tracing\"]\n * }\n * ```\n */\nexport const prismaIntegration = defineIntegration((options?: PrismaOptions) => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n instrumentPrisma(options);\n },\n setup(client) {\n // If no tracing helper exists, we skip any work here\n // this means that prisma is not being used\n if (!getPrismaTracingHelper()) {\n return;\n }\n\n // Prisma v5 engine spans are created via the `createEngineSpan` path above, which bypasses the\n // tracing helper, so this hook applies origin, the db_query rename, and the db.system backfill to\n // them. v6/v7 spans already get these from the helper; the guards are idempotent, so it's a no-op there.\n client.on('spanStart', span => {\n const spanJSON = spanToJSON(span);\n if (spanJSON.description?.startsWith('prisma:')) {\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, 'auto.db.otel.prisma');\n\n // Register client spans so a v5 engine span (dispatched later, detached) can resolve one as a\n // parent by the Sentry span id Prisma reported via `getTraceParent` (see\n // `createResolvedEngineSpans`). Only client spans are referenced this way; engine spans\n // reference their parent by the engine's own id and are registered in `createResolvedEngineSpans`,\n // so registering them here too would just leave entries that are never looked up.\n if (spanJSON.description.startsWith('prisma:client:')) {\n registerPrismaSpan(span.spanContext().spanId, span);\n }\n }\n\n // Make sure we use the query text as the span name, for ex. SELECT * FROM \"User\" WHERE \"id\" = $1.\n // v5/v6 emit `prisma:engine:db_query`; v7 inlined the engine and emits `prisma:client:db_query`.\n if (\n (spanJSON.description === 'prisma:engine:db_query' || spanJSON.description === 'prisma:client:db_query') &&\n spanJSON.data['db.query.text']\n ) {\n span.updateName(spanJSON.data['db.query.text'] as string);\n }\n\n // In Prisma v5.22+, the `db.system` attribute is automatically set\n // On older versions, this is missing, so we add it here\n if (spanJSON.description === 'prisma:engine:db_query' && !spanJSON.data['db.system']) {\n span.setAttribute('db.system', 'prisma');\n }\n });\n },\n };\n});\n"],"names":["LRUMap","startInactiveSpan","SPAN_KIND","PrismaInstrumentation","DEBUG_BUILD","debug","generateInstrumentOnce","defineIntegration","spanToJSON","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN"],"mappings":";;;;;;;AAiBA,MAAM,gBAAA,GAAmB,QAAA;AAyBzB,SAAS,wBAAwB,MAAA,EAAkD;AACjF,EAAA,OAAO,CAAC,CAAC,MAAA,IAAU,OAAO,MAAA,KAAW,YAAY,qBAAA,IAAyB,MAAA;AAC5E;AAEA,SAAS,sBAAA,GAA8C;AACrD,EAAA,MAAM,8BAA+B,UAAA,CAAuC,sBAAA;AAC5E,EAAA,MAAM,mBAAA,GACJ,+BACA,OAAO,2BAAA,KAAgC,YACvC,QAAA,IAAY,2BAAA,GACR,4BAA4B,MAAA,GAC5B,MAAA;AAEN,EAAA,OAAO,mBAAA;AACT;AASA,MAAM,wBAAA,GAA2B,GAAA;AACjC,MAAM,kBAAA,GAAqB,IAAIA,WAAA,CAAqB,wBAAwB,CAAA;AAC5E,MAAM,qBAAqC,EAAC;AAG5C,SAAS,kBAAA,CAAmB,IAAY,IAAA,EAAkB;AACxD,EAAA,kBAAA,CAAmB,GAAA,CAAI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AAA,MAAA,CAAO,EAAA,CAAG,aAAa,CAAA,IAAA,KAAQ;AAC7B,QAAA,MAAM,QAAA,GAAWC,gBAAW,IAAI,CAAA;AAChC,QAAA,IAAI,QAAA,CAAS,WAAA,EAAa,UAAA,CAAW,SAAS,CAAA,EAAG;AAC/C,UAAA,IAAA,CAAK,YAAA,CAAaC,uCAAkC,qBAAqB,CAAA;AAOzE,UAAA,IAAI,QAAA,CAAS,WAAA,CAAY,UAAA,CAAW,gBAAgB,CAAA,EAAG;AACrD,YAAA,kBAAA,CAAmB,IAAA,CAAK,WAAA,EAAY,CAAE,MAAA,EAAQ,IAAI,CAAA;AAAA,UACpD;AAAA,QACF;AAIA,QAAA,IAAA,CACG,QAAA,CAAS,gBAAgB,wBAAA,IAA4B,QAAA,CAAS,gBAAgB,wBAAA,KAC/E,QAAA,CAAS,IAAA,CAAK,eAAe,CAAA,EAC7B;AACA,UAAA,IAAA,CAAK,UAAA,CAAW,QAAA,CAAS,IAAA,CAAK,eAAe,CAAW,CAAA;AAAA,QAC1D;AAIA,QAAA,IAAI,SAAS,WAAA,KAAgB,wBAAA,IAA4B,CAAC,QAAA,CAAS,IAAA,CAAK,WAAW,CAAA,EAAG;AACpF,UAAA,IAAA,CAAK,YAAA,CAAa,aAAa,QAAQ,CAAA;AAAA,QACzC;AAAA,MACF,CAAC,CAAA;AAAA,IACH;AAAA,GACF;AACF,CAAC;;;;;"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
|
|
3
|
+
const core = require('@sentry/core');
|
|
4
|
+
const redisCache = require('../../../utils/redisCache.js');
|
|
5
|
+
|
|
6
|
+
exports._redisOptions = {};
|
|
7
|
+
function setRedisOptions(options) {
|
|
8
|
+
exports._redisOptions = options;
|
|
9
|
+
}
|
|
10
|
+
const cacheResponseHook = (span, redisCommand, cmdArgs, response) => {
|
|
11
|
+
const safeKey = redisCache.getCacheKeySafely(redisCommand, cmdArgs);
|
|
12
|
+
const cacheOperation = redisCache.getCacheOperation(redisCommand);
|
|
13
|
+
if (!safeKey || !cacheOperation || !exports._redisOptions.cachePrefixes || !redisCache.shouldConsiderForCache(redisCommand, safeKey, exports._redisOptions.cachePrefixes)) {
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
const spanData = core.spanToJSON(span).data;
|
|
17
|
+
const networkPeerAddress = spanData["net.peer.name"] ?? spanData["server.address"];
|
|
18
|
+
const networkPeerPort = spanData["net.peer.port"] ?? spanData["server.port"];
|
|
19
|
+
if (networkPeerPort && networkPeerAddress) {
|
|
20
|
+
span.setAttributes({ "network.peer.address": networkPeerAddress, "network.peer.port": networkPeerPort });
|
|
21
|
+
}
|
|
22
|
+
const cacheItemSize = redisCache.calculateCacheItemSize(response);
|
|
23
|
+
if (cacheItemSize) {
|
|
24
|
+
span.setAttribute(core.SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE, cacheItemSize);
|
|
25
|
+
}
|
|
26
|
+
if (redisCache.isInCommands(redisCache.GET_COMMANDS, redisCommand) && cacheItemSize !== void 0) {
|
|
27
|
+
span.setAttribute(core.SEMANTIC_ATTRIBUTE_CACHE_HIT, cacheItemSize > 0);
|
|
28
|
+
}
|
|
29
|
+
span.setAttributes({
|
|
30
|
+
[core.SEMANTIC_ATTRIBUTE_SENTRY_OP]: cacheOperation,
|
|
31
|
+
[core.SEMANTIC_ATTRIBUTE_CACHE_KEY]: safeKey
|
|
32
|
+
});
|
|
33
|
+
const spanDescription = safeKey.join(", ");
|
|
34
|
+
span.updateName(
|
|
35
|
+
exports._redisOptions.maxCacheKeyLength ? core.truncate(spanDescription, exports._redisOptions.maxCacheKeyLength) : spanDescription
|
|
36
|
+
);
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
exports.cacheResponseHook = cacheResponseHook;
|
|
40
|
+
exports.setRedisOptions = setRedisOptions;
|
|
41
|
+
//# sourceMappingURL=cache.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cache.js","sources":["../../../../../src/integrations/tracing/redis/cache.ts"],"sourcesContent":["import type { Span } from '@sentry/core';\nimport {\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 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';\n\n// This module deliberately does NOT import the vendored OTel `IORedisInstrumentation`/\n// `RedisInstrumentation`, so the orchestrion opt-in can pull `cacheResponseHook`\n// without dragging the OTel redis instrumentation into its module graph.\n\nexport interface 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\n/* Only exported for testing purposes */\nexport let _redisOptions: RedisOptions = {};\n\n/** Set the options consumed by {@link cacheResponseHook}. */\nexport function setRedisOptions(options: RedisOptions): void {\n _redisOptions = options;\n}\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"],"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"],"mappings":";;;;;AA0CWA,wBAA8B;AAGlC,SAAS,gBAAgB,OAAA,EAA6B;AAC3D,EAA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A;AAGD,EAAA,MAAM,eAAA,GAAkB,OAAA,CAAQ,IAAA,CAAK,IAAI,CAAA;AAEzC,EAAA,IAAA,CAAK,UAAA;AAAA,IACHX,sBAAc,iBAAA,GAAoBY,aAAA,CAAS,eAAA,EAAiBZ,qBAAA,CAAc,iBAAiB,CAAA,GAAI;AAAA,GACjG;AACF;;;;;"}
|
|
@@ -4,57 +4,31 @@ const core = require('@sentry/core');
|
|
|
4
4
|
const dc = require('node:diagnostics_channel');
|
|
5
5
|
const serverUtils = require('@sentry/server-utils');
|
|
6
6
|
const nodeCore = require('@sentry/node-core');
|
|
7
|
-
const
|
|
7
|
+
const diagnosticsChannelInjection = require('../../../sdk/diagnosticsChannelInjection.js');
|
|
8
|
+
const cache = require('./cache.js');
|
|
8
9
|
const ioredisInstrumentation = require('./vendored/ioredis-instrumentation.js');
|
|
9
10
|
const redisInstrumentation = require('./vendored/redis-instrumentation.js');
|
|
10
11
|
|
|
11
12
|
const INTEGRATION_NAME = "Redis";
|
|
12
|
-
exports._redisOptions = {};
|
|
13
|
-
const cacheResponseHook = (span, redisCommand, cmdArgs, response) => {
|
|
14
|
-
const safeKey = redisCache.getCacheKeySafely(redisCommand, cmdArgs);
|
|
15
|
-
const cacheOperation = redisCache.getCacheOperation(redisCommand);
|
|
16
|
-
if (!safeKey || !cacheOperation || !exports._redisOptions.cachePrefixes || !redisCache.shouldConsiderForCache(redisCommand, safeKey, exports._redisOptions.cachePrefixes)) {
|
|
17
|
-
return;
|
|
18
|
-
}
|
|
19
|
-
const spanData = core.spanToJSON(span).data;
|
|
20
|
-
const networkPeerAddress = spanData["net.peer.name"] ?? spanData["server.address"];
|
|
21
|
-
const networkPeerPort = spanData["net.peer.port"] ?? spanData["server.port"];
|
|
22
|
-
if (networkPeerPort && networkPeerAddress) {
|
|
23
|
-
span.setAttributes({ "network.peer.address": networkPeerAddress, "network.peer.port": networkPeerPort });
|
|
24
|
-
}
|
|
25
|
-
const cacheItemSize = redisCache.calculateCacheItemSize(response);
|
|
26
|
-
if (cacheItemSize) {
|
|
27
|
-
span.setAttribute(core.SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE, cacheItemSize);
|
|
28
|
-
}
|
|
29
|
-
if (redisCache.isInCommands(redisCache.GET_COMMANDS, redisCommand) && cacheItemSize !== void 0) {
|
|
30
|
-
span.setAttribute(core.SEMANTIC_ATTRIBUTE_CACHE_HIT, cacheItemSize > 0);
|
|
31
|
-
}
|
|
32
|
-
span.setAttributes({
|
|
33
|
-
[core.SEMANTIC_ATTRIBUTE_SENTRY_OP]: cacheOperation,
|
|
34
|
-
[core.SEMANTIC_ATTRIBUTE_CACHE_KEY]: safeKey
|
|
35
|
-
});
|
|
36
|
-
const spanDescription = safeKey.join(", ");
|
|
37
|
-
span.updateName(
|
|
38
|
-
exports._redisOptions.maxCacheKeyLength ? core.truncate(spanDescription, exports._redisOptions.maxCacheKeyLength) : spanDescription
|
|
39
|
-
);
|
|
40
|
-
};
|
|
41
13
|
const instrumentIORedis = nodeCore.generateInstrumentOnce(`${INTEGRATION_NAME}.IORedis`, () => {
|
|
42
14
|
return new ioredisInstrumentation.IORedisInstrumentation({
|
|
43
|
-
responseHook: cacheResponseHook
|
|
15
|
+
responseHook: cache.cacheResponseHook
|
|
44
16
|
});
|
|
45
17
|
});
|
|
46
18
|
const instrumentRedisModule = nodeCore.generateInstrumentOnce(`${INTEGRATION_NAME}.Redis`, () => {
|
|
47
19
|
return new redisInstrumentation.RedisInstrumentation({
|
|
48
|
-
responseHook: cacheResponseHook
|
|
20
|
+
responseHook: cache.cacheResponseHook
|
|
49
21
|
});
|
|
50
22
|
});
|
|
51
23
|
const instrumentRedis = Object.assign(
|
|
52
24
|
() => {
|
|
53
|
-
|
|
25
|
+
if (!diagnosticsChannelInjection.isDiagnosticsChannelInjectionEnabled() || !dc.tracingChannel) {
|
|
26
|
+
instrumentIORedis();
|
|
27
|
+
}
|
|
54
28
|
instrumentRedisModule();
|
|
55
29
|
if (dc.tracingChannel) {
|
|
56
30
|
core.waitForTracingChannelBinding(() => {
|
|
57
|
-
serverUtils.subscribeRedisDiagnosticChannels(dc.tracingChannel, cacheResponseHook);
|
|
31
|
+
serverUtils.subscribeRedisDiagnosticChannels(dc.tracingChannel, cache.cacheResponseHook);
|
|
58
32
|
});
|
|
59
33
|
}
|
|
60
34
|
},
|
|
@@ -64,14 +38,18 @@ const _redisIntegration = ((options = {}) => {
|
|
|
64
38
|
return {
|
|
65
39
|
name: INTEGRATION_NAME,
|
|
66
40
|
setupOnce() {
|
|
67
|
-
|
|
41
|
+
cache.setRedisOptions(options);
|
|
68
42
|
instrumentRedis();
|
|
69
43
|
}
|
|
70
44
|
};
|
|
71
45
|
});
|
|
72
46
|
const redisIntegration = core.defineIntegration(_redisIntegration);
|
|
73
47
|
|
|
74
|
-
exports
|
|
48
|
+
Object.defineProperty(exports, "_redisOptions", {
|
|
49
|
+
enumerable: true,
|
|
50
|
+
get: () => cache._redisOptions
|
|
51
|
+
});
|
|
52
|
+
exports.cacheResponseHook = cache.cacheResponseHook;
|
|
75
53
|
exports.instrumentRedis = instrumentRedis;
|
|
76
54
|
exports.redisIntegration = redisIntegration;
|
|
77
55
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../../../src/integrations/tracing/redis/index.ts"],"sourcesContent":["import type { IntegrationFn
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../../../src/integrations/tracing/redis/index.ts"],"sourcesContent":["import type { IntegrationFn } from '@sentry/core';\nimport { defineIntegration, waitForTracingChannelBinding } from '@sentry/core';\nimport * as dc from 'node:diagnostics_channel';\nimport { subscribeRedisDiagnosticChannels, type RedisTracingChannelFactory } from '@sentry/server-utils';\nimport { generateInstrumentOnce } from '@sentry/node-core';\nimport { isDiagnosticsChannelInjectionEnabled } from '../../../sdk/diagnosticsChannelInjection';\nimport { cacheResponseHook, type RedisOptions, setRedisOptions } from './cache';\nimport { IORedisInstrumentation } from './vendored/ioredis-instrumentation';\nimport { RedisInstrumentation } from './vendored/redis-instrumentation';\n\n// `cacheResponseHook`/`_redisOptions` live in `./cache` (which has no OTel\n// instrumentation imports) so the orchestrion opt-in can pull the hook without\n// dragging the OTel redis instrumentation in. Re-exported here for tests.\nexport { _redisOptions, cacheResponseHook } from './cache';\n\nconst INTEGRATION_NAME = 'Redis' as const;\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 // When diagnostics-channel injection is opted in, orchestrion owns ioredis\n // `<5.11.0`, so skip the OTel ioredis monkey-patch to avoid double instrumentation.\n // On Node without `tracingChannel` (<18.19) orchestrion can't run, so keep the\n // OTel patch there — otherwise ioredis `<5.11.0` would not be traced at all.\n if (!isDiagnosticsChannelInjectionEnabled() || !dc.tracingChannel) {\n instrumentIORedis();\n }\n instrumentRedisModule();\n // node-redis >= 5.12.0 and ioredis >= 5.11.0 publish via diagnostics_channel.\n // `bindTracingChannelToSpan` (inside the subscriber) makes the span the active\n // OTel context via `bindStore`, which needs the Sentry OTel context manager to\n // be registered — `initOpenTelemetry()` does that after integration `setupOnce`,\n // so defer to the next tick.\n // Check this here to ensure this does not fail at runtime for Node <= 18.18.0\n if (dc.tracingChannel) {\n waitForTracingChannelBinding(() => {\n subscribeRedisDiagnosticChannels(dc.tracingChannel as RedisTracingChannelFactory, cacheResponseHook);\n });\n }\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 setRedisOptions(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":["generateInstrumentOnce","IORedisInstrumentation","cacheResponseHook","RedisInstrumentation","isDiagnosticsChannelInjectionEnabled","waitForTracingChannelBinding","subscribeRedisDiagnosticChannels","setRedisOptions","defineIntegration"],"mappings":";;;;;;;;;;;AAeA,MAAM,gBAAA,GAAmB,OAAA;AAEzB,MAAM,iBAAA,GAAoBA,+BAAA,CAAuB,CAAA,EAAG,gBAAgB,YAAY,MAAM;AACpF,EAAA,OAAO,IAAIC,6CAAA,CAAuB;AAAA,IAChC,YAAA,EAAcC;AAAA,GACf,CAAA;AACH,CAAC,CAAA;AAED,MAAM,qBAAA,GAAwBF,+BAAA,CAAuB,CAAA,EAAG,gBAAgB,UAAU,MAAM;AACtF,EAAA,OAAO,IAAIG,yCAAA,CAAqB;AAAA,IAC9B,YAAA,EAAcD;AAAA,GACf,CAAA;AACH,CAAC,CAAA;AAMM,MAAM,kBAAkB,MAAA,CAAO,MAAA;AAAA,EACpC,MAAY;AAKV,IAAA,IAAI,CAACE,gEAAA,EAAqC,IAAK,CAAC,GAAG,cAAA,EAAgB;AACjE,MAAA,iBAAA,EAAkB;AAAA,IACpB;AACA,IAAA,qBAAA,EAAsB;AAOtB,IAAA,IAAI,GAAG,cAAA,EAAgB;AACrB,MAAAC,iCAAA,CAA6B,MAAM;AACjC,QAAAC,4CAAA,CAAiC,EAAA,CAAG,gBAA8CJ,uBAAiB,CAAA;AAAA,MACrG,CAAC,CAAA;AAAA,IACH;AAAA,EAIF,CAAA;AAAA,EACA,EAAE,IAAI,gBAAA;AACR;AAEA,MAAM,iBAAA,IAAqB,CAAC,OAAA,GAAwB,EAAC,KAAM;AACzD,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,SAAA,GAAY;AACV,MAAAK,qBAAA,CAAgB,OAAO,CAAA;AACvB,MAAA,eAAA,EAAgB;AAAA,IAClB;AAAA,GACF;AACF,CAAA,CAAA;AAiBO,MAAM,gBAAA,GAAmBC,uBAAkB,iBAAiB;;;;;;;;;;"}
|
|
@@ -2,7 +2,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
2
2
|
|
|
3
3
|
const instrumentation = require('@opentelemetry/instrumentation');
|
|
4
4
|
const core = require('@sentry/core');
|
|
5
|
-
const
|
|
5
|
+
const attributes = require('@sentry/conventions/attributes');
|
|
6
|
+
const serverUtils = require('@sentry/server-utils');
|
|
6
7
|
const semconv = require('./semconv.js');
|
|
7
8
|
|
|
8
9
|
const PACKAGE_NAME = "@sentry/instrumentation-ioredis";
|
|
@@ -53,15 +54,19 @@ class IORedisInstrumentation extends instrumentation.InstrumentationBase {
|
|
|
53
54
|
return original.apply(this, args);
|
|
54
55
|
}
|
|
55
56
|
const { host, port } = this.options;
|
|
56
|
-
const attributes = {
|
|
57
|
-
|
|
58
|
-
[
|
|
57
|
+
const attributes$1 = {
|
|
58
|
+
// oxlint-disable-next-line typescript/no-deprecated
|
|
59
|
+
[attributes.DB_SYSTEM]: semconv.DB_SYSTEM_VALUE_REDIS,
|
|
60
|
+
// oxlint-disable-next-line typescript/no-deprecated
|
|
61
|
+
[attributes.DB_STATEMENT]: serverUtils.defaultDbStatementSerializer(cmd.name, cmd.args),
|
|
59
62
|
[semconv.ATTR_DB_CONNECTION_STRING]: `redis://${host}:${port}`,
|
|
60
|
-
|
|
61
|
-
[
|
|
63
|
+
// oxlint-disable-next-line typescript/no-deprecated
|
|
64
|
+
[attributes.NET_PEER_NAME]: host,
|
|
65
|
+
// oxlint-disable-next-line typescript/no-deprecated
|
|
66
|
+
[attributes.NET_PEER_PORT]: port,
|
|
62
67
|
[core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: ORIGIN
|
|
63
68
|
};
|
|
64
|
-
const span = core.startInactiveSpan({ name: cmd.name, kind: core.SPAN_KIND.CLIENT, attributes });
|
|
69
|
+
const span = core.startInactiveSpan({ name: cmd.name, kind: core.SPAN_KIND.CLIENT, attributes: attributes$1 });
|
|
65
70
|
try {
|
|
66
71
|
const result = original.apply(this, args);
|
|
67
72
|
const origResolve = cmd.resolve;
|
|
@@ -90,15 +95,19 @@ class IORedisInstrumentation extends instrumentation.InstrumentationBase {
|
|
|
90
95
|
return original.apply(this, args);
|
|
91
96
|
}
|
|
92
97
|
const { host, port } = this.options;
|
|
93
|
-
const attributes = {
|
|
94
|
-
|
|
95
|
-
[
|
|
98
|
+
const attributes$1 = {
|
|
99
|
+
// oxlint-disable-next-line typescript/no-deprecated
|
|
100
|
+
[attributes.DB_SYSTEM]: semconv.DB_SYSTEM_VALUE_REDIS,
|
|
101
|
+
// oxlint-disable-next-line typescript/no-deprecated
|
|
102
|
+
[attributes.DB_STATEMENT]: "connect",
|
|
96
103
|
[semconv.ATTR_DB_CONNECTION_STRING]: `redis://${host}:${port}`,
|
|
97
|
-
|
|
98
|
-
[
|
|
104
|
+
// oxlint-disable-next-line typescript/no-deprecated
|
|
105
|
+
[attributes.NET_PEER_NAME]: host,
|
|
106
|
+
// oxlint-disable-next-line typescript/no-deprecated
|
|
107
|
+
[attributes.NET_PEER_PORT]: port,
|
|
99
108
|
[core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: ORIGIN
|
|
100
109
|
};
|
|
101
|
-
const span = core.startInactiveSpan({ name: "connect", kind: core.SPAN_KIND.CLIENT, attributes });
|
|
110
|
+
const span = core.startInactiveSpan({ name: "connect", kind: core.SPAN_KIND.CLIENT, attributes: attributes$1 });
|
|
102
111
|
try {
|
|
103
112
|
const result = original.apply(this, args);
|
|
104
113
|
if (result instanceof Promise) {
|