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..9cd52f415a --- /dev/null +++ b/examples/router/client.js @@ -0,0 +1,38 @@ +'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'); +// 404 +makeRequest('/bye/world'); +// error +makeRequest('/err'); diff --git a/examples/router/package.json b/examples/router/package.json new file mode 100644 index 0000000000..80a2b97186 --- /dev/null +++ b/examples/router/package.json @@ -0,0 +1,45 @@ +{ + "name": "router-example", + "private": true, + "version": "0.16.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": "^0.16.0", + "@opentelemetry/node": "^0.18.0", + "@opentelemetry/tracing": "^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..8e06630d1e --- /dev/null +++ b/examples/router/server.js @@ -0,0 +1,46 @@ +'use strict'; + +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 +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, (error) => { + if (error) { + res.statusCode = 500; + } else { + 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-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 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..cbeb105bc9 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-router/README.md @@ -0,0 +1,60 @@ +# OpenTelemetry Router Instrumentation for Node.js + +[![NPM Published Version][npm-img]][npm-url] +[![dependencies][dependencies-image]][dependencies-url] +[![devDependencies][devDependencies-image]][devDependencies-url] +[![Apache License][license-image]][license-image] + +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. + +## Installation + +```bash +npm install --save @opentelemetry/instrumentation-router +``` +### Supported Versions + - `>=1.0.0` + +## Usage + +```js +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(); + +provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter())); +provider.register(); + +registerInstrumentations({ + instrumentations: [new RouterInstrumentation()], + tracerProvider: provider, +}); +``` + +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 in [GitHub Discussions][discussions-url] + +## License + +Apache 2.0 - See [LICENSE][license-url] for more information. + +[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://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 diff --git a/plugins/node/opentelemetry-instrumentation-router/package.json b/plugins/node/opentelemetry-instrumentation-router/package.json new file mode 100644 index 0000000000..01f89aae8c --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-router/package.json @@ -0,0 +1,65 @@ +{ + "name": "@opentelemetry/instrumentation-router", + "version": "0.16.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/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/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..a5de82c8e0 --- /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 type * as Router from 'router'; + +import * as types from './types'; +import { VERSION } from './version'; +import * as constants from './constants'; +import * as utils from './utils'; +import AttributeNames from './enums/AttributeNames'; +import LayerType from './enums/LayerType'; + +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) => { + api.diag.debug( + `Applying patch for ${constants.MODULE_NAME}@${moduleVersion}` + ); + this._moduleVersion = moduleVersion; + return moduleExports; + }, + (moduleExports, moduleVersion) => { + api.diag.debug( + `Removing patch for ${constants.MODULE_NAME}@${moduleVersion}` + ); + return moduleExports; + } + ); + + module.files.push( + new InstrumentationNodeModuleFile( + 'router/lib/layer.js', + constants.SUPPORTED_VERSIONS, + (moduleExports, moduleVersion) => { + api.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 moduleExports; + }, + (moduleExports, moduleVersion) => { + api.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 moduleExports; + } + ) + ); + + return module; + } + + // Define handle_request wrapper separately to ensure the signature has the correct length + private _requestHandlerPatcher(original: Router.Layer['handle_request']) { + const instrumentation = this; + return function wrapped_handle_request( + this: Router.Layer, + req: Router.RoutedRequest, + 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); + } + const { context, wrappedNext } = instrumentation._setupSpan( + this, + req, + res, + next + ); + 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: Router.Layer['handle_error']) { + const instrumentation = this; + return function wrapped_handle_request( + this: Router.Layer, + error: Error, + req: Router.RoutedRequest, + 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); + } + const { context, wrappedNext } = instrumentation._setupSpan( + this, + req, + res, + next + ); + return api.context.with( + context, + original, + this, + error, + req, + res, + wrappedNext + ); + }; + } + + private _setupSpan( + layer: Router.Layer, + req: Router.RoutedRequest, + res: http.ServerResponse, + next: Router.NextFunction + ) { + const fnName = layer.handle.name || ''; + const type = layer.method + ? LayerType.REQUEST_HANDLER + : LayerType.MIDDLEWARE; + const route = utils.getRoute(req); + const spanName = + type === LayerType.REQUEST_HANDLER + ? `request handler - ${route}` + : `middleware - ${fnName}`; + const attributes = { + [AttributeNames.NAME]: fnName, + [AttributeNames.VERSION]: this._moduleVersion, + [AttributeNames.TYPE]: type, + [SemanticAttributes.HTTP_ROUTE]: route, + }; + + const parent = api.context.active(); + const parentSpan = api.getSpan(parent) as types.InstrumentationSpan; + const span = this.tracer.startSpan( + spanName, + { + attributes, + }, + 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', endSpan); + + const wrappedNext: Router.NextFunction = err => { + if (err) { + span.recordException(err); + } + endSpan(); + if (parent) { + return api.context.with(parent, next, undefined, err); + } + return next(err); + }; + + return { + context: api.setSpan(parent, 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..613f68c946 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-router/src/router.d.ts @@ -0,0 +1,253 @@ +/* + * 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. + */ + +// From https://github.com/pillarjs/router/pull/100 +declare module 'router' { + import * as http from 'http'; + + export = Router; + + namespace Router { + interface RouterOptions { + strict?: boolean; + caseSensitive?: boolean; + mergeParams?: boolean; + } + + interface Layer { + 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; + 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/src/types.ts b/plugins/node/opentelemetry-instrumentation-router/src/types.ts new file mode 100644 index 0000000000..0f5069343b --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-router/src/types.ts @@ -0,0 +1,23 @@ +/* + * 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 { Span } from '@opentelemetry/api'; + +/** + * 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..82159fb5bc --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-router/src/utils.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 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) { + return true; + } + if (fn.name === 'router' && fn.toString() === constants.ROUTE_ROUTER_FN) { + return true; + } + return false; +}; + +export const getRoute = (req: Router.RoutedRequest) => + req.baseUrl + (req.route?.path ?? '') || '/'; + +export const renameHttpSpan = ( + span?: types.InstrumentationSpan, + method?: string, + route?: string +) => { + if ( + typeof method === 'string' && + typeof route === 'string' && + span?.name?.startsWith('HTTP ') + ) { + span.updateName(`${method.toUpperCase()} ${route}`); + } +}; + +export const once = (fn: Function) => { + let run = true; + return () => { + if (run) { + run = false; + fn(); + } + }; +}; 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..eacb17da85 --- /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.16.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..3b23d92320 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-router/test/index.test.ts @@ -0,0 +1,270 @@ +/* + * 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'; +import { InstrumentationSpan } from '../src/types'; +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 ({ + parentSpan, +}: { parentSpan?: InstrumentationSpan } = {}) => { + const router = new Router(); + + router.use((req, res, next) => { + // anonymous middleware + next(); + }); + + router.get('/err', (req, res, next) => { + next(new Error('Oops')); + }); + + router.get('/deep/hello/someone', (req, res, next) => { + next(); + }); + + const helloRouter = new Router(); + + 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); + + /* eslint-disable-next-line prefer-arrow-callback */ + helloRouter.get('/:name', function announceRude(req, res, next) { + res.end('How rude!'); + }); + + router.use('/hello', helloRouter); + + const deepRouter = new Router(); + + deepRouter.use('/hello', helloRouter); + router.use('/deep', deepRouter); + + const errHandler: Router.ErrorRequestHandler = (err, req, res, next) => { + 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: http.IncomingMessage, + res: http.ServerResponse + ) => { + router(req, res, err => { + if (err) { + res.statusCode = 500; + res.end(err.message); + } + if (!res.headersSent) { + res.statusCode = 404; + res.end('Not Found'); + } + 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)); + + return server; +}; + +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' + ); + 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(typeof span.attributes['router.version'], 'string'); + assert.strictEqual(span.attributes['http.route'], expected.route); + } catch (e) { + e.message = `At span[${idx}]: ${e.message}`; + throw e; + } + }); +}; + +const ANONYMOUS = ''; +const spans = { + anonymousUse: { type: 'middleware', name: ANONYMOUS, 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', + }, +}; + +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, 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 = ''; + resp.on('data', chunk => { + data += chunk; + }); + resp.on('end', () => { + resolve(data); + }); + resp.on('error', err => { + reject(err); + }); + }); + }); + }; + + beforeEach(async () => { + plugin.enable(); + // To force `require-in-the-middle` to definitely reload and patch the layer + require('router/lib/layer.js'); + server = await createServer(); + contextManager = new AsyncHooksContextManager(); + context.setGlobalContextManager(contextManager.enable()); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + }); + + afterEach(() => { + memoryExporter.reset(); + context.disable(); + server.close(); + plugin.disable(); + }); + + 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, + ]); + }); + + 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' }, + ]); + }); + + 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: '/' }, + ]); + }); + + it('should create spans for errored routes', async () => { + assert.strictEqual(await request('/err'), 'Server error: Oops!'); + assertSpans(memoryExporter.getFinishedSpans(), [ + spans.anonymousUse, + { ...spans.preName, name: ANONYMOUS, route: '/err' }, + { ...spans.anonymousUse, name: 'errHandler', route: '/err' }, + ]); + }); + + it('should create spans under parent', async () => { + 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: ANONYMOUS, route: '/deep/hello/someone' }, + { ...spans.preName, route: '/deep/hello/:name' }, + ]); + + memoryExporter.getFinishedSpans().forEach((span, idx) => { + assert.strictEqual( + span.parentSpanId, + parentSpan.context().spanId, + `span[${idx}] has invalid parent` + ); + }); + assert.strictEqual(parentSpan.name, 'GET /deep/hello/someone'); + } finally { + testLocalServer.close(); + } + }); + }); + + describe('Disabling instrumentation', () => { + it('should not create new spans', async () => { + plugin.disable(); + await request('/hello/nobody'); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + }); + }); +}); 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" + ] +}