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

PPI-165 : fix timestamp rounding issues and expose helpers for high res timestamps #179

Merged
merged 3 commits into from
Aug 1, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
45 changes: 30 additions & 15 deletions lib/src/sdk/platforms/web/time_providers/web_time_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,37 @@
// Licensed under the Apache License, Version 2.0. Please see https://github.com/Workiva/opentelemetry-dart/blob/master/LICENSE for more information

import 'dart:html';
import 'dart:js';

import 'package:fixnum/fixnum.dart';
import 'package:meta/meta.dart';

import '../../../../../sdk.dart' as sdk;
import '../../../time_providers/time_provider.dart';

Int64 msToNs(num n, {int? fractionDigits}) {
const nsPerMs = 1000 * 1000;
final whole = n.truncate();
if (fractionDigits == null) {
final frac = ((n - whole) * nsPerMs).round();
return Int64(whole * nsPerMs + frac);
}
final frac =
double.parse((n - whole).toStringAsFixed(fractionDigits)) * nsPerMs;
return Int64(whole) * nsPerMs + Int64(frac.round());
}

/// Time when navigation started or the service worker was started in
/// nanoseconds.
@experimental
final Int64 timeOrigin = msToNs(
window.performance.timeOrigin ?? window.performance.timing.navigationStart,
fractionDigits: 1);

/// Converts a high-resolution timestamp from the browser performance API to an
/// Int64 representing nanoseconds since Unix Epoch.
@experimental
Int64 fromDOMHighResTimeStamp(num ts) {
return timeOrigin + msToNs(ts);
}

/// BrowserTimeProvider retrieves high-resolution timestamps utilizing the
/// `window.performance` API.
Expand All @@ -17,23 +43,12 @@ import '../../../../../sdk.dart' as sdk;
/// Note that this time may be inaccurate if the executing system is suspended
/// for sleep. See https://github.com/open-telemetry/opentelemetry-js/issues/852
/// for more information.
class WebTimeProvider implements sdk.TimeProvider {
static final Int64 _timeOrigin = _fromDouble(
JsObject.fromBrowserObject(window)['performance']['timeOrigin'] ??
// fallback for browsers that don't support timeOrigin, like Dartium
window.performance.timing.navigationStart.toDouble());

/// Derive a time, in nanoseconds, from a floating-point time, in milliseconds.
static Int64 _fromDouble(double time) =>
Int64((time * sdk.TimeProvider.nanosecondsPerMillisecond).round());

class WebTimeProvider implements TimeProvider {
/// The current time, in nanoseconds since Unix Epoch.
///
/// Note that this time may be inaccurate if the executing system is suspended
/// for sleep. See https://github.com/open-telemetry/opentelemetry-js/issues/852
/// for more information.
@override
Int64 get now =>
// .now() returns an int in Dartium, requiring .toDouble()
_timeOrigin + _fromDouble(window.performance.now().toDouble());
Int64 get now => fromDOMHighResTimeStamp(window.performance.now());
}
4 changes: 1 addition & 3 deletions lib/src/sdk/time_providers/datetime_time_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,5 @@ import 'time_provider.dart';
/// DateTimeTimeProvider retrieves timestamps using DateTime.
class DateTimeTimeProvider implements TimeProvider {
@override
Int64 get now =>
Int64(DateTime.now().microsecondsSinceEpoch) *
TimeProvider.nanosecondsPerMicrosecond;
Int64 get now => Int64(DateTime.now().microsecondsSinceEpoch) * 1000;
}
2 changes: 2 additions & 0 deletions lib/src/sdk/time_providers/time_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@ import 'package:fixnum/fixnum.dart';
abstract class TimeProvider {
// The smallest increment that DateTime can report is in microseconds, while
// OpenTelemetry expects time in nanoseconds.
@Deprecated('This constant will be removed in 0.19.0 without replacement.')
static const int nanosecondsPerMicrosecond = 1000;

// window.performance API reports time in fractional milliseconds, while
// OpenTelemetry expects time in nanoseconds.
@Deprecated('This constant will be removed in 0.19.0 without replacement.')
static const int nanosecondsPerMillisecond = 1000000;

/// The current time, in nanoseconds since Unix Epoch.
Expand Down
2 changes: 1 addition & 1 deletion lib/web_sdk.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
// Licensed under the Apache License, Version 2.0. Please see https://github.com/Workiva/opentelemetry-dart/blob/master/LICENSE for more information

export 'src/sdk/platforms/web/time_providers/web_time_provider.dart'
show WebTimeProvider;
show fromDOMHighResTimeStamp, timeOrigin, WebTimeProvider;
export 'src/sdk/platforms/web/trace/web_tracer_provider.dart'
show WebTracerProvider;
47 changes: 25 additions & 22 deletions test/unit/sdk/platforms/web/web_time_provider_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,34 @@
// Licensed under the Apache License, Version 2.0. Please see https://github.com/Workiva/opentelemetry-dart/blob/master/LICENSE for more information

@TestOn('chrome')
import 'package:opentelemetry/api.dart' as api;
import 'package:opentelemetry/sdk.dart' as sdk;

import 'package:fixnum/fixnum.dart';
import 'package:opentelemetry/src/sdk/platforms/web/time_providers/web_time_provider.dart';
import 'package:opentelemetry/src/sdk/trace/span.dart';
import 'package:test/test.dart';

void main() {
test('records start and end times with browser performance API', () async {
final span = Span(
'testStartAndEndTimes',
api.SpanContext(api.TraceId([1, 2, 3]), api.SpanId([7, 8, 9]),
api.TraceFlags.none, api.TraceState.empty()),
api.SpanId([4, 5, 6]),
[],
WebTimeProvider(),
sdk.Resource([]),
sdk.InstrumentationScope(
'library_name', 'library_version', 'url://schema', []),
api.SpanKind.internal,
[],
sdk.SpanLimits(),
WebTimeProvider().now)
..end();

expect(span.endTime, isNotNull);
expect(span.startTime, lessThanOrEqualTo(span.endTime!));
group('msToNs', () {
test('msToNs rounds large fractions', () {
final cases = [
[809.2223347138977, Int64(809222335)],
[821.5999999046326, Int64(821600000)],
[1427.1999998092651, Int64(1427200000)],
];
for (final c in cases) {
final expected = c[1];
expect(msToNs(c[0] as double), expected);
}
});
test('msToNs rounds large wholes', () {
final cases = [
[1722291888610.5, Int64(17222918886105000) * 100],
[1722292170313.4, Int64(17222921703134000) * 100],
[1722292193622.1, Int64(17222921936221000) * 100],
];
for (final c in cases) {
final expected = c[1];
expect(msToNs(c[0] as double, fractionDigits: 1), expected);
}
});
});
}