Skip to content
This repository was archived by the owner on Oct 3, 2023. It is now read-only.

Commit 7fe73e9

Browse files
Peter Martonmayurkale22
Peter Marton
authored andcommitted
fix(span): make child span clock relative to root span (#628)
* fix(span): make child span clock relative to root span * test(span): improve comment * test(span): fix
1 parent ad6c0d4 commit 7fe73e9

File tree

3 files changed

+27
-4
lines changed

3 files changed

+27
-4
lines changed

packages/opencensus-core/src/internal/clock.ts

+13-3
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,11 @@ export class Clock {
2727
/** The duration between start and end of the clock. */
2828
private diff: [number, number] = [0, 0];
2929

30-
/** Constructs a new SamplerImpl instance. */
31-
constructor() {
32-
this.startTimeLocal = new Date();
30+
/** Constructs a new Clock instance. */
31+
constructor(startTime?: Date) {
32+
// In some cases clocks need to be relative to other resources, passing a
33+
// startTime makes it possible.
34+
this.startTimeLocal = startTime || new Date();
3335
this.hrtimeLocal = process.hrtime();
3436
}
3537

@@ -42,6 +44,14 @@ export class Clock {
4244
this.endedLocal = true;
4345
}
4446

47+
/** Gets the current date from ellapsed milliseconds and start time. */
48+
get currentDate(): Date {
49+
const diff = process.hrtime(this.hrtimeLocal);
50+
const ns = diff[0] * 1e9 + diff[1];
51+
const ellapsed = ns / 1e6;
52+
return new Date(this.startTime.getTime() + ellapsed);
53+
}
54+
4555
/** Gets the duration of the clock. */
4656
get duration(): number {
4757
if (!this.endedLocal) {

packages/opencensus-core/src/trace/model/span.ts

+6-1
Original file line numberDiff line numberDiff line change
@@ -316,7 +316,12 @@ export class Span implements types.Span {
316316
);
317317
return;
318318
}
319-
this.clock = new Clock();
319+
// start child span's clock from root's current time to preserve integrity.
320+
if (this.parentSpan) {
321+
this.clock = new Clock(this.parentSpan.clock.currentDate);
322+
} else {
323+
this.clock = new Clock();
324+
}
320325
this.startedLocal = true;
321326
this.logger.debug('starting %s %o', this.className, {
322327
traceId: this.traceId,

packages/opencensus-core/test/test-span.ts

+8
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,14 @@ describe('Span', () => {
4747
const span = new Span(tracer, rootSpan);
4848
assert.ok(span instanceof Span);
4949
});
50+
51+
it('should use relative clock for child spans', () => {
52+
const rootSpan = new RootSpan(tracer, name, kind, traceId, parentSpanId);
53+
rootSpan.start();
54+
const span = new Span(tracer, rootSpan);
55+
span.start();
56+
assert.ok(rootSpan.startTime.getTime() <= span.startTime.getTime());
57+
});
5058
});
5159

5260
/**

0 commit comments

Comments
 (0)