Tracer web (#334)

* feat(tracer-web): adding tracer web

* feat(basic-tracer): adding karma tests

* feat(tracer-web): adding some example for easier debugging in browser - for development purposes

* fix: lint

* fix: creating base for karma

* fix: fixing problem with target for browser, cleanup tests

* refactor: moving polyfills for node karma tests to one file

* fix: adding missing package

* refactor: removing unneeded file

* refactor: prefixing privates, cleanup

* fix: duplicate package

* refactor: aligning tslint with other tslint packages

* refactor: cleanups, adding comments for class

* fix: linting

* fix: type

* refactor: generation of id for scope

* refactor: removed previous uid for scope as originally it was meant to be used with async which is not the case anymore

* chore: adding test for restoring scope

* fix: lint

* refactor: simplifying the stack scope manager

* chore: updating readme with basic example

* chore: fixes after merge

* fix: updating test to accept greater or equal - fails on browser

* refactor: moving example for web tracer

* refactor: removing WebTracerConfig to use BasicTracerConfig which changed recently

* chore: updating types

* chore: spacing

* chore: removing mocha tests for tracer-web

* chore: updating types and linting

* chore: updating packages after merge

* chore: adding nyc report for karma tests for browser

* chore: updating lerna script to run coverage for browsers

* feat(tracer-web): bump version to 0.1.0
This commit is contained in:
Bartlomiej Obecny 2019-10-07 20:08:55 +02:00 committed by Mayur Kale
parent 00cd2ec37f
commit 82b5fad03f
31 changed files with 1205 additions and 85 deletions

View File

@ -41,6 +41,9 @@ browsers_unit_tests: &browsers_unit_tests
- run:
name: Unit tests
command: yarn test:browser
- run:
name: report coverage
command: yarn codecov:browser
jobs:
lint:

View File

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JS Example</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
Testing, debugging in development
<script type="text/javascript" src="/bundle.js"></script>
</body>
</html>

View File

@ -0,0 +1,38 @@
import { WebTracer } from '@opentelemetry/tracer-web';
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);
});
tester.add('foo');
console.log(span);

View File

@ -0,0 +1,41 @@
{
"name": "web-tracer-example",
"private": true,
"version": "0.1.0",
"description": "Example of using @opentelemetry/tracer-web in browser",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server -d --progress --colors --port 8090 --config webpack.config.js --hot --inline --host 0.0.0.0"
},
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/open-telemetry/opentelemetry-js.git"
},
"keywords": [
"opentelemetry",
"tracing",
"web"
],
"engines": {
"node": ">=8"
},
"author": "OpenTelemetry Authors",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/open-telemetry/opentelemetry-js/issues"
},
"devDependencies": {
"@babel/core": "^7.6.0",
"@types/shimmer": "^1.0.1",
"babel-loader": "^8.0.6",
"shimmer": "^1.2.0",
"webpack": "^4.35.2",
"webpack-cli": "^3.3.9",
"webpack-dev-server": "^3.8.1",
"webpack-merge": "^4.2.2"
},
"dependencies": {
"@opentelemetry/tracer-web": "^0.1.0"
},
"homepage": "https://github.com/open-telemetry/opentelemetry-js#readme"
}

View File

@ -0,0 +1,63 @@
const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const path = require('path');
const mainPath = path.resolve('');
const directory = path.resolve(__dirname);
const common = {
mode: 'development',
entry: 'index.js',
target: 'web',
module: {
rules: [
{
test: /\.js[x]?$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader'
}
},
{
test: /\.ts$/,
exclude: /(node_modules)/,
use: {
loader: 'ts-loader'
}
}
]
},
plugins: [
new webpack.ProvidePlugin({
jQuery: 'jquery',
$: 'jquery',
jquery: 'jquery',
'window.jQuery': 'jquery'
})
],
resolve: {
modules: [
path.resolve(mainPath, 'src'),
path.resolve(directory),
'node_modules'
],
extensions: ['.ts', '.js', '.jsx', '.json']
}
};
module.exports = webpackMerge(common, {
devtool: 'eval-source-map',
output: {
filename: 'bundle.js',
sourceMapFilename: '[file].map'
},
devServer: {
contentBase: path.resolve(__dirname),
// contentBase: path.resolve('.'),
// historyApiFallback: true
},
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development')
})
]
});

26
karma.base.js Normal file
View File

@ -0,0 +1,26 @@
/*!
* 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.
*/
module.exports = {
listenAddress: 'localhost',
hostname: 'localhost',
browsers: ['ChromeHeadless'],
frameworks: ['mocha'],
reporters: ['spec'],
files: ['test/index-webpack.ts'],
preprocessors: { 'test/index-webpack.ts': ['webpack'] },
webpackMiddleware: { noInfo: true }
};

View File

@ -5,6 +5,7 @@
"main": "build/src/index.js",
"types": "build/src/index.d.ts",
"scripts": {
"clean": "lerna run clean",
"fix": "lerna run fix",
"postinstall": "yarn run bootstrap",
"compile": "lerna run compile",
@ -13,6 +14,7 @@
"bootstrap": "lerna bootstrap",
"bump": "lerna publish",
"codecov": "lerna run codecov",
"codecov:browser": "lerna run codecov:browser",
"check": "lerna run check",
"predocs-test": "yarn docs",
"docs-test": "lerna run docs-test",

View File

@ -15,17 +15,10 @@
*/
const webpackConfig = require('./webpack/test.config.js');
const karmaBaseConfig = require('../../karma.base');
module.exports = (config) => {
config.set({
listenAddress: 'localhost',
hostname: 'localhost',
browsers: ['ChromeHeadless'],
frameworks: ['mocha'],
reporters: ['spec'],
files: ['test/index-webpack.ts'],
preprocessors: {'test/index-webpack.ts': ['webpack']},
webpack: webpackConfig,
webpackMiddleware: {noInfo: true},
});
config.set(Object.assign({}, karmaBaseConfig, {
webpack: webpackConfig
}))
};

View File

@ -4,7 +4,8 @@
"description": "OpenTelemetry Core",
"main": "build/src/index.js",
"browser": {
"./src/platform/index.ts": "./src/platform/browser/index.ts"
"./src/platform/index.ts": "./src/platform/browser/index.ts",
"./build/src/platform/index.js": "./build/src/platform/browser/index.js"
},
"types": "build/src/index.d.ts",
"repository": "open-telemetry/opentelemetry-js",

View File

@ -14,73 +14,21 @@
* limitations under the License.
*/
// This is the webpack configuration for browesr Karma tests.
const webpackNodePolyfills = require('../../../webpack.node-polyfills.js');
// This is the webpack configuration for browser Karma tests.
module.exports = {
mode: 'development',
output: {filename: 'bundle.js'},
resolve: {extensions: ['.ts', '.js']},
target: 'web',
output: { filename: 'bundle.js' },
resolve: { extensions: ['.ts', '.js'] },
devtool: 'inline-source-map',
module: {
rules: [
{test: /\.ts$/, use: 'ts-loader'},
{
parser: {
// This setting configures Node polyfills for the browser that will be
// added to the webpack bundle for Karma tests.
node: {
// Enable the assert library polyfill because that is used in tests
assert: true,
// The assert polyfill from github.com/browserify/commonjs-assert
// also requires the `global` polyfill.
global: true,
// Turn off all other Node.js API polyfills for the browser tests to
// make sure that we are not attempting to use Node-specific APIs in
// the browser code. Instead, we will write browser specific
// implementations of platform functionality we need under the
// `./src/platform/browser` folder. This allows for writing browser
// optimized implementations of the specific needed functionality
// rather than bringing in (sometimes large) polyfills for the
// corresponding Node APIs.
Buffer: false,
__dirname: false,
__filename: false,
buffer: false,
child_process: false,
cluster: false,
console: false,
constants: false,
crypto: false,
dgram: false,
dns: false,
domain: false,
events: false,
fs: false,
http: false,
https: false,
module: false,
net: false,
os: false,
path: false,
process: false,
punycode: false,
querystring: false,
readline: false,
repl: false,
setImmediate: false,
stream: false,
string_decoder: false,
sys: false,
timers: false,
tls: false,
tty: false,
url: false,
util: false,
vm: false,
zlib: false,
},
},
},
],
},
{ 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 } }
]
}
};

View File

@ -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
}))
};

View File

@ -3,10 +3,15 @@
"version": "0.1.0",
"description": "OpenTelemetry Basic Tracer",
"main": "build/src/index.js",
"browser": {
"./src/platform/index.ts": "./src/platform/browser/index.ts",
"./build/src/platform/index.js": "./build/src/platform/browser/index.js"
},
"types": "build/src/index.d.ts",
"repository": "open-telemetry/opentelemetry-js",
"scripts": {
"test": "nyc ts-mocha -p tsconfig.json test/**/**/*.ts",
"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/*",
@ -40,16 +45,24 @@
"devDependencies": {
"@types/mocha": "^5.2.5",
"@types/node": "^12.6.8",
"@types/webpack-env": "1.13.9",
"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",
"tslint-microsoft-contrib": "^6.2.0",
"tslint-consistent-codestyle": "^1.15.1",
"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"
"typescript": "^3.6.3",
"webpack": "^4.35.2"
},
"dependencies": {
"@opentelemetry/core": "^0.1.0",

View File

@ -15,7 +15,6 @@
*/
import * as assert from 'assert';
import { performance } from 'perf_hooks';
import {
SpanKind,
CanonicalCode,
@ -24,11 +23,14 @@ import {
} from '@opentelemetry/types';
import { BasicTracer, Span } from '../src';
import {
hrTime,
hrTimeToNanoseconds,
hrTimeToMilliseconds,
NoopLogger,
} from '@opentelemetry/core';
const performanceTimeOrigin = hrTime();
describe('Span', () => {
const tracer = new BasicTracer({
logger: new NoopLogger(),
@ -49,19 +51,23 @@ describe('Span', () => {
it('should have valid startTime', () => {
const span = new Span(tracer, name, spanContext, SpanKind.SERVER);
assert.ok(hrTimeToMilliseconds(span.startTime) > performance.timeOrigin);
assert.ok(
hrTimeToMilliseconds(span.startTime) >
hrTimeToMilliseconds(performanceTimeOrigin)
);
});
it('should have valid endTime', () => {
const span = new Span(tracer, name, spanContext, SpanKind.SERVER);
span.end();
assert.ok(
hrTimeToNanoseconds(span.endTime) > hrTimeToNanoseconds(span.startTime),
'end time must be bigger than start time'
hrTimeToNanoseconds(span.endTime) >= hrTimeToNanoseconds(span.startTime),
'end time must be bigger or equal start time'
);
assert.ok(
hrTimeToMilliseconds(span.endTime) > performance.timeOrigin,
hrTimeToMilliseconds(span.endTime) >
hrTimeToMilliseconds(performanceTimeOrigin),
'end time must be bigger than time origin'
);
});
@ -76,7 +82,8 @@ describe('Span', () => {
const span = new Span(tracer, name, spanContext, SpanKind.SERVER);
span.addEvent('my-event');
assert.ok(
hrTimeToMilliseconds(span.events[0].time) > performance.timeOrigin
hrTimeToMilliseconds(span.events[0].time) >
hrTimeToMilliseconds(performanceTimeOrigin)
);
});

View File

@ -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);

View File

@ -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 } }
]
}
};

View File

@ -0,0 +1,4 @@
/bin
/coverage
/doc
/test

View File

@ -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.

View File

@ -0,0 +1,53 @@
# OpenTelemetry Browser Tracer SDK
[![Gitter chat][gitter-image]][gitter-url]
[![dependencies][dependencies-image]][dependencies-url]
[![devDependencies][devDependencies-image]][devDependencies-url]
[![Apache License][license-image]][license-image]
This module provides automatic tracing for Web applications.
For manual instrumentation see the
[@opentelemetry/tracer-web](https://github.com/open-telemetry/opentelemetry-js/tree/master/packages/opentelemetry-tracer-web) package.
## How does automatic tracing work?
> Automatic Instrumentation is in progress, manual instrumentation only supported
## Installation
```bash
npm install --save @opentelemetry/tracer-web
```
## Usage
```js
// Manual
const { WebTracer } = require('@opentelemetry/tracer-web');
const webTracer = new WebTracer();
const span = webTracer.startSpan('span1');
webTracer.withSpan(span, function () {
// this === span
this.addEvent('start');
});
span.addEvent('middle');
span.end();
```
## Useful links
- For more information on OpenTelemetry, visit: <https://opentelemetry.io/>
- For more about OpenTelemetry JavaScript: <https://github.com/open-telemetry/opentelemetry-js>
- 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-tracer-web
[dependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-tracer-web
[devDependencies-image]: https://david-dm.org/open-telemetry/opentelemetry-js/dev-status.svg?path=packages/opentelemetry-tracer-web
[devDependencies-url]: https://david-dm.org/open-telemetry/opentelemetry-js?path=packages%2Fopentelemetry-tracer-web&type=dev

View File

@ -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
}))
};

View File

@ -0,0 +1,74 @@
{
"name": "@opentelemetry/tracer-web",
"version": "0.1.0",
"description": "OpenTelemetry Automatic Web Tracer",
"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 .",
"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/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/tracer-basic": "^0.1.0"
}
}

View File

@ -0,0 +1,123 @@
/*!
* 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 { ScopeManager } from '@opentelemetry/scope-base';
/**
* Stack Scope Manager for managing the state in web
* it doesn't fully support the async calls though
*/
export class StackScopeManager implements ScopeManager {
/**
* whether the scope manager is enabled or not
*/
private _enabled = false;
/**
* Keeps the reference to current scope
*/
public _currentScope: unknown;
/**
*
* @param target Function to be executed within the scope
* @param scope
* @private
*/
private _bindFunction<T extends Function>(target: T, scope?: unknown): T {
const manager = this;
const contextWrapper = function(...args: unknown[]) {
return manager.with(scope, () => target.apply(scope, args));
};
Object.defineProperty(contextWrapper, 'length', {
enumerable: false,
configurable: true,
writable: false,
value: target.length,
});
return (contextWrapper as unknown) as T;
}
/**
* Returns the active scope
*/
active(): unknown {
return this._currentScope;
}
/**
* Binds a the certain scope or the active one to the target function and then returns the target
* @param target
* @param scope
*/
bind<T>(target: T, scope?: unknown): T {
// if no specific scope to propagate is given, we use the current one
if (scope === undefined) {
scope = this.active();
}
if (typeof target === 'function') {
return this._bindFunction(target, scope);
}
return target;
}
/**
* Disable the scope manager (clears the current scope)
*/
disable(): this {
this._currentScope = undefined;
this._enabled = false;
return this;
}
/**
* Enables the scope manager and creates a default(root) scope
*/
enable(): this {
if (this._enabled) {
return this;
}
this._enabled = true;
this._currentScope = window;
return this;
}
/**
* Calls the callback function [fn] with the provided [scope]. If [scope] is undefined then it will use the window.
* The scope will be set as active
* @param scope
* @param fn Callback function
*/
with<T extends (...args: unknown[]) => ReturnType<T>>(
scope: unknown,
fn: () => ReturnType<T>
): ReturnType<T> {
if (typeof scope === 'undefined' || scope === null) {
scope = window;
}
const previousScope = this._currentScope;
this._currentScope = scope;
try {
return fn.apply(scope);
} catch (err) {
throw err;
} finally {
this._currentScope = previousScope;
}
}
}

View File

@ -0,0 +1,38 @@
/*!
* 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, BasicTracerConfig } from '@opentelemetry/tracer-basic';
import { StackScopeManager } from './StackScopeManager';
/**
* This class represents a web tracer with {@link StackScopeManager}
*/
export class WebTracer extends BasicTracer {
/**
* Constructs a new Tracer instance.
*/
/**
*
* @param {BasicTracerConfig} config Web Tracer config
*/
constructor(config: BasicTracerConfig = {}) {
if (typeof config.scopeManager === 'undefined') {
config.scopeManager = new StackScopeManager();
}
config.scopeManager.enable();
super(Object.assign({}, { scopeManager: config.scopeManager }, config));
}
}

View File

@ -0,0 +1,18 @@
/*!
* 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 './WebTracer';
export * from './StackScopeManager';

View File

@ -0,0 +1,171 @@
/*!
* 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 { StackScopeManager } from '../src';
describe('StackScopeManager', () => {
let scopeManager: StackScopeManager;
beforeEach(() => {
scopeManager = new StackScopeManager();
scopeManager.enable();
});
afterEach(() => {
scopeManager.disable();
});
describe('.enable()', () => {
it('should work', () => {
assert.doesNotThrow(() => {
assert(scopeManager.enable() === scopeManager, 'should return this');
assert(scopeManager.active() === window, 'should has root scope');
});
});
});
describe('.disable()', () => {
it('should work', () => {
assert.doesNotThrow(() => {
assert(scopeManager.disable() === scopeManager, 'should return this');
assert(scopeManager.active() === undefined, 'should has no scope');
});
});
});
describe('.with()', () => {
it('should run the callback (null as target)', done => {
scopeManager.with(null, done);
});
it('should run the callback (object as target)', done => {
const test = { a: 1 };
scopeManager.with(test, () => {
assert.strictEqual(scopeManager.active(), test, 'should have scope');
return done();
});
});
it('should run the callback (when disabled)', done => {
scopeManager.disable();
scopeManager.with(null, () => {
scopeManager.enable();
return done();
});
});
it('should rethrow errors', done => {
assert.throws(() => {
scopeManager.with(null, () => {
throw new Error('This should be rethrown');
});
});
return done();
});
it('should finally restore an old scope', done => {
const scope1 = 'scope1';
const scope2 = 'scope2';
const scope3 = 'scope3';
scopeManager.with(scope1, () => {
assert.strictEqual(scopeManager.active(), 'scope1');
scopeManager.with(scope2, () => {
assert.strictEqual(scopeManager.active(), 'scope2');
scopeManager.with(scope3, () => {
assert.strictEqual(scopeManager.active(), 'scope3');
});
assert.strictEqual(scopeManager.active(), 'scope2');
});
assert.strictEqual(scopeManager.active(), 'scope1');
return done();
});
assert.strictEqual(scopeManager.active(), window);
});
it('should finally restore an old scope when scope is an object', done => {
const scope1 = { a: 1 };
const scope2 = { a: 2 };
const scope3 = { a: 3 };
scopeManager.with(scope1, () => {
assert.strictEqual(scopeManager.active(), scope1);
scopeManager.with(scope2, () => {
assert.strictEqual(scopeManager.active(), scope2);
scopeManager.with(scope3, () => {
assert.strictEqual(scopeManager.active(), scope3);
});
assert.strictEqual(scopeManager.active(), scope2);
});
assert.strictEqual(scopeManager.active(), scope1);
return done();
});
assert.strictEqual(scopeManager.active(), window);
});
});
describe('.bind(function)', () => {
it('should call the function with previously assigned scope', () => {
class Obj {
title: string;
constructor(title: string) {
this.title = title;
}
getTitle() {
return this.title;
}
}
const obj1 = new Obj('a1');
obj1.title = 'a2';
const obj2 = new Obj('b1');
const wrapper: any = scopeManager.bind(obj2.getTitle, obj1);
assert.ok(wrapper(), 'a2');
});
it('should return the same target (when enabled)', () => {
const test = { a: 1 };
assert.deepStrictEqual(scopeManager.bind(test), test);
});
it('should return the same target (when disabled)', () => {
scopeManager.disable();
const test = { a: 1 };
assert.deepStrictEqual(scopeManager.bind(test), test);
scopeManager.enable();
});
it('should return current scope (when enabled)', done => {
const scope = { a: 1 };
const fn: any = scopeManager.bind(() => {
assert.strictEqual(scopeManager.active(), scope, 'should have scope');
return done();
}, scope);
fn();
});
it('should return current scope (when disabled)', done => {
scopeManager.disable();
const scope = { a: 1 };
const fn: any = scopeManager.bind(() => {
assert.strictEqual(scopeManager.active(), scope, 'should have scope');
return done();
}, scope);
fn();
});
});
});

View File

@ -0,0 +1,56 @@
/*!
* 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 { BasicTracerConfig } from '@opentelemetry/tracer-basic';
import { StackScopeManager } from '../src/StackScopeManager';
import { WebTracer } from '../src/WebTracer';
describe('WebTracer', () => {
let tracer: WebTracer;
describe('constructor', () => {
let defaultOptions: BasicTracerConfig;
beforeEach(() => {
defaultOptions = {
scopeManager: new StackScopeManager(),
};
});
it('should construct an instance with required only options', () => {
tracer = new WebTracer(Object.assign({}, defaultOptions));
assert.ok(tracer instanceof WebTracer);
});
it('should enable the scope manager', () => {
let options: BasicTracerConfig;
const scopeManager = new StackScopeManager();
options = { scopeManager };
const spy = sinon.spy(scopeManager, 'enable');
tracer = new WebTracer(options);
assert.ok(spy.calledOnce === true);
});
it('should work without default scope manager', () => {
assert.doesNotThrow(() => {
tracer = new WebTracer({});
});
});
});
});

View File

@ -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);

View File

@ -0,0 +1,7 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"types": []
},
"include": ["src/**/*.ts"]
}

View File

@ -0,0 +1,11 @@
{
"extends": "../tsconfig.base",
"compilerOptions": {
"rootDir": ".",
"outDir": "build"
},
"include": [
"src/**/*.ts",
"test/**/*.ts"
]
}

View File

@ -0,0 +1,4 @@
{
"rulesDirectory": ["node_modules/tslint-microsoft-contrib"],
"extends": ["../../tslint.base.js", "./node_modules/tslint-consistent-codestyle"]
}

View File

@ -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 } }
]
}
};

52
webpack.node-polyfills.js Normal file
View File

@ -0,0 +1,52 @@
module.exports = {
// Enable the assert library polyfill because that is used in tests
assert: true,
// The assert polyfill from github.com/browserify/commonjs-assert
// also requires the `global` polyfill.
global: true,
// Turn off all other Node.js API polyfills for the browser tests to
// make sure that we are not attempting to use Node-specific APIs in
// the browser code. Instead, we will write browser specific
// implementations of platform functionality we need under the
// `./src/platform/browser` folder. This allows for writing browser
// optimized implementations of the specific needed functionality
// rather than bringing in (sometimes large) polyfills for the
// corresponding Node APIs.
Buffer: false,
__dirname: false,
__filename: false,
buffer: false,
child_process: false,
cluster: false,
console: false,
constants: false,
crypto: false,
dgram: false,
dns: false,
domain: false,
events: false,
fs: false,
http: false,
https: false,
module: false,
net: false,
os: false,
path: false,
process: false,
punycode: false,
querystring: false,
readline: false,
repl: false,
setImmediate: false,
stream: false,
string_decoder: false,
sys: false,
timers: false,
tls: false,
tty: false,
url: false,
util: false,
vm: false,
zlib: false
};