Skip to content

Commit 8f187b1

Browse files
authored
chore: Improve OTEL hrtime processing (newrelic#3557)
1 parent 8386360 commit 8f187b1

File tree

2 files changed

+28
-7
lines changed

2 files changed

+28
-7
lines changed

lib/otel/normalize-timestamp.js

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,12 +42,7 @@ function normalizeTimestamp(input) {
4242
}
4343

4444
if (isTimeInputHrTime(input) === true) {
45-
// It's unclear why upstream tries to support a `process.hrtime()` value.
46-
// Such tuples are relative to an arbitrary point in time, not the Unix
47-
// epoch. So there's no way to determine an actual wall clock time and date
48-
// from such input. For lack of a better solution, we'll return the
49-
// current epoch in this case.
50-
return Date.now()
45+
return hrtimeToMilliseconds(input)
5146
}
5247

5348
if (Object.getPrototypeOf(input) === Date.prototype) {
@@ -57,3 +52,28 @@ function normalizeTimestamp(input) {
5752
// We don't know what they've given us, so just return the current time.
5853
return Date.now()
5954
}
55+
56+
const { performance } = require('node:perf_hooks')
57+
58+
/**
59+
* Converts a JS Open Telemetry hrtime tuple to milliseconds since the
60+
* standard epoch.
61+
*
62+
* @param {number[]} hrtime Upstream represents hrtime as `[seconds, nanoseconds]`.
63+
*
64+
* @returns {number} Milliseconds since standard epoch time.
65+
*/
66+
function hrtimeToMilliseconds(hrtime) {
67+
const seconds = hrtime[0]
68+
const nanoseconds = hrtime[1]
69+
70+
// Convert the seconds portion to milliseconds.
71+
const msSeconds = seconds * 1_000
72+
// Convert the nanoseconds portion to milliseconds.
73+
const msNanoseconds = nanoseconds / 1_000_000
74+
// At this point, we have the number of milliseconds since the application
75+
// was started.
76+
const msSinceStart = msSeconds + msNanoseconds
77+
78+
return Math.trunc(performance.timeOrigin + msSinceStart)
79+
}

test/unit/lib/otel/normalize-timestamp.test.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
const test = require('node:test')
99
const assert = require('node:assert')
1010
const { performance } = require('node:perf_hooks')
11+
const { hrTime } = require('@opentelemetry/core')
1112

1213
const normalizeTimestamp = require('#agentlib/otel/normalize-timestamp.js')
1314

@@ -43,7 +44,7 @@ test('normalizes performance.now', () => {
4344

4445
test('normalizes hrtime', () => {
4546
const dnow = Date.now()
46-
const input = process.hrtime()
47+
const input = hrTime()
4748
const found = normalizeTimestamp(input)
4849
assert.equal(found >= dnow, true)
4950
assert.equal(isNaN(new Date(found)), false)

0 commit comments

Comments
 (0)