diff --git a/examples/hapi/README.md b/examples/hapi/README.md new file mode 100644 index 0000000000..38bbf9f1dd --- /dev/null +++ b/examples/hapi/README.md @@ -0,0 +1,76 @@ +# Overview + +OpenTelemetry Hapi 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), to give observability to distributed systems. + +This is a simple example that demonstrates tracing calls made in a Hapi application. The example shows key aspects of tracing such as +- Root Span (on Client) +- Child Span (on Client) +- Span Attributes +- Instrumentation for routes and request extension points +- Instrumentation of Hapi plugins + +## Installation + +```sh +$ # from this directory +$ npm install +``` + +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 + +### Zipkin + + - Run the server + + ```sh + # from this directory + $ npm run zipkin:server + ``` + + - Run the client + + ```sh + # from this directory + npm run zipkin:client + ``` + +#### Zipkin UI +`zipkin:server` script should output the `traceid` in the terminal (e.g `traceid: 4815c3d576d930189725f1f1d1bdfcc6`). +Go to Zipkin with your browser [http://localhost:9411/zipkin/traces/(your-trace-id)]() (e.g http://localhost:9411/zipkin/traces/4815c3d576d930189725f1f1d1bdfcc6) + +

+ +### Jaeger + + - Run the server + + ```sh + # from this directory + $ npm run jaeger:server + ``` + + - Run the client + + ```sh + # from this directory + npm run jaeger:client + ``` + +#### Jaeger UI + +`jaeger:server` script should output the `traceid` in the terminal (e.g `traceid: 4815c3d576d930189725f1f1d1bdfcc6`). +Go to Jaeger with your browser [http://localhost:16686/trace/(your-trace-id)]() (e.g http://localhost:16686/trace/4815c3d576d930189725f1f1d1bdfcc6) + +

+ +## 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/hapi/client.js b/examples/hapi/client.js new file mode 100644 index 0000000000..0876f32201 --- /dev/null +++ b/examples/hapi/client.js @@ -0,0 +1,28 @@ +'use strict'; + +// eslint-disable-next-line import/order +const tracer = require('./tracer')('example-hapi-client'); +const api = require('@opentelemetry/api'); +const axios = require('axios').default; + +function makeRequest() { + const span = tracer.startSpan('client.makeRequest()', { + parent: tracer.getCurrentSpan(), + kind: api.SpanKind.CLIENT, + }); + + tracer.withSpan(span, async () => { + try { + const res = await axios.get('http://localhost:8081/run_test'); + span.setStatus({ code: api.CanonicalCode.OK }); + console.log(res.statusText); + } catch (e) { + span.setStatus({ code: api.CanonicalCode.UNKNOWN, message: e.message }); + } + span.end(); + console.log('Sleeping 5 seconds before shutdown to ensure all records are flushed.'); + setTimeout(() => { console.log('Completed.'); }, 5000); + }); +} + +makeRequest(); diff --git a/examples/hapi/images/jaeger.jpg b/examples/hapi/images/jaeger.jpg new file mode 100644 index 0000000000..b7202360a0 Binary files /dev/null and b/examples/hapi/images/jaeger.jpg differ diff --git a/examples/hapi/images/zipkin.jpg b/examples/hapi/images/zipkin.jpg new file mode 100644 index 0000000000..f763aa4825 Binary files /dev/null and b/examples/hapi/images/zipkin.jpg differ diff --git a/examples/hapi/package.json b/examples/hapi/package.json new file mode 100644 index 0000000000..5414e713b7 --- /dev/null +++ b/examples/hapi/package.json @@ -0,0 +1,49 @@ +{ + "name": "hapi-example", + "private": true, + "version": "0.9.0", + "description": "Example of Hapi auto-instrumentation 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", + "lint": "eslint . --ext .js", + "lint:fix": "eslint . --ext .js --fix" + }, + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/open-telemetry/opentelemetry-js-contrib.git" + }, + "keywords": [ + "opentelemetry", + "hapi", + "tracing", + "instrumentation" + ], + "engines": { + "node": ">=8" + }, + "author": "OpenTelemetry Authors", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/open-telemetry/opentelemetry-js-contrib/issues" + }, + "dependencies": { + "@hapi/hapi": "^19.2.0", + "@opentelemetry/api": "^0.10.2", + "@opentelemetry/exporter-jaeger": "^0.10.2", + "@opentelemetry/exporter-zipkin": "^0.10.2", + "@opentelemetry/hapi-instrumentation": "^0.9.0", + "@opentelemetry/node": "^0.10.2", + "@opentelemetry/plugin-http": "^0.9.0", + "@opentelemetry/tracing": "^0.10.2", + "axios": "^0.19.0" + }, + "homepage": "https://github.com/open-telemetry/opentelemetry-js-contrib#readme", + "devDependencies": { + "cross-env": "^6.0.0", + "eslint": "^7.4.0" + } +} diff --git a/examples/hapi/server.js b/examples/hapi/server.js new file mode 100644 index 0000000000..cee9885d07 --- /dev/null +++ b/examples/hapi/server.js @@ -0,0 +1,95 @@ +'use strict'; + +const tracer = require('./tracer')('example-hapi-server'); +// eslint-disable-next-line +const Hapi = require('@hapi/hapi'); + +const PORT = 8081; +const server = Hapi.server({ + port: PORT, + host: 'localhost', +}); + +const BlogPostPlugin = { + name: 'blog-post-plugin', + version: '1.0.0', + async register(serverClone) { + console.log('Registering basic hapi plugin'); + + serverClone.route([ + { + method: 'GET', + path: '/post/new', + handler: addPost, + }, + { + method: 'GET', + path: '/post/{id}', + handler: showNewPost, + }]); + }, +}; + +async function setUp() { + await server.register( + { plugin: BlogPostPlugin }, + ); + + server.route( + { + method: 'GET', + path: '/run_test', + handler: runTest, + }, + ); + + server.ext('onRequest', async (request, h) => { + console.log('No-op Hapi lifecycle extension method'); + const syntheticDelay = 50; + await new Promise((r) => setTimeout(r, syntheticDelay)); + return h.continue; + }); + + await server.start(); + console.log('Server running on %s', server.info.uri); + console.log(`Listening on http://localhost:${PORT}`); +} + +/** + * Blog Post functions: list, add, or show posts +*/ +const posts = ['post 0', 'post 1', 'post 2']; + +function addPost(_, h) { + posts.push(`post ${posts.length}`); + const currentSpan = tracer.getCurrentSpan(); + currentSpan.addEvent('Added post'); + currentSpan.setAttribute('Date', new Date()); + console.log(`Added post: ${posts[posts.length - 1]}`); + return h.redirect('/post/3'); +} + +async function showNewPost(request) { + const { id } = request.params; + console.log(`showNewPost with id: ${id}`); + const post = posts[id]; + if (!post) throw new Error('Invalid post id'); + const syntheticDelay = 200; + await new Promise((r) => setTimeout(r, syntheticDelay)); + return post; +} + +function runTest(_, h) { + const currentSpan = tracer.getCurrentSpan(); + const { traceId } = currentSpan.context(); + console.log(`traceid: ${traceId}`); + console.log(`Jaeger URL: http://localhost:16686/trace/${traceId}`); + console.log(`Zipkin URL: http://localhost:9411/zipkin/traces/${traceId}`); + return h.redirect('/post/new'); +} + +setUp(); +process.on('unhandledRejection', (err) => { + console.log(err); + process.exit(1); +}); diff --git a/examples/hapi/tracer.js b/examples/hapi/tracer.js new file mode 100644 index 0000000000..142ad5d595 --- /dev/null +++ b/examples/hapi/tracer.js @@ -0,0 +1,38 @@ +'use strict'; + +const opentelemetry = require('@opentelemetry/api'); +const { NodeTracerProvider } = require('@opentelemetry/node'); +const { SimpleSpanProcessor } = require('@opentelemetry/tracing'); +const { JaegerExporter } = require('@opentelemetry/exporter-jaeger'); +const { ZipkinExporter } = require('@opentelemetry/exporter-zipkin'); + +const EXPORTER = process.env.EXPORTER || ''; + +module.exports = (serviceName) => { + const provider = new NodeTracerProvider({ + plugins: { + '@hapi/hapi': { + enabled: true, + path: '@opentelemetry/hapi-instrumentation', + enhancedDatabaseReporting: true, + }, + http: { + enabled: true, + path: '@opentelemetry/plugin-http', + }, + }, + }); + + let exporter; + if (EXPORTER === 'jaeger') { + exporter = new JaegerExporter({ serviceName }); + } else { + exporter = new ZipkinExporter({ serviceName }); + } + provider.addSpanProcessor(new SimpleSpanProcessor(exporter)); + + // Initialize the OpenTelemetry APIs to use the NodeTracerProvider bindings + provider.register(); + + return opentelemetry.trace.getTracer('hapi-example'); +}; diff --git a/plugins/node/opentelemetry-hapi-instrumentation/.eslintignore b/plugins/node/opentelemetry-hapi-instrumentation/.eslintignore new file mode 100644 index 0000000000..378eac25d3 --- /dev/null +++ b/plugins/node/opentelemetry-hapi-instrumentation/.eslintignore @@ -0,0 +1 @@ +build diff --git a/plugins/node/opentelemetry-hapi-instrumentation/.eslintrc.js b/plugins/node/opentelemetry-hapi-instrumentation/.eslintrc.js new file mode 100644 index 0000000000..f756f4488b --- /dev/null +++ b/plugins/node/opentelemetry-hapi-instrumentation/.eslintrc.js @@ -0,0 +1,7 @@ +module.exports = { + "env": { + "mocha": true, + "node": true + }, + ...require('../../../eslint.config.js') +} diff --git a/plugins/node/opentelemetry-hapi-instrumentation/.mocharc.js b/plugins/node/opentelemetry-hapi-instrumentation/.mocharc.js new file mode 100644 index 0000000000..802a8a3ed7 --- /dev/null +++ b/plugins/node/opentelemetry-hapi-instrumentation/.mocharc.js @@ -0,0 +1,12 @@ +'use strict'; + +const semver = require('semver'); + +if (semver.satisfies(process.version, '>=12.0.0')) { + module.exports = { + spec: 'test/**/*.ts', + }; +} else { + console.log(`Hapi instrumentation tests skipped for Node.js ${process.version} - unsupported by Hapi`); + module.exports = {}; +} diff --git a/plugins/node/opentelemetry-hapi-instrumentation/.npmignore b/plugins/node/opentelemetry-hapi-instrumentation/.npmignore new file mode 100644 index 0000000000..9505ba9450 --- /dev/null +++ b/plugins/node/opentelemetry-hapi-instrumentation/.npmignore @@ -0,0 +1,4 @@ +/bin +/coverage +/doc +/test diff --git a/plugins/node/opentelemetry-hapi-instrumentation/LICENSE b/plugins/node/opentelemetry-hapi-instrumentation/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/plugins/node/opentelemetry-hapi-instrumentation/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-hapi-instrumentation/README.md b/plugins/node/opentelemetry-hapi-instrumentation/README.md new file mode 100644 index 0000000000..e8abaf98eb --- /dev/null +++ b/plugins/node/opentelemetry-hapi-instrumentation/README.md @@ -0,0 +1,67 @@ +# OpenTelemetry Hapi 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 [`Hapi`](https://hapi.dev). + +For automatic instrumentation see the +[@opentelemetry/node](https://github.com/open-telemetry/opentelemetry-js/tree/master/packages/opentelemetry-node) package. + +## Installation + +```bash +npm install --save @opentelemetry/hapi-instrumentation +``` +### Supported Versions + - @hapi/hapi `^17.0.0` + +## Usage + +OpenTelemetry Hapi Instrumentation allows the user to automatically collect trace data and export them to their backend of choice, to give observability to distributed systems. + +To load a specific instrumentation (Hapi in this case), specify it in the Node Tracer's configuration. +```js +const { NodeTracerProvider } = require('@opentelemetry/node'); + +const provider = new NodeTracerProvider({ + plugins: { + '@hapi/hapi': { + enabled: true, + // You may use a package name or absolute path to the file. + path: '@opentelemetry/hapi-instrumentation', + } + } +}); +``` + +To load all of the [supported instrumentations](https://github.com/open-telemetry/opentelemetry-js#plugins), use below approach. Each instrumentation is only loaded when the module that it patches is loaded; in other words, there is no computational overhead for listing instrumentations for unused modules. +```js +const { NodeTracerProvider } = require('@opentelemetry/node'); + +const provider = new NodeTracerProvider(); +``` + +See [examples/hapi](https://github.com/open-telemetry/opentelemetry-js-contrib/tree/master/examples/hapi) for a short example using Hapi + +## Hapi Instrumentation Support +This package provides automatic tracing for hapi server routes and [request lifecycle](https://github.com/hapijs/hapi/blob/master/API.md#request-lifecycle) extensions defined either directly or via a Hapi plugin. + +## 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/master/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=plugins/node/opentelemetry-hapi-instrumentation +[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=plugins/node/opentelemetry-hapi-instrumentation +[devDependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib/dev-status.svg?path=plugins/node/opentelemetry-hapi-instrumentation +[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=plugins/node/opentelemetry-hapi-instrumentation&type=dev diff --git a/plugins/node/opentelemetry-hapi-instrumentation/package.json b/plugins/node/opentelemetry-hapi-instrumentation/package.json new file mode 100644 index 0000000000..73772b8ae6 --- /dev/null +++ b/plugins/node/opentelemetry-hapi-instrumentation/package.json @@ -0,0 +1,72 @@ +{ + "name": "@opentelemetry/hapi-instrumentation", + "version": "0.9.0", + "description": "OpenTelemetry Hapi 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 --config .mocharc.js", + "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" + }, + "keywords": [ + "opentelemetry", + "hapi", + "nodejs", + "tracing", + "profiling", + "instrumentation" + ], + "author": "OpenTelemetry Authors", + "license": "Apache-2.0", + "engines": { + "node": ">=8.0.0" + }, + "files": [ + "build/src/**/*.js", + "build/src/**/*.d.ts", + "doc", + "LICENSE", + "README.md" + ], + "publishConfig": { + "access": "public" + }, + "devDependencies": { + "@hapi/hapi": "^19.2.0", + "@opentelemetry/context-async-hooks": "^0.10.2", + "@opentelemetry/node": "^0.10.2", + "@opentelemetry/tracing": "^0.10.2", + "@types/hapi__hapi": "^19.0.3", + "@types/mocha": "7.0.2", + "@types/node": "12.12.47", + "@types/shimmer": "1.0.1", + "codecov": "3.7.0", + "eslint": "^7.4.0", + "eslint-plugin-header": "^3.0.0", + "gts": "2.0.2", + "mocha": "7.2.0", + "nyc": "15.1.0", + "rimraf": "3.0.2", + "semver": "^7.3.2", + "ts-mocha": "7.0.0", + "ts-node": "8.10.2", + "tslint-consistent-codestyle": "1.16.0", + "tslint-microsoft-contrib": "6.2.0", + "typescript": "3.9.6" + }, + "dependencies": { + "@opentelemetry/api": "^0.10.2", + "@opentelemetry/core": "^0.10.2", + "@opentelemetry/semantic-conventions": "^0.10.2", + "shimmer": "^1.2.1" + } +} diff --git a/plugins/node/opentelemetry-hapi-instrumentation/src/hapi.ts b/plugins/node/opentelemetry-hapi-instrumentation/src/hapi.ts new file mode 100644 index 0000000000..0bd4862f7e --- /dev/null +++ b/plugins/node/opentelemetry-hapi-instrumentation/src/hapi.ts @@ -0,0 +1,385 @@ +/* + * 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 { BasePlugin } from '@opentelemetry/core'; +import type * as Hapi from '@hapi/hapi'; +import { VERSION } from './version'; +import { + HapiComponentName, + HapiServerRouteInput, + handlerPatched, + PatchableServerRoute, + HapiServerRouteInputMethod, + HapiPluginInput, + RegisterFunction, + PatchableExtMethod, + ServerExtDirectInput, +} from './types'; +import * as shimmer from 'shimmer'; +import { + getRouteMetadata, + getPluginName, + isLifecycleExtType, + isLifecycleExtEventObj, + getExtMetadata, + isDirectExtInput, + isPatchableExtMethod, +} from './utils'; + +/** Hapi instrumentation for OpenTelemetry */ +export class HapiInstrumentation extends BasePlugin { + static readonly component = HapiComponentName; + + constructor(readonly moduleName: string) { + super('@opentelemetry/hapi-instrumentation', VERSION); + } + + /** + * Patches Hapi operations by wrapping the Hapi.server and Hapi.Server functions + */ + protected patch(): typeof Hapi { + this._logger.debug('Patching Hapi'); + if (this._moduleExports == null) { + return this._moduleExports; + } + + this._logger.debug('Patching Hapi.server'); + shimmer.wrap( + this._moduleExports, + 'server', + this._getServerPatch.bind(this) + ); + + // Casting as any is necessary here due to an issue with the @types/hapi__hapi + // type definition for Hapi.Server. Hapi.Server (note the uppercase) can also function + // as a factory function, similarly to Hapi.server (lowercase), and so should + // also be supported and instrumented. This is an issue with the DefinitelyTyped repo. + // Function is defined at: https://github.com/hapijs/hapi/blob/master/lib/index.js#L9 + this._logger.debug('Patching Hapi.Server'); + shimmer.wrap( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this._moduleExports as any, + 'Server', + this._getServerPatch.bind(this) + ); + + return this._moduleExports; + } + + /** + * Unpatches all Hapi operations + */ + protected unpatch(): void { + this._logger.debug('Unpatching Hapi'); + shimmer.massUnwrap([this._moduleExports], ['server', 'Server']); + } + + /** + * Patches the Hapi.server and Hapi.Server functions in order to instrument + * the server.route, server.ext, and server.register functions via calls to the + * @function _getServerRoutePatch, @function _getServerExtPatch, and + * @function _getServerRegisterPatch functions + * @param original - the original Hapi Server creation function + */ + private _getServerPatch( + original: (options?: Hapi.ServerOptions) => Hapi.Server + ) { + const instrumentation: HapiInstrumentation = this; + return function server(this: Hapi.Server, opts?: Hapi.ServerOptions) { + const newServer: Hapi.Server = original.apply(this, [opts]); + + shimmer.wrap(newServer, 'route', originalRouter => { + return instrumentation._getServerRoutePatch.bind(instrumentation)( + originalRouter + ); + }); + + // Casting as any is necessary here due to multiple overloads on the Hapi.ext + // function, which requires supporting a variety of different parameters + // as extension inputs + shimmer.wrap(newServer, 'ext', originalExtHandler => { + return instrumentation._getServerExtPatch.bind(instrumentation)( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + originalExtHandler as any + ); + }); + + // Casting as any is necessary here due to multiple overloads on the Hapi.Server.register + // function, which requires supporting a variety of different types of Plugin inputs + shimmer.wrap( + newServer, + 'register', + // eslint-disable-next-line @typescript-eslint/no-explicit-any + instrumentation._getServerRegisterPatch.bind(instrumentation) as any + ); + return newServer; + }; + } + + /** + * Patches the plugin register function used by the Hapi Server. This function + * goes through each plugin that is being registered and adds instrumentation + * via a call to the @function _wrapRegisterHandler function. + * @param {RegisterFunction} original - the original register function which + * registers each plugin on the server + */ + private _getServerRegisterPatch( + original: RegisterFunction + ): RegisterFunction { + const instrumentation: HapiInstrumentation = this; + this._logger.debug('Patching Hapi.Server register function'); + return function register( + this: Hapi.Server, + pluginInput: HapiPluginInput, + options?: Hapi.ServerRegisterOptions + ) { + if (Array.isArray(pluginInput)) { + for (const pluginObj of pluginInput) { + instrumentation._wrapRegisterHandler(pluginObj.plugin); + } + } else { + instrumentation._wrapRegisterHandler(pluginInput.plugin); + } + return original.apply(this, [pluginInput, options]); + }; + } + + /** + * Patches the Server.ext function which adds extension methods to the specified + * point along the request lifecycle. This function accepts the full range of + * accepted input into the standard Hapi `server.ext` function. For each extension, + * it adds instrumentation to the handler via a call to the @function _wrapExtMethods + * function. + * @param original - the original ext function which adds the extension method to the server + * @param {string} [pluginName] - if present, represents the name of the plugin responsible + * for adding this server extension. Else, signifies that the extension was added directly + */ + private _getServerExtPatch( + original: (...args: unknown[]) => unknown, + pluginName?: string + ) { + const instrumentation: HapiInstrumentation = this; + instrumentation._logger.debug('Patching Hapi.Server ext function'); + + return function ext( + this: ThisParameterType, + ...args: Parameters + ) { + if (Array.isArray(args[0])) { + const eventsList: + | Hapi.ServerExtEventsObject[] + | Hapi.ServerExtEventsRequestObject[] = args[0]; + for (let i = 0; i < eventsList.length; i++) { + const eventObj = eventsList[i]; + if (isLifecycleExtType(eventObj.type)) { + const lifecycleEventObj = eventObj as Hapi.ServerExtEventsRequestObject; + const handler = instrumentation._wrapExtMethods( + lifecycleEventObj.method, + eventObj.type, + pluginName + ); + lifecycleEventObj.method = handler; + eventsList[i] = lifecycleEventObj; + } + } + return original.apply(this, args); + } else if (isDirectExtInput(args)) { + const extInput: ServerExtDirectInput = args; + const method: PatchableExtMethod = extInput[1]; + const handler = instrumentation._wrapExtMethods( + method, + extInput[0], + pluginName + ); + return original.apply(this, [extInput[0], handler, extInput[2]]); + } else if (isLifecycleExtEventObj(args[0])) { + const lifecycleEventObj = args[0]; + const handler = instrumentation._wrapExtMethods( + lifecycleEventObj.method, + lifecycleEventObj.type, + pluginName + ); + lifecycleEventObj.method = handler; + return original.call(this, lifecycleEventObj); + } + return original.apply(this, args); + }; + } + + /** + * Patches the Server.route function. This function accepts either one or an array + * of Hapi.ServerRoute objects and adds instrumentation on each route via a call to + * the @function _wrapRouteHandler function. + * @param {HapiServerRouteInputMethod} original - the original route function which adds + * the route to the server + * @param {string} [pluginName] - if present, represents the name of the plugin responsible + * for adding this server route. Else, signifies that the route was added directly + */ + private _getServerRoutePatch( + original: HapiServerRouteInputMethod, + pluginName?: string + ) { + const instrumentation: HapiInstrumentation = this; + instrumentation._logger.debug('Patching Hapi.Server route function'); + return function route( + this: Hapi.Server, + route: HapiServerRouteInput + ): void { + if (Array.isArray(route)) { + for (let i = 0; i < route.length; i++) { + const newRoute = instrumentation._wrapRouteHandler.call( + instrumentation, + route[i], + pluginName + ); + route[i] = newRoute; + } + } else { + route = instrumentation._wrapRouteHandler.call( + instrumentation, + route, + pluginName + ); + } + return original.apply(this, [route]); + }; + } + + /** + * Wraps newly registered plugins to add instrumentation to the plugin's clone of + * the original server. Specifically, wraps the server.route and server.ext functions + * via calls to @function _getServerRoutePatch and @function _getServerExtPatch + * @param {Hapi.Plugin} plugin - the new plugin which is being instrumented + */ + private _wrapRegisterHandler(plugin: Hapi.Plugin): void { + const instrumentation: HapiInstrumentation = this; + const pluginName = getPluginName(plugin); + const oldHandler = plugin.register; + const newRegisterHandler = function (server: Hapi.Server, options: T) { + shimmer.wrap(server, 'route', original => { + return instrumentation._getServerRoutePatch.bind(instrumentation)( + original, + pluginName + ); + }); + + // Casting as any is necessary here due to multiple overloads on the Hapi.ext + // function, which requires supporting a variety of different parameters + // as extension inputs + shimmer.wrap(server, 'ext', originalExtHandler => { + return instrumentation._getServerExtPatch.bind(instrumentation)( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + originalExtHandler as any, + pluginName + ); + }); + return oldHandler(server, options); + }; + plugin.register = newRegisterHandler; + } + + /** + * Wraps request extension methods to add instrumentation to each new extension handler. + * Patches each individual extension in order to create the + * span and propagate context. It does not create spans when there is no parent span. + * @param {PatchableExtMethod | PatchableExtMethod[]} method - the request extension + * handler which is being instrumented + * @param {Hapi.ServerRequestExtType} extPoint - the point in the Hapi request lifecycle + * which this extension targets + * @param {string} [pluginName] - if present, represents the name of the plugin responsible + * for adding this server route. Else, signifies that the route was added directly + */ + private _wrapExtMethods( + method: T, + extPoint: Hapi.ServerRequestExtType, + pluginName?: string + ): T { + const instrumentation: HapiInstrumentation = this; + + if (method instanceof Array) { + for (let i = 0; i < method.length; i++) { + method[i] = instrumentation._wrapExtMethods( + method[i], + extPoint + ) as PatchableExtMethod; + } + return method; + } else if (isPatchableExtMethod(method)) { + if (method[handlerPatched] === true) return method; + method[handlerPatched] = true; + + const newHandler: PatchableExtMethod = async function ( + ...params: Parameters + ) { + if (instrumentation._tracer.getCurrentSpan() === undefined) { + return await method(...params); + } + const metadata = getExtMetadata(extPoint, pluginName); + const span = instrumentation._tracer.startSpan(metadata.name, { + attributes: metadata.attributes, + }); + let res; + await instrumentation._tracer.withSpan(span, async () => { + res = await method(...params); + }); + span.end(); + return res; + }; + return newHandler as T; + } + return method; + } + + /** + * Patches each individual route handler method in order to create the + * span and propagate context. It does not create spans when there is no parent span. + * @param {PatchableServerRoute} route - the route handler which is being instrumented + * @param {string} [pluginName] - if present, represents the name of the plugin responsible + * for adding this server route. Else, signifies that the route was added directly + */ + private _wrapRouteHandler( + route: PatchableServerRoute, + pluginName?: string + ): PatchableServerRoute { + const instrumentation: HapiInstrumentation = this; + if (route[handlerPatched] === true) return route; + route[handlerPatched] = true; + if (typeof route.handler === 'function') { + const handler = route.handler as Hapi.Lifecycle.Method; + const newHandler: Hapi.Lifecycle.Method = async function ( + request: Hapi.Request, + h: Hapi.ResponseToolkit, + err?: Error + ) { + if (instrumentation._tracer.getCurrentSpan() === undefined) { + return await handler(request, h, err); + } + const metadata = getRouteMetadata(route, pluginName); + const span = instrumentation._tracer.startSpan(metadata.name, { + attributes: metadata.attributes, + }); + const res = await handler(request, h, err); + span.end(); + + return res; + }; + route.handler = newHandler; + } + return route; + } +} + +export const plugin = new HapiInstrumentation(HapiComponentName); diff --git a/plugins/node/opentelemetry-hapi-instrumentation/src/index.ts b/plugins/node/opentelemetry-hapi-instrumentation/src/index.ts new file mode 100644 index 0000000000..c05f3ee2b4 --- /dev/null +++ b/plugins/node/opentelemetry-hapi-instrumentation/src/index.ts @@ -0,0 +1,17 @@ +/* + * 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 * from './hapi'; diff --git a/plugins/node/opentelemetry-hapi-instrumentation/src/types.ts b/plugins/node/opentelemetry-hapi-instrumentation/src/types.ts new file mode 100644 index 0000000000..f8e0fa0c08 --- /dev/null +++ b/plugins/node/opentelemetry-hapi-instrumentation/src/types.ts @@ -0,0 +1,77 @@ +/* + * 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 type * as Hapi from '@hapi/hapi'; + +export const HapiComponentName = '@hapi/hapi'; + +/** + * This symbol is used to mark a Hapi route handler or server extension handler as + * already patched, since its possible to use these handlers multiple times + * i.e. when allowing multiple versions of one plugin, or when registering a plugin + * multiple times on different servers. + */ +export const handlerPatched: unique symbol = Symbol('hapi-handler-patched'); + +export type HapiServerRouteInputMethod = (route: HapiServerRouteInput) => void; + +export type HapiServerRouteInput = + | PatchableServerRoute + | PatchableServerRoute[]; + +export type PatchableServerRoute = Hapi.ServerRoute & { + [handlerPatched]?: boolean; +}; + +export type HapiPluginInput = + | Hapi.ServerRegisterPluginObject + | Array>; + +export type RegisterFunction = ( + plugin: HapiPluginInput, + options?: Hapi.ServerRegisterOptions +) => Promise; + +export type PatchableExtMethod = Hapi.Lifecycle.Method & { + [handlerPatched]?: boolean; +}; + +export type ServerExtDirectInput = [ + Hapi.ServerRequestExtType, + Hapi.Lifecycle.Method, + (Hapi.ServerExtOptions | undefined)? +]; + +export const AttributeNames = { + HAPI_TYPE: 'hapi.type', + PLUGIN_NAME: 'hapi.plugin.name', + EXT_TYPE: 'server.ext.type', +}; + +export const HapiLayerType = { + ROUTER: 'router', + PLUGIN: 'plugin', + EXT: 'server.ext', +}; + +export const HapiLifecycleMethodNames = new Set([ + 'onPreAuth', + 'onCredentials', + 'onPostAuth', + 'onPreHandler', + 'onPostHandler', + 'onPreResponse', + 'onRequest', +]); diff --git a/plugins/node/opentelemetry-hapi-instrumentation/src/utils.ts b/plugins/node/opentelemetry-hapi-instrumentation/src/utils.ts new file mode 100644 index 0000000000..ae34d01f9b --- /dev/null +++ b/plugins/node/opentelemetry-hapi-instrumentation/src/utils.ts @@ -0,0 +1,121 @@ +/* + * 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 { Attributes } from '@opentelemetry/api'; +import { HttpAttribute } from '@opentelemetry/semantic-conventions'; +import type * as Hapi from '@hapi/hapi'; +import { + AttributeNames, + HapiLayerType, + HapiLifecycleMethodNames, + PatchableExtMethod, + ServerExtDirectInput, +} from './types'; + +export function getPluginName(plugin: Hapi.Plugin): string { + if ((plugin as Hapi.PluginNameVersion).name) { + return (plugin as Hapi.PluginNameVersion).name; + } else { + return (plugin as Hapi.PluginPackage).pkg.name; + } +} + +export const isLifecycleExtType = ( + variableToCheck: unknown +): variableToCheck is Hapi.ServerRequestExtType => { + return ( + typeof variableToCheck === 'string' && + HapiLifecycleMethodNames.has(variableToCheck) + ); +}; + +export const isLifecycleExtEventObj = ( + variableToCheck: unknown +): variableToCheck is Hapi.ServerExtEventsRequestObject => { + const event = (variableToCheck as Hapi.ServerExtEventsRequestObject)?.type; + return event !== undefined && isLifecycleExtType(event); +}; + +export const isDirectExtInput = ( + variableToCheck: unknown +): variableToCheck is ServerExtDirectInput => { + return ( + Array.isArray(variableToCheck) && + variableToCheck.length <= 3 && + isLifecycleExtType(variableToCheck[0]) && + typeof variableToCheck[1] === 'function' + ); +}; + +export const isPatchableExtMethod = ( + variableToCheck: PatchableExtMethod | PatchableExtMethod[] +): variableToCheck is PatchableExtMethod => { + return !Array.isArray(variableToCheck); +}; + +export const getRouteMetadata = ( + route: Hapi.ServerRoute, + pluginName?: string +): { + attributes: Attributes; + name: string; +} => { + if (pluginName) { + return { + attributes: { + [HttpAttribute.HTTP_ROUTE]: route.path, + [HttpAttribute.HTTP_METHOD]: route.method, + [AttributeNames.HAPI_TYPE]: HapiLayerType.PLUGIN, + [AttributeNames.PLUGIN_NAME]: pluginName, + }, + name: `${pluginName}: route - ${route.path}`, + }; + } + return { + attributes: { + [HttpAttribute.HTTP_ROUTE]: route.path, + [HttpAttribute.HTTP_METHOD]: route.method, + [AttributeNames.HAPI_TYPE]: HapiLayerType.ROUTER, + }, + name: `route - ${route.path}`, + }; +}; + +export const getExtMetadata = ( + extPoint: Hapi.ServerRequestExtType, + pluginName?: string +): { + attributes: Attributes; + name: string; +} => { + if (pluginName) { + return { + attributes: { + [AttributeNames.EXT_TYPE]: extPoint, + [AttributeNames.HAPI_TYPE]: HapiLayerType.EXT, + [AttributeNames.PLUGIN_NAME]: pluginName, + }, + name: `${pluginName}: ext - ${extPoint}`, + }; + } + return { + attributes: { + [AttributeNames.EXT_TYPE]: extPoint, + [AttributeNames.HAPI_TYPE]: HapiLayerType.EXT, + }, + name: `ext - ${extPoint}`, + }; +}; diff --git a/plugins/node/opentelemetry-hapi-instrumentation/src/version.ts b/plugins/node/opentelemetry-hapi-instrumentation/src/version.ts new file mode 100644 index 0000000000..d42e22554c --- /dev/null +++ b/plugins/node/opentelemetry-hapi-instrumentation/src/version.ts @@ -0,0 +1,16 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export const VERSION = '0.9.0'; diff --git a/plugins/node/opentelemetry-hapi-instrumentation/test/hapi-plugin.test.ts b/plugins/node/opentelemetry-hapi-instrumentation/test/hapi-plugin.test.ts new file mode 100644 index 0000000000..b3a252b0b3 --- /dev/null +++ b/plugins/node/opentelemetry-hapi-instrumentation/test/hapi-plugin.test.ts @@ -0,0 +1,329 @@ +/* + * 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 } from '@opentelemetry/api'; +import { NoopLogger } from '@opentelemetry/core'; +import { NodeTracerProvider } from '@opentelemetry/node'; +import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks'; +import { + InMemorySpanExporter, + SimpleSpanProcessor, +} from '@opentelemetry/tracing'; +import * as assert from 'assert'; +import * as hapi from '@hapi/hapi'; +import { plugin } from '../src'; +import { AttributeNames, HapiLayerType } from '../src/types'; + +describe('Hapi Instrumentation - Hapi.Plugin Tests', () => { + const logger = new NoopLogger(); + const provider = new NodeTracerProvider(); + const memoryExporter = new InMemorySpanExporter(); + const spanProcessor = new SimpleSpanProcessor(memoryExporter); + provider.addSpanProcessor(spanProcessor); + const tracer = provider.getTracer('default'); + let contextManager: AsyncHooksContextManager; + let server: hapi.Server; + + before(() => { + plugin.enable(hapi, provider, logger); + }); + + beforeEach(async () => { + contextManager = new AsyncHooksContextManager(); + context.setGlobalContextManager(contextManager.enable()); + server = hapi.server({ + port: 3000, + host: 'localhost', + }); + }); + + afterEach(async () => { + await server.stop(); + + memoryExporter.reset(); + context.disable(); + }); + + after(() => { + plugin.disable(); + }); + + const multipleVersionPlugin = { + name: 'multipleVersionPlugin', + version: '1.0.0', + multiple: true, + register: async function (server: hapi.Server, options: any) { + server.route({ + method: 'GET', + path: `/${options.path}`, + handler: function (request, h) { + return `hello, world, ${options.name}`; + }, + }); + }, + }; + + const simplePlugin = { + name: 'simplePlugin', + version: '1.0.0', + multiple: true, + register: async function (server: hapi.Server, options: any) { + server.route({ + method: 'GET', + path: '/hello', + handler: function (request, h) { + return `hello, world, ${options.name}`; + }, + }); + }, + }; + + const packagePlugin = { + pkg: require('./testPackage.json'), + register: async function (server: hapi.Server, options: any) { + server.route({ + method: 'GET', + path: '/package', + handler: function (request, h) { + return 'Package'; + }, + }); + }, + }; + + describe('Instrumenting Hapi Plugins', () => { + it('should create spans for routes within single plugins', async () => { + const rootSpan = tracer.startSpan('rootSpan'); + + await server.register({ + plugin: multipleVersionPlugin, + options: { + name: 'world', + path: 'test', + }, + }); + await server.start(); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + + await tracer.withSpan(rootSpan, async () => { + const res = await server.inject({ + method: 'GET', + url: '/test', + }); + assert.strictEqual(res.statusCode, 200); + + rootSpan.end(); + assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); + + const requestHandlerSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'multipleVersionPlugin: route - /test'); + assert.notStrictEqual(requestHandlerSpan, undefined); + assert.strictEqual( + requestHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], + HapiLayerType.PLUGIN + ); + assert.strictEqual( + requestHandlerSpan?.attributes[AttributeNames.PLUGIN_NAME], + 'multipleVersionPlugin' + ); + + const exportedRootSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'rootSpan'); + assert.notStrictEqual(exportedRootSpan, undefined); + }); + }); + + it('should create spans for routes across multiple plugins', async () => { + const rootSpan = tracer.startSpan('rootSpan'); + + await server.register([ + { + plugin: multipleVersionPlugin, + options: { + name: 'world', + path: 'test', + }, + }, + { + plugin: simplePlugin, + options: { + name: 'simple', + }, + }, + ]); + await server.start(); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + + await tracer.withSpan(rootSpan, async () => { + const res1 = await server.inject({ + method: 'GET', + url: '/test', + }); + assert.strictEqual(res1.statusCode, 200); + const res2 = await server.inject({ + method: 'GET', + url: '/hello', + }); + assert.strictEqual(res2.statusCode, 200); + + rootSpan.end(); + + assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 3); + + const firstHandlerSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'multipleVersionPlugin: route - /test'); + assert.notStrictEqual(firstHandlerSpan, undefined); + assert.strictEqual( + firstHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], + HapiLayerType.PLUGIN + ); + assert.strictEqual( + firstHandlerSpan?.attributes[AttributeNames.PLUGIN_NAME], + 'multipleVersionPlugin' + ); + const secondHandlerSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'simplePlugin: route - /hello'); + assert.notStrictEqual(secondHandlerSpan, undefined); + assert.strictEqual( + secondHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], + HapiLayerType.PLUGIN + ); + assert.strictEqual( + secondHandlerSpan?.attributes[AttributeNames.PLUGIN_NAME], + 'simplePlugin' + ); + + const exportedRootSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'rootSpan'); + assert.notStrictEqual(exportedRootSpan, undefined); + }); + }); + + it('should instrument multiple versions of the same plugin just once', async () => { + const rootSpan = tracer.startSpan('rootSpan'); + + await server.register([ + { + plugin: multipleVersionPlugin, + options: { + name: 'world', + path: 'test', + }, + }, + { + plugin: multipleVersionPlugin, + options: { + name: 'world', + path: 'test2', + }, + }, + ]); + await server.start(); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + + await tracer.withSpan(rootSpan, async () => { + const res1 = await server.inject({ + method: 'GET', + url: '/test', + }); + assert.strictEqual(res1.statusCode, 200); + const res2 = await server.inject({ + method: 'GET', + url: '/test2', + }); + assert.strictEqual(res2.statusCode, 200); + + rootSpan.end(); + + assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 3); + + const firstHandlerSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'multipleVersionPlugin: route - /test'); + assert.notStrictEqual(firstHandlerSpan, undefined); + assert.strictEqual( + firstHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], + HapiLayerType.PLUGIN + ); + assert.strictEqual( + firstHandlerSpan?.attributes[AttributeNames.PLUGIN_NAME], + 'multipleVersionPlugin' + ); + const secondHandlerSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'multipleVersionPlugin: route - /test2'); + assert.notStrictEqual(secondHandlerSpan, undefined); + assert.strictEqual( + secondHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], + HapiLayerType.PLUGIN + ); + assert.strictEqual( + secondHandlerSpan?.attributes[AttributeNames.PLUGIN_NAME], + 'multipleVersionPlugin' + ); + + const exportedRootSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'rootSpan'); + assert.notStrictEqual(exportedRootSpan, undefined); + }); + }); + + it('should instrument package-based plugins', async () => { + const rootSpan = tracer.startSpan('rootSpan'); + + await server.register({ + plugin: packagePlugin, + }); + await server.start(); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + + await tracer.withSpan(rootSpan, async () => { + const res = await server.inject({ + method: 'GET', + url: '/package', + }); + assert.strictEqual(res.statusCode, 200); + + rootSpan.end(); + assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); + + const requestHandlerSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'plugin-by-package: route - /package'); + assert.notStrictEqual(requestHandlerSpan, undefined); + assert.strictEqual( + requestHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], + HapiLayerType.PLUGIN + ); + assert.strictEqual( + requestHandlerSpan?.attributes[AttributeNames.PLUGIN_NAME], + 'plugin-by-package' + ); + + const exportedRootSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'rootSpan'); + assert.notStrictEqual(exportedRootSpan, undefined); + }); + }); + }); +}); diff --git a/plugins/node/opentelemetry-hapi-instrumentation/test/hapi-server-ext.test.ts b/plugins/node/opentelemetry-hapi-instrumentation/test/hapi-server-ext.test.ts new file mode 100644 index 0000000000..a984f13b08 --- /dev/null +++ b/plugins/node/opentelemetry-hapi-instrumentation/test/hapi-server-ext.test.ts @@ -0,0 +1,355 @@ +/* + * 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 } from '@opentelemetry/api'; +import { NoopLogger } from '@opentelemetry/core'; +import { NodeTracerProvider } from '@opentelemetry/node'; +import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks'; +import { + InMemorySpanExporter, + SimpleSpanProcessor, +} from '@opentelemetry/tracing'; +import * as assert from 'assert'; +import * as hapi from '@hapi/hapi'; +import { plugin } from '../src'; +import { AttributeNames, HapiLayerType } from '../src/types'; + +describe('Hapi Instrumentation - Server.Ext Tests', () => { + const logger = new NoopLogger(); + const provider = new NodeTracerProvider(); + const memoryExporter = new InMemorySpanExporter(); + const spanProcessor = new SimpleSpanProcessor(memoryExporter); + provider.addSpanProcessor(spanProcessor); + const tracer = provider.getTracer('default'); + let contextManager: AsyncHooksContextManager; + let server: hapi.Server; + + before(() => { + plugin.enable(hapi, provider, logger); + }); + + beforeEach(async () => { + contextManager = new AsyncHooksContextManager(); + context.setGlobalContextManager(contextManager.enable()); + server = hapi.server({ + port: 5000, + host: 'localhost', + }); + server.route({ method: 'GET', path: '/test', handler: () => 'okay' }); + }); + + afterEach(async () => { + await server.stop(); + + memoryExporter.reset(); + context.disable(); + }); + + after(() => { + plugin.disable(); + }); + + describe('Instrumenting Hapi Server Extension methods', () => { + it('instruments direct Hapi.Lifecycle.Method extensions', async () => { + const rootSpan = tracer.startSpan('rootSpan'); + + server.ext('onRequest', async (request, h, err) => { + return h.continue; + }); + await server.start(); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + + await tracer.withSpan(rootSpan, async () => { + const res = await server.inject({ + method: 'GET', + url: '/test', + }); + assert.strictEqual(res.statusCode, 200); + + rootSpan.end(); + assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 3); + const extHandlerSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'ext - onRequest'); + assert.notStrictEqual(extHandlerSpan, undefined); + assert.strictEqual( + extHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], + HapiLayerType.EXT + ); + assert.strictEqual( + extHandlerSpan?.attributes[AttributeNames.EXT_TYPE], + 'onRequest' + ); + + const exportedRootSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'rootSpan'); + assert.notStrictEqual(exportedRootSpan, undefined); + }); + }); + + it('instruments single ServerExtEventsRequestObject', async () => { + const rootSpan = tracer.startSpan('rootSpan'); + const extension: hapi.ServerExtEventsRequestObject = { + type: 'onRequest', + method: async (request, h, err) => { + return h.continue; + }, + }; + server.ext(extension); + await server.start(); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + + await tracer.withSpan(rootSpan, async () => { + const res = await server.inject({ + method: 'GET', + url: '/test', + }); + assert.strictEqual(res.statusCode, 200); + + rootSpan.end(); + assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 3); + const extHandlerSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'ext - onRequest'); + assert.notStrictEqual(extHandlerSpan, undefined); + assert.strictEqual( + extHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], + HapiLayerType.EXT + ); + assert.strictEqual( + extHandlerSpan?.attributes[AttributeNames.EXT_TYPE], + 'onRequest' + ); + + const exportedRootSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'rootSpan'); + assert.notStrictEqual(exportedRootSpan, undefined); + }); + }); + + it('instruments single ServerExtEventsRequestObject with multiple handlers', async () => { + const rootSpan = tracer.startSpan('rootSpan'); + const firstHandler: hapi.Lifecycle.Method = async (request, h, err) => { + return h.continue; + }; + const secondHandler: hapi.Lifecycle.Method = async (request, h, err) => { + return h.continue; + }; + + const extension: hapi.ServerExtEventsRequestObject = { + type: 'onRequest', + method: [firstHandler, secondHandler], + }; + server.ext(extension); + await server.start(); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + + await tracer.withSpan(rootSpan, async () => { + const res = await server.inject({ + method: 'GET', + url: '/test', + }); + assert.strictEqual(res.statusCode, 200); + + rootSpan.end(); + assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 4); + + const extHandlerSpans = memoryExporter + .getFinishedSpans() + .filter(span => span.name === 'ext - onRequest'); + assert.notStrictEqual(extHandlerSpans, undefined); + assert.strictEqual(extHandlerSpans.length, 2); + + assert.strictEqual( + extHandlerSpans[0]?.attributes[AttributeNames.HAPI_TYPE], + HapiLayerType.EXT + ); + assert.strictEqual( + extHandlerSpans[0]?.attributes[AttributeNames.EXT_TYPE], + 'onRequest' + ); + assert.strictEqual( + extHandlerSpans[1]?.attributes[AttributeNames.HAPI_TYPE], + HapiLayerType.EXT + ); + assert.strictEqual( + extHandlerSpans[1]?.attributes[AttributeNames.EXT_TYPE], + 'onRequest' + ); + + const exportedRootSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'rootSpan'); + assert.notStrictEqual(exportedRootSpan, undefined); + }); + }); + + it('instruments array of ServerExtEventsRequestObject', async () => { + const rootSpan = tracer.startSpan('rootSpan'); + const extensions: hapi.ServerExtEventsRequestObject[] = [ + { + type: 'onRequest', + method: async (request, h, err) => { + return h.continue; + }, + }, + { + type: 'onPostAuth', + method: async (request, h, err) => { + return h.continue; + }, + }, + ]; + server.ext(extensions); + await server.start(); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + + await tracer.withSpan(rootSpan, async () => { + const res = await server.inject({ + method: 'GET', + url: '/test', + }); + assert.strictEqual(res.statusCode, 200); + + rootSpan.end(); + assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 4); + const firstExtHandlerSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'ext - onRequest'); + assert.notStrictEqual(firstExtHandlerSpan, undefined); + assert.strictEqual( + firstExtHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], + HapiLayerType.EXT + ); + assert.strictEqual( + firstExtHandlerSpan?.attributes[AttributeNames.EXT_TYPE], + 'onRequest' + ); + + const secondExtHandlerSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'ext - onPostAuth'); + assert.notStrictEqual(secondExtHandlerSpan, undefined); + assert.strictEqual( + secondExtHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], + HapiLayerType.EXT + ); + assert.strictEqual( + secondExtHandlerSpan?.attributes[AttributeNames.EXT_TYPE], + 'onPostAuth' + ); + + const exportedRootSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'rootSpan'); + assert.notStrictEqual(exportedRootSpan, undefined); + }); + }); + + it('instruments server extensions added within plugin', async () => { + const rootSpan = tracer.startSpan('rootSpan'); + + const simplePlugin = { + name: 'simplePlugin', + version: '1.0.0', + multiple: true, + register: async function (server: hapi.Server, options: any) { + server.ext('onRequest', async (request, h, err) => { + return h.continue; + }); + }, + }; + + await server.register({ + plugin: simplePlugin, + }); + + await server.start(); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + + await tracer.withSpan(rootSpan, async () => { + const res = await server.inject({ + method: 'GET', + url: '/test', + }); + assert.strictEqual(res.statusCode, 200); + + rootSpan.end(); + assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 3); + const extHandlerSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'simplePlugin: ext - onRequest'); + assert.notStrictEqual(extHandlerSpan, undefined); + assert.strictEqual( + extHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], + HapiLayerType.EXT + ); + assert.strictEqual( + extHandlerSpan?.attributes[AttributeNames.EXT_TYPE], + 'onRequest' + ); + + const exportedRootSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'rootSpan'); + assert.notStrictEqual(exportedRootSpan, undefined); + }); + }); + + it('does not instrument Hapi.ServerExtPointFunction handlers', async () => { + const rootSpan = tracer.startSpan('rootSpan'); + await tracer.withSpan(rootSpan, async () => { + server.ext('onPreStart', async (server: hapi.Server) => { + return; + }); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + + await server.start(); + + const res = await server.inject({ + method: 'GET', + url: '/test', + }); + assert.strictEqual(res.statusCode, 200); + + rootSpan.end(); + assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); + + const exportedRootSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'rootSpan'); + assert.notStrictEqual(exportedRootSpan, undefined); + }); + }); + + it('should not create span if there is no parent span', async () => { + server.ext('onRequest', async (request, h, err) => { + return h.continue; + }); + await server.start(); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + + const res = await server.inject({ + method: 'GET', + url: '/test', + }); + assert.strictEqual(res.statusCode, 200); + assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 0); + }); + }); +}); diff --git a/plugins/node/opentelemetry-hapi-instrumentation/test/hapi.test.ts b/plugins/node/opentelemetry-hapi-instrumentation/test/hapi.test.ts new file mode 100644 index 0000000000..5c1e5727ea --- /dev/null +++ b/plugins/node/opentelemetry-hapi-instrumentation/test/hapi.test.ts @@ -0,0 +1,305 @@ +/* + * 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 } from '@opentelemetry/api'; +import { NoopLogger } from '@opentelemetry/core'; +import { NodeTracerProvider } from '@opentelemetry/node'; +import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks'; +import { + InMemorySpanExporter, + SimpleSpanProcessor, +} from '@opentelemetry/tracing'; +import * as assert from 'assert'; +import * as hapi from '@hapi/hapi'; +import { plugin } from '../src'; +import { AttributeNames, HapiLayerType } from '../src/types'; + +describe('Hapi Instrumentation - Core Tests', () => { + const logger = new NoopLogger(); + const provider = new NodeTracerProvider(); + const memoryExporter = new InMemorySpanExporter(); + const spanProcessor = new SimpleSpanProcessor(memoryExporter); + provider.addSpanProcessor(spanProcessor); + const tracer = provider.getTracer('default'); + let contextManager: AsyncHooksContextManager; + let server: hapi.Server; + + before(() => { + plugin.enable(hapi, provider, logger); + }); + + beforeEach(async () => { + contextManager = new AsyncHooksContextManager(); + context.setGlobalContextManager(contextManager.enable()); + server = hapi.server({ + port: 3000, + host: 'localhost', + }); + }); + + afterEach(async () => { + await server.stop(); + memoryExporter.reset(); + context.disable(); + }); + + after(() => { + plugin.disable(); + }); + + describe('Instrumenting Hapi Routes', () => { + it('should create a child span for single routes', async () => { + const rootSpan = tracer.startSpan('rootSpan'); + server.route({ + method: 'GET', + path: '/', + handler: (request, h) => { + return 'Hello World!'; + }, + }); + + await server.start(); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + + await tracer.withSpan(rootSpan, async () => { + const res = await server.inject({ + method: 'GET', + url: '/', + }); + assert.strictEqual(res.statusCode, 200); + + rootSpan.end(); + assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); + + const requestHandlerSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'route - /'); + assert.notStrictEqual(requestHandlerSpan, undefined); + assert.strictEqual( + requestHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], + HapiLayerType.ROUTER + ); + + const exportedRootSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'rootSpan'); + assert.notStrictEqual(exportedRootSpan, undefined); + }); + }); + + it('should instrument the Hapi.Server (note: uppercase) method', async () => { + const rootSpan = tracer.startSpan('rootSpan'); + server = new hapi.Server({ + port: 3000, + host: 'localhost', + }); + + server.route({ + method: 'GET', + path: '/', + handler: (request, h) => { + return 'Hello World!'; + }, + }); + + await server.start(); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + + await tracer.withSpan(rootSpan, async () => { + const res = await server.inject({ + method: 'GET', + url: '/', + }); + assert.strictEqual(res.statusCode, 200); + + rootSpan.end(); + assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); + + const requestHandlerSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'route - /'); + assert.notStrictEqual(requestHandlerSpan, undefined); + assert.strictEqual( + requestHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], + HapiLayerType.ROUTER + ); + + const exportedRootSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'rootSpan'); + assert.notStrictEqual(exportedRootSpan, undefined); + }); + }); + + it('should create child spans for multiple routes', async () => { + const rootSpan = tracer.startSpan('rootSpan'); + server.route([ + { + method: 'GET', + path: '/first', + handler: (request, h) => { + return 'First!'; + }, + }, + { + method: 'GET', + path: '/second', + handler: (request, h) => { + return 'Second!'; + }, + }, + ]); + + await server.start(); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + + await tracer.withSpan(rootSpan, async () => { + const resFirst = await server.inject({ + method: 'GET', + url: '/first', + }); + const resSecond = await server.inject({ + method: 'GET', + url: '/second', + }); + + assert.strictEqual(resFirst.statusCode, 200); + assert.strictEqual(resSecond.statusCode, 200); + + rootSpan.end(); + assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 3); + + const firstHandlerSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'route - /first'); + assert.notStrictEqual(firstHandlerSpan, undefined); + assert.strictEqual( + firstHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], + HapiLayerType.ROUTER + ); + + const secondHandlerSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'route - /second'); + assert.notStrictEqual(secondHandlerSpan, undefined); + assert.strictEqual( + secondHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], + HapiLayerType.ROUTER + ); + + const exportedRootSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'rootSpan'); + assert.notStrictEqual(exportedRootSpan, undefined); + }); + }); + + it('should access route parameters and add to span', async () => { + const rootSpan = tracer.startSpan('rootSpan'); + server.route({ + method: 'GET', + path: '/users/{userId}', + handler: (request, h) => { + return `Hello ${request.params.userId}`; + }, + }); + + await server.start(); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + + await tracer.withSpan(rootSpan, async () => { + const res = await server.inject({ + method: 'GET', + url: '/users/1', + }); + assert.strictEqual(res.statusCode, 200); + + rootSpan.end(); + assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 2); + + const requestHandlerSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'route - /users/{userId}'); + assert.notStrictEqual(requestHandlerSpan, undefined); + assert.strictEqual( + requestHandlerSpan?.attributes[AttributeNames.HAPI_TYPE], + HapiLayerType.ROUTER + ); + + const exportedRootSpan = memoryExporter + .getFinishedSpans() + .find(span => span.name === 'rootSpan'); + assert.notStrictEqual(exportedRootSpan, undefined); + }); + }); + + it('should not create span if there is no parent span', async () => { + server.route({ + method: 'GET', + path: '/', + handler: (request, h) => { + return 'Hello World!'; + }, + }); + await server.start(); + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + + const res = await server.inject({ + method: 'GET', + url: '/', + }); + assert.strictEqual(res.statusCode, 200); + assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 0); + }); + }); + + describe('Disabling Hapi instrumentation', () => { + it('should not create new spans', async () => { + plugin.disable(); + + // must reininitialize here for effects of disabling plugin to become apparent + server = hapi.server({ + port: 3000, + host: 'localhost', + }); + + const rootSpan = tracer.startSpan('rootSpan'); + + server.route({ + method: 'GET', + path: '/', + handler: (request, h) => { + return 'Hello World!'; + }, + }); + + await server.start(); + + assert.strictEqual(memoryExporter.getFinishedSpans().length, 0); + + await tracer.withSpan(rootSpan, async () => { + const res = await server.inject({ + method: 'GET', + url: '/', + }); + assert.strictEqual(res.statusCode, 200); + rootSpan.end(); + assert.deepStrictEqual(memoryExporter.getFinishedSpans().length, 1); + assert.notStrictEqual(memoryExporter.getFinishedSpans()[0], undefined); + }); + }); + }); +}); diff --git a/plugins/node/opentelemetry-hapi-instrumentation/test/testPackage.json b/plugins/node/opentelemetry-hapi-instrumentation/test/testPackage.json new file mode 100644 index 0000000000..f348a1a971 --- /dev/null +++ b/plugins/node/opentelemetry-hapi-instrumentation/test/testPackage.json @@ -0,0 +1,4 @@ +{ + "name": "plugin-by-package", + "version": "0.0.0" +} \ No newline at end of file diff --git a/plugins/node/opentelemetry-hapi-instrumentation/tsconfig.json b/plugins/node/opentelemetry-hapi-instrumentation/tsconfig.json new file mode 100644 index 0000000000..ec22e03b9e --- /dev/null +++ b/plugins/node/opentelemetry-hapi-instrumentation/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../../tsconfig.base", + "compilerOptions": { + "rootDir": ".", + "outDir": "build" + }, + "include": [ + "src/**/*.ts", + "test/**/*.ts" + ] + }