@sentry/server-utils 11.16.0 → 11.18.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/chunks/config.js +62 -2
- package/build/cjs/chunks/config.js.map +1 -1
- package/build/cjs/chunks/exports.js +231 -66
- package/build/cjs/chunks/exports.js.map +1 -1
- package/build/cjs/chunks/moduleInjectedTransform.js +8 -0
- package/build/cjs/chunks/moduleInjectedTransform.js.map +1 -1
- package/build/cjs/index.js +447 -199
- package/build/cjs/index.js.map +1 -1
- package/build/cjs/index.no-diagnostic-channels.js +1 -0
- package/build/cjs/index.request-handler.js +48 -3
- package/build/cjs/index.request-handler.js.map +1 -1
- package/build/esm/ai/langchain/embeddings.js +23 -8
- package/build/esm/ai/langchain/embeddings.js.map +1 -1
- package/build/esm/ai/langchain/index.js +41 -30
- package/build/esm/ai/langchain/index.js.map +1 -1
- package/build/esm/ai/langchain/utils.js +1 -5
- package/build/esm/ai/langchain/utils.js.map +1 -1
- package/build/esm/ai/langgraph/agent-span.js +6 -2
- package/build/esm/ai/langgraph/agent-span.js.map +1 -1
- package/build/esm/ai/langgraph/index.js +5 -1
- package/build/esm/ai/langgraph/index.js.map +1 -1
- package/build/esm/ai/langgraph/stream.js +4 -1
- package/build/esm/ai/langgraph/stream.js.map +1 -1
- package/build/esm/ai/mistral/streaming.js.map +1 -1
- package/build/esm/ai/pi-durable/index.js +10 -13
- package/build/esm/ai/pi-durable/index.js.map +1 -1
- package/build/esm/ai/pi-durable/runs.js +6 -5
- package/build/esm/ai/pi-durable/runs.js.map +1 -1
- package/build/esm/ai/pi-durable/tools.js +21 -17
- package/build/esm/ai/pi-durable/tools.js.map +1 -1
- package/build/esm/exports.js +2 -1
- package/build/esm/index.js +5 -2
- package/build/esm/index.js.map +1 -1
- package/build/esm/index.no-diagnostic-channels.js +2 -1
- package/build/esm/index.request-handler.js +3 -1
- package/build/esm/integrations/amqplib.js.map +1 -1
- package/build/esm/integrations/anthropic.js.map +1 -1
- package/build/esm/integrations/bullmq/tracer.js.map +1 -1
- package/build/esm/integrations/clickhouse-sql.js +31 -0
- package/build/esm/integrations/clickhouse-sql.js.map +1 -0
- package/build/esm/integrations/clickhouse.js +88 -0
- package/build/esm/integrations/clickhouse.js.map +1 -0
- package/build/esm/integrations/express/instrumentation.js +1 -0
- package/build/esm/integrations/express/instrumentation.js.map +1 -1
- package/build/esm/integrations/fastify/instrumentation.js +3 -1
- package/build/esm/integrations/fastify/instrumentation.js.map +1 -1
- package/build/esm/integrations/graphql/utils.js.map +1 -1
- package/build/esm/integrations/hapi/hapi-utils.js +6 -9
- package/build/esm/integrations/hapi/hapi-utils.js.map +1 -1
- package/build/esm/integrations/hapi/index.js +15 -1
- package/build/esm/integrations/hapi/index.js.map +1 -1
- package/build/esm/integrations/hono/isMiddleware.js.map +1 -1
- package/build/esm/integrations/hono/middlewareHandlers.js +3 -1
- package/build/esm/integrations/hono/middlewareHandlers.js.map +1 -1
- package/build/esm/integrations/hono/patchRoute.js +2 -1
- package/build/esm/integrations/hono/patchRoute.js.map +1 -1
- package/build/esm/integrations/hono/unwrapThrownValue.js +20 -0
- package/build/esm/integrations/hono/unwrapThrownValue.js.map +1 -0
- package/build/esm/integrations/index.js +2 -0
- package/build/esm/integrations/index.js.map +1 -1
- package/build/esm/integrations/langchain.js +10 -3
- package/build/esm/integrations/langchain.js.map +1 -1
- package/build/esm/integrations/mongodb/mongodb-span.js +7 -9
- package/build/esm/integrations/mongodb/mongodb-span.js.map +1 -1
- package/build/esm/integrations/pino.js +2 -2
- package/build/esm/integrations/pino.js.map +1 -1
- package/build/esm/integrations/prisma/tracing-helper.js.map +1 -1
- package/build/esm/integrations/serveTunnel.js +2 -2
- package/build/esm/integrations/serveTunnel.js.map +1 -1
- package/build/esm/integrations/vercel-ai/extract.js +88 -0
- package/build/esm/integrations/vercel-ai/extract.js.map +1 -0
- package/build/esm/integrations/vercel-ai/util.js +5 -1
- package/build/esm/integrations/vercel-ai/util.js.map +1 -1
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js +19 -9
- package/build/esm/integrations/vercel-ai/vercel-ai-dc-subscriber.js.map +1 -1
- package/build/esm/integrations/winston.js +2 -2
- package/build/esm/integrations/winston.js.map +1 -1
- package/build/esm/orchestrion/channels.js +2 -0
- package/build/esm/orchestrion/channels.js.map +1 -1
- package/build/esm/orchestrion/config/channel-integration-definitions.js +8 -0
- package/build/esm/orchestrion/config/channel-integration-definitions.js.map +1 -1
- package/build/esm/orchestrion/config/clickhouse.js +51 -0
- package/build/esm/orchestrion/config/clickhouse.js.map +1 -0
- package/build/esm/orchestrion/config/hono.js +2 -2
- package/build/esm/orchestrion/config/hono.js.map +1 -1
- package/build/esm/orchestrion/config/index.js +2 -0
- package/build/esm/orchestrion/config/index.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/esm/utils/installedModules.js +87 -0
- package/build/esm/utils/installedModules.js.map +1 -0
- package/build/esm/utils/module.js +29 -0
- package/build/esm/utils/module.js.map +1 -0
- package/build/esm/utils/serverTimingTraceHeader.js +49 -0
- package/build/esm/utils/serverTimingTraceHeader.js.map +1 -0
- package/build/esm/utils/sql.js +41 -19
- package/build/esm/utils/sql.js.map +1 -1
- package/build/esm/utils/tunnelServer.js +3 -3
- package/build/esm/utils/tunnelServer.js.map +1 -1
- package/build/esm/utils/wrapServerRequestHandler.js +5 -4
- package/build/esm/utils/wrapServerRequestHandler.js.map +1 -1
- package/build/types/ai/langchain/embeddings.d.ts +2 -2
- package/build/types/ai/langchain/embeddings.d.ts.map +1 -1
- package/build/types/ai/langchain/index.d.ts.map +1 -1
- package/build/types/ai/langchain/types.d.ts +8 -4
- package/build/types/ai/langchain/types.d.ts.map +1 -1
- package/build/types/ai/langchain/utils.d.ts.map +1 -1
- package/build/types/ai/langgraph/agent-span.d.ts +5 -2
- package/build/types/ai/langgraph/agent-span.d.ts.map +1 -1
- package/build/types/ai/langgraph/index.d.ts.map +1 -1
- package/build/types/ai/langgraph/stream.d.ts.map +1 -1
- package/build/types/ai/langgraph/types.d.ts +10 -2
- package/build/types/ai/langgraph/types.d.ts.map +1 -1
- package/build/types/ai/mistral/streaming.d.ts.map +1 -1
- package/build/types/ai/pi-durable/index.d.ts.map +1 -1
- package/build/types/ai/pi-durable/runs.d.ts +4 -2
- package/build/types/ai/pi-durable/runs.d.ts.map +1 -1
- package/build/types/ai/pi-durable/tools.d.ts +4 -6
- package/build/types/ai/pi-durable/tools.d.ts.map +1 -1
- package/build/types/ai/pi-durable/types.d.ts +10 -1
- package/build/types/ai/pi-durable/types.d.ts.map +1 -1
- package/build/types/exports.d.ts +1 -0
- package/build/types/exports.d.ts.map +1 -1
- package/build/types/index.d.ts +5 -3
- package/build/types/index.d.ts.map +1 -1
- package/build/types/index.request-handler.d.ts +1 -0
- package/build/types/index.request-handler.d.ts.map +1 -1
- package/build/types/integrations/amqplib.d.ts.map +1 -1
- package/build/types/integrations/anthropic.d.ts.map +1 -1
- package/build/types/integrations/bullmq/tracer.d.ts.map +1 -1
- package/build/types/integrations/clickhouse-sql.d.ts +8 -0
- package/build/types/integrations/clickhouse-sql.d.ts.map +1 -0
- package/build/types/integrations/clickhouse.d.ts +11 -0
- package/build/types/integrations/clickhouse.d.ts.map +1 -0
- package/build/types/integrations/express/types.d.ts +1 -0
- package/build/types/integrations/express/types.d.ts.map +1 -1
- package/build/types/integrations/fastify/instrumentation.d.ts.map +1 -1
- package/build/types/integrations/hapi/hapi-utils.d.ts.map +1 -1
- package/build/types/integrations/hapi/index.d.ts +12 -0
- package/build/types/integrations/hapi/index.d.ts.map +1 -1
- package/build/types/integrations/hono/isMiddleware.d.ts.map +1 -1
- package/build/types/integrations/hono/middlewareHandlers.d.ts.map +1 -1
- package/build/types/integrations/hono/patchRoute.d.ts.map +1 -1
- package/build/types/integrations/hono/unwrapThrownValue.d.ts +10 -0
- package/build/types/integrations/hono/unwrapThrownValue.d.ts.map +1 -0
- package/build/types/integrations/index.d.ts.map +1 -1
- package/build/types/integrations/langchain.d.ts.map +1 -1
- package/build/types/integrations/mongodb/mongodb-span.d.ts.map +1 -1
- package/build/types/integrations/prisma/tracing-helper.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/extract.d.ts +27 -0
- package/build/types/integrations/vercel-ai/extract.d.ts.map +1 -0
- package/build/types/integrations/vercel-ai/util.d.ts +2 -0
- package/build/types/integrations/vercel-ai/util.d.ts.map +1 -1
- package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts +1 -1
- package/build/types/integrations/vercel-ai/vercel-ai-dc-subscriber.d.ts.map +1 -1
- package/build/types/orchestrion/channels.d.ts +12 -0
- package/build/types/orchestrion/channels.d.ts.map +1 -1
- package/build/types/orchestrion/config/channel-integration-definitions.d.ts +3 -0
- package/build/types/orchestrion/config/channel-integration-definitions.d.ts.map +1 -1
- package/build/types/orchestrion/config/clickhouse.d.ts +18 -0
- package/build/types/orchestrion/config/clickhouse.d.ts.map +1 -0
- package/build/types/orchestrion/config/index.d.ts.map +1 -1
- package/build/types/utils/installedModules.d.ts +17 -0
- package/build/types/utils/installedModules.d.ts.map +1 -0
- package/build/types/utils/module.d.ts +3 -0
- package/build/types/utils/module.d.ts.map +1 -0
- package/build/types/utils/serverTimingTraceHeader.d.ts +18 -0
- package/build/types/utils/serverTimingTraceHeader.d.ts.map +1 -0
- package/build/types/utils/sql.d.ts +28 -3
- package/build/types/utils/sql.d.ts.map +1 -1
- package/build/types/utils/tunnelServer.d.ts.map +1 -1
- package/build/types/utils/wrapServerRequestHandler.d.ts.map +1 -1
- package/package.json +4 -4
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { DB_COLLECTION_NAME, DB_CONNECTION_STRING, DB_NAMESPACE, DB_OPERATION_NAME, DB_QUERY_TEXT, DB_SYSTEM_NAME, SENTRY_KIND, SENTRY_OP, SENTRY_ORIGIN, SERVER_ADDRESS, SERVER_PORT } from "@sentry/conventions/attributes";
|
|
2
|
-
import { getClient, hasSpanStreamingEnabled, isObjectLike, startInactiveSpan } from "@sentry/core";
|
|
2
|
+
import { getActiveSpan, getClient, hasSpanStreamingEnabled, isObjectLike, startInactiveSpan } from "@sentry/core";
|
|
3
3
|
import { DB } from "@sentry/conventions/op";
|
|
4
4
|
// src/integrations/mongodb/mongodb-span.ts
|
|
5
5
|
const DB_SYSTEM_VALUE_MONGODB = "mongodb";
|
|
@@ -13,10 +13,11 @@ function serializeDbStatement(commandObj) {
|
|
|
13
13
|
}
|
|
14
14
|
function scrubStatement(value) {
|
|
15
15
|
if (Array.isArray(value)) return value.map((element) => scrubStatement(element));
|
|
16
|
-
if (isCommandObj(value))
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
16
|
+
if (isCommandObj(value)) {
|
|
17
|
+
const scrubbed = {};
|
|
18
|
+
for (const key of Object.keys(value)) scrubbed[key] = scrubStatement(value[key]);
|
|
19
|
+
return scrubbed;
|
|
20
|
+
}
|
|
20
21
|
return "?";
|
|
21
22
|
}
|
|
22
23
|
function isCommandObj(value) {
|
|
@@ -25,9 +26,6 @@ function isCommandObj(value) {
|
|
|
25
26
|
function isBuffer(value) {
|
|
26
27
|
return typeof Buffer !== "undefined" && Buffer.isBuffer(value);
|
|
27
28
|
}
|
|
28
|
-
function isCommandEntry(value) {
|
|
29
|
-
return Array.isArray(value);
|
|
30
|
-
}
|
|
31
29
|
/**
|
|
32
30
|
* Build span attributes for a mongodb v4+ command from the connection
|
|
33
31
|
* context, namespace and command.
|
|
@@ -66,7 +64,7 @@ function getSpanAttributes(dbName, dbCollection, host, port, commandObj, operati
|
|
|
66
64
|
const portNumber = parseInt(port, 10);
|
|
67
65
|
if (!isNaN(portNumber)) attributes[SERVER_PORT] = portNumber;
|
|
68
66
|
}
|
|
69
|
-
if (commandObj) try {
|
|
67
|
+
if (commandObj && getActiveSpan()?.isRecording()) try {
|
|
70
68
|
attributes[DB_QUERY_TEXT] = serializeDbStatement(commandObj);
|
|
71
69
|
} catch {}
|
|
72
70
|
return attributes;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mongodb-span.js","names":[],"sources":["../../../../src/integrations/mongodb/mongodb-span.ts"],"sourcesContent":["import {\n DB_COLLECTION_NAME,\n DB_NAMESPACE,\n DB_OPERATION_NAME,\n DB_QUERY_TEXT,\n DB_SYSTEM_NAME,\n SENTRY_KIND,\n SENTRY_OP,\n SERVER_ADDRESS,\n SERVER_PORT,\n SENTRY_ORIGIN,\n DB_CONNECTION_STRING,\n} from '@sentry/conventions/attributes';\nimport { DB } from '@sentry/conventions/op';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport { getClient, hasSpanStreamingEnabled, isObjectLike, startInactiveSpan } from '@sentry/core';\n\nconst DB_SYSTEM_VALUE_MONGODB = 'mongodb';\n\n/**\n * The db/collection namespace mongodb (v4+) passes to `Connection.command`\n */\nexport interface MongodbNamespace {\n db: string;\n collection?: string;\n}\n\ninterface V4Command {\n documents?: unknown[];\n cursors?: unknown;\n [key: string]: unknown;\n}\n\n/**\n * Replaces every leaf value in the command object with '?', keeping keys\n * and Mongo operators. hides PII and improves grouping. Reproduced from\n * the OTel instrumentation.\n */\nexport function serializeDbStatement(commandObj: Record<string, unknown>): string {\n return JSON.stringify(scrubStatement(commandObj));\n}\n\nfunction scrubStatement(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(element => scrubStatement(element));\n }\n\n if (isCommandObj(value)) {\n const
|
|
1
|
+
{"version":3,"file":"mongodb-span.js","names":[],"sources":["../../../../src/integrations/mongodb/mongodb-span.ts"],"sourcesContent":["import {\n DB_COLLECTION_NAME,\n DB_NAMESPACE,\n DB_OPERATION_NAME,\n DB_QUERY_TEXT,\n DB_SYSTEM_NAME,\n SENTRY_KIND,\n SENTRY_OP,\n SERVER_ADDRESS,\n SERVER_PORT,\n SENTRY_ORIGIN,\n DB_CONNECTION_STRING,\n} from '@sentry/conventions/attributes';\nimport { DB } from '@sentry/conventions/op';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport { getActiveSpan, getClient, hasSpanStreamingEnabled, isObjectLike, startInactiveSpan } from '@sentry/core';\n\nconst DB_SYSTEM_VALUE_MONGODB = 'mongodb';\n\n/**\n * The db/collection namespace mongodb (v4+) passes to `Connection.command`\n */\nexport interface MongodbNamespace {\n db: string;\n collection?: string;\n}\n\ninterface V4Command {\n documents?: unknown[];\n cursors?: unknown;\n [key: string]: unknown;\n}\n\n/**\n * Replaces every leaf value in the command object with '?', keeping keys\n * and Mongo operators. hides PII and improves grouping. Reproduced from\n * the OTel instrumentation.\n */\nexport function serializeDbStatement(commandObj: Record<string, unknown>): string {\n return JSON.stringify(scrubStatement(commandObj));\n}\n\nfunction scrubStatement(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(element => scrubStatement(element));\n }\n\n if (isCommandObj(value)) {\n const scrubbed: Record<string, unknown> = {};\n for (const key of Object.keys(value)) {\n scrubbed[key] = scrubStatement(value[key]);\n }\n return scrubbed;\n }\n\n // A value like string or number, possibly contains PII, scrub it.\n return '?';\n}\n\nfunction isCommandObj(value: unknown): value is Record<string, unknown> {\n return isObjectLike(value) && !isBuffer(value);\n}\n\nfunction isBuffer(value: unknown): boolean {\n return typeof Buffer !== 'undefined' && Buffer.isBuffer(value);\n}\n\n/**\n * Build span attributes for a mongodb v4+ command from the connection\n * context, namespace and command.\n */\nexport function getV4SpanAttributes(\n connectionCtx: { address?: string } | undefined,\n ns: MongodbNamespace,\n command: V4Command | undefined,\n operation: string | undefined,\n origin: string,\n): SpanAttributes {\n let host: string | undefined;\n let port: string | undefined;\n if (connectionCtx) {\n const hostParts = typeof connectionCtx.address === 'string' ? connectionCtx.address.split(':') : '';\n if (hostParts.length === 2) {\n host = hostParts[0];\n port = hostParts[1];\n }\n }\n\n let commandObj: Record<string, unknown> | undefined;\n if (command?.documents?.[0]) {\n commandObj = command.documents[0] as Record<string, unknown>;\n } else if (command?.cursors) {\n commandObj = command.cursors as Record<string, unknown>;\n } else {\n commandObj = command;\n }\n\n return getSpanAttributes(ns.db, ns.collection, host, port, commandObj, operation, origin);\n}\n\n/**\n * Shared attribute builder used by both the v3 topology path and the v4+\n * connection path.\n */\nexport function getSpanAttributes(\n dbName: string | undefined,\n dbCollection: string | undefined,\n host: string | undefined,\n port: string | undefined,\n commandObj: Record<string, unknown> | undefined,\n operation: string | undefined,\n origin: string,\n): SpanAttributes {\n const attributes: SpanAttributes = {\n [SENTRY_ORIGIN]: origin,\n [DB_SYSTEM_NAME]: DB_SYSTEM_VALUE_MONGODB,\n [DB_NAMESPACE]: dbName,\n [DB_COLLECTION_NAME]: dbCollection,\n [DB_OPERATION_NAME]: operation,\n // oxlint-disable-next-line typescript/no-deprecated -- Preserve the existing attribute name.\n [DB_CONNECTION_STRING]: `mongodb://${host}:${port}/${dbName}`,\n };\n\n if (host && port) {\n attributes[SERVER_ADDRESS] = host;\n const portNumber = parseInt(port, 10);\n if (!isNaN(portNumber)) {\n attributes[SERVER_PORT] = portNumber;\n }\n }\n\n // The statement is only sent with a recording span. Skip it otherwise, as the\n // serialization walks the whole command, which is expensive for large write payloads.\n if (commandObj && getActiveSpan()?.isRecording()) {\n try {\n attributes[DB_QUERY_TEXT] = serializeDbStatement(commandObj);\n } catch {\n // ignore serialization errors — the statement is best-effort metadata\n }\n }\n\n return attributes;\n}\n\n/** The v3 driver topology, from which host/port are read (mongodb 3.x). */\nexport interface MongoV3Topology {\n s?: {\n options?: { host?: string; port?: number };\n host?: string;\n port?: number;\n };\n description?: { address?: string };\n}\n\n/**\n * Determine the operation name for a mongodb v3 `command` from the command\n * document, mirroring the vendored instrumentation. Returns `undefined` for\n * commands it doesn't classify (e.g. `endSessions`).\n */\nexport function getV3CommandOperation(command: Record<string, unknown>): string | undefined {\n if (command.createIndexes !== undefined) {\n return 'createIndexes';\n } else if (command.findandmodify !== undefined) {\n return 'findAndModify';\n } else if (command.ismaster !== undefined) {\n return 'isMaster';\n } else if (command.count !== undefined) {\n return 'count';\n } else if (command.aggregate !== undefined) {\n return 'aggregate';\n }\n return undefined;\n}\n\n/**\n * Build span attributes for a mongodb v3 operation from the topology,\n * namespace string and command.\n */\nexport function getV3SpanAttributes(\n ns: string,\n topology: MongoV3Topology | undefined,\n command: Record<string, unknown> | undefined,\n operation: string | undefined,\n origin: string,\n): SpanAttributes {\n let host: string | undefined;\n let port: string | undefined;\n if (topology?.s) {\n host = topology.s.options?.host ?? topology.s.host;\n port = (topology.s.options?.port ?? topology.s.port)?.toString();\n if (host == null || port == null) {\n const address = topology.description?.address;\n if (address) {\n const segments = address.split(':');\n host = segments[0];\n port = segments[1];\n }\n }\n }\n\n // The namespace is `[db].[collection-or-index]`; coerce to string\n // (might be a MongoDBNamespace)\n const [dbName, dbCollection] = ns.toString().split('.');\n const commandObj =\n (command?.query as Record<string, unknown> | undefined) ??\n (command?.q as Record<string, unknown> | undefined) ??\n command;\n\n return getSpanAttributes(dbName, dbCollection, host, port, commandObj, operation, origin);\n}\n\n/**\n * Start a mongodb client span on the stable conventions.\n *\n * The `db` op is set explicitly rather than relying on `inferDbSpanData`,\n * to support platforms that lack it (ie, Deno).\n */\nexport function startMongoSpan(attributes: SpanAttributes): Span {\n const operation = attributes[DB_OPERATION_NAME] as string | undefined;\n const target = (attributes[DB_COLLECTION_NAME] || attributes[DB_NAMESPACE]) as string | undefined;\n\n const client = getClient();\n const name =\n client && hasSpanStreamingEnabled(client)\n ? operation && target\n ? `${operation} ${target}`\n : target || DB_SYSTEM_VALUE_MONGODB\n : (attributes[DB_QUERY_TEXT] as string) || `mongodb.${attributes[DB_OPERATION_NAME] || 'command'}`;\n\n return startInactiveSpan({\n name,\n onlyIfParent: true,\n attributes: {\n [SENTRY_OP]: DB,\n [SENTRY_KIND]: 'client',\n ...attributes,\n },\n });\n}\n"],"mappings":";;;;AAiBA,MAAM,0BAA0B;;;;;;AAqBhC,SAAgB,qBAAqB,YAA6C;CAChF,OAAO,KAAK,UAAU,eAAe,UAAU,CAAC;AAClD;AAEA,SAAS,eAAe,OAAyB;CAC/C,IAAI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AAG;EACL;CACF,CAAC;AACH"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { tracingChannel } from "../utils/diagnosticsChannel.js";
|
|
2
2
|
import { SENTRY_ORIGIN } from "@sentry/conventions/attributes";
|
|
3
|
-
import {
|
|
3
|
+
import { addExceptionMechanism, captureException, captureLogEvent, captureMessage, defineIntegration, isObjectLike, severityLevelFromString, withScope } from "@sentry/core";
|
|
4
4
|
// src/integrations/pino.ts
|
|
5
5
|
const SENTRY_TRACK_SYMBOL = Symbol("sentry-track-pino-logger");
|
|
6
6
|
/**
|
|
@@ -68,7 +68,7 @@ const _pinoIntegration = defineIntegration((userOptions = {}) => {
|
|
|
68
68
|
[SENTRY_ORIGIN]: "auto.log.pino",
|
|
69
69
|
"pino.logger.level": levelNumber
|
|
70
70
|
};
|
|
71
|
-
|
|
71
|
+
captureLogEvent({
|
|
72
72
|
level,
|
|
73
73
|
message: logMessage,
|
|
74
74
|
attributes
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pino.js","names":[],"sources":["../../../src/integrations/pino.ts"],"sourcesContent":["import { SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport type { IntegrationFn, LogSeverityLevel } from '@sentry/core';\nimport {\n
|
|
1
|
+
{"version":3,"file":"pino.js","names":[],"sources":["../../../src/integrations/pino.ts"],"sourcesContent":["import { SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport type { IntegrationFn, LogSeverityLevel } from '@sentry/core';\nimport {\n captureLogEvent,\n addExceptionMechanism,\n captureException,\n captureMessage,\n defineIntegration,\n isObjectLike,\n severityLevelFromString,\n withScope,\n} from '@sentry/core';\nimport { tracingChannel } from '../utils/diagnosticsChannel';\n\nconst SENTRY_TRACK_SYMBOL = Symbol('sentry-track-pino-logger');\n\ntype LevelMapping = {\n // Fortunately pino uses the same levels as Sentry\n labels: { [level: number]: LogSeverityLevel };\n};\n\ntype Pino = {\n [key: symbol]: unknown;\n levels: LevelMapping;\n [SENTRY_TRACK_SYMBOL]?: 'track' | 'ignore';\n};\n\n/**\n * Gets a custom Pino key from a logger instance by searching for the symbol.\n * Pino uses non-global symbols like Symbol('pino.messageKey'): https://github.com/pinojs/pino/blob/8a816c0b1f72de5ae9181f3bb402109b66f7d812/lib/symbols.js\n */\nfunction getPinoKey(logger: Pino, symbolName: string, defaultKey: string): string {\n const symbols = Object.getOwnPropertySymbols(logger);\n const symbolString = `Symbol(${symbolName})`;\n for (const sym of symbols) {\n if (sym.toString() === symbolString) {\n const value = logger[sym];\n return typeof value === 'string' ? value : defaultKey;\n }\n }\n return defaultKey;\n}\n\ntype MergeObject = {\n [key: string]: unknown;\n err?: Error;\n};\n\ntype PinoHookArgs = [MergeObject, string, number];\n\ntype PinoOptions = {\n /**\n * Automatically instrument all Pino loggers.\n *\n * When set to `false`, only loggers marked with `pinoIntegration.trackLogger(logger)` will be captured.\n *\n * @default true\n */\n autoInstrument: boolean;\n /**\n * Options to enable capturing of error events.\n */\n error: {\n /**\n * Levels that trigger capturing of events.\n *\n * @default []\n */\n levels: LogSeverityLevel[];\n /**\n * By default, Sentry will mark captured errors as handled.\n * Set this to `false` if you want to mark them as unhandled instead.\n *\n * @default true\n */\n handled: boolean;\n };\n /**\n * Options to enable capturing of logs.\n */\n log: {\n /**\n * Levels that trigger capturing of logs.\n *\n * @default [\"trace\", \"debug\", \"info\", \"warn\", \"error\", \"fatal\"]\n */\n levels: LogSeverityLevel[];\n };\n};\n\nconst DEFAULT_OPTIONS: PinoOptions = {\n autoInstrument: true,\n error: { levels: [], handled: true },\n log: { levels: ['trace', 'debug', 'info', 'warn', 'error', 'fatal'] },\n};\n\ntype DeepPartial<T> = {\n [P in keyof T]?: T[P] extends object ? Partial<T[P]> : T[P];\n};\n\ntype PinoResult = {\n level?: string;\n time?: string;\n pid?: number;\n hostname?: string;\n} & Record<string, unknown>;\n\nfunction stripIgnoredFields(result: PinoResult): PinoResult {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { level, time, pid, hostname, ...rest } = result;\n return rest;\n}\n\nconst _pinoIntegration = defineIntegration((userOptions: DeepPartial<PinoOptions> = {}) => {\n const options: PinoOptions = {\n autoInstrument: userOptions.autoInstrument !== false,\n error: { ...DEFAULT_OPTIONS.error, ...userOptions.error },\n log: { ...DEFAULT_OPTIONS.log, ...userOptions.log },\n };\n\n function shouldTrackLogger(logger: Pino): boolean {\n const override = logger[SENTRY_TRACK_SYMBOL];\n return override === 'track' || (override !== 'ignore' && options.autoInstrument);\n }\n\n return {\n name: 'Pino',\n setup: () => {\n const integratedChannel = tracingChannel('pino_asJson');\n\n function onPinoStart(self: Pino, args: PinoHookArgs, result: PinoResult): void {\n if (!shouldTrackLogger(self)) {\n return;\n }\n\n const resultObj = stripIgnoredFields(result);\n\n const [captureObj, message, levelNumber] = args;\n const level = self?.levels?.labels?.[levelNumber] || 'info';\n const messageKey = getPinoKey(self, 'pino.messageKey', 'msg');\n const logMessage = message || (resultObj?.[messageKey] as string | undefined) || '';\n\n if (options.log.levels.includes(level)) {\n const attributes: Record<string, unknown> = {\n ...resultObj,\n [SENTRY_ORIGIN]: 'auto.log.pino',\n 'pino.logger.level': levelNumber,\n };\n\n captureLogEvent({ level, message: logMessage, attributes });\n }\n\n if (options.error.levels.includes(level)) {\n const errorKey = getPinoKey(self, 'pino.errorKey', 'err');\n\n // Attach the log message and remaining log fields (e.g. child logger\n // bindings, merge object fields) to the event. The serialized error is\n // excluded since it is captured as the event exception itself.\n const pinoContext: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(resultObj)) {\n if (key !== errorKey && key !== messageKey) {\n pinoContext[key] = value;\n }\n }\n if (logMessage) {\n pinoContext[messageKey] = logMessage;\n }\n\n const captureContext = {\n level: severityLevelFromString(level),\n contexts: { pino: pinoContext },\n };\n\n withScope(scope => {\n scope.addEventProcessor(event => {\n event.logger = 'pino';\n\n addExceptionMechanism(event, {\n handled: options.error.handled,\n type: 'auto.log.pino',\n });\n\n return event;\n });\n\n const error = captureObj[errorKey];\n if (error) {\n captureException(error, captureContext);\n return;\n }\n\n captureMessage(logMessage, captureContext);\n });\n }\n }\n\n integratedChannel.end.subscribe(data => {\n const {\n instance,\n arguments: args,\n result,\n } = data as { instance: Pino; arguments: PinoHookArgs; result: string };\n onPinoStart(instance, args, JSON.parse(result));\n });\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Integration for Pino logging library.\n * Captures Pino logs as Sentry logs and optionally captures some log levels as events.\n *\n * By default, all Pino loggers will be captured. To ignore a specific logger, use `pinoIntegration.untrackLogger(logger)`.\n *\n * If you disable automatic instrumentation with `autoInstrument: false`, you can mark specific loggers to be tracked with `pinoIntegration.trackLogger(logger)`.\n *\n * Requires Pino >=v8.0.0\n */\nexport const pinoIntegration = Object.assign(_pinoIntegration, {\n trackLogger(logger: unknown): void {\n if (isObjectLike(logger) && 'levels' in logger) {\n (logger as Pino)[SENTRY_TRACK_SYMBOL] = 'track';\n }\n },\n untrackLogger(logger: unknown): void {\n if (isObjectLike(logger) && 'levels' in logger) {\n (logger as Pino)[SENTRY_TRACK_SYMBOL] = 'ignore';\n }\n },\n});\n"],"mappings":";;;;AAcA,MAAM,sBAAsB,OAAO,0BAA0B;;;;;AAiB7D,SAAS,WAAW,QAAc,YAAoB,YAA4B;CAChF,MAAM,UAAU,OAAO,sBAAsB,MAAM;CACnD,MAAM,eAAe,UAAU,WAAW;CAC1C,KAAK,MAAM,OAAO,SAChB,IAAI,IAAI,SAAS,MAAM,cAAc;EACnC,MAAM,QAAQ,OAAO;EACrB,OAAO,OAAO,UAAU,WAAW,QAAQ;CAC7C;CAEF,OAAO;AACT;AAiDA,MAAM,kBAA+B;CACnC,gBAAgB;CAChB,OAAO;EAAE,QAAQ,CAAC;EAAG,SAAS;CAAK;CACnC,KAAK,EAAE,QAAQ;EAAC;EAAS;EAAS;EAAQ;EAAQ;EAAS;CAAO,EAAE;AACtE;AAaA,SAAS,mBAAmB,QAAgC;CAE1D,MAAM,EAAE,OAAO,MAAM,KAAK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AS;MACjB,MAAM,mBAAkB,UAAS;OAC/B,MAAM,SAAS;OAEf,sBAAsB,OAAO;QAC3B,SAAS,QAAQ,MAAM;QACvB,MAAM;OACR,CAAC;OAED,OAAO;MACT,CAAC;MAED,MAAM,QAAQ,WAAW;MACzB,IAAI,OAAO;OACT,iBAAiB,OAAO,cAAc;OACtC;MACF;MAEA,eAAe,YAAY,cAAc;KAC3C,CAAC;IACH;GACF;GAEA,kBAAkB,IAAI,WAAU,SAAQ;IACtC,MAAM,EACJ,UACA,WAAW,MACX,WACE;IACJ,YAAY,UAAU,MAAM,KAAK,MAAM,MAAM,CAAC;GAChD,CAAC;EACH;CACF;AACF,CAAC;;;;;;;;;;;AAYD,MAAa,kBAAkB,OAAO,OAAO,kBAAkB;CAC7D,YAAY,QAAuB;EACjC,IAAI,aAAa,MAAM,KAAK,YAAY,QACrC,OAAgB,uBAAuB;CAE5C;CACA,cAAc,QAAuB;EACnC,IAAI,aAAa,MAAM,KAAK,YAAY,QACrC,OAAgB,uBAAuB;CAE5C;AACF,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tracing-helper.js","names":[],"sources":["../../../../src/integrations/prisma/tracing-helper.ts"],"sourcesContent":["/*\n * Copyright Prisma\n * SPDX-License-Identifier: Apache-2.0\n *\n * NOTICE from the Sentry authors:\n * - Vendored from: https://github.com/prisma/prisma/tree/b6feea5565ec577545a79547d24273ccdd11b4c7/packages/instrumentation\n * - Upstream version: @prisma/instrumentation@7.8.0\n * - Replaced `@prisma/instrumentation-contract` imports with local vendored types\n * - Span creation uses Sentry's span APIs (`startSpanManual` / `startInactiveSpan`) instead of the OTel tracer\n * - Span creation sets the Sentry origin, renames `db_query` spans to their SQL text, and backfills\n * the db system for older Prisma versions\n * - Added a `createEngineSpan` method so a single helper serves both Prisma v5 (which calls\n * `createEngineSpan`) and v6/v7 (which call `dispatchEngineSpans`)\n */\n\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport { debug, getActiveSpan, LRUMap, startInactiveSpan, startSpanManual } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type { EngineSpan, ExtendedSpanOptions, SpanCallback, TracingHelper } from './types';\nimport {\n DB_QUERY_SUMMARY,\n DB_QUERY_TEXT,\n DB_STATEMENT,\n DB_SYSTEM,\n DB_SYSTEM_NAME,\n SENTRY_KIND,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { getSqlQueryAttributes, getSqlSpanName, type SqlDialect, toSqlDialect } from '../../utils/sql';\n\n// Reading `process.env` can throw in runtimes that gate env access (e.g. Deno without `--allow-env`)\n// and `process` may be absent altogether (edge runtimes), so this degrades to `false` in those cases.\nconst showAllTraces = ((): boolean => {\n try {\n return process.env.PRISMA_SHOW_ALL_TRACES === 'true';\n } catch {\n return false;\n }\n})();\n\nconst nonSampledTraceParent = `00-10-10-00`;\n\nconst PRISMA_ORIGIN = 'auto.db.prisma';\n\ntype Options = {\n ignoreSpanTypes: (string | RegExp)[];\n};\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\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 * Older Prisma versions emit `prisma:engine:db_query` spans without a db system, so it's backfilled here.\n */\nfunction buildSpanAttributes(name: string, attributes: Record<string, unknown> | undefined): SpanAttributes {\n const spanAttributes: SpanAttributes = (attributes as SpanAttributes) || {};\n const statement = getSqlStatement(name, spanAttributes);\n const queryAttributes = getSqlQueryAttributes(statement, getSqlDialect(spanAttributes));\n\n const merged: SpanAttributes = {\n ...queryAttributes,\n ...spanAttributes,\n [SENTRY_ORIGIN]: PRISMA_ORIGIN,\n // Always ours, so the summary (and the streamed span name built from it) is dialect-aware and\n // consistent across Prisma versions, even if Prisma starts reporting its own.\n [DB_QUERY_SUMMARY]: queryAttributes[DB_QUERY_SUMMARY],\n };\n\n // Prisma itself emits the deprecated `db.system` on older versions, so both spellings are checked\n // before backfilling; the backfilled value goes on the stable one.\n // oxlint-disable-next-line typescript/no-deprecated\n if (name === 'prisma:engine:db_query' && merged[DB_SYSTEM] == null && merged[DB_SYSTEM_NAME] == null) {\n merged[DB_SYSTEM_NAME] = 'prisma';\n }\n\n // oxlint-disable-next-line typescript/no-deprecated\n if (merged[DB_SYSTEM] || merged[DB_SYSTEM_NAME]) {\n merged[SENTRY_OP] = 'db';\n }\n\n return merged;\n}\n\n/**\n * The dialect the reported SQL is written in. Prisma is multi-connector, and on MySQL a `\"...\"` run is\n * a string literal rather than a quoted identifier, so sanitizing it as standard SQL leaves the value\n * in place — and a literal containing `FROM`/`JOIN` then reads as a table name in the summary.\n */\nfunction getSqlDialect(attributes: SpanAttributes): SqlDialect {\n // oxlint-disable-next-line typescript/no-deprecated\n const system = attributes[DB_SYSTEM_NAME] ?? attributes[DB_SYSTEM];\n return toSqlDialect(system);\n}\n\n/**\n * The SQL a span reports, if any. Prisma emits it as the deprecated `db.statement` on older versions\n * and as `db.query.text` on the `db_query` spans of newer ones.\n */\nfunction getSqlStatement(name: string, attributes: SpanAttributes): string | undefined {\n // oxlint-disable-next-line typescript/no-deprecated\n const dbStatement = attributes[DB_STATEMENT];\n if (typeof dbStatement === 'string' && dbStatement) {\n return dbStatement;\n }\n const queryText = attributes[DB_QUERY_TEXT];\n if (isDbQuerySpan(name) && typeof queryText === 'string') {\n return queryText;\n }\n return undefined;\n}\n\n/**\n * Db query spans are named like every other SQL span (see `getSqlSpanName`), falling back to the\n * Prisma span name. v5/v6 emit `prisma:engine:db_query`; v7 inlined the engine and emits\n * `prisma:client:db_query`. Other Prisma spans keep their own name, even when they carry db attributes.\n */\nfunction buildSpanName(name: string, attributes: SpanAttributes): string {\n return isDbQuerySpan(name) ? getSqlSpanName(attributes, name) : name;\n}\n\nfunction isDbQuerySpan(name: string): boolean {\n return name === 'prisma:engine:db_query' || name === 'prisma:client:db_query';\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 here, 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 attributes = buildSpanAttributes(engineSpan.name, engineSpan.attributes);\n const span = startInactiveSpan({\n name: buildSpanName(engineSpan.name, attributes),\n attributes: {\n ...attributes,\n [SENTRY_KIND]: engineSpan.kind === 'client' ? 'client' : undefined,\n },\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\n/**\n * This satisifes the TracingHelper interface for Prisma v5 and v6/v7.\n */\nexport class ActiveTracingHelper implements TracingHelper {\n private ignoreSpanTypes: (string | RegExp)[];\n\n public constructor({ ignoreSpanTypes }: Options) {\n this.ignoreSpanTypes = ignoreSpanTypes;\n }\n\n public isEnabled(): boolean {\n return true;\n }\n\n public getTraceParent(span?: Span): string {\n const spanContext = (span ?? getActiveSpan())?.spanContext();\n if (spanContext) {\n return `00-${spanContext.traceId}-${spanContext.spanId}-0${spanContext.traceFlags}`;\n }\n return nonSampledTraceParent;\n }\n\n public dispatchEngineSpans(spans: EngineSpan[]): void {\n const linkIds = new Map<string, string>();\n const roots = spans.filter(span => span.parentId === null);\n\n for (const root of roots) {\n dispatchEngineSpan(root, spans, linkIds, this.ignoreSpanTypes);\n }\n }\n\n /**\n * Prisma v5 broke the tracing helper interface with the v6 major, replacing `createEngineSpan` with\n * `dispatchEngineSpans`. We implement the v6/v7 interface (`dispatchEngineSpans`) but also keep this\n * v5-only method so the same helper doesn't blow up in Prisma 5 users' faces, minting v5 engine spans\n * through Sentry's span APIs instead of crashing.\n */\n public createEngineSpan(engineSpanEvent: V5EngineSpanEvent): void {\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 public getActiveContext(): Span | undefined {\n return getActiveSpan();\n }\n\n public runInChildSpan<R>(nameOrOptions: string | ExtendedSpanOptions, callback: SpanCallback<R>): R {\n const options: ExtendedSpanOptions = typeof nameOrOptions === 'string' ? { name: nameOrOptions } : nameOrOptions;\n\n if (options.internal && !showAllTraces) {\n return callback();\n }\n\n const name = `prisma:client:${options.name}`;\n\n if (shouldIgnoreSpan(name, this.ignoreSpanTypes)) {\n return callback();\n }\n\n const parentSpan = getActiveSpan();\n\n const attributes = buildSpanAttributes(name, options.attributes);\n const spanOptions = {\n name: buildSpanName(name, attributes),\n attributes,\n kind: options.kind,\n links: options.links,\n startTime: options.startTime,\n parentSpan,\n };\n\n if (options.active === false) {\n const span = startInactiveSpan(spanOptions);\n // Register the client span so a v5 engine span (dispatched later, detached) can resolve it as a\n // parent by the Sentry span id Prisma reported via `getTraceParent` (see `createResolvedEngineSpans`).\n registerPrismaSpan(span.spanContext().spanId, span);\n return endSpan(span, () => callback(span, parentSpan));\n }\n\n return startSpanManual(spanOptions, span => {\n registerPrismaSpan(span.spanContext().spanId, span);\n return endSpan(span, () => callback(span, parentSpan));\n });\n }\n}\n\nfunction dispatchEngineSpan(\n engineSpan: EngineSpan,\n allSpans: EngineSpan[],\n linkIds: Map<string, string>,\n ignoreSpanTypes: (string | RegExp)[],\n): void {\n if (shouldIgnoreSpan(engineSpan.name, ignoreSpanTypes)) {\n return;\n }\n\n const attributes = buildSpanAttributes(engineSpan.name, engineSpan.attributes);\n\n startSpanManual(\n {\n name: buildSpanName(engineSpan.name, attributes),\n attributes: {\n ...attributes,\n [SENTRY_KIND]: engineSpan.kind === 'client' ? 'client' : undefined,\n },\n startTime: engineSpan.startTime,\n },\n span => {\n linkIds.set(engineSpan.id, span.spanContext().spanId);\n\n if (engineSpan.links) {\n span.addLinks(\n engineSpan.links.flatMap(link => {\n const linkedId = linkIds.get(link);\n if (!linkedId) {\n return [];\n }\n return {\n context: {\n spanId: linkedId,\n traceId: span.spanContext().traceId,\n traceFlags: span.spanContext().traceFlags,\n },\n };\n }),\n );\n }\n\n const children = allSpans.filter(s => s.parentId === engineSpan.id);\n for (const child of children) {\n dispatchEngineSpan(child, allSpans, linkIds, ignoreSpanTypes);\n }\n\n span.end(engineSpan.endTime);\n },\n );\n}\n\nfunction endSpan<T>(span: Span, run: () => T): T {\n let result: T;\n try {\n result = run();\n } catch (reason) {\n span.end();\n throw reason;\n }\n\n if (isPromiseLike(result)) {\n return result.then(\n value => {\n span.end();\n return value;\n },\n reason => {\n span.end();\n throw reason;\n },\n ) as T;\n }\n span.end();\n return result;\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return value != null && typeof (value as Record<string, unknown>)['then'] === 'function';\n}\n\n/** Whether `spanName` matches one of the configured `ignoreSpanTypes` patterns. */\nexport function shouldIgnoreSpan(spanName: string, ignoreSpanTypes: (string | RegExp)[]): boolean {\n return ignoreSpanTypes.some(pattern => (typeof pattern === 'string' ? pattern === spanName : pattern.test(spanName)));\n}\n"],"mappings":";;;;;AAiCA,MAAM,uBAAgC;CACpC,IAAI;EACF,OAAO,QAAQ,IAAI,2BAA2B;CAChD,QAAQ;EACN,OAAO;CACT;AACF,EAAA,CAAG;AAEH,MAAM,wBAAwB;AAE9B,MAAM,gBAAgB;AAkCtB,MAAM,2BAA2B;AACjC,MAAM,qBAAqB,IAAI,OAAqB,wBAAwB;AAC5E,MAAM,qBAAqC,CAAC;;AAG5C,SAAS,mBAAmB,IAAY,MAAkB;C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R,SAAS,KAAK,YAAY,CAAC,CAAC;IAC5B,YAAY,KAAK,YAAY,CAAC,CAAC;GACjC,EACF;EACF,CAAC,CACH;EAGF,MAAM,WAAW,SAAS,QAAO,MAAK,EAAE,aAAa,WAAW,EAAE;EAClE,KAAK,MAAM,SAAS,UAClB,mBAAmB,OAAO,UAAU,SAAS,eAAe;EAG9D,KAAK,IAAI,WAAW,OAAO;CAC7B,CACF;AACF;AAEA,SAAS,QAAW,MAAY,KAAiB;CAC/C,IAAI;CACJ,IAAI;EACF,SAAS,IAAI;CACf,SAAS,QAAQ;EACf,KAAK,IAAI;EACT,MAAM;CACR;CAEA,IAAI,cAAc,MAAM,GACtB,OAAO,OAAO,MACZ,UAAS;EACP,KAAK,IAAI;EACT,OAAO;CACT,IACA,WAAU;EACR,KAAK,IAAI;EACT,MAAM;CACR,CACF;CAEF,KAAK,IAAI;CACT,OAAO;AACT;AAEA,SAAS,cAAc,OAA+C;CACpE,OAAO,SAAS,QAAQ,OAAQ,MAAkC,YAAY;AAChF;;AAGA,SAAgB,iBAAiB,UAAkB,iBAA+C;CAChG,OAAO,gBAAgB,MAAK,YAAY,OAAO,YAAY,WAAW,YAAY,WAAW,QAAQ,KAAK,QAAQ,CAAE;AACtH"}
|
|
1
|
+
{"version":3,"file":"tracing-helper.js","names":[],"sources":["../../../../src/integrations/prisma/tracing-helper.ts"],"sourcesContent":["/*\n * Copyright Prisma\n * SPDX-License-Identifier: Apache-2.0\n *\n * NOTICE from the Sentry authors:\n * - Vendored from: https://github.com/prisma/prisma/tree/b6feea5565ec577545a79547d24273ccdd11b4c7/packages/instrumentation\n * - Upstream version: @prisma/instrumentation@7.8.0\n * - Replaced `@prisma/instrumentation-contract` imports with local vendored types\n * - Span creation uses Sentry's span APIs (`startSpanManual` / `startInactiveSpan`) instead of the OTel tracer\n * - Span creation sets the Sentry origin, renames `db_query` spans to their SQL text, and backfills\n * the db system for older Prisma versions\n * - Added a `createEngineSpan` method so a single helper serves both Prisma v5 (which calls\n * `createEngineSpan`) and v6/v7 (which call `dispatchEngineSpans`)\n */\n\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport { debug, getActiveSpan, LRUMap, startInactiveSpan, startSpanManual } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type { EngineSpan, ExtendedSpanOptions, SpanCallback, TracingHelper } from './types';\nimport {\n DB_QUERY_SUMMARY,\n DB_QUERY_TEXT,\n DB_STATEMENT,\n DB_SYSTEM,\n DB_SYSTEM_NAME,\n SENTRY_KIND,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { getSqlQueryAttributes, getSqlSpanName, type SqlDialect, toSqlDialect } from '../../utils/sql';\n\n// Reading `process.env` can throw in runtimes that gate env access (e.g. Deno without `--allow-env`)\n// and `process` may be absent altogether (edge runtimes), so this degrades to `false` in those cases.\nconst showAllTraces = ((): boolean => {\n try {\n return process.env.PRISMA_SHOW_ALL_TRACES === 'true';\n } catch {\n return false;\n }\n})();\n\nconst nonSampledTraceParent = `00-10-10-00`;\n\nconst PRISMA_ORIGIN = 'auto.db.prisma';\n\ntype Options = {\n ignoreSpanTypes: (string | RegExp)[];\n};\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\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 * Older Prisma versions emit `prisma:engine:db_query` spans without a db system, so it's backfilled here.\n */\nfunction buildSpanAttributes(name: string, attributes: Record<string, unknown> | undefined): SpanAttributes {\n const spanAttributes: SpanAttributes = (attributes as SpanAttributes) || {};\n const statement = getSqlStatement(name, spanAttributes);\n const queryAttributes = getSqlQueryAttributes(statement, getSqlDialect(spanAttributes));\n\n const merged: SpanAttributes = {\n ...queryAttributes,\n ...spanAttributes,\n [SENTRY_ORIGIN]: PRISMA_ORIGIN,\n // Always ours, so the summary (and the streamed span name built from it) is dialect-aware and\n // consistent across Prisma versions, even if Prisma starts reporting its own.\n [DB_QUERY_SUMMARY]: queryAttributes[DB_QUERY_SUMMARY],\n };\n\n // Prisma itself emits the deprecated `db.system` on older versions, so both spellings are checked\n // before backfilling; the backfilled value goes on the stable one.\n // oxlint-disable-next-line typescript/no-deprecated\n if (name === 'prisma:engine:db_query' && merged[DB_SYSTEM] == null && merged[DB_SYSTEM_NAME] == null) {\n merged[DB_SYSTEM_NAME] = 'prisma';\n }\n\n // oxlint-disable-next-line typescript/no-deprecated\n if (merged[DB_SYSTEM] || merged[DB_SYSTEM_NAME]) {\n merged[SENTRY_OP] = 'db';\n }\n\n return merged;\n}\n\n/**\n * The dialect the reported SQL is written in. Prisma is multi-connector, and on MySQL a `\"...\"` run is\n * a string literal rather than a quoted identifier, so sanitizing it as standard SQL leaves the value\n * in place — and a literal containing `FROM`/`JOIN` then reads as a table name in the summary.\n */\nfunction getSqlDialect(attributes: SpanAttributes): SqlDialect {\n // oxlint-disable-next-line typescript/no-deprecated\n const system = attributes[DB_SYSTEM_NAME] ?? attributes[DB_SYSTEM];\n return toSqlDialect(system);\n}\n\n/**\n * The SQL a span reports, if any. Prisma emits it as the deprecated `db.statement` on older versions\n * and as `db.query.text` on the `db_query` spans of newer ones.\n */\nfunction getSqlStatement(name: string, attributes: SpanAttributes): string | undefined {\n // oxlint-disable-next-line typescript/no-deprecated\n const dbStatement = attributes[DB_STATEMENT];\n if (typeof dbStatement === 'string' && dbStatement) {\n return dbStatement;\n }\n const queryText = attributes[DB_QUERY_TEXT];\n if (isDbQuerySpan(name) && typeof queryText === 'string') {\n return queryText;\n }\n return undefined;\n}\n\n/**\n * Db query spans are named like every other SQL span (see `getSqlSpanName`), falling back to the\n * Prisma span name. v5/v6 emit `prisma:engine:db_query`; v7 inlined the engine and emits\n * `prisma:client:db_query`. Other Prisma spans keep their own name, even when they carry db attributes.\n */\nfunction buildSpanName(name: string, attributes: SpanAttributes): string {\n return isDbQuerySpan(name) ? getSqlSpanName(attributes, name) : name;\n}\n\nfunction isDbQuerySpan(name: string): boolean {\n return name === 'prisma:engine:db_query' || name === 'prisma:client:db_query';\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 here, 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 // oxlint-disable-next-line typescript/no-non-null-assertion -- `i` is bounded by the loop\n const engineSpan = pendingEngineSpans[i]!;\n const parentSpan = prismaSpanRegistry.get(engineSpan.parent_span_id);\n if (!parentSpan) {\n continue;\n }\n\n const attributes = buildSpanAttributes(engineSpan.name, engineSpan.attributes);\n const span = startInactiveSpan({\n name: buildSpanName(engineSpan.name, attributes),\n attributes: {\n ...attributes,\n [SENTRY_KIND]: engineSpan.kind === 'client' ? 'client' : undefined,\n },\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\n/**\n * This satisifes the TracingHelper interface for Prisma v5 and v6/v7.\n */\nexport class ActiveTracingHelper implements TracingHelper {\n private ignoreSpanTypes: (string | RegExp)[];\n\n public constructor({ ignoreSpanTypes }: Options) {\n this.ignoreSpanTypes = ignoreSpanTypes;\n }\n\n public isEnabled(): boolean {\n return true;\n }\n\n public getTraceParent(span?: Span): string {\n const spanContext = (span ?? getActiveSpan())?.spanContext();\n if (spanContext) {\n return `00-${spanContext.traceId}-${spanContext.spanId}-0${spanContext.traceFlags}`;\n }\n return nonSampledTraceParent;\n }\n\n public dispatchEngineSpans(spans: EngineSpan[]): void {\n const linkIds = new Map<string, string>();\n const roots = spans.filter(span => span.parentId === null);\n\n for (const root of roots) {\n dispatchEngineSpan(root, spans, linkIds, this.ignoreSpanTypes);\n }\n }\n\n /**\n * Prisma v5 broke the tracing helper interface with the v6 major, replacing `createEngineSpan` with\n * `dispatchEngineSpans`. We implement the v6/v7 interface (`dispatchEngineSpans`) but also keep this\n * v5-only method so the same helper doesn't blow up in Prisma 5 users' faces, minting v5 engine spans\n * through Sentry's span APIs instead of crashing.\n */\n public createEngineSpan(engineSpanEvent: V5EngineSpanEvent): void {\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 public getActiveContext(): Span | undefined {\n return getActiveSpan();\n }\n\n public runInChildSpan<R>(nameOrOptions: string | ExtendedSpanOptions, callback: SpanCallback<R>): R {\n const options: ExtendedSpanOptions = typeof nameOrOptions === 'string' ? { name: nameOrOptions } : nameOrOptions;\n\n if (options.internal && !showAllTraces) {\n return callback();\n }\n\n const name = `prisma:client:${options.name}`;\n\n if (shouldIgnoreSpan(name, this.ignoreSpanTypes)) {\n return callback();\n }\n\n const parentSpan = getActiveSpan();\n\n const attributes = buildSpanAttributes(name, options.attributes);\n const spanOptions = {\n name: buildSpanName(name, attributes),\n attributes,\n kind: options.kind,\n links: options.links,\n startTime: options.startTime,\n parentSpan,\n };\n\n if (options.active === false) {\n const span = startInactiveSpan(spanOptions);\n // Register the client span so a v5 engine span (dispatched later, detached) can resolve it as a\n // parent by the Sentry span id Prisma reported via `getTraceParent` (see `createResolvedEngineSpans`).\n registerPrismaSpan(span.spanContext().spanId, span);\n return endSpan(span, () => callback(span, parentSpan));\n }\n\n return startSpanManual(spanOptions, span => {\n registerPrismaSpan(span.spanContext().spanId, span);\n return endSpan(span, () => callback(span, parentSpan));\n });\n }\n}\n\nfunction dispatchEngineSpan(\n engineSpan: EngineSpan,\n allSpans: EngineSpan[],\n linkIds: Map<string, string>,\n ignoreSpanTypes: (string | RegExp)[],\n): void {\n if (shouldIgnoreSpan(engineSpan.name, ignoreSpanTypes)) {\n return;\n }\n\n const attributes = buildSpanAttributes(engineSpan.name, engineSpan.attributes);\n\n startSpanManual(\n {\n name: buildSpanName(engineSpan.name, attributes),\n attributes: {\n ...attributes,\n [SENTRY_KIND]: engineSpan.kind === 'client' ? 'client' : undefined,\n },\n startTime: engineSpan.startTime,\n },\n span => {\n linkIds.set(engineSpan.id, span.spanContext().spanId);\n\n if (engineSpan.links) {\n span.addLinks(\n engineSpan.links.flatMap(link => {\n const linkedId = linkIds.get(link);\n if (!linkedId) {\n return [];\n }\n return {\n context: {\n spanId: linkedId,\n traceId: span.spanContext().traceId,\n traceFlags: span.spanContext().traceFlags,\n },\n };\n }),\n );\n }\n\n const children = allSpans.filter(s => s.parentId === engineSpan.id);\n for (const child of children) {\n dispatchEngineSpan(child, allSpans, linkIds, ignoreSpanTypes);\n }\n\n span.end(engineSpan.endTime);\n },\n );\n}\n\nfunction endSpan<T>(span: Span, run: () => T): T {\n let result: T;\n try {\n result = run();\n } catch (reason) {\n span.end();\n throw reason;\n }\n\n if (isPromiseLike(result)) {\n return result.then(\n value => {\n span.end();\n return value;\n },\n reason => {\n span.end();\n throw reason;\n },\n ) as T;\n }\n span.end();\n return result;\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return value != null && typeof (value as Record<string, unknown>)['then'] === 'function';\n}\n\n/** Whether `spanName` matches one of the configured `ignoreSpanTypes` patterns. */\nexport function shouldIgnoreSpan(spanName: string, ignoreSpanTypes: (string | RegExp)[]): boolean {\n return ignoreSpanTypes.some(pattern => (typeof pattern === 'string' ? pattern === spanName : pattern.test(spanName)));\n}\n"],"mappings":";;;;;AAiCA,MAAM,uBAAgC;CACpC,IAAI;EACF,OAAO,QAAQ,IAAI,2BAA2B;CAChD,QAAQ;EACN,OAAO;CACT;AACF,EAAA,CAAG;AAEH,MAAM,wBAAwB;AAE9B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AAK,SACH,WAAW,MAAM,SAAQ,SAAQ;GAC/B,MAAM,WAAW,QAAQ,IAAI,IAAI;GACjC,IAAI,CAAC,UACH,OAAO,CAAC;GAEV,OAAO,EACL,SAAS;IACP,QAAQ;IACR,SAAS,KAAK,YAAY,CAAC,CAAC;IAC5B,YAAY,KAAK,YAAY,CAAC,CAAC;GACjC,EACF;EACF,CAAC,CACH;EAGF,MAAM,WAAW,SAAS,QAAO,MAAK,EAAE,aAAa,WAAW,EAAE;EAClE,KAAK,MAAM,SAAS,UAClB,mBAAmB,OAAO,UAAU,SAAS,eAAe;EAG9D,KAAK,IAAI,WAAW,OAAO;CAC7B,CACF;AACF;AAEA,SAAS,QAAW,MAAY,KAAiB;CAC/C,IAAI;CACJ,IAAI;EACF,SAAS,IAAI;CACf,SAAS,QAAQ;EACf,KAAK,IAAI;EACT,MAAM;CACR;CAEA,IAAI,cAAc,MAAM,GACtB,OAAO,OAAO,MACZ,UAAS;EACP,KAAK,IAAI;EACT,OAAO;CACT,IACA,WAAU;EACR,KAAK,IAAI;EACT,MAAM;CACR,CACF;CAEF,KAAK,IAAI;CACT,OAAO;AACT;AAEA,SAAS,cAAc,OAA+C;CACpE,OAAO,SAAS,QAAQ,OAAQ,MAAkC,YAAY;AAChF;;AAGA,SAAgB,iBAAiB,UAAkB,iBAA+C;CAChG,OAAO,gBAAgB,MAAK,YAAY,OAAO,YAAY,WAAW,YAAY,WAAW,QAAQ,KAAK,QAAQ,CAAE;AACtH"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { subscribe } from "../utils/diagnosticsChannel.js";
|
|
2
2
|
import { instrumentTunnelServer } from "../utils/tunnelServer.js";
|
|
3
3
|
import { defineIntegration } from "@sentry/core";
|
|
4
|
-
import { HTTP_ON_SERVER_REQUEST,
|
|
4
|
+
import { HTTP_ON_SERVER_REQUEST, handleServedNodeTunnelRequest, serveTunnelIntegration, setNodeTunnelHandler } from "@sentry/core/server";
|
|
5
5
|
// src/integrations/serveTunnel.ts
|
|
6
6
|
let isSubscribed = false;
|
|
7
7
|
/**
|
|
@@ -11,7 +11,7 @@ let isSubscribed = false;
|
|
|
11
11
|
function instrumentTunnelServers() {
|
|
12
12
|
if (isSubscribed) return;
|
|
13
13
|
isSubscribed = true;
|
|
14
|
-
|
|
14
|
+
setNodeTunnelHandler(handleServedNodeTunnelRequest);
|
|
15
15
|
subscribe(HTTP_ON_SERVER_REQUEST, instrumentTunnelServer);
|
|
16
16
|
}
|
|
17
17
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"serveTunnel.js","names":["
|
|
1
|
+
{"version":3,"file":"serveTunnel.js","names":["coreServeTunnelIntegration"],"sources":["../../../src/integrations/serveTunnel.ts"],"sourcesContent":["import type { ServerTunnelOptions } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport {\n handleServedNodeTunnelRequest,\n setNodeTunnelHandler,\n HTTP_ON_SERVER_REQUEST,\n serveTunnelIntegration as coreServeTunnelIntegration,\n} from '@sentry/core/server';\nimport { subscribe } from '../utils/diagnosticsChannel';\nimport { instrumentTunnelServer } from '../utils/tunnelServer';\n\nlet isSubscribed = false;\n\n/**\n * Lets every `node:http` server answer managed tunnel requests before the app sees them, whatever framework runs on\n * it. Nothing is answered unless the tunnel is on, through `serveTunnelIntegration` or a framework SDK.\n */\nexport function instrumentTunnelServers(): void {\n if (isSubscribed) {\n return;\n }\n\n isSubscribed = true;\n // Core's HTTP server instrumentation answers tunnel requests through it, without bundling it for apps that have no\n // tunnel.\n setNodeTunnelHandler(handleServedNodeTunnelRequest);\n subscribe(HTTP_ON_SERVER_REQUEST, instrumentTunnelServer);\n}\n\n/**\n * Makes a `serveTunnelIntegration` that, unless `intercept` is off, also runs `instrumentRuntimeServers` to answer\n * tunnel requests on the runtime's own servers, like `Bun.serve` or `Deno.serve`.\n */\nexport function makeServeTunnelIntegration(instrumentRuntimeServers?: () => void) {\n return defineIntegration((options: ServerTunnelOptions = {}) => {\n return {\n ...coreServeTunnelIntegration(options),\n setupOnce() {\n if (options.intercept !== false) {\n instrumentTunnelServers();\n instrumentRuntimeServers?.();\n }\n },\n };\n });\n}\n"],"mappings":";;;;;AAWA,IAAI,eAAe;;;;;AAMnB,SAAgB,0BAAgC;CAC9C,IAAI,cACF;CAGF,eAAe;CAGf,qBAAqB,6BAA6B;CAClD,UAAU,wBAAwB,sBAAsB;AAC1D;;;;;AAMA,SAAgB,2BAA2B,0BAAuC;CAChF,OAAO,mBAAmB,UAA+B,CAAC,MAAM;EAC9D,OAAO;GACL,GAAGA,uBAA2B,OAAO;GACrC,YAAY;IACV,IAAI,QAAQ,cAAc,OAAO;KAC/B,wBAAwB;KACxB,2BAA2B;IAC7B;GACF;EACF;CACF,CAAC;AACH"}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { mapObjectValues } from "./util.js";
|
|
2
|
+
import { isObjectLike, stringify } from "@sentry/core";
|
|
3
|
+
// src/integrations/vercel-ai/extract.ts
|
|
4
|
+
/** Maps the AI SDK `experimental_extract` input and output to the Clairic shape of the `gen_ai.extract` schemas. */
|
|
5
|
+
/**
|
|
6
|
+
* Joins the text of the AI SDK state parts into one Clairic `state` string. The gateway does this join on
|
|
7
|
+
* the server and does not show its separator, so this one is our choice. It only makes the recorded text
|
|
8
|
+
* easier to read: the answer spans stay correct with any separator, because we add each part's offset.
|
|
9
|
+
*/
|
|
10
|
+
const EXTRACT_STATE_SEPARATOR = "\n\n";
|
|
11
|
+
const BLOB_SUBSTITUTE = "[Blob substitute]";
|
|
12
|
+
/**
|
|
13
|
+
* Clairic takes the text as one `state` string, with images and PDF documents in their own arrays. The AI SDK
|
|
14
|
+
* also takes a JSON object, or an array of text, JSON and file parts. Join the text of the parts and keep the
|
|
15
|
+
* offset of each part, so that the answer spans point into the joined `state`.
|
|
16
|
+
*/
|
|
17
|
+
function toExtractState(state) {
|
|
18
|
+
const images = [];
|
|
19
|
+
const documents = [];
|
|
20
|
+
let joined = "";
|
|
21
|
+
const parts = (Array.isArray(state) ? state : [{
|
|
22
|
+
type: "json",
|
|
23
|
+
value: state
|
|
24
|
+
}]).map((part) => {
|
|
25
|
+
if (!isObjectLike(part)) return;
|
|
26
|
+
if (part.type === "file") {
|
|
27
|
+
if (String(part.mediaType).split("/")[0] === "image") {
|
|
28
|
+
images.push(BLOB_SUBSTITUTE);
|
|
29
|
+
return "image";
|
|
30
|
+
}
|
|
31
|
+
if (part.mediaType === "application/pdf") documents.push(BLOB_SUBSTITUTE);
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
const text = part.type === "text" ? part.text : stringify(part.value);
|
|
35
|
+
if (typeof text !== "string") return;
|
|
36
|
+
joined += EXTRACT_STATE_SEPARATOR + text;
|
|
37
|
+
return joined.length - text.length - 2;
|
|
38
|
+
});
|
|
39
|
+
return {
|
|
40
|
+
request: {
|
|
41
|
+
state: joined ? joined.slice(2) : void 0,
|
|
42
|
+
images: images.length ? images : void 0,
|
|
43
|
+
documents: documents.length ? documents : void 0
|
|
44
|
+
},
|
|
45
|
+
parts
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* The AI SDK also takes JSON or `null` as field `instructions`, but the schema allows only a string.
|
|
50
|
+
*/
|
|
51
|
+
function toExtractFields(fields) {
|
|
52
|
+
return isObjectLike(fields) ? mapObjectValues(fields, (field) => ({
|
|
53
|
+
...field,
|
|
54
|
+
instructions: field.instructions === null ? void 0 : stringify(field.instructions)
|
|
55
|
+
})) : fields;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* The AI SDK normalizes the provider's extraction answers. Map them back to the provider shape of
|
|
59
|
+
* `gen_ai.output.messages` on `gen_ai.extract` spans. The AI SDK does not expose `truncated`.
|
|
60
|
+
*/
|
|
61
|
+
function toExtractAnswers(answers, parts) {
|
|
62
|
+
return mapObjectValues(answers, ({ pNull, source, items, ...rest }) => {
|
|
63
|
+
const mapped = {
|
|
64
|
+
...rest,
|
|
65
|
+
p_null: pNull
|
|
66
|
+
};
|
|
67
|
+
const span = toExtractSpan(source, parts);
|
|
68
|
+
if (span) {
|
|
69
|
+
mapped.source = "input";
|
|
70
|
+
mapped.span = span;
|
|
71
|
+
} else if (isObjectLike(source) && parts[Number(source.part)] === "image") mapped.source = "image";
|
|
72
|
+
if (Array.isArray(items)) {
|
|
73
|
+
const confidences = items.map((item) => isObjectLike(item) ? item.confidence : void 0);
|
|
74
|
+
if (confidences.every((confidence) => typeof confidence === "number")) mapped.confidences = confidences;
|
|
75
|
+
const spans = items.map((item) => toExtractSpan(isObjectLike(item) ? item.source : void 0, parts));
|
|
76
|
+
if (spans.some(Boolean)) mapped.spans = spans;
|
|
77
|
+
}
|
|
78
|
+
return mapped;
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
function toExtractSpan(source, parts) {
|
|
82
|
+
if (!isObjectLike(source) || source.type !== "text") return null;
|
|
83
|
+
const offset = parts[Number(source.part)];
|
|
84
|
+
return typeof offset === "number" ? [offset + Number(source.start), offset + Number(source.end)] : null;
|
|
85
|
+
}
|
|
86
|
+
export { toExtractAnswers, toExtractFields, toExtractState };
|
|
87
|
+
|
|
88
|
+
//# sourceMappingURL=extract.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"extract.js","names":[],"sources":["../../../../src/integrations/vercel-ai/extract.ts"],"sourcesContent":["/** Maps the AI SDK `experimental_extract` input and output to the Clairic shape of the `gen_ai.extract` schemas. */\n\nimport { isObjectLike, stringify } from '@sentry/core';\nimport { mapObjectValues } from './util';\n\n/**\n * Joins the text of the AI SDK state parts into one Clairic `state` string. The gateway does this join on\n * the server and does not show its separator, so this one is our choice. It only makes the recorded text\n * easier to read: the answer spans stay correct with any separator, because we add each part's offset.\n */\nconst EXTRACT_STATE_SEPARATOR = '\\n\\n';\nconst BLOB_SUBSTITUTE = '[Blob substitute]';\n\ninterface ExtractState {\n request: { state?: string; images?: string[]; documents?: string[] };\n /** For each AI SDK state part, the offset of its text in `request.state`, or `'image'` for an image part. */\n parts: (number | 'image' | undefined)[];\n}\n\n/**\n * Clairic takes the text as one `state` string, with images and PDF documents in their own arrays. The AI SDK\n * also takes a JSON object, or an array of text, JSON and file parts. Join the text of the parts and keep the\n * offset of each part, so that the answer spans point into the joined `state`.\n */\nexport function toExtractState(state: unknown): ExtractState {\n const images: string[] = [];\n const documents: string[] = [];\n // Each text gets a separator in front, which is cut off from the start of `state` at the end.\n let joined = '';\n\n const parts = (Array.isArray(state) ? state : [{ type: 'json', value: state }]).map(part => {\n if (!isObjectLike(part)) {\n return undefined;\n }\n if (part.type === 'file') {\n if (String(part.mediaType).split('/')[0] === 'image') {\n images.push(BLOB_SUBSTITUTE);\n return 'image' as const;\n }\n if (part.mediaType === 'application/pdf') {\n documents.push(BLOB_SUBSTITUTE);\n }\n return undefined;\n }\n const text = part.type === 'text' ? part.text : stringify(part.value);\n if (typeof text !== 'string') {\n return undefined;\n }\n joined += EXTRACT_STATE_SEPARATOR + text;\n return joined.length - text.length - EXTRACT_STATE_SEPARATOR.length;\n });\n\n return {\n request: {\n state: joined ? joined.slice(EXTRACT_STATE_SEPARATOR.length) : undefined,\n images: images.length ? images : undefined,\n documents: documents.length ? documents : undefined,\n },\n parts,\n };\n}\n\n/**\n * The AI SDK also takes JSON or `null` as field `instructions`, but the schema allows only a string.\n */\nexport function toExtractFields(fields: unknown): unknown {\n return isObjectLike(fields)\n ? mapObjectValues(fields, field => ({\n ...field,\n instructions: field.instructions === null ? undefined : stringify(field.instructions),\n }))\n : fields;\n}\n\n/**\n * The AI SDK normalizes the provider's extraction answers. Map them back to the provider shape of\n * `gen_ai.output.messages` on `gen_ai.extract` spans. The AI SDK does not expose `truncated`.\n */\nexport function toExtractAnswers(\n answers: Record<string, unknown>,\n parts: ExtractState['parts'],\n): Record<string, unknown> {\n return mapObjectValues(answers, ({ pNull, source, items, ...rest }) => {\n const mapped: Record<string, unknown> = { ...rest, p_null: pNull };\n const span = toExtractSpan(source, parts);\n if (span) {\n mapped.source = 'input';\n mapped.span = span;\n } else if (isObjectLike(source) && parts[Number(source.part)] === 'image') {\n mapped.source = 'image';\n }\n if (Array.isArray(items)) {\n const confidences = items.map(item => (isObjectLike(item) ? item.confidence : undefined));\n if (confidences.every(confidence => typeof confidence === 'number')) {\n mapped.confidences = confidences;\n }\n const spans = items.map(item => toExtractSpan(isObjectLike(item) ? item.source : undefined, parts));\n if (spans.some(Boolean)) {\n mapped.spans = spans;\n }\n }\n return mapped;\n });\n}\n\nfunction toExtractSpan(source: unknown, parts: ExtractState['parts']): [number, number] | null {\n if (!isObjectLike(source) || source.type !== 'text') {\n return null;\n }\n const offset = parts[Number(source.part)];\n return typeof offset === 'number' ? [offset + Number(source.start), offset + Number(source.end)] : null;\n}\n"],"mappings":";;;;;;;;;AAUA,MAAM,0BAA0B;AAChC,MAAM,kBAAkB;;;;;;AAaxB,SAAgB,eAAe,OAA8B;CAC3D,MAAM,SAAmB,CAAC;CAC1B,MAAM,YAAsB,CAAC;CAE7B,IAAI,SAAS;CAEb,MAAM,SAAS,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC;EAAE,MAAM;EAAQ,OAAO;CAAM,CAAC,EAAA,CAAG,KAAI,SAAQ;EAC1F,IAAI,CAAC,aAAa,IAAI,GACpB;EAEF,IAAI,KAAK,SAAS,QAAQ;GACxB,IAAI,OAAO,KAAK,SAAS,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,OAAO,SAAS;IACpD,OAAO,KAAK,eAAe;IAC3B,OAAO;GACT;GACA,IAAI,KAAK,cAAc,mBACrB,UAAU,KAAK,eAAe;GAEhC;EACF;EACA,MAAM,OAAO,KAAK,SAAS,SAAS,KAAK,OAAO,UAAU,KAAK,KAAK;EACpE,IAAI,OAAO,SAAS,UAClB;EAEF,UAAU,0BAA0B;EACpC,OAAO,OAAO,SAAS,KAAK,SAAS;CACvC,CAAC;CAED,OAAO;EACL,SAAS;GACP,OAAO,SAAS,OAAO,MAAM,CAA8B,IAA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6 +93,10 @@ function accumulateChunk(state, chunk) {
|
|
|
93
93
|
default: return;
|
|
94
94
|
}
|
|
95
95
|
}
|
|
96
|
-
|
|
96
|
+
/** Maps each object value of `record` and keeps the other values as they are. */
|
|
97
|
+
function mapObjectValues(record, fn) {
|
|
98
|
+
return Object.fromEntries(Object.entries(record).map(([key, value]) => [key, isObjectLike(value) ? fn(value, key) : value]));
|
|
99
|
+
}
|
|
100
|
+
export { asNumber, asString, isReadableStream, mapObjectValues, sum, tapModelCallStream };
|
|
97
101
|
|
|
98
102
|
//# sourceMappingURL=util.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"util.js","names":[],"sources":["../../../../src/integrations/vercel-ai/util.ts"],"sourcesContent":["/** Shared, state-free helpers for the Vercel AI (`ai`) channel subscribers, plus the streamed model-call tap. */\n\nimport type { Span } from '@sentry/core';\nimport { isObjectLike } from '@sentry/core';\nimport { recordTimeToFirstChunk } from '../../ai/core/time-to-first-chunk';\n\n/** Narrow to a string, or `undefined` for anything else. */\nexport function asString(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\n/** Narrow to a finite number, or `undefined` for anything else (including `NaN`). */\nexport function asNumber(value: unknown): number | undefined {\n return typeof value === 'number' && !isNaN(value) ? value : undefined;\n}\n\n/** Add two optional numbers, treating a missing operand as `0` but returning `undefined` when both are absent. */\nexport function sum(a: number | undefined, b: number | undefined): number | undefined {\n return a === undefined && b === undefined ? undefined : (a ?? 0) + (b ?? 0);\n}\n\n/*\n * Streaming support for the `ai:telemetry` tracing channel.\n *\n * For a streamed model call (`doStream`) the SDK resolves the `languageModelCall` channel promise as\n * soon as it hands back the *unconsumed* stream — so `result.stream` is a `ReadableStream` and the\n * final usage / finish reason / output only arrive later, as the stream is drained (they ride the\n * stream's own `finish`/`text-delta`/`tool-call` chunks, never the channel context). The SDK\n * deliberately leaves `result` undefined on the `streamText`/`step` contexts and exposes the stream\n * only on the model call, expecting consumers to tap it themselves.\n * @see https://github.com/vercel/ai/pull/15660 (discussion: \"tee off and aggregate ourselves\")\n *\n * We replace `result.stream` with a passthrough that forwards every chunk untouched (so the SDK's own\n * consumption is unaffected) while accumulating the data we need, then hand the aggregate back once the\n * stream settles so the model-call span can be enriched and ended out-of-band.\n */\n\n/** The subset of a streamed provider chunk we read. Unknown chunk types are forwarded and ignored. */\ninterface StreamChunk {\n type?: unknown;\n delta?: unknown;\n // v4 text-delta chunks carry the text on `textDelta`; v5+ uses `delta`.\n textDelta?: unknown;\n id?: unknown;\n modelId?: unknown;\n toolCallId?: unknown;\n toolName?: unknown;\n input?: unknown;\n args?: unknown;\n finishReason?: unknown;\n usage?: unknown;\n providerMetadata?: unknown;\n error?: unknown;\n}\n\n/** The aggregate handed back once a streamed model call finishes, in the shape `enrichSpanOnEnd` expects. */\nexport interface StreamedModelCallResult {\n text?: string;\n toolCalls: Array<Record<string, unknown>>;\n usage?: unknown;\n finishReason?: unknown;\n responseId?: string;\n responseModel?: string;\n providerMetadata?: unknown;\n}\n\n/** The streamed model call exposes a web `ReadableStream` on `result.stream`. */\nexport { isReadableStream } from '../../ai/core/utils';\n\n/**\n * Wrap a streamed model call's `ReadableStream` so its chunks are observed as the SDK consumes them,\n * without altering what the SDK sees. Returns a replacement stream to swap onto `result.stream`.\n *\n * `onFinal` runs exactly once when the stream drains cleanly; `onError` runs exactly once if it errors\n * or is cancelled. Reading one source chunk per `pull` preserves the SDK's backpressure. The\n * `try/catch` around every read guarantees the owning span is always ended — a leaked open span on a\n * mid-stream failure would be worse than a slightly-less-enriched one.\n */\nexport function tapModelCallStream(\n span: Span,\n stream: ReadableStream<unknown>,\n onFinal: (result: StreamedModelCallResult) => void,\n onError: (error: unknown) => void,\n): ReadableStream<unknown> {\n const reader = stream.getReader();\n const state: StreamedModelCallResult = { toolCalls: [] };\n let text = '';\n let settled = false;\n\n const finalize = (): void => {\n if (settled) {\n return;\n }\n settled = true;\n if (text) {\n state.text = text;\n }\n onFinal(state);\n };\n\n const fail = (error: unknown): void => {\n if (settled) {\n return;\n }\n settled = true;\n onError(error);\n };\n\n return new ReadableStream<unknown>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n finalize();\n controller.close();\n\n return;\n }\n // The model emits `stream-start` before the response arrives.\n if ((value as StreamChunk | undefined)?.type !== 'stream-start') {\n recordTimeToFirstChunk(span);\n }\n text += accumulateChunk(state, value) ?? '';\n controller.enqueue(value);\n } catch (error) {\n fail(error);\n controller.error(error);\n }\n },\n cancel(reason) {\n // Consumer stopped reading early (e.g. a `break` out of `for await`); close out the span with\n // whatever we have rather than leave it open. A non-error reason is a deliberate stop, not a failure.\n finalize();\n\n return reader.cancel(reason);\n },\n });\n}\n\n/**\n * Fold a single streamed chunk into the running aggregate. Returns any text delta so the caller can\n * accumulate it (kept out of `state` until the end to avoid re-joining on every chunk).\n */\nfunction accumulateChunk(state: StreamedModelCallResult, chunk: unknown): string | undefined {\n if (!isObjectLike(chunk)) {\n return undefined;\n }\n const {\n type,\n delta,\n textDelta,\n id,\n modelId,\n toolCallId,\n toolName,\n input,\n args,\n finishReason,\n usage,\n providerMetadata,\n } = chunk as StreamChunk;\n\n switch (type) {\n case 'text-delta': {\n const textChunk = delta ?? textDelta;\n return typeof textChunk === 'string' ? textChunk : undefined;\n }\n case 'tool-call':\n state.toolCalls.push({ toolCallId, toolName, input: input ?? args });\n\n return undefined;\n case 'response-metadata':\n if (typeof id === 'string') {\n state.responseId = id;\n }\n if (typeof modelId === 'string') {\n state.responseModel = modelId;\n }\n\n return undefined;\n case 'finish':\n state.finishReason = finishReason;\n state.usage = usage;\n if (providerMetadata !== undefined) {\n state.providerMetadata = providerMetadata;\n }\n\n return undefined;\n default:\n return undefined;\n }\n}\n"],"mappings":";;;;;AAOA,SAAgB,SAAS,OAAoC;CAC3D,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;AAC7C;;AAGA,SAAgB,SAAS,OAAoC;CAC3D,OAAO,OAAO,UAAU,YAAY,CAAC,MAAM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IAAY;IAAU,OAAO,SAAS;GAAK,CAAC;GAEnE;EACF,KAAK;GACH,IAAI,OAAO,OAAO,UAChB,MAAM,aAAa;GAErB,IAAI,OAAO,YAAY,UACrB,MAAM,gBAAgB;GAGxB;EACF,KAAK;GACH,MAAM,eAAe;GACrB,MAAM,QAAQ;GACd,IAAI,qBAAqB,KAAA,GACvB,MAAM,mBAAmB;GAG3B;EACF,SACE;CACJ;AACF"}
|
|
1
|
+
{"version":3,"file":"util.js","names":[],"sources":["../../../../src/integrations/vercel-ai/util.ts"],"sourcesContent":["/** Shared, state-free helpers for the Vercel AI (`ai`) channel subscribers, plus the streamed model-call tap. */\n\nimport type { Span } from '@sentry/core';\nimport { isObjectLike } from '@sentry/core';\nimport { recordTimeToFirstChunk } from '../../ai/core/time-to-first-chunk';\n\n/** Narrow to a string, or `undefined` for anything else. */\nexport function asString(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined;\n}\n\n/** Narrow to a finite number, or `undefined` for anything else (including `NaN`). */\nexport function asNumber(value: unknown): number | undefined {\n return typeof value === 'number' && !isNaN(value) ? value : undefined;\n}\n\n/** Add two optional numbers, treating a missing operand as `0` but returning `undefined` when both are absent. */\nexport function sum(a: number | undefined, b: number | undefined): number | undefined {\n return a === undefined && b === undefined ? undefined : (a ?? 0) + (b ?? 0);\n}\n\n/*\n * Streaming support for the `ai:telemetry` tracing channel.\n *\n * For a streamed model call (`doStream`) the SDK resolves the `languageModelCall` channel promise as\n * soon as it hands back the *unconsumed* stream — so `result.stream` is a `ReadableStream` and the\n * final usage / finish reason / output only arrive later, as the stream is drained (they ride the\n * stream's own `finish`/`text-delta`/`tool-call` chunks, never the channel context). The SDK\n * deliberately leaves `result` undefined on the `streamText`/`step` contexts and exposes the stream\n * only on the model call, expecting consumers to tap it themselves.\n * @see https://github.com/vercel/ai/pull/15660 (discussion: \"tee off and aggregate ourselves\")\n *\n * We replace `result.stream` with a passthrough that forwards every chunk untouched (so the SDK's own\n * consumption is unaffected) while accumulating the data we need, then hand the aggregate back once the\n * stream settles so the model-call span can be enriched and ended out-of-band.\n */\n\n/** The subset of a streamed provider chunk we read. Unknown chunk types are forwarded and ignored. */\ninterface StreamChunk {\n type?: unknown;\n delta?: unknown;\n // v4 text-delta chunks carry the text on `textDelta`; v5+ uses `delta`.\n textDelta?: unknown;\n id?: unknown;\n modelId?: unknown;\n toolCallId?: unknown;\n toolName?: unknown;\n input?: unknown;\n args?: unknown;\n finishReason?: unknown;\n usage?: unknown;\n providerMetadata?: unknown;\n error?: unknown;\n}\n\n/** The aggregate handed back once a streamed model call finishes, in the shape `enrichSpanOnEnd` expects. */\nexport interface StreamedModelCallResult {\n text?: string;\n toolCalls: Array<Record<string, unknown>>;\n usage?: unknown;\n finishReason?: unknown;\n responseId?: string;\n responseModel?: string;\n providerMetadata?: unknown;\n}\n\n/** The streamed model call exposes a web `ReadableStream` on `result.stream`. */\nexport { isReadableStream } from '../../ai/core/utils';\n\n/**\n * Wrap a streamed model call's `ReadableStream` so its chunks are observed as the SDK consumes them,\n * without altering what the SDK sees. Returns a replacement stream to swap onto `result.stream`.\n *\n * `onFinal` runs exactly once when the stream drains cleanly; `onError` runs exactly once if it errors\n * or is cancelled. Reading one source chunk per `pull` preserves the SDK's backpressure. The\n * `try/catch` around every read guarantees the owning span is always ended — a leaked open span on a\n * mid-stream failure would be worse than a slightly-less-enriched one.\n */\nexport function tapModelCallStream(\n span: Span,\n stream: ReadableStream<unknown>,\n onFinal: (result: StreamedModelCallResult) => void,\n onError: (error: unknown) => void,\n): ReadableStream<unknown> {\n const reader = stream.getReader();\n const state: StreamedModelCallResult = { toolCalls: [] };\n let text = '';\n let settled = false;\n\n const finalize = (): void => {\n if (settled) {\n return;\n }\n settled = true;\n if (text) {\n state.text = text;\n }\n onFinal(state);\n };\n\n const fail = (error: unknown): void => {\n if (settled) {\n return;\n }\n settled = true;\n onError(error);\n };\n\n return new ReadableStream<unknown>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n finalize();\n controller.close();\n\n return;\n }\n // The model emits `stream-start` before the response arrives.\n if ((value as StreamChunk | undefined)?.type !== 'stream-start') {\n recordTimeToFirstChunk(span);\n }\n text += accumulateChunk(state, value) ?? '';\n controller.enqueue(value);\n } catch (error) {\n fail(error);\n controller.error(error);\n }\n },\n cancel(reason) {\n // Consumer stopped reading early (e.g. a `break` out of `for await`); close out the span with\n // whatever we have rather than leave it open. A non-error reason is a deliberate stop, not a failure.\n finalize();\n\n return reader.cancel(reason);\n },\n });\n}\n\n/**\n * Fold a single streamed chunk into the running aggregate. Returns any text delta so the caller can\n * accumulate it (kept out of `state` until the end to avoid re-joining on every chunk).\n */\nfunction accumulateChunk(state: StreamedModelCallResult, chunk: unknown): string | undefined {\n if (!isObjectLike(chunk)) {\n return undefined;\n }\n const {\n type,\n delta,\n textDelta,\n id,\n modelId,\n toolCallId,\n toolName,\n input,\n args,\n finishReason,\n usage,\n providerMetadata,\n } = chunk as StreamChunk;\n\n switch (type) {\n case 'text-delta': {\n const textChunk = delta ?? textDelta;\n return typeof textChunk === 'string' ? textChunk : undefined;\n }\n case 'tool-call':\n state.toolCalls.push({ toolCallId, toolName, input: input ?? args });\n\n return undefined;\n case 'response-metadata':\n if (typeof id === 'string') {\n state.responseId = id;\n }\n if (typeof modelId === 'string') {\n state.responseModel = modelId;\n }\n\n return undefined;\n case 'finish':\n state.finishReason = finishReason;\n state.usage = usage;\n if (providerMetadata !== undefined) {\n state.providerMetadata = providerMetadata;\n }\n\n return undefined;\n default:\n return undefined;\n }\n}\n\n/** Maps each object value of `record` and keeps the other values as they are. */\nexport function mapObjectValues(\n record: Record<string, unknown>,\n fn: (value: Record<string, unknown>, key: string) => unknown,\n): Record<string, unknown> {\n return Object.fromEntries(\n Object.entries(record).map(([key, value]) => [key, isObjectLike(value) ? fn(value, key) : value]),\n );\n}\n"],"mappings":";;;;;AAOA,SAAgB,SAAS,OAAoC;CAC3D,OAAO,OAAO,UAAU,WAAW,QAAQ,KAAA;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,OAAO,cAAc,WAAW,YAAY,KAAA;EACrD;EACA,KAAK;GACH,MAAM,UAAU,KAAK;IAAE;IAAY;IAAU,OAAO,SAAS;GAAK,CAAC;GAEnE;EACF,KAAK;GACH,IAAI,OAAO,OAAO,UAChB,MAAM,aAAa;GAErB,IAAI,OAAO,YAAY,UACrB,MAAM,gBAAgB;GAGxB;EACF,KAAK;GACH,MAAM,eAAe;GACrB,MAAM,QAAQ;GACd,IAAI,qBAAqB,KAAA,GACvB,MAAM,mBAAmB;GAG3B;EACF,SACE;CACJ;AACF;;AAGA,SAAgB,gBACd,QACA,IACyB;CACzB,OAAO,OAAO,YACZ,OAAO,QAAQ,MAAM,CAAC,CAAC,KAAK,CAAC,KAAK,WAAW,CAAC,KAAK,aAAa,KAAK,IAAI,GAAG,OAAO,GAAG,IAAI,KAAK,CAAC,CAClG;AACF"}
|
|
@@ -5,10 +5,11 @@ import { getEvaluationOutputMessages, isReadableStream, resolveRecordingOption }
|
|
|
5
5
|
import { LAST_STEP_ONLY_USAGE_KEYS, getProviderMetadataAttributes } from "../../ai/vercel-ai/index.js";
|
|
6
6
|
import { WORKERS_AI_INTEGRATION_NAME } from "../../ai/workers-ai/constants.js";
|
|
7
7
|
import { bindTracingChannelToSpan } from "../../tracing-channel.js";
|
|
8
|
-
import {
|
|
8
|
+
import { toExtractAnswers, toExtractFields, toExtractState } from "./extract.js";
|
|
9
|
+
import { asNumber, asString, mapObjectValues, sum, tapModelCallStream } from "./util.js";
|
|
9
10
|
import { GEN_AI_CONVERSATION_ID, GEN_AI_COST_TOTAL_TOKENS, GEN_AI_EMBEDDINGS_INPUT, GEN_AI_FUNCTION_ID, GEN_AI_INPUT_MESSAGES, GEN_AI_OPERATION_NAME, GEN_AI_OUTPUT_MESSAGES, GEN_AI_PROVIDER_NAME, GEN_AI_REQUEST_MODEL, GEN_AI_RESPONSE_FINISH_REASONS, GEN_AI_RESPONSE_ID, GEN_AI_RESPONSE_MODEL, GEN_AI_RESPONSE_STREAMING, GEN_AI_SYSTEM_INSTRUCTIONS, GEN_AI_TOOL_CALL_ARGUMENTS, GEN_AI_TOOL_CALL_RESULT, GEN_AI_TOOL_DEFINITIONS, GEN_AI_TOOL_DESCRIPTION, GEN_AI_TOOL_NAME, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS, GEN_AI_USAGE_INPUT_TOKENS, GEN_AI_USAGE_OUTPUT_TOKENS, GEN_AI_USAGE_REASONING_OUTPUT_TOKENS, GEN_AI_USAGE_TOTAL_TOKENS, SENTRY_OP, SENTRY_ORIGIN, VERCEL_AI_SETTINGS_CONTEXT_KEY_BASE, VERCEL_AI_TOOL_CALL_CONTEXT_KEY_BASE } from "@sentry/conventions/attributes";
|
|
10
11
|
import { SPAN_STATUS_ERROR, _INTERNAL_skipAiProviderWrapping, captureException, getActiveSpan, getClient, isObjectLike, isPlainObject, spanToJSON, spanToTraceContext, startInactiveSpan, stringify, withScope } from "@sentry/core";
|
|
11
|
-
import { GEN_AI_DECIDE, GEN_AI_EMBEDDINGS, GEN_AI_EXECUTE_TOOL, GEN_AI_GENERATE_CONTENT, GEN_AI_INVOKE_AGENT, GEN_AI_RERANK } from "@sentry/conventions/op";
|
|
12
|
+
import { GEN_AI_DECIDE, GEN_AI_EMBEDDINGS, GEN_AI_EXECUTE_TOOL, GEN_AI_EXTRACT, GEN_AI_GENERATE_CONTENT, GEN_AI_INVOKE_AGENT, GEN_AI_RERANK } from "@sentry/conventions/op";
|
|
12
13
|
// src/integrations/vercel-ai/vercel-ai-dc-subscriber.ts
|
|
13
14
|
/**
|
|
14
15
|
* The single tracing channel the `ai` package (>= 7) publishes all telemetry lifecycle events to
|
|
@@ -21,6 +22,7 @@ const GEN_AI_OPERATION_SPAN_OPS = {
|
|
|
21
22
|
embeddings: GEN_AI_EMBEDDINGS,
|
|
22
23
|
rerank: GEN_AI_RERANK,
|
|
23
24
|
decide: GEN_AI_DECIDE,
|
|
25
|
+
extract: GEN_AI_EXTRACT,
|
|
24
26
|
invoke_agent: GEN_AI_INVOKE_AGENT,
|
|
25
27
|
execute_tool: GEN_AI_EXECUTE_TOOL,
|
|
26
28
|
generate_content: GEN_AI_GENERATE_CONTENT
|
|
@@ -307,6 +309,14 @@ function startSpanFromEvent(type, event, recordInputs) {
|
|
|
307
309
|
questions: event.questions
|
|
308
310
|
}]) } : {}
|
|
309
311
|
});
|
|
312
|
+
case "experimental_extract": return startGenAiSpan("extract", modelId, {
|
|
313
|
+
...baseAttributes,
|
|
314
|
+
...recordInputs && !(isStrippedInput(event.state) && isStrippedInput(event.fields)) ? { [GEN_AI_INPUT_MESSAGES]: stringify([{
|
|
315
|
+
...toExtractState(event.state).request,
|
|
316
|
+
fields: toExtractFields(event.fields),
|
|
317
|
+
reference_date: event.referenceDate
|
|
318
|
+
}]) } : {}
|
|
319
|
+
});
|
|
310
320
|
default: return;
|
|
311
321
|
}
|
|
312
322
|
}
|
|
@@ -431,12 +441,13 @@ function enrichSpanOnEnd(span, data) {
|
|
|
431
441
|
dropLastStepOnlyUsage(providerAttributes, type);
|
|
432
442
|
span.setAttributes(providerAttributes);
|
|
433
443
|
if (recordOutputs) {
|
|
434
|
-
const outputMessages = getOutputMessages(type, result, finishReason);
|
|
444
|
+
const outputMessages = getOutputMessages(type, result, finishReason, data.event);
|
|
435
445
|
if (outputMessages) span.setAttribute(GEN_AI_OUTPUT_MESSAGES, outputMessages);
|
|
436
446
|
}
|
|
437
447
|
}
|
|
438
|
-
function getOutputMessages(type, result, finishReason) {
|
|
448
|
+
function getOutputMessages(type, result, finishReason, event) {
|
|
439
449
|
if (type === "experimental_evaluate" || type === "experimental_decide") return getEvaluationOutputMessages(withProviderAnswerFields(result));
|
|
450
|
+
if (type === "experimental_extract") return isObjectLike(result.answers) ? stringify([{ answers: toExtractAnswers(result.answers, toExtractState(event.state).parts) }]) : void 0;
|
|
440
451
|
return buildOutputMessages(type === "languageModelCall" && Array.isArray(result.content) ? partsFromContent(result.content) : partsFromTextAndToolCalls(result.text, result.toolCalls), finishReason);
|
|
441
452
|
}
|
|
442
453
|
/**
|
|
@@ -450,17 +461,16 @@ function withProviderAnswerFields(result) {
|
|
|
450
461
|
const { openrouter } = providerMetadata;
|
|
451
462
|
const openrouterById = isObjectLike(openrouter) && isObjectLike(openrouter.answers) ? openrouter.answers : void 0;
|
|
452
463
|
if (!confidenceById && !openrouterById) return answers;
|
|
453
|
-
return
|
|
454
|
-
if (!isObjectLike(answer)) return [id, answer];
|
|
464
|
+
return mapObjectValues(answers, (answer, id) => {
|
|
455
465
|
const openrouterAnswer = openrouterById?.[id];
|
|
456
466
|
const fields = isObjectLike(openrouterAnswer) ? openrouterAnswer : {};
|
|
457
467
|
const { confidence = asNumber(confidenceById?.[id]) ?? asNumber(fields.confidence), legend = isObjectLike(fields.legend) ? fields.legend : void 0 } = answer;
|
|
458
|
-
return
|
|
468
|
+
return {
|
|
459
469
|
...answer,
|
|
460
470
|
confidence,
|
|
461
471
|
legend
|
|
462
|
-
}
|
|
463
|
-
})
|
|
472
|
+
};
|
|
473
|
+
});
|
|
464
474
|
}
|
|
465
475
|
/** Maps a Vercel AI finish reason to the OTel `gen_ai.output.messages` form (`tool-calls` → `tool_call`). */
|
|
466
476
|
function normalizeFinishReason(finishReason) {
|