-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathreplay.ts
1404 lines (1189 loc) · 43.9 KB
/
replay.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable max-lines */ // TODO: We might want to split this file up
import { EventType, record } from '@sentry-internal/rrweb';
import type { ReplayRecordingMode, Span } from '@sentry/core';
import { SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, getActiveSpan, getClient, getRootSpan, spanToJSON } from '@sentry/core';
import {
BUFFER_CHECKOUT_TIME,
SESSION_IDLE_EXPIRE_DURATION,
SESSION_IDLE_PAUSE_DURATION,
SLOW_CLICK_SCROLL_TIMEOUT,
SLOW_CLICK_THRESHOLD,
WINDOW,
MUTATION_DEBOUNCE_TIME,
} from './constants';
import { ClickDetector } from './coreHandlers/handleClick';
import { handleKeyboardEvent } from './coreHandlers/handleKeyboardEvent';
import { setupPerformanceObserver } from './coreHandlers/performanceObserver';
import { DEBUG_BUILD } from './debug-build';
import { createEventBuffer } from './eventBuffer';
import { clearSession } from './session/clearSession';
import { loadOrCreateSession } from './session/loadOrCreateSession';
import { saveSession } from './session/saveSession';
import { shouldRefreshSession } from './session/shouldRefreshSession';
import type {
AddEventResult,
AddUpdateCallback,
AllPerformanceEntry,
AllPerformanceEntryData,
EventBuffer,
InternalEventContext,
PopEventContext,
RecordingEvent,
RecordingOptions,
ReplayBreadcrumbFrame,
ReplayCanvasIntegrationOptions,
ReplayContainer as ReplayContainerInterface,
ReplayPerformanceEntry,
ReplayPluginOptions,
SendBufferedReplayOptions,
Session,
SlowClickConfig,
Timeouts,
} from './types';
import { ReplayEventTypeCustom } from './types';
import { addEvent, addEventSync } from './util/addEvent';
import { addGlobalListeners } from './util/addGlobalListeners';
import { addMemoryEntry } from './util/addMemoryEntry';
import { createBreadcrumb } from './util/createBreadcrumb';
import { createPerformanceEntries } from './util/createPerformanceEntries';
import { createPerformanceSpans } from './util/createPerformanceSpans';
import { debounce } from './util/debounce';
import { getRecordingSamplingOptions } from './util/getRecordingSamplingOptions';
import { getHandleRecordingEmit } from './util/handleRecordingEmit';
import { isExpired } from './util/isExpired';
import { isSessionExpired } from './util/isSessionExpired';
import { logger } from './util/logger';
import { resetReplayIdOnDynamicSamplingContext } from './util/resetReplayIdOnDynamicSamplingContext';
import { sendReplay } from './util/sendReplay';
import { RateLimitError } from './util/sendReplayRequest';
import type { SKIPPED } from './util/throttle';
import { THROTTLED, throttle } from './util/throttle';
/**
* The main replay container class, which holds all the state and methods for recording and sending replays.
*/
export class ReplayContainer implements ReplayContainerInterface {
public eventBuffer: EventBuffer | null;
public performanceEntries: AllPerformanceEntry[];
public replayPerformanceEntries: ReplayPerformanceEntry<AllPerformanceEntryData>[];
public session: Session | undefined;
public clickDetector: ClickDetector | undefined;
/**
* Recording can happen in one of two modes:
* - session: Record the whole session, sending it continuously
* - buffer: Always keep the last 60s of recording, requires:
* - having replaysOnErrorSampleRate > 0 to capture replay when an error occurs
* - or calling `flush()` to send the replay
*/
public recordingMode: ReplayRecordingMode;
/**
* The current or last active span.
* This is only available when performance is enabled.
*/
public lastActiveSpan?: Span;
/**
* These are here so we can overwrite them in tests etc.
* @hidden
*/
public readonly timeouts: Timeouts;
/** The replay has to be manually started, because no sample rate (neither session or error) was provided. */
private _requiresManualStart: boolean;
private _throttledAddEvent: (
event: RecordingEvent,
isCheckout?: boolean,
) => typeof THROTTLED | typeof SKIPPED | Promise<AddEventResult | null>;
/**
* Options to pass to `rrweb.record()`
*/
private readonly _recordingOptions: RecordingOptions;
private readonly _options: ReplayPluginOptions;
private _performanceCleanupCallback?: () => void;
private _debouncedFlush: ReturnType<typeof debounce>;
private _flushLock: Promise<unknown> | undefined;
/**
* Timestamp of the last user activity. This lives across sessions.
*/
private _lastActivity: number;
/**
* Is the integration currently active?
*/
private _isEnabled: boolean;
/**
* Paused is a state where:
* - DOM Recording is not listening at all
* - Nothing will be added to event buffer (e.g. core SDK events)
*/
private _isPaused: boolean;
/**
* Have we attached listeners to the core SDK?
* Note we have to track this as there is no way to remove instrumentation handlers.
*/
private _hasInitializedCoreListeners: boolean;
/**
* Function to stop recording
*/
private _stopRecording: ReturnType<typeof record> | undefined;
private _context: InternalEventContext;
/**
* Internal use for canvas recording options
*/
private _canvas: ReplayCanvasIntegrationOptions | undefined;
/**
* Handle when visibility of the page content changes. Opening a new tab will
* cause the state to change to hidden because of content of current page will
* be hidden. Likewise, moving a different window to cover the contents of the
* page will also trigger a change to a hidden state.
*/
private _handleVisibilityChange: () => void;
/**
* Handle when page is blurred
*/
private _handleWindowBlur: () => void;
/**
* Handle when page is focused
*/
private _handleWindowFocus: () => void;
/** Ensure page remains active when a key is pressed. */
private _handleKeyboardEvent: (event: KeyboardEvent) => void;
/**
* Map to track the history for DOM node mutations
*/
private _lastMutationMap: WeakMap<
Node,
{
timestamp: number;
fingerprint: string;
}
>;
public constructor({
options,
recordingOptions,
}: {
options: ReplayPluginOptions;
recordingOptions: RecordingOptions;
}) {
this.eventBuffer = null;
this.performanceEntries = [];
this.replayPerformanceEntries = [];
this.recordingMode = 'session';
this.timeouts = {
sessionIdlePause: SESSION_IDLE_PAUSE_DURATION,
sessionIdleExpire: SESSION_IDLE_EXPIRE_DURATION,
} as const;
this._lastActivity = Date.now();
this._isEnabled = false;
this._isPaused = false;
this._requiresManualStart = false;
this._hasInitializedCoreListeners = false;
this._context = {
errorIds: new Set(),
traceIds: new Set(),
urls: [],
initialTimestamp: Date.now(),
initialUrl: '',
};
this._recordingOptions = recordingOptions;
this._options = options;
this._debouncedFlush = debounce(() => this._flush(), this._options.flushMinDelay, {
maxWait: this._options.flushMaxDelay,
});
this._throttledAddEvent = throttle(
(event: RecordingEvent, isCheckout?: boolean) => addEvent(this, event, isCheckout),
// Max 300 events...
300,
// ... per 5s
5,
);
const { slowClickTimeout, slowClickIgnoreSelectors } = this.getOptions();
const slowClickConfig: SlowClickConfig | undefined = slowClickTimeout
? {
threshold: Math.min(SLOW_CLICK_THRESHOLD, slowClickTimeout),
timeout: slowClickTimeout,
scrollTimeout: SLOW_CLICK_SCROLL_TIMEOUT,
ignoreSelector: slowClickIgnoreSelectors ? slowClickIgnoreSelectors.join(',') : '',
}
: undefined;
if (slowClickConfig) {
this.clickDetector = new ClickDetector(this, slowClickConfig);
}
// Configure replay logger w/ experimental options
if (DEBUG_BUILD) {
const experiments = options._experiments;
logger.setConfig({
captureExceptions: !!experiments.captureExceptions,
traceInternals: !!experiments.traceInternals,
});
}
// We set these handler properties as class properties, to make binding/unbinding them easier
this._handleVisibilityChange = () => {
if (WINDOW.document.visibilityState === 'visible') {
this._doChangeToForegroundTasks();
} else {
this._doChangeToBackgroundTasks();
}
};
/**
* Handle when page is blurred
*/
this._handleWindowBlur = () => {
const breadcrumb = createBreadcrumb({
category: 'ui.blur',
});
// Do not count blur as a user action -- it's part of the process of them
// leaving the page
this._doChangeToBackgroundTasks(breadcrumb);
};
this._handleWindowFocus = () => {
const breadcrumb = createBreadcrumb({
category: 'ui.focus',
});
// Do not count focus as a user action -- instead wait until they focus and
// interactive with page
this._doChangeToForegroundTasks(breadcrumb);
};
/** Ensure page remains active when a key is pressed. */
this._handleKeyboardEvent = (event: KeyboardEvent) => {
handleKeyboardEvent(this, event);
};
if (options._experiments.dropRepetitiveMutations) {
this._lastMutationMap = new WeakMap();
}
}
/** Get the event context. */
public getContext(): InternalEventContext {
return this._context;
}
/** If recording is currently enabled. */
public isEnabled(): boolean {
return this._isEnabled;
}
/** If recording is currently paused. */
public isPaused(): boolean {
return this._isPaused;
}
/**
* Determine if canvas recording is enabled
*/
public isRecordingCanvas(): boolean {
return Boolean(this._canvas);
}
/** Get the replay integration options. */
public getOptions(): ReplayPluginOptions {
return this._options;
}
/** A wrapper to conditionally capture exceptions. */
public handleException(error: unknown): void {
DEBUG_BUILD && logger.exception(error);
if (this._options.onError) {
this._options.onError(error);
}
}
/**
* Initializes the plugin based on sampling configuration. Should not be
* called outside of constructor.
*/
public initializeSampling(previousSessionId?: string): void {
const { errorSampleRate, sessionSampleRate } = this._options;
// If neither sample rate is > 0, then do nothing - user will need to call one of
// `start()` or `startBuffering` themselves.
const requiresManualStart = errorSampleRate <= 0 && sessionSampleRate <= 0;
this._requiresManualStart = requiresManualStart;
if (requiresManualStart) {
return;
}
// Otherwise if there is _any_ sample rate set, try to load an existing
// session, or create a new one.
this._initializeSessionForSampling(previousSessionId);
if (!this.session) {
// This should not happen, something wrong has occurred
DEBUG_BUILD && logger.exception(new Error('Unable to initialize and create session'));
return;
}
if (this.session.sampled === false) {
// This should only occur if `errorSampleRate` is 0 and was unsampled for
// session-based replay. In this case there is nothing to do.
return;
}
// If segmentId > 0, it means we've previously already captured this session
// In this case, we still want to continue in `session` recording mode
this.recordingMode = this.session.sampled === 'buffer' && this.session.segmentId === 0 ? 'buffer' : 'session';
DEBUG_BUILD && logger.infoTick(`Starting replay in ${this.recordingMode} mode`);
this._initializeRecording();
}
/**
* Start a replay regardless of sampling rate. Calling this will always
* create a new session. Will log a message if replay is already in progress.
*
* Creates or loads a session, attaches listeners to varying events (DOM,
* _performanceObserver, Recording, Sentry SDK, etc)
*/
public start(): void {
if (this._isEnabled && this.recordingMode === 'session') {
DEBUG_BUILD && logger.info('Recording is already in progress');
return;
}
if (this._isEnabled && this.recordingMode === 'buffer') {
DEBUG_BUILD && logger.info('Buffering is in progress, call `flush()` to save the replay');
return;
}
DEBUG_BUILD && logger.infoTick('Starting replay in session mode');
// Required as user activity is initially set in
// constructor, so if `start()` is called after
// session idle expiration, a replay will not be
// created due to an idle timeout.
this._updateUserActivity();
const session = loadOrCreateSession(
{
maxReplayDuration: this._options.maxReplayDuration,
sessionIdleExpire: this.timeouts.sessionIdleExpire,
},
{
stickySession: this._options.stickySession,
// This is intentional: create a new session-based replay when calling `start()`
sessionSampleRate: 1,
allowBuffering: false,
},
);
this.session = session;
this._initializeRecording();
}
/**
* Start replay buffering. Buffers until `flush()` is called or, if
* `replaysOnErrorSampleRate` > 0, an error occurs.
*/
public startBuffering(): void {
if (this._isEnabled) {
DEBUG_BUILD && logger.info('Buffering is in progress, call `flush()` to save the replay');
return;
}
DEBUG_BUILD && logger.infoTick('Starting replay in buffer mode');
const session = loadOrCreateSession(
{
sessionIdleExpire: this.timeouts.sessionIdleExpire,
maxReplayDuration: this._options.maxReplayDuration,
},
{
stickySession: this._options.stickySession,
sessionSampleRate: 0,
allowBuffering: true,
},
);
this.session = session;
this.recordingMode = 'buffer';
this._initializeRecording();
}
/**
* Start recording.
*
* Note that this will cause a new DOM checkout
*/
public startRecording(): void {
try {
const canvasOptions = this._canvas;
this._stopRecording = record({
...this._recordingOptions,
// When running in error sampling mode, we need to overwrite `checkoutEveryNms`
// Without this, it would record forever, until an error happens, which we don't want
// instead, we'll always keep the last 60 seconds of replay before an error happened
...(this.recordingMode === 'buffer'
? { checkoutEveryNms: BUFFER_CHECKOUT_TIME }
: // Otherwise, use experimental option w/ min checkout time of 6 minutes
// This is to improve playback seeking as there could potentially be
// less mutations to process in the worse cases.
//
// checkout by "N" events is probably ideal, but means we have less
// control about the number of checkouts we make (which generally
// increases replay size)
this._options._experiments.continuousCheckout && {
// Minimum checkout time is 6 minutes
checkoutEveryNms: Math.max(360_000, this._options._experiments.continuousCheckout),
}),
emit: getHandleRecordingEmit(this),
...getRecordingSamplingOptions(),
onMutation: this._onMutationHandler.bind(this),
...(canvasOptions
? {
recordCanvas: canvasOptions.recordCanvas,
getCanvasManager: canvasOptions.getCanvasManager,
sampling: canvasOptions.sampling,
dataURLOptions: canvasOptions.dataURLOptions,
}
: {}),
});
} catch (err) {
this.handleException(err);
}
}
/**
* Stops the recording, if it was running.
*
* Returns true if it was previously stopped, or is now stopped,
* otherwise false.
*/
public stopRecording(): boolean {
try {
if (this._stopRecording) {
this._stopRecording();
this._stopRecording = undefined;
}
return true;
} catch (err) {
this.handleException(err);
return false;
}
}
/**
* Currently, this needs to be manually called (e.g. for tests). Sentry SDK
* does not support a teardown
*/
public async stop({ forceFlush = false, reason }: { forceFlush?: boolean; reason?: string } = {}): Promise<void> {
if (!this._isEnabled) {
return;
}
// We can't move `_isEnabled` after awaiting a flush, otherwise we can
// enter into an infinite loop when `stop()` is called while flushing.
this._isEnabled = false;
try {
DEBUG_BUILD && logger.info(`Stopping Replay${reason ? ` triggered by ${reason}` : ''}`);
resetReplayIdOnDynamicSamplingContext();
this._removeListeners();
this.stopRecording();
this._debouncedFlush.cancel();
// See comment above re: `_isEnabled`, we "force" a flush, ignoring the
// `_isEnabled` state of the plugin since it was disabled above.
if (forceFlush) {
await this._flush({ force: true });
}
// After flush, destroy event buffer
this.eventBuffer?.destroy();
this.eventBuffer = null;
// Clear session from session storage, note this means if a new session
// is started after, it will not have `previousSessionId`
clearSession(this);
} catch (err) {
this.handleException(err);
}
}
/**
* Pause some replay functionality. See comments for `_isPaused`.
* This differs from stop as this only stops DOM recording, it is
* not as thorough of a shutdown as `stop()`.
*/
public pause(): void {
if (this._isPaused) {
return;
}
this._isPaused = true;
this.stopRecording();
DEBUG_BUILD && logger.info('Pausing replay');
}
/**
* Resumes recording, see notes for `pause().
*
* Note that calling `startRecording()` here will cause a
* new DOM checkout.`
*/
public resume(): void {
if (!this._isPaused || !this._checkSession()) {
return;
}
this._isPaused = false;
this.startRecording();
DEBUG_BUILD && logger.info('Resuming replay');
}
/**
* If not in "session" recording mode, flush event buffer which will create a new replay.
* Unless `continueRecording` is false, the replay will continue to record and
* behave as a "session"-based replay.
*
* Otherwise, queue up a flush.
*/
public async sendBufferedReplayOrFlush({ continueRecording = true }: SendBufferedReplayOptions = {}): Promise<void> {
if (this.recordingMode === 'session') {
return this.flushImmediate();
}
const activityTime = Date.now();
DEBUG_BUILD && logger.info('Converting buffer to session');
// Allow flush to complete before resuming as a session recording, otherwise
// the checkout from `startRecording` may be included in the payload.
// Prefer to keep the error replay as a separate (and smaller) segment
// than the session replay.
await this.flushImmediate();
const hasStoppedRecording = this.stopRecording();
if (!continueRecording || !hasStoppedRecording) {
return;
}
// To avoid race conditions where this is called multiple times, we check here again that we are still buffering
if ((this.recordingMode as ReplayRecordingMode) === 'session') {
return;
}
// Re-start recording in session-mode
this.recordingMode = 'session';
// Once this session ends, we do not want to refresh it
if (this.session) {
this._updateUserActivity(activityTime);
this._updateSessionActivity(activityTime);
this._maybeSaveSession();
}
this.startRecording();
}
/**
* We want to batch uploads of replay events. Save events only if
* `<flushMinDelay>` milliseconds have elapsed since the last event
* *OR* if `<flushMaxDelay>` milliseconds have elapsed.
*
* Accepts a callback to perform side-effects and returns true to stop batch
* processing and hand back control to caller.
*/
public addUpdate(cb: AddUpdateCallback): void {
// We need to always run `cb` (e.g. in the case of `this.recordingMode == 'buffer'`)
const cbResult = cb();
// If this option is turned on then we will only want to call `flush`
// explicitly
if (this.recordingMode === 'buffer') {
return;
}
// If callback is true, we do not want to continue with flushing -- the
// caller will need to handle it.
if (cbResult === true) {
return;
}
// addUpdate is called quite frequently - use _debouncedFlush so that it
// respects the flush delays and does not flush immediately
this._debouncedFlush();
}
/**
* Updates the user activity timestamp and resumes recording. This should be
* called in an event handler for a user action that we consider as the user
* being "active" (e.g. a mouse click).
*/
public triggerUserActivity(): void {
this._updateUserActivity();
// This case means that recording was once stopped due to inactivity.
// Ensure that recording is resumed.
if (!this._stopRecording) {
// Create a new session, otherwise when the user action is flushed, it
// will get rejected due to an expired session.
if (!this._checkSession()) {
return;
}
// Note: This will cause a new DOM checkout
this.resume();
return;
}
// Otherwise... recording was never suspended, continue as normalish
this.checkAndHandleExpiredSession();
this._updateSessionActivity();
}
/**
* Updates the user activity timestamp *without* resuming
* recording. Some user events (e.g. keydown) can be create
* low-value replays that only contain the keypress as a
* breadcrumb. Instead this would require other events to
* create a new replay after a session has expired.
*/
public updateUserActivity(): void {
this._updateUserActivity();
this._updateSessionActivity();
}
/**
* Only flush if `this.recordingMode === 'session'`
*/
public conditionalFlush(): Promise<void> {
if (this.recordingMode === 'buffer') {
return Promise.resolve();
}
return this.flushImmediate();
}
/**
* Flush using debounce flush
*/
public flush(): Promise<void> {
return this._debouncedFlush() as Promise<void>;
}
/**
* Always flush via `_debouncedFlush` so that we do not have flushes triggered
* from calling both `flush` and `_debouncedFlush`. Otherwise, there could be
* cases of multiple flushes happening closely together.
*/
public flushImmediate(): Promise<void> {
this._debouncedFlush();
// `.flush` is provided by the debounced function, analogously to lodash.debounce
return this._debouncedFlush.flush() as Promise<void>;
}
/**
* Cancels queued up flushes.
*/
public cancelFlush(): void {
this._debouncedFlush.cancel();
}
/** Get the current session (=replay) ID */
public getSessionId(): string | undefined {
return this.session?.id;
}
/**
* Checks if recording should be stopped due to user inactivity. Otherwise
* check if session is expired and create a new session if so. Triggers a new
* full snapshot on new session.
*
* Returns true if session is not expired, false otherwise.
* @hidden
*/
public checkAndHandleExpiredSession(): boolean | void {
// Prevent starting a new session if the last user activity is older than
// SESSION_IDLE_PAUSE_DURATION. Otherwise non-user activity can trigger a new
// session+recording. This creates noisy replays that do not have much
// content in them.
if (
this._lastActivity &&
isExpired(this._lastActivity, this.timeouts.sessionIdlePause) &&
this.session &&
this.session.sampled === 'session'
) {
// Pause recording only for session-based replays. Otherwise, resuming
// will create a new replay and will conflict with users who only choose
// to record error-based replays only. (e.g. the resumed replay will not
// contain a reference to an error)
this.pause();
return;
}
// --- There is recent user activity --- //
// This will create a new session if expired, based on expiry length
if (!this._checkSession()) {
// Check session handles the refreshing itself
return false;
}
return true;
}
/**
* Capture some initial state that can change throughout the lifespan of the
* replay. This is required because otherwise they would be captured at the
* first flush.
*/
public setInitialState(): void {
const urlPath = `${WINDOW.location.pathname}${WINDOW.location.hash}${WINDOW.location.search}`;
const url = `${WINDOW.location.origin}${urlPath}`;
this.performanceEntries = [];
this.replayPerformanceEntries = [];
// Reset _context as well
this._clearContext();
this._context.initialUrl = url;
this._context.initialTimestamp = Date.now();
this._context.urls.push(url);
}
/**
* Add a breadcrumb event, that may be throttled.
* If it was throttled, we add a custom breadcrumb to indicate that.
*/
public throttledAddEvent(
event: RecordingEvent,
isCheckout?: boolean,
): typeof THROTTLED | typeof SKIPPED | Promise<AddEventResult | null> {
const res = this._throttledAddEvent(event, isCheckout);
// If this is THROTTLED, it means we have throttled the event for the first time
// In this case, we want to add a breadcrumb indicating that something was skipped
if (res === THROTTLED) {
const breadcrumb = createBreadcrumb({
category: 'replay.throttled',
});
this.addUpdate(() => {
// Return `false` if the event _was_ added, as that means we schedule a flush
return !addEventSync(this, {
type: ReplayEventTypeCustom,
timestamp: breadcrumb.timestamp || 0,
data: {
tag: 'breadcrumb',
payload: breadcrumb,
metric: true,
},
});
});
}
return res;
}
/**
* This will get the parametrized route name of the current page.
* This is only available if performance is enabled, and if an instrumented router is used.
*/
public getCurrentRoute(): string | undefined {
const lastActiveSpan = this.lastActiveSpan || getActiveSpan();
const lastRootSpan = lastActiveSpan && getRootSpan(lastActiveSpan);
const attributes = (lastRootSpan && spanToJSON(lastRootSpan).data) || {};
const source = attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];
if (!lastRootSpan || !source || !['route', 'custom'].includes(source)) {
return undefined;
}
return spanToJSON(lastRootSpan).description;
}
/**
* Initialize and start all listeners to varying events (DOM,
* Performance Observer, Recording, Sentry SDK, etc)
*/
private _initializeRecording(): void {
this.setInitialState();
// this method is generally called on page load or manually - in both cases
// we should treat it as an activity
this._updateSessionActivity();
this.eventBuffer = createEventBuffer({
useCompression: this._options.useCompression,
workerUrl: this._options.workerUrl,
});
this._removeListeners();
this._addListeners();
// Need to set as enabled before we start recording, as `record()` can trigger a flush with a new checkout
this._isEnabled = true;
this._isPaused = false;
this.startRecording();
}
/**
* Loads (or refreshes) the current session.
*/
private _initializeSessionForSampling(previousSessionId?: string): void {
// Whenever there is _any_ error sample rate, we always allow buffering
// Because we decide on sampling when an error occurs, we need to buffer at all times if sampling for errors
const allowBuffering = this._options.errorSampleRate > 0;
const session = loadOrCreateSession(
{
sessionIdleExpire: this.timeouts.sessionIdleExpire,
maxReplayDuration: this._options.maxReplayDuration,
previousSessionId,
},
{
stickySession: this._options.stickySession,
sessionSampleRate: this._options.sessionSampleRate,
allowBuffering,
},
);
this.session = session;
}
/**
* Checks and potentially refreshes the current session.
* Returns false if session is not recorded.
*/
private _checkSession(): boolean {
// If there is no session yet, we do not want to refresh anything
// This should generally not happen, but to be safe....
if (!this.session) {
return false;
}
const currentSession = this.session;
if (
shouldRefreshSession(currentSession, {
sessionIdleExpire: this.timeouts.sessionIdleExpire,
maxReplayDuration: this._options.maxReplayDuration,
})
) {
// This should never reject
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this._refreshSession(currentSession);
return false;
}
return true;
}
/**
* Refresh a session with a new one.
* This stops the current session (without forcing a flush, as that would never work since we are expired),
* and then does a new sampling based on the refreshed session.
*/
private async _refreshSession(session: Session): Promise<void> {
if (!this._isEnabled) {
return;
}
await this.stop({ reason: 'refresh session' });
this.initializeSampling(session.id);
}
/**
* Adds listeners to record events for the replay
*/
private _addListeners(): void {
try {
WINDOW.document.addEventListener('visibilitychange', this._handleVisibilityChange);
WINDOW.addEventListener('blur', this._handleWindowBlur);
WINDOW.addEventListener('focus', this._handleWindowFocus);
WINDOW.addEventListener('keydown', this._handleKeyboardEvent);
if (this.clickDetector) {
this.clickDetector.addListeners();
}
// There is no way to remove these listeners, so ensure they are only added once
if (!this._hasInitializedCoreListeners) {
addGlobalListeners(this, { autoFlushOnFeedback: this._options._experiments.autoFlushOnFeedback });
this._hasInitializedCoreListeners = true;
}
} catch (err) {
this.handleException(err);
}
this._performanceCleanupCallback = setupPerformanceObserver(this);
}
/**
* Cleans up listeners that were created in `_addListeners`
*/
private _removeListeners(): void {
try {
WINDOW.document.removeEventListener('visibilitychange', this._handleVisibilityChange);
WINDOW.removeEventListener('blur', this._handleWindowBlur);
WINDOW.removeEventListener('focus', this._handleWindowFocus);
WINDOW.removeEventListener('keydown', this._handleKeyboardEvent);
if (this.clickDetector) {
this.clickDetector.removeListeners();
}
if (this._performanceCleanupCallback) {
this._performanceCleanupCallback();
}
} catch (err) {
this.handleException(err);
}
}
/**
* Tasks to run when we consider a page to be hidden (via blurring and/or visibility)
*/
private _doChangeToBackgroundTasks(breadcrumb?: ReplayBreadcrumbFrame): void {
if (!this.session) {
return;
}
const expired = isSessionExpired(this.session, {
maxReplayDuration: this._options.maxReplayDuration,
sessionIdleExpire: this.timeouts.sessionIdleExpire,
});
if (expired) {
return;