@sentry/node 11.0.0-alpha.2 → 11.0.0-beta.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/README.md +19 -0
- package/build/cjs/index.js +4 -3
- package/build/cjs/index.js.map +1 -1
- package/build/cjs/integrations/anr/index.js +1 -1
- package/build/cjs/integrations/fs/vendored/instrumentation.js +2 -1
- package/build/cjs/integrations/fs/vendored/instrumentation.js.map +1 -1
- package/build/cjs/integrations/http/SentryHttpInstrumentation.js +5 -4
- package/build/cjs/integrations/http/SentryHttpInstrumentation.js.map +1 -1
- package/build/cjs/integrations/http/httpServerIntegration.js +4 -3
- package/build/cjs/integrations/http/httpServerIntegration.js.map +1 -1
- package/build/cjs/integrations/http/httpServerSpansIntegration.js +5 -33
- package/build/cjs/integrations/http/httpServerSpansIntegration.js.map +1 -1
- package/build/cjs/integrations/http/index.js +8 -4
- package/build/cjs/integrations/http/index.js.map +1 -1
- package/build/cjs/integrations/local-variables/local-variables-async.js +1 -1
- package/build/cjs/integrations/node-fetch/undici-instrumentation.js +13 -2
- package/build/cjs/integrations/node-fetch/undici-instrumentation.js.map +1 -1
- package/build/cjs/integrations/nodeRuntimeMetrics.js +2 -1
- package/build/cjs/integrations/nodeRuntimeMetrics.js.map +1 -1
- package/build/cjs/integrations/onunhandledrejection.js +5 -3
- package/build/cjs/integrations/onunhandledrejection.js.map +1 -1
- package/build/cjs/sdk/api.js +2 -1
- package/build/cjs/sdk/api.js.map +1 -1
- package/build/cjs/sdk/client.js +2 -1
- package/build/cjs/sdk/client.js.map +1 -1
- package/build/cjs/sdk/index.js +1 -1
- package/build/cjs/sdk/index.js.map +1 -1
- package/build/esm/index.js +3 -2
- package/build/esm/index.js.map +1 -1
- package/build/esm/integrations/anr/index.js +1 -1
- package/build/esm/integrations/anr/worker-script.js +2 -2
- package/build/esm/integrations/fs/vendored/instrumentation.js +2 -1
- package/build/esm/integrations/fs/vendored/instrumentation.js.map +1 -1
- package/build/esm/integrations/http/SentryHttpInstrumentation.js +2 -1
- package/build/esm/integrations/http/SentryHttpInstrumentation.js.map +1 -1
- package/build/esm/integrations/http/httpServerIntegration.js +3 -2
- package/build/esm/integrations/http/httpServerIntegration.js.map +1 -1
- package/build/esm/integrations/http/httpServerSpansIntegration.js +7 -35
- package/build/esm/integrations/http/httpServerSpansIntegration.js.map +1 -1
- package/build/esm/integrations/http/index.js +6 -2
- package/build/esm/integrations/http/index.js.map +1 -1
- package/build/esm/integrations/local-variables/local-variables-async.js +1 -1
- package/build/esm/integrations/local-variables/worker-script.js +1 -1
- package/build/esm/integrations/node-fetch/undici-instrumentation.js +15 -4
- package/build/esm/integrations/node-fetch/undici-instrumentation.js.map +1 -1
- package/build/esm/integrations/nodeRuntimeMetrics.js +2 -1
- package/build/esm/integrations/nodeRuntimeMetrics.js.map +1 -1
- package/build/esm/integrations/onunhandledrejection.js +5 -3
- package/build/esm/integrations/onunhandledrejection.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/esm/sdk/api.js +2 -1
- package/build/esm/sdk/api.js.map +1 -1
- package/build/esm/sdk/client.js +2 -1
- package/build/esm/sdk/client.js.map +1 -1
- package/build/esm/sdk/index.js +1 -1
- package/build/esm/sdk/index.js.map +1 -1
- package/build/import-hook.mjs +1 -1
- package/build/types/index.d.ts +4 -3
- package/build/types/index.d.ts.map +1 -1
- package/build/types/integrations/fs/vendored/instrumentation.d.ts.map +1 -1
- package/build/types/integrations/http/SentryHttpInstrumentation.d.ts +2 -1
- package/build/types/integrations/http/SentryHttpInstrumentation.d.ts.map +1 -1
- package/build/types/integrations/http/httpServerIntegration.d.ts +3 -2
- package/build/types/integrations/http/httpServerIntegration.d.ts.map +1 -1
- package/build/types/integrations/http/httpServerSpansIntegration.d.ts +2 -1
- package/build/types/integrations/http/httpServerSpansIntegration.d.ts.map +1 -1
- package/build/types/integrations/http/index.d.ts.map +1 -1
- package/build/types/integrations/node-fetch/undici-instrumentation.d.ts.map +1 -1
- package/build/types/integrations/nodeRuntimeMetrics.d.ts.map +1 -1
- package/build/types/sdk/api.d.ts.map +1 -1
- package/build/types/sdk/client.d.ts +1 -1
- package/build/types/sdk/client.d.ts.map +1 -1
- package/build/types/types.d.ts +2 -1
- package/build/types/types.d.ts.map +1 -1
- package/package.json +6 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"httpServerSpansIntegration.js","sources":["../../../../src/integrations/http/httpServerSpansIntegration.ts"],"sourcesContent":["/* eslint-disable max-lines */\nimport { errorMonitor } from 'node:events';\nimport {\n SENTRY_SEGMENT_NAME_SOURCE,\n HTTP_REQUEST_METHOD,\n HTTP_RESPONSE_STATUS_CODE,\n CLIENT_ADDRESS,\n CLIENT_PORT,\n NETWORK_LOCAL_ADDRESS,\n NETWORK_LOCAL_PORT,\n NETWORK_PEER_ADDRESS,\n NETWORK_PEER_PORT,\n NETWORK_PROTOCOL_NAME,\n NETWORK_PROTOCOL_VERSION,\n NETWORK_TRANSPORT,\n SERVER_ADDRESS,\n SERVER_PORT,\n SENTRY_HTTP_PREFETCH,\n SENTRY_KIND,\n URL_FRAGMENT,\n URL_FULL,\n URL_PATH,\n URL_QUERY,\n URL_SCHEME,\n USER_AGENT_ORIGINAL,\n} from '@sentry/conventions/attributes';\nimport type {\n Event,\n HttpIncomingMessage,\n HttpServerResponse,\n Integration,\n IntegrationFn,\n Span,\n SpanAttributes,\n SpanStatus,\n} from '@sentry/core';\nimport {\n debug,\n getSpanStatusFromHttpCode,\n httpHeadersToSpanAttributes,\n getContentLengthFromHeaders,\n parseStringToURLObject,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SPAN_STATUS_ERROR,\n stripUrlQueryAndFragment,\n isTracingSuppressed,\n bindScopeToEmitter,\n startInactiveSpan,\n withActiveSpan,\n getUrlFragment,\n getUrlQuery,\n filterCollectedUrl,\n filterCollectedUrlQuery,\n hasSpanStreamingEnabled,\n HTTP_SPAN_NAME_FALLBACK,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type { NodeClient } from '../../sdk/client';\nimport { addStartSpanCallback } from './httpServerIntegration';\n\nconst INTEGRATION_NAME = 'Http.ServerSpans' as const;\n\n// Tree-shakable guard to remove all code related to tracing\ndeclare const __SENTRY_TRACING__: boolean;\n\nexport interface HttpServerSpansIntegrationOptions {\n /**\n * Do not capture spans for incoming HTTP requests to URLs where the given callback returns `true`.\n * Spans will be non recording if tracing is disabled.\n *\n * The `urlPath` param consists of the URL path and query string (if any) of the incoming request.\n * For example: `'/users/details?id=123'`\n *\n * The `request` param contains the original {@type IncomingMessage} object of the incoming request.\n * You can use it to filter on additional properties like method, headers, etc.\n */\n ignoreIncomingRequests?: (urlPath: string, request: HttpIncomingMessage) => boolean;\n\n /**\n * Whether to automatically ignore common static asset requests like favicon.ico, robots.txt, etc.\n * This helps reduce noise in your transactions.\n *\n * @default `true`\n */\n ignoreStaticAssets?: boolean;\n\n /**\n * Do not capture spans for incoming HTTP requests with the given status codes.\n * By default, spans with some 3xx and 4xx status codes are ignored (see @default).\n * Expects an array of status codes or a range of status codes, e.g. [[300,399], 404] would ignore 3xx and 404 status codes.\n *\n * @default `[[401, 404], [301, 303], [305, 399]]`\n */\n ignoreStatusCodes?: (number | [number, number])[];\n\n /**\n * A hook that can be used to mutate the span for incoming requests.\n * This is triggered after the span is created, but before it is recorded.\n */\n onSpanCreated?: (span: Span, request: HttpIncomingMessage, response: HttpServerResponse) => void;\n}\n\nconst _httpServerSpansIntegration = ((options: HttpServerSpansIntegrationOptions = {}) => {\n const ignoreStaticAssets = options.ignoreStaticAssets ?? true;\n const ignoreIncomingRequests = options.ignoreIncomingRequests;\n const ignoreStatusCodes = options.ignoreStatusCodes ?? [\n [401, 404],\n // 300 and 304 are possibly valid status codes we do not want to filter\n [301, 303],\n [305, 399],\n ];\n\n const { onSpanCreated } = options;\n\n return {\n name: INTEGRATION_NAME,\n setup(client: NodeClient) {\n // If no tracing, we can just skip everything here\n if (typeof __SENTRY_TRACING__ !== 'undefined' && !__SENTRY_TRACING__) {\n return;\n }\n\n client.on('httpServerRequest', (_request, _response, normalizedRequest) => {\n // Type-casting this here because we do not want to put the node types into core\n const request = _request as HttpIncomingMessage;\n const response = _response as HttpServerResponse;\n\n const startSpan = (next: () => boolean): boolean => {\n if (\n shouldIgnoreSpansForIncomingRequest(request, {\n ignoreStaticAssets,\n ignoreIncomingRequests,\n })\n ) {\n DEBUG_BUILD && debug.log(INTEGRATION_NAME, 'Skipping span creation for incoming request', request.url);\n return next();\n }\n\n const fullUrl = normalizedRequest.url || request.url || '/';\n const urlObj = parseStringToURLObject(fullUrl);\n\n const headers = request.headers;\n const userAgent = headers['user-agent'];\n const httpVersion = request.httpVersion;\n const host = headers.host as string | undefined;\n const hostname = host?.replace(/^(.*)(:[0-9]{1,5})/, '$1') || 'localhost';\n\n const scheme = fullUrl.startsWith('https') ? 'https' : 'http';\n\n const requestMethod = normalizedRequest.method || request.method?.toUpperCase();\n const method = requestMethod || 'GET';\n const httpTargetWithoutQueryFragment = urlObj ? urlObj.pathname : stripUrlQueryAndFragment(fullUrl);\n const bestEffortTransactionName = `${method} ${httpTargetWithoutQueryFragment}`;\n\n const query = getUrlQuery(urlObj?.search);\n const fragment = getUrlFragment(urlObj?.hash);\n\n const span = startInactiveSpan({\n // With span streaming, span names have to be low cardinality, so we can't fall back to the URL path.\n // Route instrumentations rename the span to `${method} ${route}` once a route is known.\n name: hasSpanStreamingEnabled(client)\n ? requestMethod || HTTP_SPAN_NAME_FALLBACK\n : bestEffortTransactionName,\n attributes: {\n // Sentry specific attributes\n [SENTRY_KIND]: 'server',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.server',\n [SENTRY_SEGMENT_NAME_SOURCE]: 'url',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.http_server',\n [SENTRY_HTTP_PREFETCH]: isKnownPrefetchRequest(request) || undefined,\n [URL_FULL]: filterCollectedUrl(fullUrl, client),\n [URL_PATH]: urlObj?.pathname ?? httpTargetWithoutQueryFragment,\n [URL_QUERY]: filterCollectedUrlQuery(query, client),\n [URL_FRAGMENT]: fragment,\n [HTTP_REQUEST_METHOD]: normalizedRequest.method,\n [USER_AGENT_ORIGINAL]: userAgent,\n [URL_SCHEME]: scheme,\n [SERVER_ADDRESS]: hostname,\n [NETWORK_PROTOCOL_NAME]: 'http',\n [NETWORK_PROTOCOL_VERSION]: httpVersion,\n [NETWORK_TRANSPORT]: httpVersion?.toUpperCase() === 'QUIC' ? 'udp' : 'tcp',\n 'http.request.body.size': getContentLengthFromHeaders(request.headers),\n ...httpHeadersToSpanAttributes(normalizedRequest.headers || {}, client.getDataCollectionOptions()),\n },\n });\n\n onSpanCreated?.(span, request, response);\n\n return withActiveSpan(span, () => {\n bindScopeToEmitter(request);\n bindScopeToEmitter(response);\n\n // Ensure we only end the span once\n // E.g. error can be emitted before close is emitted\n let isEnded = false;\n function endSpan(status: SpanStatus): void {\n if (isEnded) {\n return;\n }\n\n isEnded = true;\n\n const newAttributes = getIncomingRequestAttributesOnResponse(\n request,\n response,\n client.getDataCollectionOptions().userInfo,\n );\n span.setAttributes(newAttributes);\n span.setStatus(status);\n span.end();\n }\n\n response.on('close', () => {\n endSpan(getSpanStatusFromHttpCode(response.statusCode));\n });\n response.on(errorMonitor, () => {\n const httpStatus = getSpanStatusFromHttpCode(response.statusCode);\n // Ensure we def. have an error status here\n endSpan(httpStatus.code === SPAN_STATUS_ERROR ? httpStatus : { code: SPAN_STATUS_ERROR });\n });\n\n return next();\n });\n };\n\n addStartSpanCallback(request, startSpan);\n });\n },\n processEvent(event) {\n if (event.type === 'transaction') {\n const statusCode = event.contexts?.trace?.data?.[HTTP_RESPONSE_STATUS_CODE];\n if (typeof statusCode === 'number') {\n // Drop transaction if it has a status code that should be ignored\n if (shouldFilterStatusCode(statusCode, ignoreStatusCodes)) {\n DEBUG_BUILD && debug.log('Dropping transaction due to status code', statusCode);\n return null;\n }\n\n // Surface the HTTP status as the top-level `response` context. The OTel SDK span\n // exporter already does this on its path; doing it here covers transactions produced\n // by the `SentryTracerProvider`, which bypasses that exporter.\n event.contexts = {\n ...event.contexts,\n response: {\n ...event.contexts?.response,\n status_code: statusCode,\n },\n };\n }\n }\n\n return event;\n },\n afterAllSetup(client) {\n if (!DEBUG_BUILD) {\n return;\n }\n\n if (client.getIntegrationByName('Http')) {\n debug.warn(\n 'It seems that you have manually added `httpServerSpansIntegration` while `httpIntegration` is also present. Make sure to remove `httpIntegration` when adding `httpServerSpansIntegration`.',\n );\n }\n\n if (!client.getIntegrationByName('Http.Server')) {\n debug.error(\n 'It seems that you have manually added `httpServerSpansIntegration` without adding `httpServerIntegration`. This is a requiement for spans to be created - please add the `httpServerIntegration` integration.',\n );\n }\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * This integration emits spans for incoming requests handled via the node `http` module.\n * It requires the `httpServerIntegration` to be present.\n */\nexport const httpServerSpansIntegration = _httpServerSpansIntegration as (\n options?: HttpServerSpansIntegrationOptions,\n) => Integration & {\n name: 'Http.ServerSpans';\n setup: (client: NodeClient) => void;\n processEvent: (event: Event) => Event | null;\n};\n\nfunction isKnownPrefetchRequest(req: HttpIncomingMessage): boolean {\n // Currently only handles Next.js prefetch requests but may check other frameworks in the future.\n return req.headers['next-router-prefetch'] === '1';\n}\n\n/**\n * Check if a request is for a common static asset that should be ignored by default.\n *\n * Only exported for tests.\n */\nexport function isStaticAssetRequest(urlPath: string): boolean {\n const path = stripUrlQueryAndFragment(urlPath);\n // Common static file extensions\n if (path.match(/\\.(ico|png|jpg|jpeg|gif|svg|css|js|woff|woff2|ttf|eot|webp|avif)$/)) {\n return true;\n }\n\n // Common metadata files\n if (path.match(/^\\/(robots\\.txt|sitemap\\.xml|manifest\\.json|browserconfig\\.xml)$/)) {\n return true;\n }\n\n return false;\n}\n\nfunction shouldIgnoreSpansForIncomingRequest(\n request: HttpIncomingMessage,\n {\n ignoreStaticAssets,\n ignoreIncomingRequests,\n }: {\n ignoreStaticAssets?: boolean;\n ignoreIncomingRequests?: (urlPath: string, request: HttpIncomingMessage) => boolean;\n },\n): boolean {\n if (isTracingSuppressed()) {\n return true;\n }\n\n // request.url is the only property that holds any information about the url\n // it only consists of the URL path and query string (if any)\n const urlPath = request.url;\n\n const method = request.method?.toUpperCase();\n // We do not capture OPTIONS/HEAD requests as spans\n if (method === 'OPTIONS' || method === 'HEAD' || !urlPath) {\n return true;\n }\n\n // Default static asset filtering\n if (ignoreStaticAssets && method === 'GET' && isStaticAssetRequest(urlPath)) {\n return true;\n }\n\n if (ignoreIncomingRequests?.(urlPath, request)) {\n return true;\n }\n\n return false;\n}\n\n/**\n * First entry of `X-Forwarded-For`: the client as seen by the outermost proxy.\n * https://opentelemetry.io/docs/specs/semconv/registry/attributes/client/#client-address\n */\nfunction getForwardedClientAddress(forwardedFor: string | string[] | undefined): string | undefined {\n return typeof forwardedFor === 'string' ? forwardedFor.split(',')[0]?.trim() || undefined : undefined;\n}\n\nfunction getIncomingRequestAttributesOnResponse(\n request: HttpIncomingMessage,\n response: HttpServerResponse,\n collectClientAddress: boolean,\n): SpanAttributes {\n // take socket from the request,\n // since it may be detached from the response object in keep-alive mode\n const { socket } = request;\n const { statusCode, statusMessage } = response;\n\n const newAttributes: SpanAttributes = {\n [HTTP_RESPONSE_STATUS_CODE]: statusCode,\n 'http.response.status_text': statusMessage?.toUpperCase(),\n };\n\n if (collectClientAddress) {\n // `client.address` is the originating client, so a forwarding header wins over the socket, which\n // behind a proxy holds the proxy's address. `network.peer.address` below keeps the socket value.\n newAttributes[CLIENT_ADDRESS] =\n getForwardedClientAddress(request.headers['x-forwarded-for']) ?? socket?.remoteAddress;\n }\n\n if (socket) {\n const { localAddress, localPort, remoteAddress, remotePort } = socket;\n newAttributes[SERVER_PORT] = localPort;\n newAttributes[NETWORK_LOCAL_ADDRESS] = localAddress;\n newAttributes[NETWORK_LOCAL_PORT] = localPort;\n newAttributes[CLIENT_PORT] = remotePort;\n newAttributes[NETWORK_PEER_ADDRESS] = collectClientAddress ? remoteAddress : undefined;\n newAttributes[NETWORK_PEER_PORT] = remotePort;\n }\n\n return newAttributes;\n}\n\n/**\n * If the given status code should be filtered for the given list of status codes/ranges.\n */\nfunction shouldFilterStatusCode(statusCode: number, dropForStatusCodes: (number | [number, number])[]): boolean {\n return dropForStatusCodes.some(code => {\n if (typeof code === 'number') {\n return code === statusCode;\n }\n\n const [min, max] = code;\n return statusCode >= min && statusCode <= max;\n });\n}\n"],"names":["DEBUG_BUILD","debug","parseStringToURLObject","stripUrlQueryAndFragment","getUrlQuery","getUrlFragment","startInactiveSpan","hasSpanStreamingEnabled","HTTP_SPAN_NAME_FALLBACK","SENTRY_KIND","SEMANTIC_ATTRIBUTE_SENTRY_OP","SENTRY_SEGMENT_NAME_SOURCE","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","SENTRY_HTTP_PREFETCH","URL_FULL","filterCollectedUrl","URL_PATH","URL_QUERY","filterCollectedUrlQuery","URL_FRAGMENT","HTTP_REQUEST_METHOD","USER_AGENT_ORIGINAL","URL_SCHEME","SERVER_ADDRESS","NETWORK_PROTOCOL_NAME","NETWORK_PROTOCOL_VERSION","NETWORK_TRANSPORT","getContentLengthFromHeaders","httpHeadersToSpanAttributes","withActiveSpan","bindScopeToEmitter","getSpanStatusFromHttpCode","errorMonitor","SPAN_STATUS_ERROR","addStartSpanCallback","HTTP_RESPONSE_STATUS_CODE","isTracingSuppressed","CLIENT_ADDRESS","SERVER_PORT","NETWORK_LOCAL_ADDRESS","NETWORK_LOCAL_PORT","CLIENT_PORT","NETWORK_PEER_ADDRESS","NETWORK_PEER_PORT"],"mappings":";;;;;;;;AA6DA,MAAM,gBAAA,GAAmB,kBAAA;AA0CzB,MAAM,2BAAA,IAA+B,CAAC,OAAA,GAA6C,EAAC,KAAM;AACxF,EAAA,MAAM,kBAAA,GAAqB,QAAQ,kBAAA,IAAsB,IAAA;AACzD,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,CAAmB,KAAK,CAAA,IAAA,KAAQ;AACrC,IAAA,IAAI,OAAO,SAAS,QAAA,EAAU;AAC5B,MAAA,OAAO,IAAA,KAAS,UAAA;AAAA,IAClB;AAEA,IAAA,MAAM,CAAC,GAAA,EAAK,GAAG,CAAA,GAAI,IAAA;AACnB,IAAA,OAAO,UAAA,IAAc,OAAO,UAAA,IAAc,GAAA;AAAA,EAC5C,CAAC,CAAA;AACH;;;;;"}
|
|
1
|
+
{"version":3,"file":"httpServerSpansIntegration.js","sources":["../../../../src/integrations/http/httpServerSpansIntegration.ts"],"sourcesContent":["/* eslint-disable max-lines */\nimport { errorMonitor } from 'node:events';\nimport {\n CLIENT_ADDRESS,\n CLIENT_PORT,\n HTTP_REQUEST_METHOD,\n HTTP_RESPONSE_STATUS_CODE,\n NETWORK_LOCAL_ADDRESS,\n NETWORK_LOCAL_PORT,\n NETWORK_PEER_ADDRESS,\n NETWORK_PEER_PORT,\n NETWORK_PROTOCOL_NAME,\n NETWORK_PROTOCOL_VERSION,\n NETWORK_TRANSPORT,\n SENTRY_HTTP_PREFETCH,\n SENTRY_KIND,\n SENTRY_OP,\n SENTRY_SEGMENT_NAME_SOURCE,\n SERVER_ADDRESS,\n SERVER_PORT,\n URL_FRAGMENT,\n URL_FULL,\n URL_PATH,\n URL_QUERY,\n URL_SCHEME,\n USER_AGENT_ORIGINAL,\n} from '@sentry/conventions/attributes';\nimport { HTTP_SERVER } from '@sentry/conventions/op';\nimport type { Event, Integration, IntegrationFn, Span, SpanAttributes, SpanStatus } from '@sentry/core';\nimport type { HttpIncomingMessage, HttpServerResponse } from '@sentry/core/server';\nimport { DEFAULT_IGNORE_STATUS_CODES, processHttpServerTransactionEvent } from '@sentry/core/server';\nimport {\n debug,\n getSpanStatusFromHttpCode,\n httpHeadersToSpanAttributes,\n getContentLengthFromHeaders,\n parseStringToURLObject,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SPAN_STATUS_ERROR,\n stripUrlQueryAndFragment,\n isTracingSuppressed,\n bindScopeToEmitter,\n startInactiveSpan,\n withActiveSpan,\n getUrlFragment,\n getUrlQuery,\n filterCollectedUrl,\n filterCollectedUrlQuery,\n hasSpanStreamingEnabled,\n HTTP_SPAN_NAME_FALLBACK,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type { NodeClient } from '../../sdk/client';\nimport { addStartSpanCallback } from './httpServerIntegration';\n\nconst INTEGRATION_NAME = 'Http.ServerSpans' as const;\n\n// Tree-shakable guard to remove all code related to tracing\ndeclare const __SENTRY_TRACING__: boolean;\n\nexport interface HttpServerSpansIntegrationOptions {\n /**\n * Do not capture spans for incoming HTTP requests to URLs where the given callback returns `true`.\n * Spans will be non recording if tracing is disabled.\n *\n * The `urlPath` param consists of the URL path and query string (if any) of the incoming request.\n * For example: `'/users/details?id=123'`\n *\n * The `request` param contains the original {@type IncomingMessage} object of the incoming request.\n * You can use it to filter on additional properties like method, headers, etc.\n */\n ignoreIncomingRequests?: (urlPath: string, request: HttpIncomingMessage) => boolean;\n\n /**\n * Whether to automatically ignore common static asset requests like favicon.ico, robots.txt, etc.\n * This helps reduce noise in your transactions.\n *\n * @default `true`\n */\n ignoreStaticAssets?: boolean;\n\n /**\n * Do not capture spans for incoming HTTP requests with the given status codes.\n * By default, spans with some 3xx and 4xx status codes are ignored (see @default).\n * Expects an array of status codes or a range of status codes, e.g. [[300,399], 404] would ignore 3xx and 404 status codes.\n *\n * @default `[[401, 404], [301, 303], [305, 399]]`\n */\n ignoreStatusCodes?: (number | [number, number])[];\n\n /**\n * A hook that can be used to mutate the span for incoming requests.\n * This is triggered after the span is created, but before it is recorded.\n */\n onSpanCreated?: (span: Span, request: HttpIncomingMessage, response: HttpServerResponse) => void;\n}\n\nconst _httpServerSpansIntegration = ((options: HttpServerSpansIntegrationOptions = {}) => {\n const ignoreStaticAssets = options.ignoreStaticAssets ?? true;\n const ignoreIncomingRequests = options.ignoreIncomingRequests;\n const ignoreStatusCodes = options.ignoreStatusCodes ?? DEFAULT_IGNORE_STATUS_CODES;\n\n const { onSpanCreated } = options;\n\n return {\n name: INTEGRATION_NAME,\n setup(client: NodeClient) {\n // If no tracing, we can just skip everything here\n if (typeof __SENTRY_TRACING__ !== 'undefined' && !__SENTRY_TRACING__) {\n return;\n }\n\n client.on('httpServerRequest', (_request, _response, normalizedRequest) => {\n // Type-casting this here because we do not want to put the node types into core\n const request = _request as HttpIncomingMessage;\n const response = _response as HttpServerResponse;\n\n const startSpan = (next: () => boolean): boolean => {\n if (\n shouldIgnoreSpansForIncomingRequest(request, {\n ignoreStaticAssets,\n ignoreIncomingRequests,\n })\n ) {\n DEBUG_BUILD && debug.log(INTEGRATION_NAME, 'Skipping span creation for incoming request', request.url);\n return next();\n }\n\n const fullUrl = normalizedRequest.url || request.url || '/';\n const urlObj = parseStringToURLObject(fullUrl);\n\n const headers = request.headers;\n const userAgent = headers['user-agent'];\n const httpVersion = request.httpVersion;\n const host = headers.host as string | undefined;\n const hostname = host?.replace(/^(.*)(:[0-9]{1,5})/, '$1') || 'localhost';\n\n const scheme = fullUrl.startsWith('https') ? 'https' : 'http';\n\n const requestMethod = normalizedRequest.method || request.method?.toUpperCase();\n const method = requestMethod || 'GET';\n const httpTargetWithoutQueryFragment = urlObj ? urlObj.pathname : stripUrlQueryAndFragment(fullUrl);\n const bestEffortTransactionName = `${method} ${httpTargetWithoutQueryFragment}`;\n\n const query = getUrlQuery(urlObj?.search);\n const fragment = getUrlFragment(urlObj?.hash);\n\n const span = startInactiveSpan({\n // With span streaming, span names have to be low cardinality, so we can't fall back to the URL path.\n // Route instrumentations rename the span to `${method} ${route}` once a route is known.\n name: hasSpanStreamingEnabled(client)\n ? requestMethod || HTTP_SPAN_NAME_FALLBACK\n : bestEffortTransactionName,\n attributes: {\n // Sentry specific attributes\n [SENTRY_KIND]: 'server',\n [SENTRY_OP]: HTTP_SERVER,\n [SENTRY_SEGMENT_NAME_SOURCE]: 'url',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.http_server',\n [SENTRY_HTTP_PREFETCH]: isKnownPrefetchRequest(request) || undefined,\n [URL_FULL]: filterCollectedUrl(fullUrl, client),\n [URL_PATH]: urlObj?.pathname ?? httpTargetWithoutQueryFragment,\n [URL_QUERY]: filterCollectedUrlQuery(query, client),\n [URL_FRAGMENT]: fragment,\n [HTTP_REQUEST_METHOD]: normalizedRequest.method,\n [USER_AGENT_ORIGINAL]: userAgent,\n [URL_SCHEME]: scheme,\n [SERVER_ADDRESS]: hostname,\n [NETWORK_PROTOCOL_NAME]: 'http',\n [NETWORK_PROTOCOL_VERSION]: httpVersion,\n [NETWORK_TRANSPORT]: httpVersion?.toUpperCase() === 'QUIC' ? 'udp' : 'tcp',\n 'http.request.body.size': getContentLengthFromHeaders(request.headers),\n ...httpHeadersToSpanAttributes(normalizedRequest.headers || {}, client.getDataCollectionOptions()),\n },\n });\n\n onSpanCreated?.(span, request, response);\n\n return withActiveSpan(span, () => {\n bindScopeToEmitter(request);\n bindScopeToEmitter(response);\n\n // Ensure we only end the span once\n // E.g. error can be emitted before close is emitted\n let isEnded = false;\n function endSpan(status: SpanStatus): void {\n if (isEnded) {\n return;\n }\n\n isEnded = true;\n\n const newAttributes = getIncomingRequestAttributesOnResponse(\n request,\n response,\n client.getDataCollectionOptions().userInfo,\n );\n span.setAttributes(newAttributes);\n span.setStatus(status);\n span.end();\n }\n\n response.on('close', () => {\n endSpan(getSpanStatusFromHttpCode(response.statusCode));\n });\n response.on(errorMonitor, () => {\n const httpStatus = getSpanStatusFromHttpCode(response.statusCode);\n // Ensure we def. have an error status here\n endSpan(httpStatus.code === SPAN_STATUS_ERROR ? httpStatus : { code: SPAN_STATUS_ERROR });\n });\n\n return next();\n });\n };\n\n addStartSpanCallback(request, startSpan);\n });\n },\n processEvent(event) {\n return processHttpServerTransactionEvent(event, ignoreStatusCodes);\n },\n afterAllSetup(client) {\n if (!DEBUG_BUILD) {\n return;\n }\n\n if (client.getIntegrationByName('Http')) {\n debug.warn(\n 'It seems that you have manually added `httpServerSpansIntegration` while `httpIntegration` is also present. Make sure to remove `httpIntegration` when adding `httpServerSpansIntegration`.',\n );\n }\n\n if (!client.getIntegrationByName('Http.Server')) {\n debug.error(\n 'It seems that you have manually added `httpServerSpansIntegration` without adding `httpServerIntegration`. This is a requiement for spans to be created - please add the `httpServerIntegration` integration.',\n );\n }\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * This integration emits spans for incoming requests handled via the node `http` module.\n * It requires the `httpServerIntegration` to be present.\n */\nexport const httpServerSpansIntegration = _httpServerSpansIntegration as (\n options?: HttpServerSpansIntegrationOptions,\n) => Integration & {\n name: 'Http.ServerSpans';\n setup: (client: NodeClient) => void;\n processEvent: (event: Event) => Event | null;\n};\n\nfunction isKnownPrefetchRequest(req: HttpIncomingMessage): boolean {\n // Currently only handles Next.js prefetch requests but may check other frameworks in the future.\n return req.headers['next-router-prefetch'] === '1';\n}\n\n/**\n * Check if a request is for a common static asset that should be ignored by default.\n *\n * Only exported for tests.\n */\nexport function isStaticAssetRequest(urlPath: string): boolean {\n const path = stripUrlQueryAndFragment(urlPath);\n // Common static file extensions\n if (path.match(/\\.(ico|png|jpg|jpeg|gif|svg|css|js|woff|woff2|ttf|eot|webp|avif)$/)) {\n return true;\n }\n\n // Common metadata files\n if (path.match(/^\\/(robots\\.txt|sitemap\\.xml|manifest\\.json|browserconfig\\.xml)$/)) {\n return true;\n }\n\n return false;\n}\n\nfunction shouldIgnoreSpansForIncomingRequest(\n request: HttpIncomingMessage,\n {\n ignoreStaticAssets,\n ignoreIncomingRequests,\n }: {\n ignoreStaticAssets?: boolean;\n ignoreIncomingRequests?: (urlPath: string, request: HttpIncomingMessage) => boolean;\n },\n): boolean {\n if (isTracingSuppressed()) {\n return true;\n }\n\n // request.url is the only property that holds any information about the url\n // it only consists of the URL path and query string (if any)\n const urlPath = request.url;\n\n const method = request.method?.toUpperCase();\n // We do not capture OPTIONS/HEAD requests as spans\n if (method === 'OPTIONS' || method === 'HEAD' || !urlPath) {\n return true;\n }\n\n // Default static asset filtering\n if (ignoreStaticAssets && method === 'GET' && isStaticAssetRequest(urlPath)) {\n return true;\n }\n\n if (ignoreIncomingRequests?.(urlPath, request)) {\n return true;\n }\n\n return false;\n}\n\n/**\n * First entry of `X-Forwarded-For`: the client as seen by the outermost proxy.\n * https://opentelemetry.io/docs/specs/semconv/registry/attributes/client/#client-address\n */\nfunction getForwardedClientAddress(forwardedFor: string | string[] | undefined): string | undefined {\n return typeof forwardedFor === 'string' ? forwardedFor.split(',')[0]?.trim() || undefined : undefined;\n}\n\nfunction getIncomingRequestAttributesOnResponse(\n request: HttpIncomingMessage,\n response: HttpServerResponse,\n collectClientAddress: boolean,\n): SpanAttributes {\n // take socket from the request,\n // since it may be detached from the response object in keep-alive mode\n const { socket } = request;\n const { statusCode, statusMessage } = response;\n\n const newAttributes: SpanAttributes = {\n [HTTP_RESPONSE_STATUS_CODE]: statusCode,\n 'http.response.status_text': statusMessage?.toUpperCase(),\n };\n\n if (collectClientAddress) {\n // `client.address` is the originating client, so a forwarding header wins over the socket, which\n // behind a proxy holds the proxy's address. `network.peer.address` below keeps the socket value.\n newAttributes[CLIENT_ADDRESS] =\n getForwardedClientAddress(request.headers['x-forwarded-for']) ?? socket?.remoteAddress;\n }\n\n if (socket) {\n const { localAddress, localPort, remoteAddress, remotePort } = socket;\n newAttributes[SERVER_PORT] = localPort;\n newAttributes[NETWORK_LOCAL_ADDRESS] = localAddress;\n newAttributes[NETWORK_LOCAL_PORT] = localPort;\n newAttributes[CLIENT_PORT] = remotePort;\n newAttributes[NETWORK_PEER_ADDRESS] = collectClientAddress ? remoteAddress : undefined;\n newAttributes[NETWORK_PEER_PORT] = remotePort;\n }\n\n return newAttributes;\n}\n"],"names":["DEFAULT_IGNORE_STATUS_CODES","DEBUG_BUILD","debug","parseStringToURLObject","stripUrlQueryAndFragment","getUrlQuery","getUrlFragment","startInactiveSpan","hasSpanStreamingEnabled","HTTP_SPAN_NAME_FALLBACK","SENTRY_KIND","SENTRY_OP","HTTP_SERVER","SENTRY_SEGMENT_NAME_SOURCE","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","SENTRY_HTTP_PREFETCH","URL_FULL","filterCollectedUrl","URL_PATH","URL_QUERY","filterCollectedUrlQuery","URL_FRAGMENT","HTTP_REQUEST_METHOD","USER_AGENT_ORIGINAL","URL_SCHEME","SERVER_ADDRESS","NETWORK_PROTOCOL_NAME","NETWORK_PROTOCOL_VERSION","NETWORK_TRANSPORT","getContentLengthFromHeaders","httpHeadersToSpanAttributes","withActiveSpan","bindScopeToEmitter","getSpanStatusFromHttpCode","errorMonitor","SPAN_STATUS_ERROR","addStartSpanCallback","processHttpServerTransactionEvent","isTracingSuppressed","HTTP_RESPONSE_STATUS_CODE","CLIENT_ADDRESS","SERVER_PORT","NETWORK_LOCAL_ADDRESS","NETWORK_LOCAL_PORT","CLIENT_PORT","NETWORK_PEER_ADDRESS","NETWORK_PEER_PORT"],"mappings":";;;;;;;;;;AAuDA,MAAM,gBAAA,GAAmB,kBAAA;AA0CzB,MAAM,2BAAA,IAA+B,CAAC,OAAA,GAA6C,EAAC,KAAM;AACxF,EAAA,MAAM,kBAAA,GAAqB,QAAQ,kBAAA,IAAsB,IAAA;AACzD,EAAA,MAAM,yBAAyB,OAAA,CAAQ,sBAAA;AACvC,EAAA,MAAM,iBAAA,GAAoB,QAAQ,iBAAA,IAAqBA,kCAAA;AAEvD,EAAA,MAAM,EAAE,eAAc,GAAI,OAAA;AAE1B,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,MAAM,MAAA,EAAoB;AAExB,MAAA,IAAI,OAAO,kBAAA,KAAuB,WAAA,IAAe,CAAC,kBAAA,EAAoB;AACpE,QAAA;AAAA,MACF;AAEA,MAAA,MAAA,CAAO,EAAA,CAAG,mBAAA,EAAqB,CAAC,QAAA,EAAU,WAAW,iBAAA,KAAsB;AAEzE,QAAA,MAAM,OAAA,G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C7E,IAAA,aAAA,CAAcC,4BAAiB,CAAA,GAAI,UAAA;AAAA,EACrC;AAEA,EAAA,OAAO,aAAA;AACT;;;;;"}
|
|
@@ -2,6 +2,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
2
2
|
|
|
3
3
|
const attributes = require('@sentry/conventions/attributes');
|
|
4
4
|
const core = require('@sentry/core');
|
|
5
|
+
const server = require('@sentry/core/server');
|
|
5
6
|
const httpServerIntegration = require('./httpServerIntegration.js');
|
|
6
7
|
const httpServerSpansIntegration = require('./httpServerSpansIntegration.js');
|
|
7
8
|
const SentryHttpInstrumentation = require('./SentryHttpInstrumentation.js');
|
|
@@ -10,7 +11,7 @@ const INTEGRATION_NAME = "Http";
|
|
|
10
11
|
const httpIntegration = core.defineIntegration((options = {}) => {
|
|
11
12
|
const spans = options.spans ?? true;
|
|
12
13
|
const enableServerSpans = spans && !options.disableIncomingRequestSpans;
|
|
13
|
-
const server = httpServerIntegration.httpServerIntegration(options);
|
|
14
|
+
const server$1 = httpServerIntegration.httpServerIntegration(options);
|
|
14
15
|
const serverSpans = httpServerSpansIntegration.httpServerSpansIntegration(options);
|
|
15
16
|
return {
|
|
16
17
|
name: INTEGRATION_NAME,
|
|
@@ -21,17 +22,20 @@ const httpIntegration = core.defineIntegration((options = {}) => {
|
|
|
21
22
|
}
|
|
22
23
|
},
|
|
23
24
|
setupOnce() {
|
|
24
|
-
server.setupOnce();
|
|
25
|
+
server$1.setupOnce();
|
|
25
26
|
const outgoingRequestOptions = {
|
|
26
27
|
breadcrumbs: options.breadcrumbs,
|
|
27
28
|
spans,
|
|
28
29
|
tracePropagation: options.tracePropagation ?? true,
|
|
29
30
|
ignoreOutgoingRequests: options.ignoreOutgoingRequests,
|
|
30
31
|
outgoingRequestHook: (span, request) => {
|
|
31
|
-
const url =
|
|
32
|
+
const url = server.getRequestUrlFromClientRequest(request);
|
|
32
33
|
if (url.startsWith("data:")) {
|
|
33
34
|
const sanitizedUrl = core.stripDataUrlContent(url);
|
|
34
|
-
|
|
35
|
+
const client = core.getClient();
|
|
36
|
+
if (!client || !core.hasSpanStreamingEnabled(client)) {
|
|
37
|
+
span.updateName(`${request.method || "GET"} ${sanitizedUrl}`);
|
|
38
|
+
}
|
|
35
39
|
span.setAttributes({
|
|
36
40
|
[attributes.URL_FULL]: sanitizedUrl
|
|
37
41
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../../src/integrations/http/index.ts"],"sourcesContent":["import type { ClientRequest, RequestOptions } from 'node:http';\nimport type { Span } from '@sentry/core';\nimport { URL_FULL } from '@sentry/conventions/attributes';\nimport {
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../../src/integrations/http/index.ts"],"sourcesContent":["import type { ClientRequest, RequestOptions } from 'node:http';\nimport type { Span } from '@sentry/core';\nimport { URL_FULL } from '@sentry/conventions/attributes';\nimport {\n defineIntegration,\n getClient,\n hasSpansEnabled,\n hasSpanStreamingEnabled,\n stripDataUrlContent,\n} from '@sentry/core';\nimport { getRequestUrlFromClientRequest } from '@sentry/core/server';\nimport type { NodeClient } from '../../sdk/client';\nimport type { HttpServerIntegrationOptions } from './httpServerIntegration';\nimport { httpServerIntegration } from './httpServerIntegration';\nimport type { HttpServerSpansIntegrationOptions } from './httpServerSpansIntegration';\nimport { httpServerSpansIntegration } from './httpServerSpansIntegration';\nimport type { OutgoingHttpRequestInstrumentationOptions } from './SentryHttpInstrumentation';\nimport { instrumentHttpOutgoingRequests } from './SentryHttpInstrumentation';\n\nconst INTEGRATION_NAME = 'Http' as const;\n\ninterface HttpOptions extends HttpServerIntegrationOptions, HttpServerSpansIntegrationOptions {\n /**\n * Whether breadcrumbs should be recorded for outgoing requests.\n * Defaults to true\n */\n breadcrumbs?: boolean;\n\n /**\n * If set to false, do not emit any spans.\n * This will ensure that the default HttpInstrumentation from OpenTelemetry is not setup,\n * only the Sentry-specific instrumentation for request isolation is applied.\n *\n * Defaults to `true` when tracing is enabled.\n */\n spans?: boolean;\n\n /**\n * Whether to inject trace propagation headers (sentry-trace, baggage, traceparent) into outgoing HTTP requests.\n *\n * When set to `false`, Sentry will not inject any trace propagation headers, but will still create breadcrumbs\n * (if `breadcrumbs` is enabled). This is useful when you run your own OpenTelemetry `HttpInstrumentation` and\n * want to avoid duplicate trace headers being injected by both Sentry and OpenTelemetry.\n *\n * @default `true`\n */\n tracePropagation?: boolean;\n\n /**\n * Do not capture spans or breadcrumbs for outgoing HTTP requests to URLs where the given callback returns `true`.\n * This controls both span & breadcrumb creation - spans will be non recording if tracing is disabled.\n *\n * The `url` param contains the entire URL, including query string (if any), protocol, host, etc. of the outgoing request.\n * For example: `'https://someService.com/users/details?id=123'`\n *\n * The `request` param contains the original {@type RequestOptions} object used to make the outgoing request.\n * You can use it to filter on additional properties like method, headers, etc.\n */\n ignoreOutgoingRequests?: (url: string, request: RequestOptions) => boolean;\n\n /**\n * If true, do not generate spans for incoming requests at all.\n * This is used by Remix to avoid generating spans for incoming requests, as it generates its own spans.\n */\n disableIncomingRequestSpans?: boolean;\n\n /**\n * Called after an outgoing request span is created.\n * Only invoked when spans are created for outgoing requests.\n */\n outgoingRequestHook?: OutgoingHttpRequestInstrumentationOptions['outgoingRequestHook'];\n\n /**\n * Called when the outgoing request receives a response.\n * Only invoked when spans are created for outgoing requests.\n */\n outgoingResponseHook?: OutgoingHttpRequestInstrumentationOptions['outgoingResponseHook'];\n\n /**\n * Called when both the outgoing request and response are available.\n * Only invoked when spans are created for outgoing requests.\n */\n outgoingRequestApplyCustomAttributes?: OutgoingHttpRequestInstrumentationOptions['outgoingRequestApplyCustomAttributes'];\n}\n\n/**\n * The http integration instruments Node's internal http and https modules.\n * It creates breadcrumbs and spans for outgoing HTTP requests which will be attached to the currently active span.\n */\nexport const httpIntegration = defineIntegration((options: HttpOptions = {}) => {\n const spans = options.spans ?? true;\n const enableServerSpans = spans && !options.disableIncomingRequestSpans;\n\n const server = httpServerIntegration(options);\n const serverSpans = httpServerSpansIntegration(options);\n\n return {\n name: INTEGRATION_NAME,\n setup(client: NodeClient) {\n const clientOptions = client.getOptions();\n\n if (enableServerSpans && hasSpansEnabled(clientOptions)) {\n serverSpans.setup(client);\n }\n },\n setupOnce() {\n server.setupOnce();\n\n const outgoingRequestOptions: OutgoingHttpRequestInstrumentationOptions = {\n breadcrumbs: options.breadcrumbs,\n spans,\n tracePropagation: options.tracePropagation ?? true,\n ignoreOutgoingRequests: options.ignoreOutgoingRequests,\n outgoingRequestHook: (span: Span, request: ClientRequest) => {\n // Sanitize data URLs to prevent long base64 strings in span attributes\n const url = getRequestUrlFromClientRequest(request);\n if (url.startsWith('data:')) {\n const sanitizedUrl = stripDataUrlContent(url);\n // With span streaming the span already carries a low-cardinality name, so it must not be\n // renamed back to something containing the URL.\n const client = getClient();\n if (!client || !hasSpanStreamingEnabled(client)) {\n span.updateName(`${request.method || 'GET'} ${sanitizedUrl}`);\n }\n span.setAttributes({\n [URL_FULL]: sanitizedUrl,\n });\n }\n options.outgoingRequestHook?.(span, request);\n },\n outgoingResponseHook: options.outgoingResponseHook,\n outgoingRequestApplyCustomAttributes: options.outgoingRequestApplyCustomAttributes,\n };\n\n // This is Sentry-specific instrumentation for outgoing request\n // breadcrumbs & trace propagation. It uses the diagnostic channels on\n // node versions that support it, falling back to monkey-patching when\n // needed.\n instrumentHttpOutgoingRequests(outgoingRequestOptions);\n },\n processEvent(event) {\n // Always run this, even if spans are disabled\n // The reason being that e.g. the remix integration disables span\n // creation here but still wants to use the ignore status codes option\n return serverSpans.processEvent(event);\n },\n };\n});\n"],"names":["defineIntegration","server","httpServerIntegration","httpServerSpansIntegration","hasSpansEnabled","getRequestUrlFromClientRequest","stripDataUrlContent","getClient","hasSpanStreamingEnabled","URL_FULL","instrumentHttpOutgoingRequests"],"mappings":";;;;;;;;;AAmBA,MAAM,gBAAA,GAAmB,MAAA;AAsElB,MAAM,eAAA,GAAkBA,sBAAA,CAAkB,CAAC,OAAA,GAAuB,EAAC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AK,aAAA,CAAc;AAAA,cACjB,CAACC,mBAAQ,GAAG;AAAA,aACb,CAAA;AAAA,UACH;AACA,UAAA,OAAA,CAAQ,mBAAA,GAAsB,MAAM,OAAO,CAAA;AAAA,QAC7C,CAAA;AAAA,QACA,sBAAsB,OAAA,CAAQ,oBAAA;AAAA,QAC9B,sCAAsC,OAAA,CAAQ;AAAA,OAChD;AAMA,MAAAC,wDAAA,CAA+B,sBAAsB,CAAA;AAAA,IACvD,CAAA;AAAA,IACA,aAAa,KAAA,EAAO;AAIlB,MAAA,OAAO,WAAA,CAAY,aAAa,KAAK,CAAA;AAAA,IACvC;AAAA,GACF;AACF,CAAC;;;;"}
|
|
@@ -5,7 +5,7 @@ const core = require('@sentry/core');
|
|
|
5
5
|
const debug = require('../../utils/debug.js');
|
|
6
6
|
const common = require('./common.js');
|
|
7
7
|
|
|
8
|
-
const base64WorkerScript = "
|
|
8
|
+
const base64WorkerScript = "LyohIEBzZW50cnkvbm9kZSAxMS4wLjAtYmV0YS4wICg1NGJiYWU5KSB8IGh0dHBzOi8vZ2l0aHViLmNvbS9nZXRzZW50cnkvc2VudHJ5LWphdmFzY3JpcHQgKi8KaW1wb3J0e1Nlc3Npb24gYXMgZX1mcm9tIm5vZGU6aW5zcGVjdG9yL3Byb21pc2VzIjtpbXBvcnR7d29ya2VyRGF0YSBhcyB0fWZyb20ibm9kZTp3b3JrZXJfdGhyZWFkcyI7Y29uc3Qgbj1nbG9iYWxUaGlzLGk9e307Y29uc3Qgbz0iX19TRU5UUllfRVJST1JfTE9DQUxfVkFSSUFCTEVTX18iO2NvbnN0IGE9dDtmdW5jdGlvbiBzKC4uLmUpe2EuZGVidWcmJmZ1bmN0aW9uKGUpe2lmKCEoImNvbnNvbGUiaW4gbikpcmV0dXJuIGUoKTtjb25zdCB0PW4uY29uc29sZSxvPXt9LGE9T2JqZWN0LmtleXMoaSk7YS5mb3JFYWNoKGU9Pntjb25zdCBuPWlbZV07b1tlXT10W2VdLHRbZV09bn0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PT57aSs9MX19KGUsYXN5bmMoKT0+e3MoIlJhdGUtbGltaXQgbGlmdGVkLiIpLGF3YWl0IHQucG9zdCgiRGVidWdnZXIuc2V0UGF1c2VPbkV4Y2VwdGlvbnMiLHtzdGF0ZToiYWxsIn0pfSxhc3luYyBlPT57cyhgUmF0ZS1saW1pdCBleGNlZWRlZC4gRGlzYWJsaW5nIGNhcHR1cmluZyBvZiBjYXVnaHQgZXhjZXB0aW9ucyBmb3IgJHtlfSBzZWNvbmRzLmApLGF3YWl0IHQucG9zdCgiRGVidWdnZXIuc2V0UGF1c2VPbkV4Y2VwdGlvbnMiLHtzdGF0ZToidW5jYXVnaHQifSl9KX19KSgpLmNhdGNoKGU9PntzKCJGYWlsZWQgdG8gc3RhcnQgZGVidWdnZXIiLGUpfSksc2V0SW50ZXJ2YWwoKCk9Pnt9LDFlNCk7";
|
|
9
9
|
function log(...args) {
|
|
10
10
|
core.debug.log("[LocalVariables]", ...args);
|
|
11
11
|
}
|
|
@@ -5,6 +5,7 @@ const url = require('url');
|
|
|
5
5
|
const core = require('@sentry/core');
|
|
6
6
|
const outgoingFetchRequest = require('../../utils/outgoingFetchRequest.js');
|
|
7
7
|
const attributes = require('@sentry/conventions/attributes');
|
|
8
|
+
const op = require('@sentry/conventions/op');
|
|
8
9
|
const debugBuild = require('../../debug-build.js');
|
|
9
10
|
|
|
10
11
|
const ATTR_HTTP_REQUEST_METHOD_ORIGINAL = "http.request.method_original";
|
|
@@ -98,10 +99,11 @@ function onRequestCreated(config, { request }) {
|
|
|
98
99
|
const requestMethod = getRequestMethod(request.method);
|
|
99
100
|
const attributes$1 = {
|
|
100
101
|
[attributes.SENTRY_KIND]: "client",
|
|
101
|
-
[attributes.SENTRY_OP]:
|
|
102
|
+
[attributes.SENTRY_OP]: op.HTTP_CLIENT,
|
|
102
103
|
[attributes.HTTP_REQUEST_METHOD]: requestMethod,
|
|
103
104
|
[ATTR_HTTP_REQUEST_METHOD_ORIGINAL]: request.method,
|
|
104
105
|
[attributes.URL_FULL]: core.filterCollectedUrl(requestUrl.toString()),
|
|
106
|
+
[attributes.URL_DOMAIN]: requestUrl.hostname || void 0,
|
|
105
107
|
[attributes.URL_PATH]: requestUrl.pathname,
|
|
106
108
|
[attributes.URL_QUERY]: core.filterCollectedUrlQuery(core.getUrlQuery(requestUrl.search)),
|
|
107
109
|
[attributes.URL_FRAGMENT]: core.getUrlFragment(requestUrl.hash),
|
|
@@ -127,8 +129,17 @@ function onRequestCreated(config, { request }) {
|
|
|
127
129
|
attributes$1[attributes.USER_AGENT_ORIGINAL] = userAgent;
|
|
128
130
|
}
|
|
129
131
|
const isDataUrl = url$1.startsWith("data:");
|
|
130
|
-
const spanName = requestMethod === "_OTHER" ? "HTTP" : isDataUrl ? `${request.method || "GET"} ${core.stripDataUrlContent(url$1)}` : `${requestMethod} ${core.getSanitizedUrlString(core.parseUrl(requestUrl.toString()))}`;
|
|
131
132
|
const client = core.getClient();
|
|
133
|
+
let spanName;
|
|
134
|
+
if (requestMethod === "_OTHER") {
|
|
135
|
+
spanName = core.HTTP_SPAN_NAME_FALLBACK;
|
|
136
|
+
} else if (!!client && core.hasSpanStreamingEnabled(client)) {
|
|
137
|
+
spanName = requestUrl.hostname ? `${requestMethod} ${requestUrl.hostname}` : requestMethod;
|
|
138
|
+
} else if (isDataUrl) {
|
|
139
|
+
spanName = `${request.method || "GET"} ${core.stripDataUrlContent(url$1)}`;
|
|
140
|
+
} else {
|
|
141
|
+
spanName = `${requestMethod} ${core.getSanitizedUrlString(core.parseUrl(requestUrl.toString()))}`;
|
|
142
|
+
}
|
|
132
143
|
const span = core.startInactiveSpan({
|
|
133
144
|
name: spanName,
|
|
134
145
|
attributes: attributes$1,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"undici-instrumentation.js","sources":["../../../../src/integrations/node-fetch/undici-instrumentation.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n *\n * NOTICE from the Sentry authors:\n * - Vendored from: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/ed97091c9890dd18e52759f2ea98e9d7593b3ae4/packages/instrumentation-undici\n * - Upstream version: @opentelemetry/instrumentation-undici@0.24.0\n * - Tracking issue: https://github.com/getsentry/sentry-javascript/issues/20165\n * - Refactored to use Sentry's span APIs instead of OpenTelemetry tracing APIs\n * - Dropped the OTel metrics (no MeterProvider is wired up) and the dead\n * `requireParentforSpans` code path (the SDK always passes `false`)\n * - Dropped the `@opentelemetry/instrumentation` base (undici reports via `diagnostics_channel`,\n * so no module patching was needed) — exposed as a plain `instrumentUndici()` function that the\n * integration wires up directly\n */\n\n/* eslint-disable max-lines */\n\nimport * as diagch from 'diagnostics_channel';\nimport { URL } from 'url';\n\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport {\n debug,\n getClient,\n getSanitizedUrlString,\n getSpanStatusFromHttpCode,\n hasSpanStreamingEnabled,\n isTracingSuppressed,\n LRUMap,\n parseUrl,\n SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n stripDataUrlContent,\n getUrlFragment,\n getUrlQuery,\n filterCollectedUrl,\n filterCollectedUrlQuery,\n} from '@sentry/core';\nimport { addFetchRequestBreadcrumb, addTracePropagationHeadersToFetchRequest } from '../../utils/outgoingFetchRequest';\nimport {\n HTTP_REQUEST_METHOD,\n HTTP_RESPONSE_STATUS_CODE,\n NETWORK_PEER_ADDRESS,\n NETWORK_PEER_PORT,\n SENTRY_KIND,\n SENTRY_OP,\n SERVER_ADDRESS,\n SERVER_PORT,\n URL_FRAGMENT,\n URL_FULL,\n URL_PATH,\n URL_QUERY,\n URL_SCHEME,\n USER_AGENT_ORIGINAL,\n} from '@sentry/conventions/attributes';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type {\n NodeFetchOptions,\n UndiciRequest,\n RequestErrorMessage,\n RequestHeadersMessage,\n RequestMessage,\n RequestTrailersMessage,\n ResponseHeadersMessage,\n} from './types';\n\n// `http.request.method_original` is not part of `@sentry/conventions`, so we keep it inline.\nconst ATTR_HTTP_REQUEST_METHOD_ORIGINAL = 'http.request.method_original';\n\n// Keep ref to avoid https://github.com/nodejs/node/issues/42170 bug\n// We can replace this with _isInstrumented once we drop support for Node.js 18.18.0\nconst _channelSubs: Array<unknown> = [];\nconst spanFromReq = new WeakMap<UndiciRequest, Span>();\n// Whether breadcrumbs (and span-less trace propagation) should be skipped for a given request.\n// We evaluate this at request-creation time because the active context is no longer correct by the\n// time the response-headers event fires.\nconst ignoreRequestMap = new WeakMap<UndiciRequest, boolean>();\n// Caches trace-propagation decisions per URL so we don't recompute the `tracePropagationTargets` regexes per request.\nconst propagationDecisionMap = new LRUMap<string, boolean>(100);\n\n/**\n * Instrument outgoing HTTP requests made through `undici` or the global `fetch` API: emit `http.client`\n * spans, record breadcrumbs, and propagate traces into the outgoing request headers.\n *\n * Span creation is gated by the `spans` option (defaults to `true`). When spans are disabled, breadcrumbs\n * are still recorded and trace propagation headers are still injected (gated by `tracePropagation`).\n *\n * undici reports its request lifecycle via `diagnostics_channel`, so rather than patching any module we\n * subscribe to those channels directly. This is idempotent — subsequent calls are no-ops once the\n * channels have been subscribed to, and the config of the first call wins.\n *\n * A combination of https://github.com/elastic/apm-agent-nodejs and\n * https://github.com/gadget-inc/opentelemetry-instrumentations/blob/main/packages/opentelemetry-instrumentation-undici/src/index.ts\n */\nexport function instrumentUndici(config: NodeFetchOptions = {}): void {\n // Avoid duplicate subscriptions\n if (_channelSubs.length) {\n return;\n }\n\n subscribeToChannel('undici:request:create', message => onRequestCreated(config, message as RequestMessage));\n subscribeToChannel('undici:client:sendHeaders', message =>\n onRequestHeaders(config, message as RequestHeadersMessage),\n );\n subscribeToChannel('undici:request:headers', message => onResponseHeaders(config, message as ResponseHeadersMessage));\n subscribeToChannel('undici:request:trailers', message => onDone(message as RequestTrailersMessage));\n subscribeToChannel('undici:request:error', message => onError(message as RequestErrorMessage));\n}\n\n/** Replaces OTel's `safeExecuteInTheMiddle`: run `fn`, route any error to `onError`, and swallow it. */\nfunction safeExecute<T>(fn: () => T, onError: (error: unknown) => void): T | undefined {\n try {\n return fn();\n } catch (error) {\n onError(error);\n return undefined;\n }\n}\n\nfunction subscribeToChannel(\n diagnosticChannel: string,\n onMessage: (message: unknown, name: string | symbol) => void,\n): void {\n _channelSubs.push(diagch.subscribe?.(diagnosticChannel, onMessage));\n}\n\nfunction parseRequestHeaders(request: UndiciRequest): Map<string, string | string[]> {\n const result = new Map<string, string | string[]>();\n\n if (Array.isArray(request.headers)) {\n // headers are an array [k1, v2, k2, v2] (undici v6+)\n // values could be string or a string[] for multiple values\n for (let i = 0; i < request.headers.length; i += 2) {\n const key = request.headers[i];\n const value = request.headers[i + 1];\n\n // Key should always be a string, but the types don't know that, and let's be safe\n if (typeof key === 'string' && value !== undefined) {\n result.set(key.toLowerCase(), value);\n }\n }\n } else if (typeof request.headers === 'string') {\n // headers are a raw string (undici v5)\n // headers could be repeated in several lines for multiple values\n const headers = request.headers.split('\\r\\n');\n for (const line of headers) {\n if (!line) {\n continue;\n }\n const colonIndex = line.indexOf(':');\n if (colonIndex === -1) {\n // Invalid header? Probably this can't happen, but again let's be safe.\n continue;\n }\n const key = line.substring(0, colonIndex).toLowerCase();\n const value = line.substring(colonIndex + 1).trim();\n const allValues = result.get(key);\n\n if (allValues && Array.isArray(allValues)) {\n allValues.push(value);\n } else if (allValues) {\n result.set(key, [allValues, value]);\n } else {\n result.set(key, value);\n }\n }\n }\n return result;\n}\n\n// This is the 1st message we receive for each request (fired after request creation). Here we will\n// create the span and populate some atttributes, then link the span to the request for further\n// span processing\nfunction onRequestCreated(config: NodeFetchOptions, { request }: RequestMessage): void {\n const url = getAbsoluteUrl(request.origin, request.path);\n\n const ignoredByCallback = safeExecute(\n () => !!config.ignoreOutgoingRequests?.(url),\n e => e && DEBUG_BUILD && debug.error('caught ignoreOutgoingRequests error: ', e),\n );\n\n // Breadcrumbs & span-less trace propagation are additionally skipped when tracing is suppressed.\n // We store this here because the active context is no longer correct in later channel events.\n const ignoreForBreadcrumbs = isTracingSuppressed() || !!ignoredByCallback;\n ignoreRequestMap.set(request, ignoreForBreadcrumbs);\n\n // When spans are disabled we do not create a span, but we still inject trace propagation headers\n // directly (unless disabled via `tracePropagation`).\n if (!config.spans) {\n if (config.tracePropagation !== false && !ignoreForBreadcrumbs) {\n addTracePropagationHeadersToFetchRequest(request, propagationDecisionMap);\n }\n return;\n }\n\n // Ignore span creation if:\n // - the outgoing request is ignored via config\n // - method is 'CONNECT'\n if (request.method === 'CONNECT' || ignoredByCallback) {\n return;\n }\n\n let requestUrl;\n try {\n requestUrl = new URL(request.path, request.origin);\n } catch (err) {\n DEBUG_BUILD && debug.warn('could not determine url.full:', err);\n // Skip instrumenting this request.\n return;\n }\n\n const urlScheme = requestUrl.protocol.replace(':', '');\n const requestMethod = getRequestMethod(request.method);\n const attributes: SpanAttributes = {\n [SENTRY_KIND]: 'client',\n [SENTRY_OP]: 'http.client',\n [HTTP_REQUEST_METHOD]: requestMethod,\n [ATTR_HTTP_REQUEST_METHOD_ORIGINAL]: request.method,\n [URL_FULL]: filterCollectedUrl(requestUrl.toString()),\n [URL_PATH]: requestUrl.pathname,\n [URL_QUERY]: filterCollectedUrlQuery(getUrlQuery(requestUrl.search)),\n [URL_FRAGMENT]: getUrlFragment(requestUrl.hash),\n [URL_SCHEME]: urlScheme,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.node_fetch',\n };\n\n // Sanitize data URLs to prevent long base64 strings in span attributes\n if (url.startsWith('data:')) {\n const sanitizedUrl = stripDataUrlContent(url);\n attributes[URL_FULL] = sanitizedUrl;\n attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME] = `${request.method || 'GET'} ${sanitizedUrl}`;\n }\n\n const schemePorts: Record<string, string> = { https: '443', http: '80' };\n const serverAddress = requestUrl.hostname;\n const serverPort = requestUrl.port || schemePorts[urlScheme];\n\n attributes[SERVER_ADDRESS] = serverAddress;\n if (serverPort && !isNaN(Number(serverPort))) {\n attributes[SERVER_PORT] = Number(serverPort);\n }\n\n // Get user agent from headers\n const headersMap = parseRequestHeaders(request);\n const userAgentValues = headersMap.get('user-agent');\n\n if (userAgentValues) {\n // NOTE: having multiple user agents is not expected so\n // we're going to take last one like `curl` does\n // ref: https://curl.se/docs/manpage.html#-A\n const userAgent = Array.isArray(userAgentValues) ? userAgentValues[userAgentValues.length - 1] : userAgentValues;\n attributes[USER_AGENT_ORIGINAL] = userAgent;\n }\n\n // Outside of span streaming, only record an `http.client` span when it has a parent. An orphan\n // one (no local parent) is left to the server for the downstream sampling decision: `onlyIfParent`\n // still creates a non-recording span so trace propagation headers are injected, but it isn't\n // emitted as a standalone transaction. This rule also lives in `SentrySampler`, but that only runs\n // when an OpenTelemetry SDK tracer provider is set up, so we enforce it here too, which covers\n // SDKs that don't use an OpenTelemetry tracer provider at all.\n const isDataUrl = url.startsWith('data:');\n const spanName =\n requestMethod === '_OTHER'\n ? 'HTTP'\n : isDataUrl\n ? `${request.method || 'GET'} ${stripDataUrlContent(url)}`\n : `${requestMethod} ${getSanitizedUrlString(parseUrl(requestUrl.toString()))}`;\n\n const client = getClient();\n const span = startInactiveSpan({\n name: spanName,\n attributes,\n onlyIfParent: !client || !hasSpanStreamingEnabled(client),\n });\n\n // Execute the request hook if defined\n safeExecute(\n () => config.requestHook?.(span, request),\n e => e && DEBUG_BUILD && debug.error('caught requestHook error: ', e),\n );\n\n // Context propagation goes last so no hook can tamper the propagation headers.\n // We propagate the trace data of the freshly created client span (not the active parent span)\n // so downstream services are parented to the http.client span, matching the upstream behavior.\n // This also de-duplicates against any trace headers the user set manually (e.g. via `getTraceData()`).\n addTracePropagationHeadersToFetchRequest(request, propagationDecisionMap, span);\n\n spanFromReq.set(request, span);\n}\n\n// This is the 2nd message we receive for each request. It is fired when connection with\n// the remote is established and about to send the first byte. Here we do have info about the\n// remote address and port so we can populate some `network.*` attributes into the span\nfunction onRequestHeaders(config: NodeFetchOptions, { request, socket }: RequestHeadersMessage): void {\n const span = spanFromReq.get(request);\n\n if (!span) {\n return;\n }\n\n const { remoteAddress, remotePort } = socket;\n const spanAttributes: SpanAttributes = {\n [NETWORK_PEER_ADDRESS]: remoteAddress,\n [NETWORK_PEER_PORT]: remotePort,\n };\n\n // After hooks have been processed (which may modify request headers)\n // we can collect the headers based on the configuration\n if (config.headersToSpanAttributes?.requestHeaders) {\n const headersToAttribs = new Set(config.headersToSpanAttributes.requestHeaders.map(n => n.toLowerCase()));\n const headersMap = parseRequestHeaders(request);\n\n for (const [name, value] of headersMap.entries()) {\n if (headersToAttribs.has(name)) {\n const attrValue = Array.isArray(value) ? value : [value];\n spanAttributes[`http.request.header.${name}`] = attrValue;\n }\n }\n }\n\n span.setAttributes(spanAttributes);\n}\n\n// This is the 3rd message we get for each request and it's fired when the server\n// headers are received, body may not be accessible yet.\n// From the response headers we can set the status and content length\nfunction onResponseHeaders(config: NodeFetchOptions, { request, response }: ResponseHeadersMessage): void {\n // Breadcrumbs are recorded independently of spans, so this runs even when span creation is disabled.\n const breadcrumbsEnabled = config.breadcrumbs !== false;\n if (breadcrumbsEnabled && !ignoreRequestMap.get(request)) {\n addFetchRequestBreadcrumb(request, response);\n }\n\n const span = spanFromReq.get(request);\n\n if (!span) {\n return;\n }\n\n const spanAttributes: SpanAttributes = {\n [HTTP_RESPONSE_STATUS_CODE]: response.statusCode,\n };\n\n // Execute the response hook if defined\n safeExecute(\n () => config.responseHook?.(span, { request, response }),\n e => e && DEBUG_BUILD && debug.error('caught responseHook error: ', e),\n );\n\n if (config.headersToSpanAttributes?.responseHeaders) {\n const headersToAttribs = new Set<string>();\n config.headersToSpanAttributes?.responseHeaders.forEach(name => headersToAttribs.add(name.toLowerCase()));\n\n for (let idx = 0; idx < response.headers.length; idx = idx + 2) {\n const nameBuf = response.headers[idx];\n const valueBuf = response.headers[idx + 1];\n if (nameBuf === undefined || valueBuf === undefined) {\n continue;\n }\n const name = nameBuf.toString().toLowerCase();\n const value = valueBuf;\n\n if (headersToAttribs.has(name)) {\n const attrName = `http.response.header.${name}`;\n if (!Object.prototype.hasOwnProperty.call(spanAttributes, attrName)) {\n spanAttributes[attrName] = [value.toString()];\n } else {\n (spanAttributes[attrName] as string[]).push(value.toString());\n }\n }\n }\n }\n\n span.setAttributes(spanAttributes);\n\n // Resolve the HTTP status code to a Sentry span status here (like the raw http client/server\n // instrumentation does) instead of setting a bare error and deferring to downstream inference.\n // The SentryTracerProvider's status finalization reads the already-stringified span status, which\n // can no longer be inferred back to `not_found` etc. the way the OpenTelemetry SDK exporter's\n // `mapStatus` does from the raw `{ code, message }`.\n if (response.statusCode >= 400) {\n span.setStatus(getSpanStatusFromHttpCode(response.statusCode));\n }\n}\n\n// This is the last event we receive if the request went without any errors\nfunction onDone({ request }: RequestTrailersMessage): void {\n const span = spanFromReq.get(request);\n\n if (!span) {\n return;\n }\n\n span.end();\n spanFromReq.delete(request);\n}\n\n// This is the event we get when something is wrong in the request like\n// - invalid options when calling `fetch` global API or any undici method for request\n// - connectivity errors such as unreachable host\n// - requests aborted through an `AbortController.signal`\n// NOTE: server errors are considered valid responses and it's the lib consumer\n// who should deal with that.\nfunction onError({ request, error }: RequestErrorMessage): void {\n const span = spanFromReq.get(request);\n\n if (!span) {\n return;\n }\n\n // NOTE: in `undici@6.3.0` when request aborted the error type changes from\n // a custom error (`RequestAbortedError`) to a built-in `DOMException` carrying\n // some differences:\n // - `code` is from DOMEXception (ABORT_ERR: 20)\n // - `message` changes\n // - stacktrace is smaller and contains node internal frames\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message: error.message,\n });\n span.end();\n spanFromReq.delete(request);\n}\n\nfunction getRequestMethod(original: string): string {\n const knownMethods = {\n CONNECT: true,\n OPTIONS: true,\n HEAD: true,\n GET: true,\n POST: true,\n PUT: true,\n PATCH: true,\n DELETE: true,\n TRACE: true,\n // QUERY from https://datatracker.ietf.org/doc/rfc10008/\n QUERY: true,\n };\n\n if (original.toUpperCase() in knownMethods) {\n return original.toUpperCase();\n }\n\n return '_OTHER';\n}\n\n// Matching the behavior of the base instrumentation\nfunction getAbsoluteUrl(origin: string, path: string = '/'): string {\n const url = `${origin}`;\n\n if (url.endsWith('/') && path.startsWith('/')) {\n return `${url}${path.slice(1)}`;\n }\n\n if (!url.endsWith('/') && !path.startsWith('/')) {\n return `${url}/${path}`;\n }\n\n return `${url}${path}`;\n}\n"],"names":["LRUMap","onError","url","DEBUG_BUILD","debug","isTracingSuppressed","addTracePropagationHeadersToFetchRequest","URL","attributes","SENTRY_KIND","SENTRY_OP","HTTP_REQUEST_METHOD","URL_FULL","filterCollectedUrl","URL_PATH","URL_QUERY","filterCollectedUrlQuery","getUrlQuery","URL_FRAGMENT","getUrlFragment","URL_SCHEME","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","stripDataUrlContent","SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME","SERVER_ADDRESS","SERVER_PORT","USER_AGENT_ORIGINAL","getSanitizedUrlString","parseUrl","getClient","startInactiveSpan","hasSpanStreamingEnabled","NETWORK_PEER_ADDRESS","NETWORK_PEER_PORT","addFetchRequestBreadcrumb","HTTP_RESPONSE_STATUS_CODE","getSpanStatusFromHttpCode","SPAN_STATUS_ERROR"],"mappings":";;;;;;;;;AAsEA,MAAM,iCAAA,GAAoC,8BAAA;AAI1C,MAAM,eAA+B,EAAC;AACtC,MAAM,WAAA,uBAAkB,OAAA,EAA6B;AAIrD,MAAM,gBAAA,uBAAuB,OAAA,EAAgC;AAE7D,MAAM,sBAAA,GAAyB,IAAIA,WAAA,CAAwB,GAAG,CAAA;AAgBvD,SAAS,gBAAA,CAAiB,MAAA,GAA2B,EAAC,EAAS;AAEpE,EAAA,IAAI,aAAa,MAAA,EAAQ;AACvB,IAAA;AAAA,EACF;AAEA,EAAA,kBAAA,CA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,EAAS,IAAA;AAAA,IACT,OAAA,EAAS,IAAA;AAAA,IACT,IAAA,EAAM,IAAA;AAAA,IACN,GAAA,EAAK,IAAA;AAAA,IACL,IAAA,EAAM,IAAA;AAAA,IACN,GAAA,EAAK,IAAA;AAAA,IACL,KAAA,EAAO,IAAA;AAAA,IACP,MAAA,EAAQ,IAAA;AAAA,IACR,KAAA,EAAO,IAAA;AAAA;AAAA,IAEP,KAAA,EAAO;AAAA,GACT;AAEA,EAAA,IAAI,QAAA,CAAS,WAAA,EAAY,IAAK,YAAA,EAAc;AAC1C,IAAA,OAAO,SAAS,WAAA,EAAY;AAAA,EAC9B;AAEA,EAAA,OAAO,QAAA;AACT;AAGA,SAAS,cAAA,CAAe,MAAA,EAAgB,IAAA,GAAe,GAAA,EAAa;AAClE,EAAA,MAAM,GAAA,GAAM,GAAG,MAAM,CAAA,CAAA;AAErB,EAAA,IAAI,IAAI,QAAA,CAAS,GAAG,KAAK,IAAA,CAAK,UAAA,CAAW,GAAG,CAAA,EAAG;AAC7C,IAAA,OAAO,GAAG,GAAG,CAAA,EAAG,IAAA,CAAK,KAAA,CAAM,CAAC,CAAC,CAAA,CAAA;AAAA,EAC/B;AAEA,EAAA,IAAI,CAAC,IAAI,QAAA,CAAS,GAAG,KAAK,CAAC,IAAA,CAAK,UAAA,CAAW,GAAG,CAAA,EAAG;AAC/C,IAAA,OAAO,CAAA,EAAG,GAAG,CAAA,CAAA,EAAI,IAAI,CAAA,CAAA;AAAA,EACvB;AAEA,EAAA,OAAO,CAAA,EAAG,GAAG,CAAA,EAAG,IAAI,CAAA,CAAA;AACtB;;;;"}
|
|
1
|
+
{"version":3,"file":"undici-instrumentation.js","sources":["../../../../src/integrations/node-fetch/undici-instrumentation.ts"],"sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n *\n * NOTICE from the Sentry authors:\n * - Vendored from: https://github.com/open-telemetry/opentelemetry-js-contrib/tree/ed97091c9890dd18e52759f2ea98e9d7593b3ae4/packages/instrumentation-undici\n * - Upstream version: @opentelemetry/instrumentation-undici@0.24.0\n * - Tracking issue: https://github.com/getsentry/sentry-javascript/issues/20165\n * - Refactored to use Sentry's span APIs instead of OpenTelemetry tracing APIs\n * - Dropped the OTel metrics (no MeterProvider is wired up) and the dead\n * `requireParentforSpans` code path (the SDK always passes `false`)\n * - Dropped the `@opentelemetry/instrumentation` base (undici reports via `diagnostics_channel`,\n * so no module patching was needed) — exposed as a plain `instrumentUndici()` function that the\n * integration wires up directly\n */\n\n/* eslint-disable max-lines */\n\nimport * as diagch from 'diagnostics_channel';\nimport { URL } from 'url';\n\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport {\n debug,\n getClient,\n getSanitizedUrlString,\n getSpanStatusFromHttpCode,\n hasSpanStreamingEnabled,\n HTTP_SPAN_NAME_FALLBACK,\n isTracingSuppressed,\n LRUMap,\n parseUrl,\n SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SPAN_STATUS_ERROR,\n startInactiveSpan,\n stripDataUrlContent,\n getUrlFragment,\n getUrlQuery,\n filterCollectedUrl,\n filterCollectedUrlQuery,\n} from '@sentry/core';\nimport { addFetchRequestBreadcrumb, addTracePropagationHeadersToFetchRequest } from '../../utils/outgoingFetchRequest';\nimport {\n HTTP_REQUEST_METHOD,\n HTTP_RESPONSE_STATUS_CODE,\n NETWORK_PEER_ADDRESS,\n NETWORK_PEER_PORT,\n SENTRY_KIND,\n SENTRY_OP,\n SERVER_ADDRESS,\n SERVER_PORT,\n URL_DOMAIN,\n URL_FRAGMENT,\n URL_FULL,\n URL_PATH,\n URL_QUERY,\n URL_SCHEME,\n USER_AGENT_ORIGINAL,\n} from '@sentry/conventions/attributes';\nimport { HTTP_CLIENT } from '@sentry/conventions/op';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport type {\n NodeFetchOptions,\n UndiciRequest,\n RequestErrorMessage,\n RequestHeadersMessage,\n RequestMessage,\n RequestTrailersMessage,\n ResponseHeadersMessage,\n} from './types';\n\n// `http.request.method_original` is not part of `@sentry/conventions`, so we keep it inline.\nconst ATTR_HTTP_REQUEST_METHOD_ORIGINAL = 'http.request.method_original';\n\n// Keep ref to avoid https://github.com/nodejs/node/issues/42170 bug\n// We can replace this with _isInstrumented once we drop support for Node.js 18.18.0\nconst _channelSubs: Array<unknown> = [];\nconst spanFromReq = new WeakMap<UndiciRequest, Span>();\n// Whether breadcrumbs (and span-less trace propagation) should be skipped for a given request.\n// We evaluate this at request-creation time because the active context is no longer correct by the\n// time the response-headers event fires.\nconst ignoreRequestMap = new WeakMap<UndiciRequest, boolean>();\n// Caches trace-propagation decisions per URL so we don't recompute the `tracePropagationTargets` regexes per request.\nconst propagationDecisionMap = new LRUMap<string, boolean>(100);\n\n/**\n * Instrument outgoing HTTP requests made through `undici` or the global `fetch` API: emit `http.client`\n * spans, record breadcrumbs, and propagate traces into the outgoing request headers.\n *\n * Span creation is gated by the `spans` option (defaults to `true`). When spans are disabled, breadcrumbs\n * are still recorded and trace propagation headers are still injected (gated by `tracePropagation`).\n *\n * undici reports its request lifecycle via `diagnostics_channel`, so rather than patching any module we\n * subscribe to those channels directly. This is idempotent — subsequent calls are no-ops once the\n * channels have been subscribed to, and the config of the first call wins.\n *\n * A combination of https://github.com/elastic/apm-agent-nodejs and\n * https://github.com/gadget-inc/opentelemetry-instrumentations/blob/main/packages/opentelemetry-instrumentation-undici/src/index.ts\n */\nexport function instrumentUndici(config: NodeFetchOptions = {}): void {\n // Avoid duplicate subscriptions\n if (_channelSubs.length) {\n return;\n }\n\n subscribeToChannel('undici:request:create', message => onRequestCreated(config, message as RequestMessage));\n subscribeToChannel('undici:client:sendHeaders', message =>\n onRequestHeaders(config, message as RequestHeadersMessage),\n );\n subscribeToChannel('undici:request:headers', message => onResponseHeaders(config, message as ResponseHeadersMessage));\n subscribeToChannel('undici:request:trailers', message => onDone(message as RequestTrailersMessage));\n subscribeToChannel('undici:request:error', message => onError(message as RequestErrorMessage));\n}\n\n/** Replaces OTel's `safeExecuteInTheMiddle`: run `fn`, route any error to `onError`, and swallow it. */\nfunction safeExecute<T>(fn: () => T, onError: (error: unknown) => void): T | undefined {\n try {\n return fn();\n } catch (error) {\n onError(error);\n return undefined;\n }\n}\n\nfunction subscribeToChannel(\n diagnosticChannel: string,\n onMessage: (message: unknown, name: string | symbol) => void,\n): void {\n _channelSubs.push(diagch.subscribe?.(diagnosticChannel, onMessage));\n}\n\nfunction parseRequestHeaders(request: UndiciRequest): Map<string, string | string[]> {\n const result = new Map<string, string | string[]>();\n\n if (Array.isArray(request.headers)) {\n // headers are an array [k1, v2, k2, v2] (undici v6+)\n // values could be string or a string[] for multiple values\n for (let i = 0; i < request.headers.length; i += 2) {\n const key = request.headers[i];\n const value = request.headers[i + 1];\n\n // Key should always be a string, but the types don't know that, and let's be safe\n if (typeof key === 'string' && value !== undefined) {\n result.set(key.toLowerCase(), value);\n }\n }\n } else if (typeof request.headers === 'string') {\n // headers are a raw string (undici v5)\n // headers could be repeated in several lines for multiple values\n const headers = request.headers.split('\\r\\n');\n for (const line of headers) {\n if (!line) {\n continue;\n }\n const colonIndex = line.indexOf(':');\n if (colonIndex === -1) {\n // Invalid header? Probably this can't happen, but again let's be safe.\n continue;\n }\n const key = line.substring(0, colonIndex).toLowerCase();\n const value = line.substring(colonIndex + 1).trim();\n const allValues = result.get(key);\n\n if (allValues && Array.isArray(allValues)) {\n allValues.push(value);\n } else if (allValues) {\n result.set(key, [allValues, value]);\n } else {\n result.set(key, value);\n }\n }\n }\n return result;\n}\n\n// This is the 1st message we receive for each request (fired after request creation). Here we will\n// create the span and populate some atttributes, then link the span to the request for further\n// span processing\nfunction onRequestCreated(config: NodeFetchOptions, { request }: RequestMessage): void {\n const url = getAbsoluteUrl(request.origin, request.path);\n\n const ignoredByCallback = safeExecute(\n () => !!config.ignoreOutgoingRequests?.(url),\n e => e && DEBUG_BUILD && debug.error('caught ignoreOutgoingRequests error: ', e),\n );\n\n // Breadcrumbs & span-less trace propagation are additionally skipped when tracing is suppressed.\n // We store this here because the active context is no longer correct in later channel events.\n const ignoreForBreadcrumbs = isTracingSuppressed() || !!ignoredByCallback;\n ignoreRequestMap.set(request, ignoreForBreadcrumbs);\n\n // When spans are disabled we do not create a span, but we still inject trace propagation headers\n // directly (unless disabled via `tracePropagation`).\n if (!config.spans) {\n if (config.tracePropagation !== false && !ignoreForBreadcrumbs) {\n addTracePropagationHeadersToFetchRequest(request, propagationDecisionMap);\n }\n return;\n }\n\n // Ignore span creation if:\n // - the outgoing request is ignored via config\n // - method is 'CONNECT'\n if (request.method === 'CONNECT' || ignoredByCallback) {\n return;\n }\n\n let requestUrl;\n try {\n requestUrl = new URL(request.path, request.origin);\n } catch (err) {\n DEBUG_BUILD && debug.warn('could not determine url.full:', err);\n // Skip instrumenting this request.\n return;\n }\n\n const urlScheme = requestUrl.protocol.replace(':', '');\n const requestMethod = getRequestMethod(request.method);\n const attributes: SpanAttributes = {\n [SENTRY_KIND]: 'client',\n [SENTRY_OP]: HTTP_CLIENT,\n [HTTP_REQUEST_METHOD]: requestMethod,\n [ATTR_HTTP_REQUEST_METHOD_ORIGINAL]: request.method,\n [URL_FULL]: filterCollectedUrl(requestUrl.toString()),\n [URL_DOMAIN]: requestUrl.hostname || undefined,\n [URL_PATH]: requestUrl.pathname,\n [URL_QUERY]: filterCollectedUrlQuery(getUrlQuery(requestUrl.search)),\n [URL_FRAGMENT]: getUrlFragment(requestUrl.hash),\n [URL_SCHEME]: urlScheme,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.node_fetch',\n };\n\n // Sanitize data URLs to prevent long base64 strings in span attributes\n if (url.startsWith('data:')) {\n const sanitizedUrl = stripDataUrlContent(url);\n attributes[URL_FULL] = sanitizedUrl;\n attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME] = `${request.method || 'GET'} ${sanitizedUrl}`;\n }\n\n const schemePorts: Record<string, string> = { https: '443', http: '80' };\n const serverAddress = requestUrl.hostname;\n const serverPort = requestUrl.port || schemePorts[urlScheme];\n\n attributes[SERVER_ADDRESS] = serverAddress;\n if (serverPort && !isNaN(Number(serverPort))) {\n attributes[SERVER_PORT] = Number(serverPort);\n }\n\n // Get user agent from headers\n const headersMap = parseRequestHeaders(request);\n const userAgentValues = headersMap.get('user-agent');\n\n if (userAgentValues) {\n // NOTE: having multiple user agents is not expected so\n // we're going to take last one like `curl` does\n // ref: https://curl.se/docs/manpage.html#-A\n const userAgent = Array.isArray(userAgentValues) ? userAgentValues[userAgentValues.length - 1] : userAgentValues;\n attributes[USER_AGENT_ORIGINAL] = userAgent;\n }\n\n // Outside of span streaming, only record an `http.client` span when it has a parent. An orphan\n // one (no local parent) is left to the server for the downstream sampling decision: `onlyIfParent`\n // still creates a non-recording span so trace propagation headers are injected, but it isn't\n // emitted as a standalone transaction. This rule also lives in `SentrySampler`, but that only runs\n // when an OpenTelemetry SDK tracer provider is set up, so we enforce it here too, which covers\n // SDKs that don't use an OpenTelemetry tracer provider at all.\n const isDataUrl = url.startsWith('data:');\n const client = getClient();\n\n let spanName: string;\n if (requestMethod === '_OTHER') {\n spanName = HTTP_SPAN_NAME_FALLBACK;\n } else if (!!client && hasSpanStreamingEnabled(client)) {\n // With span streaming, span names have to be low cardinality, so the URL path is dropped and only\n // the domain is kept. Outgoing requests have no route to parameterize, and data URLs have no domain.\n spanName = requestUrl.hostname ? `${requestMethod} ${requestUrl.hostname}` : requestMethod;\n } else if (isDataUrl) {\n spanName = `${request.method || 'GET'} ${stripDataUrlContent(url)}`;\n } else {\n spanName = `${requestMethod} ${getSanitizedUrlString(parseUrl(requestUrl.toString()))}`;\n }\n\n const span = startInactiveSpan({\n name: spanName,\n attributes,\n onlyIfParent: !client || !hasSpanStreamingEnabled(client),\n });\n\n // Execute the request hook if defined\n safeExecute(\n () => config.requestHook?.(span, request),\n e => e && DEBUG_BUILD && debug.error('caught requestHook error: ', e),\n );\n\n // Context propagation goes last so no hook can tamper the propagation headers.\n // We propagate the trace data of the freshly created client span (not the active parent span)\n // so downstream services are parented to the http.client span, matching the upstream behavior.\n // This also de-duplicates against any trace headers the user set manually (e.g. via `getTraceData()`).\n addTracePropagationHeadersToFetchRequest(request, propagationDecisionMap, span);\n\n spanFromReq.set(request, span);\n}\n\n// This is the 2nd message we receive for each request. It is fired when connection with\n// the remote is established and about to send the first byte. Here we do have info about the\n// remote address and port so we can populate some `network.*` attributes into the span\nfunction onRequestHeaders(config: NodeFetchOptions, { request, socket }: RequestHeadersMessage): void {\n const span = spanFromReq.get(request);\n\n if (!span) {\n return;\n }\n\n const { remoteAddress, remotePort } = socket;\n const spanAttributes: SpanAttributes = {\n [NETWORK_PEER_ADDRESS]: remoteAddress,\n [NETWORK_PEER_PORT]: remotePort,\n };\n\n // After hooks have been processed (which may modify request headers)\n // we can collect the headers based on the configuration\n if (config.headersToSpanAttributes?.requestHeaders) {\n const headersToAttribs = new Set(config.headersToSpanAttributes.requestHeaders.map(n => n.toLowerCase()));\n const headersMap = parseRequestHeaders(request);\n\n for (const [name, value] of headersMap.entries()) {\n if (headersToAttribs.has(name)) {\n const attrValue = Array.isArray(value) ? value : [value];\n spanAttributes[`http.request.header.${name}`] = attrValue;\n }\n }\n }\n\n span.setAttributes(spanAttributes);\n}\n\n// This is the 3rd message we get for each request and it's fired when the server\n// headers are received, body may not be accessible yet.\n// From the response headers we can set the status and content length\nfunction onResponseHeaders(config: NodeFetchOptions, { request, response }: ResponseHeadersMessage): void {\n // Breadcrumbs are recorded independently of spans, so this runs even when span creation is disabled.\n const breadcrumbsEnabled = config.breadcrumbs !== false;\n if (breadcrumbsEnabled && !ignoreRequestMap.get(request)) {\n addFetchRequestBreadcrumb(request, response);\n }\n\n const span = spanFromReq.get(request);\n\n if (!span) {\n return;\n }\n\n const spanAttributes: SpanAttributes = {\n [HTTP_RESPONSE_STATUS_CODE]: response.statusCode,\n };\n\n // Execute the response hook if defined\n safeExecute(\n () => config.responseHook?.(span, { request, response }),\n e => e && DEBUG_BUILD && debug.error('caught responseHook error: ', e),\n );\n\n if (config.headersToSpanAttributes?.responseHeaders) {\n const headersToAttribs = new Set<string>();\n config.headersToSpanAttributes?.responseHeaders.forEach(name => headersToAttribs.add(name.toLowerCase()));\n\n for (let idx = 0; idx < response.headers.length; idx = idx + 2) {\n const nameBuf = response.headers[idx];\n const valueBuf = response.headers[idx + 1];\n if (nameBuf === undefined || valueBuf === undefined) {\n continue;\n }\n const name = nameBuf.toString().toLowerCase();\n const value = valueBuf;\n\n if (headersToAttribs.has(name)) {\n const attrName = `http.response.header.${name}`;\n if (!Object.prototype.hasOwnProperty.call(spanAttributes, attrName)) {\n spanAttributes[attrName] = [value.toString()];\n } else {\n (spanAttributes[attrName] as string[]).push(value.toString());\n }\n }\n }\n }\n\n span.setAttributes(spanAttributes);\n\n // Resolve the HTTP status code to a Sentry span status here (like the raw http client/server\n // instrumentation does) instead of setting a bare error and deferring to downstream inference.\n // The SentryTracerProvider's status finalization reads the already-stringified span status, which\n // can no longer be inferred back to `not_found` etc. the way the OpenTelemetry SDK exporter's\n // `mapStatus` does from the raw `{ code, message }`.\n if (response.statusCode >= 400) {\n span.setStatus(getSpanStatusFromHttpCode(response.statusCode));\n }\n}\n\n// This is the last event we receive if the request went without any errors\nfunction onDone({ request }: RequestTrailersMessage): void {\n const span = spanFromReq.get(request);\n\n if (!span) {\n return;\n }\n\n span.end();\n spanFromReq.delete(request);\n}\n\n// This is the event we get when something is wrong in the request like\n// - invalid options when calling `fetch` global API or any undici method for request\n// - connectivity errors such as unreachable host\n// - requests aborted through an `AbortController.signal`\n// NOTE: server errors are considered valid responses and it's the lib consumer\n// who should deal with that.\nfunction onError({ request, error }: RequestErrorMessage): void {\n const span = spanFromReq.get(request);\n\n if (!span) {\n return;\n }\n\n // NOTE: in `undici@6.3.0` when request aborted the error type changes from\n // a custom error (`RequestAbortedError`) to a built-in `DOMException` carrying\n // some differences:\n // - `code` is from DOMEXception (ABORT_ERR: 20)\n // - `message` changes\n // - stacktrace is smaller and contains node internal frames\n span.setStatus({\n code: SPAN_STATUS_ERROR,\n message: error.message,\n });\n span.end();\n spanFromReq.delete(request);\n}\n\nfunction getRequestMethod(original: string): string {\n const knownMethods = {\n CONNECT: true,\n OPTIONS: true,\n HEAD: true,\n GET: true,\n POST: true,\n PUT: true,\n PATCH: true,\n DELETE: true,\n TRACE: true,\n // QUERY from https://datatracker.ietf.org/doc/rfc10008/\n QUERY: true,\n };\n\n if (original.toUpperCase() in knownMethods) {\n return original.toUpperCase();\n }\n\n return '_OTHER';\n}\n\n// Matching the behavior of the base instrumentation\nfunction getAbsoluteUrl(origin: string, path: string = '/'): string {\n const url = `${origin}`;\n\n if (url.endsWith('/') && path.startsWith('/')) {\n return `${url}${path.slice(1)}`;\n }\n\n if (!url.endsWith('/') && !path.startsWith('/')) {\n return `${url}/${path}`;\n }\n\n return `${url}${path}`;\n}\n"],"names":["LRUMap","onError","url","DEBUG_BUILD","debug","isTracingSuppressed","addTracePropagationHeadersToFetchRequest","URL","attributes","SENTRY_KIND","SENTRY_OP","HTTP_CLIENT","HTTP_REQUEST_METHOD","URL_FULL","filterCollectedUrl","URL_DOMAIN","URL_PATH","URL_QUERY","filterCollectedUrlQuery","getUrlQuery","URL_FRAGMENT","getUrlFragment","URL_SCHEME","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","stripDataUrlContent","SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME","SERVER_ADDRESS","SERVER_PORT","USER_AGENT_ORIGINAL","getClient","HTTP_SPAN_NAME_FALLBACK","hasSpanStreamingEnabled","getSanitizedUrlString","parseUrl","startInactiveSpan","NETWORK_PEER_ADDRESS","NETWORK_PEER_PORT","addFetchRequestBreadcrumb","HTTP_RESPONSE_STATUS_CODE","getSpanStatusFromHttpCode","SPAN_STATUS_ERROR"],"mappings":";;;;;;;;;;AAyEA,MAAM,iCAAA,GAAoC,8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MAAM,CAAA,CAAA;AAErB,EAAA,IAAI,IAAI,QAAA,CAAS,GAAG,KAAK,IAAA,CAAK,UAAA,CAAW,GAAG,CAAA,EAAG;AAC7C,IAAA,OAAO,GAAG,GAAG,CAAA,EAAG,IAAA,CAAK,KAAA,CAAM,CAAC,CAAC,CAAA,CAAA;AAAA,EAC/B;AAEA,EAAA,IAAI,CAAC,IAAI,QAAA,CAAS,GAAG,KAAK,CAAC,IAAA,CAAK,UAAA,CAAW,GAAG,CAAA,EAAG;AAC/C,IAAA,OAAO,CAAA,EAAG,GAAG,CAAA,CAAA,EAAI,IAAI,CAAA,CAAA;AAAA,EACvB;AAEA,EAAA,OAAO,CAAA,EAAG,GAAG,CAAA,EAAG,IAAI,CAAA,CAAA;AACtB;;;;"}
|
|
@@ -2,6 +2,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
2
2
|
|
|
3
3
|
const perf_hooks = require('perf_hooks');
|
|
4
4
|
const core = require('@sentry/core');
|
|
5
|
+
const server = require('@sentry/core/server');
|
|
5
6
|
|
|
6
7
|
const INTEGRATION_NAME = "NodeRuntimeMetrics";
|
|
7
8
|
const DEFAULT_INTERVAL_MS = 3e4;
|
|
@@ -171,7 +172,7 @@ const nodeRuntimeMetricsIntegration = core.defineIntegration((options = {}) => {
|
|
|
171
172
|
if (intervalId) {
|
|
172
173
|
clearInterval(intervalId);
|
|
173
174
|
}
|
|
174
|
-
intervalId =
|
|
175
|
+
intervalId = server._INTERNAL_safeUnref(setInterval(collectMetrics, collectionIntervalMs));
|
|
175
176
|
}
|
|
176
177
|
};
|
|
177
178
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nodeRuntimeMetrics.js","sources":["../../../src/integrations/nodeRuntimeMetrics.ts"],"sourcesContent":["import { monitorEventLoopDelay, performance } from 'perf_hooks';\nimport { _INTERNAL_safeDateNow, _INTERNAL_safeUnref, defineIntegration, metrics } from '@sentry/core';\n\nconst INTEGRATION_NAME = 'NodeRuntimeMetrics' as const;\nconst DEFAULT_INTERVAL_MS = 30_000;\nconst MIN_COLLECTION_INTERVAL_MS = 1_000;\nconst EVENT_LOOP_DELAY_RESOLUTION_MS = 10;\n\n/**\n * Normalizes a `collectionIntervalMs` value, enforcing a minimum of 1000ms.\n * - Non-finite values (NaN, Infinity): warns and falls back to `defaultInterval`.\n * - Values below the minimum: warns and clamps to 1000ms.\n * @internal\n */\nexport function _INTERNAL_normalizeCollectionInterval(\n rawInterval: number,\n integrationName: string,\n defaultInterval: number,\n): number {\n if (!Number.isFinite(rawInterval)) {\n // eslint-disable-next-line no-console\n console.warn(\n `[Sentry] ${integrationName}: collectionIntervalMs (${rawInterval}) is invalid. Using default of ${defaultInterval}ms.`,\n );\n return defaultInterval;\n }\n if (rawInterval < MIN_COLLECTION_INTERVAL_MS) {\n // eslint-disable-next-line no-console\n console.warn(\n `[Sentry] ${integrationName}: collectionIntervalMs (${rawInterval}) is below the minimum of ${MIN_COLLECTION_INTERVAL_MS}ms. Using minimum of ${MIN_COLLECTION_INTERVAL_MS}ms.`,\n );\n return MIN_COLLECTION_INTERVAL_MS;\n }\n return rawInterval;\n}\n\nexport interface NodeRuntimeMetricsOptions {\n /**\n * Which metrics to collect.\n *\n * Default on (8 metrics):\n * - `cpuUtilization` — CPU utilization ratio\n * - `memRss` — Resident Set Size (actual memory footprint)\n * - `memHeapUsed` — V8 heap currently in use\n * - `memHeapTotal` — total V8 heap allocated (headroom paired with `memHeapUsed`)\n * - `eventLoopDelayP50` — median event loop delay (baseline latency)\n * - `eventLoopDelayP99` — 99th percentile event loop delay (tail latency / spikes)\n * - `eventLoopUtilization` — fraction of time the event loop was active\n * - `uptime` — process uptime (detect restarts/crashes)\n *\n * Default off (opt-in):\n * - `cpuTime` — raw user/system CPU time in seconds\n * - `memExternal` — external/ArrayBuffer memory (relevant for native addons)\n * - `eventLoopDelayMin` / `eventLoopDelayMax` / `eventLoopDelayMean` / `eventLoopDelayP90`\n */\n collect?: {\n // Default on\n cpuUtilization?: boolean;\n memHeapUsed?: boolean;\n memRss?: boolean;\n eventLoopDelayP99?: boolean;\n eventLoopUtilization?: boolean;\n uptime?: boolean;\n // Default off\n cpuTime?: boolean;\n memHeapTotal?: boolean;\n memExternal?: boolean;\n eventLoopDelayMin?: boolean;\n eventLoopDelayMax?: boolean;\n eventLoopDelayMean?: boolean;\n eventLoopDelayP50?: boolean;\n eventLoopDelayP90?: boolean;\n };\n /**\n * How often to collect metrics, in milliseconds.\n * Minimum allowed value is 1000ms.\n * @default 30000\n * @minimum 1000\n */\n collectionIntervalMs?: number;\n}\n\n/**\n * Automatically collects Node.js runtime metrics and emits them to Sentry.\n *\n * @example\n * ```ts\n * Sentry.init({\n * integrations: [\n * Sentry.nodeRuntimeMetricsIntegration(),\n * ],\n * });\n * ```\n */\nexport const nodeRuntimeMetricsIntegration = defineIntegration((options: NodeRuntimeMetricsOptions = {}) => {\n const collectionIntervalMs = _INTERNAL_normalizeCollectionInterval(\n options.collectionIntervalMs ?? DEFAULT_INTERVAL_MS,\n INTEGRATION_NAME,\n DEFAULT_INTERVAL_MS,\n );\n const collect = {\n // Default on\n cpuUtilization: true,\n memHeapUsed: true,\n memHeapTotal: true,\n memRss: true,\n eventLoopDelayP50: true,\n eventLoopDelayP99: true,\n eventLoopUtilization: true,\n uptime: true,\n // Default off\n cpuTime: false,\n memExternal: false,\n eventLoopDelayMin: false,\n eventLoopDelayMax: false,\n eventLoopDelayMean: false,\n eventLoopDelayP90: false,\n ...options.collect,\n };\n\n const needsEventLoopDelay =\n collect.eventLoopDelayP99 ||\n collect.eventLoopDelayMin ||\n collect.eventLoopDelayMax ||\n collect.eventLoopDelayMean ||\n collect.eventLoopDelayP50 ||\n collect.eventLoopDelayP90;\n\n const needsCpu = collect.cpuUtilization || collect.cpuTime;\n\n let intervalId: ReturnType<typeof setInterval> | undefined;\n let prevCpuUsage: NodeJS.CpuUsage | undefined;\n let prevElu: ReturnType<typeof performance.eventLoopUtilization> | undefined;\n let prevFlushTime: number = 0;\n let eventLoopDelayHistogram: ReturnType<typeof monitorEventLoopDelay> | undefined;\n\n const resolutionNs = EVENT_LOOP_DELAY_RESOLUTION_MS * 1e6;\n const nsToS = (ns: number): number => Math.max(0, (ns - resolutionNs) / 1e9);\n\n const METRIC_ATTRIBUTES = { attributes: { 'sentry.origin': 'auto.node.runtime_metrics' } };\n const METRIC_ATTRIBUTES_BYTE = { unit: 'byte', attributes: { 'sentry.origin': 'auto.node.runtime_metrics' } };\n const METRIC_ATTRIBUTES_SECOND = { unit: 'second', attributes: { 'sentry.origin': 'auto.node.runtime_metrics' } };\n\n function collectMetrics(): void {\n const now = _INTERNAL_safeDateNow();\n const elapsed = now - prevFlushTime;\n\n if (needsCpu && prevCpuUsage !== undefined) {\n const delta = process.cpuUsage(prevCpuUsage);\n\n if (collect.cpuTime) {\n metrics.gauge('node.runtime.cpu.user', delta.user / 1e6, METRIC_ATTRIBUTES_SECOND);\n metrics.gauge('node.runtime.cpu.system', delta.system / 1e6, METRIC_ATTRIBUTES_SECOND);\n }\n if (collect.cpuUtilization && elapsed > 0) {\n // Ratio of CPU time to wall-clock time. Can exceed 1.0 on multi-core systems.\n // TODO: In cluster mode, add a runtime_id/process_id attribute to disambiguate per-worker metrics.\n metrics.gauge(\n 'node.runtime.cpu.utilization',\n (delta.user + delta.system) / (elapsed * 1000),\n METRIC_ATTRIBUTES,\n );\n }\n\n prevCpuUsage = process.cpuUsage();\n }\n\n if (collect.memRss || collect.memHeapUsed || collect.memHeapTotal || collect.memExternal) {\n const mem = process.memoryUsage();\n if (collect.memRss) {\n metrics.gauge('node.runtime.mem.rss', mem.rss, METRIC_ATTRIBUTES_BYTE);\n }\n if (collect.memHeapUsed) {\n metrics.gauge('node.runtime.mem.heap_used', mem.heapUsed, METRIC_ATTRIBUTES_BYTE);\n }\n if (collect.memHeapTotal) {\n metrics.gauge('node.runtime.mem.heap_total', mem.heapTotal, METRIC_ATTRIBUTES_BYTE);\n }\n if (collect.memExternal) {\n metrics.gauge('node.runtime.mem.external', mem.external, METRIC_ATTRIBUTES_BYTE);\n metrics.gauge('node.runtime.mem.array_buffers', mem.arrayBuffers, METRIC_ATTRIBUTES_BYTE);\n }\n }\n\n if (needsEventLoopDelay && eventLoopDelayHistogram) {\n if (collect.eventLoopDelayMin) {\n metrics.gauge(\n 'node.runtime.event_loop.delay.min',\n nsToS(eventLoopDelayHistogram.min),\n METRIC_ATTRIBUTES_SECOND,\n );\n }\n if (collect.eventLoopDelayMax) {\n metrics.gauge(\n 'node.runtime.event_loop.delay.max',\n nsToS(eventLoopDelayHistogram.max),\n METRIC_ATTRIBUTES_SECOND,\n );\n }\n if (collect.eventLoopDelayMean) {\n metrics.gauge(\n 'node.runtime.event_loop.delay.mean',\n nsToS(eventLoopDelayHistogram.mean),\n METRIC_ATTRIBUTES_SECOND,\n );\n }\n if (collect.eventLoopDelayP50) {\n metrics.gauge(\n 'node.runtime.event_loop.delay.p50',\n nsToS(eventLoopDelayHistogram.percentile(50)),\n METRIC_ATTRIBUTES_SECOND,\n );\n }\n if (collect.eventLoopDelayP90) {\n metrics.gauge(\n 'node.runtime.event_loop.delay.p90',\n nsToS(eventLoopDelayHistogram.percentile(90)),\n METRIC_ATTRIBUTES_SECOND,\n );\n }\n if (collect.eventLoopDelayP99) {\n metrics.gauge(\n 'node.runtime.event_loop.delay.p99',\n nsToS(eventLoopDelayHistogram.percentile(99)),\n METRIC_ATTRIBUTES_SECOND,\n );\n }\n\n eventLoopDelayHistogram.reset();\n }\n\n if (collect.eventLoopUtilization && prevElu !== undefined) {\n const currentElu = performance.eventLoopUtilization();\n const delta = performance.eventLoopUtilization(currentElu, prevElu);\n metrics.gauge('node.runtime.event_loop.utilization', delta.utilization, METRIC_ATTRIBUTES);\n prevElu = currentElu;\n }\n\n if (collect.uptime && elapsed > 0) {\n metrics.count('node.runtime.process.uptime', elapsed / 1000, METRIC_ATTRIBUTES_SECOND);\n }\n\n prevFlushTime = now;\n }\n\n return {\n name: INTEGRATION_NAME,\n\n setup(): void {\n if (needsEventLoopDelay) {\n // Disable any previous histogram before overwriting (prevents native resource leak on re-init).\n eventLoopDelayHistogram?.disable();\n try {\n eventLoopDelayHistogram = monitorEventLoopDelay({ resolution: EVENT_LOOP_DELAY_RESOLUTION_MS });\n eventLoopDelayHistogram.enable();\n } catch {\n // Not available in all runtimes (e.g. Bun throws NotImplementedError).\n eventLoopDelayHistogram = undefined;\n }\n }\n\n // Prime baselines before the first collection interval.\n if (needsCpu) {\n prevCpuUsage = process.cpuUsage();\n }\n if (collect.eventLoopUtilization) {\n prevElu = performance.eventLoopUtilization();\n }\n prevFlushTime = _INTERNAL_safeDateNow();\n\n // Guard against double setup (e.g. re-init).\n if (intervalId) {\n clearInterval(intervalId);\n }\n intervalId = _INTERNAL_safeUnref(setInterval(collectMetrics, collectionIntervalMs));\n },\n };\n});\n"],"names":["defineIntegration","_INTERNAL_safeDateNow","metrics","performance","monitorEventLoopDelay","_INTERNAL_safeUnref"],"mappings":";;;;;AAGA,MAAM,gBAAA,GAAmB,oBAAA;AACzB,MAAM,mBAAA,GAAsB,GAAA;AAC5B,MAAM,0BAAA,GAA6B,GAAA;AACnC,MAAM,8BAAA,GAAiC,EAAA;AAQhC,SAAS,qCAAA,CACd,WAAA,EACA,eAAA,EACA,eAAA,EACQ;AACR,EAAA,IAAI,CAAC,MAAA,CAAO,QAAA,CAAS,WAAW,CAAA,EAAG;AAEjC,IAAA,OAAA,CAAQ,IAAA;AAAA,MACN,CAAA,SAAA,EAAY,eAAe,CAAA,wBAAA,EAA2B,WAAW,kCAAkC,eAAe,CAAA,GAAA;AAAA,KACpH;AACA,IAAA,OAAO,eAAA;AAAA,EACT;AACA,EAAA,IAAI,cAAc,0BAAA,EAA4B;AAE5C,IAAA,OAAA,CAAQ,IAAA;AAAA,MACN,YAAY,eAAe,CAAA,wBAAA,EAA2B,WAAW,CAAA,0BAAA,EAA6B,0BAA0B,wBAAwB,0BAA0B,CAAA,GAAA;AA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GAAgB,GAAA;AAAA,EAClB;AAEA,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IAEN,KAAA,GAAc;AACZ,MAAA,IAAI,mBAAA,EAAqB;AAEvB,QAAA,uBAAA,EAAyB,OAAA,EAAQ;AACjC,QAAA,IAAI;AACF,UAAA,uBAAA,GAA0BE,gCAAA,CAAsB,EAAE,UAAA,EAAY,8BAAA,EAAgC,CAAA;AAC9F,UAAA,uBAAA,CAAwB,MAAA,EAAO;AAAA,QACjC,CAAA,CAAA,MAAQ;AAEN,UAAA,uBAAA,GAA0B,MAAA;AAAA,QAC5B;AAAA,MACF;AAGA,MAAA,IAAI,QAAA,EAAU;AACZ,QAAA,YAAA,GAAe,QAAQ,QAAA,EAAS;AAAA,MAClC;AACA,MAAA,IAAI,QAAQ,oBAAA,EAAsB;AAChC,QAAA,OAAA,GAAUD,uBAAY,oBAAA,EAAqB;AAAA,MAC7C;AACA,MAAA,aAAA,GAAgBF,0BAAA,EAAsB;AAGtC,MAAA,IAAI,UAAA,EAAY;AACd,QAAA,aAAA,CAAc,UAAU,CAAA;AAAA,MAC1B;AACA,MAAA,UAAA,GAAaI,wBAAA,CAAoB,WAAA,CAAY,cAAA,EAAgB,oBAAoB,CAAC,CAAA;AAAA,IACpF;AAAA,GACF;AACF,CAAC;;;;;"}
|
|
1
|
+
{"version":3,"file":"nodeRuntimeMetrics.js","sources":["../../../src/integrations/nodeRuntimeMetrics.ts"],"sourcesContent":["import { monitorEventLoopDelay, performance } from 'perf_hooks';\nimport { _INTERNAL_safeDateNow, defineIntegration, metrics } from '@sentry/core';\nimport { _INTERNAL_safeUnref } from '@sentry/core/server';\n\nconst INTEGRATION_NAME = 'NodeRuntimeMetrics' as const;\nconst DEFAULT_INTERVAL_MS = 30_000;\nconst MIN_COLLECTION_INTERVAL_MS = 1_000;\nconst EVENT_LOOP_DELAY_RESOLUTION_MS = 10;\n\n/**\n * Normalizes a `collectionIntervalMs` value, enforcing a minimum of 1000ms.\n * - Non-finite values (NaN, Infinity): warns and falls back to `defaultInterval`.\n * - Values below the minimum: warns and clamps to 1000ms.\n * @internal\n */\nexport function _INTERNAL_normalizeCollectionInterval(\n rawInterval: number,\n integrationName: string,\n defaultInterval: number,\n): number {\n if (!Number.isFinite(rawInterval)) {\n // eslint-disable-next-line no-console\n console.warn(\n `[Sentry] ${integrationName}: collectionIntervalMs (${rawInterval}) is invalid. Using default of ${defaultInterval}ms.`,\n );\n return defaultInterval;\n }\n if (rawInterval < MIN_COLLECTION_INTERVAL_MS) {\n // eslint-disable-next-line no-console\n console.warn(\n `[Sentry] ${integrationName}: collectionIntervalMs (${rawInterval}) is below the minimum of ${MIN_COLLECTION_INTERVAL_MS}ms. Using minimum of ${MIN_COLLECTION_INTERVAL_MS}ms.`,\n );\n return MIN_COLLECTION_INTERVAL_MS;\n }\n return rawInterval;\n}\n\nexport interface NodeRuntimeMetricsOptions {\n /**\n * Which metrics to collect.\n *\n * Default on (8 metrics):\n * - `cpuUtilization` — CPU utilization ratio\n * - `memRss` — Resident Set Size (actual memory footprint)\n * - `memHeapUsed` — V8 heap currently in use\n * - `memHeapTotal` — total V8 heap allocated (headroom paired with `memHeapUsed`)\n * - `eventLoopDelayP50` — median event loop delay (baseline latency)\n * - `eventLoopDelayP99` — 99th percentile event loop delay (tail latency / spikes)\n * - `eventLoopUtilization` — fraction of time the event loop was active\n * - `uptime` — process uptime (detect restarts/crashes)\n *\n * Default off (opt-in):\n * - `cpuTime` — raw user/system CPU time in seconds\n * - `memExternal` — external/ArrayBuffer memory (relevant for native addons)\n * - `eventLoopDelayMin` / `eventLoopDelayMax` / `eventLoopDelayMean` / `eventLoopDelayP90`\n */\n collect?: {\n // Default on\n cpuUtilization?: boolean;\n memHeapUsed?: boolean;\n memRss?: boolean;\n eventLoopDelayP99?: boolean;\n eventLoopUtilization?: boolean;\n uptime?: boolean;\n // Default off\n cpuTime?: boolean;\n memHeapTotal?: boolean;\n memExternal?: boolean;\n eventLoopDelayMin?: boolean;\n eventLoopDelayMax?: boolean;\n eventLoopDelayMean?: boolean;\n eventLoopDelayP50?: boolean;\n eventLoopDelayP90?: boolean;\n };\n /**\n * How often to collect metrics, in milliseconds.\n * Minimum allowed value is 1000ms.\n * @default 30000\n * @minimum 1000\n */\n collectionIntervalMs?: number;\n}\n\n/**\n * Automatically collects Node.js runtime metrics and emits them to Sentry.\n *\n * @example\n * ```ts\n * Sentry.init({\n * integrations: [\n * Sentry.nodeRuntimeMetricsIntegration(),\n * ],\n * });\n * ```\n */\nexport const nodeRuntimeMetricsIntegration = defineIntegration((options: NodeRuntimeMetricsOptions = {}) => {\n const collectionIntervalMs = _INTERNAL_normalizeCollectionInterval(\n options.collectionIntervalMs ?? DEFAULT_INTERVAL_MS,\n INTEGRATION_NAME,\n DEFAULT_INTERVAL_MS,\n );\n const collect = {\n // Default on\n cpuUtilization: true,\n memHeapUsed: true,\n memHeapTotal: true,\n memRss: true,\n eventLoopDelayP50: true,\n eventLoopDelayP99: true,\n eventLoopUtilization: true,\n uptime: true,\n // Default off\n cpuTime: false,\n memExternal: false,\n eventLoopDelayMin: false,\n eventLoopDelayMax: false,\n eventLoopDelayMean: false,\n eventLoopDelayP90: false,\n ...options.collect,\n };\n\n const needsEventLoopDelay =\n collect.eventLoopDelayP99 ||\n collect.eventLoopDelayMin ||\n collect.eventLoopDelayMax ||\n collect.eventLoopDelayMean ||\n collect.eventLoopDelayP50 ||\n collect.eventLoopDelayP90;\n\n const needsCpu = collect.cpuUtilization || collect.cpuTime;\n\n let intervalId: ReturnType<typeof setInterval> | undefined;\n let prevCpuUsage: NodeJS.CpuUsage | undefined;\n let prevElu: ReturnType<typeof performance.eventLoopUtilization> | undefined;\n let prevFlushTime: number = 0;\n let eventLoopDelayHistogram: ReturnType<typeof monitorEventLoopDelay> | undefined;\n\n const resolutionNs = EVENT_LOOP_DELAY_RESOLUTION_MS * 1e6;\n const nsToS = (ns: number): number => Math.max(0, (ns - resolutionNs) / 1e9);\n\n const METRIC_ATTRIBUTES = { attributes: { 'sentry.origin': 'auto.node.runtime_metrics' } };\n const METRIC_ATTRIBUTES_BYTE = { unit: 'byte', attributes: { 'sentry.origin': 'auto.node.runtime_metrics' } };\n const METRIC_ATTRIBUTES_SECOND = { unit: 'second', attributes: { 'sentry.origin': 'auto.node.runtime_metrics' } };\n\n function collectMetrics(): void {\n const now = _INTERNAL_safeDateNow();\n const elapsed = now - prevFlushTime;\n\n if (needsCpu && prevCpuUsage !== undefined) {\n const delta = process.cpuUsage(prevCpuUsage);\n\n if (collect.cpuTime) {\n metrics.gauge('node.runtime.cpu.user', delta.user / 1e6, METRIC_ATTRIBUTES_SECOND);\n metrics.gauge('node.runtime.cpu.system', delta.system / 1e6, METRIC_ATTRIBUTES_SECOND);\n }\n if (collect.cpuUtilization && elapsed > 0) {\n // Ratio of CPU time to wall-clock time. Can exceed 1.0 on multi-core systems.\n // TODO: In cluster mode, add a runtime_id/process_id attribute to disambiguate per-worker metrics.\n metrics.gauge(\n 'node.runtime.cpu.utilization',\n (delta.user + delta.system) / (elapsed * 1000),\n METRIC_ATTRIBUTES,\n );\n }\n\n prevCpuUsage = process.cpuUsage();\n }\n\n if (collect.memRss || collect.memHeapUsed || collect.memHeapTotal || collect.memExternal) {\n const mem = process.memoryUsage();\n if (collect.memRss) {\n metrics.gauge('node.runtime.mem.rss', mem.rss, METRIC_ATTRIBUTES_BYTE);\n }\n if (collect.memHeapUsed) {\n metrics.gauge('node.runtime.mem.heap_used', mem.heapUsed, METRIC_ATTRIBUTES_BYTE);\n }\n if (collect.memHeapTotal) {\n metrics.gauge('node.runtime.mem.heap_total', mem.heapTotal, METRIC_ATTRIBUTES_BYTE);\n }\n if (collect.memExternal) {\n metrics.gauge('node.runtime.mem.external', mem.external, METRIC_ATTRIBUTES_BYTE);\n metrics.gauge('node.runtime.mem.array_buffers', mem.arrayBuffers, METRIC_ATTRIBUTES_BYTE);\n }\n }\n\n if (needsEventLoopDelay && eventLoopDelayHistogram) {\n if (collect.eventLoopDelayMin) {\n metrics.gauge(\n 'node.runtime.event_loop.delay.min',\n nsToS(eventLoopDelayHistogram.min),\n METRIC_ATTRIBUTES_SECOND,\n );\n }\n if (collect.eventLoopDelayMax) {\n metrics.gauge(\n 'node.runtime.event_loop.delay.max',\n nsToS(eventLoopDelayHistogram.max),\n METRIC_ATTRIBUTES_SECOND,\n );\n }\n if (collect.eventLoopDelayMean) {\n metrics.gauge(\n 'node.runtime.event_loop.delay.mean',\n nsToS(eventLoopDelayHistogram.mean),\n METRIC_ATTRIBUTES_SECOND,\n );\n }\n if (collect.eventLoopDelayP50) {\n metrics.gauge(\n 'node.runtime.event_loop.delay.p50',\n nsToS(eventLoopDelayHistogram.percentile(50)),\n METRIC_ATTRIBUTES_SECOND,\n );\n }\n if (collect.eventLoopDelayP90) {\n metrics.gauge(\n 'node.runtime.event_loop.delay.p90',\n nsToS(eventLoopDelayHistogram.percentile(90)),\n METRIC_ATTRIBUTES_SECOND,\n );\n }\n if (collect.eventLoopDelayP99) {\n metrics.gauge(\n 'node.runtime.event_loop.delay.p99',\n nsToS(eventLoopDelayHistogram.percentile(99)),\n METRIC_ATTRIBUTES_SECOND,\n );\n }\n\n eventLoopDelayHistogram.reset();\n }\n\n if (collect.eventLoopUtilization && prevElu !== undefined) {\n const currentElu = performance.eventLoopUtilization();\n const delta = performance.eventLoopUtilization(currentElu, prevElu);\n metrics.gauge('node.runtime.event_loop.utilization', delta.utilization, METRIC_ATTRIBUTES);\n prevElu = currentElu;\n }\n\n if (collect.uptime && elapsed > 0) {\n metrics.count('node.runtime.process.uptime', elapsed / 1000, METRIC_ATTRIBUTES_SECOND);\n }\n\n prevFlushTime = now;\n }\n\n return {\n name: INTEGRATION_NAME,\n\n setup(): void {\n if (needsEventLoopDelay) {\n // Disable any previous histogram before overwriting (prevents native resource leak on re-init).\n eventLoopDelayHistogram?.disable();\n try {\n eventLoopDelayHistogram = monitorEventLoopDelay({ resolution: EVENT_LOOP_DELAY_RESOLUTION_MS });\n eventLoopDelayHistogram.enable();\n } catch {\n // Not available in all runtimes (e.g. Bun throws NotImplementedError).\n eventLoopDelayHistogram = undefined;\n }\n }\n\n // Prime baselines before the first collection interval.\n if (needsCpu) {\n prevCpuUsage = process.cpuUsage();\n }\n if (collect.eventLoopUtilization) {\n prevElu = performance.eventLoopUtilization();\n }\n prevFlushTime = _INTERNAL_safeDateNow();\n\n // Guard against double setup (e.g. re-init).\n if (intervalId) {\n clearInterval(intervalId);\n }\n intervalId = _INTERNAL_safeUnref(setInterval(collectMetrics, collectionIntervalMs));\n },\n };\n});\n"],"names":["defineIntegration","_INTERNAL_safeDateNow","metrics","performance","monitorEventLoopDelay","_INTERNAL_safeUnref"],"mappings":";;;;;;AAIA,MAAM,gBAAA,GAAmB,oBAAA;AACzB,MAAM,mBAAA,GAAsB,GAAA;AAC5B,MAAM,0BAAA,GAA6B,GAAA;AACnC,MAAM,8BAAA,GAAiC,EAAA;AAQhC,SAAS,qCAAA,CACd,WAAA,EACA,eAAA,EACA,eAAA,EACQ;AACR,EAAA,IAAI,CAAC,MAAA,CAAO,QAAA,CAAS,WAAW,CAAA,EAAG;AAEjC,IAAA,OAAA,CAAQ,IAAA;AAAA,MACN,CAAA,SAAA,EAAY,eAAe,CAAA,wBAAA,EAA2B,WAAW,kCAAkC,eAAe,CAAA,GAAA;AAAA,KACpH;AACA,IAAA,OAAO,eAAA;AAAA,EACT;AACA,EAAA,IAAI,cAAc,0BAAA,EAA4B;AAE5C,IAAA,OAAA,CAAQ,IAAA;AAAA,MACN,YAAY,eAAe,CAAA,wBAAA,EAA2B,WAAW,CAAA,0BAAA,EAA6B,0BAA0B,wBAAwB,0BAA0B,CAAA,GAAA;AAAA,KAC5K;AACA,IAAA,OAAO,0BAAA;AAAA,EACT;AACA,EAAA,OAAO,WAAA;AACT;AA4DO,MAAM,6BAAA,GAAgCA,sBAAA,CAAkB,CAAC,OAAA,GAAqC,EAAC,KAAM;AAC1G,EAAA,MAAM,oBAAA,GAAuB,q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IAAI;AACF,UAAA,uBAAA,GAA0BE,gCAAA,CAAsB,EAAE,UAAA,EAAY,8BAAA,EAAgC,CAAA;AAC9F,UAAA,uBAAA,CAAwB,MAAA,EAAO;AAAA,QACjC,CAAA,CAAA,MAAQ;AAEN,UAAA,uBAAA,GAA0B,MAAA;AAAA,QAC5B;AAAA,MACF;AAGA,MAAA,IAAI,QAAA,EAAU;AACZ,QAAA,YAAA,GAAe,QAAQ,QAAA,EAAS;AAAA,MAClC;AACA,MAAA,IAAI,QAAQ,oBAAA,EAAsB;AAChC,QAAA,OAAA,GAAUD,uBAAY,oBAAA,EAAqB;AAAA,MAC7C;AACA,MAAA,aAAA,GAAgBF,0BAAA,EAAsB;AAGtC,MAAA,IAAI,UAAA,EAAY;AACd,QAAA,aAAA,CAAc,UAAU,CAAA;AAAA,MAC1B;AACA,MAAA,UAAA,GAAaI,0BAAA,CAAoB,WAAA,CAAY,cAAA,EAAgB,oBAAoB,CAAC,CAAA;AAAA,IACpF;AAAA,GACF;AACF,CAAC;;;;;"}
|
|
@@ -80,9 +80,11 @@ function handleRejection(reason, mode) {
|
|
|
80
80
|
console.error(core.isObjectLike(reason) && "stack" in reason ? reason.stack : reason);
|
|
81
81
|
});
|
|
82
82
|
} else if (mode === "strict") {
|
|
83
|
-
core.
|
|
84
|
-
|
|
85
|
-
|
|
83
|
+
if (!(core.isObjectLike(reason) && "stack" in reason)) {
|
|
84
|
+
core.consoleSandbox(() => {
|
|
85
|
+
console.warn(rejectionWarning);
|
|
86
|
+
});
|
|
87
|
+
}
|
|
86
88
|
errorhandling.logAndExitProcess(reason);
|
|
87
89
|
}
|
|
88
90
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"onunhandledrejection.js","sources":["../../../src/integrations/onunhandledrejection.ts"],"sourcesContent":["import type { Client, IntegrationFn, SeverityLevel, Span } from '@sentry/core';\nimport {\n captureException,\n consoleSandbox,\n defineIntegration,\n getClient,\n isMatchingPattern,\n isObjectLike,\n withActiveSpan,\n} from '@sentry/core';\nimport { logAndExitProcess } from '../utils/errorhandling';\n\ntype UnhandledRejectionMode = 'none' | 'warn' | 'strict';\n\ntype IgnoreMatcher = { name?: string | RegExp; message?: string | RegExp };\n\ninterface OnUnhandledRejectionOptions {\n /**\n * Option deciding what to do after capturing unhandledRejection,\n * that mimicks behavior of node's --unhandled-rejection flag.\n */\n mode: UnhandledRejectionMode;\n /** Rejection Errors to ignore (don't capture or warn). */\n ignore?: IgnoreMatcher[];\n}\n\nconst INTEGRATION_NAME = 'OnUnhandledRejection';\n\nconst DEFAULT_IGNORES: IgnoreMatcher[] = [\n {\n name: 'AI_NoOutputGeneratedError', // When stream aborts in Vercel AI SDK V5, Vercel flush() fails with an error\n },\n {\n name: 'AbortError', // When stream aborts in Vercel AI SDK V6\n },\n];\n\nconst _onUnhandledRejectionIntegration = ((options: Partial<OnUnhandledRejectionOptions> = {}) => {\n const opts: OnUnhandledRejectionOptions = {\n mode: options.mode ?? 'warn',\n ignore: [...DEFAULT_IGNORES, ...(options.ignore ?? [])],\n };\n\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n global.process.on('unhandledRejection', makeUnhandledPromiseHandler(client, opts));\n },\n };\n}) satisfies IntegrationFn;\n\nexport const onUnhandledRejectionIntegration = defineIntegration(_onUnhandledRejectionIntegration);\n\n/** Extract error info safely */\nfunction extractErrorInfo(reason: unknown): { name: string; message: string } {\n // Check if reason is an object (including Error instances, not just plain objects)\n if (!isObjectLike(reason)) {\n return { name: '', message: String(reason ?? '') };\n }\n\n const errorLike = reason as Record<string, unknown>;\n const name = typeof errorLike.name === 'string' ? errorLike.name : '';\n const message = typeof errorLike.message === 'string' ? errorLike.message : String(reason);\n\n return { name, message };\n}\n\n/** Check if a matcher matches the reason */\nfunction isMatchingReason(matcher: IgnoreMatcher, errorInfo: ReturnType<typeof extractErrorInfo>): boolean {\n // name/message matcher\n const nameMatches = matcher.name === undefined || isMatchingPattern(errorInfo.name, matcher.name, true);\n\n const messageMatches = matcher.message === undefined || isMatchingPattern(errorInfo.message, matcher.message);\n\n return nameMatches && messageMatches;\n}\n\n/** Match helper */\nfunction matchesIgnore(list: IgnoreMatcher[], reason: unknown): boolean {\n const errorInfo = extractErrorInfo(reason);\n return list.some(matcher => isMatchingReason(matcher, errorInfo));\n}\n\n/** Core handler */\nexport function makeUnhandledPromiseHandler(\n client: Client,\n options: OnUnhandledRejectionOptions,\n): (reason: unknown, promise: unknown) => void {\n return function sendUnhandledPromise(reason: unknown, _promise: unknown): void {\n // Only handle for the active client\n if (getClient() !== client) {\n return;\n }\n\n // Skip if configured to ignore\n if (matchesIgnore(options.ignore ?? [], reason)) {\n return;\n }\n\n const level: SeverityLevel = options.mode === 'strict' ? 'fatal' : 'error';\n\n // this can be set in places where we cannot reliably get access to the active span/error\n // when the error bubbles up to this handler, we can use this to set the active span\n const activeSpanForError = isObjectLike(reason)\n ? (reason as { _sentry_active_span?: Span })._sentry_active_span\n : undefined;\n\n const activeSpanWrapper = activeSpanForError\n ? (fn: () => void) => withActiveSpan(activeSpanForError, fn)\n : (fn: () => void) => fn();\n\n activeSpanWrapper(() => {\n captureException(reason, {\n originalException: reason,\n captureContext: {\n extra: { unhandledPromiseRejection: true },\n level,\n },\n mechanism: {\n handled: false,\n type: 'auto.node.onunhandledrejection',\n },\n });\n });\n\n handleRejection(reason, options.mode);\n };\n}\n\n/**\n * Handler for `mode` option\n */\nfunction handleRejection(reason: unknown, mode: UnhandledRejectionMode): void {\n // https://github.com/nodejs/node/blob/7cf6f9e964aa00772965391c23acda6d71972a9a/lib/internal/process/promises.js#L234-L240\n const rejectionWarning =\n 'This error originated either by ' +\n 'throwing inside of an async function without a catch block, ' +\n 'or by rejecting a promise which was not handled with .catch().' +\n ' The promise rejected with the reason:';\n\n /* eslint-disable no-console */\n if (mode === 'warn') {\n consoleSandbox(() => {\n console.warn(rejectionWarning);\n console.error(isObjectLike(reason) && 'stack' in reason ? reason.stack : reason);\n });\n } else if (mode === 'strict') {\n consoleSandbox(() => {\n
|
|
1
|
+
{"version":3,"file":"onunhandledrejection.js","sources":["../../../src/integrations/onunhandledrejection.ts"],"sourcesContent":["import type { Client, IntegrationFn, SeverityLevel, Span } from '@sentry/core';\nimport {\n captureException,\n consoleSandbox,\n defineIntegration,\n getClient,\n isMatchingPattern,\n isObjectLike,\n withActiveSpan,\n} from '@sentry/core';\nimport { logAndExitProcess } from '../utils/errorhandling';\n\ntype UnhandledRejectionMode = 'none' | 'warn' | 'strict';\n\ntype IgnoreMatcher = { name?: string | RegExp; message?: string | RegExp };\n\ninterface OnUnhandledRejectionOptions {\n /**\n * Option deciding what to do after capturing unhandledRejection,\n * that mimicks behavior of node's --unhandled-rejection flag.\n */\n mode: UnhandledRejectionMode;\n /** Rejection Errors to ignore (don't capture or warn). */\n ignore?: IgnoreMatcher[];\n}\n\nconst INTEGRATION_NAME = 'OnUnhandledRejection';\n\nconst DEFAULT_IGNORES: IgnoreMatcher[] = [\n {\n name: 'AI_NoOutputGeneratedError', // When stream aborts in Vercel AI SDK V5, Vercel flush() fails with an error\n },\n {\n name: 'AbortError', // When stream aborts in Vercel AI SDK V6\n },\n];\n\nconst _onUnhandledRejectionIntegration = ((options: Partial<OnUnhandledRejectionOptions> = {}) => {\n const opts: OnUnhandledRejectionOptions = {\n mode: options.mode ?? 'warn',\n ignore: [...DEFAULT_IGNORES, ...(options.ignore ?? [])],\n };\n\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n global.process.on('unhandledRejection', makeUnhandledPromiseHandler(client, opts));\n },\n };\n}) satisfies IntegrationFn;\n\nexport const onUnhandledRejectionIntegration = defineIntegration(_onUnhandledRejectionIntegration);\n\n/** Extract error info safely */\nfunction extractErrorInfo(reason: unknown): { name: string; message: string } {\n // Check if reason is an object (including Error instances, not just plain objects)\n if (!isObjectLike(reason)) {\n return { name: '', message: String(reason ?? '') };\n }\n\n const errorLike = reason as Record<string, unknown>;\n const name = typeof errorLike.name === 'string' ? errorLike.name : '';\n const message = typeof errorLike.message === 'string' ? errorLike.message : String(reason);\n\n return { name, message };\n}\n\n/** Check if a matcher matches the reason */\nfunction isMatchingReason(matcher: IgnoreMatcher, errorInfo: ReturnType<typeof extractErrorInfo>): boolean {\n // name/message matcher\n const nameMatches = matcher.name === undefined || isMatchingPattern(errorInfo.name, matcher.name, true);\n\n const messageMatches = matcher.message === undefined || isMatchingPattern(errorInfo.message, matcher.message);\n\n return nameMatches && messageMatches;\n}\n\n/** Match helper */\nfunction matchesIgnore(list: IgnoreMatcher[], reason: unknown): boolean {\n const errorInfo = extractErrorInfo(reason);\n return list.some(matcher => isMatchingReason(matcher, errorInfo));\n}\n\n/** Core handler */\nexport function makeUnhandledPromiseHandler(\n client: Client,\n options: OnUnhandledRejectionOptions,\n): (reason: unknown, promise: unknown) => void {\n return function sendUnhandledPromise(reason: unknown, _promise: unknown): void {\n // Only handle for the active client\n if (getClient() !== client) {\n return;\n }\n\n // Skip if configured to ignore\n if (matchesIgnore(options.ignore ?? [], reason)) {\n return;\n }\n\n const level: SeverityLevel = options.mode === 'strict' ? 'fatal' : 'error';\n\n // this can be set in places where we cannot reliably get access to the active span/error\n // when the error bubbles up to this handler, we can use this to set the active span\n const activeSpanForError = isObjectLike(reason)\n ? (reason as { _sentry_active_span?: Span })._sentry_active_span\n : undefined;\n\n const activeSpanWrapper = activeSpanForError\n ? (fn: () => void) => withActiveSpan(activeSpanForError, fn)\n : (fn: () => void) => fn();\n\n activeSpanWrapper(() => {\n captureException(reason, {\n originalException: reason,\n captureContext: {\n extra: { unhandledPromiseRejection: true },\n level,\n },\n mechanism: {\n handled: false,\n type: 'auto.node.onunhandledrejection',\n },\n });\n });\n\n handleRejection(reason, options.mode);\n };\n}\n\n/**\n * Handler for `mode` option\n */\nfunction handleRejection(reason: unknown, mode: UnhandledRejectionMode): void {\n // https://github.com/nodejs/node/blob/7cf6f9e964aa00772965391c23acda6d71972a9a/lib/internal/process/promises.js#L234-L240\n const rejectionWarning =\n 'This error originated either by ' +\n 'throwing inside of an async function without a catch block, ' +\n 'or by rejecting a promise which was not handled with .catch().' +\n ' The promise rejected with the reason:';\n\n /* eslint-disable no-console */\n if (mode === 'warn') {\n consoleSandbox(() => {\n console.warn(rejectionWarning);\n console.error(isObjectLike(reason) && 'stack' in reason ? reason.stack : reason);\n });\n } else if (mode === 'strict') {\n if (!(isObjectLike(reason) && 'stack' in reason)) {\n consoleSandbox(() => {\n console.warn(rejectionWarning);\n });\n }\n logAndExitProcess(reason);\n }\n /* eslint-enable no-console */\n}\n"],"names":["defineIntegration","isObjectLike","isMatchingPattern","getClient","withActiveSpan","captureException","consoleSandbox","logAndExitProcess"],"mappings":";;;;;AA0BA,MAAM,gBAAA,GAAmB,sBAAA;AAEzB,MAAM,eAAA,GAAmC;AAAA,EACvC;AAAA,IACE,IAAA,EAAM;AAAA;AAAA,GACR;AAAA,EACA;AAAA,IACE,IAAA,EAAM;AAAA;AAAA;AAEV,CAAA;AAEA,MAAM,gCAAA,IAAoC,CAAC,OAAA,GAAgD,EAAC,KAAM;AAChG,EAAA,MAAM,IAAA,GAAoC;AAAA,IACxC,IAAA,EAAM,QAAQ,IAAA,IAAQ,MAAA;AAAA,IACtB,MAAA,EAAQ,CAAC,GAAG,eAAA,EAAiB,GAAI,OAAA,CAAQ,MAAA,IAAU,EAAG;AAAA,GACxD;AAEA,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,MAAM,MAAA,EAAQ;AACZ,MAAA,MAAA,CAAO,QAAQ,EAAA,CAAG,oBAAA,EAAsB,2BAAA,CAA4B,MAAA,EAAQ,IAAI,CAAC,CAAA;AAAA,IACnF;AAAA,GACF;AACF,CAAA,CAAA;AAEO,MAAM,+BAAA,GAAkCA,uBAAkB,gCAAgC;AAGjG,SAAS,iBAAiB,MAAA,EAAoD;AAE5E,EAAA,IAAI,CAACC,iBAAA,CAAa,MAAM,CAAA,EAAG;AACzB,IAAA,OAAO,EAAE,IAAA,EAAM,EAAA,EAAI,SAAS,MA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ACH;AACA,IAAAC,+BAAA,CAAkB,MAAM,CAAA;AAAA,EAC1B;AAEF;;;;;"}
|
package/build/cjs/sdk/api.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
2
|
|
|
3
3
|
const core = require('@sentry/core');
|
|
4
|
+
const server = require('@sentry/core/server');
|
|
4
5
|
const module$1 = require('../utils/module.js');
|
|
5
6
|
|
|
6
7
|
function getSentryRelease(fallback) {
|
|
@@ -54,7 +55,7 @@ function getSentryRelease(fallback) {
|
|
|
54
55
|
);
|
|
55
56
|
return possibleReleaseNameOfGitProvider || possibleReleaseNameOfCiProvidersWithSpecificEnvVar || possibleReleaseNameOfCiProvidersWithGenericEnvVar || fallback;
|
|
56
57
|
}
|
|
57
|
-
const defaultStackParser = core.createStackParser(
|
|
58
|
+
const defaultStackParser = core.createStackParser(server.nodeStackLineParser(module$1.createGetModuleFromFilename()));
|
|
58
59
|
|
|
59
60
|
exports.defaultStackParser = defaultStackParser;
|
|
60
61
|
exports.getSentryRelease = getSentryRelease;
|