@sentry/node 11.0.0-alpha.1 → 11.0.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/cjs/bundler-plugin/esbuild.js.map +1 -1
- package/build/cjs/bundler-plugin/rollup.js.map +1 -1
- package/build/cjs/bundler-plugin/vite.js.map +1 -1
- package/build/cjs/bundler-plugin/webpack.js.map +1 -1
- package/build/cjs/index.js +52 -53
- package/build/cjs/index.js.map +1 -1
- package/build/cjs/integrations/anr/index.js +1 -1
- package/build/cjs/integrations/childProcess.js +0 -24
- package/build/cjs/integrations/childProcess.js.map +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 +2 -8
- package/build/cjs/integrations/http/SentryHttpInstrumentation.js.map +1 -1
- package/build/cjs/integrations/http/httpServerIntegration.js.map +1 -1
- package/build/cjs/integrations/http/httpServerSpansIntegration.js +34 -60
- package/build/cjs/integrations/http/httpServerSpansIntegration.js.map +1 -1
- package/build/cjs/integrations/http/index.js +9 -27
- 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 +2 -5
- package/build/cjs/integrations/node-fetch/undici-instrumentation.js.map +1 -1
- package/build/cjs/integrations/pino.js +2 -3
- package/build/cjs/integrations/pino.js.map +1 -1
- package/build/cjs/integrations/processSession.js +1 -1
- package/build/cjs/integrations/processSession.js.map +1 -1
- package/build/cjs/integrations/tracing/hapi.js +10 -0
- package/build/cjs/integrations/tracing/hapi.js.map +1 -0
- package/build/cjs/integrations/tracing/index.js +1 -34
- package/build/cjs/integrations/tracing/index.js.map +1 -1
- package/build/cjs/integrations/tracing/koa.js +10 -0
- package/build/cjs/integrations/tracing/koa.js.map +1 -0
- package/build/cjs/integrations/workerThreads.js +35 -0
- package/build/cjs/integrations/workerThreads.js.map +1 -0
- package/build/cjs/sdk/client.js +23 -13
- package/build/cjs/sdk/client.js.map +1 -1
- package/build/cjs/sdk/index.js +16 -29
- package/build/cjs/sdk/index.js.map +1 -1
- package/build/cjs/transports/http.js +10 -3
- package/build/cjs/transports/http.js.map +1 -1
- package/build/cjs/utils/outgoingFetchRequest.js +1 -1
- package/build/cjs/utils/outgoingFetchRequest.js.map +1 -1
- package/build/esm/bundler-plugin/esbuild.js.map +1 -1
- package/build/esm/bundler-plugin/rollup.js.map +1 -1
- package/build/esm/bundler-plugin/vite.js.map +1 -1
- package/build/esm/bundler-plugin/webpack.js.map +1 -1
- package/build/esm/index.js +6 -8
- 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/childProcess.js +1 -25
- package/build/esm/integrations/childProcess.js.map +1 -1
- 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 +3 -9
- package/build/esm/integrations/http/SentryHttpInstrumentation.js.map +1 -1
- package/build/esm/integrations/http/httpServerIntegration.js.map +1 -1
- package/build/esm/integrations/http/httpServerSpansIntegration.js +36 -62
- package/build/esm/integrations/http/httpServerSpansIntegration.js.map +1 -1
- package/build/esm/integrations/http/index.js +10 -28
- 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 +3 -6
- package/build/esm/integrations/node-fetch/undici-instrumentation.js.map +1 -1
- package/build/esm/integrations/pino.js +2 -3
- package/build/esm/integrations/pino.js.map +1 -1
- package/build/esm/integrations/processSession.js +1 -1
- package/build/esm/integrations/processSession.js.map +1 -1
- package/build/esm/integrations/tracing/hapi.js +8 -0
- package/build/esm/integrations/tracing/hapi.js.map +1 -0
- package/build/esm/integrations/tracing/index.js +2 -35
- package/build/esm/integrations/tracing/index.js.map +1 -1
- package/build/esm/integrations/tracing/koa.js +8 -0
- package/build/esm/integrations/tracing/koa.js.map +1 -0
- package/build/esm/integrations/workerThreads.js +33 -0
- package/build/esm/integrations/workerThreads.js.map +1 -0
- package/build/esm/package.json +1 -1
- package/build/esm/sdk/client.js +23 -13
- package/build/esm/sdk/client.js.map +1 -1
- package/build/esm/sdk/index.js +10 -23
- package/build/esm/sdk/index.js.map +1 -1
- package/build/esm/transports/http.js +10 -3
- package/build/esm/transports/http.js.map +1 -1
- package/build/esm/utils/outgoingFetchRequest.js +2 -2
- package/build/esm/utils/outgoingFetchRequest.js.map +1 -1
- package/build/types/bundler-plugin/esbuild.d.ts +3 -4
- package/build/types/bundler-plugin/esbuild.d.ts.map +1 -1
- package/build/types/bundler-plugin/rollup.d.ts +3 -4
- package/build/types/bundler-plugin/rollup.d.ts.map +1 -1
- package/build/types/bundler-plugin/vite.d.ts +3 -4
- package/build/types/bundler-plugin/vite.d.ts.map +1 -1
- package/build/types/bundler-plugin/webpack.d.ts +2 -2
- package/build/types/bundler-plugin/webpack.d.ts.map +1 -1
- package/build/types/index.d.ts +6 -6
- package/build/types/index.d.ts.map +1 -1
- package/build/types/integrations/childProcess.d.ts +2 -7
- package/build/types/integrations/childProcess.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 +6 -61
- package/build/types/integrations/http/SentryHttpInstrumentation.d.ts.map +1 -1
- package/build/types/integrations/http/httpServerIntegration.d.ts +1 -1
- package/build/types/integrations/http/httpServerSpansIntegration.d.ts +1 -9
- package/build/types/integrations/http/httpServerSpansIntegration.d.ts.map +1 -1
- package/build/types/integrations/http/index.d.ts +16 -74
- 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/pino.d.ts.map +1 -1
- package/build/types/integrations/tracing/hapi.d.ts +13 -0
- package/build/types/integrations/tracing/hapi.d.ts.map +1 -0
- package/build/types/integrations/tracing/index.d.ts.map +1 -1
- package/build/types/integrations/tracing/koa.d.ts +27 -0
- package/build/types/integrations/tracing/koa.d.ts.map +1 -0
- package/build/types/integrations/workerThreads.d.ts +8 -0
- package/build/types/integrations/workerThreads.d.ts.map +1 -0
- package/build/types/sdk/client.d.ts +2 -0
- package/build/types/sdk/client.d.ts.map +1 -1
- package/build/types/sdk/index.d.ts.map +1 -1
- package/build/types/transports/http.d.ts +1 -1
- package/build/types/transports/http.d.ts.map +1 -1
- package/build/types/types.d.ts +11 -0
- package/build/types/types.d.ts.map +1 -1
- package/package.json +7 -6
- package/build/cjs/integrations/tracing/express.js +0 -11
- package/build/cjs/integrations/tracing/express.js.map +0 -1
- package/build/cjs/integrations/tracing/fastify/index.js +0 -40
- package/build/cjs/integrations/tracing/fastify/index.js.map +0 -1
- package/build/cjs/integrations/tracing/hapi/index.js +0 -44
- package/build/cjs/integrations/tracing/hapi/index.js.map +0 -1
- package/build/cjs/integrations/tracing/koa/index.js +0 -22
- package/build/cjs/integrations/tracing/koa/index.js.map +0 -1
- package/build/cjs/integrations/tracing/redis/cache.js +0 -43
- package/build/cjs/integrations/tracing/redis/cache.js.map +0 -1
- package/build/cjs/integrations/tracing/redis/index.js +0 -34
- package/build/cjs/integrations/tracing/redis/index.js.map +0 -1
- package/build/cjs/utils/redisCache.js +0 -98
- package/build/cjs/utils/redisCache.js.map +0 -1
- package/build/esm/integrations/tracing/express.js +0 -9
- package/build/esm/integrations/tracing/express.js.map +0 -1
- package/build/esm/integrations/tracing/fastify/index.js +0 -37
- package/build/esm/integrations/tracing/fastify/index.js.map +0 -1
- package/build/esm/integrations/tracing/hapi/index.js +0 -41
- package/build/esm/integrations/tracing/hapi/index.js.map +0 -1
- package/build/esm/integrations/tracing/koa/index.js +0 -20
- package/build/esm/integrations/tracing/koa/index.js.map +0 -1
- package/build/esm/integrations/tracing/redis/cache.js +0 -40
- package/build/esm/integrations/tracing/redis/cache.js.map +0 -1
- package/build/esm/integrations/tracing/redis/index.js +0 -28
- package/build/esm/integrations/tracing/redis/index.js.map +0 -1
- package/build/esm/utils/redisCache.js +0 -89
- package/build/esm/utils/redisCache.js.map +0 -1
- package/build/types/integrations/tracing/express.d.ts +0 -6
- package/build/types/integrations/tracing/express.d.ts.map +0 -1
- package/build/types/integrations/tracing/fastify/index.d.ts +0 -115
- package/build/types/integrations/tracing/fastify/index.d.ts.map +0 -1
- package/build/types/integrations/tracing/fastify/types.d.ts +0 -33
- package/build/types/integrations/tracing/fastify/types.d.ts.map +0 -1
- package/build/types/integrations/tracing/hapi/index.d.ts +0 -29
- package/build/types/integrations/tracing/hapi/index.d.ts.map +0 -1
- package/build/types/integrations/tracing/hapi/types.d.ts +0 -166
- package/build/types/integrations/tracing/hapi/types.d.ts.map +0 -1
- package/build/types/integrations/tracing/koa/index.d.ts +0 -26
- package/build/types/integrations/tracing/koa/index.d.ts.map +0 -1
- package/build/types/integrations/tracing/redis/cache.d.ts +0 -22
- package/build/types/integrations/tracing/redis/cache.d.ts.map +0 -1
- package/build/types/integrations/tracing/redis/index.d.ts +0 -21
- package/build/types/integrations/tracing/redis/index.d.ts.map +0 -1
- package/build/types/integrations/tracing/redis/vendored/types.d.ts +0 -9
- package/build/types/integrations/tracing/redis/vendored/types.d.ts.map +0 -1
- package/build/types/utils/redisCache.d.ts +0 -17
- package/build/types/utils/redisCache.d.ts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"instrumentation.js","sources":["../../../../../src/integrations/fs/vendored/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/15ef7506553f631ea4181391e0c5725a56f0d082/packages/instrumentation-fs\n * - Upstream version: @opentelemetry/instrumentation-fs@0.37.0\n * - Minor TypeScript strictness adjustments for this repository's compiler settings\n * - The OpenTelemetry tracer APIs were replaced with Sentry's `startSpan`/`startInactiveSpan`/`suppressTracing`\n * and the configurable `createHook`/`endHook`/`requireParentSpan` options were removed in favor of inlined,\n * Sentry-specific span attributes.\n * - Completely reworked to no longer reference OpenTelemetry.\n */\n\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SPAN_STATUS_ERROR,\n getActiveSpan,\n startInactiveSpan,\n startSpan,\n suppressTracing,\n withActiveSpan,\n} from '@sentry/core';\nimport * as fs from 'fs';\nimport { promisify } from 'util';\nimport { CALLBACK_FUNCTIONS, PROMISE_FUNCTIONS, SYNC_FUNCTIONS } from './constants';\nimport type { FMember, FPMember, FsInstrumentationConfig, GenericFunction } from './types';\nimport { indexFs } from './utils';\n\nconst SPAN_ORIGIN = 'auto.file.fs';\nconst SPAN_OP = 'file';\n\n// The following lists categorize `fs` functions by the shape of their leading path arguments, so we can\n// record meaningful span attributes for them. These are Sentry-specific additions (not part of upstream).\nconst FS_OPERATIONS_WITH_OLD_PATH_NEW_PATH = ['rename', 'renameSync'];\nconst FS_OPERATIONS_WITH_SRC_DEST = ['copyFile', 'cp', 'copyFileSync', 'cpSync'];\nconst FS_OPERATIONS_WITH_EXISTING_PATH_NEW_PATH = ['link', 'linkSync'];\nconst FS_OPERATIONS_WITH_PREFIX = ['mkdtemp', 'mkdtempSync'];\nconst FS_OPERATIONS_WITH_TARGET_PATH = ['symlink', 'symlinkSync'];\nconst FS_OPERATIONS_WITH_PATH_ARG = [\n 'access',\n 'appendFile',\n 'chmod',\n 'chown',\n 'exists',\n 'mkdir',\n 'lchown',\n 'lstat',\n 'lutimes',\n 'open',\n 'opendir',\n 'readdir',\n 'readFile',\n 'readlink',\n 'realpath',\n 'realpath.native',\n 'rm',\n 'rmdir',\n 'stat',\n 'truncate',\n 'unlink',\n 'utimes',\n 'writeFile',\n 'accessSync',\n 'appendFileSync',\n 'chmodSync',\n 'chownSync',\n 'existsSync',\n 'lchownSync',\n 'lstatSync',\n 'lutimesSync',\n 'opendirSync',\n 'mkdirSync',\n 'openSync',\n 'readdirSync',\n 'readFileSync',\n 'readlinkSync',\n 'realpathSync',\n 'realpathSync.native',\n 'rmdirSync',\n 'rmSync',\n 'statSync',\n 'truncateSync',\n 'unlinkSync',\n 'utimesSync',\n 'writeFileSync',\n];\n\n/**\n * Builds the span attributes for a given `fs` operation, optionally including the file path arguments.\n */\nfunction getSpanAttributes(\n functionName: FMember | FPMember,\n args: ArrayLike<unknown>,\n config: FsInstrumentationConfig,\n): SpanAttributes {\n const attributes: SpanAttributes = {\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: SPAN_OP,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: SPAN_ORIGIN,\n };\n\n if (!config.recordFilePaths) {\n return attributes;\n }\n\n if (typeof args[0] === 'string' && FS_OPERATIONS_WITH_PATH_ARG.includes(functionName)) {\n attributes['path_argument'] = args[0];\n } else if (typeof args[0] === 'string' && typeof args[1] === 'string') {\n if (FS_OPERATIONS_WITH_TARGET_PATH.includes(functionName)) {\n attributes['target_argument'] = args[0];\n attributes['path_argument'] = args[1];\n } else if (FS_OPERATIONS_WITH_EXISTING_PATH_NEW_PATH.includes(functionName)) {\n attributes['existing_path_argument'] = args[0];\n attributes['new_path_argument'] = args[1];\n } else if (FS_OPERATIONS_WITH_SRC_DEST.includes(functionName)) {\n attributes['src_argument'] = args[0];\n attributes['dest_argument'] = args[1];\n } else if (FS_OPERATIONS_WITH_OLD_PATH_NEW_PATH.includes(functionName)) {\n attributes['old_path_argument'] = args[0];\n attributes['new_path_argument'] = args[1];\n }\n } else if (typeof args[0] === 'string' && FS_OPERATIONS_WITH_PREFIX.includes(functionName)) {\n attributes['prefix_argument'] = args[0];\n }\n\n return attributes;\n}\n\n/**\n * This is important for 2-level functions like `realpath.native` to retain the 2nd-level\n * when patching the 1st-level.\n */\nfunction patchedFunctionWithOriginalProperties<T extends GenericFunction>(patchedFunction: T, original: T): T {\n return Object.assign(patchedFunction, original);\n}\n\n// Tracks patched methods to prevent double-patching if `enableFsInstrumentation` is called more than once.\nconst _patched = new WeakMap<Record<string, GenericFunction>, Set<string>>();\n\nfunction _patchMethod(\n obj: Record<string, GenericFunction>,\n name: string,\n wrapper: (original: GenericFunction) => GenericFunction,\n): void {\n const original = obj[name];\n if (typeof original !== 'function') return;\n let patched = _patched.get(obj);\n if (!patched) {\n patched = new Set();\n _patched.set(obj, patched);\n }\n if (patched.has(name)) return;\n patched.add(name);\n obj[name] = wrapper(original);\n}\n\nfunction _patchSyncFunction<T extends GenericFunction>(\n functionName: FMember,\n original: T,\n config: FsInstrumentationConfig,\n): T {\n const patchedFunction = function (this: unknown, ...args: Parameters<T>): ReturnType<T> {\n const attributes = getSpanAttributes(functionName, args, config);\n return startSpan({ name: `fs.${functionName}`, onlyIfParent: true, attributes }, span => {\n try {\n return suppressTracing(() => original.apply(this, args)) as ReturnType<T>;\n } catch (error) {\n recordError(span, error, config);\n throw error;\n }\n });\n };\n return patchedFunctionWithOriginalProperties(patchedFunction as T, original);\n}\n\nfunction _patchCallbackFunction<T extends GenericFunction>(\n functionName: FMember,\n original: T,\n config: FsInstrumentationConfig,\n): T {\n const patchedFunction = function (this: unknown, ...args: Parameters<T>): ReturnType<T> {\n const lastIdx = args.length - 1;\n const cb: unknown = args[lastIdx];\n if (typeof cb !== 'function') {\n return original.apply(this, args) as ReturnType<T>;\n }\n\n const attributes = getSpanAttributes(functionName, args, config);\n const span = startInactiveSpan({ name: `fs.${functionName}`, onlyIfParent: true, attributes });\n const parentSpan = getActiveSpan();\n\n // Wrap the callback to end the span and restore the caller's active span context.\n // fs callbacks fire from Node's I/O event loop where the AsyncLocalStorage context\n // is lost, so any spans created inside the callback would otherwise have no parent.\n args[lastIdx] = function (this: unknown, ...cbArgs: unknown[]) {\n const error = cbArgs[0];\n if (error) {\n recordError(span, error, config);\n }\n span.end();\n if (parentSpan) {\n return withActiveSpan(parentSpan, () => (cb as GenericFunction).apply(this, cbArgs));\n }\n return (cb as GenericFunction).apply(this, cbArgs);\n };\n\n try {\n return suppressTracing(() => original.apply(this, args)) as ReturnType<T>;\n } catch (error) {\n recordError(span, error, config);\n span.end();\n throw error;\n }\n };\n return patchedFunctionWithOriginalProperties(patchedFunction as T, original);\n}\n\nfunction _patchExistsCallbackFunction<T extends GenericFunction>(original: T, config: FsInstrumentationConfig): T {\n const functionName = 'exists' as FMember;\n const patchedFunction = function (this: unknown, ...args: Parameters<T>): ReturnType<T> {\n const lastIdx = args.length - 1;\n const cb: unknown = args[lastIdx];\n if (typeof cb !== 'function') {\n return original.apply(this, args) as ReturnType<T>;\n }\n\n const attributes = getSpanAttributes(functionName, args, config);\n const span = startInactiveSpan({ name: `fs.${functionName}`, onlyIfParent: true, attributes });\n const parentSpan = getActiveSpan();\n\n // `exists` never calls the callback with an error\n args[lastIdx] = function (this: unknown, ...cbArgs: unknown[]) {\n span.end();\n if (parentSpan) {\n return withActiveSpan(parentSpan, () => (cb as GenericFunction).apply(this, cbArgs));\n }\n return (cb as GenericFunction).apply(this, cbArgs);\n };\n\n try {\n return suppressTracing(() => original.apply(this, args)) as ReturnType<T>;\n } catch (error) {\n recordError(span, error, config);\n span.end();\n throw error;\n }\n };\n const functionWithOriginalProperties = patchedFunctionWithOriginalProperties(patchedFunction as T, original);\n\n // `exists` has a custom promisify function because of the inconsistent signature\n // replicating that on the patched function\n const promisified = function (path: unknown): Promise<unknown> {\n return new Promise(resolve => (functionWithOriginalProperties as GenericFunction)(path, resolve));\n };\n Object.defineProperty(promisified, 'name', { value: functionName });\n Object.defineProperty(functionWithOriginalProperties, promisify.custom, {\n value: promisified,\n });\n\n return functionWithOriginalProperties;\n}\n\nfunction _patchPromiseFunction<T extends GenericFunction>(\n functionName: FPMember,\n original: T,\n config: FsInstrumentationConfig,\n): T {\n const patchedFunction = async function (this: unknown, ...args: Parameters<T>): Promise<unknown> {\n const attributes = getSpanAttributes(functionName, args, config);\n return startSpan({ name: `fs.${functionName}`, onlyIfParent: true, attributes }, async span => {\n try {\n return await suppressTracing(() => original.apply(this, args) as Promise<unknown>);\n } catch (error) {\n recordError(span, error, config);\n throw error;\n }\n });\n };\n return patchedFunctionWithOriginalProperties(patchedFunction as unknown as T, original);\n}\n\nexport function enableFsInstrumentation(config: FsInstrumentationConfig = {}): void {\n for (const fName of SYNC_FUNCTIONS) {\n const { objectToPatch, functionNameToPatch } = indexFs(fs, fName);\n _patchMethod(objectToPatch, functionNameToPatch, original => _patchSyncFunction(fName, original, config));\n }\n\n for (const fName of CALLBACK_FUNCTIONS) {\n const { objectToPatch, functionNameToPatch } = indexFs(fs, fName);\n if (fName === 'exists') {\n _patchMethod(objectToPatch, functionNameToPatch, original => _patchExistsCallbackFunction(original, config));\n } else {\n _patchMethod(objectToPatch, functionNameToPatch, original => _patchCallbackFunction(fName, original, config));\n }\n }\n\n // `fs.promises` and `import { readFile } from 'fs/promises'` share the same object in Node 14+,\n // so patching one covers both.\n const fsPromises = fs.promises as unknown as Record<string, GenericFunction>;\n for (const fName of PROMISE_FUNCTIONS) {\n _patchMethod(fsPromises, fName, original => _patchPromiseFunction(fName, original, config));\n }\n}\n\n/**\n * Sets the error status on the span and, if configured, records the error message as a span attribute.\n */\nfunction recordError(span: Span, error: unknown, config: FsInstrumentationConfig): void {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n if (config.recordErrorMessagesAsSpanAttributes && error instanceof Error) {\n span.setAttribute('fs_error', error.message);\n }\n}\n"],"names":["SEMANTIC_ATTRIBUTE_SENTRY_OP","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","startSpan","suppressTracing","startInactiveSpan","getActiveSpan","withActiveSpan","promisify","SYNC_FUNCTIONS","indexFs","CALLBACK_FUNCTIONS","PROMISE_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CAAA,QAAA,KAAY,uBAAuB,KAAA,EAAO,QAAA,EAAU,MAAM,CAAC,CAAA;AAAA,IAC9G;AAAA,EACF;AAIA,EAAA,MAAM,aAAa,EAAA,CAAG,QAAA;AACtB,EAAA,KAAA,MAAW,SAASE,2BAAA,EAAmB;AACrC,IAAA,YAAA,CAAa,YAAY,KAAA,EAAO,CAAA,QAAA,KAAY,sBAAsB,KAAA,EAAO,QAAA,EAAU,MAAM,CAAC,CAAA;AAAA,EAC5F;AACF;AAKA,SAAS,WAAA,CAAY,IAAA,EAAY,KAAA,EAAgB,MAAA,EAAuC;AACtF,EAAA,IAAA,CAAK,UAAU,EAAE,IAAA,EAAMC,sBAAA,EAAmB,OAAA,EAAS,kBAAkB,CAAA;AACrE,EAAA,IAAI,MAAA,CAAO,mCAAA,IAAuC,KAAA,YAAiB,KAAA,EAAO;AACxE,IAAA,IAAA,CAAK,YAAA,CAAa,UAAA,EAAY,KAAA,CAAM,OAAO,CAAA;AAAA,EAC7C;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"instrumentation.js","sources":["../../../../../src/integrations/fs/vendored/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/15ef7506553f631ea4181391e0c5725a56f0d082/packages/instrumentation-fs\n * - Upstream version: @opentelemetry/instrumentation-fs@0.37.0\n * - Minor TypeScript strictness adjustments for this repository's compiler settings\n * - The OpenTelemetry tracer APIs were replaced with Sentry's `startSpan`/`startInactiveSpan`/`suppressTracing`\n * and the configurable `createHook`/`endHook`/`requireParentSpan` options were removed in favor of inlined,\n * Sentry-specific span attributes.\n * - Completely reworked to no longer reference OpenTelemetry.\n * - The upstream `fs_error` span attribute (the error message) was replaced with the conventions-backed\n * `error.type` (the syscall error code, e.g. `ENOENT`).\n */\n\nimport { ERROR_TYPE } from '@sentry/conventions/attributes';\nimport type { Span, SpanAttributes } from '@sentry/core';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SPAN_STATUS_ERROR,\n getActiveSpan,\n startInactiveSpan,\n startSpan,\n suppressTracing,\n withActiveSpan,\n} from '@sentry/core';\nimport * as fs from 'fs';\nimport { promisify } from 'util';\nimport { CALLBACK_FUNCTIONS, PROMISE_FUNCTIONS, SYNC_FUNCTIONS } from './constants';\nimport type { FMember, FPMember, FsInstrumentationConfig, GenericFunction } from './types';\nimport { indexFs } from './utils';\n\nconst SPAN_ORIGIN = 'auto.file.fs';\nconst SPAN_OP = 'file';\n\n// The following lists categorize `fs` functions by the shape of their leading path arguments, so we can\n// record meaningful span attributes for them. These are Sentry-specific additions (not part of upstream).\nconst FS_OPERATIONS_WITH_OLD_PATH_NEW_PATH = ['rename', 'renameSync'];\nconst FS_OPERATIONS_WITH_SRC_DEST = ['copyFile', 'cp', 'copyFileSync', 'cpSync'];\nconst FS_OPERATIONS_WITH_EXISTING_PATH_NEW_PATH = ['link', 'linkSync'];\nconst FS_OPERATIONS_WITH_PREFIX = ['mkdtemp', 'mkdtempSync'];\nconst FS_OPERATIONS_WITH_TARGET_PATH = ['symlink', 'symlinkSync'];\nconst FS_OPERATIONS_WITH_PATH_ARG = [\n 'access',\n 'appendFile',\n 'chmod',\n 'chown',\n 'exists',\n 'mkdir',\n 'lchown',\n 'lstat',\n 'lutimes',\n 'open',\n 'opendir',\n 'readdir',\n 'readFile',\n 'readlink',\n 'realpath',\n 'realpath.native',\n 'rm',\n 'rmdir',\n 'stat',\n 'truncate',\n 'unlink',\n 'utimes',\n 'writeFile',\n 'accessSync',\n 'appendFileSync',\n 'chmodSync',\n 'chownSync',\n 'existsSync',\n 'lchownSync',\n 'lstatSync',\n 'lutimesSync',\n 'opendirSync',\n 'mkdirSync',\n 'openSync',\n 'readdirSync',\n 'readFileSync',\n 'readlinkSync',\n 'realpathSync',\n 'realpathSync.native',\n 'rmdirSync',\n 'rmSync',\n 'statSync',\n 'truncateSync',\n 'unlinkSync',\n 'utimesSync',\n 'writeFileSync',\n];\n\n/**\n * Builds the span attributes for a given `fs` operation, optionally including the file path arguments.\n */\nfunction getSpanAttributes(\n functionName: FMember | FPMember,\n args: ArrayLike<unknown>,\n config: FsInstrumentationConfig,\n): SpanAttributes {\n const attributes: SpanAttributes = {\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: SPAN_OP,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: SPAN_ORIGIN,\n };\n\n if (!config.recordFilePaths) {\n return attributes;\n }\n\n if (typeof args[0] === 'string' && FS_OPERATIONS_WITH_PATH_ARG.includes(functionName)) {\n attributes['path_argument'] = args[0];\n } else if (typeof args[0] === 'string' && typeof args[1] === 'string') {\n if (FS_OPERATIONS_WITH_TARGET_PATH.includes(functionName)) {\n attributes['target_argument'] = args[0];\n attributes['path_argument'] = args[1];\n } else if (FS_OPERATIONS_WITH_EXISTING_PATH_NEW_PATH.includes(functionName)) {\n attributes['existing_path_argument'] = args[0];\n attributes['new_path_argument'] = args[1];\n } else if (FS_OPERATIONS_WITH_SRC_DEST.includes(functionName)) {\n attributes['src_argument'] = args[0];\n attributes['dest_argument'] = args[1];\n } else if (FS_OPERATIONS_WITH_OLD_PATH_NEW_PATH.includes(functionName)) {\n attributes['old_path_argument'] = args[0];\n attributes['new_path_argument'] = args[1];\n }\n } else if (typeof args[0] === 'string' && FS_OPERATIONS_WITH_PREFIX.includes(functionName)) {\n attributes['prefix_argument'] = args[0];\n }\n\n return attributes;\n}\n\n/**\n * This is important for 2-level functions like `realpath.native` to retain the 2nd-level\n * when patching the 1st-level.\n */\nfunction patchedFunctionWithOriginalProperties<T extends GenericFunction>(patchedFunction: T, original: T): T {\n return Object.assign(patchedFunction, original);\n}\n\n// Tracks patched methods to prevent double-patching if `enableFsInstrumentation` is called more than once.\nconst _patched = new WeakMap<Record<string, GenericFunction>, Set<string>>();\n\nfunction _patchMethod(\n obj: Record<string, GenericFunction>,\n name: string,\n wrapper: (original: GenericFunction) => GenericFunction,\n): void {\n const original = obj[name];\n if (typeof original !== 'function') return;\n let patched = _patched.get(obj);\n if (!patched) {\n patched = new Set();\n _patched.set(obj, patched);\n }\n if (patched.has(name)) return;\n patched.add(name);\n obj[name] = wrapper(original);\n}\n\nfunction _patchSyncFunction<T extends GenericFunction>(\n functionName: FMember,\n original: T,\n config: FsInstrumentationConfig,\n): T {\n const patchedFunction = function (this: unknown, ...args: Parameters<T>): ReturnType<T> {\n const attributes = getSpanAttributes(functionName, args, config);\n return startSpan({ name: `fs.${functionName}`, onlyIfParent: true, attributes }, span => {\n try {\n return suppressTracing(() => original.apply(this, args)) as ReturnType<T>;\n } catch (error) {\n recordError(span, error, config);\n throw error;\n }\n });\n };\n return patchedFunctionWithOriginalProperties(patchedFunction as T, original);\n}\n\nfunction _patchCallbackFunction<T extends GenericFunction>(\n functionName: FMember,\n original: T,\n config: FsInstrumentationConfig,\n): T {\n const patchedFunction = function (this: unknown, ...args: Parameters<T>): ReturnType<T> {\n const lastIdx = args.length - 1;\n const cb: unknown = args[lastIdx];\n if (typeof cb !== 'function') {\n return original.apply(this, args) as ReturnType<T>;\n }\n\n const attributes = getSpanAttributes(functionName, args, config);\n const span = startInactiveSpan({ name: `fs.${functionName}`, onlyIfParent: true, attributes });\n const parentSpan = getActiveSpan();\n\n // Wrap the callback to end the span and restore the caller's active span context.\n // fs callbacks fire from Node's I/O event loop where the AsyncLocalStorage context\n // is lost, so any spans created inside the callback would otherwise have no parent.\n args[lastIdx] = function (this: unknown, ...cbArgs: unknown[]) {\n const error = cbArgs[0];\n if (error) {\n recordError(span, error, config);\n }\n span.end();\n if (parentSpan) {\n return withActiveSpan(parentSpan, () => (cb as GenericFunction).apply(this, cbArgs));\n }\n return (cb as GenericFunction).apply(this, cbArgs);\n };\n\n try {\n return suppressTracing(() => original.apply(this, args)) as ReturnType<T>;\n } catch (error) {\n recordError(span, error, config);\n span.end();\n throw error;\n }\n };\n return patchedFunctionWithOriginalProperties(patchedFunction as T, original);\n}\n\nfunction _patchExistsCallbackFunction<T extends GenericFunction>(original: T, config: FsInstrumentationConfig): T {\n const functionName = 'exists' as FMember;\n const patchedFunction = function (this: unknown, ...args: Parameters<T>): ReturnType<T> {\n const lastIdx = args.length - 1;\n const cb: unknown = args[lastIdx];\n if (typeof cb !== 'function') {\n return original.apply(this, args) as ReturnType<T>;\n }\n\n const attributes = getSpanAttributes(functionName, args, config);\n const span = startInactiveSpan({ name: `fs.${functionName}`, onlyIfParent: true, attributes });\n const parentSpan = getActiveSpan();\n\n // `exists` never calls the callback with an error\n args[lastIdx] = function (this: unknown, ...cbArgs: unknown[]) {\n span.end();\n if (parentSpan) {\n return withActiveSpan(parentSpan, () => (cb as GenericFunction).apply(this, cbArgs));\n }\n return (cb as GenericFunction).apply(this, cbArgs);\n };\n\n try {\n return suppressTracing(() => original.apply(this, args)) as ReturnType<T>;\n } catch (error) {\n recordError(span, error, config);\n span.end();\n throw error;\n }\n };\n const functionWithOriginalProperties = patchedFunctionWithOriginalProperties(patchedFunction as T, original);\n\n // `exists` has a custom promisify function because of the inconsistent signature\n // replicating that on the patched function\n const promisified = function (path: unknown): Promise<unknown> {\n return new Promise(resolve => (functionWithOriginalProperties as GenericFunction)(path, resolve));\n };\n Object.defineProperty(promisified, 'name', { value: functionName });\n Object.defineProperty(functionWithOriginalProperties, promisify.custom, {\n value: promisified,\n });\n\n return functionWithOriginalProperties;\n}\n\nfunction _patchPromiseFunction<T extends GenericFunction>(\n functionName: FPMember,\n original: T,\n config: FsInstrumentationConfig,\n): T {\n const patchedFunction = async function (this: unknown, ...args: Parameters<T>): Promise<unknown> {\n const attributes = getSpanAttributes(functionName, args, config);\n return startSpan({ name: `fs.${functionName}`, onlyIfParent: true, attributes }, async span => {\n try {\n return await suppressTracing(() => original.apply(this, args) as Promise<unknown>);\n } catch (error) {\n recordError(span, error, config);\n throw error;\n }\n });\n };\n return patchedFunctionWithOriginalProperties(patchedFunction as unknown as T, original);\n}\n\nexport function enableFsInstrumentation(config: FsInstrumentationConfig = {}): void {\n for (const fName of SYNC_FUNCTIONS) {\n const { objectToPatch, functionNameToPatch } = indexFs(fs, fName);\n _patchMethod(objectToPatch, functionNameToPatch, original => _patchSyncFunction(fName, original, config));\n }\n\n for (const fName of CALLBACK_FUNCTIONS) {\n const { objectToPatch, functionNameToPatch } = indexFs(fs, fName);\n if (fName === 'exists') {\n _patchMethod(objectToPatch, functionNameToPatch, original => _patchExistsCallbackFunction(original, config));\n } else {\n _patchMethod(objectToPatch, functionNameToPatch, original => _patchCallbackFunction(fName, original, config));\n }\n }\n\n // `fs.promises` and `import { readFile } from 'fs/promises'` share the same object in Node 14+,\n // so patching one covers both.\n const fsPromises = fs.promises as unknown as Record<string, GenericFunction>;\n for (const fName of PROMISE_FUNCTIONS) {\n _patchMethod(fsPromises, fName, original => _patchPromiseFunction(fName, original, config));\n }\n}\n\n/**\n * Sets the error status on the span and, if configured, records the error type as a span attribute.\n */\nfunction recordError(span: Span, error: unknown, config: FsInstrumentationConfig): void {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n if (config.recordErrorMessagesAsSpanAttributes && error instanceof Error) {\n span.setAttribute(ERROR_TYPE, (error as NodeJS.ErrnoException).code ?? error.name);\n }\n}\n"],"names":["SEMANTIC_ATTRIBUTE_SENTRY_OP","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","startSpan","suppressTracing","startInactiveSpan","getActiveSpan","withActiveSpan","promisify","SYNC_FUNCTIONS","indexFs","CALLBACK_FUNCTIONS","PROMISE_FUNCTIONS","SPAN_STATUS_ERROR","ERROR_TYPE"],"mappings":";;;;;;;;;AAkCA,MAAM,WAAA,GAAc,cAAA;AACpB,MAAM,OAAA,GAAU,MAAA;AAIhB,MAAM,oCAAA,GAAuC,CAAC,QAAA,EAAU,YAAY,CAAA;AACpE,MAAM,2BAAA,GAA8B,CAAC,UAAA,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YAAY,KAAA,EAAO,CAAA,QAAA,KAAY,sBAAsB,KAAA,EAAO,QAAA,EAAU,MAAM,CAAC,CAAA;AAAA,EAC5F;AACF;AAKA,SAAS,WAAA,CAAY,IAAA,EAAY,KAAA,EAAgB,MAAA,EAAuC;AACtF,EAAA,IAAA,CAAK,UAAU,EAAE,IAAA,EAAMC,sBAAA,EAAmB,OAAA,EAAS,kBAAkB,CAAA;AACrE,EAAA,IAAI,MAAA,CAAO,mCAAA,IAAuC,KAAA,YAAiB,KAAA,EAAO;AACxE,IAAA,IAAA,CAAK,YAAA,CAAaC,qBAAA,EAAa,KAAA,CAAgC,IAAA,IAAQ,MAAM,IAAI,CAAA;AAAA,EACnF;AACF;;;;"}
|
|
@@ -11,11 +11,10 @@ const FULLY_SUPPORTS_HTTP_DIAGNOSTICS_CHANNEL = nodeVersion.NODE_VERSION.major =
|
|
|
11
11
|
function instrumentHttpOutgoingRequests(instrumentationOptions = {}) {
|
|
12
12
|
const { outgoingRequestApplyCustomAttributes: applyCustomAttributesOnSpan, ...options } = instrumentationOptions;
|
|
13
13
|
const patchOptions = {
|
|
14
|
-
propagateTrace: options.propagateTraceInOutgoingRequests ?? true,
|
|
15
14
|
applyCustomAttributesOnSpan,
|
|
16
15
|
...options,
|
|
17
|
-
|
|
18
|
-
spans: options.
|
|
16
|
+
tracePropagation: options.tracePropagation ?? true,
|
|
17
|
+
spans: options.spans ?? true,
|
|
19
18
|
ignoreOutgoingRequests(url, request) {
|
|
20
19
|
return core.isTracingSuppressed() || !!options.ignoreOutgoingRequests?.(url, core.getRequestOptions(request));
|
|
21
20
|
},
|
|
@@ -50,14 +49,9 @@ function instrumentHttpOutgoingRequests(instrumentationOptions = {}) {
|
|
|
50
49
|
instrumentHttpOutgoingRequestsViaMonkeyPatching(patchOptions);
|
|
51
50
|
}
|
|
52
51
|
}
|
|
53
|
-
let _currentListener;
|
|
54
52
|
function instrumentHttpOutgoingRequestsViaChannel(options) {
|
|
55
53
|
const { [core.HTTP_ON_CLIENT_REQUEST]: onHttpClientRequestCreated } = core.getHttpClientSubscriptions(options);
|
|
56
|
-
if (_currentListener) {
|
|
57
|
-
diagnosticsChannel.unsubscribe(core.HTTP_ON_CLIENT_REQUEST, _currentListener);
|
|
58
|
-
}
|
|
59
54
|
diagnosticsChannel.subscribe(core.HTTP_ON_CLIENT_REQUEST, onHttpClientRequestCreated);
|
|
60
|
-
_currentListener = onHttpClientRequestCreated;
|
|
61
55
|
}
|
|
62
56
|
function instrumentHttpOutgoingRequestsViaMonkeyPatching(options) {
|
|
63
57
|
core.patchHttpModuleClient(http, options);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SentryHttpInstrumentation.js","sources":["../../../../src/integrations/http/SentryHttpInstrumentation.ts"],"sourcesContent":["import type { ChannelListener } from 'node:diagnostics_channel';\nimport { subscribe, unsubscribe } from 'node:diagnostics_channel';\nimport { context, trace } from '@opentelemetry/api';\nimport type { ClientRequest, IncomingMessage, ServerResponse } from 'node:http';\nimport type { HttpClientRequest, HttpIncomingMessage, HttpInstrumentationOptions, Span } from '@sentry/core';\nimport {\n getHttpClientSubscriptions,\n patchHttpModuleClient,\n getRequestOptions,\n isTracingSuppressed,\n} from '@sentry/core';\nimport { HTTP_ON_CLIENT_REQUEST } from '@sentry/core';\nimport { NODE_VERSION } from '../../nodeVersion';\nimport { errorMonitor } from 'node:events';\nimport * as http from 'node:http';\n\nconst FULLY_SUPPORTS_HTTP_DIAGNOSTICS_CHANNEL =\n (NODE_VERSION.major === 22 && NODE_VERSION.minor >= 12) ||\n (NODE_VERSION.major === 23 && NODE_VERSION.minor >= 2) ||\n NODE_VERSION.major >= 24;\n\ninterface OutgoingHttpRequestInstrumentationOptions {\n /**\n * Whether breadcrumbs should be recorded for outgoing requests.\n *\n * @default `true`\n */\n breadcrumbs?: boolean;\n\n /**\n * Whether to create spans for outgoing requests (user preference).\n * This only takes effect if `createSpansForOutgoingRequests` is not disabled.\n * If `createSpansForOutgoingRequests` is explicitly set false, this option is ignored.\n *\n * @default `true`\n */\n spans?: boolean;\n\n /**\n * Whether to propagate Sentry trace headers in outgoing requests.\n *\n * @default `true`\n */\n propagateTraceInOutgoingRequests?: boolean;\n\n /**\n * @deprecated Use spans option instead.\n *\n * @default `true`\n */\n createSpansForOutgoingRequests?: boolean;\n\n /**\n * Do not instrument outgoing HTTP requests to URLs where the given callback returns `true`.\n * When it returns `true`, the request is skipped entirely: no breadcrumb and no span are created,\n * and no trace headers are propagated for that request.\n *\n * @param url Contains the entire URL, including query string (if any), protocol, host, etc. of the outgoing request.\n * @param request Contains the {@type RequestOptions} object used to make the outgoing request.\n */\n ignoreOutgoingRequests?: (url: string, request: http.RequestOptions) => boolean;\n\n /**\n * Hooks for outgoing request spans, only called when spans are created for outgoing requests\n * (i.e. when `spans` is enabled).\n * These mirror the OTEL HttpInstrumentation hooks for backwards compatibility.\n */\n outgoingRequestHook?: (span: Span, request: ClientRequest | HttpClientRequest) => void;\n outgoingResponseHook?: (span: Span, response: IncomingMessage | HttpIncomingMessage) => void;\n outgoingRequestApplyCustomAttributes?: (\n span: Span,\n request: HttpClientRequest,\n response: HttpIncomingMessage,\n ) => void;\n}\n\nexport type SentryHttpInstrumentationOptions = OutgoingHttpRequestInstrumentationOptions & {\n // All options below do not do anything anymore in this instrumentation, and will be removed in the future.\n // They are only kept here for backwards compatibility - the respective functionality is now handled by the httpServerIntegration/httpServerSpansIntegration.\n\n /**\n * @deprecated This no longer does anything.\n */\n extractIncomingTraceFromHeader?: boolean;\n\n /**\n * @deprecated This no longer does anything.\n */\n ignoreStaticAssets?: boolean;\n\n /**\n * @deprecated This no longer does anything.\n */\n disableIncomingRequestSpans?: boolean;\n\n /**\n * @deprecated This no longer does anything.\n */\n ignoreSpansForIncomingRequests?: (urlPath: string, request: IncomingMessage) => boolean;\n\n /**\n * @deprecated This no longer does anything.\n */\n ignoreIncomingRequestBody?: (url: string, request: http.RequestOptions) => boolean;\n\n /**\n * @deprecated This no longer does anything.\n */\n maxIncomingRequestBodySize?: 'none' | 'small' | 'medium' | 'always';\n\n /**\n * @deprecated This no longer does anything.\n */\n trackIncomingRequestsAsSessions?: boolean;\n\n /**\n * @deprecated This no longer does anything.\n */\n instrumentation?: {\n requestHook?: (span: Span, req: ClientRequest | IncomingMessage) => void;\n responseHook?: (span: Span, response: IncomingMessage | ServerResponse) => void;\n applyCustomAttributesOnSpan?: (\n span: Span,\n request: ClientRequest | IncomingMessage,\n response: IncomingMessage | ServerResponse,\n ) => void;\n };\n\n /**\n * @deprecated This no longer does anything.\n */\n sessionFlushingDelayMS?: number;\n};\n\n/**\n * This instruments the http modules for outgoing requests.\n * It uses the diagnostics channel if available, otherwise it falls back to monkey-patching.\n *\n * The instrumentation will start spans, create breadcrumbs, and propagate trace headers in outgoing requests (depending on the settings).\n * This can be called multiple times, where the last invocation will have the current options.\n *\n * @TODO Cleanup options in v11\n */\nexport function instrumentHttpOutgoingRequests(\n instrumentationOptions: OutgoingHttpRequestInstrumentationOptions = {},\n): void {\n const { outgoingRequestApplyCustomAttributes: applyCustomAttributesOnSpan, ...options } = instrumentationOptions;\n const patchOptions = {\n propagateTrace: options.propagateTraceInOutgoingRequests ?? true,\n applyCustomAttributesOnSpan,\n ...options,\n // oxlint-disable-next-line typescript/no-deprecated\n spans: options.createSpansForOutgoingRequests !== false && (options.spans ?? true),\n ignoreOutgoingRequests(url, request) {\n return isTracingSuppressed() || !!options.ignoreOutgoingRequests?.(url, getRequestOptions(request));\n },\n outgoingRequestHook(span, request) {\n options.outgoingRequestHook?.(span, request);\n // We monkey-patch `req.once('response'), which is used to trigger\n // the callback of the request, so that it runs in the active context\n // eslint-disable-next-line @typescript-eslint/unbound-method, typescript/no-deprecated\n const originalOnce = request.once;\n\n const newOnce = new Proxy(originalOnce, {\n apply(target, thisArg, args: Parameters<typeof originalOnce>) {\n const [event] = args;\n if (event !== 'response') {\n return target.apply(thisArg, args);\n }\n\n const parentContext = context.active();\n const requestContext = trace.setSpan(parentContext, span);\n\n return context.with(requestContext, () => {\n return target.apply(thisArg, args);\n });\n },\n });\n\n // eslint-disable-next-line typescript/no-deprecated\n request.once = newOnce;\n },\n outgoingResponseHook(span, response) {\n options.outgoingResponseHook?.(span, response);\n },\n errorMonitor,\n // Pass these in to detect OTel double-wrapping if we're enabling spans\n http,\n } satisfies HttpInstrumentationOptions;\n\n if (FULLY_SUPPORTS_HTTP_DIAGNOSTICS_CHANNEL) {\n instrumentHttpOutgoingRequestsViaChannel(patchOptions);\n } else {\n instrumentHttpOutgoingRequestsViaMonkeyPatching(patchOptions);\n }\n}\n\nlet _currentListener: ChannelListener | undefined;\nfunction instrumentHttpOutgoingRequestsViaChannel(options: HttpInstrumentationOptions): void {\n const { [HTTP_ON_CLIENT_REQUEST]: onHttpClientRequestCreated } = getHttpClientSubscriptions(options);\n // If it was previously subscribed, first unsubscribe it\n // TODO(v11): We can likely remove this when we drop preload support\n if (_currentListener) {\n unsubscribe(HTTP_ON_CLIENT_REQUEST, _currentListener);\n }\n\n subscribe(HTTP_ON_CLIENT_REQUEST, onHttpClientRequestCreated);\n _currentListener = onHttpClientRequestCreated;\n}\n\n/**\n * Instrument outgoing HTTP(S) requests by old-school monkey-patching the `http` module.\n * This is the fallback for runtimes that do not fully support the `node:http` client diagnostics channel\n * (Node < 22.12).\n */\nfunction instrumentHttpOutgoingRequestsViaMonkeyPatching(options: HttpInstrumentationOptions): void {\n // Patching http also patches https, as this uses the same underlying object\n patchHttpModuleClient(http, options);\n}\n"],"names":["NODE_VERSION","isTracingSuppressed","getRequestOptions","context","trace","errorMonitor","HTTP_ON_CLIENT_REQUEST","getHttpClientSubscriptions","unsubscribe","subscribe","patchHttpModuleClient"],"mappings":";;;;;;;;;AAgBA,MAAM,uCAAA,GACHA,wBAAA,CAAa,KAAA,KAAU,EAAA,IAAMA,yBAAa,KAAA,IAAS,EAAA,IACnDA,wBAAA,CAAa,KAAA,KAAU,EAAA,IAAMA,wBAAA,CAAa,KAAA,IAAS,CAAA,IACpD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CAAM,OAAA,EAAS,IAAI,CAAA;AAAA,UACnC,CAAC,CAAA;AAAA,QACH;AAAA,OACD,CAAA;AAGD,MAAA,OAAA,CAAQ,IAAA,GAAO,OAAA;AAAA,IACjB,CAAA;AAAA,IACA,oBAAA,CAAqB,MAAM,QAAA,EAAU;AACnC,MAAA,OAAA,CAAQ,oBAAA,GAAuB,MAAM,QAAQ,CAAA;AAAA,IAC/C,CAAA;AAAA,kBACAE,wBAAA;AAAA;AAAA,IAEA;AAAA,GACF;AAEA,EAAA,IAAI,uCAAA,EAAyC;AAC3C,IAAA,wCAAA,CAAyC,YAAY,CAAA;AAAA,EACvD,CAAA,MAAO;AACL,IAAA,+CAAA,CAAgD,YAAY,CAAA;AAAA,EAC9D;AACF;AAEA,IAAI,gBAAA;AACJ,SAAS,yCAAyC,OAAA,EAA2C;AAC3F,EAAA,MAAM,EAAE,CAACC,2BAAsB,GAAG,0BAAA,EAA2B,GAAIC,gCAA2B,OAAO,CAAA;AAGnG,EAAA,IAAI,gBAAA,EAAkB;AACpB,IAAAC,8BAAA,CAAYF,6BAAwB,gBAAgB,CAAA;AAAA,EACtD;AAEA,EAAAG,4BAAA,CAAUH,6BAAwB,0BAA0B,CAAA;AAC5D,EAAA,gBAAA,GAAmB,0BAAA;AACrB;AAOA,SAAS,gDAAgD,OAAA,EAA2C;AAElG,EAAAI,0BAAA,CAAsB,MAAM,OAAO,CAAA;AACrC;;;;"}
|
|
1
|
+
{"version":3,"file":"SentryHttpInstrumentation.js","sources":["../../../../src/integrations/http/SentryHttpInstrumentation.ts"],"sourcesContent":["import { subscribe } from 'node:diagnostics_channel';\nimport { context, trace } from '@opentelemetry/api';\nimport type { ClientRequest, IncomingMessage } from 'node:http';\nimport type { HttpClientRequest, HttpIncomingMessage, HttpInstrumentationOptions, Span } from '@sentry/core';\nimport {\n getHttpClientSubscriptions,\n patchHttpModuleClient,\n getRequestOptions,\n isTracingSuppressed,\n} from '@sentry/core';\nimport { HTTP_ON_CLIENT_REQUEST } from '@sentry/core';\nimport { NODE_VERSION } from '../../nodeVersion';\nimport { errorMonitor } from 'node:events';\nimport * as http from 'node:http';\n\nconst FULLY_SUPPORTS_HTTP_DIAGNOSTICS_CHANNEL =\n (NODE_VERSION.major === 22 && NODE_VERSION.minor >= 12) ||\n (NODE_VERSION.major === 23 && NODE_VERSION.minor >= 2) ||\n NODE_VERSION.major >= 24;\n\nexport interface OutgoingHttpRequestInstrumentationOptions {\n /**\n * Whether breadcrumbs should be recorded for outgoing requests.\n *\n * @default `true`\n */\n breadcrumbs?: boolean;\n\n /**\n * Whether to create spans for outgoing requests.\n *\n * @default `true`\n */\n spans?: boolean;\n\n /**\n * Whether to propagate Sentry trace headers in outgoing requests.\n *\n * @default `true`\n */\n tracePropagation?: boolean;\n\n /**\n * Do not instrument outgoing HTTP requests to URLs where the given callback returns `true`.\n * When it returns `true`, the request is skipped entirely: no breadcrumb and no span are created,\n * and no trace headers are propagated for that request.\n *\n * @param url Contains the entire URL, including query string (if any), protocol, host, etc. of the outgoing request.\n * @param request Contains the {@type RequestOptions} object used to make the outgoing request.\n */\n ignoreOutgoingRequests?: (url: string, request: http.RequestOptions) => boolean;\n\n /**\n * Hooks for outgoing request spans, only called when spans are created for outgoing requests\n * (i.e. when `spans` is enabled).\n */\n outgoingRequestHook?: (span: Span, request: ClientRequest) => void;\n outgoingResponseHook?: (span: Span, response: IncomingMessage) => void;\n outgoingRequestApplyCustomAttributes?: (\n span: Span,\n request: HttpClientRequest,\n response: HttpIncomingMessage,\n ) => void;\n}\n\n/**\n * This instruments the http modules for outgoing requests.\n * It uses the diagnostics channel if available, otherwise it falls back to monkey-patching.\n *\n * The instrumentation will start spans, create breadcrumbs, and propagate trace headers in outgoing requests (depending on the settings).\n */\nexport function instrumentHttpOutgoingRequests(\n instrumentationOptions: OutgoingHttpRequestInstrumentationOptions = {},\n): void {\n const { outgoingRequestApplyCustomAttributes: applyCustomAttributesOnSpan, ...options } = instrumentationOptions;\n const patchOptions = {\n applyCustomAttributesOnSpan,\n ...options,\n tracePropagation: options.tracePropagation ?? true,\n spans: options.spans ?? true,\n ignoreOutgoingRequests(url, request) {\n return isTracingSuppressed() || !!options.ignoreOutgoingRequests?.(url, getRequestOptions(request));\n },\n outgoingRequestHook(span, request) {\n options.outgoingRequestHook?.(span, request as ClientRequest);\n // We monkey-patch `req.once('response'), which is used to trigger\n // the callback of the request, so that it runs in the active context\n // eslint-disable-next-line @typescript-eslint/unbound-method, typescript/no-deprecated\n const originalOnce = request.once;\n\n const newOnce = new Proxy(originalOnce, {\n apply(target, thisArg, args: Parameters<typeof originalOnce>) {\n const [event] = args;\n if (event !== 'response') {\n return target.apply(thisArg, args);\n }\n\n const parentContext = context.active();\n const requestContext = trace.setSpan(parentContext, span);\n\n return context.with(requestContext, () => {\n return target.apply(thisArg, args);\n });\n },\n });\n\n // eslint-disable-next-line typescript/no-deprecated\n request.once = newOnce;\n },\n outgoingResponseHook(span, response) {\n options.outgoingResponseHook?.(span, response as IncomingMessage);\n },\n errorMonitor,\n // Pass these in to detect OTel double-wrapping if we're enabling spans\n http,\n } satisfies HttpInstrumentationOptions;\n\n if (FULLY_SUPPORTS_HTTP_DIAGNOSTICS_CHANNEL) {\n instrumentHttpOutgoingRequestsViaChannel(patchOptions);\n } else {\n instrumentHttpOutgoingRequestsViaMonkeyPatching(patchOptions);\n }\n}\n\nfunction instrumentHttpOutgoingRequestsViaChannel(options: HttpInstrumentationOptions): void {\n const { [HTTP_ON_CLIENT_REQUEST]: onHttpClientRequestCreated } = getHttpClientSubscriptions(options);\n subscribe(HTTP_ON_CLIENT_REQUEST, onHttpClientRequestCreated);\n}\n\n/**\n * Instrument outgoing HTTP(S) requests by old-school monkey-patching the `http` module.\n * This is the fallback for runtimes that do not fully support the `node:http` client diagnostics channel\n * (Node < 22.12).\n */\nfunction instrumentHttpOutgoingRequestsViaMonkeyPatching(options: HttpInstrumentationOptions): void {\n // Patching http also patches https, as this uses the same underlying object\n patchHttpModuleClient(http, options);\n}\n"],"names":["NODE_VERSION","isTracingSuppressed","getRequestOptions","context","trace","errorMonitor","HTTP_ON_CLIENT_REQUEST","getHttpClientSubscriptions","subscribe","patchHttpModuleClient"],"mappings":";;;;;;;;;AAeA,MAAM,uCAAA,GACHA,wBAAA,CAAa,KAAA,KAAU,EAAA,IAAMA,yBAAa,KAAA,IAAS,EAAA,IACnDA,wBAAA,CAAa,KAAA,KAAU,EAAA,IAAMA,wBAAA,CAAa,KAAA,IAAS,CAAA,IACpDA,yBAAa,KAAA,IAAS,EAAA;AAqDjB,SAAS,8BAAA,CACd,sBAAA,GAAoE,EAAC,EAC/D;AACN,EAAA,MAAM,EAAE,oCAAA,EAAsC,2BAAA,EAA6B,GAAG,SAAQ,GAAI,sBAAA;AAC1F,EAAA,MAAM,YAAA,GAAe;AAAA,IACnB,2BAAA;AAAA,IACA,GAAG,OAAA;AAAA,IACH,gBAAA,EAAkB,QAAQ,gBAAA,IAAoB,IAAA;AAAA,IAC9C,KAAA,EAAO,QAAQ,KAAA,IAAS,IAAA;AAAA,IACxB,sBAAA,CAAuB,KAAK,OAAA,EAAS;AACnC,MAAA,OAAOC,wBAAA,MAAyB,CAAC,CAAC,QAAQ,sBAAA,GAAyB,GAAA,EAAKC,sBAAA,CAAkB,OAAO,CAAC,CAAA;AAAA,IACpG,CAAA;AAAA,IACA,mBAAA,CAAoB,MAAM,OAAA,EAAS;AACjC,MAAA,OAAA,CAAQ,mBAAA,GAAsB,MAAM,OAAwB,CAAA;AAI5D,MAAA,MAAM,eAAe,OAAA,CAAQ,IAAA;AAE7B,MAAA,MAAM,OAAA,GAAU,IAAI,KAAA,CAAM,YAAA,EAAc;AAAA,QACtC,KAAA,CAAM,MAAA,EAAQ,OAAA,EAAS,IAAA,EAAuC;AAC5D,UAAA,MAAM,CAAC,KAAK,CAAA,GAAI,IAAA;AAChB,UAAA,IAAI,UAAU,UAAA,EAAY;AACxB,YAAA,OAAO,MAAA,CAAO,KAAA,CAAM,OAAA,EAAS,IAAI,CAAA;AAAA,UACnC;AAEA,UAAA,MAAM,aAAA,GAAgBC,YAAQ,MAAA,EAAO;AACrC,UAAA,MAAM,cAAA,GAAiBC,SAAA,CAAM,OAAA,CAAQ,aAAA,EAAe,IAAI,CAAA;AAExD,UAAA,OAAOD,WAAA,CAAQ,IAAA,CAAK,cAAA,EAAgB,MAAM;AACxC,YAAA,OAAO,MAAA,CAAO,KAAA,CAAM,OAAA,EAAS,IAAI,CAAA;AAAA,UACnC,CAAC,CAAA;AAAA,QACH;AAAA,OACD,CAAA;AAGD,MAAA,OAAA,CAAQ,IAAA,GAAO,OAAA;AAAA,IACjB,CAAA;AAAA,IACA,oBAAA,CAAqB,MAAM,QAAA,EAAU;AACnC,MAAA,OAAA,CAAQ,oBAAA,GAAuB,MAAM,QAA2B,CAAA;AAAA,IAClE,CAAA;AAAA,kBACAE,wBAAA;AAAA;AAAA,IAEA;AAAA,GACF;AAEA,EAAA,IAAI,uCAAA,EAAyC;AAC3C,IAAA,wCAAA,CAAyC,YAAY,CAAA;AAAA,EACvD,CAAA,MAAO;AACL,IAAA,+CAAA,CAAgD,YAAY,CAAA;AAAA,EAC9D;AACF;AAEA,SAAS,yCAAyC,OAAA,EAA2C;AAC3F,EAAA,MAAM,EAAE,CAACC,2BAAsB,GAAG,0BAAA,EAA2B,GAAIC,gCAA2B,OAAO,CAAA;AACnG,EAAAC,4BAAA,CAAUF,6BAAwB,0BAA0B,CAAA;AAC9D;AAOA,SAAS,gDAAgD,OAAA,EAA2C;AAElG,EAAAG,0BAAA,CAAsB,MAAM,OAAO,CAAA;AACrC;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"httpServerIntegration.js","sources":["../../../../src/integrations/http/httpServerIntegration.ts"],"sourcesContent":["import { subscribe } from 'node:diagnostics_channel';\nimport type { RequestOptions } from 'node:http';\nimport { context, createContextKey, propagation } from '@opentelemetry/api';\nimport type { HttpIncomingMessage, HttpServerResponse, Integration, IntegrationFn } from '@sentry/core';\nimport {\n addNonEnumerableProperty,\n debug,\n getClient,\n getHttpServerSubscriptions,\n HTTP_ON_SERVER_REQUEST,\n recordRequestSession,\n} from '@sentry/core';\nimport type { RequestEventData } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\n\n// Re-export so existing test imports continue to work; the implementation now lives in core.\nexport { recordRequestSession };\n\nconst HTTP_SERVER_INSTRUMENTED_KEY = createContextKey('sentry_http_server_instrumented');\nconst INTEGRATION_NAME = 'Http.Server' as const;\n\n// Inlining this type to not depend on newer TS types\ninterface WeakRefImpl<T> {\n deref(): T | undefined;\n}\n\ntype StartSpanCallback = (next: () => boolean) => boolean;\ntype RequestWithOptionalStartSpanCallback = HttpIncomingMessage & {\n _startSpanCallback?: WeakRefImpl<StartSpanCallback>;\n};\n\nexport interface HttpServerIntegrationOptions {\n /**\n * Whether the integration should create [Sessions](https://docs.sentry.io/product/releases/health/#sessions) for incoming requests to track the health and crash-free rate of your releases in Sentry.\n * Read more about Release Health: https://docs.sentry.io/product/releases/health/\n *\n * Defaults to `true`.\n */\n sessions?: boolean;\n\n /**\n * Number of milliseconds until sessions tracked with `
|
|
1
|
+
{"version":3,"file":"httpServerIntegration.js","sources":["../../../../src/integrations/http/httpServerIntegration.ts"],"sourcesContent":["import { subscribe } from 'node:diagnostics_channel';\nimport type { RequestOptions } from 'node:http';\nimport { context, createContextKey, propagation } from '@opentelemetry/api';\nimport type { HttpIncomingMessage, HttpServerResponse, Integration, IntegrationFn } from '@sentry/core';\nimport {\n addNonEnumerableProperty,\n debug,\n getClient,\n getHttpServerSubscriptions,\n HTTP_ON_SERVER_REQUEST,\n recordRequestSession,\n} from '@sentry/core';\nimport type { RequestEventData } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\n\n// Re-export so existing test imports continue to work; the implementation now lives in core.\nexport { recordRequestSession };\n\nconst HTTP_SERVER_INSTRUMENTED_KEY = createContextKey('sentry_http_server_instrumented');\nconst INTEGRATION_NAME = 'Http.Server' as const;\n\n// Inlining this type to not depend on newer TS types\ninterface WeakRefImpl<T> {\n deref(): T | undefined;\n}\n\ntype StartSpanCallback = (next: () => boolean) => boolean;\ntype RequestWithOptionalStartSpanCallback = HttpIncomingMessage & {\n _startSpanCallback?: WeakRefImpl<StartSpanCallback>;\n};\n\nexport interface HttpServerIntegrationOptions {\n /**\n * Whether the integration should create [Sessions](https://docs.sentry.io/product/releases/health/#sessions) for incoming requests to track the health and crash-free rate of your releases in Sentry.\n * Read more about Release Health: https://docs.sentry.io/product/releases/health/\n *\n * Defaults to `true`.\n */\n sessions?: boolean;\n\n /**\n * Number of milliseconds until sessions tracked with `sessions` will be flushed as a session aggregate.\n *\n * Defaults to `60000` (60s).\n */\n sessionFlushingDelayMS?: number;\n\n /**\n * Do not capture the request body for incoming HTTP requests to URLs where the given callback returns `true`.\n * This can be useful for long running requests where the body is not needed and we want to avoid capturing it.\n *\n * @param url Contains the entire URL, including query string (if any), protocol, host, etc. of the incoming request.\n * @param request Contains the {@type RequestOptions} object used to make the incoming request.\n */\n ignoreRequestBody?: (url: string, request: RequestOptions) => boolean;\n\n /**\n * Controls the maximum size of incoming HTTP request bodies attached to events.\n *\n * Available options:\n * - 'none': No request bodies will be attached\n * - 'small': Request bodies up to 1,000 bytes will be attached\n * - 'medium': Request bodies up to 10,000 bytes will be attached (default)\n * - 'always': Request bodies will always be attached\n *\n * Note that even with 'always' setting, bodies exceeding 1MB will never be attached\n * for performance and security reasons.\n *\n * @default 'medium'\n */\n maxRequestBodySize?: 'none' | 'small' | 'medium' | 'always';\n}\n\n/**\n * Add a callback to the request object that will be called when the request is started.\n * The callback will receive the next function to continue processing the request.\n */\nexport function addStartSpanCallback(request: RequestWithOptionalStartSpanCallback, callback: StartSpanCallback): void {\n addNonEnumerableProperty(request, '_startSpanCallback', new WeakRef(callback));\n}\n\nconst _httpServerIntegration = ((options: HttpServerIntegrationOptions = {}) => {\n const _options = {\n sessions: options.sessions ?? true,\n sessionFlushingDelayMS: options.sessionFlushingDelayMS ?? 60_000,\n maxRequestBodySize: options.maxRequestBodySize,\n // Server spans are created by `httpServerSpansIntegration` via the\n // `httpServerRequest` client event + `_startSpanCallback`, not by the\n // core subscription helper. Explicitly opt out so the helper does not\n // double-create spans when the client has tracing enabled.\n spans: false as const,\n // Cast: core uses HttpIncomingMessage; node consumers pass\n // RequestOptions-typed callbacks.\n // The two are structurally compatible for the fields the callback reads\n // (url, method, headers).\n ignoreRequestBody: options.ignoreRequestBody as\n | ((url: string, request: HttpIncomingMessage) => boolean)\n | undefined,\n\n /**\n * Hook called by core's `instrumentServer` to wrap the upstream\n * `emit('request')` call.\n *\n * We use it to extract OTel context from request headers and re-enter\n * the OTel context before the framework sees the request, so subsequent\n * spans (eg from `httpServerSpansIntegration`) attach to the right trace.\n */\n wrapServerEmitRequest(\n request: HttpIncomingMessage,\n response: HttpServerResponse,\n normalizedRequest: RequestEventData,\n next: () => void,\n ): void {\n const client = getClient();\n if (!client) return next();\n\n // Guard against double-wrapping: if our wrapper somehow runs inside an\n // already-instrumented context, just continue without re-extracting\n // and re-emitting.\n if (context.active().getValue(HTTP_SERVER_INSTRUMENTED_KEY)) {\n return next();\n }\n\n const ctx = propagation\n .extract(context.active(), normalizedRequest.headers)\n .setValue(HTTP_SERVER_INSTRUMENTED_KEY, true);\n\n context.with(ctx, () => {\n // httpServerSpansIntegration listens for this and may attach\n // `_startSpanCallback` to the request to wrap span creation around\n // the emit.\n client.emit('httpServerRequest', request, response, normalizedRequest);\n\n const callback = (request as RequestWithOptionalStartSpanCallback)._startSpanCallback?.deref();\n if (callback) {\n callback(() => {\n next();\n return true;\n });\n } else {\n next();\n }\n });\n },\n };\n\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n const { [HTTP_ON_SERVER_REQUEST]: onHttpServerRequestStart } = getHttpServerSubscriptions(_options);\n subscribe(HTTP_ON_SERVER_REQUEST, onHttpServerRequestStart);\n },\n afterAllSetup(client) {\n if (DEBUG_BUILD && client.getIntegrationByName('Http')) {\n debug.warn(\n 'It seems that you have manually added `httpServerIntegration` while `httpIntegration` is also present. Make sure to remove `httpServerIntegration` when adding `httpIntegration`.',\n );\n }\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * This integration handles request isolation, trace continuation and other core Sentry functionality around incoming http requests\n * handled via the node `http` module.\n *\n * This version uses OpenTelemetry for context propagation and span management.\n *\n * @see {@link ../../light/integrations/httpServerIntegration.ts} for the lightweight version without OpenTelemetry\n */\nexport const httpServerIntegration = _httpServerIntegration as (\n options?: HttpServerIntegrationOptions,\n) => Integration & {\n name: 'Http.Server';\n setupOnce: () => void;\n};\n"],"names":["createContextKey","addNonEnumerableProperty","getClient","context","propagation","HTTP_ON_SERVER_REQUEST","getHttpServerSubscriptions","subscribe","DEBUG_BUILD","debug"],"mappings":";;;;;;;AAkBA,MAAM,4BAAA,GAA+BA,qBAAiB,iCAAiC,CAAA;AACvF,MAAM,gBAAA,GAAmB,aAAA;AA0DlB,SAAS,oBAAA,CAAqB,SAA+C,QAAA,EAAmC;AACrH,EAAAC,6BAAA,CAAyB,OAAA,EAAS,oBAAA,EAAsB,IAAI,OAAA,CAAQ,QAAQ,CAAC,CAAA;AAC/E;AAEA,MAAM,sBAAA,IAA0B,CAAC,OAAA,GAAwC,EAAC,KAAM;AAC9E,EAAA,MAAM,QAAA,GAAW;AAAA,IACf,QAAA,EAAU,QAAQ,QAAA,IAAY,IAAA;AAAA,IAC9B,sBAAA,EAAwB,QAAQ,sBAAA,IAA0B,GAAA;AAAA,IAC1D,oBAAoB,OAAA,CAAQ,kBAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAK5B,KAAA,EAAO,KAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAKP,mBAAmB,OAAA,CAAQ,iBAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAY3B,qBAAA,CACE,OAAA,EACA,QAAA,EACA,iBAAA,EACA,IAAA,EACM;AACN,MAAA,MAAM,SAASC,cA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O,MAAM,qBAAA,GAAwB;;;;;;"}
|
|
@@ -17,7 +17,6 @@ const _httpServerSpansIntegration = ((options = {}) => {
|
|
|
17
17
|
[305, 399]
|
|
18
18
|
];
|
|
19
19
|
const { onSpanCreated } = options;
|
|
20
|
-
const { requestHook, responseHook, applyCustomAttributesOnSpan } = options.instrumentation ?? {};
|
|
21
20
|
return {
|
|
22
21
|
name: INTEGRATION_NAME,
|
|
23
22
|
setup(client) {
|
|
@@ -39,51 +38,42 @@ const _httpServerSpansIntegration = ((options = {}) => {
|
|
|
39
38
|
const urlObj = core.parseStringToURLObject(fullUrl);
|
|
40
39
|
const headers = request.headers;
|
|
41
40
|
const userAgent = headers["user-agent"];
|
|
42
|
-
const ips = headers["x-forwarded-for"];
|
|
43
41
|
const httpVersion = request.httpVersion;
|
|
44
42
|
const host = headers.host;
|
|
45
43
|
const hostname = host?.replace(/^(.*)(:[0-9]{1,5})/, "$1") || "localhost";
|
|
46
44
|
const scheme = fullUrl.startsWith("https") ? "https" : "http";
|
|
47
|
-
const
|
|
45
|
+
const requestMethod = normalizedRequest.method || request.method?.toUpperCase();
|
|
46
|
+
const method = requestMethod || "GET";
|
|
48
47
|
const httpTargetWithoutQueryFragment = urlObj ? urlObj.pathname : core.stripUrlQueryAndFragment(fullUrl);
|
|
49
48
|
const bestEffortTransactionName = `${method} ${httpTargetWithoutQueryFragment}`;
|
|
50
49
|
const query = core.getUrlQuery(urlObj?.search);
|
|
51
50
|
const fragment = core.getUrlFragment(urlObj?.hash);
|
|
52
51
|
const span = core.startInactiveSpan({
|
|
53
|
-
|
|
52
|
+
// With span streaming, span names have to be low cardinality, so we can't fall back to the URL path.
|
|
53
|
+
// Route instrumentations rename the span to `${method} ${route}` once a route is known.
|
|
54
|
+
name: core.hasSpanStreamingEnabled(client) ? requestMethod || core.HTTP_SPAN_NAME_FALLBACK : bestEffortTransactionName,
|
|
54
55
|
attributes: {
|
|
55
56
|
// Sentry specific attributes
|
|
56
57
|
[attributes.SENTRY_KIND]: "server",
|
|
57
58
|
[core.SEMANTIC_ATTRIBUTE_SENTRY_OP]: "http.server",
|
|
58
|
-
[
|
|
59
|
-
[core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.http.
|
|
59
|
+
[attributes.SENTRY_SEGMENT_NAME_SOURCE]: "url",
|
|
60
|
+
[core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.http.http_server",
|
|
60
61
|
[attributes.SENTRY_HTTP_PREFETCH]: isKnownPrefetchRequest(request) || void 0,
|
|
61
62
|
[attributes.URL_FULL]: core.filterCollectedUrl(fullUrl, client),
|
|
62
63
|
[attributes.URL_PATH]: urlObj?.pathname ?? httpTargetWithoutQueryFragment,
|
|
63
64
|
[attributes.URL_QUERY]: core.filterCollectedUrlQuery(query, client),
|
|
64
65
|
[attributes.URL_FRAGMENT]: fragment,
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
[attributes.
|
|
68
|
-
[attributes.
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
),
|
|
72
|
-
|
|
73
|
-
[attributes.NET_HOST_NAME]: hostname,
|
|
74
|
-
[attributes.HTTP_CLIENT_IP]: typeof ips === "string" ? ips.split(",")[0] : void 0,
|
|
75
|
-
[attributes.HTTP_USER_AGENT]: userAgent,
|
|
76
|
-
[attributes.HTTP_SCHEME]: scheme,
|
|
77
|
-
[attributes.HTTP_FLAVOR]: httpVersion,
|
|
78
|
-
[attributes.NET_TRANSPORT]: httpVersion?.toUpperCase() === "QUIC" ? "ip_udp" : "ip_tcp",
|
|
79
|
-
/* eslint-enable typescript/no-deprecated */
|
|
80
|
-
...getRequestContentLengthAttribute(request),
|
|
66
|
+
[attributes.HTTP_REQUEST_METHOD]: normalizedRequest.method,
|
|
67
|
+
[attributes.USER_AGENT_ORIGINAL]: userAgent,
|
|
68
|
+
[attributes.URL_SCHEME]: scheme,
|
|
69
|
+
[attributes.SERVER_ADDRESS]: hostname,
|
|
70
|
+
[attributes.NETWORK_PROTOCOL_NAME]: "http",
|
|
71
|
+
[attributes.NETWORK_PROTOCOL_VERSION]: httpVersion,
|
|
72
|
+
[attributes.NETWORK_TRANSPORT]: httpVersion?.toUpperCase() === "QUIC" ? "udp" : "tcp",
|
|
73
|
+
"http.request.body.size": core.getContentLengthFromHeaders(request.headers),
|
|
81
74
|
...core.httpHeadersToSpanAttributes(normalizedRequest.headers || {}, client.getDataCollectionOptions())
|
|
82
75
|
}
|
|
83
76
|
});
|
|
84
|
-
requestHook?.(span, request);
|
|
85
|
-
responseHook?.(span, response);
|
|
86
|
-
applyCustomAttributesOnSpan?.(span, request, response);
|
|
87
77
|
onSpanCreated?.(span, request, response);
|
|
88
78
|
return core.withActiveSpan(span, () => {
|
|
89
79
|
core.bindScopeToEmitter(request);
|
|
@@ -94,7 +84,11 @@ const _httpServerSpansIntegration = ((options = {}) => {
|
|
|
94
84
|
return;
|
|
95
85
|
}
|
|
96
86
|
isEnded = true;
|
|
97
|
-
const newAttributes = getIncomingRequestAttributesOnResponse(
|
|
87
|
+
const newAttributes = getIncomingRequestAttributesOnResponse(
|
|
88
|
+
request,
|
|
89
|
+
response,
|
|
90
|
+
client.getDataCollectionOptions().userInfo
|
|
91
|
+
);
|
|
98
92
|
span.setAttributes(newAttributes);
|
|
99
93
|
span.setStatus(status);
|
|
100
94
|
span.end();
|
|
@@ -114,7 +108,7 @@ const _httpServerSpansIntegration = ((options = {}) => {
|
|
|
114
108
|
},
|
|
115
109
|
processEvent(event) {
|
|
116
110
|
if (event.type === "transaction") {
|
|
117
|
-
const statusCode = event.contexts?.trace?.data?.[
|
|
111
|
+
const statusCode = event.contexts?.trace?.data?.[attributes.HTTP_RESPONSE_STATUS_CODE];
|
|
118
112
|
if (typeof statusCode === "number") {
|
|
119
113
|
if (shouldFilterStatusCode(statusCode, ignoreStatusCodes)) {
|
|
120
114
|
debugBuild.DEBUG_BUILD && core.debug.log("Dropping transaction due to status code", statusCode);
|
|
@@ -182,47 +176,27 @@ function shouldIgnoreSpansForIncomingRequest(request, {
|
|
|
182
176
|
}
|
|
183
177
|
return false;
|
|
184
178
|
}
|
|
185
|
-
function
|
|
186
|
-
|
|
187
|
-
if (length == null) {
|
|
188
|
-
return {};
|
|
189
|
-
}
|
|
190
|
-
if (isCompressed(request.headers)) {
|
|
191
|
-
return {
|
|
192
|
-
["http.request_content_length"]: length
|
|
193
|
-
};
|
|
194
|
-
} else {
|
|
195
|
-
return {
|
|
196
|
-
["http.request_content_length_uncompressed"]: length
|
|
197
|
-
};
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
function getContentLength(headers) {
|
|
201
|
-
const contentLengthHeader = headers["content-length"];
|
|
202
|
-
if (contentLengthHeader === void 0) return null;
|
|
203
|
-
const contentLength = parseInt(contentLengthHeader, 10);
|
|
204
|
-
if (isNaN(contentLength)) return null;
|
|
205
|
-
return contentLength;
|
|
179
|
+
function getForwardedClientAddress(forwardedFor) {
|
|
180
|
+
return typeof forwardedFor === "string" ? forwardedFor.split(",")[0]?.trim() || void 0 : void 0;
|
|
206
181
|
}
|
|
207
|
-
function
|
|
208
|
-
const encoding = headers["content-encoding"];
|
|
209
|
-
return !!encoding && encoding !== "identity";
|
|
210
|
-
}
|
|
211
|
-
function getIncomingRequestAttributesOnResponse(request, response) {
|
|
182
|
+
function getIncomingRequestAttributesOnResponse(request, response, collectClientAddress) {
|
|
212
183
|
const { socket } = request;
|
|
213
184
|
const { statusCode, statusMessage } = response;
|
|
214
185
|
const newAttributes = {
|
|
215
186
|
[attributes.HTTP_RESPONSE_STATUS_CODE]: statusCode,
|
|
216
|
-
|
|
217
|
-
[attributes.HTTP_STATUS_CODE]: statusCode,
|
|
218
|
-
"http.status_text": statusMessage?.toUpperCase()
|
|
187
|
+
"http.response.status_text": statusMessage?.toUpperCase()
|
|
219
188
|
};
|
|
189
|
+
if (collectClientAddress) {
|
|
190
|
+
newAttributes[attributes.CLIENT_ADDRESS] = getForwardedClientAddress(request.headers["x-forwarded-for"]) ?? socket?.remoteAddress;
|
|
191
|
+
}
|
|
220
192
|
if (socket) {
|
|
221
193
|
const { localAddress, localPort, remoteAddress, remotePort } = socket;
|
|
222
|
-
newAttributes[attributes.
|
|
223
|
-
newAttributes[attributes.
|
|
224
|
-
newAttributes[attributes.
|
|
225
|
-
newAttributes[attributes.
|
|
194
|
+
newAttributes[attributes.SERVER_PORT] = localPort;
|
|
195
|
+
newAttributes[attributes.NETWORK_LOCAL_ADDRESS] = localAddress;
|
|
196
|
+
newAttributes[attributes.NETWORK_LOCAL_PORT] = localPort;
|
|
197
|
+
newAttributes[attributes.CLIENT_PORT] = remotePort;
|
|
198
|
+
newAttributes[attributes.NETWORK_PEER_ADDRESS] = collectClientAddress ? remoteAddress : void 0;
|
|
199
|
+
newAttributes[attributes.NETWORK_PEER_PORT] = remotePort;
|
|
226
200
|
}
|
|
227
201
|
return newAttributes;
|
|
228
202
|
}
|
|
@@ -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 type { IncomingHttpHeaders } from 'node:http';\nimport {\n HTTP_CLIENT_IP,\n HTTP_FLAVOR,\n HTTP_HOST,\n HTTP_METHOD,\n HTTP_RESPONSE_STATUS_CODE,\n HTTP_SCHEME,\n HTTP_STATUS_CODE,\n HTTP_TARGET,\n HTTP_USER_AGENT,\n NET_HOST_IP,\n NET_HOST_NAME,\n NET_HOST_PORT,\n NET_PEER_IP,\n NET_PEER_PORT,\n NET_TRANSPORT,\n SENTRY_HTTP_PREFETCH,\n URL_FRAGMENT,\n URL_FULL,\n URL_PATH,\n URL_QUERY,\n SENTRY_KIND,\n} from '@sentry/conventions/attributes';\nimport type {\n Event,\n HttpClientRequest,\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 parseStringToURLObject,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n SPAN_STATUS_ERROR,\n stripUrlQueryAndFragment,\n isTracingSuppressed,\n bindScopeToEmitter,\n startInactiveSpan,\n withActiveSpan,\n getUrlFragment,\n getUrlQuery,\n filterCollectedUrl,\n filterCollectedUrlQuery,\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 * @deprecated This is deprecated in favor of `incomingRequestSpanHook`.\n */\n instrumentation?: {\n requestHook?: (span: Span, req: HttpClientRequest | HttpIncomingMessage) => void;\n responseHook?: (span: Span, response: HttpIncomingMessage | HttpServerResponse) => void;\n applyCustomAttributesOnSpan?: (\n span: Span,\n request: HttpClientRequest | HttpIncomingMessage,\n response: HttpIncomingMessage | HttpServerResponse,\n ) => void;\n };\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 // eslint-disable-next-line typescript/no-deprecated\n const { requestHook, responseHook, applyCustomAttributesOnSpan } = options.instrumentation ?? {};\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 ips = headers['x-forwarded-for'];\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 method = normalizedRequest.method || request.method?.toUpperCase() || '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 name: bestEffortTransactionName,\n attributes: {\n // Sentry specific attributes\n [SENTRY_KIND]: 'server',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.server',\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.otel.http',\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 // Old Semantic Conventions attributes - added for compatibility with what `@opentelemetry/instrumentation-http` output before\n /* eslint-disable typescript/no-deprecated */\n [HTTP_METHOD]: normalizedRequest.method,\n [HTTP_TARGET]: filterCollectedUrl(\n urlObj ? `${urlObj.pathname}${urlObj.search}` : httpTargetWithoutQueryFragment,\n client,\n ),\n [HTTP_HOST]: host,\n [NET_HOST_NAME]: hostname,\n [HTTP_CLIENT_IP]: typeof ips === 'string' ? ips.split(',')[0] : undefined,\n [HTTP_USER_AGENT]: userAgent,\n [HTTP_SCHEME]: scheme,\n [HTTP_FLAVOR]: httpVersion,\n [NET_TRANSPORT]: httpVersion?.toUpperCase() === 'QUIC' ? 'ip_udp' : 'ip_tcp',\n /* eslint-enable typescript/no-deprecated */\n ...getRequestContentLengthAttribute(request),\n ...httpHeadersToSpanAttributes(normalizedRequest.headers || {}, client.getDataCollectionOptions()),\n },\n });\n\n // TODO v11: Remove the following three hooks, only onSpanCreated should remain\n requestHook?.(span, request);\n responseHook?.(span, response);\n applyCustomAttributesOnSpan?.(span, request, response);\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(request, response);\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\nfunction getRequestContentLengthAttribute(request: HttpIncomingMessage): SpanAttributes {\n const length = getContentLength(request.headers);\n if (length == null) {\n return {};\n }\n\n if (isCompressed(request.headers)) {\n return {\n ['http.request_content_length']: length,\n };\n } else {\n return {\n ['http.request_content_length_uncompressed']: length,\n };\n }\n}\n\nfunction getContentLength(headers: IncomingHttpHeaders): number | null {\n const contentLengthHeader = headers['content-length'];\n if (contentLengthHeader === undefined) return null;\n\n const contentLength = parseInt(contentLengthHeader, 10);\n if (isNaN(contentLength)) return null;\n\n return contentLength;\n}\n\nfunction isCompressed(headers: IncomingHttpHeaders): boolean {\n const encoding = headers['content-encoding'];\n\n return !!encoding && encoding !== 'identity';\n}\n\nfunction getIncomingRequestAttributesOnResponse(\n request: HttpIncomingMessage,\n response: HttpServerResponse,\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 // eslint-disable-next-line typescript/no-deprecated\n [HTTP_STATUS_CODE]: statusCode,\n 'http.status_text': statusMessage?.toUpperCase(),\n };\n\n if (socket) {\n const { localAddress, localPort, remoteAddress, remotePort } = socket;\n // eslint-disable-next-line typescript/no-deprecated\n newAttributes[NET_HOST_IP] = localAddress;\n // eslint-disable-next-line typescript/no-deprecated\n newAttributes[NET_HOST_PORT] = localPort;\n // eslint-disable-next-line typescript/no-deprecated\n newAttributes[NET_PEER_IP] = remoteAddress;\n // oxlint-disable-next-line typescript/no-deprecated\n newAttributes[NET_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","SENTRY_KIND","SEMANTIC_ATTRIBUTE_SENTRY_OP","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","SENTRY_HTTP_PREFETCH","URL_FULL","filterCollectedUrl","URL_PATH","URL_QUERY","filterCollectedUrlQuery","URL_FRAGMENT","HTTP_METHOD","HTTP_TARGET","HTTP_HOST","NET_HOST_NAME","HTTP_CLIENT_IP","HTTP_USER_AGENT","HTTP_SCHEME","HTTP_FLAVOR","NET_TRANSPORT","httpHeadersToSpanAttributes","withActiveSpan","bindScopeToEmitter","getSpanStatusFromHttpCode","errorMonitor","SPAN_STATUS_ERROR","addStartSpanCallback","isTracingSuppressed","HTTP_RESPONSE_STATUS_CODE","HTTP_STATUS_CODE","NET_HOST_IP","NET_HOST_PORT","NET_PEER_IP","NET_PEER_PORT"],"mappings":";;;;;;;;AA4DA,MAAM,gBAAA,GAAmB,kBAAA;AAuDzB,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,IAAqB;AAAA,IACrD,CAAC,KAAK,GAAG,CAAA;AAAA;AAAA,IAET,CAAC,KAAK,GAAG,CAAA;AAAA,IACT,CAAC,KAAK,GAAG;AAAA,GACX;AAEA,EAAA,MAAM,EAAE,eAAc,GAAI,OAAA;AAE1B,EAAA,MAAM,EAAE,WAAA,EAAa,YAAA,EAAc,6BAA4B,GAAI,OAAA,CAAQ,mBAAmB,EAAC;AAE/F,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,MAAM,MAAA,EAAoB;AAExB,MAAA,IAAI,OAAO,kBAAA,KAAuB,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GAAI,MAAA;AAE/D,IAAA,aAAA,CAAcC,sBAAW,CAAA,GAAI,YAAA;AAE7B,IAAA,aAAA,CAAcC,wBAAa,CAAA,GAAI,SAAA;AAE/B,IAAA,aAAA,CAAcC,sBAAW,CAAA,GAAI,aAAA;AAE7B,IAAA,aAAA,CAAcC,wBAAa,CAAA,GAAI,UAAA;AAAA,EACjC;AAEA,EAAA,OAAO,aAAA;AACT;AAKA,SAAS,sBAAA,CAAuB,YAAoB,kBAAA,EAA4D;AAC9G,EAAA,OAAO,kBAAA,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 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,EAAA,MAAM,yBAAyB,OAAA,CAAQ,sBAAA;AACvC,EAAA,MAAM,iBAAA,GAAoB,QAAQ,iBAAA,IAAqB;AAAA,IACrD,CAAC,KAAK,GAAG,CAAA;AAAA;AAAA,IAET,CAAC,KAAK,GAAG,CAAA;AAAA,IACT,CAAC,KAAK,GAAG;AAAA,GACX;AAEA,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,GAAU,QAAA;AAChB,QAAA,MAAM,QAAA,GAAW,SAAA;AAEjB,QAAA,MAAM,SAAA,GAAY,CAAC,IAAA,KAAiC;AAClD,UAAA,IACE,oCAAoC,OAAA,EAAS;AAAA,YAC3C,kBAAA;AAAA,YACA;AAAA,WACD,CAAA,EACD;AACA,YAAAA,sBAAA,IAAeC,UAAA,CAAM,GAAA,CAAI,gBAAA,EAAkB,6CAAA,EAA+C,QAAQ,GAAG,CAAA;AAC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C7B,IAAA,aAAA,CAAcC,gCAAqB,CAAA,GAAI,YAAA;AACvC,IAAA,aAAA,CAAcC,6BAAkB,CAAA,GAAI,SAAA;AACpC,IAAA,aAAA,CAAcC,sBAAW,CAAA,GAAI,UAAA;AAC7B,IAAA,aAAA,CAAcC,+BAAoB,CAAA,GAAI,oBAAA,GAAuB,aAAA,GAAgB,MAAA;AAC7E,IAAA,aAAA,CAAcC,4BAAiB,CAAA,GAAI,UAAA;AAAA,EACrC;AAEA,EAAA,OAAO,aAAA;AACT;AAKA,SAAS,sBAAA,CAAuB,YAAoB,kBAAA,EAA4D;AAC9G,EAAA,OAAO,kBAAA,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;;;;;"}
|
|
@@ -9,24 +9,9 @@ const SentryHttpInstrumentation = require('./SentryHttpInstrumentation.js');
|
|
|
9
9
|
const INTEGRATION_NAME = "Http";
|
|
10
10
|
const httpIntegration = core.defineIntegration((options = {}) => {
|
|
11
11
|
const spans = options.spans ?? true;
|
|
12
|
-
const
|
|
13
|
-
const
|
|
14
|
-
const
|
|
15
|
-
sessions: options.trackIncomingRequestsAsSessions,
|
|
16
|
-
sessionFlushingDelayMS: options.sessionFlushingDelayMS,
|
|
17
|
-
ignoreRequestBody: options.ignoreIncomingRequestBody,
|
|
18
|
-
maxRequestBodySize: options.maxIncomingRequestBodySize
|
|
19
|
-
};
|
|
20
|
-
const serverSpansOptions = {
|
|
21
|
-
ignoreIncomingRequests: options.ignoreIncomingRequests,
|
|
22
|
-
ignoreStaticAssets: options.ignoreStaticAssets,
|
|
23
|
-
ignoreStatusCodes: options.dropSpansForIncomingRequestStatusCodes,
|
|
24
|
-
// oxlint-disable-next-line typescript/no-deprecated -- pass through the deprecated option for back-compat
|
|
25
|
-
instrumentation: options.instrumentation,
|
|
26
|
-
onSpanCreated: options.incomingRequestSpanHook
|
|
27
|
-
};
|
|
28
|
-
const server = httpServerIntegration.httpServerIntegration(serverOptions);
|
|
29
|
-
const serverSpans = httpServerSpansIntegration.httpServerSpansIntegration(serverSpansOptions);
|
|
12
|
+
const enableServerSpans = spans && !options.disableIncomingRequestSpans;
|
|
13
|
+
const server = httpServerIntegration.httpServerIntegration(options);
|
|
14
|
+
const serverSpans = httpServerSpansIntegration.httpServerSpansIntegration(options);
|
|
30
15
|
return {
|
|
31
16
|
name: INTEGRATION_NAME,
|
|
32
17
|
setup(client) {
|
|
@@ -37,12 +22,10 @@ const httpIntegration = core.defineIntegration((options = {}) => {
|
|
|
37
22
|
},
|
|
38
23
|
setupOnce() {
|
|
39
24
|
server.setupOnce();
|
|
40
|
-
const
|
|
25
|
+
const outgoingRequestOptions = {
|
|
41
26
|
breadcrumbs: options.breadcrumbs,
|
|
42
27
|
spans,
|
|
43
|
-
|
|
44
|
-
// oxlint-disable-next-line typescript/no-deprecated -- deprecated alias kept until removal
|
|
45
|
-
createSpansForOutgoingRequests: spans,
|
|
28
|
+
tracePropagation: options.tracePropagation ?? true,
|
|
46
29
|
ignoreOutgoingRequests: options.ignoreOutgoingRequests,
|
|
47
30
|
outgoingRequestHook: (span, request) => {
|
|
48
31
|
const url = core.getRequestUrlFromClientRequest(request);
|
|
@@ -50,16 +33,15 @@ const httpIntegration = core.defineIntegration((options = {}) => {
|
|
|
50
33
|
const sanitizedUrl = core.stripDataUrlContent(url);
|
|
51
34
|
span.updateName(`${request.method || "GET"} ${sanitizedUrl}`);
|
|
52
35
|
span.setAttributes({
|
|
53
|
-
[core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: "url",
|
|
54
36
|
[attributes.URL_FULL]: sanitizedUrl
|
|
55
37
|
});
|
|
56
38
|
}
|
|
57
|
-
options.
|
|
39
|
+
options.outgoingRequestHook?.(span, request);
|
|
58
40
|
},
|
|
59
|
-
outgoingResponseHook: options.
|
|
60
|
-
outgoingRequestApplyCustomAttributes: options.
|
|
41
|
+
outgoingResponseHook: options.outgoingResponseHook,
|
|
42
|
+
outgoingRequestApplyCustomAttributes: options.outgoingRequestApplyCustomAttributes
|
|
61
43
|
};
|
|
62
|
-
SentryHttpInstrumentation.instrumentHttpOutgoingRequests(
|
|
44
|
+
SentryHttpInstrumentation.instrumentHttpOutgoingRequests(outgoingRequestOptions);
|
|
63
45
|
},
|
|
64
46
|
processEvent(event) {
|
|
65
47
|
return serverSpans.processEvent(event);
|