Skip to content

Commit

Permalink
Merge branch 'master' into http-sender
Browse files Browse the repository at this point in the history
  • Loading branch information
leonardodalcin authored Apr 17, 2020
2 parents 256eb0e + d71954e commit cf5fe82
Show file tree
Hide file tree
Showing 26 changed files with 1,039 additions and 53 deletions.
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,11 @@ Maintainers ([@open-telemetry/js-maintainers](https://github.com/orgs/open-telem

*Find more about the maintainer role in [community repository](https://github.com/open-telemetry/community/blob/master/community-membership.md#maintainer).*

### Thanks to all the people who already contributed!
<a href="https://github.com/open-telemetry/opentelemetry-js/graphs/contributors">
<img src="https://contributors-img.web.app/image?repo=open-telemetry/opentelemetry-js" />
</a>

## Packages

### API
Expand Down Expand Up @@ -192,7 +197,6 @@ Apache 2.0 - See [LICENSE][license-url] for more information.

[node-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

[up-for-grabs-issues]: https://github.com/open-telemetry/OpenTelemetry-js/issues?q=is%3Aissue+is%3Aopen+label%3Aup-for-grabs
[good-first-issues]: https://github.com/open-telemetry/OpenTelemetry-js/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22

Expand Down
4 changes: 4 additions & 0 deletions packages/opentelemetry-plugin-express/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ const provider = new NodeTracerProvider();

See [examples/express](https://github.com/open-telemetry/opentelemetry-js/tree/master/examples/express) for a short example.

### Caveats

Because of the way express works, it's hard to correctly compute the time taken by asynchronous middlewares and request handlers. For this reason, the time you'll see reported for asynchronous middlewares and request handlers will only represent the synchronous execution time, and **not** any asynchronous work.

### Express Plugin Options

Express plugin has few options available to choose from. You can set the following:
Expand Down
45 changes: 27 additions & 18 deletions packages/opentelemetry-plugin-express/src/express.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* limitations under the License.
*/

import { BasePlugin } from '@opentelemetry/core';
import { BasePlugin, hrTime } from '@opentelemetry/core';
import { Attributes } from '@opentelemetry/api';
import * as express from 'express';
import * as core from 'express-serve-static-core';
Expand All @@ -30,12 +30,7 @@ import {
ExpressPluginConfig,
ExpressLayerType,
} from './types';
import {
getLayerMetadata,
storeLayerPath,
patchEnd,
isLayerIgnored,
} from './utils';
import { getLayerMetadata, storeLayerPath, isLayerIgnored } from './utils';
import { VERSION } from './version';

/**
Expand Down Expand Up @@ -190,26 +185,40 @@ export class ExpressPlugin extends BasePlugin<typeof express> {
const span = plugin._tracer.startSpan(metadata.name, {
attributes: Object.assign(attributes, metadata.attributes),
});
const startTime = hrTime();
let spanHasEnded: boolean = false;
// If we found anything that isnt a middleware, there no point of measuring
// stheir time ince they dont have callback.
if (
metadata.attributes[AttributeNames.EXPRESS_TYPE] !==
ExpressLayerType.MIDDLEWARE
) {
span.end(startTime);
spanHasEnded = true;
}
// verify we have a callback
let callbackIdx = Array.from(arguments).findIndex(
arg => typeof arg === 'function'
);
let callbackHasBeenCalled = false;
const args = Array.from(arguments);
const callbackIdx = args.findIndex(arg => typeof arg === 'function');
if (callbackIdx >= 0) {
arguments[callbackIdx] = function() {
callbackHasBeenCalled = true;
if (spanHasEnded === false) {
span.end();
spanHasEnded = true;
}
if (!(req.route && arguments[0] instanceof Error)) {
(req[_LAYERS_STORE_PROPERTY] as string[]).pop();
}
return patchEnd(span, plugin._tracer.bind(next))();
const callback = args[callbackIdx] as Function;
return plugin._tracer.bind(callback).apply(this, arguments);
};
}
const result = original.apply(this, arguments);
// if the layer return a response, the callback will never
// be called, so we need to manually close the span
if (callbackHasBeenCalled === false) {
span.end();
}
// If the callback is never called, we need to close the span.
setImmediate(() => {
if (spanHasEnded === false) {
span.end(startTime);
}
}).unref();
return result;
};
});
Expand Down
27 changes: 2 additions & 25 deletions packages/opentelemetry-plugin-express/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
* limitations under the License.
*/

import { CanonicalCode, Span, Attributes } from '@opentelemetry/api';
import { Attributes } from '@opentelemetry/api';
import {
ExpressLayer,
AttributeNames,
Expand Down Expand Up @@ -67,7 +67,7 @@ export const getLayerMetadata = (
[AttributeNames.EXPRESS_NAME]: layerPath ?? 'request handler',
[AttributeNames.EXPRESS_TYPE]: ExpressLayerType.REQUEST_HANDLER,
},
name: 'request handler',
name: `request handler${layer.path ? ` - ${layerPath}` : ''}`,
};
} else {
return {
Expand All @@ -80,29 +80,6 @@ export const getLayerMetadata = (
}
};

/**
* Ends a created span.
* @param span The created span to end.
* @param resultHandler A callback function.
*/
export const patchEnd = (span: Span, resultHandler: Function): Function => {
return function patchedEnd(this: {}, ...args: unknown[]) {
const error = args[0];
if (error instanceof Error) {
span.setStatus({
code: CanonicalCode.INTERNAL,
message: error.message,
});
} else {
span.setStatus({
code: CanonicalCode.OK,
});
}
span.end();
return resultHandler.apply(this, args);
};
};

/**
* Check whether the given obj match pattern
* @param constant e.g URL of request
Expand Down
2 changes: 1 addition & 1 deletion packages/opentelemetry-plugin-express/src/version.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,4 @@
*/

// this is autogenerated file, see scripts/version-update.js
export const VERSION = '0.6.1';
export const VERSION = '0.6.3';
2 changes: 1 addition & 1 deletion packages/opentelemetry-plugin-express/test/express.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ describe('Express Plugin', () => {
const app = express();
app.use(express.json());
app.use(function customMiddleware(req, res, next) {
for (let i = 0; i < 1000; i++) {
for (let i = 0; i < 1000000; i++) {
continue;
}
return next();
Expand Down
4 changes: 2 additions & 2 deletions packages/opentelemetry-plugin-http/src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ export class HttpPlugin extends BasePlugin<Http> {

protected _getPatchOutgoingGetFunction(
clientRequest: (
options: RequestOptions | string | URL,
options: RequestOptions | string | url.URL,
...args: HttpRequestArgs
) => ClientRequest
) {
Expand All @@ -161,7 +161,7 @@ export class HttpPlugin extends BasePlugin<Http> {
// https://nodejs.org/dist/latest/docs/api/http.html#http_http_get_options_callback
// https://github.com/googleapis/cloud-trace-nodejs/blob/master/src/plugins/plugin-http.ts#L198
return function outgoingGetRequest<
T extends RequestOptions | string | URL
T extends RequestOptions | string | url.URL
>(options: T, ...args: HttpRequestArgs): ClientRequest {
const req = clientRequest(options, ...args);
req.end();
Expand Down
10 changes: 9 additions & 1 deletion packages/opentelemetry-resources/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
"version": "0.6.1",
"description": "OpenTelemetry SDK resources",
"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": {
Expand Down Expand Up @@ -42,11 +46,14 @@
"devDependencies": {
"@types/mocha": "^7.0.0",
"@types/node": "^12.6.9",
"@types/sinon": "^7.0.13",
"codecov": "^3.6.1",
"gts": "^1.1.0",
"mocha": "^6.2.0",
"nock": "^12.0.2",
"nyc": "^15.0.0",
"rimraf": "^3.0.0",
"sinon": "^7.5.0",
"ts-mocha": "^6.0.0",
"ts-node": "^8.6.2",
"tslint-consistent-codestyle": "^1.16.0",
Expand All @@ -55,6 +62,7 @@
},
"dependencies": {
"@opentelemetry/api": "^0.6.1",
"@opentelemetry/base": "^0.6.1"
"@opentelemetry/base": "^0.6.1",
"gcp-metadata": "^3.5.0"
}
}
3 changes: 2 additions & 1 deletion packages/opentelemetry-resources/src/Resource.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import { SDK_INFO } from '@opentelemetry/base';
import { TELEMETRY_SDK_RESOURCE } from './constants';
import { ResourceLabels } from './types';

/**
* A Resource describes the entity for which a signals (metrics or trace) are
Expand Down Expand Up @@ -48,7 +49,7 @@ export class Resource {
* about the entity as numbers, strings or booleans
* TODO: Consider to add check/validation on labels.
*/
readonly labels: { [key: string]: number | string | boolean }
readonly labels: ResourceLabels
) {}

/**
Expand Down
4 changes: 3 additions & 1 deletion packages/opentelemetry-resources/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,7 @@
* limitations under the License.
*/

export { Resource } from './Resource';
export * from './Resource';
export * from './platform';
export * from './constants';
export * from './types';
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* Copyright 2020, OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 { Resource } from '../../Resource';

/**
* Detects resources for the browser platform, which is currently only the
* telemetry SDK resource. More could be added in the future. This method
* is async to match the signature of corresponding method for node.
*/
export const detectResources = async (): Promise<Resource> => {
return Resource.createTelemetrySDKResource();
};
17 changes: 17 additions & 0 deletions packages/opentelemetry-resources/src/platform/browser/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/*!
* Copyright 2020, OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 './detect-resources';
20 changes: 20 additions & 0 deletions packages/opentelemetry-resources/src/platform/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*!
* Copyright 2020, OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.
*/

// Use the node platform by default. The "browser" field of package.json is used
// to override this file to use `./browser/index.ts` when packaged with
// webpack, Rollup, etc.
export * from './node';
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/**
* Copyright 2020, OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 { Resource } from '../../Resource';
import { envDetector, awsEc2Detector, gcpDetector } from './detectors';
import { Detector } from '../../types';

const DETECTORS: Array<Detector> = [envDetector, awsEc2Detector, gcpDetector];

/**
* Runs all resource detectors and returns the results merged into a single
* Resource.
*/
export const detectResources = async (): Promise<Resource> => {
const resources: Array<Resource> = await Promise.all(
DETECTORS.map(d => {
try {
return d.detect();
} catch {
return Resource.empty();
}
})
);
return resources.reduce(
(acc, resource) => acc.merge(resource),
Resource.createTelemetrySDKResource()
);
};
Loading

0 comments on commit cf5fe82

Please sign in to comment.