@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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"amqplib.js","names":["diagnosticsChannel.tracingChannel","diagnosticsChannel\n .tracingChannel"],"sources":["../../../src/integrations/amqplib.ts"],"sourcesContent":["/* eslint-disable max-lines */\nimport * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span, SpanAttributes } from '@sentry/core';\nimport {\n continueTrace,\n defineIntegration,\n getClient,\n getTraceData,\n hasSpanStreamingEnabled,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n timestampInSeconds,\n} from '@sentry/core';\nimport {\n MESSAGING_DESTINATION_NAME,\n MESSAGING_MESSAGE_ID,\n MESSAGING_OPERATION_NAME,\n MESSAGING_OPERATION_TYPE,\n MESSAGING_SYSTEM,\n NETWORK_PROTOCOL_NAME,\n NETWORK_PROTOCOL_VERSION,\n SENTRY_KIND,\n SENTRY_OP,\n SENTRY_SEGMENT_NAME_SOURCE,\n SERVER_ADDRESS,\n SERVER_PORT,\n URL_FULL,\n SENTRY_ORIGIN,\n MESSAGING_MESSAGE_CONVERSATION_ID,\n MESSAGING_RABBITMQ_DESTINATION_ROUTING_KEY,\n} from '@sentry/conventions/attributes';\nimport { QUEUE_PROCESS, QUEUE_PUBLISH } from '@sentry/conventions/op';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { amqplibModuleNames } from '../orchestrion/config/amqplib';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\n\n// NOTE: this uses the same name as the OTel integration by design.\n// When enabled, the OTel 'Amqplib' integration is omitted from the default set.\nconst INTEGRATION_NAME = 'Amqplib' as const;\n\nconst PUBLISHER_ORIGIN = 'auto.queue.amqplib.publisher';\nconst CONSUMER_ORIGIN = 'auto.queue.amqplib.consumer';\n\nconst MESSAGING_OPERATION_VALUE_PROCESS = 'process';\nconst MESSAGING_OPERATION_VALUE_SEND = 'send';\n\n// To prevent reference leaks from un-acked messages, their spans are closed after this timeout. The\n// upstream instrumentation exposed this as the `consumeTimeoutMs` option; the SDK always used the default.\nconst CONSUME_TIMEOUT_MS = 1000 * 60; // 1 minute\n\n// The end-operation labels used in the consumer span's error status message.\nconst END_OP = {\n Ack: 'ack',\n AckAll: 'ackAll',\n Reject: 'reject',\n Nack: 'nack',\n NackAll: 'nackAll',\n ChannelClosed: 'channel closed',\n ChannelError: 'channel error',\n InstrumentationTimeout: 'instrumentation timeout',\n} as const;\ntype EndOp = (typeof END_OP)[keyof typeof END_OP];\n\n// State stashed on the live amqplib objects (mirrors the vendored OTel instrumentation's symbols).\nconst MESSAGE_STORED_SPAN: unique symbol = Symbol('sentry.amqplib.message.stored-span');\nconst CHANNEL_SPANS_NOT_ENDED: unique symbol = Symbol('sentry.amqplib.channel.spans-not-ended');\nconst CHANNEL_CONSUME_TIMEOUT_TIMER: unique symbol = Symbol('sentry.amqplib.channel.consume-timeout-timer');\nconst CHANNEL_CONSUMER_INFO: unique symbol = Symbol('sentry.amqplib.channel.consumer-info');\nconst CHANNEL_PENDING_CONSUMERS: unique symbol = Symbol('sentry.amqplib.channel.pending-consumers');\nconst CHANNEL_IS_CONFIRM_PUBLISHING: unique symbol = Symbol('sentry.amqplib.channel.is-confirm-publishing');\nconst CONNECTION_ATTRIBUTES: unique symbol = Symbol('sentry.amqplib.connection.attributes');\n\ninterface MessageFields {\n deliveryTag?: number;\n exchange?: string;\n routingKey?: string;\n consumerTag?: string;\n}\n\ninterface MessageProperties {\n headers?: Record<string, unknown>;\n messageId?: unknown;\n correlationId?: unknown;\n}\n\ninterface ConsumeMessage {\n fields?: MessageFields;\n properties?: MessageProperties;\n [MESSAGE_STORED_SPAN]?: Span;\n}\n\ninterface PublishOptions {\n headers?: Record<string, unknown>;\n messageId?: unknown;\n correlationId?: unknown;\n}\n\ninterface ConnectionLike {\n serverProperties?: { product?: string };\n // Some amqplib versions nest the low-level connection one level deeper.\n connection?: { serverProperties?: { product?: string } };\n [CONNECTION_ATTRIBUTES]?: SpanAttributes;\n}\n\ninterface ConsumerInfo {\n noAck: boolean;\n queue: string;\n}\n\n/** A `consume` call waiting for the broker to assign it a consumer tag. */\ninterface PendingConsumer {\n callback: unknown;\n info: ConsumerInfo;\n}\n\ninterface ChannelLike {\n connection?: ConnectionLike;\n on?: (event: string, listener: (...args: unknown[]) => void) => unknown;\n [CHANNEL_SPANS_NOT_ENDED]?: { msg: ConsumeMessage; timeOfConsume: number }[];\n [CHANNEL_CONSUME_TIMEOUT_TIMER]?: ReturnType<typeof setInterval>;\n [CHANNEL_CONSUMER_INFO]?: Map<string, ConsumerInfo>;\n [CHANNEL_PENDING_CONSUMERS]?: PendingConsumer[];\n [CHANNEL_IS_CONFIRM_PUBLISHING]?: boolean;\n}\n\ninterface AmqpChannelContext extends OrchestrionChannelContext {\n self?: ChannelLike;\n}\n\ninterface AmqpDispatchContext extends AmqpChannelContext {\n // Whether the delivering consumer registered with `noAck`; set at span creation so `deferSpanEnd`\n // knows whether the helper should end the span (noAck) or leave it open until ack/nack (manual ack).\n _sentryNoAck?: boolean;\n}\n\ninterface AmqpConsumeContext extends AmqpChannelContext {\n // The entry this call queued, so the error hook can drop it.\n _sentryPendingConsumer?: PendingConsumer;\n}\n\nconst NOOP = (): void => {};\n\nconst _amqplibIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, amqplibModuleNames, instrumentAmqplib, []);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentAmqplib(): void {\n subscribeConnect();\n subscribePublish();\n subscribeConfirmPublish();\n subscribeConsume();\n subscribeRegisterConsumer();\n subscribeDispatch();\n subscribeSettle();\n}\n\n/**\n * Producer span for `Channel.prototype.publish`. Creates a PRODUCER span, injects the trace headers\n * into the publish options, and ends when the (synchronous) publish call returns. Skips the confirm\n * channel's internal `super.publish` call, which is already handled by {@link subscribeConfirmPublish}.\n */\nfunction subscribePublish(): void {\n bindTracingChannelToSpan(diagnosticsChannel.tracingChannel<AmqpChannelContext>(CHANNELS.AMQPLIB_PUBLISH), data => {\n if (data.self?.[CHANNEL_IS_CONFIRM_PUBLISHING]) {\n return undefined;\n }\n return startPublishSpan(data);\n });\n}\n\n/**\n * Producer span for `ConfirmChannel.prototype.publish`. The span ends on the broker-confirm callback\n * (the channel's trailing `cb` arg, wrapped by orchestrion) rather than synchronously. A synchronous\n * flag on the channel suppresses the base `publish` channel that `super.publish` triggers.\n */\nfunction subscribeConfirmPublish(): void {\n const channel = diagnosticsChannel.tracingChannel<AmqpChannelContext>(CHANNELS.AMQPLIB_CONFIRM_PUBLISH);\n\n bindTracingChannelToSpan(channel, data => {\n if (data.self) {\n data.self[CHANNEL_IS_CONFIRM_PUBLISHING] = true;\n }\n return startPublishSpan(data);\n });\n\n // `super.publish` runs synchronously inside the confirm publish body, so clearing the flag on the\n // synchronous `end` (which fires after the body returns) is enough to guard the base publish.\n channel.end.subscribe(message => {\n const self = (message as AmqpChannelContext).self;\n if (self) {\n self[CHANNEL_IS_CONFIRM_PUBLISHING] = false;\n }\n });\n}\n\n/** Stashes the `{ noAck, queue }` each `consume` asks for until the broker assigns it a tag. */\nfunction subscribeConsume(): void {\n const channel = diagnosticsChannel.tracingChannel<AmqpConsumeContext>(CHANNELS.AMQPLIB_CONSUME);\n\n channel.start.subscribe(message => {\n const data = message as AmqpConsumeContext;\n const consumerChannel = data.self;\n if (!consumerChannel) {\n return;\n }\n\n ensureChannelState(consumerChannel);\n const queueArg = data.arguments[0];\n const queue = typeof queueArg === 'string' ? queueArg : '<unknown>';\n const callback = data.arguments[1];\n const options = data.arguments[2] as { noAck?: boolean } | undefined;\n const entry = { callback, info: { noAck: !!options?.noAck, queue } };\n consumerChannel[CHANNEL_PENDING_CONSUMERS]?.push(entry);\n data._sentryPendingConsumer = entry;\n });\n\n // A synchronous throw, such as for invalid `arguments`, leaves the channel open. RPC failures close it.\n // A stale entry would label the next consumer that shares this callback.\n channel.error.subscribe(message => {\n const data = message as AmqpConsumeContext;\n if (data.self && data._sentryPendingConsumer) {\n removePendingConsumer(data.self, data._sentryPendingConsumer);\n }\n });\n}\n\n/**\n * Records `consumerTag -> { noAck, queue }` for the dispatch hook. `consume`'s promise resolves too late,\n * because amqplib can decode `BasicConsumeOk` and the first delivery in one socket read. amqplib always\n * registers a consumer before it dispatches to it.\n */\nfunction subscribeRegisterConsumer(): void {\n const channel = diagnosticsChannel.tracingChannel<AmqpChannelContext>(CHANNELS.AMQPLIB_REGISTER_CONSUMER);\n\n channel.start.subscribe(message => {\n const data = message as AmqpChannelContext;\n const consumerChannel = data.self;\n const consumerTag = data.arguments[0];\n const callback = data.arguments[1];\n if (!consumerChannel || typeof consumerTag !== 'string') {\n return;\n }\n\n const entry = consumerChannel[CHANNEL_PENDING_CONSUMERS]?.find(pending => pending.callback === callback);\n if (!entry) {\n return;\n }\n\n removePendingConsumer(consumerChannel, entry);\n consumerChannel[CHANNEL_CONSUMER_INFO]?.set(consumerTag, entry.info);\n });\n}\n\nfunction removePendingConsumer(channel: ChannelLike, entry: PendingConsumer): void {\n channel[CHANNEL_PENDING_CONSUMERS] = channel[CHANNEL_PENDING_CONSUMERS]?.filter(pending => pending !== entry);\n}\n\n/**\n * Per delivered message (`BaseChannel.prototype.dispatchMessage`): continues the producer's trace,\n * opens a CONSUMER span, and runs the user callback under it. Manual-ack consumers keep the span open\n * until `ack`/`nack`/`reject`/timeout/close; `noAck` consumers end it when dispatch returns.\n */\nfunction subscribeDispatch(): void {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<AmqpDispatchContext>(CHANNELS.AMQPLIB_DISPATCH),\n data => {\n const channel = data.self;\n const fields = data.arguments[0] as MessageFields | undefined;\n const msg = data.arguments[1] as ConsumeMessage | null | undefined;\n // `message` is null for a consumer-cancel notification: not a real message, so no span.\n if (!channel || !msg) {\n return undefined;\n }\n\n ensureChannelState(channel);\n const info = fields?.consumerTag ? channel[CHANNEL_CONSUMER_INFO]?.get(fields.consumerTag) : undefined;\n const queue = info?.queue ?? msg.fields?.routingKey;\n const noAck = info?.noAck ?? false;\n\n const headers = msg.properties?.headers;\n const sentryTrace = getHeaderAsString(headers, 'sentry-trace');\n const baggage = getHeaderAsString(headers, 'baggage');\n\n // Continue the producer's trace so the consumer span links back to the publishing service.\n const span = continueTrace({ sentryTrace, baggage }, () => startConsumeSpan(queue, msg, channel));\n\n if (!noAck) {\n // Track the message so its span can be ended when the user calls ack/nack/reject (or on\n // timeout/channel close).\n channel[CHANNEL_SPANS_NOT_ENDED]?.push({ msg, timeOfConsume: timestampInSeconds() });\n msg[MESSAGE_STORED_SPAN] = span;\n }\n\n data._sentryNoAck = noAck;\n return span;\n },\n {\n // Manual-ack consumers: the span outlives the dispatch call and is ended by ack/nack/reject\n // (or timeout/close), so take ownership and don't let the helper end it here. noAck consumers\n // have no settle call, so let the helper end the span when dispatch returns.\n deferSpanEnd({ data }) {\n return !data._sentryNoAck;\n },\n },\n );\n}\n\n/** Ends consumer spans when the user acks/nacks/rejects a message or the channel closes/errors. */\nfunction subscribeSettle(): void {\n diagnosticsChannel\n .tracingChannel<AmqpChannelContext>(CHANNELS.AMQPLIB_ACK)\n .start.subscribe(message => handleAck(message as AmqpChannelContext, false, END_OP.Ack));\n diagnosticsChannel\n .tracingChannel<AmqpChannelContext>(CHANNELS.AMQPLIB_NACK)\n .start.subscribe(message => handleAck(message as AmqpChannelContext, true, END_OP.Nack));\n diagnosticsChannel\n .tracingChannel<AmqpChannelContext>(CHANNELS.AMQPLIB_REJECT)\n .start.subscribe(message => handleAck(message as AmqpChannelContext, true, END_OP.Reject));\n diagnosticsChannel.tracingChannel<AmqpChannelContext>(CHANNELS.AMQPLIB_ACK_ALL).start.subscribe(message => {\n const data = message as AmqpChannelContext;\n if (data.self) {\n endAllSpansOnChannel(data.self, false, END_OP.AckAll, undefined);\n }\n });\n diagnosticsChannel.tracingChannel<AmqpChannelContext>(CHANNELS.AMQPLIB_NACK_ALL).start.subscribe(message => {\n const data = message as AmqpChannelContext;\n if (data.self) {\n endAllSpansOnChannel(data.self, true, END_OP.NackAll, data.arguments[0] as boolean | undefined);\n }\n });\n}\n\n/** Captures connection attributes on the connection object for span-time reads via `channel.connection`. */\nfunction subscribeConnect(): void {\n const channel = diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(CHANNELS.AMQPLIB_CONNECT);\n // A `start` subscriber is required for orchestrion to wrap the callback-style `connect` at all.\n channel.start.subscribe(NOOP);\n channel.asyncEnd.subscribe(message => {\n const data = message as OrchestrionChannelContext;\n const conn = data.result as ConnectionLike | undefined;\n if (!conn || typeof conn !== 'object') {\n return;\n }\n conn[CONNECTION_ATTRIBUTES] = {\n ...getConnectionAttributesFromUrl(data.arguments?.[0]),\n ...getConnectionAttributesFromServer(conn),\n };\n });\n}\n\nfunction handleAck(data: AmqpChannelContext, isRejected: boolean, endOperation: EndOp): void {\n const channel = data.self;\n if (!channel) {\n return;\n }\n const message = data.arguments[0] as ConsumeMessage | undefined;\n if (!message) {\n return;\n }\n\n // `reject(message, requeue)` carries requeue in arg 1; `ack`/`nack` carry `allUpTo` in arg 1.\n const allUpToOrRequeue = data.arguments[1] as boolean | undefined;\n const requeue = data.arguments[2] as boolean | undefined;\n const requeueResolved = endOperation === END_OP.Reject ? allUpToOrRequeue : requeue;\n\n const spansNotEnded = channel[CHANNEL_SPANS_NOT_ENDED] ?? [];\n const msgIndex = spansNotEnded.findIndex(msgDetails => msgDetails.msg === message);\n if (msgIndex < 0) {\n // Not tracked (e.g. the user acked the same message twice) — end the stored span directly.\n endConsumerSpan(message, isRejected, endOperation, requeueResolved);\n } else if (endOperation !== END_OP.Reject && allUpToOrRequeue) {\n for (let i = 0; i <= msgIndex; i++) {\n endConsumerSpan(spansNotEnded[i]!.msg, isRejected, endOperation, requeueResolved);\n }\n spansNotEnded.splice(0, msgIndex + 1);\n } else {\n endConsumerSpan(message, isRejected, endOperation, requeueResolved);\n spansNotEnded.splice(msgIndex, 1);\n }\n}\n\nfunction ensureChannelState(channel: ChannelLike): void {\n if (Object.prototype.hasOwnProperty.call(channel, CHANNEL_SPANS_NOT_ENDED)) {\n return;\n }\n\n channel[CHANNEL_SPANS_NOT_ENDED] = [];\n channel[CHANNEL_CONSUMER_INFO] = new Map();\n channel[CHANNEL_PENDING_CONSUMERS] = [];\n\n const timer = setInterval(() => checkConsumeTimeoutOnChannel(channel), CONSUME_TIMEOUT_MS);\n timer.unref?.();\n channel[CHANNEL_CONSUME_TIMEOUT_TIMER] = timer;\n\n // End outstanding spans and stop the timer when the channel goes away (replaces patching `emit`).\n // amqplib emits 'close' after 'error', but we clear in both to avoid leaking the interval (which\n // pins the channel via its closure) should a version or edge case ever skip the trailing 'close'.\n if (typeof channel.on === 'function') {\n channel.on('close', () => {\n endAllSpansOnChannel(channel, true, END_OP.ChannelClosed, undefined);\n clearConsumeTimeoutTimer(channel);\n });\n channel.on('error', () => {\n endAllSpansOnChannel(channel, true, END_OP.ChannelError, undefined);\n clearConsumeTimeoutTimer(channel);\n });\n }\n}\n\n/** Stops and clears the per-channel consume-timeout interval. Idempotent. */\nfunction clearConsumeTimeoutTimer(channel: ChannelLike): void {\n const activeTimer = channel[CHANNEL_CONSUME_TIMEOUT_TIMER];\n if (activeTimer) {\n clearInterval(activeTimer);\n channel[CHANNEL_CONSUME_TIMEOUT_TIMER] = undefined;\n }\n}\n\nfunction checkConsumeTimeoutOnChannel(channel: ChannelLike): void {\n const currentTime = timestampInSeconds();\n const spansNotEnded = channel[CHANNEL_SPANS_NOT_ENDED] ?? [];\n let i: number;\n for (i = 0; i < spansNotEnded.length; i++) {\n const currMessage = spansNotEnded[i]!;\n const timeFromConsumeMs = (currentTime - currMessage.timeOfConsume) * 1000;\n if (timeFromConsumeMs < CONSUME_TIMEOUT_MS) {\n break;\n }\n endConsumerSpan(currMessage.msg, null, END_OP.InstrumentationTimeout, true);\n }\n spansNotEnded.splice(0, i);\n}\n\nfunction endAllSpansOnChannel(\n channel: ChannelLike,\n isRejected: boolean,\n operation: EndOp,\n requeue: boolean | undefined,\n): void {\n const spansNotEnded = channel[CHANNEL_SPANS_NOT_ENDED] ?? [];\n spansNotEnded.forEach(msgDetails => {\n endConsumerSpan(msgDetails.msg, isRejected, operation, requeue);\n });\n channel[CHANNEL_SPANS_NOT_ENDED] = [];\n}\n\nfunction endConsumerSpan(\n message: ConsumeMessage,\n isRejected: boolean | null,\n operation: EndOp,\n requeue: boolean | undefined,\n): void {\n const storedSpan = message[MESSAGE_STORED_SPAN];\n if (!storedSpan) {\n return;\n }\n if (isRejected !== false) {\n storedSpan.setStatus({\n code: SPAN_STATUS_ERROR,\n message:\n operation !== END_OP.ChannelClosed && operation !== END_OP.ChannelError\n ? `${operation} called on message${\n requeue === true ? ' with requeue' : requeue === false ? ' without requeue' : ''\n }`\n : operation,\n });\n }\n storedSpan.end();\n message[MESSAGE_STORED_SPAN] = undefined;\n}\n\n/** Starts an inactive PRODUCER span and propagates its trace into the publish `options.headers`. */\nfunction startPublishSpan(data: AmqpChannelContext): Span {\n const exchangeArg = data.arguments[0];\n const routingKeyArg = data.arguments[1];\n const exchange = typeof exchangeArg === 'string' ? exchangeArg : '';\n const routingKey = typeof routingKeyArg === 'string' ? routingKeyArg : '';\n let options = data.arguments[3] as PublishOptions | undefined;\n\n const client = getClient();\n const destination = resolveDestination(exchange, routingKey);\n const streamedName = destination\n ? `${MESSAGING_OPERATION_VALUE_SEND} ${destination}`\n : MESSAGING_OPERATION_VALUE_SEND;\n\n const span = startInactiveSpan({\n name: client && hasSpanStreamingEnabled(client) ? streamedName : `publish ${normalizeExchange(exchange)}`,\n attributes: {\n [SENTRY_OP]: QUEUE_PUBLISH,\n [SENTRY_KIND]: 'producer',\n ...getStoredConnectionAttributes(data.self),\n [MESSAGING_DESTINATION_NAME]: destination,\n [MESSAGING_RABBITMQ_DESTINATION_ROUTING_KEY]: routingKey,\n [MESSAGING_OPERATION_NAME]: MESSAGING_OPERATION_VALUE_SEND,\n [MESSAGING_OPERATION_TYPE]: MESSAGING_OPERATION_VALUE_SEND,\n [MESSAGING_MESSAGE_ID]: options?.messageId as string | undefined,\n [MESSAGING_MESSAGE_CONVERSATION_ID]: options?.correlationId as string | undefined,\n [SENTRY_ORIGIN]: PUBLISHER_ORIGIN,\n },\n });\n\n if (!options || typeof options !== 'object') {\n options = {};\n data.arguments[3] = options;\n }\n const headers = options.headers && typeof options.headers === 'object' ? options.headers : (options.headers = {});\n const traceData = getTraceData({ span });\n if (traceData['sentry-trace']) {\n headers['sentry-trace'] = traceData['sentry-trace'];\n }\n if (traceData.baggage) {\n headers['baggage'] = traceData.baggage;\n }\n\n return span;\n}\n\n/** Starts an inactive CONSUMER (process) span carrying the amqplib messaging attributes. */\nfunction startConsumeSpan(queue: string | undefined, msg: ConsumeMessage, channel: ChannelLike): Span {\n const client = getClient();\n const destination = resolveDestination(msg.fields?.exchange, msg.fields?.routingKey);\n const streamedName = destination\n ? `${MESSAGING_OPERATION_VALUE_PROCESS} ${destination}`\n : MESSAGING_OPERATION_VALUE_PROCESS;\n\n return startInactiveSpan({\n name:\n client && hasSpanStreamingEnabled(client)\n ? streamedName\n : queue\n ? `${queue} ${MESSAGING_OPERATION_VALUE_PROCESS}`\n : MESSAGING_OPERATION_VALUE_PROCESS,\n attributes: {\n [SENTRY_OP]: QUEUE_PROCESS,\n [SENTRY_KIND]: 'consumer',\n [SENTRY_SEGMENT_NAME_SOURCE]: 'component',\n ...getStoredConnectionAttributes(channel),\n [MESSAGING_DESTINATION_NAME]: destination,\n [MESSAGING_RABBITMQ_DESTINATION_ROUTING_KEY]: msg.fields?.routingKey,\n [MESSAGING_OPERATION_NAME]: MESSAGING_OPERATION_VALUE_PROCESS,\n [MESSAGING_OPERATION_TYPE]: MESSAGING_OPERATION_VALUE_PROCESS,\n [MESSAGING_MESSAGE_ID]: msg.properties?.messageId as string | undefined,\n [MESSAGING_MESSAGE_CONVERSATION_ID]: msg.properties?.correlationId as string | undefined,\n [SENTRY_ORIGIN]: CONSUMER_ORIGIN,\n },\n });\n}\n\n/**\n * Reads the connection attributes stashed by the `connect` channel, falling back to the live\n * connection's server product so `messaging.system` is populated even when the connection was\n * established before the integration ran.\n */\nfunction getStoredConnectionAttributes(channel: ChannelLike | undefined): SpanAttributes {\n const connection = channel?.connection;\n const stored = connection?.[CONNECTION_ATTRIBUTES];\n if (stored) {\n return stored;\n }\n const product = connection?.serverProperties?.product ?? connection?.connection?.serverProperties?.product;\n if (typeof product === 'string' && product) {\n return { [MESSAGING_SYSTEM]: product.toLowerCase() };\n }\n return {};\n}\n\nfunction getConnectionAttributesFromServer(conn: ConnectionLike): SpanAttributes {\n const product = conn.serverProperties?.product ?? conn.connection?.serverProperties?.product;\n if (typeof product === 'string' && product) {\n return { [MESSAGING_SYSTEM]: product.toLowerCase() };\n }\n return {};\n}\n\nfunction getConnectionAttributesFromUrl(url: unknown): SpanAttributes {\n const attributes: SpanAttributes = {\n // The only protocol supported by the instrumented library.\n [NETWORK_PROTOCOL_VERSION]: '0.9.1',\n };\n\n const resolvedUrl = url || 'amqp://localhost';\n if (typeof resolvedUrl === 'object') {\n const connectOptions = resolvedUrl as { protocol?: string; hostname?: string; port?: number };\n const protocol = getProtocol(connectOptions.protocol);\n const hostname = getHostname(connectOptions.hostname);\n const port = getPort(connectOptions.port, protocol);\n\n attributes[NETWORK_PROTOCOL_NAME] = protocol;\n\n attributes[SERVER_ADDRESS] = hostname;\n attributes[SERVER_PORT] = port;\n } else if (typeof resolvedUrl === 'string') {\n const censoredUrl = censorPassword(resolvedUrl);\n // oxlint-disable-next-line sdk/no-unfiltered-url-attributes -- AMQP connection URL, not an HTTP request URL\n attributes[URL_FULL] = censoredUrl;\n\n try {\n const urlParts = new URL(censoredUrl);\n const protocol = getProtocol(urlParts.protocol);\n const hostname = getHostname(urlParts.hostname);\n const port = getPort(urlParts.port ? parseInt(urlParts.port, 10) : undefined, protocol);\n\n attributes[NETWORK_PROTOCOL_NAME] = protocol;\n\n attributes[SERVER_ADDRESS] = hostname;\n attributes[SERVER_PORT] = port;\n } catch {\n // best-effort: a malformed url simply yields fewer connection attributes\n }\n }\n return attributes;\n}\n\n/**\n * The default exchange has no name and binds every queue under a key equal to the queue's own name, so\n * a routing key used with it is the queue name. On a named exchange the routing key is per-message\n * (`order.created.12345`), so only the exchange is used.\n *\n * @see https://www.rabbitmq.com/docs/exchanges#default-exchange\n * @internal Exported for tests; every scenario publishes through `sendToQueue`.\n */\nexport function resolveDestination(exchange: string | undefined, routingKey: string | undefined): string | undefined {\n // `undefined` so an absent destination is omitted rather than reported as an empty string.\n return exchange || routingKey || undefined;\n}\n\nfunction normalizeExchange(exchangeName: string): string {\n return exchangeName !== '' ? exchangeName : '<default>';\n}\n\nfunction censorPassword(url: string): string {\n return url.replace(/:[^:@/]*@/, ':***@');\n}\n\nfunction getPort(portFromUrl: number | undefined, resolvedProtocol: string): number {\n // Mimics amqplib's own defaulting; the resolved protocol is upper-cased.\n return portFromUrl || (resolvedProtocol === 'AMQP' ? 5672 : 5671);\n}\n\nfunction getProtocol(protocolFromUrl: string | undefined): string {\n const resolvedProtocol = protocolFromUrl || 'amqp';\n const noEndingColon = resolvedProtocol.endsWith(':')\n ? resolvedProtocol.substring(0, resolvedProtocol.length - 1)\n : resolvedProtocol;\n return noEndingColon.toUpperCase();\n}\n\nfunction getHostname(hostnameFromUrl: string | undefined): string {\n // An empty hostname is forwarded to `net`, which defaults it to localhost.\n return hostnameFromUrl || 'localhost';\n}\n\nfunction getHeaderAsString(headers: Record<string, unknown> | undefined, key: string): string | undefined {\n const value = headers?.[key];\n if (value == null) {\n return undefined;\n }\n return Array.isArray(value) ? String(value[0]) : String(value);\n}\n\n/**\n * Diagnostics-channel-based `amqplib` integration.\n *\n * Subscribes to the `orchestrion:amqplib:*` diagnostics_channels that Sentry's code transform\n * injects into `amqplib`'s channel/connection methods. Requires the Sentry runtime hook or\n * bundler plugin to be active.\n */\nexport const amqplibIntegration = defineIntegration(_amqplibIntegration);\n"],"mappings":";;;;;;;;;AAwCA,MAAM,mBAAmB;AAEzB,MAAM,mBAAmB;AACzB,MAAM,kBAAkB;AAExB,MAAM,oCAAoC;AAC1C,MAAM,iCAAiC;AAIvC,MAAM,qBAAqB;AAG3B,MAAM,SAAS;CACb,KAAK;CACL,QAAQ;CACR,QAAQ;CACR,MAAM;CACN,SAAS;CACT,eAAe;CACf,cAAc;CACd,wBAAwB;AAC1B;AAIA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C7B,WAAW,eAAe;EAC5B,QAAQ,CAER;CACF;CACA,OAAO;AACT;;;;;;;;;AAUA,SAAgB,mBAAmB,UAA8B,YAAoD;CAEnH,OAAO,YAAY,cAAc,KAAA;AACnC;AAEA,SAAS,kBAAkB,cAA8B;CACvD,OAAO,iBAAiB,KAAK,eAAe;AAC9C;AAEA,SAAS,eAAe,KAAqB;CAC3C,OAAO,IAAI,QAAQ,aAAa,OAAO;AACzC;AAEA,SAAS,QAAQ,aAAiC,kBAAkC;CAElF,OAAO,gBAAgB,qBAAqB,SAAS,OAAO;AAC9D;AAEA,SAAS,YAAY,iBAA6C;CAChE,MAAM,mBAAmB,mBAAmB;CAI5C,QAHsB,iBAAiB,SAAS,GAAG,IAC/C,iBAAiB,UAAU,GAAG,iBAAiB,SAAS,CAAC,IACzD,iBAAA,CACiB,YAAY;AACnC;AAEA,SAAS,YAAY,iBAA6C;CAEhE,OAAO,mBAAmB;AAC5B;AAEA,SAAS,kBAAkB,SAA8C,KAAiC;CACxG,MAAM,QAAQ,UAAU;CACxB,IAAI,SAAS,MACX;CAEF,OAAO,MAAM,QAAQ,KAAK,IAAI,OAAO,MAAM,EAAE,IAAI,OAAO,KAAK;AAC/D;;;;;;;;AASA,MAAa,qBAAqB,kBAAkB,mBAAmB"}
|
|
1
|
+
{"version":3,"file":"amqplib.js","names":["diagnosticsChannel.tracingChannel","diagnosticsChannel\n .tracingChannel"],"sources":["../../../src/integrations/amqplib.ts"],"sourcesContent":["/* eslint-disable max-lines */\nimport * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span, SpanAttributes } from '@sentry/core';\nimport {\n continueTrace,\n defineIntegration,\n getClient,\n getTraceData,\n hasSpanStreamingEnabled,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n timestampInSeconds,\n} from '@sentry/core';\nimport {\n MESSAGING_DESTINATION_NAME,\n MESSAGING_MESSAGE_ID,\n MESSAGING_OPERATION_NAME,\n MESSAGING_OPERATION_TYPE,\n MESSAGING_SYSTEM,\n NETWORK_PROTOCOL_NAME,\n NETWORK_PROTOCOL_VERSION,\n SENTRY_KIND,\n SENTRY_OP,\n SENTRY_SEGMENT_NAME_SOURCE,\n SERVER_ADDRESS,\n SERVER_PORT,\n URL_FULL,\n SENTRY_ORIGIN,\n MESSAGING_MESSAGE_CONVERSATION_ID,\n MESSAGING_RABBITMQ_DESTINATION_ROUTING_KEY,\n} from '@sentry/conventions/attributes';\nimport { QUEUE_PROCESS, QUEUE_PUBLISH } from '@sentry/conventions/op';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { amqplibModuleNames } from '../orchestrion/config/amqplib';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\n\n// NOTE: this uses the same name as the OTel integration by design.\n// When enabled, the OTel 'Amqplib' integration is omitted from the default set.\nconst INTEGRATION_NAME = 'Amqplib' as const;\n\nconst PUBLISHER_ORIGIN = 'auto.queue.amqplib.publisher';\nconst CONSUMER_ORIGIN = 'auto.queue.amqplib.consumer';\n\nconst MESSAGING_OPERATION_VALUE_PROCESS = 'process';\nconst MESSAGING_OPERATION_VALUE_SEND = 'send';\n\n// To prevent reference leaks from un-acked messages, their spans are closed after this timeout. The\n// upstream instrumentation exposed this as the `consumeTimeoutMs` option; the SDK always used the default.\nconst CONSUME_TIMEOUT_MS = 1000 * 60; // 1 minute\n\n// The end-operation labels used in the consumer span's error status message.\nconst END_OP = {\n Ack: 'ack',\n AckAll: 'ackAll',\n Reject: 'reject',\n Nack: 'nack',\n NackAll: 'nackAll',\n ChannelClosed: 'channel closed',\n ChannelError: 'channel error',\n InstrumentationTimeout: 'instrumentation timeout',\n} as const;\ntype EndOp = (typeof END_OP)[keyof typeof END_OP];\n\n// State stashed on the live amqplib objects (mirrors the vendored OTel instrumentation's symbols).\nconst MESSAGE_STORED_SPAN: unique symbol = Symbol('sentry.amqplib.message.stored-span');\nconst CHANNEL_SPANS_NOT_ENDED: unique symbol = Symbol('sentry.amqplib.channel.spans-not-ended');\nconst CHANNEL_CONSUME_TIMEOUT_TIMER: unique symbol = Symbol('sentry.amqplib.channel.consume-timeout-timer');\nconst CHANNEL_CONSUMER_INFO: unique symbol = Symbol('sentry.amqplib.channel.consumer-info');\nconst CHANNEL_PENDING_CONSUMERS: unique symbol = Symbol('sentry.amqplib.channel.pending-consumers');\nconst CHANNEL_IS_CONFIRM_PUBLISHING: unique symbol = Symbol('sentry.amqplib.channel.is-confirm-publishing');\nconst CONNECTION_ATTRIBUTES: unique symbol = Symbol('sentry.amqplib.connection.attributes');\n\ninterface MessageFields {\n deliveryTag?: number;\n exchange?: string;\n routingKey?: string;\n consumerTag?: string;\n}\n\ninterface MessageProperties {\n headers?: Record<string, unknown>;\n messageId?: unknown;\n correlationId?: unknown;\n}\n\ninterface ConsumeMessage {\n fields?: MessageFields;\n properties?: MessageProperties;\n [MESSAGE_STORED_SPAN]?: Span;\n}\n\ninterface PublishOptions {\n headers?: Record<string, unknown>;\n messageId?: unknown;\n correlationId?: unknown;\n}\n\ninterface ConnectionLike {\n serverProperties?: { product?: string };\n // Some amqplib versions nest the low-level connection one level deeper.\n connection?: { serverProperties?: { product?: string } };\n [CONNECTION_ATTRIBUTES]?: SpanAttributes;\n}\n\ninterface ConsumerInfo {\n noAck: boolean;\n queue: string;\n}\n\n/** A `consume` call waiting for the broker to assign it a consumer tag. */\ninterface PendingConsumer {\n callback: unknown;\n info: ConsumerInfo;\n}\n\ninterface ChannelLike {\n connection?: ConnectionLike;\n on?: (event: string, listener: (...args: unknown[]) => void) => unknown;\n [CHANNEL_SPANS_NOT_ENDED]?: { msg: ConsumeMessage; timeOfConsume: number }[];\n [CHANNEL_CONSUME_TIMEOUT_TIMER]?: ReturnType<typeof setInterval>;\n [CHANNEL_CONSUMER_INFO]?: Map<string, ConsumerInfo>;\n [CHANNEL_PENDING_CONSUMERS]?: PendingConsumer[];\n [CHANNEL_IS_CONFIRM_PUBLISHING]?: boolean;\n}\n\ninterface AmqpChannelContext extends OrchestrionChannelContext {\n self?: ChannelLike;\n}\n\ninterface AmqpDispatchContext extends AmqpChannelContext {\n // Whether the delivering consumer registered with `noAck`; set at span creation so `deferSpanEnd`\n // knows whether the helper should end the span (noAck) or leave it open until ack/nack (manual ack).\n _sentryNoAck?: boolean;\n}\n\ninterface AmqpConsumeContext extends AmqpChannelContext {\n // The entry this call queued, so the error hook can drop it.\n _sentryPendingConsumer?: PendingConsumer;\n}\n\nconst NOOP = (): void => {};\n\nconst _amqplibIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, amqplibModuleNames, instrumentAmqplib, []);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentAmqplib(): void {\n subscribeConnect();\n subscribePublish();\n subscribeConfirmPublish();\n subscribeConsume();\n subscribeRegisterConsumer();\n subscribeDispatch();\n subscribeSettle();\n}\n\n/**\n * Producer span for `Channel.prototype.publish`. Creates a PRODUCER span, injects the trace headers\n * into the publish options, and ends when the (synchronous) publish call returns. Skips the confirm\n * channel's internal `super.publish` call, which is already handled by {@link subscribeConfirmPublish}.\n */\nfunction subscribePublish(): void {\n bindTracingChannelToSpan(diagnosticsChannel.tracingChannel<AmqpChannelContext>(CHANNELS.AMQPLIB_PUBLISH), data => {\n if (data.self?.[CHANNEL_IS_CONFIRM_PUBLISHING]) {\n return undefined;\n }\n return startPublishSpan(data);\n });\n}\n\n/**\n * Producer span for `ConfirmChannel.prototype.publish`. The span ends on the broker-confirm callback\n * (the channel's trailing `cb` arg, wrapped by orchestrion) rather than synchronously. A synchronous\n * flag on the channel suppresses the base `publish` channel that `super.publish` triggers.\n */\nfunction subscribeConfirmPublish(): void {\n const channel = diagnosticsChannel.tracingChannel<AmqpChannelContext>(CHANNELS.AMQPLIB_CONFIRM_PUBLISH);\n\n bindTracingChannelToSpan(channel, data => {\n if (data.self) {\n data.self[CHANNEL_IS_CONFIRM_PUBLISHING] = true;\n }\n return startPublishSpan(data);\n });\n\n // `super.publish` runs synchronously inside the confirm publish body, so clearing the flag on the\n // synchronous `end` (which fires after the body returns) is enough to guard the base publish.\n channel.end.subscribe(message => {\n const self = (message as AmqpChannelContext).self;\n if (self) {\n self[CHANNEL_IS_CONFIRM_PUBLISHING] = false;\n }\n });\n}\n\n/** Stashes the `{ noAck, queue }` each `consume` asks for until the broker assigns it a tag. */\nfunction subscribeConsume(): void {\n const channel = diagnosticsChannel.tracingChannel<AmqpConsumeContext>(CHANNELS.AMQPLIB_CONSUME);\n\n channel.start.subscribe(message => {\n const data = message as AmqpConsumeContext;\n const consumerChannel = data.self;\n if (!consumerChannel) {\n return;\n }\n\n ensureChannelState(consumerChannel);\n const queueArg = data.arguments[0];\n const queue = typeof queueArg === 'string' ? queueArg : '<unknown>';\n const callback = data.arguments[1];\n const options = data.arguments[2] as { noAck?: boolean } | undefined;\n const entry = { callback, info: { noAck: !!options?.noAck, queue } };\n consumerChannel[CHANNEL_PENDING_CONSUMERS]?.push(entry);\n data._sentryPendingConsumer = entry;\n });\n\n // A synchronous throw, such as for invalid `arguments`, leaves the channel open. RPC failures close it.\n // A stale entry would label the next consumer that shares this callback.\n channel.error.subscribe(message => {\n const data = message as AmqpConsumeContext;\n if (data.self && data._sentryPendingConsumer) {\n removePendingConsumer(data.self, data._sentryPendingConsumer);\n }\n });\n}\n\n/**\n * Records `consumerTag -> { noAck, queue }` for the dispatch hook. `consume`'s promise resolves too late,\n * because amqplib can decode `BasicConsumeOk` and the first delivery in one socket read. amqplib always\n * registers a consumer before it dispatches to it.\n */\nfunction subscribeRegisterConsumer(): void {\n const channel = diagnosticsChannel.tracingChannel<AmqpChannelContext>(CHANNELS.AMQPLIB_REGISTER_CONSUMER);\n\n channel.start.subscribe(message => {\n const data = message as AmqpChannelContext;\n const consumerChannel = data.self;\n const consumerTag = data.arguments[0];\n const callback = data.arguments[1];\n if (!consumerChannel || typeof consumerTag !== 'string') {\n return;\n }\n\n const entry = consumerChannel[CHANNEL_PENDING_CONSUMERS]?.find(pending => pending.callback === callback);\n if (!entry) {\n return;\n }\n\n removePendingConsumer(consumerChannel, entry);\n consumerChannel[CHANNEL_CONSUMER_INFO]?.set(consumerTag, entry.info);\n });\n}\n\nfunction removePendingConsumer(channel: ChannelLike, entry: PendingConsumer): void {\n channel[CHANNEL_PENDING_CONSUMERS] = channel[CHANNEL_PENDING_CONSUMERS]?.filter(pending => pending !== entry);\n}\n\n/**\n * Per delivered message (`BaseChannel.prototype.dispatchMessage`): continues the producer's trace,\n * opens a CONSUMER span, and runs the user callback under it. Manual-ack consumers keep the span open\n * until `ack`/`nack`/`reject`/timeout/close; `noAck` consumers end it when dispatch returns.\n */\nfunction subscribeDispatch(): void {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<AmqpDispatchContext>(CHANNELS.AMQPLIB_DISPATCH),\n data => {\n const channel = data.self;\n const fields = data.arguments[0] as MessageFields | undefined;\n const msg = data.arguments[1] as ConsumeMessage | null | undefined;\n // `message` is null for a consumer-cancel notification: not a real message, so no span.\n if (!channel || !msg) {\n return undefined;\n }\n\n ensureChannelState(channel);\n const info = fields?.consumerTag ? channel[CHANNEL_CONSUMER_INFO]?.get(fields.consumerTag) : undefined;\n const queue = info?.queue ?? msg.fields?.routingKey;\n const noAck = info?.noAck ?? false;\n\n const headers = msg.properties?.headers;\n const sentryTrace = getHeaderAsString(headers, 'sentry-trace');\n const baggage = getHeaderAsString(headers, 'baggage');\n\n // Continue the producer's trace so the consumer span links back to the publishing service.\n const span = continueTrace({ sentryTrace, baggage }, () => startConsumeSpan(queue, msg, channel));\n\n if (!noAck) {\n // Track the message so its span can be ended when the user calls ack/nack/reject (or on\n // timeout/channel close).\n channel[CHANNEL_SPANS_NOT_ENDED]?.push({ msg, timeOfConsume: timestampInSeconds() });\n msg[MESSAGE_STORED_SPAN] = span;\n }\n\n data._sentryNoAck = noAck;\n return span;\n },\n {\n // Manual-ack consumers: the span outlives the dispatch call and is ended by ack/nack/reject\n // (or timeout/close), so take ownership and don't let the helper end it here. noAck consumers\n // have no settle call, so let the helper end the span when dispatch returns.\n deferSpanEnd({ data }) {\n return !data._sentryNoAck;\n },\n },\n );\n}\n\n/** Ends consumer spans when the user acks/nacks/rejects a message or the channel closes/errors. */\nfunction subscribeSettle(): void {\n diagnosticsChannel\n .tracingChannel<AmqpChannelContext>(CHANNELS.AMQPLIB_ACK)\n .start.subscribe(message => handleAck(message as AmqpChannelContext, false, END_OP.Ack));\n diagnosticsChannel\n .tracingChannel<AmqpChannelContext>(CHANNELS.AMQPLIB_NACK)\n .start.subscribe(message => handleAck(message as AmqpChannelContext, true, END_OP.Nack));\n diagnosticsChannel\n .tracingChannel<AmqpChannelContext>(CHANNELS.AMQPLIB_REJECT)\n .start.subscribe(message => handleAck(message as AmqpChannelContext, true, END_OP.Reject));\n diagnosticsChannel.tracingChannel<AmqpChannelContext>(CHANNELS.AMQPLIB_ACK_ALL).start.subscribe(message => {\n const data = message as AmqpChannelContext;\n if (data.self) {\n endAllSpansOnChannel(data.self, false, END_OP.AckAll, undefined);\n }\n });\n diagnosticsChannel.tracingChannel<AmqpChannelContext>(CHANNELS.AMQPLIB_NACK_ALL).start.subscribe(message => {\n const data = message as AmqpChannelContext;\n if (data.self) {\n endAllSpansOnChannel(data.self, true, END_OP.NackAll, data.arguments[0] as boolean | undefined);\n }\n });\n}\n\n/** Captures connection attributes on the connection object for span-time reads via `channel.connection`. */\nfunction subscribeConnect(): void {\n const channel = diagnosticsChannel.tracingChannel<OrchestrionChannelContext>(CHANNELS.AMQPLIB_CONNECT);\n // A `start` subscriber is required for orchestrion to wrap the callback-style `connect` at all.\n channel.start.subscribe(NOOP);\n channel.asyncEnd.subscribe(message => {\n const data = message as OrchestrionChannelContext;\n const conn = data.result as ConnectionLike | undefined;\n if (!conn || typeof conn !== 'object') {\n return;\n }\n conn[CONNECTION_ATTRIBUTES] = {\n ...getConnectionAttributesFromUrl(data.arguments?.[0]),\n ...getConnectionAttributesFromServer(conn),\n };\n });\n}\n\nfunction handleAck(data: AmqpChannelContext, isRejected: boolean, endOperation: EndOp): void {\n const channel = data.self;\n if (!channel) {\n return;\n }\n const message = data.arguments[0] as ConsumeMessage | undefined;\n if (!message) {\n return;\n }\n\n // `reject(message, requeue)` carries requeue in arg 1; `ack`/`nack` carry `allUpTo` in arg 1.\n const allUpToOrRequeue = data.arguments[1] as boolean | undefined;\n const requeue = data.arguments[2] as boolean | undefined;\n const requeueResolved = endOperation === END_OP.Reject ? allUpToOrRequeue : requeue;\n\n const spansNotEnded = channel[CHANNEL_SPANS_NOT_ENDED] ?? [];\n const msgIndex = spansNotEnded.findIndex(msgDetails => msgDetails.msg === message);\n if (msgIndex < 0) {\n // Not tracked (e.g. the user acked the same message twice) — end the stored span directly.\n endConsumerSpan(message, isRejected, endOperation, requeueResolved);\n } else if (endOperation !== END_OP.Reject && allUpToOrRequeue) {\n for (let i = 0; i <= msgIndex; i++) {\n // oxlint-disable-next-line typescript/no-non-null-assertion -- `i` is bounded by the loop\n endConsumerSpan(spansNotEnded[i]!.msg, isRejected, endOperation, requeueResolved);\n }\n spansNotEnded.splice(0, msgIndex + 1);\n } else {\n endConsumerSpan(message, isRejected, endOperation, requeueResolved);\n spansNotEnded.splice(msgIndex, 1);\n }\n}\n\nfunction ensureChannelState(channel: ChannelLike): void {\n if (Object.prototype.hasOwnProperty.call(channel, CHANNEL_SPANS_NOT_ENDED)) {\n return;\n }\n\n channel[CHANNEL_SPANS_NOT_ENDED] = [];\n channel[CHANNEL_CONSUMER_INFO] = new Map();\n channel[CHANNEL_PENDING_CONSUMERS] = [];\n\n const timer = setInterval(() => checkConsumeTimeoutOnChannel(channel), CONSUME_TIMEOUT_MS);\n timer.unref?.();\n channel[CHANNEL_CONSUME_TIMEOUT_TIMER] = timer;\n\n // End outstanding spans and stop the timer when the channel goes away (replaces patching `emit`).\n // amqplib emits 'close' after 'error', but we clear in both to avoid leaking the interval (which\n // pins the channel via its closure) should a version or edge case ever skip the trailing 'close'.\n if (typeof channel.on === 'function') {\n channel.on('close', () => {\n endAllSpansOnChannel(channel, true, END_OP.ChannelClosed, undefined);\n clearConsumeTimeoutTimer(channel);\n });\n channel.on('error', () => {\n endAllSpansOnChannel(channel, true, END_OP.ChannelError, undefined);\n clearConsumeTimeoutTimer(channel);\n });\n }\n}\n\n/** Stops and clears the per-channel consume-timeout interval. Idempotent. */\nfunction clearConsumeTimeoutTimer(channel: ChannelLike): void {\n const activeTimer = channel[CHANNEL_CONSUME_TIMEOUT_TIMER];\n if (activeTimer) {\n clearInterval(activeTimer);\n channel[CHANNEL_CONSUME_TIMEOUT_TIMER] = undefined;\n }\n}\n\nfunction checkConsumeTimeoutOnChannel(channel: ChannelLike): void {\n const currentTime = timestampInSeconds();\n const spansNotEnded = channel[CHANNEL_SPANS_NOT_ENDED] ?? [];\n let i: number;\n for (i = 0; i < spansNotEnded.length; i++) {\n // oxlint-disable-next-line typescript/no-non-null-assertion -- `i` is bounded by the loop\n const currMessage = spansNotEnded[i]!;\n const timeFromConsumeMs = (currentTime - currMessage.timeOfConsume) * 1000;\n if (timeFromConsumeMs < CONSUME_TIMEOUT_MS) {\n break;\n }\n endConsumerSpan(currMessage.msg, null, END_OP.InstrumentationTimeout, true);\n }\n spansNotEnded.splice(0, i);\n}\n\nfunction endAllSpansOnChannel(\n channel: ChannelLike,\n isRejected: boolean,\n operation: EndOp,\n requeue: boolean | undefined,\n): void {\n const spansNotEnded = channel[CHANNEL_SPANS_NOT_ENDED] ?? [];\n spansNotEnded.forEach(msgDetails => {\n endConsumerSpan(msgDetails.msg, isRejected, operation, requeue);\n });\n channel[CHANNEL_SPANS_NOT_ENDED] = [];\n}\n\nfunction endConsumerSpan(\n message: ConsumeMessage,\n isRejected: boolean | null,\n operation: EndOp,\n requeue: boolean | undefined,\n): void {\n const storedSpan = message[MESSAGE_STORED_SPAN];\n if (!storedSpan) {\n return;\n }\n if (isRejected !== false) {\n storedSpan.setStatus({\n code: SPAN_STATUS_ERROR,\n message:\n operation !== END_OP.ChannelClosed && operation !== END_OP.ChannelError\n ? `${operation} called on message${\n requeue === true ? ' with requeue' : requeue === false ? ' without requeue' : ''\n }`\n : operation,\n });\n }\n storedSpan.end();\n message[MESSAGE_STORED_SPAN] = undefined;\n}\n\n/** Starts an inactive PRODUCER span and propagates its trace into the publish `options.headers`. */\nfunction startPublishSpan(data: AmqpChannelContext): Span {\n const exchangeArg = data.arguments[0];\n const routingKeyArg = data.arguments[1];\n const exchange = typeof exchangeArg === 'string' ? exchangeArg : '';\n const routingKey = typeof routingKeyArg === 'string' ? routingKeyArg : '';\n let options = data.arguments[3] as PublishOptions | undefined;\n\n const client = getClient();\n const destination = resolveDestination(exchange, routingKey);\n const streamedName = destination\n ? `${MESSAGING_OPERATION_VALUE_SEND} ${destination}`\n : MESSAGING_OPERATION_VALUE_SEND;\n\n const span = startInactiveSpan({\n name: client && hasSpanStreamingEnabled(client) ? streamedName : `publish ${normalizeExchange(exchange)}`,\n attributes: {\n [SENTRY_OP]: QUEUE_PUBLISH,\n [SENTRY_KIND]: 'producer',\n ...getStoredConnectionAttributes(data.self),\n [MESSAGING_DESTINATION_NAME]: destination,\n [MESSAGING_RABBITMQ_DESTINATION_ROUTING_KEY]: routingKey,\n [MESSAGING_OPERATION_NAME]: MESSAGING_OPERATION_VALUE_SEND,\n [MESSAGING_OPERATION_TYPE]: MESSAGING_OPERATION_VALUE_SEND,\n [MESSAGING_MESSAGE_ID]: options?.messageId as string | undefined,\n [MESSAGING_MESSAGE_CONVERSATION_ID]: options?.correlationId as string | undefined,\n [SENTRY_ORIGIN]: PUBLISHER_ORIGIN,\n },\n });\n\n if (!options || typeof options !== 'object') {\n options = {};\n data.arguments[3] = options;\n }\n const headers = options.headers && typeof options.headers === 'object' ? options.headers : (options.headers = {});\n const traceData = getTraceData({ span });\n if (traceData['sentry-trace']) {\n headers['sentry-trace'] = traceData['sentry-trace'];\n }\n if (traceData.baggage) {\n headers['baggage'] = traceData.baggage;\n }\n\n return span;\n}\n\n/** Starts an inactive CONSUMER (process) span carrying the amqplib messaging attributes. */\nfunction startConsumeSpan(queue: string | undefined, msg: ConsumeMessage, channel: ChannelLike): Span {\n const client = getClient();\n const destination = resolveDestination(msg.fields?.exchange, msg.fields?.routingKey);\n const streamedName = destination\n ? `${MESSAGING_OPERATION_VALUE_PROCESS} ${destination}`\n : MESSAGING_OPERATION_VALUE_PROCESS;\n\n return startInactiveSpan({\n name:\n client && hasSpanStreamingEnabled(client)\n ? streamedName\n : queue\n ? `${queue} ${MESSAGING_OPERATION_VALUE_PROCESS}`\n : MESSAGING_OPERATION_VALUE_PROCESS,\n attributes: {\n [SENTRY_OP]: QUEUE_PROCESS,\n [SENTRY_KIND]: 'consumer',\n [SENTRY_SEGMENT_NAME_SOURCE]: 'component',\n ...getStoredConnectionAttributes(channel),\n [MESSAGING_DESTINATION_NAME]: destination,\n [MESSAGING_RABBITMQ_DESTINATION_ROUTING_KEY]: msg.fields?.routingKey,\n [MESSAGING_OPERATION_NAME]: MESSAGING_OPERATION_VALUE_PROCESS,\n [MESSAGING_OPERATION_TYPE]: MESSAGING_OPERATION_VALUE_PROCESS,\n [MESSAGING_MESSAGE_ID]: msg.properties?.messageId as string | undefined,\n [MESSAGING_MESSAGE_CONVERSATION_ID]: msg.properties?.correlationId as string | undefined,\n [SENTRY_ORIGIN]: CONSUMER_ORIGIN,\n },\n });\n}\n\n/**\n * Reads the connection attributes stashed by the `connect` channel, falling back to the live\n * connection's server product so `messaging.system` is populated even when the connection was\n * established before the integration ran.\n */\nfunction getStoredConnectionAttributes(channel: ChannelLike | undefined): SpanAttributes {\n const connection = channel?.connection;\n const stored = connection?.[CONNECTION_ATTRIBUTES];\n if (stored) {\n return stored;\n }\n const product = connection?.serverProperties?.product ?? connection?.connection?.serverProperties?.product;\n if (typeof product === 'string' && product) {\n return { [MESSAGING_SYSTEM]: product.toLowerCase() };\n }\n return {};\n}\n\nfunction getConnectionAttributesFromServer(conn: ConnectionLike): SpanAttributes {\n const product = conn.serverProperties?.product ?? conn.connection?.serverProperties?.product;\n if (typeof product === 'string' && product) {\n return { [MESSAGING_SYSTEM]: product.toLowerCase() };\n }\n return {};\n}\n\nfunction getConnectionAttributesFromUrl(url: unknown): SpanAttributes {\n const attributes: SpanAttributes = {\n // The only protocol supported by the instrumented library.\n [NETWORK_PROTOCOL_VERSION]: '0.9.1',\n };\n\n const resolvedUrl = url || 'amqp://localhost';\n if (typeof resolvedUrl === 'object') {\n const connectOptions = resolvedUrl as { protocol?: string; hostname?: string; port?: number };\n const protocol = getProtocol(connectOptions.protocol);\n const hostname = getHostname(connectOptions.hostname);\n const port = getPort(connectOptions.port, protocol);\n\n attributes[NETWORK_PROTOCOL_NAME] = protocol;\n\n attributes[SERVER_ADDRESS] = hostname;\n attributes[SERVER_PORT] = port;\n } else if (typeof resolvedUrl === 'string') {\n const censoredUrl = censorPassword(resolvedUrl);\n // oxlint-disable-next-line sdk/no-unfiltered-url-attributes -- AMQP connection URL, not an HTTP request URL\n attributes[URL_FULL] = censoredUrl;\n\n try {\n const urlParts = new URL(censoredUrl);\n const protocol = getProtocol(urlParts.protocol);\n const hostname = getHostname(urlParts.hostname);\n const port = getPort(urlParts.port ? parseInt(urlParts.port, 10) : undefined, protocol);\n\n attributes[NETWORK_PROTOCOL_NAME] = protocol;\n\n attributes[SERVER_ADDRESS] = hostname;\n attributes[SERVER_PORT] = port;\n } catch {\n // best-effort: a malformed url simply yields fewer connection attributes\n }\n }\n return attributes;\n}\n\n/**\n * The default exchange has no name and binds every queue under a key equal to the queue's own name, so\n * a routing key used with it is the queue name. On a named exchange the routing key is per-message\n * (`order.created.12345`), so only the exchange is used.\n *\n * @see https://www.rabbitmq.com/docs/exchanges#default-exchange\n * @internal Exported for tests; every scenario publishes through `sendToQueue`.\n */\nexport function resolveDestination(exchange: string | undefined, routingKey: string | undefined): string | undefined {\n // `undefined` so an absent destination is omitted rather than reported as an empty string.\n return exchange || routingKey || undefined;\n}\n\nfunction normalizeExchange(exchangeName: string): string {\n return exchangeName !== '' ? exchangeName : '<default>';\n}\n\nfunction censorPassword(url: string): string {\n return url.replace(/:[^:@/]*@/, ':***@');\n}\n\nfunction getPort(portFromUrl: number | undefined, resolvedProtocol: string): number {\n // Mimics amqplib's own defaulting; the resolved protocol is upper-cased.\n return portFromUrl || (resolvedProtocol === 'AMQP' ? 5672 : 5671);\n}\n\nfunction getProtocol(protocolFromUrl: string | undefined): string {\n const resolvedProtocol = protocolFromUrl || 'amqp';\n const noEndingColon = resolvedProtocol.endsWith(':')\n ? resolvedProtocol.substring(0, resolvedProtocol.length - 1)\n : resolvedProtocol;\n return noEndingColon.toUpperCase();\n}\n\nfunction getHostname(hostnameFromUrl: string | undefined): string {\n // An empty hostname is forwarded to `net`, which defaults it to localhost.\n return hostnameFromUrl || 'localhost';\n}\n\nfunction getHeaderAsString(headers: Record<string, unknown> | undefined, key: string): string | undefined {\n const value = headers?.[key];\n if (value == null) {\n return undefined;\n }\n return Array.isArray(value) ? String(value[0]) : String(value);\n}\n\n/**\n * Diagnostics-channel-based `amqplib` integration.\n *\n * Subscribes to the `orchestrion:amqplib:*` diagnostics_channels that Sentry's code transform\n * injects into `amqplib`'s channel/connection methods. Requires the Sentry runtime hook or\n * bundler plugin to be active.\n */\nexport const amqplibIntegration = defineIntegration(_amqplibIntegration);\n"],"mappings":";;;;;;;;;AAwCA,MAAM,mBAAmB;AAEzB,MAAM,mBAAmB;AACzB,MAAM,kBAAkB;AAExB,MAAM,oCAAoC;AAC1C,MAAM,iCAAiC;AAIvC,MAAM,qBAAqB;AAG3B,MAAM,SAAS;CACb,KAAK;CACL,QAAQ;CACR,QAAQ;CACR,MAAM;CACN,SAAS;CACT,eAAe;CACf,cAAc;CACd,wBAAwB;AAC1B;AAIA,MAAM,sBAAqC,OAAO,oCAAoC;AACtF,MAAM,0BAAyC,OAAO,wCAAwC;AAC9F,MAAM,gCAA+C,OAAO,8CAA8C;AAC1G,M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,OAAO,YAAY,cAAc,KAAA;AACnC;AAEA,SAAS,kBAAkB,cAA8B;CACvD,OAAO,iBAAiB,KAAK,eAAe;AAC9C;AAEA,SAAS,eAAe,KAAqB;CAC3C,OAAO,IAAI,QAAQ,aAAa,OAAO;AACzC;AAEA,SAAS,QAAQ,aAAiC,kBAAkC;CAElF,OAAO,gBAAgB,qBAAqB,SAAS,OAAO;AAC9D;AAEA,SAAS,YAAY,iBAA6C;CAChE,MAAM,mBAAmB,mBAAmB;CAI5C,QAHsB,iBAAiB,SAAS,GAAG,IAC/C,iBAAiB,UAAU,GAAG,iBAAiB,SAAS,CAAC,IACzD,iBAAA,CACiB,YAAY;AACnC;AAEA,SAAS,YAAY,iBAA6C;CAEhE,OAAO,mBAAmB;AAC5B;AAEA,SAAS,kBAAkB,SAA8C,KAAiC;CACxG,MAAM,QAAQ,UAAU;CACxB,IAAI,SAAS,MACX;CAEF,OAAO,MAAM,QAAQ,KAAK,IAAI,OAAO,MAAM,EAAE,IAAI,OAAO,KAAK;AAC/D;;;;;;;;AASA,MAAa,qBAAqB,kBAAkB,mBAAmB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"anthropic.js","names":["diagnosticsChannel.tracingChannel","diagnosticsChannel\n .tracingChannel"],"sources":["../../../src/integrations/anthropic.ts"],"sourcesContent":["import { GEN_AI_REQUEST_MODEL, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span, SpanAttributeValue } from '@sentry/core';\nimport { defineIntegration, getActiveSpan, getClient, hasSpanStreamingEnabled, startInactiveSpan } from '@sentry/core';\nimport { getGenAiSpanOp, getRequestSignal, markCancelledIfAborted, resolveGenAiCallRecording } from '../ai/core/utils';\nimport { wrapApiPromiseResponse } from '../ai/core/apiPromise';\nimport { type GenAiSpanResult, runGenAiSpanEnd, runGenAiSpanStart } from '../ai/core/span-hooks';\nimport { addPrivateRequestAttributes, extractRequestAttributes } from '../ai/anthropic-ai';\nimport { ANTHROPIC_AI_ORIGIN } from '../ai/anthropic-ai/constants';\nimport { addResponseAttributes, getProviderName } from '../ai/anthropic-ai/utils';\nimport { instrumentAsyncIterableStream, instrumentMessageStream } from '../ai/anthropic-ai/streaming';\nimport { instrumentSessionToolRunner, instrumentToolRunner } from '../ai/anthropic-ai/tool-runner';\nimport type { AnthropicAiCallInfo, AnthropicAiOptions, AnthropicAiResponse } from '../ai/anthropic-ai/types';\nimport { shouldSkipAiProviderSpan } from '../ai/pi-ai/providers';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { anthropicAiModuleNames } from '../orchestrion/config/anthropic-ai';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\n\n// Same name as the OTel integration by design, so the OTel 'Anthropic_AI'\n// integration is deduplicated out of the default set.\nconst INTEGRATION_NAME = 'Anthropic_AI' as const;\n\n// The recording decision is made once, when the span starts, in the caller's async context.\ntype AnthropicChannelContext = OrchestrionChannelContext & {\n _sentryRecordOutputs?: boolean;\n _sentryOnSpanEnd?: (result: GenAiSpanResult<unknown>) => void;\n};\n\n// `stream` determines how the span is ended\nconst INSTRUMENTED_CHANNELS = [\n { channel: CHANNELS.ANTHROPIC_CHAT, operation: 'chat', stream: 'async-iterable' },\n {\n channel: CHANNELS.ANTHROPIC_MESSAGES_STREAM,\n operation: 'chat',\n stream: 'message-stream',\n },\n] as const;\n\ntype StreamMode = (typeof INSTRUMENTED_CHANNELS)[number]['stream'];\n\nconst _anthropicAIIntegration = ((options: AnthropicAiOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, anthropicAiModuleNames, instrumentAnthropic, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\n// Since 0.134 `@anthropic-ai/sdk` traces itself through the global OTel tracer provider, which duplicates our\n// spans. Only turned off once our channels subscribe, so an app we do not instrument keeps the SDK's spans.\n// A value the user set wins.\nfunction disableNativeTracing(): void {\n try {\n process.env.ANTHROPIC_OPEN_TELEMETRY ??= 'false';\n } catch {\n // `process` is absent (edge runtimes) or env access is gated (Deno without `--allow-env`).\n }\n}\n\nfunction instrumentAnthropic(options: AnthropicAiOptions): void {\n disableNativeTracing();\n for (const { channel, operation, stream } of INSTRUMENTED_CHANNELS) {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<AnthropicChannelContext>(channel),\n data => createGenAiSpan(data, operation, options, stream),\n {\n beforeSpanEnd: (span, data) => {\n if ('error' in data) {\n markCancelledIfAborted(span, getRequestSignal(data.arguments?.[1]));\n }\n addResponseAttributes(span, data.result as AnthropicAiResponse, !!data._sentryRecordOutputs);\n data._sentryOnSpanEnd?.('error' in data ? { error: data.error } : { response: data.result });\n },\n deferSpanEnd: ({ span, data, end }) =>\n wrapThreadStreamRequest(span, data, end) ||\n wrapApiPromiseResponse(\n data.result,\n response => {\n data.result = response;\n if (!wrapStreamResult(span, data, stream)) {\n end();\n }\n },\n end,\n ) ||\n wrapStreamResult(span, data, stream),\n },\n );\n }\n\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.ANTHROPIC_TOOL_RUNNER)\n .end.subscribe(message => {\n instrumentToolRunner((message as OrchestrionChannelContext).result, options);\n });\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.ANTHROPIC_SESSION_TOOL_RUNNER)\n .end.subscribe(message => {\n instrumentSessionToolRunner((message as OrchestrionChannelContext).self, options);\n });\n // On `start`, because `_start()` sends the first request before it returns.\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.ANTHROPIC_THREAD_STREAM)\n .start.subscribe(message => {\n const data = message as OrchestrionChannelContext;\n const stream = data.self as ThreadStream | undefined;\n if (isMessageStream(stream) && stream.controller?.signal) {\n // `_start(create, params, options)`: each `create()` gets only the stream's own signal, which doesn't carry\n // the reason a caller's signal fired with.\n threadStreams.set(stream.controller.signal, { stream, callerSignal: getRequestSignal(data.arguments?.[2]) });\n }\n });\n}\n\n/**\n * Build the span for an instrumented call.\n * Returning `undefined` opts the payload out so no span is opened.\n */\nfunction createGenAiSpan(\n data: AnthropicChannelContext,\n operation: 'chat',\n options: AnthropicAiOptions,\n stream: StreamMode,\n): Span | undefined {\n const args = data.arguments ?? [];\n\n if (shouldSkipAiProviderSpan(INTEGRATION_NAME)) {\n return undefined;\n }\n\n // `messages.stream()` internally calls the instrumented `messages.create({ stream: true })` tagged with\n // a `stream` helper-method header. The messages-stream channel already covers it, so skip the nested\n // create to avoid a duplicate span. Only the non-beta helper is on that channel, though:\n // `beta.messages.stream()` and the streaming tool runner send the same header with no span covering\n // them, so the header alone is not enough. Skip only while a stream-helper span of ours is active.\n const requestOptions = args[1] as { headers?: unknown } | undefined;\n if (isStreamHelperRequest(requestOptions?.headers) && isInsideStreamHelperSpan()) {\n return undefined;\n }\n\n const params = typeof args[0] === 'object' && args[0] !== null ? (args[0] as Record<string, unknown>) : undefined;\n\n const call: AnthropicAiCallInfo = { operation, request: params };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n data._sentryRecordOutputs = recordOutputs;\n\n const attributes = extractRequestAttributes(args, operation, recordInputs, getProviderName(data.self));\n const model = (attributes[GEN_AI_REQUEST_MODEL] as string) || 'unknown';\n attributes[SENTRY_ORIGIN] = ANTHROPIC_AI_ORIGIN;\n const client = getClient();\n\n const span = startInactiveSpan({\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name: model !== 'unknown' || !(client && hasSpanStreamingEnabled(client)) ? `${operation} ${model}` : operation,\n op: getGenAiSpanOp(operation),\n attributes: attributes as Record<string, SpanAttributeValue>,\n });\n\n if (recordInputs && params) {\n addPrivateRequestAttributes(span, params);\n }\n\n runGenAiSpanStart(options, span, call);\n data._sentryOnSpanEnd = result => runGenAiSpanEnd(options, span, call, result);\n\n if (stream === 'message-stream') {\n streamHelperSpans.add(span);\n }\n\n return span;\n}\n\nconst STREAM_HELPER_METHOD_HEADER = 'x-stainless-helper-method';\n\n/** The spans opened for the messages-stream channel, i.e. for `messages.stream()` calls. */\nconst streamHelperSpans = new WeakSet<Span>();\n\n/**\n * Whether the active span is one this integration opened for `messages.stream()`. The helper's\n * internal `create` runs inside that span, so this is what tells it apart from the beta helper and\n * the tool runner, which send the same header but are not on the messages-stream channel.\n */\nfunction isInsideStreamHelperSpan(): boolean {\n const activeSpan = getActiveSpan();\n return !!activeSpan && streamHelperSpans.has(activeSpan);\n}\n\n/**\n * Whether request options carry the header the SDK's `messages.stream()` helper puts on its internal\n * `create` call. The SDK sent it as `X-Stainless-Helper-Method` up to 0.105 and lowercase since 0.106, and\n * HTTP header names are case-insensitive either way, so match without regard to case. The headers\n * arrive as a plain object; a `Headers` instance is handled for completeness.\n */\nfunction isStreamHelperRequest(headers: unknown): boolean {\n if (!headers || typeof headers !== 'object') {\n return false;\n }\n\n if (typeof (headers as Headers).get === 'function') {\n return (headers as Headers).get(STREAM_HELPER_METHOD_HEADER) === 'stream';\n }\n\n return Object.entries(headers as Record<string, unknown>).some(\n ([name, value]) => name.toLowerCase() === STREAM_HELPER_METHOD_HEADER && value === 'stream',\n );\n}\n\ntype AsyncIterableStream = { [Symbol.asyncIterator]: () => AsyncIterator<unknown> };\ntype MessageStreamEmitter = { on: (...args: unknown[]) => void };\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterableStream {\n return !!value && typeof (value as AsyncIterableStream)[Symbol.asyncIterator] === 'function';\n}\n\nfunction isMessageStream(value: unknown): value is MessageStreamEmitter {\n return !!value && typeof (value as MessageStreamEmitter).on === 'function';\n}\n\ntype ThreadStream = MessageStreamEmitter & { ended?: boolean; controller?: { signal?: AbortSignal } };\n\n/**\n * The streams of threads and tool runners on 1.2+, by the signal they send each `create()` call with. Such a\n * stream parses the response itself, so the `create()` result is never parsed and never ends its span.\n */\nconst threadStreams = new WeakMap<AbortSignal, { stream: ThreadStream; callerSignal: AbortSignal | undefined }>();\n\n/**\n * End the span of a thread stream's `create()` call from the stream once the response arrives. A thread may\n * retry a rejected call, so a failed call ends its own span and only the one that succeeds reads the stream.\n */\nfunction wrapThreadStreamRequest(span: Span, data: AnthropicChannelContext, end: (error?: unknown) => void): boolean {\n const signal = (data.arguments?.[1] as { signal?: AbortSignal } | undefined)?.signal;\n const threadStream = signal && threadStreams.get(signal);\n const request = data.result as { _responseProps?: () => Promise<unknown> } | undefined;\n // A finished stream sends no more requests, so a later call with its signal is the caller's own.\n if (!threadStream || threadStream.stream.ended || typeof request?._responseProps !== 'function') {\n return false;\n }\n const { stream, callerSignal } = threadStream;\n\n const recordOutputs = !!data._sentryRecordOutputs;\n // Not `asResponse()`, which on 1.x also ends the SDK's own span when the user turned its tracing on.\n void request._responseProps().then(\n () => {\n // Only a rejected attempt is retried, so nothing else may claim this stream.\n threadStreams.delete(signal);\n instrumentMessageStream(stream, span, recordOutputs, callerSignal, data._sentryOnSpanEnd);\n },\n error => {\n // An abort is not a failed request. The stream still emits 'end', which sets the status from the caller's signal.\n if (signal.aborted) {\n instrumentMessageStream(stream, span, recordOutputs, callerSignal, data._sentryOnSpanEnd);\n } else {\n end(error);\n }\n },\n );\n return true;\n}\n\n/**\n * Hand span-ending ownership to a streamed result: returns `true` to skip the normal `beforeSpanEnd`,\n * `false` for non-streaming results (which end via `beforeSpanEnd`).\n *\n * - `async-iterable`: patch the `Stream`'s async iterator in place so `instrumentAsyncIterableStream` ends\n * the span when iteration finishes.\n * - `message-stream`: `instrumentMessageStream` attaches `'message'`/`'error'`/`'end'` listeners that end the span.\n */\nfunction wrapStreamResult(span: Span, data: AnthropicChannelContext, stream: StreamMode): boolean {\n const recordOutputs = !!data._sentryRecordOutputs;\n const result = data.result;\n\n if (stream === 'async-iterable' && isAsyncIterable(result)) {\n const iterate = result[Symbol.asyncIterator].bind(result);\n const instrumented = instrumentAsyncIterableStream(\n { [Symbol.asyncIterator]: iterate },\n span,\n recordOutputs,\n data._sentryOnSpanEnd,\n );\n result[Symbol.asyncIterator] = () => instrumented;\n return true;\n }\n\n if (stream === 'message-stream' && isMessageStream(result)) {\n instrumentMessageStream(result, span, recordOutputs, getRequestSignal(data.arguments?.[1]), data._sentryOnSpanEnd);\n return true;\n }\n\n return false;\n}\n\n/**\n * Diagnostics-channel-based Anthropic integration. Subscribes to the `orchestrion:@anthropic-ai/sdk:*`\n * diagnostics_channels injected into the SDK's chat (`messages`/`completions`/beta `messages`) and\n * `messages.stream()` methods, so it requires the Sentry runtime hook or bundler plugin.\n */\nexport const anthropicAIIntegration = defineIntegration(_anthropicAIIntegration);\n"],"mappings":";;;;;;;;;;;;;;;;;AAsBA,MAAM,mBAAmB;AASzB,MAAM,wBAAwB,CAC5B;CAAE,SAAS,SAAS;CAAgB,WAAW;CAAQ,QAAQ;AAAiB,GAChF;CACE,SAAS,SAAS;CAClB,WAAW;CACX,QAAQ;AACV,CACF;AAIA,MAAM,4BAA4B,UAA8B,CAAC,MAAM;CACrE,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,wBAAwB,qBAAqB,CAAC,OAAO,CAAC;EACjG;CACF;AACF;AAKA,SAAS,uBAA6B;CACpC,IAAI;;EACF,CAAA,eAAA,QAAQ,IAAA,CAAI,6BAAA,aAAA,2BAA6B;CAC3C,QAAQ,CAER;AACF;AAEA,SAAS,oBAAoB,SAAmC;CAC9D,qBAAqB;CACrB,KAAK,MAAM,EAAE,SAAS,WAAW,YAAY,uBAC3C,yBACEA,eAA2D,OAAO,IAClE,SAAQ,gBAAgB,MAAM,WAAW,SAAS,MAAM,GACxD;EACE,gBAAgB,MAAM,SAAS;GAC7B,IAAI,WAAW,MACb,uBAAuB,MAAM,iBAAiB,KAAK,YAAY,EAAE,CAAC;GAEpE,sBAAsB,MAAM,KAAK,QAA+B,CAAC,CAAC,KAAK,oBAAoB;GAC3F,KAAK,mBAAmB,WAAW,OAAO,EAAE,OAAO,KAA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AAI,CAAC,gBAAgB,aAAa,OAAO,SAAS,OAAO,SAAS,mBAAmB,YACnF,OAAO;CAET,MAAM,EAAE,QAAQ,iBAAiB;CAEjC,MAAM,gBAAgB,CAAC,CAAC,KAAK;CAExB,QAAQ,eAAe,CAAC,CAAC,WACtB;EAEJ,cAAc,OAAO,MAAM;EAC3B,wBAAwB,QAAQ,MAAM,eAAe,cAAc,KAAK,gBAAgB;CAC1F,IACA,UAAS;EAEP,IAAI,OAAO,SACT,wBAAwB,QAAQ,MAAM,eAAe,cAAc,KAAK,gBAAgB;OAExF,IAAI,KAAK;CAEb,CACF;CACA,OAAO;AACT;;;;;;;;;AAUA,SAAS,iBAAiB,MAAY,MAA+B,QAA6B;CAChG,MAAM,gBAAgB,CAAC,CAAC,KAAK;CAC7B,MAAM,SAAS,KAAK;CAEpB,IAAI,WAAW,oBAAoB,gBAAgB,MAAM,GAAG;EAC1D,MAAM,UAAU,OAAO,OAAO,cAAc,CAAC,KAAK,MAAM;EACxD,MAAM,eAAe,8BACnB,GAAG,OAAO,gBAAgB,QAAQ,GAClC,MACA,eACA,KAAK,gBACP;EACA,OAAO,OAAO,uBAAuB;EACrC,OAAO;CACT;CAEA,IAAI,WAAW,oBAAoB,gBAAgB,MAAM,GAAG;EAC1D,wBAAwB,QAAQ,MAAM,eAAe,iBAAiB,KAAK,YAAY,EAAE,GAAG,KAAK,gBAAgB;EACjH,OAAO;CACT;CAEA,OAAO;AACT;;;;;;AAOA,MAAa,yBAAyB,kBAAkB,uBAAuB"}
|
|
1
|
+
{"version":3,"file":"anthropic.js","names":["diagnosticsChannel.tracingChannel","diagnosticsChannel\n .tracingChannel"],"sources":["../../../src/integrations/anthropic.ts"],"sourcesContent":["import { GEN_AI_REQUEST_MODEL, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport type { IntegrationFn, Span, SpanAttributeValue } from '@sentry/core';\nimport { defineIntegration, getActiveSpan, getClient, hasSpanStreamingEnabled, startInactiveSpan } from '@sentry/core';\nimport { getGenAiSpanOp, getRequestSignal, markCancelledIfAborted, resolveGenAiCallRecording } from '../ai/core/utils';\nimport { wrapApiPromiseResponse } from '../ai/core/apiPromise';\nimport { type GenAiSpanResult, runGenAiSpanEnd, runGenAiSpanStart } from '../ai/core/span-hooks';\nimport { addPrivateRequestAttributes, extractRequestAttributes } from '../ai/anthropic-ai';\nimport { ANTHROPIC_AI_ORIGIN } from '../ai/anthropic-ai/constants';\nimport { addResponseAttributes, getProviderName } from '../ai/anthropic-ai/utils';\nimport { instrumentAsyncIterableStream, instrumentMessageStream } from '../ai/anthropic-ai/streaming';\nimport { instrumentSessionToolRunner, instrumentToolRunner } from '../ai/anthropic-ai/tool-runner';\nimport type { AnthropicAiCallInfo, AnthropicAiOptions, AnthropicAiResponse } from '../ai/anthropic-ai/types';\nimport { shouldSkipAiProviderSpan } from '../ai/pi-ai/providers';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { anthropicAiModuleNames } from '../orchestrion/config/anthropic-ai';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\n\n// Same name as the OTel integration by design, so the OTel 'Anthropic_AI'\n// integration is deduplicated out of the default set.\nconst INTEGRATION_NAME = 'Anthropic_AI' as const;\n\n// The recording decision is made once, when the span starts, in the caller's async context.\ntype AnthropicChannelContext = OrchestrionChannelContext & {\n _sentryRecordOutputs?: boolean;\n _sentryOnSpanEnd?: (result: GenAiSpanResult<unknown>) => void;\n};\n\n// `stream` determines how the span is ended\nconst INSTRUMENTED_CHANNELS = [\n { channel: CHANNELS.ANTHROPIC_CHAT, operation: 'chat', stream: 'async-iterable' },\n {\n channel: CHANNELS.ANTHROPIC_MESSAGES_STREAM,\n operation: 'chat',\n stream: 'message-stream',\n },\n] as const;\n\ntype StreamMode = (typeof INSTRUMENTED_CHANNELS)[number]['stream'];\n\nconst _anthropicAIIntegration = ((options: AnthropicAiOptions = {}) => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, anthropicAiModuleNames, instrumentAnthropic, [options]);\n },\n };\n}) satisfies IntegrationFn;\n\n// Since 0.134 `@anthropic-ai/sdk` traces itself through the global OTel tracer provider, which duplicates our\n// spans. Only turned off once our channels subscribe, so an app we do not instrument keeps the SDK's spans.\n// A value the user set wins.\nfunction disableNativeTracing(): void {\n try {\n process.env.ANTHROPIC_OPEN_TELEMETRY ??= 'false';\n } catch {\n // `process` is absent (edge runtimes) or env access is gated (Deno without `--allow-env`).\n }\n}\n\nfunction instrumentAnthropic(options: AnthropicAiOptions): void {\n disableNativeTracing();\n for (const { channel, operation, stream } of INSTRUMENTED_CHANNELS) {\n bindTracingChannelToSpan(\n diagnosticsChannel.tracingChannel<AnthropicChannelContext>(channel),\n data => createGenAiSpan(data, operation, options, stream),\n {\n beforeSpanEnd: (span, data) => {\n if ('error' in data) {\n markCancelledIfAborted(span, getRequestSignal(data.arguments?.[1]));\n }\n addResponseAttributes(span, data.result as AnthropicAiResponse, !!data._sentryRecordOutputs);\n data._sentryOnSpanEnd?.('error' in data ? { error: data.error } : { response: data.result });\n },\n deferSpanEnd: ({ span, data, end }) =>\n wrapThreadStreamRequest(span, data, end) ||\n wrapApiPromiseResponse(\n data.result,\n response => {\n data.result = response;\n if (!wrapStreamResult(span, data, stream)) {\n end();\n }\n },\n end,\n ) ||\n wrapStreamResult(span, data, stream),\n },\n );\n }\n\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.ANTHROPIC_TOOL_RUNNER)\n .end.subscribe(message => {\n instrumentToolRunner((message as OrchestrionChannelContext).result, options);\n });\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.ANTHROPIC_SESSION_TOOL_RUNNER)\n .end.subscribe(message => {\n instrumentSessionToolRunner((message as OrchestrionChannelContext).self, options);\n });\n // On `start`, because `_start()` sends the first request before it returns.\n diagnosticsChannel\n .tracingChannel<OrchestrionChannelContext>(CHANNELS.ANTHROPIC_THREAD_STREAM)\n .start.subscribe(message => {\n const data = message as OrchestrionChannelContext;\n const stream = data.self as ThreadStream | undefined;\n if (isMessageStream(stream) && stream.controller?.signal) {\n // `_start(create, params, options)`: each `create()` gets only the stream's own signal, which doesn't carry\n // the reason a caller's signal fired with.\n threadStreams.set(stream.controller.signal, { stream, callerSignal: getRequestSignal(data.arguments?.[2]) });\n }\n });\n}\n\n/**\n * Build the span for an instrumented call.\n * Returning `undefined` opts the payload out so no span is opened.\n */\nfunction createGenAiSpan(\n data: AnthropicChannelContext,\n operation: 'chat',\n options: AnthropicAiOptions,\n stream: StreamMode,\n): Span | undefined {\n const args = data.arguments ?? [];\n\n if (shouldSkipAiProviderSpan(INTEGRATION_NAME)) {\n return undefined;\n }\n\n // `messages.stream()` internally calls the instrumented `messages.create({ stream: true })` tagged with\n // a `stream` helper-method header. The messages-stream channel already covers it, so skip the nested\n // create to avoid a duplicate span. Only the non-beta helper is on that channel, though:\n // `beta.messages.stream()` and the streaming tool runner send the same header with no span covering\n // them, so the header alone is not enough. Skip only while a stream-helper span of ours is active.\n const requestOptions = args[1] as { headers?: unknown } | undefined;\n if (isStreamHelperRequest(requestOptions?.headers) && isInsideStreamHelperSpan()) {\n return undefined;\n }\n\n const params = typeof args[0] === 'object' && args[0] !== null ? (args[0] as Record<string, unknown>) : undefined;\n\n const call: AnthropicAiCallInfo = { operation, request: params };\n const { recordInputs, recordOutputs } = resolveGenAiCallRecording(options, call);\n data._sentryRecordOutputs = recordOutputs;\n\n const attributes = extractRequestAttributes(args, operation, recordInputs, getProviderName(data.self));\n const model = (attributes[GEN_AI_REQUEST_MODEL] as string) || 'unknown';\n attributes[SENTRY_ORIGIN] = ANTHROPIC_AI_ORIGIN;\n const client = getClient();\n\n const span = startInactiveSpan({\n // With span streaming, omit the `'unknown'` model sentinel so the name stays low-cardinality.\n name: model !== 'unknown' || !(client && hasSpanStreamingEnabled(client)) ? `${operation} ${model}` : operation,\n op: getGenAiSpanOp(operation),\n attributes: attributes as Record<string, SpanAttributeValue>,\n });\n\n if (recordInputs && params) {\n addPrivateRequestAttributes(span, params);\n }\n\n runGenAiSpanStart(options, span, call);\n data._sentryOnSpanEnd = result => runGenAiSpanEnd(options, span, call, result);\n\n if (stream === 'message-stream') {\n streamHelperSpans.add(span);\n }\n\n return span;\n}\n\nconst STREAM_HELPER_METHOD_HEADER = 'x-stainless-helper-method';\n\n/** The spans opened for the messages-stream channel, i.e. for `messages.stream()` calls. */\nconst streamHelperSpans = new WeakSet<Span>();\n\n/**\n * Whether the active span is one this integration opened for `messages.stream()`. The helper's\n * internal `create` runs inside that span, so this is what tells it apart from the beta helper and\n * the tool runner, which send the same header but are not on the messages-stream channel.\n */\nfunction isInsideStreamHelperSpan(): boolean {\n const activeSpan = getActiveSpan();\n return !!activeSpan && streamHelperSpans.has(activeSpan);\n}\n\n/**\n * Whether request options carry the header the SDK's `messages.stream()` helper puts on its internal\n * `create` call. The SDK sent it as `X-Stainless-Helper-Method` up to 0.105 and lowercase since 0.106, and\n * HTTP header names are case-insensitive either way, so match without regard to case. The headers\n * arrive as a plain object; a `Headers` instance is handled for completeness.\n */\nfunction isStreamHelperRequest(headers: unknown): boolean {\n if (!headers || typeof headers !== 'object') {\n return false;\n }\n\n if (typeof (headers as Headers).get === 'function') {\n return (headers as Headers).get(STREAM_HELPER_METHOD_HEADER) === 'stream';\n }\n\n return Object.entries(headers as Record<string, unknown>).some(\n ([name, value]) => name.toLowerCase() === STREAM_HELPER_METHOD_HEADER && value === 'stream',\n );\n}\n\ntype AsyncIterableStream = { [Symbol.asyncIterator]: () => AsyncIterator<unknown> };\ntype MessageStreamEmitter = { on: (...args: unknown[]) => void };\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterableStream {\n return !!value && typeof (value as AsyncIterableStream)[Symbol.asyncIterator] === 'function';\n}\n\nfunction isMessageStream(value: unknown): value is MessageStreamEmitter {\n return !!value && typeof (value as MessageStreamEmitter).on === 'function';\n}\n\ntype ThreadStream = MessageStreamEmitter & { ended?: boolean; controller?: { signal?: AbortSignal } };\n\n/**\n * The streams of threads and tool runners on 1.2+, by the signal they send each `create()` call with. Such a\n * stream parses the response itself, so the `create()` result is never parsed and never ends its span.\n */\nconst threadStreams = new WeakMap<AbortSignal, { stream: ThreadStream; callerSignal: AbortSignal | undefined }>();\n\n/**\n * End the span of a thread stream's `create()` call from the stream once the response arrives. A thread may\n * retry a rejected call, so a failed call ends its own span and only the one that succeeds reads the stream.\n */\nfunction wrapThreadStreamRequest(span: Span, data: AnthropicChannelContext, end: (error?: unknown) => void): boolean {\n const signal = (data.arguments?.[1] as { signal?: AbortSignal } | undefined)?.signal;\n const threadStream = signal && threadStreams.get(signal);\n const request = data.result as { _responseProps?: () => Promise<unknown> } | undefined;\n // A finished stream sends no more requests, so a later call with its signal is the caller's own.\n if (!threadStream || threadStream.stream.ended || typeof request?._responseProps !== 'function') {\n return false;\n }\n const { stream, callerSignal } = threadStream;\n\n const recordOutputs = !!data._sentryRecordOutputs;\n // Not `asResponse()`, which on 1.x also ends the SDK's own span when the user turned its tracing on.\n void request._responseProps().then(\n () => {\n // Only a rejected attempt is retried, so nothing else may claim this stream.\n threadStreams.delete(signal);\n instrumentMessageStream(stream, span, recordOutputs, callerSignal, data._sentryOnSpanEnd);\n },\n error => {\n // An abort is not a failed request. The stream still emits 'end', which sets the status from the caller's signal.\n // The thread emits 'abort' and 'end' only after it awaits `_responseProps()` itself, which is after this handler,\n // so the listeners cannot miss them.\n if (signal.aborted) {\n instrumentMessageStream(stream, span, recordOutputs, callerSignal, data._sentryOnSpanEnd);\n } else {\n end(error);\n }\n },\n );\n return true;\n}\n\n/**\n * Hand span-ending ownership to a streamed result: returns `true` to skip the normal `beforeSpanEnd`,\n * `false` for non-streaming results (which end via `beforeSpanEnd`).\n *\n * - `async-iterable`: patch the `Stream`'s async iterator in place so `instrumentAsyncIterableStream` ends\n * the span when iteration finishes.\n * - `message-stream`: `instrumentMessageStream` attaches `'message'`/`'error'`/`'end'` listeners that end the span.\n */\nfunction wrapStreamResult(span: Span, data: AnthropicChannelContext, stream: StreamMode): boolean {\n const recordOutputs = !!data._sentryRecordOutputs;\n const result = data.result;\n\n if (stream === 'async-iterable' && isAsyncIterable(result)) {\n const iterate = result[Symbol.asyncIterator].bind(result);\n const instrumented = instrumentAsyncIterableStream(\n { [Symbol.asyncIterator]: iterate },\n span,\n recordOutputs,\n data._sentryOnSpanEnd,\n );\n result[Symbol.asyncIterator] = () => instrumented;\n return true;\n }\n\n if (stream === 'message-stream' && isMessageStream(result)) {\n instrumentMessageStream(result, span, recordOutputs, getRequestSignal(data.arguments?.[1]), data._sentryOnSpanEnd);\n return true;\n }\n\n return false;\n}\n\n/**\n * Diagnostics-channel-based Anthropic integration. Subscribes to the `orchestrion:@anthropic-ai/sdk:*`\n * diagnostics_channels injected into the SDK's chat (`messages`/`completions`/beta `messages`) and\n * `messages.stream()` methods, so it requires the Sentry runtime hook or bundler plugin.\n */\nexport const anthropicAIIntegration = defineIntegration(_anthropicAIIntegration);\n"],"mappings":";;;;;;;;;;;;;;;;;AAsBA,MAAM,mBAAmB;AASzB,MAAM,wBAAwB,CAC5B;CAAE,SAAS,SAAS;CAAgB,WAAW;CAAQ,QAAQ;AAAiB,GAChF;CACE,SAAS,SAAS;CAClB,WAAW;CACX,QAAQ;AACV,CACF;AAIA,MAAM,4BAA4B,UAA8B,CAAC,MAAM;CACrE,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,wBAAwB,qBAAqB,CAAC,OAAO,CAAC;EACjG;CACF;AACF;AAKA,SAAS,uBAA6B;CACpC,IAAI;;EACF,CAAA,eAAA,QAAQ,IAAA,CAAI,6BAAA,aAAA,2BAA6B;CAC3C,QAAQ,CAER;AACF;AAEA,SAAS,oBAAoB,SAAmC;CAC9D,qBAAqB;CACrB,KAAK,MAAM,EAAE,SAA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,uBAAuB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tracer.js","names":[],"sources":["../../../../src/integrations/bullmq/tracer.ts"],"sourcesContent":["import { MESSAGING_SYSTEM, SENTRY_LINK_TYPE, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { QUEUE, QUEUE_PROCESS, QUEUE_PUBLISH } from '@sentry/conventions/op';\nimport type { SpanAttributes } from '@sentry/core';\nimport { getCurrentScope, startInactiveSpan, startNewTrace } from '@sentry/core';\nimport { SentryBullMQSpan, toSentryAttributes } from './span';\nimport type { SpanOptions, TelemetrySpan, Tracer, SentryContext } from './types';\n\n// BullMQ span names follow OTel messaging semconv: \"{operation} {destination}\"\n// e.g. \"add myQueue\", \"addBulk myQueue\", \"process myQueue\", \"addFlow myQueue\"\nconst PRODUCER_OPERATIONS = new Set(['add', 'addbulk', 'addflow', 'addbulkflows']);\nconst CONSUMER_OPERATIONS = new Set(['process']);\n\nfunction getOperation(name: string): string {\n return name.split(' ')[0]!.toLowerCase();\n}\n\nfunction getOpFromSpanName(name: string): string {\n const operation = getOperation(name);\n\n if (CONSUMER_OPERATIONS.has(operation)) {\n return QUEUE_PROCESS;\n }\n\n if (PRODUCER_OPERATIONS.has(operation)) {\n return QUEUE_PUBLISH;\n }\n\n return QUEUE;\n}\n\nfunction getOriginFromSpanName(name: string): string {\n const operation = getOperation(name);\n\n if (CONSUMER_OPERATIONS.has(operation)) {\n return 'auto.queue.bullmq.consumer';\n }\n\n if (PRODUCER_OPERATIONS.has(operation)) {\n return 'auto.queue.bullmq.producer';\n }\n\n return 'auto.queue.bullmq';\n}\n\nexport class SentryBullMQTracer implements Tracer<SentryContext> {\n public startSpan(name: string, options?: SpanOptions, context?: SentryContext): TelemetrySpan {\n const op = getOpFromSpanName(name);\n const origin = getOriginFromSpanName(name);\n\n const attributes: SpanAttributes = {\n [SENTRY_OP]: op,\n [SENTRY_ORIGIN]: origin,\n [MESSAGING_SYSTEM]: 'bullmq',\n ...(options?.attributes && toSentryAttributes(options.attributes)),\n };\n\n // Internal operations such as `moveStalledJobsToWait` run on timers. Without a parent, each tick would start a new root span.\n const span =\n op === QUEUE_PROCESS\n ? startNewTrace(() => startInactiveSpan({ name, attributes }))\n : startInactiveSpan({ name, attributes, onlyIfParent: op === QUEUE });\n\n if (context?.producerSpanContext) {\n const producerSpanCtx = {\n traceId: context.producerSpanContext.traceId,\n spanId: context.producerSpanContext.spanId,\n traceFlags: context.producerSpanContext.sampled ? 1 : 0,\n };\n\n span.addLink({\n context: producerSpanCtx,\n attributes: {\n [SENTRY_LINK_TYPE]: 'message_origin',\n },\n });\n }\n\n return new SentryBullMQSpan(span, getCurrentScope());\n }\n}\n"],"mappings":";;;;;AASA,MAAM,sCAAsB,IAAI,IAAI;CAAC;CAAO;CAAW;CAAW;AAAc,CAAC;AACjF,MAAM,sCAAsB,IAAI,IAAI,CAAC,SAAS,CAAC;AAE/C,SAAS,aAAa,MAAsB;
|
|
1
|
+
{"version":3,"file":"tracer.js","names":[],"sources":["../../../../src/integrations/bullmq/tracer.ts"],"sourcesContent":["import { MESSAGING_SYSTEM, SENTRY_LINK_TYPE, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { QUEUE, QUEUE_PROCESS, QUEUE_PUBLISH } from '@sentry/conventions/op';\nimport type { SpanAttributes } from '@sentry/core';\nimport { getCurrentScope, startInactiveSpan, startNewTrace } from '@sentry/core';\nimport { SentryBullMQSpan, toSentryAttributes } from './span';\nimport type { SpanOptions, TelemetrySpan, Tracer, SentryContext } from './types';\n\n// BullMQ span names follow OTel messaging semconv: \"{operation} {destination}\"\n// e.g. \"add myQueue\", \"addBulk myQueue\", \"process myQueue\", \"addFlow myQueue\"\nconst PRODUCER_OPERATIONS = new Set(['add', 'addbulk', 'addflow', 'addbulkflows']);\nconst CONSUMER_OPERATIONS = new Set(['process']);\n\nfunction getOperation(name: string): string {\n // oxlint-disable-next-line typescript/no-non-null-assertion -- `split` always returns at least one item\n return name.split(' ')[0]!.toLowerCase();\n}\n\nfunction getOpFromSpanName(name: string): string {\n const operation = getOperation(name);\n\n if (CONSUMER_OPERATIONS.has(operation)) {\n return QUEUE_PROCESS;\n }\n\n if (PRODUCER_OPERATIONS.has(operation)) {\n return QUEUE_PUBLISH;\n }\n\n return QUEUE;\n}\n\nfunction getOriginFromSpanName(name: string): string {\n const operation = getOperation(name);\n\n if (CONSUMER_OPERATIONS.has(operation)) {\n return 'auto.queue.bullmq.consumer';\n }\n\n if (PRODUCER_OPERATIONS.has(operation)) {\n return 'auto.queue.bullmq.producer';\n }\n\n return 'auto.queue.bullmq';\n}\n\nexport class SentryBullMQTracer implements Tracer<SentryContext> {\n public startSpan(name: string, options?: SpanOptions, context?: SentryContext): TelemetrySpan {\n const op = getOpFromSpanName(name);\n const origin = getOriginFromSpanName(name);\n\n const attributes: SpanAttributes = {\n [SENTRY_OP]: op,\n [SENTRY_ORIGIN]: origin,\n [MESSAGING_SYSTEM]: 'bullmq',\n ...(options?.attributes && toSentryAttributes(options.attributes)),\n };\n\n // Internal operations such as `moveStalledJobsToWait` run on timers. Without a parent, each tick would start a new root span.\n const span =\n op === QUEUE_PROCESS\n ? startNewTrace(() => startInactiveSpan({ name, attributes }))\n : startInactiveSpan({ name, attributes, onlyIfParent: op === QUEUE });\n\n if (context?.producerSpanContext) {\n const producerSpanCtx = {\n traceId: context.producerSpanContext.traceId,\n spanId: context.producerSpanContext.spanId,\n traceFlags: context.producerSpanContext.sampled ? 1 : 0,\n };\n\n span.addLink({\n context: producerSpanCtx,\n attributes: {\n [SENTRY_LINK_TYPE]: 'message_origin',\n },\n });\n }\n\n return new SentryBullMQSpan(span, getCurrentScope());\n }\n}\n"],"mappings":";;;;;AASA,MAAM,sCAAsB,IAAI,IAAI;CAAC;CAAO;CAAW;CAAW;AAAc,CAAC;AACjF,MAAM,sCAAsB,IAAI,IAAI,CAAC,SAAS,CAAC;AAE/C,SAAS,aAAa,MAAsB;CAE1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_]*)?|\.\d[\d_]*)(?:e[+-]?[\d_]+)?)(?![\w$])/iy;
|
|
4
|
+
const FORMAT_RE = /FORMAT(?!\s*[=<>!])(?:\s|\/\*|--|#)/iy;
|
|
5
|
+
const FORMAT_IDENTIFIER_RE = /(?:\b(?:INTO|TABLE|FROM|JOIN|ON|SELECT|PREWHERE|WHERE|HAVING|QUALIFY|AND|OR|NOT|BY|AS)|[,.=<>(])\s*$/i;
|
|
6
|
+
/**
|
|
7
|
+
* ClickHouse SQL: `"` quotes an identifier as in `standard`, but `\` escapes the next character, `#`
|
|
8
|
+
* starts a line comment, block comments nest, and `$$…$$` heredocs open a literal. Numbers can have
|
|
9
|
+
* `_` separators.
|
|
10
|
+
*/
|
|
11
|
+
const CLICKHOUSE_SQL_RULES = {
|
|
12
|
+
hashComments: true,
|
|
13
|
+
nestedComments: true,
|
|
14
|
+
backslashEscapes: true,
|
|
15
|
+
dollarQuote: /\$\w*\$/y,
|
|
16
|
+
matchLiteral(sql, start) {
|
|
17
|
+
if (isIdentifierChar(sql[start - 1]) || sql[start - 1] === "?") return 0;
|
|
18
|
+
NUMBER_RE.lastIndex = start;
|
|
19
|
+
return NUMBER_RE.exec(sql)?.[0].length ?? 0;
|
|
20
|
+
},
|
|
21
|
+
isInlineData(sql, start, out) {
|
|
22
|
+
if (isIdentifierChar(sql[start - 1])) return false;
|
|
23
|
+
FORMAT_RE.lastIndex = start;
|
|
24
|
+
if (!FORMAT_RE.test(sql)) return false;
|
|
25
|
+
const before = out.join("");
|
|
26
|
+
return /^[\s;]*INSERT\b/i.test(before) && !FORMAT_IDENTIFIER_RE.test(before);
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
export { CLICKHOUSE_SQL_RULES };
|
|
30
|
+
|
|
31
|
+
//# sourceMappingURL=clickhouse-sql.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"clickhouse-sql.js","names":[],"sources":["../../../src/integrations/clickhouse-sql.ts"],"sourcesContent":["import type { SqlLexerRules } from '../utils/sql';\nimport { isIdentifierChar } from '../utils/sql';\n\nconst NUMBER_RE = /-?(?:0x[\\dA-F_]+|0b[01_]+|(?:\\d[\\d_]*(?:\\.[\\d_]*)?|\\.\\d[\\d_]*)(?:e[+-]?[\\d_]+)?)(?![\\w$])/iy;\n// A comparison operator can follow a column named `format`, but cannot start a format name.\nconst FORMAT_RE = /FORMAT(?!\\s*[=<>!])(?:\\s|\\/\\*|--|#)/iy;\n// After one of these tokens, `format` is a table, column or alias name.\nconst FORMAT_IDENTIFIER_RE =\n /(?:\\b(?:INTO|TABLE|FROM|JOIN|ON|SELECT|PREWHERE|WHERE|HAVING|QUALIFY|AND|OR|NOT|BY|AS)|[,.=<>(])\\s*$/i;\n\n/**\n * ClickHouse SQL: `\"` quotes an identifier as in `standard`, but `\\` escapes the next character, `#`\n * starts a line comment, block comments nest, and `$$…$$` heredocs open a literal. Numbers can have\n * `_` separators.\n */\nexport const CLICKHOUSE_SQL_RULES: SqlLexerRules = {\n hashComments: true,\n nestedComments: true,\n backslashEscapes: true,\n dollarQuote: /\\$\\w*\\$/y,\n matchLiteral(sql, start) {\n if (isIdentifierChar(sql[start - 1]) || sql[start - 1] === '?') {\n return 0;\n }\n NUMBER_RE.lastIndex = start;\n return NUMBER_RE.exec(sql)?.[0].length ?? 0;\n },\n // Everything after the FORMAT clause of an INSERT is inline data. That includes `INSERT ... SELECT`,\n // where the `input()` table function reads that data.\n isInlineData(sql, start, out) {\n if (isIdentifierChar(sql[start - 1])) {\n return false;\n }\n FORMAT_RE.lastIndex = start;\n if (!FORMAT_RE.test(sql)) {\n return false;\n }\n const before = out.join('');\n return /^[\\s;]*INSERT\\b/i.test(before) && !FORMAT_IDENTIFIER_RE.test(before);\n },\n};\n"],"mappings":";;AAGA,MAAM,YAAY;AAElB,MAAM,YAAY;AAElB,MAAM,uBACJ;;;;;;AAOF,MAAa,uBAAsC;CACjD,cAAc;CACd,gBAAgB;CAChB,kBAAkB;CAClB,aAAa;CACb,aAAa,KAAK,OAAO;EACvB,IAAI,iBAAiB,IAAI,QAAQ,EAAE,KAAK,IAAI,QAAQ,OAAO,KACzD,OAAO;EAET,UAAU,YAAY;EACtB,OAAO,UAAU,KAAK,GAAG,CAAC,GAAG,EAAE,CAAC,UAAU;CAC5C;CAGA,aAAa,KAAK,OAAO,KAAK;EAC5B,IAAI,iBAAiB,IAAI,QAAQ,EAAE,GACjC,OAAO;EAET,UAAU,YAAY;EACtB,IAAI,CAAC,UAAU,KAAK,GAAG,GACrB,OAAO;EAET,MAAM,SAAS,IAAI,KAAK,EAAE;EAC1B,OAAO,mBAAmB,KAAK,MAAM,KAAK,CAAC,qBAAqB,KAAK,MAAM;CAC7E;AACF"}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { tracingChannel } from "../utils/diagnosticsChannel.js";
|
|
2
|
+
import { CHANNELS } from "../orchestrion/channels.js";
|
|
3
|
+
import { clickhouseModuleNames } from "../orchestrion/config/clickhouse.js";
|
|
4
|
+
import { invokeOrchestrionInstrumentation } from "../orchestrion/instrumentation.js";
|
|
5
|
+
import { bindTracingChannelToSpan } from "../tracing-channel.js";
|
|
6
|
+
import { getLowCardinalitySqlSpanName, getSqlQueryAttributes } from "../utils/sql.js";
|
|
7
|
+
import { CLICKHOUSE_SQL_RULES } from "./clickhouse-sql.js";
|
|
8
|
+
import { DB_COLLECTION_NAME, DB_NAMESPACE, DB_OPERATION_NAME, DB_QUERY_SUMMARY, DB_SYSTEM_NAME, DB_USER, SENTRY_KIND, SENTRY_OP, SENTRY_ORIGIN, SERVER_ADDRESS, SERVER_PORT } from "@sentry/conventions/attributes";
|
|
9
|
+
import { defineIntegration, startInactiveSpan } from "@sentry/core";
|
|
10
|
+
import { DB } from "@sentry/conventions/op";
|
|
11
|
+
// src/integrations/clickhouse.ts
|
|
12
|
+
const INTEGRATION_NAME = "ClickHouse";
|
|
13
|
+
const ORIGIN = "auto.db.clickhouse";
|
|
14
|
+
const DB_SYSTEM_CLICKHOUSE = "clickhouse";
|
|
15
|
+
const _clickhouseIntegration = (() => {
|
|
16
|
+
return {
|
|
17
|
+
name: INTEGRATION_NAME,
|
|
18
|
+
setup(client) {
|
|
19
|
+
invokeOrchestrionInstrumentation(client, clickhouseModuleNames, instrumentClickhouse, []);
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
});
|
|
23
|
+
function instrumentClickhouse() {
|
|
24
|
+
const channels = [
|
|
25
|
+
[CHANNELS.CLICKHOUSE_QUERY, "query"],
|
|
26
|
+
[CHANNELS.CLICKHOUSE_COMMAND, "command"],
|
|
27
|
+
[CHANNELS.CLICKHOUSE_EXEC, "exec"],
|
|
28
|
+
[CHANNELS.CLICKHOUSE_INSERT, "insert"],
|
|
29
|
+
[CHANNELS.CLICKHOUSE_WEB_QUERY, "query"],
|
|
30
|
+
[CHANNELS.CLICKHOUSE_WEB_COMMAND, "command"],
|
|
31
|
+
[CHANNELS.CLICKHOUSE_WEB_EXEC, "exec"],
|
|
32
|
+
[CHANNELS.CLICKHOUSE_WEB_INSERT, "insert"],
|
|
33
|
+
[CHANNELS.CLICKHOUSE_COMMON_QUERY, "query"],
|
|
34
|
+
[CHANNELS.CLICKHOUSE_COMMON_COMMAND, "command"],
|
|
35
|
+
[CHANNELS.CLICKHOUSE_COMMON_EXEC, "exec"],
|
|
36
|
+
[CHANNELS.CLICKHOUSE_COMMON_INSERT, "insert"]
|
|
37
|
+
];
|
|
38
|
+
for (const [channelName, method] of channels) bindTracingChannelToSpan(tracingChannel(channelName), (data) => {
|
|
39
|
+
const params = data.arguments[0];
|
|
40
|
+
if (method === "insert" && Array.isArray(params?.values) && params.values.length === 0) return;
|
|
41
|
+
const attributes = {
|
|
42
|
+
[SENTRY_OP]: DB,
|
|
43
|
+
[SENTRY_KIND]: "client",
|
|
44
|
+
[SENTRY_ORIGIN]: ORIGIN,
|
|
45
|
+
...getConnectionAttributes(data.self?.connectionParams, params),
|
|
46
|
+
...method === "insert" ? getInsertAttributes(params) : getSqlQueryAttributes(typeof params?.query === "string" ? params.query : void 0, CLICKHOUSE_SQL_RULES)
|
|
47
|
+
};
|
|
48
|
+
return startInactiveSpan({
|
|
49
|
+
name: getLowCardinalitySqlSpanName(attributes, DB_SYSTEM_CLICKHOUSE),
|
|
50
|
+
attributes,
|
|
51
|
+
onlyIfParent: true
|
|
52
|
+
});
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
function getInsertAttributes(params) {
|
|
56
|
+
const table = typeof params?.table === "string" && params.table ? params.table : void 0;
|
|
57
|
+
return {
|
|
58
|
+
[DB_OPERATION_NAME]: "INSERT",
|
|
59
|
+
[DB_COLLECTION_NAME]: table,
|
|
60
|
+
[DB_QUERY_SUMMARY]: table ? `INSERT ${table}` : "INSERT"
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
function getConnectionAttributes(connectionParams, params) {
|
|
64
|
+
const url = connectionParams?.url;
|
|
65
|
+
const user = params?.auth?.username ?? connectionParams?.auth?.username ?? connectionParams?.username;
|
|
66
|
+
return {
|
|
67
|
+
[DB_SYSTEM_NAME]: DB_SYSTEM_CLICKHOUSE,
|
|
68
|
+
[DB_NAMESPACE]: connectionParams?.database,
|
|
69
|
+
[DB_USER]: typeof user === "string" ? user : void 0,
|
|
70
|
+
[SERVER_ADDRESS]: url?.hostname || void 0,
|
|
71
|
+
[SERVER_PORT]: url ? getServerPort(url) : void 0
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
function getServerPort(url) {
|
|
75
|
+
if (url.port) return Number(url.port);
|
|
76
|
+
return url.protocol === "https:" ? 443 : 80;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Diagnostics-channel-based `@clickhouse/client` and `@clickhouse/client-web` integration.
|
|
80
|
+
*
|
|
81
|
+
* Subscribes to the channels Sentry's code transform injects into `ClickHouseClient`'s `query`,
|
|
82
|
+
* `command`, `exec` and `insert` methods, and emits a `db` span for each call. Requires the Sentry
|
|
83
|
+
* runtime hook or bundler plugin to be active.
|
|
84
|
+
*/
|
|
85
|
+
const clickhouseIntegration = defineIntegration(_clickhouseIntegration);
|
|
86
|
+
export { clickhouseIntegration };
|
|
87
|
+
|
|
88
|
+
//# sourceMappingURL=clickhouse.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"clickhouse.js","names":["diagnosticsChannel.tracingChannel"],"sources":["../../../src/integrations/clickhouse.ts"],"sourcesContent":["import * as diagnosticsChannel from '../utils/diagnosticsChannel';\nimport {\n DB_COLLECTION_NAME,\n DB_NAMESPACE,\n DB_OPERATION_NAME,\n DB_QUERY_SUMMARY,\n DB_SYSTEM_NAME,\n DB_USER,\n SENTRY_KIND,\n SENTRY_OP,\n SENTRY_ORIGIN,\n SERVER_ADDRESS,\n SERVER_PORT,\n} from '@sentry/conventions/attributes';\nimport { DB } from '@sentry/conventions/op';\nimport type { IntegrationFn, SpanAttributes } from '@sentry/core';\nimport { defineIntegration, startInactiveSpan } from '@sentry/core';\nimport type { OrchestrionChannelContext } from '../orchestrion/types';\nimport { CHANNELS } from '../orchestrion/channels';\nimport { clickhouseModuleNames } from '../orchestrion/config/clickhouse';\nimport { invokeOrchestrionInstrumentation } from '../orchestrion/instrumentation';\nimport { bindTracingChannelToSpan } from '../tracing-channel';\nimport { getLowCardinalitySqlSpanName, getSqlQueryAttributes } from '../utils/sql';\nimport { CLICKHOUSE_SQL_RULES } from './clickhouse-sql';\n\nconst INTEGRATION_NAME = 'ClickHouse' as const;\nconst ORIGIN = 'auto.db.clickhouse';\nconst DB_SYSTEM_CLICKHOUSE = 'clickhouse';\n\ntype ClickHouseMethod = 'query' | 'command' | 'exec' | 'insert';\n\n// The parts of `ClickHouseClient`'s `connectionParams` the span reads. `>=1.10` moved the username\n// into `auth` (which can hold an access token instead); older versions keep it at the top level.\ninterface ClickHouseConnectionParams {\n url?: URL;\n database?: string;\n username?: string;\n auth?: { username?: string };\n}\n\ninterface ClickHouseClient {\n connectionParams?: ClickHouseConnectionParams;\n}\n\n// `query`/`command`/`exec` take `{ query }`, `insert` takes `{ table, values }`. Every method accepts a\n// per-call `auth` override.\ninterface ClickHouseParams {\n query?: unknown;\n table?: unknown;\n values?: unknown;\n auth?: { username?: unknown };\n}\n\n/** Context orchestrion attaches to the channels wrapping `ClickHouseClient`'s methods. */\ninterface ClickHouseChannelContext extends OrchestrionChannelContext {\n arguments: [ClickHouseParams?, ...unknown[]];\n self?: ClickHouseClient;\n}\n\nconst _clickhouseIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n invokeOrchestrionInstrumentation(client, clickhouseModuleNames, instrumentClickhouse, []);\n },\n };\n}) satisfies IntegrationFn;\n\nfunction instrumentClickhouse(): void {\n // The Node and web clients publish the same calls under their own module names. Before 1.23.0,\n // both use `@clickhouse/client-common`.\n const channels: [string, ClickHouseMethod][] = [\n [CHANNELS.CLICKHOUSE_QUERY, 'query'],\n [CHANNELS.CLICKHOUSE_COMMAND, 'command'],\n [CHANNELS.CLICKHOUSE_EXEC, 'exec'],\n [CHANNELS.CLICKHOUSE_INSERT, 'insert'],\n [CHANNELS.CLICKHOUSE_WEB_QUERY, 'query'],\n [CHANNELS.CLICKHOUSE_WEB_COMMAND, 'command'],\n [CHANNELS.CLICKHOUSE_WEB_EXEC, 'exec'],\n [CHANNELS.CLICKHOUSE_WEB_INSERT, 'insert'],\n [CHANNELS.CLICKHOUSE_COMMON_QUERY, 'query'],\n [CHANNELS.CLICKHOUSE_COMMON_COMMAND, 'command'],\n [CHANNELS.CLICKHOUSE_COMMON_EXEC, 'exec'],\n [CHANNELS.CLICKHOUSE_COMMON_INSERT, 'insert'],\n ];\n\n for (const [channelName, method] of channels) {\n // Failed calls only get an error status on the span. The error still rejects to the caller, who\n // decides whether to handle it, so it isn't captured here.\n bindTracingChannelToSpan(diagnosticsChannel.tracingChannel<ClickHouseChannelContext>(channelName), data => {\n const params = data.arguments[0];\n // `insert` with an empty array returns without sending a request.\n if (method === 'insert' && Array.isArray(params?.values) && params.values.length === 0) {\n return undefined;\n }\n\n const attributes: SpanAttributes = {\n [SENTRY_OP]: DB,\n [SENTRY_KIND]: 'client',\n [SENTRY_ORIGIN]: ORIGIN,\n ...getConnectionAttributes(data.self?.connectionParams, params),\n ...(method === 'insert'\n ? getInsertAttributes(params)\n : getSqlQueryAttributes(typeof params?.query === 'string' ? params.query : undefined, CLICKHOUSE_SQL_RULES)),\n };\n\n return startInactiveSpan({\n name: getLowCardinalitySqlSpanName(attributes, DB_SYSTEM_CLICKHOUSE),\n attributes,\n onlyIfParent: true,\n });\n });\n }\n}\n\n// `insert` builds its `INSERT INTO <table> FORMAT <format>` statement internally, so the span is\n// described from the target table instead of a statement.\nfunction getInsertAttributes(params: ClickHouseParams | undefined): SpanAttributes {\n const table = typeof params?.table === 'string' && params.table ? params.table : undefined;\n return {\n [DB_OPERATION_NAME]: 'INSERT',\n [DB_COLLECTION_NAME]: table,\n [DB_QUERY_SUMMARY]: table ? `INSERT ${table}` : 'INSERT',\n };\n}\n\nfunction getConnectionAttributes(\n connectionParams: ClickHouseConnectionParams | undefined,\n params: ClickHouseParams | undefined,\n): SpanAttributes {\n const url = connectionParams?.url;\n const user = params?.auth?.username ?? connectionParams?.auth?.username ?? connectionParams?.username;\n return {\n [DB_SYSTEM_NAME]: DB_SYSTEM_CLICKHOUSE,\n [DB_NAMESPACE]: connectionParams?.database,\n [DB_USER]: typeof user === 'string' ? user : undefined,\n [SERVER_ADDRESS]: url?.hostname || undefined,\n [SERVER_PORT]: url ? getServerPort(url) : undefined,\n };\n}\n\n// The client talks HTTP(S), so a URL without an explicit port uses the protocol's default.\nfunction getServerPort(url: URL): number {\n if (url.port) {\n return Number(url.port);\n }\n return url.protocol === 'https:' ? 443 : 80;\n}\n\n/**\n * Diagnostics-channel-based `@clickhouse/client` and `@clickhouse/client-web` integration.\n *\n * Subscribes to the channels Sentry's code transform injects into `ClickHouseClient`'s `query`,\n * `command`, `exec` and `insert` methods, and emits a `db` span for each call. Requires the Sentry\n * runtime hook or bundler plugin to be active.\n */\nexport const clickhouseIntegration = defineIntegration(_clickhouseIntegration);\n"],"mappings":";;;;;;;;;;;AAyBA,MAAM,mBAAmB;AACzB,MAAM,SAAS;AACf,MAAM,uBAAuB;AAgC7B,MAAM,gCAAgC;CACpC,OAAO;EACL,MAAM;EACN,MAAM,QAAQ;GACZ,iCAAiC,QAAQ,uBAAuB,sBAAsB,CAAC,CAAC;EAC1F;CACF;AACF;AAEA,SAAS,uBAA6B;CAGpC,MAAM,WAAyC;EAC7C,CAAC,SAAS,kBAAkB,OAAO;EACnC,CAAC,SAAS,oBAAoB,SAAS;EACvC,CAAC,SAAS,iBAAiB,MAAM;EACjC,CAAC,SAAS,mBAAmB,QAAQ;EACrC,CAAC,SAAS,sBAAsB,OAAO;EACvC,CAAC,SAAS,wBAAwB,SAAS;EAC3C,CAAC,SAAS,qBAAqB,MAAM;EACrC,CAAC,SAAS,uBAAuB,QAAQ;EACzC,CAAC,SAAS,yBAAyB,OAAO;EAC1C,CAAC,SAAS,2BAA2B,SAAS;EAC9C,CAAC,SAAS,wBAAwB,MAAM;EACxC,CAAC,SAAS,0BAA0B,QAAQ;CAC9C;CAEA,KAAK,MAAM,CAAC,aAAa,WAAW,UAGlC,yBAAyBA,eAA4D,WAAW,IAAG,SAAQ;EACzG,MAAM,SAAS,KAAK,UAAU;EAE9B,IAAI,WAAW,YAAY,MAAM,QAAQ,QAAQ,MAAM,KAAK,OAAO,OAAO,WAAW,GACnF;EAGF,MAAM,aAA6B;IAChC,YAAY;IACZ,cAAc;IACd,gBAAgB;GACjB,GAAG,wBAAwB,KAAK,MAAM,kBAAkB,MAAM;GAC9D,GAAI,WAAW,WACX,oBAAoB,MAAM,IAC1B,sBAAsB,OAAO,QAAQ,UAAU,WAAW,OAAO,QAAQ,KAAA,GAAW,oBAAoB;EAC9G;EAEA,OAAO,kBAAkB;GACvB,MAAM,6BAA6B,YAAY,oBAAoB;GACnE;GACA,cAAc;EAChB,CAAC;CACH,CAAC;AAEL;AAIA,SAAS,oBAAoB,QAAsD;CACjF,MAAM,QAAQ,OAAO,QAAQ,UAAU,YAAY,OAAO,QAAQ,OAAO,QAAQ,KAAA;CACjF,OAAO;GACJ,oBAAoB;GACpB,qBAAqB;GACrB,mBAAmB,QAAQ,UAAU,UAAU;CAClD;AACF;AAEA,SAAS,wBACP,kBACA,QACgB;CAChB,MAAM,MAAM,kBAAkB;CAC9B,MAAM,OAAO,QAAQ,MAAM,YAAY,kBAAkB,MAAM,YAAY,kBAAkB;CAC7F,OAAO;GACJ,iBAAiB;GACjB,eAAe,kBAAkB;GACjC,UAAU,OAAO,SAAS,WAAW,OAAO,KAAA;GAC5C,iBAAiB,KAAK,YAAY,KAAA;GAClC,cAAc,MAAM,cAAc,GAAG,IAAI,KAAA;CAC5C;AACF;AAGA,SAAS,cAAc,KAAkB;CACvC,IAAI,IAAI,MACN,OAAO,OAAO,IAAI,IAAI;CAExB,OAAO,IAAI,aAAa,WAAW,MAAM;AAC3C;;;;;;;;AASA,MAAa,wBAAwB,kBAAkB,sBAAsB"}
|
|
@@ -186,6 +186,7 @@ function getSpanForLayer(data, options) {
|
|
|
186
186
|
*/
|
|
187
187
|
function getMatchedLayerPath(layer) {
|
|
188
188
|
if (layer.route) return getLayerPath([layer.route.path]);
|
|
189
|
+
if (layer.rawPath !== void 0) return getLayerPath([layer.rawPath]);
|
|
189
190
|
return layer.keys?.length ? void 0 : layer.path || void 0;
|
|
190
191
|
}
|
|
191
192
|
function getLayerType(layer) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"instrumentation.js","names":[],"sources":["../../../../src/integrations/express/instrumentation.ts"],"sourcesContent":["import type * as diagnosticsChannel from 'node:diagnostics_channel';\nimport { HTTP_ROUTE, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { HANDLER, MIDDLEWARE, ROUTER } from '@sentry/conventions/op';\nimport type { Span } from '@sentry/core';\nimport {\n captureException,\n debug,\n getActiveSpan,\n getClient,\n getDefaultIsolationScope,\n getIsolationScope,\n hasSpanStreamingEnabled,\n REQUEST_HANDLER_SPAN_NAME_FALLBACK,\n ROUTER_SPAN_NAME_FALLBACK,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n stringMatchesSomePattern,\n withActiveSpan,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\nimport {\n getActualMatchedRoute,\n getConstructedRoute,\n getLayerPath,\n getLayerRegisteredPath,\n popLayerPath,\n pushLayerPath,\n setLayerRegisteredPath,\n} from './route';\nimport type {\n ExpressIntegrationOptions,\n ExpressLayer,\n ExpressLayerType,\n ExpressRequest,\n ExpressResponse,\n ExpressShouldHandleError,\n HandleChannelContext,\n MiddlewareError,\n RegistrationChannelContext,\n} from './types';\nimport { defaultShouldHandleError } from './utils';\nimport { isExpressErrorHandled, markExpressErrorHandled } from './error-handled';\nimport { setHttpServerSpanRouteAttribute } from '../../utils/setHttpServerSpanRouteAttribute';\n\nconst ORIGIN = 'auto.http.express';\n\n// `express.name`/`express.type` are Sentry-internal Express attributes (not part\n// of `@sentry/conventions`); kept in sync with `@sentry/core`'s OTel-derived\n// Express integration so the emitted spans are identical across both code paths.\nconst ATTR_EXPRESS_NAME = 'express.name';\nconst ATTR_EXPRESS_TYPE = 'express.type';\n\nconst EXPRESS_TYPE_TO_SPAN_OP: Record<string, string> = {\n middleware: MIDDLEWARE,\n request_handler: HANDLER,\n router: ROUTER,\n};\n\nconst NOOP = (): void => {};\n\nlet _isInstrumented = false;\n\nexport function instrumentExpress(\n options: ExpressIntegrationOptions,\n tracingChannel: typeof diagnosticsChannel.tracingChannel,\n): void {\n if (_isInstrumented) {\n return;\n }\n _isInstrumented = true;\n\n // Record each layer's registered path *pattern* as it is registered, so the\n // matched route can be reconstructed with its parameters intact at request\n // time. Only the `end` event matters (the layer is on the router's stack by\n // then); the others are required by the subscriber type, so no-op them.\n for (const channelName of [CHANNELS.EXPRESS_REGISTER, CHANNELS.ROUTER_REGISTER]) {\n tracingChannel<RegistrationChannelContext>(channelName).subscribe({\n start: NOOP,\n asyncStart: NOOP,\n asyncEnd: NOOP,\n error: NOOP,\n end: captureRegisteredLayerPath,\n });\n }\n\n for (const channelName of [CHANNELS.EXPRESS_HANDLE, CHANNELS.ROUTER_HANDLE]) {\n const channel = tracingChannel<HandleChannelContext>(channelName);\n\n bindTracingChannelToSpan(channel, data => getSpanForLayer(data, options), {\n beforeSpanEnd(_span, data) {\n data._sentryCleanup?.();\n },\n });\n\n // Pop the layer path and end the layer span when the layer hands off via\n // `next`. `asyncStart` fires when `next` is called and *before* the\n // downstream layer runs, so the per-request path chain reflects only the\n // current chain when each layer reconstructs its route, and each span covers\n // only its own layer. The `error` event captures throws at the layer level\n // (see `captureLayerError`), before any user error-handling middleware.\n channel.subscribe({\n start: NOOP,\n asyncEnd: NOOP,\n end: NOOP,\n error: data => captureLayerError(data, options.shouldHandleError),\n asyncStart: data => {\n popLayerPathForLayer(data);\n endLayerSpanOnNext(data);\n },\n });\n }\n}\n\n/**\n * Capture an error surfaced on a layer's `handle_request` channel — the throw\n * site, which runs before any user error-handling middleware.\n *\n * Each request's error is handled exactly once: the same error surfaces on every\n * parent layer's `error` event as it bubbles, and a user may also still call the\n * deprecated `setupExpressErrorHandler`. We mark the request the first time we\n * see it, so later layers and that middleware defer to this decision — the\n * integration is the single registered handler and its `shouldHandleError` wins.\n * This deliberately does not rely on `captureException`'s global dedup, which is\n * only set when an error is actually captured and so cannot express a\n * \"deliberately skipped\" decision (leaving the deprecated middleware free to\n * capture it and override `shouldHandleError`).\n *\n * `shouldHandleError` is the raw integration option: `false` disables capture\n * entirely, a function customizes the gate, and `undefined` falls back to\n * {@link defaultShouldHandleError}.\n */\nexport function captureLayerError(\n data: HandleChannelContext,\n shouldHandleError: ExpressShouldHandleError | undefined,\n): void {\n const error = data.error;\n\n // `next('route')` / `next('router')` are Express control-flow signals, not errors.\n if (!error || error === 'route' || error === 'router') {\n return;\n }\n\n // Take responsibility for this request's error exactly once (see the doc comment above). The marker\n // lives on the request — the same instance across every bubbling layer and the error middleware,\n // and always a mutable object, unlike the thrown value which may be frozen or a primitive. Mark\n // before the `shouldHandleError` gate so a \"skip\" decision also suppresses the deprecated middleware.\n const request = data.arguments?.[0] as ExpressRequest | undefined;\n if (request) {\n if (isExpressErrorHandled(request)) {\n return;\n }\n markExpressErrorHandled(request);\n }\n\n if (shouldHandleError === false) {\n return;\n }\n\n if (!(shouldHandleError ?? defaultShouldHandleError)(error as MiddlewareError)) {\n return;\n }\n\n const capture = (): string =>\n captureException(error, {\n mechanism: {\n type: 'auto.http.express',\n handled: false,\n },\n });\n\n // The channel's `error` event runs outside the layer span's async context, so\n // re-activate the bound span (when present) to parent the error event to the\n // request's trace instead of capturing it context-free.\n if (data._sentrySpan) {\n withActiveSpan(data._sentrySpan, capture);\n } else {\n capture();\n }\n}\n\n/** Record the freshly-registered layer's path pattern from a `route`/`use` call. */\nfunction captureRegisteredLayerPath(data: RegistrationChannelContext): void {\n const stack = data.self?.stack;\n if (!Array.isArray(stack)) {\n return;\n }\n const layer = stack[stack.length - 1];\n if (layer) {\n setLayerRegisteredPath(layer, getLayerPath(data.arguments ?? []));\n }\n}\n\n/** Pop the path a layer pushed once it hands control onward via `next`. */\nfunction popLayerPathForLayer(data: HandleChannelContext): void {\n if (!data._sentryStoredLayer) {\n return;\n }\n // Clear the marker first so a layer that (incorrectly) calls `next` more than\n // once can't pop again and take a parent's entry off the stack with it.\n data._sentryStoredLayer = false;\n const req = data.arguments?.[0] as ExpressRequest | undefined;\n if (req) {\n popLayerPath(req);\n }\n}\n\n/**\n * End a layer's span once it hands control onward via `next`.\n *\n * The tracing-channel helper would otherwise end it on `asyncEnd`, which only\n * fires once `next` *returns*. Express runs the rest of the chain synchronously\n * inside `next`, so that would keep every layer on the synchronous chain open\n * (each holding a response `finish` listener) until the whole chain unwinds,\n * and inflate each span with the downstream layers' synchronous work. The\n * helper's later `asyncEnd` is then a no-op, since `span.end()` is idempotent.\n */\nfunction endLayerSpanOnNext(data: HandleChannelContext): void {\n const span = data._sentrySpan;\n if (!span) {\n return;\n }\n data._sentryCleanup?.();\n span.end();\n}\n\n/**\n * Open a span for one layer invocation. Returns `undefined` to opt the layer\n * out (error handlers, or a layer with no active parent trace) — the helper\n * then leaves the active context untouched.\n */\nfunction getSpanForLayer(data: HandleChannelContext, options: ExpressIntegrationOptions): Span | undefined {\n const layer = data.self;\n const args = data.arguments;\n if (!layer || !Array.isArray(args)) {\n return undefined;\n }\n\n // Express only treats a 4-arg handler as an error handler and skips it in\n // the normal request pipeline; match the OTel integration and don't trace it.\n if (layer.handle?.length === 4) {\n return undefined;\n }\n\n // A Route dispatches to its handlers via the same `handle_request` method,\n // but those inner layers already run inside the route-dispatch layer's\n // `request_handler` span. They carry `.method` (and no `.route`); skip them\n // so we emit one span per route, matching the OTel Express integration.\n if (layer.method && !layer.route) {\n return undefined;\n }\n\n const req = args[0] as ExpressRequest | undefined;\n const res = args[1] as ExpressResponse | undefined;\n if (!req) {\n return undefined;\n }\n\n // No active parent span means this request is being ignored (unsampled /\n // filtered), so don't open a span\n if (!getActiveSpan()) {\n return undefined;\n }\n\n const type = getLayerType(layer);\n\n // Push this layer's registered path onto the request's chain so a\n // `request_handler` can reconstruct the full route with parameters intact\n // (`req.baseUrl` only exposes the *resolved* mount prefix). The matching pop\n // happens on `asyncStart` when the layer hands off via `next`.\n const registeredPath = getLayerRegisteredPath(layer) ?? getMatchedLayerPath(layer);\n if (registeredPath != null) {\n pushLayerPath(req, registeredPath);\n data._sentryStoredLayer = true;\n }\n\n // `constructedRoute` (the full registered pattern) names the span/transaction;\n // `matchedRoute` (validated against the request URL) is the `http.route`.\n // Computed for every layer type (not just `request_handler`) so routes served\n // by mounted middleware (`app.use('/trpc', handler)`) still propagate their\n // path to the root `http.server` span — mirroring the OTel Express integration,\n // which resolves the route on every layer. Without this, such transactions keep\n // the raw URL name (e.g. `GET /trpc/foo` instead of `GET /trpc`).\n const constructedRoute = getConstructedRoute(req);\n const matchedRoute = constructedRoute != null ? getActualMatchedRoute(req, constructedRoute) : undefined;\n\n const name =\n type === 'request_handler'\n ? constructedRoute || 'request handler'\n : type === 'router'\n ? (layer.path ?? '/')\n : (layer.name ?? '<anonymous>');\n\n // Propagate the route to the root `http.server` span *before* the ignore\n // check, so the transaction is still named even when the layer's own span is\n // ignored — matches the OTel Express integration's `onRouteResolved` timing.\n if (matchedRoute) {\n setHttpServerSpanRouteAttribute(matchedRoute);\n }\n\n if (type === 'request_handler' && constructedRoute) {\n const isolationScope = getIsolationScope();\n if (isolationScope !== getDefaultIsolationScope()) {\n const method = typeof req.method === 'string' ? req.method.toUpperCase() : 'GET';\n isolationScope.setTransactionName(`${method} ${constructedRoute}`);\n } else {\n DEBUG_BUILD &&\n debug.warn(\n '[instrumentation:express] Isolation scope is still default isolation scope - skipping transaction name',\n );\n }\n }\n\n // Honor `ignoreLayers`/`ignoreLayersType`: skip the span for matching layers.\n // We intentionally do NOT pop the pushed path here (unlike OTel Express, which\n // pops on ignore): the path is still popped on `asyncStart` when the layer\n // calls `next`, so a following sibling isn't polluted, while an ignored\n // *router* keeps its mount prefix on the stack for the sub-stack it dispatches\n // — so routes under an ignored router stay correct. The only entries that\n // never pop come from layers that end the response without `next()`, and those\n // sit on a per-request store that is discarded when the request ends.\n if (isLayerIgnored(name, type, options)) {\n return undefined;\n }\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so router\n // and request handler spans are named after their route. A route that did\n // not validate against the request URL can describe a different request,\n // so those spans take the static fallback instead.\n const isStreamedSpan = !!client && hasSpanStreamingEnabled(client);\n const isStreamedRouterSpan = isStreamedSpan && type === 'router';\n const isStreamedRequestHandlerSpan = isStreamedSpan && type === 'request_handler';\n\n const span = startInactiveSpan({\n name: isStreamedRouterSpan\n ? matchedRoute || ROUTER_SPAN_NAME_FALLBACK\n : isStreamedRequestHandlerSpan\n ? matchedRoute || REQUEST_HANDLER_SPAN_NAME_FALLBACK\n : name,\n attributes: {\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_OP]: EXPRESS_TYPE_TO_SPAN_OP[type],\n [ATTR_EXPRESS_NAME]: name,\n [ATTR_EXPRESS_TYPE]: type,\n [HTTP_ROUTE]: matchedRoute,\n },\n });\n\n // A layer that sends the response (route handlers, typically) never calls\n // `next`, so the channel's `asyncStart` never fires. End on the response's\n // `finish` in that case. When `next` *is* called, `endLayerSpanOnNext` ends\n // the span and removes these now-redundant listeners.\n // `finish` never fires when the client aborts, so also end on `close`, which\n // is when the `http.server` span ends. Otherwise the span and its subtree\n // would be dropped from the transaction.\n if (res && typeof res.once === 'function') {\n const cleanup = (): void => {\n res.removeListener('finish', onFinish);\n res.removeListener('close', onClose);\n };\n const onFinish = (): void => {\n cleanup();\n span.end();\n };\n const onClose = (): void => {\n cleanup();\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n span.end();\n };\n res.once('finish', onFinish);\n res.once('close', onClose);\n data._sentryCleanup = cleanup;\n }\n\n return span;\n}\n\n/**\n * The path of a matched layer for which no registration event recorded a path. That is the case when the events\n * arrive after the registration calls: Cloudflare delivers the events of calls at module scope with the first\n * request.\n */\nfunction getMatchedLayerPath(layer: ExpressLayer): string | undefined {\n if (layer.route) {\n return getLayerPath([layer.route.path]);\n }\n // A mount path without parameters is equal to the part of the URL that the layer matched.\n return layer.keys?.length ? undefined : layer.path || undefined;\n}\n\nfunction getLayerType(layer: ExpressLayer): ExpressLayerType {\n if (layer.name === 'router') {\n return 'router';\n }\n // `bound dispatch` (v4) / `handle` — the route-dispatch layer created by `router.route()`.\n if (layer.name === 'bound dispatch' || layer.name === 'handle') {\n return 'request_handler';\n }\n return 'middleware';\n}\n\n/**\n * Whether a layer should be skipped per the `ignoreLayers`/`ignoreLayersType`\n * options. Matches `@sentry/core`'s Express `isLayerIgnored`: `ignoreLayersType`\n * filters by layer type, `ignoreLayers` matches the layer's name against\n * string/RegExp/predicate patterns (exact string match).\n */\nfunction isLayerIgnored(name: string, type: ExpressLayerType, options: ExpressIntegrationOptions): boolean {\n const { ignoreLayers, ignoreLayersType } = options;\n\n if (Array.isArray(ignoreLayersType) && ignoreLayersType.includes(type)) {\n return true;\n }\n\n if (!Array.isArray(ignoreLayers)) {\n return false;\n }\n\n try {\n return stringMatchesSomePattern(name, ignoreLayers, true);\n } catch {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;AA8CA,MAAM,SAAS;AAKf,MAAM,oBAAoB;AAC1B,MAAM,oBAAoB;AAE1B,MAAM,0BAAkD;CACtD,YAAY;CACZ,iBAAiB;CACjB,QAAQ;AACV;AAEA,MAAM,aAAmB,CAAC;AAE1B,IAAI,kBAAkB;AAEtB,SAAgB,kBACd,SACA,gBACM;CACN,IAAI,iBACF;CAEF,kBAAkB;CAMlB,KAAK,MAAM,eAAe,CAAC,SAAS,kBAAkB,SAAS,eAAe,GAC5E,eAA2C,WAAW,CAAC,CAAC,UAAU;EAChE,OAAO;EACP,YAAY;EACZ,UAAU;EACV,OAAO;EACP,KAAK;CACP,CAAC;CAGH,KAAK,MAAM,eAAe,CAAC,SAAS,gBAAgB,SAAS,aAAa,GAAG;EAC3E,MAAM,UAAU,eAAqC,WAAW;EAEhE,yBAAyB,UAAS,SAAQ,gBAAgB,MAAM,OAAO,GAAG,EACxE,cAAc,OAAO,MAAM;GACzB,KAAK,iBAAiB;EACxB,EACF,CAAC;EAQD,QAAQ,UAAU;GAChB,OAAO;GACP,UAAU;GACV,KAAK;GACL,QAAO,SAAQ,kBAAkB,MAAM,QAAQ,iBAAiB;GAChE,aAAY,SAAQ;IAClB,qBAAqB,IAAI;IACzB,mBAAmB,IAAI;GACzB;EACF,CAAC;CACH;AACF;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,kBACd,MACA,mBACM;CACN,MAAM,QAAQ,KAAK;CAGnB,IAAI,CAAC,SAAS,UAAU,WAAW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IAAI,KAAK,UAAU,QAAQ;EAC3B,IAAI,KAAK,SAAS,OAAO;EACzB,KAAK,iBAAiB;CACxB;CAEA,OAAO;AACT;;;;;;AAOA,SAAS,oBAAoB,OAAyC;CACpE,IAAI,MAAM,OACR,OAAO,aAAa,CAAC,MAAM,MAAM,IAAI,CAAC;CAGxC,OAAO,MAAM,MAAM,SAAS,KAAA,IAAY,MAAM,QAAQ,KAAA;AACxD;AAEA,SAAS,aAAa,OAAuC;CAC3D,IAAI,MAAM,SAAS,UACjB,OAAO;CAGT,IAAI,MAAM,SAAS,oBAAoB,MAAM,SAAS,UACpD,OAAO;CAET,OAAO;AACT;;;;;;;AAQA,SAAS,eAAe,MAAc,MAAwB,SAA6C;CACzG,MAAM,EAAE,cAAc,qBAAqB;CAE3C,IAAI,MAAM,QAAQ,gBAAgB,KAAK,iBAAiB,SAAS,IAAI,GACnE,OAAO;CAGT,IAAI,CAAC,MAAM,QAAQ,YAAY,GAC7B,OAAO;CAGT,IAAI;EACF,OAAO,yBAAyB,MAAM,cAAc,IAAI;CAC1D,QAAQ;EACN,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"instrumentation.js","names":[],"sources":["../../../../src/integrations/express/instrumentation.ts"],"sourcesContent":["import type * as diagnosticsChannel from 'node:diagnostics_channel';\nimport { HTTP_ROUTE, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { HANDLER, MIDDLEWARE, ROUTER } from '@sentry/conventions/op';\nimport type { Span } from '@sentry/core';\nimport {\n captureException,\n debug,\n getActiveSpan,\n getClient,\n getDefaultIsolationScope,\n getIsolationScope,\n hasSpanStreamingEnabled,\n REQUEST_HANDLER_SPAN_NAME_FALLBACK,\n ROUTER_SPAN_NAME_FALLBACK,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n stringMatchesSomePattern,\n withActiveSpan,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { CHANNELS } from '../../orchestrion/channels';\nimport { bindTracingChannelToSpan } from '../../tracing-channel';\nimport {\n getActualMatchedRoute,\n getConstructedRoute,\n getLayerPath,\n getLayerRegisteredPath,\n popLayerPath,\n pushLayerPath,\n setLayerRegisteredPath,\n} from './route';\nimport type {\n ExpressIntegrationOptions,\n ExpressLayer,\n ExpressLayerType,\n ExpressRequest,\n ExpressResponse,\n ExpressShouldHandleError,\n HandleChannelContext,\n MiddlewareError,\n RegistrationChannelContext,\n} from './types';\nimport { defaultShouldHandleError } from './utils';\nimport { isExpressErrorHandled, markExpressErrorHandled } from './error-handled';\nimport { setHttpServerSpanRouteAttribute } from '../../utils/setHttpServerSpanRouteAttribute';\n\nconst ORIGIN = 'auto.http.express';\n\n// `express.name`/`express.type` are Sentry-internal Express attributes (not part\n// of `@sentry/conventions`); kept in sync with `@sentry/core`'s OTel-derived\n// Express integration so the emitted spans are identical across both code paths.\nconst ATTR_EXPRESS_NAME = 'express.name';\nconst ATTR_EXPRESS_TYPE = 'express.type';\n\nconst EXPRESS_TYPE_TO_SPAN_OP: Record<string, string> = {\n middleware: MIDDLEWARE,\n request_handler: HANDLER,\n router: ROUTER,\n};\n\nconst NOOP = (): void => {};\n\nlet _isInstrumented = false;\n\nexport function instrumentExpress(\n options: ExpressIntegrationOptions,\n tracingChannel: typeof diagnosticsChannel.tracingChannel,\n): void {\n if (_isInstrumented) {\n return;\n }\n _isInstrumented = true;\n\n // Record each layer's registered path *pattern* as it is registered, so the\n // matched route can be reconstructed with its parameters intact at request\n // time. Only the `end` event matters (the layer is on the router's stack by\n // then); the others are required by the subscriber type, so no-op them.\n for (const channelName of [CHANNELS.EXPRESS_REGISTER, CHANNELS.ROUTER_REGISTER]) {\n tracingChannel<RegistrationChannelContext>(channelName).subscribe({\n start: NOOP,\n asyncStart: NOOP,\n asyncEnd: NOOP,\n error: NOOP,\n end: captureRegisteredLayerPath,\n });\n }\n\n for (const channelName of [CHANNELS.EXPRESS_HANDLE, CHANNELS.ROUTER_HANDLE]) {\n const channel = tracingChannel<HandleChannelContext>(channelName);\n\n bindTracingChannelToSpan(channel, data => getSpanForLayer(data, options), {\n beforeSpanEnd(_span, data) {\n data._sentryCleanup?.();\n },\n });\n\n // Pop the layer path and end the layer span when the layer hands off via\n // `next`. `asyncStart` fires when `next` is called and *before* the\n // downstream layer runs, so the per-request path chain reflects only the\n // current chain when each layer reconstructs its route, and each span covers\n // only its own layer. The `error` event captures throws at the layer level\n // (see `captureLayerError`), before any user error-handling middleware.\n channel.subscribe({\n start: NOOP,\n asyncEnd: NOOP,\n end: NOOP,\n error: data => captureLayerError(data, options.shouldHandleError),\n asyncStart: data => {\n popLayerPathForLayer(data);\n endLayerSpanOnNext(data);\n },\n });\n }\n}\n\n/**\n * Capture an error surfaced on a layer's `handle_request` channel — the throw\n * site, which runs before any user error-handling middleware.\n *\n * Each request's error is handled exactly once: the same error surfaces on every\n * parent layer's `error` event as it bubbles, and a user may also still call the\n * deprecated `setupExpressErrorHandler`. We mark the request the first time we\n * see it, so later layers and that middleware defer to this decision — the\n * integration is the single registered handler and its `shouldHandleError` wins.\n * This deliberately does not rely on `captureException`'s global dedup, which is\n * only set when an error is actually captured and so cannot express a\n * \"deliberately skipped\" decision (leaving the deprecated middleware free to\n * capture it and override `shouldHandleError`).\n *\n * `shouldHandleError` is the raw integration option: `false` disables capture\n * entirely, a function customizes the gate, and `undefined` falls back to\n * {@link defaultShouldHandleError}.\n */\nexport function captureLayerError(\n data: HandleChannelContext,\n shouldHandleError: ExpressShouldHandleError | undefined,\n): void {\n const error = data.error;\n\n // `next('route')` / `next('router')` are Express control-flow signals, not errors.\n if (!error || error === 'route' || error === 'router') {\n return;\n }\n\n // Take responsibility for this request's error exactly once (see the doc comment above). The marker\n // lives on the request — the same instance across every bubbling layer and the error middleware,\n // and always a mutable object, unlike the thrown value which may be frozen or a primitive. Mark\n // before the `shouldHandleError` gate so a \"skip\" decision also suppresses the deprecated middleware.\n const request = data.arguments?.[0] as ExpressRequest | undefined;\n if (request) {\n if (isExpressErrorHandled(request)) {\n return;\n }\n markExpressErrorHandled(request);\n }\n\n if (shouldHandleError === false) {\n return;\n }\n\n if (!(shouldHandleError ?? defaultShouldHandleError)(error as MiddlewareError)) {\n return;\n }\n\n const capture = (): string =>\n captureException(error, {\n mechanism: {\n type: 'auto.http.express',\n handled: false,\n },\n });\n\n // The channel's `error` event runs outside the layer span's async context, so\n // re-activate the bound span (when present) to parent the error event to the\n // request's trace instead of capturing it context-free.\n if (data._sentrySpan) {\n withActiveSpan(data._sentrySpan, capture);\n } else {\n capture();\n }\n}\n\n/** Record the freshly-registered layer's path pattern from a `route`/`use` call. */\nfunction captureRegisteredLayerPath(data: RegistrationChannelContext): void {\n const stack = data.self?.stack;\n if (!Array.isArray(stack)) {\n return;\n }\n const layer = stack[stack.length - 1];\n if (layer) {\n setLayerRegisteredPath(layer, getLayerPath(data.arguments ?? []));\n }\n}\n\n/** Pop the path a layer pushed once it hands control onward via `next`. */\nfunction popLayerPathForLayer(data: HandleChannelContext): void {\n if (!data._sentryStoredLayer) {\n return;\n }\n // Clear the marker first so a layer that (incorrectly) calls `next` more than\n // once can't pop again and take a parent's entry off the stack with it.\n data._sentryStoredLayer = false;\n const req = data.arguments?.[0] as ExpressRequest | undefined;\n if (req) {\n popLayerPath(req);\n }\n}\n\n/**\n * End a layer's span once it hands control onward via `next`.\n *\n * The tracing-channel helper would otherwise end it on `asyncEnd`, which only\n * fires once `next` *returns*. Express runs the rest of the chain synchronously\n * inside `next`, so that would keep every layer on the synchronous chain open\n * (each holding a response `finish` listener) until the whole chain unwinds,\n * and inflate each span with the downstream layers' synchronous work. The\n * helper's later `asyncEnd` is then a no-op, since `span.end()` is idempotent.\n */\nfunction endLayerSpanOnNext(data: HandleChannelContext): void {\n const span = data._sentrySpan;\n if (!span) {\n return;\n }\n data._sentryCleanup?.();\n span.end();\n}\n\n/**\n * Open a span for one layer invocation. Returns `undefined` to opt the layer\n * out (error handlers, or a layer with no active parent trace) — the helper\n * then leaves the active context untouched.\n */\nfunction getSpanForLayer(data: HandleChannelContext, options: ExpressIntegrationOptions): Span | undefined {\n const layer = data.self;\n const args = data.arguments;\n if (!layer || !Array.isArray(args)) {\n return undefined;\n }\n\n // Express only treats a 4-arg handler as an error handler and skips it in\n // the normal request pipeline; match the OTel integration and don't trace it.\n if (layer.handle?.length === 4) {\n return undefined;\n }\n\n // A Route dispatches to its handlers via the same `handle_request` method,\n // but those inner layers already run inside the route-dispatch layer's\n // `request_handler` span. They carry `.method` (and no `.route`); skip them\n // so we emit one span per route, matching the OTel Express integration.\n if (layer.method && !layer.route) {\n return undefined;\n }\n\n const req = args[0] as ExpressRequest | undefined;\n const res = args[1] as ExpressResponse | undefined;\n if (!req) {\n return undefined;\n }\n\n // No active parent span means this request is being ignored (unsampled /\n // filtered), so don't open a span\n if (!getActiveSpan()) {\n return undefined;\n }\n\n const type = getLayerType(layer);\n\n // Push this layer's registered path onto the request's chain so a\n // `request_handler` can reconstruct the full route with parameters intact\n // (`req.baseUrl` only exposes the *resolved* mount prefix). The matching pop\n // happens on `asyncStart` when the layer hands off via `next`.\n const registeredPath = getLayerRegisteredPath(layer) ?? getMatchedLayerPath(layer);\n if (registeredPath != null) {\n pushLayerPath(req, registeredPath);\n data._sentryStoredLayer = true;\n }\n\n // `constructedRoute` (the full registered pattern) names the span/transaction;\n // `matchedRoute` (validated against the request URL) is the `http.route`.\n // Computed for every layer type (not just `request_handler`) so routes served\n // by mounted middleware (`app.use('/trpc', handler)`) still propagate their\n // path to the root `http.server` span — mirroring the OTel Express integration,\n // which resolves the route on every layer. Without this, such transactions keep\n // the raw URL name (e.g. `GET /trpc/foo` instead of `GET /trpc`).\n const constructedRoute = getConstructedRoute(req);\n const matchedRoute = constructedRoute != null ? getActualMatchedRoute(req, constructedRoute) : undefined;\n\n const name =\n type === 'request_handler'\n ? constructedRoute || 'request handler'\n : type === 'router'\n ? (layer.path ?? '/')\n : (layer.name ?? '<anonymous>');\n\n // Propagate the route to the root `http.server` span *before* the ignore\n // check, so the transaction is still named even when the layer's own span is\n // ignored — matches the OTel Express integration's `onRouteResolved` timing.\n if (matchedRoute) {\n setHttpServerSpanRouteAttribute(matchedRoute);\n }\n\n if (type === 'request_handler' && constructedRoute) {\n const isolationScope = getIsolationScope();\n if (isolationScope !== getDefaultIsolationScope()) {\n const method = typeof req.method === 'string' ? req.method.toUpperCase() : 'GET';\n isolationScope.setTransactionName(`${method} ${constructedRoute}`);\n } else {\n DEBUG_BUILD &&\n debug.warn(\n '[instrumentation:express] Isolation scope is still default isolation scope - skipping transaction name',\n );\n }\n }\n\n // Honor `ignoreLayers`/`ignoreLayersType`: skip the span for matching layers.\n // We intentionally do NOT pop the pushed path here (unlike OTel Express, which\n // pops on ignore): the path is still popped on `asyncStart` when the layer\n // calls `next`, so a following sibling isn't polluted, while an ignored\n // *router* keeps its mount prefix on the stack for the sub-stack it dispatches\n // — so routes under an ignored router stay correct. The only entries that\n // never pop come from layers that end the response without `next()`, and those\n // sit on a per-request store that is discarded when the request ends.\n if (isLayerIgnored(name, type, options)) {\n return undefined;\n }\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so router\n // and request handler spans are named after their route. A route that did\n // not validate against the request URL can describe a different request,\n // so those spans take the static fallback instead.\n const isStreamedSpan = !!client && hasSpanStreamingEnabled(client);\n const isStreamedRouterSpan = isStreamedSpan && type === 'router';\n const isStreamedRequestHandlerSpan = isStreamedSpan && type === 'request_handler';\n\n const span = startInactiveSpan({\n name: isStreamedRouterSpan\n ? matchedRoute || ROUTER_SPAN_NAME_FALLBACK\n : isStreamedRequestHandlerSpan\n ? matchedRoute || REQUEST_HANDLER_SPAN_NAME_FALLBACK\n : name,\n attributes: {\n [SENTRY_ORIGIN]: ORIGIN,\n [SENTRY_OP]: EXPRESS_TYPE_TO_SPAN_OP[type],\n [ATTR_EXPRESS_NAME]: name,\n [ATTR_EXPRESS_TYPE]: type,\n [HTTP_ROUTE]: matchedRoute,\n },\n });\n\n // A layer that sends the response (route handlers, typically) never calls\n // `next`, so the channel's `asyncStart` never fires. End on the response's\n // `finish` in that case. When `next` *is* called, `endLayerSpanOnNext` ends\n // the span and removes these now-redundant listeners.\n // `finish` never fires when the client aborts, so also end on `close`, which\n // is when the `http.server` span ends. Otherwise the span and its subtree\n // would be dropped from the transaction.\n if (res && typeof res.once === 'function') {\n const cleanup = (): void => {\n res.removeListener('finish', onFinish);\n res.removeListener('close', onClose);\n };\n const onFinish = (): void => {\n cleanup();\n span.end();\n };\n const onClose = (): void => {\n cleanup();\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n span.end();\n };\n res.once('finish', onFinish);\n res.once('close', onClose);\n data._sentryCleanup = cleanup;\n }\n\n return span;\n}\n\n/**\n * The path of a matched layer for which no registration event recorded a path. That is the case when the events\n * arrive after the registration calls: Cloudflare delivers the events of calls at module scope with the first\n * request.\n */\nfunction getMatchedLayerPath(layer: ExpressLayer): string | undefined {\n if (layer.route) {\n return getLayerPath([layer.route.path]);\n }\n // `router` 2.3.0 and later keep the registered mount path in `rawPath` and no longer store the matched `path`.\n if (layer.rawPath !== undefined) {\n return getLayerPath([layer.rawPath]);\n }\n // A mount path without parameters is equal to the part of the URL that the layer matched.\n return layer.keys?.length ? undefined : layer.path || undefined;\n}\n\nfunction getLayerType(layer: ExpressLayer): ExpressLayerType {\n if (layer.name === 'router') {\n return 'router';\n }\n // `bound dispatch` (v4) / `handle` — the route-dispatch layer created by `router.route()`.\n if (layer.name === 'bound dispatch' || layer.name === 'handle') {\n return 'request_handler';\n }\n return 'middleware';\n}\n\n/**\n * Whether a layer should be skipped per the `ignoreLayers`/`ignoreLayersType`\n * options. Matches `@sentry/core`'s Express `isLayerIgnored`: `ignoreLayersType`\n * filters by layer type, `ignoreLayers` matches the layer's name against\n * string/RegExp/predicate patterns (exact string match).\n */\nfunction isLayerIgnored(name: string, type: ExpressLayerType, options: ExpressIntegrationOptions): boolean {\n const { ignoreLayers, ignoreLayersType } = options;\n\n if (Array.isArray(ignoreLayersType) && ignoreLayersType.includes(type)) {\n return true;\n }\n\n if (!Array.isArray(ignoreLayers)) {\n return false;\n }\n\n try {\n return stringMatchesSomePattern(name, ignoreLayers, true);\n } catch {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;AA8CA,MAAM,SAAS;AAKf,MAAM,oBAAoB;AAC1B,MAAM,oBAAoB;AAE1B,MAAM,0BAAkD;CACtD,YAAY;CACZ,iBAAiB;CACjB,QAAQ;AACV;AAEA,MAAM,aAAmB,CAAC;AAE1B,IAAI,kBAAkB;AAEtB,SAAgB,kBACd,SACA,gBACM;CACN,IAAI,iBACF;CAEF,kBAAkB;CAMlB,KAAK,MAAM,eAAe,CAAC,SAAS,kBAAkB,SAAS,eAAe,GAC5E,eAA2C,WAAW,CAAC,CAAC,UAAU;EAChE,OAAO;EACP,YAAY;EACZ,UAAU;EACV,OAAO;EACP,KAAK;CACP,CAAC;CAGH,KAAK,MAAM,eAAe,CAAC,SAAS,gBAAgB,SAAS,aAAa,GAAG;EAC3E,MAAM,UAAU,eAAqC,WAAW;EAEhE,yBAAyB,UAAS,SAAQ,gBAAgB,MAAM,OAAO,GAAG,EACxE,cAAc,OAAO,MAAM;GACzB,KAAK,iBAAiB;EACxB,EACF,CAAC;EAQD,QAAQ,UAAU;GAChB,OAAO;GACP,UAAU;GACV,KAAK;GACL,QAAO,SAAQ,kBAAkB,MAAM,QAAQ,iBAAiB;GAChE,aAAY,SAAQ;IAClB,qBAAqB,IAAI;IACzB,mBAAmB,IAAI;GACzB;EACF,CAAC;CACH;AACF;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,kBACd,MACA,mBACM;CACN,MAAM,QAAQ,KAAK;CAGnB,IAAI,CAAC,SAAS,UAAU,WAAW,UAAU,UAC3C;CAOF,MAAM,UAAU,KAAK,YAAY;CACjC,IAAI,SAAS;EACX,IAAI,sBAAsB,OAAO,GAC/B;EAEF,wBAAwB,OAAO;CACjC;CAEA,IAAI,sBAAsB,OACxB;CAGF,IAAI,EAAE,qBAAq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C,MAAM,MAAM,IAAI,CAAC;CAGxC,IAAI,MAAM,YAAY,KAAA,GACpB,OAAO,aAAa,CAAC,MAAM,OAAO,CAAC;CAGrC,OAAO,MAAM,MAAM,SAAS,KAAA,IAAY,MAAM,QAAQ,KAAA;AACxD;AAEA,SAAS,aAAa,OAAuC;CAC3D,IAAI,MAAM,SAAS,UACjB,OAAO;CAGT,IAAI,MAAM,SAAS,oBAAoB,MAAM,SAAS,UACpD,OAAO;CAET,OAAO;AACT;;;;;;;AAQA,SAAS,eAAe,MAAc,MAAwB,SAA6C;CACzG,MAAM,EAAE,cAAc,qBAAqB;CAE3C,IAAI,MAAM,QAAQ,gBAAgB,KAAK,iBAAiB,SAAS,IAAI,GACnE,OAAO;CAGT,IAAI,CAAC,MAAM,QAAQ,YAAY,GAC7B,OAAO;CAGT,IAAI;EACF,OAAO,yBAAyB,MAAM,cAAc,IAAI;CAC1D,QAAQ;EACN,OAAO;CACT;AACF"}
|
|
@@ -2,7 +2,7 @@ import { subscribe } from "../../utils/diagnosticsChannel.js";
|
|
|
2
2
|
import { setHttpServerSpanRouteAttribute } from "../../utils/setHttpServerSpanRouteAttribute.js";
|
|
3
3
|
import { handleFastifyError } from "./errors.js";
|
|
4
4
|
import { HTTP_REQUEST_METHOD, HTTP_RESPONSE_STATUS_CODE, HTTP_ROUTE, SENTRY_OP, SENTRY_ORIGIN, URL_PATH } from "@sentry/conventions/attributes";
|
|
5
|
-
import { REQUEST_HANDLER_SPAN_NAME_FALLBACK, SPAN_STATUS_ERROR, getClient, getIsolationScope, hasSpanStreamingEnabled, isObjectLike, startInactiveSpan, startSpan, withActiveSpan } from "@sentry/core";
|
|
5
|
+
import { REQUEST_HANDLER_SPAN_NAME_FALLBACK, SPAN_STATUS_ERROR, getActiveSpan, getClient, getIsolationScope, hasSpanStreamingEnabled, isObjectLike, spanIsSampled, startInactiveSpan, startSpan, withActiveSpan } from "@sentry/core";
|
|
6
6
|
import { HANDLER, MIDDLEWARE } from "@sentry/conventions/op";
|
|
7
7
|
// src/integrations/fastify/instrumentation.ts
|
|
8
8
|
const ORIGIN = "auto.http.fastify";
|
|
@@ -194,6 +194,8 @@ function handlerWrapper(handler, hookName, spanAttributes = {}) {
|
|
|
194
194
|
const request = getRequestFromArgs(args);
|
|
195
195
|
if (!request) return handler.call(this, ...args);
|
|
196
196
|
const parentSpan = request[kRequestSpan] ?? void 0;
|
|
197
|
+
const effectiveParentSpan = parentSpan ?? getActiveSpan();
|
|
198
|
+
if (effectiveParentSpan && !spanIsSampled(effectiveParentSpan)) return handler.call(this, ...args);
|
|
197
199
|
const handlerName = handler.name?.length > 0 ? handler.name : this.pluginName ?? ANONYMOUS_FUNCTION_NAME;
|
|
198
200
|
const hookType = spanAttributes[ATTRIBUTE_FASTIFY_TYPE];
|
|
199
201
|
const op = hookType === HOOK_TYPE_INSTANCE ? MIDDLEWARE : hookType === HOOK_TYPE_HANDLER ? HANDLER : void 0;
|