Skip to content

Commit

Permalink
Merge branch 'main' into lint-warnings-3
Browse files Browse the repository at this point in the history
  • Loading branch information
vmarchaud committed Aug 14, 2021
2 parents 321781d + 33e6f71 commit f5ac849
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 58 deletions.
21 changes: 8 additions & 13 deletions packages/opentelemetry-instrumentation-fetch/src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -284,23 +284,18 @@ export class FetchInstrumentation extends InstrumentationBase<
/**
* Patches the constructor of fetch
*/
private _patchConstructor(): (
original: (input: RequestInfo, init?: RequestInit) => Promise<Response>
) => (input: RequestInfo, init?: RequestInit) => Promise<Response> {
return (
original: (input: RequestInfo, init?: RequestInit) => Promise<Response>
): ((input: RequestInfo, init?: RequestInit) => Promise<Response>) => {
private _patchConstructor(): (original: Window['fetch']) => Window['fetch'] {
return original => {
const plugin = this;
return function patchConstructor(
this: (input: RequestInfo, init?: RequestInit) => Promise<Response>,
input: RequestInfo,
init?: RequestInit
this: Window,
...args: Parameters<Window['fetch']>
): Promise<Response> {
const url = input instanceof Request ? input.url : input;
const options = input instanceof Request ? input : init || {};
const url = args[0] instanceof Request ? args[0].url : args[0];
const options = args[0] instanceof Request ? args[0] : args[1] || {};
const createdSpan = plugin._createSpan(url, options);
if (!createdSpan) {
return original.apply(this, [url, options]);
return original.apply(this, args);
}
const spanData = plugin._prepareSpanData(url);

Expand Down Expand Up @@ -380,7 +375,7 @@ export class FetchInstrumentation extends InstrumentationBase<
plugin._addHeaders(options, url);
plugin._tasksCount++;
return original
.apply(this, [url, options])
.apply(this, options instanceof Request ? [options] : [url, options])
.then(
(onSuccess as any).bind(this, createdSpan, resolve),
onError.bind(this, createdSpan, reject)
Expand Down
26 changes: 24 additions & 2 deletions packages/opentelemetry-instrumentation-fetch/test/fetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,11 +176,16 @@ describe('fetch', () => {
};
response.headers = Object.assign({}, init.headers);

if (init.method === 'DELETE') {
if (init instanceof Request) {
// Passing request as 2nd argument causes missing body bug (#2411)
response.status = 400;
response.statusText = 'Bad Request (Request object as 2nd argument)';
reject(new window.Response(JSON.stringify(response), response));
} else if (init.method === 'DELETE') {
response.status = 405;
response.statusText = 'OK';
resolve(new window.Response('foo', response));
} else if (input === url) {
} else if ((input instanceof Request && input.url === url) || input === url) {
response.status = 200;
response.statusText = 'OK';
resolve(new window.Response(JSON.stringify(response), response));
Expand Down Expand Up @@ -530,6 +535,15 @@ describe('fetch', () => {
assert.ok(typeof r.headers.get(X_B3_TRACE_ID) === 'string');
});

it('should pass request object as first parameter to the original function (#2411)', () => {
const r = new Request(url);
return window.fetch(r).then(() => {
assert.ok(true);
}, (response: Response) => {
assert.fail(response.statusText);
});
});

it('should NOT clear the resources', () => {
assert.strictEqual(
clearResourceTimingsSpy.args.length,
Expand Down Expand Up @@ -659,6 +673,14 @@ describe('fetch', () => {
it('should NOT create any span', () => {
assert.strictEqual(exportSpy.args.length, 0, "span shouldn't b exported");
});
it('should pass request object as the first parameter to the original function (#2411)', () => {
const r = new Request(url);
return window.fetch(r).then(() => {
assert.ok(true);
}, (response: Response) => {
assert.fail(response.statusText);
});
});
});

describe('when clearTimingResources is TRUE', () => {
Expand Down
46 changes: 15 additions & 31 deletions website_docs/getting_started/nodejs.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,9 @@ The following dependencies are required to trace a Node.js application.

These dependencies are required to configure the tracing SDK and create spans.

- `@opentelemetry/api`
- `@opentelemetry/sdk-trace-node`
- `@opentelemetry/sdk-trace-base`
```shell
npm install @opentelemetry/sdk-node @opentelemetry/api
```

#### Exporter

Expand All @@ -91,6 +91,10 @@ Many common modules such as the `http` standard library module, `express`, and o

You can also install all instrumentations maintained by the OpenTelemetry authors by using the `@opentelemetry/auto-instrumentations-node` module.

```shell
npm install @opentelemetry/auto-instrumentations-node
```

### Setup

The tracing setup and configuration should be run before your application code. One tool commonly used for this task is the [`-r, --require module`](https://nodejs.org/api/cli.html#cli_r_require_module) flag.
Expand All @@ -101,47 +105,27 @@ Create a file with a name like `tracing.js` which will contain your tracing setu
/* tracing.js */

// Require dependencies
const { NodeTracerProvider } = require("@opentelemetry/sdk-trace-node");
const { SimpleSpanProcessor, ConsoleSpanExporter } = require("@opentelemetry/sdk-trace-base");
const { getNodeAutoInstrumentations } = require("@opentelemetry/auto-instrumentations-node');
const { registerInstrumentations } = require('@opentelemetry/instrumentation');
// Create a tracer provider
const provider = new NodeTracerProvider();
// The exporter handles sending spans to your tracing backend
const exporter = new ConsoleSpanExporter();
// The simple span processor sends spans to the exporter as soon as they are ended.
const processor = new SimpleSpanProcessor(exporter);
provider.addSpanProcessor(processor);
const opentelemetry = require("@opentelemetry/sdk-node");
const { getNodeAutoInstrumentations } = require("@opentelemetry/auto-instrumentations-node");

// The provider must be registered in order to
// be used by the OpenTelemetry API and instrumentations
provider.register();
// This will automatically enable all instrumentations
registerInstrumentations({
instrumentations: [getNodeAutoInstrumentations()],
const sdk = new opentelemetry.NodeSDK({
traceExporter: new opentelemetry.tracing.ConsoleSpanExporter(),
instrumentations: [getNodeAutoInstrumentations()]
});

sdk.start()
```

### Run Application

First, install the dependencies as described above. Here you need to add the following:
```shell
npm install --save @opentelemetry/sdk-trace-node @opentelemetry/auto-instrumentations-node
```
Now you can run your application as you normally would, but you can use the `--require` flag to load the tracing code before the application code.

```shell
$ node --require './tracing.js' app.js
Listening for requests on http://localhost:8080
```

Now, when you open <http://localhost:8080> in your web browser, you should see the spans printed in the console by the `ConsoleSpanExporter`.
Open <http://localhost:8080> in your web browser and reload the page a few times, after a while you should see the spans printed in the console by the `ConsoleSpanExporter`.

<details>
<summary>View example output</summary>
Expand Down
23 changes: 11 additions & 12 deletions website_docs/instrumentation.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,16 +108,17 @@ for (let i = 0; i < 10; i += 1) {
function doWork(parent) {
// Start another span. In this example, the main method already started a
// span, so that'll be the parent span, and this will be a child span.
const span = tracer.startSpan('doWork', {
parent,
});
const ctx = opentelemetry.trace.setSpan(opentelemetry.context.active(), parent);
const span = tracer.startSpan('doWork', undefined, ctx);

// simulate some random work.
for (let i = 0; i <= Math.floor(Math.random() * 40000000); i += 1) {
// empty
}
span.end();
}
// Be sure to end the span.
parentSpan.end();
```

Invoking your application once again will give you a list of traces being exported.
Expand All @@ -128,9 +129,8 @@ Attributes can be used to describe your spans. Attributes can be added to a span

```javascript
function doWork(parent) {
const span = tracer.startSpan('doWork', {
parent, attributes: { attribute1 : 'value1' }
});
const ctx = opentelemetry.trace.setSpan(opentelemetry.context.active(), parent);
const span = tracer.startSpan('doWork', { attributes: { attribute1 : 'value1' } }, ctx);
for (let i = 0; i <= Math.floor(Math.random() * 40000000); i += 1) {
// empty
}
Expand Down Expand Up @@ -159,9 +159,8 @@ Finally, you can update your file to include semantic attributes:

```javascript
function doWork(parent) {
const span = tracer.startSpan('doWork', {
parent, attributes: { SemanticAttributes.CODE_FUNCTION : 'doWork' }
});
const ctx = opentelemetry.trace.setSpan(opentelemetry.context.active(), parent);
const span = tracer.startSpan('doWork', { attributes: { [SemanticAttributes.CODE_FUNCTION] : 'doWork' } }, ctx);
for (let i = 0; i <= Math.floor(Math.random() * 40000000); i += 1) {
// empty
}
Expand All @@ -178,9 +177,9 @@ The status can be set at any time before the span is finished:

```javascript
function doWork(parent) {
const span = tracer.startSpan('doWork', {
parent,
});
const ctx = opentelemetry.trace.setSpan(opentelemetry.context.active(), parent);
const span = tracer.startSpan('doWork', undefined, ctx);

span.setStatus({
code: opentelemetry.SpanStatusCode.OK,
message: 'Ok.'
Expand Down

0 comments on commit f5ac849

Please sign in to comment.