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

Commit

Permalink
fix(span): make child span clock relative to root span (#628)
Browse files Browse the repository at this point in the history
* fix(span): make child span clock relative to root span

* test(span): improve comment

* test(span): fix
  • Loading branch information
Peter Marton authored and mayurkale22 committed Jul 19, 2019
1 parent ad6c0d4 commit 7fe73e9
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 4 deletions.
16 changes: 13 additions & 3 deletions packages/opencensus-core/src/internal/clock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,11 @@ export class Clock {
/** The duration between start and end of the clock. */
private diff: [number, number] = [0, 0];

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

Expand All @@ -42,6 +44,14 @@ export class Clock {
this.endedLocal = true;
}

/** Gets the current date from ellapsed milliseconds and start time. */
get currentDate(): Date {
const diff = process.hrtime(this.hrtimeLocal);
const ns = diff[0] * 1e9 + diff[1];
const ellapsed = ns / 1e6;
return new Date(this.startTime.getTime() + ellapsed);
}

/** Gets the duration of the clock. */
get duration(): number {
if (!this.endedLocal) {
Expand Down
7 changes: 6 additions & 1 deletion packages/opencensus-core/src/trace/model/span.ts
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,12 @@ export class Span implements types.Span {
);
return;
}
this.clock = new Clock();
// start child span's clock from root's current time to preserve integrity.
if (this.parentSpan) {
this.clock = new Clock(this.parentSpan.clock.currentDate);
} else {
this.clock = new Clock();
}
this.startedLocal = true;
this.logger.debug('starting %s %o', this.className, {
traceId: this.traceId,
Expand Down
8 changes: 8 additions & 0 deletions packages/opencensus-core/test/test-span.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@ describe('Span', () => {
const span = new Span(tracer, rootSpan);
assert.ok(span instanceof Span);
});

it('should use relative clock for child spans', () => {
const rootSpan = new RootSpan(tracer, name, kind, traceId, parentSpanId);
rootSpan.start();
const span = new Span(tracer, rootSpan);
span.start();
assert.ok(rootSpan.startTime.getTime() <= span.startTime.getTime());
});
});

/**
Expand Down

0 comments on commit 7fe73e9

Please sign in to comment.