Skip to content
Closed
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
5 changes: 4 additions & 1 deletion packages/browser-utils/src/web-vitals/spans.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import type { Client, Span, SpanAttributes } from '@sentry/core';
import {
browserPerformanceTimeOrigin,
correctedPerformanceTimeOrigin,
debug,
getActiveSpan,
getClient,
Expand Down Expand Up @@ -409,8 +410,10 @@ export function _sendInpSpan(
// A web vital span carries the metric, not a real interaction timing, so an INP without an entry
// is still worth reporting. It just has no element or interaction type to describe, and is placed
// at the start of the navigation it belongs to rather than at the interaction.
// INP reports on pagehide, potentially hours after the origin cached at init, so the corrected origin is used to stay
// on the same timeline as span and event timestamps.
const startTime = msToSec(
(browserPerformanceTimeOrigin() as number) + (entry?.startTime ?? metric?.navigationStartTime ?? 0),
(correctedPerformanceTimeOrigin() as number) + (entry?.startTime ?? metric?.navigationStartTime ?? 0),
);
const duration = msToSec(inpValue);
// An INP without an entry has no interaction type to report. It still has to land inside the
Expand Down
4 changes: 4 additions & 0 deletions packages/browser-utils/test/web-vitals/spans.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ vi.mock('@sentry/core', async () => {
return {
...actual,
browserPerformanceTimeOrigin: vi.fn(),
correctedPerformanceTimeOrigin: vi.fn(),
timestampInSeconds: vi.fn(),
getCurrentScope: vi.fn(),
getClient: vi.fn(),
Expand Down Expand Up @@ -612,6 +613,7 @@ describe('_sendInpSpan', () => {
beforeEach(() => {
vi.mocked(SentryCore.getCurrentScope).mockReturnValue(mockScope as any);
vi.mocked(SentryCore.browserPerformanceTimeOrigin).mockReturnValue(1000);
vi.mocked(SentryCore.correctedPerformanceTimeOrigin).mockReturnValue(1000);
vi.mocked(htmlTreeAsString).mockReturnValue('<button>');
vi.mocked(SentryCoreBrowser.startInactiveSpan).mockReturnValue(mockSpan as any);
vi.mocked(SentryCore.getActiveSpan).mockReturnValue(undefined);
Expand Down Expand Up @@ -792,6 +794,7 @@ describe('trackInpAsSpan', () => {

beforeEach(() => {
vi.mocked(SentryCore.browserPerformanceTimeOrigin).mockReturnValue(1000);
vi.mocked(SentryCore.correctedPerformanceTimeOrigin).mockReturnValue(1000);
vi.mocked(SentryCore.getCurrentScope).mockReturnValue(mockScope as any);
vi.mocked(SentryCore.getActiveSpan).mockReturnValue(undefined);
vi.mocked(SentryCoreBrowser.startInactiveSpan).mockReturnValue({ end: vi.fn() } as any);
Expand Down Expand Up @@ -890,6 +893,7 @@ describe('soft navigation web vitals', () => {
supportedEntryTypes: ['largest-contentful-paint', 'layout-shift', 'soft-navigation'],
});
vi.mocked(SentryCore.browserPerformanceTimeOrigin).mockReturnValue(1000);
vi.mocked(SentryCore.correctedPerformanceTimeOrigin).mockReturnValue(1000);
vi.mocked(SentryCore.getCurrentScope).mockReturnValue(mockScope as any);
vi.mocked(SentryCoreBrowser.startInactiveSpan).mockReturnValue({ end: vi.fn() } as any);
vi.mocked(SentryCore.spanToJSON).mockImplementation(
Expand Down
4 changes: 2 additions & 2 deletions packages/browser/src/profiling/utils.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable max-lines */
import type { Client, ContinuousThreadCpuProfile, DebugImage, ProfileChunk, Span } from '@sentry/core';
import {
browserPerformanceTimeOrigin,
correctedPerformanceTimeOrigin,
debug,
getClient,
getDebugImagesForResources,
Expand Down Expand Up @@ -148,7 +148,7 @@ function convertToContinuousProfile(input: {
}

// Align timestamps to SDK time origin to match span/event timelines
const perfOrigin = browserPerformanceTimeOrigin();
const perfOrigin = correctedPerformanceTimeOrigin();
const origin = typeof performance.timeOrigin === 'number' ? performance.timeOrigin : perfOrigin || 0;
const adjustForOriginChange = origin - (perfOrigin || origin);

Expand Down
7 changes: 6 additions & 1 deletion packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,12 @@ export {
supportsReferrerPolicy,
} from './utils/supports';
export { SyncPromise, rejectedSyncPromise, resolvedSyncPromise } from './utils/syncpromise';
export { browserPerformanceTimeOrigin, dateTimestampInSeconds, timestampInSeconds } from './utils/time';
export {
browserPerformanceTimeOrigin,
correctedPerformanceTimeOrigin,
dateTimestampInSeconds,
timestampInSeconds,
} from './utils/time';
export {
TRACEPARENT_REGEXP,
extractTraceparentData,
Expand Down
24 changes: 22 additions & 2 deletions packages/core/src/utils/time.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@ export function dateTimestampInSeconds(): number {
return safeDateNow() / ONE_SECOND_IN_MS;
}

/**
* The time origin `timestampInSeconds` currently maps the monotonic clock against, kept in sync with the corrections it
* applies. `undefined` until the first `timestampInSeconds` call, and whenever the Performance API is unavailable.
*/
let _correctedTimeOrigin: number | undefined;

/**
* Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not
* support the API.
Expand All @@ -47,7 +53,7 @@ function createUnixTimestampInSecondsFunc(): () => number {

// performance.now() is a monotonic clock, which means it starts at 0 when the process begins. To get the current
// wall clock time (actual UNIX timestamp), we need to add the starting time origin and the current time elapsed.
let timeOrigin = performance.timeOrigin;
let timeOrigin = (_correctedTimeOrigin = performance.timeOrigin);

return () => {
return withRandomSafeContext(() => {
Expand All @@ -66,7 +72,7 @@ function createUnixTimestampInSecondsFunc(): () => number {
// See: https://github.com/mdn/content/issues/4713
// See: https://dev.to/noamr/when-a-millisecond-is-not-a-millisecond-3h6
if (Math.abs(timeOrigin + performanceNow - dateNow) > CLOCK_DRIFT_THRESHOLD_MS) {
timeOrigin = dateNow - performanceNow;
timeOrigin = _correctedTimeOrigin = dateNow - performanceNow;
}

return (timeOrigin + performanceNow) / ONE_SECOND_IN_MS;
Expand All @@ -76,6 +82,20 @@ function createUnixTimestampInSecondsFunc(): () => number {

let _cachedTimestampInSeconds: (() => number) | undefined;

/**
* Returns the time origin (in milliseconds since the UNIX epoch) that {@link timestampInSeconds} currently maps
* `performance.now()` against, including any correction it has applied for clock drift.
*
* Use this over {@link browserPerformanceTimeOrigin} when converting a `PerformanceEntry`'s monotonic `startTime` to
* wall clock time at the moment the entry is observed, so the result shares a timeline with span and event timestamps.
* Returns `undefined` if the Performance API is unavailable, in which case monotonic timestamps cannot be converted.
*/
export function correctedPerformanceTimeOrigin(): number | undefined {
// The origin is only populated once `timestampInSeconds` has resolved which clock source to use.
timestampInSeconds();
return _correctedTimeOrigin;
}

/**
* Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the
* availability of the Performance API.
Expand Down
81 changes: 78 additions & 3 deletions packages/core/test/lib/utils/time.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,17 @@ async function getFreshPerformanceTimeOrigin() {

let freshImportCounter = 0;

async function getFreshTimestampInSeconds(): Promise<() => number> {
async function getFreshTimeModule(): Promise<{
timestampInSeconds: () => number;
correctedPerformanceTimeOrigin: () => number | undefined;
}> {
// A counter rather than `Date.now()`: these tests run under fake timers, which freeze the wall clock and would
// otherwise hand out a cached module.
const timeModule = await import(`../../../src/utils/time?update=${freshImportCounter++}`);
return timeModule.timestampInSeconds;
return import(`../../../src/utils/time?update=${freshImportCounter++}`);
}

async function getFreshTimestampInSeconds(): Promise<() => number> {
return (await getFreshTimeModule()).timestampInSeconds;
}

const RELIABLE_THRESHOLD_MS = 300_000;
Expand Down Expand Up @@ -180,6 +186,75 @@ describe('timestampInSeconds', () => {
});
});

describe('correctedPerformanceTimeOrigin', () => {
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
});

it('returns `performance.timeOrigin` while the clocks agree', async () => {
const currentTimeMs = 1767778040866;
const timeSincePageloadMs = 1_000;
const timeOrigin = currentTimeMs - timeSincePageloadMs;

vi.useFakeTimers();
vi.setSystemTime(new Date(currentTimeMs));
vi.stubGlobal('performance', { timeOrigin, now: () => timeSincePageloadMs });

const { correctedPerformanceTimeOrigin } = await getFreshTimeModule();

expect(correctedPerformanceTimeOrigin()).toBe(timeOrigin);
});

it('returns the corrected origin after clock drift, without a prior `timestampInSeconds` call', async () => {
const currentTimeMs = 1767778040866;
const timeSincePageloadMs = 1_000;
const sleepDurationMs = RELIABLE_THRESHOLD_MS + 60_000;

vi.useFakeTimers();
vi.setSystemTime(new Date(currentTimeMs));
vi.stubGlobal('performance', {
timeOrigin: currentTimeMs - timeSincePageloadMs,
now: () => timeSincePageloadMs,
});

const { correctedPerformanceTimeOrigin } = await getFreshTimeModule();

vi.setSystemTime(new Date(currentTimeMs + sleepDurationMs));

expect(correctedPerformanceTimeOrigin()).toBe(currentTimeMs + sleepDurationMs - timeSincePageloadMs);
});

it('stays on the same timeline as `timestampInSeconds`', async () => {
const currentTimeMs = 1767778040866;
const timeSincePageloadMs = 1_000;
const sleepDurationMs = RELIABLE_THRESHOLD_MS + 60_000;

vi.useFakeTimers();
vi.setSystemTime(new Date(currentTimeMs));
vi.stubGlobal('performance', {
timeOrigin: currentTimeMs - timeSincePageloadMs,
now: () => timeSincePageloadMs,
});

const { correctedPerformanceTimeOrigin, timestampInSeconds } = await getFreshTimeModule();

vi.setSystemTime(new Date(currentTimeMs + sleepDurationMs));

// Converting the current `performance.now()` against the origin must yield the same wall clock time that
// `timestampInSeconds` reports, otherwise perf entries and spans land on diverging timelines.
expect((correctedPerformanceTimeOrigin() as number) + timeSincePageloadMs).toBe(timestampInSeconds() * 1000);
});

it('returns `undefined` if the performance API is unavailable', async () => {
vi.stubGlobal('performance', undefined);

const { correctedPerformanceTimeOrigin } = await getFreshTimeModule();

expect(correctedPerformanceTimeOrigin()).toBeUndefined();
});
});

describe('browserPerformanceTimeOrigin', () => {
it('returns `performance.timeOrigin` if it is available and reliable', async () => {
const timeOrigin = await getFreshPerformanceTimeOrigin();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { browserPerformanceTimeOrigin } from '@sentry/core';
import { correctedPerformanceTimeOrigin } from '@sentry/core';
import { record } from '@sentry/rrweb';
import { WINDOW } from '../constants';
import type {
Expand Down Expand Up @@ -87,9 +87,9 @@ function createPerformanceEntry(entry: AllPerformanceEntry): ReplayPerformanceEn
}

function getAbsoluteTime(time: number): number {
// browserPerformanceTimeOrigin can be undefined if `performance` or
// correctedPerformanceTimeOrigin can be undefined if `performance` or
// `performance.now` doesn't exist, but this is already checked by this integration
return ((browserPerformanceTimeOrigin() || WINDOW.performance.timeOrigin) + time) / 1000;
return ((correctedPerformanceTimeOrigin() || WINDOW.performance.timeOrigin) + time) / 1000;
}

function createPaintEntry(entry: PerformancePaintTiming): ReplayPerformanceEntry<PaintData> {
Expand Down
Loading