From df5ca9aab79f85dcb768c475c0386d9cde16418d Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Tue, 15 Oct 2019 01:58:59 +0200 Subject: [PATCH 01/33] feat(plugin-document-load): new plugin for document load for web tracer --- examples/tracer-web/index.html | 4 +- examples/tracer-web/index.js | 42 +-- examples/tracer-web/package.json | 8 +- .../opentelemetry-core/src/common/time.ts | 4 +- .../opentelemetry-exporter-console/LICENSE | 201 +++++++++++++ .../opentelemetry-exporter-console/README.md | 55 ++++ .../karma.conf.js | 24 ++ .../package.json | 72 +++++ .../src/ConsoleExporter.ts | 81 +++++ .../src/index.ts | 17 ++ .../test/ConsoleExporter.test.ts | 75 +++++ .../test/index-webpack.ts | 20 ++ .../tsconfig.json | 11 + .../tslint.json | 4 + .../webpack/test.config.js | 34 +++ .../karma.conf.js | 24 ++ .../package.json | 76 +++++ .../src/documentLoad.ts | 283 ++++++++++++++++++ .../src/enums/AttributeNames.ts | 25 ++ .../src/enums/PerformanceTimingNames.ts | 37 +++ .../src/index.ts | 17 ++ .../src/types.ts | 25 ++ .../src/utils.ts | 24 ++ .../test/documentLoad.test.ts | 282 +++++++++++++++++ .../test/index-webpack.ts | 20 ++ .../tsconfig.json | 11 + .../tslint.json | 4 + .../webpack/test.config.js | 34 +++ packages/opentelemetry-web/package.json | 3 +- packages/opentelemetry-web/src/WebTracer.ts | 41 ++- .../opentelemetry-web/test/WebTracer.test.ts | 28 +- 31 files changed, 1537 insertions(+), 49 deletions(-) create mode 100644 packages/opentelemetry-exporter-console/LICENSE create mode 100644 packages/opentelemetry-exporter-console/README.md create mode 100644 packages/opentelemetry-exporter-console/karma.conf.js create mode 100644 packages/opentelemetry-exporter-console/package.json create mode 100644 packages/opentelemetry-exporter-console/src/ConsoleExporter.ts create mode 100644 packages/opentelemetry-exporter-console/src/index.ts create mode 100644 packages/opentelemetry-exporter-console/test/ConsoleExporter.test.ts create mode 100644 packages/opentelemetry-exporter-console/test/index-webpack.ts create mode 100644 packages/opentelemetry-exporter-console/tsconfig.json create mode 100644 packages/opentelemetry-exporter-console/tslint.json create mode 100644 packages/opentelemetry-exporter-console/webpack/test.config.js create mode 100644 packages/opentelemetry-plugin-document-load/karma.conf.js create mode 100644 packages/opentelemetry-plugin-document-load/package.json create mode 100644 packages/opentelemetry-plugin-document-load/src/documentLoad.ts create mode 100644 packages/opentelemetry-plugin-document-load/src/enums/AttributeNames.ts create mode 100644 packages/opentelemetry-plugin-document-load/src/enums/PerformanceTimingNames.ts create mode 100644 packages/opentelemetry-plugin-document-load/src/index.ts create mode 100644 packages/opentelemetry-plugin-document-load/src/types.ts create mode 100644 packages/opentelemetry-plugin-document-load/src/utils.ts create mode 100644 packages/opentelemetry-plugin-document-load/test/documentLoad.test.ts create mode 100644 packages/opentelemetry-plugin-document-load/test/index-webpack.ts create mode 100644 packages/opentelemetry-plugin-document-load/tsconfig.json create mode 100644 packages/opentelemetry-plugin-document-load/tslint.json create mode 100644 packages/opentelemetry-plugin-document-load/webpack/test.config.js diff --git a/examples/tracer-web/index.html b/examples/tracer-web/index.html index cf9634a00a..08bab8e1b0 100644 --- a/examples/tracer-web/index.html +++ b/examples/tracer-web/index.html @@ -3,14 +3,14 @@ - JS Example + Web Tracer Example - Testing, debugging in development + Example of using Web Tracer with document load plugin and console exporter diff --git a/examples/tracer-web/index.js b/examples/tracer-web/index.js index 1d149f8af3..627ebe0f64 100644 --- a/examples/tracer-web/index.js +++ b/examples/tracer-web/index.js @@ -1,38 +1,12 @@ +import { ConsoleExporter } from '@opentelemetry/exporter-console'; +import { SimpleSpanProcessor } from '@opentelemetry/tracing'; import { WebTracer } from '@opentelemetry/web'; +import { DocumentLoad } from '@opentelemetry/plugin-document-load'; -import * as shimmer from 'shimmer'; - -class Tester { - constructor() { - } - add(name) { - console.log('calling add', name); - } -} - -const tester = new Tester(); - -const webTracer = new WebTracer(); -const span = webTracer.startSpan('span1'); - -shimmer.wrap(Tester.prototype, 'add', (originalFunction) => { - return function patchedFunction() { - try { - span.addEvent('start'); - } catch (e) { - console.log('error', e); - } finally { - const result = originalFunction.apply(this, arguments); - span.addEvent('after call'); - span.end(); - return result; - } - }; -}); - -webTracer.withSpan(span, function () { - console.log(this === span); +const webTracer = new WebTracer({ + plugins: [ + new DocumentLoad() + ] }); -tester.add('foo'); -console.log(span); +webTracer.addSpanProcessor(new SimpleSpanProcessor(new ConsoleExporter())); diff --git a/examples/tracer-web/package.json b/examples/tracer-web/package.json index fd34287e67..5f222c8bda 100644 --- a/examples/tracer-web/package.json +++ b/examples/tracer-web/package.json @@ -26,16 +26,18 @@ }, "devDependencies": { "@babel/core": "^7.6.0", - "@types/shimmer": "^1.0.1", "babel-loader": "^8.0.6", - "shimmer": "^1.2.0", + "ts-loader": "^6.0.4", "webpack": "^4.35.2", "webpack-cli": "^3.3.9", "webpack-dev-server": "^3.8.1", "webpack-merge": "^4.2.2" }, "dependencies": { + "@opentelemetry/exporter-console": "^0.1.0", + "@opentelemetry/plugin-document-load": "^0.1.0", + "@opentelemetry/tracing": "^0.1.0", "@opentelemetry/web": "^0.1.0" }, "homepage": "https://github.com/open-telemetry/opentelemetry-js#readme" -} \ No newline at end of file +} diff --git a/packages/opentelemetry-core/src/common/time.ts b/packages/opentelemetry-core/src/common/time.ts index 9a9d0e22b7..893cbd8758 100644 --- a/packages/opentelemetry-core/src/common/time.ts +++ b/packages/opentelemetry-core/src/common/time.ts @@ -35,7 +35,9 @@ function numberToHrtime(epochMillis: number): types.HrTime { // Returns an hrtime calculated via performance component. export function hrTime(performanceNow?: number): types.HrTime { const timeOrigin = numberToHrtime(performance.timeOrigin); - const now = numberToHrtime(performanceNow || performance.now()); + const now = numberToHrtime( + typeof performanceNow === 'number' ? performanceNow : performance.now() + ); let seconds = timeOrigin[0] + now[0]; let nanos = timeOrigin[1] + now[1]; diff --git a/packages/opentelemetry-exporter-console/LICENSE b/packages/opentelemetry-exporter-console/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/packages/opentelemetry-exporter-console/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/opentelemetry-exporter-console/README.md b/packages/opentelemetry-exporter-console/README.md new file mode 100644 index 0000000000..edbc423dbe --- /dev/null +++ b/packages/opentelemetry-exporter-console/README.md @@ -0,0 +1,55 @@ +# OpenTelemetry Console Exporter +[![Gitter chat][gitter-image]][gitter-url] +[![NPM Published Version][npm-img]][npm-url] +[![dependencies][dependencies-image]][dependencies-url] +[![devDependencies][devDependencies-image]][devDependencies-url] +[![Apache License][license-image]][license-image] + +This module provides a helper exporter that can be used when working with Web applications. + +## Installation + +```bash +npm install --save @opentelemetry/exporter-console +``` + +## Usage + +```js + +import { ConsoleExporter } from '@opentelemetry/exporter-console'; +import { SimpleSpanProcessor } from '@opentelemetry/tracing'; +import { WebTracer } from '@opentelemetry/web'; +import { DocumentLoad } from '@opentelemetry/plugin-document-load'; + +const webTracer = new WebTracer({ + plugins: [ + new DocumentLoad() + ] +}); + +webTracer.addSpanProcessor(new SimpleSpanProcessor(new ConsoleExporter())); + +// if you run this example you should see the exported spans in console + +``` + +## Useful links +- For more information on OpenTelemetry, visit: +- For more about OpenTelemetry JavaScript: +- For help or feedback on this project, join us on [gitter][gitter-url] + +## License + +Apache 2.0 - See [LICENSE][license-url] for more information. + +[gitter-image]: https://badges.gitter.im/open-telemetry/opentelemetry-js.svg +[gitter-url]: https://gitter.im/open-telemetry/opentelemetry-node?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge +[license-url]: https://github.com/open-telemetry/opentelemetry-js/blob/master/LICENSE +[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat +[dependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js/status.svg?path=packages/opentelemetry-exporter-console +[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-exporter-console +[devDependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js/dev-status.svg?path=packages/opentelemetry-exporter-console +[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-web&type=dev +[npm-url]: https://www.npmjs.com/package/@opentelemetry/exporter-console +[npm-img]: https://badge.fury.io/js/%40opentelemetry%2Fexporter-console.svg diff --git a/packages/opentelemetry-exporter-console/karma.conf.js b/packages/opentelemetry-exporter-console/karma.conf.js new file mode 100644 index 0000000000..66529c7d92 --- /dev/null +++ b/packages/opentelemetry-exporter-console/karma.conf.js @@ -0,0 +1,24 @@ +/*! + * Copyright 2019, 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 webpackConfig = require('./webpack/test.config.js'); +const karmaBaseConfig = require('../../karma.base'); + +module.exports = (config) => { + config.set(Object.assign({}, karmaBaseConfig, { + webpack: webpackConfig + })) +}; diff --git a/packages/opentelemetry-exporter-console/package.json b/packages/opentelemetry-exporter-console/package.json new file mode 100644 index 0000000000..bf3864dc72 --- /dev/null +++ b/packages/opentelemetry-exporter-console/package.json @@ -0,0 +1,72 @@ +{ + "name": "@opentelemetry/exporter-console", + "version": "0.1.0", + "description": "OpenTelemetry Console Exporter", + "main": "build/src/index.js", + "types": "build/src/index.d.ts", + "repository": "open-telemetry/opentelemetry-js", + "scripts": { + "test:browser": "nyc karma start --single-run", + "tdd": "karma start", + "codecov:browser": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../", + "clean": "rimraf build/*", + "check": "gts check", + "compile": "tsc -p .", + "watch": "tsc -w", + "fix": "gts fix" + }, + "keywords": [ + "opentelemetry", + "web", + "tracing", + "profiling", + "metrics", + "stats" + ], + "author": "OpenTelemetry Authors", + "license": "Apache-2.0", + "engines": { + "node": ">=8.0.0" + }, + "files": [ + "build/src/**/*.js", + "build/src/**/*.d.ts", + "doc", + "LICENSE", + "README.md" + ], + "publishConfig": { + "access": "public" + }, + "devDependencies": { + "@types/mocha": "^5.2.5", + "@types/webpack-env": "1.13.9", + "@types/sinon": "^7.0.13", + "@babel/core": "^7.6.0", + "babel-loader": "^8.0.6", + "codecov": "^3.1.0", + "gts": "^1.0.0", + "karma": "^4.1.0", + "karma-chrome-launcher": "^2.2.0", + "karma-mocha": "^1.3.0", + "karma-spec-reporter": "^0.0.32", + "karma-webpack": "^4.0.2", + "mocha": "^6.1.0", + "nyc": "^14.1.1", + "rimraf": "^3.0.0", + "sinon": "^7.5.0", + "tslint-consistent-codestyle": "^1.16.0", + "tslint-microsoft-contrib": "^6.2.0", + "ts-loader": "^6.0.4", + "ts-mocha": "^6.0.0", + "typescript": "^3.6.3", + "webpack": "^4.35.2", + "webpack-cli": "^3.3.9", + "webpack-merge": "^4.2.2" + }, + "dependencies": { + "@opentelemetry/base": "^0.1.0", + "@opentelemetry/core": "^0.1.0", + "@opentelemetry/tracing": "^0.1.0" + } +} diff --git a/packages/opentelemetry-exporter-console/src/ConsoleExporter.ts b/packages/opentelemetry-exporter-console/src/ConsoleExporter.ts new file mode 100644 index 0000000000..61e84f5f61 --- /dev/null +++ b/packages/opentelemetry-exporter-console/src/ConsoleExporter.ts @@ -0,0 +1,81 @@ +/*! + * Copyright 2019, 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 { hrTimeToMicroseconds } from '@opentelemetry/core'; +import { ReadableSpan, SpanExporter } from '@opentelemetry/tracing'; +import { ExportResult } from '@opentelemetry/base'; + +/** + * Simple console exporter for spans + */ +export class ConsoleExporter implements SpanExporter { + /** + * Export spans. + * @param spans + * @param resultCallback + */ + export( + spans: ReadableSpan[], + resultCallback: (result: ExportResult) => void + ) { + return this._sendSpans(spans, resultCallback); + } + + /** + * Shutdown the exporter. + */ + shutdown() { + this._sendSpans([]); + } + + /** + * converts span info into more readable format + * @param {ReadableSpan} span + * @private + */ + private _exportInfo(span: ReadableSpan) { + return { + traceId: span.spanContext.traceId, + parentId: span.parentSpanId, + name: span.name, + id: span.spanContext.spanId, + kind: span.kind, + timestamp: hrTimeToMicroseconds(span.startTime), + duration: hrTimeToMicroseconds(span.duration), + attributes: span.attributes, + status: span.status, + events: span.events, + }; + } + + /** + * Showing spans in console + * @param {ReadableSpan[]} spans + * @param done + * @private + */ + private _sendSpans( + spans: ReadableSpan[], + done?: (result: ExportResult) => void + ) { + for (let i = 0, j = spans.length; i < j; i++) { + console.log(this._exportInfo(spans[i])); + } + if (done) { + return done(ExportResult.SUCCESS); + } + } +} diff --git a/packages/opentelemetry-exporter-console/src/index.ts b/packages/opentelemetry-exporter-console/src/index.ts new file mode 100644 index 0000000000..ae07b0c2b0 --- /dev/null +++ b/packages/opentelemetry-exporter-console/src/index.ts @@ -0,0 +1,17 @@ +/*! + * Copyright 2019, 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 './ConsoleExporter'; diff --git a/packages/opentelemetry-exporter-console/test/ConsoleExporter.test.ts b/packages/opentelemetry-exporter-console/test/ConsoleExporter.test.ts new file mode 100644 index 0000000000..79691de6b7 --- /dev/null +++ b/packages/opentelemetry-exporter-console/test/ConsoleExporter.test.ts @@ -0,0 +1,75 @@ +/*! + * Copyright 2019, 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 { BasicTracer, SimpleSpanProcessor } from '@opentelemetry/tracing'; +import * as assert from 'assert'; +import { ConsoleExporter } from '../src'; +import * as sinon from 'sinon'; + +describe('ConsoleExporter', () => { + let consoleExporter: ConsoleExporter; + + beforeEach(() => { + consoleExporter = new ConsoleExporter(); + }); + + afterEach(() => {}); + + describe('.export()', () => { + it('should export information about span', () => { + assert.doesNotThrow(() => { + const basicTracer = new BasicTracer(); + consoleExporter = new ConsoleExporter(); + const spyExport = sinon.spy(consoleExporter, 'export'); + const spyConsole = sinon.spy(console, 'log'); + + basicTracer.addSpanProcessor(new SimpleSpanProcessor(consoleExporter)); + const span = basicTracer.startSpan('foo'); + span.addEvent('foobar'); + span.end(); + + const spans = spyExport.args[0]; + const firstSpan = spans[0][0]; + const firstEvent = firstSpan.events[0]; + const consoleArgs = spyConsole.args[0]; + const consoleSpan = consoleArgs[0]; + const keys = Object.keys(consoleSpan) + .sort() + .join(','); + + const expectedKeys = [ + 'attributes', + 'duration', + 'events', + 'id', + 'kind', + 'name', + 'parentId', + 'status', + 'timestamp', + 'traceId', + ].join(','); + + assert.ok(firstSpan.name === 'foo'); + assert.ok(firstEvent.name === 'foobar'); + assert.ok(consoleSpan.id === firstSpan.spanContext.spanId); + assert.ok(keys === expectedKeys); + + assert.ok(spyExport.calledOnce); + }); + }); + }); +}); diff --git a/packages/opentelemetry-exporter-console/test/index-webpack.ts b/packages/opentelemetry-exporter-console/test/index-webpack.ts new file mode 100644 index 0000000000..3899f0edc9 --- /dev/null +++ b/packages/opentelemetry-exporter-console/test/index-webpack.ts @@ -0,0 +1,20 @@ +/*! + * Copyright 2019, 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 file is the webpack entry point for the browser Karma tests. It requires +// all modules ending in "test" from the current folder and all its subfolders. +const testsContext = require.context('.', true, /test$/); +testsContext.keys().forEach(testsContext); diff --git a/packages/opentelemetry-exporter-console/tsconfig.json b/packages/opentelemetry-exporter-console/tsconfig.json new file mode 100644 index 0000000000..a2042cd68b --- /dev/null +++ b/packages/opentelemetry-exporter-console/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../tsconfig.base", + "compilerOptions": { + "rootDir": ".", + "outDir": "build" + }, + "include": [ + "src/**/*.ts", + "test/**/*.ts" + ] +} diff --git a/packages/opentelemetry-exporter-console/tslint.json b/packages/opentelemetry-exporter-console/tslint.json new file mode 100644 index 0000000000..0710b135d0 --- /dev/null +++ b/packages/opentelemetry-exporter-console/tslint.json @@ -0,0 +1,4 @@ +{ + "rulesDirectory": ["node_modules/tslint-microsoft-contrib"], + "extends": ["../../tslint.base.js", "./node_modules/tslint-consistent-codestyle"] +} diff --git a/packages/opentelemetry-exporter-console/webpack/test.config.js b/packages/opentelemetry-exporter-console/webpack/test.config.js new file mode 100644 index 0000000000..997cce7182 --- /dev/null +++ b/packages/opentelemetry-exporter-console/webpack/test.config.js @@ -0,0 +1,34 @@ +/*! + * Copyright 2019, 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 webpackNodePolyfills = require('../../../webpack.node-polyfills.js'); + +// This is the webpack configuration for browser Karma tests. +module.exports = { + mode: 'development', + target: 'web', + output: { filename: 'bundle.js' }, + resolve: { extensions: ['.ts', '.js'] }, + devtool: 'inline-source-map', + module: { + rules: [ + { test: /\.ts$/, use: 'ts-loader' }, + // This setting configures Node polyfills for the browser that will be + // added to the webpack bundle for Karma tests. + { parser: { node: webpackNodePolyfills } } + ] + } +}; diff --git a/packages/opentelemetry-plugin-document-load/karma.conf.js b/packages/opentelemetry-plugin-document-load/karma.conf.js new file mode 100644 index 0000000000..66529c7d92 --- /dev/null +++ b/packages/opentelemetry-plugin-document-load/karma.conf.js @@ -0,0 +1,24 @@ +/*! + * Copyright 2019, 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 webpackConfig = require('./webpack/test.config.js'); +const karmaBaseConfig = require('../../karma.base'); + +module.exports = (config) => { + config.set(Object.assign({}, karmaBaseConfig, { + webpack: webpackConfig + })) +}; diff --git a/packages/opentelemetry-plugin-document-load/package.json b/packages/opentelemetry-plugin-document-load/package.json new file mode 100644 index 0000000000..fc0f3c030a --- /dev/null +++ b/packages/opentelemetry-plugin-document-load/package.json @@ -0,0 +1,76 @@ +{ + "name": "@opentelemetry/plugin-document-load", + "version": "0.1.0", + "description": "OpenTelemetry document-load automatic instrumentation package.", + "main": "build/src/index.js", + "types": "build/src/index.d.ts", + "repository": "open-telemetry/opentelemetry-js", + "scripts": { + "test:browser": "nyc karma start --single-run", + "tdd": "karma start", + "clean": "rimraf build/*", + "check": "gts check", + "codecov:browser": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../", + "compile": "tsc -p .", + "fix": "gts fix", + "watch": "tsc -w" + }, + "keywords": [ + "opentelemetry", + "document-load", + "web", + "tracing", + "profiling", + "plugin" + ], + "author": "OpenTelemetry Authors", + "license": "Apache-2.0", + "engines": { + "node": ">=8.0.0" + }, + "files": [ + "build/src/**/*.js", + "build/src/**/*.d.ts", + "doc", + "LICENSE", + "README.md" + ], + "publishConfig": { + "access": "public" + }, + "devDependencies": { + "@types/mocha": "^5.2.5", + "@types/node": "^12.6.8", + "@types/webpack-env": "1.13.9", + "@types/sinon": "^7.0.13", + "@babel/core": "^7.6.0", + "babel-loader": "^8.0.6", + "codecov": "^3.1.0", + "gts": "^1.0.0", + "karma": "^4.1.0", + "karma-chrome-launcher": "^2.2.0", + "karma-mocha": "^1.3.0", + "karma-spec-reporter": "^0.0.32", + "karma-webpack": "^4.0.2", + "mocha": "^6.1.0", + "nyc": "^14.1.1", + "rimraf": "^3.0.0", + "sinon": "^7.5.0", + "tslint-consistent-codestyle" : "^1.16.0", + "tslint-microsoft-contrib": "^6.2.0", + "ts-loader": "^6.0.4", + "ts-mocha": "^6.0.0", + "ts-node": "^8.0.0", + "typescript": "^3.6.3", + "webpack": "^4.35.2", + "webpack-cli": "^3.3.9", + "webpack-merge": "^4.2.2" + }, + "dependencies": { + "@opentelemetry/core": "^0.1.0", + "@opentelemetry/scope-base": "^0.1.0", + "@opentelemetry/types": "^0.1.0", + "@opentelemetry/tracing": "^0.1.0", + "@opentelemetry/web": "^0.1.0" + } +} diff --git a/packages/opentelemetry-plugin-document-load/src/documentLoad.ts b/packages/opentelemetry-plugin-document-load/src/documentLoad.ts new file mode 100644 index 0000000000..1856d15f94 --- /dev/null +++ b/packages/opentelemetry-plugin-document-load/src/documentLoad.ts @@ -0,0 +1,283 @@ +/*! + * Copyright 2019, OpenTelemetry Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { BasePlugin, otperformance } from '@opentelemetry/core'; +import { PluginConfig, Span, SpanOptions } from '@opentelemetry/types'; +import { AttributeNames } from './enums/AttributeNames'; +import { PerformanceTimingNames } from './enums/PerformanceTimingNames'; +import { PerformanceEntries, PerformanceLegacy } from './types'; +import { hasKey } from './utils'; + +// import { IPerformanceEntries, PerformanceEntries, PerformanceLegacy } from './types'; + +/** + * This class represents a document load plugin + */ +export class DocumentLoad extends BasePlugin { + readonly component: string = 'document-load'; + readonly version: string = '1'; + moduleName = this.component; + protected _config!: PluginConfig; + + /** + * + * @param {DocumentLoadConfig} config + */ + constructor(config: PluginConfig = {}) { + super(); + this._onDocumentLoaded = this._onDocumentLoaded.bind(this); + this._config = config; + } + + /** + * callback to be executed when page is loaded + * @private + */ + private _onDocumentLoaded() { + this._collectPerformance(); + } + + /** + * Collects information about performance and creates appropriate spans + * @private + */ + private _collectPerformance() { + const entries = this._getEntries(); + + const rootSpan = this._startSpan( + AttributeNames.DOCUMENT_LOAD, + PerformanceTimingNames.FETCH_START, + entries + ); + + this._startAndFinishSpan( + AttributeNames.DOMAIN_LOOKUP, + PerformanceTimingNames.DOMAIN_LOOKUP_START, + PerformanceTimingNames.DOMAIN_LOOKUP_END, + entries, + { + parent: rootSpan, + } + ); + + // Opening Connection + const connectSpan = this._startSpan( + AttributeNames.CONNECT, + PerformanceTimingNames.CONNECT_START, + entries, + { + parent: rootSpan, + } + ); + + // TLS negotiation + if (hasKey(entries, PerformanceTimingNames.SECURE_CONNECTION_START)) { + const value = entries[PerformanceTimingNames.SECURE_CONNECTION_START]; + if (typeof value === 'number' && value > 0) { + this._startAndFinishSpan( + AttributeNames.CONNECT_SECURE, + PerformanceTimingNames.SECURE_CONNECTION_START, + PerformanceTimingNames.CONNECT_END, + entries, + { + parent: connectSpan, + } + ); + } + } + // Connection negotiation ends + this._endSpan(connectSpan, PerformanceTimingNames.CONNECT_END, entries); + + // Cache seek plus response time + this._startAndFinishSpan( + AttributeNames.CACHE_SEEK, + PerformanceTimingNames.FETCH_START, + PerformanceTimingNames.RESPONSE_END, + entries, + { + parent: rootSpan, + } + ); + + // TTFB - time to first byte + this._startAndFinishSpan( + AttributeNames.TTFB, + PerformanceTimingNames.REQUEST_START, + PerformanceTimingNames.RESPONSE_START, + entries, + { + parent: rootSpan, + } + ); + + // Response time only (download) + this._startAndFinishSpan( + AttributeNames.RESPONSE_TIME, + PerformanceTimingNames.RESPONSE_START, + PerformanceTimingNames.RESPONSE_END, + entries, + { + parent: rootSpan, + } + ); + + this._endSpan(rootSpan, PerformanceTimingNames.LOAD_EVENT_START, entries); + } + + /** + * Helper function for ending span + * @param {Span} span + * @param {string} performanceName - name of performance entry for time end + * @param {PerformanceEntries} entries + * @private + */ + private _endSpan( + span: Span | undefined, + performanceName: string, + entries: PerformanceEntries + ) { + if (typeof span !== 'undefined' && hasKey(entries, performanceName)) { + span.addEvent(performanceName); + span.end(entries[performanceName]); + } + } + + /** + * gets performance entries of navigation + * @private + */ + private _getEntries() { + const entries: PerformanceEntries = {}; + const performanceNavigationTiming = otperformance.getEntriesByType( + 'navigation' + )[0] as PerformanceEntries; + if (performanceNavigationTiming) { + const keys = Object.values(PerformanceTimingNames); + const startTime = otperformance.timeOrigin; + keys.forEach((key: string) => { + if (hasKey(performanceNavigationTiming, key)) { + const value = performanceNavigationTiming[key]; + if (typeof value === 'number' && value > 0) { + entries[key] = value + startTime; + } + } + }); + } else { + // // fallback to previous version + const perf: (typeof otperformance) & PerformanceLegacy = otperformance; + const performanceTiming = perf.timing; + if (performanceTiming) { + const keys = Object.values(PerformanceTimingNames); + keys.forEach((key: string) => { + if (hasKey(performanceTiming, key)) { + const value = performanceTiming[key]; + if (typeof value === 'number' && value > 0) { + entries[key] = value; + } + } + }); + } + } + return entries; + } + + /** + * Helper function for starting and finishing a span + * @param {string} spanName - name of span + * @param {string} performanceNameStart - name of performance entry for time start + * @param {string} performanceNameEnd - name of performance entry for time end + * @param {PerformanceEntries} entries + * @param {SpanOptions} spanOptions + * @private + */ + private _startAndFinishSpan( + spanName: string, + performanceNameStart: string, + performanceNameEnd: string, + entries: PerformanceEntries, + spanOptions: SpanOptions = {} + ): Span | undefined { + const span = this._startSpan( + spanName, + performanceNameStart, + entries, + spanOptions + ); + this._endSpan(span, performanceNameEnd, entries); + return span; + } + + /** + * Helper function for starting a span + * @param {string} spanName - name of span + * @param {string} performanceName - name of performance entry for time start + * @param {PerformanceEntries} entries + * @param {SpanOptions} spanOptions + * @private + */ + private _startSpan( + spanName: string, + performanceName: string, + entries: PerformanceEntries, + spanOptions: SpanOptions = {} + ): Span | undefined { + if ( + hasKey(entries, performanceName) && + typeof entries[performanceName] === 'number' + ) { + const span = this._tracer.startSpan( + spanName, + Object.assign( + {}, + { + startTime: entries[performanceName], + }, + spanOptions + ) + ); + span.addEvent(performanceName); + return span; + } + return undefined; + } + + /** + * executes callback {_onDocumentLoaded} when the page is loaded + * @private + */ + private _waitForPageLoad() { + if (window.document.readyState === 'complete') { + this._onDocumentLoaded(); + } else { + window.addEventListener('load', this._onDocumentLoaded); + } + } + + /** + * implements patch function + */ + protected patch() { + this._waitForPageLoad(); + return this._moduleExports; + } + + /** + * implements unpatch function + */ + protected unpatch() { + window.removeEventListener('load', this._onDocumentLoaded); + } +} diff --git a/packages/opentelemetry-plugin-document-load/src/enums/AttributeNames.ts b/packages/opentelemetry-plugin-document-load/src/enums/AttributeNames.ts new file mode 100644 index 0000000000..625aad4220 --- /dev/null +++ b/packages/opentelemetry-plugin-document-load/src/enums/AttributeNames.ts @@ -0,0 +1,25 @@ +/*! + * Copyright 2019, 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 AttributeNames { + CACHE_SEEK = 'cacheSeek', + CONNECT = 'connect', + CONNECT_SECURE = 'connectSecure', + DOMAIN_LOOKUP = 'domainLookup', + RESPONSE_TIME = 'responseTime', + DOCUMENT_LOAD = 'documentLoad', + TTFB = 'ttfb', +} diff --git a/packages/opentelemetry-plugin-document-load/src/enums/PerformanceTimingNames.ts b/packages/opentelemetry-plugin-document-load/src/enums/PerformanceTimingNames.ts new file mode 100644 index 0000000000..12d5a44fa8 --- /dev/null +++ b/packages/opentelemetry-plugin-document-load/src/enums/PerformanceTimingNames.ts @@ -0,0 +1,37 @@ +/*! + * Copyright 2019, 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 PerformanceTimingNames { + CONNECT_END = 'connectEnd', + CONNECT_START = 'connectStart', + DOM_COMPLETE = 'domComplete', + DOM_CONTENT_LOADED_EVENT_END = 'domContentLoadedEventEnd', + DOM_CONTENT_LOADED_EVENT_START = 'domContentLoadedEventStart', + DOM_INTERACTIVE = 'domInteractive', + DOMAIN_LOOKUP_END = 'domainLookupEnd', + DOMAIN_LOOKUP_START = 'domainLookupStart', + FETCH_START = 'fetchStart', + LOAD_EVENT_END = 'loadEventEnd', + LOAD_EVENT_START = 'loadEventStart', + REDIRECT_END = 'redirectEnd', + REDIRECT_START = 'redirectStart', + REQUEST_START = 'requestStart', + RESPONSE_END = 'responseEnd', + RESPONSE_START = 'responseStart', + SECURE_CONNECTION_START = 'secureConnectionStart', + UNLOAD_EVENT_END = 'unloadEventEnd', + UNLOAD_EVENT_START = 'unloadEventStart', +} diff --git a/packages/opentelemetry-plugin-document-load/src/index.ts b/packages/opentelemetry-plugin-document-load/src/index.ts new file mode 100644 index 0000000000..865a66fe1a --- /dev/null +++ b/packages/opentelemetry-plugin-document-load/src/index.ts @@ -0,0 +1,17 @@ +/*! + * Copyright 2019, 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 './documentLoad'; diff --git a/packages/opentelemetry-plugin-document-load/src/types.ts b/packages/opentelemetry-plugin-document-load/src/types.ts new file mode 100644 index 0000000000..ca9ad0560e --- /dev/null +++ b/packages/opentelemetry-plugin-document-load/src/types.ts @@ -0,0 +1,25 @@ +/*! + * Copyright 2019, 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 { PerformanceTimingNames } from './enums/PerformanceTimingNames'; + +export type PerformanceEntries = { + [index in PerformanceTimingNames]?: number; +}; + +export interface PerformanceLegacy { + timing?: PerformanceEntries; +} diff --git a/packages/opentelemetry-plugin-document-load/src/utils.ts b/packages/opentelemetry-plugin-document-load/src/utils.ts new file mode 100644 index 0000000000..cb585de753 --- /dev/null +++ b/packages/opentelemetry-plugin-document-load/src/utils.ts @@ -0,0 +1,24 @@ +/*! + * Copyright 2019, 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. + */ + +/** + * Helper function to be able to use enum as typed key in type and in interface when using forEach + * @param obj + * @param key + */ +export function hasKey(obj: O, key: keyof any): key is keyof O { + return key in obj; +} diff --git a/packages/opentelemetry-plugin-document-load/test/documentLoad.test.ts b/packages/opentelemetry-plugin-document-load/test/documentLoad.test.ts new file mode 100644 index 0000000000..b496ac00e7 --- /dev/null +++ b/packages/opentelemetry-plugin-document-load/test/documentLoad.test.ts @@ -0,0 +1,282 @@ +/*! + * Copyright 2019, 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 { ConsoleLogger } from '@opentelemetry/core'; +import { + BasicTracer, + ReadableSpan, + SimpleSpanProcessor, + SpanExporter, +} from '@opentelemetry/tracing'; +import { Logger, PluginConfig } from '@opentelemetry/types'; + +import { ExportResult } from '../../opentelemetry-base/build/src'; +import { DocumentLoad } from '../src'; + +export class DummyExporter implements SpanExporter { + export( + spans: ReadableSpan[], + resultCallback: (result: ExportResult) => void + ) {} + + shutdown() {} +} + +describe('DocumentLoad Plugin', () => { + let plugin: DocumentLoad; + let moduleExports: any; + let tracer: BasicTracer; + let logger: Logger; + let config: PluginConfig; + let spanProcessor: SimpleSpanProcessor; + let dummyExporter: DummyExporter; + + beforeEach(() => { + Object.defineProperty(window.document, 'readyState', { + writable: true, + value: 'complete', + }); + moduleExports = {}; + tracer = new BasicTracer(); + logger = new ConsoleLogger(); + config = {}; + plugin = new DocumentLoad(); + dummyExporter = new DummyExporter(); + spanProcessor = new SimpleSpanProcessor(dummyExporter); + tracer.addSpanProcessor(spanProcessor); + }); + + afterEach(() => { + Object.defineProperty(window.document, 'readyState', { + writable: true, + value: 'complete', + }); + }); + + describe('constructor', () => { + it('should construct an instance', () => { + plugin = new DocumentLoad(); + assert.ok(plugin instanceof DocumentLoad); + }); + }); + + describe('when document readyState is complete', () => { + it('should start collecting the performance immediately', () => { + const spy_OnDocumentLoaded = sinon.spy( + plugin, + '_collectPerformance' as never + ); + plugin.enable(moduleExports, tracer, logger, config); + assert.strictEqual(window.document.readyState, 'complete'); + assert.ok(spy_OnDocumentLoaded.calledOnce); + }); + }); + + describe('when document readyState is not complete', () => { + beforeEach(() => { + Object.defineProperty(window.document, 'readyState', { + writable: true, + value: 'loading', + }); + }); + + it('should collect performance after document load event', () => { + const spy = sinon.spy(window, 'addEventListener'); + const spy_OnDocumentLoaded = sinon.spy( + plugin, + '_collectPerformance' as never + ); + + plugin.enable(moduleExports, tracer, logger, config); + const args = spy.args[0]; + const name = args[0]; + assert.strictEqual(name, 'load'); + assert.ok(spy.calledOnce); + assert.ok(spy_OnDocumentLoaded.calledOnce === false); + + window.dispatchEvent( + new CustomEvent('load', { + bubbles: true, + cancelable: false, + composed: true, + detail: {}, + }) + ); + assert.ok(spy_OnDocumentLoaded.calledOnce); + }); + }); + + describe('when navigation entries types are available', () => { + let spyExport: any; + + beforeEach(() => { + const entries = { + name: 'http://localhost:8090/', + entryType: 'navigation', + startTime: 0, + duration: 374.0100000286475, + initiatorType: 'navigation', + nextHopProtocol: 'http/1.1', + workerStart: 0, + redirectStart: 0, + redirectEnd: 0, + fetchStart: 0.7999999215826392, + domainLookupStart: 0.7999999215826392, + domainLookupEnd: 0.7999999215826392, + connectStart: 0.7999999215826392, + connectEnd: 0.7999999215826393, + secureConnectionStart: 0.7999999215826392, + requestStart: 4.480000003241003, + responseStart: 5.729999975301325, + responseEnd: 6.154999951831996, + transferSize: 655, + encodedBodySize: 362, + decodedBodySize: 362, + serverTiming: [], + unloadEventStart: 12.63499993365258, + unloadEventEnd: 13.514999998733401, + domInteractive: 200.12499997392297, + domContentLoadedEventStart: 200.13999997172505, + domContentLoadedEventEnd: 201.6000000294298, + domComplete: 370.62499998137355, + loadEventStart: 370.64999993890524, + loadEventEnd: 374.0100000286475, + type: 'reload', + redirectCount: 0, + } as any; + spyExport = sinon + .stub(window.performance, 'getEntriesByType') + .returns([entries]); + }); + + it('should export correct spans', () => { + const spyOnEnd = sinon.spy(dummyExporter, 'export'); + plugin.enable(moduleExports, tracer, logger, config); + + const span1 = spyOnEnd.args[0][0][0] as ReadableSpan; + const span2 = spyOnEnd.args[1][0][0] as ReadableSpan; + const span3 = spyOnEnd.args[2][0][0] as ReadableSpan; + const span4 = spyOnEnd.args[3][0][0] as ReadableSpan; + const span5 = spyOnEnd.args[4][0][0] as ReadableSpan; + const span6 = spyOnEnd.args[5][0][0] as ReadableSpan; + const span7 = spyOnEnd.args[6][0][0] as ReadableSpan; + + assert.strictEqual(span1.name, 'domainLookup'); + assert.strictEqual(span2.name, 'connectSecure'); + assert.strictEqual(span3.name, 'connect'); + assert.strictEqual(span4.name, 'cacheSeek'); + assert.strictEqual(span5.name, 'ttfb'); + assert.strictEqual(span6.name, 'responseTime'); + assert.strictEqual(span7.name, 'documentLoad'); + assert.ok(spyOnEnd.callCount === 7); + }); + afterEach(() => { + spyExport.restore(); + }); + }); + + describe('when navigation entries types are NOT available then fallback to "performance.timing"', () => { + let spyExport: any; + + beforeEach(() => { + const entries = { + navigationStart: 1571078170305, + unloadEventStart: 0, + unloadEventEnd: 0, + redirectStart: 0, + redirectEnd: 0, + fetchStart: 1571078170305, + domainLookupStart: 1571078170307, + domainLookupEnd: 1571078170308, + connectStart: 1571078170309, + connectEnd: 1571078170310, + secureConnectionStart: 1571078170310, + requestStart: 1571078170310, + responseStart: 1571078170313, + responseEnd: 1571078170330, + domLoading: 1571078170331, + domInteractive: 1571078170392, + domContentLoadedEventStart: 1571078170392, + domContentLoadedEventEnd: 1571078170392, + domComplete: 1571078170393, + loadEventStart: 1571078170393, + loadEventEnd: 1571078170394, + } as any; + + spyExport = sinon + .stub(window.performance, 'getEntriesByType') + .returns([]); + Object.defineProperty(window.performance, 'timing', { + writable: true, + value: entries, + }); + }); + + it('should export correct spans', () => { + const spyOnEnd = sinon.spy(dummyExporter, 'export'); + plugin.enable(moduleExports, tracer, logger, config); + + const span1 = spyOnEnd.args[0][0][0] as ReadableSpan; + const span2 = spyOnEnd.args[1][0][0] as ReadableSpan; + const span3 = spyOnEnd.args[2][0][0] as ReadableSpan; + const span4 = spyOnEnd.args[3][0][0] as ReadableSpan; + const span5 = spyOnEnd.args[4][0][0] as ReadableSpan; + const span6 = spyOnEnd.args[5][0][0] as ReadableSpan; + const span7 = spyOnEnd.args[6][0][0] as ReadableSpan; + + assert.strictEqual(span1.name, 'domainLookup'); + assert.strictEqual(span2.name, 'connectSecure'); + assert.strictEqual(span3.name, 'connect'); + assert.strictEqual(span4.name, 'cacheSeek'); + assert.strictEqual(span5.name, 'ttfb'); + assert.strictEqual(span6.name, 'responseTime'); + assert.strictEqual(span7.name, 'documentLoad'); + assert.ok(spyOnEnd.callCount === 7); + }); + + afterEach(() => { + spyExport.restore(); + }); + }); + + describe('when navigation entries types and "performance.timing" are NOT available', () => { + let spyExport: any; + + beforeEach(() => { + spyExport = sinon + .stub(window.performance, 'getEntriesByType') + .returns([]); + Object.defineProperty(window.performance, 'timing', { + writable: true, + value: undefined, + }); + }); + + it('should not create any spans', () => { + const spyOnEnd = sinon.spy(dummyExporter, 'export'); + plugin.enable(moduleExports, tracer, logger, config); + + assert.ok(spyOnEnd.callCount === 0); + }); + + afterEach(() => { + spyExport.restore(); + }); + }); +}); diff --git a/packages/opentelemetry-plugin-document-load/test/index-webpack.ts b/packages/opentelemetry-plugin-document-load/test/index-webpack.ts new file mode 100644 index 0000000000..3899f0edc9 --- /dev/null +++ b/packages/opentelemetry-plugin-document-load/test/index-webpack.ts @@ -0,0 +1,20 @@ +/*! + * Copyright 2019, 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 file is the webpack entry point for the browser Karma tests. It requires +// all modules ending in "test" from the current folder and all its subfolders. +const testsContext = require.context('.', true, /test$/); +testsContext.keys().forEach(testsContext); diff --git a/packages/opentelemetry-plugin-document-load/tsconfig.json b/packages/opentelemetry-plugin-document-load/tsconfig.json new file mode 100644 index 0000000000..a2042cd68b --- /dev/null +++ b/packages/opentelemetry-plugin-document-load/tsconfig.json @@ -0,0 +1,11 @@ +{ + "extends": "../tsconfig.base", + "compilerOptions": { + "rootDir": ".", + "outDir": "build" + }, + "include": [ + "src/**/*.ts", + "test/**/*.ts" + ] +} diff --git a/packages/opentelemetry-plugin-document-load/tslint.json b/packages/opentelemetry-plugin-document-load/tslint.json new file mode 100644 index 0000000000..0710b135d0 --- /dev/null +++ b/packages/opentelemetry-plugin-document-load/tslint.json @@ -0,0 +1,4 @@ +{ + "rulesDirectory": ["node_modules/tslint-microsoft-contrib"], + "extends": ["../../tslint.base.js", "./node_modules/tslint-consistent-codestyle"] +} diff --git a/packages/opentelemetry-plugin-document-load/webpack/test.config.js b/packages/opentelemetry-plugin-document-load/webpack/test.config.js new file mode 100644 index 0000000000..997cce7182 --- /dev/null +++ b/packages/opentelemetry-plugin-document-load/webpack/test.config.js @@ -0,0 +1,34 @@ +/*! + * Copyright 2019, 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 webpackNodePolyfills = require('../../../webpack.node-polyfills.js'); + +// This is the webpack configuration for browser Karma tests. +module.exports = { + mode: 'development', + target: 'web', + output: { filename: 'bundle.js' }, + resolve: { extensions: ['.ts', '.js'] }, + devtool: 'inline-source-map', + module: { + rules: [ + { test: /\.ts$/, use: 'ts-loader' }, + // This setting configures Node polyfills for the browser that will be + // added to the webpack bundle for Karma tests. + { parser: { node: webpackNodePolyfills } } + ] + } +}; diff --git a/packages/opentelemetry-web/package.json b/packages/opentelemetry-web/package.json index 7d34a66b65..46c2f14cad 100644 --- a/packages/opentelemetry-web/package.json +++ b/packages/opentelemetry-web/package.json @@ -12,6 +12,7 @@ "clean": "rimraf build/*", "check": "gts check", "compile": "tsc -p .", + "watch": "tsc -w", "fix": "gts fix" }, "keywords": [ @@ -71,4 +72,4 @@ "@opentelemetry/types": "^0.1.0", "@opentelemetry/tracing": "^0.1.0" } -} \ No newline at end of file +} diff --git a/packages/opentelemetry-web/src/WebTracer.ts b/packages/opentelemetry-web/src/WebTracer.ts index ece595195a..fa1bfa9433 100644 --- a/packages/opentelemetry-web/src/WebTracer.ts +++ b/packages/opentelemetry-web/src/WebTracer.ts @@ -14,25 +14,52 @@ * limitations under the License. */ -import { BasicTracer, BasicTracerConfig } from '@opentelemetry/tracing'; +import { BasePlugin } from '@opentelemetry/core'; +import { + BasicTracer, + BasicTracerConfig, + SpanProcessor, +} from '@opentelemetry/tracing'; import { StackScopeManager } from './StackScopeManager'; +/** + * WebTracerConfig provides an interface for configuring a Web Tracer. + */ +export interface WebTracerConfig extends BasicTracerConfig { + /** + * span processor + */ + spanProcessor?: SpanProcessor; + /** + * plugins to be used with tracer, they will be enabled automatically + */ + plugins?: BasePlugin[]; +} + /** * This class represents a web tracer with {@link StackScopeManager} */ export class WebTracer extends BasicTracer { /** * Constructs a new Tracer instance. + * @param {WebTracerConfig} config Web Tracer config */ - /** - * - * @param {BasicTracerConfig} config Web Tracer config - */ - constructor(config: BasicTracerConfig = {}) { + constructor(config: WebTracerConfig = {}) { if (typeof config.scopeManager === 'undefined') { config.scopeManager = new StackScopeManager(); } - config.scopeManager.enable(); + if (typeof config.plugins === 'undefined') { + config.plugins = []; + } super(Object.assign({}, { scopeManager: config.scopeManager }, config)); + + // enable scope manager + config.scopeManager.enable(); + + // enable all plugins + for (let i = 0, j = config.plugins.length; i < j; i++) { + config.plugins[i].enable([], this, this.logger, {}); + } + } } diff --git a/packages/opentelemetry-web/test/WebTracer.test.ts b/packages/opentelemetry-web/test/WebTracer.test.ts index 621aae2977..e1474508ea 100644 --- a/packages/opentelemetry-web/test/WebTracer.test.ts +++ b/packages/opentelemetry-web/test/WebTracer.test.ts @@ -14,16 +14,24 @@ * limitations under the License. */ +import { BasePlugin } from '@opentelemetry/core'; import * as assert from 'assert'; import * as sinon from 'sinon'; import { BasicTracerConfig } from '@opentelemetry/tracing'; +import { WebTracerConfig } from '../src'; import { StackScopeManager } from '../src/StackScopeManager'; import { WebTracer } from '../src/WebTracer'; +class DummyPlugin extends BasePlugin { + patch() {} + + unpatch() {} +} + describe('WebTracer', () => { let tracer: WebTracer; describe('constructor', () => { - let defaultOptions: BasicTracerConfig; + let defaultOptions: WebTracerConfig; beforeEach(() => { defaultOptions = { @@ -47,6 +55,24 @@ describe('WebTracer', () => { assert.ok(spy.calledOnce === true); }); + it('should enable all plugins', () => { + let options: WebTracerConfig; + const dummyPlugin1 = new DummyPlugin(); + const dummyPlugin2 = new DummyPlugin(); + const spyEnable1 = sinon.spy(dummyPlugin1, 'enable'); + const spyEnable2 = sinon.spy(dummyPlugin2, 'enable'); + + const scopeManager = new StackScopeManager(); + + const plugins = [dummyPlugin1, dummyPlugin2]; + + options = { plugins, scopeManager }; + tracer = new WebTracer(options); + + assert.ok(spyEnable1.calledOnce === true); + assert.ok(spyEnable2.calledOnce === true); + }); + it('should work without default scope manager', () => { assert.doesNotThrow(() => { tracer = new WebTracer({}); From a718b7474d22107ed68d923c91273326e7e603ea Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Tue, 15 Oct 2019 02:24:59 +0200 Subject: [PATCH 02/33] chore: lint --- packages/opentelemetry-web/src/WebTracer.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/opentelemetry-web/src/WebTracer.ts b/packages/opentelemetry-web/src/WebTracer.ts index fa1bfa9433..efed55e3f4 100644 --- a/packages/opentelemetry-web/src/WebTracer.ts +++ b/packages/opentelemetry-web/src/WebTracer.ts @@ -60,6 +60,5 @@ export class WebTracer extends BasicTracer { for (let i = 0, j = config.plugins.length; i < j; i++) { config.plugins[i].enable([], this, this.logger, {}); } - } } From fe0487012d6c91b76dbcd8e738cea8396757782c Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Tue, 15 Oct 2019 14:35:43 +0200 Subject: [PATCH 03/33] chore: removing unused dependency --- packages/opentelemetry-plugin-document-load/package.json | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/opentelemetry-plugin-document-load/package.json b/packages/opentelemetry-plugin-document-load/package.json index fc0f3c030a..9b0067722c 100644 --- a/packages/opentelemetry-plugin-document-load/package.json +++ b/packages/opentelemetry-plugin-document-load/package.json @@ -68,7 +68,6 @@ }, "dependencies": { "@opentelemetry/core": "^0.1.0", - "@opentelemetry/scope-base": "^0.1.0", "@opentelemetry/types": "^0.1.0", "@opentelemetry/tracing": "^0.1.0", "@opentelemetry/web": "^0.1.0" From 4563aa92cca560bc8d45d723701638c66c664d98 Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Tue, 15 Oct 2019 14:39:22 +0200 Subject: [PATCH 04/33] chore: adding prepare script --- .../opentelemetry-plugin-document-load/package.json | 5 +++-- packages/opentelemetry-web/package.json | 13 +++++++------ 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/packages/opentelemetry-plugin-document-load/package.json b/packages/opentelemetry-plugin-document-load/package.json index 9b0067722c..0d2c4b0b3c 100644 --- a/packages/opentelemetry-plugin-document-load/package.json +++ b/packages/opentelemetry-plugin-document-load/package.json @@ -6,13 +6,14 @@ "types": "build/src/index.d.ts", "repository": "open-telemetry/opentelemetry-js", "scripts": { - "test:browser": "nyc karma start --single-run", - "tdd": "karma start", "clean": "rimraf build/*", "check": "gts check", "codecov:browser": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../", "compile": "tsc -p .", "fix": "gts fix", + "prepare": "npm run compile", + "tdd": "karma start", + "test:browser": "nyc karma start --single-run", "watch": "tsc -w" }, "keywords": [ diff --git a/packages/opentelemetry-web/package.json b/packages/opentelemetry-web/package.json index 46c2f14cad..40003cfb75 100644 --- a/packages/opentelemetry-web/package.json +++ b/packages/opentelemetry-web/package.json @@ -6,14 +6,15 @@ "types": "build/src/index.d.ts", "repository": "open-telemetry/opentelemetry-js", "scripts": { - "test:browser": "nyc karma start --single-run", - "tdd": "karma start", - "codecov:browser": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../", - "clean": "rimraf build/*", "check": "gts check", + "clean": "rimraf build/*", + "codecov:browser": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../", "compile": "tsc -p .", - "watch": "tsc -w", - "fix": "gts fix" + "fix": "gts fix", + "prepare": "npm run compile", + "tdd": "karma start", + "test:browser": "nyc karma start --single-run", + "watch": "tsc -w" }, "keywords": [ "opentelemetry", From 0c435a090fff7c03a0fd159860e99471ec6d5ffc Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Tue, 15 Oct 2019 14:40:56 +0200 Subject: [PATCH 05/33] chore: cleanup of not used span processor --- packages/opentelemetry-web/src/WebTracer.ts | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/packages/opentelemetry-web/src/WebTracer.ts b/packages/opentelemetry-web/src/WebTracer.ts index efed55e3f4..de3b51e254 100644 --- a/packages/opentelemetry-web/src/WebTracer.ts +++ b/packages/opentelemetry-web/src/WebTracer.ts @@ -17,8 +17,7 @@ import { BasePlugin } from '@opentelemetry/core'; import { BasicTracer, - BasicTracerConfig, - SpanProcessor, + BasicTracerConfig } from '@opentelemetry/tracing'; import { StackScopeManager } from './StackScopeManager'; @@ -26,10 +25,6 @@ import { StackScopeManager } from './StackScopeManager'; * WebTracerConfig provides an interface for configuring a Web Tracer. */ export interface WebTracerConfig extends BasicTracerConfig { - /** - * span processor - */ - spanProcessor?: SpanProcessor; /** * plugins to be used with tracer, they will be enabled automatically */ @@ -51,7 +46,7 @@ export class WebTracer extends BasicTracer { if (typeof config.plugins === 'undefined') { config.plugins = []; } - super(Object.assign({}, { scopeManager: config.scopeManager }, config)); + super(Object.assign({}, {scopeManager: config.scopeManager}, config)); // enable scope manager config.scopeManager.enable(); From 8301b03885c83ab74c10df820792eeba92c92a29 Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Tue, 15 Oct 2019 15:16:10 +0200 Subject: [PATCH 06/33] chore: merging exporter-console into tracing --- examples/tracer-web/index.js | 5 +- examples/tracer-web/package.json | 1 - .../opentelemetry-exporter-console/LICENSE | 201 ------------------ .../opentelemetry-exporter-console/README.md | 55 ----- .../karma.conf.js | 24 --- .../package.json | 72 ------- .../src/ConsoleExporter.ts | 81 ------- .../src/index.ts | 17 -- .../test/index-webpack.ts | 20 -- .../tsconfig.json | 11 - .../tslint.json | 4 - .../webpack/test.config.js | 34 --- packages/opentelemetry-tracing/package.json | 2 + .../src/export/ConsoleSpanExporter.ts | 63 ++++-- .../test/export/ConsoleSpanExporter.test.ts} | 26 ++- packages/opentelemetry-web/README.md | 15 +- packages/opentelemetry-web/src/WebTracer.ts | 7 +- 17 files changed, 88 insertions(+), 550 deletions(-) delete mode 100644 packages/opentelemetry-exporter-console/LICENSE delete mode 100644 packages/opentelemetry-exporter-console/README.md delete mode 100644 packages/opentelemetry-exporter-console/karma.conf.js delete mode 100644 packages/opentelemetry-exporter-console/package.json delete mode 100644 packages/opentelemetry-exporter-console/src/ConsoleExporter.ts delete mode 100644 packages/opentelemetry-exporter-console/src/index.ts delete mode 100644 packages/opentelemetry-exporter-console/test/index-webpack.ts delete mode 100644 packages/opentelemetry-exporter-console/tsconfig.json delete mode 100644 packages/opentelemetry-exporter-console/tslint.json delete mode 100644 packages/opentelemetry-exporter-console/webpack/test.config.js rename packages/{opentelemetry-exporter-console/test/ConsoleExporter.test.ts => opentelemetry-tracing/test/export/ConsoleSpanExporter.test.ts} (82%) diff --git a/examples/tracer-web/index.js b/examples/tracer-web/index.js index 627ebe0f64..a8e3e34b41 100644 --- a/examples/tracer-web/index.js +++ b/examples/tracer-web/index.js @@ -1,5 +1,4 @@ -import { ConsoleExporter } from '@opentelemetry/exporter-console'; -import { SimpleSpanProcessor } from '@opentelemetry/tracing'; +import { ConsoleSpanExporter, SimpleSpanProcessor } from '@opentelemetry/tracing'; import { WebTracer } from '@opentelemetry/web'; import { DocumentLoad } from '@opentelemetry/plugin-document-load'; @@ -9,4 +8,4 @@ const webTracer = new WebTracer({ ] }); -webTracer.addSpanProcessor(new SimpleSpanProcessor(new ConsoleExporter())); +webTracer.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter())); diff --git a/examples/tracer-web/package.json b/examples/tracer-web/package.json index 5f222c8bda..d3ac017de0 100644 --- a/examples/tracer-web/package.json +++ b/examples/tracer-web/package.json @@ -34,7 +34,6 @@ "webpack-merge": "^4.2.2" }, "dependencies": { - "@opentelemetry/exporter-console": "^0.1.0", "@opentelemetry/plugin-document-load": "^0.1.0", "@opentelemetry/tracing": "^0.1.0", "@opentelemetry/web": "^0.1.0" diff --git a/packages/opentelemetry-exporter-console/LICENSE b/packages/opentelemetry-exporter-console/LICENSE deleted file mode 100644 index 261eeb9e9f..0000000000 --- a/packages/opentelemetry-exporter-console/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-exporter-console/README.md b/packages/opentelemetry-exporter-console/README.md deleted file mode 100644 index edbc423dbe..0000000000 --- a/packages/opentelemetry-exporter-console/README.md +++ /dev/null @@ -1,55 +0,0 @@ -# OpenTelemetry Console Exporter -[![Gitter chat][gitter-image]][gitter-url] -[![NPM Published Version][npm-img]][npm-url] -[![dependencies][dependencies-image]][dependencies-url] -[![devDependencies][devDependencies-image]][devDependencies-url] -[![Apache License][license-image]][license-image] - -This module provides a helper exporter that can be used when working with Web applications. - -## Installation - -```bash -npm install --save @opentelemetry/exporter-console -``` - -## Usage - -```js - -import { ConsoleExporter } from '@opentelemetry/exporter-console'; -import { SimpleSpanProcessor } from '@opentelemetry/tracing'; -import { WebTracer } from '@opentelemetry/web'; -import { DocumentLoad } from '@opentelemetry/plugin-document-load'; - -const webTracer = new WebTracer({ - plugins: [ - new DocumentLoad() - ] -}); - -webTracer.addSpanProcessor(new SimpleSpanProcessor(new ConsoleExporter())); - -// if you run this example you should see the exported spans in console - -``` - -## Useful links -- For more information on OpenTelemetry, visit: -- For more about OpenTelemetry JavaScript: -- For help or feedback on this project, join us on [gitter][gitter-url] - -## License - -Apache 2.0 - See [LICENSE][license-url] for more information. - -[gitter-image]: https://badges.gitter.im/open-telemetry/opentelemetry-js.svg -[gitter-url]: https://gitter.im/open-telemetry/opentelemetry-node?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge -[license-url]: https://github.com/open-telemetry/opentelemetry-js/blob/master/LICENSE -[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat -[dependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js/status.svg?path=packages/opentelemetry-exporter-console -[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-exporter-console -[devDependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js/dev-status.svg?path=packages/opentelemetry-exporter-console -[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-web&type=dev -[npm-url]: https://www.npmjs.com/package/@opentelemetry/exporter-console -[npm-img]: https://badge.fury.io/js/%40opentelemetry%2Fexporter-console.svg diff --git a/packages/opentelemetry-exporter-console/karma.conf.js b/packages/opentelemetry-exporter-console/karma.conf.js deleted file mode 100644 index 66529c7d92..0000000000 --- a/packages/opentelemetry-exporter-console/karma.conf.js +++ /dev/null @@ -1,24 +0,0 @@ -/*! - * Copyright 2019, 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 webpackConfig = require('./webpack/test.config.js'); -const karmaBaseConfig = require('../../karma.base'); - -module.exports = (config) => { - config.set(Object.assign({}, karmaBaseConfig, { - webpack: webpackConfig - })) -}; diff --git a/packages/opentelemetry-exporter-console/package.json b/packages/opentelemetry-exporter-console/package.json deleted file mode 100644 index bf3864dc72..0000000000 --- a/packages/opentelemetry-exporter-console/package.json +++ /dev/null @@ -1,72 +0,0 @@ -{ - "name": "@opentelemetry/exporter-console", - "version": "0.1.0", - "description": "OpenTelemetry Console Exporter", - "main": "build/src/index.js", - "types": "build/src/index.d.ts", - "repository": "open-telemetry/opentelemetry-js", - "scripts": { - "test:browser": "nyc karma start --single-run", - "tdd": "karma start", - "codecov:browser": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../", - "clean": "rimraf build/*", - "check": "gts check", - "compile": "tsc -p .", - "watch": "tsc -w", - "fix": "gts fix" - }, - "keywords": [ - "opentelemetry", - "web", - "tracing", - "profiling", - "metrics", - "stats" - ], - "author": "OpenTelemetry Authors", - "license": "Apache-2.0", - "engines": { - "node": ">=8.0.0" - }, - "files": [ - "build/src/**/*.js", - "build/src/**/*.d.ts", - "doc", - "LICENSE", - "README.md" - ], - "publishConfig": { - "access": "public" - }, - "devDependencies": { - "@types/mocha": "^5.2.5", - "@types/webpack-env": "1.13.9", - "@types/sinon": "^7.0.13", - "@babel/core": "^7.6.0", - "babel-loader": "^8.0.6", - "codecov": "^3.1.0", - "gts": "^1.0.0", - "karma": "^4.1.0", - "karma-chrome-launcher": "^2.2.0", - "karma-mocha": "^1.3.0", - "karma-spec-reporter": "^0.0.32", - "karma-webpack": "^4.0.2", - "mocha": "^6.1.0", - "nyc": "^14.1.1", - "rimraf": "^3.0.0", - "sinon": "^7.5.0", - "tslint-consistent-codestyle": "^1.16.0", - "tslint-microsoft-contrib": "^6.2.0", - "ts-loader": "^6.0.4", - "ts-mocha": "^6.0.0", - "typescript": "^3.6.3", - "webpack": "^4.35.2", - "webpack-cli": "^3.3.9", - "webpack-merge": "^4.2.2" - }, - "dependencies": { - "@opentelemetry/base": "^0.1.0", - "@opentelemetry/core": "^0.1.0", - "@opentelemetry/tracing": "^0.1.0" - } -} diff --git a/packages/opentelemetry-exporter-console/src/ConsoleExporter.ts b/packages/opentelemetry-exporter-console/src/ConsoleExporter.ts deleted file mode 100644 index 61e84f5f61..0000000000 --- a/packages/opentelemetry-exporter-console/src/ConsoleExporter.ts +++ /dev/null @@ -1,81 +0,0 @@ -/*! - * Copyright 2019, 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 { hrTimeToMicroseconds } from '@opentelemetry/core'; -import { ReadableSpan, SpanExporter } from '@opentelemetry/tracing'; -import { ExportResult } from '@opentelemetry/base'; - -/** - * Simple console exporter for spans - */ -export class ConsoleExporter implements SpanExporter { - /** - * Export spans. - * @param spans - * @param resultCallback - */ - export( - spans: ReadableSpan[], - resultCallback: (result: ExportResult) => void - ) { - return this._sendSpans(spans, resultCallback); - } - - /** - * Shutdown the exporter. - */ - shutdown() { - this._sendSpans([]); - } - - /** - * converts span info into more readable format - * @param {ReadableSpan} span - * @private - */ - private _exportInfo(span: ReadableSpan) { - return { - traceId: span.spanContext.traceId, - parentId: span.parentSpanId, - name: span.name, - id: span.spanContext.spanId, - kind: span.kind, - timestamp: hrTimeToMicroseconds(span.startTime), - duration: hrTimeToMicroseconds(span.duration), - attributes: span.attributes, - status: span.status, - events: span.events, - }; - } - - /** - * Showing spans in console - * @param {ReadableSpan[]} spans - * @param done - * @private - */ - private _sendSpans( - spans: ReadableSpan[], - done?: (result: ExportResult) => void - ) { - for (let i = 0, j = spans.length; i < j; i++) { - console.log(this._exportInfo(spans[i])); - } - if (done) { - return done(ExportResult.SUCCESS); - } - } -} diff --git a/packages/opentelemetry-exporter-console/src/index.ts b/packages/opentelemetry-exporter-console/src/index.ts deleted file mode 100644 index ae07b0c2b0..0000000000 --- a/packages/opentelemetry-exporter-console/src/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -/*! - * Copyright 2019, 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 './ConsoleExporter'; diff --git a/packages/opentelemetry-exporter-console/test/index-webpack.ts b/packages/opentelemetry-exporter-console/test/index-webpack.ts deleted file mode 100644 index 3899f0edc9..0000000000 --- a/packages/opentelemetry-exporter-console/test/index-webpack.ts +++ /dev/null @@ -1,20 +0,0 @@ -/*! - * Copyright 2019, 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 file is the webpack entry point for the browser Karma tests. It requires -// all modules ending in "test" from the current folder and all its subfolders. -const testsContext = require.context('.', true, /test$/); -testsContext.keys().forEach(testsContext); diff --git a/packages/opentelemetry-exporter-console/tsconfig.json b/packages/opentelemetry-exporter-console/tsconfig.json deleted file mode 100644 index a2042cd68b..0000000000 --- a/packages/opentelemetry-exporter-console/tsconfig.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "extends": "../tsconfig.base", - "compilerOptions": { - "rootDir": ".", - "outDir": "build" - }, - "include": [ - "src/**/*.ts", - "test/**/*.ts" - ] -} diff --git a/packages/opentelemetry-exporter-console/tslint.json b/packages/opentelemetry-exporter-console/tslint.json deleted file mode 100644 index 0710b135d0..0000000000 --- a/packages/opentelemetry-exporter-console/tslint.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "rulesDirectory": ["node_modules/tslint-microsoft-contrib"], - "extends": ["../../tslint.base.js", "./node_modules/tslint-consistent-codestyle"] -} diff --git a/packages/opentelemetry-exporter-console/webpack/test.config.js b/packages/opentelemetry-exporter-console/webpack/test.config.js deleted file mode 100644 index 997cce7182..0000000000 --- a/packages/opentelemetry-exporter-console/webpack/test.config.js +++ /dev/null @@ -1,34 +0,0 @@ -/*! - * Copyright 2019, 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 webpackNodePolyfills = require('../../../webpack.node-polyfills.js'); - -// This is the webpack configuration for browser Karma tests. -module.exports = { - mode: 'development', - target: 'web', - output: { filename: 'bundle.js' }, - resolve: { extensions: ['.ts', '.js'] }, - devtool: 'inline-source-map', - module: { - rules: [ - { test: /\.ts$/, use: 'ts-loader' }, - // This setting configures Node polyfills for the browser that will be - // added to the webpack bundle for Karma tests. - { parser: { node: webpackNodePolyfills } } - ] - } -}; diff --git a/packages/opentelemetry-tracing/package.json b/packages/opentelemetry-tracing/package.json index b462582559..47477f2435 100644 --- a/packages/opentelemetry-tracing/package.json +++ b/packages/opentelemetry-tracing/package.json @@ -45,6 +45,7 @@ "devDependencies": { "@types/mocha": "^5.2.5", "@types/node": "^12.6.8", + "@types/sinon": "^7.0.13", "@types/webpack-env": "1.13.9", "codecov": "^3.1.0", "gts": "^1.0.0", @@ -56,6 +57,7 @@ "mocha": "^6.1.0", "nyc": "^14.1.1", "rimraf": "^3.0.0", + "sinon": "^7.5.0", "tslint-consistent-codestyle": "^1.15.1", "tslint-microsoft-contrib": "^6.2.0", "ts-loader": "^6.0.4", diff --git a/packages/opentelemetry-tracing/src/export/ConsoleSpanExporter.ts b/packages/opentelemetry-tracing/src/export/ConsoleSpanExporter.ts index 0a569a0541..a428467b87 100644 --- a/packages/opentelemetry-tracing/src/export/ConsoleSpanExporter.ts +++ b/packages/opentelemetry-tracing/src/export/ConsoleSpanExporter.ts @@ -17,28 +17,67 @@ import { SpanExporter } from './SpanExporter'; import { ReadableSpan } from './ReadableSpan'; import { ExportResult } from '@opentelemetry/base'; -import { hrTimeToMilliseconds } from '@opentelemetry/core'; +import { hrTimeToMicroseconds } from '@opentelemetry/core'; /** * This is implementation of {@link SpanExporter} that prints spans to the * console. This class can be used for diagnostic purposes. */ export class ConsoleSpanExporter implements SpanExporter { + /** + * Export spans. + * @param spans + * @param resultCallback + */ export( spans: ReadableSpan[], resultCallback: (result: ExportResult) => void ): void { - for (const span of spans) { - console.log( - `{name=${span.name}, traceId=${span.spanContext.traceId}, spanId=${ - span.spanContext.spanId - }, kind=${span.kind}, parent=${ - span.parentSpanId - }, duration=${hrTimeToMilliseconds(span.duration)}}}` - ); - } - return resultCallback(ExportResult.SUCCESS); + return this._sendSpans(spans, resultCallback); + } + + /** + * Shutdown the exporter. + */ + shutdown(): void { + return this._sendSpans([]); + } + + /** + * converts span info into more readable format + * @param {ReadableSpan} span + * @private + */ + private _exportInfo(span: ReadableSpan) { + return { + traceId: span.spanContext.traceId, + parentId: span.parentSpanId, + name: span.name, + id: span.spanContext.spanId, + kind: span.kind, + timestamp: hrTimeToMicroseconds(span.startTime), + duration: hrTimeToMicroseconds(span.duration), + attributes: span.attributes, + status: span.status, + events: span.events, + }; } - shutdown(): void {} + /** + * Showing spans in console + * @param {ReadableSpan[]} spans + * @param done + * @private + */ + private _sendSpans( + spans: ReadableSpan[], + done?: (result: ExportResult) => void + ): void { + for (let i = 0, j = spans.length; i < j; i++) { + console.log(this._exportInfo(spans[i])); + } + if (done) { + return done(ExportResult.SUCCESS); + } + } } diff --git a/packages/opentelemetry-exporter-console/test/ConsoleExporter.test.ts b/packages/opentelemetry-tracing/test/export/ConsoleSpanExporter.test.ts similarity index 82% rename from packages/opentelemetry-exporter-console/test/ConsoleExporter.test.ts rename to packages/opentelemetry-tracing/test/export/ConsoleSpanExporter.test.ts index 79691de6b7..95691ea0e0 100644 --- a/packages/opentelemetry-exporter-console/test/ConsoleExporter.test.ts +++ b/packages/opentelemetry-tracing/test/export/ConsoleSpanExporter.test.ts @@ -14,29 +14,39 @@ * limitations under the License. */ -import { BasicTracer, SimpleSpanProcessor } from '@opentelemetry/tracing'; import * as assert from 'assert'; -import { ConsoleExporter } from '../src'; import * as sinon from 'sinon'; +import { + BasicTracer, + ConsoleSpanExporter, + SimpleSpanProcessor, +} from '../../src'; -describe('ConsoleExporter', () => { - let consoleExporter: ConsoleExporter; +describe('ConsoleSpanExporter', () => { + let consoleExporter: ConsoleSpanExporter; + let previousConsoleLog: any; beforeEach(() => { - consoleExporter = new ConsoleExporter(); + previousConsoleLog = console.log; + console.log = () => {}; + consoleExporter = new ConsoleSpanExporter(); }); - afterEach(() => {}); + afterEach(() => { + console.log = previousConsoleLog; + }); describe('.export()', () => { it('should export information about span', () => { assert.doesNotThrow(() => { const basicTracer = new BasicTracer(); - consoleExporter = new ConsoleExporter(); - const spyExport = sinon.spy(consoleExporter, 'export'); + consoleExporter = new ConsoleSpanExporter(); + const spyConsole = sinon.spy(console, 'log'); + const spyExport = sinon.spy(consoleExporter, 'export'); basicTracer.addSpanProcessor(new SimpleSpanProcessor(consoleExporter)); + const span = basicTracer.startSpan('foo'); span.addEvent('foobar'); span.end(); diff --git a/packages/opentelemetry-web/README.md b/packages/opentelemetry-web/README.md index 56f7d30332..20117c68fc 100644 --- a/packages/opentelemetry-web/README.md +++ b/packages/opentelemetry-web/README.md @@ -11,7 +11,19 @@ For manual instrumentation see the [@opentelemetry/web](https://github.com/open-telemetry/opentelemetry-js/tree/master/packages/opentelemetry-web) package. ## How does automatic tracing work? -> Automatic Instrumentation is in progress, manual instrumentation only supported +```js +import { ConsoleSpanExporter, SimpleSpanProcessor } from '@opentelemetry/tracing'; +import { WebTracer } from '@opentelemetry/web'; +import { DocumentLoad } from '@opentelemetry/plugin-document-load'; + +const webTracer = new WebTracer({ + plugins: [ + new DocumentLoad() + ] +}); + +webTracer.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter())); +``` ## Installation @@ -27,7 +39,6 @@ const { WebTracer } = require('@opentelemetry/web'); const webTracer = new WebTracer(); const span = webTracer.startSpan('span1'); webTracer.withSpan(span, function () { - // this === span this.addEvent('start'); }); span.addEvent('middle'); diff --git a/packages/opentelemetry-web/src/WebTracer.ts b/packages/opentelemetry-web/src/WebTracer.ts index de3b51e254..b64f8c0a65 100644 --- a/packages/opentelemetry-web/src/WebTracer.ts +++ b/packages/opentelemetry-web/src/WebTracer.ts @@ -15,10 +15,7 @@ */ import { BasePlugin } from '@opentelemetry/core'; -import { - BasicTracer, - BasicTracerConfig -} from '@opentelemetry/tracing'; +import { BasicTracer, BasicTracerConfig } from '@opentelemetry/tracing'; import { StackScopeManager } from './StackScopeManager'; /** @@ -46,7 +43,7 @@ export class WebTracer extends BasicTracer { if (typeof config.plugins === 'undefined') { config.plugins = []; } - super(Object.assign({}, {scopeManager: config.scopeManager}, config)); + super(Object.assign({}, { scopeManager: config.scopeManager }, config)); // enable scope manager config.scopeManager.enable(); From f6a526e64131dcbe085e5282c9e037dcb801d275 Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Tue, 15 Oct 2019 16:45:44 +0200 Subject: [PATCH 07/33] chore: fixing timeOrigin when browser is using older version of performance (safari for example) --- packages/opentelemetry-core/src/common/time.ts | 13 +++++++++++-- packages/opentelemetry-core/src/common/types.ts | 6 ++++++ .../opentelemetry-core/test/common/time.test.ts | 17 +++++++++++++++++ packages/opentelemetry-tracing/package.json | 13 +++++++------ 4 files changed, 41 insertions(+), 8 deletions(-) diff --git a/packages/opentelemetry-core/src/common/time.ts b/packages/opentelemetry-core/src/common/time.ts index 893cbd8758..0918acb6b3 100644 --- a/packages/opentelemetry-core/src/common/time.ts +++ b/packages/opentelemetry-core/src/common/time.ts @@ -16,6 +16,7 @@ import * as types from '@opentelemetry/types'; import { otperformance as performance } from '../platform'; +import { TimeOriginLegacy } from './types'; const NANOSECOND_DIGITS = 9; const SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS); @@ -32,9 +33,17 @@ function numberToHrtime(epochMillis: number): types.HrTime { return [seconds, nanos]; } +function getTimeOrigin(): number { + let timeOrigin = performance.timeOrigin; + if (typeof timeOrigin !== 'number') { + const perf: TimeOriginLegacy = (performance as unknown) as TimeOriginLegacy; + timeOrigin = perf.timing && perf.timing.fetchStart; + } + return timeOrigin; +} // Returns an hrtime calculated via performance component. export function hrTime(performanceNow?: number): types.HrTime { - const timeOrigin = numberToHrtime(performance.timeOrigin); + const timeOrigin = numberToHrtime(getTimeOrigin()); const now = numberToHrtime( typeof performanceNow === 'number' ? performanceNow : performance.now() ); @@ -58,7 +67,7 @@ export function timeInputToHrTime(time: types.TimeInput): types.HrTime { return time; } else if (typeof time === 'number') { // Must be a performance.now() if it's smaller than process start time. - if (time < performance.timeOrigin) { + if (time < getTimeOrigin()) { return hrTime(time); } // epoch milliseconds or performance.timeOrigin diff --git a/packages/opentelemetry-core/src/common/types.ts b/packages/opentelemetry-core/src/common/types.ts index 7c549e3a12..4826b53a48 100644 --- a/packages/opentelemetry-core/src/common/types.ts +++ b/packages/opentelemetry-core/src/common/types.ts @@ -21,3 +21,9 @@ export enum LogLevel { INFO, DEBUG, } + +export interface TimeOriginLegacy { + timing: { + fetchStart: number; + }; +} diff --git a/packages/opentelemetry-core/test/common/time.test.ts b/packages/opentelemetry-core/test/common/time.test.ts index a974dda198..48060b00a4 100644 --- a/packages/opentelemetry-core/test/common/time.test.ts +++ b/packages/opentelemetry-core/test/common/time.test.ts @@ -62,6 +62,23 @@ describe('time', () => { const output = hrTime(performanceNow); assert.deepStrictEqual(output, [0, 23100000]); }); + + describe('when timeOrigin is not available', () => { + it('should use the performance.timing.fetchStart as a fallback', () => { + Object.defineProperty(performance, 'timing', { + writable: true, + value: { + fetchStart: 11.5, + }, + }); + + sandbox.stub(performance, 'timeOrigin').value(undefined); + sandbox.stub(performance, 'now').callsFake(() => 11.3); + + const output = hrTime(); + assert.deepStrictEqual(output, [0, 22800000]); + }); + }); }); describe('#timeInputToHrTime', () => { diff --git a/packages/opentelemetry-tracing/package.json b/packages/opentelemetry-tracing/package.json index 47477f2435..c0193af9c6 100644 --- a/packages/opentelemetry-tracing/package.json +++ b/packages/opentelemetry-tracing/package.json @@ -10,14 +10,15 @@ "types": "build/src/index.d.ts", "repository": "open-telemetry/opentelemetry-js", "scripts": { - "test": "nyc ts-mocha -p tsconfig.json 'test/**/*.ts' --exclude 'test/index-webpack.ts'", - "test:browser": "karma start --single-run", - "tdd": "yarn test -- --watch-extensions ts --watch", - "codecov": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../", - "clean": "rimraf build/*", "check": "gts check", + "clean": "rimraf build/*", + "codecov": "nyc report --reporter=json && codecov -f coverage/*.json -p ../../", "compile": "tsc -p .", - "fix": "gts fix" + "fix": "gts fix", + "tdd": "yarn test -- --watch-extensions ts --watch", + "test": "nyc ts-mocha -p tsconfig.json 'test/**/*.ts' --exclude 'test/index-webpack.ts'", + "test:browser": "karma start --single-run", + "watch": "tsc -w" }, "keywords": [ "opentelemetry", From edd982269924184585909e3037b6451a4f2b301c Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Tue, 15 Oct 2019 18:21:18 +0200 Subject: [PATCH 08/33] chore: removing @private --- .../opentelemetry-plugin-document-load/src/documentLoad.ts | 7 ------- .../src/export/ConsoleSpanExporter.ts | 2 -- packages/opentelemetry-web/src/StackScopeManager.ts | 1 - 3 files changed, 10 deletions(-) diff --git a/packages/opentelemetry-plugin-document-load/src/documentLoad.ts b/packages/opentelemetry-plugin-document-load/src/documentLoad.ts index 1856d15f94..e97d9491f9 100644 --- a/packages/opentelemetry-plugin-document-load/src/documentLoad.ts +++ b/packages/opentelemetry-plugin-document-load/src/documentLoad.ts @@ -44,7 +44,6 @@ export class DocumentLoad extends BasePlugin { /** * callback to be executed when page is loaded - * @private */ private _onDocumentLoaded() { this._collectPerformance(); @@ -52,7 +51,6 @@ export class DocumentLoad extends BasePlugin { /** * Collects information about performance and creates appropriate spans - * @private */ private _collectPerformance() { const entries = this._getEntries(); @@ -142,7 +140,6 @@ export class DocumentLoad extends BasePlugin { * @param {Span} span * @param {string} performanceName - name of performance entry for time end * @param {PerformanceEntries} entries - * @private */ private _endSpan( span: Span | undefined, @@ -157,7 +154,6 @@ export class DocumentLoad extends BasePlugin { /** * gets performance entries of navigation - * @private */ private _getEntries() { const entries: PerformanceEntries = {}; @@ -201,7 +197,6 @@ export class DocumentLoad extends BasePlugin { * @param {string} performanceNameEnd - name of performance entry for time end * @param {PerformanceEntries} entries * @param {SpanOptions} spanOptions - * @private */ private _startAndFinishSpan( spanName: string, @@ -226,7 +221,6 @@ export class DocumentLoad extends BasePlugin { * @param {string} performanceName - name of performance entry for time start * @param {PerformanceEntries} entries * @param {SpanOptions} spanOptions - * @private */ private _startSpan( spanName: string, @@ -256,7 +250,6 @@ export class DocumentLoad extends BasePlugin { /** * executes callback {_onDocumentLoaded} when the page is loaded - * @private */ private _waitForPageLoad() { if (window.document.readyState === 'complete') { diff --git a/packages/opentelemetry-tracing/src/export/ConsoleSpanExporter.ts b/packages/opentelemetry-tracing/src/export/ConsoleSpanExporter.ts index a428467b87..14fa951943 100644 --- a/packages/opentelemetry-tracing/src/export/ConsoleSpanExporter.ts +++ b/packages/opentelemetry-tracing/src/export/ConsoleSpanExporter.ts @@ -46,7 +46,6 @@ export class ConsoleSpanExporter implements SpanExporter { /** * converts span info into more readable format * @param {ReadableSpan} span - * @private */ private _exportInfo(span: ReadableSpan) { return { @@ -67,7 +66,6 @@ export class ConsoleSpanExporter implements SpanExporter { * Showing spans in console * @param {ReadableSpan[]} spans * @param done - * @private */ private _sendSpans( spans: ReadableSpan[], diff --git a/packages/opentelemetry-web/src/StackScopeManager.ts b/packages/opentelemetry-web/src/StackScopeManager.ts index 9f9e5f9f7a..c6dc866c20 100644 --- a/packages/opentelemetry-web/src/StackScopeManager.ts +++ b/packages/opentelemetry-web/src/StackScopeManager.ts @@ -35,7 +35,6 @@ export class StackScopeManager implements ScopeManager { * * @param target Function to be executed within the scope * @param scope - * @private */ private _bindFunction(target: T, scope?: unknown): T { const manager = this; From 67523332c644ed9d1b8bcf0dd4bedad8ec8afd10 Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Tue, 15 Oct 2019 18:25:56 +0200 Subject: [PATCH 09/33] chore: cleaning the docs --- .../src/documentLoad.ts | 28 +++++++++---------- .../src/export/ConsoleSpanExporter.ts | 4 +-- 2 files changed, 15 insertions(+), 17 deletions(-) diff --git a/packages/opentelemetry-plugin-document-load/src/documentLoad.ts b/packages/opentelemetry-plugin-document-load/src/documentLoad.ts index e97d9491f9..00ab18a981 100644 --- a/packages/opentelemetry-plugin-document-load/src/documentLoad.ts +++ b/packages/opentelemetry-plugin-document-load/src/documentLoad.ts @@ -21,8 +21,6 @@ import { PerformanceTimingNames } from './enums/PerformanceTimingNames'; import { PerformanceEntries, PerformanceLegacy } from './types'; import { hasKey } from './utils'; -// import { IPerformanceEntries, PerformanceEntries, PerformanceLegacy } from './types'; - /** * This class represents a document load plugin */ @@ -34,7 +32,7 @@ export class DocumentLoad extends BasePlugin { /** * - * @param {DocumentLoadConfig} config + * @param config */ constructor(config: PluginConfig = {}) { super(); @@ -137,9 +135,9 @@ export class DocumentLoad extends BasePlugin { /** * Helper function for ending span - * @param {Span} span - * @param {string} performanceName - name of performance entry for time end - * @param {PerformanceEntries} entries + * @param span + * @param performanceName name of performance entry for time end + * @param entries */ private _endSpan( span: Span | undefined, @@ -192,11 +190,11 @@ export class DocumentLoad extends BasePlugin { /** * Helper function for starting and finishing a span - * @param {string} spanName - name of span - * @param {string} performanceNameStart - name of performance entry for time start - * @param {string} performanceNameEnd - name of performance entry for time end - * @param {PerformanceEntries} entries - * @param {SpanOptions} spanOptions + * @param spanName name of span + * @param performanceNameStart name of performance entry for time start + * @param performanceNameEnd name of performance entry for time end + * @param entries + * @param spanOptions */ private _startAndFinishSpan( spanName: string, @@ -217,10 +215,10 @@ export class DocumentLoad extends BasePlugin { /** * Helper function for starting a span - * @param {string} spanName - name of span - * @param {string} performanceName - name of performance entry for time start - * @param {PerformanceEntries} entries - * @param {SpanOptions} spanOptions + * @param spanName name of span + * @param performanceName name of performance entry for time start + * @param entries + * @param spanOptions */ private _startSpan( spanName: string, diff --git a/packages/opentelemetry-tracing/src/export/ConsoleSpanExporter.ts b/packages/opentelemetry-tracing/src/export/ConsoleSpanExporter.ts index 14fa951943..abc0459f47 100644 --- a/packages/opentelemetry-tracing/src/export/ConsoleSpanExporter.ts +++ b/packages/opentelemetry-tracing/src/export/ConsoleSpanExporter.ts @@ -45,7 +45,7 @@ export class ConsoleSpanExporter implements SpanExporter { /** * converts span info into more readable format - * @param {ReadableSpan} span + * @param span */ private _exportInfo(span: ReadableSpan) { return { @@ -64,7 +64,7 @@ export class ConsoleSpanExporter implements SpanExporter { /** * Showing spans in console - * @param {ReadableSpan[]} spans + * @param spans * @param done */ private _sendSpans( From 1d6593d6f7c3db0aa113db265cb5957c3f7980fd Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Tue, 15 Oct 2019 18:33:56 +0200 Subject: [PATCH 10/33] chore: using stubs on public instead of private --- .../test/documentLoad.test.ts | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/packages/opentelemetry-plugin-document-load/test/documentLoad.test.ts b/packages/opentelemetry-plugin-document-load/test/documentLoad.test.ts index b496ac00e7..4b931de7b1 100644 --- a/packages/opentelemetry-plugin-document-load/test/documentLoad.test.ts +++ b/packages/opentelemetry-plugin-document-load/test/documentLoad.test.ts @@ -78,13 +78,10 @@ describe('DocumentLoad Plugin', () => { describe('when document readyState is complete', () => { it('should start collecting the performance immediately', () => { - const spy_OnDocumentLoaded = sinon.spy( - plugin, - '_collectPerformance' as never - ); + const spyOnEnd = sinon.spy(dummyExporter, 'export'); plugin.enable(moduleExports, tracer, logger, config); assert.strictEqual(window.document.readyState, 'complete'); - assert.ok(spy_OnDocumentLoaded.calledOnce); + assert.ok(spyOnEnd.callCount === 6); }); }); @@ -98,17 +95,14 @@ describe('DocumentLoad Plugin', () => { it('should collect performance after document load event', () => { const spy = sinon.spy(window, 'addEventListener'); - const spy_OnDocumentLoaded = sinon.spy( - plugin, - '_collectPerformance' as never - ); + const spyOnEnd = sinon.spy(dummyExporter, 'export'); plugin.enable(moduleExports, tracer, logger, config); const args = spy.args[0]; const name = args[0]; assert.strictEqual(name, 'load'); assert.ok(spy.calledOnce); - assert.ok(spy_OnDocumentLoaded.calledOnce === false); + assert.ok(spyOnEnd.callCount === 0); window.dispatchEvent( new CustomEvent('load', { @@ -118,7 +112,7 @@ describe('DocumentLoad Plugin', () => { detail: {}, }) ); - assert.ok(spy_OnDocumentLoaded.calledOnce); + assert.ok(spyOnEnd.callCount === 6); }); }); From da85aa4aa757d3dd3434597f43b571992721fb9e Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Tue, 15 Oct 2019 18:37:52 +0200 Subject: [PATCH 11/33] chore: added explanation when span can be undefined --- packages/opentelemetry-plugin-document-load/src/documentLoad.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/opentelemetry-plugin-document-load/src/documentLoad.ts b/packages/opentelemetry-plugin-document-load/src/documentLoad.ts index 00ab18a981..da213ff69b 100644 --- a/packages/opentelemetry-plugin-document-load/src/documentLoad.ts +++ b/packages/opentelemetry-plugin-document-load/src/documentLoad.ts @@ -144,6 +144,7 @@ export class DocumentLoad extends BasePlugin { performanceName: string, entries: PerformanceEntries ) { + // span can be undefined when entries are missing the certain performance - the span will not be created if (typeof span !== 'undefined' && hasKey(entries, performanceName)) { span.addEvent(performanceName); span.end(entries[performanceName]); @@ -203,6 +204,7 @@ export class DocumentLoad extends BasePlugin { entries: PerformanceEntries, spanOptions: SpanOptions = {} ): Span | undefined { + // span can be undefined when entries are missing the certain performance - the span will not be created const span = this._startSpan( spanName, performanceNameStart, From 2dba249dc2d0df9749026a644322224093090456 Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Tue, 15 Oct 2019 22:32:45 +0200 Subject: [PATCH 12/33] chore: adding unit test for case when passed "performanceNow" is equal to 0 --- packages/opentelemetry-core/test/common/time.test.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/packages/opentelemetry-core/test/common/time.test.ts b/packages/opentelemetry-core/test/common/time.test.ts index 48060b00a4..b8058df4bc 100644 --- a/packages/opentelemetry-core/test/common/time.test.ts +++ b/packages/opentelemetry-core/test/common/time.test.ts @@ -63,6 +63,13 @@ describe('time', () => { assert.deepStrictEqual(output, [0, 23100000]); }); + it('should allow passed "performanceNow" equal to 0', () => { + sandbox.stub(performance, 'timeOrigin').value(11.5); + + const output = hrTime(0); + assert.deepStrictEqual(output, [0, 11500000]); + }); + describe('when timeOrigin is not available', () => { it('should use the performance.timing.fetchStart as a fallback', () => { Object.defineProperty(performance, 'timing', { From 2880dc3a20c2915abf35938094d7da698f2740ad Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Tue, 15 Oct 2019 22:45:12 +0200 Subject: [PATCH 13/33] chore: adding unit test for case when passed "performanceNow" is null or undefined --- .../opentelemetry-core/test/common/time.test.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/packages/opentelemetry-core/test/common/time.test.ts b/packages/opentelemetry-core/test/common/time.test.ts index b8058df4bc..acdac2badc 100644 --- a/packages/opentelemetry-core/test/common/time.test.ts +++ b/packages/opentelemetry-core/test/common/time.test.ts @@ -65,11 +65,28 @@ describe('time', () => { it('should allow passed "performanceNow" equal to 0', () => { sandbox.stub(performance, 'timeOrigin').value(11.5); + sandbox.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); + + 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); + + const output = hrTime(null); + assert.deepStrictEqual(output, [0, 22800000]); + }); + describe('when timeOrigin is not available', () => { it('should use the performance.timing.fetchStart as a fallback', () => { Object.defineProperty(performance, 'timing', { From e6abf4eea50225e10a5f4231496b84727a891ec4 Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Tue, 15 Oct 2019 22:51:22 +0200 Subject: [PATCH 14/33] chore: fixing unit test with null --- packages/opentelemetry-core/test/common/time.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/opentelemetry-core/test/common/time.test.ts b/packages/opentelemetry-core/test/common/time.test.ts index acdac2badc..b7ac8a5f32 100644 --- a/packages/opentelemetry-core/test/common/time.test.ts +++ b/packages/opentelemetry-core/test/common/time.test.ts @@ -83,7 +83,7 @@ describe('time', () => { sandbox.stub(performance, 'timeOrigin').value(11.5); sandbox.stub(performance, 'now').callsFake(() => 11.3); - const output = hrTime(null); + const output = hrTime(null as any); assert.deepStrictEqual(output, [0, 22800000]); }); From 921049d3094489e505f62c310f1a532ebeb13e78 Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Wed, 16 Oct 2019 17:59:44 +0200 Subject: [PATCH 15/33] chore: bump version --- packages/opentelemetry-plugin-document-load/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/opentelemetry-plugin-document-load/package.json b/packages/opentelemetry-plugin-document-load/package.json index 0d2c4b0b3c..d3c4d56920 100644 --- a/packages/opentelemetry-plugin-document-load/package.json +++ b/packages/opentelemetry-plugin-document-load/package.json @@ -1,6 +1,6 @@ { "name": "@opentelemetry/plugin-document-load", - "version": "0.1.0", + "version": "0.1.1", "description": "OpenTelemetry document-load automatic instrumentation package.", "main": "build/src/index.js", "types": "build/src/index.d.ts", From da2f9bb0940ddbe99a90749d1108573a2357731f Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Wed, 16 Oct 2019 21:04:39 +0200 Subject: [PATCH 16/33] chore: after changing enum keys to capitals I had to use values to align them with performance metric in type "PerformanceEntries" --- .../src/documentLoad.ts | 5 +++-- .../src/types.ts | 20 ++++++++++++++++++- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/packages/opentelemetry-plugin-document-load/src/documentLoad.ts b/packages/opentelemetry-plugin-document-load/src/documentLoad.ts index da213ff69b..a483b4c1d1 100644 --- a/packages/opentelemetry-plugin-document-load/src/documentLoad.ts +++ b/packages/opentelemetry-plugin-document-load/src/documentLoad.ts @@ -156,9 +156,10 @@ export class DocumentLoad extends BasePlugin { */ private _getEntries() { const entries: PerformanceEntries = {}; - const performanceNavigationTiming = otperformance.getEntriesByType( + const performanceNavigationTiming = (otperformance.getEntriesByType( 'navigation' - )[0] as PerformanceEntries; + )[0] as unknown) as PerformanceEntries; + if (performanceNavigationTiming) { const keys = Object.values(PerformanceTimingNames); const startTime = otperformance.timeOrigin; diff --git a/packages/opentelemetry-plugin-document-load/src/types.ts b/packages/opentelemetry-plugin-document-load/src/types.ts index ca9ad0560e..0cdba4ee79 100644 --- a/packages/opentelemetry-plugin-document-load/src/types.ts +++ b/packages/opentelemetry-plugin-document-load/src/types.ts @@ -17,7 +17,25 @@ import { PerformanceTimingNames } from './enums/PerformanceTimingNames'; export type PerformanceEntries = { - [index in PerformanceTimingNames]?: number; + [PerformanceTimingNames.CONNECT_END]?: number; + [PerformanceTimingNames.CONNECT_START]?: number; + [PerformanceTimingNames.DOM_COMPLETE]?: number; + [PerformanceTimingNames.DOM_CONTENT_LOADED_EVENT_END]?: number; + [PerformanceTimingNames.DOM_CONTENT_LOADED_EVENT_START]?: number; + [PerformanceTimingNames.DOM_INTERACTIVE]?: number; + [PerformanceTimingNames.DOMAIN_LOOKUP_END]?: number; + [PerformanceTimingNames.DOMAIN_LOOKUP_START]?: number; + [PerformanceTimingNames.FETCH_START]?: number; + [PerformanceTimingNames.LOAD_EVENT_END]?: number; + [PerformanceTimingNames.LOAD_EVENT_START]?: number; + [PerformanceTimingNames.REDIRECT_END]?: number; + [PerformanceTimingNames.REDIRECT_START]?: number; + [PerformanceTimingNames.REQUEST_START]?: number; + [PerformanceTimingNames.RESPONSE_END]?: number; + [PerformanceTimingNames.RESPONSE_START]?: number; + [PerformanceTimingNames.SECURE_CONNECTION_START]?: number; + [PerformanceTimingNames.UNLOAD_EVENT_END]?: number; + [PerformanceTimingNames.UNLOAD_EVENT_START]?: number; }; export interface PerformanceLegacy { From c1b17fbfb6ade65f58dc16515f815d8cfb8c49b6 Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Thu, 17 Oct 2019 14:11:36 +0200 Subject: [PATCH 17/33] chore: adding comments for interfaces --- packages/opentelemetry-core/src/common/types.ts | 5 +++++ packages/opentelemetry-plugin-document-load/src/types.ts | 7 +++++++ 2 files changed, 12 insertions(+) diff --git a/packages/opentelemetry-core/src/common/types.ts b/packages/opentelemetry-core/src/common/types.ts index 4826b53a48..d765535031 100644 --- a/packages/opentelemetry-core/src/common/types.ts +++ b/packages/opentelemetry-core/src/common/types.ts @@ -22,6 +22,11 @@ export enum LogLevel { DEBUG, } +/** + * This interface defines a fallback to read a timeOrigin when it is not available on performance.timeOrigin, + * this happens for example on Safari Mac + * then the timeOrigin is taken from fetchStart - which is the closest to timeOrigin + */ export interface TimeOriginLegacy { timing: { fetchStart: number; diff --git a/packages/opentelemetry-plugin-document-load/src/types.ts b/packages/opentelemetry-plugin-document-load/src/types.ts index 0cdba4ee79..cd99cb6e9c 100644 --- a/packages/opentelemetry-plugin-document-load/src/types.ts +++ b/packages/opentelemetry-plugin-document-load/src/types.ts @@ -16,6 +16,9 @@ import { PerformanceTimingNames } from './enums/PerformanceTimingNames'; +/** + * Performance metrics + */ export type PerformanceEntries = { [PerformanceTimingNames.CONNECT_END]?: number; [PerformanceTimingNames.CONNECT_START]?: number; @@ -38,6 +41,10 @@ export type PerformanceEntries = { [PerformanceTimingNames.UNLOAD_EVENT_START]?: number; }; +/** + * This interface defines a fallback to read performance metrics, + * this happens for example on Safari Mac + */ export interface PerformanceLegacy { timing?: PerformanceEntries; } From 486a7401eab97e7e534d11119d065153090ea836 Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Mon, 21 Oct 2019 17:25:10 +0200 Subject: [PATCH 18/33] feat: adding possibility of setting start time for event --- packages/opentelemetry-tracing/src/Span.ts | 16 +++++++++++++-- .../opentelemetry-tracing/test/Span.test.ts | 20 +++++++++++++++++++ .../opentelemetry-types/src/trace/span.ts | 3 ++- 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/packages/opentelemetry-tracing/src/Span.ts b/packages/opentelemetry-tracing/src/Span.ts index 0713e01a3a..bf974e3bb1 100644 --- a/packages/opentelemetry-tracing/src/Span.ts +++ b/packages/opentelemetry-tracing/src/Span.ts @@ -101,13 +101,25 @@ export class Span implements types.Span, ReadableSpan { return this; } - addEvent(name: string, attributes?: types.Attributes): this { + /** + * + * @param name Span Name + * @param attributes Span attributes + * @param startTime Specified start time for the event + */ + addEvent( + name: string, + attributes?: types.Attributes, + startTime?: number + ): this { if (this._isSpanEnded()) return this; if (this.events.length >= this._traceParams.numberOfEventsPerSpan!) { this._logger.warn('Dropping extra events.'); this.events.shift(); } - this.events.push({ name, attributes, time: hrTime() }); + const time = + typeof startTime === 'number' ? timeInputToHrTime(startTime) : hrTime(); + this.events.push({ name, attributes, time }); return this; } diff --git a/packages/opentelemetry-tracing/test/Span.test.ts b/packages/opentelemetry-tracing/test/Span.test.ts index f485e5a915..3c52d107f8 100644 --- a/packages/opentelemetry-tracing/test/Span.test.ts +++ b/packages/opentelemetry-tracing/test/Span.test.ts @@ -27,6 +27,7 @@ import { hrTimeToNanoseconds, hrTimeToMilliseconds, NoopLogger, + hrTimeDuration, } from '@opentelemetry/core'; const performanceTimeOrigin = hrTime(); @@ -87,6 +88,25 @@ describe('Span', () => { ); }); + it('should have an entered time for event', () => { + const span = new Span( + tracer, + name, + spanContext, + SpanKind.SERVER, + undefined, + 0 + ); + const timeMS = 123; + const spanStartTime = hrTimeToMilliseconds(span.startTime); + const eventTime = spanStartTime + timeMS; + + span.addEvent('my-event', undefined, eventTime); + + const diff = hrTimeDuration(span.startTime, span.events[0].time); + assert.strictEqual(hrTimeToMilliseconds(diff), 123); + }); + it('should get the span context of span', () => { const span = new Span(tracer, name, spanContext, SpanKind.CLIENT); const context = span.context(); diff --git a/packages/opentelemetry-types/src/trace/span.ts b/packages/opentelemetry-types/src/trace/span.ts index 2791594981..75cf6ee52e 100644 --- a/packages/opentelemetry-types/src/trace/span.ts +++ b/packages/opentelemetry-types/src/trace/span.ts @@ -62,8 +62,9 @@ export interface Span { * @param name the name of the event. * @param [attributes] the attributes that will be added; these are * associated with this event. + * @param [startTime] start time of the event. */ - addEvent(name: string, attributes?: Attributes): this; + addEvent(name: string, attributes?: Attributes, startTime?: number): this; /** * Adds a link to the Span. From 2607a8deb8017a6966a94699bbaee6bc122050c0 Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Mon, 21 Oct 2019 17:25:58 +0200 Subject: [PATCH 19/33] chore: refactoring document load to use events instead of new spans --- .../src/documentLoad.ts | 148 ++++++------------ .../src/enums/AttributeNames.ts | 6 - .../test/documentLoad.test.ts | 85 +++++----- 3 files changed, 95 insertions(+), 144 deletions(-) diff --git a/packages/opentelemetry-plugin-document-load/src/documentLoad.ts b/packages/opentelemetry-plugin-document-load/src/documentLoad.ts index a483b4c1d1..623758c1b3 100644 --- a/packages/opentelemetry-plugin-document-load/src/documentLoad.ts +++ b/packages/opentelemetry-plugin-document-load/src/documentLoad.ts @@ -17,7 +17,7 @@ import { BasePlugin, otperformance } from '@opentelemetry/core'; import { PluginConfig, Span, SpanOptions } from '@opentelemetry/types'; import { AttributeNames } from './enums/AttributeNames'; -import { PerformanceTimingNames } from './enums/PerformanceTimingNames'; +import { PerformanceTimingNames as PTN } from './enums/PerformanceTimingNames'; import { PerformanceEntries, PerformanceLegacy } from './types'; import { hasKey } from './utils'; @@ -47,6 +47,27 @@ export class DocumentLoad extends BasePlugin { this._collectPerformance(); } + /** + * Helper function for starting an event + * @param span + * @param performanceName name of performance entry for time start + * @param entries + */ + private _addSpanEvent( + span: Span, + performanceName: string, + entries: PerformanceEntries + ): Span | undefined { + if ( + hasKey(entries, performanceName) && + typeof entries[performanceName] === 'number' + ) { + span.addEvent(performanceName, undefined, entries[performanceName]); + return span; + } + return undefined; + } + /** * Collects information about performance and creates appropriate spans */ @@ -55,82 +76,29 @@ export class DocumentLoad extends BasePlugin { const rootSpan = this._startSpan( AttributeNames.DOCUMENT_LOAD, - PerformanceTimingNames.FETCH_START, + PTN.FETCH_START, entries ); - - this._startAndFinishSpan( - AttributeNames.DOMAIN_LOOKUP, - PerformanceTimingNames.DOMAIN_LOOKUP_START, - PerformanceTimingNames.DOMAIN_LOOKUP_END, - entries, - { - parent: rootSpan, - } - ); - - // Opening Connection - const connectSpan = this._startSpan( - AttributeNames.CONNECT, - PerformanceTimingNames.CONNECT_START, - entries, - { - parent: rootSpan, - } - ); - - // TLS negotiation - if (hasKey(entries, PerformanceTimingNames.SECURE_CONNECTION_START)) { - const value = entries[PerformanceTimingNames.SECURE_CONNECTION_START]; - if (typeof value === 'number' && value > 0) { - this._startAndFinishSpan( - AttributeNames.CONNECT_SECURE, - PerformanceTimingNames.SECURE_CONNECTION_START, - PerformanceTimingNames.CONNECT_END, - entries, - { - parent: connectSpan, - } - ); - } + if (!rootSpan) { + return; } - // Connection negotiation ends - this._endSpan(connectSpan, PerformanceTimingNames.CONNECT_END, entries); - - // Cache seek plus response time - this._startAndFinishSpan( - AttributeNames.CACHE_SEEK, - PerformanceTimingNames.FETCH_START, - PerformanceTimingNames.RESPONSE_END, - entries, - { - parent: rootSpan, - } - ); - - // TTFB - time to first byte - this._startAndFinishSpan( - AttributeNames.TTFB, - PerformanceTimingNames.REQUEST_START, - PerformanceTimingNames.RESPONSE_START, - entries, - { - parent: rootSpan, - } - ); - - // Response time only (download) - this._startAndFinishSpan( - AttributeNames.RESPONSE_TIME, - PerformanceTimingNames.RESPONSE_START, - PerformanceTimingNames.RESPONSE_END, - entries, - { - parent: rootSpan, - } - ); - this._endSpan(rootSpan, PerformanceTimingNames.LOAD_EVENT_START, entries); + this._addSpanEvent(rootSpan, PTN.DOMAIN_LOOKUP_START, entries); + this._addSpanEvent(rootSpan, PTN.DOMAIN_LOOKUP_END, entries); + this._addSpanEvent(rootSpan, PTN.CONNECT_START, entries); + this._addSpanEvent(rootSpan, PTN.SECURE_CONNECTION_START, entries); + this._addSpanEvent(rootSpan, PTN.CONNECT_END, entries); + this._addSpanEvent(rootSpan, PTN.REQUEST_START, entries); + this._addSpanEvent(rootSpan, PTN.RESPONSE_START, entries); + this._addSpanEvent(rootSpan, PTN.RESPONSE_END, entries); + this._addSpanEvent(rootSpan, PTN.UNLOAD_EVENT_START, entries); + this._addSpanEvent(rootSpan, PTN.UNLOAD_EVENT_END, entries); + this._addSpanEvent(rootSpan, PTN.DOM_INTERACTIVE, entries); + this._addSpanEvent(rootSpan, PTN.DOM_CONTENT_LOADED_EVENT_START, entries); + this._addSpanEvent(rootSpan, PTN.DOM_CONTENT_LOADED_EVENT_END, entries); + this._addSpanEvent(rootSpan, PTN.DOM_COMPLETE, entries); + + this._endSpan(rootSpan, PTN.LOAD_EVENT_START, entries); } /** @@ -146,7 +114,7 @@ export class DocumentLoad extends BasePlugin { ) { // span can be undefined when entries are missing the certain performance - the span will not be created if (typeof span !== 'undefined' && hasKey(entries, performanceName)) { - span.addEvent(performanceName); + this._addSpanEvent(span, performanceName, entries); span.end(entries[performanceName]); } } @@ -161,7 +129,7 @@ export class DocumentLoad extends BasePlugin { )[0] as unknown) as PerformanceEntries; if (performanceNavigationTiming) { - const keys = Object.values(PerformanceTimingNames); + const keys = Object.values(PTN); const startTime = otperformance.timeOrigin; keys.forEach((key: string) => { if (hasKey(performanceNavigationTiming, key)) { @@ -176,7 +144,7 @@ export class DocumentLoad extends BasePlugin { const perf: (typeof otperformance) & PerformanceLegacy = otperformance; const performanceTiming = perf.timing; if (performanceTiming) { - const keys = Object.values(PerformanceTimingNames); + const keys = Object.values(PTN); keys.forEach((key: string) => { if (hasKey(performanceTiming, key)) { const value = performanceTiming[key]; @@ -190,32 +158,6 @@ export class DocumentLoad extends BasePlugin { return entries; } - /** - * Helper function for starting and finishing a span - * @param spanName name of span - * @param performanceNameStart name of performance entry for time start - * @param performanceNameEnd name of performance entry for time end - * @param entries - * @param spanOptions - */ - private _startAndFinishSpan( - spanName: string, - performanceNameStart: string, - performanceNameEnd: string, - entries: PerformanceEntries, - spanOptions: SpanOptions = {} - ): Span | undefined { - // span can be undefined when entries are missing the certain performance - the span will not be created - const span = this._startSpan( - spanName, - performanceNameStart, - entries, - spanOptions - ); - this._endSpan(span, performanceNameEnd, entries); - return span; - } - /** * Helper function for starting a span * @param spanName name of span @@ -243,7 +185,7 @@ export class DocumentLoad extends BasePlugin { spanOptions ) ); - span.addEvent(performanceName); + this._addSpanEvent(span, performanceName, entries); return span; } return undefined; diff --git a/packages/opentelemetry-plugin-document-load/src/enums/AttributeNames.ts b/packages/opentelemetry-plugin-document-load/src/enums/AttributeNames.ts index 625aad4220..6a18a6c0cd 100644 --- a/packages/opentelemetry-plugin-document-load/src/enums/AttributeNames.ts +++ b/packages/opentelemetry-plugin-document-load/src/enums/AttributeNames.ts @@ -15,11 +15,5 @@ */ export enum AttributeNames { - CACHE_SEEK = 'cacheSeek', - CONNECT = 'connect', - CONNECT_SECURE = 'connectSecure', - DOMAIN_LOOKUP = 'domainLookup', - RESPONSE_TIME = 'responseTime', DOCUMENT_LOAD = 'documentLoad', - TTFB = 'ttfb', } diff --git a/packages/opentelemetry-plugin-document-load/test/documentLoad.test.ts b/packages/opentelemetry-plugin-document-load/test/documentLoad.test.ts index 4b931de7b1..9d3a435465 100644 --- a/packages/opentelemetry-plugin-document-load/test/documentLoad.test.ts +++ b/packages/opentelemetry-plugin-document-load/test/documentLoad.test.ts @@ -28,6 +28,7 @@ import { Logger, PluginConfig } from '@opentelemetry/types'; import { ExportResult } from '../../opentelemetry-base/build/src'; import { DocumentLoad } from '../src'; +import { PerformanceTimingNames as PTN } from '../src/enums/PerformanceTimingNames'; export class DummyExporter implements SpanExporter { export( @@ -81,7 +82,7 @@ describe('DocumentLoad Plugin', () => { const spyOnEnd = sinon.spy(dummyExporter, 'export'); plugin.enable(moduleExports, tracer, logger, config); assert.strictEqual(window.document.readyState, 'complete'); - assert.ok(spyOnEnd.callCount === 6); + assert.ok(spyOnEnd.callCount === 1); }); }); @@ -112,7 +113,7 @@ describe('DocumentLoad Plugin', () => { detail: {}, }) ); - assert.ok(spyOnEnd.callCount === 6); + assert.ok(spyOnEnd.callCount === 1); }); }); @@ -159,26 +160,34 @@ describe('DocumentLoad Plugin', () => { .returns([entries]); }); - it('should export correct spans', () => { + it('should export correct span with events', () => { const spyOnEnd = sinon.spy(dummyExporter, 'export'); plugin.enable(moduleExports, tracer, logger, config); const span1 = spyOnEnd.args[0][0][0] as ReadableSpan; - const span2 = spyOnEnd.args[1][0][0] as ReadableSpan; - const span3 = spyOnEnd.args[2][0][0] as ReadableSpan; - const span4 = spyOnEnd.args[3][0][0] as ReadableSpan; - const span5 = spyOnEnd.args[4][0][0] as ReadableSpan; - const span6 = spyOnEnd.args[5][0][0] as ReadableSpan; - const span7 = spyOnEnd.args[6][0][0] as ReadableSpan; - - assert.strictEqual(span1.name, 'domainLookup'); - assert.strictEqual(span2.name, 'connectSecure'); - assert.strictEqual(span3.name, 'connect'); - assert.strictEqual(span4.name, 'cacheSeek'); - assert.strictEqual(span5.name, 'ttfb'); - assert.strictEqual(span6.name, 'responseTime'); - assert.strictEqual(span7.name, 'documentLoad'); - assert.ok(spyOnEnd.callCount === 7); + const events = span1.events; + + assert.strictEqual(span1.name, 'documentLoad'); + + assert.strictEqual(events[0].name, PTN.FETCH_START); + assert.strictEqual(events[1].name, PTN.DOMAIN_LOOKUP_START); + assert.strictEqual(events[2].name, PTN.DOMAIN_LOOKUP_END); + assert.strictEqual(events[3].name, PTN.CONNECT_START); + assert.strictEqual(events[4].name, PTN.SECURE_CONNECTION_START); + assert.strictEqual(events[5].name, PTN.CONNECT_END); + assert.strictEqual(events[6].name, PTN.REQUEST_START); + assert.strictEqual(events[7].name, PTN.RESPONSE_START); + assert.strictEqual(events[8].name, PTN.RESPONSE_END); + assert.strictEqual(events[9].name, PTN.UNLOAD_EVENT_START); + assert.strictEqual(events[10].name, PTN.UNLOAD_EVENT_END); + assert.strictEqual(events[11].name, PTN.DOM_INTERACTIVE); + assert.strictEqual(events[12].name, PTN.DOM_CONTENT_LOADED_EVENT_START); + assert.strictEqual(events[13].name, PTN.DOM_CONTENT_LOADED_EVENT_END); + assert.strictEqual(events[14].name, PTN.DOM_COMPLETE); + assert.strictEqual(events[15].name, PTN.LOAD_EVENT_START); + + assert.strictEqual(events.length, 16); + assert.ok(spyOnEnd.callCount === 1); }); afterEach(() => { spyExport.restore(); @@ -222,26 +231,32 @@ describe('DocumentLoad Plugin', () => { }); }); - it('should export correct spans', () => { + it('should export correct span with events', () => { const spyOnEnd = sinon.spy(dummyExporter, 'export'); plugin.enable(moduleExports, tracer, logger, config); const span1 = spyOnEnd.args[0][0][0] as ReadableSpan; - const span2 = spyOnEnd.args[1][0][0] as ReadableSpan; - const span3 = spyOnEnd.args[2][0][0] as ReadableSpan; - const span4 = spyOnEnd.args[3][0][0] as ReadableSpan; - const span5 = spyOnEnd.args[4][0][0] as ReadableSpan; - const span6 = spyOnEnd.args[5][0][0] as ReadableSpan; - const span7 = spyOnEnd.args[6][0][0] as ReadableSpan; - - assert.strictEqual(span1.name, 'domainLookup'); - assert.strictEqual(span2.name, 'connectSecure'); - assert.strictEqual(span3.name, 'connect'); - assert.strictEqual(span4.name, 'cacheSeek'); - assert.strictEqual(span5.name, 'ttfb'); - assert.strictEqual(span6.name, 'responseTime'); - assert.strictEqual(span7.name, 'documentLoad'); - assert.ok(spyOnEnd.callCount === 7); + const events = span1.events; + + assert.strictEqual(span1.name, 'documentLoad'); + + assert.strictEqual(events[0].name, PTN.FETCH_START); + assert.strictEqual(events[1].name, PTN.DOMAIN_LOOKUP_START); + assert.strictEqual(events[2].name, PTN.DOMAIN_LOOKUP_END); + assert.strictEqual(events[3].name, PTN.CONNECT_START); + assert.strictEqual(events[4].name, PTN.SECURE_CONNECTION_START); + assert.strictEqual(events[5].name, PTN.CONNECT_END); + assert.strictEqual(events[6].name, PTN.REQUEST_START); + assert.strictEqual(events[7].name, PTN.RESPONSE_START); + assert.strictEqual(events[8].name, PTN.RESPONSE_END); + assert.strictEqual(events[9].name, PTN.DOM_INTERACTIVE); + assert.strictEqual(events[10].name, PTN.DOM_CONTENT_LOADED_EVENT_START); + assert.strictEqual(events[11].name, PTN.DOM_CONTENT_LOADED_EVENT_END); + assert.strictEqual(events[12].name, PTN.DOM_COMPLETE); + assert.strictEqual(events[13].name, PTN.LOAD_EVENT_START); + + assert.strictEqual(events.length, 14); + assert.ok(spyOnEnd.callCount === 1); }); afterEach(() => { @@ -262,7 +277,7 @@ describe('DocumentLoad Plugin', () => { }); }); - it('should not create any spans', () => { + it('should not create any span', () => { const spyOnEnd = sinon.spy(dummyExporter, 'export'); plugin.enable(moduleExports, tracer, logger, config); From ec5cb9d741f7c15ac984b06bb09c95fb4fd3c079 Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Mon, 21 Oct 2019 17:26:31 +0200 Subject: [PATCH 20/33] chore: reformatting --- packages/opentelemetry-core/src/common/time.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/packages/opentelemetry-core/src/common/time.ts b/packages/opentelemetry-core/src/common/time.ts index 0918acb6b3..6f4f5bcee1 100644 --- a/packages/opentelemetry-core/src/common/time.ts +++ b/packages/opentelemetry-core/src/common/time.ts @@ -69,9 +69,8 @@ export function timeInputToHrTime(time: types.TimeInput): types.HrTime { // Must be a performance.now() if it's smaller than process start time. if (time < getTimeOrigin()) { return hrTime(time); - } - // epoch milliseconds or performance.timeOrigin - else { + } else { + // epoch milliseconds or performance.timeOrigin return numberToHrtime(time); } } else if (time instanceof Date) { From a67db8510ec68c45eb6b9d1655f01bd4ec8e6ff7 Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Mon, 21 Oct 2019 21:30:18 +0200 Subject: [PATCH 21/33] chore: updating loop --- .../opentelemetry-tracing/src/export/ConsoleSpanExporter.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/opentelemetry-tracing/src/export/ConsoleSpanExporter.ts b/packages/opentelemetry-tracing/src/export/ConsoleSpanExporter.ts index abc0459f47..7f5fc96804 100644 --- a/packages/opentelemetry-tracing/src/export/ConsoleSpanExporter.ts +++ b/packages/opentelemetry-tracing/src/export/ConsoleSpanExporter.ts @@ -71,8 +71,8 @@ export class ConsoleSpanExporter implements SpanExporter { spans: ReadableSpan[], done?: (result: ExportResult) => void ): void { - for (let i = 0, j = spans.length; i < j; i++) { - console.log(this._exportInfo(spans[i])); + for (const span of spans) { + console.log(this._exportInfo(span)); } if (done) { return done(ExportResult.SUCCESS); From ed4a0b529f4faab83bb2f23595d04ea90826f23f Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Mon, 21 Oct 2019 21:31:45 +0200 Subject: [PATCH 22/33] chore: changing type for time --- packages/opentelemetry-tracing/src/Span.ts | 6 ++---- packages/opentelemetry-types/src/trace/span.ts | 2 +- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/packages/opentelemetry-tracing/src/Span.ts b/packages/opentelemetry-tracing/src/Span.ts index 49c4765f51..30e5b3c159 100644 --- a/packages/opentelemetry-tracing/src/Span.ts +++ b/packages/opentelemetry-tracing/src/Span.ts @@ -104,16 +104,14 @@ export class Span implements types.Span, ReadableSpan { addEvent( name: string, attributes?: types.Attributes, - startTime?: number + startTime: types.TimeInput = hrTime() ): this { if (this._isSpanEnded()) return this; if (this.events.length >= this._traceParams.numberOfEventsPerSpan!) { this._logger.warn('Dropping extra events.'); this.events.shift(); } - const time = - typeof startTime === 'number' ? timeInputToHrTime(startTime) : hrTime(); - this.events.push({ name, attributes, time }); + this.events.push({ name, attributes, time: timeInputToHrTime(startTime) }); return this; } diff --git a/packages/opentelemetry-types/src/trace/span.ts b/packages/opentelemetry-types/src/trace/span.ts index 7659439d5d..9a1ae6fd22 100644 --- a/packages/opentelemetry-types/src/trace/span.ts +++ b/packages/opentelemetry-types/src/trace/span.ts @@ -57,7 +57,7 @@ export interface Span { * associated with this event. * @param [startTime] start time of the event. */ - addEvent(name: string, attributes?: Attributes, startTime?: number): this; + addEvent(name: string, attributes?: Attributes, startTime?: TimeInput): this; /** * Adds a link to the Span. From 5090b5475d494e79cf7b329bec2cef8a3346c97e Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Mon, 21 Oct 2019 21:46:31 +0200 Subject: [PATCH 23/33] chore: refactoring loop, updating jsdoc --- packages/opentelemetry-web/src/WebTracer.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/opentelemetry-web/src/WebTracer.ts b/packages/opentelemetry-web/src/WebTracer.ts index b64f8c0a65..a6e1911381 100644 --- a/packages/opentelemetry-web/src/WebTracer.ts +++ b/packages/opentelemetry-web/src/WebTracer.ts @@ -34,7 +34,7 @@ export interface WebTracerConfig extends BasicTracerConfig { export class WebTracer extends BasicTracer { /** * Constructs a new Tracer instance. - * @param {WebTracerConfig} config Web Tracer config + * @param config Web Tracer config */ constructor(config: WebTracerConfig = {}) { if (typeof config.scopeManager === 'undefined') { @@ -49,8 +49,8 @@ export class WebTracer extends BasicTracer { config.scopeManager.enable(); // enable all plugins - for (let i = 0, j = config.plugins.length; i < j; i++) { - config.plugins[i].enable([], this, this.logger, {}); + for (const plugin of config.plugins) { + plugin.enable([], this, this.logger, {}); } } } From 8a38ca33c2dbcf8b007cc44768da25b5ae3afeed Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Mon, 21 Oct 2019 22:47:02 +0200 Subject: [PATCH 24/33] chore: splitting events into 2 spans --- .../src/documentLoad.ts | 30 +++-- .../src/enums/AttributeNames.ts | 1 + .../test/documentLoad.test.ts | 104 ++++++++++-------- 3 files changed, 79 insertions(+), 56 deletions(-) diff --git a/packages/opentelemetry-plugin-document-load/src/documentLoad.ts b/packages/opentelemetry-plugin-document-load/src/documentLoad.ts index 623758c1b3..135a6c06b4 100644 --- a/packages/opentelemetry-plugin-document-load/src/documentLoad.ts +++ b/packages/opentelemetry-plugin-document-load/src/documentLoad.ts @@ -82,15 +82,26 @@ export class DocumentLoad extends BasePlugin { if (!rootSpan) { return; } + const fetchSpan = this._startSpan( + AttributeNames.DOCUMENT_FETCH, + PTN.FETCH_START, + entries, + { + parent: rootSpan, + } + ); + if (fetchSpan) { + this._addSpanEvent(fetchSpan, PTN.DOMAIN_LOOKUP_START, entries); + this._addSpanEvent(fetchSpan, PTN.DOMAIN_LOOKUP_END, entries); + this._addSpanEvent(fetchSpan, PTN.CONNECT_START, entries); + this._addSpanEvent(fetchSpan, PTN.SECURE_CONNECTION_START, entries); + this._addSpanEvent(fetchSpan, PTN.CONNECT_END, entries); + this._addSpanEvent(fetchSpan, PTN.REQUEST_START, entries); + this._addSpanEvent(fetchSpan, PTN.RESPONSE_START, entries); + + this._endSpan(fetchSpan, PTN.RESPONSE_END, entries); + } - this._addSpanEvent(rootSpan, PTN.DOMAIN_LOOKUP_START, entries); - this._addSpanEvent(rootSpan, PTN.DOMAIN_LOOKUP_END, entries); - this._addSpanEvent(rootSpan, PTN.CONNECT_START, entries); - this._addSpanEvent(rootSpan, PTN.SECURE_CONNECTION_START, entries); - this._addSpanEvent(rootSpan, PTN.CONNECT_END, entries); - this._addSpanEvent(rootSpan, PTN.REQUEST_START, entries); - this._addSpanEvent(rootSpan, PTN.RESPONSE_START, entries); - this._addSpanEvent(rootSpan, PTN.RESPONSE_END, entries); this._addSpanEvent(rootSpan, PTN.UNLOAD_EVENT_START, entries); this._addSpanEvent(rootSpan, PTN.UNLOAD_EVENT_END, entries); this._addSpanEvent(rootSpan, PTN.DOM_INTERACTIVE, entries); @@ -130,12 +141,11 @@ export class DocumentLoad extends BasePlugin { if (performanceNavigationTiming) { const keys = Object.values(PTN); - const startTime = otperformance.timeOrigin; keys.forEach((key: string) => { if (hasKey(performanceNavigationTiming, key)) { const value = performanceNavigationTiming[key]; if (typeof value === 'number' && value > 0) { - entries[key] = value + startTime; + entries[key] = value; } } }); diff --git a/packages/opentelemetry-plugin-document-load/src/enums/AttributeNames.ts b/packages/opentelemetry-plugin-document-load/src/enums/AttributeNames.ts index 6a18a6c0cd..b9985bae59 100644 --- a/packages/opentelemetry-plugin-document-load/src/enums/AttributeNames.ts +++ b/packages/opentelemetry-plugin-document-load/src/enums/AttributeNames.ts @@ -16,4 +16,5 @@ export enum AttributeNames { DOCUMENT_LOAD = 'documentLoad', + DOCUMENT_FETCH = 'documentFetch', } diff --git a/packages/opentelemetry-plugin-document-load/test/documentLoad.test.ts b/packages/opentelemetry-plugin-document-load/test/documentLoad.test.ts index 9d3a435465..ab7b7358fd 100644 --- a/packages/opentelemetry-plugin-document-load/test/documentLoad.test.ts +++ b/packages/opentelemetry-plugin-document-load/test/documentLoad.test.ts @@ -82,7 +82,7 @@ describe('DocumentLoad Plugin', () => { const spyOnEnd = sinon.spy(dummyExporter, 'export'); plugin.enable(moduleExports, tracer, logger, config); assert.strictEqual(window.document.readyState, 'complete'); - assert.ok(spyOnEnd.callCount === 1); + assert.strictEqual(spyOnEnd.callCount, 2); }); }); @@ -113,7 +113,7 @@ describe('DocumentLoad Plugin', () => { detail: {}, }) ); - assert.ok(spyOnEnd.callCount === 1); + assert.strictEqual(spyOnEnd.callCount, 2); }); }); @@ -165,29 +165,35 @@ describe('DocumentLoad Plugin', () => { plugin.enable(moduleExports, tracer, logger, config); const span1 = spyOnEnd.args[0][0][0] as ReadableSpan; - const events = span1.events; - - assert.strictEqual(span1.name, 'documentLoad'); - - assert.strictEqual(events[0].name, PTN.FETCH_START); - assert.strictEqual(events[1].name, PTN.DOMAIN_LOOKUP_START); - assert.strictEqual(events[2].name, PTN.DOMAIN_LOOKUP_END); - assert.strictEqual(events[3].name, PTN.CONNECT_START); - assert.strictEqual(events[4].name, PTN.SECURE_CONNECTION_START); - assert.strictEqual(events[5].name, PTN.CONNECT_END); - assert.strictEqual(events[6].name, PTN.REQUEST_START); - assert.strictEqual(events[7].name, PTN.RESPONSE_START); - assert.strictEqual(events[8].name, PTN.RESPONSE_END); - assert.strictEqual(events[9].name, PTN.UNLOAD_EVENT_START); - assert.strictEqual(events[10].name, PTN.UNLOAD_EVENT_END); - assert.strictEqual(events[11].name, PTN.DOM_INTERACTIVE); - assert.strictEqual(events[12].name, PTN.DOM_CONTENT_LOADED_EVENT_START); - assert.strictEqual(events[13].name, PTN.DOM_CONTENT_LOADED_EVENT_END); - assert.strictEqual(events[14].name, PTN.DOM_COMPLETE); - assert.strictEqual(events[15].name, PTN.LOAD_EVENT_START); - - assert.strictEqual(events.length, 16); - assert.ok(spyOnEnd.callCount === 1); + const span2 = spyOnEnd.args[1][0][0] as ReadableSpan; + const events1 = span1.events; + const events2 = span2.events; + + assert.strictEqual(span1.name, 'documentFetch'); + assert.strictEqual(span2.name, 'documentLoad'); + + assert.strictEqual(events1[0].name, PTN.FETCH_START); + assert.strictEqual(events1[1].name, PTN.DOMAIN_LOOKUP_START); + assert.strictEqual(events1[2].name, PTN.DOMAIN_LOOKUP_END); + assert.strictEqual(events1[3].name, PTN.CONNECT_START); + assert.strictEqual(events1[4].name, PTN.SECURE_CONNECTION_START); + assert.strictEqual(events1[5].name, PTN.CONNECT_END); + assert.strictEqual(events1[6].name, PTN.REQUEST_START); + assert.strictEqual(events1[7].name, PTN.RESPONSE_START); + assert.strictEqual(events1[8].name, PTN.RESPONSE_END); + + assert.strictEqual(events2[0].name, PTN.FETCH_START); + assert.strictEqual(events2[1].name, PTN.UNLOAD_EVENT_START); + assert.strictEqual(events2[2].name, PTN.UNLOAD_EVENT_END); + assert.strictEqual(events2[3].name, PTN.DOM_INTERACTIVE); + assert.strictEqual(events2[4].name, PTN.DOM_CONTENT_LOADED_EVENT_START); + assert.strictEqual(events2[5].name, PTN.DOM_CONTENT_LOADED_EVENT_END); + assert.strictEqual(events2[6].name, PTN.DOM_COMPLETE); + assert.strictEqual(events2[7].name, PTN.LOAD_EVENT_START); + + assert.strictEqual(events1.length, 9); + assert.strictEqual(events2.length, 8); + assert.strictEqual(spyOnEnd.callCount, 2); }); afterEach(() => { spyExport.restore(); @@ -236,27 +242,33 @@ describe('DocumentLoad Plugin', () => { plugin.enable(moduleExports, tracer, logger, config); const span1 = spyOnEnd.args[0][0][0] as ReadableSpan; - const events = span1.events; - - assert.strictEqual(span1.name, 'documentLoad'); - - assert.strictEqual(events[0].name, PTN.FETCH_START); - assert.strictEqual(events[1].name, PTN.DOMAIN_LOOKUP_START); - assert.strictEqual(events[2].name, PTN.DOMAIN_LOOKUP_END); - assert.strictEqual(events[3].name, PTN.CONNECT_START); - assert.strictEqual(events[4].name, PTN.SECURE_CONNECTION_START); - assert.strictEqual(events[5].name, PTN.CONNECT_END); - assert.strictEqual(events[6].name, PTN.REQUEST_START); - assert.strictEqual(events[7].name, PTN.RESPONSE_START); - assert.strictEqual(events[8].name, PTN.RESPONSE_END); - assert.strictEqual(events[9].name, PTN.DOM_INTERACTIVE); - assert.strictEqual(events[10].name, PTN.DOM_CONTENT_LOADED_EVENT_START); - assert.strictEqual(events[11].name, PTN.DOM_CONTENT_LOADED_EVENT_END); - assert.strictEqual(events[12].name, PTN.DOM_COMPLETE); - assert.strictEqual(events[13].name, PTN.LOAD_EVENT_START); - - assert.strictEqual(events.length, 14); - assert.ok(spyOnEnd.callCount === 1); + const span2 = spyOnEnd.args[1][0][0] as ReadableSpan; + const events1 = span1.events; + const events2 = span2.events; + + assert.strictEqual(span1.name, 'documentFetch'); + assert.strictEqual(span2.name, 'documentLoad'); + + assert.strictEqual(events1[0].name, PTN.FETCH_START); + assert.strictEqual(events1[1].name, PTN.DOMAIN_LOOKUP_START); + assert.strictEqual(events1[2].name, PTN.DOMAIN_LOOKUP_END); + assert.strictEqual(events1[3].name, PTN.CONNECT_START); + assert.strictEqual(events1[4].name, PTN.SECURE_CONNECTION_START); + assert.strictEqual(events1[5].name, PTN.CONNECT_END); + assert.strictEqual(events1[6].name, PTN.REQUEST_START); + assert.strictEqual(events1[7].name, PTN.RESPONSE_START); + assert.strictEqual(events1[8].name, PTN.RESPONSE_END); + + assert.strictEqual(events2[0].name, PTN.FETCH_START); + assert.strictEqual(events2[1].name, PTN.DOM_INTERACTIVE); + assert.strictEqual(events2[2].name, PTN.DOM_CONTENT_LOADED_EVENT_START); + assert.strictEqual(events2[3].name, PTN.DOM_CONTENT_LOADED_EVENT_END); + assert.strictEqual(events2[4].name, PTN.DOM_COMPLETE); + assert.strictEqual(events2[5].name, PTN.LOAD_EVENT_START); + + assert.strictEqual(events1.length, 9); + assert.strictEqual(events2.length, 6); + assert.strictEqual(spyOnEnd.callCount, 2); }); afterEach(() => { From cfcee4a2ef70bec24526c8b1c5b0baf451da70be Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Mon, 21 Oct 2019 23:29:42 +0200 Subject: [PATCH 25/33] chore: adding possibility of calling addEvent with 2nd param as time --- packages/opentelemetry-tracing/src/Span.ts | 22 +++++++++++++++---- .../opentelemetry-tracing/test/Span.test.ts | 21 ++++++++++++++++++ .../opentelemetry-types/src/trace/span.ts | 9 ++++++-- 3 files changed, 46 insertions(+), 6 deletions(-) diff --git a/packages/opentelemetry-tracing/src/Span.ts b/packages/opentelemetry-tracing/src/Span.ts index 30e5b3c159..3e5bb9c385 100644 --- a/packages/opentelemetry-tracing/src/Span.ts +++ b/packages/opentelemetry-tracing/src/Span.ts @@ -98,19 +98,33 @@ export class Span implements types.Span, ReadableSpan { /** * * @param name Span Name - * @param attributes Span attributes - * @param startTime Specified start time for the event + * @param [attributes] Span attributes or start time + * if type is {@type TimeInput} and 3rd param is undefined + * @param [startTime] Specified start time for the event */ addEvent( name: string, - attributes?: types.Attributes, - startTime: types.TimeInput = hrTime() + attributes?: types.Attributes | types.TimeInput, + startTime?: types.TimeInput ): this { if (this._isSpanEnded()) return this; if (this.events.length >= this._traceParams.numberOfEventsPerSpan!) { this._logger.warn('Dropping extra events.'); this.events.shift(); } + if ( + Array.isArray(attributes) || + typeof attributes === 'number' || + attributes instanceof Date + ) { + if (typeof startTime === 'undefined') { + startTime = attributes; + } + attributes = undefined; + } + if (typeof startTime === 'undefined') { + startTime = hrTime(); + } this.events.push({ name, attributes, time: timeInputToHrTime(startTime) }); return this; } diff --git a/packages/opentelemetry-tracing/test/Span.test.ts b/packages/opentelemetry-tracing/test/Span.test.ts index 3521c13bc5..0329fd5cfd 100644 --- a/packages/opentelemetry-tracing/test/Span.test.ts +++ b/packages/opentelemetry-tracing/test/Span.test.ts @@ -106,6 +106,27 @@ describe('Span', () => { assert.strictEqual(hrTimeToMilliseconds(diff), 123); }); + describe('when 2nd param is "TimeInput" type', () => { + it('should have an entered time for event - ', () => { + const span = new Span( + tracer, + name, + spanContext, + SpanKind.SERVER, + undefined, + 0 + ); + const timeMS = 123; + const spanStartTime = hrTimeToMilliseconds(span.startTime); + const eventTime = spanStartTime + timeMS; + + span.addEvent('my-event', eventTime); + + const diff = hrTimeDuration(span.startTime, span.events[0].time); + assert.strictEqual(hrTimeToMilliseconds(diff), 123); + }); + }); + it('should get the span context of span', () => { const span = new Span(tracer, name, spanContext, SpanKind.CLIENT); const context = span.context(); diff --git a/packages/opentelemetry-types/src/trace/span.ts b/packages/opentelemetry-types/src/trace/span.ts index 9a1ae6fd22..f243d545c0 100644 --- a/packages/opentelemetry-types/src/trace/span.ts +++ b/packages/opentelemetry-types/src/trace/span.ts @@ -54,10 +54,15 @@ export interface Span { * * @param name the name of the event. * @param [attributes] the attributes that will be added; these are - * associated with this event. + * 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, attributes?: Attributes, startTime?: TimeInput): this; + addEvent( + name: string, + attributes?: Attributes | TimeInput, + startTime?: TimeInput + ): this; /** * Adds a link to the Span. From 9bb6197d29fe91ab0371336c4b06455f94bd3f9d Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Tue, 22 Oct 2019 22:41:51 +0200 Subject: [PATCH 26/33] chore: updating the last event to be "load end" --- .../opentelemetry-plugin-document-load/src/documentLoad.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/opentelemetry-plugin-document-load/src/documentLoad.ts b/packages/opentelemetry-plugin-document-load/src/documentLoad.ts index 135a6c06b4..8bc0c03dde 100644 --- a/packages/opentelemetry-plugin-document-load/src/documentLoad.ts +++ b/packages/opentelemetry-plugin-document-load/src/documentLoad.ts @@ -108,8 +108,9 @@ export class DocumentLoad extends BasePlugin { this._addSpanEvent(rootSpan, PTN.DOM_CONTENT_LOADED_EVENT_START, entries); this._addSpanEvent(rootSpan, PTN.DOM_CONTENT_LOADED_EVENT_END, entries); this._addSpanEvent(rootSpan, PTN.DOM_COMPLETE, entries); + this._addSpanEvent(rootSpan, PTN.LOAD_EVENT_START, entries); - this._endSpan(rootSpan, PTN.LOAD_EVENT_START, entries); + this._endSpan(rootSpan, PTN.LOAD_EVENT_END, entries); } /** From d1502b368e10882bc6f0df9304dde93058392653 Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Tue, 22 Oct 2019 22:42:10 +0200 Subject: [PATCH 27/33] chore: updating the name for attributes --- packages/opentelemetry-tracing/src/Span.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/packages/opentelemetry-tracing/src/Span.ts b/packages/opentelemetry-tracing/src/Span.ts index 3e5bb9c385..c06013ed3d 100644 --- a/packages/opentelemetry-tracing/src/Span.ts +++ b/packages/opentelemetry-tracing/src/Span.ts @@ -98,13 +98,13 @@ export class Span implements types.Span, ReadableSpan { /** * * @param name Span Name - * @param [attributes] Span attributes or start time - * if type is {@type TimeInput} and 3rd param is undefined + * @param [attributesOrStartTime] Span attributes or start time + * if type is {@type TimeInput} and 3rd param is undefined * @param [startTime] Specified start time for the event */ addEvent( name: string, - attributes?: types.Attributes | types.TimeInput, + attributesOrStartTime?: types.Attributes | types.TimeInput, startTime?: types.TimeInput ): this { if (this._isSpanEnded()) return this; @@ -113,19 +113,19 @@ export class Span implements types.Span, ReadableSpan { this.events.shift(); } if ( - Array.isArray(attributes) || - typeof attributes === 'number' || - attributes instanceof Date + Array.isArray(attributesOrStartTime) || + typeof attributesOrStartTime === 'number' || + attributesOrStartTime instanceof Date ) { if (typeof startTime === 'undefined') { - startTime = attributes; + startTime = attributesOrStartTime; } - attributes = undefined; + attributesOrStartTime = undefined; } if (typeof startTime === 'undefined') { startTime = hrTime(); } - this.events.push({ name, attributes, time: timeInputToHrTime(startTime) }); + this.events.push({ name, attributes: attributesOrStartTime, time: timeInputToHrTime(startTime) }); return this; } From 036944ac9f79496db83d9480f402a223e1749714 Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Tue, 22 Oct 2019 23:19:53 +0200 Subject: [PATCH 28/33] chore: fixing test --- .../test/documentLoad.test.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/opentelemetry-plugin-document-load/test/documentLoad.test.ts b/packages/opentelemetry-plugin-document-load/test/documentLoad.test.ts index ab7b7358fd..ecd99ce0c3 100644 --- a/packages/opentelemetry-plugin-document-load/test/documentLoad.test.ts +++ b/packages/opentelemetry-plugin-document-load/test/documentLoad.test.ts @@ -190,9 +190,10 @@ describe('DocumentLoad Plugin', () => { assert.strictEqual(events2[5].name, PTN.DOM_CONTENT_LOADED_EVENT_END); assert.strictEqual(events2[6].name, PTN.DOM_COMPLETE); assert.strictEqual(events2[7].name, PTN.LOAD_EVENT_START); + assert.strictEqual(events2[8].name, PTN.LOAD_EVENT_END); assert.strictEqual(events1.length, 9); - assert.strictEqual(events2.length, 8); + assert.strictEqual(events2.length, 9); assert.strictEqual(spyOnEnd.callCount, 2); }); afterEach(() => { @@ -265,9 +266,10 @@ describe('DocumentLoad Plugin', () => { assert.strictEqual(events2[3].name, PTN.DOM_CONTENT_LOADED_EVENT_END); assert.strictEqual(events2[4].name, PTN.DOM_COMPLETE); assert.strictEqual(events2[5].name, PTN.LOAD_EVENT_START); + assert.strictEqual(events2[6].name, PTN.LOAD_EVENT_END); assert.strictEqual(events1.length, 9); - assert.strictEqual(events2.length, 6); + assert.strictEqual(events2.length, 7); assert.strictEqual(spyOnEnd.callCount, 2); }); From 006a46782e21f154336eae0e3177e6028dd0e30e Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Tue, 22 Oct 2019 23:20:11 +0200 Subject: [PATCH 29/33] chore: cleanups --- packages/opentelemetry-web/src/WebTracer.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/packages/opentelemetry-web/src/WebTracer.ts b/packages/opentelemetry-web/src/WebTracer.ts index a6e1911381..5d3fad465e 100644 --- a/packages/opentelemetry-web/src/WebTracer.ts +++ b/packages/opentelemetry-web/src/WebTracer.ts @@ -45,10 +45,8 @@ export class WebTracer extends BasicTracer { } super(Object.assign({}, { scopeManager: config.scopeManager }, config)); - // enable scope manager config.scopeManager.enable(); - // enable all plugins for (const plugin of config.plugins) { plugin.enable([], this, this.logger, {}); } From 077eec2a5522ed504b734f1f2880204d1a29d1bd Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Tue, 22 Oct 2019 23:21:16 +0200 Subject: [PATCH 30/33] chore: adding isTimeInput function with unit tests --- .../opentelemetry-core/src/common/time.ts | 23 +++++++++++++-- .../test/common/time.test.ts | 29 +++++++++++++++++++ packages/opentelemetry-tracing/src/Span.ts | 21 +++++++++----- .../opentelemetry-types/src/trace/span.ts | 4 +-- 4 files changed, 65 insertions(+), 12 deletions(-) diff --git a/packages/opentelemetry-core/src/common/time.ts b/packages/opentelemetry-core/src/common/time.ts index 6f4f5bcee1..fcc564692e 100644 --- a/packages/opentelemetry-core/src/common/time.ts +++ b/packages/opentelemetry-core/src/common/time.ts @@ -41,6 +41,7 @@ function getTimeOrigin(): number { } return timeOrigin; } + // Returns an hrtime calculated via performance component. export function hrTime(performanceNow?: number): types.HrTime { const timeOrigin = numberToHrtime(getTimeOrigin()); @@ -63,8 +64,8 @@ export function hrTime(performanceNow?: number): types.HrTime { // Converts a TimeInput to an HrTime, defaults to _hrtime(). export function timeInputToHrTime(time: types.TimeInput): types.HrTime { // process.hrtime - if (Array.isArray(time)) { - return time; + if (isTimeInputHrTime(time)) { + return time as types.HrTime; } else if (typeof time === 'number') { // Must be a performance.now() if it's smaller than process start time. if (time < getTimeOrigin()) { @@ -112,3 +113,21 @@ export function hrTimeToMilliseconds(hrTime: types.HrTime): number { export function hrTimeToMicroseconds(hrTime: types.HrTime): number { return Math.round(hrTime[0] * 1e6 + hrTime[1] / 1e3); } + +export function isTimeInputHrTime(value: unknown) { + return ( + Array.isArray(value) && + value.length === 2 && + typeof value[0] === 'number' && + typeof value[1] === 'number' + ); +} + +// check if input value is a correct types.TimeInput +export function isTimeInput(value: unknown) { + return ( + isTimeInputHrTime(value) || + typeof value === 'number' || + value instanceof Date + ); +} diff --git a/packages/opentelemetry-core/test/common/time.test.ts b/packages/opentelemetry-core/test/common/time.test.ts index b7ac8a5f32..4eb82a9b78 100644 --- a/packages/opentelemetry-core/test/common/time.test.ts +++ b/packages/opentelemetry-core/test/common/time.test.ts @@ -25,6 +25,7 @@ import { hrTimeToNanoseconds, hrTimeToMilliseconds, hrTimeToMicroseconds, + isTimeInput, } from '../../src/common/time'; describe('time', () => { @@ -175,4 +176,32 @@ describe('time', () => { assert.deepStrictEqual(output, 1200000); }); }); + describe('#isTimeInput', () => { + it('should return true for a number', () => { + assert.strictEqual(isTimeInput(12), true); + }); + it('should return true for a date', () => { + assert.strictEqual(isTimeInput(new Date()), true); + }); + it('should return true for an array with 2 elements type number', () => { + assert.strictEqual(isTimeInput([1, 1]), true); + }); + it('should return FALSE for different cases for an array ', () => { + assert.strictEqual(isTimeInput([1, 1, 1]), false); + assert.strictEqual(isTimeInput([1]), false); + assert.strictEqual(isTimeInput([1, 'a']), false); + }); + it('should return FALSE for a string', () => { + assert.strictEqual(isTimeInput('a'), false); + }); + it('should return FALSE for an object', () => { + assert.strictEqual(isTimeInput({}), false); + }); + it('should return FALSE for a null', () => { + assert.strictEqual(isTimeInput(null), false); + }); + it('should return FALSE for undefined', () => { + assert.strictEqual(isTimeInput(undefined), false); + }); + }); }); diff --git a/packages/opentelemetry-tracing/src/Span.ts b/packages/opentelemetry-tracing/src/Span.ts index c06013ed3d..0a5c7b09fd 100644 --- a/packages/opentelemetry-tracing/src/Span.ts +++ b/packages/opentelemetry-tracing/src/Span.ts @@ -15,7 +15,12 @@ */ import * as types from '@opentelemetry/types'; -import { hrTime, hrTimeDuration, timeInputToHrTime } from '@opentelemetry/core'; +import { + hrTime, + hrTimeDuration, + isTimeInput, + timeInputToHrTime, +} from '@opentelemetry/core'; import { ReadableSpan } from './export/ReadableSpan'; import { BasicTracer } from './BasicTracer'; import { SpanProcessor } from './SpanProcessor'; @@ -112,20 +117,20 @@ export class Span implements types.Span, ReadableSpan { this._logger.warn('Dropping extra events.'); this.events.shift(); } - if ( - Array.isArray(attributesOrStartTime) || - typeof attributesOrStartTime === 'number' || - attributesOrStartTime instanceof Date - ) { + if (isTimeInput(attributesOrStartTime)) { if (typeof startTime === 'undefined') { - startTime = attributesOrStartTime; + startTime = attributesOrStartTime as types.TimeInput; } attributesOrStartTime = undefined; } if (typeof startTime === 'undefined') { startTime = hrTime(); } - this.events.push({ name, attributes: attributesOrStartTime, time: timeInputToHrTime(startTime) }); + this.events.push({ + name, + attributes: attributesOrStartTime as types.Attributes, + time: timeInputToHrTime(startTime), + }); return this; } diff --git a/packages/opentelemetry-types/src/trace/span.ts b/packages/opentelemetry-types/src/trace/span.ts index f243d545c0..ae54ed0571 100644 --- a/packages/opentelemetry-types/src/trace/span.ts +++ b/packages/opentelemetry-types/src/trace/span.ts @@ -53,14 +53,14 @@ export interface Span { * Adds an event to the Span. * * @param name the name of the event. - * @param [attributes] the attributes that will be added; these are + * @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, - attributes?: Attributes | TimeInput, + attributesOrStartTime?: Attributes | TimeInput, startTime?: TimeInput ): this; From 734ffea9020323822a9ee4aa23cfab0e9d08476b Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Wed, 23 Oct 2019 14:47:38 +0200 Subject: [PATCH 31/33] chore: adding component name --- packages/opentelemetry-plugin-document-load/src/documentLoad.ts | 1 + .../src/enums/AttributeNames.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/packages/opentelemetry-plugin-document-load/src/documentLoad.ts b/packages/opentelemetry-plugin-document-load/src/documentLoad.ts index 8bc0c03dde..6b8255cc88 100644 --- a/packages/opentelemetry-plugin-document-load/src/documentLoad.ts +++ b/packages/opentelemetry-plugin-document-load/src/documentLoad.ts @@ -196,6 +196,7 @@ export class DocumentLoad extends BasePlugin { spanOptions ) ); + span.setAttribute(AttributeNames.COMPONENT, this.component); this._addSpanEvent(span, performanceName, entries); return span; } diff --git a/packages/opentelemetry-plugin-document-load/src/enums/AttributeNames.ts b/packages/opentelemetry-plugin-document-load/src/enums/AttributeNames.ts index b9985bae59..2e4a7d9ddf 100644 --- a/packages/opentelemetry-plugin-document-load/src/enums/AttributeNames.ts +++ b/packages/opentelemetry-plugin-document-load/src/enums/AttributeNames.ts @@ -15,6 +15,7 @@ */ export enum AttributeNames { + COMPONENT = 'component', DOCUMENT_LOAD = 'documentLoad', DOCUMENT_FETCH = 'documentFetch', } From 7e4aab1c3d87822c6906ede8213bab6b718f3503 Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Wed, 23 Oct 2019 16:42:32 +0200 Subject: [PATCH 32/33] chore: adding license and readme --- .../LICENSE | 201 ++++++++++++++++++ .../README.md | 50 +++++ 2 files changed, 251 insertions(+) create mode 100644 packages/opentelemetry-plugin-document-load/LICENSE create mode 100644 packages/opentelemetry-plugin-document-load/README.md diff --git a/packages/opentelemetry-plugin-document-load/LICENSE b/packages/opentelemetry-plugin-document-load/LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/packages/opentelemetry-plugin-document-load/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/opentelemetry-plugin-document-load/README.md b/packages/opentelemetry-plugin-document-load/README.md new file mode 100644 index 0000000000..cfc8346618 --- /dev/null +++ b/packages/opentelemetry-plugin-document-load/README.md @@ -0,0 +1,50 @@ +# OpenTelemetry Plugin Document Load +[![Gitter chat][gitter-image]][gitter-url] +[![NPM Published Version][npm-img]][npm-url] +[![dependencies][dependencies-image]][dependencies-url] +[![devDependencies][devDependencies-image]][devDependencies-url] +[![Apache License][license-image]][license-image] + +This module provides *automated instrumentation for document load* for Web applications. + +## Installation + +```bash +npm install --save @opentelemetry/plugin-document-load +``` + +## Usage + +```js +import { ConsoleSpanExporter, SimpleSpanProcessor } from '@opentelemetry/tracing'; +import { WebTracer } from '@opentelemetry/web'; +import { DocumentLoad } from '@opentelemetry/plugin-document-load'; + +const webTracer = new WebTracer({ + plugins: [ + new DocumentLoad() + ] +}); + +webTracer.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter())); +``` + +## Useful links +- For more information on OpenTelemetry, visit: +- For more about OpenTelemetry JavaScript: +- For help or feedback on this project, join us on [gitter][gitter-url] + +## License + +Apache 2.0 - See [LICENSE][license-url] for more information. + +[gitter-image]: https://badges.gitter.im/open-telemetry/opentelemetry-js.svg +[gitter-url]: https://gitter.im/open-telemetry/opentelemetry-node?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge +[license-url]: https://github.com/open-telemetry/opentelemetry-js/blob/master/LICENSE +[license-image]: https://img.shields.io/badge/license-Apache_2.0-green.svg?style=flat +[dependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js/status.svg?path=packages/opentelemetry-plugin-document-load +[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-plugin-document-load +[devDependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js/dev-status.svg?path=packages/opentelemetry-plugin-document-load +[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-plugin-document-load&type=dev +[npm-url]: https://www.npmjs.com/package/@opentelemetry/plugin-document-load +[npm-img]: https://badge.fury.io/js/%40opentelemetry%2Fplugin-document-load.svg From abf408bdf3b6defea18c6b6d9173d24d3dbf23d6 Mon Sep 17 00:00:00 2001 From: Bartlomiej Obecny Date: Wed, 23 Oct 2019 17:43:00 +0200 Subject: [PATCH 33/33] chore: updating lint and docs jobs to use node12 image in circleci --- .circleci/config.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 208c5f711d..8138c5e300 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -48,7 +48,7 @@ browsers_unit_tests: &browsers_unit_tests jobs: lint: docker: - - image: node + - image: node:12 steps: - checkout - run: @@ -59,7 +59,7 @@ jobs: command: yarn run check docs: docker: - - image: node + - image: node:12 steps: - checkout - run: