From 3e3ad83cc565c4c5fe7314fec2d3f6d7bf6a8455 Mon Sep 17 00:00:00 2001 From: Rauno Viskus Date: Wed, 30 Jun 2021 13:11:56 +0300 Subject: [PATCH] feat: WIP version of nestjs-core instrumentation --- .../.eslintignore | 1 + .../.eslintrc.js | 7 + .../.npmignore | 4 + .../LICENSE | 201 ++++++++++++++++++ .../README.md | 72 +++++++ .../package.json | 74 +++++++ .../src/index.ts | 22 ++ .../src/instrumentation.ts | 92 ++++++++ .../src/types.ts | 21 ++ .../src/utils.ts | 54 +++++ .../src/version.ts | 18 ++ .../test/index.test.ts | 173 +++++++++++++++ .../test/setup.ts | 97 +++++++++ .../tsconfig.json | 11 + 14 files changed, 847 insertions(+) create mode 100644 plugins/node/opentelemetry-instrumentation-nestjs-core/.eslintignore create mode 100644 plugins/node/opentelemetry-instrumentation-nestjs-core/.eslintrc.js create mode 100644 plugins/node/opentelemetry-instrumentation-nestjs-core/.npmignore create mode 100644 plugins/node/opentelemetry-instrumentation-nestjs-core/LICENSE create mode 100644 plugins/node/opentelemetry-instrumentation-nestjs-core/README.md create mode 100644 plugins/node/opentelemetry-instrumentation-nestjs-core/package.json create mode 100644 plugins/node/opentelemetry-instrumentation-nestjs-core/src/index.ts create mode 100644 plugins/node/opentelemetry-instrumentation-nestjs-core/src/instrumentation.ts create mode 100644 plugins/node/opentelemetry-instrumentation-nestjs-core/src/types.ts create mode 100644 plugins/node/opentelemetry-instrumentation-nestjs-core/src/utils.ts create mode 100644 plugins/node/opentelemetry-instrumentation-nestjs-core/src/version.ts create mode 100644 plugins/node/opentelemetry-instrumentation-nestjs-core/test/index.test.ts create mode 100644 plugins/node/opentelemetry-instrumentation-nestjs-core/test/setup.ts create mode 100644 plugins/node/opentelemetry-instrumentation-nestjs-core/tsconfig.json diff --git a/plugins/node/opentelemetry-instrumentation-nestjs-core/.eslintignore b/plugins/node/opentelemetry-instrumentation-nestjs-core/.eslintignore new file mode 100644 index 0000000000..378eac25d3 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-nestjs-core/.eslintignore @@ -0,0 +1 @@ +build diff --git a/plugins/node/opentelemetry-instrumentation-nestjs-core/.eslintrc.js b/plugins/node/opentelemetry-instrumentation-nestjs-core/.eslintrc.js new file mode 100644 index 0000000000..f756f4488b --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-nestjs-core/.eslintrc.js @@ -0,0 +1,7 @@ +module.exports = { + "env": { + "mocha": true, + "node": true + }, + ...require('../../../eslint.config.js') +} diff --git a/plugins/node/opentelemetry-instrumentation-nestjs-core/.npmignore b/plugins/node/opentelemetry-instrumentation-nestjs-core/.npmignore new file mode 100644 index 0000000000..9505ba9450 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-nestjs-core/.npmignore @@ -0,0 +1,4 @@ +/bin +/coverage +/doc +/test diff --git a/plugins/node/opentelemetry-instrumentation-nestjs-core/LICENSE b/plugins/node/opentelemetry-instrumentation-nestjs-core/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-nestjs-core/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-nestjs-core/README.md b/plugins/node/opentelemetry-instrumentation-nestjs-core/README.md new file mode 100644 index 0000000000..2c388041d4 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-nestjs-core/README.md @@ -0,0 +1,72 @@ +# OpenTelemetry Memcached Instrumentation for Node.js + +[![NPM Published Version][npm-img]][npm-url] +[![dependencies][dependencies-image]][dependencies-url] +[![devDependencies][devDependencies-image]][devDependencies-url] +[![Apache License][license-image]][license-image] + +This module provides automatic instrumentation for [`memcached@>=2.2.0`][repo-url]. + +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-memcached +``` + +### Supported Versions + +- `>=2.2` + +## Usage + +OpenTelemetry Memcached Instrumentation allows the user to automatically collect trace data and export them to the backend of choice, to give observability to distributed systems when working with [memcached][pkg-url]. + +To load a specific instrumentation (**memcached** in this case), specify it in the registerInstrumentations' configuration + +```javascript +const { NodeTracerProvider } = require('@opentelemetry/node'); +const { MemcachedInstrumentation } = require('@opentelemetry/instrumentation-memcached'); +const { registerInstrumentations } = require('@opentelemetry/instrumentation'); + +const provider = new NodeTracerProvider(); +provider.register(); + +registerInstrumentations({ + instrumentations: [ + new MemcachedInstrumentation({ + collectCommand: false, + }), + ], +}); +``` + +### Configuration Options + +| Option | Type | Example | Description | +| ------- | ---- | ------- | ----------- | +| `collectCommand` | `boolean` | `false` | Include full command statement in the span - **leaks potentially sensitive information to your spans**. Defaults to `false`. | + +## Useful links + +- For more information on OpenTelemetry, visit: +- For more about OpenTelemetry JavaScript: +- For help or feedback on this project, join us in [GitHub Discussions][discussions-url] + +## License + +Apache 2.0 - See [LICENSE][license-url] for more information. + +[discussions-url]: https://github.com/open-telemetry/opentelemetry-js/discussions +[license-url]: https://github.com/open-telemetry/opentelemetry-js-contrib/blob/main/LICENSE +[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat +[dependencies-image]: https://status.david-dm.org/gh/open-telemetry/opentelemetry-js-contrib.svg?path=plugins%2Fnode%2Fopentelemetry-instrumentation-memcached +[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=plugins%2Fnode%2Fopentelemetry-instrumentation-memcached +[devDependencies-image]: https://status.david-dm.org/gh/open-telemetry/opentelemetry-js-contrib.svg?path=plugins%2Fnode%2Fopentelemetry-instrumentation-memcached&type=dev +[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=plugins%2Fnode%2Fopentelemetry-instrumentation-memcached&type=dev +[npm-url]: https://www.npmjs.com/package/@opentelemetry/instrumentation-memcached +[npm-img]: https://badge.fury.io/js/%40opentelemetry%2Finstrumentation-memcached.svg +[repo-url]: https://github.com/3rd-Eden/memcached +[pkg-url]: https://www.npmjs.com/package/memcached diff --git a/plugins/node/opentelemetry-instrumentation-nestjs-core/package.json b/plugins/node/opentelemetry-instrumentation-nestjs-core/package.json new file mode 100644 index 0000000000..c3141636c9 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-nestjs-core/package.json @@ -0,0 +1,74 @@ +{ + "name": "@opentelemetry/instrumentation-nestjs-core", + "version": "0.21.0", + "description": "OpenTelemetry NestJS automatic instrumentation package.", + "main": "build/src/index.js", + "types": "build/src/index.d.ts", + "repository": "open-telemetry/opentelemetry-js-contrib", + "scripts": { + "clean": "rimraf build/*", + "codecov": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../", + "compile": "npm run version:update && tsc -p .", + "lint": "eslint . --ext .ts", + "lint:fix": "eslint . --ext .ts --fix", + "precompile": "tsc --version", + "prepare": "npm run compile", + "tdd": "npm run test -- --watch-extensions ts --watch", + "test": "nyc ts-mocha -p tsconfig.json 'test/**/*.test.ts'", + "TODO: make sure all cmds are up to date": ":TODO", + "version:update": "node ../../../scripts/version-update.js" + }, + "keywords": [ + "opentelemetry", + "nestjs", + "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" + }, + "peerDependencies": { + "@opentelemetry/api": "^0.21.0" + }, + "devDependencies": { + "@nestjs/common": "^6.11.11", + "@nestjs/core": "^6.11.11", + "@nestjs/platform-express": "^7.6.18", + "@opentelemetry/api": "0.21.0", + "@opentelemetry/context-async-hooks": "0.21.0", + "@opentelemetry/node": "0.21.0", + "@opentelemetry/test-utils": "^0.21.0", + "@opentelemetry/tracing": "0.21.0", + "@types/mocha": "7.0.2", + "@types/node": "14.17.2", + "codecov": "3.8.2", + "cross-env": "7.0.3", + "gts": "3.1.0", + "mocha": "7.2.0", + "nyc": "15.1.0", + "reflect-metadata": "^0.1.13", + "rimraf": "3.0.2", + "rxjs": "^6.6.7", + "semver": "^7.3.5", + "ts-mocha": "8.0.0", + "typescript": "4.3.2" + }, + "dependencies": { + "@opentelemetry/instrumentation": "^0.21.0", + "@opentelemetry/semantic-conventions": "^0.21.0" + } +} diff --git a/plugins/node/opentelemetry-instrumentation-nestjs-core/src/index.ts b/plugins/node/opentelemetry-instrumentation-nestjs-core/src/index.ts new file mode 100644 index 0000000000..4c831c2980 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-nestjs-core/src/index.ts @@ -0,0 +1,22 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Instrumentation } from './instrumentation'; +export { InstrumentationConfig } from './types'; + +export * from './instrumentation'; +export default Instrumentation; +export { Instrumentation as MemcachedInstrumentation }; diff --git a/plugins/node/opentelemetry-instrumentation-nestjs-core/src/instrumentation.ts b/plugins/node/opentelemetry-instrumentation-nestjs-core/src/instrumentation.ts new file mode 100644 index 0000000000..bdb281dc73 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-nestjs-core/src/instrumentation.ts @@ -0,0 +1,92 @@ +/* + * 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 { + isWrapped, + InstrumentationBase, + InstrumentationNodeModuleDefinition, +} from '@opentelemetry/instrumentation'; +import type * as NestJS from '@nestjs/core'; +import { SemanticAttributes } from '@opentelemetry/semantic-conventions'; +// import * as utils from './utils'; +import { InstrumentationConfig } from './types'; +import { VERSION } from './version'; + +export class Instrumentation extends InstrumentationBase { + static readonly COMPONENT = '@nestjs/core'; + static readonly COMMON_ATTRIBUTES = { + [SemanticAttributes.DB_SYSTEM]: Instrumentation.COMPONENT, + }; + static readonly DEFAULT_CONFIG: InstrumentationConfig = { + collectCommand: false, + }; + + constructor(config: InstrumentationConfig = Instrumentation.DEFAULT_CONFIG) { + super( + '@opentelemetry/instrumentation-nestjs-core', + VERSION, + Object.assign({}, Instrumentation.DEFAULT_CONFIG, config) + ); + } + + setConfig(config: InstrumentationConfig = Instrumentation.DEFAULT_CONFIG) { + this._config = Object.assign({}, Instrumentation.DEFAULT_CONFIG, config); + } + + init() { + return [ + new InstrumentationNodeModuleDefinition( + '@nestjs/core', + ['>=2.2'], + (moduleExports, moduleVersion) => { + console.debug( + `Patching ${Instrumentation.COMPONENT}@${moduleVersion}` + ); + // this.ensureWrapped( + // moduleVersion, + // moduleExports.prototype, + // 'command', + // ); + return moduleExports; + }, + (moduleExports, moduleVersion) => { + console.debug( + `Unpatching ${Instrumentation.COMPONENT}@${moduleVersion}` + ); + if (moduleExports === undefined) return; + // `command` is documented API missing from the types + // this._unwrap(moduleExports.prototype, 'command' as keyof Memcached); + } + ), + ]; + } + + private ensureWrapped( + moduleVersion: string | undefined, + obj: any, + methodName: string, + wrapper: (original: any) => any + ) { + console.debug( + `Applying ${methodName} patch for ${Instrumentation.COMPONENT}@${moduleVersion}` + ); + if (isWrapped(obj[methodName])) { + this._unwrap(obj, methodName); + } + this._wrap(obj, methodName, wrapper); + } +} diff --git a/plugins/node/opentelemetry-instrumentation-nestjs-core/src/types.ts b/plugins/node/opentelemetry-instrumentation-nestjs-core/src/types.ts new file mode 100644 index 0000000000..b24a002eb5 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-nestjs-core/src/types.ts @@ -0,0 +1,21 @@ +/* + * 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 { InstrumentationConfig as BaseInstrumentationConfig } from '@opentelemetry/instrumentation'; + +export interface InstrumentationConfig extends BaseInstrumentationConfig { + collectCommand?: boolean; +} diff --git a/plugins/node/opentelemetry-instrumentation-nestjs-core/src/utils.ts b/plugins/node/opentelemetry-instrumentation-nestjs-core/src/utils.ts new file mode 100644 index 0000000000..aa49f6c357 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-nestjs-core/src/utils.ts @@ -0,0 +1,54 @@ +/* + * 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 Memcached from 'memcached'; +import { SemanticAttributes } from '@opentelemetry/semantic-conventions'; + +export const getPeerAttributes = ( + client: any /* Memcached, but the type definitions are lacking */, + server: string | undefined, + query: Memcached.CommandData +) => { + if (!server) { + if (client.servers.length === 1) { + server = client.servers[0]; + } else { + let redundancy = + client.redundancy && client.redundancy < client.servers.length; + const queryRedundancy = query.redundancyEnabled; + + if (redundancy && queryRedundancy) { + redundancy = client.HashRing.range( + query.key, + client.redundancy + 1, + true + ); + server = redundancy.shift(); + } else { + server = client.HashRing.get(query.key); + } + } + } + + if (typeof server === 'string') { + const [host, port] = server && server.split(':'); + return { + [SemanticAttributes.NET_PEER_NAME]: host, + [SemanticAttributes.NET_PEER_PORT]: port, + }; + } + return {}; +}; diff --git a/plugins/node/opentelemetry-instrumentation-nestjs-core/src/version.ts b/plugins/node/opentelemetry-instrumentation-nestjs-core/src/version.ts new file mode 100644 index 0000000000..fb47fc303b --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-nestjs-core/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.21.0'; diff --git a/plugins/node/opentelemetry-instrumentation-nestjs-core/test/index.test.ts b/plugins/node/opentelemetry-instrumentation-nestjs-core/test/index.test.ts new file mode 100644 index 0000000000..f8101b1d33 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-nestjs-core/test/index.test.ts @@ -0,0 +1,173 @@ +/* + * 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, SpanKind, SpanStatusCode, trace } from '@opentelemetry/api'; +import { NodeTracerProvider } from '@opentelemetry/node'; +import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks'; +import * as testUtils from '@opentelemetry/test-utils'; +import { + InMemorySpanExporter, + SimpleSpanProcessor, +} from '@opentelemetry/tracing'; +import * as assert from 'assert'; +import Instrumentation from '../src'; +import { SemanticAttributes } from '@opentelemetry/semantic-conventions'; +import { getRequester, setup } from './setup'; + +import * as http from 'http'; +import { AddressInfo } from 'net'; + +const instrumentation = new Instrumentation(); +const memoryExporter = new InMemorySpanExporter(); + +const CONFIG = { + host: process.env.OPENTELEMETRY_MEMCACHED_HOST || 'localhost', + port: process.env.OPENTELEMETRY_MEMCACHED_PORT || '11211', +}; + +const DEFAULT_ATTRIBUTES = { + [SemanticAttributes.DB_SYSTEM]: Instrumentation.COMPONENT, + [SemanticAttributes.NET_PEER_NAME]: CONFIG.host, + [SemanticAttributes.NET_PEER_PORT]: CONFIG.port, +}; + +describe('nestjs-core', () => { + const provider = new NodeTracerProvider(); + const tracer = provider.getTracer('default'); + provider.addSpanProcessor(new SimpleSpanProcessor(memoryExporter)); + instrumentation.setTracerProvider(provider); + let contextManager: AsyncHooksContextManager; + + beforeEach(() => { + contextManager = new AsyncHooksContextManager(); + context.setGlobalContextManager(contextManager.enable()); + instrumentation.setConfig({}); + instrumentation.enable(); + }); + + afterEach(() => { + memoryExporter.reset(); + context.disable(); + instrumentation.disable(); + }); + + before(function () { + }); + + after(() => {}); + + it('happy paths', async () => { + const app = await setup('6'); + const request = getRequester(app); + const path = '/users' // v<5 expected path is / + + console.log(await request('/users')); + + assert.ok(memoryExporter.getFinishedSpans().length > 0); + assertSpans(memoryExporter.getFinishedSpans(), [{}]); + }) +}); + + + // expect(spans[0]).to.have.property('service', 'test') + // expect(spans[0]).to.have.property('name', 'nest.factory.create') + // expect(spans[0].meta).to.have.property('component', 'nest') + // expect(spans[0].meta).to.have.property('nest.module', 'AppModule') + + // expect(spans[1]).to.have.property('service', 'test') + // expect(spans[1]).to.have.property('name', 'UsersController(getUsers)') + // expect(spans[1].meta).to.have.property('component', 'nest') + // expect(spans[1].meta).to.have.property('http.method', 'GET') + // expect(spans[1].meta).to.have.property('http.url', '/users') + // expect(spans[1].meta).to.have.property('nest.route.path', routePath) + // expect(spans[1].meta).to.have.property('nest.callback', 'getUsers') + + // expect(spans[2]).to.have.property('service', 'test') + // expect(spans[2]).to.have.property('name', 'nest.guard.canActivate.UsersController(getUsers)') + // expect(spans[2].meta).to.have.property('component', 'nest') + // expect(spans[2].meta).to.have.property('http.url', '/users') + // expect(spans[2].meta).to.have.property('nest.controller.instance', 'UsersController') + // expect(spans[2].meta).to.have.property('nest.route.path', routePath) + // expect(spans[2].meta).to.have.property('nest.callback', 'getUsers') + // expect(spans[2].parent_id.toString()).to.equal(spans[1].span_id.toString()) + + // expect(spans[3]).to.have.property('service', 'test') + // expect(spans[3]).to.have.property('name', 'nest.interceptor.intercept') + // expect(spans[3].meta).to.have.property('component', 'nest') + // expect(spans[3].meta).to.have.property('http.method', 'GET') + // expect(spans[3].meta).to.have.property('http.url', '/users') + // expect(spans[3].meta).to.have.property('nest.callback', 'getUsers') + // expect(spans[3].meta).to.have.property('nest.route.path', routePath) + // expect(spans[3].meta).to.have.property('nest.controller.instance', 'UsersController') + // expect(spans[3].parent_id.toString()).to.equal(spans[1].span_id.toString()) + + // expect(spans[4]).to.have.property('service', 'test') + // expect(spans[4]).to.have.property('name', 'getUsers') + // expect(spans[4].meta).to.not.have.property('error') + // expect(spans[4].meta).to.have.property('component', 'nest') + // expect(spans[4].meta).to.have.property('nest.callback', 'getUsers') + // expect(spans[4].parent_id.toString()).to.equal(spans[3].span_id.toString()) + + +const assertSpans = (actualSpans: any[], expectedSpans: any[]) => { + assert(Array.isArray(actualSpans), 'Expected `actualSpans` to be an array'); + assert( + Array.isArray(expectedSpans), + 'Expected `expectedSpans` to be an array' + ); + assert.strictEqual( + actualSpans.length, + expectedSpans.length, + 'Expected span count different from actual' + ); + actualSpans.forEach((span, idx) => { + const expected = expectedSpans[idx]; + if (expected === null) return; + try { + assert.notStrictEqual(span, undefined); + assert.notStrictEqual(expected, undefined); + assertMatch(span.name, new RegExp(expected.op)); + assertMatch(span.name, new RegExp(expected.key)); + assert.strictEqual(span.kind, SpanKind.CLIENT); + assert.strictEqual(span.attributes['db.statement'], expected.statement); + for (const attr in DEFAULT_ATTRIBUTES) { + assert.strictEqual(span.attributes[attr], DEFAULT_ATTRIBUTES[attr]); + } + assert.strictEqual(span.attributes['db.memcached.key'], expected.key); + assert.strictEqual( + typeof span.attributes['memcached.version'], + 'string', + 'memcached.version not specified' + ); + assert.deepEqual( + span.status, + expected.status || { code: SpanStatusCode.UNSET } + ); + assert.strictEqual(span.attributes['db.operation'], expected.op); + assert.strictEqual( + span.parentSpanId, + expected.parentSpan?.spanContext().spanId + ); + } catch (e) { + e.message = `At span[${idx}]: ${e.message}`; + throw e; + } + }); +}; + +const assertMatch = (str: string, regexp: RegExp, err?: any) => { + assert.ok(regexp.test(str), err ?? `Expected '${str} to match ${regexp}`); +}; diff --git a/plugins/node/opentelemetry-instrumentation-nestjs-core/test/setup.ts b/plugins/node/opentelemetry-instrumentation-nestjs-core/test/setup.ts new file mode 100644 index 0000000000..2ea0488691 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-nestjs-core/test/setup.ts @@ -0,0 +1,97 @@ +import * as http from 'http'; +import * as semver from 'semver'; +import { AddressInfo } from 'net'; + +// mimics the support for @decorators +const __decorate = function (decorators: any, target?: any, key?: any, desc?: any) { + if (typeof Reflect === 'object' && typeof Reflect.decorate === 'function') { + return Reflect.decorate(decorators, target, key, desc) + } + switch (arguments.length) { + case 2: return decorators.reduceRight(function (o, d) { return (d && d(o)) || o }, target) + case 3: return decorators.reduceRight(function (o, d) { return (d && d(target, key)) || o }, void 0) + case 4: return decorators.reduceRight(function (o, d) { return (d && d(target, key, o)) || o }, desc) + } +} + +export const setup = async (version) => { + let UsersController = class UsersController {} + let UsersModule = class UsersModule {} + let ErrorController = class ErrorController {} + let ErrorModule = class ErrorModule {} + let AppModule = class AppModule {} + + // const core = require(`../../versions/@nestjs/core@${version}`).get() + // const common = require(`../../versions/@nestjs/core@${version}/node_modules/@nestjs/common`) + const core = require(`@nestjs/core`); + const common = require(`@nestjs/common`); + + UsersController = __decorate([common.Controller('users')], UsersController) + UsersController.prototype.getUsers = function getUsers () { + return '\nHello, world!\n\n' + } + Object.defineProperty(UsersController.prototype, 'getUsers', + __decorate([common.Get()], UsersController.prototype, 'getUsers', + Object.getOwnPropertyDescriptor(UsersController.prototype, 'getUsers'))) + + UsersModule = __decorate([ + common.Module({ + controllers: [UsersController] + }) + ], UsersModule) + + ErrorController = __decorate([common.Controller('errors')], ErrorController) + ErrorController.prototype.getErrors = function getErrors () { + throw new Error('custom error') + } + Object.defineProperty(ErrorController.prototype, 'getErrors', + __decorate([common.Get()], ErrorController.prototype, 'getErrors', + Object.getOwnPropertyDescriptor(ErrorController.prototype, 'getErrors'))) + + ErrorModule = __decorate([ + common.Module({ + controllers: [ErrorController] + }) + ], ErrorModule) + + if (semver.intersects(version, '>=4.6.3')) { + AppModule = __decorate([ + common.Module({ + imports: [UsersModule, ErrorModule], + controllers: [UsersController, ErrorController] + })], AppModule) + } else { + AppModule = __decorate([ + common.Module({ + modules: [UsersModule, ErrorModule], + controllers: [UsersController, ErrorController] + })], AppModule) + } + + const app = await core.NestFactory.create(AppModule) + await app.listenAsync(0, 'localhost'); + + return app; +} + +export const getRequester = (app: any) => { + const port = (app.httpServer.address() as AddressInfo).port; + return (path: string) => { + return new Promise((resolve, reject) => { + return http.get(`http://localhost:${port}${path}`, resp => { + let data = ''; + resp.on('data', chunk => { + data += chunk; + }); + resp.on('end', () => { + resolve(data); + }); + resp.on('error', err => { + reject(err); + }); + }); + }); + }; +}; + +export default setup; diff --git a/plugins/node/opentelemetry-instrumentation-nestjs-core/tsconfig.json b/plugins/node/opentelemetry-instrumentation-nestjs-core/tsconfig.json new file mode 100644 index 0000000000..28be80d266 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-nestjs-core/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../../tsconfig.base", + "compilerOptions": { + "rootDir": ".", + "outDir": "build" + }, + "include": [ + "src/**/*.ts", + "test/**/*.ts" + ] +}