-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy patherrorSampleRate.test.ts
More file actions
771 lines (628 loc) · 24.2 KB
/
errorSampleRate.test.ts
File metadata and controls
771 lines (628 loc) · 24.2 KB
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
import { captureException, getCurrentHub } from '@sentry/core';
import {
BUFFER_CHECKOUT_TIME,
DEFAULT_FLUSH_MIN_DELAY,
MAX_SESSION_LIFE,
REPLAY_SESSION_KEY,
SESSION_IDLE_EXPIRE_DURATION,
WINDOW,
} from '../../src/constants';
import type { ReplayContainer } from '../../src/replay';
import { clearSession } from '../../src/session/clearSession';
import { addEvent } from '../../src/util/addEvent';
import { createOptionsEvent } from '../../src/util/handleRecordingEmit';
import { PerformanceEntryResource } from '../fixtures/performanceEntry/resource';
import type { RecordMock } from '../index';
import { BASE_TIMESTAMP } from '../index';
import { resetSdkMock } from '../mocks/resetSdkMock';
import type { DomHandler } from '../types';
import { useFakeTimers } from '../utils/use-fake-timers';
useFakeTimers();
async function advanceTimers(time: number) {
jest.advanceTimersByTime(time);
await new Promise(process.nextTick);
}
describe('Integration | errorSampleRate', () => {
let replay: ReplayContainer;
let mockRecord: RecordMock;
let domHandler: DomHandler;
beforeEach(async () => {
({ mockRecord, domHandler, replay } = await resetSdkMock({
replayOptions: {
stickySession: true,
},
sentryOptions: {
replaysSessionSampleRate: 0.0,
replaysOnErrorSampleRate: 1.0,
},
}));
});
afterEach(async () => {
clearSession(replay);
replay.stop();
});
it('uploads a replay when `Sentry.captureException` is called and continues recording', async () => {
const TEST_EVENT = { data: {}, timestamp: BASE_TIMESTAMP, type: 3 };
mockRecord._emitter(TEST_EVENT);
const optionsEvent = createOptionsEvent(replay);
expect(mockRecord.takeFullSnapshot).not.toHaveBeenCalled();
expect(replay).not.toHaveLastSentReplay();
// Does not capture on mouse click
domHandler({
name: 'click',
});
jest.runAllTimers();
await new Promise(process.nextTick);
expect(replay).not.toHaveLastSentReplay();
captureException(new Error('testing'));
await new Promise(process.nextTick);
jest.advanceTimersByTime(DEFAULT_FLUSH_MIN_DELAY);
await new Promise(process.nextTick);
expect(replay).toHaveSentReplay({
recordingPayloadHeader: { segment_id: 0 },
replayEventPayload: expect.objectContaining({
replay_type: 'buffer',
}),
recordingData: JSON.stringify([
{ data: { isCheckout: true }, timestamp: BASE_TIMESTAMP, type: 2 },
optionsEvent,
TEST_EVENT,
{
type: 5,
timestamp: BASE_TIMESTAMP,
data: {
tag: 'breadcrumb',
payload: {
timestamp: BASE_TIMESTAMP / 1000,
type: 'default',
category: 'ui.click',
message: '<unknown>',
data: {},
},
},
},
]),
});
// This is from when we stop recording and start a session recording
expect(replay).toHaveLastSentReplay({
recordingPayloadHeader: { segment_id: 1 },
replayEventPayload: expect.objectContaining({
replay_type: 'buffer',
}),
recordingData: JSON.stringify([
{ data: { isCheckout: true }, timestamp: BASE_TIMESTAMP + DEFAULT_FLUSH_MIN_DELAY + 40, type: 2 },
]),
});
jest.advanceTimersByTime(DEFAULT_FLUSH_MIN_DELAY);
// New checkout when we call `startRecording` again after uploading segment
// after an error occurs
expect(replay).toHaveLastSentReplay({
recordingData: JSON.stringify([
{
data: { isCheckout: true },
timestamp: BASE_TIMESTAMP + DEFAULT_FLUSH_MIN_DELAY + 40,
type: 2,
},
]),
});
// Check that click will get captured
domHandler({
name: 'click',
});
jest.advanceTimersByTime(DEFAULT_FLUSH_MIN_DELAY);
await new Promise(process.nextTick);
expect(replay).toHaveLastSentReplay({
recordingData: JSON.stringify([
{
type: 5,
timestamp: BASE_TIMESTAMP + 10000 + 60,
data: {
tag: 'breadcrumb',
payload: {
timestamp: (BASE_TIMESTAMP + 10000 + 60) / 1000,
type: 'default',
category: 'ui.click',
message: '<unknown>',
data: {},
},
},
},
]),
});
});
it('manually flushes replay and does not continue to record', async () => {
const TEST_EVENT = { data: {}, timestamp: BASE_TIMESTAMP, type: 3 };
mockRecord._emitter(TEST_EVENT);
const optionsEvent = createOptionsEvent(replay);
expect(mockRecord.takeFullSnapshot).not.toHaveBeenCalled();
expect(replay).not.toHaveLastSentReplay();
// Does not capture on mouse click
domHandler({
name: 'click',
});
jest.runAllTimers();
await new Promise(process.nextTick);
expect(replay).not.toHaveLastSentReplay();
replay.sendBufferedReplayOrFlush({ continueRecording: false });
await new Promise(process.nextTick);
jest.advanceTimersByTime(DEFAULT_FLUSH_MIN_DELAY);
await new Promise(process.nextTick);
expect(replay).toHaveSentReplay({
recordingPayloadHeader: { segment_id: 0 },
replayEventPayload: expect.objectContaining({
replay_type: 'buffer',
}),
recordingData: JSON.stringify([
{ data: { isCheckout: true }, timestamp: BASE_TIMESTAMP, type: 2 },
optionsEvent,
TEST_EVENT,
{
type: 5,
timestamp: BASE_TIMESTAMP,
data: {
tag: 'breadcrumb',
payload: {
timestamp: BASE_TIMESTAMP / 1000,
type: 'default',
category: 'ui.click',
message: '<unknown>',
data: {},
},
},
},
]),
});
jest.advanceTimersByTime(DEFAULT_FLUSH_MIN_DELAY);
// Check that click will not get captured
domHandler({
name: 'click',
});
jest.advanceTimersByTime(DEFAULT_FLUSH_MIN_DELAY);
await new Promise(process.nextTick);
// This is still the last replay sent since we passed `continueRecording:
// false`.
expect(replay).toHaveLastSentReplay({
recordingPayloadHeader: { segment_id: 0 },
replayEventPayload: expect.objectContaining({
replay_type: 'buffer',
}),
recordingData: JSON.stringify([
{ data: { isCheckout: true }, timestamp: BASE_TIMESTAMP, type: 2 },
optionsEvent,
TEST_EVENT,
{
type: 5,
timestamp: BASE_TIMESTAMP,
data: {
tag: 'breadcrumb',
payload: {
timestamp: BASE_TIMESTAMP / 1000,
type: 'default',
category: 'ui.click',
message: '<unknown>',
data: {},
},
},
},
]),
});
});
// This tests a regression where we were calling flush indiscriminantly in `stop()`
it('does not upload a replay event if error is not sampled', async () => {
// We are trying to replicate the case where error rate is 0 and session
// rate is > 0, we can't set them both to 0 otherwise
// `_loadAndCheckSession` is not called when initializing the plugin.
replay.stop();
replay['_options']['errorSampleRate'] = 0;
replay['_loadAndCheckSession']();
jest.runAllTimers();
await new Promise(process.nextTick);
expect(mockRecord.takeFullSnapshot).not.toHaveBeenCalled();
expect(replay).not.toHaveLastSentReplay();
});
it('does not send a replay when triggering a full dom snapshot when document becomes visible after [SESSION_IDLE_EXPIRE_DURATION]ms', async () => {
Object.defineProperty(document, 'visibilityState', {
configurable: true,
get: function () {
return 'visible';
},
});
jest.advanceTimersByTime(SESSION_IDLE_EXPIRE_DURATION + 1);
document.dispatchEvent(new Event('visibilitychange'));
jest.runAllTimers();
await new Promise(process.nextTick);
expect(replay).not.toHaveLastSentReplay();
});
it('does not send a replay if user hides the tab and comes back within 60 seconds', async () => {
Object.defineProperty(document, 'visibilityState', {
configurable: true,
get: function () {
return 'hidden';
},
});
document.dispatchEvent(new Event('visibilitychange'));
jest.runAllTimers();
await new Promise(process.nextTick);
expect(replay).not.toHaveLastSentReplay();
// User comes back before `SESSION_IDLE_EXPIRE_DURATION` elapses
jest.advanceTimersByTime(SESSION_IDLE_EXPIRE_DURATION - 100);
Object.defineProperty(document, 'visibilityState', {
configurable: true,
get: function () {
return 'visible';
},
});
document.dispatchEvent(new Event('visibilitychange'));
jest.runAllTimers();
await new Promise(process.nextTick);
expect(mockRecord.takeFullSnapshot).not.toHaveBeenCalled();
expect(replay).not.toHaveLastSentReplay();
});
it('does not upload a replay event when document becomes hidden', async () => {
Object.defineProperty(document, 'visibilityState', {
configurable: true,
get: function () {
return 'hidden';
},
});
// Pretend 5 seconds have passed
const ELAPSED = 5000;
jest.advanceTimersByTime(ELAPSED);
const TEST_EVENT = { data: {}, timestamp: BASE_TIMESTAMP, type: 2 };
addEvent(replay, TEST_EVENT);
document.dispatchEvent(new Event('visibilitychange'));
jest.runAllTimers();
await new Promise(process.nextTick);
expect(mockRecord.takeFullSnapshot).not.toHaveBeenCalled();
expect(replay).not.toHaveLastSentReplay();
});
it('does not upload a replay event if 5 seconds have elapsed since the last replay event occurred', async () => {
const TEST_EVENT = { data: {}, timestamp: BASE_TIMESTAMP, type: 3 };
mockRecord._emitter(TEST_EVENT);
// Pretend 5 seconds have passed
const ELAPSED = 5000;
await advanceTimers(ELAPSED);
expect(mockRecord.takeFullSnapshot).not.toHaveBeenCalled();
jest.runAllTimers();
await new Promise(process.nextTick);
expect(replay).not.toHaveLastSentReplay();
});
it('does not upload a replay event if 15 seconds have elapsed since the last replay upload', async () => {
const TEST_EVENT = { data: {}, timestamp: BASE_TIMESTAMP, type: 3 };
// Fire a new event every 4 seconds, 4 times
[...Array(4)].forEach(() => {
mockRecord._emitter(TEST_EVENT);
jest.advanceTimersByTime(4000);
});
// We are at time = +16seconds now (relative to BASE_TIMESTAMP)
// The next event should cause an upload immediately
mockRecord._emitter(TEST_EVENT);
await new Promise(process.nextTick);
expect(replay).not.toHaveLastSentReplay();
// There should also not be another attempt at an upload 5 seconds after the last replay event
await advanceTimers(DEFAULT_FLUSH_MIN_DELAY);
expect(replay).not.toHaveLastSentReplay();
// Let's make sure it continues to work
mockRecord._emitter(TEST_EVENT);
await advanceTimers(DEFAULT_FLUSH_MIN_DELAY);
jest.runAllTimers();
await new Promise(process.nextTick);
expect(replay).not.toHaveLastSentReplay();
});
// When the error session records as a normal session, we want to stop
// recording after the session ends. Otherwise, we get into a state where the
// new session is a session type replay (this could conflict with the session
// sample rate of 0.0), or an error session that has no errors. Instead we
// simply stop the session replay completely and wait for a new page load to
// resample.
it.each([
['MAX_SESSION_LIFE', MAX_SESSION_LIFE],
['SESSION_IDLE_DURATION', SESSION_IDLE_EXPIRE_DURATION],
])(
'stops replay if session had an error and exceeds %s and does not start a new session thereafter',
async (_label, waitTime) => {
expect(replay.session?.shouldRefresh).toBe(true);
captureException(new Error('testing'));
await new Promise(process.nextTick);
jest.advanceTimersByTime(DEFAULT_FLUSH_MIN_DELAY);
await new Promise(process.nextTick);
// segment_id is 1 because it sends twice on error
expect(replay).toHaveLastSentReplay({
recordingPayloadHeader: { segment_id: 1 },
replayEventPayload: expect.objectContaining({
replay_type: 'buffer',
}),
});
expect(replay.session?.shouldRefresh).toBe(false);
// Idle for given time
jest.advanceTimersByTime(waitTime + 1);
await new Promise(process.nextTick);
const TEST_EVENT = {
data: { name: 'lost event' },
timestamp: BASE_TIMESTAMP,
type: 3,
};
mockRecord._emitter(TEST_EVENT);
jest.runAllTimers();
await new Promise(process.nextTick);
// We stop recording after 15 minutes of inactivity in error mode
// still no new replay sent
expect(replay).toHaveLastSentReplay({
recordingPayloadHeader: { segment_id: 1 },
replayEventPayload: expect.objectContaining({
replay_type: 'buffer',
}),
});
expect(replay.isEnabled()).toBe(false);
domHandler({
name: 'click',
});
// Remains disabled!
expect(replay.isEnabled()).toBe(false);
},
);
it.each([
['MAX_SESSION_LIFE', MAX_SESSION_LIFE],
['SESSION_IDLE_EXPIRE_DURATION', SESSION_IDLE_EXPIRE_DURATION],
])('continues buffering replay if session had no error and exceeds %s', async (_label, waitTime) => {
expect(replay).not.toHaveLastSentReplay();
// Idle for given time
jest.advanceTimersByTime(waitTime + 1);
await new Promise(process.nextTick);
const TEST_EVENT = {
data: { name: 'lost event' },
timestamp: BASE_TIMESTAMP,
type: 3,
};
mockRecord._emitter(TEST_EVENT);
jest.runAllTimers();
await new Promise(process.nextTick);
// still no new replay sent
expect(replay).not.toHaveLastSentReplay();
expect(replay.isEnabled()).toBe(true);
expect(replay.isPaused()).toBe(false);
expect(replay.recordingMode).toBe('buffer');
domHandler({
name: 'click',
});
await new Promise(process.nextTick);
jest.advanceTimersByTime(DEFAULT_FLUSH_MIN_DELAY);
await new Promise(process.nextTick);
expect(replay).not.toHaveLastSentReplay();
expect(replay.isEnabled()).toBe(true);
expect(replay.isPaused()).toBe(false);
expect(replay.recordingMode).toBe('buffer');
// should still react to errors later on
captureException(new Error('testing'));
await new Promise(process.nextTick);
jest.advanceTimersByTime(DEFAULT_FLUSH_MIN_DELAY);
await new Promise(process.nextTick);
expect(replay).toHaveLastSentReplay({
recordingPayloadHeader: { segment_id: 0 },
replayEventPayload: expect.objectContaining({
replay_type: 'buffer',
}),
});
expect(replay.isEnabled()).toBe(true);
expect(replay.isPaused()).toBe(false);
expect(replay.recordingMode).toBe('session');
expect(replay.session?.sampled).toBe('buffer');
expect(replay.session?.shouldRefresh).toBe(false);
});
// Should behave the same as above test
it('stops replay if user has been idle for more than SESSION_IDLE_EXPIRE_DURATION and does not start a new session thereafter', async () => {
// Idle for 15 minutes
jest.advanceTimersByTime(SESSION_IDLE_EXPIRE_DURATION + 1);
const TEST_EVENT = {
data: { name: 'lost event' },
timestamp: BASE_TIMESTAMP,
type: 3,
};
mockRecord._emitter(TEST_EVENT);
expect(replay).not.toHaveLastSentReplay();
jest.runAllTimers();
await new Promise(process.nextTick);
// We stop recording after SESSION_IDLE_EXPIRE_DURATION of inactivity in error mode
expect(replay).not.toHaveLastSentReplay();
expect(replay.isEnabled()).toBe(true);
expect(replay.isPaused()).toBe(false);
expect(replay.recordingMode).toBe('buffer');
// should still react to errors later on
captureException(new Error('testing'));
await new Promise(process.nextTick);
jest.advanceTimersByTime(DEFAULT_FLUSH_MIN_DELAY);
await new Promise(process.nextTick);
expect(replay).toHaveLastSentReplay({
recordingPayloadHeader: { segment_id: 0 },
replayEventPayload: expect.objectContaining({
replay_type: 'buffer',
}),
});
expect(replay.isEnabled()).toBe(true);
expect(replay.isPaused()).toBe(false);
expect(replay.recordingMode).toBe('session');
expect(replay.session?.sampled).toBe('buffer');
expect(replay.session?.shouldRefresh).toBe(false);
});
it('has the correct timestamps with deferred root event and last replay update', async () => {
const TEST_EVENT = { data: {}, timestamp: BASE_TIMESTAMP, type: 3 };
mockRecord._emitter(TEST_EVENT);
const optionsEvent = createOptionsEvent(replay);
expect(mockRecord.takeFullSnapshot).not.toHaveBeenCalled();
expect(replay).not.toHaveLastSentReplay();
jest.runAllTimers();
await new Promise(process.nextTick);
jest.advanceTimersByTime(DEFAULT_FLUSH_MIN_DELAY);
captureException(new Error('testing'));
await new Promise(process.nextTick);
jest.advanceTimersByTime(DEFAULT_FLUSH_MIN_DELAY);
await new Promise(process.nextTick);
expect(replay).toHaveSentReplay({
recordingData: JSON.stringify([
{ data: { isCheckout: true }, timestamp: BASE_TIMESTAMP, type: 2 },
optionsEvent,
TEST_EVENT,
]),
replayEventPayload: expect.objectContaining({
replay_start_timestamp: BASE_TIMESTAMP / 1000,
// the exception happens roughly 10 seconds after BASE_TIMESTAMP
// (advance timers + waiting for flush after the checkout) and
// extra time is likely due to async of `addMemoryEntry()`
timestamp: (BASE_TIMESTAMP + DEFAULT_FLUSH_MIN_DELAY + DEFAULT_FLUSH_MIN_DELAY + 40) / 1000,
error_ids: [expect.any(String)],
trace_ids: [],
urls: ['http://localhost/'],
replay_id: expect.any(String),
}),
recordingPayloadHeader: { segment_id: 0 },
});
});
it('has correct timestamps when error occurs much later than initial pageload/checkout', async () => {
const ELAPSED = BUFFER_CHECKOUT_TIME;
const TEST_EVENT = { data: {}, timestamp: BASE_TIMESTAMP, type: 3 };
mockRecord._emitter(TEST_EVENT);
// add a mock performance event
replay.performanceEvents.push(PerformanceEntryResource());
jest.runAllTimers();
await new Promise(process.nextTick);
expect(mockRecord.takeFullSnapshot).not.toHaveBeenCalled();
expect(replay).not.toHaveLastSentReplay();
jest.advanceTimersByTime(ELAPSED);
// in production, this happens at a time interval
// session started time should be updated to this current timestamp
mockRecord.takeFullSnapshot(true);
const optionsEvent = createOptionsEvent(replay);
jest.runAllTimers();
jest.advanceTimersByTime(20);
await new Promise(process.nextTick);
captureException(new Error('testing'));
await new Promise(process.nextTick);
jest.runAllTimers();
jest.advanceTimersByTime(20);
await new Promise(process.nextTick);
expect(replay.session?.started).toBe(BASE_TIMESTAMP + ELAPSED + 20);
// Does not capture mouse click
expect(replay).toHaveSentReplay({
recordingPayloadHeader: { segment_id: 0 },
replayEventPayload: expect.objectContaining({
// Make sure the old performance event is thrown out
replay_start_timestamp: (BASE_TIMESTAMP + ELAPSED + 20) / 1000,
}),
recordingData: JSON.stringify([
{
data: { isCheckout: true },
timestamp: BASE_TIMESTAMP + ELAPSED + 20,
type: 2,
},
optionsEvent,
]),
});
});
it('stops replay when user goes idle', async () => {
jest.setSystemTime(BASE_TIMESTAMP);
const TEST_EVENT = { data: {}, timestamp: BASE_TIMESTAMP, type: 3 };
mockRecord._emitter(TEST_EVENT);
expect(mockRecord.takeFullSnapshot).not.toHaveBeenCalled();
expect(replay).not.toHaveLastSentReplay();
jest.runAllTimers();
await new Promise(process.nextTick);
captureException(new Error('testing'));
await new Promise(process.nextTick);
jest.advanceTimersByTime(DEFAULT_FLUSH_MIN_DELAY);
await new Promise(process.nextTick);
expect(replay).toHaveLastSentReplay();
// Now wait after session expires - should stop recording
mockRecord.takeFullSnapshot.mockClear();
(getCurrentHub().getClient()!.getTransport()!.send as unknown as jest.SpyInstance<any>).mockClear();
expect(replay).not.toHaveLastSentReplay();
// Go idle
jest.advanceTimersByTime(SESSION_IDLE_EXPIRE_DURATION + 1);
await new Promise(process.nextTick);
mockRecord._emitter(TEST_EVENT);
expect(replay).not.toHaveLastSentReplay();
jest.advanceTimersByTime(DEFAULT_FLUSH_MIN_DELAY);
await new Promise(process.nextTick);
expect(replay).not.toHaveLastSentReplay();
expect(mockRecord.takeFullSnapshot).toHaveBeenCalledTimes(0);
expect(replay.isEnabled()).toBe(false);
});
it('stops replay when session exceeds max length', async () => {
jest.setSystemTime(BASE_TIMESTAMP);
const TEST_EVENT = { data: {}, timestamp: BASE_TIMESTAMP, type: 3 };
mockRecord._emitter(TEST_EVENT);
expect(mockRecord.takeFullSnapshot).not.toHaveBeenCalled();
expect(replay).not.toHaveLastSentReplay();
jest.runAllTimers();
await new Promise(process.nextTick);
captureException(new Error('testing'));
jest.advanceTimersByTime(DEFAULT_FLUSH_MIN_DELAY);
await new Promise(process.nextTick);
expect(replay).not.toHaveLastSentReplay();
// Wait a bit, shortly before session expires
jest.advanceTimersByTime(MAX_SESSION_LIFE - 1000);
await new Promise(process.nextTick);
mockRecord._emitter(TEST_EVENT);
replay.triggerUserActivity();
expect(replay).toHaveLastSentReplay();
// Now wait after session expires - should stop recording
mockRecord.takeFullSnapshot.mockClear();
(getCurrentHub().getClient()!.getTransport()!.send as unknown as jest.SpyInstance<any>).mockClear();
jest.advanceTimersByTime(10_000);
await new Promise(process.nextTick);
mockRecord._emitter(TEST_EVENT);
replay.triggerUserActivity();
jest.advanceTimersByTime(DEFAULT_FLUSH_MIN_DELAY);
await new Promise(process.nextTick);
expect(replay).not.toHaveLastSentReplay();
expect(mockRecord.takeFullSnapshot).toHaveBeenCalledTimes(0);
expect(replay.isEnabled()).toBe(false);
});
});
/**
* This is testing a case that should only happen with error-only sessions.
* Previously we had assumed that loading a session from session storage meant
* that the session was not new. However, this is not the case with error-only
* sampling since we can load a saved session that did not have an error (and
* thus no replay was created).
*/
it('sends a replay after loading the session multiple times', async () => {
// Pretend that a session is already saved before loading replay
WINDOW.sessionStorage.setItem(
REPLAY_SESSION_KEY,
`{"segmentId":0,"id":"fd09adfc4117477abc8de643e5a5798a","sampled":"buffer","started":${BASE_TIMESTAMP},"lastActivity":${BASE_TIMESTAMP}}`,
);
const { mockRecord, replay, integration } = await resetSdkMock({
replayOptions: {
stickySession: true,
},
sentryOptions: {
replaysOnErrorSampleRate: 1.0,
},
autoStart: false,
});
integration['_initialize']();
const optionsEvent = createOptionsEvent(replay);
jest.runAllTimers();
await new Promise(process.nextTick);
const TEST_EVENT = { data: {}, timestamp: BASE_TIMESTAMP, type: 3 };
mockRecord._emitter(TEST_EVENT);
expect(replay).not.toHaveLastSentReplay();
captureException(new Error('testing'));
await new Promise(process.nextTick);
jest.advanceTimersByTime(DEFAULT_FLUSH_MIN_DELAY);
await new Promise(process.nextTick);
expect(replay).toHaveSentReplay({
recordingPayloadHeader: { segment_id: 0 },
recordingData: JSON.stringify([
{ data: { isCheckout: true }, timestamp: BASE_TIMESTAMP, type: 2 },
optionsEvent,
TEST_EVENT,
]),
});
// Latest checkout when we call `startRecording` again after uploading segment
// after an error occurs (e.g. when we switch to session replay recording)
expect(replay).toHaveLastSentReplay({
recordingPayloadHeader: { segment_id: 1 },
recordingData: JSON.stringify([{ data: { isCheckout: true }, timestamp: BASE_TIMESTAMP + 5040, type: 2 }]),
});
});