3
3
import { DEFAULT_ENVIRONMENT , getCurrentHub } from '@sentry/core' ;
4
4
import type { DebugImage , Envelope , Event , StackFrame , StackParser } from '@sentry/types' ;
5
5
import type { Profile , ThreadCpuProfile } from '@sentry/types/src/profiling' ;
6
- import { forEachEnvelopeItem , GLOBAL_OBJ , logger , uuid4 } from '@sentry/utils' ;
6
+ import { browserPerformanceTimeOrigin , forEachEnvelopeItem , GLOBAL_OBJ , logger , uuid4 } from '@sentry/utils' ;
7
7
8
8
import { WINDOW } from '../helpers' ;
9
9
import type { JSSelfProfile , JSSelfProfileStack } from './jsSelfProfiling' ;
@@ -213,6 +213,13 @@ export function convertJSSelfProfileToSampledFormat(input: JSSelfProfile): Profi
213
213
214
214
// We assert samples.length > 0 above and timestamp should always be present
215
215
const start = input . samples [ 0 ] . timestamp ;
216
+ // The JS SDK might change it's time origin based on some heuristic (see See packages/utils/src/time.ts)
217
+ // when that happens, we need to ensure we are correcting the profile timings so the two timelines stay in sync.
218
+ // Since JS self profiling time origin is always initialized to performance.timeOrigin, we need to adjust for
219
+ // the drift between the SDK selected value and our profile time origin.
220
+ const origin =
221
+ typeof performance . timeOrigin === 'number' ? performance . timeOrigin : browserPerformanceTimeOrigin || 0 ;
222
+ const adjustForOriginChange = origin - ( browserPerformanceTimeOrigin || origin ) ;
216
223
217
224
for ( let i = 0 ; i < input . samples . length ; i ++ ) {
218
225
const jsSample = input . samples [ i ] ;
@@ -227,7 +234,7 @@ export function convertJSSelfProfileToSampledFormat(input: JSSelfProfile): Profi
227
234
228
235
profile [ 'samples' ] [ i ] = {
229
236
// convert ms timestamp to ns
230
- elapsed_since_start_ns : ( ( jsSample . timestamp - start ) * MS_TO_NS ) . toFixed ( 0 ) ,
237
+ elapsed_since_start_ns : ( ( jsSample . timestamp + adjustForOriginChange - start ) * MS_TO_NS ) . toFixed ( 0 ) ,
231
238
stack_id : EMPTY_STACK_ID ,
232
239
thread_id : THREAD_ID_STRING ,
233
240
} ;
@@ -260,7 +267,7 @@ export function convertJSSelfProfileToSampledFormat(input: JSSelfProfile): Profi
260
267
261
268
const sample : Profile [ 'profile' ] [ 'samples' ] [ 0 ] = {
262
269
// convert ms timestamp to ns
263
- elapsed_since_start_ns : ( ( jsSample . timestamp - start ) * MS_TO_NS ) . toFixed ( 0 ) ,
270
+ elapsed_since_start_ns : ( ( jsSample . timestamp + adjustForOriginChange - start ) * MS_TO_NS ) . toFixed ( 0 ) ,
264
271
stack_id : STACK_ID ,
265
272
thread_id : THREAD_ID_STRING ,
266
273
} ;
0 commit comments