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: Make ID generator configurable #1331

Merged
merged 15 commits into from
Jul 31, 2020
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,15 @@
* limitations under the License.
*/

import * as crypto from 'crypto';

const SPAN_ID_BYTES = 8;
const TRACE_ID_BYTES = 16;

/**
* Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
* characters corresponding to 128 bits.
* IdGenerator provides an interface for generating Trace Id and Span Id
*
* The prototype IdGenerator generates random 16-byte trace ID and 8-byte span ID
*/
export function randomTraceId(): string {
return crypto.randomBytes(TRACE_ID_BYTES).toString('hex');
}

/**
* Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex
* characters corresponding to 64 bits.
*/
export function randomSpanId(): string {
return crypto.randomBytes(SPAN_ID_BYTES).toString('hex');
export interface IdGenerator {
/** Generate Trace ID which is default to be 16 bytes */
GenerateTraceId(): string;
/** Generate Span ID which is default to be 8 bytes */
GenerateSpanId(): string;
}
1 change: 1 addition & 0 deletions packages/opentelemetry-api/src/platform/node/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,4 @@
*/

export * from './globalThis';
export * from './IdGenerator';
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/*
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This file needs to be in contrib, not this repo / package. https://github.com/open-telemetry/opentelemetry-js-contrib.

You can leave it out of this PR and we'll add it there later.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This definitely does not belong in core. I'm not sure it belongs in contrib either though. We have been keeping proprietary vendor code out of our repositories across all of otel AFAIK. Dis something change?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In Java we have them in the main repo

https://github.com/open-telemetry/opentelemetry-java/tree/master/sdk_extensions/aws_v1_support

From what I understand currently this is being left up to the language sigs. So if JS says separate repo we'll do that :)

* Copyright The 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 crypto from 'crypto';
import * as api from '@opentelemetry/api';

const SPAN_ID_BYTES = 8;
const TRACE_ID_BYTES = 16;
const TIME_BYTES = 4;

export class AWSXrayIdGenerator implements api.IdGenerator {
private SpanIdBytes: number = SPAN_ID_BYTES;
private TraceIdBytes: number = TRACE_ID_BYTES;

/**
* Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
* characters corresponding to 128 bits.
* And in AWS Xray Exporter, the first 4 bytes originate from the current
* time (unit: second)
*/
GenerateTraceId(): string {
var nowSec = Math.floor(Date.now() / 1000).toString(16);
return nowSec + crypto.randomBytes(this.TraceIdBytes - TIME_BYTES).toString('hex');
}

/**
* Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex
* characters corresponding to 64 bits.
*/
GenerateSpanId(): string {
return crypto.randomBytes(this.SpanIdBytes).toString('hex');
}
}
52 changes: 52 additions & 0 deletions packages/opentelemetry-core/src/platform/node/RandomIdGenerator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* Copyright The 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 crypto from 'crypto';
import * as api from '@opentelemetry/api';

const SPAN_ID_BYTES = 8;
const TRACE_ID_BYTES = 16;

export class RandomIdGenerator implements api.IdGenerator {
private SpanIdBytes: number = SPAN_ID_BYTES;
private TraceIdBytes: number = TRACE_ID_BYTES;

// In case if user would like to adjust the length of ID
constructor(Span_Id_Bytes?: number, Trace_Id_Bytes?: number) {
if (Span_Id_Bytes) {
this.SpanIdBytes = Span_Id_Bytes;
}
if (Trace_Id_Bytes) {
this.TraceIdBytes = Trace_Id_Bytes;
}
}

/**
* Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex
* characters corresponding to 128 bits.
*/
GenerateTraceId(): string {
return crypto.randomBytes(this.TraceIdBytes).toString('hex');
}

/**
* Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex
* characters corresponding to 64 bits.
*/
GenerateSpanId(): string {
return crypto.randomBytes(this.SpanIdBytes).toString('hex');
}
}
3 changes: 2 additions & 1 deletion packages/opentelemetry-core/src/platform/node/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
export * from './BasePlugin';
export * from './environment';
export * from './hex-to-base64';
export * from './id';
export * from './RandomIdGenerator';
export * from './performance';
export * from './sdk-info';
export * from './timer-util';
export * from './AWSXrayIdGenerator';
8 changes: 4 additions & 4 deletions packages/opentelemetry-core/test/context/composite.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,7 @@ import * as assert from 'assert';
import {
CompositePropagator,
HttpTraceContext,
randomSpanId,
randomTraceId,
RandomIdGenerator,
} from '../../src';
import {
getExtractedSpanContext,
Expand All @@ -49,8 +48,9 @@ describe('Composite Propagator', () => {
let spanId: string;

beforeEach(() => {
traceId = randomTraceId();
spanId = randomSpanId();
let IdGenerator = new RandomIdGenerator();
traceId = IdGenerator.GenerateTraceId();
spanId = IdGenerator.GenerateSpanId();
});

describe('inject', () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* Copyright The 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 { AWSXrayIdGenerator } from '../../src/platform';

const IdGenerator = new AWSXrayIdGenerator();

describe('AWSXrayTraceId', () => {
let TraceId1: string, TraceId2: string;
let PrevTime: number, CurrTime: number, NextTime: number;
beforeEach(() => {
PrevTime = Math.floor(Date.now() / 1000);
TraceId1 = IdGenerator.GenerateTraceId();
CurrTime = parseInt(TraceId1.substring(0, 8), 16);
NextTime = Math.floor(Date.now() / 1000);
console.log(TraceId1.length);
TraceId2 = IdGenerator.GenerateTraceId();
});

it('returns 32 character hex strings', () => {
assert.ok(TraceId1.match(/[a-f0-9]{32}/));
assert.ok(!TraceId1.match(/^0+$/));
});

it('returns different ids on each call', () => {
assert.notDeepStrictEqual(TraceId1, TraceId2);
});

it('using current time to encode trace id', () => {
assert.ok(CurrTime >= PrevTime);
assert.ok(CurrTime <= NextTime);
})
});

describe('AWSXraySpanId', () => {
let SpanId1: string, SpanId2: string;
beforeEach(() => {
SpanId1 = IdGenerator.GenerateSpanId();
SpanId2 = IdGenerator.GenerateSpanId();
});

it('returns 16 character hex strings', () => {
assert.ok(SpanId1.match(/[a-f0-9]{16}/));
assert.ok(!SpanId1.match(/^0+$/));
});

it('returns different ids on each call', () => {
assert.notDeepStrictEqual(SpanId1, SpanId2);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
* Copyright The 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 { RandomIdGenerator } from '../../src/platform';

const IdGenerator = new RandomIdGenerator();
const IdGeneratorWithParameters = new RandomIdGenerator(8, 16);

describe('IdGeneratorConstructor', () => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Once you remove the length parameters, make sure this is mostly just copy-paste from previous tests

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I actually added beforeEach() keyword to separate obtaining value part and testing value part. Is that good or not?

it('Default provides 16-byte TraceId and 8-byte SpanId', () => {
assert.equal(
IdGenerator.GenerateTraceId().length,
IdGeneratorWithParameters.GenerateTraceId().length
);
assert.equal(
IdGenerator.GenerateSpanId().length,
IdGeneratorWithParameters.GenerateSpanId().length
);
});
});

describe('randomTraceId', () => {
let TraceId1: string, TraceId2: string;
beforeEach(() => {
TraceId1 = IdGenerator.GenerateTraceId();
TraceId2 = IdGenerator.GenerateTraceId();
});

it('returns 32 character hex strings', () => {
assert.ok(TraceId1.match(/[a-f0-9]{32}/));
assert.ok(!TraceId1.match(/^0+$/));
});

it('returns different ids on each call', () => {
assert.notDeepStrictEqual(TraceId1, TraceId2);
});
});

describe('randomSpanId', () => {
let SpanId1: string, SpanId2: string;
beforeEach(() => {
SpanId1 = IdGenerator.GenerateSpanId();
SpanId2 = IdGenerator.GenerateSpanId();
});

it('returns 16 character hex strings', () => {
assert.ok(SpanId1.match(/[a-f0-9]{16}/));
assert.ok(!SpanId1.match(/^0+$/));
});

it('returns different ids on each call', () => {
assert.notDeepStrictEqual(SpanId1, SpanId2);
});
});
48 changes: 0 additions & 48 deletions packages/opentelemetry-core/test/platform/id.test.ts

This file was deleted.

9 changes: 5 additions & 4 deletions packages/opentelemetry-tracing/src/Tracer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@ import {
InstrumentationLibrary,
isValid,
NoRecordingSpan,
randomSpanId,
randomTraceId,
RandomIdGenerator,
setActiveSpan,
} from '@opentelemetry/core';
import { Resource } from '@opentelemetry/resources';
Expand All @@ -42,6 +41,7 @@ export class Tracer implements api.Tracer {
readonly resource: Resource;
readonly instrumentationLibrary: InstrumentationLibrary;
readonly logger: api.Logger;
readonly idGenerator: api.IdGenerator;

/**
* Constructs a new Tracer instance.
Expand All @@ -58,6 +58,7 @@ export class Tracer implements api.Tracer {
this.resource = _tracerProvider.resource;
this.instrumentationLibrary = instrumentationLibrary;
this.logger = config.logger || new ConsoleLogger(config.logLevel);
this.idGenerator = config.idGenerator || new RandomIdGenerator();
}

/**
Expand All @@ -70,12 +71,12 @@ export class Tracer implements api.Tracer {
context = api.context.active()
): api.Span {
const parentContext = getParent(options, context);
const spanId = randomSpanId();
const spanId = this.idGenerator.GenerateSpanId();
let traceId;
let traceState;
if (!parentContext || !isValid(parentContext)) {
// New root span.
traceId = randomTraceId();
traceId = this.idGenerator.GenerateTraceId();
} else {
// New child span.
traceId = parentContext.traceId;
Expand Down
Loading