Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(traceparent): setting parent span from server #477

Merged
merged 13 commits into from
Nov 8, 2019
Merged
9 changes: 9 additions & 0 deletions examples/tracer-web/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,15 @@
</head>

<body>
<script>
// https://www.w3.org/TR/trace-context/
// Set the `traceparent` in the server's HTML template code. It should be
// dynamically generated server side to have the server's request trace Id,
// a parent span Id that was set on the server's request span, and the trace
// flags to indicate the server's sampling decision (01 = sampled, 00 = not
// sampled). '{version}-{traceId}-{spanId}-{sampleDecision}'
window.traceparent = '00-ab42124a3c573678d4d8b21ba52df3bf-d21f7bc17caa5aba-01';
</script>
Example of using Web Tracer with document load plugin and console exporter
<script type="text/javascript" src="/bundle.js"></script>
</body>
Expand Down
14 changes: 11 additions & 3 deletions packages/opentelemetry-plugin-document-load/src/documentLoad.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,12 @@ import { BasePlugin, otperformance } from '@opentelemetry/core';
import { PluginConfig, Span, SpanOptions } from '@opentelemetry/types';
import { AttributeNames } from './enums/AttributeNames';
import { PerformanceTimingNames as PTN } from './enums/PerformanceTimingNames';
import { PerformanceEntries, PerformanceLegacy } from './types';
import { hasKey } from './utils';
import {
PerformanceEntries,
PerformanceLegacy,
WindowWithTrace,
} from './types';
import { hasKey, extractServerContext } from './utils';

/**
* This class represents a document load plugin
Expand Down Expand Up @@ -76,12 +80,16 @@ export class DocumentLoad extends BasePlugin<unknown> {
* Collects information about performance and creates appropriate spans
*/
private _collectPerformance() {
const windowWithTrace: WindowWithTrace = (window as unknown) as WindowWithTrace;
const serverContext = extractServerContext(windowWithTrace.traceparent);

const entries = this._getEntries();

const rootSpan = this._startSpan(
AttributeNames.DOCUMENT_LOAD,
PTN.FETCH_START,
entries
entries,
{ parent: serverContext }
);
if (!rootSpan) {
return;
Expand Down
7 changes: 7 additions & 0 deletions packages/opentelemetry-plugin-document-load/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,10 @@ export type PerformanceEntries = {
export interface PerformanceLegacy {
timing?: PerformanceEntries;
}

/**
* A window object with traceparent information from server
*/
export interface WindowWithTrace {
traceparent?: string;
}
42 changes: 42 additions & 0 deletions packages/opentelemetry-plugin-document-load/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
* limitations under the License.
*/

import * as types from '@opentelemetry/types';
import { TraceFlags } from '@opentelemetry/types';

/**
* Helper function to be able to use enum as typed key in type and in interface when using forEach
* @param obj
Expand All @@ -22,3 +25,42 @@
export function hasKey<O>(obj: O, key: keyof any): key is keyof O {
return key in obj;
}

// '{version}-{traceId}-{spanId}-{TraceFlags}';
const TRACE_PARENT_REGEX = /^[\da-f]{2}-([\da-f]{32})-([\da-f]{16})-([\da-f]{2})$/;

/**
* Extracts information from [traceParent] window property and converts it into {@link types.SpanContext}
* @param traceParent - A window property that comes from server.
* It should be dynamically generated server side to have the server's request trace Id,
* a parent span Id that was set on the server's request span,
* and the trace flags to indicate the server's sampling decision
* (01 = sampled, 00 = not sampled).
* for example: '{version}-{traceId}-{spanId}-{sampleDecision}'
* For more information see {@link https://www.w3.org/TR/trace-context/}
*/
export function extractServerContext(
obecny marked this conversation as resolved.
Show resolved Hide resolved
traceParent: string = ''
): types.SpanContext | undefined {
const match =
typeof traceParent === 'string' && traceParent.match(TRACE_PARENT_REGEX);
if (!match) {
return;
}
const traceId = match[1];
const spanId = match[2];
let traceFlags;

if (match[3] === '00') {
traceFlags = TraceFlags.UNSAMPLED;
} else if (match[3] === '01') {
traceFlags = TraceFlags.SAMPLED;
}

let spanContext: types.SpanContext | undefined;
if (traceId && spanId && typeof traceFlags !== 'undefined') {
spanContext = { traceId, spanId, traceFlags };
}

return spanContext;
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,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';
import { WindowWithTrace } from '../src/types';

export class DummyExporter implements SpanExporter {
export(
Expand Down Expand Up @@ -238,6 +239,38 @@ describe('DocumentLoad Plugin', () => {
});
});

describe('AND window has information about server root span', () => {
beforeEach(() => {
((window as unknown) as WindowWithTrace).traceparent =
'00-ab42124a3c573678d4d8b21ba52df3bf-d21f7bc17caa5aba-01';
});
it('should create a root span with server context traceId', done => {
const spyOnEnd = sinon.spy(dummyExporter, 'export');
plugin.enable(moduleExports, tracer, logger, config);
setTimeout(() => {
const rootSpan = spyOnEnd.args[0][0][0] as ReadableSpan;
const fetchSpan = spyOnEnd.args[1][0][0] as ReadableSpan;
assert.strictEqual(rootSpan.name, 'documentFetch');
assert.strictEqual(fetchSpan.name, 'documentLoad');

assert.strictEqual(
rootSpan.spanContext.traceId,
'ab42124a3c573678d4d8b21ba52df3bf'
);
assert.strictEqual(
fetchSpan.spanContext.traceId,
'ab42124a3c573678d4d8b21ba52df3bf'
);

assert.strictEqual(spyOnEnd.callCount, 2);
done();
}, 1);
});
afterEach(() => {
delete ((window as unknown) as WindowWithTrace).traceparent;
});
});

afterEach(() => {
spyExport.restore();
});
Expand Down
112 changes: 112 additions & 0 deletions packages/opentelemetry-plugin-document-load/test/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/*!
* 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 types from '@opentelemetry/types';
import * as utils from '../src/utils';

const traceParentSampled =
'00-ab42124a3c573678d4d8b21ba52df3bf-d21f7bc17caa5aba-01';
const traceParentUnSampled =
'00-ab42124a3c573678d4d8b21ba52df3bf-d21f7bc17caa5aba-00';
const traceParentBadTraceFlags =
'00-ab42124a3c573678d4d8b21ba52df3bf-d21f7bc17caa5aba-02';
const traceParentBadSpanId =
'00-ab42124a3c573678d4d8b21ba52df3bf-d21f7bc17caa5ab-00';
const traceParentBadTraceId =
'00-ab42124a3c573678d4d8b21ba52df3b-d21f7bc17caa5aba-00';

describe('utils', () => {
describe('extractServerContext', () => {
describe('when traceParent is correct', () => {
it('should create context span with traceId', () => {
const spanContext = utils.extractServerContext(traceParentSampled);
assert.strictEqual(
spanContext && spanContext.traceId,
'ab42124a3c573678d4d8b21ba52df3bf',
'Trace Id is correct'
);
});
it('should create context span with spanId', () => {
const spanContext = utils.extractServerContext(traceParentSampled);
assert.strictEqual(
spanContext && spanContext.spanId,
'd21f7bc17caa5aba',
'Span Id is correct'
);
});
it('should create context span with traceFlags SAMPLED', () => {
const spanContext = utils.extractServerContext(traceParentSampled);
assert.strictEqual(
spanContext && spanContext.traceFlags,
types.TraceFlags.SAMPLED,
'Trace Flag is SAMPLED'
);
});
it('should create context span with traceFlags UNSAMPLED', () => {
const spanContext = utils.extractServerContext(traceParentUnSampled);
assert.strictEqual(
spanContext && spanContext.traceFlags,
types.TraceFlags.UNSAMPLED,
'Trace Flag is UNSAMPLED'
);
});
});
describe('when traceParent has incorrect traceFlags', () => {
it('should NOT create context span', () => {
const spanContext = utils.extractServerContext(
traceParentBadTraceFlags
);
assert.strictEqual(spanContext, undefined);
});
});
describe('when traceParent has incorrect spanId', () => {
it('should NOT create context span', () => {
const spanContext = utils.extractServerContext(traceParentBadSpanId);
assert.strictEqual(spanContext, undefined);
});
});
describe('when traceParent has incorrect traceId', () => {
it('should NOT create context span', () => {
const spanContext = utils.extractServerContext(traceParentBadTraceId);
assert.strictEqual(spanContext, undefined);
});
});
describe('when traceParent has incorrect structure', () => {
it('should NOT create context span', () => {
assert.strictEqual(
utils.extractServerContext(
'ab42124a3c573678d4d8b21ba52df3bf-d21f7bc17caa5aba-00'
),
undefined
);
assert.strictEqual(
utils.extractServerContext(
'0-ab42124a3c573678d4d8b21ba52df3bf-d21f7bc17caa5aba-00'
),
undefined
);
assert.strictEqual(
utils.extractServerContext(
'00-ab42124a3c573678d4d8b21ba52df3bf-d21f7bc17caa5aba-01-foo'
),
undefined
);
});
});
});
});