UNPKG

@sentry/core

Version:
132 lines (131 loc) • 5.03 kB
import { safeDateNow, withRandomSafeContext } from "./randomSafeContext.js"; import { GLOBAL_OBJ } from "./worldwide.js"; // src/utils/time.ts const ONE_SECOND_IN_MS = 1e3; /** * If `performance.timeOrigin + performance.now()` and `Date.now()` differ by more than this, we correct the time origin. */ const CLOCK_DRIFT_THRESHOLD_MS = 1e3; /** * Max number of time origins we store. When we hit it, we drop the oldest one, except the page load origin, which * the pageload span uses. */ const MAX_TIME_ORIGIN_SEGMENTS = 100; /** * Returns a timestamp in seconds since the UNIX epoch using the Date API. */ function dateTimestampInSeconds() { return safeDateNow() / ONE_SECOND_IN_MS; } /** * All time origins of the page, oldest first. Empty until the first `timestampInSeconds` call, or if the Performance * API is unavailable. */ let _timeOriginSegments = []; /** * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not * support the API. * * Wrapping the native API works around differences in behavior from different browsers. */ function createUnixTimestampInSecondsFunc() { const { performance } = GLOBAL_OBJ; if (!performance?.now || !performance.timeOrigin) { if (performance?.now) _timeOriginSegments = [{ from: 0, origin: safeDateNow() - withRandomSafeContext(() => performance.now()) }]; return dateTimestampInSeconds; } let correctedTimeOrigin = performance.timeOrigin; _timeOriginSegments = [{ from: 0, origin: correctedTimeOrigin }]; let isFirstCall = true; let lastCheckedPerformanceNow = 0; return () => { return withRandomSafeContext(() => { const performanceNow = performance.now(); const dateNow = Date.now(); if (Math.abs(correctedTimeOrigin + performanceNow - dateNow) > CLOCK_DRIFT_THRESHOLD_MS) { correctedTimeOrigin = dateNow - performanceNow; if (isFirstCall) _timeOriginSegments = [{ from: 0, origin: correctedTimeOrigin }]; else { _timeOriginSegments.push({ from: lastCheckedPerformanceNow, origin: correctedTimeOrigin }); if (_timeOriginSegments.length > MAX_TIME_ORIGIN_SEGMENTS) _timeOriginSegments.splice(1, 1); } } isFirstCall = false; lastCheckedPerformanceNow = performanceNow; return (correctedTimeOrigin + performanceNow) / ONE_SECOND_IN_MS; }); }; } /** * Returns `performance.now()` in milliseconds, or `undefined` if the Performance API is unavailable. */ function safePerformanceNow() { const { performance } = GLOBAL_OBJ; return performance?.now ? withRandomSafeContext(() => performance.now()) : void 0; } let _cachedTimestampInSecondsFn; let _checkedForDriftInThisTask = false; /** * Converts a `performance.now()` based, relative time in milliseconds (e.g. a `PerformanceEntry`'s `startTime`) * to a UNIX timestamp in seconds, matching {@link timestampInSeconds}. * * Corrects for clock drift via browserPerformanceTimeOrigin(). * * Pass `entryStartTimeInMs` (also a `performance.now()` based time) to use the time origin that was valid at the entry's * start. Use it for all timings of one entry, so its duration stays correct. * * Returns `undefined` if the Performance API is unavailable. */ function performanceTimeToSeconds(monotonicTimeInMs, entryStartTimeInMs = monotonicTimeInMs) { const origin = browserPerformanceTimeOrigin(entryStartTimeInMs); return origin == null ? void 0 : (origin + monotonicTimeInMs) / ONE_SECOND_IN_MS; } /** * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the * availability of the Performance API. * * If the Performance API time and `Date.now()` differ by more than {@link CLOCK_DRIFT_THRESHOLD_MS} (e.g. after the * device slept), the time origin is corrected based on `Date.now()`. * See https://github.com/getsentry/sentry-javascript/issues/2590. */ function timestampInSeconds() { return (_cachedTimestampInSecondsFn ?? (_cachedTimestampInSecondsFn = createUnixTimestampInSecondsFunc()))(); } /** * Returns the time origin in milliseconds that was valid at the given `performance.now()` time. Defaults to the page * load origin. * * Pass the time you want to convert, so entries that are reported late (e.g. INP on pagehide) are not shifted by a * drift that happened after they were recorded. Use the same time for all timings of one entry to keep its duration. * * Returns `undefined` if the Performance API is unavailable. */ function browserPerformanceTimeOrigin(monotonicTimeInMs = 0) { if (!_checkedForDriftInThisTask) { _checkedForDriftInThisTask = true; Promise.resolve().then(() => { _checkedForDriftInThisTask = false; }); timestampInSeconds(); } let segment; for (const candidate of _timeOriginSegments) { if (segment && candidate.from > monotonicTimeInMs) break; segment = candidate; } return segment?.origin; } export { browserPerformanceTimeOrigin, dateTimestampInSeconds, performanceTimeToSeconds, safePerformanceNow, timestampInSeconds }; //# sourceMappingURL=time.js.map