diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml deleted file mode 100644 index 7d1b7d63052..00000000000 --- a/.github/workflows/docs.yml +++ /dev/null @@ -1,49 +0,0 @@ -name: Deploy API Documentation - -on: - release: - types: [published] - -jobs: - build-and-deploy: - runs-on: ubuntu-latest - steps: - - name: Checkout 🛎️ - uses: actions/checkout@v2 - - - name: restore lock files - uses: actions/cache@master # must use unreleased master to cache multiple paths - id: cache - with: - # must be done before bootstrap to not include node_modules files in the cache paths - path: | - packages/*/package-lock.json - benchmark/*/package-lock.json - backwards-compatability/*/package-lock.json - metapackages/*/package-lock.json - packages/*/package-lock.json - integration-tests/*/package-lock.json - key: ${{ runner.os }}-docs-${{ hashFiles('**/package.json') }} - - - name: Install root dependencies - run: npm ci --ignore-scripts - - - name: Install and Build (cache miss) 🔧 - if: steps.cache.outputs.cache-hit != 'true' - run: npx lerna bootstrap --no-ci --scope @opentelemetry/api --include-dependencies - - - name: Install and Build (cache hit) 🔧 - if: steps.cache.outputs.cache-hit == 'true' - run: npx lerna bootstrap --scope @opentelemetry/api --include-dependencies - - - name: Build 🔧 - run: | - npx lerna run compile --scope @opentelemetry/api - npx lerna run docs - - - name: Deploy 🚀 - uses: JamesIves/github-pages-deploy-action@releases/v3 - with: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - BRANCH: gh-pages # The branch the action should deploy to. - FOLDER: packages/opentelemetry-api/docs/out # The folder the action should deploy. \ No newline at end of file diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 19584d1b4d3..d90ee914bf3 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -59,19 +59,3 @@ jobs: run: | npm run lint npm run lint:examples - - - name: Install API Dependencies (cache hit) - if: steps.cache.outputs.cache-hit == 'true' - run: npx lerna bootstrap --scope @opentelemetry/api --include-dependencies - - - name: Install API Dependencies (cache miss) - if: steps.cache.outputs.cache-hit != 'true' - run: npx lerna bootstrap --no-ci --scope @opentelemetry/api --include-dependencies - - - name: Build 🔧 - run: | - npx lerna run compile --scope @opentelemetry/api - npx lerna run docs - - - name: Test Docs - run: npm run docs-test diff --git a/README.md b/README.md index 9e8d561795a..3511731e8b0 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,8 @@ This is the JavaScript version of [OpenTelemetry](https://opentelemetry.io/), a | Core version | Contrib Version | |--------------|-------------------------| -| 0.16.x | 0.14.x not released yet | +| 0.17.x | 0.14.x not released yet | +| 0.16.x | ------ | | 0.15.x | 0.13.x | | 0.14.x | 0.12.x | | 0.13.x | ------ | @@ -203,7 +204,7 @@ OpenTelemetry can collect tracing data automatically using instrumentations. Ven - [@opentelemetry/instrumentation-grpc][otel-instrumentation-grpc] previous [@opentelemetry/plugin-grpc][otel-plugin-grpc] - [@opentelemetry/plugin-grpc-js][otel-plugin-grpc-js] -- [@opentelemetry/instrumentation-http][otel-plugin-http] previous [@opentelemetry/plugin-http][otel-plugin-http] and [@opentelemetry/plugin-https][otel-plugin-https] +- [@opentelemetry/instrumentation-http][otel-instrumentation-http] previous [@opentelemetry/plugin-http][otel-plugin-http] and [@opentelemetry/plugin-https][otel-plugin-https] ##### Contrib @@ -410,7 +411,6 @@ Apache 2.0 - See [LICENSE][license-url] for more information. [otel-instrumentation-fetch]: https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-instrumentation-fetch [otel-instrumentation-grpc]: https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-instrumentation-grpc [otel-instrumentation-http]: https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-instrumentation-http -[otel-instrumentation-https]: https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-instrumentation-https [otel-instrumentation-xml-http-request]: https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-instrumentation-xml-http-request [otel-shim-opentracing]: https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-shim-opentracing diff --git a/integration-tests/propagation-validation-server/package.json b/integration-tests/propagation-validation-server/package.json index 5d3a93f982e..68aa801cdd3 100644 --- a/integration-tests/propagation-validation-server/package.json +++ b/integration-tests/propagation-validation-server/package.json @@ -11,7 +11,7 @@ "compile": "tsc --build" }, "dependencies": { - "@opentelemetry/api": "^0.17.0", + "@opentelemetry/api": "^0.18.0", "@opentelemetry/context-async-hooks": "^0.17.0", "@opentelemetry/core": "^0.17.0", "@opentelemetry/tracing": "^0.17.0", diff --git a/integration-tests/propagation-validation-server/tsconfig.json b/integration-tests/propagation-validation-server/tsconfig.json index 187a1228e97..529c32cf6d3 100644 --- a/integration-tests/propagation-validation-server/tsconfig.json +++ b/integration-tests/propagation-validation-server/tsconfig.json @@ -6,9 +6,6 @@ }, "include": [], "references": [ - { - "path": "../../packages/opentelemetry-api" - }, { "path": "../../packages/opentelemetry-context-async-hooks" }, diff --git a/packages/opentelemetry-api-metrics/package.json b/packages/opentelemetry-api-metrics/package.json index 44da79ad82c..e86ea8cbc10 100644 --- a/packages/opentelemetry-api-metrics/package.json +++ b/packages/opentelemetry-api-metrics/package.json @@ -48,7 +48,7 @@ "access": "public" }, "dependencies": { - "@opentelemetry/api": "^0.17.0" + "@opentelemetry/api": "^0.18.0" }, "devDependencies": { "@types/mocha": "8.2.0", diff --git a/packages/opentelemetry-api-metrics/tsconfig.json b/packages/opentelemetry-api-metrics/tsconfig.json index f0d9f58500a..b8d88215e40 100644 --- a/packages/opentelemetry-api-metrics/tsconfig.json +++ b/packages/opentelemetry-api-metrics/tsconfig.json @@ -7,10 +7,5 @@ "include": [ "src/**/*.ts", "test/**/*.ts" - ], - "references": [ - { - "path": "../opentelemetry-api" - } ] } diff --git a/packages/opentelemetry-api/.eslintignore b/packages/opentelemetry-api/.eslintignore deleted file mode 100644 index 378eac25d31..00000000000 --- a/packages/opentelemetry-api/.eslintignore +++ /dev/null @@ -1 +0,0 @@ -build diff --git a/packages/opentelemetry-api/.eslintrc.js b/packages/opentelemetry-api/.eslintrc.js deleted file mode 100644 index e20344660f9..00000000000 --- a/packages/opentelemetry-api/.eslintrc.js +++ /dev/null @@ -1,8 +0,0 @@ -module.exports = { - "env": { - "mocha": true, - "commonjs": true, - "shared-node-browser": true - }, - ...require('../../eslint.config.js') -} diff --git a/packages/opentelemetry-api/LICENSE b/packages/opentelemetry-api/LICENSE deleted file mode 100644 index 261eeb9e9f8..00000000000 --- a/packages/opentelemetry-api/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - 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-api/README.md b/packages/opentelemetry-api/README.md deleted file mode 100644 index eea8b287fc9..00000000000 --- a/packages/opentelemetry-api/README.md +++ /dev/null @@ -1,175 +0,0 @@ -# OpenTelemetry API for JavaScript - -[![NPM Published Version][npm-img]][npm-url] -[![dependencies][dependencies-image]][dependencies-url] -[![devDependencies][devDependencies-image]][devDependencies-url] -[![Apache License][license-image]][license-image] - -This package provides everything needed to interact with the OpenTelemetry API, including all TypeScript interfaces, enums, and no-op implementations. It is intended for use both on the server and in the browser. - -## Quick Start - -To get started you need to install the SDK and plugins, create a TracerProvider, and register it with the API. - -### Install Dependencies - -```sh -$ # Install tracing dependencies -$ npm install \ - @opentelemetry/api \ - @opentelemetry/core \ - @opentelemetry/node \ - @opentelemetry/tracing \ - @opentelemetry/exporter-jaeger \ # add exporters as needed - @opentelemetry/plugin-http # add plugins as needed -``` - -> Note: this example is for node.js. See [examples/tracer-web](https://github.com/open-telemetry/opentelemetry-js/tree/main/examples/tracer-web) for a browser example. - -### Initialize the SDK - -Before any other module in your application is loaded, you must initialize the global tracer and meter providers. If you fail to initialize a provider, no-op implementations will be provided to any library which acquires them from the API. - -To collect traces and metrics, you will have to tell the SDK where to export telemetry data to. This example uses Jaeger and Prometheus, but exporters exist for [other tracing backends][other-tracing-backends]. If you're not sure if there is an exporter for your tracing backend, contact your tracing provider. - -#### Tracing - -```javascript -const { NodeTracerProvider } = require("@opentelemetry/node"); -const { SimpleSpanProcessor } = require("@opentelemetry/tracing"); -const { JaegerExporter } = require("@opentelemetry/exporter-jaeger"); - -const tracerProvider = new NodeTracerProvider(); - -/** - * The SimpleSpanProcessor does no batching and exports spans - * immediately when they end. For most production use cases, - * OpenTelemetry recommends use of the BatchSpanProcessor. - */ -tracerProvider.addSpanProcessor( - new SimpleSpanProcessor( - new JaegerExporter({ - serviceName: 'my-service' - }) - ) -); - -/** - * Registering the provider with the API allows it to be discovered - * and used by instrumentation libraries. The OpenTelemetry API provides - * methods to set global SDK implementations, but the default SDK provides - * a convenience method named `register` which registers same defaults - * for you. - * - * By default the NodeTracerProvider uses Trace Context for propagation - * and AsyncHooksScopeManager for context management. To learn about - * customizing this behavior, see API Registration Options below. - */ -tracerProvider.register(); -``` - -## Version Compatibility - -Because the npm installer and node module resolution algorithm could potentially allow two or more copies of any given package to exist within the same `node_modules` structure, the OpenTelemetry API takes advantage of a variable on the `global` object to store the global API. When an API method in the API package is called, it checks if this `global` API exists and proxies calls to it if and only if it is a compatible API version. This means if a package has a dependency on an OpenTelemetry API version which is not compatible with the API used by the end user, the package will receive a no-op implementation of the API. - -## Advanced Use - -### API Registration Options - -If you prefer to choose your own propagator or context manager, you may pass an options object into the `tracerProvider.register()` method. Omitted or `undefined` options will be replaced by a default value and `null` values will be skipped. - -```javascript -const { B3Propagator } = require("@opentelemetry/propagator-b3"); - -tracerProvider.register({ - // Use B3 Propagation - propagator: new B3Propagator(), - - // Skip registering a default context manager - contextManager: null, -}); -``` - -### API Methods - -If you are writing an instrumentation library, or prefer to call the API methods directly rather than using the `register` method on the Tracer/Meter Provider, OpenTelemetry provides direct access to the underlying API methods through the `@opentelemetry/api` package. API entry points are defined as global singleton objects `trace`, `metrics`, `propagation`, and `context` which contain methods used to initialize SDK implementations and acquire resources from the API. - -- [Trace API Documentation][trace-api-docs] -- [Propagation API Documentation][propagation-api-docs] -- [Context API Documentation][context-api-docs] - -```javascript -const api = require("@opentelemetry/api"); - -/* Initialize TracerProvider */ -api.trace.setGlobalTracerProvider(tracerProvider); -/* returns tracerProvider (no-op if a working provider has not been initialized) */ -api.trace.getTracerProvider(); -/* returns a tracer from the registered global tracer provider (no-op if a working provider has not been initialized) */ -api.trace.getTracer(name, version); - -/* Initialize Propagator */ -api.propagation.setGlobalPropagator(httpTraceContextPropagator); - -/* Initialize Context Manager */ -api.context.setGlobalContextManager(asyncHooksContextManager); -``` - -### Library Authors - -Library authors need only to depend on the `@opentelemetry/api` package and trust that the application owners which use their library will initialize an appropriate SDK. - -```javascript -const api = require("@opentelemetry/api"); - -const tracer = api.trace.getTracer("my-library-name", "0.2.3"); - -async function doSomething() { - const span = tracer.startSpan("doSomething"); - try { - const result = await doSomethingElse(); - span.end(); - return result; - } catch (err) { - span.setStatus({ - // use an appropriate status code here - code: api.SpanStatusCode.ERROR, - message: err.message, - }); - span.end(); - return null; - } -} -``` - -## 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/blob/main/LICENSE -[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat -[dependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js/status.svg?path=packages/opentelemetry-api -[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-api -[devDependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js/dev-status.svg?path=packages/opentelemetry-api -[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-api&type=dev -[npm-url]: https://www.npmjs.com/package/@opentelemetry/api -[npm-img]: https://badge.fury.io/js/%40opentelemetry%2Fapi.svg - -[trace-api-docs]: https://open-telemetry.github.io/opentelemetry-js/classes/traceapi.html -[metrics-api-docs]: https://open-telemetry.github.io/opentelemetry-js/classes/metricsapi.html -[propagation-api-docs]: https://open-telemetry.github.io/opentelemetry-js/classes/propagationapi.html -[context-api-docs]: https://open-telemetry.github.io/opentelemetry-js/classes/contextapi.html - -[web]: https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-web -[tracing]: https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-tracing -[node]: https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-node -[metrics]: https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-metrics - -[other-tracing-backends]: https://github.com/open-telemetry/opentelemetry-js#trace-exporters diff --git a/packages/opentelemetry-api/karma.conf.js b/packages/opentelemetry-api/karma.conf.js deleted file mode 100644 index 3019564a15b..00000000000 --- a/packages/opentelemetry-api/karma.conf.js +++ /dev/null @@ -1,24 +0,0 @@ -/*! - * 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 - * - * 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-api/package.json b/packages/opentelemetry-api/package.json deleted file mode 100644 index 3c9e10aae78..00000000000 --- a/packages/opentelemetry-api/package.json +++ /dev/null @@ -1,79 +0,0 @@ -{ - "name": "@opentelemetry/api", - "version": "0.17.0", - "description": "Public API for OpenTelemetry", - "main": "build/src/index.js", - "types": "build/src/index.d.ts", - "browser": { - "./src/platform/index.ts": "./src/platform/browser/index.ts", - "./build/src/platform/index.js": "./build/src/platform/browser/index.js" - }, - "repository": "open-telemetry/opentelemetry-js", - "scripts": { - "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 ../../", - "codecov:browser": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../", - "build": "npm run compile", - "lint": "eslint . --ext .ts", - "lint:fix": "eslint . --ext .ts --fix", - "version": "node ../../scripts/version-update.js", - "docs-test": "linkinator docs/out --silent --skip david-dm.org", - "docs": "typedoc --tsconfig tsconfig.docs.json", - "watch": "tsc --build --watch" - }, - "keywords": [ - "opentelemetry", - "nodejs", - "browser", - "tracing", - "profiling", - "stats", - "monitoring" - ], - "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" - ], - "publishConfig": { - "access": "public" - }, - "dependencies": { - "@opentelemetry/context-base": "^0.17.0" - }, - "devDependencies": { - "@types/mocha": "8.2.0", - "@types/node": "14.14.20", - "@types/sinon": "9.0.10", - "@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": "4.0.2", - "linkinator": "2.13.1", - "mocha": "7.2.0", - "nyc": "15.1.0", - "sinon": "9.2.3", - "ts-loader": "8.0.14", - "ts-mocha": "8.0.0", - "typedoc": "0.20.14", - "typescript": "4.1.3", - "webpack": "4.46.0" - } -} diff --git a/packages/opentelemetry-api/src/api/context.ts b/packages/opentelemetry-api/src/api/context.ts deleted file mode 100644 index fee5f30e49c..00000000000 --- a/packages/opentelemetry-api/src/api/context.ts +++ /dev/null @@ -1,116 +0,0 @@ -/* - * 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, - ContextManager, - NoopContextManager, -} from '@opentelemetry/context-base'; -import { - API_BACKWARDS_COMPATIBILITY_VERSION, - GLOBAL_CONTEXT_MANAGER_API_KEY, - makeGetter, - _global, -} from './global-utils'; - -const NOOP_CONTEXT_MANAGER = new NoopContextManager(); - -/** - * Singleton object which represents the entry point to the OpenTelemetry Context API - */ -export class ContextAPI { - private static _instance?: ContextAPI; - - /** Empty private constructor prevents end users from constructing a new instance of the API */ - private constructor() {} - - /** Get the singleton instance of the Context API */ - public static getInstance(): ContextAPI { - if (!this._instance) { - this._instance = new ContextAPI(); - } - - return this._instance; - } - - /** - * Set the current context manager. Returns the initialized context manager - */ - public setGlobalContextManager( - contextManager: ContextManager - ): ContextManager { - if (_global[GLOBAL_CONTEXT_MANAGER_API_KEY]) { - // global context manager has already been set - return this._getContextManager(); - } - - _global[GLOBAL_CONTEXT_MANAGER_API_KEY] = makeGetter( - API_BACKWARDS_COMPATIBILITY_VERSION, - contextManager, - NOOP_CONTEXT_MANAGER - ); - - return contextManager; - } - - /** - * Get the currently active context - */ - public active(): Context { - return this._getContextManager().active(); - } - - /** - * Execute a function with an active context - * - * @param context context to be active during function execution - * @param fn function to execute in a context - * @param thisArg optional receiver to be used for calling fn - * @param args optional arguments forwarded to fn - */ - public with ReturnType>( - context: Context, - fn: F, - thisArg?: ThisParameterType, - ...args: A - ): ReturnType { - return this._getContextManager().with(context, fn, thisArg, ...args); - } - - /** - * Bind a context to a target function or event emitter - * - * @param target function or event emitter to bind - * @param context context to bind to the event emitter or function. Defaults to the currently active context - */ - public bind(target: T, context: Context = this.active()): T { - return this._getContextManager().bind(target, context); - } - - private _getContextManager(): ContextManager { - return ( - _global[GLOBAL_CONTEXT_MANAGER_API_KEY]?.( - API_BACKWARDS_COMPATIBILITY_VERSION - ) ?? NOOP_CONTEXT_MANAGER - ); - } - - /** Disable and remove the global context manager */ - public disable() { - this._getContextManager().disable(); - delete _global[GLOBAL_CONTEXT_MANAGER_API_KEY]; - } -} diff --git a/packages/opentelemetry-api/src/api/diag.ts b/packages/opentelemetry-api/src/api/diag.ts deleted file mode 100644 index 58a5cdd1439..00000000000 --- a/packages/opentelemetry-api/src/api/diag.ts +++ /dev/null @@ -1,150 +0,0 @@ -/* - * 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 { - DiagLogger, - DiagLogFunction, - createNoopDiagLogger, - diagLoggerFunctions, -} from '../diag/logger'; -import { DiagLogLevel, createLogLevelDiagLogger } from '../diag/logLevel'; -import { - API_BACKWARDS_COMPATIBILITY_VERSION, - GLOBAL_DIAG_LOGGER_API_KEY, - makeGetter, - _global, -} from './global-utils'; - -/** Internal simple Noop Diag API that returns a noop logger and does not allow any changes */ -function noopDiagApi(): DiagAPI { - const noopApi = createNoopDiagLogger() as DiagAPI; - - noopApi.getLogger = () => noopApi; - noopApi.setLogger = noopApi.getLogger; - noopApi.setLogLevel = () => {}; - - return noopApi; -} - -/** - * Singleton object which represents the entry point to the OpenTelemetry internal - * diagnostic API - */ -export class DiagAPI implements DiagLogger { - /** Get the singleton instance of the DiagAPI API */ - public static instance(): DiagAPI { - let theInst = null; - if (_global[GLOBAL_DIAG_LOGGER_API_KEY]) { - // Looks like a previous instance was set, so try and fetch it - theInst = _global[GLOBAL_DIAG_LOGGER_API_KEY]?.( - API_BACKWARDS_COMPATIBILITY_VERSION - ) as DiagAPI; - } - - if (!theInst) { - theInst = new DiagAPI(); - _global[GLOBAL_DIAG_LOGGER_API_KEY] = makeGetter( - API_BACKWARDS_COMPATIBILITY_VERSION, - theInst, - noopDiagApi() - ); - } - - return theInst; - } - - /** - * Private internal constructor - * @private - */ - private constructor() { - let _logLevel: DiagLogLevel = DiagLogLevel.INFO; - let _filteredLogger: DiagLogger | null; - let _logger: DiagLogger = createNoopDiagLogger(); - - function _logProxy(funcName: keyof DiagLogger): DiagLogFunction { - return function () { - const orgArguments = arguments as unknown; - const theLogger = _filteredLogger || _logger; - const theFunc = theLogger[funcName]; - if (typeof theFunc === 'function') { - return theFunc.apply( - theLogger, - orgArguments as Parameters - ); - } - }; - } - - // Using self local variable for minification purposes as 'this' cannot be minified - const self = this; - - // DiagAPI specific functions - - self.getLogger = (): DiagLogger => { - // Return itself if no existing logger is defined (defaults effectively to a Noop) - return _logger; - }; - - self.setLogger = (logger?: DiagLogger): DiagLogger => { - const prevLogger = _logger; - if (!logger || logger !== self) { - // Simple special case to avoid any possible infinite recursion on the logging functions - _logger = logger || createNoopDiagLogger(); - _filteredLogger = createLogLevelDiagLogger(_logLevel, _logger); - } - - return prevLogger; - }; - - self.setLogLevel = (maxLogLevel: DiagLogLevel) => { - if (maxLogLevel !== _logLevel) { - _logLevel = maxLogLevel; - if (_logger) { - _filteredLogger = createLogLevelDiagLogger(maxLogLevel, _logger); - } - } - }; - - for (let i = 0; i < diagLoggerFunctions.length; i++) { - const name = diagLoggerFunctions[i]; - self[name] = _logProxy(name); - } - } - - /** - * Return the currently configured logger instance, if no logger has been configured - * it will return itself so any log level filtering will still be applied in this case. - */ - public getLogger!: () => DiagLogger; - - /** - * Set the DiagLogger instance - * @param logger - [Optional] The DiagLogger instance to set as the default logger, if not provided it will set it back as a noop - * @returns The previously registered DiagLogger - */ - public setLogger!: (logger?: DiagLogger) => DiagLogger; - - /** Set the default maximum diagnostic logging level */ - public setLogLevel!: (maxLogLevel: DiagLogLevel) => void; - - // DiagLogger implementation - public verbose!: DiagLogFunction; - public debug!: DiagLogFunction; - public info!: DiagLogFunction; - public warn!: DiagLogFunction; - public error!: DiagLogFunction; -} diff --git a/packages/opentelemetry-api/src/api/global-utils.ts b/packages/opentelemetry-api/src/api/global-utils.ts deleted file mode 100644 index a4b8f6f2800..00000000000 --- a/packages/opentelemetry-api/src/api/global-utils.ts +++ /dev/null @@ -1,70 +0,0 @@ -/* - * 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 { ContextManager } from '@opentelemetry/context-base'; -import { TextMapPropagator } from '../context/propagation/TextMapPropagator'; -import { TracerProvider } from '../trace/tracer_provider'; -import { _globalThis } from '../platform'; -import { DiagAPI } from '../api/diag'; - -export const GLOBAL_CONTEXT_MANAGER_API_KEY = Symbol.for( - 'io.opentelemetry.js.api.context' -); - -export const GLOBAL_PROPAGATION_API_KEY = Symbol.for( - 'io.opentelemetry.js.api.propagation' -); -export const GLOBAL_TRACE_API_KEY = Symbol.for('io.opentelemetry.js.api.trace'); - -export const GLOBAL_DIAG_LOGGER_API_KEY = Symbol.for( - 'io.opentelemetry.js.api.diag' -); - -type Get = (version: number) => T; -type OtelGlobal = Partial<{ - [GLOBAL_CONTEXT_MANAGER_API_KEY]: Get; - [GLOBAL_PROPAGATION_API_KEY]: Get; - [GLOBAL_TRACE_API_KEY]: Get; - [GLOBAL_DIAG_LOGGER_API_KEY]: Get; -}>; - -export const _global = _globalThis as OtelGlobal; - -/** - * Make a function which accepts a version integer and returns the instance of an API if the version - * is compatible, or a fallback version (usually NOOP) if it is not. - * - * @param requiredVersion Backwards compatibility version which is required to return the instance - * @param instance Instance which should be returned if the required version is compatible - * @param fallback Fallback instance, usually NOOP, which will be returned if the required version is not compatible - */ -export function makeGetter( - requiredVersion: number, - instance: T, - fallback: T -): Get { - return (version: number): T => - version === requiredVersion ? instance : fallback; -} - -/** - * A number which should be incremented each time a backwards incompatible - * change is made to the API. This number is used when an API package - * attempts to access the global API to ensure it is getting a compatible - * version. If the global API is not compatible with the API package - * attempting to get it, a NOOP API implementation will be returned. - */ -export const API_BACKWARDS_COMPATIBILITY_VERSION = 5; diff --git a/packages/opentelemetry-api/src/api/propagation.ts b/packages/opentelemetry-api/src/api/propagation.ts deleted file mode 100644 index b99dada22a1..00000000000 --- a/packages/opentelemetry-api/src/api/propagation.ts +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Context } from '@opentelemetry/context-base'; -import { NOOP_TEXT_MAP_PROPAGATOR } from '../context/propagation/NoopTextMapPropagator'; -import { - defaultTextMapGetter, - defaultTextMapSetter, - TextMapGetter, - TextMapPropagator, - TextMapSetter, -} from '../context/propagation/TextMapPropagator'; -import { - API_BACKWARDS_COMPATIBILITY_VERSION, - GLOBAL_PROPAGATION_API_KEY, - makeGetter, - _global, -} from './global-utils'; - -/** - * Singleton object which represents the entry point to the OpenTelemetry Propagation API - */ -export class PropagationAPI { - private static _instance?: PropagationAPI; - - /** Empty private constructor prevents end users from constructing a new instance of the API */ - private constructor() {} - - /** Get the singleton instance of the Propagator API */ - public static getInstance(): PropagationAPI { - if (!this._instance) { - this._instance = new PropagationAPI(); - } - - return this._instance; - } - - /** - * Set the current propagator. Returns the initialized propagator - */ - public setGlobalPropagator(propagator: TextMapPropagator): TextMapPropagator { - if (_global[GLOBAL_PROPAGATION_API_KEY]) { - // global propagator has already been set - return this._getGlobalPropagator(); - } - - _global[GLOBAL_PROPAGATION_API_KEY] = makeGetter( - API_BACKWARDS_COMPATIBILITY_VERSION, - propagator, - NOOP_TEXT_MAP_PROPAGATOR - ); - - return propagator; - } - - /** - * Inject context into a carrier to be propagated inter-process - * - * @param context Context carrying tracing data to inject - * @param carrier carrier to inject context into - * @param setter Function used to set values on the carrier - */ - public inject( - context: Context, - carrier: Carrier, - setter: TextMapSetter = defaultTextMapSetter - ): void { - return this._getGlobalPropagator().inject(context, carrier, setter); - } - - /** - * Extract context from a carrier - * - * @param context Context which the newly created context will inherit from - * @param carrier Carrier to extract context from - * @param getter Function used to extract keys from a carrier - */ - public extract( - context: Context, - carrier: Carrier, - getter: TextMapGetter = defaultTextMapGetter - ): Context { - return this._getGlobalPropagator().extract(context, carrier, getter); - } - - /** - * Return a list of all fields which may be used by the propagator. - */ - public fields(): string[] { - return this._getGlobalPropagator().fields(); - } - - /** Remove the global propagator */ - public disable() { - delete _global[GLOBAL_PROPAGATION_API_KEY]; - } - - private _getGlobalPropagator(): TextMapPropagator { - return ( - _global[GLOBAL_PROPAGATION_API_KEY]?.( - API_BACKWARDS_COMPATIBILITY_VERSION - ) ?? NOOP_TEXT_MAP_PROPAGATOR - ); - } -} diff --git a/packages/opentelemetry-api/src/api/trace.ts b/packages/opentelemetry-api/src/api/trace.ts deleted file mode 100644 index f0c2005577a..00000000000 --- a/packages/opentelemetry-api/src/api/trace.ts +++ /dev/null @@ -1,93 +0,0 @@ -/* - * 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 { NOOP_TRACER_PROVIDER } from '../trace/NoopTracerProvider'; -import { ProxyTracerProvider } from '../trace/ProxyTracerProvider'; -import { Tracer } from '../trace/tracer'; -import { TracerProvider } from '../trace/tracer_provider'; -import { isSpanContextValid } from '../trace/spancontext-utils'; -import { - API_BACKWARDS_COMPATIBILITY_VERSION, - GLOBAL_TRACE_API_KEY, - makeGetter, - _global, -} from './global-utils'; - -/** - * Singleton object which represents the entry point to the OpenTelemetry Tracing API - */ -export class TraceAPI { - private static _instance?: TraceAPI; - - private _proxyTracerProvider = new ProxyTracerProvider(); - - /** Empty private constructor prevents end users from constructing a new instance of the API */ - private constructor() {} - - /** Get the singleton instance of the Trace API */ - public static getInstance(): TraceAPI { - if (!this._instance) { - this._instance = new TraceAPI(); - } - - return this._instance; - } - - /** - * Set the current global tracer. Returns the initialized global tracer provider - */ - public setGlobalTracerProvider(provider: TracerProvider): TracerProvider { - if (_global[GLOBAL_TRACE_API_KEY]) { - // global tracer provider has already been set - return this.getTracerProvider(); - } - - this._proxyTracerProvider.setDelegate(provider); - - _global[GLOBAL_TRACE_API_KEY] = makeGetter( - API_BACKWARDS_COMPATIBILITY_VERSION, - this._proxyTracerProvider, - NOOP_TRACER_PROVIDER - ); - - return this.getTracerProvider(); - } - - /** - * Returns the global tracer provider. - */ - public getTracerProvider(): TracerProvider { - return ( - _global[GLOBAL_TRACE_API_KEY]?.(API_BACKWARDS_COMPATIBILITY_VERSION) ?? - this._proxyTracerProvider - ); - } - - /** - * Returns a tracer from the global tracer provider. - */ - public getTracer(name: string, version?: string): Tracer { - return this.getTracerProvider().getTracer(name, version); - } - - /** Remove the global tracer provider */ - public disable() { - delete _global[GLOBAL_TRACE_API_KEY]; - this._proxyTracerProvider = new ProxyTracerProvider(); - } - - public isSpanContextValid = isSpanContextValid; -} diff --git a/packages/opentelemetry-api/src/baggage/Baggage.ts b/packages/opentelemetry-api/src/baggage/Baggage.ts deleted file mode 100644 index 2876f5bd47b..00000000000 --- a/packages/opentelemetry-api/src/baggage/Baggage.ts +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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 { BaggageEntry } from './Entry'; - -/** - * Baggage represents collection of key-value pairs with optional metadata. - * Each key of Baggage is associated with exactly one value. - * Baggage may be used to annotate and enrich telemetry data. - */ -export interface Baggage { - /** - * Get an entry from Baggage if it exists - * - * @param key The key which identifies the BaggageEntry - */ - getEntry(key: string): BaggageEntry | undefined; - - /** - * Get a list of all entries in the Baggage - */ - getAllEntries(): [string, BaggageEntry][]; - - /** - * Returns a new baggage with the entries from the current bag and the specified entry - * - * @param key string which identifies the baggage entry - * @param entry BaggageEntry for the given key - */ - setEntry(key: string, entry: BaggageEntry): Baggage; - - /** - * Returns a new baggage with the entries from the current bag except the removed entry - * - * @param key key identifying the entry to be removed - */ - removeEntry(key: string): Baggage; - - /** - * Returns a new baggage with the entries from the current bag except the removed entries - * - * @param key keys identifying the entries to be removed - */ - removeEntries(...key: string[]): Baggage; - - /** - * Returns a new baggage with no entries - */ - clear(): Baggage; -} diff --git a/packages/opentelemetry-api/src/baggage/Entry.ts b/packages/opentelemetry-api/src/baggage/Entry.ts deleted file mode 100644 index d249c85cecd..00000000000 --- a/packages/opentelemetry-api/src/baggage/Entry.ts +++ /dev/null @@ -1,35 +0,0 @@ -/* - * 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 { baggageEntryMetadataSymbol } from './internal/symbol'; - -export interface BaggageEntry { - /** `String` value of the `BaggageEntry`. */ - value: string; - /** - * Metadata is an optional string property defined by the W3C baggage specification. - * It currently has no special meaning defined by the specification. - */ - metadata?: BaggageEntryMetadata; -} - -/** - * Serializable Metadata defined by the W3C baggage specification. - * It currently has no special meaning defined by the OpenTelemetry or W3C. - */ -export type BaggageEntryMetadata = { toString(): string } & { - __TYPE__: typeof baggageEntryMetadataSymbol; -}; diff --git a/packages/opentelemetry-api/src/baggage/index.ts b/packages/opentelemetry-api/src/baggage/index.ts deleted file mode 100644 index ba0a297c5d4..00000000000 --- a/packages/opentelemetry-api/src/baggage/index.ts +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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 { Baggage } from './Baggage'; -import { BaggageEntry, BaggageEntryMetadata } from './Entry'; -import { BaggageImpl } from './internal/baggage'; -import { baggageEntryMetadataSymbol } from './internal/symbol'; - -export * from './Baggage'; -export * from './Entry'; - -/** - * Create a new Baggage with optional entries - * - * @param entries An array of baggage entries the new baggage should contain - */ -export function createBaggage( - entries: Record = {} -): Baggage { - return new BaggageImpl(new Map(Object.entries(entries))); -} - -/** - * Create a serializable BaggageEntryMetadata object from a string. - * - * @param str string metadata. Format is currently not defined by the spec and has no special meaning. - * - */ -export function baggageEntryMetadataFromString( - str: string -): BaggageEntryMetadata { - if (typeof str !== 'string') { - // @TODO log diagnostic - str = ''; - } - - return { - __TYPE__: baggageEntryMetadataSymbol, - toString() { - return str; - }, - }; -} diff --git a/packages/opentelemetry-api/src/baggage/internal/baggage.ts b/packages/opentelemetry-api/src/baggage/internal/baggage.ts deleted file mode 100644 index f9331f411ab..00000000000 --- a/packages/opentelemetry-api/src/baggage/internal/baggage.ts +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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 { Baggage } from '../Baggage'; -import type { BaggageEntry } from '../Entry'; - -export class BaggageImpl implements Baggage { - private _entries: Map; - - constructor(entries?: Map) { - this._entries = entries ? new Map(entries) : new Map(); - } - - getEntry(key: string): BaggageEntry | undefined { - const entry = this._entries.get(key); - if (!entry) { - return undefined; - } - - return Object.assign({}, entry); - } - - getAllEntries(): [string, BaggageEntry][] { - return Array.from(this._entries.entries()).map(([k, v]) => [k, v]); - } - - setEntry(key: string, entry: BaggageEntry): BaggageImpl { - const newBaggage = new BaggageImpl(this._entries); - newBaggage._entries.set(key, entry); - return newBaggage; - } - - removeEntry(key: string): BaggageImpl { - const newBaggage = new BaggageImpl(this._entries); - newBaggage._entries.delete(key); - return newBaggage; - } - - removeEntries(...keys: string[]): BaggageImpl { - const newBaggage = new BaggageImpl(this._entries); - for (const key of keys) { - newBaggage._entries.delete(key); - } - return newBaggage; - } - - clear(): BaggageImpl { - return new BaggageImpl(); - } -} diff --git a/packages/opentelemetry-api/src/baggage/internal/symbol.ts b/packages/opentelemetry-api/src/baggage/internal/symbol.ts deleted file mode 100644 index f4213926c98..00000000000 --- a/packages/opentelemetry-api/src/baggage/internal/symbol.ts +++ /dev/null @@ -1,20 +0,0 @@ -/* - * 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. - */ - -/** - * Symbol used to make BaggageEntryMetadata an opaque type - */ -export const baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata'); diff --git a/packages/opentelemetry-api/src/common/Exception.ts b/packages/opentelemetry-api/src/common/Exception.ts deleted file mode 100644 index 5539b7e9f31..00000000000 --- a/packages/opentelemetry-api/src/common/Exception.ts +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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. - */ - -interface ExceptionWithCode { - code: string | number; - name?: string; - message?: string; - stack?: string; -} - -interface ExceptionWithMessage { - code?: string | number; - message: string; - name?: string; - stack?: string; -} - -interface ExceptionWithName { - code?: string | number; - message?: string; - name: string; - stack?: string; -} - -/** - * Defines Exception. - * - * string or an object with one of (message or name or code) and optional stack - */ -export type Exception = - | ExceptionWithCode - | ExceptionWithMessage - | ExceptionWithName - | string; diff --git a/packages/opentelemetry-api/src/common/Time.ts b/packages/opentelemetry-api/src/common/Time.ts deleted file mode 100644 index 5cf0dbb46bd..00000000000 --- a/packages/opentelemetry-api/src/common/Time.ts +++ /dev/null @@ -1,23 +0,0 @@ -/* - * 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 type HrTime = [number, number]; - -/** - * Defines TimeInput. - * - * hrtime, epoch milliseconds, performance.now() or Date - */ -export type TimeInput = HrTime | number | Date; diff --git a/packages/opentelemetry-api/src/context/context.ts b/packages/opentelemetry-api/src/context/context.ts deleted file mode 100644 index 86e7aabec3c..00000000000 --- a/packages/opentelemetry-api/src/context/context.ts +++ /dev/null @@ -1,125 +0,0 @@ -/* - * 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, createContextKey } from '@opentelemetry/context-base'; -import { Baggage, Span, SpanContext } from '../'; -import { NoopSpan } from '../trace/NoopSpan'; - -/** - * span key - */ -const SPAN_KEY = createContextKey('OpenTelemetry Context Key SPAN'); - -/** - * Shared key for indicating if instrumentation should be suppressed beyond - * this current scope. - */ -const SUPPRESS_INSTRUMENTATION_KEY = createContextKey( - 'OpenTelemetry Context Key SUPPRESS_INSTRUMENTATION' -); - -/** - * Baggage key - */ -const BAGGAGE_KEY = createContextKey('OpenTelemetry Baggage Key'); - -/** - * Return the span if one exists - * - * @param context context to get span from - */ -export function getSpan(context: Context): Span | undefined { - return (context.getValue(SPAN_KEY) as Span) || undefined; -} - -/** - * Set the span on a context - * - * @param context context to use as parent - * @param span span to set active - */ -export function setSpan(context: Context, span: Span): Context { - return context.setValue(SPAN_KEY, span); -} - -/** - * Wrap span context in a NoopSpan and set as span in a new - * context - * - * @param context context to set active span on - * @param spanContext span context to be wrapped - */ -export function setSpanContext( - context: Context, - spanContext: SpanContext -): Context { - return setSpan(context, new NoopSpan(spanContext)); -} - -/** - * Get the span context of the span if it exists. - * - * @param context context to get values from - */ -export function getSpanContext(context: Context): SpanContext | undefined { - return getSpan(context)?.context(); -} - -/** - * Sets value on context to indicate that instrumentation should - * be suppressed beyond this current scope. - * - * @param context context to set the suppress instrumentation value on. - */ -export function suppressInstrumentation(context: Context): Context { - return context.setValue(SUPPRESS_INSTRUMENTATION_KEY, true); -} - -/** - * Sets value on context to indicate that instrumentation should - * no-longer be suppressed beyond this current scope. - * - * @param context context to set the suppress instrumentation value on. - */ -export function unsuppressInstrumentation(context: Context): Context { - return context.setValue(SUPPRESS_INSTRUMENTATION_KEY, false); -} - -/** - * Return current suppress instrumentation value for the given context, - * if it exists. - * - * @param context context check for the suppress instrumentation value. - */ -export function isInstrumentationSuppressed(context: Context): boolean { - return Boolean(context.getValue(SUPPRESS_INSTRUMENTATION_KEY)); -} - -/** - * @param {Context} Context that manage all context values - * @returns {Baggage} Extracted baggage from the context - */ -export function getBaggage(context: Context): Baggage | undefined { - return (context.getValue(BAGGAGE_KEY) as Baggage) || undefined; -} - -/** - * @param {Context} Context that manage all context values - * @param {Baggage} baggage that will be set in the actual context - */ -export function setBaggage(context: Context, baggage: Baggage): Context { - return context.setValue(BAGGAGE_KEY, baggage); -} diff --git a/packages/opentelemetry-api/src/context/propagation/NoopTextMapPropagator.ts b/packages/opentelemetry-api/src/context/propagation/NoopTextMapPropagator.ts deleted file mode 100644 index e2ec6f1b92e..00000000000 --- a/packages/opentelemetry-api/src/context/propagation/NoopTextMapPropagator.ts +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Context } from '@opentelemetry/context-base'; -import { TextMapPropagator } from './TextMapPropagator'; - -/** - * No-op implementations of {@link TextMapPropagator}. - */ -export class NoopTextMapPropagator implements TextMapPropagator { - /** Noop inject function does nothing */ - inject(_context: Context, _carrier: unknown): void {} - /** Noop extract function does nothing and returns the input context */ - extract(context: Context, _carrier: unknown): Context { - return context; - } - fields(): string[] { - return []; - } -} - -export const NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator(); diff --git a/packages/opentelemetry-api/src/context/propagation/TextMapPropagator.ts b/packages/opentelemetry-api/src/context/propagation/TextMapPropagator.ts deleted file mode 100644 index b659a9704de..00000000000 --- a/packages/opentelemetry-api/src/context/propagation/TextMapPropagator.ts +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Context } from '@opentelemetry/context-base'; - -/** - * Injects `Context` into and extracts it from carriers that travel - * in-band across process boundaries. Encoding is expected to conform to the - * HTTP Header Field semantics. Values are often encoded as RPC/HTTP request - * headers. - * - * The carrier of propagated data on both the client (injector) and server - * (extractor) side is usually an object such as http headers. Propagation is - * usually implemented via library-specific request interceptors, where the - * client-side injects values and the server-side extracts them. - */ -export interface TextMapPropagator { - /** - * Injects values from a given `Context` into a carrier. - * - * OpenTelemetry defines a common set of format values (TextMapPropagator), - * and each has an expected `carrier` type. - * - * @param context the Context from which to extract values to transmit over - * the wire. - * @param carrier the carrier of propagation fields, such as http request - * headers. - * @param setter an optional {@link TextMapSetter}. If undefined, values will be - * set by direct object assignment. - */ - inject( - context: Context, - carrier: Carrier, - setter: TextMapSetter - ): void; - - /** - * Given a `Context` and a carrier, extract context values from a - * carrier and return a new context, created from the old context, with the - * extracted values. - * - * @param context the Context from which to extract values to transmit over - * the wire. - * @param carrier the carrier of propagation fields, such as http request - * headers. - * @param getter an optional {@link TextMapGetter}. If undefined, keys will be all - * own properties, and keys will be accessed by direct object access. - */ - extract( - context: Context, - carrier: Carrier, - getter: TextMapGetter - ): Context; - - /** - * Return a list of all fields which may be used by the propagator. - */ - fields(): string[]; -} - -/** - * A setter is specified by the caller to define a specific method - * to set key/value pairs on the carrier within a propagator. - */ -export interface TextMapSetter { - /** - * Callback used to set a key/value pair on an object. - * - * Should be called by the propagator each time a key/value pair - * should be set, and should set that key/value pair on the propagator. - * - * @param carrier object or class which carries key/value pairs - * @param key string key to modify - * @param value value to be set to the key on the carrier - */ - set(carrier: Carrier, key: string, value: string): void; -} - -/** - * A getter is specified by the caller to define a specific method - * to get the value of a key from a carrier. - */ -export interface TextMapGetter { - /** - * Get a list of all keys available on the carrier. - * - * @param carrier - */ - keys(carrier: Carrier): string[]; - - /** - * Get the value of a specific key from the carrier. - * - * @param carrier - * @param key - */ - get(carrier: Carrier, key: string): undefined | string | string[]; -} - -export const defaultTextMapGetter: TextMapGetter = { - get(carrier, key) { - if (carrier == null) { - return undefined; - } - return carrier[key]; - }, - - keys(carrier) { - if (carrier == null) { - return []; - } - return Object.keys(carrier); - }, -}; - -export const defaultTextMapSetter: TextMapSetter = { - set(carrier, key, value) { - if (carrier == null) { - return; - } - - carrier[key] = value; - }, -}; diff --git a/packages/opentelemetry-api/src/diag/consoleLogger.ts b/packages/opentelemetry-api/src/diag/consoleLogger.ts deleted file mode 100644 index 7ea2e9cd790..00000000000 --- a/packages/opentelemetry-api/src/diag/consoleLogger.ts +++ /dev/null @@ -1,90 +0,0 @@ -/* - * 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 { DiagLogger, DiagLogFunction } from './logger'; - -const consoleMap: { n: keyof DiagLogger; c: keyof Console }[] = [ - { n: 'error', c: 'error' }, - { n: 'warn', c: 'warn' }, - { n: 'info', c: 'info' }, - { n: 'debug', c: 'debug' }, - { n: 'verbose', c: 'trace' }, -]; - -/** - * A simple Immutable Console based diagnostic logger which will output any messages to the Console. - * If you want to limit the amount of logging to a specific level or lower use the - * {@link createLogLevelDiagLogger} - */ -export class DiagConsoleLogger implements DiagLogger { - constructor() { - function _consoleFunc(funcName: keyof Console): DiagLogFunction { - return function () { - const orgArguments = arguments; - if (console) { - // Some environments only expose the console when the F12 developer console is open - let theFunc = console[funcName]; - if (typeof theFunc !== 'function') { - // Not all environments support all functions - theFunc = console.log; - } - - // One last final check - if (typeof theFunc === 'function') { - return theFunc.apply(console, orgArguments); - } - } - }; - } - - for (let i = 0; i < consoleMap.length; i++) { - this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c); - } - } - - /** Log an error scenario that was not expected and caused the requested operation to fail. */ - public error!: DiagLogFunction; - - /** - * Log a warning scenario to inform the developer of an issues that should be investigated. - * The requested operation may or may not have succeeded or completed. - */ - public warn!: DiagLogFunction; - - /** - * Log a general informational message, this should not affect functionality. - * This is also the default logging level so this should NOT be used for logging - * debugging level information. - */ - public info!: DiagLogFunction; - - /** - * Log a general debug message that can be useful for identifying a failure. - * Information logged at this level may include diagnostic details that would - * help identify a failure scenario. Useful scenarios would be to log the execution - * order of async operations - */ - public debug!: DiagLogFunction; - - /** - * Log a detailed (verbose) trace level logging that can be used to identify failures - * where debug level logging would be insufficient, this level of tracing can include - * input and output parameters and as such may include PII information passing through - * the API. As such it is recommended that this level of tracing should not be enabled - * in a production environment. - */ - public verbose!: DiagLogFunction; -} diff --git a/packages/opentelemetry-api/src/diag/logLevel.ts b/packages/opentelemetry-api/src/diag/logLevel.ts deleted file mode 100644 index 362bb135f69..00000000000 --- a/packages/opentelemetry-api/src/diag/logLevel.ts +++ /dev/null @@ -1,126 +0,0 @@ -/* - * 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 { DiagAPI } from '../api/diag'; -import { DiagLogger, DiagLogFunction, createNoopDiagLogger } from './logger'; - -/** - * Defines the available internal logging levels for the diagnostic logger, the numeric values - * of the levels are defined to match the original values from the initial LogLevel to avoid - * compatibility/migration issues for any implementation that assume the numeric ordering. - */ -export enum DiagLogLevel { - /** Diagnostic Logging level setting to disable all logging (except and forced logs) */ - NONE = 0, - - /** Identifies an error scenario */ - ERROR = 30, - - /** Identifies a warning scenario */ - WARN = 50, - - /** General informational log message */ - INFO = 60, - - /** General debug log message */ - DEBUG = 70, - - /** - * Detailed trace level logging should only be used for development, should only be set - * in a development environment. - */ - VERBOSE = 80, - - /** Used to set the logging level to include all logging */ - ALL = 9999, -} - -/** - * This is equivalent to: - * type LogLevelString = 'NONE' | 'ERROR' | 'WARN' | 'INFO' | 'DEBUG' | 'VERBOSE' | 'ALL'; - */ -export type DiagLogLevelString = keyof typeof DiagLogLevel; - -/** Mapping from DiagLogger function name to logging level. */ -const levelMap: { n: keyof DiagLogger; l: DiagLogLevel }[] = [ - { n: 'error', l: DiagLogLevel.ERROR }, - { n: 'warn', l: DiagLogLevel.WARN }, - { n: 'info', l: DiagLogLevel.INFO }, - { n: 'debug', l: DiagLogLevel.DEBUG }, - { n: 'verbose', l: DiagLogLevel.VERBOSE }, -]; - -/** - * Create a Diagnostic logger which limits the messages that are logged via the wrapped logger based on whether the - * message has a {@link DiagLogLevel} equal to the maximum logging level or lower, unless the {@link DiagLogLevel} is - * NONE which will return a noop logger instance. This can be useful to reduce the amount of logging used for the - * system or for a specific component based on any local configuration. - * If you don't supply a logger it will use the global api.diag as the destination which will use the - * current logger and any filtering it may have applied. - * To avoid / bypass any global level filtering you should pass the current logger returned via - * api.diag.getLogger() however, any changes to the logger used by api.diag won't be reflected for this case. - * @param maxLevel - The max level to log any logging of a lower - * @param logger - The specific logger to limit, if not defined or supplied will default to api.diag - * @implements {@link DiagLogger} - * @returns {DiagLogger} - */ - -export function createLogLevelDiagLogger( - maxLevel: DiagLogLevel, - logger?: DiagLogger | null -): DiagLogger { - if (maxLevel < DiagLogLevel.NONE) { - maxLevel = DiagLogLevel.NONE; - } else if (maxLevel > DiagLogLevel.ALL) { - maxLevel = DiagLogLevel.ALL; - } - - if (maxLevel === DiagLogLevel.NONE) { - return createNoopDiagLogger(); - } - - if (!logger) { - logger = DiagAPI.instance(); - } - - function _filterFunc( - theLogger: DiagLogger, - funcName: keyof DiagLogger, - theLevel: DiagLogLevel - ): DiagLogFunction { - if (maxLevel >= theLevel) { - return function () { - const orgArguments = arguments as unknown; - const theFunc = theLogger[funcName]; - if (theFunc && typeof theFunc === 'function') { - return theFunc.apply( - logger, - orgArguments as Parameters - ); - } - }; - } - return function () {}; - } - - const newLogger = {} as DiagLogger; - for (let i = 0; i < levelMap.length; i++) { - const name = levelMap[i].n; - newLogger[name] = _filterFunc(logger, name, levelMap[i].l); - } - - return newLogger; -} diff --git a/packages/opentelemetry-api/src/diag/logger.ts b/packages/opentelemetry-api/src/diag/logger.ts deleted file mode 100644 index f718076b6a8..00000000000 --- a/packages/opentelemetry-api/src/diag/logger.ts +++ /dev/null @@ -1,86 +0,0 @@ -/* - * 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 type DiagLogFunction = (message: string, ...args: unknown[]) => void; - -/** - * Defines an internal diagnostic logger interface which is used to log internal diagnostic - * messages, you can set the default diagnostic logger via the {@link DiagAPI} setLogger function. - * API provided implementations include :- - * - a No-Op {@link createNoopDiagLogger} - * - a {@link DiagLogLevel} filtering wrapper {@link createLogLevelDiagLogger} - * - a general Console {@link DiagConsoleLogger} version. - */ -export interface DiagLogger { - /** Log an error scenario that was not expected and caused the requested operation to fail. */ - error: DiagLogFunction; - - /** - * Log a warning scenario to inform the developer of an issues that should be investigated. - * The requested operation may or may not have succeeded or completed. - */ - warn: DiagLogFunction; - - /** - * Log a general informational message, this should not affect functionality. - * This is also the default logging level so this should NOT be used for logging - * debugging level information. - */ - info: DiagLogFunction; - - /** - * Log a general debug message that can be useful for identifying a failure. - * Information logged at this level may include diagnostic details that would - * help identify a failure scenario. - * For example: Logging the order of execution of async operations. - */ - debug: DiagLogFunction; - - /** - * Log a detailed (verbose) trace level logging that can be used to identify failures - * where debug level logging would be insufficient, this level of tracing can include - * input and output parameters and as such may include PII information passing through - * the API. As such it is recommended that this level of tracing should not be enabled - * in a production environment. - */ - verbose: DiagLogFunction; -} - -// DiagLogger implementation -export const diagLoggerFunctions: Array = [ - 'verbose', - 'debug', - 'info', - 'warn', - 'error', -]; - -function noopLogFunction() {} - -/** - * Returns a No-Op Diagnostic logger where all messages do nothing. - * @implements {@link DiagLogger} - * @returns {DiagLogger} - */ -export function createNoopDiagLogger(): DiagLogger { - const diagLogger = {} as DiagLogger; - - for (let i = 0; i < diagLoggerFunctions.length; i++) { - diagLogger[diagLoggerFunctions[i]] = noopLogFunction; - } - - return diagLogger; -} diff --git a/packages/opentelemetry-api/src/index.ts b/packages/opentelemetry-api/src/index.ts deleted file mode 100644 index 819918c9911..00000000000 --- a/packages/opentelemetry-api/src/index.ts +++ /dev/null @@ -1,94 +0,0 @@ -/* - * 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 './common/Exception'; -export * from './common/Time'; -export * from './context/context'; -export * from './context/propagation/TextMapPropagator'; -export * from './context/propagation/NoopTextMapPropagator'; -export * from './baggage'; -export * from './trace/attributes'; -export * from './trace/Event'; -export * from './trace/link_context'; -export * from './trace/link'; -export * from './trace/NoopTracer'; -export * from './trace/NoopTracerProvider'; -export * from './trace/ProxyTracer'; -export * from './trace/ProxyTracerProvider'; -export * from './trace/Sampler'; -export * from './trace/SamplingResult'; -export * from './trace/span_context'; -export * from './trace/span_kind'; -export * from './trace/span'; -export * from './trace/SpanOptions'; -export * from './trace/status'; -export * from './trace/TimedEvent'; -export * from './trace/trace_flags'; -export * from './trace/trace_state'; -export * from './trace/tracer_provider'; -export * from './trace/tracer'; -export * from './diag/consoleLogger'; -export * from './diag/logger'; -export * from './diag/logLevel'; - -export { - INVALID_SPANID, - INVALID_TRACEID, - INVALID_SPAN_CONTEXT, - isSpanContextValid, - isValidTraceId, - isValidSpanId, -} from './trace/spancontext-utils'; - -export { - Context, - ROOT_CONTEXT, - createContextKey, - ContextManager, -} from '@opentelemetry/context-base'; - -import { ContextAPI } from './api/context'; -export type { ContextAPI } from './api/context'; -/** Entrypoint for context API */ -export const context = ContextAPI.getInstance(); - -import { TraceAPI } from './api/trace'; -export type { TraceAPI } from './api/trace'; -/** Entrypoint for trace API */ -export const trace = TraceAPI.getInstance(); - -import { PropagationAPI } from './api/propagation'; -export type { PropagationAPI } from './api/propagation'; -/** Entrypoint for propagation API */ -export const propagation = PropagationAPI.getInstance(); - -import { DiagAPI } from './api/diag'; -export type { DiagAPI } from './api/diag'; - -/** - * Entrypoint for Diag API. - * Defines Diagnostic handler used for internal diagnostic logging operations. - * The default provides a Noop DiagLogger implementation which may be changed via the - * diag.setLogger(logger: DiagLogger) function. - */ -export const diag = DiagAPI.instance(); - -export default { - trace, - context, - propagation, - diag, -}; diff --git a/packages/opentelemetry-api/src/platform/browser/globalThis.ts b/packages/opentelemetry-api/src/platform/browser/globalThis.ts deleted file mode 100644 index 34a8254b888..00000000000 --- a/packages/opentelemetry-api/src/platform/browser/globalThis.ts +++ /dev/null @@ -1,19 +0,0 @@ -/* - * 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. - */ - -/** only globals that common to node and browsers are allowed */ -// eslint-disable-next-line node/no-unsupported-features/es-builtins, no-undef -export const _globalThis = typeof globalThis === 'object' ? globalThis : window; diff --git a/packages/opentelemetry-api/src/platform/browser/index.ts b/packages/opentelemetry-api/src/platform/browser/index.ts deleted file mode 100644 index e9d6ebed71c..00000000000 --- a/packages/opentelemetry-api/src/platform/browser/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -/* - * 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 './globalThis'; diff --git a/packages/opentelemetry-api/src/platform/index.ts b/packages/opentelemetry-api/src/platform/index.ts deleted file mode 100644 index cdaf8858ce5..00000000000 --- a/packages/opentelemetry-api/src/platform/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -/* - * 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-api/src/platform/node/globalThis.ts b/packages/opentelemetry-api/src/platform/node/globalThis.ts deleted file mode 100644 index 36e97e27326..00000000000 --- a/packages/opentelemetry-api/src/platform/node/globalThis.ts +++ /dev/null @@ -1,19 +0,0 @@ -/* - * 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. - */ - -/** only globals that common to node and browsers are allowed */ -// eslint-disable-next-line node/no-unsupported-features/es-builtins -export const _globalThis = typeof globalThis === 'object' ? globalThis : global; diff --git a/packages/opentelemetry-api/src/platform/node/index.ts b/packages/opentelemetry-api/src/platform/node/index.ts deleted file mode 100644 index e9d6ebed71c..00000000000 --- a/packages/opentelemetry-api/src/platform/node/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -/* - * 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 './globalThis'; diff --git a/packages/opentelemetry-api/src/trace/Event.ts b/packages/opentelemetry-api/src/trace/Event.ts deleted file mode 100644 index 8bc5e274c5f..00000000000 --- a/packages/opentelemetry-api/src/trace/Event.ts +++ /dev/null @@ -1,25 +0,0 @@ -/* - * 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 { SpanAttributes } from './attributes'; - -/** A text annotation with a set of attributes. */ -export interface Event { - /** The name of the event. */ - name: string; - /** The attributes of the event. */ - attributes?: SpanAttributes; -} diff --git a/packages/opentelemetry-api/src/trace/NoopSpan.ts b/packages/opentelemetry-api/src/trace/NoopSpan.ts deleted file mode 100644 index 40f238d3ada..00000000000 --- a/packages/opentelemetry-api/src/trace/NoopSpan.ts +++ /dev/null @@ -1,75 +0,0 @@ -/* - * 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 { Exception } from '../common/Exception'; -import { TimeInput } from '../common/Time'; -import { SpanAttributes } from './attributes'; -import { Span } from './span'; -import { SpanContext } from './span_context'; -import { SpanStatus } from './status'; -import { INVALID_SPAN_CONTEXT } from './spancontext-utils'; - -/** - * The NoopSpan is the default {@link Span} that is used when no Span - * implementation is available. All operations are no-op including context - * propagation. - */ -export class NoopSpan implements Span { - constructor( - private readonly _spanContext: SpanContext = INVALID_SPAN_CONTEXT - ) {} - - // Returns a SpanContext. - context(): SpanContext { - return this._spanContext; - } - - // By default does nothing - setAttribute(_key: string, _value: unknown): this { - return this; - } - - // By default does nothing - setAttributes(_attributes: SpanAttributes): this { - return this; - } - - // By default does nothing - addEvent(_name: string, _attributes?: SpanAttributes): this { - return this; - } - - // By default does nothing - setStatus(_status: SpanStatus): this { - return this; - } - - // By default does nothing - updateName(_name: string): this { - return this; - } - - // By default does nothing - end(_endTime?: TimeInput): void {} - - // isRecording always returns false for noopSpan. - isRecording(): boolean { - return false; - } - - // By default does nothing - recordException(_exception: Exception, _time?: TimeInput): void {} -} diff --git a/packages/opentelemetry-api/src/trace/NoopTracer.ts b/packages/opentelemetry-api/src/trace/NoopTracer.ts deleted file mode 100644 index 683a7e5ab24..00000000000 --- a/packages/opentelemetry-api/src/trace/NoopTracer.ts +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Span, SpanOptions, Tracer, SpanContext } from '..'; -import { Context } from '@opentelemetry/context-base'; -import { NoopSpan } from './NoopSpan'; -import { isSpanContextValid } from './spancontext-utils'; -import { getSpanContext } from '../context/context'; - -/** - * No-op implementations of {@link Tracer}. - */ -export class NoopTracer implements Tracer { - // startSpan starts a noop span. - startSpan(name: string, options?: SpanOptions, context?: Context): Span { - const root = Boolean(options?.root); - if (root) { - return new NoopSpan(); - } - - const parentFromContext = context && getSpanContext(context); - - if ( - isSpanContext(parentFromContext) && - isSpanContextValid(parentFromContext) - ) { - return new NoopSpan(parentFromContext); - } else { - return new NoopSpan(); - } - } -} - -function isSpanContext(spanContext: any): spanContext is SpanContext { - return ( - typeof spanContext === 'object' && - typeof spanContext['spanId'] === 'string' && - typeof spanContext['traceId'] === 'string' && - typeof spanContext['traceFlags'] === 'number' - ); -} - -export const NOOP_TRACER = new NoopTracer(); diff --git a/packages/opentelemetry-api/src/trace/NoopTracerProvider.ts b/packages/opentelemetry-api/src/trace/NoopTracerProvider.ts deleted file mode 100644 index 09c86bd7d96..00000000000 --- a/packages/opentelemetry-api/src/trace/NoopTracerProvider.ts +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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 { NOOP_TRACER } from './NoopTracer'; -import { Tracer } from './tracer'; -import { TracerProvider } from './tracer_provider'; - -/** - * An implementation of the {@link TracerProvider} which returns an impotent - * Tracer for all calls to `getTracer`. - * - * All operations are no-op. - */ -export class NoopTracerProvider implements TracerProvider { - getTracer(_name?: string, _version?: string): Tracer { - return NOOP_TRACER; - } -} - -export const NOOP_TRACER_PROVIDER = new NoopTracerProvider(); diff --git a/packages/opentelemetry-api/src/trace/ProxyTracer.ts b/packages/opentelemetry-api/src/trace/ProxyTracer.ts deleted file mode 100644 index 591610c3aee..00000000000 --- a/packages/opentelemetry-api/src/trace/ProxyTracer.ts +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Context } from '@opentelemetry/context-base'; -import { Span, SpanOptions, Tracer } from '..'; -import { NOOP_TRACER } from './NoopTracer'; -import { ProxyTracerProvider } from './ProxyTracerProvider'; - -/** - * Proxy tracer provided by the proxy tracer provider - */ -export class ProxyTracer implements Tracer { - // When a real implementation is provided, this will be it - private _delegate?: Tracer; - - constructor( - private _provider: ProxyTracerProvider, - public readonly name: string, - public readonly version?: string - ) {} - - startSpan(name: string, options?: SpanOptions, context?: Context): Span { - return this._getTracer().startSpan(name, options, context); - } - - /** - * Try to get a tracer from the proxy tracer provider. - * If the proxy tracer provider has no delegate, return a noop tracer. - */ - private _getTracer() { - if (this._delegate) { - return this._delegate; - } - - const tracer = this._provider.getDelegateTracer(this.name, this.version); - - if (!tracer) { - return NOOP_TRACER; - } - - this._delegate = tracer; - return this._delegate; - } -} diff --git a/packages/opentelemetry-api/src/trace/ProxyTracerProvider.ts b/packages/opentelemetry-api/src/trace/ProxyTracerProvider.ts deleted file mode 100644 index e124dc95066..00000000000 --- a/packages/opentelemetry-api/src/trace/ProxyTracerProvider.ts +++ /dev/null @@ -1,57 +0,0 @@ -/* - * 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 { Tracer } from './tracer'; -import { TracerProvider } from './tracer_provider'; -import { ProxyTracer } from './ProxyTracer'; -import { NOOP_TRACER_PROVIDER } from './NoopTracerProvider'; - -/** - * Tracer provider which provides {@link ProxyTracer}s. - * - * Before a delegate is set, tracers provided are NoOp. - * When a delegate is set, traces are provided from the delegate. - * When a delegate is set after tracers have already been provided, - * all tracers already provided will use the provided delegate implementation. - */ -export class ProxyTracerProvider implements TracerProvider { - private _delegate?: TracerProvider; - - /** - * Get a {@link ProxyTracer} - */ - getTracer(name: string, version?: string): Tracer { - return ( - this.getDelegateTracer(name, version) ?? - new ProxyTracer(this, name, version) - ); - } - - getDelegate(): TracerProvider { - return this._delegate ?? NOOP_TRACER_PROVIDER; - } - - /** - * Set the delegate tracer provider - */ - setDelegate(delegate: TracerProvider) { - this._delegate = delegate; - } - - getDelegateTracer(name: string, version?: string): Tracer | undefined { - return this._delegate?.getTracer(name, version); - } -} diff --git a/packages/opentelemetry-api/src/trace/Sampler.ts b/packages/opentelemetry-api/src/trace/Sampler.ts deleted file mode 100644 index 7a4774e8f5c..00000000000 --- a/packages/opentelemetry-api/src/trace/Sampler.ts +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Context } from '@opentelemetry/context-base'; -import { SpanAttributes } from './attributes'; -import { Link } from './link'; -import { SamplingResult } from './SamplingResult'; -import { SpanKind } from './span_kind'; - -/** - * This interface represent a sampler. Sampling is a mechanism to control the - * noise and overhead introduced by OpenTelemetry by reducing the number of - * samples of traces collected and sent to the backend. - */ -export interface Sampler { - /** - * Checks whether span needs to be created and tracked. - * - * @param context Parent Context which may contain a span. - * @param traceId of the span to be created. It can be different from the - * traceId in the {@link SpanContext}. Typically in situations when the - * span to be created starts a new trace. - * @param spanName of the span to be created. - * @param spanKind of the span to be created. - * @param attributes Initial set of SpanAttributes for the Span being constructed. - * @param links Collection of links that will be associated with the Span to - * be created. Typically useful for batch operations. - * @returns a {@link SamplingResult}. - */ - shouldSample( - context: Context, - traceId: string, - spanName: string, - spanKind: SpanKind, - attributes: SpanAttributes, - links: Link[] - ): SamplingResult; - - /** Returns the sampler name or short description with the configuration. */ - toString(): string; -} diff --git a/packages/opentelemetry-api/src/trace/SamplingResult.ts b/packages/opentelemetry-api/src/trace/SamplingResult.ts deleted file mode 100644 index 26887338b87..00000000000 --- a/packages/opentelemetry-api/src/trace/SamplingResult.ts +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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 { SpanAttributes } from './attributes'; - -/** - * A sampling decision that determines how a {@link Span} will be recorded - * and collected. - */ -export enum SamplingDecision { - /** - * `Span.isRecording() === false`, span will not be recorded and all events - * and attributes will be dropped. - */ - NOT_RECORD, - /** - * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags} - * MUST NOT be set. - */ - RECORD, - /** - * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags} - * MUST be set. - */ - RECORD_AND_SAMPLED, -} - -/** - * A sampling result contains a decision for a {@link Span} and additional - * attributes the sampler would like to added to the Span. - */ -export interface SamplingResult { - /** - * A sampling decision, refer to {@link SamplingDecision} for details. - */ - decision: SamplingDecision; - /** - * The list of attributes returned by SamplingResult MUST be immutable. - * Caller may call {@link Sampler}.shouldSample any number of times and - * can safely cache the returned value. - */ - attributes?: Readonly; -} diff --git a/packages/opentelemetry-api/src/trace/SpanOptions.ts b/packages/opentelemetry-api/src/trace/SpanOptions.ts deleted file mode 100644 index cf368ec2870..00000000000 --- a/packages/opentelemetry-api/src/trace/SpanOptions.ts +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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 { TimeInput } from '../common/Time'; -import { SpanAttributes } from './attributes'; -import { Link } from './link'; -import { SpanKind } from './span_kind'; - -/** - * Options needed for span creation - */ -export interface SpanOptions { - /** - * The SpanKind of a span - * @default {@link SpanKind.INTERNAL} - */ - kind?: SpanKind; - - /** A span's attributes */ - attributes?: SpanAttributes; - - /** {@link Link}s span to other spans */ - links?: Link[]; - - /** A manually specified start time for the created `Span` object. */ - startTime?: TimeInput; - - /** The new span should be a root span. (Ignore parent from context). */ - root?: boolean; -} diff --git a/packages/opentelemetry-api/src/trace/TimedEvent.ts b/packages/opentelemetry-api/src/trace/TimedEvent.ts deleted file mode 100644 index 632107b2601..00000000000 --- a/packages/opentelemetry-api/src/trace/TimedEvent.ts +++ /dev/null @@ -1,26 +0,0 @@ -/* - * 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 { Event } from './Event'; -import { HrTime } from '../common/Time'; - -/** - * Represents a timed event. - * A timed event is an event with a timestamp. - */ -export interface TimedEvent extends Event { - time: HrTime; -} diff --git a/packages/opentelemetry-api/src/trace/attributes.ts b/packages/opentelemetry-api/src/trace/attributes.ts deleted file mode 100644 index a14fe1d9237..00000000000 --- a/packages/opentelemetry-api/src/trace/attributes.ts +++ /dev/null @@ -1,32 +0,0 @@ -/* - * 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 interface SpanAttributes { - [attributeKey: string]: SpanAttributeValue | undefined; -} - -/** - * Attribute values may be any non-nullish primitive value except an object. - * - * null or undefined attribute values are invalid and will result in undefined behavior. - */ -export type SpanAttributeValue = - | string - | number - | boolean - | Array - | Array - | Array; diff --git a/packages/opentelemetry-api/src/trace/link.ts b/packages/opentelemetry-api/src/trace/link.ts deleted file mode 100644 index 8bd37478b28..00000000000 --- a/packages/opentelemetry-api/src/trace/link.ts +++ /dev/null @@ -1,40 +0,0 @@ -/* - * 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 { SpanAttributes } from './attributes'; -import { LinkContext } from './link_context'; - -/** - * A pointer from the current {@link Span} to another span in the same trace or - * in a different trace. - * Few examples of Link usage. - * 1. Batch Processing: A batch of elements may contain elements associated - * with one or more traces/spans. Since there can only be one parent - * SpanContext, Link is used to keep reference to SpanContext of all - * elements in the batch. - * 2. Public Endpoint: A SpanContext in incoming client request on a public - * endpoint is untrusted from service provider perspective. In such case it - * is advisable to start a new trace with appropriate sampling decision. - * However, it is desirable to associate incoming SpanContext to new trace - * initiated on service provider side so two traces (from Client and from - * Service Provider) can be correlated. - */ -export interface Link { - /** The {@link LinkContext} of a linked span. */ - context: LinkContext; - /** A set of {@link SpanAttributes} on the link. */ - attributes?: SpanAttributes; -} diff --git a/packages/opentelemetry-api/src/trace/link_context.ts b/packages/opentelemetry-api/src/trace/link_context.ts deleted file mode 100644 index c52245975da..00000000000 --- a/packages/opentelemetry-api/src/trace/link_context.ts +++ /dev/null @@ -1,22 +0,0 @@ -/* - * 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 { SpanContext } from './span_context'; - -/** - * A pointer to another span. - */ -export type LinkContext = Pick; diff --git a/packages/opentelemetry-api/src/trace/span.ts b/packages/opentelemetry-api/src/trace/span.ts deleted file mode 100644 index 7d8b94b5a29..00000000000 --- a/packages/opentelemetry-api/src/trace/span.ts +++ /dev/null @@ -1,129 +0,0 @@ -/* - * 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 { Exception } from '../common/Exception'; -import { TimeInput } from '../common/Time'; -import { SpanAttributes, SpanAttributeValue } from './attributes'; -import { SpanContext } from './span_context'; -import { SpanStatus } from './status'; - -/** - * An interface that represents a span. A span represents a single operation - * within a trace. Examples of span might include remote procedure calls or a - * in-process function calls to sub-components. A Trace has a single, top-level - * "root" Span that in turn may have zero or more child Spans, which in turn - * may have children. - * - * Spans are created by the {@link Tracer.startSpan} method. - */ -export interface Span { - /** - * Returns the {@link SpanContext} object associated with this Span. - * - * Get an immutable, serializable identifier for this span that can be used - * to create new child spans. Returned SpanContext is usable even after the - * span ends. - * - * @returns the SpanContext object associated with this Span. - */ - context(): SpanContext; - - /** - * Sets an attribute to the span. - * - * Sets a single Attribute with the key and value passed as arguments. - * - * @param key the key for this attribute. - * @param value the value for this attribute. Setting a value null or - * undefined is invalid and will result in undefined behavior. - */ - setAttribute(key: string, value: SpanAttributeValue): this; - - /** - * Sets attributes to the span. - * - * @param attributes the attributes that will be added. - * null or undefined attribute values - * are invalid and will result in undefined behavior. - */ - setAttributes(attributes: SpanAttributes): this; - - /** - * Adds an event to the Span. - * - * @param name the name of the event. - * @param [attributesOrStartTime] the attributes that will be added; these are - * associated with this event. Can be also a start time - * if type is {@type TimeInput} and 3rd param is undefined - * @param [startTime] start time of the event. - */ - addEvent( - name: string, - attributesOrStartTime?: SpanAttributes | TimeInput, - startTime?: TimeInput - ): this; - - /** - * Sets a status to the span. If used, this will override the default Span - * status. Default is {@link SpanStatusCode.UNSET}. SetStatus overrides the value - * of previous calls to SetStatus on the Span. - * - * @param status the SpanStatus to set. - */ - setStatus(status: SpanStatus): this; - - /** - * Updates the Span name. - * - * This will override the name provided via {@link Tracer.startSpan}. - * - * Upon this update, any sampling behavior based on Span name will depend on - * the implementation. - * - * @param name the Span name. - */ - updateName(name: string): this; - - /** - * Marks the end of Span execution. - * - * Call to End of a Span MUST not have any effects on child spans. Those may - * still be running and can be ended later. - * - * Do not return `this`. The Span generally should not be used after it - * is ended so chaining is not desired in this context. - * - * @param [endTime] the time to set as Span's end time. If not provided, - * use the current time as the span's end time. - */ - end(endTime?: TimeInput): void; - - /** - * Returns the flag whether this span will be recorded. - * - * @returns true if this Span is active and recording information like events - * with the `AddEvent` operation and attributes using `setAttributes`. - */ - isRecording(): boolean; - - /** - * Sets exception as a span event - * @param exception the exception the only accepted values are string or Error - * @param [time] the time to set as Span's event time. If not provided, - * use the current time. - */ - recordException(exception: Exception, time?: TimeInput): void; -} diff --git a/packages/opentelemetry-api/src/trace/span_context.ts b/packages/opentelemetry-api/src/trace/span_context.ts deleted file mode 100644 index 613bdb8eb29..00000000000 --- a/packages/opentelemetry-api/src/trace/span_context.ts +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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 { TraceState } from './trace_state'; - -/** - * A SpanContext represents the portion of a {@link Span} which must be - * serialized and propagated along side of a {@link Baggage}. - */ -export interface SpanContext { - /** - * The ID of the trace that this span belongs to. It is worldwide unique - * with practically sufficient probability by being made as 16 randomly - * generated bytes, encoded as a 32 lowercase hex characters corresponding to - * 128 bits. - */ - traceId: string; - /** - * The ID of the Span. It is globally unique with practically sufficient - * probability by being made as 8 randomly generated bytes, encoded as a 16 - * lowercase hex characters corresponding to 64 bits. - */ - spanId: string; - /** - * Only true if the SpanContext was propagated from a remote parent. - */ - isRemote?: boolean; - /** - * Trace flags to propagate. - * - * It is represented as 1 byte (bitmap). Bit to represent whether trace is - * sampled or not. When set, the least significant bit documents that the - * caller may have recorded trace data. A caller who does not record trace - * data out-of-band leaves this flag unset. - * - * see {@link TraceFlags} for valid flag values. - */ - traceFlags: number; - /** - * Tracing-system-specific info to propagate. - * - * The tracestate field value is a `list` as defined below. The `list` is a - * series of `list-members` separated by commas `,`, and a list-member is a - * key/value pair separated by an equals sign `=`. Spaces and horizontal tabs - * surrounding `list-members` are ignored. There can be a maximum of 32 - * `list-members` in a `list`. - * More Info: https://www.w3.org/TR/trace-context/#tracestate-field - * - * Examples: - * Single tracing system (generic format): - * tracestate: rojo=00f067aa0ba902b7 - * Multiple tracing systems (with different formatting): - * tracestate: rojo=00f067aa0ba902b7,congo=t61rcWkgMzE - */ - traceState?: TraceState; -} diff --git a/packages/opentelemetry-api/src/trace/span_kind.ts b/packages/opentelemetry-api/src/trace/span_kind.ts deleted file mode 100644 index d0ed18123eb..00000000000 --- a/packages/opentelemetry-api/src/trace/span_kind.ts +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -export enum SpanKind { - /** Default value. Indicates that the span is used internally. */ - INTERNAL = 0, - - /** - * Indicates that the span covers server-side handling of an RPC or other - * remote request. - */ - SERVER = 1, - - /** - * Indicates that the span covers the client-side wrapper around an RPC or - * other remote request. - */ - CLIENT = 2, - - /** - * Indicates that the span describes producer sending a message to a - * broker. Unlike client and server, there is no direct critical path latency - * relationship between producer and consumer spans. - */ - PRODUCER = 3, - - /** - * Indicates that the span describes consumer receiving a message from a - * broker. Unlike client and server, there is no direct critical path latency - * relationship between producer and consumer spans. - */ - CONSUMER = 4, -} diff --git a/packages/opentelemetry-api/src/trace/spancontext-utils.ts b/packages/opentelemetry-api/src/trace/spancontext-utils.ts deleted file mode 100644 index ebcc3ce24fb..00000000000 --- a/packages/opentelemetry-api/src/trace/spancontext-utils.ts +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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 { SpanContext } from './span_context'; -import { TraceFlags } from './trace_flags'; - -const VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; -const VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; -export const INVALID_SPANID = '0000000000000000'; -export const INVALID_TRACEID = '00000000000000000000000000000000'; -export const INVALID_SPAN_CONTEXT: SpanContext = { - traceId: INVALID_TRACEID, - spanId: INVALID_SPANID, - traceFlags: TraceFlags.NONE, -}; - -export function isValidTraceId(traceId: string): boolean { - return VALID_TRACEID_REGEX.test(traceId) && traceId !== INVALID_TRACEID; -} - -export function isValidSpanId(spanId: string): boolean { - return VALID_SPANID_REGEX.test(spanId) && spanId !== INVALID_SPANID; -} - -/** - * Returns true if this {@link SpanContext} is valid. - * @return true if this {@link SpanContext} is valid. - */ -export function isSpanContextValid(spanContext: SpanContext): boolean { - return ( - isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId) - ); -} diff --git a/packages/opentelemetry-api/src/trace/status.ts b/packages/opentelemetry-api/src/trace/status.ts deleted file mode 100644 index f5b7a9ba56a..00000000000 --- a/packages/opentelemetry-api/src/trace/status.ts +++ /dev/null @@ -1,40 +0,0 @@ -/* - * 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 interface SpanStatus { - /** The status code of this message. */ - code: SpanStatusCode; - /** A developer-facing error message. */ - message?: string; -} - -/** - * An enumeration of status codes. - */ -export enum SpanStatusCode { - /** - * The default status. - */ - UNSET = 0, - /** - * The operation has been validated by an Application developer or - * Operator to have completed successfully. - */ - OK = 1, - /** - * The operation contains an error. - */ - ERROR = 2, -} diff --git a/packages/opentelemetry-api/src/trace/trace_flags.ts b/packages/opentelemetry-api/src/trace/trace_flags.ts deleted file mode 100644 index fd282010c7f..00000000000 --- a/packages/opentelemetry-api/src/trace/trace_flags.ts +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -export enum TraceFlags { - /** Represents no flag set. */ - NONE = 0x0, - /** Bit to represent whether trace is sampled in trace flags. */ - SAMPLED = 0x1 << 0, -} diff --git a/packages/opentelemetry-api/src/trace/trace_state.ts b/packages/opentelemetry-api/src/trace/trace_state.ts deleted file mode 100644 index 640d1578a91..00000000000 --- a/packages/opentelemetry-api/src/trace/trace_state.ts +++ /dev/null @@ -1,59 +0,0 @@ -/* - * 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 interface TraceState { - /** - * Create a new TraceState which inherits from this TraceState and has the - * given key set. - * The new entry will always be added in the front of the list of states. - * - * @param key key of the TraceState entry. - * @param value value of the TraceState entry. - */ - set(key: string, value: string): TraceState; - - /** - * Return a new TraceState which inherits from this TraceState but does not - * contain the given key. - * - * @param key the key for the TraceState entry to be removed. - */ - unset(key: string): TraceState; - - /** - * Returns the value to which the specified key is mapped, or `undefined` if - * this map contains no mapping for the key. - * - * @param key with which the specified value is to be associated. - * @returns the value to which the specified key is mapped, or `undefined` if - * this map contains no mapping for the key. - */ - get(key: string): string | undefined; - - // TODO: Consider to add support for merging an object as well by also - // accepting a single internalTraceState argument similar to the constructor. - - /** - * Serializes the TraceState to a `list` as defined below. The `list` is a - * series of `list-members` separated by commas `,`, and a list-member is a - * key/value pair separated by an equals sign `=`. Spaces and horizontal tabs - * surrounding `list-members` are ignored. There can be a maximum of 32 - * `list-members` in a `list`. - * - * @returns the serialized string. - */ - serialize(): string; -} diff --git a/packages/opentelemetry-api/src/trace/tracer.ts b/packages/opentelemetry-api/src/trace/tracer.ts deleted file mode 100644 index 270f146a9af..00000000000 --- a/packages/opentelemetry-api/src/trace/tracer.ts +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Context } from '@opentelemetry/context-base'; -import { Span } from './span'; -import { SpanOptions } from './SpanOptions'; - -/** - * Tracer provides an interface for creating {@link Span}s. - */ -export interface Tracer { - /** - * Starts a new {@link Span}. Start the span without setting it on context. - * - * This method do NOT modify the current Context. - * - * @param name The name of the span - * @param [options] SpanOptions used for span creation - * @param [context] Context to use to extract parent - * @returns Span The newly created span - * @example - * const span = tracer.startSpan('op'); - * span.setAttribute('key', 'value'); - * span.end(); - */ - startSpan(name: string, options?: SpanOptions, context?: Context): Span; -} diff --git a/packages/opentelemetry-api/src/trace/tracer_provider.ts b/packages/opentelemetry-api/src/trace/tracer_provider.ts deleted file mode 100644 index 6919cc1e26e..00000000000 --- a/packages/opentelemetry-api/src/trace/tracer_provider.ts +++ /dev/null @@ -1,35 +0,0 @@ -/* - * 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 { Tracer } from './tracer'; - -/** - * A registry for creating named {@link Tracer}s. - */ -export interface TracerProvider { - /** - * Returns a Tracer, creating one if one with the given name and version is - * not already created. - * - * This function may return different Tracer types (e.g. - * {@link NoopTracerProvider} vs. a functional tracer). - * - * @param name The name of the tracer or instrumentation library. - * @param version The version of the tracer or instrumentation library. - * @returns Tracer A Tracer with the given name and version - */ - getTracer(name: string, version?: string): Tracer; -} diff --git a/packages/opentelemetry-api/src/version.ts b/packages/opentelemetry-api/src/version.ts deleted file mode 100644 index 2544b647a56..00000000000 --- a/packages/opentelemetry-api/src/version.ts +++ /dev/null @@ -1,18 +0,0 @@ -/* - * 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.17.0'; diff --git a/packages/opentelemetry-api/test/api/api.test.ts b/packages/opentelemetry-api/test/api/api.test.ts deleted file mode 100644 index 50b905be995..00000000000 --- a/packages/opentelemetry-api/test/api/api.test.ts +++ /dev/null @@ -1,222 +0,0 @@ -/* - * 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 api, { - TraceFlags, - NoopTracerProvider, - NoopTracer, - SpanOptions, - Span, - context, - trace, - propagation, - TextMapPropagator, - Context, - TextMapSetter, - TextMapGetter, - ROOT_CONTEXT, - defaultTextMapSetter, - defaultTextMapGetter, - diag, - diagLoggerFunctions, -} from '../../src'; -import { DiagAPI } from '../../src/api/diag'; -import { _global } from '../../src/api/global-utils'; -import { NoopSpan } from '../../src/trace/NoopSpan'; - -describe('API', () => { - it('should expose a tracer provider via getTracerProvider', () => { - const tracer = api.trace.getTracerProvider(); - assert.ok(tracer); - assert.strictEqual(typeof tracer, 'object'); - }); - - describe('Context', () => { - it('with should forward this, arguments and return value', () => { - function fnWithThis(this: string, a: string, b: number): string { - assert.strictEqual(this, 'that'); - assert.strictEqual(arguments.length, 2); - assert.strictEqual(a, 'one'); - assert.strictEqual(b, 2); - return 'done'; - } - - const res = context.with(ROOT_CONTEXT, fnWithThis, 'that', 'one', 2); - assert.strictEqual(res, 'done'); - - assert.strictEqual( - context.with(ROOT_CONTEXT, () => 3.14), - 3.14 - ); - }); - }); - - describe('GlobalTracerProvider', () => { - const spanContext = { - traceId: 'd4cda95b652f4a1592b449d5929fda1b', - spanId: '6e0c63257de34c92', - traceFlags: TraceFlags.NONE, - }; - const dummySpan = new NoopSpan(spanContext); - - beforeEach(() => { - context.disable(); - trace.disable(); - propagation.disable(); - }); - - it('should use the global tracer provider', () => { - api.trace.setGlobalTracerProvider(new TestTracerProvider()); - const tracer = api.trace.getTracerProvider().getTracer('name'); - const span = tracer.startSpan('test'); - assert.deepStrictEqual(span, dummySpan); - }); - - class TestTracer extends NoopTracer { - startSpan(name: string, options?: SpanOptions): Span { - return dummySpan; - } - } - - class TestTracerProvider extends NoopTracerProvider { - getTracer(_name: string, version?: string) { - return new TestTracer(); - } - } - - describe('should use the global propagation', () => { - const testKey = Symbol('kTestKey'); - - interface Carrier { - context?: Context; - setter?: TextMapSetter; - } - - class TestTextMapPropagation implements TextMapPropagator { - inject( - context: Context, - carrier: Carrier, - setter: TextMapSetter - ): void { - carrier.context = context; - carrier.setter = setter; - } - - extract( - context: Context, - carrier: Carrier, - getter: TextMapGetter - ): Context { - return context.setValue(testKey, { - context, - carrier, - getter, - }); - } - - fields(): string[] { - return ['TestField']; - } - } - - it('inject', () => { - api.propagation.setGlobalPropagator(new TestTextMapPropagation()); - - const context = ROOT_CONTEXT.setValue(testKey, 15); - const carrier: Carrier = {}; - api.propagation.inject(context, carrier); - assert.strictEqual(carrier.context, context); - assert.strictEqual(carrier.setter, defaultTextMapSetter); - - const setter: TextMapSetter = { - set: () => {}, - }; - api.propagation.inject(context, carrier, setter); - assert.strictEqual(carrier.context, context); - assert.strictEqual(carrier.setter, setter); - }); - - it('extract', () => { - api.propagation.setGlobalPropagator(new TestTextMapPropagation()); - - const carrier: Carrier = {}; - let context = api.propagation.extract(ROOT_CONTEXT, carrier); - let data: any = context.getValue(testKey); - assert.ok(data != null); - assert.strictEqual(data.context, ROOT_CONTEXT); - assert.strictEqual(data.carrier, carrier); - assert.strictEqual(data.getter, defaultTextMapGetter); - - const getter: TextMapGetter = { - keys: () => [], - get: () => undefined, - }; - context = api.propagation.extract(ROOT_CONTEXT, carrier, getter); - data = context.getValue(testKey); - assert.ok(data != null); - assert.strictEqual(data.context, ROOT_CONTEXT); - assert.strictEqual(data.carrier, carrier); - assert.strictEqual(data.getter, getter); - }); - - it('fields', () => { - api.propagation.setGlobalPropagator(new TestTextMapPropagation()); - - const fields = api.propagation.fields(); - assert.deepStrictEqual(fields, ['TestField']); - }); - }); - }); - - describe('Global diag', () => { - it('initialization', () => { - const inst = DiagAPI.instance(); - - assert.deepStrictEqual(diag, inst); - }); - - diagLoggerFunctions.forEach(fName => { - it(`no argument logger ${fName} message doesn't throw`, () => { - diag.setLogger(); - assert.doesNotThrow(() => { - diag[fName](`${fName} message`); - }); - }); - - it(`null logger ${fName} message doesn't throw`, () => { - diag.setLogger(null as any); - assert.doesNotThrow(() => { - diag[fName](`${fName} message`); - }); - }); - - it(`undefined logger ${fName} message doesn't throw`, () => { - diag.setLogger(undefined as any); - assert.doesNotThrow(() => { - diag[fName](`${fName} message`); - }); - }); - - it(`empty logger ${fName} message doesn't throw`, () => { - diag.setLogger({} as any); - assert.doesNotThrow(() => { - diag[fName](`${fName} message`); - }); - }); - }); - }); -}); diff --git a/packages/opentelemetry-api/test/api/global.test.ts b/packages/opentelemetry-api/test/api/global.test.ts deleted file mode 100644 index 5a489650715..00000000000 --- a/packages/opentelemetry-api/test/api/global.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -/* - * 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 { NoopContextManager } from '@opentelemetry/context-base'; -import { - _global, - GLOBAL_CONTEXT_MANAGER_API_KEY, -} from '../../src/api/global-utils'; - -const api1 = require('../../src') as typeof import('../../src'); - -// clear cache and load a second instance of the api -for (const key of Object.keys(require.cache)) { - delete require.cache[key]; -} -const api2 = require('../../src') as typeof import('../../src'); - -describe('Global Utils', () => { - // prove they are separate instances - assert.notEqual(api1, api2); - // that return separate noop instances to start - assert.notStrictEqual( - api1.context['_getContextManager'](), - api2.context['_getContextManager']() - ); - - beforeEach(() => { - api1.context.disable(); - api1.propagation.disable(); - api1.trace.disable(); - }); - - it('should change the global context manager', () => { - const original = api1.context['_getContextManager'](); - const newContextManager = new NoopContextManager(); - api1.context.setGlobalContextManager(newContextManager); - assert.notStrictEqual(api1.context['_getContextManager'](), original); - assert.strictEqual(api1.context['_getContextManager'](), newContextManager); - }); - - it('should load an instance from one which was set in the other', () => { - api1.context.setGlobalContextManager(new NoopContextManager()); - assert.strictEqual( - api1.context['_getContextManager'](), - api2.context['_getContextManager']() - ); - }); - - it('should disable both if one is disabled', () => { - const original = api1.context['_getContextManager'](); - - api1.context.setGlobalContextManager(new NoopContextManager()); - - assert.notStrictEqual(original, api1.context['_getContextManager']()); - api2.context.disable(); - assert.strictEqual(original, api1.context['_getContextManager']()); - }); - - it('should return the module NoOp implementation if the version is a mismatch', () => { - const original = api1.context['_getContextManager'](); - api1.context.setGlobalContextManager(new NoopContextManager()); - const afterSet = _global[GLOBAL_CONTEXT_MANAGER_API_KEY]!(-1); - - assert.strictEqual(original, afterSet); - }); -}); diff --git a/packages/opentelemetry-api/test/baggage/Baggage.test.ts b/packages/opentelemetry-api/test/baggage/Baggage.test.ts deleted file mode 100644 index 45eb59d7b0e..00000000000 --- a/packages/opentelemetry-api/test/baggage/Baggage.test.ts +++ /dev/null @@ -1,161 +0,0 @@ -/* - * 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 { - createBaggage, - setBaggage, - getBaggage, - ROOT_CONTEXT, - baggageEntryMetadataFromString, -} from '../../src'; - -describe('Baggage', () => { - describe('create', () => { - it('should create an empty bag', () => { - const bag = createBaggage(); - - assert.deepStrictEqual(bag.getAllEntries(), []); - }); - - it('should create a bag with entries', () => { - const meta = baggageEntryMetadataFromString('opaque string'); - const bag = createBaggage({ - key1: { value: 'value1' }, - key2: { value: 'value2', metadata: meta }, - }); - - assert.deepStrictEqual(bag.getAllEntries(), [ - ['key1', { value: 'value1' }], - ['key2', { value: 'value2', metadata: meta }], - ]); - }); - }); - - describe('get', () => { - it('should not allow modification of returned entries', () => { - const bag = createBaggage().setEntry('key', { value: 'value' }); - - const entry = bag.getEntry('key'); - assert.ok(entry); - entry.value = 'mutated'; - - assert.strictEqual(bag.getEntry('key')?.value, 'value'); - }); - }); - - describe('set', () => { - it('should create a new bag when an entry is added', () => { - const bag = createBaggage(); - - const bag2 = bag.setEntry('key', { value: 'value' }); - - assert.notStrictEqual(bag, bag2); - assert.deepStrictEqual(bag.getAllEntries(), []); - assert.deepStrictEqual(bag2.getAllEntries(), [ - ['key', { value: 'value' }], - ]); - }); - }); - - describe('remove', () => { - it('should create a new bag when an entry is removed', () => { - const bag = createBaggage({ - key: { value: 'value' }, - }); - - const bag2 = bag.removeEntry('key'); - - assert.deepStrictEqual(bag.getAllEntries(), [ - ['key', { value: 'value' }], - ]); - - assert.deepStrictEqual(bag2.getAllEntries(), []); - }); - - it('should create an empty bag multiple keys are removed', () => { - const bag = createBaggage({ - key: { value: 'value' }, - key1: { value: 'value1' }, - key2: { value: 'value2' }, - }); - - const bag2 = bag.removeEntries('key', 'key1'); - - assert.deepStrictEqual(bag.getAllEntries(), [ - ['key', { value: 'value' }], - ['key1', { value: 'value1' }], - ['key2', { value: 'value2' }], - ]); - - assert.deepStrictEqual(bag2.getAllEntries(), [ - ['key2', { value: 'value2' }], - ]); - }); - - it('should create an empty bag when it cleared', () => { - const bag = createBaggage({ - key: { value: 'value' }, - key1: { value: 'value1' }, - }); - - const bag2 = bag.clear(); - - assert.deepStrictEqual(bag.getAllEntries(), [ - ['key', { value: 'value' }], - ['key1', { value: 'value1' }], - ]); - - assert.deepStrictEqual(bag2.getAllEntries(), []); - }); - }); - - describe('context', () => { - it('should set and get a baggage from a context', () => { - const bag = createBaggage(); - - const ctx = setBaggage(ROOT_CONTEXT, bag); - - assert.strictEqual(bag, getBaggage(ctx)); - }); - }); - - describe('metadata', () => { - it('should create an opaque object which returns the string unchanged', () => { - const meta = baggageEntryMetadataFromString('this is a string'); - - assert.strictEqual(meta.toString(), 'this is a string'); - }); - - it('should return an empty string if input is invalid', () => { - //@ts-expect-error only accepts string values - const meta = baggageEntryMetadataFromString(1); - - assert.strictEqual(meta.toString(), ''); - }); - - it('should retain metadata', () => { - const bag = createBaggage({ - key: { - value: 'value', - metadata: baggageEntryMetadataFromString('meta'), - }, - }); - - assert.deepStrictEqual(bag.getEntry('key')?.metadata?.toString(), 'meta'); - }); - }); -}); diff --git a/packages/opentelemetry-api/test/context/context.test.ts b/packages/opentelemetry-api/test/context/context.test.ts deleted file mode 100644 index 5c3c50929c6..00000000000 --- a/packages/opentelemetry-api/test/context/context.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -/* - * 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 { ROOT_CONTEXT, createContextKey } from '@opentelemetry/context-base'; -import { - suppressInstrumentation, - unsuppressInstrumentation, - isInstrumentationSuppressed, -} from '../../src/context/context'; - -const SUPPRESS_INSTRUMENTATION_KEY = createContextKey( - 'OpenTelemetry Context Key SUPPRESS_INSTRUMENTATION' -); - -describe('Context Helpers', () => { - describe('suppressInstrumentation', () => { - it('should set suppress to true', () => { - const context = suppressInstrumentation(ROOT_CONTEXT); - assert.deepStrictEqual(isInstrumentationSuppressed(context), true); - }); - }); - - describe('unsuppressInstrumentation', () => { - it('should set suppress to false', () => { - const context = unsuppressInstrumentation(ROOT_CONTEXT); - assert.deepStrictEqual(isInstrumentationSuppressed(context), false); - }); - }); - - describe('isInstrumentationSuppressed', () => { - it('should get value as bool', () => { - const expectedValue = true; - const context = ROOT_CONTEXT.setValue( - SUPPRESS_INSTRUMENTATION_KEY, - expectedValue - ); - - const value = isInstrumentationSuppressed(context); - - assert.equal(value, expectedValue); - }); - - describe('when suppress instrumentation set to null', () => { - const context = ROOT_CONTEXT.setValue(SUPPRESS_INSTRUMENTATION_KEY, null); - - it('should return false', () => { - const value = isInstrumentationSuppressed(context); - - assert.equal(value, false); - }); - }); - - describe('when suppress instrumentation set to undefined', () => { - const context = ROOT_CONTEXT.setValue( - SUPPRESS_INSTRUMENTATION_KEY, - undefined - ); - - it('should return false', () => { - const value = isInstrumentationSuppressed(context); - - assert.equal(value, false); - }); - }); - }); -}); diff --git a/packages/opentelemetry-api/test/diag/consoleLogger.test.ts b/packages/opentelemetry-api/test/diag/consoleLogger.test.ts deleted file mode 100644 index 07269bc9309..00000000000 --- a/packages/opentelemetry-api/test/diag/consoleLogger.test.ts +++ /dev/null @@ -1,209 +0,0 @@ -/* - * 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 { DiagConsoleLogger } from '../../src/diag/consoleLogger'; -import { diagLoggerFunctions } from '../../src/diag/logger'; - -const consoleFuncs: Array = [ - 'debug', - 'info', - 'warn', - 'error', - 'log', - 'trace', -]; - -const expectedConsoleMap: { [n: string]: keyof Console } = { - error: 'error', - warn: 'warn', - info: 'info', - debug: 'debug', - verbose: 'trace', -}; - -describe('DiagConsoleLogger', () => { - const origConsole = console; - const orig: any = {}; - const calledArgs: any = {}; - - // Save original functions - consoleFuncs.forEach(fName => { - orig[fName] = console[fName]; - calledArgs[fName] = null; - }); - - let canMockConsole = true; - - try { - // eslint-disable-next-line no-global-assign - console = origConsole; - } catch (ex) { - // Not supported on CI pipeline (works locally) - canMockConsole = false; - } - - beforeEach(() => { - // mock Console - consoleFuncs.forEach(fName => { - console[fName] = (...args: unknown[]) => { - calledArgs[fName] = args; - }; - }); - }); - - afterEach(() => { - // restore - if (canMockConsole) { - try { - // eslint-disable-next-line no-global-assign - console = origConsole; - } catch (ex) { - // Not supported on CI pipeline - canMockConsole = false; - } - } - - consoleFuncs.forEach(fName => { - calledArgs[fName] = null; - console[fName] = orig[fName]; - }); - }); - - describe('constructor', () => { - diagLoggerFunctions.forEach(fName => { - it(`console logger should provide ${fName} function`, () => { - const consoleLogger: any = new DiagConsoleLogger(); - consoleLogger[fName](`${fName} called %s`, 'param1'); - assert.ok( - typeof consoleLogger[fName] === 'function', - `Must have a ${fName} function` - ); - }); - - it(`should log ${expectedConsoleMap[fName]} message with ${fName} call only`, () => { - const consoleLogger: any = new DiagConsoleLogger(); - consoleLogger[fName](`${fName} called %s`, 'param1'); - - // Make sure only gets logged once - let matches = 0; - consoleFuncs.forEach(cName => { - if (cName !== expectedConsoleMap[fName]) { - assert.deepStrictEqual(calledArgs[cName], null); - } else { - assert.deepStrictEqual(calledArgs[expectedConsoleMap[fName]], [ - `${fName} called %s`, - 'param1', - ]); - matches++; - } - }); - - assert.deepStrictEqual(calledArgs.log, null); - assert.strictEqual(matches, 1, 'should log at least once'); - }); - - consoleFuncs.forEach(cName => { - it(`should log ${fName} message even when console doesn't support ${cName} call before construction`, () => { - console[cName] = undefined; - const consoleLogger: any = new DiagConsoleLogger(); - consoleLogger[fName](`${fName} called %s`, 'param1'); - if (cName !== expectedConsoleMap[fName]) { - assert.deepStrictEqual(calledArgs[cName], null); - } else { - assert.deepStrictEqual(calledArgs.log, [ - `${fName} called %s`, - 'param1', - ]); - } - }); - - it(`should log ${fName} message even when console doesn't support ${cName} call after construction`, () => { - const consoleLogger: any = new DiagConsoleLogger(); - console[cName] = undefined; - consoleLogger[fName](`${fName} called %s`, 'param1'); - if (cName !== expectedConsoleMap[fName]) { - assert.deepStrictEqual(calledArgs[cName], null); - } else { - assert.deepStrictEqual(calledArgs.log, [ - `${fName} called %s`, - 'param1', - ]); - } - }); - }); - }); - - if (canMockConsole) { - diagLoggerFunctions.forEach(fName => { - const cName = expectedConsoleMap[fName]; - it(`should not throw even when console is not supported for ${fName} call`, () => { - // eslint-disable-next-line no-global-assign - (console as any) = undefined; - const consoleLogger: any = new DiagConsoleLogger(); - consoleLogger[fName](`${fName} called %s`, 'param1'); - assert.deepStrictEqual(calledArgs[cName], null); - assert.deepStrictEqual(calledArgs.log, null); - }); - - it(`should not throw even when console is disabled after construction for ${fName} call`, () => { - const consoleLogger: any = new DiagConsoleLogger(); - // eslint-disable-next-line no-global-assign - (console as any) = undefined; - consoleLogger[fName](`${fName} called %s`, 'param1'); - assert.deepStrictEqual(calledArgs[expectedConsoleMap[fName]], null); - assert.deepStrictEqual(calledArgs.log, null); - }); - - it(`should not throw even when console is invalid after construction for ${fName} call`, () => { - const invalidConsole = { - debug: 1, - warn: 2, - error: 3, - trace: 4, - info: 5, - log: 6, - }; - - const consoleLogger = new DiagConsoleLogger(); - // eslint-disable-next-line no-global-assign - (console as any) = invalidConsole; - consoleLogger[fName](`${fName} called %s`, 'param1'); - assert.deepStrictEqual(calledArgs[expectedConsoleMap[fName]], null); - assert.deepStrictEqual(calledArgs.log, null); - }); - - it(`should not throw even when console is invalid before construction for ${fName} call`, () => { - const invalidConsole = { - debug: 1, - warn: 2, - error: 3, - trace: 4, - info: 5, - log: 6, - }; - - // eslint-disable-next-line no-global-assign - (console as any) = invalidConsole; - const consoleLogger = new DiagConsoleLogger(); - consoleLogger[fName](`${fName} called %s`, 'param1'); - assert.deepStrictEqual(calledArgs[expectedConsoleMap[fName]], null); - assert.deepStrictEqual(calledArgs.log, null); - }); - }); - } - }); -}); diff --git a/packages/opentelemetry-api/test/diag/logLevel.test.ts b/packages/opentelemetry-api/test/diag/logLevel.test.ts deleted file mode 100644 index 3b7fa54882d..00000000000 --- a/packages/opentelemetry-api/test/diag/logLevel.test.ts +++ /dev/null @@ -1,290 +0,0 @@ -/* - * 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 { diag } from '../../src'; -import { - createNoopDiagLogger, - DiagLogger, - diagLoggerFunctions, -} from '../../src/diag/logger'; -import { - DiagLogLevel, - createLogLevelDiagLogger, -} from '../../src/diag/logLevel'; - -// Matches the previous Logger definition -const incompleteLoggerFuncs: Array = [ - 'debug', - 'info', - 'warn', - 'error', -]; - -describe('LogLevelFilter DiagLogger', () => { - const calledArgs: any = { - error: null, - warn: null, - info: null, - debug: null, - verbose: null, - }; - - let dummyLogger: DiagLogger; - - /** Simulated Legacy logger */ - let incompleteLogger: DiagLogger; - - beforeEach(() => { - // Set no logger so that sinon doesn't complain about TypeError: Attempted to wrap xxxx which is already wrapped - diag.setLogger(); - diag.setLogLevel(DiagLogLevel.INFO); - - // mock - dummyLogger = {} as DiagLogger; - diagLoggerFunctions.forEach(fName => { - dummyLogger[fName] = (...args: unknown[]) => { - calledArgs[fName] = args; - }; - }); - - incompleteLogger = {} as DiagLogger; - incompleteLoggerFuncs.forEach(fName => { - incompleteLogger[fName] = (...args: unknown[]) => { - calledArgs[fName] = args; - }; - }); - }); - - afterEach(() => { - // restore - diagLoggerFunctions.forEach(fName => { - calledArgs[fName] = null; - }); - }); - - const levelMap: Array<{ - message: string; - level: DiagLogLevel; - ignoreFuncs: Array; - }> = [ - { message: 'ALL', level: DiagLogLevel.ALL, ignoreFuncs: [] }, - { message: 'greater than ALL', level: 32768, ignoreFuncs: [] }, - { message: 'VERBOSE', level: DiagLogLevel.VERBOSE, ignoreFuncs: [] }, - { message: 'DEBUG', level: DiagLogLevel.DEBUG, ignoreFuncs: ['verbose'] }, - { - message: 'INFO', - level: DiagLogLevel.INFO, - ignoreFuncs: ['verbose', 'debug'], - }, - { - message: 'WARN', - level: DiagLogLevel.WARN, - ignoreFuncs: ['verbose', 'debug', 'info'], - }, - { - message: 'ERROR', - level: DiagLogLevel.ERROR, - ignoreFuncs: ['verbose', 'debug', 'info', 'warn'], - }, - { - message: 'between ERROR and NONE', - level: 1, - ignoreFuncs: ['verbose', 'debug', 'info', 'warn', 'error'], - }, - { - message: 'NONE', - level: DiagLogLevel.NONE, - ignoreFuncs: ['verbose', 'debug', 'info', 'warn', 'error'], - }, - { - message: 'less than NONE', - level: -1000, - ignoreFuncs: ['verbose', 'debug', 'info', 'warn', 'error'], - }, - ]; - - levelMap.forEach(map => { - describe(`with ${map.message} log level`, () => { - diagLoggerFunctions.forEach(fName => { - describe(`calling ${fName} message`, () => { - it('should log', () => { - const testLogger = createLogLevelDiagLogger(map.level, dummyLogger); - testLogger[fName](`${fName} called %s`, 'param1'); - diagLoggerFunctions.forEach(lName => { - if (fName === lName && map.ignoreFuncs.indexOf(lName) === -1) { - assert.deepStrictEqual(calledArgs[lName], [ - `${fName} called %s`, - 'param1', - ]); - } else { - assert.strictEqual(calledArgs[lName], null); - } - }); - }); - - it('should be noop for null with explicit noop Logger log', () => { - const testLogger = createLogLevelDiagLogger( - map.level, - createNoopDiagLogger() - ); - testLogger[fName](`${fName} called %s`, 'param1'); - diagLoggerFunctions.forEach(lName => { - assert.strictEqual(calledArgs[lName], null); - }); - }); - - it('should be noop and not throw for null and no default Logger log', () => { - const testLogger = createLogLevelDiagLogger(map.level, null); - testLogger[fName](`${fName} called %s`, 'param1'); - diagLoggerFunctions.forEach(lName => { - assert.strictEqual(calledArgs[lName], null); - }); - }); - - it('should be noop and not throw for undefined and no default Logger log', () => { - const testLogger = createLogLevelDiagLogger(map.level, undefined); - testLogger[fName](`${fName} called %s`, 'param1'); - diagLoggerFunctions.forEach(lName => { - assert.strictEqual(calledArgs[lName], null); - }); - }); - - it('should use default logger for undefined and log', () => { - diag.setLogger(dummyLogger); - diag.setLogLevel(DiagLogLevel.ALL); - const testLogger = createLogLevelDiagLogger(map.level, undefined); - testLogger[fName](`${fName} called %s`, 'param1'); - diagLoggerFunctions.forEach(lName => { - if (fName === lName && map.ignoreFuncs.indexOf(lName) === -1) { - assert.deepStrictEqual(calledArgs[lName], [ - `${fName} called %s`, - 'param1', - ]); - } else { - assert.strictEqual(calledArgs[lName], null); - } - }); - }); - - it('should use default logger for null and log', () => { - diag.setLogger(dummyLogger); - diag.setLogLevel(DiagLogLevel.ALL); - const testLogger = createLogLevelDiagLogger(map.level, null); - testLogger[fName](`${fName} called %s`, 'param1'); - diagLoggerFunctions.forEach(lName => { - if (fName === lName && map.ignoreFuncs.indexOf(lName) === -1) { - assert.deepStrictEqual(calledArgs[lName], [ - `${fName} called %s`, - 'param1', - ]); - } else { - assert.strictEqual(calledArgs[lName], null); - } - }); - }); - - levelMap.forEach(masterLevelMap => { - describe(`when diag logger is set to ${masterLevelMap.message}`, () => { - it('diag setLogLevel is not ignored and using default logger', () => { - diag.setLogger(dummyLogger); - diag.setLogLevel(masterLevelMap.level); - - const testLogger = createLogLevelDiagLogger(map.level); - testLogger[fName](`${fName} called %s`, 'param1'); - diagLoggerFunctions.forEach(lName => { - if ( - fName === lName && - map.ignoreFuncs.indexOf(lName) === -1 && - masterLevelMap.ignoreFuncs.indexOf(lName) === -1 - ) { - assert.deepStrictEqual(calledArgs[lName], [ - `${fName} called %s`, - 'param1', - ]); - } else { - assert.strictEqual(calledArgs[lName], null); - } - }); - }); - - it('diag setLogLevel is ignored when using a specific logger', () => { - diag.setLogger(dummyLogger); - diag.setLogLevel(masterLevelMap.level); - - const testLogger = createLogLevelDiagLogger( - map.level, - diag.getLogger() - ); - testLogger[fName](`${fName} called %s`, 'param1'); - diagLoggerFunctions.forEach(lName => { - if ( - fName === lName && - map.ignoreFuncs.indexOf(lName) === -1 - ) { - assert.deepStrictEqual(calledArgs[lName], [ - `${fName} called %s`, - 'param1', - ]); - } else { - assert.strictEqual(calledArgs[lName], null); - } - }); - }); - }); - }); - - it('diag setLogLevel and logger should log', () => { - diag.setLogger(dummyLogger); - diag.setLogLevel(map.level); - diag[fName](`${fName} called %s`, 'param1'); - diagLoggerFunctions.forEach(lName => { - if (fName === lName && map.ignoreFuncs.indexOf(lName) === -1) { - assert.deepStrictEqual(calledArgs[lName], [ - `${fName} called %s`, - 'param1', - ]); - } else { - assert.strictEqual(calledArgs[lName], null); - } - }); - }); - - it('should not throw with an invalid DiagLogger', () => { - const invalidLogger = { - debug: 1, - warn: 2, - error: 3, - trace: 4, - info: 5, - log: 6, - }; - - const testLogger = createLogLevelDiagLogger( - map.level, - invalidLogger as any - ); - - testLogger[fName](`${fName} called %s`, 'param1'); - diagLoggerFunctions.forEach(lName => { - assert.strictEqual(calledArgs[lName], null); - }); - }); - }); - }); - }); - }); -}); diff --git a/packages/opentelemetry-api/test/diag/logger.test.ts b/packages/opentelemetry-api/test/diag/logger.test.ts deleted file mode 100644 index a957445b4b2..00000000000 --- a/packages/opentelemetry-api/test/diag/logger.test.ts +++ /dev/null @@ -1,94 +0,0 @@ -/* - * 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 { diag, DiagLogLevel } from '../../src'; -import { - DiagLogger, - createNoopDiagLogger, - diagLoggerFunctions, -} from '../../src/diag/logger'; - -describe('DiagLogger functions', () => { - const calledArgs: any = { - error: null, - warn: null, - info: null, - debug: null, - verbose: null, - }; - - let dummyLogger: DiagLogger; - - beforeEach(() => { - // mock - dummyLogger = {} as DiagLogger; - diagLoggerFunctions.forEach(fName => { - dummyLogger[fName] = (...args: unknown[]) => { - calledArgs[fName] = args; - }; - }); - }); - - afterEach(() => { - // restore - diagLoggerFunctions.forEach(fName => { - calledArgs[fName] = null; - }); - }); - - describe('constructor', () => { - diagLoggerFunctions.forEach(fName => { - it(`should log with ${fName} message`, () => { - const testLogger = dummyLogger; - testLogger[fName](`${fName} called %s`, 'param1'); - diagLoggerFunctions.forEach(lName => { - if (fName === lName) { - assert.deepStrictEqual(calledArgs[fName], [ - `${fName} called %s`, - 'param1', - ]); - } else { - assert.strictEqual(calledArgs[lName], null); - } - }); - }); - - it(`diag should log with ${fName} message`, () => { - diag.setLogger(dummyLogger); - diag.setLogLevel(DiagLogLevel.ALL); - diag[fName](`${fName} called %s`, 'param1'); - diagLoggerFunctions.forEach(lName => { - if (fName === lName) { - assert.deepStrictEqual(calledArgs[fName], [ - `${fName} called %s`, - 'param1', - ]); - } else { - assert.strictEqual(calledArgs[lName], null); - } - }); - }); - - it(`NoopLogger should implement all functions and not throw when ${fName} called`, () => { - const testLogger = createNoopDiagLogger(); - - assert.ok(typeof testLogger[fName], 'function'); - testLogger[fName](`${fName} called %s`, 'param1'); - }); - }); - }); -}); diff --git a/packages/opentelemetry-api/test/index-webpack.ts b/packages/opentelemetry-api/test/index-webpack.ts deleted file mode 100644 index 061a48ccfa7..00000000000 --- a/packages/opentelemetry-api/test/index-webpack.ts +++ /dev/null @@ -1,20 +0,0 @@ -/* - * 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); diff --git a/packages/opentelemetry-api/test/noop-implementations/noop-span.test.ts b/packages/opentelemetry-api/test/noop-implementations/noop-span.test.ts deleted file mode 100644 index d2974fca7e5..00000000000 --- a/packages/opentelemetry-api/test/noop-implementations/noop-span.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -/* - * 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 { - SpanStatusCode, - INVALID_SPANID, - INVALID_TRACEID, - TraceFlags, -} from '../../src'; -import { NoopSpan } from '../../src/trace/NoopSpan'; - -describe('NoopSpan', () => { - it('do not crash', () => { - const span = new NoopSpan(); - span.setAttribute('my_string_attribute', 'foo'); - span.setAttribute('my_number_attribute', 123); - span.setAttribute('my_boolean_attribute', false); - span.setAttribute('my_obj_attribute', { a: true }); - span.setAttribute('my_sym_attribute', Symbol('a')); - span.setAttributes({ - my_string_attribute: 'foo', - my_number_attribute: 123, - }); - - span.addEvent('sent'); - span.addEvent('sent', { id: '42', key: 'value' }); - - span.setStatus({ code: SpanStatusCode.ERROR }); - - span.updateName('my-span'); - - assert.ok(!span.isRecording()); - assert.deepStrictEqual(span.context(), { - traceId: INVALID_TRACEID, - spanId: INVALID_SPANID, - traceFlags: TraceFlags.NONE, - }); - span.end(); - }); -}); diff --git a/packages/opentelemetry-api/test/noop-implementations/noop-tracer.test.ts b/packages/opentelemetry-api/test/noop-implementations/noop-tracer.test.ts deleted file mode 100644 index 661ff34dbcf..00000000000 --- a/packages/opentelemetry-api/test/noop-implementations/noop-tracer.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -/* - * 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 { - NoopTracer, - SpanContext, - SpanKind, - TraceFlags, - context, - setSpanContext, -} from '../../src'; -import { NoopSpan } from '../../src/trace/NoopSpan'; - -describe('NoopTracer', () => { - it('should not crash', () => { - const tracer = new NoopTracer(); - - assert.ok(tracer.startSpan('span-name') instanceof NoopSpan); - assert.ok( - tracer.startSpan('span-name1', { kind: SpanKind.CLIENT }) instanceof - NoopSpan - ); - assert.ok( - tracer.startSpan('span-name2', { kind: SpanKind.CLIENT }) instanceof - NoopSpan - ); - }); - - it('should propagate valid spanContext on the span (from context)', () => { - const tracer = new NoopTracer(); - const parent: SpanContext = { - traceId: 'd4cda95b652f4a1592b449dd92ffda3b', - spanId: '6e0c63ffe4e34c42', - traceFlags: TraceFlags.NONE, - }; - const span = tracer.startSpan( - 'test-1', - {}, - setSpanContext(context.active(), parent) - ); - assert(span.context().traceId === parent.traceId); - assert(span.context().spanId === parent.spanId); - assert(span.context().traceFlags === parent.traceFlags); - }); -}); diff --git a/packages/opentelemetry-api/test/proxy-implementations/proxy-tracer.test.ts b/packages/opentelemetry-api/test/proxy-implementations/proxy-tracer.test.ts deleted file mode 100644 index c6e2756ca50..00000000000 --- a/packages/opentelemetry-api/test/proxy-implementations/proxy-tracer.test.ts +++ /dev/null @@ -1,137 +0,0 @@ -/* - * 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 { - ProxyTracerProvider, - SpanKind, - TracerProvider, - ProxyTracer, - Tracer, - Span, - NoopTracer, - ROOT_CONTEXT, - SpanOptions, -} from '../../src'; -import { NoopSpan } from '../../src/trace/NoopSpan'; - -describe('ProxyTracer', () => { - let provider: ProxyTracerProvider; - const sandbox = sinon.createSandbox(); - - beforeEach(() => { - provider = new ProxyTracerProvider(); - }); - - afterEach(() => { - sandbox.restore(); - }); - - describe('when no delegate is set', () => { - it('should return proxy tracers', () => { - const tracer = provider.getTracer('test'); - - assert.ok(tracer instanceof ProxyTracer); - }); - - it('startSpan should return Noop Spans', () => { - const tracer = provider.getTracer('test'); - - assert.ok(tracer.startSpan('span-name') instanceof NoopSpan); - assert.ok( - tracer.startSpan('span-name1', { kind: SpanKind.CLIENT }) instanceof - NoopSpan - ); - assert.ok( - tracer.startSpan('span-name2', { kind: SpanKind.CLIENT }) instanceof - NoopSpan - ); - }); - }); - - describe('when delegate is set before getTracer', () => { - let delegate: TracerProvider; - let getTracerStub: sinon.SinonStub; - - beforeEach(() => { - getTracerStub = sandbox.stub().returns(new NoopTracer()); - delegate = { - getTracer: getTracerStub, - }; - provider.setDelegate(delegate); - }); - - it('should return tracers directly from the delegate', () => { - const tracer = provider.getTracer('test', 'v0'); - - sandbox.assert.calledOnce(getTracerStub); - assert.strictEqual(getTracerStub.firstCall.returnValue, tracer); - assert.deepEqual(getTracerStub.firstCall.args, ['test', 'v0']); - }); - }); - - describe('when delegate is set after getTracer', () => { - let tracer: Tracer; - let delegate: TracerProvider; - let delegateSpan: Span; - let delegateTracer: Tracer; - - beforeEach(() => { - delegateSpan = new NoopSpan(); - delegateTracer = { - startSpan() { - return delegateSpan; - }, - }; - - tracer = provider.getTracer('test'); - - delegate = { - getTracer() { - return delegateTracer; - }, - }; - provider.setDelegate(delegate); - }); - - it('should create spans using the delegate tracer', () => { - const span = tracer.startSpan('test'); - - assert.strictEqual(span, delegateSpan); - }); - - it('should pass original arguments to DelegateTracer#startSpan', () => { - const startSpanStub = sandbox.stub(delegateTracer, 'startSpan'); - - const name = 'name1'; - const options: SpanOptions = {}; - const ctx = ROOT_CONTEXT.setValue(Symbol('test'), 1); - tracer.startSpan(name, options, ctx); - - // Assert the proxy tracer has the full API of the NoopTracer - assert.strictEqual( - NoopTracer.prototype.startSpan.length, - ProxyTracer.prototype.startSpan.length - ); - assert.deepStrictEqual(Object.getOwnPropertyNames(NoopTracer.prototype), [ - 'constructor', - 'startSpan', - ]); - sandbox.assert.calledOnceWithExactly(startSpanStub, name, options, ctx); - }); - }); -}); diff --git a/packages/opentelemetry-api/test/trace/spancontext-utils.test.ts b/packages/opentelemetry-api/test/trace/spancontext-utils.test.ts deleted file mode 100644 index e194f1d38be..00000000000 --- a/packages/opentelemetry-api/test/trace/spancontext-utils.test.ts +++ /dev/null @@ -1,57 +0,0 @@ -/* - * 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 context from '../../src/trace/spancontext-utils'; -import { TraceFlags } from '../../src'; - -describe('spancontext-utils', () => { - it('should return true for valid spancontext', () => { - const spanContext = { - traceId: 'd4cda95b652f4a1592b449d5929fda1b', - spanId: '6e0c63257de34c92', - traceFlags: TraceFlags.NONE, - }; - assert.ok(context.isSpanContextValid(spanContext)); - }); - - it('should return false when traceId is invalid', () => { - const spanContext = { - traceId: context.INVALID_TRACEID, - spanId: '6e0c63257de34c92', - traceFlags: TraceFlags.NONE, - }; - assert.ok(!context.isSpanContextValid(spanContext)); - }); - - it('should return false when spanId is invalid', () => { - const spanContext = { - traceId: 'd4cda95b652f4a1592b449d5929fda1b', - spanId: context.INVALID_SPANID, - traceFlags: TraceFlags.NONE, - }; - assert.ok(!context.isSpanContextValid(spanContext)); - }); - - it('should return false when traceId & spanId is invalid', () => { - const spanContext = { - traceId: context.INVALID_TRACEID, - spanId: context.INVALID_SPANID, - traceFlags: TraceFlags.NONE, - }; - assert.ok(!context.isSpanContextValid(spanContext)); - }); -}); diff --git a/packages/opentelemetry-api/tsconfig.docs.json b/packages/opentelemetry-api/tsconfig.docs.json deleted file mode 100644 index 0d2f7ed0546..00000000000 --- a/packages/opentelemetry-api/tsconfig.docs.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "compilerOptions": { - "rootDir": ".", - "outDir": "build" - }, - "include": [ - "src/**/*.ts" - ], - "typedocOptions": { - "name": "OpenTelemetry API for JavaScript", - "out": "docs/out", - "entryPoints": ["./src/index.ts"], - "hideGenerator": true - } -} diff --git a/packages/opentelemetry-api/tsconfig.json b/packages/opentelemetry-api/tsconfig.json deleted file mode 100644 index 8223abee15b..00000000000 --- a/packages/opentelemetry-api/tsconfig.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "extends": "../../tsconfig.es5.json", - "compilerOptions": { - "rootDir": ".", - "outDir": "build" - }, - "include": [ - "src/**/*.ts", - "test/**/*.ts" - ], - "references": [ - { - "path": "../opentelemetry-context-base" - } - ] -} diff --git a/packages/opentelemetry-context-async-hooks/package.json b/packages/opentelemetry-context-async-hooks/package.json index fbd1ce4b02c..a62e37b410e 100644 --- a/packages/opentelemetry-context-async-hooks/package.json +++ b/packages/opentelemetry-context-async-hooks/package.json @@ -53,6 +53,6 @@ "typescript": "4.1.3" }, "dependencies": { - "@opentelemetry/context-base": "^0.17.0" + "@opentelemetry/api": "^0.18.0" } } diff --git a/packages/opentelemetry-context-async-hooks/src/AbstractAsyncHooksContextManager.ts b/packages/opentelemetry-context-async-hooks/src/AbstractAsyncHooksContextManager.ts index 950b47acf3e..1a4db11c93e 100644 --- a/packages/opentelemetry-context-async-hooks/src/AbstractAsyncHooksContextManager.ts +++ b/packages/opentelemetry-context-async-hooks/src/AbstractAsyncHooksContextManager.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import { ContextManager, Context } from '@opentelemetry/context-base'; +import { ContextManager, Context } from '@opentelemetry/api'; import { EventEmitter } from 'events'; type Func = (...args: unknown[]) => T; diff --git a/packages/opentelemetry-context-async-hooks/src/AsyncHooksContextManager.ts b/packages/opentelemetry-context-async-hooks/src/AsyncHooksContextManager.ts index c7cc4d48013..5a2a3abae5f 100644 --- a/packages/opentelemetry-context-async-hooks/src/AsyncHooksContextManager.ts +++ b/packages/opentelemetry-context-async-hooks/src/AsyncHooksContextManager.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import { Context, ROOT_CONTEXT } from '@opentelemetry/context-base'; +import { Context, ROOT_CONTEXT } from '@opentelemetry/api'; import * as asyncHooks from 'async_hooks'; import { AbstractAsyncHooksContextManager } from './AbstractAsyncHooksContextManager'; diff --git a/packages/opentelemetry-context-async-hooks/src/AsyncLocalStorageContextManager.ts b/packages/opentelemetry-context-async-hooks/src/AsyncLocalStorageContextManager.ts index 4a4aa29f2ba..0af8695911b 100644 --- a/packages/opentelemetry-context-async-hooks/src/AsyncLocalStorageContextManager.ts +++ b/packages/opentelemetry-context-async-hooks/src/AsyncLocalStorageContextManager.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import { Context, ROOT_CONTEXT } from '@opentelemetry/context-base'; +import { Context, ROOT_CONTEXT } from '@opentelemetry/api'; import { AsyncLocalStorage } from 'async_hooks'; import { AbstractAsyncHooksContextManager } from './AbstractAsyncHooksContextManager'; diff --git a/packages/opentelemetry-context-async-hooks/test/AsyncHooksContextManager.test.ts b/packages/opentelemetry-context-async-hooks/test/AsyncHooksContextManager.test.ts index 2ef5b887996..5926c9485b3 100644 --- a/packages/opentelemetry-context-async-hooks/test/AsyncHooksContextManager.test.ts +++ b/packages/opentelemetry-context-async-hooks/test/AsyncHooksContextManager.test.ts @@ -20,7 +20,7 @@ import { AsyncLocalStorageContextManager, } from '../src'; import { EventEmitter } from 'events'; -import { createContextKey, ROOT_CONTEXT } from '@opentelemetry/context-base'; +import { createContextKey, ROOT_CONTEXT } from '@opentelemetry/api'; for (const contextManagerClass of [ AsyncHooksContextManager, diff --git a/packages/opentelemetry-context-async-hooks/tsconfig.json b/packages/opentelemetry-context-async-hooks/tsconfig.json index bf8999c67bf..bdc94d22137 100644 --- a/packages/opentelemetry-context-async-hooks/tsconfig.json +++ b/packages/opentelemetry-context-async-hooks/tsconfig.json @@ -7,10 +7,5 @@ "include": [ "src/**/*.ts", "test/**/*.ts" - ], - "references": [ - { - "path": "../opentelemetry-context-base" - } ] } diff --git a/packages/opentelemetry-context-base/.eslintignore b/packages/opentelemetry-context-base/.eslintignore deleted file mode 100644 index 378eac25d31..00000000000 --- a/packages/opentelemetry-context-base/.eslintignore +++ /dev/null @@ -1 +0,0 @@ -build diff --git a/packages/opentelemetry-context-base/.eslintrc.js b/packages/opentelemetry-context-base/.eslintrc.js deleted file mode 100644 index f726f3becb6..00000000000 --- a/packages/opentelemetry-context-base/.eslintrc.js +++ /dev/null @@ -1,7 +0,0 @@ -module.exports = { - "env": { - "mocha": true, - "node": true - }, - ...require('../../eslint.config.js') -} diff --git a/packages/opentelemetry-context-base/.npmignore b/packages/opentelemetry-context-base/.npmignore deleted file mode 100644 index 9505ba9450f..00000000000 --- a/packages/opentelemetry-context-base/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -/bin -/coverage -/doc -/test diff --git a/packages/opentelemetry-context-base/LICENSE b/packages/opentelemetry-context-base/LICENSE deleted file mode 100644 index 261eeb9e9f8..00000000000 --- a/packages/opentelemetry-context-base/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - 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-context-base/README.md b/packages/opentelemetry-context-base/README.md deleted file mode 100644 index c0880511df2..00000000000 --- a/packages/opentelemetry-context-base/README.md +++ /dev/null @@ -1,39 +0,0 @@ -# OpenTelemetry Base Context Manager - -[![NPM Published Version][npm-img]][npm-url] -[![dependencies][dependencies-image]][dependencies-url] -[![devDependencies][devDependencies-image]][devDependencies-url] -[![Apache License][license-image]][license-image] - -This package provides the ContextManager interface (which is used by concrete implementations) and a no-op implementation (which is used internally when no context propagation is defined). It's intended for use both on the server and in the browser. - -## What is a Context Manager - -To understand why they exists, we'll need to understand how Javascript works: when you make native function call (networks, setInterval etc) you generally call C++ code that will later callback your own code. - -A common issue when tracing a request in javascript is to link the function that have made the native call to the callback that the native code called when the response is there. Imagine you want to track for which user you made the request, you need some sort of "context/context aware storage". - -ContextManager's aim to offer exactly that, it's API offer to store an object in the current context (`with()`) and if needed, `bind()` to a specific function call to find it back when the callback fire, which can later get retrieved using `active()`. - -This package only include the interface and a Noop implementation, for more information please see the [async-hooks based ContextManager][ah-context-manager] for NodeJS. - -## 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/blob/main/LICENSE -[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat -[dependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js/status.svg?path=packages/opentelemetry-context-base -[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-context-base -[devDependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js/dev-status.svg?path=packages/opentelemetry-context-base -[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-context-base&type=dev -[ah-context-manager]: https://github.com/open-telemetry/opentelemetry-js/tree/main/packages/opentelemetry-context-async-hooks -[npm-url]: https://www.npmjs.com/package/@opentelemetry/context-base -[npm-img]: https://badge.fury.io/js/%40opentelemetry%2Fcontext-base.svg diff --git a/packages/opentelemetry-context-base/package.json b/packages/opentelemetry-context-base/package.json deleted file mode 100644 index ff3cbe3ce5c..00000000000 --- a/packages/opentelemetry-context-base/package.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "name": "@opentelemetry/context-base", - "version": "0.17.0", - "description": "OpenTelemetry Base Context Manager", - "main": "build/src/index.js", - "types": "build/src/index.d.ts", - "repository": "open-telemetry/opentelemetry-js", - "scripts": { - "compile": "tsc --build", - "clean": "tsc --build --clean", - "test": "nyc ts-mocha -p tsconfig.json 'test/**/*.test.ts'", - "tdd": "npm run test -- --watch-extensions ts --watch", - "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" - }, - "keywords": [ - "opentelemetry", - "nodejs", - "browser", - "tracing", - "profiling", - "metrics", - "stats" - ], - "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" - ], - "publishConfig": { - "access": "public" - }, - "devDependencies": { - "@types/mocha": "8.2.0", - "@types/node": "14.14.20", - "codecov": "3.8.1", - "gts": "3.1.0", - "mocha": "7.2.0", - "nyc": "15.1.0", - "rimraf": "3.0.2", - "ts-mocha": "8.0.0", - "ts-node": "9.1.1", - "typescript": "4.1.3" - } -} diff --git a/packages/opentelemetry-context-base/src/NoopContextManager.ts b/packages/opentelemetry-context-base/src/NoopContextManager.ts deleted file mode 100644 index 54589a06245..00000000000 --- a/packages/opentelemetry-context-base/src/NoopContextManager.ts +++ /dev/null @@ -1,45 +0,0 @@ -/* - * 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 { ROOT_CONTEXT } from './context'; -import * as types from './types'; - -export class NoopContextManager implements types.ContextManager { - active(): types.Context { - return ROOT_CONTEXT; - } - - with ReturnType>( - _context: types.Context, - fn: F, - thisArg?: ThisParameterType, - ...args: A - ): ReturnType { - return fn.call(thisArg, ...args); - } - - bind(target: T, _context?: types.Context): T { - return target; - } - - enable(): this { - return this; - } - - disable(): this { - return this; - } -} diff --git a/packages/opentelemetry-context-base/src/context.ts b/packages/opentelemetry-context-base/src/context.ts deleted file mode 100644 index 3010e4409fd..00000000000 --- a/packages/opentelemetry-context-base/src/context.ts +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { Context } from './types'; - -export class BaseContext implements Context { - private _currentContext: Map; - - /** - * Construct a new context which inherits values from an optional parent context. - * - * @param parentContext a context from which to inherit values - */ - constructor(parentContext?: Map) { - this._currentContext = parentContext ? new Map(parentContext) : new Map(); - } - - /** - * Get a value from the context. - * - * @param key key which identifies a context value - */ - getValue(key: symbol): unknown { - return this._currentContext.get(key); - } - - /** - * Create a new context which inherits from this context and has - * the given key set to the given value. - * - * @param key context key for which to set the value - * @param value value to set for the given key - */ - setValue(key: symbol, value: unknown): Context { - const context = new BaseContext(this._currentContext); - context._currentContext.set(key, value); - return context; - } - - /** - * Return a new context which inherits from this context but does - * not contain a value for the given key. - * - * @param key context key for which to clear a value - */ - deleteValue(key: symbol): Context { - const context = new BaseContext(this._currentContext); - context._currentContext.delete(key); - return context; - } -} - -/** The root context is used as the default parent context when there is no active context */ -export const ROOT_CONTEXT: Context = new BaseContext(); - -/** Get a key to uniquely identify a context value */ -export function createContextKey(description: string) { - return Symbol.for(description); -} diff --git a/packages/opentelemetry-context-base/src/index.ts b/packages/opentelemetry-context-base/src/index.ts deleted file mode 100644 index 0957a63910e..00000000000 --- a/packages/opentelemetry-context-base/src/index.ts +++ /dev/null @@ -1,19 +0,0 @@ -/* - * 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 { createContextKey, ROOT_CONTEXT } from './context'; -export * from './NoopContextManager'; -export * from './types'; diff --git a/packages/opentelemetry-context-base/src/types.ts b/packages/opentelemetry-context-base/src/types.ts deleted file mode 100644 index af7a1ee15db..00000000000 --- a/packages/opentelemetry-context-base/src/types.ts +++ /dev/null @@ -1,79 +0,0 @@ -/* - * 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 interface Context { - /** - * Get a value from the context. - * - * @param key key which identifies a context value - */ - getValue(key: symbol): unknown; - - /** - * Create a new context which inherits from this context and has - * the given key set to the given value. - * - * @param key context key for which to set the value - * @param value value to set for the given key - */ - setValue(key: symbol, value: unknown): Context; - - /** - * Return a new context which inherits from this context but does - * not contain a value for the given key. - * - * @param key context key for which to clear a value - */ - deleteValue(key: symbol): Context; -} - -export interface ContextManager { - /** - * Get the current active context - */ - active(): Context; - - /** - * Run the fn callback with object set as the current active context - * @param context Any object to set as the current active context - * @param fn A callback to be immediately run within a specific context - * @param thisArg optional receiver to be used for calling fn - * @param args optional arguments forwarded to fn - */ - with ReturnType>( - context: Context, - fn: F, - thisArg?: ThisParameterType, - ...args: A - ): ReturnType; - - /** - * Bind an object as the current context (or a specific one) - * @param target Any object to which a context need to be set - * @param [context] Optionally specify the context which you want to assign - */ - bind(target: T, context?: Context): T; - - /** - * Enable context management - */ - enable(): this; - - /** - * Disable context management - */ - disable(): this; -} diff --git a/packages/opentelemetry-context-base/src/version.ts b/packages/opentelemetry-context-base/src/version.ts deleted file mode 100644 index 2544b647a56..00000000000 --- a/packages/opentelemetry-context-base/src/version.ts +++ /dev/null @@ -1,18 +0,0 @@ -/* - * 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.17.0'; diff --git a/packages/opentelemetry-context-base/test/NoopContextManager.test.ts b/packages/opentelemetry-context-base/test/NoopContextManager.test.ts deleted file mode 100644 index 5528735adc9..00000000000 --- a/packages/opentelemetry-context-base/test/NoopContextManager.test.ts +++ /dev/null @@ -1,132 +0,0 @@ -/* - * 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 { NoopContextManager, ROOT_CONTEXT } from '../src'; -import { createContextKey } from '../src/context'; - -describe('NoopContextManager', () => { - let contextManager: NoopContextManager; - - describe('.enable()', () => { - it('should work', () => { - assert.doesNotThrow(() => { - contextManager = new NoopContextManager(); - assert( - contextManager.enable() === contextManager, - 'should return this' - ); - }); - }); - }); - - describe('.disable()', () => { - it('should work', () => { - assert.doesNotThrow(() => { - assert( - contextManager.disable() === contextManager, - 'should return this' - ); - }); - contextManager.enable(); - }); - }); - - describe('.with()', () => { - it('should run the callback (ROOT_CONTEXT as target)', done => { - contextManager.with(ROOT_CONTEXT, done); - }); - - it('should run the callback (object as target)', done => { - const key = createContextKey('test key 1'); - const test = ROOT_CONTEXT.setValue(key, 1); - contextManager.with(test, () => { - assert.strictEqual( - contextManager.active(), - ROOT_CONTEXT, - 'should not have context' - ); - return done(); - }); - }); - - it('should run the callback (when disabled)', done => { - contextManager.disable(); - contextManager.with(ROOT_CONTEXT, () => { - contextManager.enable(); - return done(); - }); - }); - - it('should forward this, arguments and return value', () => { - function fnWithThis(this: string, a: string, b: number): string { - assert.strictEqual(this, 'that'); - assert.strictEqual(arguments.length, 2); - assert.strictEqual(a, 'one'); - assert.strictEqual(b, 2); - return 'done'; - } - - const res = contextManager.with( - ROOT_CONTEXT, - fnWithThis, - 'that', - 'one', - 2 - ); - assert.strictEqual(res, 'done'); - - assert.strictEqual( - contextManager.with(ROOT_CONTEXT, () => 3.14), - 3.14 - ); - }); - }); - - describe('.active()', () => { - it('should always return ROOT_CONTEXT (when enabled)', () => { - assert.strictEqual( - contextManager.active(), - ROOT_CONTEXT, - 'should not have context' - ); - }); - - it('should always return ROOT_CONTEXT (when disabled)', () => { - contextManager.disable(); - assert.strictEqual( - contextManager.active(), - ROOT_CONTEXT, - 'should not have context' - ); - contextManager.enable(); - }); - }); - - describe('.bind()', () => { - it('should return the same target (when enabled)', () => { - const test = { a: 1 }; - assert.deepStrictEqual(contextManager.bind(test), test); - }); - - it('should return the same target (when disabled)', () => { - contextManager.disable(); - const test = { a: 1 }; - assert.deepStrictEqual(contextManager.bind(test), test); - contextManager.enable(); - }); - }); -}); diff --git a/packages/opentelemetry-context-base/tsconfig.json b/packages/opentelemetry-context-base/tsconfig.json deleted file mode 100644 index b8d88215e40..00000000000 --- a/packages/opentelemetry-context-base/tsconfig.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "extends": "../../tsconfig.es5.json", - "compilerOptions": { - "rootDir": ".", - "outDir": "build" - }, - "include": [ - "src/**/*.ts", - "test/**/*.ts" - ] -} diff --git a/packages/opentelemetry-context-zone-peer-dep/package.json b/packages/opentelemetry-context-zone-peer-dep/package.json index b21698246f9..63885372990 100644 --- a/packages/opentelemetry-context-zone-peer-dep/package.json +++ b/packages/opentelemetry-context-zone-peer-dep/package.json @@ -70,7 +70,7 @@ "zone.js": "0.11.3" }, "dependencies": { - "@opentelemetry/context-base": "^0.17.0" + "@opentelemetry/api": "^0.18.0" }, "peerDependencies": { "zone.js": "^0.10.2 || ^0.11.0" diff --git a/packages/opentelemetry-context-zone-peer-dep/src/ZoneContextManager.ts b/packages/opentelemetry-context-zone-peer-dep/src/ZoneContextManager.ts index b04a27247ad..edd5a0719e5 100644 --- a/packages/opentelemetry-context-zone-peer-dep/src/ZoneContextManager.ts +++ b/packages/opentelemetry-context-zone-peer-dep/src/ZoneContextManager.ts @@ -14,11 +14,7 @@ * limitations under the License. */ -import { - Context, - ContextManager, - ROOT_CONTEXT, -} from '@opentelemetry/context-base'; +import { Context, ContextManager, ROOT_CONTEXT } from '@opentelemetry/api'; import { Func, TargetWithEvents } from './types'; import { isListenerObject } from './util'; diff --git a/packages/opentelemetry-context-zone-peer-dep/test/ZoneContextManager.test.ts b/packages/opentelemetry-context-zone-peer-dep/test/ZoneContextManager.test.ts index b1f053ccdd1..43aba94e175 100644 --- a/packages/opentelemetry-context-zone-peer-dep/test/ZoneContextManager.test.ts +++ b/packages/opentelemetry-context-zone-peer-dep/test/ZoneContextManager.test.ts @@ -18,7 +18,7 @@ import 'zone.js'; import * as sinon from 'sinon'; import * as assert from 'assert'; import { ZoneContextManager } from '../src'; -import { ROOT_CONTEXT, createContextKey } from '@opentelemetry/context-base'; +import { ROOT_CONTEXT, createContextKey } from '@opentelemetry/api'; let clock: any; diff --git a/packages/opentelemetry-context-zone-peer-dep/tsconfig.json b/packages/opentelemetry-context-zone-peer-dep/tsconfig.json index 2e7c26e39c2..479d4bc0d2e 100644 --- a/packages/opentelemetry-context-zone-peer-dep/tsconfig.json +++ b/packages/opentelemetry-context-zone-peer-dep/tsconfig.json @@ -11,10 +11,5 @@ "include": [ "src/**/*.ts", "test/**/*.ts" - ], - "references": [ - { - "path": "../opentelemetry-context-base" - } ] } diff --git a/packages/opentelemetry-core/package.json b/packages/opentelemetry-core/package.json index c1711837b67..d88d6fcc269 100644 --- a/packages/opentelemetry-core/package.json +++ b/packages/opentelemetry-core/package.json @@ -76,8 +76,7 @@ "webpack": "4.46.0" }, "dependencies": { - "@opentelemetry/api": "^0.17.0", - "@opentelemetry/context-base": "^0.17.0", + "@opentelemetry/api": "^0.18.0", "semver": "^7.1.3" } } diff --git a/packages/opentelemetry-core/test/baggage/HttpBaggage.test.ts b/packages/opentelemetry-core/test/baggage/HttpBaggage.test.ts index e7231cac22b..464be7c2c9a 100644 --- a/packages/opentelemetry-core/test/baggage/HttpBaggage.test.ts +++ b/packages/opentelemetry-core/test/baggage/HttpBaggage.test.ts @@ -23,7 +23,7 @@ import { getBaggage, setBaggage, } from '@opentelemetry/api'; -import { ROOT_CONTEXT } from '@opentelemetry/context-base'; +import { ROOT_CONTEXT } from '@opentelemetry/api'; import * as assert from 'assert'; import { BAGGAGE_HEADER, diff --git a/packages/opentelemetry-core/test/common/time.test.ts b/packages/opentelemetry-core/test/common/time.test.ts index 8cbe355c4a1..a8c284b9b04 100644 --- a/packages/opentelemetry-core/test/common/time.test.ts +++ b/packages/opentelemetry-core/test/common/time.test.ts @@ -30,27 +30,21 @@ import { } from '../../src/common/time'; describe('time', () => { - let sandbox: sinon.SinonSandbox; - - beforeEach(() => { - sandbox = sinon.createSandbox(); - }); - afterEach(() => { - sandbox.restore(); + sinon.restore(); }); describe('#hrTime', () => { it('should return hrtime now', () => { - sandbox.stub(performance, 'timeOrigin').value(11.5); - sandbox.stub(performance, 'now').callsFake(() => 11.3); + sinon.stub(performance, 'timeOrigin').value(11.5); + sinon.stub(performance, 'now').callsFake(() => 11.3); const output = hrTime(); assert.deepStrictEqual(output, [0, 22800000]); }); it('should convert performance now', () => { - sandbox.stub(performance, 'timeOrigin').value(11.5); + sinon.stub(performance, 'timeOrigin').value(11.5); const performanceNow = 11.3; const output = hrTime(performanceNow); @@ -58,7 +52,7 @@ describe('time', () => { }); it('should handle nanosecond overflow', () => { - sandbox.stub(performance, 'timeOrigin').value(11.5); + sinon.stub(performance, 'timeOrigin').value(11.5); const performanceNow = 11.6; const output = hrTime(performanceNow); @@ -66,24 +60,24 @@ describe('time', () => { }); it('should allow passed "performanceNow" equal to 0', () => { - sandbox.stub(performance, 'timeOrigin').value(11.5); - sandbox.stub(performance, 'now').callsFake(() => 11.3); + sinon.stub(performance, 'timeOrigin').value(11.5); + sinon.stub(performance, 'now').callsFake(() => 11.3); const output = hrTime(0); assert.deepStrictEqual(output, [0, 11500000]); }); it('should use performance.now() when "performanceNow" is equal to undefined', () => { - sandbox.stub(performance, 'timeOrigin').value(11.5); - sandbox.stub(performance, 'now').callsFake(() => 11.3); + sinon.stub(performance, 'timeOrigin').value(11.5); + sinon.stub(performance, 'now').callsFake(() => 11.3); const output = hrTime(undefined); assert.deepStrictEqual(output, [0, 22800000]); }); it('should use performance.now() when "performanceNow" is equal to null', () => { - sandbox.stub(performance, 'timeOrigin').value(11.5); - sandbox.stub(performance, 'now').callsFake(() => 11.3); + sinon.stub(performance, 'timeOrigin').value(11.5); + sinon.stub(performance, 'now').callsFake(() => 11.3); const output = hrTime(null as any); assert.deepStrictEqual(output, [0, 22800000]); @@ -98,8 +92,8 @@ describe('time', () => { }, }); - sandbox.stub(performance, 'timeOrigin').value(undefined); - sandbox.stub(performance, 'now').callsFake(() => 11.3); + sinon.stub(performance, 'timeOrigin').value(undefined); + sinon.stub(performance, 'now').callsFake(() => 11.3); const output = hrTime(); assert.deepStrictEqual(output, [0, 22800000]); @@ -121,7 +115,7 @@ describe('time', () => { }); it('should convert performance.now() hrTime', () => { - sandbox.stub(performance, 'timeOrigin').value(111.5); + sinon.stub(performance, 'timeOrigin').value(111.5); const timeInput = 11.9; const output = timeInputToHrTime(timeInput); @@ -130,7 +124,7 @@ describe('time', () => { }); it('should not convert hrtime hrTime', () => { - sandbox.stub(performance, 'timeOrigin').value(111.5); + sinon.stub(performance, 'timeOrigin').value(111.5); const timeInput: [number, number] = [3138971, 245466222]; const output = timeInputToHrTime(timeInput); diff --git a/packages/opentelemetry-core/test/context/HttpTraceContext.test.ts b/packages/opentelemetry-core/test/context/HttpTraceContext.test.ts index d37e7f26c2c..a732a471f90 100644 --- a/packages/opentelemetry-core/test/context/HttpTraceContext.test.ts +++ b/packages/opentelemetry-core/test/context/HttpTraceContext.test.ts @@ -22,7 +22,7 @@ import { getSpanContext, setSpanContext, } from '@opentelemetry/api'; -import { ROOT_CONTEXT } from '@opentelemetry/context-base'; +import { ROOT_CONTEXT } from '@opentelemetry/api'; import * as assert from 'assert'; import { HttpTraceContext, diff --git a/packages/opentelemetry-core/test/context/composite.test.ts b/packages/opentelemetry-core/test/context/composite.test.ts index 94520fb80b2..52114aeeb98 100644 --- a/packages/opentelemetry-core/test/context/composite.test.ts +++ b/packages/opentelemetry-core/test/context/composite.test.ts @@ -22,7 +22,7 @@ import { getSpanContext, setSpanContext, } from '@opentelemetry/api'; -import { Context, ROOT_CONTEXT } from '@opentelemetry/context-base'; +import { Context, ROOT_CONTEXT } from '@opentelemetry/api'; import * as assert from 'assert'; import { CompositePropagator, diff --git a/packages/opentelemetry-core/test/utils/environment.test.ts b/packages/opentelemetry-core/test/utils/environment.test.ts index 7071b197751..38cd58a8f62 100644 --- a/packages/opentelemetry-core/test/utils/environment.test.ts +++ b/packages/opentelemetry-core/test/utils/environment.test.ts @@ -59,15 +59,9 @@ export function removeMockEnvironment() { } describe('environment', () => { - let sandbox: sinon.SinonSandbox; - - beforeEach(() => { - sandbox = sinon.createSandbox(); - }); - afterEach(() => { removeMockEnvironment(); - sandbox.restore(); + sinon.restore(); }); describe('parseEnvironment', () => { diff --git a/packages/opentelemetry-core/tsconfig.json b/packages/opentelemetry-core/tsconfig.json index 838b29bc26a..62f7aed99b7 100644 --- a/packages/opentelemetry-core/tsconfig.json +++ b/packages/opentelemetry-core/tsconfig.json @@ -9,12 +9,6 @@ "test/**/*.ts" ], "references": [ - { - "path": "../opentelemetry-api" - }, - { - "path": "../opentelemetry-context-base" - }, { "path": "../opentelemetry-propagator-b3" } diff --git a/packages/opentelemetry-exporter-collector-grpc/package.json b/packages/opentelemetry-exporter-collector-grpc/package.json index cf5b2fb952e..a0bb4edf6a8 100644 --- a/packages/opentelemetry-exporter-collector-grpc/package.json +++ b/packages/opentelemetry-exporter-collector-grpc/package.json @@ -64,7 +64,7 @@ }, "dependencies": { "@grpc/proto-loader": "^0.5.4", - "@opentelemetry/api": "^0.17.0", + "@opentelemetry/api": "^0.18.0", "@opentelemetry/core": "^0.17.0", "@opentelemetry/exporter-collector": "^0.17.0", "@opentelemetry/metrics": "^0.17.0", diff --git a/packages/opentelemetry-exporter-collector-grpc/test/CollectorMetricExporter.test.ts b/packages/opentelemetry-exporter-collector-grpc/test/CollectorMetricExporter.test.ts index 5a68d992d13..7f2a45f51a4 100644 --- a/packages/opentelemetry-exporter-collector-grpc/test/CollectorMetricExporter.test.ts +++ b/packages/opentelemetry-exporter-collector-grpc/test/CollectorMetricExporter.test.ts @@ -120,8 +120,6 @@ const testCollectorMetricExporter = (params: TestParams) => }); beforeEach(async () => { - // Set no logger so that sinon doesn't complain about TypeError: Attempted to wrap xxxx which is already wrapped - diag.setLogger(); const credentials = params.useTLS ? grpc.credentials.createSsl( fs.readFileSync('./test/certs/ca.crt'), @@ -162,12 +160,13 @@ const testCollectorMetricExporter = (params: TestParams) => afterEach(() => { exportedData = undefined; reqMetadata = undefined; + sinon.restore(); }); describe('instance', () => { it('should warn about headers', () => { // Need to stub/spy on the underlying logger as the "diag" instance is global - const spyLoggerWarn = sinon.stub(diag.getLogger(), 'warn'); + const spyLoggerWarn = sinon.stub(diag, 'warn'); collectorExporter = new CollectorMetricExporter({ serviceName: 'basic-service', url: address, diff --git a/packages/opentelemetry-exporter-collector-grpc/test/CollectorTraceExporter.test.ts b/packages/opentelemetry-exporter-collector-grpc/test/CollectorTraceExporter.test.ts index d3bed83ef48..36c752ea189 100644 --- a/packages/opentelemetry-exporter-collector-grpc/test/CollectorTraceExporter.test.ts +++ b/packages/opentelemetry-exporter-collector-grpc/test/CollectorTraceExporter.test.ts @@ -115,8 +115,6 @@ const testCollectorExporter = (params: TestParams) => }); beforeEach(done => { - // Set no logger so that sinon doesn't complain about TypeError: Attempted to wrap xxxx which is already wrapped - diag.setLogger(); const credentials = params.useTLS ? grpc.credentials.createSsl( fs.readFileSync('./test/certs/ca.crt'), @@ -139,12 +137,13 @@ const testCollectorExporter = (params: TestParams) => afterEach(() => { exportedData = undefined; reqMetadata = undefined; + sinon.restore(); }); describe('instance', () => { it('should warn about headers when using grpc', () => { // Need to stub/spy on the underlying logger as the "diag" instance is global - const spyLoggerWarn = sinon.stub(diag.getLogger(), 'warn'); + const spyLoggerWarn = sinon.stub(diag, 'warn'); collectorExporter = new CollectorTraceExporter({ serviceName: 'basic-service', url: address, diff --git a/packages/opentelemetry-exporter-collector-grpc/test/helper.ts b/packages/opentelemetry-exporter-collector-grpc/test/helper.ts index 049697892a4..607a8ad7292 100644 --- a/packages/opentelemetry-exporter-collector-grpc/test/helper.ts +++ b/packages/opentelemetry-exporter-collector-grpc/test/helper.ts @@ -422,8 +422,8 @@ export function ensureResourceIsCorrect( { key: 'version', value: { - doubleValue: 1, - value: 'doubleValue', + intValue: '1', + value: 'intValue', }, }, { diff --git a/packages/opentelemetry-exporter-collector-grpc/tsconfig.json b/packages/opentelemetry-exporter-collector-grpc/tsconfig.json index 1e107c066b5..15f3cc9624b 100644 --- a/packages/opentelemetry-exporter-collector-grpc/tsconfig.json +++ b/packages/opentelemetry-exporter-collector-grpc/tsconfig.json @@ -9,9 +9,6 @@ "test/**/*.ts" ], "references": [ - { - "path": "../opentelemetry-api" - }, { "path": "../opentelemetry-api-metrics" }, diff --git a/packages/opentelemetry-exporter-collector-proto/package.json b/packages/opentelemetry-exporter-collector-proto/package.json index 3494fd1c1b3..517a54a79f9 100644 --- a/packages/opentelemetry-exporter-collector-proto/package.json +++ b/packages/opentelemetry-exporter-collector-proto/package.json @@ -64,7 +64,7 @@ }, "dependencies": { "@grpc/proto-loader": "^0.5.4", - "@opentelemetry/api": "^0.17.0", + "@opentelemetry/api": "^0.18.0", "@opentelemetry/core": "^0.17.0", "@opentelemetry/exporter-collector": "^0.17.0", "@opentelemetry/metrics": "^0.17.0", diff --git a/packages/opentelemetry-exporter-collector-proto/test/CollectorMetricExporter.test.ts b/packages/opentelemetry-exporter-collector-proto/test/CollectorMetricExporter.test.ts index a8ec25d27a4..13fede22c51 100644 --- a/packages/opentelemetry-exporter-collector-proto/test/CollectorMetricExporter.test.ts +++ b/packages/opentelemetry-exporter-collector-proto/test/CollectorMetricExporter.test.ts @@ -55,8 +55,6 @@ describe('CollectorMetricExporter - node with proto over http', () => { describe('export', () => { beforeEach(async () => { - // Set no logger so that sinon doesn't complain about TypeError: Attempted to wrap xxxx which is already wrapped - diag.setLogger(); collectorExporterConfig = { headers: { foo: 'bar', @@ -177,7 +175,7 @@ describe('CollectorMetricExporter - node with proto over http', () => { it('should log the successful message', done => { // Need to stub/spy on the underlying logger as the "diag" instance is global - const spyLoggerError = sinon.stub(diag.getLogger(), 'error'); + const spyLoggerError = sinon.stub(diag, 'error'); collectorExporter.export(metrics, result => { assert.strictEqual(result.code, ExportResultCode.SUCCESS); diff --git a/packages/opentelemetry-exporter-collector-proto/test/CollectorTraceExporter.test.ts b/packages/opentelemetry-exporter-collector-proto/test/CollectorTraceExporter.test.ts index 85a841025cd..a826fa6ddfd 100644 --- a/packages/opentelemetry-exporter-collector-proto/test/CollectorTraceExporter.test.ts +++ b/packages/opentelemetry-exporter-collector-proto/test/CollectorTraceExporter.test.ts @@ -46,8 +46,6 @@ describe('CollectorTraceExporter - node with proto over http', () => { describe('export', () => { beforeEach(() => { - // Set no logger so that sinon doesn't complain about TypeError: Attempted to wrap xxxx which is already wrapped - diag.setLogger(); collectorExporterConfig = { headers: { foo: 'bar', @@ -126,7 +124,7 @@ describe('CollectorTraceExporter - node with proto over http', () => { it('should log the successful message', done => { // Need to stub/spy on the underlying logger as the "diag" instance is global - const spyLoggerError = sinon.stub(diag.getLogger(), 'error'); + const spyLoggerError = sinon.stub(diag, 'error'); collectorExporter.export(spans, result => { assert.strictEqual(result.code, ExportResultCode.SUCCESS); diff --git a/packages/opentelemetry-exporter-collector-proto/tsconfig.json b/packages/opentelemetry-exporter-collector-proto/tsconfig.json index 1e107c066b5..15f3cc9624b 100644 --- a/packages/opentelemetry-exporter-collector-proto/tsconfig.json +++ b/packages/opentelemetry-exporter-collector-proto/tsconfig.json @@ -9,9 +9,6 @@ "test/**/*.ts" ], "references": [ - { - "path": "../opentelemetry-api" - }, { "path": "../opentelemetry-api-metrics" }, diff --git a/packages/opentelemetry-exporter-collector/package.json b/packages/opentelemetry-exporter-collector/package.json index c4697ecc218..a95d7c886a6 100644 --- a/packages/opentelemetry-exporter-collector/package.json +++ b/packages/opentelemetry-exporter-collector/package.json @@ -77,7 +77,7 @@ "webpack-merge": "5.7.3" }, "dependencies": { - "@opentelemetry/api": "^0.17.0", + "@opentelemetry/api": "^0.18.0", "@opentelemetry/api-metrics": "^0.17.0", "@opentelemetry/core": "^0.17.0", "@opentelemetry/metrics": "^0.17.0", diff --git a/packages/opentelemetry-exporter-collector/src/transform.ts b/packages/opentelemetry-exporter-collector/src/transform.ts index bdaaaa2290a..7080713ff77 100644 --- a/packages/opentelemetry-exporter-collector/src/transform.ts +++ b/packages/opentelemetry-exporter-collector/src/transform.ts @@ -32,6 +32,9 @@ import { CollectorExporterConfigBase, } from './types'; +const MAX_INTEGER_VALUE = 2147483647; +const MIN_INTEGER_VALUE = -2147483648; + /** * Converts attributes to KeyValue array * @param attributes @@ -95,8 +98,14 @@ export function toCollectorAnyValue( anyValue.stringValue = value; } else if (typeof value === 'boolean') { anyValue.boolValue = value; + } else if ( + typeof value === 'number' && + value <= MAX_INTEGER_VALUE && + value >= MIN_INTEGER_VALUE && + Number.isInteger(value) + ) { + anyValue.intValue = value; } else if (typeof value === 'number') { - // all numbers will be treated as double anyValue.doubleValue = value; } else if (Array.isArray(value)) { anyValue.arrayValue = toCollectorArrayValue(value); diff --git a/packages/opentelemetry-exporter-collector/test/browser/CollectorMetricExporter.test.ts b/packages/opentelemetry-exporter-collector/test/browser/CollectorMetricExporter.test.ts index 160aa7e3a64..2213028b9d9 100644 --- a/packages/opentelemetry-exporter-collector/test/browser/CollectorMetricExporter.test.ts +++ b/packages/opentelemetry-exporter-collector/test/browser/CollectorMetricExporter.test.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import { diag, DiagLogLevel } from '@opentelemetry/api'; +import { diag } from '@opentelemetry/api'; import { Counter, ValueObserver, @@ -45,19 +45,16 @@ import { mockValueRecorder, } from '../helper'; -const sendBeacon = navigator.sendBeacon; - describe('CollectorMetricExporter - web', () => { let collectorExporter: CollectorMetricExporter; - let spyOpen: any; - let spySend: any; - let spyBeacon: any; + let stubOpen: sinon.SinonStub; + let stubBeacon: sinon.SinonStub; let metrics: MetricRecord[]; beforeEach(async () => { - spyOpen = sinon.stub(XMLHttpRequest.prototype, 'open'); - spySend = sinon.stub(XMLHttpRequest.prototype, 'send'); - spyBeacon = sinon.stub(navigator, 'sendBeacon'); + stubOpen = sinon.stub(XMLHttpRequest.prototype, 'open'); + sinon.stub(XMLHttpRequest.prototype, 'send'); + stubBeacon = sinon.stub(navigator, 'sendBeacon'); metrics = []; const counter: Metric & Counter = mockCounter(); const observer: Metric & ValueObserver = mockObserver( @@ -79,18 +76,12 @@ describe('CollectorMetricExporter - web', () => { }); afterEach(() => { - navigator.sendBeacon = sendBeacon; - spyOpen.restore(); - spySend.restore(); - spyBeacon.restore(); + sinon.restore(); }); describe('export', () => { describe('when "sendBeacon" is available', () => { beforeEach(() => { - // Set no logger so that sinon doesn't complain about TypeError: Attempted to wrap xxxx which is already wrapped - diag.setLogger(); - diag.setLogLevel(DiagLogLevel.VERBOSE); collectorExporter = new CollectorMetricExporter({ url: 'http://foo.bar.com', serviceName: 'bar', @@ -104,7 +95,7 @@ describe('CollectorMetricExporter - web', () => { collectorExporter.export(metrics, () => {}); setTimeout(() => { - const args = spyBeacon.args[0]; + const args = stubBeacon.args[0]; const url = args[0]; const body = args[1]; const json = JSON.parse( @@ -158,9 +149,9 @@ describe('CollectorMetricExporter - web', () => { } assert.strictEqual(url, 'http://foo.bar.com'); - assert.strictEqual(spyBeacon.callCount, 1); + assert.strictEqual(stubBeacon.callCount, 1); - assert.strictEqual(spyOpen.callCount, 0); + assert.strictEqual(stubOpen.callCount, 0); ensureExportMetricsServiceRequestIsSet(json); @@ -170,10 +161,9 @@ describe('CollectorMetricExporter - web', () => { it('should log the successful message', done => { // Need to stub/spy on the underlying logger as the "diag" instance is global - const spyLoggerDebug = sinon.stub(diag.getLogger(), 'debug'); - const spyLoggerError = sinon.stub(diag.getLogger(), 'error'); - spyBeacon.restore(); - spyBeacon = sinon.stub(window.navigator, 'sendBeacon').returns(true); + const spyLoggerDebug = sinon.stub(diag, 'debug'); + const spyLoggerError = sinon.stub(diag, 'error'); + stubBeacon.returns(true); collectorExporter.export(metrics, () => {}); @@ -187,8 +177,7 @@ describe('CollectorMetricExporter - web', () => { }); it('should log the error message', done => { - spyBeacon.restore(); - spyBeacon = sinon.stub(window.navigator, 'sendBeacon').returns(false); + stubBeacon.returns(false); collectorExporter.export(metrics, result => { assert.deepStrictEqual(result.code, ExportResultCode.FAILED); @@ -201,9 +190,6 @@ describe('CollectorMetricExporter - web', () => { describe('when "sendBeacon" is NOT available', () => { let server: any; beforeEach(() => { - // Set no logger so that sinon doesn't complain about TypeError: Attempted to wrap xxxx which is already wrapped - diag.setLogger(); - diag.setLogLevel(DiagLogLevel.VERBOSE); (window.navigator as any).sendBeacon = false; collectorExporter = new CollectorMetricExporter({ url: 'http://foo.bar.com', @@ -276,7 +262,7 @@ describe('CollectorMetricExporter - web', () => { ensureWebResourceIsCorrect(resource); } - assert.strictEqual(spyBeacon.callCount, 0); + assert.strictEqual(stubBeacon.callCount, 0); ensureExportMetricsServiceRequestIsSet(json); done(); @@ -285,8 +271,8 @@ describe('CollectorMetricExporter - web', () => { it('should log the successful message', done => { // Need to stub/spy on the underlying logger as the "diag" instance is global - const spyLoggerDebug = sinon.stub(diag.getLogger(), 'debug'); - const spyLoggerError = sinon.stub(diag.getLogger(), 'error'); + const spyLoggerDebug = sinon.stub(diag, 'debug'); + const spyLoggerError = sinon.stub(diag, 'error'); collectorExporter.export(metrics, () => {}); @@ -298,7 +284,7 @@ describe('CollectorMetricExporter - web', () => { assert.strictEqual(response, 'xhr success'); assert.strictEqual(spyLoggerError.args.length, 0); - assert.strictEqual(spyBeacon.callCount, 0); + assert.strictEqual(stubBeacon.callCount, 0); done(); }); }); @@ -307,7 +293,7 @@ describe('CollectorMetricExporter - web', () => { collectorExporter.export(metrics, result => { assert.deepStrictEqual(result.code, ExportResultCode.FAILED); assert.ok(result.error?.message.includes('Failed to export')); - assert.strictEqual(spyBeacon.callCount, 0); + assert.strictEqual(stubBeacon.callCount, 0); done(); }); @@ -323,7 +309,7 @@ describe('CollectorMetricExporter - web', () => { const request = server.requests[0]; request.respond(200); - assert.strictEqual(spyBeacon.callCount, 0); + assert.strictEqual(stubBeacon.callCount, 0); done(); }); }); @@ -339,9 +325,6 @@ describe('CollectorMetricExporter - web', () => { let collectorExporterConfig: CollectorExporterConfigBase; beforeEach(() => { - // Set no logger so that sinon doesn't complain about TypeError: Attempted to wrap xxxx which is already wrapped - diag.setLogger(); - diag.setLogLevel(DiagLogLevel.VERBOSE); collectorExporterConfig = { headers: customHeaders, }; @@ -365,8 +348,8 @@ describe('CollectorMetricExporter - web', () => { const [{ requestHeaders }] = server.requests; ensureHeadersContain(requestHeaders, customHeaders); - assert.strictEqual(spyBeacon.callCount, 0); - assert.strictEqual(spyOpen.callCount, 0); + assert.strictEqual(stubBeacon.callCount, 0); + assert.strictEqual(stubOpen.callCount, 0); done(); }); @@ -388,8 +371,8 @@ describe('CollectorMetricExporter - web', () => { const [{ requestHeaders }] = server.requests; ensureHeadersContain(requestHeaders, customHeaders); - assert.strictEqual(spyBeacon.callCount, 0); - assert.strictEqual(spyOpen.callCount, 0); + assert.strictEqual(stubBeacon.callCount, 0); + assert.strictEqual(stubOpen.callCount, 0); done(); }); diff --git a/packages/opentelemetry-exporter-collector/test/browser/CollectorTraceExporter.test.ts b/packages/opentelemetry-exporter-collector/test/browser/CollectorTraceExporter.test.ts index ec61e8b98c7..2c02f751cb8 100644 --- a/packages/opentelemetry-exporter-collector/test/browser/CollectorTraceExporter.test.ts +++ b/packages/opentelemetry-exporter-collector/test/browser/CollectorTraceExporter.test.ts @@ -14,7 +14,7 @@ * limitations under the License. */ -import { diag, DiagLogLevel } from '@opentelemetry/api'; +import { diag } from '@opentelemetry/api'; import { ExportResultCode } from '@opentelemetry/core'; import { ReadableSpan } from '@opentelemetry/tracing'; import * as assert from 'assert'; @@ -30,36 +30,28 @@ import { ensureHeadersContain, mockedReadableSpan, } from '../helper'; -const sendBeacon = navigator.sendBeacon; describe('CollectorTraceExporter - web', () => { let collectorTraceExporter: CollectorTraceExporter; let collectorExporterConfig: CollectorExporterConfigBase; - let spyOpen: sinon.SinonSpy; - let spySend: sinon.SinonSpy; - let spyBeacon: sinon.SinonSpy; + let stubOpen: sinon.SinonStub; + let stubBeacon: sinon.SinonStub; let spans: ReadableSpan[]; beforeEach(() => { - spyOpen = sinon.stub(XMLHttpRequest.prototype, 'open'); - spySend = sinon.stub(XMLHttpRequest.prototype, 'send'); - spyBeacon = sinon.stub(navigator, 'sendBeacon'); + stubOpen = sinon.stub(XMLHttpRequest.prototype, 'open'); + sinon.stub(XMLHttpRequest.prototype, 'send'); + stubBeacon = sinon.stub(navigator, 'sendBeacon'); spans = []; spans.push(Object.assign({}, mockedReadableSpan)); }); afterEach(() => { - navigator.sendBeacon = sendBeacon; - spyOpen.restore(); - spySend.restore(); - spyBeacon.restore(); + sinon.restore(); }); describe('export', () => { beforeEach(() => { - // Set no logger so that sinon doesn't complain about TypeError: Attempted to wrap xxxx which is already wrapped - diag.setLogger(); - diag.setLogLevel(DiagLogLevel.VERBOSE); collectorExporterConfig = { hostname: 'foo', serviceName: 'bar', @@ -79,7 +71,7 @@ describe('CollectorTraceExporter - web', () => { collectorTraceExporter.export(spans, () => {}); setTimeout(() => { - const args = spyBeacon.args[0]; + const args = stubBeacon.args[0]; const url = args[0]; const body = args[1]; const json = JSON.parse( @@ -100,9 +92,9 @@ describe('CollectorTraceExporter - web', () => { } assert.strictEqual(url, 'http://foo.bar.com'); - assert.strictEqual(spyBeacon.callCount, 1); + assert.strictEqual(stubBeacon.callCount, 1); - assert.strictEqual(spyOpen.callCount, 0); + assert.strictEqual(stubOpen.callCount, 0); ensureExportTraceServiceRequestIsSet(json); @@ -112,10 +104,9 @@ describe('CollectorTraceExporter - web', () => { it('should log the successful message', done => { // Need to stub/spy on the underlying logger as the "diag" instance is global - const spyLoggerDebug = sinon.stub(diag.getLogger(), 'debug'); - const spyLoggerError = sinon.stub(diag.getLogger(), 'error'); - spyBeacon.restore(); - spyBeacon = sinon.stub(window.navigator, 'sendBeacon').returns(true); + const spyLoggerDebug = sinon.stub(diag, 'debug'); + const spyLoggerError = sinon.stub(diag, 'error'); + stubBeacon.returns(true); collectorTraceExporter.export(spans, () => {}); @@ -129,8 +120,7 @@ describe('CollectorTraceExporter - web', () => { }); it('should log the error message', done => { - spyBeacon.restore(); - spyBeacon = sinon.stub(window.navigator, 'sendBeacon').returns(false); + stubBeacon.returns(false); collectorTraceExporter.export(spans, result => { assert.deepStrictEqual(result.code, ExportResultCode.FAILED); @@ -179,7 +169,7 @@ describe('CollectorTraceExporter - web', () => { ensureWebResourceIsCorrect(resource); } - assert.strictEqual(spyBeacon.callCount, 0); + assert.strictEqual(stubBeacon.callCount, 0); ensureExportTraceServiceRequestIsSet(json); @@ -189,8 +179,8 @@ describe('CollectorTraceExporter - web', () => { it('should log the successful message', done => { // Need to stub/spy on the underlying logger as the "diag" instance is global - const spyLoggerDebug = sinon.stub(diag.getLogger(), 'debug'); - const spyLoggerError = sinon.stub(diag.getLogger(), 'error'); + const spyLoggerDebug = sinon.stub(diag, 'debug'); + const spyLoggerError = sinon.stub(diag, 'error'); collectorTraceExporter.export(spans, () => {}); @@ -202,7 +192,7 @@ describe('CollectorTraceExporter - web', () => { assert.strictEqual(response, 'xhr success'); assert.strictEqual(spyLoggerError.args.length, 0); - assert.strictEqual(spyBeacon.callCount, 0); + assert.strictEqual(stubBeacon.callCount, 0); done(); }); }); @@ -227,7 +217,7 @@ describe('CollectorTraceExporter - web', () => { const request = server.requests[0]; request.respond(200); - assert.strictEqual(spyBeacon.callCount, 0); + assert.strictEqual(stubBeacon.callCount, 0); done(); }); }); @@ -242,9 +232,6 @@ describe('CollectorTraceExporter - web', () => { }; beforeEach(() => { - // Set no logger so that sinon doesn't complain about TypeError: Attempted to wrap xxxx which is already wrapped - diag.setLogger(); - diag.setLogLevel(DiagLogLevel.VERBOSE); collectorExporterConfig = { headers: customHeaders, }; @@ -268,8 +255,8 @@ describe('CollectorTraceExporter - web', () => { const [{ requestHeaders }] = server.requests; ensureHeadersContain(requestHeaders, customHeaders); - assert.strictEqual(spyBeacon.callCount, 0); - assert.strictEqual(spyOpen.callCount, 0); + assert.strictEqual(stubBeacon.callCount, 0); + assert.strictEqual(stubOpen.callCount, 0); done(); }); @@ -291,8 +278,8 @@ describe('CollectorTraceExporter - web', () => { const [{ requestHeaders }] = server.requests; ensureHeadersContain(requestHeaders, customHeaders); - assert.strictEqual(spyBeacon.callCount, 0); - assert.strictEqual(spyOpen.callCount, 0); + assert.strictEqual(stubBeacon.callCount, 0); + assert.strictEqual(stubOpen.callCount, 0); done(); }); diff --git a/packages/opentelemetry-exporter-collector/test/common/CollectorMetricExporter.test.ts b/packages/opentelemetry-exporter-collector/test/common/CollectorMetricExporter.test.ts index 966483bfc1d..c455c0d1ad0 100644 --- a/packages/opentelemetry-exporter-collector/test/common/CollectorMetricExporter.test.ts +++ b/packages/opentelemetry-exporter-collector/test/common/CollectorMetricExporter.test.ts @@ -14,7 +14,6 @@ * limitations under the License. */ -import { diag } from '@opentelemetry/api'; import { Counter, ValueObserver } from '@opentelemetry/api-metrics'; import { ExportResultCode } from '@opentelemetry/core'; import { @@ -56,12 +55,15 @@ describe('CollectorMetricExporter - common', () => { let collectorExporter: CollectorMetricExporter; let collectorExporterConfig: CollectorExporterConfig; let metrics: MetricRecord[]; + + afterEach(() => { + sinon.restore(); + }); + describe('constructor', () => { let onInitSpy: any; beforeEach(async () => { - // Set no logger so that sinon doesn't complain about TypeError: Attempted to wrap xxxx which is already wrapped - diag.setLogger(); onInitSpy = sinon.stub(CollectorMetricExporter.prototype, 'onInit'); collectorExporterConfig = { hostname: 'foo', @@ -85,10 +87,6 @@ describe('CollectorMetricExporter - common', () => { metrics.push((await observer.getMetricRecord())[0]); }); - afterEach(() => { - onInitSpy.restore(); - }); - it('should create an instance', () => { assert.ok(typeof collectorExporter !== 'undefined'); }); @@ -131,9 +129,6 @@ describe('CollectorMetricExporter - common', () => { spySend = sinon.stub(CollectorMetricExporter.prototype, 'send'); collectorExporter = new CollectorMetricExporter(collectorExporterConfig); }); - afterEach(() => { - spySend.restore(); - }); it('should export metrics as collectorTypes.Metrics', done => { collectorExporter.export(metrics, () => {}); @@ -200,8 +195,6 @@ describe('CollectorMetricExporter - common', () => { describe('shutdown', () => { let onShutdownSpy: any; beforeEach(() => { - // Set no logger so that sinon doesn't complain about TypeError: Attempted to wrap xxxx which is already wrapped - diag.setLogger(); onShutdownSpy = sinon.stub( CollectorMetricExporter.prototype, 'onShutdown' @@ -214,9 +207,6 @@ describe('CollectorMetricExporter - common', () => { }; collectorExporter = new CollectorMetricExporter(collectorExporterConfig); }); - afterEach(() => { - onShutdownSpy.restore(); - }); it('should call onShutdown', async () => { await collectorExporter.shutdown(); diff --git a/packages/opentelemetry-exporter-collector/test/common/CollectorTraceExporter.test.ts b/packages/opentelemetry-exporter-collector/test/common/CollectorTraceExporter.test.ts index 058a83cd76f..d104fd26c1b 100644 --- a/packages/opentelemetry-exporter-collector/test/common/CollectorTraceExporter.test.ts +++ b/packages/opentelemetry-exporter-collector/test/common/CollectorTraceExporter.test.ts @@ -13,7 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import { diag } from '@opentelemetry/api'; + import { ExportResultCode } from '@opentelemetry/core'; import { ReadableSpan } from '@opentelemetry/tracing'; import * as assert from 'assert'; @@ -61,12 +61,14 @@ describe('CollectorTraceExporter - common', () => { let collectorExporter: CollectorTraceExporter; let collectorExporterConfig: CollectorExporterConfig; + afterEach(() => { + sinon.restore(); + }); + describe('constructor', () => { let onInitSpy: any; beforeEach(() => { - // Set no logger so that sinon doesn't complain about TypeError: Attempted to wrap xxxx which is already wrapped - diag.setLogger(); onInitSpy = sinon.stub(CollectorTraceExporter.prototype, 'onInit'); collectorExporterConfig = { hostname: 'foo', @@ -77,10 +79,6 @@ describe('CollectorTraceExporter - common', () => { collectorExporter = new CollectorTraceExporter(collectorExporterConfig); }); - afterEach(() => { - onInitSpy.restore(); - }); - it('should create an instance', () => { assert.ok(typeof collectorExporter !== 'undefined'); }); @@ -120,9 +118,6 @@ describe('CollectorTraceExporter - common', () => { spySend = sinon.stub(CollectorTraceExporter.prototype, 'send'); collectorExporter = new CollectorTraceExporter(collectorExporterConfig); }); - afterEach(() => { - spySend.restore(); - }); it('should export spans as collectorTypes.Spans', done => { const spans: ReadableSpan[] = []; @@ -220,8 +215,6 @@ describe('CollectorTraceExporter - common', () => { describe('shutdown', () => { let onShutdownSpy: any; beforeEach(() => { - // Set no logger so that sinon doesn't complain about TypeError: Attempted to wrap xxxx which is already wrapped - diag.setLogger(); onShutdownSpy = sinon.stub( CollectorTraceExporter.prototype, 'onShutdown' @@ -234,9 +227,6 @@ describe('CollectorTraceExporter - common', () => { }; collectorExporter = new CollectorTraceExporter(collectorExporterConfig); }); - afterEach(() => { - onShutdownSpy.restore(); - }); it('should call onShutdown', async () => { await collectorExporter.shutdown(); diff --git a/packages/opentelemetry-exporter-collector/test/common/transform.test.ts b/packages/opentelemetry-exporter-collector/test/common/transform.test.ts index 3bcb5e8acec..f212a7774a4 100644 --- a/packages/opentelemetry-exporter-collector/test/common/transform.test.ts +++ b/packages/opentelemetry-exporter-collector/test/common/transform.test.ts @@ -37,12 +37,21 @@ describe('transform', () => { ]); }); - it('should convert attribute integer', () => { + it('should convert attribute integer to integer', () => { const attributes: SpanAttributes = { foo: 13, }; assert.deepStrictEqual(transform.toCollectorAttributes(attributes), [ - { key: 'foo', value: { doubleValue: 13 } }, + { key: 'foo', value: { intValue: 13 } }, + ]); + }); + + it('should convert attribute integer to double', () => { + const attributes: SpanAttributes = { + foo: 2247483647, + }; + assert.deepStrictEqual(transform.toCollectorAttributes(attributes), [ + { key: 'foo', value: { doubleValue: 2247483647 } }, ]); }); @@ -118,7 +127,7 @@ describe('transform', () => { }, { key: 'version', - value: { doubleValue: 1 }, + value: { intValue: 1 }, }, { key: 'success', value: { boolValue: true } }, ], diff --git a/packages/opentelemetry-exporter-collector/test/common/utils.test.ts b/packages/opentelemetry-exporter-collector/test/common/utils.test.ts index 0afeede3edf..e2414952144 100644 --- a/packages/opentelemetry-exporter-collector/test/common/utils.test.ts +++ b/packages/opentelemetry-exporter-collector/test/common/utils.test.ts @@ -20,15 +20,14 @@ import { diag } from '@opentelemetry/api'; import { parseHeaders } from '../../src/util'; describe('utils', () => { - describe('parseHeaders', () => { - beforeEach(() => { - // Set no logger so that sinon doesn't complain about TypeError: Attempted to wrap xxxx which is already wrapped - diag.setLogger(); - }); + afterEach(() => { + sinon.restore(); + }); + describe('parseHeaders', () => { it('should ignore undefined headers', () => { // Need to stub/spy on the underlying logger as the "diag" instance is global - const spyWarn = sinon.stub(diag.getLogger(), 'warn'); + const spyWarn = sinon.stub(diag, 'warn'); const headers: Partial> = { foo1: undefined, foo2: 'bar', @@ -45,6 +44,7 @@ describe('utils', () => { 'Header "foo1" has wrong value and will be ignored' ); }); + it('should parse undefined', () => { const result = parseHeaders(undefined); assert.deepStrictEqual(result, {}); diff --git a/packages/opentelemetry-exporter-collector/test/helper.ts b/packages/opentelemetry-exporter-collector/test/helper.ts index 710e1d99d56..b38785daab9 100644 --- a/packages/opentelemetry-exporter-collector/test/helper.ts +++ b/packages/opentelemetry-exporter-collector/test/helper.ts @@ -540,7 +540,7 @@ export function ensureWebResourceIsCorrect( { key: 'version', value: { - doubleValue: 1, + intValue: 1, }, }, { diff --git a/packages/opentelemetry-exporter-collector/test/node/CollectorMetricExporter.test.ts b/packages/opentelemetry-exporter-collector/test/node/CollectorMetricExporter.test.ts index b0ac06beceb..765b603077d 100644 --- a/packages/opentelemetry-exporter-collector/test/node/CollectorMetricExporter.test.ts +++ b/packages/opentelemetry-exporter-collector/test/node/CollectorMetricExporter.test.ts @@ -58,14 +58,19 @@ const address = 'localhost:1501'; describe('CollectorMetricExporter - node with json over http', () => { let collectorExporter: CollectorMetricExporter; let collectorExporterConfig: CollectorExporterNodeConfigBase; - let spyRequest: sinon.SinonSpy; - let spyWrite: sinon.SinonSpy; + let stubRequest: sinon.SinonStub; + let stubWrite: sinon.SinonStub; let metrics: MetricRecord[]; + + afterEach(() => { + sinon.restore(); + }); + describe('instance', () => { it('should warn about metadata when using json', () => { const metadata = 'foo'; // Need to stub/spy on the underlying logger as the "diag" instance is global - const spyLoggerWarn = sinon.stub(diag.getLogger(), 'warn'); + const spyLoggerWarn = sinon.stub(diag, 'warn'); collectorExporter = new CollectorMetricExporter({ serviceName: 'basic-service', url: address, @@ -78,10 +83,8 @@ describe('CollectorMetricExporter - node with json over http', () => { describe('export', () => { beforeEach(async () => { - // Set no logger so that sinon doesn't complain about TypeError: Attempted to wrap xxxx which is already wrapped - diag.setLogger(); - spyRequest = sinon.stub(http, 'request').returns(fakeRequest as any); - spyWrite = sinon.stub(fakeRequest, 'write'); + stubRequest = sinon.stub(http, 'request').returns(fakeRequest as any); + stubWrite = sinon.stub(fakeRequest, 'write'); collectorExporterConfig = { headers: { foo: 'bar', @@ -117,16 +120,11 @@ describe('CollectorMetricExporter - node with json over http', () => { metrics.push((await recorder.getMetricRecord())[0]); }); - afterEach(() => { - spyRequest.restore(); - spyWrite.restore(); - }); - it('should open the connection', done => { collectorExporter.export(metrics, () => {}); setTimeout(() => { - const args = spyRequest.args[0]; + const args = stubRequest.args[0]; const options = args[0]; assert.strictEqual(options.hostname, 'foo.bar.com'); @@ -140,7 +138,7 @@ describe('CollectorMetricExporter - node with json over http', () => { collectorExporter.export(metrics, () => {}); setTimeout(() => { - const args = spyRequest.args[0]; + const args = stubRequest.args[0]; const options = args[0]; assert.strictEqual(options.headers['foo'], 'bar'); done(); @@ -151,7 +149,7 @@ describe('CollectorMetricExporter - node with json over http', () => { collectorExporter.export(metrics, () => {}); setTimeout(() => { - const args = spyRequest.args[0]; + const args = stubRequest.args[0]; const options = args[0]; const agent = options.agent; assert.strictEqual(agent.keepAlive, true); @@ -164,7 +162,7 @@ describe('CollectorMetricExporter - node with json over http', () => { collectorExporter.export(metrics, () => {}); setTimeout(() => { - const writeArgs = spyWrite.args[0]; + const writeArgs = stubWrite.args[0]; const json = JSON.parse( writeArgs[0] ) as collectorTypes.opentelemetryProto.collector.metrics.v1.ExportMetricsServiceRequest; @@ -203,19 +201,19 @@ describe('CollectorMetricExporter - node with json over http', () => { it('should log the successful message', done => { // Need to stub/spy on the underlying logger as the "diag" instance is global - const spyLoggerError = sinon.stub(diag.getLogger(), 'error'); + const stubLoggerError = sinon.stub(diag, 'error'); const responseSpy = sinon.spy(); collectorExporter.export(metrics, responseSpy); setTimeout(() => { const mockRes = new MockedResponse(200); - const args = spyRequest.args[0]; + const args = stubRequest.args[0]; const callback = args[1]; callback(mockRes); mockRes.send('success'); setTimeout(() => { - assert.strictEqual(spyLoggerError.args.length, 0); + assert.strictEqual(stubLoggerError.args.length, 0); assert.strictEqual( responseSpy.args[0][0].code, core.ExportResultCode.SUCCESS @@ -226,8 +224,6 @@ describe('CollectorMetricExporter - node with json over http', () => { }); it('should log the error message', done => { - const spyLoggerError = sinon.spy(); - diag.error = spyLoggerError; const handler = core.loggingErrorHandler(); core.setGlobalErrorHandler(handler); @@ -236,7 +232,7 @@ describe('CollectorMetricExporter - node with json over http', () => { setTimeout(() => { const mockRes = new MockedResponse(400); - const args = spyRequest.args[0]; + const args = stubRequest.args[0]; const callback = args[1]; callback(mockRes); mockRes.send('failed'); diff --git a/packages/opentelemetry-exporter-collector/test/node/CollectorTraceExporter.test.ts b/packages/opentelemetry-exporter-collector/test/node/CollectorTraceExporter.test.ts index 6a547ff0b32..129e8b9ba6d 100644 --- a/packages/opentelemetry-exporter-collector/test/node/CollectorTraceExporter.test.ts +++ b/packages/opentelemetry-exporter-collector/test/node/CollectorTraceExporter.test.ts @@ -44,18 +44,19 @@ const address = 'localhost:1501'; describe('CollectorTraceExporter - node with json over http', () => { let collectorExporter: CollectorTraceExporter; let collectorExporterConfig: CollectorExporterNodeConfigBase; - let spyRequest: sinon.SinonSpy; - let spyWrite: sinon.SinonSpy; + let stubRequest: sinon.SinonStub; + let stubWrite: sinon.SinonStub; let spans: ReadableSpan[]; + + afterEach(() => { + sinon.restore(); + }); + describe('instance', () => { - beforeEach(() => { - // Set no logger so that sinon doesn't complain about TypeError: Attempted to wrap xxxx which is already wrapped - diag.setLogger(); - }); it('should warn about metadata when using json', () => { const metadata = 'foo'; // Need to stub/spy on the underlying logger as the "diag" instance is global - const spyLoggerWarn = sinon.stub(diag.getLogger(), 'warn'); + const spyLoggerWarn = sinon.stub(diag, 'warn'); collectorExporter = new CollectorTraceExporter({ serviceName: 'basic-service', metadata, @@ -68,10 +69,8 @@ describe('CollectorTraceExporter - node with json over http', () => { describe('export', () => { beforeEach(() => { - // Set no logger so that sinon doesn't complain about TypeError: Attempted to wrap xxxx which is already wrapped - diag.setLogger(); - spyRequest = sinon.stub(http, 'request').returns(fakeRequest as any); - spyWrite = sinon.stub(fakeRequest, 'write'); + stubRequest = sinon.stub(http, 'request').returns(fakeRequest as any); + stubWrite = sinon.stub(fakeRequest, 'write'); collectorExporterConfig = { headers: { foo: 'bar', @@ -87,16 +86,12 @@ describe('CollectorTraceExporter - node with json over http', () => { spans = []; spans.push(Object.assign({}, mockedReadableSpan)); }); - afterEach(() => { - spyRequest.restore(); - spyWrite.restore(); - }); it('should open the connection', done => { collectorExporter.export(spans, () => {}); setTimeout(() => { - const args = spyRequest.args[0]; + const args = stubRequest.args[0]; const options = args[0]; assert.strictEqual(options.hostname, 'foo.bar.com'); @@ -110,7 +105,7 @@ describe('CollectorTraceExporter - node with json over http', () => { collectorExporter.export(spans, () => {}); setTimeout(() => { - const args = spyRequest.args[0]; + const args = stubRequest.args[0]; const options = args[0]; assert.strictEqual(options.headers['foo'], 'bar'); done(); @@ -121,7 +116,7 @@ describe('CollectorTraceExporter - node with json over http', () => { collectorExporter.export(spans, () => {}); setTimeout(() => { - const args = spyRequest.args[0]; + const args = stubRequest.args[0]; const options = args[0]; const agent = options.agent; assert.strictEqual(agent.keepAlive, true); @@ -135,7 +130,7 @@ describe('CollectorTraceExporter - node with json over http', () => { collectorExporter.export(spans, () => {}); setTimeout(() => { - const [firstExportAgent, secondExportAgent] = spyRequest.args.map( + const [firstExportAgent, secondExportAgent] = stubRequest.args.map( a => a[0].agent ); assert.strictEqual(firstExportAgent, secondExportAgent); @@ -147,7 +142,7 @@ describe('CollectorTraceExporter - node with json over http', () => { collectorExporter.export(spans, () => {}); setTimeout(() => { - const writeArgs = spyWrite.args[0]; + const writeArgs = stubWrite.args[0]; const json = JSON.parse( writeArgs[0] ) as collectorTypes.opentelemetryProto.collector.trace.v1.ExportTraceServiceRequest; @@ -166,18 +161,18 @@ describe('CollectorTraceExporter - node with json over http', () => { it('should log the successful message', done => { // Need to stub/spy on the underlying logger as the "diag" instance is global - const spyLoggerError = sinon.stub(diag.getLogger(), 'error'); + const stubLoggerError = sinon.stub(diag, 'error'); const responseSpy = sinon.spy(); collectorExporter.export(spans, responseSpy); setTimeout(() => { const mockRes = new MockedResponse(200); - const args = spyRequest.args[0]; + const args = stubRequest.args[0]; const callback = args[1]; callback(mockRes); mockRes.send('success'); setTimeout(() => { - assert.strictEqual(spyLoggerError.args.length, 0); + assert.strictEqual(stubLoggerError.args.length, 0); assert.strictEqual( responseSpy.args[0][0].code, core.ExportResultCode.SUCCESS @@ -193,7 +188,7 @@ describe('CollectorTraceExporter - node with json over http', () => { setTimeout(() => { const mockResError = new MockedResponse(400); - const args = spyRequest.args[0]; + const args = stubRequest.args[0]; const callback = args[1]; callback(mockResError); mockResError.send('failed'); diff --git a/packages/opentelemetry-exporter-collector/tsconfig.json b/packages/opentelemetry-exporter-collector/tsconfig.json index c31181cd6fd..4d3d15abaf0 100644 --- a/packages/opentelemetry-exporter-collector/tsconfig.json +++ b/packages/opentelemetry-exporter-collector/tsconfig.json @@ -9,9 +9,6 @@ "test/**/*.ts" ], "references": [ - { - "path": "../opentelemetry-api" - }, { "path": "../opentelemetry-api-metrics" }, diff --git a/packages/opentelemetry-exporter-jaeger/package.json b/packages/opentelemetry-exporter-jaeger/package.json index fc6af3a595b..575ca049f29 100644 --- a/packages/opentelemetry-exporter-jaeger/package.json +++ b/packages/opentelemetry-exporter-jaeger/package.json @@ -56,7 +56,7 @@ "typescript": "4.1.3" }, "dependencies": { - "@opentelemetry/api": "^0.17.0", + "@opentelemetry/api": "^0.18.0", "@opentelemetry/core": "^0.17.0", "@opentelemetry/tracing": "^0.17.0", "jaeger-client": "^3.15.0" diff --git a/packages/opentelemetry-exporter-jaeger/tsconfig.json b/packages/opentelemetry-exporter-jaeger/tsconfig.json index 24964158810..77140114c89 100644 --- a/packages/opentelemetry-exporter-jaeger/tsconfig.json +++ b/packages/opentelemetry-exporter-jaeger/tsconfig.json @@ -9,9 +9,6 @@ "test/**/*.ts" ], "references": [ - { - "path": "../opentelemetry-api" - }, { "path": "../opentelemetry-core" }, diff --git a/packages/opentelemetry-exporter-prometheus/package.json b/packages/opentelemetry-exporter-prometheus/package.json index cb768917ce0..ca8a9f69728 100644 --- a/packages/opentelemetry-exporter-prometheus/package.json +++ b/packages/opentelemetry-exporter-prometheus/package.json @@ -53,7 +53,7 @@ "typescript": "4.1.3" }, "dependencies": { - "@opentelemetry/api": "^0.17.0", + "@opentelemetry/api": "^0.18.0", "@opentelemetry/api-metrics": "^0.17.0", "@opentelemetry/core": "^0.17.0", "@opentelemetry/metrics": "^0.17.0" diff --git a/packages/opentelemetry-exporter-prometheus/tsconfig.json b/packages/opentelemetry-exporter-prometheus/tsconfig.json index 59d79ed095d..006ea333e44 100644 --- a/packages/opentelemetry-exporter-prometheus/tsconfig.json +++ b/packages/opentelemetry-exporter-prometheus/tsconfig.json @@ -9,9 +9,6 @@ "test/**/*.ts" ], "references": [ - { - "path": "../opentelemetry-api" - }, { "path": "../opentelemetry-api-metrics" }, diff --git a/packages/opentelemetry-exporter-zipkin/package.json b/packages/opentelemetry-exporter-zipkin/package.json index 93bcdd63c02..ac055da1a2e 100644 --- a/packages/opentelemetry-exporter-zipkin/package.json +++ b/packages/opentelemetry-exporter-zipkin/package.json @@ -75,7 +75,7 @@ "webpack-merge": "5.7.3" }, "dependencies": { - "@opentelemetry/api": "^0.17.0", + "@opentelemetry/api": "^0.18.0", "@opentelemetry/core": "^0.17.0", "@opentelemetry/resources": "^0.17.0", "@opentelemetry/tracing": "^0.17.0" diff --git a/packages/opentelemetry-exporter-zipkin/test/browser/zipkin.test.ts b/packages/opentelemetry-exporter-zipkin/test/browser/zipkin.test.ts index 3e53b4e4623..684dae9fb2e 100644 --- a/packages/opentelemetry-exporter-zipkin/test/browser/zipkin.test.ts +++ b/packages/opentelemetry-exporter-zipkin/test/browser/zipkin.test.ts @@ -14,7 +14,6 @@ * limitations under the License. */ -import { diag } from '@opentelemetry/api'; import { setGlobalErrorHandler, loggingErrorHandler, @@ -38,18 +37,16 @@ describe('Zipkin Exporter - web', () => { let spySend: sinon.SinonSpy; let spyBeacon: sinon.SinonSpy; let spans: ReadableSpan[]; - let sandbox: sinon.SinonSandbox; beforeEach(() => { - sandbox = sinon.createSandbox(); - spySend = sandbox.stub(XMLHttpRequest.prototype, 'send'); - spyBeacon = sandbox.stub(navigator, 'sendBeacon'); + spySend = sinon.stub(XMLHttpRequest.prototype, 'send'); + spyBeacon = sinon.stub(navigator, 'sendBeacon'); spans = []; spans.push(Object.assign({}, mockedReadableSpan)); }); afterEach(() => { - sandbox.restore(); + sinon.restore(); navigator.sendBeacon = sendBeacon; }); @@ -109,8 +106,6 @@ describe('Zipkin Exporter - web', () => { }; beforeEach(() => { - // Set no logger so that sinon doesn't complain about TypeError: Attempted to wrap xxxx which is already wrapped - diag.setLogger(); zipkinConfig = { headers: customHeaders, }; diff --git a/packages/opentelemetry-exporter-zipkin/tsconfig.json b/packages/opentelemetry-exporter-zipkin/tsconfig.json index 24964158810..77140114c89 100644 --- a/packages/opentelemetry-exporter-zipkin/tsconfig.json +++ b/packages/opentelemetry-exporter-zipkin/tsconfig.json @@ -9,9 +9,6 @@ "test/**/*.ts" ], "references": [ - { - "path": "../opentelemetry-api" - }, { "path": "../opentelemetry-core" }, diff --git a/packages/opentelemetry-grpc-utils/package.json b/packages/opentelemetry-grpc-utils/package.json index 1929f1bd649..4a2b3373492 100644 --- a/packages/opentelemetry-grpc-utils/package.json +++ b/packages/opentelemetry-grpc-utils/package.json @@ -43,7 +43,6 @@ "@grpc/grpc-js": "1.2.3", "@grpc/proto-loader": "0.5.5", "@opentelemetry/context-async-hooks": "^0.17.0", - "@opentelemetry/context-base": "^0.17.0", "@opentelemetry/node": "^0.17.0", "@opentelemetry/tracing": "^0.17.0", "@types/mocha": "8.2.0", @@ -65,7 +64,7 @@ "typescript": "4.1.3" }, "dependencies": { - "@opentelemetry/api": "^0.17.0", + "@opentelemetry/api": "^0.18.0", "@opentelemetry/core": "^0.17.0", "@opentelemetry/semantic-conventions": "^0.17.0", "shimmer": "1.2.1" diff --git a/packages/opentelemetry-grpc-utils/test/grpcUtils.test.ts b/packages/opentelemetry-grpc-utils/test/grpcUtils.test.ts index 746511aff76..4fd0161f09a 100644 --- a/packages/opentelemetry-grpc-utils/test/grpcUtils.test.ts +++ b/packages/opentelemetry-grpc-utils/test/grpcUtils.test.ts @@ -29,7 +29,7 @@ import { } from '@opentelemetry/core'; import { NodeTracerProvider } from '@opentelemetry/node'; import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks'; -import { ContextManager } from '@opentelemetry/context-base'; +import { ContextManager } from '@opentelemetry/api'; import { InMemorySpanExporter, SimpleSpanProcessor, diff --git a/packages/opentelemetry-grpc-utils/tsconfig.json b/packages/opentelemetry-grpc-utils/tsconfig.json index 08f0364911d..a6187d76f2d 100644 --- a/packages/opentelemetry-grpc-utils/tsconfig.json +++ b/packages/opentelemetry-grpc-utils/tsconfig.json @@ -9,15 +9,9 @@ "test/**/*.ts" ], "references": [ - { - "path": "../opentelemetry-api" - }, { "path": "../opentelemetry-context-async-hooks" }, - { - "path": "../opentelemetry-context-base" - }, { "path": "../opentelemetry-core" }, diff --git a/packages/opentelemetry-instrumentation-fetch/package.json b/packages/opentelemetry-instrumentation-fetch/package.json index 1026cbb51ad..9c79025573a 100644 --- a/packages/opentelemetry-instrumentation-fetch/package.json +++ b/packages/opentelemetry-instrumentation-fetch/package.json @@ -74,7 +74,7 @@ "webpack-merge": "5.7.3" }, "dependencies": { - "@opentelemetry/api": "^0.17.0", + "@opentelemetry/api": "^0.18.0", "@opentelemetry/core": "^0.17.0", "@opentelemetry/instrumentation": "^0.17.0", "@opentelemetry/semantic-conventions": "^0.17.0", diff --git a/packages/opentelemetry-instrumentation-fetch/test/fetch.test.ts b/packages/opentelemetry-instrumentation-fetch/test/fetch.test.ts index d608059e373..9212774ca10 100644 --- a/packages/opentelemetry-instrumentation-fetch/test/fetch.test.ts +++ b/packages/opentelemetry-instrumentation-fetch/test/fetch.test.ts @@ -130,7 +130,6 @@ function createFakePerformanceObs(url: string) { } describe('fetch', () => { - let sandbox: sinon.SinonSandbox; let contextManager: ZoneContextManager; let lastResponse: any | undefined; let webTracerWithZone: api.Tracer; @@ -146,7 +145,7 @@ describe('fetch', () => { const badUrl = 'http://foo.bar.com/get'; const clearData = () => { - sandbox.restore(); + sinon.restore(); lastResponse = undefined; }; @@ -158,11 +157,10 @@ describe('fetch', () => { disablePerfObserver?: boolean, disableGetEntries?: boolean ) => { - sandbox = sinon.createSandbox(); - sandbox.useFakeTimers(); + sinon.useFakeTimers(); - sandbox.stub(core.otperformance, 'timeOrigin').value(0); - sandbox.stub(core.otperformance, 'now').callsFake(() => fakeNow); + sinon.stub(core.otperformance, 'timeOrigin').value(0); + sinon.stub(core.otperformance, 'now').callsFake(() => fakeNow); function fakeFetch(input: RequestInfo | Request, init: RequestInit = {}) { return new Promise((resolve, reject) => { @@ -188,7 +186,7 @@ describe('fetch', () => { }); } - sandbox.stub(window, 'fetch').callsFake(fakeFetch as any); + sinon.stub(window, 'fetch').callsFake(fakeFetch as any); const resources: PerformanceResourceTiming[] = []; resources.push( @@ -201,17 +199,17 @@ describe('fetch', () => { ); if (disablePerfObserver) { - sandbox.stub(window, 'PerformanceObserver').value(undefined); + sinon.stub(window, 'PerformanceObserver').value(undefined); } else { - sandbox + sinon .stub(window, 'PerformanceObserver') .value(createFakePerformanceObs(fileUrl)); } if (disableGetEntries) { - sandbox.stub(performance, 'getEntriesByType').value(undefined); + sinon.stub(performance, 'getEntriesByType').value(undefined); } else { - const spyEntries = sandbox.stub(performance, 'getEntriesByType'); + const spyEntries = sinon.stub(performance, 'getEntriesByType'); spyEntries.withArgs('resource').returns(resources); } @@ -223,8 +221,8 @@ describe('fetch', () => { }); webTracerWithZone = webTracerProviderWithZone.getTracer('fetch-test'); dummySpanExporter = new DummySpanExporter(); - exportSpy = sandbox.stub(dummySpanExporter, 'export'); - clearResourceTimingsSpy = sandbox.stub(performance, 'clearResourceTimings'); + exportSpy = sinon.stub(dummySpanExporter, 'export'); + clearResourceTimingsSpy = sinon.stub(performance, 'clearResourceTimings'); webTracerProviderWithZone.addSpanProcessor( new tracing.SimpleSpanProcessor(dummySpanExporter) ); @@ -245,13 +243,13 @@ describe('fetch', () => { }); lastResponse.headers = headers; // OBSERVER_WAIT_TIME_MS - sandbox.clock.tick(300); + sinon.clock.tick(300); done(); }, () => { lastResponse = undefined; // OBSERVER_WAIT_TIME_MS - sandbox.clock.tick(300); + sinon.clock.tick(300); done(); } ); @@ -259,7 +257,7 @@ describe('fetch', () => { () => { lastResponse = undefined; // OBSERVER_WAIT_TIME_MS - sandbox.clock.tick(300); + sinon.clock.tick(300); done(); } ); diff --git a/packages/opentelemetry-instrumentation-fetch/tsconfig.json b/packages/opentelemetry-instrumentation-fetch/tsconfig.json index 76bcef51f22..ec15c2ba210 100644 --- a/packages/opentelemetry-instrumentation-fetch/tsconfig.json +++ b/packages/opentelemetry-instrumentation-fetch/tsconfig.json @@ -10,9 +10,6 @@ "test/**/*.ts" ], "references": [ - { - "path": "../opentelemetry-api" - }, { "path": "../opentelemetry-context-zone" }, diff --git a/packages/opentelemetry-instrumentation-grpc/package.json b/packages/opentelemetry-instrumentation-grpc/package.json index 8f222485d0b..541f6201aa4 100644 --- a/packages/opentelemetry-instrumentation-grpc/package.json +++ b/packages/opentelemetry-instrumentation-grpc/package.json @@ -44,7 +44,6 @@ "@grpc/grpc-js": "1.2.3", "@grpc/proto-loader": "0.5.5", "@opentelemetry/context-async-hooks": "^0.17.0", - "@opentelemetry/context-base": "^0.17.0", "@opentelemetry/core": "^0.17.0", "@opentelemetry/node": "^0.17.0", "@opentelemetry/tracing": "^0.17.0", @@ -67,7 +66,7 @@ "typescript": "4.1.3" }, "dependencies": { - "@opentelemetry/api": "^0.17.0", + "@opentelemetry/api": "^0.18.0", "@opentelemetry/api-metrics": "^0.17.0", "@opentelemetry/instrumentation": "^0.17.0", "@opentelemetry/semantic-conventions": "^0.17.0" diff --git a/packages/opentelemetry-instrumentation-grpc/test/helper.ts b/packages/opentelemetry-instrumentation-grpc/test/helper.ts index 1cf307ba880..77665b68249 100644 --- a/packages/opentelemetry-instrumentation-grpc/test/helper.ts +++ b/packages/opentelemetry-instrumentation-grpc/test/helper.ts @@ -24,7 +24,7 @@ import { import { HttpTraceContext } from '@opentelemetry/core'; import { NodeTracerProvider } from '@opentelemetry/node'; import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks'; -import { ContextManager } from '@opentelemetry/context-base'; +import { ContextManager } from '@opentelemetry/api'; import { InMemorySpanExporter, SimpleSpanProcessor, diff --git a/packages/opentelemetry-instrumentation-grpc/tsconfig.json b/packages/opentelemetry-instrumentation-grpc/tsconfig.json index d133c182573..b016cc5541f 100644 --- a/packages/opentelemetry-instrumentation-grpc/tsconfig.json +++ b/packages/opentelemetry-instrumentation-grpc/tsconfig.json @@ -9,18 +9,12 @@ "test/**/*.ts" ], "references": [ - { - "path": "../opentelemetry-api" - }, { "path": "../opentelemetry-api-metrics" }, { "path": "../opentelemetry-context-async-hooks" }, - { - "path": "../opentelemetry-context-base" - }, { "path": "../opentelemetry-core" }, diff --git a/packages/opentelemetry-instrumentation-http/package.json b/packages/opentelemetry-instrumentation-http/package.json index 103723711d5..1697f114bb8 100644 --- a/packages/opentelemetry-instrumentation-http/package.json +++ b/packages/opentelemetry-instrumentation-http/package.json @@ -42,7 +42,6 @@ }, "devDependencies": { "@opentelemetry/context-async-hooks": "^0.17.0", - "@opentelemetry/context-base": "^0.17.0", "@opentelemetry/core": "^0.17.0", "@opentelemetry/node": "^0.17.0", "@opentelemetry/tracing": "^0.17.0", @@ -70,7 +69,7 @@ "typescript": "4.1.3" }, "dependencies": { - "@opentelemetry/api": "^0.17.0", + "@opentelemetry/api": "^0.18.0", "@opentelemetry/instrumentation": "^0.17.0", "@opentelemetry/semantic-conventions": "^0.17.0", "semver": "^7.1.3" diff --git a/packages/opentelemetry-instrumentation-http/test/functionals/http-enable.test.ts b/packages/opentelemetry-instrumentation-http/test/functionals/http-enable.test.ts index b609685fa81..8f75058b3bb 100644 --- a/packages/opentelemetry-instrumentation-http/test/functionals/http-enable.test.ts +++ b/packages/opentelemetry-instrumentation-http/test/functionals/http-enable.test.ts @@ -39,7 +39,7 @@ import { HttpInstrumentationConfig } from '../../src/types'; import { assertSpan } from '../utils/assertSpan'; import { DummyPropagation } from '../utils/DummyPropagation'; import { httpRequest } from '../utils/httpRequest'; -import { ContextManager } from '@opentelemetry/context-base'; +import { ContextManager } from '@opentelemetry/api'; import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks'; import type { ClientRequest, IncomingMessage, ServerResponse } from 'http'; import { isWrapped } from '@opentelemetry/instrumentation'; diff --git a/packages/opentelemetry-instrumentation-http/test/functionals/https-enable.test.ts b/packages/opentelemetry-instrumentation-http/test/functionals/https-enable.test.ts index e1ee7a6a52f..2dd34b2c448 100644 --- a/packages/opentelemetry-instrumentation-http/test/functionals/https-enable.test.ts +++ b/packages/opentelemetry-instrumentation-http/test/functionals/https-enable.test.ts @@ -23,7 +23,7 @@ import { setSpan, } from '@opentelemetry/api'; import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks'; -import { ContextManager } from '@opentelemetry/context-base'; +import { ContextManager } from '@opentelemetry/api'; import { BasicTracerProvider, InMemorySpanExporter, diff --git a/packages/opentelemetry-instrumentation-http/test/functionals/utils.test.ts b/packages/opentelemetry-instrumentation-http/test/functionals/utils.test.ts index 55b346bfbcb..26bef9061ce 100644 --- a/packages/opentelemetry-instrumentation-http/test/functionals/utils.test.ts +++ b/packages/opentelemetry-instrumentation-http/test/functionals/utils.test.ts @@ -141,13 +141,12 @@ describe('Utility', () => { }); describe('isIgnored()', () => { - let satisfiesPatternStub: sinon.SinonSpy<[string, IgnoreMatcher], boolean>; beforeEach(() => { - satisfiesPatternStub = sinon.spy(utils, 'satisfiesPattern'); + sinon.spy(utils, 'satisfiesPattern'); }); afterEach(() => { - satisfiesPatternStub.restore(); + sinon.restore(); }); it('should call isSatisfyPattern, n match', () => { @@ -160,7 +159,6 @@ describe('Utility', () => { }); it('should call isSatisfyPattern, match for function', () => { - satisfiesPatternStub.restore(); const answer1 = utils.isIgnored('/test/1', [ url => url.endsWith('/test/1'), ]); @@ -168,7 +166,6 @@ describe('Utility', () => { }); it('should not re-throw when function throws an exception', () => { - satisfiesPatternStub.restore(); const onException = (e: Error) => { // Do nothing }; @@ -188,7 +185,6 @@ describe('Utility', () => { }); it('should call onException when function throws an exception', () => { - satisfiesPatternStub.restore(); const onException = sinon.spy(); assert.doesNotThrow(() => utils.isIgnored( diff --git a/packages/opentelemetry-instrumentation-http/tsconfig.json b/packages/opentelemetry-instrumentation-http/tsconfig.json index ea143a7be3c..85e840b97ba 100644 --- a/packages/opentelemetry-instrumentation-http/tsconfig.json +++ b/packages/opentelemetry-instrumentation-http/tsconfig.json @@ -9,15 +9,9 @@ "test/**/*.ts" ], "references": [ - { - "path": "../opentelemetry-api" - }, { "path": "../opentelemetry-context-async-hooks" }, - { - "path": "../opentelemetry-context-base" - }, { "path": "../opentelemetry-core" }, diff --git a/packages/opentelemetry-instrumentation-xml-http-request/package.json b/packages/opentelemetry-instrumentation-xml-http-request/package.json index 57848399875..e9c600792c8 100644 --- a/packages/opentelemetry-instrumentation-xml-http-request/package.json +++ b/packages/opentelemetry-instrumentation-xml-http-request/package.json @@ -73,7 +73,7 @@ "webpack-merge": "5.7.3" }, "dependencies": { - "@opentelemetry/api": "^0.17.0", + "@opentelemetry/api": "^0.18.0", "@opentelemetry/core": "^0.17.0", "@opentelemetry/instrumentation": "^0.17.0", "@opentelemetry/semantic-conventions": "^0.17.0", diff --git a/packages/opentelemetry-instrumentation-xml-http-request/test/xhr.test.ts b/packages/opentelemetry-instrumentation-xml-http-request/test/xhr.test.ts index fdda6616ac9..689e299aa8a 100644 --- a/packages/opentelemetry-instrumentation-xml-http-request/test/xhr.test.ts +++ b/packages/opentelemetry-instrumentation-xml-http-request/test/xhr.test.ts @@ -126,7 +126,6 @@ describe('xhr', () => { asyncTests.forEach(test => { const testAsync = test.async; describe(`when async='${testAsync}'`, () => { - let sandbox: sinon.SinonSandbox; let requests: any[] = []; let prepareData: any; let clearData: any; @@ -165,20 +164,18 @@ describe('xhr', () => { clearData = () => { requests = []; - sandbox.restore(); - spyEntries.restore(); + sinon.restore(); }; prepareData = (done: any, fileUrl: string, config?: any) => { - sandbox = sinon.createSandbox(); - const fakeXhr = sandbox.useFakeXMLHttpRequest(); + const fakeXhr = sinon.useFakeXMLHttpRequest(); fakeXhr.onCreate = function (xhr: any) { requests.push(xhr); }; - sandbox.useFakeTimers(); + sinon.useFakeTimers(); - sandbox.stub(performance, 'timeOrigin').value(0); - sandbox.stub(performance, 'now').callsFake(() => fakeNow); + sinon.stub(performance, 'timeOrigin').value(0); + sinon.stub(performance, 'now').callsFake(() => fakeNow); const resources: PerformanceResourceTiming[] = []; resources.push( @@ -190,7 +187,7 @@ describe('xhr', () => { }) ); - spyEntries = sandbox.stub( + spyEntries = sinon.stub( (performance as unknown) as Performance, 'getEntriesByType' ); @@ -206,7 +203,7 @@ describe('xhr', () => { webTracerWithZone = webTracerProviderWithZone.getTracer('xhr-test'); dummySpanExporter = new DummySpanExporter(); exportSpy = sinon.stub(dummySpanExporter, 'export'); - clearResourceTimingsSpy = sandbox.stub( + clearResourceTimingsSpy = sinon.stub( (performance as unknown) as Performance, 'clearResourceTimings' ); @@ -225,7 +222,7 @@ describe('xhr', () => { testAsync ).then(() => { fakeNow = 0; - sandbox.clock.tick(1000); + sinon.clock.tick(1000); done(); }); assert.strictEqual(requests.length, 1, 'request not called'); @@ -640,7 +637,7 @@ describe('xhr', () => { testAsync ).then(() => { fakeNow = 0; - sandbox.clock.tick(1000); + sinon.clock.tick(1000); }); } ); @@ -657,7 +654,7 @@ describe('xhr', () => { testAsync ).then(() => { fakeNow = 0; - sandbox.clock.tick(1000); + sinon.clock.tick(1000); done(); }); @@ -702,16 +699,15 @@ describe('xhr', () => { let fakeNow = 0; beforeEach(() => { - sandbox = sinon.createSandbox(); - const fakeXhr = sandbox.useFakeXMLHttpRequest(); + const fakeXhr = sinon.useFakeXMLHttpRequest(); fakeXhr.onCreate = function (xhr: any) { requests.push(xhr); }; - sandbox.useFakeTimers(); + sinon.useFakeTimers(); - sandbox.stub(performance, 'timeOrigin').value(0); - sandbox.stub(performance, 'now').callsFake(() => fakeNow); + sinon.stub(performance, 'timeOrigin').value(0); + sinon.stub(performance, 'now').callsFake(() => fakeNow); const resources: PerformanceResourceTiming[] = []; resources.push( @@ -720,7 +716,7 @@ describe('xhr', () => { }) ); - spyEntries = sandbox.stub( + spyEntries = sinon.stub( (performance as unknown) as Performance, 'getEntriesByType' ); @@ -761,7 +757,7 @@ describe('xhr', () => { testAsync ).then(() => { fakeNow = 0; - sandbox.clock.tick(1000); + sinon.clock.tick(1000); done(); }); assert.strictEqual(requests.length, 1, 'request not called'); @@ -897,7 +893,7 @@ describe('xhr', () => { getData(new XMLHttpRequest(), url, () => {}, testAsync).then( () => { fakeNow = 0; - sandbox.clock.tick(1000); + sinon.clock.tick(1000); done(); } ); @@ -989,7 +985,7 @@ describe('xhr', () => { getData(new XMLHttpRequest(), url, () => {}, testAsync).then( () => { fakeNow = 0; - sandbox.clock.tick(1000); + sinon.clock.tick(1000); done(); } ); @@ -1082,12 +1078,12 @@ describe('xhr', () => { new XMLHttpRequest(), url, () => { - sandbox.clock.tick(XHR_TIMEOUT); + sinon.clock.tick(XHR_TIMEOUT); }, testAsync ).then(() => { fakeNow = 0; - sandbox.clock.tick(1000); + sinon.clock.tick(1000); done(); }); } diff --git a/packages/opentelemetry-instrumentation-xml-http-request/tsconfig.json b/packages/opentelemetry-instrumentation-xml-http-request/tsconfig.json index 76bcef51f22..ec15c2ba210 100644 --- a/packages/opentelemetry-instrumentation-xml-http-request/tsconfig.json +++ b/packages/opentelemetry-instrumentation-xml-http-request/tsconfig.json @@ -10,9 +10,6 @@ "test/**/*.ts" ], "references": [ - { - "path": "../opentelemetry-api" - }, { "path": "../opentelemetry-context-zone" }, diff --git a/packages/opentelemetry-instrumentation/package.json b/packages/opentelemetry-instrumentation/package.json index 16e9a437c63..03ad2f16aa7 100644 --- a/packages/opentelemetry-instrumentation/package.json +++ b/packages/opentelemetry-instrumentation/package.json @@ -54,7 +54,7 @@ "url": "https://github.com/open-telemetry/opentelemetry-js/issues" }, "dependencies": { - "@opentelemetry/api": "^0.17.0", + "@opentelemetry/api": "^0.18.0", "@opentelemetry/api-metrics": "^0.17.0", "require-in-the-middle": "^5.0.3", "semver": "^7.3.2", diff --git a/packages/opentelemetry-instrumentation/test/browser/autoLoader.test.ts b/packages/opentelemetry-instrumentation/test/browser/autoLoader.test.ts index cc9e15edef6..a470936123d 100644 --- a/packages/opentelemetry-instrumentation/test/browser/autoLoader.test.ts +++ b/packages/opentelemetry-instrumentation/test/browser/autoLoader.test.ts @@ -28,13 +28,9 @@ class WebPlugin implements OldClassPlugin { } describe('autoLoader', () => { - let sandbox: sinon.SinonSandbox; let unload: Function | undefined; - beforeEach(() => { - sandbox = sinon.createSandbox(); - }); afterEach(() => { - sandbox.restore(); + sinon.restore(); if (typeof unload === 'function') { unload(); unload = undefined; @@ -49,7 +45,7 @@ describe('autoLoader', () => { let webPlugin: WebPlugin; beforeEach(() => { webPlugin = new WebPlugin(); - enableSpy = sandbox.spy(webPlugin, 'enable'); + enableSpy = sinon.spy(webPlugin, 'enable'); unload = registerInstrumentations({ instrumentations: [webPlugin], tracerProvider, diff --git a/packages/opentelemetry-instrumentation/test/common/autoLoader.test.ts b/packages/opentelemetry-instrumentation/test/common/autoLoader.test.ts index 3a1abd88615..4177a347f6b 100644 --- a/packages/opentelemetry-instrumentation/test/common/autoLoader.test.ts +++ b/packages/opentelemetry-instrumentation/test/common/autoLoader.test.ts @@ -29,13 +29,10 @@ class FooInstrumentation extends InstrumentationBase { } describe('autoLoader', () => { - let sandbox: sinon.SinonSandbox; let unload: Function | undefined; - beforeEach(() => { - sandbox = sinon.createSandbox(); - }); + afterEach(() => { - sandbox.restore(); + sinon.restore(); if (typeof unload === 'function') { unload(); unload = undefined; @@ -52,12 +49,9 @@ describe('autoLoader', () => { const meterProvider = NOOP_METER_PROVIDER; beforeEach(() => { instrumentation = new FooInstrumentation('foo', '1', {}); - enableSpy = sandbox.spy(instrumentation, 'enable'); - setTracerProviderSpy = sandbox.stub( - instrumentation, - 'setTracerProvider' - ); - setsetMeterProvider = sandbox.stub(instrumentation, 'setMeterProvider'); + enableSpy = sinon.spy(instrumentation, 'enable'); + setTracerProviderSpy = sinon.stub(instrumentation, 'setTracerProvider'); + setsetMeterProvider = sinon.stub(instrumentation, 'setMeterProvider'); unload = registerInstrumentations({ instrumentations: [instrumentation], tracerProvider, diff --git a/packages/opentelemetry-instrumentation/test/common/autoLoaderUtils.test.ts b/packages/opentelemetry-instrumentation/test/common/autoLoaderUtils.test.ts index f234ad9c160..a4aaaca4732 100644 --- a/packages/opentelemetry-instrumentation/test/common/autoLoaderUtils.test.ts +++ b/packages/opentelemetry-instrumentation/test/common/autoLoaderUtils.test.ts @@ -15,7 +15,6 @@ */ import * as assert from 'assert'; -import * as sinon from 'sinon'; import { InstrumentationBase } from '../../src'; import { parseInstrumentationOptions } from '../../src/autoLoaderUtils'; import { InstrumentationOption } from '../../src/types_internal'; @@ -46,14 +45,6 @@ class FooWebPlugin implements OldClassPlugin { // const fooInstrumentation = new FooInstrumentation(); describe('autoLoaderUtils', () => { - let sandbox: sinon.SinonSandbox; - beforeEach(() => { - sandbox = sinon.createSandbox(); - }); - afterEach(() => { - sandbox.restore(); - }); - describe('parseInstrumentationOptions', () => { it('should create a new instrumentation from class', () => { const { instrumentations } = parseInstrumentationOptions([ diff --git a/packages/opentelemetry-instrumentation/test/common/utils.test.ts b/packages/opentelemetry-instrumentation/test/common/utils.test.ts index cfc10fb38f3..0497b61e2c0 100644 --- a/packages/opentelemetry-instrumentation/test/common/utils.test.ts +++ b/packages/opentelemetry-instrumentation/test/common/utils.test.ts @@ -101,10 +101,10 @@ describe('safeExecuteInTheMiddleAsync', () => { true ); }); - it('should throw error', () => { + it('should throw error', async () => { const error = new Error('test'); try { - safeExecuteInTheMiddleAsync( + await safeExecuteInTheMiddleAsync( async () => { await setTimeout(() => {}, 1); throw error; diff --git a/packages/opentelemetry-instrumentation/test/node/PluginLoader.test.ts b/packages/opentelemetry-instrumentation/test/node/PluginLoader.test.ts index d4d18858457..b9624e8a4f3 100644 --- a/packages/opentelemetry-instrumentation/test/node/PluginLoader.test.ts +++ b/packages/opentelemetry-instrumentation/test/node/PluginLoader.test.ts @@ -17,6 +17,7 @@ import { NoopTracerProvider, diag } from '@opentelemetry/api'; import * as assert from 'assert'; import * as path from 'path'; +import sinon = require('sinon'); import { HookState, PluginLoader, @@ -111,6 +112,7 @@ describe('PluginLoader', () => { afterEach(() => { // clear require cache Object.keys(require.cache).forEach(key => delete require.cache[key]); + sinon.restore(); }); describe('.state()', () => { @@ -134,10 +136,6 @@ describe('PluginLoader', () => { }); describe('.load()', () => { - beforeEach(() => { - // Set no logger so that sinon doesn't complain about TypeError: Attempted to wrap xxxx which is already wrapped - diag.setLogger(); - }); afterEach(() => { delete process.env[ENV_PLUGIN_DISABLED_LIST]; }); @@ -321,18 +319,16 @@ describe('PluginLoader', () => { pluginLoader.unload(); }); - it('should warn when module was already loaded', callback => { - const verifyWarnLogger = Object.assign({}, diag); - verifyWarnLogger.warn = (message: string, ...args: unknown[]) => { - assert(message.match(/were already required when/)); - assert(message.match(/(already-require-module)/)); - return callback(); - }; - diag.setLogger(verifyWarnLogger); + it('should warn when module was already loaded', () => { + const warnStub = sinon.stub(diag, 'warn'); require('already-require-module'); const pluginLoader = new PluginLoader(provider); pluginLoader.load(alreadyRequiredPlugins); pluginLoader.unload(); + sinon.assert.calledOnce(warnStub); + const message = warnStub.firstCall.args[0]; + assert.ok(message.match(/were already required when/)); + assert.ok(message.match(/(already-require-module)/)); }); it('should not load a plugin that patches a different module that the one configured', () => { diff --git a/packages/opentelemetry-instrumentation/test/node/autoLoader.test.ts b/packages/opentelemetry-instrumentation/test/node/autoLoader.test.ts index 45877024457..9a13de50015 100644 --- a/packages/opentelemetry-instrumentation/test/node/autoLoader.test.ts +++ b/packages/opentelemetry-instrumentation/test/node/autoLoader.test.ts @@ -37,18 +37,14 @@ const httpPlugin: Plugins = { }; describe('autoLoader', () => { - let sandbox: sinon.SinonSandbox; let unload: Function | undefined; before(() => { module.paths.push(INSTALLED_PLUGINS_PATH); searchPathForTest(INSTALLED_PLUGINS_PATH); }); - beforeEach(() => { - sandbox = sinon.createSandbox(); - }); afterEach(() => { - sandbox.restore(); + sinon.restore(); Object.keys(require.cache).forEach(key => delete require.cache[key]); if (typeof unload === 'function') { unload(); @@ -65,7 +61,7 @@ describe('autoLoader', () => { // eslint-disable-next-line node/no-extraneous-require const simpleModule = require('@opentelemetry/plugin-simple-module') .plugin; - enableSpy = sandbox.spy(simpleModule, 'enable'); + enableSpy = sinon.spy(simpleModule, 'enable'); unload = registerInstrumentations({ instrumentations: [ { diff --git a/packages/opentelemetry-instrumentation/tsconfig.json b/packages/opentelemetry-instrumentation/tsconfig.json index 8a9fb20b7a7..33b2f1cd61a 100644 --- a/packages/opentelemetry-instrumentation/tsconfig.json +++ b/packages/opentelemetry-instrumentation/tsconfig.json @@ -9,9 +9,6 @@ "test/**/*.ts" ], "references": [ - { - "path": "../opentelemetry-api" - }, { "path": "../opentelemetry-api-metrics" } diff --git a/packages/opentelemetry-metrics/package.json b/packages/opentelemetry-metrics/package.json index ab05a5c8612..6c3be48e5f6 100644 --- a/packages/opentelemetry-metrics/package.json +++ b/packages/opentelemetry-metrics/package.json @@ -55,7 +55,7 @@ "typescript": "4.1.3" }, "dependencies": { - "@opentelemetry/api": "^0.17.0", + "@opentelemetry/api": "^0.18.0", "@opentelemetry/api-metrics": "^0.17.0", "@opentelemetry/core": "^0.17.0", "@opentelemetry/resources": "^0.17.0", diff --git a/packages/opentelemetry-metrics/test/Meter.test.ts b/packages/opentelemetry-metrics/test/Meter.test.ts index aafbb610959..465f5b83013 100644 --- a/packages/opentelemetry-metrics/test/Meter.test.ts +++ b/packages/opentelemetry-metrics/test/Meter.test.ts @@ -79,11 +79,13 @@ describe('Meter', () => { const labels: api.Labels = { [keyb]: 'value2', [keya]: 'value1' }; beforeEach(() => { - // Set no logger so that sinon doesn't complain about TypeError: Attempted to wrap warn which is already wrapped - diag.setLogger(); meter = new MeterProvider().getMeter('test-meter'); }); + afterEach(() => { + sinon.restore(); + }); + describe('#counter', () => { const performanceTimeOrigin = hrTime(); @@ -772,11 +774,6 @@ describe('Meter', () => { }); describe('#SumObserverMetric', () => { - beforeEach(() => { - // Set no logger so that sinon doesn't complain about TypeError: Attempted to wrap xxxx which is already wrapped - diag.setLogger(); - }); - it('should create an Sum observer', () => { const sumObserver = meter.createSumObserver('name') as SumObserverMetric; assert.ok(sumObserver instanceof Metric); @@ -784,7 +781,7 @@ describe('Meter', () => { it('should return noop observer when name is invalid', () => { // Need to stub/spy on the underlying logger as the "diag" instance is global - const spy = sinon.stub(diag.getLogger(), 'warn'); + const spy = sinon.stub(diag, 'warn'); const sumObserver = meter.createSumObserver('na me'); assert.ok(sumObserver === api.NOOP_SUM_OBSERVER_METRIC); const args = spy.args[0]; @@ -917,11 +914,6 @@ describe('Meter', () => { }); describe('#ValueObserver', () => { - beforeEach(() => { - // Set no logger so that sinon doesn't complain about TypeError: Attempted to wrap xxxx which is already wrapped - diag.setLogger(); - }); - it('should create a value observer', () => { const valueObserver = meter.createValueObserver( 'name' @@ -931,7 +923,7 @@ describe('Meter', () => { it('should return noop observer when name is invalid', () => { // Need to stub/spy on the underlying logger as the "diag" instance is global - const spy = sinon.stub(diag.getLogger(), 'warn'); + const spy = sinon.stub(diag, 'warn'); const valueObserver = meter.createValueObserver('na me'); assert.ok(valueObserver === api.NOOP_VALUE_OBSERVER_METRIC); const args = spy.args[0]; @@ -1004,11 +996,6 @@ describe('Meter', () => { }); describe('#UpDownSumObserverMetric', () => { - beforeEach(() => { - // Set no logger so that sinon doesn't complain about TypeError: Attempted to wrap xxxx which is already wrapped - diag.setLogger(); - }); - it('should create an UpDownSum observer', () => { const upDownSumObserver = meter.createUpDownSumObserver( 'name' @@ -1018,7 +1005,7 @@ describe('Meter', () => { it('should return noop observer when name is invalid', () => { // Need to stub/spy on the underlying logger as the "diag" instance is global - const spy = sinon.stub(diag.getLogger(), 'warn'); + const spy = sinon.stub(diag, 'warn'); const upDownSumObserver = meter.createUpDownSumObserver('na me'); assert.ok(upDownSumObserver === api.NOOP_UP_DOWN_SUM_OBSERVER_METRIC); const args = spy.args[0]; diff --git a/packages/opentelemetry-metrics/test/MeterProvider.test.ts b/packages/opentelemetry-metrics/test/MeterProvider.test.ts index 98407e675be..b7bb7bd42f6 100644 --- a/packages/opentelemetry-metrics/test/MeterProvider.test.ts +++ b/packages/opentelemetry-metrics/test/MeterProvider.test.ts @@ -19,6 +19,10 @@ import * as sinon from 'sinon'; import { MeterProvider, Meter, CounterMetric } from '../src'; describe('MeterProvider', () => { + afterEach(() => { + sinon.restore(); + }); + describe('constructor', () => { it('should construct an instance without any options', () => { const provider = new MeterProvider(); @@ -77,12 +81,11 @@ describe('MeterProvider', () => { const meterProvider = new MeterProvider({ interval: Math.pow(2, 31) - 1, }); - const sandbox = sinon.createSandbox(); - const shutdownStub1 = sandbox.stub( + const shutdownStub1 = sinon.stub( meterProvider.getMeter('meter1'), 'shutdown' ); - const shutdownStub2 = sandbox.stub( + const shutdownStub2 = sinon.stub( meterProvider.getMeter('meter2'), 'shutdown' ); diff --git a/packages/opentelemetry-metrics/tsconfig.json b/packages/opentelemetry-metrics/tsconfig.json index e14e1c1b7f7..949c7109286 100644 --- a/packages/opentelemetry-metrics/tsconfig.json +++ b/packages/opentelemetry-metrics/tsconfig.json @@ -9,9 +9,6 @@ "test/**/*.ts" ], "references": [ - { - "path": "../opentelemetry-api" - }, { "path": "../opentelemetry-api-metrics" }, diff --git a/packages/opentelemetry-node/package.json b/packages/opentelemetry-node/package.json index 92d4a5cdf0e..0838c61d76c 100644 --- a/packages/opentelemetry-node/package.json +++ b/packages/opentelemetry-node/package.json @@ -41,7 +41,6 @@ "access": "public" }, "devDependencies": { - "@opentelemetry/context-base": "^0.17.0", "@opentelemetry/resources": "^0.17.0", "@types/mocha": "8.2.0", "@types/node": "14.14.20", @@ -60,7 +59,7 @@ "typescript": "4.1.3" }, "dependencies": { - "@opentelemetry/api": "^0.17.0", + "@opentelemetry/api": "^0.18.0", "@opentelemetry/context-async-hooks": "^0.17.0", "@opentelemetry/core": "^0.17.0", "@opentelemetry/tracing": "^0.17.0", diff --git a/packages/opentelemetry-node/test/NodeTracerProvider.test.ts b/packages/opentelemetry-node/test/NodeTracerProvider.test.ts index c8105f2ffea..9b45531134d 100644 --- a/packages/opentelemetry-node/test/NodeTracerProvider.test.ts +++ b/packages/opentelemetry-node/test/NodeTracerProvider.test.ts @@ -29,7 +29,7 @@ import { Resource, TELEMETRY_SDK_RESOURCE } from '@opentelemetry/resources'; import * as assert from 'assert'; import * as sinon from 'sinon'; import * as path from 'path'; -import { ContextManager, ROOT_CONTEXT } from '@opentelemetry/context-base'; +import { ContextManager, ROOT_CONTEXT } from '@opentelemetry/api'; import { NodeTracerProvider } from '../src/NodeTracerProvider'; const sleep = (time: number) => @@ -53,8 +53,6 @@ describe('NodeTracerProvider', () => { beforeEach(() => { contextManager = new AsyncHooksContextManager(); context.setGlobalContextManager(contextManager.enable()); - // Set no logger so that sinon doesn't complain about TypeError: Attempted to wrap warn which is already wrapped - diag.setLogger(); }); afterEach(() => { @@ -65,11 +63,6 @@ describe('NodeTracerProvider', () => { }); describe('constructor', () => { - beforeEach(() => { - // Set no logger so that sinon doesn't complain about TypeError: Attempted to wrap warn which is already wrapped - diag.setLogger(); - }); - it('should construct an instance with required only options', () => { provider = new NodeTracerProvider(); assert.ok(provider instanceof NodeTracerProvider); @@ -89,7 +82,7 @@ describe('NodeTracerProvider', () => { it('should show warning when plugins are defined', () => { const dummyPlugin1 = {}; - const spyWarn = sinon.spy(diag.getLogger(), 'warn'); + const spyWarn = sinon.spy(diag, 'warn'); const plugins = [dummyPlugin1]; const options = { plugins }; diff --git a/packages/opentelemetry-node/test/registration.test.ts b/packages/opentelemetry-node/test/registration.test.ts index a1f0bed8225..392568f1c12 100644 --- a/packages/opentelemetry-node/test/registration.test.ts +++ b/packages/opentelemetry-node/test/registration.test.ts @@ -25,7 +25,7 @@ import { AsyncHooksContextManager, AsyncLocalStorageContextManager, } from '@opentelemetry/context-async-hooks'; -import { NoopContextManager } from '@opentelemetry/context-base'; +import { NoopContextManager } from '@opentelemetry/api'; import { CompositePropagator } from '@opentelemetry/core'; import * as assert from 'assert'; import { NodeTracerProvider } from '../src'; @@ -50,9 +50,8 @@ describe('API registration', () => { assert.ok( propagation['_getGlobalPropagator']() instanceof CompositePropagator ); - const apiTracerProvider = trace.getTracerProvider(); + const apiTracerProvider = trace.getTracerProvider() as ProxyTracerProvider; - assert.ok(apiTracerProvider instanceof ProxyTracerProvider); assert.ok(apiTracerProvider.getDelegate() === tracerProvider); }); @@ -70,8 +69,7 @@ describe('API registration', () => { assert.ok(context['_getContextManager']() === contextManager); assert.ok(propagation['_getGlobalPropagator']() === propagator); - const apiTracerProvider = trace.getTracerProvider(); - assert.ok(apiTracerProvider instanceof ProxyTracerProvider); + const apiTracerProvider = trace.getTracerProvider() as ProxyTracerProvider; assert.ok(apiTracerProvider.getDelegate() === tracerProvider); }); @@ -87,8 +85,7 @@ describe('API registration', () => { propagation['_getGlobalPropagator']() instanceof CompositePropagator ); - const apiTracerProvider = trace.getTracerProvider(); - assert.ok(apiTracerProvider instanceof ProxyTracerProvider); + const apiTracerProvider = trace.getTracerProvider() as ProxyTracerProvider; assert.ok(apiTracerProvider.getDelegate() === tracerProvider); }); @@ -104,8 +101,7 @@ describe('API registration', () => { assert.ok(context['_getContextManager']() instanceof DefaultContextManager); - const apiTracerProvider = trace.getTracerProvider(); - assert.ok(apiTracerProvider instanceof ProxyTracerProvider); + const apiTracerProvider = trace.getTracerProvider() as ProxyTracerProvider; assert.ok(apiTracerProvider.getDelegate() === tracerProvider); }); }); diff --git a/packages/opentelemetry-node/tsconfig.json b/packages/opentelemetry-node/tsconfig.json index 1295aa1d328..38e281f4ba4 100644 --- a/packages/opentelemetry-node/tsconfig.json +++ b/packages/opentelemetry-node/tsconfig.json @@ -9,15 +9,9 @@ "test/**/*.ts" ], "references": [ - { - "path": "../opentelemetry-api" - }, { "path": "../opentelemetry-context-async-hooks" }, - { - "path": "../opentelemetry-context-base" - }, { "path": "../opentelemetry-core" }, diff --git a/packages/opentelemetry-plugin-grpc-js/package.json b/packages/opentelemetry-plugin-grpc-js/package.json index 17f823e272c..7c5abef9a19 100644 --- a/packages/opentelemetry-plugin-grpc-js/package.json +++ b/packages/opentelemetry-plugin-grpc-js/package.json @@ -44,7 +44,6 @@ "devDependencies": { "@grpc/grpc-js": "1.2.3", "@opentelemetry/context-async-hooks": "^0.17.0", - "@opentelemetry/context-base": "^0.17.0", "@opentelemetry/grpc-utils": "^0.17.0", "@opentelemetry/node": "^0.17.0", "@opentelemetry/tracing": "^0.17.0", @@ -65,7 +64,7 @@ "typescript": "4.1.3" }, "dependencies": { - "@opentelemetry/api": "^0.17.0", + "@opentelemetry/api": "^0.18.0", "@opentelemetry/core": "^0.17.0", "@opentelemetry/semantic-conventions": "^0.17.0", "shimmer": "1.2.1" diff --git a/packages/opentelemetry-plugin-grpc-js/tsconfig.json b/packages/opentelemetry-plugin-grpc-js/tsconfig.json index 00e509fd191..fed694f718a 100644 --- a/packages/opentelemetry-plugin-grpc-js/tsconfig.json +++ b/packages/opentelemetry-plugin-grpc-js/tsconfig.json @@ -9,15 +9,9 @@ "test/**/*.ts" ], "references": [ - { - "path": "../opentelemetry-api" - }, { "path": "../opentelemetry-context-async-hooks" }, - { - "path": "../opentelemetry-context-base" - }, { "path": "../opentelemetry-core" }, diff --git a/packages/opentelemetry-plugin-grpc/package.json b/packages/opentelemetry-plugin-grpc/package.json index 52420f3f52e..6ea8f6bac24 100644 --- a/packages/opentelemetry-plugin-grpc/package.json +++ b/packages/opentelemetry-plugin-grpc/package.json @@ -41,7 +41,6 @@ }, "devDependencies": { "@opentelemetry/context-async-hooks": "^0.17.0", - "@opentelemetry/context-base": "^0.17.0", "@opentelemetry/grpc-utils": "^0.17.0", "@opentelemetry/node": "^0.17.0", "@opentelemetry/tracing": "^0.17.0", @@ -64,7 +63,7 @@ "typescript": "4.1.3" }, "dependencies": { - "@opentelemetry/api": "^0.17.0", + "@opentelemetry/api": "^0.18.0", "@opentelemetry/core": "^0.17.0", "@opentelemetry/semantic-conventions": "^0.17.0", "shimmer": "^1.2.1" diff --git a/packages/opentelemetry-plugin-grpc/tsconfig.json b/packages/opentelemetry-plugin-grpc/tsconfig.json index 00e509fd191..fed694f718a 100644 --- a/packages/opentelemetry-plugin-grpc/tsconfig.json +++ b/packages/opentelemetry-plugin-grpc/tsconfig.json @@ -9,15 +9,9 @@ "test/**/*.ts" ], "references": [ - { - "path": "../opentelemetry-api" - }, { "path": "../opentelemetry-context-async-hooks" }, - { - "path": "../opentelemetry-context-base" - }, { "path": "../opentelemetry-core" }, diff --git a/packages/opentelemetry-plugin-http/package.json b/packages/opentelemetry-plugin-http/package.json index 9c01644d1af..033f29b03e4 100644 --- a/packages/opentelemetry-plugin-http/package.json +++ b/packages/opentelemetry-plugin-http/package.json @@ -42,7 +42,6 @@ }, "devDependencies": { "@opentelemetry/context-async-hooks": "^0.17.0", - "@opentelemetry/context-base": "^0.17.0", "@opentelemetry/node": "^0.17.0", "@opentelemetry/tracing": "^0.17.0", "@types/got": "9.6.11", @@ -70,7 +69,7 @@ "typescript": "4.1.3" }, "dependencies": { - "@opentelemetry/api": "^0.17.0", + "@opentelemetry/api": "^0.18.0", "@opentelemetry/core": "^0.17.0", "@opentelemetry/semantic-conventions": "^0.17.0", "semver": "^7.1.3", diff --git a/packages/opentelemetry-plugin-http/test/functionals/http-enable.test.ts b/packages/opentelemetry-plugin-http/test/functionals/http-enable.test.ts index 4514655a60f..310908abea0 100644 --- a/packages/opentelemetry-plugin-http/test/functionals/http-enable.test.ts +++ b/packages/opentelemetry-plugin-http/test/functionals/http-enable.test.ts @@ -40,7 +40,7 @@ import { Http, HttpPluginConfig } from '../../src/types'; import { assertSpan } from '../utils/assertSpan'; import { DummyPropagation } from '../utils/DummyPropagation'; import { httpRequest } from '../utils/httpRequest'; -import { ContextManager } from '@opentelemetry/context-base'; +import { ContextManager } from '@opentelemetry/api'; import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks'; import { ClientRequest, IncomingMessage, ServerResponse } from 'http'; diff --git a/packages/opentelemetry-plugin-http/test/functionals/utils.test.ts b/packages/opentelemetry-plugin-http/test/functionals/utils.test.ts index e472b849538..c14ee4bbb7c 100644 --- a/packages/opentelemetry-plugin-http/test/functionals/utils.test.ts +++ b/packages/opentelemetry-plugin-http/test/functionals/utils.test.ts @@ -140,13 +140,12 @@ describe('Utility', () => { }); describe('isIgnored()', () => { - let satisfiesPatternStub: sinon.SinonSpy<[string, IgnoreMatcher], boolean>; beforeEach(() => { - satisfiesPatternStub = sinon.spy(utils, 'satisfiesPattern'); + sinon.spy(utils, 'satisfiesPattern'); }); afterEach(() => { - satisfiesPatternStub.restore(); + sinon.restore(); }); it('should call isSatisfyPattern, n match', () => { @@ -159,7 +158,6 @@ describe('Utility', () => { }); it('should call isSatisfyPattern, match for function', () => { - satisfiesPatternStub.restore(); const answer1 = utils.isIgnored('/test/1', [ url => url.endsWith('/test/1'), ]); @@ -167,7 +165,6 @@ describe('Utility', () => { }); it('should not re-throw when function throws an exception', () => { - satisfiesPatternStub.restore(); const onException = (e: Error) => { // Do Nothing }; @@ -187,7 +184,6 @@ describe('Utility', () => { }); it('should call onException when function throws an exception', () => { - satisfiesPatternStub.restore(); const onException = sinon.spy(); assert.doesNotThrow(() => utils.isIgnored( diff --git a/packages/opentelemetry-plugin-http/tsconfig.json b/packages/opentelemetry-plugin-http/tsconfig.json index 08f0364911d..a6187d76f2d 100644 --- a/packages/opentelemetry-plugin-http/tsconfig.json +++ b/packages/opentelemetry-plugin-http/tsconfig.json @@ -9,15 +9,9 @@ "test/**/*.ts" ], "references": [ - { - "path": "../opentelemetry-api" - }, { "path": "../opentelemetry-context-async-hooks" }, - { - "path": "../opentelemetry-context-base" - }, { "path": "../opentelemetry-core" }, diff --git a/packages/opentelemetry-plugin-https/package.json b/packages/opentelemetry-plugin-https/package.json index 0650680a44a..5700d229b50 100644 --- a/packages/opentelemetry-plugin-https/package.json +++ b/packages/opentelemetry-plugin-https/package.json @@ -41,7 +41,6 @@ }, "devDependencies": { "@opentelemetry/context-async-hooks": "^0.17.0", - "@opentelemetry/context-base": "^0.17.0", "@opentelemetry/node": "^0.17.0", "@opentelemetry/tracing": "^0.17.0", "@types/got": "9.6.11", @@ -69,7 +68,7 @@ "typescript": "4.1.3" }, "dependencies": { - "@opentelemetry/api": "^0.17.0", + "@opentelemetry/api": "^0.18.0", "@opentelemetry/core": "^0.17.0", "@opentelemetry/plugin-http": "^0.17.0", "@opentelemetry/semantic-conventions": "^0.17.0", diff --git a/packages/opentelemetry-plugin-https/test/functionals/https-enable.test.ts b/packages/opentelemetry-plugin-https/test/functionals/https-enable.test.ts index 3c3c5911bbf..a4ad62f09e7 100644 --- a/packages/opentelemetry-plugin-https/test/functionals/https-enable.test.ts +++ b/packages/opentelemetry-plugin-https/test/functionals/https-enable.test.ts @@ -25,7 +25,7 @@ import { import { NodeTracerProvider } from '@opentelemetry/node'; import { Http, HttpPluginConfig } from '@opentelemetry/plugin-http'; import { AsyncHooksContextManager } from '@opentelemetry/context-async-hooks'; -import { ContextManager } from '@opentelemetry/context-base'; +import { ContextManager } from '@opentelemetry/api'; import { InMemorySpanExporter, SimpleSpanProcessor, diff --git a/packages/opentelemetry-plugin-https/tsconfig.json b/packages/opentelemetry-plugin-https/tsconfig.json index b4393cd5ea6..3308398df0a 100644 --- a/packages/opentelemetry-plugin-https/tsconfig.json +++ b/packages/opentelemetry-plugin-https/tsconfig.json @@ -9,15 +9,9 @@ "test/**/*.ts" ], "references": [ - { - "path": "../opentelemetry-api" - }, { "path": "../opentelemetry-context-async-hooks" }, - { - "path": "../opentelemetry-context-base" - }, { "path": "../opentelemetry-core" }, diff --git a/packages/opentelemetry-propagator-b3/package.json b/packages/opentelemetry-propagator-b3/package.json index 7ca41c14476..bfb51021b01 100644 --- a/packages/opentelemetry-propagator-b3/package.json +++ b/packages/opentelemetry-propagator-b3/package.json @@ -39,10 +39,9 @@ "access": "public" }, "dependencies": { - "@opentelemetry/api": "^0.17.0" + "@opentelemetry/api": "^0.18.0" }, "devDependencies": { - "@opentelemetry/context-base": "^0.17.0", "@types/mocha": "8.2.0", "@types/node": "14.14.20", "codecov": "3.8.1", diff --git a/packages/opentelemetry-propagator-b3/test/B3MultiPropagator.test.ts b/packages/opentelemetry-propagator-b3/test/B3MultiPropagator.test.ts index 3448283792d..211fd48c3e8 100644 --- a/packages/opentelemetry-propagator-b3/test/B3MultiPropagator.test.ts +++ b/packages/opentelemetry-propagator-b3/test/B3MultiPropagator.test.ts @@ -22,7 +22,7 @@ import { SpanContext, TraceFlags, } from '@opentelemetry/api'; -import { ROOT_CONTEXT } from '@opentelemetry/context-base'; +import { ROOT_CONTEXT } from '@opentelemetry/api'; import * as assert from 'assert'; import { B3MultiPropagator, diff --git a/packages/opentelemetry-propagator-b3/test/B3Propagator.test.ts b/packages/opentelemetry-propagator-b3/test/B3Propagator.test.ts index eb0aeb303d6..e68216e187e 100644 --- a/packages/opentelemetry-propagator-b3/test/B3Propagator.test.ts +++ b/packages/opentelemetry-propagator-b3/test/B3Propagator.test.ts @@ -22,8 +22,8 @@ import { TraceFlags, getSpanContext, setSpanContext, + ROOT_CONTEXT, } from '@opentelemetry/api'; -import { ROOT_CONTEXT } from '@opentelemetry/context-base'; import { B3Propagator } from '../src/B3Propagator'; import { B3InjectEncoding } from '../src/types'; import { B3_CONTEXT_HEADER } from '../src/B3SinglePropagator'; diff --git a/packages/opentelemetry-propagator-b3/test/B3SinglePropagator.test.ts b/packages/opentelemetry-propagator-b3/test/B3SinglePropagator.test.ts index e02fdae1cbc..02009821d62 100644 --- a/packages/opentelemetry-propagator-b3/test/B3SinglePropagator.test.ts +++ b/packages/opentelemetry-propagator-b3/test/B3SinglePropagator.test.ts @@ -24,7 +24,7 @@ import { SpanContext, TraceFlags, } from '@opentelemetry/api'; -import { ROOT_CONTEXT } from '@opentelemetry/context-base'; +import { ROOT_CONTEXT } from '@opentelemetry/api'; import * as assert from 'assert'; import { B3SinglePropagator, diff --git a/packages/opentelemetry-propagator-b3/tsconfig.json b/packages/opentelemetry-propagator-b3/tsconfig.json index 6ab0e214c2b..bdc94d22137 100644 --- a/packages/opentelemetry-propagator-b3/tsconfig.json +++ b/packages/opentelemetry-propagator-b3/tsconfig.json @@ -7,13 +7,5 @@ "include": [ "src/**/*.ts", "test/**/*.ts" - ], - "references": [ - { - "path": "../opentelemetry-api" - }, - { - "path": "../opentelemetry-context-base" - } ] } diff --git a/packages/opentelemetry-resource-detector-aws/package.json b/packages/opentelemetry-resource-detector-aws/package.json index f93258f70da..3e0b4b7fbf3 100644 --- a/packages/opentelemetry-resource-detector-aws/package.json +++ b/packages/opentelemetry-resource-detector-aws/package.json @@ -54,7 +54,7 @@ "typescript": "4.1.3" }, "dependencies": { - "@opentelemetry/api": "^0.17.0", + "@opentelemetry/api": "^0.18.0", "@opentelemetry/core": "^0.17.0", "@opentelemetry/resources": "^0.17.0" } diff --git a/packages/opentelemetry-resource-detector-aws/test/detectors/AwsBeanstalkDetector.test.ts b/packages/opentelemetry-resource-detector-aws/test/detectors/AwsBeanstalkDetector.test.ts index 4153276fbae..d5c8622cf86 100644 --- a/packages/opentelemetry-resource-detector-aws/test/detectors/AwsBeanstalkDetector.test.ts +++ b/packages/opentelemetry-resource-detector-aws/test/detectors/AwsBeanstalkDetector.test.ts @@ -37,29 +37,24 @@ describe('BeanstalkResourceDetector', () => { }; let readStub, fileStub; - let sandbox: sinon.SinonSandbox; - - beforeEach(() => { - sandbox = sinon.createSandbox(); - }); afterEach(() => { - sandbox.restore(); + sinon.restore(); }); it('should successfully return resource data', async () => { - fileStub = sandbox + fileStub = sinon .stub(AwsBeanstalkDetector, 'fileAccessAsync' as any) .resolves(); - readStub = sandbox + readStub = sinon .stub(AwsBeanstalkDetector, 'readFileAsync' as any) .resolves(JSON.stringify(data)); - sandbox.stub(JSON, 'parse').returns(data); + sinon.stub(JSON, 'parse').returns(data); const resource = await awsBeanstalkDetector.detect(); - sandbox.assert.calledOnce(fileStub); - sandbox.assert.calledOnce(readStub); + sinon.assert.calledOnce(fileStub); + sinon.assert.calledOnce(readStub); assert.ok(resource); assertServiceResource(resource, { name: 'elastic_beanstalk', @@ -70,18 +65,18 @@ describe('BeanstalkResourceDetector', () => { }); it('should successfully return resource data with noise', async () => { - fileStub = sandbox + fileStub = sinon .stub(AwsBeanstalkDetector, 'fileAccessAsync' as any) .resolves(); - readStub = sandbox + readStub = sinon .stub(AwsBeanstalkDetector, 'readFileAsync' as any) .resolves(JSON.stringify(noisyData)); - sandbox.stub(JSON, 'parse').returns(noisyData); + sinon.stub(JSON, 'parse').returns(noisyData); const resource = await awsBeanstalkDetector.detect(); - sandbox.assert.calledOnce(fileStub); - sandbox.assert.calledOnce(readStub); + sinon.assert.calledOnce(fileStub); + sinon.assert.calledOnce(readStub); assert.ok(resource); assertServiceResource(resource, { name: 'elastic_beanstalk', @@ -92,33 +87,33 @@ describe('BeanstalkResourceDetector', () => { }); it('should return empty resource when failing to read file', async () => { - fileStub = sandbox + fileStub = sinon .stub(AwsBeanstalkDetector, 'fileAccessAsync' as any) .resolves(); - readStub = sandbox + readStub = sinon .stub(AwsBeanstalkDetector, 'readFileAsync' as any) .rejects(err); const resource = await awsBeanstalkDetector.detect(); - sandbox.assert.calledOnce(fileStub); - sandbox.assert.calledOnce(readStub); + sinon.assert.calledOnce(fileStub); + sinon.assert.calledOnce(readStub); assert.ok(resource); assertEmptyResource(resource); }); it('should return empty resource when config file does not exist', async () => { - fileStub = sandbox + fileStub = sinon .stub(AwsBeanstalkDetector, 'fileAccessAsync' as any) .rejects(err); - readStub = sandbox + readStub = sinon .stub(AwsBeanstalkDetector, 'readFileAsync' as any) .resolves(JSON.stringify(data)); const resource = await awsBeanstalkDetector.detect(); - sandbox.assert.calledOnce(fileStub); - sandbox.assert.notCalled(readStub); + sinon.assert.calledOnce(fileStub); + sinon.assert.notCalled(readStub); assert.ok(resource); assertEmptyResource(resource); }); diff --git a/packages/opentelemetry-resource-detector-aws/test/detectors/AwsEcsDetector.test.ts b/packages/opentelemetry-resource-detector-aws/test/detectors/AwsEcsDetector.test.ts index a2abc7cb718..edfaebe4cd8 100644 --- a/packages/opentelemetry-resource-detector-aws/test/detectors/AwsEcsDetector.test.ts +++ b/packages/opentelemetry-resource-detector-aws/test/detectors/AwsEcsDetector.test.ts @@ -40,28 +40,26 @@ describe('BeanstalkResourceDetector', () => { const hostNameData = 'abcd.test.testing.com'; let readStub; - let sandbox: sinon.SinonSandbox; beforeEach(() => { - sandbox = sinon.createSandbox(); process.env.ECS_CONTAINER_METADATA_URI_V4 = ''; process.env.ECS_CONTAINER_METADATA_URI = ''; }); afterEach(() => { - sandbox.restore(); + sinon.restore(); }); it('should successfully return resource data', async () => { process.env.ECS_CONTAINER_METADATA_URI_V4 = 'ecs_metadata_v4_uri'; - sandbox.stub(os, 'hostname').returns(hostNameData); - readStub = sandbox + sinon.stub(os, 'hostname').returns(hostNameData); + readStub = sinon .stub(AwsEcsDetector, 'readFileAsync' as any) .resolves(correctCgroupData); const resource = await awsEcsDetector.detect(); - sandbox.assert.calledOnce(readStub); + sinon.assert.calledOnce(readStub); assert.ok(resource); assertContainerResource(resource, { name: 'abcd.test.testing.com', @@ -71,14 +69,14 @@ describe('BeanstalkResourceDetector', () => { it('should successfully return resource data with noisy cgroup file', async () => { process.env.ECS_CONTAINER_METADATA_URI = 'ecs_metadata_v3_uri'; - sandbox.stub(os, 'hostname').returns(hostNameData); - readStub = sandbox + sinon.stub(os, 'hostname').returns(hostNameData); + readStub = sinon .stub(AwsEcsDetector, 'readFileAsync' as any) .resolves(noisyCgroupData); const resource = await awsEcsDetector.detect(); - sandbox.assert.calledOnce(readStub); + sinon.assert.calledOnce(readStub); assert.ok(resource); assertContainerResource(resource, { name: 'abcd.test.testing.com', @@ -88,14 +86,14 @@ describe('BeanstalkResourceDetector', () => { it('should always return first valid line of data', async () => { process.env.ECS_CONTAINER_METADATA_URI = 'ecs_metadata_v3_uri'; - sandbox.stub(os, 'hostname').returns(hostNameData); - readStub = sandbox + sinon.stub(os, 'hostname').returns(hostNameData); + readStub = sinon .stub(AwsEcsDetector, 'readFileAsync' as any) .resolves(multiValidCgroupData); const resource = await awsEcsDetector.detect(); - sandbox.assert.calledOnce(readStub); + sinon.assert.calledOnce(readStub); assert.ok(resource); assertContainerResource(resource, { name: 'abcd.test.testing.com', @@ -104,28 +102,28 @@ describe('BeanstalkResourceDetector', () => { }); it('should empty resource without accessing files', async () => { - sandbox.stub(os, 'hostname').returns(hostNameData); - readStub = sandbox + sinon.stub(os, 'hostname').returns(hostNameData); + readStub = sinon .stub(AwsEcsDetector, 'readFileAsync' as any) .resolves(correctCgroupData); const resource = await awsEcsDetector.detect(); - sandbox.assert.notCalled(readStub); + sinon.assert.notCalled(readStub); assert.ok(resource); assertEmptyResource(resource); }); it('should return resource only with hostname attribute without cgroup file', async () => { process.env.ECS_CONTAINER_METADATA_URI_V4 = 'ecs_metadata_v4_uri'; - sandbox.stub(os, 'hostname').returns(hostNameData); - readStub = sandbox + sinon.stub(os, 'hostname').returns(hostNameData); + readStub = sinon .stub(AwsEcsDetector, 'readFileAsync' as any) .rejects(errorMsg.fileNotFoundError); const resource = await awsEcsDetector.detect(); - sandbox.assert.calledOnce(readStub); + sinon.assert.calledOnce(readStub); assert.ok(resource); assertContainerResource(resource, { name: 'abcd.test.testing.com', @@ -134,14 +132,12 @@ describe('BeanstalkResourceDetector', () => { it('should return resource only with hostname attribute when cgroup file does not contain valid container ID', async () => { process.env.ECS_CONTAINER_METADATA_URI_V4 = 'ecs_metadata_v4_uri'; - sandbox.stub(os, 'hostname').returns(hostNameData); - readStub = sandbox - .stub(AwsEcsDetector, 'readFileAsync' as any) - .resolves(''); + sinon.stub(os, 'hostname').returns(hostNameData); + readStub = sinon.stub(AwsEcsDetector, 'readFileAsync' as any).resolves(''); const resource = await awsEcsDetector.detect(); - sandbox.assert.calledOnce(readStub); + sinon.assert.calledOnce(readStub); assert.ok(resource); assertContainerResource(resource, { name: 'abcd.test.testing.com', @@ -150,14 +146,14 @@ describe('BeanstalkResourceDetector', () => { it('should return resource only with container ID attribute without hostname', async () => { process.env.ECS_CONTAINER_METADATA_URI_V4 = 'ecs_metadata_v4_uri'; - sandbox.stub(os, 'hostname').returns(''); - readStub = sandbox + sinon.stub(os, 'hostname').returns(''); + readStub = sinon .stub(AwsEcsDetector, 'readFileAsync' as any) .resolves(correctCgroupData); const resource = await awsEcsDetector.detect(); - sandbox.assert.calledOnce(readStub); + sinon.assert.calledOnce(readStub); assert.ok(resource); assertContainerResource(resource, { id: 'bcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklm', @@ -166,14 +162,14 @@ describe('BeanstalkResourceDetector', () => { it('should return empty resource when both hostname and container ID are invalid', async () => { process.env.ECS_CONTAINER_METADATA_URI_V4 = 'ecs_metadata_v4_uri'; - sandbox.stub(os, 'hostname').returns(''); - readStub = sandbox + sinon.stub(os, 'hostname').returns(''); + readStub = sinon .stub(AwsEcsDetector, 'readFileAsync' as any) .rejects(errorMsg.fileNotFoundError); const resource = await awsEcsDetector.detect(); - sandbox.assert.calledOnce(readStub); + sinon.assert.calledOnce(readStub); assert.ok(resource); assertEmptyResource(resource); }); diff --git a/packages/opentelemetry-resource-detector-aws/test/detectors/AwsEksDetector.test.ts b/packages/opentelemetry-resource-detector-aws/test/detectors/AwsEksDetector.test.ts index 017ee92bfd4..0c578540721 100644 --- a/packages/opentelemetry-resource-detector-aws/test/detectors/AwsEksDetector.test.ts +++ b/packages/opentelemetry-resource-detector-aws/test/detectors/AwsEksDetector.test.ts @@ -39,29 +39,27 @@ describe('awsEksDetector', () => { const mockedClusterResponse = '{"data":{"cluster.name":"my-cluster"}}'; const mockedAwsAuth = 'my-auth'; const k8s_token = 'Bearer 31ada4fd-adec-460c-809a-9e56ceb75269'; - let sandbox: sinon.SinonSandbox; let readStub, fileStub, getCredStub; beforeEach(() => { - sandbox = sinon.createSandbox(); nock.disableNetConnect(); nock.cleanAll(); }); afterEach(() => { - sandbox.restore(); + sinon.restore(); nock.enableNetConnect(); }); describe('on successful request', () => { it('should return an aws_eks_instance_resource', async () => { - fileStub = sandbox + fileStub = sinon .stub(AwsEksDetector, 'fileAccessAsync' as any) .resolves(); - readStub = sandbox + readStub = sinon .stub(AwsEksDetector, 'readFileAsync' as any) .resolves(correctCgroupData); - getCredStub = sandbox + getCredStub = sinon .stub(awsEksDetector, '_getK8sCredHeader' as any) .resolves(k8s_token); const scope = nock('https://' + K8S_SVC_URL) @@ -77,9 +75,9 @@ describe('awsEksDetector', () => { scope.done(); - sandbox.assert.calledOnce(fileStub); - sandbox.assert.calledTwice(readStub); - sandbox.assert.calledTwice(getCredStub); + sinon.assert.calledOnce(fileStub); + sinon.assert.calledTwice(readStub); + sinon.assert.calledTwice(getCredStub); assert.ok(resource); assertK8sResource(resource, { @@ -91,14 +89,14 @@ describe('awsEksDetector', () => { }); it('should return a resource with clusterName attribute without cgroup file', async () => { - fileStub = sandbox + fileStub = sinon .stub(AwsEksDetector, 'fileAccessAsync' as any) .resolves(); - readStub = sandbox + readStub = sinon .stub(AwsEksDetector, 'readFileAsync' as any) .onSecondCall() .rejects(errorMsg.fileNotFoundError); - getCredStub = sandbox + getCredStub = sinon .stub(awsEksDetector, '_getK8sCredHeader' as any) .resolves(k8s_token); const scope = nock('https://' + K8S_SVC_URL) @@ -121,13 +119,13 @@ describe('awsEksDetector', () => { }); it('should return a resource with container ID attribute without a clusterName', async () => { - fileStub = sandbox + fileStub = sinon .stub(AwsEksDetector, 'fileAccessAsync' as any) .resolves(); - readStub = sandbox + readStub = sinon .stub(AwsEksDetector, 'readFileAsync' as any) .resolves(correctCgroupData); - getCredStub = sandbox + getCredStub = sinon .stub(awsEksDetector, '_getK8sCredHeader' as any) .resolves(k8s_token); const scope = nock('https://' + K8S_SVC_URL) @@ -150,14 +148,14 @@ describe('awsEksDetector', () => { }); it('should return a resource with clusterName attribute when cgroup file does not contain valid Container ID', async () => { - fileStub = sandbox + fileStub = sinon .stub(AwsEksDetector, 'fileAccessAsync' as any) .resolves(); - readStub = sandbox + readStub = sinon .stub(AwsEksDetector, 'readFileAsync' as any) .onSecondCall() .resolves(''); - getCredStub = sandbox + getCredStub = sinon .stub(awsEksDetector, '_getK8sCredHeader' as any) .resolves(k8s_token); const scope = nock('https://' + K8S_SVC_URL) @@ -181,13 +179,13 @@ describe('awsEksDetector', () => { }); it('should return an empty resource when not running on Eks', async () => { - fileStub = sandbox + fileStub = sinon .stub(AwsEksDetector, 'fileAccessAsync' as any) .resolves(''); - readStub = sandbox + readStub = sinon .stub(AwsEksDetector, 'readFileAsync' as any) .resolves(correctCgroupData); - getCredStub = sandbox + getCredStub = sinon .stub(awsEksDetector, '_getK8sCredHeader' as any) .resolves(k8s_token); const scope = nock('https://' + K8S_SVC_URL) @@ -208,7 +206,7 @@ describe('awsEksDetector', () => { const errorMsg = { fileNotFoundError: new Error('cannot file k8s token file'), }; - fileStub = sandbox + fileStub = sinon .stub(AwsEksDetector, 'fileAccessAsync' as any) .rejects(errorMsg.fileNotFoundError); @@ -219,15 +217,15 @@ describe('awsEksDetector', () => { }); it('should return an empty resource when containerId and clusterName are invalid', async () => { - fileStub = sandbox + fileStub = sinon .stub(AwsEksDetector, 'fileAccessAsync' as any) .resolves(''); - readStub = sandbox + readStub = sinon .stub(AwsEksDetector, 'readFileAsync' as any) .onSecondCall() .rejects(errorMsg.fileNotFoundError); - getCredStub = sandbox + getCredStub = sinon .stub(awsEksDetector, '_getK8sCredHeader' as any) .resolves(k8s_token); const scope = nock('https://' + K8S_SVC_URL) @@ -251,13 +249,13 @@ describe('awsEksDetector', () => { describe('on unsuccesful request', () => { it('should throw when receiving error response code', async () => { const expectedError = new Error('EKS metadata api request timed out.'); - fileStub = sandbox + fileStub = sinon .stub(AwsEksDetector, 'fileAccessAsync' as any) .resolves(); - readStub = sandbox + readStub = sinon .stub(AwsEksDetector, 'readFileAsync' as any) .resolves(correctCgroupData); - getCredStub = sandbox + getCredStub = sinon .stub(awsEksDetector, '_getK8sCredHeader' as any) .resolves(k8s_token); const scope = nock('https://' + K8S_SVC_URL) @@ -278,13 +276,13 @@ describe('awsEksDetector', () => { it('should return an empty resource when timed out', async () => { const expectedError = new Error('Failed to load page, status code: 404'); - fileStub = sandbox + fileStub = sinon .stub(AwsEksDetector, 'fileAccessAsync' as any) .resolves(); - readStub = sandbox + readStub = sinon .stub(AwsEksDetector, 'readFileAsync' as any) .resolves(correctCgroupData); - getCredStub = sandbox + getCredStub = sinon .stub(awsEksDetector, '_getK8sCredHeader' as any) .resolves(k8s_token); const scope = nock('https://' + K8S_SVC_URL) diff --git a/packages/opentelemetry-resource-detector-aws/tsconfig.json b/packages/opentelemetry-resource-detector-aws/tsconfig.json index 954354a3a00..6549996003e 100644 --- a/packages/opentelemetry-resource-detector-aws/tsconfig.json +++ b/packages/opentelemetry-resource-detector-aws/tsconfig.json @@ -9,9 +9,6 @@ "test/**/*.ts" ], "references": [ - { - "path": "../opentelemetry-api" - }, { "path": "../opentelemetry-core" }, diff --git a/packages/opentelemetry-resource-detector-gcp/package.json b/packages/opentelemetry-resource-detector-gcp/package.json index 0e96e073df3..4040a1961e0 100644 --- a/packages/opentelemetry-resource-detector-gcp/package.json +++ b/packages/opentelemetry-resource-detector-gcp/package.json @@ -54,7 +54,7 @@ "typescript": "4.1.3" }, "dependencies": { - "@opentelemetry/api": "^0.17.0", + "@opentelemetry/api": "^0.18.0", "@opentelemetry/resources": "^0.17.0", "gcp-metadata": "^4.1.4", "semver": "7.3.4" diff --git a/packages/opentelemetry-resource-detector-gcp/tsconfig.json b/packages/opentelemetry-resource-detector-gcp/tsconfig.json index 954354a3a00..6549996003e 100644 --- a/packages/opentelemetry-resource-detector-gcp/tsconfig.json +++ b/packages/opentelemetry-resource-detector-gcp/tsconfig.json @@ -9,9 +9,6 @@ "test/**/*.ts" ], "references": [ - { - "path": "../opentelemetry-api" - }, { "path": "../opentelemetry-core" }, diff --git a/packages/opentelemetry-resources/package.json b/packages/opentelemetry-resources/package.json index 516e61aeb4a..81c2ced7ca3 100644 --- a/packages/opentelemetry-resources/package.json +++ b/packages/opentelemetry-resources/package.json @@ -58,7 +58,7 @@ "typescript": "4.1.3" }, "dependencies": { - "@opentelemetry/api": "^0.17.0", + "@opentelemetry/api": "^0.18.0", "@opentelemetry/core": "^0.17.0" } } diff --git a/packages/opentelemetry-resources/test/detectors/ProcessDetector.test.ts b/packages/opentelemetry-resources/test/detectors/ProcessDetector.test.ts index 013b919a512..ff4d3fa7a7a 100644 --- a/packages/opentelemetry-resources/test/detectors/ProcessDetector.test.ts +++ b/packages/opentelemetry-resources/test/detectors/ProcessDetector.test.ts @@ -21,20 +21,14 @@ import { } from '../util/resource-assertions'; describe('processDetector()', () => { - let sandbox: sinon.SinonSandbox; - - beforeEach(() => { - sandbox = sinon.createSandbox(); - }); - afterEach(() => { - sandbox.restore(); + sinon.restore(); }); it('should return resource information from process', async () => { - sandbox.stub(process, 'pid').value(1234); - sandbox.stub(process, 'title').value('otProcess'); - sandbox + sinon.stub(process, 'pid').value(1234); + sinon.stub(process, 'title').value('otProcess'); + sinon .stub(process, 'argv') .value(['/tmp/node', '/home/ot/test.js', 'arg1', 'arg2']); @@ -47,9 +41,9 @@ describe('processDetector()', () => { }); }); it('should return empty resources if title, command and commondLine is missing', async () => { - sandbox.stub(process, 'pid').value(1234); - sandbox.stub(process, 'title').value(undefined); - sandbox.stub(process, 'argv').value([]); + sinon.stub(process, 'pid').value(1234); + sinon.stub(process, 'title').value(undefined); + sinon.stub(process, 'argv').value([]); const resource: Resource = await processDetector.detect(); assertEmptyResource(resource); }); diff --git a/packages/opentelemetry-resources/tsconfig.json b/packages/opentelemetry-resources/tsconfig.json index 951358df054..789e61fc86b 100644 --- a/packages/opentelemetry-resources/tsconfig.json +++ b/packages/opentelemetry-resources/tsconfig.json @@ -9,9 +9,6 @@ "test/**/*.ts" ], "references": [ - { - "path": "../opentelemetry-api" - }, { "path": "../opentelemetry-core" } diff --git a/packages/opentelemetry-sdk-node/package.json b/packages/opentelemetry-sdk-node/package.json index dc30733ff03..39d40b14db0 100644 --- a/packages/opentelemetry-sdk-node/package.json +++ b/packages/opentelemetry-sdk-node/package.json @@ -40,9 +40,8 @@ "access": "public" }, "dependencies": { - "@opentelemetry/api": "^0.17.0", + "@opentelemetry/api": "^0.18.0", "@opentelemetry/api-metrics": "^0.17.0", - "@opentelemetry/context-base": "^0.17.0", "@opentelemetry/core": "^0.17.0", "@opentelemetry/instrumentation": "^0.17.0", "@opentelemetry/metrics": "^0.17.0", diff --git a/packages/opentelemetry-sdk-node/src/index.ts b/packages/opentelemetry-sdk-node/src/index.ts index b511af8046a..500eb03dd56 100644 --- a/packages/opentelemetry-sdk-node/src/index.ts +++ b/packages/opentelemetry-sdk-node/src/index.ts @@ -15,7 +15,7 @@ */ export * as api from '@opentelemetry/api'; -export * as contextBase from '@opentelemetry/context-base'; +export * as contextBase from '@opentelemetry/api'; export * as core from '@opentelemetry/core'; export * as metrics from '@opentelemetry/metrics'; export * as node from '@opentelemetry/node'; diff --git a/packages/opentelemetry-sdk-node/src/sdk.ts b/packages/opentelemetry-sdk-node/src/sdk.ts index 23f8ab7ec80..dd760d9e990 100644 --- a/packages/opentelemetry-sdk-node/src/sdk.ts +++ b/packages/opentelemetry-sdk-node/src/sdk.ts @@ -16,7 +16,7 @@ import { TextMapPropagator } from '@opentelemetry/api'; import { metrics } from '@opentelemetry/api-metrics'; -import { ContextManager } from '@opentelemetry/context-base'; +import { ContextManager } from '@opentelemetry/api'; import { MeterConfig, MeterProvider } from '@opentelemetry/metrics'; import { InstrumentationOption, diff --git a/packages/opentelemetry-sdk-node/src/types.ts b/packages/opentelemetry-sdk-node/src/types.ts index abcad0a274b..c017cf03222 100644 --- a/packages/opentelemetry-sdk-node/src/types.ts +++ b/packages/opentelemetry-sdk-node/src/types.ts @@ -15,7 +15,7 @@ */ import { SpanAttributes, TextMapPropagator, Sampler } from '@opentelemetry/api'; -import type { ContextManager } from '@opentelemetry/context-base'; +import type { ContextManager } from '@opentelemetry/api'; import { InstrumentationOption } from '@opentelemetry/instrumentation'; import { MetricExporter, Processor } from '@opentelemetry/metrics'; import { Resource } from '@opentelemetry/resources'; diff --git a/packages/opentelemetry-sdk-node/test/sdk.test.ts b/packages/opentelemetry-sdk-node/test/sdk.test.ts index 3b8f69f560a..6b8e59d5d14 100644 --- a/packages/opentelemetry-sdk-node/test/sdk.test.ts +++ b/packages/opentelemetry-sdk-node/test/sdk.test.ts @@ -29,7 +29,7 @@ import { AsyncHooksContextManager, AsyncLocalStorageContextManager, } from '@opentelemetry/context-async-hooks'; -import { NoopContextManager } from '@opentelemetry/context-base'; +import { NoopContextManager } from '@opentelemetry/api'; import { CompositePropagator } from '@opentelemetry/core'; import { ConsoleMetricExporter, MeterProvider } from '@opentelemetry/metrics'; import { NodeTracerProvider } from '@opentelemetry/node'; @@ -41,7 +41,7 @@ import { assertCloudResource, assertHostResource, assertServiceResource, -} from '@opentelemetry/resources/test/util/resource-assertions'; +} from '@opentelemetry/resources/build/test/util/resource-assertions'; import { ConsoleSpanExporter, SimpleSpanProcessor, @@ -116,9 +116,7 @@ describe('Node SDK', () => { propagation['_getGlobalPropagator']() instanceof NoopTextMapPropagator ); - const apiTracerProvider = trace.getTracerProvider(); - console.log(apiTracerProvider); - assert.ok(apiTracerProvider instanceof ProxyTracerProvider); + const apiTracerProvider = trace.getTracerProvider() as ProxyTracerProvider; assert.ok(apiTracerProvider.getDelegate() instanceof NoopTracerProvider); assert.ok(metrics.getMeterProvider() instanceof NoopMeterProvider); @@ -140,8 +138,7 @@ describe('Node SDK', () => { assert.ok( propagation['_getGlobalPropagator']() instanceof CompositePropagator ); - const apiTracerProvider = trace.getTracerProvider(); - assert.ok(apiTracerProvider instanceof ProxyTracerProvider); + const apiTracerProvider = trace.getTracerProvider() as ProxyTracerProvider; assert.ok(apiTracerProvider.getDelegate() instanceof NodeTracerProvider); }); @@ -164,8 +161,7 @@ describe('Node SDK', () => { assert.ok( propagation['_getGlobalPropagator']() instanceof CompositePropagator ); - const apiTracerProvider = trace.getTracerProvider(); - assert.ok(apiTracerProvider instanceof ProxyTracerProvider); + const apiTracerProvider = trace.getTracerProvider() as ProxyTracerProvider; assert.ok(apiTracerProvider.getDelegate() instanceof NodeTracerProvider); }); @@ -184,8 +180,7 @@ describe('Node SDK', () => { propagation['_getGlobalPropagator']() instanceof NoopTextMapPropagator ); - const apiTracerProvider = trace.getTracerProvider(); - assert.ok(apiTracerProvider instanceof ProxyTracerProvider); + const apiTracerProvider = trace.getTracerProvider() as ProxyTracerProvider; assert.ok(apiTracerProvider.getDelegate() instanceof NoopTracerProvider); assert.ok(metrics.getMeterProvider() instanceof MeterProvider); @@ -359,11 +354,6 @@ describe('Node SDK', () => { }); }; - beforeEach(() => { - diag.setLogLevel(DiagLogLevel.VERBOSE); - diag.setLogger(); - }); - it('prints detected resources and debug messages to the logger', async () => { const sdk = new NodeSDK({ autoDetectResources: true, @@ -372,10 +362,13 @@ describe('Node SDK', () => { // This test depends on the env detector to be functioning as intended const mockedLoggerMethod = Sinon.fake(); const mockedVerboseLoggerMethod = Sinon.fake(); - diag.setLogger({ - debug: mockedLoggerMethod, - verbose: mockedVerboseLoggerMethod, - } as any); + diag.setLogger( + { + debug: mockedLoggerMethod, + verbose: mockedVerboseLoggerMethod, + } as any, + DiagLogLevel.VERBOSE + ); await sdk.detectResources(); @@ -408,8 +401,6 @@ describe('Node SDK', () => { describe('with missing environment variable', () => { beforeEach(() => { delete process.env.OTEL_RESOURCE_ATTRIBUTES; - diag.setLogLevel(DiagLogLevel.DEBUG); - diag.setLogger(); }); it('prints correct error messages when EnvDetector has no env variable', async () => { @@ -417,9 +408,12 @@ describe('Node SDK', () => { autoDetectResources: true, }); const mockedLoggerMethod = Sinon.fake(); - diag.setLogger({ - debug: mockedLoggerMethod, - } as any); + diag.setLogger( + { + debug: mockedLoggerMethod, + } as any, + DiagLogLevel.DEBUG + ); await sdk.detectResources(); @@ -435,8 +429,6 @@ describe('Node SDK', () => { describe('with a faulty environment variable', () => { beforeEach(() => { process.env.OTEL_RESOURCE_ATTRIBUTES = 'bad=~attribute'; - diag.setLogLevel(DiagLogLevel.DEBUG); - diag.setLogger(); }); it('prints correct error messages when EnvDetector has an invalid variable', async () => { @@ -444,9 +436,12 @@ describe('Node SDK', () => { autoDetectResources: true, }); const mockedLoggerMethod = Sinon.fake(); - diag.setLogger({ - debug: mockedLoggerMethod, - } as any); + diag.setLogger( + { + debug: mockedLoggerMethod, + } as any, + DiagLogLevel.DEBUG + ); await sdk.detectResources(); diff --git a/packages/opentelemetry-sdk-node/tsconfig.json b/packages/opentelemetry-sdk-node/tsconfig.json index e3291a2cb02..6f2f2796df5 100644 --- a/packages/opentelemetry-sdk-node/tsconfig.json +++ b/packages/opentelemetry-sdk-node/tsconfig.json @@ -9,18 +9,12 @@ "test/**/*.ts" ], "references": [ - { - "path": "../opentelemetry-api" - }, { "path": "../opentelemetry-api-metrics" }, { "path": "../opentelemetry-context-async-hooks" }, - { - "path": "../opentelemetry-context-base" - }, { "path": "../opentelemetry-core" }, diff --git a/packages/opentelemetry-shim-opentracing/package.json b/packages/opentelemetry-shim-opentracing/package.json index 915b81dc334..9fbd8cce9db 100644 --- a/packages/opentelemetry-shim-opentracing/package.json +++ b/packages/opentelemetry-shim-opentracing/package.json @@ -53,7 +53,7 @@ "typescript": "4.1.3" }, "dependencies": { - "@opentelemetry/api": "^0.17.0", + "@opentelemetry/api": "^0.18.0", "@opentelemetry/core": "^0.17.0", "opentracing": "^0.14.4" } diff --git a/packages/opentelemetry-shim-opentracing/tsconfig.json b/packages/opentelemetry-shim-opentracing/tsconfig.json index 6f45e411475..ee62966fd1f 100644 --- a/packages/opentelemetry-shim-opentracing/tsconfig.json +++ b/packages/opentelemetry-shim-opentracing/tsconfig.json @@ -9,9 +9,6 @@ "test/**/*.ts" ], "references": [ - { - "path": "../opentelemetry-api" - }, { "path": "../opentelemetry-core" }, diff --git a/packages/opentelemetry-tracing/package.json b/packages/opentelemetry-tracing/package.json index fac68331610..4662ef0f64b 100644 --- a/packages/opentelemetry-tracing/package.json +++ b/packages/opentelemetry-tracing/package.json @@ -73,8 +73,7 @@ "webpack": "4.46.0" }, "dependencies": { - "@opentelemetry/api": "^0.17.0", - "@opentelemetry/context-base": "^0.17.0", + "@opentelemetry/api": "^0.18.0", "@opentelemetry/core": "^0.17.0", "@opentelemetry/resources": "^0.17.0", "@opentelemetry/semantic-conventions": "^0.17.0", diff --git a/packages/opentelemetry-tracing/src/types.ts b/packages/opentelemetry-tracing/src/types.ts index 10961a51171..31561c19154 100644 --- a/packages/opentelemetry-tracing/src/types.ts +++ b/packages/opentelemetry-tracing/src/types.ts @@ -17,7 +17,7 @@ import { TextMapPropagator, Sampler } from '@opentelemetry/api'; import { IdGenerator } from '@opentelemetry/core'; -import { ContextManager } from '@opentelemetry/context-base'; +import { ContextManager } from '@opentelemetry/api'; import { Resource } from '@opentelemetry/resources'; /** diff --git a/packages/opentelemetry-tracing/test/BasicTracerProvider.test.ts b/packages/opentelemetry-tracing/test/BasicTracerProvider.test.ts index cbceebb7424..bfef16e093b 100644 --- a/packages/opentelemetry-tracing/test/BasicTracerProvider.test.ts +++ b/packages/opentelemetry-tracing/test/BasicTracerProvider.test.ts @@ -34,16 +34,14 @@ import * as sinon from 'sinon'; import { BasicTracerProvider, Span } from '../src'; describe('BasicTracerProvider', () => { - let sandbox: sinon.SinonSandbox; let removeEvent: Function | undefined; beforeEach(() => { context.disable(); - sandbox = sinon.createSandbox(); }); afterEach(() => { - sandbox.restore(); + sinon.restore(); if (removeEvent) { removeEvent(); removeEvent = undefined; @@ -315,7 +313,7 @@ describe('BasicTracerProvider', () => { describe('.shutdown()', () => { it('should trigger shutdown when manually invoked', () => { const tracerProvider = new BasicTracerProvider(); - const shutdownStub = sandbox.stub( + const shutdownStub = sinon.stub( tracerProvider.getActiveSpanProcessor(), 'shutdown' ); diff --git a/packages/opentelemetry-tracing/test/export/TestStackContextManager.ts b/packages/opentelemetry-tracing/test/export/TestStackContextManager.ts index 00c86d18c4b..5196c86d79e 100644 --- a/packages/opentelemetry-tracing/test/export/TestStackContextManager.ts +++ b/packages/opentelemetry-tracing/test/export/TestStackContextManager.ts @@ -14,11 +14,7 @@ * limitations under the License. */ -import { - ContextManager, - Context, - ROOT_CONTEXT, -} from '@opentelemetry/context-base'; +import { ContextManager, Context, ROOT_CONTEXT } from '@opentelemetry/api'; /** * A test-only ContextManager that uses an in-memory stack to keep track of diff --git a/packages/opentelemetry-tracing/tsconfig.json b/packages/opentelemetry-tracing/tsconfig.json index 62cad81a138..b16c7037b42 100644 --- a/packages/opentelemetry-tracing/tsconfig.json +++ b/packages/opentelemetry-tracing/tsconfig.json @@ -9,12 +9,6 @@ "test/**/*.ts" ], "references": [ - { - "path": "../opentelemetry-api" - }, - { - "path": "../opentelemetry-context-base" - }, { "path": "../opentelemetry-core" }, diff --git a/packages/opentelemetry-web/package.json b/packages/opentelemetry-web/package.json index 7d70693849f..dc632c6a838 100644 --- a/packages/opentelemetry-web/package.json +++ b/packages/opentelemetry-web/package.json @@ -74,8 +74,7 @@ "webpack-merge": "5.7.3" }, "dependencies": { - "@opentelemetry/api": "^0.17.0", - "@opentelemetry/context-base": "^0.17.0", + "@opentelemetry/api": "^0.18.0", "@opentelemetry/core": "^0.17.0", "@opentelemetry/semantic-conventions": "^0.17.0", "@opentelemetry/tracing": "^0.17.0" diff --git a/packages/opentelemetry-web/src/StackContextManager.ts b/packages/opentelemetry-web/src/StackContextManager.ts index b63598dff09..0c87d6e7c60 100644 --- a/packages/opentelemetry-web/src/StackContextManager.ts +++ b/packages/opentelemetry-web/src/StackContextManager.ts @@ -14,8 +14,7 @@ * limitations under the License. */ -import { Context } from '@opentelemetry/api'; -import { ContextManager, ROOT_CONTEXT } from '@opentelemetry/context-base'; +import { Context, ContextManager, ROOT_CONTEXT } from '@opentelemetry/api'; /** * Stack Context Manager for managing the state in web diff --git a/packages/opentelemetry-web/test/WebTracerProvider.test.ts b/packages/opentelemetry-web/test/WebTracerProvider.test.ts index b5f0c65d2d8..ea623f9a4e5 100644 --- a/packages/opentelemetry-web/test/WebTracerProvider.test.ts +++ b/packages/opentelemetry-web/test/WebTracerProvider.test.ts @@ -14,8 +14,7 @@ * limitations under the License. */ -import { context, getSpan, setSpan } from '@opentelemetry/api'; -import { ContextManager } from '@opentelemetry/context-base'; +import { context, getSpan, setSpan, ContextManager } from '@opentelemetry/api'; import { ZoneContextManager } from '@opentelemetry/context-zone'; import { B3Propagator } from '@opentelemetry/propagator-b3'; import { Resource, TELEMETRY_SDK_RESOURCE } from '@opentelemetry/resources'; diff --git a/packages/opentelemetry-web/test/registration.test.ts b/packages/opentelemetry-web/test/registration.test.ts index 123b9667d1f..89ff0c0cd45 100644 --- a/packages/opentelemetry-web/test/registration.test.ts +++ b/packages/opentelemetry-web/test/registration.test.ts @@ -16,12 +16,12 @@ import { context, + NoopContextManager, NoopTextMapPropagator, propagation, trace, ProxyTracerProvider, } from '@opentelemetry/api'; -import { NoopContextManager } from '@opentelemetry/context-base'; import { CompositePropagator } from '@opentelemetry/core'; import * as assert from 'assert'; import { StackContextManager, WebTracerProvider } from '../src'; @@ -41,8 +41,7 @@ describe('API registration', () => { assert.ok( propagation['_getGlobalPropagator']() instanceof CompositePropagator ); - const apiTracerProvider = trace.getTracerProvider(); - assert.ok(apiTracerProvider instanceof ProxyTracerProvider); + const apiTracerProvider = trace.getTracerProvider() as ProxyTracerProvider; assert.ok(apiTracerProvider.getDelegate() === tracerProvider); }); @@ -60,8 +59,7 @@ describe('API registration', () => { assert.ok(context['_getContextManager']() === contextManager); assert.ok(propagation['_getGlobalPropagator']() === propagator); - const apiTracerProvider = trace.getTracerProvider(); - assert.ok(apiTracerProvider instanceof ProxyTracerProvider); + const apiTracerProvider = trace.getTracerProvider() as ProxyTracerProvider; assert.ok(apiTracerProvider.getDelegate() === tracerProvider); }); @@ -76,8 +74,7 @@ describe('API registration', () => { assert.ok( propagation['_getGlobalPropagator']() instanceof CompositePropagator ); - const apiTracerProvider = trace.getTracerProvider(); - assert.ok(apiTracerProvider instanceof ProxyTracerProvider); + const apiTracerProvider = trace.getTracerProvider() as ProxyTracerProvider; assert.ok(apiTracerProvider.getDelegate() === tracerProvider); }); @@ -92,8 +89,7 @@ describe('API registration', () => { ); assert.ok(context['_getContextManager']() instanceof StackContextManager); - const apiTracerProvider = trace.getTracerProvider(); - assert.ok(apiTracerProvider instanceof ProxyTracerProvider); + const apiTracerProvider = trace.getTracerProvider() as ProxyTracerProvider; assert.ok(apiTracerProvider.getDelegate() === tracerProvider); }); }); diff --git a/packages/opentelemetry-web/test/utils.test.ts b/packages/opentelemetry-web/test/utils.test.ts index 5189d397ee2..3296ff62521 100644 --- a/packages/opentelemetry-web/test/utils.test.ts +++ b/packages/opentelemetry-web/test/utils.test.ts @@ -124,14 +124,8 @@ function createResource( } describe('utils', () => { - let sandbox: sinon.SinonSandbox; - - beforeEach(() => { - sandbox = sinon.createSandbox(); - }); - afterEach(() => { - sandbox.restore(); + sinon.restore(); }); describe('addSpanNetworkEvents', () => { @@ -232,18 +226,12 @@ describe('utils', () => { }); describe('getResource', () => { const startTime = [0, 123123123] as HrTime; - let spyHrTime: any; beforeEach(() => { const time = createHrTime(startTime, 500); - sandbox.stub(performance, 'timeOrigin').value(0); - sandbox - .stub(performance, 'now') - .callsFake(() => hrTimeToNanoseconds(time)); + sinon.stub(performance, 'timeOrigin').value(0); + sinon.stub(performance, 'now').callsFake(() => hrTimeToNanoseconds(time)); - spyHrTime = sinon.stub(core, 'hrTime').returns(time); - }); - afterEach(() => { - spyHrTime.restore(); + sinon.stub(core, 'hrTime').returns(time); }); describe('when resources are empty', () => { diff --git a/packages/opentelemetry-web/tsconfig.json b/packages/opentelemetry-web/tsconfig.json index 72e685708cb..7d15edb8532 100644 --- a/packages/opentelemetry-web/tsconfig.json +++ b/packages/opentelemetry-web/tsconfig.json @@ -10,12 +10,6 @@ "test/**/*.ts" ], "references": [ - { - "path": "../opentelemetry-api" - }, - { - "path": "../opentelemetry-context-base" - }, { "path": "../opentelemetry-context-zone" }, diff --git a/tsconfig.json b/tsconfig.json index f53b81e90e7..9a415038632 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -14,15 +14,9 @@ { "path": "packages/opentelemetry-api-metrics" }, - { - "path": "packages/opentelemetry-api" - }, { "path": "packages/opentelemetry-context-async-hooks" }, - { - "path": "packages/opentelemetry-context-base" - }, { "path": "packages/opentelemetry-context-zone-peer-dep" },