@sentry/server-utils 11.17.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 +2 -2
- package/build/cjs/chunks/config.js.map +1 -1
- package/build/cjs/chunks/exports.js +115 -10
- package/build/cjs/chunks/exports.js.map +1 -1
- package/build/cjs/index.js +148 -31
- 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/utils.js +1 -5
- package/build/esm/ai/langchain/utils.js.map +1 -1
- package/build/esm/ai/mistral/streaming.js.map +1 -1
- package/build/esm/exports.js +2 -1
- package/build/esm/index.js +3 -1
- 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/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/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/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/config/hono.js +2 -2
- package/build/esm/orchestrion/config/hono.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 +4 -3
- 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/utils.d.ts.map +1 -1
- package/build/types/ai/mistral/streaming.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 +3 -2
- 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/hapi/hapi-utils.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/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/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.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,MAAM,sBAAqC,OAAO,oCAAoC;AACtF,MAAM,0BAAyC,OAAO,wCAAwC;AAC9F,MAAM,gCAA+C,OAAO,8CAA8C;AAC1G,MAAM,wBAAuC,OAAO,sCAAsC;AAC1F,MAAM,4BAA2C,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,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,MAAM,wBAAuC,OAAO,sCAAsC;AAC1F,MAAM,4BAA2C,OAAO,0CAA0C;AAClG,MAAM,gCAA+C,OAAO,8CAA8C;AAC1G,MAAM,wBAAuC,OAAO,sCAAsC;AAsE1F,MAAM,aAAmB,CA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AO;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,KAAK,MAAM,IAAI,EAAE,UAAU,KAAK,OAAO,CAAC;EAC7F;EACA,eAAe,EAAE,MAAM,MAAM,UAC3B,wBAAwB,MAAM,MAAM,GAAG,KACvC,uBACE,KAAK,SACL,aAAY;GACV,KAAK,SAAS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e,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,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,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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;CAE1C,OAAO,KAAK,MAAM,GAAG,CAAC,CAAC,EAAE,CAAE,YAAY;AACzC;AAEA,SAAS,kBAAkB,MAAsB;CAC/C,MAAM,YAAY,aAAa,IAAI;CAEnC,IAAI,oBAAoB,IAAI,SAAS,GACnC,OAAO;CAGT,IAAI,oBAAoB,IAAI,SAAS,GACnC,OAAO;CAGT,OAAO;AACT;AAEA,SAAS,sBAAsB,MAAsB;CACnD,MAAM,YAAY,aAAa,IAAI;CAEnC,IAAI,oBAAoB,IAAI,SAAS,GACnC,OAAO;CAGT,IAAI,oBAAoB,IAAI,SAAS,GACnC,OAAO;CAGT,OAAO;AACT;AAEA,IAAa,qBAAb,MAAiE;CACxD,UAAU,MAAc,SAAuB,SAAwC;EAC5F,MAAM,KAAK,kBAAkB,IAAI;EACjC,MAAM,SAAS,sBAAsB,IAAI;EAEzC,MAAM,aAA6B;IAChC,YAAY;IACZ,gBAAgB;IAChB,mBAAmB;GACpB,GAAI,SAAS,cAAc,mBAAmB,QAAQ,UAAU;EAClE;EAGA,MAAM,OACJ,OAAO,gBACH,oBAAoB,kBAAkB;GAAE;GAAM;EAAW,CAAC,CAAC,IAC3D,kBAAkB;GAAE;GAAM;GAAY,cAAc,OAAO;EAAM,CAAC;EAExE,IAAI,SAAS,qBAAqB;GAChC,MAAM,kBAAkB;IACtB,SAAS,QAAQ,oBAAoB;IACrC,QAAQ,QAAQ,oBAAoB;IACpC,YAAY,QAAQ,oBAAoB,UAAU,IAAI;GACxD;GAEA,KAAK,QAAQ;IACX,SAAS;IACT,YAAY,GACT,mBAAmB,iBACtB;GACF,CAAC;EACH;EAEA,OAAO,IAAI,iBAAiB,MAAM,gBAAgB,CAAC;CACrD;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":[],"sources":["../../../../src/integrations/graphql/utils.ts"],"sourcesContent":["import { SENTRY_SEGMENT_NAME_SOURCE, SENTRY_GRAPHQL_OPERATION } from '@sentry/conventions/attributes';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport { getClient, hasSpanStreamingEnabled, isObjectLike, getRootSpan, spanToJSON } from '@sentry/core';\nimport type { GraphqlDocumentNode, GraphqlToken } from './types';\n\n// Same key the OTel path uses, so renames stay consistent across both.\nconst ORIGINAL_DESCRIPTION_ATTRIBUTE = 'original-description';\n\n// graphql-js token kinds whose values may carry user data (literal arguments). We\n// replace them in the serialized document so raw inline values can never reach\n// `graphql.document`. Mirrors the legacy OTel instrumentation's redaction set.\nconst REDACTED_LITERAL_KINDS = new Set(['Int', 'Float', 'String', 'BlockString']);\n\n/**\n * Record the operation name(s) on the enclosing root span and, unless span streaming is enabled,\n * rename it to include them, e.g. `GET /graphql (query GetUser)`.\n */\nexport function renameRootSpanWithOperation(span: Span, operationType: string, operationName?: string): void {\n const rootSpan = getRootSpan(span);\n // Nothing to rename if the operation span is itself the root (graphql ran outside any span).\n if (rootSpan === span) {\n return;\n }\n\n const rootSpanJson = spanToJSON(rootSpan);\n\n const newOperation = operationName ? `${operationType} ${operationName}` : operationType;\n\n // A single operation is stored as a string, multiple as an array.\n const existingOperations = rootSpanJson.attributes[SENTRY_GRAPHQL_OPERATION];\n let operations: string | string[];\n if (Array.isArray(existingOperations)) {\n operations = [...(existingOperations as string[]), newOperation];\n } else if (typeof existingOperations === 'string') {\n operations = [existingOperations, newOperation];\n } else {\n operations = newOperation;\n }\n rootSpan.setAttribute(SENTRY_GRAPHQL_OPERATION, operations);\n\n const client = getClient();\n if (client && hasSpanStreamingEnabled(client)) {\n return;\n }\n\n // Keep the pre-rename name so repeated renames don't compound.\n const originalDescription =\n (rootSpanJson.attributes[ORIGINAL_DESCRIPTION_ATTRIBUTE] as string | undefined) ?? rootSpanJson.name;\n if (!rootSpanJson.attributes[ORIGINAL_DESCRIPTION_ATTRIBUTE]) {\n rootSpan.setAttribute(ORIGINAL_DESCRIPTION_ATTRIBUTE, originalDescription);\n }\n\n // `updateName` stamps `source: 'custom'`, so re-set the original source afterwards to preserve it.\n const source = rootSpanJson.attributes[SENTRY_SEGMENT_NAME_SOURCE];\n rootSpan.updateName(`${originalDescription} (${getGraphqlOperationNamesFromAttribute(operations)})`);\n rootSpan.setAttribute(SENTRY_SEGMENT_NAME_SOURCE, source as SpanAttributeValue);\n}\n\n/** Format the accumulated operations for the root span name: up to 5 sorted names, then `+N`. */\nfunction getGraphqlOperationNamesFromAttribute(attr: string | string[]): string {\n if (Array.isArray(attr)) {\n // oxlint-disable-next-line typescript/require-array-sort-compare\n const sorted = attr.slice().sort();\n if (sorted.length <= 5) {\n return sorted.join(', ');\n }\n\n return `${sorted.slice(0, 5).join(', ')}, +${sorted.length - 5}`;\n }\n\n return attr;\n}\n\n/**\n * Span name follows the GraphQL semantic conventions: `<operation.type> <operation.name>` when both\n * are available, `<operation.type>` when only the type is, otherwise a static fallback.\n */\nexport function getOperationSpanName(\n operationType: string | undefined,\n operationName: string | undefined,\n fallbackName: string,\n): string {\n if (operationType && operationName) {\n return `${operationType} ${operationName}`;\n }\n if (operationType) {\n return operationType;\n }\n\n return fallbackName;\n}\n\n/** Whether a graphql execution result carries GraphQL errors (returned on `result.errors`). */\nexport function hasResultErrors(result: unknown): boolean {\n if (isObjectLike(result) && 'errors' in result) {\n const errors = (result as { errors?: unknown }).errors;\n\n return Array.isArray(errors) && errors.length > 0;\n }\n\n return false;\n}\n\n/**\n * Serialize a parsed document into `graphql.document` while redacting every literal argument value:\n * the original source text is preserved verbatim except that string/number literal spans are\n * replaced (`\"foo\"` -> `\"*\"`, `42` -> `*`). graphql does not sanitize its channel payload, so this\n * prevents raw inline values (potential PII) from leaving the process. Variable values are never\n * included. Returns `undefined` (rather than throwing) on anything it cannot serialize.\n */\nfunction redactGraphqlDocument(document: GraphqlDocumentNode | undefined): string | undefined {\n const loc = document?.loc;\n const body = loc?.source?.body;\n if (typeof body !== 'string' || !loc?.startToken) {\n return undefined;\n }\n\n try {\n // Collect literal token spans, then splice them out back-to-front so earlier offsets stay valid.\n const ranges: Array<{ start: number; end: number; kind: string }> = [];\n for (let token: GraphqlToken | null | undefined = loc.startToken; token; token = token.next) {\n if (REDACTED_LITERAL_KINDS.has(token.kind)) {\n ranges.push({ start: token.start, end: token.end, kind: token.kind });\n }\n }\n\n let out = body;\n // Reverse index loop (not `for...of`) so we splice back-to-front
|
|
1
|
+
{"version":3,"file":"utils.js","names":[],"sources":["../../../../src/integrations/graphql/utils.ts"],"sourcesContent":["import { SENTRY_SEGMENT_NAME_SOURCE, SENTRY_GRAPHQL_OPERATION } from '@sentry/conventions/attributes';\nimport type { Span, SpanAttributeValue } from '@sentry/core';\nimport { getClient, hasSpanStreamingEnabled, isObjectLike, getRootSpan, spanToJSON } from '@sentry/core';\nimport type { GraphqlDocumentNode, GraphqlToken } from './types';\n\n// Same key the OTel path uses, so renames stay consistent across both.\nconst ORIGINAL_DESCRIPTION_ATTRIBUTE = 'original-description';\n\n// graphql-js token kinds whose values may carry user data (literal arguments). We\n// replace them in the serialized document so raw inline values can never reach\n// `graphql.document`. Mirrors the legacy OTel instrumentation's redaction set.\nconst REDACTED_LITERAL_KINDS = new Set(['Int', 'Float', 'String', 'BlockString']);\n\n/**\n * Record the operation name(s) on the enclosing root span and, unless span streaming is enabled,\n * rename it to include them, e.g. `GET /graphql (query GetUser)`.\n */\nexport function renameRootSpanWithOperation(span: Span, operationType: string, operationName?: string): void {\n const rootSpan = getRootSpan(span);\n // Nothing to rename if the operation span is itself the root (graphql ran outside any span).\n if (rootSpan === span) {\n return;\n }\n\n const rootSpanJson = spanToJSON(rootSpan);\n\n const newOperation = operationName ? `${operationType} ${operationName}` : operationType;\n\n // A single operation is stored as a string, multiple as an array.\n const existingOperations = rootSpanJson.attributes[SENTRY_GRAPHQL_OPERATION];\n let operations: string | string[];\n if (Array.isArray(existingOperations)) {\n operations = [...(existingOperations as string[]), newOperation];\n } else if (typeof existingOperations === 'string') {\n operations = [existingOperations, newOperation];\n } else {\n operations = newOperation;\n }\n rootSpan.setAttribute(SENTRY_GRAPHQL_OPERATION, operations);\n\n const client = getClient();\n if (client && hasSpanStreamingEnabled(client)) {\n return;\n }\n\n // Keep the pre-rename name so repeated renames don't compound.\n const originalDescription =\n (rootSpanJson.attributes[ORIGINAL_DESCRIPTION_ATTRIBUTE] as string | undefined) ?? rootSpanJson.name;\n if (!rootSpanJson.attributes[ORIGINAL_DESCRIPTION_ATTRIBUTE]) {\n rootSpan.setAttribute(ORIGINAL_DESCRIPTION_ATTRIBUTE, originalDescription);\n }\n\n // `updateName` stamps `source: 'custom'`, so re-set the original source afterwards to preserve it.\n const source = rootSpanJson.attributes[SENTRY_SEGMENT_NAME_SOURCE];\n rootSpan.updateName(`${originalDescription} (${getGraphqlOperationNamesFromAttribute(operations)})`);\n rootSpan.setAttribute(SENTRY_SEGMENT_NAME_SOURCE, source as SpanAttributeValue);\n}\n\n/** Format the accumulated operations for the root span name: up to 5 sorted names, then `+N`. */\nfunction getGraphqlOperationNamesFromAttribute(attr: string | string[]): string {\n if (Array.isArray(attr)) {\n // oxlint-disable-next-line typescript/require-array-sort-compare\n const sorted = attr.slice().sort();\n if (sorted.length <= 5) {\n return sorted.join(', ');\n }\n\n return `${sorted.slice(0, 5).join(', ')}, +${sorted.length - 5}`;\n }\n\n return attr;\n}\n\n/**\n * Span name follows the GraphQL semantic conventions: `<operation.type> <operation.name>` when both\n * are available, `<operation.type>` when only the type is, otherwise a static fallback.\n */\nexport function getOperationSpanName(\n operationType: string | undefined,\n operationName: string | undefined,\n fallbackName: string,\n): string {\n if (operationType && operationName) {\n return `${operationType} ${operationName}`;\n }\n if (operationType) {\n return operationType;\n }\n\n return fallbackName;\n}\n\n/** Whether a graphql execution result carries GraphQL errors (returned on `result.errors`). */\nexport function hasResultErrors(result: unknown): boolean {\n if (isObjectLike(result) && 'errors' in result) {\n const errors = (result as { errors?: unknown }).errors;\n\n return Array.isArray(errors) && errors.length > 0;\n }\n\n return false;\n}\n\n/**\n * Serialize a parsed document into `graphql.document` while redacting every literal argument value:\n * the original source text is preserved verbatim except that string/number literal spans are\n * replaced (`\"foo\"` -> `\"*\"`, `42` -> `*`). graphql does not sanitize its channel payload, so this\n * prevents raw inline values (potential PII) from leaving the process. Variable values are never\n * included. Returns `undefined` (rather than throwing) on anything it cannot serialize.\n */\nfunction redactGraphqlDocument(document: GraphqlDocumentNode | undefined): string | undefined {\n const loc = document?.loc;\n const body = loc?.source?.body;\n if (typeof body !== 'string' || !loc?.startToken) {\n return undefined;\n }\n\n try {\n // Collect literal token spans, then splice them out back-to-front so earlier offsets stay valid.\n const ranges: Array<{ start: number; end: number; kind: string }> = [];\n for (let token: GraphqlToken | null | undefined = loc.startToken; token; token = token.next) {\n if (REDACTED_LITERAL_KINDS.has(token.kind)) {\n ranges.push({ start: token.start, end: token.end, kind: token.kind });\n }\n }\n\n let out = body;\n // Reverse index loop (not `for...of`) so we splice back-to-front.\n for (let i = ranges.length - 1; i >= 0; i--) {\n // oxlint-disable-next-line typescript/no-non-null-assertion -- `i` is bounded by the loop\n const { start, end, kind } = ranges[i]!;\n const replacement = kind === 'String' || kind === 'BlockString' ? '\"*\"' : '*';\n out = out.slice(0, start) + replacement + out.slice(end);\n }\n\n return out;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Returns the redacted document if `dataCollection.graphQL.document` is enabled, `undefined` otherwise.\n */\nexport function collectGraphqlDocument(document: GraphqlDocumentNode | undefined): string | undefined {\n if (getClient()?.getDataCollectionOptions().graphQL.document !== true) {\n return undefined;\n }\n return redactGraphqlDocument(document);\n}\n"],"mappings":";;;AAMA,MAAM,iCAAiC;AAKvC,MAAM,yCAAyB,IAAI,IAAI;CAAC;CAAO;CAAS;CAAU;AAAa,CAAC;;;;;AAMhF,SAAgB,4BAA4B,MAAY,eAAuB,eAA8B;CAC3G,MAAM,WAAW,YAAY,IAAI;CAEjC,IAAI,aAAa,MACf;CAGF,MAAM,eAAe,WAAW,QAAQ;CAExC,MAAM,eAAe,gBAAgB,GAAG,cAAc,GAAG,kBAAkB;CAG3E,MAAM,qBAAqB,aAAa,WAAW;CACnD,IAAI;CACJ,IAAI,MAAM,QAAQ,kBAAkB,GAClC,aAAa,CAAC,GAAI,oBAAiC,YAAY;MAC1D,IAAI,OAAO,uBAAuB,UACvC,aAAa,CAAC,oBAAoB,YAAY;M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KAAK;GAAE,OAAO,MAAM;GAAO,KAAK,MAAM;GAAK,MAAM,MAAM;EAAK,CAAC;EAIxE,IAAI,MAAM;EAEV,KAAK,IAAI,IAAI,OAAO,SAAS,GAAG,KAAK,GAAG,KAAK;GAE3C,MAAM,EAAE,OAAO,KAAK,SAAS,OAAO;GACpC,MAAM,cAAc,SAAS,YAAY,SAAS,gBAAgB,UAAQ;GAC1E,MAAM,IAAI,MAAM,GAAG,KAAK,IAAI,cAAc,IAAI,MAAM,GAAG;EACzD;EAEA,OAAO;CACT,QAAQ;EACN;CACF;AACF;;;;AAKA,SAAgB,uBAAuB,UAA+D;CACpG,IAAI,UAAU,CAAC,EAAE,yBAAyB,CAAC,CAAC,QAAQ,aAAa,MAC/D;CAEF,OAAO,sBAAsB,QAAQ;AACvC"}
|
|
@@ -138,7 +138,7 @@ function wrapRouteHandler(route, pluginName) {
|
|
|
138
138
|
*/
|
|
139
139
|
function wrapExtMethods(method, extPoint, pluginName) {
|
|
140
140
|
if (Array.isArray(method)) {
|
|
141
|
-
for (
|
|
141
|
+
for (const [i, m] of method.entries()) method[i] = wrapExtMethods(m, extPoint);
|
|
142
142
|
return method;
|
|
143
143
|
} else if (isPatchableExtMethod(method)) {
|
|
144
144
|
if (method[handlerPatched] === true) return method;
|
|
@@ -159,7 +159,7 @@ function wrapExtMethods(method, extPoint, pluginName) {
|
|
|
159
159
|
*/
|
|
160
160
|
function wrapRouteArguments(args, pluginName) {
|
|
161
161
|
const route = args[0];
|
|
162
|
-
if (Array.isArray(route)) for (
|
|
162
|
+
if (Array.isArray(route)) for (const [i, r] of route.entries()) route[i] = wrapRouteHandler(r, pluginName);
|
|
163
163
|
else args[0] = wrapRouteHandler(route, pluginName);
|
|
164
164
|
}
|
|
165
165
|
/**
|
|
@@ -171,13 +171,10 @@ function wrapRouteArguments(args, pluginName) {
|
|
|
171
171
|
function wrapExtArguments(args, pluginName) {
|
|
172
172
|
if (Array.isArray(args[0])) {
|
|
173
173
|
const eventsList = args[0];
|
|
174
|
-
for (
|
|
175
|
-
const
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
lifecycleEventObj.method = wrapExtMethods(lifecycleEventObj.method, eventObj.type, pluginName);
|
|
179
|
-
eventsList[i] = lifecycleEventObj;
|
|
180
|
-
}
|
|
174
|
+
for (const [i, eventObj] of eventsList.entries()) if (isLifecycleExtType(eventObj.type)) {
|
|
175
|
+
const lifecycleEventObj = eventObj;
|
|
176
|
+
lifecycleEventObj.method = wrapExtMethods(lifecycleEventObj.method, eventObj.type, pluginName);
|
|
177
|
+
eventsList[i] = lifecycleEventObj;
|
|
181
178
|
}
|
|
182
179
|
return;
|
|
183
180
|
} else if (isDirectExtInput(args)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hapi-utils.js","names":[],"sources":["../../../../src/integrations/hapi/hapi-utils.ts"],"sourcesContent":["/*\n * OTel-free, `@hapi/*`-free port of the span-building helpers and handler/ext\n * wrap logic from the vendored `@opentelemetry/instrumentation-hapi`\n * (upstream @opentelemetry/instrumentation-hapi@0.64.0). Span output (names,\n * origins, attributes) is kept close to that instrumentation — except the\n * span ops, which are normalized to cross-framework ops (`handler` for plugin\n * routes, `router` for routes, `middleware` for server extensions); span\n * creation goes through the `@sentry/core` API and the OTel active-span guard\n * is replaced with `getActiveSpan()`.\n */\n\nimport {\n getActiveSpan,\n getClient,\n hasSpanStreamingEnabled,\n isObjectLike,\n REQUEST_HANDLER_SPAN_NAME_FALLBACK,\n ROUTER_SPAN_NAME_FALLBACK,\n startSpan,\n} from '@sentry/core';\nimport {\n HAPI_EXT_TYPE,\n HAPI_PLUGIN_NAME,\n HAPI_TYPE,\n HTTP_REQUEST_METHOD,\n HTTP_ROUTE,\n SENTRY_OP,\n SENTRY_ORIGIN,\n SERVER_EXT_TYPE,\n} from '@sentry/conventions/attributes';\nimport { HANDLER, MIDDLEWARE, ROUTER } from '@sentry/conventions/op';\nimport type {\n HapiRequest,\n LifecycleMethod,\n PatchableExtMethod,\n PatchableServerRoute,\n ServerExtDirectInput,\n ServerExtEventsObject,\n ServerExtEventsRequestObject,\n ServerRequestExtType,\n ServerRouteOptions,\n} from './hapi-types';\nimport { handlerPatched, HapiLayerType, HapiLifecycleMethodNames } from './hapi-types';\nimport { setHttpServerSpanRouteAttribute } from '../../utils/setHttpServerSpanRouteAttribute';\n\n/**\n * Default function deciding whether an error should be sent to Sentry.\n *\n * Captures 5xx errors and any error whose status can't be resolved; skips 3xx\n * and 4xx (client errors / redirects) and 2xx-and-below outliers are captured\n * as they usually signal an unmapped thrown error. Mirrors the defaults used by\n * the other server framework integrations.\n */\nexport function defaultShouldHandleError(error: unknown, request: HapiRequest): boolean {\n const statusCode = getResponseStatusCode(request, error);\n if (typeof statusCode !== 'number') {\n return true;\n }\n // 3xx and 4xx errors are not sent by default.\n return statusCode >= 500 || statusCode <= 299;\n}\n\n/**\n * Resolve the HTTP status for an errored hapi request: prefer the resolved\n * response (Boom `output.statusCode`, else `statusCode`), falling back to a Boom\n * error passed directly.\n */\nfunction getResponseStatusCode(request: HapiRequest, error: unknown): number | undefined {\n const response = request.response;\n if (isObjectLike(response)) {\n if (response.isBoom && isObjectLike(response.output) && typeof response.output.statusCode === 'number') {\n return response.output.statusCode;\n }\n if (typeof response.statusCode === 'number') {\n return response.statusCode;\n }\n }\n\n if (isObjectLike(error) && isObjectLike(error.output) && typeof error.output.statusCode === 'number') {\n return error.output.statusCode;\n }\n\n return undefined;\n}\n\ntype SpanAttributes = Record<string, string | undefined>;\n\ninterface SpanMetadata {\n attributes: SpanAttributes;\n name: string;\n}\n\nconst isLifecycleExtType = (variableToCheck: unknown): variableToCheck is ServerRequestExtType => {\n return typeof variableToCheck === 'string' && HapiLifecycleMethodNames.has(variableToCheck);\n};\n\nconst isLifecycleExtEventObj = (variableToCheck: unknown): variableToCheck is ServerExtEventsRequestObject => {\n const event = (variableToCheck as ServerExtEventsRequestObject)?.type;\n return event !== undefined && isLifecycleExtType(event);\n};\n\nconst isDirectExtInput = (variableToCheck: unknown): variableToCheck is ServerExtDirectInput => {\n return (\n Array.isArray(variableToCheck) &&\n variableToCheck.length <= 3 &&\n isLifecycleExtType(variableToCheck[0]) &&\n typeof variableToCheck[1] === 'function'\n );\n};\n\nconst isPatchableExtMethod = (\n variableToCheck: PatchableExtMethod | PatchableExtMethod[],\n): variableToCheck is PatchableExtMethod => {\n return !Array.isArray(variableToCheck);\n};\n\n/** Build the span name and attributes for a Hapi route. */\nexport const getRouteMetadata = ({\n path,\n method,\n pluginName,\n}: {\n path: string;\n method?: string;\n pluginName?: string;\n}): SpanMetadata => {\n const attributes: SpanAttributes = {\n [HTTP_ROUTE]: path,\n [HTTP_REQUEST_METHOD]: method,\n };\n\n if (pluginName) {\n attributes[HAPI_TYPE] = HapiLayerType.PLUGIN;\n attributes[HAPI_PLUGIN_NAME] = pluginName;\n } else {\n attributes[HAPI_TYPE] = HapiLayerType.ROUTER;\n }\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so router and request\n // handler spans are named after their route alone, without the method prefix.\n const isStreamedSpan = !!client && hasSpanStreamingEnabled(client);\n const fallbackName = pluginName ? REQUEST_HANDLER_SPAN_NAME_FALLBACK : ROUTER_SPAN_NAME_FALLBACK;\n const staticName = method ? `${method} ${path}` : path;\n\n return {\n attributes,\n name: isStreamedSpan ? path || fallbackName : staticName,\n };\n};\n\n/** Build the span name and attributes for a Hapi server extension. */\nexport const getExtMetadata = (\n extPoint: ServerRequestExtType,\n pluginName?: string,\n methodName?: string,\n): SpanMetadata => {\n let baseName = `ext - ${extPoint}`;\n if (methodName && methodName !== 'method') {\n // `method` is the default name for the extension in the ServerExtEventsObject format.\n baseName = `ext - ${extPoint} - ${methodName}`;\n }\n const attributes: SpanAttributes = {\n [HAPI_EXT_TYPE]: extPoint,\n // TODO(v12): Remove `server.ext.type`, which `hapi.ext.type` replaces.\n // oxlint-disable-next-line typescript/no-deprecated\n [SERVER_EXT_TYPE]: extPoint,\n [HAPI_TYPE]: HapiLayerType.EXT,\n };\n if (pluginName) {\n return {\n attributes: { ...attributes, [HAPI_PLUGIN_NAME]: pluginName },\n name: `${pluginName}: ${baseName}`,\n };\n }\n return { attributes, name: baseName };\n};\n\nconst HAPI_TYPE_TO_SPAN_OP: Record<string, string> = {\n [HapiLayerType.PLUGIN]: HANDLER,\n [HapiLayerType.ROUTER]: ROUTER,\n [HapiLayerType.EXT]: MIDDLEWARE,\n};\n\nfunction startMetadataSpan(metadata: SpanMetadata, original: () => unknown): unknown {\n const hapiType = metadata.attributes[HAPI_TYPE];\n const op = hapiType ? HAPI_TYPE_TO_SPAN_OP[hapiType] : undefined;\n return startSpan(\n {\n name: metadata.name,\n attributes: {\n ...metadata.attributes,\n [SENTRY_OP]: op,\n [SENTRY_ORIGIN]: 'auto.http.hapi',\n },\n },\n original,\n );\n}\n\n// The route config can register several methods (or `'*'`), so read the method\n// Hapi resolved for this request instead.\nfunction getRequestMethod(request: unknown): string | undefined {\n return isObjectLike(request) && typeof request.method === 'string' ? request.method.toUpperCase() : undefined;\n}\n\n/**\n * Patches each individual route handler method in order to create the span. It\n * does not create spans when there is no parent span.\n */\nfunction wrapRouteHandler(route: PatchableServerRoute, pluginName?: string): PatchableServerRoute {\n if (route[handlerPatched] === true) return route;\n route[handlerPatched] = true;\n\n const wrapHandler: (oldHandler: LifecycleMethod) => LifecycleMethod = oldHandler => {\n return function (this: unknown, ...params: Parameters<LifecycleMethod>) {\n if (!getActiveSpan()) {\n return oldHandler.call(this, ...params);\n }\n setHttpServerSpanRouteAttribute(route.path);\n const metadata = getRouteMetadata({ path: route.path, method: getRequestMethod(params[0]), pluginName });\n return startMetadataSpan(metadata, () => oldHandler.call(this, ...params));\n };\n };\n\n if (typeof route.handler === 'function') {\n route.handler = wrapHandler(route.handler as LifecycleMethod);\n } else if (typeof route.options === 'function') {\n const oldOptions = route.options;\n route.options = function (server: unknown): ServerRouteOptions {\n const options = oldOptions(server);\n if (typeof options.handler === 'function') {\n options.handler = wrapHandler(options.handler as LifecycleMethod);\n }\n return options;\n };\n } else if (typeof route.options?.handler === 'function') {\n route.options.handler = wrapHandler(route.options.handler as LifecycleMethod);\n }\n return route;\n}\n\n/**\n * Wraps request extension methods to add instrumentation to each new extension\n * handler. It does not create spans when there is no parent span.\n */\nfunction wrapExtMethods<T extends PatchableExtMethod | PatchableExtMethod[]>(\n method: T,\n extPoint: ServerRequestExtType,\n pluginName?: string,\n): T {\n if (Array.isArray(method)) {\n for (let i = 0; i < method.length; i++) {\n method[i] = wrapExtMethods(method[i]!, extPoint);\n }\n return method;\n } else if (isPatchableExtMethod(method)) {\n if (method[handlerPatched] === true) return method;\n method[handlerPatched] = true;\n\n const newHandler: PatchableExtMethod = function (this: unknown, ...params: Parameters<LifecycleMethod>) {\n if (!getActiveSpan()) {\n return method.apply(this, params);\n }\n const metadata = getExtMetadata(extPoint, pluginName, method.name);\n return startMetadataSpan(metadata, () => method.apply(undefined, params));\n };\n // Mark the wrapper too (not just the original)\n newHandler[handlerPatched] = true;\n return newHandler as T;\n }\n return method;\n}\n\n/**\n * Wrap the route handler(s) in the live `server.route` arguments array, mutating\n * `args[0]` in place. `args[0]` is either a single route options object or an\n * array of them. Idempotent via the `handlerPatched` marker.\n */\nexport function wrapRouteArguments(args: unknown[], pluginName?: string): void {\n const route = args[0] as PatchableServerRoute | PatchableServerRoute[];\n if (Array.isArray(route)) {\n for (let i = 0; i < route.length; i++) {\n route[i] = wrapRouteHandler(route[i]!, pluginName);\n }\n } else {\n args[0] = wrapRouteHandler(route, pluginName);\n }\n}\n\n/**\n * Wrap the extension method(s) in the live `server.ext` arguments array,\n * mutating `args` in place. Handles the three accepted input shapes:\n * `(eventsArray)`, `(lifecycleEventObject)`, and `(extTypeString, method, options)`.\n * Idempotent via the `handlerPatched` marker.\n */\nexport function wrapExtArguments(args: unknown[], pluginName?: string): void {\n if (Array.isArray(args[0])) {\n const eventsList = args[0] as ServerExtEventsObject[] | ServerExtEventsRequestObject[];\n for (let i = 0; i < eventsList.length; i++) {\n const eventObj = eventsList[i]!;\n if (isLifecycleExtType(eventObj.type)) {\n const lifecycleEventObj = eventObj as ServerExtEventsRequestObject;\n const handler = wrapExtMethods(lifecycleEventObj.method, eventObj.type, pluginName);\n lifecycleEventObj.method = handler;\n eventsList[i] = lifecycleEventObj;\n }\n }\n return;\n } else if (isDirectExtInput(args)) {\n const extInput: ServerExtDirectInput = args;\n const method: PatchableExtMethod = extInput[1];\n const handler = wrapExtMethods(method, extInput[0], pluginName);\n args[1] = handler;\n return;\n } else if (isLifecycleExtEventObj(args[0])) {\n const lifecycleEventObj = args[0];\n const handler = wrapExtMethods(lifecycleEventObj.method, lifecycleEventObj.type, pluginName);\n lifecycleEventObj.method = handler;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAqDA,SAAgB,yBAAyB,OAAgB,SAA+B;CACtF,MAAM,aAAa,sBAAsB,SAAS,KAAK;CACvD,IAAI,OAAO,eAAe,UACxB,OAAO;CAGT,OAAO,cAAc,OAAO,cAAc;AAC5C;;;;;;AAOA,SAAS,sBAAsB,SAAsB,OAAoC;CACvF,MAAM,WAAW,QAAQ;CACzB,IAAI,aAAa,QAAQ,GAAG;EAC1B,IAAI,SAAS,UAAU,aAAa,SAAS,MAAM,KAAK,OAAO,SAAS,OAAO,eAAe,UAC5F,OAAO,SAAS,OAAO;EAEzB,IAAI,OAAO,SAAS,eAAe,UACjC,OAAO,SAAS;CAEpB;CAEA,IAAI,aAAa,KAAK,KAAK,aAAa,MAAM,MAAM,KAAK,OAAO,MAAM,OAAO,eAAe,UAC1F,OAAO,MAAM,OAAO;AAIxB;AASA,MAAM,sBAAsB,oBAAsE;CAChG,OAAO,OAAO,oBAAoB,YAAY,yBAAyB,IAAI,eAAe;AAC5F;AAEA,MAAM,0BAA0B,oBAA8E;CAC5G,MAAM,QAAS,iBAAkD;CACjE,OAAO,UAAU,KAAA,KAAa,mBAAmB,KAAK;AACxD;AAEA,MAAM,oBAAoB,oBAAsE;CAC9F,OACE,MAAM,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C,cAAc,GACjB,OAAO,OAAO,MAAM,MAAM,MAAM;GAGlC,OAAO,kBADU,eAAe,UAAU,YAAY,OAAO,IAC7B,SAAS,OAAO,MAAM,KAAA,GAAW,MAAM,CAAC;EAC1E;EAEA,WAAW,kBAAkB;EAC7B,OAAO;CACT;CACA,OAAO;AACT;;;;;;AAOA,SAAgB,mBAAmB,MAAiB,YAA2B;CAC7E,MAAM,QAAQ,KAAK;CACnB,IAAI,MAAM,QAAQ,KAAK,GACrB,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAChC,MAAM,KAAK,iBAAiB,MAAM,IAAK,UAAU;MAGnD,KAAK,KAAK,iBAAiB,OAAO,UAAU;AAEhD;;;;;;;AAQA,SAAgB,iBAAiB,MAAiB,YAA2B;CAC3E,IAAI,MAAM,QAAQ,KAAK,EAAE,GAAG;EAC1B,MAAM,aAAa,KAAK;EACxB,KAAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,KAAK;GAC1C,MAAM,WAAW,WAAW;GAC5B,IAAI,mBAAmB,SAAS,IAAI,GAAG;IACrC,MAAM,oBAAoB;IAE1B,kBAAkB,SADF,eAAe,kBAAkB,QAAQ,SAAS,MAAM,UACvC;IACjC,WAAW,KAAK;GAClB;EACF;EACA;CACF,OAAO,IAAI,iBAAiB,IAAI,GAAG;EACjC,MAAM,WAAiC;EACvC,MAAM,SAA6B,SAAS;EAE5C,KAAK,KADW,eAAe,QAAQ,SAAS,IAAI,UACpC;EAChB;CACF,OAAO,IAAI,uBAAuB,KAAK,EAAE,GAAG;EAC1C,MAAM,oBAAoB,KAAK;EAE/B,kBAAkB,SADF,eAAe,kBAAkB,QAAQ,kBAAkB,MAAM,UAChD;CACnC;AACF"}
|
|
1
|
+
{"version":3,"file":"hapi-utils.js","names":[],"sources":["../../../../src/integrations/hapi/hapi-utils.ts"],"sourcesContent":["/*\n * OTel-free, `@hapi/*`-free port of the span-building helpers and handler/ext\n * wrap logic from the vendored `@opentelemetry/instrumentation-hapi`\n * (upstream @opentelemetry/instrumentation-hapi@0.64.0). Span output (names,\n * origins, attributes) is kept close to that instrumentation — except the\n * span ops, which are normalized to cross-framework ops (`handler` for plugin\n * routes, `router` for routes, `middleware` for server extensions); span\n * creation goes through the `@sentry/core` API and the OTel active-span guard\n * is replaced with `getActiveSpan()`.\n */\n\nimport {\n getActiveSpan,\n getClient,\n hasSpanStreamingEnabled,\n isObjectLike,\n REQUEST_HANDLER_SPAN_NAME_FALLBACK,\n ROUTER_SPAN_NAME_FALLBACK,\n startSpan,\n} from '@sentry/core';\nimport {\n HAPI_EXT_TYPE,\n HAPI_PLUGIN_NAME,\n HAPI_TYPE,\n HTTP_REQUEST_METHOD,\n HTTP_ROUTE,\n SENTRY_OP,\n SENTRY_ORIGIN,\n SERVER_EXT_TYPE,\n} from '@sentry/conventions/attributes';\nimport { HANDLER, MIDDLEWARE, ROUTER } from '@sentry/conventions/op';\nimport type {\n HapiRequest,\n LifecycleMethod,\n PatchableExtMethod,\n PatchableServerRoute,\n ServerExtDirectInput,\n ServerExtEventsObject,\n ServerExtEventsRequestObject,\n ServerRequestExtType,\n ServerRouteOptions,\n} from './hapi-types';\nimport { handlerPatched, HapiLayerType, HapiLifecycleMethodNames } from './hapi-types';\nimport { setHttpServerSpanRouteAttribute } from '../../utils/setHttpServerSpanRouteAttribute';\n\n/**\n * Default function deciding whether an error should be sent to Sentry.\n *\n * Captures 5xx errors and any error whose status can't be resolved; skips 3xx\n * and 4xx (client errors / redirects) and 2xx-and-below outliers are captured\n * as they usually signal an unmapped thrown error. Mirrors the defaults used by\n * the other server framework integrations.\n */\nexport function defaultShouldHandleError(error: unknown, request: HapiRequest): boolean {\n const statusCode = getResponseStatusCode(request, error);\n if (typeof statusCode !== 'number') {\n return true;\n }\n // 3xx and 4xx errors are not sent by default.\n return statusCode >= 500 || statusCode <= 299;\n}\n\n/**\n * Resolve the HTTP status for an errored hapi request: prefer the resolved\n * response (Boom `output.statusCode`, else `statusCode`), falling back to a Boom\n * error passed directly.\n */\nfunction getResponseStatusCode(request: HapiRequest, error: unknown): number | undefined {\n const response = request.response;\n if (isObjectLike(response)) {\n if (response.isBoom && isObjectLike(response.output) && typeof response.output.statusCode === 'number') {\n return response.output.statusCode;\n }\n if (typeof response.statusCode === 'number') {\n return response.statusCode;\n }\n }\n\n if (isObjectLike(error) && isObjectLike(error.output) && typeof error.output.statusCode === 'number') {\n return error.output.statusCode;\n }\n\n return undefined;\n}\n\ntype SpanAttributes = Record<string, string | undefined>;\n\ninterface SpanMetadata {\n attributes: SpanAttributes;\n name: string;\n}\n\nconst isLifecycleExtType = (variableToCheck: unknown): variableToCheck is ServerRequestExtType => {\n return typeof variableToCheck === 'string' && HapiLifecycleMethodNames.has(variableToCheck);\n};\n\nconst isLifecycleExtEventObj = (variableToCheck: unknown): variableToCheck is ServerExtEventsRequestObject => {\n const event = (variableToCheck as ServerExtEventsRequestObject)?.type;\n return event !== undefined && isLifecycleExtType(event);\n};\n\nconst isDirectExtInput = (variableToCheck: unknown): variableToCheck is ServerExtDirectInput => {\n return (\n Array.isArray(variableToCheck) &&\n variableToCheck.length <= 3 &&\n isLifecycleExtType(variableToCheck[0]) &&\n typeof variableToCheck[1] === 'function'\n );\n};\n\nconst isPatchableExtMethod = (\n variableToCheck: PatchableExtMethod | PatchableExtMethod[],\n): variableToCheck is PatchableExtMethod => {\n return !Array.isArray(variableToCheck);\n};\n\n/** Build the span name and attributes for a Hapi route. */\nexport const getRouteMetadata = ({\n path,\n method,\n pluginName,\n}: {\n path: string;\n method?: string;\n pluginName?: string;\n}): SpanMetadata => {\n const attributes: SpanAttributes = {\n [HTTP_ROUTE]: path,\n [HTTP_REQUEST_METHOD]: method,\n };\n\n if (pluginName) {\n attributes[HAPI_TYPE] = HapiLayerType.PLUGIN;\n attributes[HAPI_PLUGIN_NAME] = pluginName;\n } else {\n attributes[HAPI_TYPE] = HapiLayerType.ROUTER;\n }\n\n const client = getClient();\n // With span streaming, span names have to be low cardinality, so router and request\n // handler spans are named after their route alone, without the method prefix.\n const isStreamedSpan = !!client && hasSpanStreamingEnabled(client);\n const fallbackName = pluginName ? REQUEST_HANDLER_SPAN_NAME_FALLBACK : ROUTER_SPAN_NAME_FALLBACK;\n const staticName = method ? `${method} ${path}` : path;\n\n return {\n attributes,\n name: isStreamedSpan ? path || fallbackName : staticName,\n };\n};\n\n/** Build the span name and attributes for a Hapi server extension. */\nexport const getExtMetadata = (\n extPoint: ServerRequestExtType,\n pluginName?: string,\n methodName?: string,\n): SpanMetadata => {\n let baseName = `ext - ${extPoint}`;\n if (methodName && methodName !== 'method') {\n // `method` is the default name for the extension in the ServerExtEventsObject format.\n baseName = `ext - ${extPoint} - ${methodName}`;\n }\n const attributes: SpanAttributes = {\n [HAPI_EXT_TYPE]: extPoint,\n // TODO(v12): Remove `server.ext.type`, which `hapi.ext.type` replaces.\n // oxlint-disable-next-line typescript/no-deprecated\n [SERVER_EXT_TYPE]: extPoint,\n [HAPI_TYPE]: HapiLayerType.EXT,\n };\n if (pluginName) {\n return {\n attributes: { ...attributes, [HAPI_PLUGIN_NAME]: pluginName },\n name: `${pluginName}: ${baseName}`,\n };\n }\n return { attributes, name: baseName };\n};\n\nconst HAPI_TYPE_TO_SPAN_OP: Record<string, string> = {\n [HapiLayerType.PLUGIN]: HANDLER,\n [HapiLayerType.ROUTER]: ROUTER,\n [HapiLayerType.EXT]: MIDDLEWARE,\n};\n\nfunction startMetadataSpan(metadata: SpanMetadata, original: () => unknown): unknown {\n const hapiType = metadata.attributes[HAPI_TYPE];\n const op = hapiType ? HAPI_TYPE_TO_SPAN_OP[hapiType] : undefined;\n return startSpan(\n {\n name: metadata.name,\n attributes: {\n ...metadata.attributes,\n [SENTRY_OP]: op,\n [SENTRY_ORIGIN]: 'auto.http.hapi',\n },\n },\n original,\n );\n}\n\n// The route config can register several methods (or `'*'`), so read the method\n// Hapi resolved for this request instead.\nfunction getRequestMethod(request: unknown): string | undefined {\n return isObjectLike(request) && typeof request.method === 'string' ? request.method.toUpperCase() : undefined;\n}\n\n/**\n * Patches each individual route handler method in order to create the span. It\n * does not create spans when there is no parent span.\n */\nfunction wrapRouteHandler(route: PatchableServerRoute, pluginName?: string): PatchableServerRoute {\n if (route[handlerPatched] === true) return route;\n route[handlerPatched] = true;\n\n const wrapHandler: (oldHandler: LifecycleMethod) => LifecycleMethod = oldHandler => {\n return function (this: unknown, ...params: Parameters<LifecycleMethod>) {\n if (!getActiveSpan()) {\n return oldHandler.call(this, ...params);\n }\n setHttpServerSpanRouteAttribute(route.path);\n const metadata = getRouteMetadata({ path: route.path, method: getRequestMethod(params[0]), pluginName });\n return startMetadataSpan(metadata, () => oldHandler.call(this, ...params));\n };\n };\n\n if (typeof route.handler === 'function') {\n route.handler = wrapHandler(route.handler as LifecycleMethod);\n } else if (typeof route.options === 'function') {\n const oldOptions = route.options;\n route.options = function (server: unknown): ServerRouteOptions {\n const options = oldOptions(server);\n if (typeof options.handler === 'function') {\n options.handler = wrapHandler(options.handler as LifecycleMethod);\n }\n return options;\n };\n } else if (typeof route.options?.handler === 'function') {\n route.options.handler = wrapHandler(route.options.handler as LifecycleMethod);\n }\n return route;\n}\n\n/**\n * Wraps request extension methods to add instrumentation to each new extension\n * handler. It does not create spans when there is no parent span.\n */\nfunction wrapExtMethods<T extends PatchableExtMethod | PatchableExtMethod[]>(\n method: T,\n extPoint: ServerRequestExtType,\n pluginName?: string,\n): T {\n if (Array.isArray(method)) {\n for (const [i, m] of method.entries()) {\n method[i] = wrapExtMethods(m, extPoint);\n }\n return method;\n } else if (isPatchableExtMethod(method)) {\n if (method[handlerPatched] === true) return method;\n method[handlerPatched] = true;\n\n const newHandler: PatchableExtMethod = function (this: unknown, ...params: Parameters<LifecycleMethod>) {\n if (!getActiveSpan()) {\n return method.apply(this, params);\n }\n const metadata = getExtMetadata(extPoint, pluginName, method.name);\n return startMetadataSpan(metadata, () => method.apply(undefined, params));\n };\n // Mark the wrapper too (not just the original)\n newHandler[handlerPatched] = true;\n return newHandler as T;\n }\n return method;\n}\n\n/**\n * Wrap the route handler(s) in the live `server.route` arguments array, mutating\n * `args[0]` in place. `args[0]` is either a single route options object or an\n * array of them. Idempotent via the `handlerPatched` marker.\n */\nexport function wrapRouteArguments(args: unknown[], pluginName?: string): void {\n const route = args[0] as PatchableServerRoute | PatchableServerRoute[];\n if (Array.isArray(route)) {\n for (const [i, r] of route.entries()) {\n route[i] = wrapRouteHandler(r, pluginName);\n }\n } else {\n args[0] = wrapRouteHandler(route, pluginName);\n }\n}\n\n/**\n * Wrap the extension method(s) in the live `server.ext` arguments array,\n * mutating `args` in place. Handles the three accepted input shapes:\n * `(eventsArray)`, `(lifecycleEventObject)`, and `(extTypeString, method, options)`.\n * Idempotent via the `handlerPatched` marker.\n */\nexport function wrapExtArguments(args: unknown[], pluginName?: string): void {\n if (Array.isArray(args[0])) {\n const eventsList = args[0] as ServerExtEventsObject[] | ServerExtEventsRequestObject[];\n for (const [i, eventObj] of eventsList.entries()) {\n if (isLifecycleExtType(eventObj.type)) {\n const lifecycleEventObj = eventObj as ServerExtEventsRequestObject;\n const handler = wrapExtMethods(lifecycleEventObj.method, eventObj.type, pluginName);\n lifecycleEventObj.method = handler;\n eventsList[i] = lifecycleEventObj;\n }\n }\n return;\n } else if (isDirectExtInput(args)) {\n const extInput: ServerExtDirectInput = args;\n const method: PatchableExtMethod = extInput[1];\n const handler = wrapExtMethods(method, extInput[0], pluginName);\n args[1] = handler;\n return;\n } else if (isLifecycleExtEventObj(args[0])) {\n const lifecycleEventObj = args[0];\n const handler = wrapExtMethods(lifecycleEventObj.method, lifecycleEventObj.type, pluginName);\n lifecycleEventObj.method = handler;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAqDA,SAAgB,yBAAyB,OAAgB,SAA+B;CACtF,MAAM,aAAa,sBAAsB,SAAS,KAAK;CACvD,IAAI,OAAO,eAAe,UACxB,OAAO;CAGT,OAAO,cAAc,OAAO,cAAc;AAC5C;;;;;;AAOA,SAAS,sBAAsB,S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,kBAAkB,SADF,eAAe,kBAAkB,QAAQ,SAAS,MAAM,UACvC;GACjC,WAAW,KAAK;EAClB;EAEF;CACF,OAAO,IAAI,iBAAiB,IAAI,GAAG;EACjC,MAAM,WAAiC;EACvC,MAAM,SAA6B,SAAS;EAE5C,KAAK,KADW,eAAe,QAAQ,SAAS,IAAI,UACpC;EAChB;CACF,OAAO,IAAI,uBAAuB,KAAK,EAAE,GAAG;EAC1C,MAAM,oBAAoB,KAAK;EAE/B,kBAAkB,SADF,eAAe,kBAAkB,QAAQ,kBAAkB,MAAM,UAChD;CACnC;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"isMiddleware.js","names":[],"sources":["../../../../src/integrations/hono/isMiddleware.ts"],"sourcesContent":["import type { HonoRoute } from './honoTypes';\n\n// Hono stores the original (unwrapped) handler under this key when it wraps a sub-app's handlers\n// for a custom `onError`. Unwrapping it lets us inspect the real handler instead of the wrapper.\n// See https://github.com/honojs/hono/blob/9f0dadf141a3242a6c3b77462c7d33c6ce0f599d/src/hono-base.ts#L224-L226\nconst COMPOSED_HANDLER = '__COMPOSED_HANDLER';\n\n/**\n * Infers whether a Hono route entry is a middleware (rather than a route handler).\n *\n * Hono has no \"isMiddleware\" flag, so we rely on arity: middleware is `(context, next)` (arity >= 2)\n * while route handlers are `(context)` (arity < 2). `onError`-wrapped sub-app handlers are unwrapped\n * first so we check the original handler's arity, not the wrapper's `(c, next)` signature.\n * https://github.com/honojs/hono/blob/97c6fe1f12298c715eb7b2da65b4b6e0d81682bb/src/utils/handler.ts#L8\n *\n * This is only one signal — callers that must classify inline middleware sharing a method+path with\n * their handler additionally need positional information (`getMiddlewareFlags`).\n */\nexport function isMiddleware(handler: unknown): boolean {\n if (typeof handler !== 'function') {\n return false;\n }\n\n const composed = (handler as unknown as Record<string, unknown>)[COMPOSED_HANDLER];\n const original = typeof composed === 'function' ? composed : handler;\n\n return (original as (...args: unknown[]) => unknown).length >= 2;\n}\n\n/**\n * Tells for each route if it is a middleware. Hono has no flag for this. In a method+path group, the\n * last handler is the route handler (`app.get('/path', mw, handler)`). `.use()` adds middleware with\n * method `ALL` and no route handler, so for `ALL` routes the arity also counts. Arity alone is not\n * enough, because a route handler can declare an unused `next`.\n */\nexport function getMiddlewareFlags(routes: HonoRoute[]): boolean[] {\n // `\\0` cannot appear in an HTTP method or a URL path.\n const groupKey = (route: HonoRoute): string => `${route.method}\\0${route.path}`;\n const lastIndexByKey = new Map(routes.map((route, i) => [groupKey(route), i]));\n\n return routes.map(\n (route, i) => lastIndexByKey.get(groupKey(route)) !== i || (route.method === 'ALL' && isMiddleware(route.handler)),\n );\n}\n"],"mappings":";
|
|
1
|
+
{"version":3,"file":"isMiddleware.js","names":[],"sources":["../../../../src/integrations/hono/isMiddleware.ts"],"sourcesContent":["import type { HonoRoute } from './honoTypes';\n\n// Hono 4 stores the original (unwrapped) handler under this key when it wraps a sub-app's handlers\n// for a custom `onError`. Unwrapping it lets us inspect the real handler instead of the wrapper.\n// Hono 5 does not wrap them.\n// See https://github.com/honojs/hono/blob/9f0dadf141a3242a6c3b77462c7d33c6ce0f599d/src/hono-base.ts#L224-L226\nconst COMPOSED_HANDLER = '__COMPOSED_HANDLER';\n\n/**\n * Infers whether a Hono route entry is a middleware (rather than a route handler).\n *\n * Hono has no \"isMiddleware\" flag, so we rely on arity: middleware is `(context, next)` (arity >= 2)\n * while route handlers are `(context)` (arity < 2). `onError`-wrapped sub-app handlers are unwrapped\n * first so we check the original handler's arity, not the wrapper's `(c, next)` signature.\n * https://github.com/honojs/hono/blob/97c6fe1f12298c715eb7b2da65b4b6e0d81682bb/src/utils/handler.ts#L8\n *\n * This is only one signal — callers that must classify inline middleware sharing a method+path with\n * their handler additionally need positional information (`getMiddlewareFlags`).\n */\nexport function isMiddleware(handler: unknown): boolean {\n if (typeof handler !== 'function') {\n return false;\n }\n\n const composed = (handler as unknown as Record<string, unknown>)[COMPOSED_HANDLER];\n const original = typeof composed === 'function' ? composed : handler;\n\n return (original as (...args: unknown[]) => unknown).length >= 2;\n}\n\n/**\n * Tells for each route if it is a middleware. Hono has no flag for this. In a method+path group, the\n * last handler is the route handler (`app.get('/path', mw, handler)`). `.use()` adds middleware with\n * method `ALL` and no route handler, so for `ALL` routes the arity also counts. Arity alone is not\n * enough, because a route handler can declare an unused `next`.\n */\nexport function getMiddlewareFlags(routes: HonoRoute[]): boolean[] {\n // `\\0` cannot appear in an HTTP method or a URL path.\n const groupKey = (route: HonoRoute): string => `${route.method}\\0${route.path}`;\n const lastIndexByKey = new Map(routes.map((route, i) => [groupKey(route), i]));\n\n return routes.map(\n (route, i) => lastIndexByKey.get(groupKey(route)) !== i || (route.method === 'ALL' && isMiddleware(route.handler)),\n );\n}\n"],"mappings":";AAMA,MAAM,mBAAmB;;;;;;;;;;;;AAazB,SAAgB,aAAa,SAA2B;CACtD,IAAI,OAAO,YAAY,YACrB,OAAO;CAGT,MAAM,WAAY,QAA+C;CAGjE,QAFiB,OAAO,aAAa,aAAa,WAAW,QAAA,CAER,UAAU;AACjE;;;;;;;AAQA,SAAgB,mBAAmB,QAAgC;CAEjE,MAAM,YAAY,UAA6B,GAAG,MAAM,OAAO,IAAI,MAAM;CACzE,MAAM,iBAAiB,IAAI,IAAI,OAAO,KAAK,OAAO,MAAM,CAAC,SAAS,KAAK,GAAG,CAAC,CAAC,CAAC;CAE7E,OAAO,OAAO,KACX,OAAO,MAAM,eAAe,IAAI,SAAS,KAAK,CAAC,MAAM,KAAM,MAAM,WAAW,SAAS,aAAa,MAAM,OAAO,CAClH;AACF"}
|
|
@@ -4,6 +4,7 @@ import { defaultShouldHandleError } from "./defaultShouldHandleError.js";
|
|
|
4
4
|
import { getMiddlewareFlags } from "./isMiddleware.js";
|
|
5
5
|
import { getMatchedHandlers, onRouteHandlerStart, wrapRouteHandlers } from "./matchResult.js";
|
|
6
6
|
import { resolveRouteName } from "./resolveRouteName.js";
|
|
7
|
+
import { unwrapThrownValue } from "./unwrapThrownValue.js";
|
|
7
8
|
import { CLIENT_ADDRESS, CLIENT_PORT, HTTP_ROUTE, NETWORK_PEER_ADDRESS, NETWORK_PEER_PORT, NETWORK_TRANSPORT, NETWORK_TYPE } from "@sentry/conventions/attributes";
|
|
8
9
|
import { INTERNAL_setSegmentNameSourceIfSegment, captureException, getActiveSpan, getClient, getDefaultIsolationScope, getIsolationScope, getRootSpan, spanToJSON, updateSpanName, winterCGHeadersToDict, winterCGRequestToRequestData } from "@sentry/core";
|
|
9
10
|
import { getClientIPAddress } from "@sentry/core/server";
|
|
@@ -80,7 +81,8 @@ function responseHandler(context, shouldHandleError) {
|
|
|
80
81
|
*/
|
|
81
82
|
function captureContextError(context, shouldHandleError) {
|
|
82
83
|
if (context.error) {
|
|
83
|
-
|
|
84
|
+
const error = unwrapThrownValue(context.error);
|
|
85
|
+
if ((shouldHandleError ?? defaultShouldHandleError)(error)) captureException(error, { mechanism: {
|
|
84
86
|
handled: false,
|
|
85
87
|
type: "auto.http.hono.context_error"
|
|
86
88
|
} });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"middlewareHandlers.js","names":[],"sources":["../../../../src/integrations/hono/middlewareHandlers.ts"],"sourcesContent":["import {\n captureException,\n getActiveSpan,\n getClient,\n getDefaultIsolationScope,\n getIsolationScope,\n getRootSpan,\n INTERNAL_setSegmentNameSourceIfSegment,\n updateSpanName,\n type Scope,\n type Span,\n type SpanAttributes,\n spanToJSON,\n winterCGHeadersToDict,\n winterCGRequestToRequestData,\n} from '@sentry/core';\nimport { getClientIPAddress } from '@sentry/core/server';\nimport type { Context } from './honoTypes';\nimport { type HonoRuntime, readConnInfo } from './connInfo';\nimport { hasFetchEvent } from './hono-context';\nimport { defaultShouldHandleError } from './defaultShouldHandleError';\nimport { getMiddlewareFlags } from './isMiddleware';\nimport { getMatchedHandlers, onRouteHandlerStart, wrapRouteHandlers } from './matchResult';\nimport { resolveRouteName } from './resolveRouteName';\nimport { type SentryHonoMiddlewareOptions } from './types';\nimport {\n CLIENT_ADDRESS,\n CLIENT_PORT,\n HTTP_ROUTE,\n NETWORK_PEER_ADDRESS,\n NETWORK_PEER_PORT,\n NETWORK_TRANSPORT,\n NETWORK_TYPE,\n} from '@sentry/conventions/attributes';\n\n/**\n * Request handler for Hono framework\n */\nexport function requestHandler(context: Context, runtime: HonoRuntime): void {\n const isolationScope = getCurrentIsolationScope();\n // Read now: when a route handler starts, a user span can be active.\n const span = getActiveSpan();\n\n // Hono 5 removes `c.req.matchedRoutes`. Before Hono 4.8, it is the only source.\n const matchedHandlers = getMatchedHandlers(context);\n const routes = matchedHandlers?.map(([[, route]]) => route) ?? context.req.matchedRoutes ?? [];\n const middlewareFlags = getMiddlewareFlags(routes);\n const nameSpan = (): void =>\n updateSpanRouteName(isolationScope, span, context, resolveRouteName(context, routes, middlewareFlags));\n\n // Name early, so that events from the handlers carry the route.\n nameSpan();\n\n // A route handler that calls `next()` passes the request on, so rename when each one starts. Without\n // the getter, only the Context hook can wrap the route handlers.\n if (!matchedHandlers || wrapRouteHandlers(matchedHandlers, middlewareFlags)) {\n onRouteHandlerStart(context, nameSpan);\n }\n\n isolationScope.setSDKProcessingMetadata({\n normalizedRequest: winterCGRequestToRequestData(hasFetchEvent(context) ? context.event.request : context.req.raw),\n });\n\n setConnInfoAttributes(context, runtime, isolationScope);\n}\n\nfunction getCurrentIsolationScope(): Scope {\n const defaultScope = getDefaultIsolationScope();\n const currentIsolationScope = getIsolationScope();\n\n return defaultScope === currentIsolationScope ? defaultScope : currentIsolationScope;\n}\n\n/**\n * Adds HTTP connection info (client IP, port, transport, address type) from the runtime to the root\n * (server) span and the isolation scope.\n *\n * Keeps attributes that the runtime SDK already set: it reads forwarding headers, while the runtime\n * objects only know the socket peer, which can be a proxy.\n */\nfunction setConnInfoAttributes(context: Context, runtime: HonoRuntime, isolationScope: Scope): void {\n const activeSpan = getActiveSpan();\n if (!activeSpan) {\n return;\n }\n\n const connInfo = readConnInfo(context, runtime);\n if (!connInfo) {\n return;\n }\n\n const { address, port, transport, addressType } = connInfo;\n\n // Only collect client IP if `userInfo` is enabled (this is primarily for setting data with `.setUser`, but in this case we cannot check for `dataCollection.headers` or similar)\n const ipAddress = address && getClient()?.getDataCollectionOptions().userInfo ? address : undefined;\n\n const rootSpan = getRootSpan(activeSpan);\n const existingAttributes = spanToJSON(rootSpan).attributes ?? {};\n // Pair `client.port` only with the socket address: behind a proxy, the socket port is the proxy's.\n const writesClientAddress = ipAddress !== undefined && existingAttributes[CLIENT_ADDRESS] === undefined;\n rootSpan.setAttributes(\n onlyNewAttributes(\n {\n [CLIENT_PORT]: writesClientAddress ? port : undefined,\n [NETWORK_PEER_PORT]: port,\n [NETWORK_TRANSPORT]: transport,\n [NETWORK_TYPE]: addressType?.toLowerCase(),\n [CLIENT_ADDRESS]: ipAddress,\n [NETWORK_PEER_ADDRESS]: ipAddress,\n },\n existingAttributes,\n ),\n );\n\n if (ipAddress) {\n // Like `RequestData`, prefer the forwarding header: behind a proxy, the socket address is the proxy's.\n const userIpAddress = getClientIPAddress(winterCGHeadersToDict(context.req.raw.headers)) || ipAddress;\n isolationScope.setUser({ ...isolationScope.getUser(), ip_address: userIpAddress });\n }\n}\n\n/** Keeps the defined attributes that are not on the span yet. */\nfunction onlyNewAttributes(attributes: SpanAttributes, existingAttributes: Record<string, unknown>): SpanAttributes {\n return Object.fromEntries(\n Object.entries(attributes).filter(([key, value]) => value !== undefined && existingAttributes[key] === undefined),\n );\n}\n\n/**\n * Response handler for Hono framework\n */\nexport function responseHandler(\n context: Context,\n shouldHandleError?: SentryHonoMiddlewareOptions['shouldHandleError'],\n): void {\n captureContextError(context, shouldHandleError);\n}\n\n/**\n * Captures an unhandled context error, gated by the user's `shouldHandleError` (or the default).\n *\n * A deduplicated middleware calls it directly to report the error of its own context — e.g. the inner\n * context of an internal `.request()` whose route threw but whose failed response the outer handler\n * swallowed.\n */\nexport function captureContextError(\n context: Context,\n shouldHandleError?: SentryHonoMiddlewareOptions['shouldHandleError'],\n): void {\n if (context.error) {\n if ((shouldHandleError ?? defaultShouldHandleError)(
|
|
1
|
+
{"version":3,"file":"middlewareHandlers.js","names":[],"sources":["../../../../src/integrations/hono/middlewareHandlers.ts"],"sourcesContent":["import {\n captureException,\n getActiveSpan,\n getClient,\n getDefaultIsolationScope,\n getIsolationScope,\n getRootSpan,\n INTERNAL_setSegmentNameSourceIfSegment,\n updateSpanName,\n type Scope,\n type Span,\n type SpanAttributes,\n spanToJSON,\n winterCGHeadersToDict,\n winterCGRequestToRequestData,\n} from '@sentry/core';\nimport { getClientIPAddress } from '@sentry/core/server';\nimport type { Context } from './honoTypes';\nimport { type HonoRuntime, readConnInfo } from './connInfo';\nimport { hasFetchEvent } from './hono-context';\nimport { defaultShouldHandleError } from './defaultShouldHandleError';\nimport { getMiddlewareFlags } from './isMiddleware';\nimport { getMatchedHandlers, onRouteHandlerStart, wrapRouteHandlers } from './matchResult';\nimport { resolveRouteName } from './resolveRouteName';\nimport { type SentryHonoMiddlewareOptions } from './types';\nimport { unwrapThrownValue } from './unwrapThrownValue';\nimport {\n CLIENT_ADDRESS,\n CLIENT_PORT,\n HTTP_ROUTE,\n NETWORK_PEER_ADDRESS,\n NETWORK_PEER_PORT,\n NETWORK_TRANSPORT,\n NETWORK_TYPE,\n} from '@sentry/conventions/attributes';\n\n/**\n * Request handler for Hono framework\n */\nexport function requestHandler(context: Context, runtime: HonoRuntime): void {\n const isolationScope = getCurrentIsolationScope();\n // Read now: when a route handler starts, a user span can be active.\n const span = getActiveSpan();\n\n // Hono 5 removes `c.req.matchedRoutes`. Before Hono 4.8, it is the only source.\n const matchedHandlers = getMatchedHandlers(context);\n const routes = matchedHandlers?.map(([[, route]]) => route) ?? context.req.matchedRoutes ?? [];\n const middlewareFlags = getMiddlewareFlags(routes);\n const nameSpan = (): void =>\n updateSpanRouteName(isolationScope, span, context, resolveRouteName(context, routes, middlewareFlags));\n\n // Name early, so that events from the handlers carry the route.\n nameSpan();\n\n // A route handler that calls `next()` passes the request on, so rename when each one starts. Without\n // the getter, only the Context hook can wrap the route handlers.\n if (!matchedHandlers || wrapRouteHandlers(matchedHandlers, middlewareFlags)) {\n onRouteHandlerStart(context, nameSpan);\n }\n\n isolationScope.setSDKProcessingMetadata({\n normalizedRequest: winterCGRequestToRequestData(hasFetchEvent(context) ? context.event.request : context.req.raw),\n });\n\n setConnInfoAttributes(context, runtime, isolationScope);\n}\n\nfunction getCurrentIsolationScope(): Scope {\n const defaultScope = getDefaultIsolationScope();\n const currentIsolationScope = getIsolationScope();\n\n return defaultScope === currentIsolationScope ? defaultScope : currentIsolationScope;\n}\n\n/**\n * Adds HTTP connection info (client IP, port, transport, address type) from the runtime to the root\n * (server) span and the isolation scope.\n *\n * Keeps attributes that the runtime SDK already set: it reads forwarding headers, while the runtime\n * objects only know the socket peer, which can be a proxy.\n */\nfunction setConnInfoAttributes(context: Context, runtime: HonoRuntime, isolationScope: Scope): void {\n const activeSpan = getActiveSpan();\n if (!activeSpan) {\n return;\n }\n\n const connInfo = readConnInfo(context, runtime);\n if (!connInfo) {\n return;\n }\n\n const { address, port, transport, addressType } = connInfo;\n\n // Only collect client IP if `userInfo` is enabled (this is primarily for setting data with `.setUser`, but in this case we cannot check for `dataCollection.headers` or similar)\n const ipAddress = address && getClient()?.getDataCollectionOptions().userInfo ? address : undefined;\n\n const rootSpan = getRootSpan(activeSpan);\n const existingAttributes = spanToJSON(rootSpan).attributes ?? {};\n // Pair `client.port` only with the socket address: behind a proxy, the socket port is the proxy's.\n const writesClientAddress = ipAddress !== undefined && existingAttributes[CLIENT_ADDRESS] === undefined;\n rootSpan.setAttributes(\n onlyNewAttributes(\n {\n [CLIENT_PORT]: writesClientAddress ? port : undefined,\n [NETWORK_PEER_PORT]: port,\n [NETWORK_TRANSPORT]: transport,\n [NETWORK_TYPE]: addressType?.toLowerCase(),\n [CLIENT_ADDRESS]: ipAddress,\n [NETWORK_PEER_ADDRESS]: ipAddress,\n },\n existingAttributes,\n ),\n );\n\n if (ipAddress) {\n // Like `RequestData`, prefer the forwarding header: behind a proxy, the socket address is the proxy's.\n const userIpAddress = getClientIPAddress(winterCGHeadersToDict(context.req.raw.headers)) || ipAddress;\n isolationScope.setUser({ ...isolationScope.getUser(), ip_address: userIpAddress });\n }\n}\n\n/** Keeps the defined attributes that are not on the span yet. */\nfunction onlyNewAttributes(attributes: SpanAttributes, existingAttributes: Record<string, unknown>): SpanAttributes {\n return Object.fromEntries(\n Object.entries(attributes).filter(([key, value]) => value !== undefined && existingAttributes[key] === undefined),\n );\n}\n\n/**\n * Response handler for Hono framework\n */\nexport function responseHandler(\n context: Context,\n shouldHandleError?: SentryHonoMiddlewareOptions['shouldHandleError'],\n): void {\n captureContextError(context, shouldHandleError);\n}\n\n/**\n * Captures an unhandled context error, gated by the user's `shouldHandleError` (or the default).\n *\n * A deduplicated middleware calls it directly to report the error of its own context — e.g. the inner\n * context of an internal `.request()` whose route threw but whose failed response the outer handler\n * swallowed.\n */\nexport function captureContextError(\n context: Context,\n shouldHandleError?: SentryHonoMiddlewareOptions['shouldHandleError'],\n): void {\n if (context.error) {\n const error = unwrapThrownValue(context.error);\n if ((shouldHandleError ?? defaultShouldHandleError)(error)) {\n captureException(error, {\n mechanism: { handled: false, type: 'auto.http.hono.context_error' },\n });\n }\n }\n}\n\nfunction updateSpanRouteName(\n isolationScope: Scope,\n activeSpan: Span | undefined,\n context: Context,\n route: string | undefined,\n): void {\n // Without a route, keep the span name from the runtime.\n if (route === undefined) {\n return;\n }\n\n const routeName = `${context.req.method} ${route}`;\n\n if (activeSpan) {\n activeSpan.updateName(routeName);\n\n const rootSpan = getRootSpan(activeSpan);\n updateSpanName(rootSpan, routeName);\n INTERNAL_setSegmentNameSourceIfSegment(rootSpan, 'route');\n rootSpan.setAttribute(HTTP_ROUTE, route);\n }\n\n isolationScope.setTransactionName(routeName);\n}\n"],"mappings":";;;;;;;;;;;;;;AAuCA,SAAgB,eAAe,SAAkB,SAA4B;CAC3E,MAAM,iBAAiB,yBAAyB;CAEh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,WAAW;EAEb,MAAM,gBAAgB,mBAAmB,sBAAsB,QAAQ,IAAI,IAAI,OAAO,CAAC,KAAK;EAC5F,eAAe,QAAQ;GAAE,GAAG,eAAe,QAAQ;GAAG,YAAY;EAAc,CAAC;CACnF;AACF;;AAGA,SAAS,kBAAkB,YAA4B,oBAA6D;CAClH,OAAO,OAAO,YACZ,OAAO,QAAQ,UAAU,CAAC,CAAC,QAAQ,CAAC,KAAK,WAAW,UAAU,KAAA,KAAa,mBAAmB,SAAS,KAAA,CAAS,CAClH;AACF;;;;AAKA,SAAgB,gBACd,SACA,mBACM;CACN,oBAAoB,SAAS,iBAAiB;AAChD;;;;;;;;AASA,SAAgB,oBACd,SACA,mBACM;CACN,IAAI,QAAQ,OAAO;EACjB,MAAM,QAAQ,kBAAkB,QAAQ,KAAK;EAC7C,KAAK,qBAAqB,yBAAA,CAA0B,KAAK,GACvD,iBAAiB,OAAO,EACtB,WAAW;GAAE,SAAS;GAAO,MAAM;EAA+B,EACpE,CAAC;CAEL;AACF;AAEA,SAAS,oBACP,gBACA,YACA,SACA,OACM;CAEN,IAAI,UAAU,KAAA,GACZ;CAGF,MAAM,YAAY,GAAG,QAAQ,IAAI,OAAO,GAAG;CAE3C,IAAI,YAAY;EACd,WAAW,WAAW,SAAS;EAE/B,MAAM,WAAW,YAAY,UAAU;EACvC,eAAe,UAAU,SAAS;EAClC,uCAAuC,UAAU,OAAO;EACxD,SAAS,aAAa,YAAY,KAAK;CACzC;CAEA,eAAe,mBAAmB,SAAS;AAC7C"}
|
|
@@ -68,12 +68,13 @@ function installRouteHookOnPrototype(honoBaseProto) {
|
|
|
68
68
|
DEBUG_BUILD && debug.log("[hono] Installed route hook on HonoBase.prototype.");
|
|
69
69
|
return handle;
|
|
70
70
|
}
|
|
71
|
+
const ERROR_AND_NOT_FOUND_METHODS = /* @__PURE__ */ new Set(["@ERROR", "@NOT_FOUND"]);
|
|
71
72
|
/**
|
|
72
73
|
* Wraps the middleware handlers of a sub-app's routes in spans.
|
|
73
74
|
*/
|
|
74
75
|
function wrapSubAppMiddleware(routes) {
|
|
75
76
|
const middlewareFlags = getMiddlewareFlags(routes);
|
|
76
|
-
for (const [i, route] of routes.entries()) if (middlewareFlags[i] && typeof route.handler === "function") route.handler = wrapMiddlewareWithSpan(route.handler);
|
|
77
|
+
for (const [i, route] of routes.entries()) if (middlewareFlags[i] && !ERROR_AND_NOT_FOUND_METHODS.has(route.method) && typeof route.handler === "function") route.handler = wrapMiddlewareWithSpan(route.handler);
|
|
77
78
|
}
|
|
78
79
|
export { installRouteHookOnPrototype, wrapSubAppMiddleware };
|
|
79
80
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"patchRoute.js","names":[],"sources":["../../../../src/integrations/hono/patchRoute.ts"],"sourcesContent":["import { debug, getOriginalFunction } from '@sentry/core';\nimport type { WrappedFunction } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type { Hono, HonoRoute } from './honoTypes';\nimport { getMiddlewareFlags } from './isMiddleware';\nimport { patchAppRequest } from './patchAppRequest';\nimport { wrapMiddlewareWithSpan } from './wrapMiddlewareSpan';\nimport { sentryOriginalTraps } from './sentryOriginalTraps';\n\nexport type { HonoRoute };\n\n// oxlint-disable-next-line typescript/no-explicit-any\ntype HonoAny = Hono<any>;\n\nexport type RouteHookHandle = {\n activate: () => void;\n getPendingSubApps: () => Set<HonoAny>;\n};\n\ntype HonoBaseProto = {\n route?: (path: string, app: HonoAny) => HonoAny;\n __sentryRouteHook__?: RouteHookHandle;\n};\n\n/**\n * Creates the two-phase state machine for the route hook.\n *\n * - Pre-activation: collects sub-app references into a pending set.\n * - Post-activation: instruments sub-apps immediately at mount time.\n */\nfunction createRouteHook(): { handle: RouteHookHandle; onSubAppMounted: (subApp: HonoAny) => void } {\n const pendingSubApps = new Set<HonoAny>();\n let activated = false;\n\n return {\n handle: {\n activate: () => {\n activated = true;\n },\n getPendingSubApps: () => pendingSubApps,\n },\n onSubAppMounted: (subApp: HonoAny) => {\n if (activated) {\n DEBUG_BUILD && debug.log(`[hono] Instrumenting sub-app at mount time (${subApp.routes.length} routes).`);\n wrapSubAppMiddleware(subApp.routes);\n patchAppRequest(subApp);\n } else {\n DEBUG_BUILD &&\n debug.log(`[hono] Collecting sub-app for deferred instrumentation (${subApp.routes.length} routes).`);\n pendingSubApps.add(subApp);\n }\n },\n };\n}\n\n/**\n * Installs a hook on `HonoBase.prototype.route` to intercept sub-app mounting.\n *\n * `honoBaseProto` is `HonoBase.prototype`, where `route` is defined — one level above the concrete\n * subclass. Callers derive it from a live app instance (`Object.getPrototypeOf(Object.getPrototypeOf(app))`)\n * or from the `Hono` class (`Object.getPrototypeOf(Hono.prototype)`), so the instrumentation never\n * imports `hono` itself.\n *\n * Returns a handle with `activate()` and `getPendingSubApps()`.\n * Idempotent: subsequent calls return the same handle\n */\nexport function installRouteHookOnPrototype(honoBaseProto: HonoBaseProto): RouteHookHandle {\n const noopHandle: RouteHookHandle = { activate: () => {}, getPendingSubApps: () => new Set() };\n\n if (!honoBaseProto || typeof honoBaseProto.route !== 'function') {\n DEBUG_BUILD && debug.warn('[hono] Could not find HonoBase.prototype.route — sub-app instrumentation disabled.');\n return noopHandle;\n }\n\n // Already patched\n if (getOriginalFunction(honoBaseProto.route as unknown as WrappedFunction)) {\n return honoBaseProto.__sentryRouteHook__ ?? noopHandle;\n }\n\n const originalRoute = honoBaseProto.route;\n const { handle, onSubAppMounted } = createRouteHook();\n\n honoBaseProto.route = new Proxy(originalRoute, {\n apply(_target, thisArg, args: [string, HonoAny]) {\n const [, subApp] = args;\n if (subApp && Array.isArray(subApp.routes)) {\n onSubAppMounted(subApp);\n }\n\n return Reflect.apply(_target, thisArg, args);\n },\n ...sentryOriginalTraps(originalRoute),\n });\n honoBaseProto.__sentryRouteHook__ = handle;\n\n DEBUG_BUILD && debug.log('[hono] Installed route hook on HonoBase.prototype.');\n\n return handle;\n}\n\n/**\n * Wraps the middleware handlers of a sub-app's routes in spans.\n */\nexport function wrapSubAppMiddleware(routes: HonoRoute[]): void {\n const middlewareFlags = getMiddlewareFlags(routes);\n for (const [i, route] of routes.entries()) {\n if (middlewareFlags[i] && typeof route.handler === 'function') {\n route.handler = wrapMiddlewareWithSpan(route.handler);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA8BA,SAAS,kBAA2F;CAClG,MAAM,iCAAiB,IAAI,IAAa;CACxC,IAAI,YAAY;CAEhB,OAAO;EACL,QAAQ;GACN,gBAAgB;IACd,YAAY;GACd;GACA,yBAAyB;EAC3B;EACA,kBAAkB,WAAoB;GACpC,IAAI,WAAW;IACb,eAAe,MAAM,IAAI,+CAA+C,OAAO,OAAO,OAAO,UAAU;IACvG,qBAAqB,OAAO,MAAM;IAClC,gBAAgB,MAAM;GACxB,OAAO;IACL,eACE,MAAM,IAAI,2DAA2D,OAAO,OAAO,OAAO,UAAU;IACtG,eAAe,IAAI,MAAM;GAC3B;EACF;CACF;AACF;;;;;;;;;;;;AAaA,SAAgB,4BAA4B,eAA+C;CACzF,MAAM,aAA8B;EAAE,gBAAgB,CAAC;EAAG,yCAAyB,IAAI,IAAI;CAAE;CAE7F,IAAI,CAAC,iBAAiB,OAAO,cAAc,UAAU,YAAY;EAC/D,eAAe,MAAM,KAAK,oFAAoF;EAC9G,OAAO;CACT;CAGA,IAAI,oBAAoB,cAAc,KAAmC,GACvE,OAAO,cAAc,uBAAuB;CAG9C,MAAM,gBAAgB,cAAc;CACpC,MAAM,EAAE,QAAQ,oBAAoB,gBAAgB;CAEpD,cAAc,QAAQ,IAAI,MAAM,eAAe;EAC7C,MAAM,SAAS,SAAS,MAAyB;GAC/C,MAAM,GAAG,UAAU;GACnB,IAAI,UAAU,MAAM,QAAQ,OAAO,MAAM,GACvC,gBAAgB,MAAM;GAGxB,OAAO,QAAQ,MAAM,SAAS,SAAS,IAAI;EAC7C;EACA,GAAG,oBAAoB,aAAa;CACtC,CAAC;CACD,cAAc,sBAAsB;CAEpC,eAAe,MAAM,IAAI,oDAAoD;CAE7E,OAAO;AACT;;;;
|
|
1
|
+
{"version":3,"file":"patchRoute.js","names":[],"sources":["../../../../src/integrations/hono/patchRoute.ts"],"sourcesContent":["import { debug, getOriginalFunction } from '@sentry/core';\nimport type { WrappedFunction } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type { Hono, HonoRoute } from './honoTypes';\nimport { getMiddlewareFlags } from './isMiddleware';\nimport { patchAppRequest } from './patchAppRequest';\nimport { wrapMiddlewareWithSpan } from './wrapMiddlewareSpan';\nimport { sentryOriginalTraps } from './sentryOriginalTraps';\n\nexport type { HonoRoute };\n\n// oxlint-disable-next-line typescript/no-explicit-any\ntype HonoAny = Hono<any>;\n\nexport type RouteHookHandle = {\n activate: () => void;\n getPendingSubApps: () => Set<HonoAny>;\n};\n\ntype HonoBaseProto = {\n route?: (path: string, app: HonoAny) => HonoAny;\n __sentryRouteHook__?: RouteHookHandle;\n};\n\n/**\n * Creates the two-phase state machine for the route hook.\n *\n * - Pre-activation: collects sub-app references into a pending set.\n * - Post-activation: instruments sub-apps immediately at mount time.\n */\nfunction createRouteHook(): { handle: RouteHookHandle; onSubAppMounted: (subApp: HonoAny) => void } {\n const pendingSubApps = new Set<HonoAny>();\n let activated = false;\n\n return {\n handle: {\n activate: () => {\n activated = true;\n },\n getPendingSubApps: () => pendingSubApps,\n },\n onSubAppMounted: (subApp: HonoAny) => {\n if (activated) {\n DEBUG_BUILD && debug.log(`[hono] Instrumenting sub-app at mount time (${subApp.routes.length} routes).`);\n wrapSubAppMiddleware(subApp.routes);\n patchAppRequest(subApp);\n } else {\n DEBUG_BUILD &&\n debug.log(`[hono] Collecting sub-app for deferred instrumentation (${subApp.routes.length} routes).`);\n pendingSubApps.add(subApp);\n }\n },\n };\n}\n\n/**\n * Installs a hook on `HonoBase.prototype.route` to intercept sub-app mounting.\n *\n * `honoBaseProto` is `HonoBase.prototype`, where `route` is defined — one level above the concrete\n * subclass. Callers derive it from a live app instance (`Object.getPrototypeOf(Object.getPrototypeOf(app))`)\n * or from the `Hono` class (`Object.getPrototypeOf(Hono.prototype)`), so the instrumentation never\n * imports `hono` itself.\n *\n * Returns a handle with `activate()` and `getPendingSubApps()`.\n * Idempotent: subsequent calls return the same handle\n */\nexport function installRouteHookOnPrototype(honoBaseProto: HonoBaseProto): RouteHookHandle {\n const noopHandle: RouteHookHandle = { activate: () => {}, getPendingSubApps: () => new Set() };\n\n if (!honoBaseProto || typeof honoBaseProto.route !== 'function') {\n DEBUG_BUILD && debug.warn('[hono] Could not find HonoBase.prototype.route — sub-app instrumentation disabled.');\n return noopHandle;\n }\n\n // Already patched\n if (getOriginalFunction(honoBaseProto.route as unknown as WrappedFunction)) {\n return honoBaseProto.__sentryRouteHook__ ?? noopHandle;\n }\n\n const originalRoute = honoBaseProto.route;\n const { handle, onSubAppMounted } = createRouteHook();\n\n honoBaseProto.route = new Proxy(originalRoute, {\n apply(_target, thisArg, args: [string, HonoAny]) {\n const [, subApp] = args;\n if (subApp && Array.isArray(subApp.routes)) {\n onSubAppMounted(subApp);\n }\n\n return Reflect.apply(_target, thisArg, args);\n },\n ...sentryOriginalTraps(originalRoute),\n });\n honoBaseProto.__sentryRouteHook__ = handle;\n\n DEBUG_BUILD && debug.log('[hono] Installed route hook on HonoBase.prototype.');\n\n return handle;\n}\n\n// Hono 5 registers `onError()` and `notFound()` handlers as `(c, next)` middleware routes with these\n// methods. Like on Hono 4, they get no middleware span.\nconst ERROR_AND_NOT_FOUND_METHODS = new Set(['@ERROR', '@NOT_FOUND']);\n\n/**\n * Wraps the middleware handlers of a sub-app's routes in spans.\n */\nexport function wrapSubAppMiddleware(routes: HonoRoute[]): void {\n const middlewareFlags = getMiddlewareFlags(routes);\n for (const [i, route] of routes.entries()) {\n if (middlewareFlags[i] && !ERROR_AND_NOT_FOUND_METHODS.has(route.method) && typeof route.handler === 'function') {\n route.handler = wrapMiddlewareWithSpan(route.handler);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;A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