From a77c69d209db13193700d2dd4ac295ced277c109 Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Tue, 27 Apr 2021 14:03:25 +0300 Subject: [PATCH 01/36] feat: implement first version of router instrumentation --- .../.eslintignore | 1 + .../.eslintrc.js | 7 + .../.npmignore | 4 + .../LICENSE | 201 ++++++++++++++++ .../README.md | 58 +++++ .../package.json | 65 ++++++ .../src/constants.ts | 28 +++ .../src/index.ts | 20 ++ .../src/instrumentation.ts | 216 ++++++++++++++++++ .../src/router.d.ts | 16 ++ .../src/types.ts | 58 +++++ .../src/utils.ts | 40 ++++ .../src/version.ts | 18 ++ .../test/index.test.ts | 167 ++++++++++++++ .../tsconfig.json | 11 + 15 files changed, 910 insertions(+) create mode 100644 plugins/node/opentelemetry-instrumentation-router/.eslintignore create mode 100644 plugins/node/opentelemetry-instrumentation-router/.eslintrc.js create mode 100644 plugins/node/opentelemetry-instrumentation-router/.npmignore create mode 100644 plugins/node/opentelemetry-instrumentation-router/LICENSE create mode 100644 plugins/node/opentelemetry-instrumentation-router/README.md create mode 100644 plugins/node/opentelemetry-instrumentation-router/package.json create mode 100644 plugins/node/opentelemetry-instrumentation-router/src/constants.ts create mode 100644 plugins/node/opentelemetry-instrumentation-router/src/index.ts create mode 100644 plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts create mode 100644 plugins/node/opentelemetry-instrumentation-router/src/router.d.ts create mode 100644 plugins/node/opentelemetry-instrumentation-router/src/types.ts create mode 100644 plugins/node/opentelemetry-instrumentation-router/src/utils.ts create mode 100644 plugins/node/opentelemetry-instrumentation-router/src/version.ts create mode 100644 plugins/node/opentelemetry-instrumentation-router/test/index.test.ts create mode 100644 plugins/node/opentelemetry-instrumentation-router/tsconfig.json diff --git a/plugins/node/opentelemetry-instrumentation-router/.eslintignore b/plugins/node/opentelemetry-instrumentation-router/.eslintignore new file mode 100644 index 0000000000..378eac25d3 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-router/.eslintignore @@ -0,0 +1 @@ +build diff --git a/plugins/node/opentelemetry-instrumentation-router/.eslintrc.js b/plugins/node/opentelemetry-instrumentation-router/.eslintrc.js new file mode 100644 index 0000000000..f756f4488b --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-router/.eslintrc.js @@ -0,0 +1,7 @@ +module.exports = { + "env": { + "mocha": true, + "node": true + }, + ...require('../../../eslint.config.js') +} diff --git a/plugins/node/opentelemetry-instrumentation-router/.npmignore b/plugins/node/opentelemetry-instrumentation-router/.npmignore new file mode 100644 index 0000000000..9505ba9450 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-router/.npmignore @@ -0,0 +1,4 @@ +/bin +/coverage +/doc +/test diff --git a/plugins/node/opentelemetry-instrumentation-router/LICENSE b/plugins/node/opentelemetry-instrumentation-router/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-router/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/plugins/node/opentelemetry-instrumentation-router/README.md b/plugins/node/opentelemetry-instrumentation-router/README.md new file mode 100644 index 0000000000..5d1e6b5a2e --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-router/README.md @@ -0,0 +1,58 @@ +# OpenTelemetry __package name__ Instrumentation for Node.js + +[![Gitter chat][gitter-image]][gitter-url] +[![dependencies][dependencies-image]][dependencies-url] +[![devDependencies][devDependencies-image]][devDependencies-url] +[![Apache License][license-image]][license-image] + +This module provides automatic instrumentation for [`__package name__`](https://github.com/__package name__/node-__package name__) and allows the user to automatically collect trace data and export them to their backend of choice. + +For automatic instrumentation see the +[@opentelemetry/node](https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-node) package. + +## Installation + +```bash +npm install --save @opentelemetry/instrumentation-__package name__ +``` +### Supported Versions + - `>=4.0.0` + +## Usage + +```js +const { __package name__Instrumentation } = require('@opentelemetry/instrumentation-__package name__'); +const { ConsoleSpanExporter, SimpleSpanProcessor } = require('@opentelemetry/tracing'); +const { NodeTracerProvider } = require('@opentelemetry/node'); +const { registerInstrumentations } = require('@opentelemetry/instrumentation'); + +const provider = new NodeTracerProvider(); + +provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter())); +provider.register(); + +registerInstrumentations({ + instrumentations: [new __package name__Instrumentation()], + tracerProvider: provider, +}); +``` + +See [examples/__package name__](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/examples/__package name__) for a short example. + +## Useful links +- For more information on OpenTelemetry, visit: +- For more about OpenTelemetry JavaScript: +- For help or feedback on this project, join us on [gitter][gitter-url] + +## License + +Apache 2.0 - See [LICENSE][license-url] for more information. + +[gitter-image]: https://badges.gitter.im/open-telemetry/opentelemetry-js.svg +[gitter-url]: https://gitter.im/open-telemetry/opentelemetry-node?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge +[license-url]: https://github.com/open-telemetry/opentelemetry-js-contrib/blob/main/LICENSE +[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat +[dependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib/status.svg?path=packages/opentelemetry-instrumentation-__package name__ +[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=packages%2Fopentelemetry-instrumentation-__package name__ +[devDependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib/dev-status.svg?path=packages/opentelemetry-instrumentation-__package name__ +[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=packages%2Fopentelemetry-instrumentation-__package name__&type=dev diff --git a/plugins/node/opentelemetry-instrumentation-router/package.json b/plugins/node/opentelemetry-instrumentation-router/package.json new file mode 100644 index 0000000000..5b59492c95 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-router/package.json @@ -0,0 +1,65 @@ +{ + "name": "@opentelemetry/instrumentation-router", + "version": "0.15.0", + "description": "OpenTelemetry router automatic instrumentation package", + "main": "build/src/index.js", + "types": "build/src/index.d.ts", + "repository": "open-telemetry/opentelemetry-js-contrib", + "scripts": { + "test": "nyc ts-mocha -p tsconfig.json 'test/**/*.ts'", + "codecov": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../", + "tdd": "yarn test -- --watch-extensions ts --watch", + "clean": "rimraf build/*", + "lint": "eslint . --ext .ts", + "lint:fix": "eslint . --ext .ts --fix", + "precompile": "tsc --version", + "version:update": "node ../../../scripts/version-update.js", + "compile": "npm run version:update && tsc -p .", + "prepare": "npm run compile", + "watch": "tsc -w" + }, + "keywords": [ + "opentelemetry", + "router", + "nodejs", + "tracing", + "instrumentation" + ], + "author": "OpenTelemetry Authors", + "license": "Apache-2.0", + "engines": { + "node": ">=8.5.0" + }, + "files": [ + "build/src/**/*.js", + "build/src/**/*.d.ts", + "doc", + "LICENSE", + "README.md" + ], + "publishConfig": { + "access": "public" + }, + "devDependencies": { + "@opentelemetry/context-async-hooks": "0.19.0", + "@opentelemetry/node": "0.19.0", + "@opentelemetry/tracing": "0.19.0", + "@types/mocha": "7.0.2", + "@types/node": "14.0.27", + "codecov": "3.7.2", + "gts": "3.1.0", + "mocha": "7.2.0", + "nyc": "15.1.0", + "rimraf": "3.0.2", + "router": "^1.3.5", + "ts-mocha": "8.0.0", + "tslint-consistent-codestyle": "1.16.0", + "tslint-microsoft-contrib": "6.2.0", + "typescript": "4.1.3" + }, + "dependencies": { + "@opentelemetry/api": "^1.0.0-rc.0", + "@opentelemetry/instrumentation": "^0.19.0", + "@opentelemetry/semantic-conventions": "^0.19.0" + } +} diff --git a/plugins/node/opentelemetry-instrumentation-router/src/constants.ts b/plugins/node/opentelemetry-instrumentation-router/src/constants.ts new file mode 100644 index 0000000000..ae69202fe3 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-router/src/constants.ts @@ -0,0 +1,28 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export const MODULE_NAME = 'router'; +export const SUPPORTED_VERSIONS = ['1']; + +// Router.prototype.handle +export const ROUTE_ROUTER_FN = `function router(req, res, next) { + router.handle(req, res, next) + }`; + +// Route.prototype.dispatch +export const ROUTER_HANDLE_FN = `function handle(req, res, next) { + route.dispatch(req, res, next) + }`; diff --git a/plugins/node/opentelemetry-instrumentation-router/src/index.ts b/plugins/node/opentelemetry-instrumentation-router/src/index.ts new file mode 100644 index 0000000000..df07144357 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-router/src/index.ts @@ -0,0 +1,20 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import RouterInstrumentation from './instrumentation'; + +export { RouterInstrumentation }; +export default RouterInstrumentation; diff --git a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts new file mode 100644 index 0000000000..c7f912d49f --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts @@ -0,0 +1,216 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as api from '@opentelemetry/api'; +import { + InstrumentationBase, + InstrumentationNodeModuleDefinition, + InstrumentationNodeModuleFile, + isWrapped, +} from '@opentelemetry/instrumentation'; +import { SemanticAttributes } from '@opentelemetry/semantic-conventions'; + +import * as http from 'http'; +import * as router from 'router'; + +import * as types from './types'; +import { VERSION } from './version'; +import * as constants from './constants'; +import * as utils from './utils'; + +const { diag } = api; + +export default class RouterInstrumentation extends InstrumentationBase< + typeof router +> { + constructor() { + super(`@opentelemetry/instrumentation-${constants.MODULE_NAME}`, VERSION); + } + + private _moduleVersion?: string; + + init() { + const module = new InstrumentationNodeModuleDefinition( + constants.MODULE_NAME, + constants.SUPPORTED_VERSIONS, + (moduleExports, moduleVersion) => { + diag.debug( + `Applying patch for ${constants.MODULE_NAME}@${moduleVersion}` + ); + this._moduleVersion = moduleVersion; + return moduleExports; + }, + (moduleExports, moduleVersion) => { + diag.debug( + `Removing patch for ${constants.MODULE_NAME}@${moduleVersion}` + ); + } + ); + + module.files.push( + new InstrumentationNodeModuleFile( + 'router/lib/layer.js', + constants.SUPPORTED_VERSIONS, + (moduleExports, moduleVersion) => { + diag.debug( + `Applying patch for "lib/layer.js" of ${constants.MODULE_NAME}@${moduleVersion}` + ); + const Layer: any = moduleExports; + if (isWrapped(Layer.prototype.handle_request)) { + this._unwrap(Layer.prototype, 'handle_request'); + } + this._wrap( + Layer.prototype, + 'handle_request', + this._requestHandlerPatcher.bind(this) + ); + if (isWrapped(Layer.prototype.handle_error)) { + this._unwrap(Layer.prototype, 'handle_error'); + } + this._wrap( + Layer.prototype, + 'handle_error', + this._errorHandlerPatcher.bind(this) + ); + return Layer; + }, + (moduleExports, moduleVersion) => { + diag.debug( + `Removing patch for "lib/layer.js" of ${constants.MODULE_NAME}@${moduleVersion}` + ); + const Layer: any = moduleExports; + this._unwrap(Layer.prototype, 'handle_request'); + this._unwrap(Layer.prototype, 'handle_error'); + } + ) + ); + return module; + } + + private _requestHandlerPatcher(original: types.Layer['handle_request']) { + const instrumentation = this; + return function wrapped_handle_request( + this: types.Layer, + req: types.RouterIncomingMessage, + res: http.ServerResponse, + next: types.Next + ) { + if (utils.isInternal(this.handle) || this.handle.length > 3) { + return original.call(this, req, res, next); + } + const { span, wrappedNext } = instrumentation._setupSpan( + this.handle, + this.method, + req, + res, + next + ); + return api.context.with( + api.setSpan(api.context.active(), span), + original, + this, + req, + res, + wrappedNext + ); + }; + } + + private _errorHandlerPatcher(original: types.Layer['handle_error']) { + const instrumentation = this; + return function wrapped_handle_request( + this: types.Layer, + error: Error, + req: types.RouterIncomingMessage, + res: http.ServerResponse, + next: types.Next + ) { + if (utils.isInternal(this.handle) || this.handle.length !== 4) { + return original.call(this, error, req, res, next); + } + const { span, wrappedNext } = instrumentation._setupSpan( + this.handle, + this.method, + req, + res, + next + ); + return api.context.with( + api.setSpan(api.context.active(), span), + original, + this, + error, + req, + res, + wrappedNext + ); + }; + } + + private _setupSpan( + handle: Function, + method: string | undefined, + req: types.RouterIncomingMessage, + res: http.ServerResponse, + next: types.Next + ) { + // Router sets "" as the default + const fnName = handle.name; + const type = method + ? types.LayerType.REQUEST_HANDLER + : types.LayerType.MIDDLEWARE; + const route = utils.getRoute(req); + const spanName = + type === types.LayerType.REQUEST_HANDLER + ? `request handler - ${route}` + : `middleware - ${fnName || ''}`; + const attributes = { + [types.CustomAttributeNames.NAME]: fnName, + [types.CustomAttributeNames.VERSION]: this._moduleVersion || 'n/a', + [types.CustomAttributeNames.TYPE]: type, + [SemanticAttributes.HTTP_ROUTE]: route, + }; + const span = this.tracer.startSpan( + spanName, + { + attributes, + }, + api.context.active() + ); + + let called = false; + const endSpan = () => { + if (!called) { + called = true; + utils.renameHttpSpan(api.getSpan(api.context.active()), method, route); + return span.end(); + } + }; + // prependListener fires correctly, if syncronous internal handlers would be tracked as well + // TODO: define what "correctly" means here. Also affects the renaming of http span. + res.prependOnceListener('finish', endSpan); + + const wrappedNext: types.Next = (...args) => { + endSpan(); + return next(...args); + }; + + return { + span, + wrappedNext, + }; + } +} diff --git a/plugins/node/opentelemetry-instrumentation-router/src/router.d.ts b/plugins/node/opentelemetry-instrumentation-router/src/router.d.ts new file mode 100644 index 0000000000..360b2f4631 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-router/src/router.d.ts @@ -0,0 +1,16 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare module 'router'; diff --git a/plugins/node/opentelemetry-instrumentation-router/src/types.ts b/plugins/node/opentelemetry-instrumentation-router/src/types.ts new file mode 100644 index 0000000000..4ef3b9c1e4 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-router/src/types.ts @@ -0,0 +1,58 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as http from 'http'; +import { Span } from '@opentelemetry/api'; + +export enum LayerType { + MIDDLEWARE = 'middleware', + REQUEST_HANDLER = 'request_handler', +} +export interface RouterIncomingMessage extends http.IncomingMessage { + baseUrl: string; + route?: { + path: string; + }; +} +export type Next = (...args: any[]) => void; +export interface Layer { + handle: Function; + method?: string; + handle_request: ( + req: RouterIncomingMessage, + res: http.ServerResponse, + next: Next + ) => void; + handle_error: ( + error: Error, + req: RouterIncomingMessage, + res: http.ServerResponse, + next: Next + ) => void; +} + +export enum CustomAttributeNames { + TYPE = 'router.type', + NAME = 'router.name', + METHOD = 'router.method', + VERSION = 'router.version', +} + +/** + * extends opentelemetry/api Span object to instrument the root span name of http instrumentation + */ +export interface InstrumentationSpan extends Span { + name?: string; +} diff --git a/plugins/node/opentelemetry-instrumentation-router/src/utils.ts b/plugins/node/opentelemetry-instrumentation-router/src/utils.ts new file mode 100644 index 0000000000..62ba416036 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-router/src/utils.ts @@ -0,0 +1,40 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as constants from './constants'; +import * as types from './types'; + +export const isInternal = (fn: Function) => { + // Note that both of those functions are sync + if (fn.name === 'handle' && fn.toString() === constants.ROUTER_HANDLE_FN) { + return true; + } + if (fn.name === 'router' && fn.toString() === constants.ROUTE_ROUTER_FN) { + return true; + } + return false; +}; +export const getRoute = (req: types.RouterIncomingMessage) => + req.baseUrl + (req.route?.path || '') || '/'; +export const renameHttpSpan = ( + span?: types.InstrumentationSpan, + method?: string, + route?: string +) => { + if (method && route && span?.name?.startsWith('HTTP ')) { + (span as types.InstrumentationSpan).updateName(`${method} ${route}`); + } +}; diff --git a/plugins/node/opentelemetry-instrumentation-router/src/version.ts b/plugins/node/opentelemetry-instrumentation-router/src/version.ts new file mode 100644 index 0000000000..1e4172026f --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-router/src/version.ts @@ -0,0 +1,18 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// this is autogenerated file, see scripts/version-update.js +export const VERSION = '0.15.0'; diff --git a/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts b/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts new file mode 100644 index 0000000000..0051bf4e39 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts @@ -0,0 +1,167 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { context, setSpan } from '@opentelemetry/api'; +import { NodeTracerProvider } from '@opentelemetry/node'; +import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks'; +import { + InMemorySpanExporter, + SimpleSpanProcessor, +} from '@opentelemetry/tracing'; + +import Instrumentation from '../src'; +const plugin = new Instrumentation(); + +import * as http from 'http'; +import * as Router from 'router'; +import * as assert from 'assert'; +import { AddressInfo } from 'net'; + +const createServer = async () => { + const router = Router(); + + router.use((req, res, next) => { + // + next(); + }); + + router.get('/', (req, res) => { + res.setHeader('Content-Type', 'text/plain; charset=utf-8'); + res.end('Hello World!'); + }); + + const helloRouter = Router(); + + helloRouter.get('/:name', (req, res, next) => { + if (req.params.name.toLowerCase() === 'nobody') { + return next(); + } + res.setHeader('Content-Type', 'text/plain; charset=utf-8'); + res.end(`Hello, ${req.params.name}!`); + }); + + helloRouter.get('/:name', (req, res, next) => { + res.setHeader('Content-Type', 'text/plain; charset=utf-8'); + res.end('How rude!'); + }); + + router.use('/hello', helloRouter); + + const deepRouter = Router(); + + deepRouter.use('/hello', helloRouter); + router.use('/deep', deepRouter); + + const server = http.createServer((req, res) => { + router(req, res, (...args) => { + console.log('args', args); + if (!res.headersSent) { + res.statusCode = 404; + res.end('Not Found'); + } + }); + }); + + await new Promise(resolve => server.listen(0, resolve)); + + return server; +}; + +describe('Router instrumentation', () => { + const provider = new NodeTracerProvider(); + const memoryExporter = new InMemorySpanExporter(); + const spanProcessor = new SimpleSpanProcessor(memoryExporter); + provider.addSpanProcessor(spanProcessor); + // plugin.setTracerProvider(provider); + const tracer = provider.getTracer('default'); + let contextManager: AsyncHooksContextManager; + let server: http.Server; + + const request = (path: string, options?: http.ClientRequestArgs | string) => { + const port = (server.address() as AddressInfo).port; + return new Promise((resolve, reject) => { + return http.get(`http://localhost:${port}${path}`, resp => { + let data = ''; + resp.on('data', chunk => { + data += chunk; + }); + resp.on('end', arg => { + resolve(data); + }); + resp.on('error', err => { + reject(err); + }); + }); + }); + }; + + before(async () => { + server = await createServer(); + // plugin.enable(); + }); + + after(() => { + plugin.disable(); + }); + + beforeEach(async () => { + contextManager = new AsyncHooksContextManager(); + context.setGlobalContextManager(contextManager.enable()); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + }); + + afterEach(() => { + memoryExporter.reset(); + context.disable(); + server.close(); + }); + + describe('Instrumenting', () => { + it('should work', async () => { + const rootSpan = tracer.startSpan('clientSpan'); + + await context.with(setSpan(context.active(), rootSpan), async () => { + const res = await request('/'); + assert.strictEqual(res, 'Hello World!'); + console.error(); + console.error(); + console.error(); + assert.strictEqual(await request('/hello/you'), 'Hello, you!'); + console.error(); + console.error(); + console.error(); + assert.strictEqual(await request('/deep/hello/you'), 'Hello, you!'); + console.error(); + console.error(); + console.error(); + assert.strictEqual(await request('/deep/hello/nobody'), 'How rude!'); + }); + }); + }); + + describe('Disabling instrumentation', () => { + it('should not create new spans', async () => { + plugin.disable(); + const rootSpan = tracer.startSpan('rootSpan'); + + await context.with(setSpan(context.active(), rootSpan), async () => { + rootSpan.end(); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 1); + assert.notStrictEqual(memoryExporter.getFinishedSpans()[0], undefined); + }); + }); + }); +}); diff --git a/plugins/node/opentelemetry-instrumentation-router/tsconfig.json b/plugins/node/opentelemetry-instrumentation-router/tsconfig.json new file mode 100644 index 0000000000..28be80d266 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-router/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../../tsconfig.base", + "compilerOptions": { + "rootDir": ".", + "outDir": "build" + }, + "include": [ + "src/**/*.ts", + "test/**/*.ts" + ] +} From 1f423a592418f101e26ebf785a440edea7f01eee Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Thu, 29 Apr 2021 11:44:55 +0300 Subject: [PATCH 02/36] chore: add types for router --- .../src/instrumentation.ts | 8 +- .../src/router.d.ts | 206 +++++++++++++++++- .../test/index.test.ts | 47 ++-- 3 files changed, 230 insertions(+), 31 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts index c7f912d49f..c430636324 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts @@ -24,7 +24,7 @@ import { import { SemanticAttributes } from '@opentelemetry/semantic-conventions'; import * as http from 'http'; -import * as router from 'router'; +import * as Router from 'router'; import * as types from './types'; import { VERSION } from './version'; @@ -34,7 +34,7 @@ import * as utils from './utils'; const { diag } = api; export default class RouterInstrumentation extends InstrumentationBase< - typeof router + typeof Router > { constructor() { super(`@opentelemetry/instrumentation-${constants.MODULE_NAME}`, VERSION); @@ -43,7 +43,7 @@ export default class RouterInstrumentation extends InstrumentationBase< private _moduleVersion?: string; init() { - const module = new InstrumentationNodeModuleDefinition( + const module = new InstrumentationNodeModuleDefinition( constants.MODULE_NAME, constants.SUPPORTED_VERSIONS, (moduleExports, moduleVersion) => { @@ -61,7 +61,7 @@ export default class RouterInstrumentation extends InstrumentationBase< ); module.files.push( - new InstrumentationNodeModuleFile( + new InstrumentationNodeModuleFile( 'router/lib/layer.js', constants.SUPPORTED_VERSIONS, (moduleExports, moduleVersion) => { diff --git a/plugins/node/opentelemetry-instrumentation-router/src/router.d.ts b/plugins/node/opentelemetry-instrumentation-router/src/router.d.ts index 360b2f4631..cfc617c424 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/router.d.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/router.d.ts @@ -13,4 +13,208 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -declare module 'router'; + +declare module 'router' { + import * as http from 'http'; + + export = Router; + + namespace Router { + + interface RouterOptions { + strict?: boolean; + caseSensitive?: boolean; + mergeParams?: boolean; + } + + interface Layer { + name: string, + handle: RequestHandler | ErrorRequestHandler, + handle_request: RequestHandler, + handle_error: ErrorRequestHandler, + match: (path: string) => boolean, + } + + interface IncomingRequest extends http.IncomingMessage { + url: string, + method: string, + originalUrl?: string, + params?: { + [key: string]: any, + }, + } + + interface RoutedRequest extends IncomingRequest { + baseUrl: string, + next?: NextFunction, + route?: IRoute + } + + type RequestParamHandler = (req: IncomingRequest, res: http.ServerResponse, next: NextFunction, value: string, name: string) => void; + + type RouteHandler = (req: RoutedRequest, res: http.ServerResponse, next: NextFunction) => void; + type RequestHandler = (req: IncomingRequest, res: http.ServerResponse, next: NextFunction) => void; + + type NextFunction = (err?: Error | "route" | "router") => void; + type Callback = (err?: Error) => void; + + type ErrorRequestHandler = (err: Error, req: IncomingRequest, res: http.ServerResponse, next: NextFunction) => void; + + type PathParams = string | RegExp | Array; + + type RequestHandlerParams = RouteHandler | ErrorRequestHandler | Array; + + interface IRouterMatcher { + (path: PathParams, ...handlers: RouteHandler[]): T; + (path: PathParams, ...handlers: RequestHandlerParams[]): T; + } + + interface IRouterHandler { + (...handlers: RouteHandler[]): T; + (...handlers: RequestHandlerParams[]): T; + } + + interface IRouter { + /** + * Map the given param placeholder `name`(s) to the given callback(s). + * + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code, + * + * The callback uses the same signature as middleware, the only differencing + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. + * + * app.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * next(err); + * } else if (user) { + * req.user = user; + * next(); + * } else { + * next(new Error('failed to load user')); + * } + * }); + * }); + */ + param(name: string, handler: RequestParamHandler): this; + + /** + * Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param() + * + * @deprecated since version 4.11 + */ + param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this; + + /** + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. + */ + all: IRouterMatcher; + + use: IRouterHandler & IRouterMatcher; + + handle: (req: http.IncomingMessage, res: http.ServerResponse, cb: Callback) => void; + + route(prefix: PathParams): IRoute; + // Stack of configured routes + stack: Layer[]; + + // Common HTTP methods + delete: IRouterMatcher; + get: IRouterMatcher; + head: IRouterMatcher; + options: IRouterMatcher; + patch: IRouterMatcher; + post: IRouterMatcher; + put: IRouterMatcher; + + // Exotic HTTP methods + acl: IRouterMatcher; + bind: IRouterMatcher; + checkout: IRouterMatcher; + connect: IRouterMatcher; + copy: IRouterMatcher; + link: IRouterMatcher; + lock: IRouterMatcher; + "m-search": IRouterMatcher; + merge: IRouterMatcher; + mkactivity: IRouterMatcher; + mkcalendar: IRouterMatcher; + mkcol: IRouterMatcher; + move: IRouterMatcher; + notify: IRouterMatcher; + pri: IRouterMatcher; + propfind: IRouterMatcher; + proppatch: IRouterMatcher; + purge: IRouterMatcher; + rebind: IRouterMatcher; + report: IRouterMatcher; + search: IRouterMatcher; + source: IRouterMatcher; + subscribe: IRouterMatcher; + trace: IRouterMatcher; + unbind: IRouterMatcher; + unlink: IRouterMatcher; + unlock: IRouterMatcher; + unsubscribe: IRouterMatcher; + } + + interface IRoute { + path: string; + stack: Layer[]; + + all: IRouterHandler; + + // Common HTTP methods + delete: IRouterHandler; + get: IRouterHandler; + head: IRouterHandler; + options: IRouterHandler; + patch: IRouterHandler; + post: IRouterHandler; + put: IRouterHandler; + + // Exotic HTTP methods + acl: IRouterHandler; + bind: IRouterHandler; + checkout: IRouterHandler; + connect: IRouterHandler; + copy: IRouterHandler; + link: IRouterHandler; + lock: IRouterHandler; + "m-search": IRouterHandler; + merge: IRouterHandler; + mkactivity: IRouterHandler; + mkcalendar: IRouterHandler; + mkcol: IRouterHandler; + move: IRouterHandler; + notify: IRouterHandler; + pri: IRouterHandler; + propfind: IRouterHandler; + proppatch: IRouterHandler; + purge: IRouterHandler; + rebind: IRouterHandler; + report: IRouterHandler; + search: IRouterHandler; + source: IRouterHandler; + subscribe: IRouterHandler; + trace: IRouterHandler; + unbind: IRouterHandler; + unlink: IRouterHandler; + unlock: IRouterHandler; + unsubscribe: IRouterHandler; + } + + interface RouterConstructor extends IRouter { + new(options?: RouterOptions): IRouter & ((req: http.IncomingMessage, res: http.ServerResponse, cb: Callback) => void); + } + + } + + const Router: Router.RouterConstructor; +} diff --git a/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts b/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts index 0051bf4e39..3ce9239a70 100644 --- a/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts +++ b/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts @@ -31,43 +31,47 @@ import * as assert from 'assert'; import { AddressInfo } from 'net'; const createServer = async () => { - const router = Router(); + const router = new Router(); router.use((req, res, next) => { - // next(); }); + router.get('/err', (req, res, next) => { + next(new Error('Oops')); + }); + router.get('/', (req, res) => { - res.setHeader('Content-Type', 'text/plain; charset=utf-8'); res.end('Hello World!'); }); - const helloRouter = Router(); + const helloRouter = new Router(); helloRouter.get('/:name', (req, res, next) => { - if (req.params.name.toLowerCase() === 'nobody') { + if (req.params?.name?.toLowerCase() === 'nobody') { return next(); } - res.setHeader('Content-Type', 'text/plain; charset=utf-8'); - res.end(`Hello, ${req.params.name}!`); + res.end(`Hello, ${req.params?.name}!`); }); helloRouter.get('/:name', (req, res, next) => { - res.setHeader('Content-Type', 'text/plain; charset=utf-8'); res.end('How rude!'); }); router.use('/hello', helloRouter); - const deepRouter = Router(); + const deepRouter = new Router(); deepRouter.use('/hello', helloRouter); router.use('/deep', deepRouter); + const errHandler: Router.ErrorRequestHandler = (err, req, res, next) => { + res.end('Server error!'); + }; + router.use(errHandler); + const server = http.createServer((req, res) => { - router(req, res, (...args) => { - console.log('args', args); + router(req, res, (err) => { if (!res.headersSent) { res.statusCode = 404; res.end('Not Found'); @@ -85,7 +89,7 @@ describe('Router instrumentation', () => { const memoryExporter = new InMemorySpanExporter(); const spanProcessor = new SimpleSpanProcessor(memoryExporter); provider.addSpanProcessor(spanProcessor); - // plugin.setTracerProvider(provider); + plugin.setTracerProvider(provider); const tracer = provider.getTracer('default'); let contextManager: AsyncHooksContextManager; let server: http.Server; @@ -93,12 +97,12 @@ describe('Router instrumentation', () => { const request = (path: string, options?: http.ClientRequestArgs | string) => { const port = (server.address() as AddressInfo).port; return new Promise((resolve, reject) => { - return http.get(`http://localhost:${port}${path}`, resp => { + return http.get(`http://localhost:${port}${path}`, (resp) => { let data = ''; resp.on('data', chunk => { data += chunk; }); - resp.on('end', arg => { + resp.on('end', () => { resolve(data); }); resp.on('error', err => { @@ -110,7 +114,7 @@ describe('Router instrumentation', () => { before(async () => { server = await createServer(); - // plugin.enable(); + plugin.enable(); }); after(() => { @@ -134,20 +138,11 @@ describe('Router instrumentation', () => { const rootSpan = tracer.startSpan('clientSpan'); await context.with(setSpan(context.active(), rootSpan), async () => { - const res = await request('/'); - assert.strictEqual(res, 'Hello World!'); - console.error(); - console.error(); - console.error(); + assert.strictEqual(await request('/'), 'Hello World!'); assert.strictEqual(await request('/hello/you'), 'Hello, you!'); - console.error(); - console.error(); - console.error(); assert.strictEqual(await request('/deep/hello/you'), 'Hello, you!'); - console.error(); - console.error(); - console.error(); assert.strictEqual(await request('/deep/hello/nobody'), 'How rude!'); + assert.strictEqual(await request('/err'), 'Server error!'); }); }); }); From f5e88db9e17b9be69a15ff557d5e9896be1b1357 Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Thu, 29 Apr 2021 17:02:39 +0300 Subject: [PATCH 03/36] chore: stop debugging the behaviour of ritm and instrumentation patcher --- .../src/instrumentation.ts | 7 ++++++- .../opentelemetry-instrumentation-router/src/router.d.ts | 1 + .../test/index.test.ts | 8 ++++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts index c430636324..69bbc2ffa4 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts @@ -57,6 +57,7 @@ export default class RouterInstrumentation extends InstrumentationBase< diag.debug( `Removing patch for ${constants.MODULE_NAME}@${moduleVersion}` ); + return moduleExports; } ); @@ -85,7 +86,7 @@ export default class RouterInstrumentation extends InstrumentationBase< 'handle_error', this._errorHandlerPatcher.bind(this) ); - return Layer; + return moduleExports; }, (moduleExports, moduleVersion) => { diag.debug( @@ -94,12 +95,15 @@ export default class RouterInstrumentation extends InstrumentationBase< const Layer: any = moduleExports; this._unwrap(Layer.prototype, 'handle_request'); this._unwrap(Layer.prototype, 'handle_error'); + return moduleExports; } ) ); + return module; } + // Define handle_request wrapper separately to ensure the signature has the correct length private _requestHandlerPatcher(original: types.Layer['handle_request']) { const instrumentation = this; return function wrapped_handle_request( @@ -129,6 +133,7 @@ export default class RouterInstrumentation extends InstrumentationBase< }; } + // Define handle_error wrapper separately to ensure the signature has the correct length private _errorHandlerPatcher(original: types.Layer['handle_error']) { const instrumentation = this; return function wrapped_handle_request( diff --git a/plugins/node/opentelemetry-instrumentation-router/src/router.d.ts b/plugins/node/opentelemetry-instrumentation-router/src/router.d.ts index cfc617c424..78ee77dfda 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/router.d.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/router.d.ts @@ -14,6 +14,7 @@ * limitations under the License. */ +// From https://github.com/pillarjs/router/pull/100 declare module 'router' { import * as http from 'http'; diff --git a/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts b/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts index 3ce9239a70..efd5a6d54a 100644 --- a/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts +++ b/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts @@ -22,6 +22,9 @@ import { SimpleSpanProcessor, } from '@opentelemetry/tracing'; +import { diag, DiagConsoleLogger, DiagLogLevel } from '@opentelemetry/api'; +diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.VERBOSE); + import Instrumentation from '../src'; const plugin = new Instrumentation(); @@ -115,6 +118,8 @@ describe('Router instrumentation', () => { before(async () => { server = await createServer(); plugin.enable(); + // To force ritm to definitely reload and patch the layer + require('router/lib/layer.js') }); after(() => { @@ -138,11 +143,14 @@ describe('Router instrumentation', () => { const rootSpan = tracer.startSpan('clientSpan'); await context.with(setSpan(context.active(), rootSpan), async () => { + rootSpan.end(); assert.strictEqual(await request('/'), 'Hello World!'); assert.strictEqual(await request('/hello/you'), 'Hello, you!'); assert.strictEqual(await request('/deep/hello/you'), 'Hello, you!'); assert.strictEqual(await request('/deep/hello/nobody'), 'How rude!'); assert.strictEqual(await request('/err'), 'Server error!'); + + assert.strictEqual(memoryExporter.getFinishedSpans().length, 13); }); }); }); From 347b7f52d73fc7208b6fbc902dc8095f0de7b009 Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Thu, 6 May 2021 12:46:59 +0300 Subject: [PATCH 04/36] refactor: pass layer into _setupSpan instead of individual parts of it --- .../src/instrumentation.ts | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts index 69bbc2ffa4..7937af598f 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts @@ -116,8 +116,7 @@ export default class RouterInstrumentation extends InstrumentationBase< return original.call(this, req, res, next); } const { span, wrappedNext } = instrumentation._setupSpan( - this.handle, - this.method, + this, req, res, next @@ -147,8 +146,7 @@ export default class RouterInstrumentation extends InstrumentationBase< return original.call(this, error, req, res, next); } const { span, wrappedNext } = instrumentation._setupSpan( - this.handle, - this.method, + this, req, res, next @@ -166,15 +164,13 @@ export default class RouterInstrumentation extends InstrumentationBase< } private _setupSpan( - handle: Function, - method: string | undefined, + layer: types.Layer, req: types.RouterIncomingMessage, res: http.ServerResponse, next: types.Next ) { - // Router sets "" as the default - const fnName = handle.name; - const type = method + const fnName = layer.handle.name || undefined; + const type = layer.method ? types.LayerType.REQUEST_HANDLER : types.LayerType.MIDDLEWARE; const route = utils.getRoute(req); @@ -200,7 +196,8 @@ export default class RouterInstrumentation extends InstrumentationBase< const endSpan = () => { if (!called) { called = true; - utils.renameHttpSpan(api.getSpan(api.context.active()), method, route); + // This is not the way to get HTTP span. Open issues: #466 and #464 + utils.renameHttpSpan(api.getSpan(api.context.active()), layer.method, route); return span.end(); } }; From 38311e5ebfcfaac950eb8fb14bc10f2dc6510c09 Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Thu, 6 May 2021 12:55:11 +0300 Subject: [PATCH 05/36] test: test few common cases --- .../test/index.test.ts | 148 +++++++++++++++--- 1 file changed, 126 insertions(+), 22 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts b/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts index efd5a6d54a..258934595f 100644 --- a/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts +++ b/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts @@ -37,6 +37,7 @@ const createServer = async () => { const router = new Router(); router.use((req, res, next) => { + // anonymous middleware next(); }); @@ -50,14 +51,15 @@ const createServer = async () => { const helloRouter = new Router(); - helloRouter.get('/:name', (req, res, next) => { + const preName: Router.RequestHandler = (req, res, next) => { if (req.params?.name?.toLowerCase() === 'nobody') { return next(); } res.end(`Hello, ${req.params?.name}!`); - }); + }; + helloRouter.get('/:name', preName); - helloRouter.get('/:name', (req, res, next) => { + helloRouter.get('/:name', function announceRude(req, res, next) { res.end('How rude!'); }); @@ -69,8 +71,12 @@ const createServer = async () => { router.use('/deep', deepRouter); const errHandler: Router.ErrorRequestHandler = (err, req, res, next) => { - res.end('Server error!'); + res.end(`Server error: ${err.message}!`); }; + + router.use(function postMiddleware(req, res, next) { + next(); + }); router.use(errHandler); const server = http.createServer((req, res) => { @@ -87,6 +93,35 @@ const createServer = async () => { return server; }; +const assertSpans = (actualSpans: any[], expectedSpans: any[]) => { + assert(Array.isArray(actualSpans), 'Expected `actualSpans` to be an array'); + assert(Array.isArray(actualSpans), 'Expected `actualSpans` to be an array'); + assert.strictEqual(actualSpans.length, expectedSpans.length, 'Expected span count different from actual'); + actualSpans.forEach((span, idx) => { + const expected = expectedSpans[idx]; + if (expected === null) return; + try { + assert.notStrictEqual(span, undefined); + assert.notStrictEqual(expected, undefined); + assert.strictEqual(span.attributes['router.name'], expected.name); + assert.strictEqual(span.attributes['router.type'], expected.type); + assert.strictEqual(span.attributes['router.version'], '1.3.5'); + assert.strictEqual(span.attributes['http.route'], expected.route); + } catch (e) { + e.message = `At span[${idx}]: ${e.message}`; + throw e; + } + }); +}; + +const spans = { + anonymousUse: { type: 'middleware', route: '/' }, + preName: { type: 'request_handler', name: 'preName', route: '/hello/:name' }, + announceRude: { type: 'request_handler', name: 'announceRude', route: '/hello/:name' }, + postMiddleware: { name: 'postMiddleware', type: 'middleware', route: '/:name' }, +}; + + describe('Router instrumentation', () => { const provider = new NodeTracerProvider(); const memoryExporter = new InMemorySpanExporter(); @@ -115,18 +150,11 @@ describe('Router instrumentation', () => { }); }; - before(async () => { - server = await createServer(); + beforeEach(async () => { plugin.enable(); - // To force ritm to definitely reload and patch the layer + // To force `require-in-the-middle` to definitely reload and patch the layer require('router/lib/layer.js') - }); - - after(() => { - plugin.disable(); - }); - - beforeEach(async () => { + server = await createServer(); contextManager = new AsyncHooksContextManager(); context.setGlobalContextManager(contextManager.enable()); assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); @@ -136,23 +164,99 @@ describe('Router instrumentation', () => { memoryExporter.reset(); context.disable(); server.close(); + plugin.disable(); }); - describe('Instrumenting', () => { - it('should work', async () => { + describe('Instrumenting handler calls', () => { + it('should create a span for each handler', async () => { const rootSpan = tracer.startSpan('clientSpan'); await context.with(setSpan(context.active(), rootSpan), async () => { + assert.strictEqual(await request('/hello/nobody'), 'How rude!'); rootSpan.end(); - assert.strictEqual(await request('/'), 'Hello World!'); - assert.strictEqual(await request('/hello/you'), 'Hello, you!'); - assert.strictEqual(await request('/deep/hello/you'), 'Hello, you!'); - assert.strictEqual(await request('/deep/hello/nobody'), 'How rude!'); - assert.strictEqual(await request('/err'), 'Server error!'); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 13); + assertSpans( + memoryExporter.getFinishedSpans(), + [ + spans.anonymousUse, + spans.preName, + spans.announceRude, + null, + ] + ); }); }); + + it('should gather full route for nested routers', async () => { + const rootSpan = tracer.startSpan('clientSpan'); + + await context.with(setSpan(context.active(), rootSpan), async () => { + assert.strictEqual(await request('/deep/hello/world'), 'Hello, world!'); + rootSpan.end(); + + assertSpans( + memoryExporter.getFinishedSpans(), + [ + spans.anonymousUse, + { ...spans.preName, route: '/deep/hello/:name' }, + null, + ] + ); + }); + }); + + it('should create spans for requests that did not result with response from the router', async () => { + const rootSpan = tracer.startSpan('clientSpan'); + + await context.with(setSpan(context.active(), rootSpan), async () => { + assert.strictEqual(await request('/not-found'), 'Not Found'); + rootSpan.end(); + + assertSpans( + memoryExporter.getFinishedSpans(), + [ + spans.anonymousUse, + { ...spans.postMiddleware, route: '/' }, + null, + ] + ); + }); + }); + + it('should create spans for errored routes', async () => { + const rootSpan = tracer.startSpan('clientSpan'); + + await context.with(setSpan(context.active(), rootSpan), async () => { + assert.strictEqual(await request('/err'), 'Server error: Oops!'); + rootSpan.end(); + + assertSpans( + memoryExporter.getFinishedSpans(), + [ + spans.anonymousUse, + { ...spans.preName, name: undefined, route: '/err' }, + { ...spans.anonymousUse, name: 'errHandler', route: '/err' }, + null, + ] + ); + }); + }); + + it('should rename HTTP span', async () => { + // const httpSpan: types.InstrumentationSpan = tracer.startSpan('HTTP GET'); + + // try { + // const res = await httpRequest.get( + // `http://localhost:${testLocalPort}/route/hello` + // ); + // httpSpan.end(); + // assert.strictEqual(memoryExporter.getFinishedSpans().length, 3); + // assert.strictEqual(httpSpan.name, 'GET /route/:param'); + // assert.strictEqual(res, '{"route":"hello"}'); + // } finally { + // testLocalServer.close(); + // } + }); }); describe('Disabling instrumentation', () => { From 873f7cb83367dc601768b1ce015debb96faf357c Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Fri, 7 May 2021 10:40:06 +0300 Subject: [PATCH 06/36] feat: rename HTTP span --- .../src/instrumentation.ts | 33 +++++---- .../src/utils.ts | 6 +- .../test/index.test.ts | 67 ++++++++++++------- 3 files changed, 60 insertions(+), 46 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts index 7937af598f..99ef1753f7 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts @@ -115,14 +115,14 @@ export default class RouterInstrumentation extends InstrumentationBase< if (utils.isInternal(this.handle) || this.handle.length > 3) { return original.call(this, req, res, next); } - const { span, wrappedNext } = instrumentation._setupSpan( + const { context, wrappedNext } = instrumentation._setupSpan( this, req, res, next ); return api.context.with( - api.setSpan(api.context.active(), span), + context, original, this, req, @@ -145,14 +145,14 @@ export default class RouterInstrumentation extends InstrumentationBase< if (utils.isInternal(this.handle) || this.handle.length !== 4) { return original.call(this, error, req, res, next); } - const { span, wrappedNext } = instrumentation._setupSpan( + const { context, wrappedNext } = instrumentation._setupSpan( this, req, res, next ); return api.context.with( - api.setSpan(api.context.active(), span), + context, original, this, error, @@ -184,6 +184,9 @@ export default class RouterInstrumentation extends InstrumentationBase< [types.CustomAttributeNames.TYPE]: type, [SemanticAttributes.HTTP_ROUTE]: route, }; + + const parent = api.context.active(); + const parentSpan = api.getSpan(parent); const span = this.tracer.startSpan( spanName, { @@ -192,26 +195,20 @@ export default class RouterInstrumentation extends InstrumentationBase< api.context.active() ); - let called = false; - const endSpan = () => { - if (!called) { - called = true; - // This is not the way to get HTTP span. Open issues: #466 and #464 - utils.renameHttpSpan(api.getSpan(api.context.active()), layer.method, route); - return span.end(); - } - }; - // prependListener fires correctly, if syncronous internal handlers would be tracked as well - // TODO: define what "correctly" means here. Also affects the renaming of http span. - res.prependOnceListener('finish', endSpan); + utils.renameHttpSpan(parentSpan, layer.method, route); + // make sure spans are ended at least when response is finished + res.prependOnceListener('finish', () => span.end()); const wrappedNext: types.Next = (...args) => { - endSpan(); + span.end(); + if (parent) { + return api.context.with(parent, next, undefined, ...args); + } return next(...args); }; return { - span, + context: api.setSpan(parent, span), wrappedNext, }; } diff --git a/plugins/node/opentelemetry-instrumentation-router/src/utils.ts b/plugins/node/opentelemetry-instrumentation-router/src/utils.ts index 62ba416036..d75d7fca90 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/utils.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/utils.ts @@ -27,14 +27,16 @@ export const isInternal = (fn: Function) => { } return false; }; + export const getRoute = (req: types.RouterIncomingMessage) => req.baseUrl + (req.route?.path || '') || '/'; + export const renameHttpSpan = ( span?: types.InstrumentationSpan, method?: string, route?: string ) => { - if (method && route && span?.name?.startsWith('HTTP ')) { - (span as types.InstrumentationSpan).updateName(`${method} ${route}`); + if (typeof method === 'string' && typeof route === 'string' && span?.name?.startsWith('HTTP ')) { + (span as types.InstrumentationSpan).updateName(`${method.toUpperCase()} ${route}`); } }; diff --git a/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts b/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts index 258934595f..7540291501 100644 --- a/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts +++ b/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts @@ -15,6 +15,7 @@ */ import { context, setSpan } from '@opentelemetry/api'; +import * as api from '@opentelemetry/api'; import { NodeTracerProvider } from '@opentelemetry/node'; import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks'; import { @@ -22,9 +23,6 @@ import { SimpleSpanProcessor, } from '@opentelemetry/tracing'; -import { diag, DiagConsoleLogger, DiagLogLevel } from '@opentelemetry/api'; -diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.VERBOSE); - import Instrumentation from '../src'; const plugin = new Instrumentation(); @@ -33,7 +31,7 @@ import * as Router from 'router'; import * as assert from 'assert'; import { AddressInfo } from 'net'; -const createServer = async () => { +const createServer = async ({ parentSpan } = {}) => { const router = new Router(); router.use((req, res, next) => { @@ -45,8 +43,8 @@ const createServer = async () => { next(new Error('Oops')); }); - router.get('/', (req, res) => { - res.end('Hello World!'); + router.get('/deep/hello/someone', (req, res, next) => { + next(); }); const helloRouter = new Router(); @@ -79,14 +77,23 @@ const createServer = async () => { }); router.use(errHandler); - const server = http.createServer((req, res) => { + const defaultHandler = (req, res) => { router(req, res, (err) => { + if (err) { + res.statusCode = 500; + res.end(err.message); + } if (!res.headersSent) { res.statusCode = 404; res.end('Not Found'); } + parentSpan && parentSpan.end(); }); - }); + }; + const handler = parentSpan ? + context.bind(defaultHandler, setSpan(context.active(), parentSpan)) : + defaultHandler; + const server = http.createServer(handler); await new Promise(resolve => server.listen(0, resolve)); @@ -118,7 +125,7 @@ const spans = { anonymousUse: { type: 'middleware', route: '/' }, preName: { type: 'request_handler', name: 'preName', route: '/hello/:name' }, announceRude: { type: 'request_handler', name: 'announceRude', route: '/hello/:name' }, - postMiddleware: { name: 'postMiddleware', type: 'middleware', route: '/:name' }, + postMiddleware: { type: 'middleware', name: 'postMiddleware', route: '/:name' }, }; @@ -132,8 +139,8 @@ describe('Router instrumentation', () => { let contextManager: AsyncHooksContextManager; let server: http.Server; - const request = (path: string, options?: http.ClientRequestArgs | string) => { - const port = (server.address() as AddressInfo).port; + const request = (path: string, serverOverwrite?: http.Server) => { + const port = ((serverOverwrite ?? server).address() as AddressInfo).port; return new Promise((resolve, reject) => { return http.get(`http://localhost:${port}${path}`, (resp) => { let data = ''; @@ -242,24 +249,32 @@ describe('Router instrumentation', () => { }); }); - it('should rename HTTP span', async () => { - // const httpSpan: types.InstrumentationSpan = tracer.startSpan('HTTP GET'); - - // try { - // const res = await httpRequest.get( - // `http://localhost:${testLocalPort}/route/hello` - // ); - // httpSpan.end(); - // assert.strictEqual(memoryExporter.getFinishedSpans().length, 3); - // assert.strictEqual(httpSpan.name, 'GET /route/:param'); - // assert.strictEqual(res, '{"route":"hello"}'); - // } finally { - // testLocalServer.close(); - // } + it('should create spans under parent', async () => { + const parentSpan = tracer.startSpan('HTTP GET'); + const testLocalServer = await createServer({ parentSpan }); + + try { + assert.strictEqual(await request('/deep/hello/someone', testLocalServer), 'Hello, someone!'); + assertSpans( + memoryExporter.getFinishedSpans(), + [ + spans.anonymousUse, + { ...spans.preName, name: undefined, route: '/deep/hello/someone' }, + { ...spans.preName, route: '/deep/hello/:name' }, + ] + ); + + memoryExporter.getFinishedSpans().forEach((span, idx) => { + assert.strictEqual(span.parentSpanId, parentSpan.spanContext.spanId, `span[${idx}] has invalid parent`); + }); + assert.strictEqual(parentSpan.name, 'GET /deep/hello/someone'); + } finally { + testLocalServer.close(); + } }); }); - describe('Disabling instrumentation', () => { + describe.skip('Disabling instrumentation', () => { it('should not create new spans', async () => { plugin.disable(); const rootSpan = tracer.startSpan('rootSpan'); From 7c2f0e37e8555c3b775a64319f3704a73651a22d Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Fri, 7 May 2021 10:41:39 +0300 Subject: [PATCH 07/36] test: test disabling --- .../test/index.test.ts | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts b/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts index 7540291501..8814bbbc7a 100644 --- a/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts +++ b/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts @@ -274,16 +274,11 @@ describe('Router instrumentation', () => { }); }); - describe.skip('Disabling instrumentation', () => { + describe('Disabling instrumentation', () => { it('should not create new spans', async () => { plugin.disable(); - const rootSpan = tracer.startSpan('rootSpan'); - - await context.with(setSpan(context.active(), rootSpan), async () => { - rootSpan.end(); - assert.strictEqual(memoryExporter.getFinishedSpans().length, 1); - assert.notStrictEqual(memoryExporter.getFinishedSpans()[0], undefined); - }); + await request('/hello/nobody'); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); }); }); }); From 0e4ecfd693ac0d82bcbd95f7e23f32ca7c98d924 Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Fri, 7 May 2021 10:45:25 +0300 Subject: [PATCH 08/36] test: remove usage of rootSpan in tests --- .../test/index.test.ts | 96 +++++++------------ 1 file changed, 34 insertions(+), 62 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts b/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts index 8814bbbc7a..8819d65b42 100644 --- a/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts +++ b/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts @@ -176,77 +176,49 @@ describe('Router instrumentation', () => { describe('Instrumenting handler calls', () => { it('should create a span for each handler', async () => { - const rootSpan = tracer.startSpan('clientSpan'); - - await context.with(setSpan(context.active(), rootSpan), async () => { - assert.strictEqual(await request('/hello/nobody'), 'How rude!'); - rootSpan.end(); - - assertSpans( - memoryExporter.getFinishedSpans(), - [ - spans.anonymousUse, - spans.preName, - spans.announceRude, - null, - ] - ); - }); + assert.strictEqual(await request('/hello/nobody'), 'How rude!'); + assertSpans( + memoryExporter.getFinishedSpans(), + [ + spans.anonymousUse, + spans.preName, + spans.announceRude, + ] + ); }); it('should gather full route for nested routers', async () => { - const rootSpan = tracer.startSpan('clientSpan'); - - await context.with(setSpan(context.active(), rootSpan), async () => { - assert.strictEqual(await request('/deep/hello/world'), 'Hello, world!'); - rootSpan.end(); - - assertSpans( - memoryExporter.getFinishedSpans(), - [ - spans.anonymousUse, - { ...spans.preName, route: '/deep/hello/:name' }, - null, - ] - ); - }); + assert.strictEqual(await request('/deep/hello/world'), 'Hello, world!'); + assertSpans( + memoryExporter.getFinishedSpans(), + [ + spans.anonymousUse, + { ...spans.preName, route: '/deep/hello/:name' }, + ] + ); }); it('should create spans for requests that did not result with response from the router', async () => { - const rootSpan = tracer.startSpan('clientSpan'); - - await context.with(setSpan(context.active(), rootSpan), async () => { - assert.strictEqual(await request('/not-found'), 'Not Found'); - rootSpan.end(); - - assertSpans( - memoryExporter.getFinishedSpans(), - [ - spans.anonymousUse, - { ...spans.postMiddleware, route: '/' }, - null, - ] - ); - }); + assert.strictEqual(await request('/not-found'), 'Not Found'); + assertSpans( + memoryExporter.getFinishedSpans(), + [ + spans.anonymousUse, + { ...spans.postMiddleware, route: '/' }, + ] + ); }); it('should create spans for errored routes', async () => { - const rootSpan = tracer.startSpan('clientSpan'); - - await context.with(setSpan(context.active(), rootSpan), async () => { - assert.strictEqual(await request('/err'), 'Server error: Oops!'); - rootSpan.end(); - - assertSpans( - memoryExporter.getFinishedSpans(), - [ - spans.anonymousUse, - { ...spans.preName, name: undefined, route: '/err' }, - { ...spans.anonymousUse, name: 'errHandler', route: '/err' }, - null, - ] - ); - }); + assert.strictEqual(await request('/err'), 'Server error: Oops!'); + assertSpans( + memoryExporter.getFinishedSpans(), + [ + spans.anonymousUse, + { ...spans.preName, name: undefined, route: '/err' }, + { ...spans.anonymousUse, name: 'errHandler', route: '/err' }, + ] + ); }); it('should create spans under parent', async () => { From 147ed6b637cd48d69b477a722d0286d25ad919b1 Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Fri, 7 May 2021 10:46:08 +0300 Subject: [PATCH 09/36] fix: use a stable version API in inst implementation --- plugins/node/opentelemetry-instrumentation-router/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/node/opentelemetry-instrumentation-router/package.json b/plugins/node/opentelemetry-instrumentation-router/package.json index 5b59492c95..3306768116 100644 --- a/plugins/node/opentelemetry-instrumentation-router/package.json +++ b/plugins/node/opentelemetry-instrumentation-router/package.json @@ -58,7 +58,7 @@ "typescript": "4.1.3" }, "dependencies": { - "@opentelemetry/api": "^1.0.0-rc.0", + "@opentelemetry/api": "^0.18.0", "@opentelemetry/instrumentation": "^0.19.0", "@opentelemetry/semantic-conventions": "^0.19.0" } From b82ab4a8106dfce24e728a65742445483104c4d5 Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Fri, 7 May 2021 10:46:50 +0300 Subject: [PATCH 10/36] fix: fix typo in assertSpans --- .../opentelemetry-instrumentation-router/test/index.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts b/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts index 8819d65b42..96151e5bfe 100644 --- a/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts +++ b/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts @@ -102,7 +102,7 @@ const createServer = async ({ parentSpan } = {}) => { const assertSpans = (actualSpans: any[], expectedSpans: any[]) => { assert(Array.isArray(actualSpans), 'Expected `actualSpans` to be an array'); - assert(Array.isArray(actualSpans), 'Expected `actualSpans` to be an array'); + assert(Array.isArray(expectedSpans), 'Expected `expectedSpans` to be an array'); assert.strictEqual(actualSpans.length, expectedSpans.length, 'Expected span count different from actual'); actualSpans.forEach((span, idx) => { const expected = expectedSpans[idx]; From 97ccf0ca349e25a8a2eefd27cbe8fd92aace28c0 Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Fri, 7 May 2021 11:16:41 +0300 Subject: [PATCH 11/36] style: fix typing and linting issues --- .../src/instrumentation.ts | 35 ++--- .../src/router.d.ts | 88 +++++++++---- .../src/types.ts | 23 ---- .../src/utils.ts | 13 +- .../test/index.test.ts | 121 ++++++++++-------- 5 files changed, 151 insertions(+), 129 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts index 99ef1753f7..24ffd0dce7 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts @@ -104,13 +104,13 @@ export default class RouterInstrumentation extends InstrumentationBase< } // Define handle_request wrapper separately to ensure the signature has the correct length - private _requestHandlerPatcher(original: types.Layer['handle_request']) { + private _requestHandlerPatcher(original: Router.Layer['handle_request']) { const instrumentation = this; return function wrapped_handle_request( - this: types.Layer, - req: types.RouterIncomingMessage, + this: Router.Layer, + req: Router.RoutedRequest, res: http.ServerResponse, - next: types.Next + next: Router.NextFunction ) { if (utils.isInternal(this.handle) || this.handle.length > 3) { return original.call(this, req, res, next); @@ -121,26 +121,19 @@ export default class RouterInstrumentation extends InstrumentationBase< res, next ); - return api.context.with( - context, - original, - this, - req, - res, - wrappedNext - ); + return api.context.with(context, original, this, req, res, wrappedNext); }; } // Define handle_error wrapper separately to ensure the signature has the correct length - private _errorHandlerPatcher(original: types.Layer['handle_error']) { + private _errorHandlerPatcher(original: Router.Layer['handle_error']) { const instrumentation = this; return function wrapped_handle_request( - this: types.Layer, + this: Router.Layer, error: Error, - req: types.RouterIncomingMessage, + req: Router.RoutedRequest, res: http.ServerResponse, - next: types.Next + next: Router.NextFunction ) { if (utils.isInternal(this.handle) || this.handle.length !== 4) { return original.call(this, error, req, res, next); @@ -164,10 +157,10 @@ export default class RouterInstrumentation extends InstrumentationBase< } private _setupSpan( - layer: types.Layer, - req: types.RouterIncomingMessage, + layer: Router.Layer, + req: Router.RoutedRequest, res: http.ServerResponse, - next: types.Next + next: Router.NextFunction ) { const fnName = layer.handle.name || undefined; const type = layer.method @@ -199,10 +192,10 @@ export default class RouterInstrumentation extends InstrumentationBase< // make sure spans are ended at least when response is finished res.prependOnceListener('finish', () => span.end()); - const wrappedNext: types.Next = (...args) => { + const wrappedNext: Router.NextFunction = (...args) => { span.end(); if (parent) { - return api.context.with(parent, next, undefined, ...args); + return api.context.with(parent, next, undefined, ...args); } return next(...args); }; diff --git a/plugins/node/opentelemetry-instrumentation-router/src/router.d.ts b/plugins/node/opentelemetry-instrumentation-router/src/router.d.ts index 78ee77dfda..613f68c946 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/router.d.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/router.d.ts @@ -21,7 +21,6 @@ declare module 'router' { export = Router; namespace Router { - interface RouterOptions { strict?: boolean; caseSensitive?: boolean; @@ -29,41 +28,64 @@ declare module 'router' { } interface Layer { - name: string, - handle: RequestHandler | ErrorRequestHandler, - handle_request: RequestHandler, - handle_error: ErrorRequestHandler, - match: (path: string) => boolean, + name: string; + method: string; + handle: RequestHandler | ErrorRequestHandler; + handle_request: RequestHandler; + handle_error: ErrorRequestHandler; + match: (path: string) => boolean; } interface IncomingRequest extends http.IncomingMessage { - url: string, - method: string, - originalUrl?: string, + url: string; + method: string; + originalUrl?: string; params?: { - [key: string]: any, - }, + [key: string]: any; + }; } interface RoutedRequest extends IncomingRequest { - baseUrl: string, - next?: NextFunction, - route?: IRoute + baseUrl: string; + next?: NextFunction; + route?: IRoute; } - type RequestParamHandler = (req: IncomingRequest, res: http.ServerResponse, next: NextFunction, value: string, name: string) => void; - - type RouteHandler = (req: RoutedRequest, res: http.ServerResponse, next: NextFunction) => void; - type RequestHandler = (req: IncomingRequest, res: http.ServerResponse, next: NextFunction) => void; - - type NextFunction = (err?: Error | "route" | "router") => void; + type RequestParamHandler = ( + req: IncomingRequest, + res: http.ServerResponse, + next: NextFunction, + value: string, + name: string + ) => void; + + type RouteHandler = ( + req: RoutedRequest, + res: http.ServerResponse, + next: NextFunction + ) => void; + type RequestHandler = ( + req: IncomingRequest, + res: http.ServerResponse, + next: NextFunction + ) => void; + + type NextFunction = (err?: Error | 'route' | 'router') => void; type Callback = (err?: Error) => void; - type ErrorRequestHandler = (err: Error, req: IncomingRequest, res: http.ServerResponse, next: NextFunction) => void; + type ErrorRequestHandler = ( + err: Error, + req: IncomingRequest, + res: http.ServerResponse, + next: NextFunction + ) => void; type PathParams = string | RegExp | Array; - type RequestHandlerParams = RouteHandler | ErrorRequestHandler | Array; + type RequestHandlerParams = + | RouteHandler + | ErrorRequestHandler + | Array; interface IRouterMatcher { (path: PathParams, ...handlers: RouteHandler[]): T; @@ -109,7 +131,9 @@ declare module 'router' { * * @deprecated since version 4.11 */ - param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this; + param( + callback: (name: string, matcher: RegExp) => RequestParamHandler + ): this; /** * Special-cased "all" method, applying the given route `path`, @@ -119,7 +143,11 @@ declare module 'router' { use: IRouterHandler & IRouterMatcher; - handle: (req: http.IncomingMessage, res: http.ServerResponse, cb: Callback) => void; + handle: ( + req: http.IncomingMessage, + res: http.ServerResponse, + cb: Callback + ) => void; route(prefix: PathParams): IRoute; // Stack of configured routes @@ -142,7 +170,7 @@ declare module 'router' { copy: IRouterMatcher; link: IRouterMatcher; lock: IRouterMatcher; - "m-search": IRouterMatcher; + 'm-search': IRouterMatcher; merge: IRouterMatcher; mkactivity: IRouterMatcher; mkcalendar: IRouterMatcher; @@ -188,7 +216,7 @@ declare module 'router' { copy: IRouterHandler; link: IRouterHandler; lock: IRouterHandler; - "m-search": IRouterHandler; + 'm-search': IRouterHandler; merge: IRouterHandler; mkactivity: IRouterHandler; mkcalendar: IRouterHandler; @@ -212,9 +240,13 @@ declare module 'router' { } interface RouterConstructor extends IRouter { - new(options?: RouterOptions): IRouter & ((req: http.IncomingMessage, res: http.ServerResponse, cb: Callback) => void); + new (options?: RouterOptions): IRouter & + (( + req: http.IncomingMessage, + res: http.ServerResponse, + cb: Callback + ) => void); } - } const Router: Router.RouterConstructor; diff --git a/plugins/node/opentelemetry-instrumentation-router/src/types.ts b/plugins/node/opentelemetry-instrumentation-router/src/types.ts index 4ef3b9c1e4..c1baca7525 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/types.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/types.ts @@ -13,35 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import * as http from 'http'; import { Span } from '@opentelemetry/api'; export enum LayerType { MIDDLEWARE = 'middleware', REQUEST_HANDLER = 'request_handler', } -export interface RouterIncomingMessage extends http.IncomingMessage { - baseUrl: string; - route?: { - path: string; - }; -} -export type Next = (...args: any[]) => void; -export interface Layer { - handle: Function; - method?: string; - handle_request: ( - req: RouterIncomingMessage, - res: http.ServerResponse, - next: Next - ) => void; - handle_error: ( - error: Error, - req: RouterIncomingMessage, - res: http.ServerResponse, - next: Next - ) => void; -} export enum CustomAttributeNames { TYPE = 'router.type', diff --git a/plugins/node/opentelemetry-instrumentation-router/src/utils.ts b/plugins/node/opentelemetry-instrumentation-router/src/utils.ts index d75d7fca90..92afdba92f 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/utils.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/utils.ts @@ -16,6 +16,7 @@ import * as constants from './constants'; import * as types from './types'; +import * as Router from 'router'; export const isInternal = (fn: Function) => { // Note that both of those functions are sync @@ -28,7 +29,7 @@ export const isInternal = (fn: Function) => { return false; }; -export const getRoute = (req: types.RouterIncomingMessage) => +export const getRoute = (req: Router.RoutedRequest) => req.baseUrl + (req.route?.path || '') || '/'; export const renameHttpSpan = ( @@ -36,7 +37,13 @@ export const renameHttpSpan = ( method?: string, route?: string ) => { - if (typeof method === 'string' && typeof route === 'string' && span?.name?.startsWith('HTTP ')) { - (span as types.InstrumentationSpan).updateName(`${method.toUpperCase()} ${route}`); + if ( + typeof method === 'string' && + typeof route === 'string' && + span?.name?.startsWith('HTTP ') + ) { + (span as types.InstrumentationSpan).updateName( + `${method.toUpperCase()} ${route}` + ); } }; diff --git a/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts b/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts index 96151e5bfe..ae10d69866 100644 --- a/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts +++ b/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts @@ -15,7 +15,6 @@ */ import { context, setSpan } from '@opentelemetry/api'; -import * as api from '@opentelemetry/api'; import { NodeTracerProvider } from '@opentelemetry/node'; import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks'; import { @@ -24,6 +23,7 @@ import { } from '@opentelemetry/tracing'; import Instrumentation from '../src'; +import { InstrumentationSpan } from '../src/types'; const plugin = new Instrumentation(); import * as http from 'http'; @@ -31,7 +31,9 @@ import * as Router from 'router'; import * as assert from 'assert'; import { AddressInfo } from 'net'; -const createServer = async ({ parentSpan } = {}) => { +const createServer = async ({ + parentSpan, +}: { parentSpan?: InstrumentationSpan } = {}) => { const router = new Router(); router.use((req, res, next) => { @@ -57,6 +59,7 @@ const createServer = async ({ parentSpan } = {}) => { }; helloRouter.get('/:name', preName); + /* eslint-disable-next-line prefer-arrow-callback */ helloRouter.get('/:name', function announceRude(req, res, next) { res.end('How rude!'); }); @@ -72,13 +75,17 @@ const createServer = async ({ parentSpan } = {}) => { res.end(`Server error: ${err.message}!`); }; + /* eslint-disable-next-line prefer-arrow-callback */ router.use(function postMiddleware(req, res, next) { next(); }); router.use(errHandler); - const defaultHandler = (req, res) => { - router(req, res, (err) => { + const defaultHandler = ( + req: http.IncomingMessage, + res: http.ServerResponse + ) => { + router(req, res, err => { if (err) { res.statusCode = 500; res.end(err.message); @@ -90,9 +97,9 @@ const createServer = async ({ parentSpan } = {}) => { parentSpan && parentSpan.end(); }); }; - const handler = parentSpan ? - context.bind(defaultHandler, setSpan(context.active(), parentSpan)) : - defaultHandler; + const handler = parentSpan + ? context.bind(defaultHandler, setSpan(context.active(), parentSpan)) + : defaultHandler; const server = http.createServer(handler); await new Promise(resolve => server.listen(0, resolve)); @@ -102,8 +109,15 @@ const createServer = async ({ parentSpan } = {}) => { const assertSpans = (actualSpans: any[], expectedSpans: any[]) => { assert(Array.isArray(actualSpans), 'Expected `actualSpans` to be an array'); - assert(Array.isArray(expectedSpans), 'Expected `expectedSpans` to be an array'); - assert.strictEqual(actualSpans.length, expectedSpans.length, 'Expected span count different from actual'); + assert( + Array.isArray(expectedSpans), + 'Expected `expectedSpans` to be an array' + ); + assert.strictEqual( + actualSpans.length, + expectedSpans.length, + 'Expected span count different from actual' + ); actualSpans.forEach((span, idx) => { const expected = expectedSpans[idx]; if (expected === null) return; @@ -124,11 +138,18 @@ const assertSpans = (actualSpans: any[], expectedSpans: any[]) => { const spans = { anonymousUse: { type: 'middleware', route: '/' }, preName: { type: 'request_handler', name: 'preName', route: '/hello/:name' }, - announceRude: { type: 'request_handler', name: 'announceRude', route: '/hello/:name' }, - postMiddleware: { type: 'middleware', name: 'postMiddleware', route: '/:name' }, + announceRude: { + type: 'request_handler', + name: 'announceRude', + route: '/hello/:name', + }, + postMiddleware: { + type: 'middleware', + name: 'postMiddleware', + route: '/:name', + }, }; - describe('Router instrumentation', () => { const provider = new NodeTracerProvider(); const memoryExporter = new InMemorySpanExporter(); @@ -142,7 +163,7 @@ describe('Router instrumentation', () => { const request = (path: string, serverOverwrite?: http.Server) => { const port = ((serverOverwrite ?? server).address() as AddressInfo).port; return new Promise((resolve, reject) => { - return http.get(`http://localhost:${port}${path}`, (resp) => { + return http.get(`http://localhost:${port}${path}`, resp => { let data = ''; resp.on('data', chunk => { data += chunk; @@ -160,7 +181,7 @@ describe('Router instrumentation', () => { beforeEach(async () => { plugin.enable(); // To force `require-in-the-middle` to definitely reload and patch the layer - require('router/lib/layer.js') + require('router/lib/layer.js'); server = await createServer(); contextManager = new AsyncHooksContextManager(); context.setGlobalContextManager(contextManager.enable()); @@ -177,67 +198,59 @@ describe('Router instrumentation', () => { describe('Instrumenting handler calls', () => { it('should create a span for each handler', async () => { assert.strictEqual(await request('/hello/nobody'), 'How rude!'); - assertSpans( - memoryExporter.getFinishedSpans(), - [ - spans.anonymousUse, - spans.preName, - spans.announceRude, - ] - ); + assertSpans(memoryExporter.getFinishedSpans(), [ + spans.anonymousUse, + spans.preName, + spans.announceRude, + ]); }); it('should gather full route for nested routers', async () => { assert.strictEqual(await request('/deep/hello/world'), 'Hello, world!'); - assertSpans( - memoryExporter.getFinishedSpans(), - [ - spans.anonymousUse, - { ...spans.preName, route: '/deep/hello/:name' }, - ] - ); + assertSpans(memoryExporter.getFinishedSpans(), [ + spans.anonymousUse, + { ...spans.preName, route: '/deep/hello/:name' }, + ]); }); it('should create spans for requests that did not result with response from the router', async () => { assert.strictEqual(await request('/not-found'), 'Not Found'); - assertSpans( - memoryExporter.getFinishedSpans(), - [ - spans.anonymousUse, - { ...spans.postMiddleware, route: '/' }, - ] - ); + assertSpans(memoryExporter.getFinishedSpans(), [ + spans.anonymousUse, + { ...spans.postMiddleware, route: '/' }, + ]); }); it('should create spans for errored routes', async () => { assert.strictEqual(await request('/err'), 'Server error: Oops!'); - assertSpans( - memoryExporter.getFinishedSpans(), - [ - spans.anonymousUse, - { ...spans.preName, name: undefined, route: '/err' }, - { ...spans.anonymousUse, name: 'errHandler', route: '/err' }, - ] - ); + assertSpans(memoryExporter.getFinishedSpans(), [ + spans.anonymousUse, + { ...spans.preName, name: undefined, route: '/err' }, + { ...spans.anonymousUse, name: 'errHandler', route: '/err' }, + ]); }); it('should create spans under parent', async () => { - const parentSpan = tracer.startSpan('HTTP GET'); + const parentSpan: InstrumentationSpan = tracer.startSpan('HTTP GET'); const testLocalServer = await createServer({ parentSpan }); try { - assert.strictEqual(await request('/deep/hello/someone', testLocalServer), 'Hello, someone!'); - assertSpans( - memoryExporter.getFinishedSpans(), - [ - spans.anonymousUse, - { ...spans.preName, name: undefined, route: '/deep/hello/someone' }, - { ...spans.preName, route: '/deep/hello/:name' }, - ] + assert.strictEqual( + await request('/deep/hello/someone', testLocalServer), + 'Hello, someone!' ); + assertSpans(memoryExporter.getFinishedSpans(), [ + spans.anonymousUse, + { ...spans.preName, name: undefined, route: '/deep/hello/someone' }, + { ...spans.preName, route: '/deep/hello/:name' }, + ]); memoryExporter.getFinishedSpans().forEach((span, idx) => { - assert.strictEqual(span.parentSpanId, parentSpan.spanContext.spanId, `span[${idx}] has invalid parent`); + assert.strictEqual( + span.parentSpanId, + parentSpan.context().spanId, + `span[${idx}] has invalid parent` + ); }); assert.strictEqual(parentSpan.name, 'GET /deep/hello/someone'); } finally { From 8572f71fb4899f11c380d94e074ab6ba757debfa Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Fri, 7 May 2021 11:30:47 +0300 Subject: [PATCH 12/36] docs: fill in blanks in the readme --- .../README.md | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-router/README.md b/plugins/node/opentelemetry-instrumentation-router/README.md index 5d1e6b5a2e..90f2602da3 100644 --- a/plugins/node/opentelemetry-instrumentation-router/README.md +++ b/plugins/node/opentelemetry-instrumentation-router/README.md @@ -1,11 +1,11 @@ -# OpenTelemetry __package name__ Instrumentation for Node.js +# OpenTelemetry router Instrumentation for Node.js [![Gitter chat][gitter-image]][gitter-url] [![dependencies][dependencies-image]][dependencies-url] [![devDependencies][devDependencies-image]][devDependencies-url] [![Apache License][license-image]][license-image] -This module provides automatic instrumentation for [`__package name__`](https://github.com/__package name__/node-__package name__) and allows the user to automatically collect trace data and export them to their backend of choice. +This module provides automatic instrumentation for [`router`](https://github.com/pillarjs/router) and allows the user to automatically collect trace data and export them to their backend of choice. For automatic instrumentation see the [@opentelemetry/node](https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-node) package. @@ -13,18 +13,18 @@ For automatic instrumentation see the ## Installation ```bash -npm install --save @opentelemetry/instrumentation-__package name__ +npm install --save @opentelemetry/instrumentation-router ``` ### Supported Versions - - `>=4.0.0` + - `>=1.0.0` ## Usage ```js -const { __package name__Instrumentation } = require('@opentelemetry/instrumentation-__package name__'); const { ConsoleSpanExporter, SimpleSpanProcessor } = require('@opentelemetry/tracing'); const { NodeTracerProvider } = require('@opentelemetry/node'); const { registerInstrumentations } = require('@opentelemetry/instrumentation'); +const RouterInstrumentation = require('@opentelemetry/instrumentation-router'); const provider = new NodeTracerProvider(); @@ -32,12 +32,12 @@ provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter())); provider.register(); registerInstrumentations({ - instrumentations: [new __package name__Instrumentation()], + instrumentations: [new RouterInstrumentation()], tracerProvider: provider, }); ``` -See [examples/__package name__](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/examples/__package name__) for a short example. +See [examples/router](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/examples/router) for a short example. ## Useful links - For more information on OpenTelemetry, visit: @@ -52,7 +52,7 @@ Apache 2.0 - See [LICENSE][license-url] for more information. [gitter-url]: https://gitter.im/open-telemetry/opentelemetry-node?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge [license-url]: https://github.com/open-telemetry/opentelemetry-js-contrib/blob/main/LICENSE [license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat -[dependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib/status.svg?path=packages/opentelemetry-instrumentation-__package name__ -[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=packages%2Fopentelemetry-instrumentation-__package name__ -[devDependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib/dev-status.svg?path=packages/opentelemetry-instrumentation-__package name__ -[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=packages%2Fopentelemetry-instrumentation-__package name__&type=dev +[dependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib/status.svg?path=packages/opentelemetry-instrumentation-router +[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=packages%2Fopentelemetry-instrumentation-router +[devDependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib/dev-status.svg?path=packages/opentelemetry-instrumentation-router +[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=packages%2Fopentelemetry-instrumentation-router&type=dev From f2b5ce213d984939bb90f05ed859f2a200caba96 Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Fri, 7 May 2021 12:10:06 +0300 Subject: [PATCH 13/36] docs: add example --- examples/router/README.md | 45 +++++++++++++++++ examples/router/client.js | 35 +++++++++++++ examples/router/package.json | 44 ++++++++++++++++ examples/router/server.js | 38 ++++++++++++++ examples/router/tracer.js | 50 +++++++++++++++++++ .../src/instrumentation.ts | 6 +-- 6 files changed, 215 insertions(+), 3 deletions(-) create mode 100644 examples/router/README.md create mode 100644 examples/router/client.js create mode 100644 examples/router/package.json create mode 100644 examples/router/server.js create mode 100644 examples/router/tracer.js diff --git a/examples/router/README.md b/examples/router/README.md new file mode 100644 index 0000000000..a378da6f63 --- /dev/null +++ b/examples/router/README.md @@ -0,0 +1,45 @@ +# Overview + +OpenTelemetry Router Instrumentation allows the user to automatically collect trace data and export them to the backend of choice (we can use Zipkin or Jaeger for this example). This example demonstrates tracing calls made to Router API. All generated spans include following attributes: + +- `http.route`: resolved route; +- `router.name`: the name of the handler or middleware; +- `router.type`: either `middleware` or `request_handler`; +- `router.version`: `router` version running. + +## Setup + +Setup [Zipkin Tracing](https://zipkin.io/pages/quickstart.html) +or +Setup [Jaeger Tracing](https://www.jaegertracing.io/docs/latest/getting-started/#all-in-one) + +## Run the Application + +First install the dependencies: + +```sh +npm install +``` + +### Zipkin + +```sh +npm run zipkin:server # Run the server +npm run zipkin:client # Run the client in a separate terminal +``` + +### Jaeger + +```sh +npm run jaeger:server # Run the server +npm run jaeger:client # Run the client in a separate terminal +``` + +## Useful links + +- For more information on OpenTelemetry, visit: +- For more information on OpenTelemetry for Node.js, visit: + +## LICENSE + +Apache License 2.0 diff --git a/examples/router/client.js b/examples/router/client.js new file mode 100644 index 0000000000..aef9f0acb6 --- /dev/null +++ b/examples/router/client.js @@ -0,0 +1,35 @@ +'use strict'; + +// required to initialize the service name for the auto-instrumentation +require('./tracer')('example-client'); +// eslint-disable-next-line import/order +const http = require('http'); + +/** A function which makes requests and handles response. */ +function makeRequest(path) { + // span corresponds to outgoing requests. Here, we have manually created + // the span, which is created to track work that happens outside of the + // request lifecycle entirely. + http.get({ + host: 'localhost', + headers: { + accept: 'text/plain', + }, + port: 8080, + path, + }, (response) => { + response.on('data', (chunk) => console.log(path, '::', chunk.toString('utf8'))); + response.on('end', () => { + console.log(path, 'status', response.statusCode); + }); + }); + + // The process must live for at least the interval past any traces that + // must be exported, or some risk being lost if they are recorded after the + // last export. + console.log('Sleeping 5 seconds before shutdown to ensure all records are flushed.'); + setTimeout(() => { console.log('Completed.'); }, 5000); +} + +makeRequest('/hello/world'); +makeRequest('/bye/world'); diff --git a/examples/router/package.json b/examples/router/package.json new file mode 100644 index 0000000000..2aab8aca31 --- /dev/null +++ b/examples/router/package.json @@ -0,0 +1,44 @@ +{ + "name": "router-example", + "private": true, + "version": "0.18.0", + "description": "Example of router integration with OpenTelemetry", + "main": "index.js", + "scripts": { + "zipkin:server": "cross-env EXPORTER=zipkin node ./server.js", + "zipkin:client": "cross-env EXPORTER=zipkin node ./client.js", + "jaeger:server": "cross-env EXPORTER=jaeger node ./server.js", + "jaeger:client": "cross-env EXPORTER=jaeger node ./client.js" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/open-telemetry/opentelemetry-js.git" + }, + "keywords": [ + "opentelemetry", + "http", + "tracing" + ], + "engines": { + "node": ">=8" + }, + "author": "OpenTelemetry Authors", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/open-telemetry/opentelemetry-js/issues" + }, + "dependencies": { + "@opentelemetry/api": "^0.18.0", + "@opentelemetry/exporter-jaeger": "^0.18.0", + "@opentelemetry/exporter-zipkin": "^0.18.0", + "@opentelemetry/instrumentation": "^0.18.0", + "@opentelemetry/instrumentation-http": "^0.18.0", + "@opentelemetry/instrumentation-router": "file:../../plugins/node/opentelemetry-instrumentation-router", + "@opentelemetry/node": "^0.18.0", + "router": "^1.3.5" + }, + "homepage": "https://github.com/open-telemetry/opentelemetry-js#readme", + "devDependencies": { + "cross-env": "^6.0.0" + } +} diff --git a/examples/router/server.js b/examples/router/server.js new file mode 100644 index 0000000000..e2bc0c6129 --- /dev/null +++ b/examples/router/server.js @@ -0,0 +1,38 @@ +'use strict'; + +const api = require('@opentelemetry/api'); +require('./tracer')('example-router-server'); + +// `setDefaultName` shows up in spans as the name +const setDefaultName = (req, res, next) => { + req.defaultName = 'Stranger'; + next(); +}; + +const http = require('http'); +const Router = require('router'); + +const router = Router(); + +router.use(setDefaultName); + +router.param('name', (req, res, next, name) => { + req.params.name = typeof name === 'string' ? name.toUpperCase() : req.defaultName; + next(); +}); + +// eslint-disable-next-line prefer-arrow-callback +router.get('/hello/:name', function greetingHandler(req, res) { + res.setHeader('Content-Type', 'text/plain; charset=utf-8'); + res.end(`Hello, ${req.params.name}!`); +}); + +// eslint-disable-next-line prefer-arrow-callback, func-names +const server = http.createServer(function (req, res) { + router(req, res, (...args) => { + res.statusCode = 404; + res.end(); + }); +}); + +server.listen(8080); diff --git a/examples/router/tracer.js b/examples/router/tracer.js new file mode 100644 index 0000000000..2ef67ea3ea --- /dev/null +++ b/examples/router/tracer.js @@ -0,0 +1,50 @@ +'use strict'; + +const opentelemetry = require('@opentelemetry/api'); + +const { diag, DiagConsoleLogger, DiagLogLevel } = opentelemetry; +diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.VERBOSE); + +const { registerInstrumentations } = require('@opentelemetry/instrumentation'); +const { NodeTracerProvider } = require('@opentelemetry/node'); +const { SimpleSpanProcessor, ConsoleSpanExporter } = require('@opentelemetry/tracing'); +const { JaegerExporter } = require('@opentelemetry/exporter-jaeger'); +const { ZipkinExporter } = require('@opentelemetry/exporter-zipkin'); + +const { HttpInstrumentation } = require('@opentelemetry/instrumentation-http'); +const { RouterInstrumentation } = require('@opentelemetry/instrumentation-router'); + +const Exporter = ((exporterParam) => { + if (typeof exporterParam === 'string') { + const exporterString = exporterParam.toLowerCase(); + if (exporterString.startsWith('z')) { + return ZipkinExporter; + } + if (exporterString.startsWith('j')) { + return JaegerExporter; + } + } + return ConsoleSpanExporter; +})(process.env.EXPORTER); + +module.exports = (serviceName) => { + const provider = new NodeTracerProvider(); + registerInstrumentations({ + tracerProvider: provider, + instrumentations: [ + HttpInstrumentation, + RouterInstrumentation, + ], + }); + + const exporter = new Exporter({ + serviceName, + }); + + provider.addSpanProcessor(new SimpleSpanProcessor(exporter)); + + // Initialize the OpenTelemetry APIs to use the NodeTracerProvider bindings + provider.register(); + + return opentelemetry.trace.getTracer('router-example'); +}; diff --git a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts index 24ffd0dce7..46bbce494f 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts @@ -179,14 +179,14 @@ export default class RouterInstrumentation extends InstrumentationBase< }; const parent = api.context.active(); - const parentSpan = api.getSpan(parent); + const parentSpan = api.getSpan(parent) as types.InstrumentationSpan; const span = this.tracer.startSpan( spanName, { attributes, }, - api.context.active() - ); + parent + ) as types.InstrumentationSpan; utils.renameHttpSpan(parentSpan, layer.method, route); // make sure spans are ended at least when response is finished From 51c6eca6818a0834571088210db3b58ba0e91beb Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Fri, 7 May 2021 12:15:31 +0300 Subject: [PATCH 14/36] fix: capture exceptions --- examples/router/client.js | 3 +++ examples/router/server.js | 5 +++++ .../src/instrumentation.ts | 9 ++++++--- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/examples/router/client.js b/examples/router/client.js index aef9f0acb6..9cd52f415a 100644 --- a/examples/router/client.js +++ b/examples/router/client.js @@ -32,4 +32,7 @@ function makeRequest(path) { } makeRequest('/hello/world'); +// 404 makeRequest('/bye/world'); +// error +makeRequest('/err'); diff --git a/examples/router/server.js b/examples/router/server.js index e2bc0c6129..574bf7df23 100644 --- a/examples/router/server.js +++ b/examples/router/server.js @@ -27,6 +27,11 @@ router.get('/hello/:name', function greetingHandler(req, res) { res.end(`Hello, ${req.params.name}!`); }); +// eslint-disable-next-line prefer-arrow-callback +router.get('/err', function erroringRoute(req, res, next) { + next(new Error('Broken!')); +}); + // eslint-disable-next-line prefer-arrow-callback, func-names const server = http.createServer(function (req, res) { router(req, res, (...args) => { diff --git a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts index 46bbce494f..c9577fd038 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts @@ -192,12 +192,15 @@ export default class RouterInstrumentation extends InstrumentationBase< // make sure spans are ended at least when response is finished res.prependOnceListener('finish', () => span.end()); - const wrappedNext: Router.NextFunction = (...args) => { + const wrappedNext: Router.NextFunction = (err) => { + if (err) { + span.recordException(err); + } span.end(); if (parent) { - return api.context.with(parent, next, undefined, ...args); + return api.context.with(parent, next, undefined, err); } - return next(...args); + return next(err); }; return { From 98919bb1f45aad4ed190a6c35f7235376c1c1477 Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Fri, 7 May 2021 12:26:46 +0300 Subject: [PATCH 15/36] fix: address linting issues --- examples/router/package.json | 1 + examples/router/server.js | 9 ++++++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/examples/router/package.json b/examples/router/package.json index 2aab8aca31..f7388d4733 100644 --- a/examples/router/package.json +++ b/examples/router/package.json @@ -35,6 +35,7 @@ "@opentelemetry/instrumentation-http": "^0.18.0", "@opentelemetry/instrumentation-router": "file:../../plugins/node/opentelemetry-instrumentation-router", "@opentelemetry/node": "^0.18.0", + "@opentelemetry/tracing": "^0.18.0", "router": "^1.3.5" }, "homepage": "https://github.com/open-telemetry/opentelemetry-js#readme", diff --git a/examples/router/server.js b/examples/router/server.js index 574bf7df23..8e06630d1e 100644 --- a/examples/router/server.js +++ b/examples/router/server.js @@ -1,6 +1,5 @@ 'use strict'; -const api = require('@opentelemetry/api'); require('./tracer')('example-router-server'); // `setDefaultName` shows up in spans as the name @@ -34,8 +33,12 @@ router.get('/err', function erroringRoute(req, res, next) { // eslint-disable-next-line prefer-arrow-callback, func-names const server = http.createServer(function (req, res) { - router(req, res, (...args) => { - res.statusCode = 404; + router(req, res, (error) => { + if (error) { + res.statusCode = 500; + } else { + res.statusCode = 404; + } res.end(); }); }); From 9cde95abb912b6738d105771fc42d387aa8da965 Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Fri, 7 May 2021 12:47:45 +0300 Subject: [PATCH 16/36] style: run eslint with `--ext ts` --- .../opentelemetry-instrumentation-router/src/instrumentation.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts index c9577fd038..8a8d126275 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts @@ -192,7 +192,7 @@ export default class RouterInstrumentation extends InstrumentationBase< // make sure spans are ended at least when response is finished res.prependOnceListener('finish', () => span.end()); - const wrappedNext: Router.NextFunction = (err) => { + const wrappedNext: Router.NextFunction = err => { if (err) { span.recordException(err); } From 45120b494ccc5ecf028df08ef245642f9f537c12 Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Fri, 7 May 2021 15:31:52 +0300 Subject: [PATCH 17/36] fix: fix reference to the instrumentation package in the example --- examples/router/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/router/package.json b/examples/router/package.json index f7388d4733..ab18cc0aba 100644 --- a/examples/router/package.json +++ b/examples/router/package.json @@ -33,7 +33,7 @@ "@opentelemetry/exporter-zipkin": "^0.18.0", "@opentelemetry/instrumentation": "^0.18.0", "@opentelemetry/instrumentation-http": "^0.18.0", - "@opentelemetry/instrumentation-router": "file:../../plugins/node/opentelemetry-instrumentation-router", + "@opentelemetry/instrumentation-router": "^0.18.0", "@opentelemetry/node": "^0.18.0", "@opentelemetry/tracing": "^0.18.0", "router": "^1.3.5" From 89f1fcaeb5c9c6701d63644112463ae4bf60c731 Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Mon, 10 May 2021 13:12:14 +0300 Subject: [PATCH 18/36] fix: fix versions --- examples/router/package.json | 4 ++-- .../node/opentelemetry-instrumentation-router/package.json | 4 ++-- .../node/opentelemetry-instrumentation-router/src/version.ts | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/router/package.json b/examples/router/package.json index ab18cc0aba..80a2b97186 100644 --- a/examples/router/package.json +++ b/examples/router/package.json @@ -1,7 +1,7 @@ { "name": "router-example", "private": true, - "version": "0.18.0", + "version": "0.16.0", "description": "Example of router integration with OpenTelemetry", "main": "index.js", "scripts": { @@ -33,7 +33,7 @@ "@opentelemetry/exporter-zipkin": "^0.18.0", "@opentelemetry/instrumentation": "^0.18.0", "@opentelemetry/instrumentation-http": "^0.18.0", - "@opentelemetry/instrumentation-router": "^0.18.0", + "@opentelemetry/instrumentation-router": "^0.16.0", "@opentelemetry/node": "^0.18.0", "@opentelemetry/tracing": "^0.18.0", "router": "^1.3.5" diff --git a/plugins/node/opentelemetry-instrumentation-router/package.json b/plugins/node/opentelemetry-instrumentation-router/package.json index 3306768116..570d690b6e 100644 --- a/plugins/node/opentelemetry-instrumentation-router/package.json +++ b/plugins/node/opentelemetry-instrumentation-router/package.json @@ -1,6 +1,6 @@ { "name": "@opentelemetry/instrumentation-router", - "version": "0.15.0", + "version": "0.16.0", "description": "OpenTelemetry router automatic instrumentation package", "main": "build/src/index.js", "types": "build/src/index.d.ts", @@ -58,7 +58,7 @@ "typescript": "4.1.3" }, "dependencies": { - "@opentelemetry/api": "^0.18.0", + "@opentelemetry/api": "^0.19.0", "@opentelemetry/instrumentation": "^0.19.0", "@opentelemetry/semantic-conventions": "^0.19.0" } diff --git a/plugins/node/opentelemetry-instrumentation-router/src/version.ts b/plugins/node/opentelemetry-instrumentation-router/src/version.ts index 1e4172026f..eacb17da85 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/version.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/version.ts @@ -15,4 +15,4 @@ */ // this is autogenerated file, see scripts/version-update.js -export const VERSION = '0.15.0'; +export const VERSION = '0.16.0'; From 9ed9c624a9de84ed9746b5e7fe32170cd7e069c6 Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Mon, 10 May 2021 13:13:36 +0300 Subject: [PATCH 19/36] style: use optional chaining in tests accessing parentSpan --- .../opentelemetry-instrumentation-router/test/index.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts b/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts index ae10d69866..249318e49a 100644 --- a/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts +++ b/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts @@ -94,7 +94,7 @@ const createServer = async ({ res.statusCode = 404; res.end('Not Found'); } - parentSpan && parentSpan.end(); + parentSpan?.end(); }); }; const handler = parentSpan From 131160fc39c88c4cd079f1d473c9bc829f5089a9 Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Mon, 10 May 2021 13:18:30 +0300 Subject: [PATCH 20/36] test: fix the test asserting version number --- .../opentelemetry-instrumentation-router/test/index.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts b/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts index 249318e49a..60c85ee9bf 100644 --- a/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts +++ b/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts @@ -126,7 +126,7 @@ const assertSpans = (actualSpans: any[], expectedSpans: any[]) => { assert.notStrictEqual(expected, undefined); assert.strictEqual(span.attributes['router.name'], expected.name); assert.strictEqual(span.attributes['router.type'], expected.type); - assert.strictEqual(span.attributes['router.version'], '1.3.5'); + assert.strictEqual(typeof span.attributes['router.version'], 'string'); assert.strictEqual(span.attributes['http.route'], expected.route); } catch (e) { e.message = `At span[${idx}]: ${e.message}`; From ffa6735bb3f53a1edbf9e668276b307fbae4b4d6 Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Mon, 10 May 2021 13:44:43 +0300 Subject: [PATCH 21/36] chore: update api version used in router instrumentation --- plugins/node/opentelemetry-instrumentation-router/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/node/opentelemetry-instrumentation-router/package.json b/plugins/node/opentelemetry-instrumentation-router/package.json index 570d690b6e..cbb7670157 100644 --- a/plugins/node/opentelemetry-instrumentation-router/package.json +++ b/plugins/node/opentelemetry-instrumentation-router/package.json @@ -58,7 +58,7 @@ "typescript": "4.1.3" }, "dependencies": { - "@opentelemetry/api": "^0.19.0", + "@opentelemetry/api": "1.0.0-rc.0", "@opentelemetry/instrumentation": "^0.19.0", "@opentelemetry/semantic-conventions": "^0.19.0" } From df8b51db9c9e56d82795425e09ca48097783f429 Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Wed, 12 May 2021 15:41:34 +0300 Subject: [PATCH 22/36] docs: capitalize Router in the title Co-authored-by: Bartlomiej Obecny --- plugins/node/opentelemetry-instrumentation-router/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/node/opentelemetry-instrumentation-router/README.md b/plugins/node/opentelemetry-instrumentation-router/README.md index 90f2602da3..c415938047 100644 --- a/plugins/node/opentelemetry-instrumentation-router/README.md +++ b/plugins/node/opentelemetry-instrumentation-router/README.md @@ -1,4 +1,4 @@ -# OpenTelemetry router Instrumentation for Node.js +# OpenTelemetry Router Instrumentation for Node.js [![Gitter chat][gitter-image]][gitter-url] [![dependencies][dependencies-image]][dependencies-url] From 6a0d5ffea33bb07d61b85ddf93a52c3a1d8140c4 Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Wed, 12 May 2021 16:33:24 +0300 Subject: [PATCH 23/36] docs: remove references to gitter from router README --- .../README.md | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-router/README.md b/plugins/node/opentelemetry-instrumentation-router/README.md index c415938047..cbeb105bc9 100644 --- a/plugins/node/opentelemetry-instrumentation-router/README.md +++ b/plugins/node/opentelemetry-instrumentation-router/README.md @@ -1,6 +1,6 @@ # OpenTelemetry Router Instrumentation for Node.js -[![Gitter chat][gitter-image]][gitter-url] +[![NPM Published Version][npm-img]][npm-url] [![dependencies][dependencies-image]][dependencies-url] [![devDependencies][devDependencies-image]][devDependencies-url] [![Apache License][license-image]][license-image] @@ -40,19 +40,21 @@ registerInstrumentations({ See [examples/router](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/examples/router) for a short example. ## Useful links + - For more information on OpenTelemetry, visit: - For more about OpenTelemetry JavaScript: -- For help or feedback on this project, join us on [gitter][gitter-url] +- For help or feedback on this project, join us in [GitHub Discussions][discussions-url] ## License Apache 2.0 - See [LICENSE][license-url] for more information. -[gitter-image]: https://badges.gitter.im/open-telemetry/opentelemetry-js.svg -[gitter-url]: https://gitter.im/open-telemetry/opentelemetry-node?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge +[discussions-url]: https://github.com/open-telemetry/opentelemetry-js/discussions [license-url]: https://github.com/open-telemetry/opentelemetry-js-contrib/blob/main/LICENSE [license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat -[dependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib/status.svg?path=packages/opentelemetry-instrumentation-router -[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=packages%2Fopentelemetry-instrumentation-router -[devDependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib/dev-status.svg?path=packages/opentelemetry-instrumentation-router -[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=packages%2Fopentelemetry-instrumentation-router&type=dev +[dependencies-image]: https://status.david-dm.org/gh/open-telemetry/opentelemetry-js-contrib.svg?path=plugins%2Fnode%2Fopentelemetry-instrumentation-router +[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=plugins%2Fnode%2Fopentelemetry-instrumentation-router +[devDependencies-image]: https://status.david-dm.org/gh/open-telemetry/opentelemetry-js-contrib.svg?path=plugins%2Fnode%2Fopentelemetry-instrumentation-router&type=dev +[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=plugins%2Fnode%2Fopentelemetry-instrumentation-router&type=dev +[npm-url]: https://www.npmjs.com/package/@opentelemetry/instrumentation-router +[npm-img]: https://badge.fury.io/js/%40opentelemetry%2Finstrumentation-router.svg From 2c4651cea790a2c111f0457c28af40454d7c98fe Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Wed, 12 May 2021 16:33:59 +0300 Subject: [PATCH 24/36] docs: capitalize Router in package.json --- plugins/node/opentelemetry-instrumentation-router/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/node/opentelemetry-instrumentation-router/package.json b/plugins/node/opentelemetry-instrumentation-router/package.json index cbb7670157..01f89aae8c 100644 --- a/plugins/node/opentelemetry-instrumentation-router/package.json +++ b/plugins/node/opentelemetry-instrumentation-router/package.json @@ -1,7 +1,7 @@ { "name": "@opentelemetry/instrumentation-router", "version": "0.16.0", - "description": "OpenTelemetry router automatic instrumentation package", + "description": "OpenTelemetry Router automatic instrumentation package", "main": "build/src/index.js", "types": "build/src/index.d.ts", "repository": "open-telemetry/opentelemetry-js-contrib", From e946ae3fec0db74f8616820a9fad9089d478667a Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Wed, 12 May 2021 16:46:36 +0300 Subject: [PATCH 25/36] docs: add comments about the if statement in the wrappers --- .../src/instrumentation.ts | 4 ++++ .../node/opentelemetry-instrumentation-router/src/utils.ts | 1 + 2 files changed, 5 insertions(+) diff --git a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts index 8a8d126275..2a36b51cd3 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts @@ -112,6 +112,8 @@ export default class RouterInstrumentation extends InstrumentationBase< res: http.ServerResponse, next: Router.NextFunction ) { + // Skip creating spans if the registered handler is of invalid length, because + // we know router will ignore those if (utils.isInternal(this.handle) || this.handle.length > 3) { return original.call(this, req, res, next); } @@ -135,6 +137,8 @@ export default class RouterInstrumentation extends InstrumentationBase< res: http.ServerResponse, next: Router.NextFunction ) { + // Skip creating spans if the registered handler is of invalid length, because + // we know router will ignore those if (utils.isInternal(this.handle) || this.handle.length !== 4) { return original.call(this, error, req, res, next); } diff --git a/plugins/node/opentelemetry-instrumentation-router/src/utils.ts b/plugins/node/opentelemetry-instrumentation-router/src/utils.ts index 92afdba92f..ad509dfab6 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/utils.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/utils.ts @@ -18,6 +18,7 @@ import * as constants from './constants'; import * as types from './types'; import * as Router from 'router'; +// Detect whether a function is a router package internal plumming handler export const isInternal = (fn: Function) => { // Note that both of those functions are sync if (fn.name === 'handle' && fn.toString() === constants.ROUTER_HANDLE_FN) { From 7d01f722d15266ad3e60d04ce6570bd0a7782abf Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Wed, 12 May 2021 16:47:01 +0300 Subject: [PATCH 26/36] fix: don't fill version with arbitrary data --- .../opentelemetry-instrumentation-router/src/instrumentation.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts index 2a36b51cd3..d076019fe3 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts @@ -177,7 +177,7 @@ export default class RouterInstrumentation extends InstrumentationBase< : `middleware - ${fnName || ''}`; const attributes = { [types.CustomAttributeNames.NAME]: fnName, - [types.CustomAttributeNames.VERSION]: this._moduleVersion || 'n/a', + [types.CustomAttributeNames.VERSION]: this._moduleVersion, [types.CustomAttributeNames.TYPE]: type, [SemanticAttributes.HTTP_ROUTE]: route, }; From 8009cfd5db1be3595b1aff0fef370a7ceae60d8d Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Wed, 12 May 2021 16:52:51 +0300 Subject: [PATCH 27/36] fix: remove the unneeded cast in utils --- plugins/node/opentelemetry-instrumentation-router/src/utils.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/node/opentelemetry-instrumentation-router/src/utils.ts b/plugins/node/opentelemetry-instrumentation-router/src/utils.ts index ad509dfab6..760105702d 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/utils.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/utils.ts @@ -43,7 +43,7 @@ export const renameHttpSpan = ( typeof route === 'string' && span?.name?.startsWith('HTTP ') ) { - (span as types.InstrumentationSpan).updateName( + span.updateName( `${method.toUpperCase()} ${route}` ); } From b347a7ac7c630ddbe7c1d5c1f7bc821308e6d297 Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Wed, 12 May 2021 16:30:35 +0300 Subject: [PATCH 28/36] docs: remove references to gitter from restify README Doesn't necessarily belong here, but I'll just add it since I did the same for the package in hand. --- .../README.md | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-restify/README.md b/plugins/node/opentelemetry-instrumentation-restify/README.md index faf795a54b..8b74aabaae 100644 --- a/plugins/node/opentelemetry-instrumentation-restify/README.md +++ b/plugins/node/opentelemetry-instrumentation-restify/README.md @@ -1,6 +1,6 @@ # OpenTelemetry Restify Instrumentation for Node.js -[![Gitter chat][gitter-image]][gitter-url] +[![NPM Published Version][npm-img]][npm-url] [![dependencies][dependencies-image]][dependencies-url] [![devDependencies][devDependencies-image]][devDependencies-url] [![Apache License][license-image]][license-image] @@ -46,17 +46,18 @@ See [examples/restify](https://github.com/open-telemetry/opentelemetry-js-contri - For more information on OpenTelemetry, visit: - For more about OpenTelemetry JavaScript: -- For help or feedback on this project, join us on [gitter][gitter-url] +- For help or feedback on this project, join us in [GitHub Discussions][discussions-url] ## License Apache 2.0 - See [LICENSE][license-url] for more information. -[gitter-image]: https://badges.gitter.im/open-telemetry/opentelemetry-js.svg -[gitter-url]: https://gitter.im/open-telemetry/opentelemetry-node?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge +[discussions-url]: https://github.com/open-telemetry/opentelemetry-js/discussions [license-url]: https://github.com/open-telemetry/opentelemetry-js-contrib/blob/main/LICENSE [license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat -[dependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib/status.svg?path=packages/opentelemetry-instrumentation-restify -[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=packages%2Fopentelemetry-instrumentation-restify -[devDependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib/dev-status.svg?path=packages/opentelemetry-instrumentation-restify -[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=packages%2Fopentelemetry-instrumentation-restify&type=dev +[dependencies-image]: https://status.david-dm.org/gh/open-telemetry/opentelemetry-js-contrib.svg?path=plugins%2Fnode%2Fopentelemetry-instrumentation-restify +[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=plugins%2Fnode%2Fopentelemetry-instrumentation-restify +[devDependencies-image]: https://status.david-dm.org/gh/open-telemetry/opentelemetry-js-contrib.svg?path=plugins%2Fnode%2Fopentelemetry-instrumentation-restify&type=dev +[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=plugins%2Fnode%2Fopentelemetry-instrumentation-restify&type=dev +[npm-url]: https://www.npmjs.com/package/@opentelemetry/instrumentation-restify +[npm-img]: https://badge.fury.io/js/%40opentelemetry%2Finstrumentation-restify.svg From 6d1d0e2fef128dec1c02dd3b1da4e74f489a9f92 Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Thu, 13 May 2021 09:51:21 +0300 Subject: [PATCH 29/36] style: eslint fix --- .../node/opentelemetry-instrumentation-router/src/utils.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-router/src/utils.ts b/plugins/node/opentelemetry-instrumentation-router/src/utils.ts index 760105702d..7022bd45f4 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/utils.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/utils.ts @@ -43,8 +43,6 @@ export const renameHttpSpan = ( typeof route === 'string' && span?.name?.startsWith('HTTP ') ) { - span.updateName( - `${method.toUpperCase()} ${route}` - ); + span.updateName(`${method.toUpperCase()} ${route}`); } }; From b2d2b0a52e0ce29e6d8b77395713874646b4d44d Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Thu, 13 May 2021 10:51:50 +0300 Subject: [PATCH 30/36] fix: substitute `` for unnamed function name --- .../src/instrumentation.ts | 4 ++-- .../test/index.test.ts | 7 ++++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts index d076019fe3..92707fd0ac 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts @@ -166,7 +166,7 @@ export default class RouterInstrumentation extends InstrumentationBase< res: http.ServerResponse, next: Router.NextFunction ) { - const fnName = layer.handle.name || undefined; + const fnName = layer.handle.name || ''; const type = layer.method ? types.LayerType.REQUEST_HANDLER : types.LayerType.MIDDLEWARE; @@ -174,7 +174,7 @@ export default class RouterInstrumentation extends InstrumentationBase< const spanName = type === types.LayerType.REQUEST_HANDLER ? `request handler - ${route}` - : `middleware - ${fnName || ''}`; + : `middleware - ${fnName}`; const attributes = { [types.CustomAttributeNames.NAME]: fnName, [types.CustomAttributeNames.VERSION]: this._moduleVersion, diff --git a/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts b/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts index 60c85ee9bf..3b23d92320 100644 --- a/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts +++ b/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts @@ -135,8 +135,9 @@ const assertSpans = (actualSpans: any[], expectedSpans: any[]) => { }); }; +const ANONYMOUS = ''; const spans = { - anonymousUse: { type: 'middleware', route: '/' }, + anonymousUse: { type: 'middleware', name: ANONYMOUS, route: '/' }, preName: { type: 'request_handler', name: 'preName', route: '/hello/:name' }, announceRude: { type: 'request_handler', @@ -225,7 +226,7 @@ describe('Router instrumentation', () => { assert.strictEqual(await request('/err'), 'Server error: Oops!'); assertSpans(memoryExporter.getFinishedSpans(), [ spans.anonymousUse, - { ...spans.preName, name: undefined, route: '/err' }, + { ...spans.preName, name: ANONYMOUS, route: '/err' }, { ...spans.anonymousUse, name: 'errHandler', route: '/err' }, ]); }); @@ -241,7 +242,7 @@ describe('Router instrumentation', () => { ); assertSpans(memoryExporter.getFinishedSpans(), [ spans.anonymousUse, - { ...spans.preName, name: undefined, route: '/deep/hello/someone' }, + { ...spans.preName, name: ANONYMOUS, route: '/deep/hello/someone' }, { ...spans.preName, route: '/deep/hello/:name' }, ]); From efa99a80ab470d81001ba21c2f01a688e01b2adc Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Thu, 13 May 2021 15:13:05 +0300 Subject: [PATCH 31/36] refactor: move enums into `enums/*` --- .../src/enums/AttributeNames.ts | 24 +++++++++++++++++++ .../src/enums/LayerType.ts | 22 +++++++++++++++++ .../src/instrumentation.ts | 14 ++++++----- .../src/types.ts | 12 ---------- 4 files changed, 54 insertions(+), 18 deletions(-) create mode 100644 plugins/node/opentelemetry-instrumentation-router/src/enums/AttributeNames.ts create mode 100644 plugins/node/opentelemetry-instrumentation-router/src/enums/LayerType.ts diff --git a/plugins/node/opentelemetry-instrumentation-router/src/enums/AttributeNames.ts b/plugins/node/opentelemetry-instrumentation-router/src/enums/AttributeNames.ts new file mode 100644 index 0000000000..b710addbc6 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-router/src/enums/AttributeNames.ts @@ -0,0 +1,24 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export enum AttributeNames { + TYPE = 'router.type', + NAME = 'router.name', + METHOD = 'router.method', + VERSION = 'router.version', +} + +export default AttributeNames; diff --git a/plugins/node/opentelemetry-instrumentation-router/src/enums/LayerType.ts b/plugins/node/opentelemetry-instrumentation-router/src/enums/LayerType.ts new file mode 100644 index 0000000000..a72a1cf264 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-router/src/enums/LayerType.ts @@ -0,0 +1,22 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export enum LayerType { + MIDDLEWARE = 'middleware', + REQUEST_HANDLER = 'request_handler', +} + +export default LayerType; diff --git a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts index 92707fd0ac..1b02c32702 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts @@ -30,6 +30,8 @@ import * as types from './types'; import { VERSION } from './version'; import * as constants from './constants'; import * as utils from './utils'; +import AttributeNames from './enums/AttributeNames.ts'; +import LayerType from './enums/LayerType.ts'; const { diag } = api; @@ -168,17 +170,17 @@ export default class RouterInstrumentation extends InstrumentationBase< ) { const fnName = layer.handle.name || ''; const type = layer.method - ? types.LayerType.REQUEST_HANDLER - : types.LayerType.MIDDLEWARE; + ? LayerType.REQUEST_HANDLER + : LayerType.MIDDLEWARE; const route = utils.getRoute(req); const spanName = - type === types.LayerType.REQUEST_HANDLER + type === LayerType.REQUEST_HANDLER ? `request handler - ${route}` : `middleware - ${fnName}`; const attributes = { - [types.CustomAttributeNames.NAME]: fnName, - [types.CustomAttributeNames.VERSION]: this._moduleVersion, - [types.CustomAttributeNames.TYPE]: type, + [AttributeNames.NAME]: fnName, + [AttributeNames.VERSION]: this._moduleVersion, + [AttributeNames.TYPE]: type, [SemanticAttributes.HTTP_ROUTE]: route, }; diff --git a/plugins/node/opentelemetry-instrumentation-router/src/types.ts b/plugins/node/opentelemetry-instrumentation-router/src/types.ts index c1baca7525..0f5069343b 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/types.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/types.ts @@ -15,18 +15,6 @@ */ import { Span } from '@opentelemetry/api'; -export enum LayerType { - MIDDLEWARE = 'middleware', - REQUEST_HANDLER = 'request_handler', -} - -export enum CustomAttributeNames { - TYPE = 'router.type', - NAME = 'router.name', - METHOD = 'router.method', - VERSION = 'router.version', -} - /** * extends opentelemetry/api Span object to instrument the root span name of http instrumentation */ From 97d93f0eeb1416cd65124b16b5851d8ad61dfe45 Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Thu, 13 May 2021 15:15:17 +0300 Subject: [PATCH 32/36] feat: prefer `??` over `||` --- plugins/node/opentelemetry-instrumentation-router/src/utils.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/node/opentelemetry-instrumentation-router/src/utils.ts b/plugins/node/opentelemetry-instrumentation-router/src/utils.ts index 7022bd45f4..1b4cb916c3 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/utils.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/utils.ts @@ -31,7 +31,7 @@ export const isInternal = (fn: Function) => { }; export const getRoute = (req: Router.RoutedRequest) => - req.baseUrl + (req.route?.path || '') || '/'; + req.baseUrl + (req.route?.path ?? '') || '/'; export const renameHttpSpan = ( span?: types.InstrumentationSpan, From d311d00abd50476746621fed2d8279f3be5bdc2e Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Thu, 13 May 2021 15:17:42 +0300 Subject: [PATCH 33/36] feat: squash with enum change!! --- .../src/instrumentation.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts index 1b02c32702..b2594bdf21 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts @@ -30,8 +30,8 @@ import * as types from './types'; import { VERSION } from './version'; import * as constants from './constants'; import * as utils from './utils'; -import AttributeNames from './enums/AttributeNames.ts'; -import LayerType from './enums/LayerType.ts'; +import AttributeNames from './enums/AttributeNames'; +import LayerType from './enums/LayerType'; const { diag } = api; From 74da50edd98d07d363535a6600b22025ad2c16cb Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Thu, 13 May 2021 15:18:34 +0300 Subject: [PATCH 34/36] fix: only import Router types in instrumentation --- .../opentelemetry-instrumentation-router/src/instrumentation.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts index b2594bdf21..73822f8d42 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts @@ -24,7 +24,7 @@ import { import { SemanticAttributes } from '@opentelemetry/semantic-conventions'; import * as http from 'http'; -import * as Router from 'router'; +import type * as Router from 'router'; import * as types from './types'; import { VERSION } from './version'; From 48c30e7c4f95ef0619598d1034571f061dea83b1 Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Thu, 13 May 2021 15:20:03 +0300 Subject: [PATCH 35/36] style: prefer api.diag to destructuring --- .../src/instrumentation.ts | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts index 73822f8d42..4293143bc6 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts @@ -33,8 +33,6 @@ import * as utils from './utils'; import AttributeNames from './enums/AttributeNames'; import LayerType from './enums/LayerType'; -const { diag } = api; - export default class RouterInstrumentation extends InstrumentationBase< typeof Router > { @@ -49,14 +47,14 @@ export default class RouterInstrumentation extends InstrumentationBase< constants.MODULE_NAME, constants.SUPPORTED_VERSIONS, (moduleExports, moduleVersion) => { - diag.debug( + api.diag.debug( `Applying patch for ${constants.MODULE_NAME}@${moduleVersion}` ); this._moduleVersion = moduleVersion; return moduleExports; }, (moduleExports, moduleVersion) => { - diag.debug( + api.diag.debug( `Removing patch for ${constants.MODULE_NAME}@${moduleVersion}` ); return moduleExports; @@ -68,7 +66,7 @@ export default class RouterInstrumentation extends InstrumentationBase< 'router/lib/layer.js', constants.SUPPORTED_VERSIONS, (moduleExports, moduleVersion) => { - diag.debug( + api.diag.debug( `Applying patch for "lib/layer.js" of ${constants.MODULE_NAME}@${moduleVersion}` ); const Layer: any = moduleExports; @@ -91,7 +89,7 @@ export default class RouterInstrumentation extends InstrumentationBase< return moduleExports; }, (moduleExports, moduleVersion) => { - diag.debug( + api.diag.debug( `Removing patch for "lib/layer.js" of ${constants.MODULE_NAME}@${moduleVersion}` ); const Layer: any = moduleExports; From 7e63ae4e0c3cc54eae5775c5982673bae716d3bf Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Thu, 13 May 2021 15:33:51 +0300 Subject: [PATCH 36/36] feat: only ever run span.end once --- .../src/instrumentation.ts | 5 +++-- .../opentelemetry-instrumentation-router/src/utils.ts | 10 ++++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts index 4293143bc6..a5de82c8e0 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/instrumentation.ts @@ -191,16 +191,17 @@ export default class RouterInstrumentation extends InstrumentationBase< }, parent ) as types.InstrumentationSpan; + const endSpan = utils.once(span.end.bind(span)); utils.renameHttpSpan(parentSpan, layer.method, route); // make sure spans are ended at least when response is finished - res.prependOnceListener('finish', () => span.end()); + res.prependOnceListener('finish', endSpan); const wrappedNext: Router.NextFunction = err => { if (err) { span.recordException(err); } - span.end(); + endSpan(); if (parent) { return api.context.with(parent, next, undefined, err); } diff --git a/plugins/node/opentelemetry-instrumentation-router/src/utils.ts b/plugins/node/opentelemetry-instrumentation-router/src/utils.ts index 1b4cb916c3..82159fb5bc 100644 --- a/plugins/node/opentelemetry-instrumentation-router/src/utils.ts +++ b/plugins/node/opentelemetry-instrumentation-router/src/utils.ts @@ -46,3 +46,13 @@ export const renameHttpSpan = ( span.updateName(`${method.toUpperCase()} ${route}`); } }; + +export const once = (fn: Function) => { + let run = true; + return () => { + if (run) { + run = false; + fn(); + } + }; +};