diff --git a/examples/restify/README.md b/examples/restify/README.md new file mode 100644 index 0000000000..e031fc3b4e --- /dev/null +++ b/examples/restify/README.md @@ -0,0 +1,45 @@ +# Overview + +OpenTelemetry Restify 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 Restify API. All generated spans include following attributes: + +- `http.route`: resolved route; +- `restify.method`: server method used to register the handler. One of `use`, `pre`, `del`, `get`, `head`, `opts`, `post`, `put` or `patch`; +- `restify.type`: either `middleware` or `request_handler`; +- `restify.version`: `restify` 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/restify/client.js b/examples/restify/client.js new file mode 100644 index 0000000000..52dffcf4bf --- /dev/null +++ b/examples/restify/client.js @@ -0,0 +1,35 @@ +'use strict'; + +// required to initialize the service name for the auto-instrumentation +require('./tracer')('example-restify-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/restify/images/jaeger-ui.png b/examples/restify/images/jaeger-ui.png new file mode 100644 index 0000000000..181a097113 Binary files /dev/null and b/examples/restify/images/jaeger-ui.png differ diff --git a/examples/restify/images/zipkin-ui.png b/examples/restify/images/zipkin-ui.png new file mode 100644 index 0000000000..ac04aca4f9 Binary files /dev/null and b/examples/restify/images/zipkin-ui.png differ diff --git a/examples/restify/package.json b/examples/restify/package.json new file mode 100644 index 0000000000..357c977252 --- /dev/null +++ b/examples/restify/package.json @@ -0,0 +1,44 @@ +{ + "name": "restify-example", + "private": true, + "version": "0.18.0", + "description": "Example of restify 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/node": "^0.18.0", + "@opentelemetry/tracing": "^0.18.0", + "restify": "^4.3.4" + }, + "homepage": "https://github.com/open-telemetry/opentelemetry-js#readme", + "devDependencies": { + "cross-env": "^6.0.0" + } +} diff --git a/examples/restify/server.js b/examples/restify/server.js new file mode 100644 index 0000000000..950c8dd7ad --- /dev/null +++ b/examples/restify/server.js @@ -0,0 +1,47 @@ +'use strict'; + +const api = require('@opentelemetry/api'); + +const { diag, DiagConsoleLogger, DiagLogLevel } = api; +diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.VERBOSE); + +const restify = require('restify'); +require('./tracer')('example-restify-server'); + +const server = restify.createServer(); +const PORT = 8080; + +server.pre((req, res, next) => { + next(); +}); + +// `setDefaultName` shows up in spans as the name +const setDefaultName = (req, res, next) => { + req.defaultName = 'Stranger'; + next(); +}; + +server.use([(req, res, next) => { + /* + noop to showcase use with an array. + as this is an anonymous fn, the name is not known and cannot be displayed in traces. + */ + next(); +}, setDefaultName]); + +// named function to be used in traces +// eslint-disable-next-line prefer-arrow-callback +server.get('/hello/:name', function hello(req, res, next) { + console.log('Handling hello'); + res.send(`Hello, ${req.params.name || req.defaultName}\n`); + return next(); +}); + +server.get('/bye/:name', (req, res, next) => { + console.log('Handling bye'); + return next(new Error('Ooops in bye')); +}); + +server.listen(PORT, () => { + console.log('Ready on %s', server.url); +}); diff --git a/examples/restify/tracer.js b/examples/restify/tracer.js new file mode 100644 index 0000000000..6e6cc5f4eb --- /dev/null +++ b/examples/restify/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 { RestifyInstrumentation } = require('@opentelemetry/instrumentation-restify'); + +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, + RestifyInstrumentation, + ], + }); + + 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('restify-example'); +}; diff --git a/plugins/node/opentelemetry-instrumentation-restify/.eslintignore b/plugins/node/opentelemetry-instrumentation-restify/.eslintignore new file mode 100644 index 0000000000..378eac25d3 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-restify/.eslintignore @@ -0,0 +1 @@ +build diff --git a/plugins/node/opentelemetry-instrumentation-restify/.eslintrc.js b/plugins/node/opentelemetry-instrumentation-restify/.eslintrc.js new file mode 100644 index 0000000000..f756f4488b --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-restify/.eslintrc.js @@ -0,0 +1,7 @@ +module.exports = { + "env": { + "mocha": true, + "node": true + }, + ...require('../../../eslint.config.js') +} diff --git a/plugins/node/opentelemetry-instrumentation-restify/.npmignore b/plugins/node/opentelemetry-instrumentation-restify/.npmignore new file mode 100644 index 0000000000..9505ba9450 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-restify/.npmignore @@ -0,0 +1,4 @@ +/bin +/coverage +/doc +/test diff --git a/plugins/node/opentelemetry-instrumentation-restify/LICENSE b/plugins/node/opentelemetry-instrumentation-restify/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-restify/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-restify/README.md b/plugins/node/opentelemetry-instrumentation-restify/README.md new file mode 100644 index 0000000000..c4a438a9bc --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-restify/README.md @@ -0,0 +1,58 @@ +# OpenTelemetry Restify 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 [`restify`](https://github.com/restify/node-restify) 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-restify +``` +### Supported Versions + - `>=4.0.0` + +## Usage + +```js +const { RestifyInstrumentation } = require('@opentelemetry/instrumentation-restify'); +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 RestifyInstrumentation()], + tracerProvider: provider, +}); +``` + +See [examples/restify](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/examples/restify) 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-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 diff --git a/plugins/node/opentelemetry-instrumentation-restify/package.json b/plugins/node/opentelemetry-instrumentation-restify/package.json new file mode 100644 index 0000000000..611c12bd2d --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-restify/package.json @@ -0,0 +1,68 @@ +{ + "name": "@opentelemetry/instrumentation-restify", + "version": "0.15.0", + "description": "OpenTelemetry restify 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", + "restify", + "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.18.0", + "@opentelemetry/node": "0.18.0", + "@opentelemetry/tracing": "0.18.0", + "@types/mocha": "7.0.2", + "@types/node": "14.0.27", + "@types/restify": "^4.3.7", + "codecov": "3.7.2", + "gts": "3.1.0", + "mocha": "7.2.0", + "nyc": "15.1.0", + "restify": "^4.3.4", + "rimraf": "3.0.2", + "ts-mocha": "8.0.0", + "ts-node": "9.0.0", + "tslint-consistent-codestyle": "1.16.0", + "tslint-microsoft-contrib": "6.2.0", + "typescript": "4.1.3" + }, + "dependencies": { + "@opentelemetry/api": "^0.18.0", + "@opentelemetry/core": "^0.18.0", + "@opentelemetry/instrumentation": "^0.18.0", + "@opentelemetry/semantic-conventions": "^0.18.0" + } +} diff --git a/plugins/node/opentelemetry-instrumentation-restify/src/constants.ts b/plugins/node/opentelemetry-instrumentation-restify/src/constants.ts new file mode 100644 index 0000000000..2ca6d52182 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-restify/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 RESTIFY_MW_METHODS = ['use', 'pre']; +export const RESTIFY_METHODS = [ + 'del', + 'get', + 'head', + 'opts', + 'post', + 'put', + 'patch', +]; +export const MODULE_NAME = 'restify'; +export const SUPPORTED_VERSIONS = ['>=4.0.0']; +export const REQ_SPAN = Symbol('REQ_SPAN'); diff --git a/plugins/node/opentelemetry-instrumentation-restify/src/index.ts b/plugins/node/opentelemetry-instrumentation-restify/src/index.ts new file mode 100644 index 0000000000..1a843eb1f0 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-restify/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 { RestifyInstrumentation } from './instrumentation'; + +export * from './instrumentation'; +export default RestifyInstrumentation; diff --git a/plugins/node/opentelemetry-instrumentation-restify/src/instrumentation.ts b/plugins/node/opentelemetry-instrumentation-restify/src/instrumentation.ts new file mode 100644 index 0000000000..0eb2ff97ae --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-restify/src/instrumentation.ts @@ -0,0 +1,247 @@ +/* + * 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 * as restify from 'restify'; +import { Server } from 'restify'; +import * as types from './types'; +import { VERSION } from './version'; +import * as constants from './constants'; +import { + InstrumentationBase, + InstrumentationNodeModuleDefinition, + InstrumentationNodeModuleFile, + isWrapped, +} from '@opentelemetry/instrumentation'; +import { HttpAttribute } from '@opentelemetry/semantic-conventions'; +import { isPromise, isAsyncFunction } from './utils'; + +const { diag } = api; + +export class RestifyInstrumentation extends InstrumentationBase< + typeof restify +> { + constructor() { + super(`@opentelemetry/instrumentation-${constants.MODULE_NAME}`, VERSION); + } + + private _moduleVersion?: string; + private _isDisabled = false; + + init() { + const module = new InstrumentationNodeModuleDefinition( + constants.MODULE_NAME, + constants.SUPPORTED_VERSIONS, + (moduleExports, moduleVersion) => { + this._moduleVersion = moduleVersion; + return moduleExports; + } + ); + + module.files.push( + new InstrumentationNodeModuleFile( + 'restify/lib/server.js', + constants.SUPPORTED_VERSIONS, + (moduleExports, moduleVersion) => { + diag.debug( + `Applying patch for ${constants.MODULE_NAME}@${moduleVersion}` + ); + this._isDisabled = false; + const Server: any = moduleExports; + for (const name of constants.RESTIFY_METHODS) { + if (isWrapped(Server.prototype[name])) { + this._unwrap(Server.prototype, name); + } + this._wrap( + Server.prototype, + name as keyof Server, + this._methodPatcher.bind(this) + ); + } + for (const name of constants.RESTIFY_MW_METHODS) { + if (isWrapped(Server.prototype[name])) { + this._unwrap(Server.prototype, name); + } + this._wrap( + Server.prototype, + name as keyof Server, + this._middlewarePatcher.bind(this) + ); + } + return moduleExports; + }, + (moduleExports, moduleVersion) => { + diag.debug( + `Removing patch for ${constants.MODULE_NAME}@${moduleVersion}` + ); + this._isDisabled = true; + if (moduleExports) { + const Server: any = moduleExports; + for (const name of constants.RESTIFY_METHODS) { + this._unwrap(Server.prototype, name as keyof Server); + } + for (const name of constants.RESTIFY_MW_METHODS) { + this._unwrap(Server.prototype, name as keyof Server); + } + } + } + ) + ); + + return module; + } + + private _middlewarePatcher(original: Function, methodName?: string) { + const instrumentation = this; + return function (this: Server, ...handler: types.NestedRequestHandlers) { + return original.call( + this, + instrumentation._handlerPatcher( + { type: types.LayerType.MIDDLEWARE, methodName }, + handler + ) + ); + }; + } + + private _methodPatcher(original: Function, methodName?: string) { + const instrumentation = this; + return function ( + this: Server, + path: any, + ...handler: types.NestedRequestHandlers + ) { + return original.call( + this, + path, + ...instrumentation._handlerPatcher( + { type: types.LayerType.REQUEST_HANDLER, path, methodName }, + handler + ) + ); + }; + } + + // will return the same type as `handler`, but all functions recusively patched + private _handlerPatcher( + metadata: types.Metadata, + handler: restify.RequestHandler | types.NestedRequestHandlers + ): any { + if (Array.isArray(handler)) { + return handler.map(handler => this._handlerPatcher(metadata, handler)); + } + if (typeof handler === 'function') { + return ( + req: types.Request, + res: restify.Response, + next: restify.Next + ) => { + if (this._isDisabled) { + return handler(req, res, next); + } + const route = + typeof req.getRoute === 'function' + ? req.getRoute()?.path + : req.route?.path; + + // replace HTTP instrumentations name with one that contains a route + // in first handlers, we might not now the route yet, in which case the HTTP + // span has to be stored and fixed in later handler. + // https://github.com/open-telemetry/opentelemetry-specification/blob/a44d863edcdef63b0adce7b47df001933b7a158a/specification/trace/semantic_conventions/http.md#name + if (req[constants.REQ_SPAN] === undefined) { + req[constants.REQ_SPAN] = api.getSpan( + api.context.active() + ) as types.InstrumentationSpan; + } + if ( + route && + req[constants.REQ_SPAN] && + req[constants.REQ_SPAN]?.name?.startsWith('HTTP ') + ) { + (req[constants.REQ_SPAN] as types.InstrumentationSpan).updateName( + `${req.method} ${route}` + ); + req[constants.REQ_SPAN] = false; + } + + const fnName = handler.name || undefined; + const spanName = + metadata.type === types.LayerType.REQUEST_HANDLER + ? `request handler - ${route}` + : `middleware - ${fnName || 'anonymous'}`; + const attributes = { + [types.CustomAttributeNames.NAME]: fnName, + [types.CustomAttributeNames.VERSION]: this._moduleVersion || 'n/a', + [types.CustomAttributeNames.TYPE]: metadata.type, + [types.CustomAttributeNames.METHOD]: metadata.methodName, + [HttpAttribute.HTTP_ROUTE]: route, + }; + const span = this.tracer.startSpan( + spanName, + { + attributes, + }, + api.context.active() + ); + const patchedNext = (err?: any) => { + span.end(); + next(err); + }; + patchedNext.ifError = next.ifError; + + const wrapPromise = (promise: Promise) => { + return promise + .then(value => { + span.end(); + return value; + }) + .catch(err => { + span.recordException(err); + span.end(); + throw err; + }); + }; + + return api.context.with( + api.setSpan(api.context.active(), span), + (req: types.Request, res: restify.Response, next: restify.Next) => { + if (isAsyncFunction(handler)) { + return wrapPromise(handler(req, res, next)); + } + try { + const result = handler(req, res, next); + if (isPromise(result)) { + return wrapPromise(result); + } + span.end(); + return result; + } catch (err) { + span.recordException(err); + span.end(); + throw err; + } + }, + this, + req, + res, + patchedNext + ); + }; + } + + return handler; + } +} diff --git a/plugins/node/opentelemetry-instrumentation-restify/src/types.ts b/plugins/node/opentelemetry-instrumentation-restify/src/types.ts new file mode 100644 index 0000000000..3af3984cd1 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-restify/src/types.ts @@ -0,0 +1,55 @@ +/* + * 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'; +import * as restify from 'restify'; +import { REQ_SPAN } from './constants'; + +export enum CustomAttributeNames { + TYPE = 'restify.type', + NAME = 'restify.name', + METHOD = 'restify.method', + VERSION = 'restify.version', +} + +export enum LayerType { + MIDDLEWARE = 'middleware', + REQUEST_HANDLER = 'request_handler', +} + +declare interface RequestWithRoute extends restify.Request { + // undefined /* uninitialized */ | false /* renamed */ | InstrumentationSpan /* not yet renamed */ + [REQ_SPAN]?: any; + route: { path: string }; + getRoute: () => { path: string }; +} + +export declare type Request = RequestWithRoute; +export declare type Metadata = { + path?: string; + methodName?: string; + type: LayerType; +}; + +export type NestedRequestHandlers = Array< + NestedRequestHandlers | restify.RequestHandler +>; + +/** + * 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-restify/src/utils.ts b/plugins/node/opentelemetry-instrumentation-restify/src/utils.ts new file mode 100644 index 0000000000..d749799e1d --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-restify/src/utils.ts @@ -0,0 +1,38 @@ +/* + * 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. + */ + +// util.types.isPromise is supported from 10.0.0 +export const isPromise = (value: any): value is Promise => { + if ( + typeof value.then === 'function' && + typeof value.catch === 'function' && + value.toString() === '[object Promise]' + ) { + return true; + } + return false; +}; + +// util.types.isAsyncFunction is supported from 10.0.0 +export const isAsyncFunction = (value: unknown) => { + if ( + typeof value === 'function' && + value.constructor?.name === 'AsyncFunction' + ) { + return true; + } + return false; +}; diff --git a/plugins/node/opentelemetry-instrumentation-restify/src/version.ts b/plugins/node/opentelemetry-instrumentation-restify/src/version.ts new file mode 100644 index 0000000000..1e4172026f --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-restify/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-restify/test/restify.test.ts b/plugins/node/opentelemetry-instrumentation-restify/test/restify.test.ts new file mode 100644 index 0000000000..86fc9964c8 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-restify/test/restify.test.ts @@ -0,0 +1,452 @@ +/* + * 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 restify from 'restify'; +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 RestifyInstrumentation from '../src'; +import * as types from '../src/types'; +const plugin = new RestifyInstrumentation(); + +import * as assert from 'assert'; +import * as http from 'http'; +import { AddressInfo } from 'net'; + +const httpRequest = { + get: (options: http.ClientRequestArgs | string) => { + return new Promise((resolve, reject) => { + return http.get(options, resp => { + let data = ''; + resp.on('data', chunk => { + data += chunk; + }); + resp.on('end', () => { + resolve(data); + }); + resp.on('error', err => { + reject(err); + }); + }); + }); + }, +}; +const noop = (value: unknown) => {}; +const defer = (): { + promise: Promise; + resolve: Function; + reject: Function; +} => { + let resolve = noop; + let reject = noop; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve, reject }; +}; + +const useHandler: restify.RequestHandler = (req, res, next) => { + // only run if route was found + next(); +}; +const getHandler: restify.RequestHandler = (req, res, next) => { + res.send({ route: req?.params?.param }); +}; +const throwError: restify.RequestHandler = (req, res, next) => { + throw new Error('NOK'); +}; + +const createServer = async (setupRoutes?: Function) => { + const server = restify.createServer(); + + if (typeof setupRoutes === 'function') { + setupRoutes(server); + } else { + // to force an anonymous fn for testing + server.pre((req, res, next) => { + // run before routing + next(); + }); + + server.use(useHandler); + server.get('/route/:param', getHandler); + server.get('/failing', throwError); + } + + await new Promise(resolve => server.listen(0, resolve)); + return server; +}; + +describe('Restify 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: restify.Server; + let port: number; + + before(() => { + plugin.enable(); + }); + + after(() => { + plugin.disable(); + }); + + beforeEach(async () => { + contextManager = new AsyncHooksContextManager(); + context.setGlobalContextManager(contextManager.enable()); + + server = await createServer(); + port = (server.address() as AddressInfo).port; + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + }); + + afterEach(() => { + memoryExporter.reset(); + context.disable(); + server.close(); + }); + + describe('Instrumenting core middleware calls', () => { + it('should create a span for each handler', async () => { + const rootSpan = tracer.startSpan('clientSpan'); + + await context.with(setSpan(context.active(), rootSpan), async () => { + await httpRequest.get(`http://localhost:${port}/route/foo`); + rootSpan.end(); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 4); + + { + // span from pre + const span = memoryExporter.getFinishedSpans()[0]; + assert.notStrictEqual(span, undefined); + assert.strictEqual(span.attributes['http.route'], undefined); + assert.strictEqual(span.attributes['restify.method'], 'pre'); + assert.strictEqual(span.attributes['restify.type'], 'middleware'); + assert.strictEqual(span.attributes['restify.name'], undefined); + assert.strictEqual(span.attributes['restify.version'], 'n/a'); + } + { + // span from use + const span = memoryExporter.getFinishedSpans()[1]; + assert.notStrictEqual(span, undefined); + assert.strictEqual(span.attributes['http.route'], '/route/:param'); + assert.strictEqual(span.attributes['restify.method'], 'use'); + assert.strictEqual(span.attributes['restify.type'], 'middleware'); + assert.strictEqual(span.attributes['restify.name'], 'useHandler'); + assert.strictEqual(span.attributes['restify.version'], 'n/a'); + } + { + // span from get + const span = memoryExporter.getFinishedSpans()[2]; + assert.notStrictEqual(span, undefined); + assert.strictEqual(span.attributes['http.route'], '/route/:param'); + assert.strictEqual(span.attributes['restify.method'], 'get'); + assert.strictEqual( + span.attributes['restify.type'], + 'request_handler' + ); + assert.strictEqual(span.attributes['restify.name'], 'getHandler'); + assert.strictEqual(span.attributes['restify.version'], 'n/a'); + } + }); + }); + + it('should lack `http.route` but still have `restify.version` if route was 404', async () => { + const rootSpan = tracer.startSpan('rootSpan'); + + await context.with(setSpan(context.active(), rootSpan), async () => { + const res = await httpRequest.get(`http://localhost:${port}/not-found`); + rootSpan.end(); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 2); + + { + // span from pre + const span = memoryExporter.getFinishedSpans()[0]; + assert.notStrictEqual(span, undefined); + assert.strictEqual(span.attributes['http.route'], undefined); + assert.strictEqual(span.attributes['restify.method'], 'pre'); + assert.strictEqual(span.attributes['restify.type'], 'middleware'); + assert.strictEqual(span.attributes['restify.name'], undefined); + assert.strictEqual(span.attributes['restify.version'], 'n/a'); + } + assert.strictEqual( + res, + '{"code":"ResourceNotFound","message":"/not-found does not exist"}' + ); + }); + }); + + it('should create a span for an endpoint that threw', async () => { + const rootSpan = tracer.startSpan('clientSpan'); + + await context.with(setSpan(context.active(), rootSpan), async () => { + await httpRequest.get(`http://localhost:${port}/failing`); + rootSpan.end(); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 4); + + { + // span from pre + const span = memoryExporter.getFinishedSpans()[0]; + assert.notStrictEqual(span, undefined); + assert.strictEqual(span.attributes['http.route'], undefined); + assert.strictEqual(span.attributes['restify.method'], 'pre'); + assert.strictEqual(span.attributes['restify.type'], 'middleware'); + assert.strictEqual(span.attributes['restify.name'], undefined); + assert.strictEqual(span.attributes['restify.version'], 'n/a'); + } + { + // span from use + const span = memoryExporter.getFinishedSpans()[1]; + assert.notStrictEqual(span, undefined); + assert.strictEqual(span.attributes['http.route'], '/failing'); + assert.strictEqual(span.attributes['restify.method'], 'use'); + assert.strictEqual(span.attributes['restify.type'], 'middleware'); + assert.strictEqual(span.attributes['restify.name'], 'useHandler'); + assert.strictEqual(span.attributes['restify.version'], 'n/a'); + } + { + // span from get + const span = memoryExporter.getFinishedSpans()[2]; + assert.notStrictEqual(span, undefined); + assert.strictEqual(span.attributes['http.route'], '/failing'); + assert.strictEqual(span.attributes['restify.method'], 'get'); + assert.strictEqual( + span.attributes['restify.type'], + 'request_handler' + ); + assert.strictEqual(span.attributes['restify.name'], 'throwError'); + assert.strictEqual(span.attributes['restify.version'], 'n/a'); + } + }); + }); + + it('should rename HTTP span', async () => { + const httpSpan: types.InstrumentationSpan = tracer.startSpan('HTTP GET'); + + const testLocalServer = await createServer((server: restify.Server) => { + server.pre((req, res, next) => { + // to simulate HTTP instrumentation + context.with(setSpan(context.active(), httpSpan), next); + }); + server.get('/route/:param', getHandler); + }); + const testLocalPort = testLocalServer.address().port; + + 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 work with verbose API', async () => { + const testLocalServer = await createServer((server: restify.Server) => { + server.get( + { + path: '/route/:param', + }, + getHandler + ); + }); + const testLocalPort = testLocalServer.address().port; + + try { + const res = await httpRequest.get( + `http://localhost:${testLocalPort}/route/hello` + ); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 1); + { + // span from get + const span = memoryExporter.getFinishedSpans()[0]; + assert.notStrictEqual(span, undefined); + assert.strictEqual(span.attributes['http.route'], '/route/:param'); + assert.strictEqual(span.attributes['restify.method'], 'get'); + assert.strictEqual( + span.attributes['restify.type'], + 'request_handler' + ); + assert.strictEqual(span.attributes['restify.name'], 'getHandler'); + assert.strictEqual(span.attributes['restify.version'], 'n/a'); + } + assert.strictEqual(res, '{"route":"hello"}'); + } finally { + testLocalServer.close(); + } + }); + + it('should work with async handlers', async () => { + const { promise: work, resolve: resolveWork } = defer(); + const { promise: started, resolve: resolveStarted } = defer(); + // status to assert the correctness of the test + let status = 'uninit'; + const asyncHandler: restify.RequestHandler = async (req, res, next) => { + status = 'started'; + resolveStarted(); + await work; + status = 'done'; + return getHandler(req, res, next); + }; + const testLocalServer = await createServer((server: restify.Server) => { + server.get('/route/:param', asyncHandler); + }); + const testLocalPort = testLocalServer.address().port; + + try { + const requestPromise = httpRequest + .get(`http://localhost:${testLocalPort}/route/hello`) + .then(res => { + // assert request results + assert.strictEqual(res, '{"route":"hello"}'); + }); + + // assert pre request state + assert.strictEqual(status, 'uninit'); + await started; + + // assert started state + assert.strictEqual(status, 'started'); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + + resolveWork(); + await requestPromise; + + // assert done state + assert.strictEqual(status, 'done'); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 1); + { + // span from get + const span = memoryExporter.getFinishedSpans()[0]; + assert.notStrictEqual(span, undefined); + assert.strictEqual(span.attributes['http.route'], '/route/:param'); + assert.strictEqual(span.attributes['restify.method'], 'get'); + assert.strictEqual( + span.attributes['restify.type'], + 'request_handler' + ); + assert.strictEqual(span.attributes['restify.name'], 'asyncHandler'); + assert.strictEqual(span.attributes['restify.version'], 'n/a'); + } + } finally { + testLocalServer.close(); + } + }); + + it('should work with promise-returning handlers', async () => { + const { promise: work, resolve: resolveWork } = defer(); + const { promise: started, resolve: resolveStarted } = defer(); + // status to assert the correctness of the test + let status = 'uninit'; + const promiseReturningHandler: restify.RequestHandler = ( + req, + res, + next + ) => { + status = 'started'; + resolveStarted(); + return work.then(() => { + status = 'done'; + return getHandler(req, res, next); + }); + }; + const testLocalServer = await createServer((server: restify.Server) => { + server.get('/route/:param', promiseReturningHandler); + }); + const testLocalPort = testLocalServer.address().port; + + try { + const requestPromise = httpRequest + .get(`http://localhost:${testLocalPort}/route/hello`) + .then(res => { + // assert request results + assert.strictEqual(res, '{"route":"hello"}'); + }); + + // assert pre request state + assert.strictEqual(status, 'uninit'); + await started; + + // assert started state + assert.strictEqual(status, 'started'); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + + resolveWork(); + await requestPromise; + + // assert done state + assert.strictEqual(status, 'done'); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 1); + { + // span from get + const span = memoryExporter.getFinishedSpans()[0]; + assert.notStrictEqual(span, undefined); + assert.strictEqual(span.attributes['http.route'], '/route/:param'); + assert.strictEqual(span.attributes['restify.method'], 'get'); + assert.strictEqual( + span.attributes['restify.type'], + 'request_handler' + ); + assert.strictEqual( + span.attributes['restify.name'], + 'promiseReturningHandler' + ); + assert.strictEqual(span.attributes['restify.version'], 'n/a'); + } + } finally { + testLocalServer.close(); + } + }); + + it('should create spans even if there is no parent', async () => { + const res = await httpRequest.get(`http://localhost:${port}/route/bar`); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 3); + assert.strictEqual(res, '{"route":"bar"}'); + }); + }); + + describe('Disabling restify instrumentation', () => { + it('should not create new spans', async () => { + plugin.disable(); + const rootSpan = tracer.startSpan('rootSpan'); + + await context.with(setSpan(context.active(), rootSpan), async () => { + assert.strictEqual( + await httpRequest.get(`http://localhost:${port}/route/foo`), + '{"route":"foo"}' + ); + rootSpan.end(); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 1); + assert.notStrictEqual(memoryExporter.getFinishedSpans()[0], undefined); + }); + }); + }); +}); diff --git a/plugins/node/opentelemetry-instrumentation-restify/tsconfig.json b/plugins/node/opentelemetry-instrumentation-restify/tsconfig.json new file mode 100644 index 0000000000..28be80d266 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-restify/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../../tsconfig.base", + "compilerOptions": { + "rootDir": ".", + "outDir": "build" + }, + "include": [ + "src/**/*.ts", + "test/**/*.ts" + ] +}