From a6edb842d851fa888091f7242d50c9ba23410974 Mon Sep 17 00:00:00 2001 From: Anuraag Agrawal Date: Thu, 15 Apr 2021 15:32:45 +0900 Subject: [PATCH 1/7] feat: add x-ray id generator --- .../.eslintignore | 1 + .../.eslintrc.js | 9 + .../.npmignore | 4 + .../LICENSE | 201 ++++++++++++++++++ .../README.md | 67 ++++++ .../karma.conf.js | 24 +++ .../package.json | 68 ++++++ .../src/index.ts | 16 ++ .../platform/browser/AWSXRayIdGenerator.ts | 62 ++++++ .../src/platform/browser/index.ts | 17 ++ .../src/platform/index.ts | 16 ++ .../src/platform/node/AWSXRayIdGenerator.ts | 67 ++++++ .../src/platform/node/index.ts | 17 ++ .../src/version.ts | 18 ++ .../test/platform/AWSXrayIdGenerator.test.ts | 93 ++++++++ .../tsconfig.json | 11 + 16 files changed, 691 insertions(+) create mode 100644 packages/opentelemetry-id-generator-aws-xray/.eslintignore create mode 100644 packages/opentelemetry-id-generator-aws-xray/.eslintrc.js create mode 100644 packages/opentelemetry-id-generator-aws-xray/.npmignore create mode 100644 packages/opentelemetry-id-generator-aws-xray/LICENSE create mode 100644 packages/opentelemetry-id-generator-aws-xray/README.md create mode 100644 packages/opentelemetry-id-generator-aws-xray/karma.conf.js create mode 100644 packages/opentelemetry-id-generator-aws-xray/package.json create mode 100644 packages/opentelemetry-id-generator-aws-xray/src/index.ts create mode 100644 packages/opentelemetry-id-generator-aws-xray/src/platform/browser/AWSXRayIdGenerator.ts create mode 100644 packages/opentelemetry-id-generator-aws-xray/src/platform/browser/index.ts create mode 100644 packages/opentelemetry-id-generator-aws-xray/src/platform/index.ts create mode 100644 packages/opentelemetry-id-generator-aws-xray/src/platform/node/AWSXRayIdGenerator.ts create mode 100644 packages/opentelemetry-id-generator-aws-xray/src/platform/node/index.ts create mode 100644 packages/opentelemetry-id-generator-aws-xray/src/version.ts create mode 100644 packages/opentelemetry-id-generator-aws-xray/test/platform/AWSXrayIdGenerator.test.ts create mode 100644 packages/opentelemetry-id-generator-aws-xray/tsconfig.json diff --git a/packages/opentelemetry-id-generator-aws-xray/.eslintignore b/packages/opentelemetry-id-generator-aws-xray/.eslintignore new file mode 100644 index 0000000000..378eac25d3 --- /dev/null +++ b/packages/opentelemetry-id-generator-aws-xray/.eslintignore @@ -0,0 +1 @@ +build diff --git a/packages/opentelemetry-id-generator-aws-xray/.eslintrc.js b/packages/opentelemetry-id-generator-aws-xray/.eslintrc.js new file mode 100644 index 0000000000..9dfe62f9b8 --- /dev/null +++ b/packages/opentelemetry-id-generator-aws-xray/.eslintrc.js @@ -0,0 +1,9 @@ +module.exports = { + "env": { + "mocha": true, + "commonjs": true, + "node": true, + "browser": true + }, + ...require('../../eslint.config.js') +} diff --git a/packages/opentelemetry-id-generator-aws-xray/.npmignore b/packages/opentelemetry-id-generator-aws-xray/.npmignore new file mode 100644 index 0000000000..9505ba9450 --- /dev/null +++ b/packages/opentelemetry-id-generator-aws-xray/.npmignore @@ -0,0 +1,4 @@ +/bin +/coverage +/doc +/test diff --git a/packages/opentelemetry-id-generator-aws-xray/LICENSE b/packages/opentelemetry-id-generator-aws-xray/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/packages/opentelemetry-id-generator-aws-xray/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/packages/opentelemetry-id-generator-aws-xray/README.md b/packages/opentelemetry-id-generator-aws-xray/README.md new file mode 100644 index 0000000000..7e54653ea2 --- /dev/null +++ b/packages/opentelemetry-id-generator-aws-xray/README.md @@ -0,0 +1,67 @@ +# AWS OpenTelemetry X-Ray IdGenerator + +[![NPM Published Version][npm-img]][npm-url] +[![dependencies][dependencies-image]][dependencies-url] +[![devDependencies][devDependencies-image]][devDependencies-url] +[![Apache License][license-image]][license-image] + +The OpenTelemetry IdGenerator for AWS X-Ray generates trace IDs with its first four bytes set to the start time of the +trace followed by a unique identifier consisting of 12 bytes of randomly generated numbers. OpenTelemetry offers an +extension point which allows the usage of this custom IdGenerator as opposed to the out-of-the-box random IdGenerator, +enabling compatibility with AWS X-Ray. + +### Installation + +` +npm install --save @opentelemetry/id-generator-aws-xray +` + +### Usage + +In the [global tracer configuration file](https://github.com/open-telemetry/opentelemetry-js/blob/master/getting-started/README.md#initialize-a-global-tracer), +configure the following: + +```js +const { NodeTracerProvider } = require('@opentelemetry/node'); +const { AWSXRayIdGenerator } = require('@opentelemetry/id-generator-aws-xray'); +// ... + +module.exports = ("service_name_here") => { + const tracerConfig = { + idGenerator: new AWSXRayIdGenerator(), + resources: resources + }; + const tracerProvider = new NodeTracerProvider(tracerConfig); + // ...} +``` + +### Trace ID Details + +Example trace ID format: 58406520a006649127e371903a2de979 + +A trace ID consists of two parts; the timestamp and the unique identifier. + +#### Time Stamp + +* the first 8 hexadecimal digits represent the time of the original request in Unix epoch time +* for example, 10:00AM December 1st, 2016 PST in epoch time is 1480615200 seconds, or 58406520 in hexadecimal digits. + +#### Unique Identifier + +* the last 24 hexadecimal digits is an random identifier for the trace + +## 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=packages%2Fopentelemetry-id-generator-aws-xray +[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=packages%2Fopentelemetry-id-generator-aws-xray +[devDependencies-image]: https://status.david-dm.org/gh/open-telemetry/opentelemetry-js-contrib.svg?path=packages%2Fopentelemetry-id-generator-aws-xray&type=dev +[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js-contrib?path=packages%2Fopentelemetry-id-generator-aws-xray&type=dev +[npm-url]: https://www.npmjs.com/package/@opentelemetry/id-generator-aws-xray +[npm-img]: https://badge.fury.io/js/%40opentelemetry%2Fid-generator-aws-xray.svg diff --git a/packages/opentelemetry-id-generator-aws-xray/karma.conf.js b/packages/opentelemetry-id-generator-aws-xray/karma.conf.js new file mode 100644 index 0000000000..edcd9f055f --- /dev/null +++ b/packages/opentelemetry-id-generator-aws-xray/karma.conf.js @@ -0,0 +1,24 @@ +/*! + * Copyright 2020, 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 + * + * 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. + */ + +const karmaWebpackConfig = require('../../karma.webpack'); +const karmaBaseConfig = require('../../karma.base'); + +module.exports = (config) => { + config.set(Object.assign({}, karmaBaseConfig, { + webpack: karmaWebpackConfig + })) +}; diff --git a/packages/opentelemetry-id-generator-aws-xray/package.json b/packages/opentelemetry-id-generator-aws-xray/package.json new file mode 100644 index 0000000000..dc22e54ca7 --- /dev/null +++ b/packages/opentelemetry-id-generator-aws-xray/package.json @@ -0,0 +1,68 @@ +{ + "name": "@opentelemetry/id-generator-aws-xray", + "version": "0.15.0", + "description": "AWS X-Ray ID generator for OpenTelemetry", + "main": "build/src/index.js", + "types": "build/src/index.d.ts", + "repository": "open-telemetry/opentelemetry-js-contrib", + "scripts": { + "precompile": "tsc --version", + "compile": "tsc --build", + "clean": "tsc --build --clean", + "test": "nyc ts-mocha -p tsconfig.json test/**/*.test.ts", + "test:browser": "nyc karma start --single-run", + "codecov": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../", + "lint": "eslint . --ext .ts", + "lint:fix": "eslint . --ext .ts --fix", + "version": "node ../../scripts/version-update.js", + "watch": "tsc --build --watch", + "prepare": "npm run compile" + }, + "keywords": [ + "opentelemetry", + "nodejs", + "browser", + "tracing", + "AWS", + "X-Ray" + ], + "author": "OpenTelemetry Authors", + "license": "Apache-2.0", + "engines": { + "node": ">=8.0.0" + }, + "files": [ + "build/src/**/*.js", + "build/src/**/*.js.map", + "build/src/**/*.d.ts", + "doc", + "LICENSE", + "README.md" + ], + "devDependencies": { + "@types/mocha": "8.2.0", + "@types/node": "14.14.12", + "@types/sinon": "9.0.4", + "@types/webpack-env": "1.16.0", + "codecov": "3.8.1", + "gts": "3.1.0", + "istanbul-instrumenter-loader": "3.0.1", + "karma": "5.2.3", + "karma-chrome-launcher": "3.1.0", + "karma-coverage-istanbul-reporter": "3.0.3", + "karma-mocha": "2.0.1", + "karma-spec-reporter": "0.0.32", + "karma-webpack": "5.0.0", + "mocha": "7.2.0", + "nyc": "15.1.0", + "rimraf": "3.0.2", + "sinon": "10.0.0", + "ts-loader": "8.0.12", + "ts-mocha": "8.0.0", + "typescript": "4.1.3", + "webpack": "4.46.0" + }, + "dependencies": { + "@opentelemetry/core": "^0.18.0" + } +} diff --git a/packages/opentelemetry-id-generator-aws-xray/src/index.ts b/packages/opentelemetry-id-generator-aws-xray/src/index.ts new file mode 100644 index 0000000000..e76b3a3593 --- /dev/null +++ b/packages/opentelemetry-id-generator-aws-xray/src/index.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 * from './platform'; diff --git a/packages/opentelemetry-id-generator-aws-xray/src/platform/browser/AWSXRayIdGenerator.ts b/packages/opentelemetry-id-generator-aws-xray/src/platform/browser/AWSXRayIdGenerator.ts new file mode 100644 index 0000000000..c20036fc28 --- /dev/null +++ b/packages/opentelemetry-id-generator-aws-xray/src/platform/browser/AWSXRayIdGenerator.ts @@ -0,0 +1,62 @@ +/* + * 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 { IdGenerator } from '@opentelemetry/core'; + +const SPAN_ID_BYTES = 8; +const TRACE_ID_BYTES = 16; +const EPOCH_BYTES = 4; + +/** IdGenerator that generates trace IDs conforming to AWS X-Ray format. + * https://docs.aws.amazon.com/xray/latest/devguide/xray-api-sendingdata.html#xray-api-traceids + */ +export class AWSXRayIdGenerator implements IdGenerator { + /** + * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex + * characters corresponding to 128 bits. The first 4 bytes correspond to the current + * time, in seconds, as per X-Ray trace ID format. + */ + generateTraceId = (): string => { + const epoch = Math.floor(Date.now() / 1000).toString(16); + const rand = generateRandomBytes(TRACE_ID_BYTES - EPOCH_BYTES); + return epoch + rand; + }; + + /** + * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex + * characters corresponding to 64 bits. + */ + generateSpanId = (): string => { + return generateRandomBytes(SPAN_ID_BYTES); + }; +} + +const SHARED_CHAR_CODES_ARRAY = Array(32); + +function generateRandomBytes(bytes: number) { + for (let i = 0; i < bytes * 2; i++) { + SHARED_CHAR_CODES_ARRAY[i] = Math.floor(Math.random() * 16) + 48; + // valid hex characters in the range 48-57 and 97-102 + if (SHARED_CHAR_CODES_ARRAY[i] >= 58) { + SHARED_CHAR_CODES_ARRAY[i] += 39; + } + } + + return String.fromCharCode.apply( + null, + SHARED_CHAR_CODES_ARRAY.slice(0, bytes * 2) + ); +} diff --git a/packages/opentelemetry-id-generator-aws-xray/src/platform/browser/index.ts b/packages/opentelemetry-id-generator-aws-xray/src/platform/browser/index.ts new file mode 100644 index 0000000000..2f90698a9e --- /dev/null +++ b/packages/opentelemetry-id-generator-aws-xray/src/platform/browser/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 './AWSXRayIdGenerator'; diff --git a/packages/opentelemetry-id-generator-aws-xray/src/platform/index.ts b/packages/opentelemetry-id-generator-aws-xray/src/platform/index.ts new file mode 100644 index 0000000000..a12506ffa9 --- /dev/null +++ b/packages/opentelemetry-id-generator-aws-xray/src/platform/index.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 * from './node'; diff --git a/packages/opentelemetry-id-generator-aws-xray/src/platform/node/AWSXRayIdGenerator.ts b/packages/opentelemetry-id-generator-aws-xray/src/platform/node/AWSXRayIdGenerator.ts new file mode 100644 index 0000000000..4dc6b15322 --- /dev/null +++ b/packages/opentelemetry-id-generator-aws-xray/src/platform/node/AWSXRayIdGenerator.ts @@ -0,0 +1,67 @@ +/* + * 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 { IdGenerator } from '@opentelemetry/core'; + +const SPAN_ID_BYTES = 8; +const TRACE_ID_BYTES = 16; +const EPOCH_BYTES = 4; + +/** + * IdGenerator that generates trace IDs conforming to AWS X-Ray format. + * https://docs.aws.amazon.com/xray/latest/devguide/xray-api-sendingdata.html#xray-api-traceids + */ +export class AWSXRayIdGenerator implements IdGenerator { + /** + * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex + * characters corresponding to 128 bits. The first 4 bytes correspond to the current + * time, in seconds, as per X-Ray trace ID format. + */ + generateTraceId = (): string => { + const epoch = Math.floor(Date.now() / 1000).toString(16); + const rand = generateRandomBytes(TRACE_ID_BYTES - EPOCH_BYTES); + return epoch + rand; + }; + + /** + * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex + * characters corresponding to 64 bits. + */ + generateSpanId = (): string => { + return generateRandomBytes(SPAN_ID_BYTES); + }; +} + +const SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES); + +function generateRandomBytes(bytes: number): string { + for (let i = 0; i < bytes / 4; i++) { + // unsigned right shift drops decimal part of the number + // it is required because if a number between 2**32 and 2**32 - 1 is generated, an out of range error is thrown by writeUInt32BE + SHARED_BUFFER.writeUInt32BE((Math.random() * 2 ** 32) >>> 0, i * 4); + } + + // If buffer is all 0, set the last byte to 1 to guarantee a valid w3c id is generated + for (let i = 0; i < bytes; i++) { + if (SHARED_BUFFER[i] > 0) { + break; + } else if (i === bytes - 1) { + SHARED_BUFFER[bytes - 1] = 1; + } + } + + return SHARED_BUFFER.toString('hex', 0, bytes); +} diff --git a/packages/opentelemetry-id-generator-aws-xray/src/platform/node/index.ts b/packages/opentelemetry-id-generator-aws-xray/src/platform/node/index.ts new file mode 100644 index 0000000000..2f90698a9e --- /dev/null +++ b/packages/opentelemetry-id-generator-aws-xray/src/platform/node/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 './AWSXRayIdGenerator'; diff --git a/packages/opentelemetry-id-generator-aws-xray/src/version.ts b/packages/opentelemetry-id-generator-aws-xray/src/version.ts new file mode 100644 index 0000000000..1e4172026f --- /dev/null +++ b/packages/opentelemetry-id-generator-aws-xray/src/version.ts @@ -0,0 +1,18 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// this is autogenerated file, see scripts/version-update.js +export const VERSION = '0.15.0'; diff --git a/packages/opentelemetry-id-generator-aws-xray/test/platform/AWSXrayIdGenerator.test.ts b/packages/opentelemetry-id-generator-aws-xray/test/platform/AWSXrayIdGenerator.test.ts new file mode 100644 index 0000000000..2c2a865c3f --- /dev/null +++ b/packages/opentelemetry-id-generator-aws-xray/test/platform/AWSXrayIdGenerator.test.ts @@ -0,0 +1,93 @@ +/* + * 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 assert from 'assert'; +import * as sinon from 'sinon'; +import { AWSXRayIdGenerator } from '../../src'; + +const idGenerator = new AWSXRayIdGenerator(); + +describe('AwsXRayTraceId', () => { + let traceId1: string, traceId2: string; + let prevTime: number, currTime: number, nextTime: number; + const inValidTraceId = '00000000000000000000000000000000'; + let sandbox: sinon.SinonSandbox; + + beforeEach(() => { + sandbox = sinon.createSandbox(); + prevTime = Math.floor(Date.now() / 1000); + traceId1 = idGenerator.generateTraceId(); + currTime = parseInt(traceId1.substring(0, 8), 16); + nextTime = Math.floor(Date.now() / 1000); + traceId2 = idGenerator.generateTraceId(); + }); + + afterEach(() => { + sandbox.restore(); + }); + + it('returns 32 character hex strings', () => { + assert.ok(traceId1.match(/[a-f0-9]{32}/)); + assert.ok(!traceId1.match(/^0+$/)); + }); + + it('returns different ids on each call', () => { + assert.notStrictEqual(traceId1, traceId2); + }); + + it('using current time to encode trace id', () => { + assert.ok(currTime >= prevTime); + assert.ok(currTime <= nextTime); + }); + + it('should not be all zero', () => { + sandbox.stub(Math, 'random').returns(0); + const traceIdTemp = idGenerator.generateTraceId(); + + assert.notStrictEqual(traceIdTemp, inValidTraceId); + }); +}); + +describe('AwsXRaySpanId', () => { + let spanId1: string, spanId2: string; + const inValidSpanId = '0000000000000000'; + let sandbox: sinon.SinonSandbox; + + beforeEach(() => { + sandbox = sinon.createSandbox(); + spanId1 = idGenerator.generateSpanId(); + spanId2 = idGenerator.generateSpanId(); + }); + + afterEach(() => { + sandbox.restore(); + }); + + it('returns 16 character hex strings', () => { + assert.ok(spanId1.match(/[a-f0-9]{16}/)); + assert.ok(!spanId1.match(/^0+$/)); + }); + + it('returns different ids on each call', () => { + assert.notStrictEqual(spanId1, spanId2); + }); + + it('should not be all zero', () => { + sandbox.stub(Math, 'random').returns(0); + const spanIdTemp = idGenerator.generateSpanId(); + + assert.notStrictEqual(spanIdTemp, inValidSpanId); + }); +}); diff --git a/packages/opentelemetry-id-generator-aws-xray/tsconfig.json b/packages/opentelemetry-id-generator-aws-xray/tsconfig.json new file mode 100644 index 0000000000..4078877ce6 --- /dev/null +++ b/packages/opentelemetry-id-generator-aws-xray/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../../tsconfig.base", + "compilerOptions": { + "rootDir": ".", + "outDir": "build" + }, + "include": [ + "src/**/*.ts", + "test/**/*.ts" + ] +} From c9c9b2333a7b214baa2894626d3cfaf4fb407f50 Mon Sep 17 00:00:00 2001 From: Anuraag Agrawal Date: Thu, 15 Apr 2021 16:00:00 +0900 Subject: [PATCH 2/7] fix: add webpack test config --- .../test/platform/index-webpack.ts | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 packages/opentelemetry-id-generator-aws-xray/test/platform/index-webpack.ts diff --git a/packages/opentelemetry-id-generator-aws-xray/test/platform/index-webpack.ts b/packages/opentelemetry-id-generator-aws-xray/test/platform/index-webpack.ts new file mode 100644 index 0000000000..061a48ccfa --- /dev/null +++ b/packages/opentelemetry-id-generator-aws-xray/test/platform/index-webpack.ts @@ -0,0 +1,20 @@ +/* + * Copyright The OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const testsContext = require.context('.', true, /test$/); +testsContext.keys().forEach(testsContext); + +const srcContext = require.context('.', true, /src$/); +srcContext.keys().forEach(srcContext); From e00d1f0b32af8ffec1b8161e928674b75b791f76 Mon Sep 17 00:00:00 2001 From: Anuraag Agrawal Date: Thu, 15 Apr 2021 16:18:41 +0900 Subject: [PATCH 3/7] fix: test folder structure --- .../test/{platform => }/AWSXrayIdGenerator.test.ts | 2 +- .../test/{platform => }/index-webpack.ts | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename packages/opentelemetry-id-generator-aws-xray/test/{platform => }/AWSXrayIdGenerator.test.ts (98%) rename packages/opentelemetry-id-generator-aws-xray/test/{platform => }/index-webpack.ts (100%) diff --git a/packages/opentelemetry-id-generator-aws-xray/test/platform/AWSXrayIdGenerator.test.ts b/packages/opentelemetry-id-generator-aws-xray/test/AWSXrayIdGenerator.test.ts similarity index 98% rename from packages/opentelemetry-id-generator-aws-xray/test/platform/AWSXrayIdGenerator.test.ts rename to packages/opentelemetry-id-generator-aws-xray/test/AWSXrayIdGenerator.test.ts index 2c2a865c3f..8c5a021400 100644 --- a/packages/opentelemetry-id-generator-aws-xray/test/platform/AWSXrayIdGenerator.test.ts +++ b/packages/opentelemetry-id-generator-aws-xray/test/AWSXrayIdGenerator.test.ts @@ -15,7 +15,7 @@ */ import * as assert from 'assert'; import * as sinon from 'sinon'; -import { AWSXRayIdGenerator } from '../../src'; +import { AWSXRayIdGenerator } from '../src'; const idGenerator = new AWSXRayIdGenerator(); diff --git a/packages/opentelemetry-id-generator-aws-xray/test/platform/index-webpack.ts b/packages/opentelemetry-id-generator-aws-xray/test/index-webpack.ts similarity index 100% rename from packages/opentelemetry-id-generator-aws-xray/test/platform/index-webpack.ts rename to packages/opentelemetry-id-generator-aws-xray/test/index-webpack.ts From 580261ce4cd492bccccf616da099332843c65384 Mon Sep 17 00:00:00 2001 From: Anuraag Agrawal Date: Thu, 15 Apr 2021 16:32:22 +0900 Subject: [PATCH 4/7] fix: structure? --- .../test/{ => browser}/index-webpack.ts | 9 ++++++--- .../test/{ => common}/AWSXrayIdGenerator.test.ts | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) rename packages/opentelemetry-id-generator-aws-xray/test/{ => browser}/index-webpack.ts (68%) rename packages/opentelemetry-id-generator-aws-xray/test/{ => common}/AWSXrayIdGenerator.test.ts (98%) diff --git a/packages/opentelemetry-id-generator-aws-xray/test/index-webpack.ts b/packages/opentelemetry-id-generator-aws-xray/test/browser/index-webpack.ts similarity index 68% rename from packages/opentelemetry-id-generator-aws-xray/test/index-webpack.ts rename to packages/opentelemetry-id-generator-aws-xray/test/browser/index-webpack.ts index 061a48ccfa..d49f67165c 100644 --- a/packages/opentelemetry-id-generator-aws-xray/test/index-webpack.ts +++ b/packages/opentelemetry-id-generator-aws-xray/test/browser/index-webpack.ts @@ -13,8 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const testsContext = require.context('.', true, /test$/); +const testsContext = require.context('../browser', true, /test$/); testsContext.keys().forEach(testsContext); -const srcContext = require.context('.', true, /src$/); -srcContext.keys().forEach(srcContext); +const testsContextCommon = require.context('../common', true, /test$/); +testsContextCommon.keys().forEach(testsContextCommon); + +// const srcContext = require.context('.', true, /src$/); +// srcContext.keys().forEach(srcContext); diff --git a/packages/opentelemetry-id-generator-aws-xray/test/AWSXrayIdGenerator.test.ts b/packages/opentelemetry-id-generator-aws-xray/test/common/AWSXrayIdGenerator.test.ts similarity index 98% rename from packages/opentelemetry-id-generator-aws-xray/test/AWSXrayIdGenerator.test.ts rename to packages/opentelemetry-id-generator-aws-xray/test/common/AWSXrayIdGenerator.test.ts index 8c5a021400..2c2a865c3f 100644 --- a/packages/opentelemetry-id-generator-aws-xray/test/AWSXrayIdGenerator.test.ts +++ b/packages/opentelemetry-id-generator-aws-xray/test/common/AWSXrayIdGenerator.test.ts @@ -15,7 +15,7 @@ */ import * as assert from 'assert'; import * as sinon from 'sinon'; -import { AWSXRayIdGenerator } from '../src'; +import { AWSXRayIdGenerator } from '../../src'; const idGenerator = new AWSXRayIdGenerator(); From 2de107b426feb9abbfcb744af588d1d23dcf80bf Mon Sep 17 00:00:00 2001 From: Anuraag Agrawal Date: Fri, 16 Apr 2021 15:10:36 +0900 Subject: [PATCH 5/7] chore: cleanups --- .../README.md | 18 +++++----- .../karma.conf.js | 10 +++--- .../package.json | 7 +++- .../src/internal/xray-id-generation.ts | 36 +++++++++++++++++++ .../platform/browser/AWSXRayIdGenerator.ts | 27 +++++++------- .../src/platform/node/AWSXRayIdGenerator.ts | 22 ++++++------ .../{common => }/AWSXrayIdGenerator.test.ts | 23 ++++++------ .../test/{browser => }/index-webpack.ts | 9 ++--- .../package.json | 2 +- 9 files changed, 96 insertions(+), 58 deletions(-) create mode 100644 packages/opentelemetry-id-generator-aws-xray/src/internal/xray-id-generation.ts rename packages/opentelemetry-id-generator-aws-xray/test/{common => }/AWSXrayIdGenerator.test.ts (80%) rename packages/opentelemetry-id-generator-aws-xray/test/{browser => }/index-webpack.ts (68%) diff --git a/packages/opentelemetry-id-generator-aws-xray/README.md b/packages/opentelemetry-id-generator-aws-xray/README.md index 7e54653ea2..f70288ba7a 100644 --- a/packages/opentelemetry-id-generator-aws-xray/README.md +++ b/packages/opentelemetry-id-generator-aws-xray/README.md @@ -24,15 +24,12 @@ configure the following: ```js const { NodeTracerProvider } = require('@opentelemetry/node'); const { AWSXRayIdGenerator } = require('@opentelemetry/id-generator-aws-xray'); -// ... - -module.exports = ("service_name_here") => { - const tracerConfig = { - idGenerator: new AWSXRayIdGenerator(), - resources: resources - }; - const tracerProvider = new NodeTracerProvider(tracerConfig); - // ...} + +const tracerConfig = { + idGenerator: new AWSXRayIdGenerator(), + resources: resources +}; +const tracerProvider = new NodeTracerProvider(tracerConfig); ``` ### Trace ID Details @@ -51,10 +48,13 @@ A trace ID consists of two parts; the timestamp and the unique identifier. * the last 24 hexadecimal digits is an random identifier for the trace ## 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 diff --git a/packages/opentelemetry-id-generator-aws-xray/karma.conf.js b/packages/opentelemetry-id-generator-aws-xray/karma.conf.js index edcd9f055f..feb5554b21 100644 --- a/packages/opentelemetry-id-generator-aws-xray/karma.conf.js +++ b/packages/opentelemetry-id-generator-aws-xray/karma.conf.js @@ -17,8 +17,10 @@ const karmaWebpackConfig = require('../../karma.webpack'); const karmaBaseConfig = require('../../karma.base'); -module.exports = (config) => { - config.set(Object.assign({}, karmaBaseConfig, { - webpack: karmaWebpackConfig - })) +module.exports = config => { + config.set( + Object.assign({}, karmaBaseConfig, { + webpack: karmaWebpackConfig, + }) + ); }; diff --git a/packages/opentelemetry-id-generator-aws-xray/package.json b/packages/opentelemetry-id-generator-aws-xray/package.json index dc22e54ca7..95c3bcbbb6 100644 --- a/packages/opentelemetry-id-generator-aws-xray/package.json +++ b/packages/opentelemetry-id-generator-aws-xray/package.json @@ -3,6 +3,10 @@ "version": "0.15.0", "description": "AWS X-Ray ID generator for OpenTelemetry", "main": "build/src/index.js", + "browser": { + "./src/platform/index.ts": "./src/platform/browser/index.ts", + "./build/src/platform/index.js": "./build/src/platform/browser/index.js" + }, "types": "build/src/index.d.ts", "repository": "open-telemetry/opentelemetry-js-contrib", "scripts": { @@ -29,7 +33,7 @@ "author": "OpenTelemetry Authors", "license": "Apache-2.0", "engines": { - "node": ">=8.0.0" + "node": ">=8.5.0" }, "files": [ "build/src/**/*.js", @@ -44,6 +48,7 @@ "@types/node": "14.14.12", "@types/sinon": "9.0.4", "@types/webpack-env": "1.16.0", + "@opentelemetry/api": "0.18.1", "codecov": "3.8.1", "gts": "3.1.0", "istanbul-instrumenter-loader": "3.0.1", diff --git a/packages/opentelemetry-id-generator-aws-xray/src/internal/xray-id-generation.ts b/packages/opentelemetry-id-generator-aws-xray/src/internal/xray-id-generation.ts new file mode 100644 index 0000000000..d19f96ea8b --- /dev/null +++ b/packages/opentelemetry-id-generator-aws-xray/src/internal/xray-id-generation.ts @@ -0,0 +1,36 @@ +/* + * 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 TRACE_ID_BYTES = 16; + +const SPAN_ID_BYTES = 8; +const EPOCH_BYTES = 4; + +type RandomBytesGenerator = (numBytes: number) => string; + +export function generateTraceId( + generateRandomBytes: RandomBytesGenerator +): string { + const epoch = Math.floor(Date.now() / 1000).toString(16); + const rand = generateRandomBytes(TRACE_ID_BYTES - EPOCH_BYTES); + return epoch + rand; +} + +export function generateSpanId( + generateRandomBytes: RandomBytesGenerator +): string { + return generateRandomBytes(SPAN_ID_BYTES); +} diff --git a/packages/opentelemetry-id-generator-aws-xray/src/platform/browser/AWSXRayIdGenerator.ts b/packages/opentelemetry-id-generator-aws-xray/src/platform/browser/AWSXRayIdGenerator.ts index c20036fc28..d3f20583c0 100644 --- a/packages/opentelemetry-id-generator-aws-xray/src/platform/browser/AWSXRayIdGenerator.ts +++ b/packages/opentelemetry-id-generator-aws-xray/src/platform/browser/AWSXRayIdGenerator.ts @@ -16,11 +16,14 @@ import { IdGenerator } from '@opentelemetry/core'; -const SPAN_ID_BYTES = 8; -const TRACE_ID_BYTES = 16; -const EPOCH_BYTES = 4; +import { + generateTraceId, + generateSpanId, + TRACE_ID_BYTES, +} from '../../internal/xray-id-generation'; -/** IdGenerator that generates trace IDs conforming to AWS X-Ray format. +/** + * IdGenerator that generates trace IDs conforming to AWS X-Ray format. * https://docs.aws.amazon.com/xray/latest/devguide/xray-api-sendingdata.html#xray-api-traceids */ export class AWSXRayIdGenerator implements IdGenerator { @@ -29,22 +32,20 @@ export class AWSXRayIdGenerator implements IdGenerator { * characters corresponding to 128 bits. The first 4 bytes correspond to the current * time, in seconds, as per X-Ray trace ID format. */ - generateTraceId = (): string => { - const epoch = Math.floor(Date.now() / 1000).toString(16); - const rand = generateRandomBytes(TRACE_ID_BYTES - EPOCH_BYTES); - return epoch + rand; - }; + generateTraceId(): string { + return generateTraceId(generateRandomBytes); + } /** * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex * characters corresponding to 64 bits. */ - generateSpanId = (): string => { - return generateRandomBytes(SPAN_ID_BYTES); - }; + generateSpanId(): string { + return generateSpanId(generateRandomBytes); + } } -const SHARED_CHAR_CODES_ARRAY = Array(32); +const SHARED_CHAR_CODES_ARRAY = Array(TRACE_ID_BYTES * 2); function generateRandomBytes(bytes: number) { for (let i = 0; i < bytes * 2; i++) { diff --git a/packages/opentelemetry-id-generator-aws-xray/src/platform/node/AWSXRayIdGenerator.ts b/packages/opentelemetry-id-generator-aws-xray/src/platform/node/AWSXRayIdGenerator.ts index 4dc6b15322..3f4da918a3 100644 --- a/packages/opentelemetry-id-generator-aws-xray/src/platform/node/AWSXRayIdGenerator.ts +++ b/packages/opentelemetry-id-generator-aws-xray/src/platform/node/AWSXRayIdGenerator.ts @@ -16,9 +16,11 @@ import { IdGenerator } from '@opentelemetry/core'; -const SPAN_ID_BYTES = 8; -const TRACE_ID_BYTES = 16; -const EPOCH_BYTES = 4; +import { + generateTraceId, + generateSpanId, + TRACE_ID_BYTES, +} from '../../internal/xray-id-generation'; /** * IdGenerator that generates trace IDs conforming to AWS X-Ray format. @@ -30,19 +32,17 @@ export class AWSXRayIdGenerator implements IdGenerator { * characters corresponding to 128 bits. The first 4 bytes correspond to the current * time, in seconds, as per X-Ray trace ID format. */ - generateTraceId = (): string => { - const epoch = Math.floor(Date.now() / 1000).toString(16); - const rand = generateRandomBytes(TRACE_ID_BYTES - EPOCH_BYTES); - return epoch + rand; - }; + generateTraceId(): string { + return generateTraceId(generateRandomBytes); + } /** * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex * characters corresponding to 64 bits. */ - generateSpanId = (): string => { - return generateRandomBytes(SPAN_ID_BYTES); - }; + generateSpanId(): string { + return generateSpanId(generateRandomBytes); + } } const SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES); diff --git a/packages/opentelemetry-id-generator-aws-xray/test/common/AWSXrayIdGenerator.test.ts b/packages/opentelemetry-id-generator-aws-xray/test/AWSXrayIdGenerator.test.ts similarity index 80% rename from packages/opentelemetry-id-generator-aws-xray/test/common/AWSXrayIdGenerator.test.ts rename to packages/opentelemetry-id-generator-aws-xray/test/AWSXrayIdGenerator.test.ts index 2c2a865c3f..f2398a69be 100644 --- a/packages/opentelemetry-id-generator-aws-xray/test/common/AWSXrayIdGenerator.test.ts +++ b/packages/opentelemetry-id-generator-aws-xray/test/AWSXrayIdGenerator.test.ts @@ -15,18 +15,18 @@ */ import * as assert from 'assert'; import * as sinon from 'sinon'; -import { AWSXRayIdGenerator } from '../../src'; + +import { INVALID_SPANID, INVALID_TRACEID } from '@opentelemetry/api'; + +import { AWSXRayIdGenerator } from '../src'; const idGenerator = new AWSXRayIdGenerator(); describe('AwsXRayTraceId', () => { let traceId1: string, traceId2: string; let prevTime: number, currTime: number, nextTime: number; - const inValidTraceId = '00000000000000000000000000000000'; - let sandbox: sinon.SinonSandbox; beforeEach(() => { - sandbox = sinon.createSandbox(); prevTime = Math.floor(Date.now() / 1000); traceId1 = idGenerator.generateTraceId(); currTime = parseInt(traceId1.substring(0, 8), 16); @@ -35,7 +35,7 @@ describe('AwsXRayTraceId', () => { }); afterEach(() => { - sandbox.restore(); + sinon.restore(); }); it('returns 32 character hex strings', () => { @@ -53,26 +53,23 @@ describe('AwsXRayTraceId', () => { }); it('should not be all zero', () => { - sandbox.stub(Math, 'random').returns(0); + sinon.stub(Math, 'random').returns(0); const traceIdTemp = idGenerator.generateTraceId(); - assert.notStrictEqual(traceIdTemp, inValidTraceId); + assert.notStrictEqual(traceIdTemp, INVALID_TRACEID); }); }); describe('AwsXRaySpanId', () => { let spanId1: string, spanId2: string; - const inValidSpanId = '0000000000000000'; - let sandbox: sinon.SinonSandbox; beforeEach(() => { - sandbox = sinon.createSandbox(); spanId1 = idGenerator.generateSpanId(); spanId2 = idGenerator.generateSpanId(); }); afterEach(() => { - sandbox.restore(); + sinon.restore(); }); it('returns 16 character hex strings', () => { @@ -85,9 +82,9 @@ describe('AwsXRaySpanId', () => { }); it('should not be all zero', () => { - sandbox.stub(Math, 'random').returns(0); + sinon.stub(Math, 'random').returns(0); const spanIdTemp = idGenerator.generateSpanId(); - assert.notStrictEqual(spanIdTemp, inValidSpanId); + assert.notStrictEqual(spanIdTemp, INVALID_SPANID); }); }); diff --git a/packages/opentelemetry-id-generator-aws-xray/test/browser/index-webpack.ts b/packages/opentelemetry-id-generator-aws-xray/test/index-webpack.ts similarity index 68% rename from packages/opentelemetry-id-generator-aws-xray/test/browser/index-webpack.ts rename to packages/opentelemetry-id-generator-aws-xray/test/index-webpack.ts index d49f67165c..061a48ccfa 100644 --- a/packages/opentelemetry-id-generator-aws-xray/test/browser/index-webpack.ts +++ b/packages/opentelemetry-id-generator-aws-xray/test/index-webpack.ts @@ -13,11 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -const testsContext = require.context('../browser', true, /test$/); +const testsContext = require.context('.', true, /test$/); testsContext.keys().forEach(testsContext); -const testsContextCommon = require.context('../common', true, /test$/); -testsContextCommon.keys().forEach(testsContextCommon); - -// const srcContext = require.context('.', true, /src$/); -// srcContext.keys().forEach(srcContext); +const srcContext = require.context('.', true, /src$/); +srcContext.keys().forEach(srcContext); diff --git a/propagators/opentelemetry-propagator-ot-trace/package.json b/propagators/opentelemetry-propagator-ot-trace/package.json index 278c60351b..806d36ddf7 100644 --- a/propagators/opentelemetry-propagator-ot-trace/package.json +++ b/propagators/opentelemetry-propagator-ot-trace/package.json @@ -30,7 +30,7 @@ "author": "OpenTelemetry Authors", "license": "Apache-2.0", "engines": { - "node": ">=8.0.0" + "node": ">=8.5.0" }, "files": [ "build/src/**/*.js", From a8f377e3ffab5b7dad646705b07c0924d9fb60fc Mon Sep 17 00:00:00 2001 From: Anuraag Agrawal Date: Fri, 16 Apr 2021 15:36:45 +0900 Subject: [PATCH 6/7] fix: guarantee valid span ID for browser too --- .../opentelemetry-id-generator-aws-xray/package.json | 2 +- .../src/internal/xray-id-generation.ts | 12 +++++++++++- .../src/platform/node/AWSXRayIdGenerator.ts | 9 --------- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/packages/opentelemetry-id-generator-aws-xray/package.json b/packages/opentelemetry-id-generator-aws-xray/package.json index 95c3bcbbb6..c5c3c47903 100644 --- a/packages/opentelemetry-id-generator-aws-xray/package.json +++ b/packages/opentelemetry-id-generator-aws-xray/package.json @@ -48,7 +48,6 @@ "@types/node": "14.14.12", "@types/sinon": "9.0.4", "@types/webpack-env": "1.16.0", - "@opentelemetry/api": "0.18.1", "codecov": "3.8.1", "gts": "3.1.0", "istanbul-instrumenter-loader": "3.0.1", @@ -68,6 +67,7 @@ "webpack": "4.46.0" }, "dependencies": { + "@opentelemetry/api": "^0.18.0", "@opentelemetry/core": "^0.18.0" } } diff --git a/packages/opentelemetry-id-generator-aws-xray/src/internal/xray-id-generation.ts b/packages/opentelemetry-id-generator-aws-xray/src/internal/xray-id-generation.ts index d19f96ea8b..752917aaab 100644 --- a/packages/opentelemetry-id-generator-aws-xray/src/internal/xray-id-generation.ts +++ b/packages/opentelemetry-id-generator-aws-xray/src/internal/xray-id-generation.ts @@ -14,11 +14,15 @@ * limitations under the License. */ +import { INVALID_SPANID } from '@opentelemetry/api'; + export const TRACE_ID_BYTES = 16; const SPAN_ID_BYTES = 8; const EPOCH_BYTES = 4; +const FALLBACK_SPANID = '0000000000000001'; + type RandomBytesGenerator = (numBytes: number) => string; export function generateTraceId( @@ -26,11 +30,17 @@ export function generateTraceId( ): string { const epoch = Math.floor(Date.now() / 1000).toString(16); const rand = generateRandomBytes(TRACE_ID_BYTES - EPOCH_BYTES); + // Starts with epoch so guaranteed to be valid. return epoch + rand; } export function generateSpanId( generateRandomBytes: RandomBytesGenerator ): string { - return generateRandomBytes(SPAN_ID_BYTES); + const spanId = generateRandomBytes(SPAN_ID_BYTES); + if (spanId === INVALID_SPANID) { + // Random was all zero. Very low chance, but in case it happens return a non-0 span ID to ensure it is valid. + return FALLBACK_SPANID; + } + return spanId; } diff --git a/packages/opentelemetry-id-generator-aws-xray/src/platform/node/AWSXRayIdGenerator.ts b/packages/opentelemetry-id-generator-aws-xray/src/platform/node/AWSXRayIdGenerator.ts index 3f4da918a3..3d72ebd81b 100644 --- a/packages/opentelemetry-id-generator-aws-xray/src/platform/node/AWSXRayIdGenerator.ts +++ b/packages/opentelemetry-id-generator-aws-xray/src/platform/node/AWSXRayIdGenerator.ts @@ -54,14 +54,5 @@ function generateRandomBytes(bytes: number): string { SHARED_BUFFER.writeUInt32BE((Math.random() * 2 ** 32) >>> 0, i * 4); } - // If buffer is all 0, set the last byte to 1 to guarantee a valid w3c id is generated - for (let i = 0; i < bytes; i++) { - if (SHARED_BUFFER[i] > 0) { - break; - } else if (i === bytes - 1) { - SHARED_BUFFER[bytes - 1] = 1; - } - } - return SHARED_BUFFER.toString('hex', 0, bytes); } From 1abf6ec337e7d1636d8dc461abda00ad5cba3f5d Mon Sep 17 00:00:00 2001 From: Anuraag Agrawal Date: Tue, 20 Apr 2021 11:41:07 +0900 Subject: [PATCH 7/7] Update packages/opentelemetry-id-generator-aws-xray/karma.conf.js Co-authored-by: Bartlomiej Obecny --- packages/opentelemetry-id-generator-aws-xray/karma.conf.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/opentelemetry-id-generator-aws-xray/karma.conf.js b/packages/opentelemetry-id-generator-aws-xray/karma.conf.js index feb5554b21..f1a1f3a7e8 100644 --- a/packages/opentelemetry-id-generator-aws-xray/karma.conf.js +++ b/packages/opentelemetry-id-generator-aws-xray/karma.conf.js @@ -1,5 +1,5 @@ /*! - * Copyright 2020, OpenTelemetry Authors + * 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.