@opentelemetry/instrumentation-express 0.51.0 → 0.52.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/src/instrumentation.js +7 -10
- package/build/src/instrumentation.js.map +1 -1
- package/build/src/types.d.ts +1 -1
- package/build/src/types.js.map +1 -1
- package/build/src/utils.d.ts +17 -1
- package/build/src/utils.js +69 -1
- package/build/src/utils.js.map +1 -1
- package/build/src/version.d.ts +1 -1
- package/build/src/version.js +1 -1
- package/build/src/version.js.map +1 -1
- package/package.json +13 -9
|
@@ -132,19 +132,16 @@ class ExpressInstrumentation extends instrumentation_1.InstrumentationBase {
|
|
|
132
132
|
return original;
|
|
133
133
|
const patched = function (req, res) {
|
|
134
134
|
const { isLayerPathStored } = (0, utils_1.storeLayerPath)(req, layerPath);
|
|
135
|
-
const
|
|
136
|
-
|
|
137
|
-
.join('')
|
|
138
|
-
// remove duplicate slashes to normalize route
|
|
139
|
-
.replace(/\/{2,}/g, '/');
|
|
135
|
+
const constructedRoute = (0, utils_1.getConstructedRoute)(req);
|
|
136
|
+
const actualMatchedRoute = (0, utils_1.getActualMatchedRoute)(req);
|
|
140
137
|
const attributes = {
|
|
141
|
-
[semantic_conventions_1.ATTR_HTTP_ROUTE]:
|
|
138
|
+
[semantic_conventions_1.ATTR_HTTP_ROUTE]: actualMatchedRoute,
|
|
142
139
|
};
|
|
143
|
-
const metadata = (0, utils_1.getLayerMetadata)(
|
|
140
|
+
const metadata = (0, utils_1.getLayerMetadata)(constructedRoute, layer, layerPath);
|
|
144
141
|
const type = metadata.attributes[AttributeNames_1.AttributeNames.EXPRESS_TYPE];
|
|
145
142
|
const rpcMetadata = (0, core_1.getRPCMetadata)(api_1.context.active());
|
|
146
143
|
if (rpcMetadata?.type === core_1.RPCType.HTTP) {
|
|
147
|
-
rpcMetadata.route =
|
|
144
|
+
rpcMetadata.route = actualMatchedRoute;
|
|
148
145
|
}
|
|
149
146
|
// verify against the config if the layer should be ignored
|
|
150
147
|
if ((0, utils_1.isLayerIgnored)(metadata.name, type, instrumentation.getConfig())) {
|
|
@@ -159,7 +156,7 @@ class ExpressInstrumentation extends instrumentation_1.InstrumentationBase {
|
|
|
159
156
|
const spanName = instrumentation._getSpanName({
|
|
160
157
|
request: req,
|
|
161
158
|
layerType: type,
|
|
162
|
-
route,
|
|
159
|
+
route: constructedRoute,
|
|
163
160
|
}, metadata.name);
|
|
164
161
|
const span = instrumentation.tracer.startSpan(spanName, {
|
|
165
162
|
attributes: Object.assign(attributes, metadata.attributes),
|
|
@@ -171,7 +168,7 @@ class ExpressInstrumentation extends instrumentation_1.InstrumentationBase {
|
|
|
171
168
|
(0, instrumentation_1.safeExecuteInTheMiddle)(() => requestHook(span, {
|
|
172
169
|
request: req,
|
|
173
170
|
layerType: type,
|
|
174
|
-
route,
|
|
171
|
+
route: constructedRoute,
|
|
175
172
|
}), e => {
|
|
176
173
|
if (e) {
|
|
177
174
|
api_1.diag.error('express instrumentation: request hook failed', e);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"instrumentation.js","sourceRoot":"","sources":["../../src/instrumentation.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,8CAA8D;AAC9D,4CAM4B;AAG5B,+DAA4D;AAC5D,2DAAwD;AACxD,mCAMiB;AACjB,kBAAkB;AAClB,uCAA0D;AAC1D,oEAKwC;AACxC,8EAAsE;AACtE,qDAM0B;AAE1B,gDAAgD;AAChD,MAAa,sBAAuB,SAAQ,qCAAiD;IAC3F,YAAY,SAAuC,EAAE;QACnD,KAAK,CAAC,sBAAY,EAAE,yBAAe,EAAE,MAAM,CAAC,CAAC;IAC/C,CAAC;IAED,IAAI;QACF,OAAO;YACL,IAAI,qDAAmC,CACrC,SAAS,EACT,CAAC,YAAY,CAAC,EACd,aAAa,CAAC,EAAE;gBACd,MAAM,4BAA4B,GAChC,OAAO,aAAa,EAAE,MAAM,EAAE,SAAS,EAAE,K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AY,EAAE,GAAG,IAAI,CAAC,SAAS,EAAE,CAAC;QAE1C,IAAI,CAAC,CAAC,YAAY,YAAY,QAAQ,CAAC,EAAE;YACvC,OAAO,WAAW,CAAC;SACpB;QAED,IAAI;YACF,OAAO,YAAY,CAAC,IAAI,EAAE,WAAW,CAAC,IAAI,WAAW,CAAC;SACvD;QAAC,OAAO,GAAG,EAAE;YACZ,UAAI,CAAC,KAAK,CACR,+DAA+D,EAC/D,GAAG,CACJ,CAAC;YACF,OAAO,WAAW,CAAC;SACpB;IACH,CAAC;CACF;AA3TD,wDA2TC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getRPCMetadata, RPCType } from '@opentelemetry/core';\nimport {\n trace,\n context,\n diag,\n Attributes,\n SpanStatusCode,\n} from '@opentelemetry/api';\nimport type * as express from 'express';\nimport { ExpressInstrumentationConfig, ExpressRequestInfo } from './types';\nimport { ExpressLayerType } from './enums/ExpressLayerType';\nimport { AttributeNames } from './enums/AttributeNames';\nimport {\n asErrorAndMessage,\n getLayerMetadata,\n getLayerPath,\n isLayerIgnored,\n storeLayerPath,\n} from './utils';\n/** @knipignore */\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\nimport {\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n isWrapped,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport { ATTR_HTTP_ROUTE } from '@opentelemetry/semantic-conventions';\nimport {\n ExpressLayer,\n ExpressRouter,\n kLayerPatched,\n PatchedRequest,\n _LAYERS_STORE_PROPERTY,\n} from './internal-types';\n\n/** Express instrumentation for OpenTelemetry */\nexport class ExpressInstrumentation extends InstrumentationBase<ExpressInstrumentationConfig> {\n constructor(config: ExpressInstrumentationConfig = {}) {\n super(PACKAGE_NAME, PACKAGE_VERSION, config);\n }\n\n init() {\n return [\n new InstrumentationNodeModuleDefinition(\n 'express',\n ['>=4.0.0 <6'],\n moduleExports => {\n const isExpressWithRouterPrototype =\n typeof moduleExports?.Router?.prototype?.route === 'function';\n const routerProto = isExpressWithRouterPrototype\n ? moduleExports.Router.prototype // Express v5\n : moduleExports.Router; // Express v4\n // patch express.Router.route\n if (isWrapped(routerProto.route)) {\n this._unwrap(routerProto, 'route');\n }\n this._wrap(routerProto, 'route', this._getRoutePatch());\n // patch express.Router.use\n if (isWrapped(routerProto.use)) {\n this._unwrap(routerProto, 'use');\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this._wrap(routerProto, 'use', this._getRouterUsePatch() as any);\n // patch express.Application.use\n if (isWrapped(moduleExports.application.use)) {\n this._unwrap(moduleExports.application, 'use');\n }\n this._wrap(\n moduleExports.application,\n 'use',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this._getAppUsePatch(isExpressWithRouterPrototype) as any\n );\n return moduleExports;\n },\n moduleExports => {\n if (moduleExports === undefined) return;\n const isExpressWithRouterPrototype =\n typeof moduleExports?.Router?.prototype?.route === 'function';\n const routerProto = isExpressWithRouterPrototype\n ? moduleExports.Router.prototype\n : moduleExports.Router;\n this._unwrap(routerProto, 'route');\n this._unwrap(routerProto, 'use');\n this._unwrap(moduleExports.application, 'use');\n }\n ),\n ];\n }\n\n /**\n * Get the patch for Router.route function\n */\n private _getRoutePatch() {\n const instrumentation = this;\n return function (original: express.Router['route']) {\n return function route_trace(\n this: ExpressRouter,\n ...args: Parameters<typeof original>\n ) {\n const route = original.apply(this, args);\n const layer = this.stack[this.stack.length - 1] as ExpressLayer;\n instrumentation._applyPatch(layer, getLayerPath(args));\n return route;\n };\n };\n }\n\n /**\n * Get the patch for Router.use function\n */\n private _getRouterUsePatch() {\n const instrumentation = this;\n return function (original: express.Router['use']) {\n return function use(\n this: express.Application,\n ...args: Parameters<typeof original>\n ) {\n const route = original.apply(this, args);\n const layer = this.stack[this.stack.length - 1] as ExpressLayer;\n instrumentation._applyPatch(layer, getLayerPath(args));\n return route;\n };\n };\n }\n\n /**\n * Get the patch for Application.use function\n */\n private _getAppUsePatch(isExpressWithRouterPrototype: boolean) {\n const instrumentation = this;\n return function (original: express.Application['use']) {\n return function use(\n // `router` in express@5, `_router` in express@4.\n this: { _router?: ExpressRouter; router?: ExpressRouter },\n ...args: Parameters<typeof original>\n ) {\n // If we access app.router in express 4.x we trigger an assertion error.\n // This property existed in v3, was removed in v4 and then re-added in v5.\n const router = isExpressWithRouterPrototype\n ? this.router\n : this._router;\n const route = original.apply(this, args);\n if (router) {\n const layer = router.stack[router.stack.length - 1];\n instrumentation._applyPatch(layer, getLayerPath(args));\n }\n return route;\n };\n };\n }\n\n /** Patch each express layer to create span and propagate context */\n private _applyPatch(\n this: ExpressInstrumentation,\n layer: ExpressLayer,\n layerPath?: string\n ) {\n const instrumentation = this;\n // avoid patching multiple times the same layer\n if (layer[kLayerPatched] === true) return;\n layer[kLayerPatched] = true;\n\n this._wrap(layer, 'handle', original => {\n // TODO: instrument error handlers\n if (original.length === 4) return original;\n\n const patched = function (\n this: ExpressLayer,\n req: PatchedRequest,\n res: express.Response\n ) {\n const { isLayerPathStored } = storeLayerPath(req, layerPath);\n const route = (req[_LAYERS_STORE_PROPERTY] as string[])\n .filter(path => path !== '/' && path !== '/*')\n .join('')\n // remove duplicate slashes to normalize route\n .replace(/\\/{2,}/g, '/');\n\n const attributes: Attributes = {\n [ATTR_HTTP_ROUTE]: route.length > 0 ? route : '/',\n };\n const metadata = getLayerMetadata(route, layer, layerPath);\n const type = metadata.attributes[\n AttributeNames.EXPRESS_TYPE\n ] as ExpressLayerType;\n\n const rpcMetadata = getRPCMetadata(context.active());\n if (rpcMetadata?.type === RPCType.HTTP) {\n rpcMetadata.route = route || '/';\n }\n\n // verify against the config if the layer should be ignored\n if (isLayerIgnored(metadata.name, type, instrumentation.getConfig())) {\n if (type === ExpressLayerType.MIDDLEWARE) {\n (req[_LAYERS_STORE_PROPERTY] as string[]).pop();\n }\n return original.apply(this, arguments);\n }\n\n if (trace.getSpan(context.active()) === undefined) {\n return original.apply(this, arguments);\n }\n\n const spanName = instrumentation._getSpanName(\n {\n request: req,\n layerType: type,\n route,\n },\n metadata.name\n );\n const span = instrumentation.tracer.startSpan(spanName, {\n attributes: Object.assign(attributes, metadata.attributes),\n });\n\n const parentContext = context.active();\n let currentContext = trace.setSpan(parentContext, span);\n\n const { requestHook } = instrumentation.getConfig();\n if (requestHook) {\n safeExecuteInTheMiddle(\n () =>\n requestHook(span, {\n request: req,\n layerType: type,\n route,\n }),\n e => {\n if (e) {\n diag.error('express instrumentation: request hook failed', e);\n }\n },\n true\n );\n }\n\n let spanHasEnded = false;\n // TODO: Fix router spans (getRouterPath does not work properly) to\n // have useful names before removing this branch\n if (\n metadata.attributes[AttributeNames.EXPRESS_TYPE] ===\n ExpressLayerType.ROUTER\n ) {\n span.end();\n spanHasEnded = true;\n currentContext = parentContext;\n }\n // listener for response.on('finish')\n const onResponseFinish = () => {\n if (spanHasEnded === false) {\n spanHasEnded = true;\n span.end();\n }\n };\n\n // verify we have a callback\n const args = Array.from(arguments);\n const callbackIdx = args.findIndex(arg => typeof arg === 'function');\n if (callbackIdx >= 0) {\n arguments[callbackIdx] = function () {\n // express considers anything but an empty value, \"route\" or \"router\"\n // passed to its callback to be an error\n const maybeError = arguments[0];\n const isError = ![undefined, null, 'route', 'router'].includes(\n maybeError\n );\n if (!spanHasEnded && isError) {\n const [error, message] = asErrorAndMessage(maybeError);\n span.recordException(error);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message,\n });\n }\n\n if (spanHasEnded === false) {\n spanHasEnded = true;\n req.res?.removeListener('finish', onResponseFinish);\n span.end();\n }\n if (!(req.route && isError) && isLayerPathStored) {\n (req[_LAYERS_STORE_PROPERTY] as string[]).pop();\n }\n const callback = args[callbackIdx] as Function;\n return context.bind(parentContext, callback).apply(this, arguments);\n };\n }\n\n try {\n return context.bind(currentContext, original).apply(this, arguments);\n } catch (anyError) {\n const [error, message] = asErrorAndMessage(anyError);\n span.recordException(error);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message,\n });\n throw anyError;\n } finally {\n /**\n * At this point if the callback wasn't called, that means either the\n * layer is asynchronous (so it will call the callback later on) or that\n * the layer directly ends the http response, so we'll hook into the \"finish\"\n * event to handle the later case.\n */\n if (!spanHasEnded) {\n res.once('finish', onResponseFinish);\n }\n }\n };\n\n // `handle` isn't just a regular function in some cases. It also contains\n // some properties holding metadata and state so we need to proxy them\n // through through patched function\n // ref: https://github.com/open-telemetry/opentelemetry-js-contrib/issues/1950\n // Also some apps/libs do their own patching before OTEL and have these properties\n // in the proptotype. So we use a `for...in` loop to get own properties and also\n // any enumerable prop in the prototype chain\n // ref: https://github.com/open-telemetry/opentelemetry-js-contrib/issues/2271\n for (const key in original) {\n Object.defineProperty(patched, key, {\n get() {\n return original[key];\n },\n set(value) {\n original[key] = value;\n },\n });\n }\n return patched;\n });\n }\n\n _getSpanName(info: ExpressRequestInfo, defaultName: string) {\n const { spanNameHook } = this.getConfig();\n\n if (!(spanNameHook instanceof Function)) {\n return defaultName;\n }\n\n try {\n return spanNameHook(info, defaultName) ?? defaultName;\n } catch (err) {\n diag.error(\n 'express instrumentation: error calling span name rewrite hook',\n err\n );\n return defaultName;\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"instrumentation.js","sourceRoot":"","sources":["../../src/instrumentation.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,8CAA8D;AAC9D,4CAM4B;AAG5B,+DAA4D;AAC5D,2DAAwD;AACxD,mCAQiB;AACjB,kBAAkB;AAClB,uCAA0D;AAC1D,oEAKwC;AACxC,8EAAsE;AACtE,q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AC,GAAG,KAAK,CAAC;oBACxB,CAAC;iBACF,CAAC,CAAC;aACJ;YACD,OAAO,OAAO,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;IAED,YAAY,CAAC,IAAwB,EAAE,WAAmB;QACxD,MAAM,EAAE,YAAY,EAAE,GAAG,IAAI,CAAC,SAAS,EAAE,CAAC;QAE1C,IAAI,CAAC,CAAC,YAAY,YAAY,QAAQ,CAAC,EAAE;YACvC,OAAO,WAAW,CAAC;SACpB;QAED,IAAI;YACF,OAAO,YAAY,CAAC,IAAI,EAAE,WAAW,CAAC,IAAI,WAAW,CAAC;SACvD;QAAC,OAAO,GAAG,EAAE;YACZ,UAAI,CAAC,KAAK,CACR,+DAA+D,EAC/D,GAAG,CACJ,CAAC;YACF,OAAO,WAAW,CAAC;SACpB;IACH,CAAC;CACF;AAzTD,wDAyTC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getRPCMetadata, RPCType } from '@opentelemetry/core';\nimport {\n trace,\n context,\n diag,\n Attributes,\n SpanStatusCode,\n} from '@opentelemetry/api';\nimport type * as express from 'express';\nimport { ExpressInstrumentationConfig, ExpressRequestInfo } from './types';\nimport { ExpressLayerType } from './enums/ExpressLayerType';\nimport { AttributeNames } from './enums/AttributeNames';\nimport {\n asErrorAndMessage,\n getLayerMetadata,\n getLayerPath,\n isLayerIgnored,\n storeLayerPath,\n getActualMatchedRoute,\n getConstructedRoute,\n} from './utils';\n/** @knipignore */\nimport { PACKAGE_NAME, PACKAGE_VERSION } from './version';\nimport {\n InstrumentationBase,\n InstrumentationNodeModuleDefinition,\n isWrapped,\n safeExecuteInTheMiddle,\n} from '@opentelemetry/instrumentation';\nimport { ATTR_HTTP_ROUTE } from '@opentelemetry/semantic-conventions';\nimport {\n ExpressLayer,\n ExpressRouter,\n kLayerPatched,\n PatchedRequest,\n _LAYERS_STORE_PROPERTY,\n} from './internal-types';\n\n/** Express instrumentation for OpenTelemetry */\nexport class ExpressInstrumentation extends InstrumentationBase<ExpressInstrumentationConfig> {\n constructor(config: ExpressInstrumentationConfig = {}) {\n super(PACKAGE_NAME, PACKAGE_VERSION, config);\n }\n\n init() {\n return [\n new InstrumentationNodeModuleDefinition(\n 'express',\n ['>=4.0.0 <6'],\n moduleExports => {\n const isExpressWithRouterPrototype =\n typeof moduleExports?.Router?.prototype?.route === 'function';\n const routerProto = isExpressWithRouterPrototype\n ? moduleExports.Router.prototype // Express v5\n : moduleExports.Router; // Express v4\n // patch express.Router.route\n if (isWrapped(routerProto.route)) {\n this._unwrap(routerProto, 'route');\n }\n this._wrap(routerProto, 'route', this._getRoutePatch());\n // patch express.Router.use\n if (isWrapped(routerProto.use)) {\n this._unwrap(routerProto, 'use');\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this._wrap(routerProto, 'use', this._getRouterUsePatch() as any);\n // patch express.Application.use\n if (isWrapped(moduleExports.application.use)) {\n this._unwrap(moduleExports.application, 'use');\n }\n this._wrap(\n moduleExports.application,\n 'use',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this._getAppUsePatch(isExpressWithRouterPrototype) as any\n );\n return moduleExports;\n },\n moduleExports => {\n if (moduleExports === undefined) return;\n const isExpressWithRouterPrototype =\n typeof moduleExports?.Router?.prototype?.route === 'function';\n const routerProto = isExpressWithRouterPrototype\n ? moduleExports.Router.prototype\n : moduleExports.Router;\n this._unwrap(routerProto, 'route');\n this._unwrap(routerProto, 'use');\n this._unwrap(moduleExports.application, 'use');\n }\n ),\n ];\n }\n\n /**\n * Get the patch for Router.route function\n */\n private _getRoutePatch() {\n const instrumentation = this;\n return function (original: express.Router['route']) {\n return function route_trace(\n this: ExpressRouter,\n ...args: Parameters<typeof original>\n ) {\n const route = original.apply(this, args);\n const layer = this.stack[this.stack.length - 1] as ExpressLayer;\n instrumentation._applyPatch(layer, getLayerPath(args));\n return route;\n };\n };\n }\n\n /**\n * Get the patch for Router.use function\n */\n private _getRouterUsePatch() {\n const instrumentation = this;\n return function (original: express.Router['use']) {\n return function use(\n this: express.Application,\n ...args: Parameters<typeof original>\n ) {\n const route = original.apply(this, args);\n const layer = this.stack[this.stack.length - 1] as ExpressLayer;\n instrumentation._applyPatch(layer, getLayerPath(args));\n return route;\n };\n };\n }\n\n /**\n * Get the patch for Application.use function\n */\n private _getAppUsePatch(isExpressWithRouterPrototype: boolean) {\n const instrumentation = this;\n return function (original: express.Application['use']) {\n return function use(\n // `router` in express@5, `_router` in express@4.\n this: { _router?: ExpressRouter; router?: ExpressRouter },\n ...args: Parameters<typeof original>\n ) {\n // If we access app.router in express 4.x we trigger an assertion error.\n // This property existed in v3, was removed in v4 and then re-added in v5.\n const router = isExpressWithRouterPrototype\n ? this.router\n : this._router;\n const route = original.apply(this, args);\n if (router) {\n const layer = router.stack[router.stack.length - 1];\n instrumentation._applyPatch(layer, getLayerPath(args));\n }\n return route;\n };\n };\n }\n\n /** Patch each express layer to create span and propagate context */\n private _applyPatch(\n this: ExpressInstrumentation,\n layer: ExpressLayer,\n layerPath?: string\n ) {\n const instrumentation = this;\n // avoid patching multiple times the same layer\n if (layer[kLayerPatched] === true) return;\n layer[kLayerPatched] = true;\n\n this._wrap(layer, 'handle', original => {\n // TODO: instrument error handlers\n if (original.length === 4) return original;\n\n const patched = function (\n this: ExpressLayer,\n req: PatchedRequest,\n res: express.Response\n ) {\n const { isLayerPathStored } = storeLayerPath(req, layerPath);\n\n const constructedRoute = getConstructedRoute(req);\n const actualMatchedRoute = getActualMatchedRoute(req);\n\n const attributes: Attributes = {\n [ATTR_HTTP_ROUTE]: actualMatchedRoute,\n };\n const metadata = getLayerMetadata(constructedRoute, layer, layerPath);\n const type = metadata.attributes[\n AttributeNames.EXPRESS_TYPE\n ] as ExpressLayerType;\n\n const rpcMetadata = getRPCMetadata(context.active());\n if (rpcMetadata?.type === RPCType.HTTP) {\n rpcMetadata.route = actualMatchedRoute;\n }\n\n // verify against the config if the layer should be ignored\n if (isLayerIgnored(metadata.name, type, instrumentation.getConfig())) {\n if (type === ExpressLayerType.MIDDLEWARE) {\n (req[_LAYERS_STORE_PROPERTY] as string[]).pop();\n }\n return original.apply(this, arguments);\n }\n\n if (trace.getSpan(context.active()) === undefined) {\n return original.apply(this, arguments);\n }\n\n const spanName = instrumentation._getSpanName(\n {\n request: req,\n layerType: type,\n route: constructedRoute,\n },\n metadata.name\n );\n const span = instrumentation.tracer.startSpan(spanName, {\n attributes: Object.assign(attributes, metadata.attributes),\n });\n\n const parentContext = context.active();\n let currentContext = trace.setSpan(parentContext, span);\n\n const { requestHook } = instrumentation.getConfig();\n if (requestHook) {\n safeExecuteInTheMiddle(\n () =>\n requestHook(span, {\n request: req,\n layerType: type,\n route: constructedRoute,\n }),\n e => {\n if (e) {\n diag.error('express instrumentation: request hook failed', e);\n }\n },\n true\n );\n }\n\n let spanHasEnded = false;\n // TODO: Fix router spans (getRouterPath does not work properly) to\n // have useful names before removing this branch\n if (\n metadata.attributes[AttributeNames.EXPRESS_TYPE] ===\n ExpressLayerType.ROUTER\n ) {\n span.end();\n spanHasEnded = true;\n currentContext = parentContext;\n }\n // listener for response.on('finish')\n const onResponseFinish = () => {\n if (spanHasEnded === false) {\n spanHasEnded = true;\n span.end();\n }\n };\n\n // verify we have a callback\n const args = Array.from(arguments);\n const callbackIdx = args.findIndex(arg => typeof arg === 'function');\n if (callbackIdx >= 0) {\n arguments[callbackIdx] = function () {\n // express considers anything but an empty value, \"route\" or \"router\"\n // passed to its callback to be an error\n const maybeError = arguments[0];\n const isError = ![undefined, null, 'route', 'router'].includes(\n maybeError\n );\n if (!spanHasEnded && isError) {\n const [error, message] = asErrorAndMessage(maybeError);\n span.recordException(error);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message,\n });\n }\n\n if (spanHasEnded === false) {\n spanHasEnded = true;\n req.res?.removeListener('finish', onResponseFinish);\n span.end();\n }\n if (!(req.route && isError) && isLayerPathStored) {\n (req[_LAYERS_STORE_PROPERTY] as string[]).pop();\n }\n const callback = args[callbackIdx] as Function;\n return context.bind(parentContext, callback).apply(this, arguments);\n };\n }\n\n try {\n return context.bind(currentContext, original).apply(this, arguments);\n } catch (anyError) {\n const [error, message] = asErrorAndMessage(anyError);\n span.recordException(error);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message,\n });\n throw anyError;\n } finally {\n /**\n * At this point if the callback wasn't called, that means either the\n * layer is asynchronous (so it will call the callback later on) or that\n * the layer directly ends the http response, so we'll hook into the \"finish\"\n * event to handle the later case.\n */\n if (!spanHasEnded) {\n res.once('finish', onResponseFinish);\n }\n }\n };\n\n // `handle` isn't just a regular function in some cases. It also contains\n // some properties holding metadata and state so we need to proxy them\n // through through patched function\n // ref: https://github.com/open-telemetry/opentelemetry-js-contrib/issues/1950\n // Also some apps/libs do their own patching before OTEL and have these properties\n // in the proptotype. So we use a `for...in` loop to get own properties and also\n // any enumerable prop in the prototype chain\n // ref: https://github.com/open-telemetry/opentelemetry-js-contrib/issues/2271\n for (const key in original) {\n Object.defineProperty(patched, key, {\n get() {\n return original[key];\n },\n set(value) {\n original[key] = value;\n },\n });\n }\n return patched;\n });\n }\n\n _getSpanName(info: ExpressRequestInfo, defaultName: string) {\n const { spanNameHook } = this.getConfig();\n\n if (!(spanNameHook instanceof Function)) {\n return defaultName;\n }\n\n try {\n return spanNameHook(info, defaultName) ?? defaultName;\n } catch (err) {\n diag.error(\n 'express instrumentation: error calling span name rewrite hook',\n err\n );\n return defaultName;\n }\n }\n}\n"]}
|
package/build/src/types.d.ts
CHANGED
|
@@ -25,7 +25,7 @@ export interface ExpressRequestCustomAttributeFunction {
|
|
|
25
25
|
(span: Span, info: ExpressRequestInfo): void;
|
|
26
26
|
}
|
|
27
27
|
/**
|
|
28
|
-
* Options available for the Express Instrumentation (see [documentation](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/
|
|
28
|
+
* Options available for the Express Instrumentation (see [documentation](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-express#express-instrumentation-options))
|
|
29
29
|
*/
|
|
30
30
|
export interface ExpressInstrumentationConfig extends InstrumentationConfig {
|
|
31
31
|
/** Ignore specific based on their name */
|
package/build/src/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Span } from '@opentelemetry/api';\nimport { InstrumentationConfig } from '@opentelemetry/instrumentation';\nimport { ExpressLayerType } from './enums/ExpressLayerType';\n\nexport type LayerPathSegment = string | RegExp | number;\n\nexport type IgnoreMatcher = string | RegExp | ((name: string) => boolean);\n\nexport type ExpressRequestInfo<T = any> = {\n /** An express request object */\n request: T;\n route: string;\n layerType: ExpressLayerType;\n};\n\nexport type SpanNameHook = (\n info: ExpressRequestInfo,\n /**\n * If no decision is taken based on RequestInfo, the default name\n * supplied by the instrumentation can be used instead.\n */\n defaultName: string\n) => string;\n\n/**\n * Function that can be used to add custom attributes to the current span or the root span on\n * a Express request\n * @param span - The Express middleware layer span.\n * @param info - An instance of ExpressRequestInfo that contains info about the request such as the route, and the layer type.\n */\nexport interface ExpressRequestCustomAttributeFunction {\n (span: Span, info: ExpressRequestInfo): void;\n}\n\n/**\n * Options available for the Express Instrumentation (see [documentation](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Span } from '@opentelemetry/api';\nimport { InstrumentationConfig } from '@opentelemetry/instrumentation';\nimport { ExpressLayerType } from './enums/ExpressLayerType';\n\nexport type LayerPathSegment = string | RegExp | number;\n\nexport type IgnoreMatcher = string | RegExp | ((name: string) => boolean);\n\nexport type ExpressRequestInfo<T = any> = {\n /** An express request object */\n request: T;\n route: string;\n layerType: ExpressLayerType;\n};\n\nexport type SpanNameHook = (\n info: ExpressRequestInfo,\n /**\n * If no decision is taken based on RequestInfo, the default name\n * supplied by the instrumentation can be used instead.\n */\n defaultName: string\n) => string;\n\n/**\n * Function that can be used to add custom attributes to the current span or the root span on\n * a Express request\n * @param span - The Express middleware layer span.\n * @param info - An instance of ExpressRequestInfo that contains info about the request such as the route, and the layer type.\n */\nexport interface ExpressRequestCustomAttributeFunction {\n (span: Span, info: ExpressRequestInfo): void;\n}\n\n/**\n * Options available for the Express Instrumentation (see [documentation](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-express#express-instrumentation-options))\n */\nexport interface ExpressInstrumentationConfig extends InstrumentationConfig {\n /** Ignore specific based on their name */\n ignoreLayers?: IgnoreMatcher[];\n /** Ignore specific layers based on their type */\n ignoreLayersType?: ExpressLayerType[];\n spanNameHook?: SpanNameHook;\n\n /** Function for adding custom attributes on Express request */\n requestHook?: ExpressRequestCustomAttributeFunction;\n}\n"]}
|
package/build/src/utils.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Attributes } from '@opentelemetry/api';
|
|
2
2
|
import { ExpressInstrumentationConfig, LayerPathSegment } from './types';
|
|
3
3
|
import { ExpressLayerType } from './enums/ExpressLayerType';
|
|
4
|
-
import { ExpressLayer, PatchedRequest } from './internal-types';
|
|
4
|
+
import { ExpressLayer, PatchedRequest, _LAYERS_STORE_PROPERTY } from './internal-types';
|
|
5
5
|
/**
|
|
6
6
|
* Store layers path in the request to be able to construct route later
|
|
7
7
|
* @param request The request where
|
|
@@ -50,4 +50,20 @@ export declare const asErrorAndMessage: (error: unknown) => [error: string | Err
|
|
|
50
50
|
* @returns The layer path
|
|
51
51
|
*/
|
|
52
52
|
export declare const getLayerPath: (args: [LayerPathSegment | LayerPathSegment[], ...unknown[]]) => string | undefined;
|
|
53
|
+
export declare function getConstructedRoute(req: {
|
|
54
|
+
originalUrl: PatchedRequest['originalUrl'];
|
|
55
|
+
[_LAYERS_STORE_PROPERTY]?: string[];
|
|
56
|
+
}): string;
|
|
57
|
+
/**
|
|
58
|
+
* Extracts the actual matched route from Express request for OpenTelemetry instrumentation.
|
|
59
|
+
* Returns the route that should be used as the http.route attribute.
|
|
60
|
+
*
|
|
61
|
+
* @param req - The Express request object with layers store
|
|
62
|
+
* @param layersStoreProperty - The property name where layer paths are stored
|
|
63
|
+
* @returns The matched route string or undefined if no valid route is found
|
|
64
|
+
*/
|
|
65
|
+
export declare function getActualMatchedRoute(req: {
|
|
66
|
+
originalUrl: PatchedRequest['originalUrl'];
|
|
67
|
+
[_LAYERS_STORE_PROPERTY]?: string[];
|
|
68
|
+
}): string | undefined;
|
|
53
69
|
//# sourceMappingURL=utils.d.ts.map
|
package/build/src/utils.js
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/
|
|
17
17
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
|
-
exports.getLayerPath = exports.asErrorAndMessage = exports.isLayerIgnored = exports.getLayerMetadata = exports.getRouterPath = exports.storeLayerPath = void 0;
|
|
18
|
+
exports.getActualMatchedRoute = exports.getConstructedRoute = exports.getLayerPath = exports.asErrorAndMessage = exports.isLayerIgnored = exports.getLayerMetadata = exports.getRouterPath = exports.storeLayerPath = void 0;
|
|
19
19
|
const ExpressLayerType_1 = require("./enums/ExpressLayerType");
|
|
20
20
|
const AttributeNames_1 = require("./enums/AttributeNames");
|
|
21
21
|
const internal_types_1 = require("./internal-types");
|
|
@@ -175,4 +175,72 @@ const extractLayerPathSegment = (arg) => {
|
|
|
175
175
|
}
|
|
176
176
|
return;
|
|
177
177
|
};
|
|
178
|
+
function getConstructedRoute(req) {
|
|
179
|
+
const layersStore = Array.isArray(req[internal_types_1._LAYERS_STORE_PROPERTY])
|
|
180
|
+
? req[internal_types_1._LAYERS_STORE_PROPERTY]
|
|
181
|
+
: [];
|
|
182
|
+
const meaningfulPaths = layersStore.filter(path => path !== '/' && path !== '/*');
|
|
183
|
+
if (meaningfulPaths.length === 1 && meaningfulPaths[0] === '*') {
|
|
184
|
+
return '*';
|
|
185
|
+
}
|
|
186
|
+
// Join parts and remove duplicate slashes
|
|
187
|
+
return meaningfulPaths.join('').replace(/\/{2,}/g, '/');
|
|
188
|
+
}
|
|
189
|
+
exports.getConstructedRoute = getConstructedRoute;
|
|
190
|
+
/**
|
|
191
|
+
* Extracts the actual matched route from Express request for OpenTelemetry instrumentation.
|
|
192
|
+
* Returns the route that should be used as the http.route attribute.
|
|
193
|
+
*
|
|
194
|
+
* @param req - The Express request object with layers store
|
|
195
|
+
* @param layersStoreProperty - The property name where layer paths are stored
|
|
196
|
+
* @returns The matched route string or undefined if no valid route is found
|
|
197
|
+
*/
|
|
198
|
+
function getActualMatchedRoute(req) {
|
|
199
|
+
const layersStore = Array.isArray(req[internal_types_1._LAYERS_STORE_PROPERTY])
|
|
200
|
+
? req[internal_types_1._LAYERS_STORE_PROPERTY]
|
|
201
|
+
: [];
|
|
202
|
+
// If no layers are stored, no route can be determined
|
|
203
|
+
if (layersStore.length === 0) {
|
|
204
|
+
return undefined;
|
|
205
|
+
}
|
|
206
|
+
// Handle root path case - if all paths are root, only return root if originalUrl is also root
|
|
207
|
+
// The layer store also includes root paths in case a non-existing url was requested
|
|
208
|
+
if (layersStore.every(path => path === '/')) {
|
|
209
|
+
return req.originalUrl === '/' ? '/' : undefined;
|
|
210
|
+
}
|
|
211
|
+
const constructedRoute = getConstructedRoute(req);
|
|
212
|
+
if (constructedRoute === '*') {
|
|
213
|
+
return constructedRoute;
|
|
214
|
+
}
|
|
215
|
+
// For RegExp routes or route arrays, return the constructed route
|
|
216
|
+
// This handles the case where the route is defined using RegExp or an array
|
|
217
|
+
if (constructedRoute.includes('/') &&
|
|
218
|
+
(constructedRoute.includes(',') ||
|
|
219
|
+
constructedRoute.includes('\\') ||
|
|
220
|
+
constructedRoute.includes('*') ||
|
|
221
|
+
constructedRoute.includes('['))) {
|
|
222
|
+
return constructedRoute;
|
|
223
|
+
}
|
|
224
|
+
// Ensure route starts with '/' if it doesn't already
|
|
225
|
+
const normalizedRoute = constructedRoute.startsWith('/')
|
|
226
|
+
? constructedRoute
|
|
227
|
+
: `/${constructedRoute}`;
|
|
228
|
+
// Validate that this appears to be a matched route
|
|
229
|
+
// A route is considered matched if:
|
|
230
|
+
// 1. We have a constructed route
|
|
231
|
+
// 2. The original URL matches or starts with our route pattern
|
|
232
|
+
const isValidRoute = normalizedRoute.length > 0 &&
|
|
233
|
+
(req.originalUrl === normalizedRoute ||
|
|
234
|
+
req.originalUrl.startsWith(normalizedRoute) ||
|
|
235
|
+
isRoutePattern(normalizedRoute));
|
|
236
|
+
return isValidRoute ? normalizedRoute : undefined;
|
|
237
|
+
}
|
|
238
|
+
exports.getActualMatchedRoute = getActualMatchedRoute;
|
|
239
|
+
/**
|
|
240
|
+
* Checks if a route contains parameter patterns (e.g., :id, :userId)
|
|
241
|
+
* which are valid even if they don't exactly match the original URL
|
|
242
|
+
*/
|
|
243
|
+
function isRoutePattern(route) {
|
|
244
|
+
return route.includes(':') || route.includes('*');
|
|
245
|
+
}
|
|
178
246
|
//# sourceMappingURL=utils.js.map
|
package/build/src/utils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAQH,+DAA4D;AAC5D,2DAAwD;AACxD,qDAI0B;AAE1B;;;;GAIG;AACI,MAAM,cAAc,GAAG,CAC5B,OAAuB,EACvB,KAAc,EACkB,EAAE;IAClC,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,uCAAsB,CAAC,CAAC,KAAK,KAAK,EAAE;QAC5D,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,uCAAsB,EAAE;YACrD,UAAU,EAAE,KAAK;YACjB,KAAK,EAAE,EAAE;SACV,CAAC,CAAC;KACJ;IACD,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,EAAE,iBAAiB,EAAE,KAAK,EAAE,CAAC;IAE5D,OAAO,CAAC,uCAAsB,CAAc,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAE1D,OAAO,EAAE,iBAAiB,EAAE,IAAI,EAAE,CAAC;AACrC,CAAC,CAAC;AAfW,QAAA,cAAc,kBAezB;AAEF;;;;;GAKG;AACI,MAAM,aAAa,GAAG,CAAC,IAAY,EAAE,KAAmB,EAAU,EAAE;IACzE,MAAM,UAAU,GAAG,KAAK,CAAC,MAAM,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC;IAE5C,IAAI,UAAU,EAAE,KAAK,EAAE,IAAI,EAAE;QAC3B,OAAO,GA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IAED,OAAO,KAAK,CAAC;AACf,CAAC,CAAC;AAvBW,QAAA,cAAc,kBAuBzB;AAEF;;;;;GAKG;AACI,MAAM,iBAAiB,GAAG,CAC/B,KAAc,EAC4B,EAAE,CAC5C,KAAK,YAAY,KAAK;IACpB,CAAC,CAAC,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,CAAC;IACxB,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;AALxB,QAAA,iBAAiB,qBAKO;AAErC;;;;;GAKG;AACI,MAAM,YAAY,GAAG,CAC1B,IAA2D,EACvC,EAAE;IACtB,MAAM,QAAQ,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;IAEzB,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE;QAC3B,OAAO,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,CAAC,uBAAuB,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;KAC1E;IAED,OAAO,uBAAuB,CAAC,QAAQ,CAAC,CAAC;AAC3C,CAAC,CAAC;AAVW,QAAA,YAAY,gBAUvB;AAEF,MAAM,uBAAuB,GAAG,CAAC,GAAqB,EAAE,EAAE;IACxD,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;QAC3B,OAAO,GAAG,CAAC;KACZ;IAED,IAAI,GAAG,YAAY,MAAM,IAAI,OAAO,GAAG,KAAK,QAAQ,EAAE;QACpD,OAAO,GAAG,CAAC,QAAQ,EAAE,CAAC;KACvB;IAED,OAAO;AACT,CAAC,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Attributes } from '@opentelemetry/api';\nimport {\n IgnoreMatcher,\n ExpressInstrumentationConfig,\n LayerPathSegment,\n} from './types';\nimport { ExpressLayerType } from './enums/ExpressLayerType';\nimport { AttributeNames } from './enums/AttributeNames';\nimport {\n ExpressLayer,\n PatchedRequest,\n _LAYERS_STORE_PROPERTY,\n} from './internal-types';\n\n/**\n * Store layers path in the request to be able to construct route later\n * @param request The request where\n * @param [value] the value to push into the array\n */\nexport const storeLayerPath = (\n request: PatchedRequest,\n value?: string\n): { isLayerPathStored: boolean } => {\n if (Array.isArray(request[_LAYERS_STORE_PROPERTY]) === false) {\n Object.defineProperty(request, _LAYERS_STORE_PROPERTY, {\n enumerable: false,\n value: [],\n });\n }\n if (value === undefined) return { isLayerPathStored: false };\n\n (request[_LAYERS_STORE_PROPERTY] as string[]).push(value);\n\n return { isLayerPathStored: true };\n};\n\n/**\n * Recursively search the router path from layer stack\n * @param path The path to reconstruct\n * @param layer The layer to reconstruct from\n * @returns The reconstructed path\n */\nexport const getRouterPath = (path: string, layer: ExpressLayer): string => {\n const stackLayer = layer.handle?.stack?.[0];\n\n if (stackLayer?.route?.path) {\n return `${path}${stackLayer.route.path}`;\n }\n\n if (stackLayer?.handle?.stack) {\n return getRouterPath(path, stackLayer);\n }\n\n return path;\n};\n\n/**\n * Parse express layer context to retrieve a name and attributes.\n * @param route The route of the layer\n * @param layer Express layer\n * @param [layerPath] if present, the path on which the layer has been mounted\n */\nexport const getLayerMetadata = (\n route: string,\n layer: ExpressLayer,\n layerPath?: string\n): {\n attributes: Attributes;\n name: string;\n} => {\n if (layer.name === 'router') {\n const maybeRouterPath = getRouterPath('', layer);\n const extractedRouterPath = maybeRouterPath\n ? maybeRouterPath\n : layerPath || route || '/';\n\n return {\n attributes: {\n [AttributeNames.EXPRESS_NAME]: extractedRouterPath,\n [AttributeNames.EXPRESS_TYPE]: ExpressLayerType.ROUTER,\n },\n name: `router - ${extractedRouterPath}`,\n };\n } else if (layer.name === 'bound dispatch' || layer.name === 'handle') {\n return {\n attributes: {\n [AttributeNames.EXPRESS_NAME]:\n (route || layerPath) ?? 'request handler',\n [AttributeNames.EXPRESS_TYPE]: ExpressLayerType.REQUEST_HANDLER,\n },\n name: `request handler${layer.path ? ` - ${route || layerPath}` : ''}`,\n };\n } else {\n return {\n attributes: {\n [AttributeNames.EXPRESS_NAME]: layer.name,\n [AttributeNames.EXPRESS_TYPE]: ExpressLayerType.MIDDLEWARE,\n },\n name: `middleware - ${layer.name}`,\n };\n }\n};\n\n/**\n * Check whether the given obj match pattern\n * @param constant e.g URL of request\n * @param obj obj to inspect\n * @param pattern Match pattern\n */\nconst satisfiesPattern = (\n constant: string,\n pattern: IgnoreMatcher\n): boolean => {\n if (typeof pattern === 'string') {\n return pattern === constant;\n } else if (pattern instanceof RegExp) {\n return pattern.test(constant);\n } else if (typeof pattern === 'function') {\n return pattern(constant);\n } else {\n throw new TypeError('Pattern is in unsupported datatype');\n }\n};\n\n/**\n * Check whether the given request is ignored by configuration\n * It will not re-throw exceptions from `list` provided by the client\n * @param constant e.g URL of request\n * @param [list] List of ignore patterns\n * @param [onException] callback for doing something when an exception has\n * occurred\n */\nexport const isLayerIgnored = (\n name: string,\n type: ExpressLayerType,\n config?: ExpressInstrumentationConfig\n): boolean => {\n if (\n Array.isArray(config?.ignoreLayersType) &&\n config?.ignoreLayersType?.includes(type)\n ) {\n return true;\n }\n if (Array.isArray(config?.ignoreLayers) === false) return false;\n try {\n for (const pattern of config!.ignoreLayers!) {\n if (satisfiesPattern(name, pattern)) {\n return true;\n }\n }\n } catch (e) {\n /* catch block*/\n }\n\n return false;\n};\n\n/**\n * Converts a user-provided error value into an error and error message pair\n *\n * @param error - User-provided error value\n * @returns Both an Error or string representation of the value and an error message\n */\nexport const asErrorAndMessage = (\n error: unknown\n): [error: string | Error, message: string] =>\n error instanceof Error\n ? [error, error.message]\n : [String(error), String(error)];\n\n/**\n * Extracts the layer path from the route arguments\n *\n * @param args - Arguments of the route\n * @returns The layer path\n */\nexport const getLayerPath = (\n args: [LayerPathSegment | LayerPathSegment[], ...unknown[]]\n): string | undefined => {\n const firstArg = args[0];\n\n if (Array.isArray(firstArg)) {\n return firstArg.map(arg => extractLayerPathSegment(arg) || '').join(',');\n }\n\n return extractLayerPathSegment(firstArg);\n};\n\nconst extractLayerPathSegment = (arg: LayerPathSegment) => {\n if (typeof arg === 'string') {\n return arg;\n }\n\n if (arg instanceof RegExp || typeof arg === 'number') {\n return arg.toString();\n }\n\n return;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAQH,+DAA4D;AAC5D,2DAAwD;AACxD,qDAI0B;AAE1B;;;;GAIG;AACI,MAAM,cAAc,GAAG,CAC5B,OAAuB,EACvB,KAAc,EACkB,EAAE;IAClC,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,uCAAsB,CAAC,CAAC,KAAK,KAAK,EAAE;QAC5D,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,uCAAsB,EAAE;YACrD,UAAU,EAAE,KAAK;YACjB,KAAK,EAAE,EAAE;SACV,CAAC,CAAC;KACJ;IACD,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,EAAE,iBAAiB,EAAE,KAAK,EAAE,CAAC;IAE5D,OAAO,CAAC,uCAAsB,CAAc,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAE1D,OAAO,EAAE,iBAAiB,EAAE,IAAI,EAAE,CAAC;AACrC,CAAC,CAAC;AAfW,QAAA,cAAc,kBAezB;AAEF;;;;;GAKG;AACI,MAAM,aAAa,GAAG,CAAC,IAAY,EAAE,KAAmB,EAAU,EAAE;IACzE,MAAM,UAAU,GAAG,KAAK,CAAC,MAAM,EAAE,KAAK,EAAE,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AAC,GAAG,CAAC;YAC7B,gBAAgB,CAAC,QAAQ,CAAC,IAAI,CAAC;YAC/B,gBAAgB,CAAC,QAAQ,CAAC,GAAG,CAAC;YAC9B,gBAAgB,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EACjC;QACA,OAAO,gBAAgB,CAAC;KACzB;IAED,qDAAqD;IACrD,MAAM,eAAe,GAAG,gBAAgB,CAAC,UAAU,CAAC,GAAG,CAAC;QACtD,CAAC,CAAC,gBAAgB;QAClB,CAAC,CAAC,IAAI,gBAAgB,EAAE,CAAC;IAE3B,mDAAmD;IACnD,oCAAoC;IACpC,iCAAiC;IACjC,+DAA+D;IAC/D,MAAM,YAAY,GAChB,eAAe,CAAC,MAAM,GAAG,CAAC;QAC1B,CAAC,GAAG,CAAC,WAAW,KAAK,eAAe;YAClC,GAAG,CAAC,WAAW,CAAC,UAAU,CAAC,eAAe,CAAC;YAC3C,cAAc,CAAC,eAAe,CAAC,CAAC,CAAC;IAErC,OAAO,YAAY,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,SAAS,CAAC;AACpD,CAAC;AApDD,sDAoDC;AAED;;;GAGG;AACH,SAAS,cAAc,CAAC,KAAa;IACnC,OAAO,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;AACpD,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Attributes } from '@opentelemetry/api';\nimport {\n IgnoreMatcher,\n ExpressInstrumentationConfig,\n LayerPathSegment,\n} from './types';\nimport { ExpressLayerType } from './enums/ExpressLayerType';\nimport { AttributeNames } from './enums/AttributeNames';\nimport {\n ExpressLayer,\n PatchedRequest,\n _LAYERS_STORE_PROPERTY,\n} from './internal-types';\n\n/**\n * Store layers path in the request to be able to construct route later\n * @param request The request where\n * @param [value] the value to push into the array\n */\nexport const storeLayerPath = (\n request: PatchedRequest,\n value?: string\n): { isLayerPathStored: boolean } => {\n if (Array.isArray(request[_LAYERS_STORE_PROPERTY]) === false) {\n Object.defineProperty(request, _LAYERS_STORE_PROPERTY, {\n enumerable: false,\n value: [],\n });\n }\n if (value === undefined) return { isLayerPathStored: false };\n\n (request[_LAYERS_STORE_PROPERTY] as string[]).push(value);\n\n return { isLayerPathStored: true };\n};\n\n/**\n * Recursively search the router path from layer stack\n * @param path The path to reconstruct\n * @param layer The layer to reconstruct from\n * @returns The reconstructed path\n */\nexport const getRouterPath = (path: string, layer: ExpressLayer): string => {\n const stackLayer = layer.handle?.stack?.[0];\n\n if (stackLayer?.route?.path) {\n return `${path}${stackLayer.route.path}`;\n }\n\n if (stackLayer?.handle?.stack) {\n return getRouterPath(path, stackLayer);\n }\n\n return path;\n};\n\n/**\n * Parse express layer context to retrieve a name and attributes.\n * @param route The route of the layer\n * @param layer Express layer\n * @param [layerPath] if present, the path on which the layer has been mounted\n */\nexport const getLayerMetadata = (\n route: string,\n layer: ExpressLayer,\n layerPath?: string\n): {\n attributes: Attributes;\n name: string;\n} => {\n if (layer.name === 'router') {\n const maybeRouterPath = getRouterPath('', layer);\n const extractedRouterPath = maybeRouterPath\n ? maybeRouterPath\n : layerPath || route || '/';\n\n return {\n attributes: {\n [AttributeNames.EXPRESS_NAME]: extractedRouterPath,\n [AttributeNames.EXPRESS_TYPE]: ExpressLayerType.ROUTER,\n },\n name: `router - ${extractedRouterPath}`,\n };\n } else if (layer.name === 'bound dispatch' || layer.name === 'handle') {\n return {\n attributes: {\n [AttributeNames.EXPRESS_NAME]:\n (route || layerPath) ?? 'request handler',\n [AttributeNames.EXPRESS_TYPE]: ExpressLayerType.REQUEST_HANDLER,\n },\n name: `request handler${layer.path ? ` - ${route || layerPath}` : ''}`,\n };\n } else {\n return {\n attributes: {\n [AttributeNames.EXPRESS_NAME]: layer.name,\n [AttributeNames.EXPRESS_TYPE]: ExpressLayerType.MIDDLEWARE,\n },\n name: `middleware - ${layer.name}`,\n };\n }\n};\n\n/**\n * Check whether the given obj match pattern\n * @param constant e.g URL of request\n * @param obj obj to inspect\n * @param pattern Match pattern\n */\nconst satisfiesPattern = (\n constant: string,\n pattern: IgnoreMatcher\n): boolean => {\n if (typeof pattern === 'string') {\n return pattern === constant;\n } else if (pattern instanceof RegExp) {\n return pattern.test(constant);\n } else if (typeof pattern === 'function') {\n return pattern(constant);\n } else {\n throw new TypeError('Pattern is in unsupported datatype');\n }\n};\n\n/**\n * Check whether the given request is ignored by configuration\n * It will not re-throw exceptions from `list` provided by the client\n * @param constant e.g URL of request\n * @param [list] List of ignore patterns\n * @param [onException] callback for doing something when an exception has\n * occurred\n */\nexport const isLayerIgnored = (\n name: string,\n type: ExpressLayerType,\n config?: ExpressInstrumentationConfig\n): boolean => {\n if (\n Array.isArray(config?.ignoreLayersType) &&\n config?.ignoreLayersType?.includes(type)\n ) {\n return true;\n }\n if (Array.isArray(config?.ignoreLayers) === false) return false;\n try {\n for (const pattern of config!.ignoreLayers!) {\n if (satisfiesPattern(name, pattern)) {\n return true;\n }\n }\n } catch (e) {\n /* catch block*/\n }\n\n return false;\n};\n\n/**\n * Converts a user-provided error value into an error and error message pair\n *\n * @param error - User-provided error value\n * @returns Both an Error or string representation of the value and an error message\n */\nexport const asErrorAndMessage = (\n error: unknown\n): [error: string | Error, message: string] =>\n error instanceof Error\n ? [error, error.message]\n : [String(error), String(error)];\n\n/**\n * Extracts the layer path from the route arguments\n *\n * @param args - Arguments of the route\n * @returns The layer path\n */\nexport const getLayerPath = (\n args: [LayerPathSegment | LayerPathSegment[], ...unknown[]]\n): string | undefined => {\n const firstArg = args[0];\n\n if (Array.isArray(firstArg)) {\n return firstArg.map(arg => extractLayerPathSegment(arg) || '').join(',');\n }\n\n return extractLayerPathSegment(firstArg);\n};\n\nconst extractLayerPathSegment = (arg: LayerPathSegment) => {\n if (typeof arg === 'string') {\n return arg;\n }\n\n if (arg instanceof RegExp || typeof arg === 'number') {\n return arg.toString();\n }\n\n return;\n};\n\nexport function getConstructedRoute(req: {\n originalUrl: PatchedRequest['originalUrl'];\n [_LAYERS_STORE_PROPERTY]?: string[];\n}) {\n const layersStore: string[] = Array.isArray(req[_LAYERS_STORE_PROPERTY])\n ? (req[_LAYERS_STORE_PROPERTY] as string[])\n : [];\n\n const meaningfulPaths = layersStore.filter(\n path => path !== '/' && path !== '/*'\n );\n\n if (meaningfulPaths.length === 1 && meaningfulPaths[0] === '*') {\n return '*';\n }\n\n // Join parts and remove duplicate slashes\n return meaningfulPaths.join('').replace(/\\/{2,}/g, '/');\n}\n\n/**\n * Extracts the actual matched route from Express request for OpenTelemetry instrumentation.\n * Returns the route that should be used as the http.route attribute.\n *\n * @param req - The Express request object with layers store\n * @param layersStoreProperty - The property name where layer paths are stored\n * @returns The matched route string or undefined if no valid route is found\n */\nexport function getActualMatchedRoute(req: {\n originalUrl: PatchedRequest['originalUrl'];\n [_LAYERS_STORE_PROPERTY]?: string[];\n}): string | undefined {\n const layersStore: string[] = Array.isArray(req[_LAYERS_STORE_PROPERTY])\n ? (req[_LAYERS_STORE_PROPERTY] as string[])\n : [];\n\n // If no layers are stored, no route can be determined\n if (layersStore.length === 0) {\n return undefined;\n }\n\n // Handle root path case - if all paths are root, only return root if originalUrl is also root\n // The layer store also includes root paths in case a non-existing url was requested\n if (layersStore.every(path => path === '/')) {\n return req.originalUrl === '/' ? '/' : undefined;\n }\n\n const constructedRoute = getConstructedRoute(req);\n if (constructedRoute === '*') {\n return constructedRoute;\n }\n\n // For RegExp routes or route arrays, return the constructed route\n // This handles the case where the route is defined using RegExp or an array\n if (\n constructedRoute.includes('/') &&\n (constructedRoute.includes(',') ||\n constructedRoute.includes('\\\\') ||\n constructedRoute.includes('*') ||\n constructedRoute.includes('['))\n ) {\n return constructedRoute;\n }\n\n // Ensure route starts with '/' if it doesn't already\n const normalizedRoute = constructedRoute.startsWith('/')\n ? constructedRoute\n : `/${constructedRoute}`;\n\n // Validate that this appears to be a matched route\n // A route is considered matched if:\n // 1. We have a constructed route\n // 2. The original URL matches or starts with our route pattern\n const isValidRoute =\n normalizedRoute.length > 0 &&\n (req.originalUrl === normalizedRoute ||\n req.originalUrl.startsWith(normalizedRoute) ||\n isRoutePattern(normalizedRoute));\n\n return isValidRoute ? normalizedRoute : undefined;\n}\n\n/**\n * Checks if a route contains parameter patterns (e.g., :id, :userId)\n * which are valid even if they don't exactly match the original URL\n */\nfunction isRoutePattern(route: string): boolean {\n return route.includes(':') || route.includes('*');\n}\n"]}
|
package/build/src/version.d.ts
CHANGED
package/build/src/version.js
CHANGED
|
@@ -17,6 +17,6 @@
|
|
|
17
17
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
18
18
|
exports.PACKAGE_NAME = exports.PACKAGE_VERSION = void 0;
|
|
19
19
|
// this is autogenerated file, see scripts/version-update.js
|
|
20
|
-
exports.PACKAGE_VERSION = '0.
|
|
20
|
+
exports.PACKAGE_VERSION = '0.52.0';
|
|
21
21
|
exports.PACKAGE_NAME = '@opentelemetry/instrumentation-express';
|
|
22
22
|
//# sourceMappingURL=version.js.map
|
package/build/src/version.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4DAA4D;AAC/C,QAAA,eAAe,GAAG,QAAQ,CAAC;AAC3B,QAAA,YAAY,GAAG,wCAAwC,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const PACKAGE_VERSION = '0.
|
|
1
|
+
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/version.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,4DAA4D;AAC/C,QAAA,eAAe,GAAG,QAAQ,CAAC;AAC3B,QAAA,YAAY,GAAG,wCAAwC,CAAC","sourcesContent":["/*\n * Copyright The OpenTelemetry Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// this is autogenerated file, see scripts/version-update.js\nexport const PACKAGE_VERSION = '0.52.0';\nexport const PACKAGE_NAME = '@opentelemetry/instrumentation-express';\n"]}
|
package/package.json
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@opentelemetry/instrumentation-express",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.52.0",
|
|
4
4
|
"description": "OpenTelemetry instrumentation for `express` http web application framework",
|
|
5
5
|
"main": "build/src/index.js",
|
|
6
6
|
"types": "build/src/index.d.ts",
|
|
7
|
-
"repository":
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "https://github.com/open-telemetry/opentelemetry-js-contrib.git",
|
|
10
|
+
"directory": "packages/instrumentation-express"
|
|
11
|
+
},
|
|
8
12
|
"scripts": {
|
|
9
13
|
"test-all-versions": "tav",
|
|
10
14
|
"test": "nyc mocha 'test/**/*.test.ts'",
|
|
@@ -12,8 +16,8 @@
|
|
|
12
16
|
"clean": "rimraf build/*",
|
|
13
17
|
"lint": "eslint . --ext .ts",
|
|
14
18
|
"lint:fix": "eslint . --ext .ts --fix",
|
|
15
|
-
"lint:readme": "node
|
|
16
|
-
"version:update": "node
|
|
19
|
+
"lint:readme": "node ../../scripts/lint-readme.js",
|
|
20
|
+
"version:update": "node ../../scripts/version-update.js",
|
|
17
21
|
"setup:dev": "nx run-many -t compile -p @opentelemetry/instrumentation-express",
|
|
18
22
|
"compile": "tsc -p .",
|
|
19
23
|
"prepublishOnly": "npm run compile",
|
|
@@ -46,10 +50,10 @@
|
|
|
46
50
|
"devDependencies": {
|
|
47
51
|
"@opentelemetry/api": "^1.3.0",
|
|
48
52
|
"@opentelemetry/context-async-hooks": "^2.0.0",
|
|
49
|
-
"@opentelemetry/contrib-test-utils": "^0.
|
|
53
|
+
"@opentelemetry/contrib-test-utils": "^0.49.0",
|
|
50
54
|
"@opentelemetry/sdk-trace-base": "^2.0.0",
|
|
51
55
|
"@opentelemetry/sdk-trace-node": "^2.0.0",
|
|
52
|
-
"@types/express": "4.17.
|
|
56
|
+
"@types/express": "4.17.23",
|
|
53
57
|
"@types/mocha": "10.0.10",
|
|
54
58
|
"@types/node": "18.18.14",
|
|
55
59
|
"@types/sinon": "17.0.4",
|
|
@@ -62,9 +66,9 @@
|
|
|
62
66
|
},
|
|
63
67
|
"dependencies": {
|
|
64
68
|
"@opentelemetry/core": "^2.0.0",
|
|
65
|
-
"@opentelemetry/instrumentation": "^0.
|
|
69
|
+
"@opentelemetry/instrumentation": "^0.203.0",
|
|
66
70
|
"@opentelemetry/semantic-conventions": "^1.27.0"
|
|
67
71
|
},
|
|
68
|
-
"homepage": "https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/
|
|
69
|
-
"gitHead": "
|
|
72
|
+
"homepage": "https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/packages/instrumentation-express#readme",
|
|
73
|
+
"gitHead": "e7960a2061c0a039ffa57ed8dbb73d605d65f4f6"
|
|
70
74
|
}
|