-
Notifications
You must be signed in to change notification settings - Fork 190
Expand file tree
/
Copy pathrecord.spec.ts
More file actions
531 lines (431 loc) · 19.1 KB
/
Copy pathrecord.spec.ts
File metadata and controls
531 lines (431 loc) · 19.1 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
import { DefaultPrivacyLevel, findLast, noop } from '@datadog/browser-core'
import type { RumConfiguration, ViewCreatedEvent } from '@datadog/browser-rum-core'
import { LifeCycle, LifeCycleEventType } from '@datadog/browser-rum-core'
import { createNewEvent, collectAsyncCalls, mockClock, registerCleanupTask } from '@datadog/browser-core/test'
import { recordsPerFullSnapshot } from '../../../test'
import type {
AddNodeChange,
BrowserChangeRecord,
BrowserIncrementalSnapshotRecord,
BrowserMutationData,
BrowserRecord,
Change,
ScrollData,
} from '../../types'
import { ChangeType, RecordType, IncrementalSource, SnapshotFormat } from '../../types'
import { appendElement } from '../../../../browser-rum-core/test'
import { getReplayStats } from '../replayStats'
import type { RecordAPI } from './record'
import { record } from './record'
import type { EmitRecordCallback } from './record.types'
import { createChangeDecoder } from './serialization'
describe('record', () => {
let recordApi: RecordAPI
let lifeCycle: LifeCycle
let emitSpy: jasmine.Spy<EmitRecordCallback>
const FAKE_VIEW_ID = '123'
beforeEach(() => {
emitSpy = jasmine.createSpy()
registerCleanupTask(() => {
recordApi?.stop()
})
})
it('captures stylesheet rules', () => {
const clock = mockClock()
const styleElement = appendElement('<style></style>') as HTMLStyleElement
startRecording()
const styleSheet = styleElement.sheet as CSSStyleSheet
const ruleIdx0 = styleSheet.insertRule('body { background: #000; }')
const ruleIdx1 = styleSheet.insertRule('body { background: #111; }')
styleSheet.deleteRule(ruleIdx1)
setTimeout(() => {
styleSheet.insertRule('body { color: #fff; }')
}, 0)
setTimeout(() => {
styleSheet.deleteRule(ruleIdx0)
}, 5)
setTimeout(() => {
styleSheet.insertRule('body { color: #ccc; }')
}, 10)
clock.tick(10)
const styleSheetRuleData = getEmittedRecords()
.filter(
(record): record is BrowserIncrementalSnapshotRecord =>
record.type === RecordType.IncrementalSnapshot && record.data.source === IncrementalSource.StyleSheetRule
)
.map((record) => record.data)
expect(styleSheetRuleData).toEqual([
jasmine.objectContaining({ adds: [{ rule: 'body { background: #000; }', index: undefined }] }),
jasmine.objectContaining({ adds: [{ rule: 'body { background: #111; }', index: undefined }] }),
jasmine.objectContaining({ removes: [{ index: 0 }] }),
jasmine.objectContaining({ adds: [{ rule: 'body { color: #fff; }', index: undefined }] }),
jasmine.objectContaining({ removes: [{ index: 0 }] }),
jasmine.objectContaining({ adds: [{ rule: 'body { color: #ccc; }', index: undefined }] }),
])
})
describe('canvas mutation tracking', () => {
it('instruments canvas drawing when canvas recording is enabled', () => {
const originalFillRect = Object.getOwnPropertyDescriptor(CanvasRenderingContext2D.prototype, 'fillRect')!.value
startRecording({ enableSessionReplayCanvasRecording: { maxFramesPerSecond: 1 } })
expect(Object.getOwnPropertyDescriptor(CanvasRenderingContext2D.prototype, 'fillRect')!.value).not.toBe(
originalFillRect
)
})
it('does not instrument canvas drawing when canvas recording is disabled', () => {
const originalFillRect = Object.getOwnPropertyDescriptor(CanvasRenderingContext2D.prototype, 'fillRect')!.value
startRecording()
expect(Object.getOwnPropertyDescriptor(CanvasRenderingContext2D.prototype, 'fillRect')!.value).toBe(
originalFillRect
)
})
it('does not instrument canvas drawing when the maximum frame rate is zero', () => {
const originalFillRect = Object.getOwnPropertyDescriptor(CanvasRenderingContext2D.prototype, 'fillRect')!.value
startRecording({ enableSessionReplayCanvasRecording: { maxFramesPerSecond: 0 } })
expect(Object.getOwnPropertyDescriptor(CanvasRenderingContext2D.prototype, 'fillRect')!.value).toBe(
originalFillRect
)
})
it('captures dirty canvases at the configured maximum frame rate', async () => {
const clock = mockClock()
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')!
const blob = new Blob(['frame'], { type: 'image/png' })
const capturedImageSpy = jasmine.createSpy()
spyOn(canvas, 'toBlob').and.callFake((callback) => callback(blob))
startRecording({ recordCanvas: true, canvasMaxFramesPerSecond: 1 })
recordApi.canvasImageObservable.subscribe(capturedImageSpy)
context.fillRect(0, 0, 1, 1)
clock.tick(999)
expect(capturedImageSpy).not.toHaveBeenCalled()
clock.tick(1)
await collectAsyncCalls(capturedImageSpy)
expect(capturedImageSpy).toHaveBeenCalledOnceWith({
blob,
canvas,
hash: jasmine.any(String),
})
})
})
it('flushes pending mutation records before taking a full snapshot', async () => {
startRecording()
appendElement('<hr/>')
// trigger full snapshot by starting a new view
newView()
await collectAsyncCalls(emitSpy, 1 + 2 * recordsPerFullSnapshot())
const records = getEmittedRecords()
let i = 0
expect(records[i++].type).toEqual(RecordType.Meta)
expect(records[i++].type).toEqual(RecordType.Focus)
expect(records[i++].type).toEqual(RecordType.FullSnapshot)
if (window.visualViewport) {
expect(records[i++].type).toEqual(RecordType.VisualViewport)
}
expect(records[i].type).toEqual(RecordType.Change)
expect((records[i++] as BrowserChangeRecord).data.map((change) => change[0])).toContain(ChangeType.AddNode)
expect(records[i++].type).toEqual(RecordType.Meta)
expect(records[i++].type).toEqual(RecordType.Focus)
expect(records[i].type).toEqual(RecordType.FullSnapshot)
})
describe('Shadow dom', () => {
it('should record a simple mutation inside a shadow root', () => {
const element = appendElement('<hr class="toto" />', createShadow())
startRecording()
expect(getEmittedRecordCount()).toBe(recordsPerFullSnapshot())
element.className = 'titi'
recordApi.flushMutations()
expect(getEmittedRecordCount()).toBe(recordsPerFullSnapshot() + 1)
const [, ...attributeMutations] = getLastChangeOfType(ChangeType.Attribute, getEmittedRecords())
expect(attributeMutations[0][1]).toEqual(['class', 'titi'])
})
it('should record a direct removal inside a shadow root', () => {
const element = appendElement('<hr/>', createShadow())
startRecording()
expect(getEmittedRecordCount()).toBe(recordsPerFullSnapshot())
element.remove()
recordApi.flushMutations()
expect(getEmittedRecordCount()).toBe(recordsPerFullSnapshot() + 1)
const records = getEmittedRecords()
const horizontalRuleId = findNodeId(records, (change) => change[1] === 'HR')
const [, ...removeMutations] = getLastChangeOfType(ChangeType.RemoveNode, records)
expect(removeMutations.length).toBe(1)
expect(removeMutations[0]).toBe(horizontalRuleId)
})
it('should record a direct addition inside a shadow root', () => {
const shadowRoot = createShadow()
appendElement('<hr/>', shadowRoot)
startRecording()
expect(getEmittedRecordCount()).toBe(recordsPerFullSnapshot())
appendElement('<span></span>', shadowRoot)
recordApi.flushMutations()
expect(getEmittedRecordCount()).toBe(recordsPerFullSnapshot() + 1)
const records = getEmittedRecords()
const [, ...addMutations] = getLastChangeOfType(ChangeType.AddNode, records)
expect(addMutations.length).toBe(1)
expect(addMutations[0][1]).toBe('SPAN')
})
it('should record mutation inside a shadow root added after the FS', () => {
startRecording()
expect(getEmittedRecordCount()).toBe(recordsPerFullSnapshot())
// shadow DOM mutation
const span = appendElement('<span class="toto"></span>', createShadow())
recordApi.flushMutations()
expect(getEmittedRecordCount()).toBe(recordsPerFullSnapshot() + 1)
const [, ...addMutations] = getLastChangeOfType(ChangeType.AddNode, getEmittedRecords())
expect(addMutations.length).toBe(3)
expect(addMutations[0][1]).toBe('DIV')
expect(addMutations[1][1]).toBe('#shadow-root')
expect(addMutations[2][1]).toBe('SPAN')
// inner mutation
span.className = 'titi'
recordApi.flushMutations()
expect(getEmittedRecordCount()).toBe(recordsPerFullSnapshot() + 2)
const [, ...attributeMutations] = getLastChangeOfType(ChangeType.Attribute, getEmittedRecords())
expect(attributeMutations[0][1]).toEqual(['class', 'titi'])
})
it('should record the change event inside a shadow root', () => {
const radio = appendElement('<input type="radio"/>', createShadow()) as HTMLInputElement
startRecording()
expect(getEmittedRecordCount()).toBe(recordsPerFullSnapshot())
// inner mutation
radio.checked = true
radio.dispatchEvent(createNewEvent('change', { target: radio, composed: false }))
recordApi.flushMutations()
const innerMutationData = getLastIncrementalSnapshotData<BrowserMutationData & { isChecked: boolean }>(
getEmittedRecords(),
IncrementalSource.Input
)
expect(innerMutationData.isChecked).toBe(true)
})
it('should record the change event inside a shadow root only once, regardless if the DOM is serialized multiple times', () => {
const radio = appendElement('<input type="radio"/>', createShadow()) as HTMLInputElement
startRecording()
// trigger full snapshot by starting a new view
newView()
radio.checked = true
radio.dispatchEvent(createNewEvent('change', { target: radio, composed: false }))
const inputRecords = getEmittedRecords().filter(
(record) => record.type === RecordType.IncrementalSnapshot && record.data.source === IncrementalSource.Input
)
expect(inputRecords.length).toBe(1)
})
it('should record the scroll event inside a shadow root', () => {
const div = appendElement('<div unique-selector="enabled"></div>', createShadow()) as HTMLDivElement
startRecording()
expect(getEmittedRecordCount()).toBe(recordsPerFullSnapshot())
div.dispatchEvent(createNewEvent('scroll', { target: div, composed: false }))
recordApi.flushMutations()
const scrollRecords = getEmittedRecords().filter(
(record) => record.type === RecordType.IncrementalSnapshot && record.data.source === IncrementalSource.Scroll
)
expect(scrollRecords.length).toBe(1)
const records = getEmittedRecords()
const scrollableNodeId = findNodeId(records, (change) => {
const [, , ...attributes]: AddNodeChange = change
return attributes.some(
(attribute) => Array.isArray(attribute) && attribute[0] === 'unique-selector' && attribute[1] === 'enabled'
)
})
const scrollData = getLastIncrementalSnapshotData<ScrollData>(getEmittedRecords(), IncrementalSource.Scroll)
expect(scrollData.id).toBe(scrollableNodeId)
})
it('should clean the state once the shadow dom is removed to avoid memory leak', () => {
const shadowRoot = createShadow()
appendElement('<div class="toto"></div>', shadowRoot)
startRecording()
spyOn(recordApi.shadowRootsController, 'removeShadowRoot')
expect(getEmittedRecordCount()).toBe(recordsPerFullSnapshot())
expect(recordApi.shadowRootsController.removeShadowRoot).toHaveBeenCalledTimes(0)
shadowRoot.host.remove()
recordApi.flushMutations()
expect(recordApi.shadowRootsController.removeShadowRoot).toHaveBeenCalledTimes(1)
expect(getEmittedRecordCount()).toBe(recordsPerFullSnapshot() + 1)
const records = getEmittedRecords()
const [, ...removeMutations] = getLastChangeOfType(ChangeType.RemoveNode, records)
expect(removeMutations.length).toBe(1)
})
it('should clean the state when both the parent and the shadow host is removed to avoid memory leak', () => {
const host = appendElement(`
<div id="grand-parent">
<div id="parent">
<div class="host" target></div>
</div>
</div>`)
host.attachShadow({ mode: 'open' })
const parent = host.parentElement!
const grandParent = parent.parentElement!
appendElement('<div></div>', host.shadowRoot!)
startRecording()
spyOn(recordApi.shadowRootsController, 'removeShadowRoot')
expect(getEmittedRecordCount()).toBe(recordsPerFullSnapshot())
expect(recordApi.shadowRootsController.removeShadowRoot).toHaveBeenCalledTimes(0)
parent.remove()
grandParent.remove()
recordApi.flushMutations()
expect(recordApi.shadowRootsController.removeShadowRoot).toHaveBeenCalledTimes(1)
expect(getEmittedRecordCount()).toBe(recordsPerFullSnapshot() + 1)
const records = getEmittedRecords()
const [, ...removeMutations] = getLastChangeOfType(ChangeType.RemoveNode, records)
expect(removeMutations.length).toBe(2)
})
function createShadow() {
const host = appendElement('<div></div>')
const shadowRoot = host.attachShadow({ mode: 'open' })
return shadowRoot
}
})
describe('updates record replay stats', () => {
it('when recording new records', () => {
startRecording()
const records = getEmittedRecords()
expect(getReplayStats(FAKE_VIEW_ID)?.records_count).toEqual(records.length)
})
})
describe('should collect records', () => {
let div: HTMLDivElement
let input: HTMLInputElement
let audio: HTMLAudioElement
beforeEach(() => {
div = appendElement('<div target></div>') as HTMLDivElement
input = appendElement('<input target />') as HTMLInputElement
audio = appendElement('<audio controls autoplay target></audio>') as HTMLAudioElement
startRecording()
emitSpy.calls.reset()
})
it('move', () => {
document.body.dispatchEvent(createNewEvent('mousemove', { clientX: 1, clientY: 2 }))
expect(getEmittedRecords()[0].type).toBe(RecordType.IncrementalSnapshot)
expect((getEmittedRecords()[0] as BrowserIncrementalSnapshotRecord).data.source).toBe(IncrementalSource.MouseMove)
})
it('interaction', () => {
document.body.dispatchEvent(createNewEvent('click', { clientX: 1, clientY: 2 }))
expect((getEmittedRecords()[0] as BrowserIncrementalSnapshotRecord).data.source).toBe(
IncrementalSource.MouseInteraction
)
})
it('scroll', () => {
div.dispatchEvent(createNewEvent('scroll', { target: div }))
expect(getEmittedRecords()[0].type).toBe(RecordType.IncrementalSnapshot)
expect((getEmittedRecords()[0] as BrowserIncrementalSnapshotRecord).data.source).toBe(IncrementalSource.Scroll)
})
it('viewport resize', () => {
window.dispatchEvent(createNewEvent('resize'))
expect(getEmittedRecords()[0].type).toBe(RecordType.IncrementalSnapshot)
expect((getEmittedRecords()[0] as BrowserIncrementalSnapshotRecord).data.source).toBe(
IncrementalSource.ViewportResize
)
})
it('input', () => {
input.value = 'newValue'
input.dispatchEvent(createNewEvent('input', { target: input }))
expect(getEmittedRecords()[0].type).toBe(RecordType.IncrementalSnapshot)
expect((getEmittedRecords()[0] as BrowserIncrementalSnapshotRecord).data.source).toBe(IncrementalSource.Input)
})
it('media interaction', () => {
audio.dispatchEvent(createNewEvent('play', { target: audio }))
expect(getEmittedRecords()[0].type).toBe(RecordType.IncrementalSnapshot)
expect((getEmittedRecords()[0] as BrowserIncrementalSnapshotRecord).data.source).toBe(
IncrementalSource.MediaInteraction
)
})
it('focus', () => {
window.dispatchEvent(createNewEvent('blur'))
expect(getEmittedRecords()[0].type).toBe(RecordType.Focus)
})
it('visual viewport resize', () => {
if (!window.visualViewport) {
pending('visualViewport not supported')
}
visualViewport!.dispatchEvent(createNewEvent('resize'))
expect(getEmittedRecords()[0].type).toBe(RecordType.VisualViewport)
})
it('view end event', () => {
lifeCycle.notify(LifeCycleEventType.VIEW_ENDED, {} as any)
expect(getEmittedRecords()[0].type).toBe(RecordType.ViewEnd)
})
})
function startRecording(configuration: Partial<RumConfiguration> = {}) {
lifeCycle = new LifeCycle()
recordApi = record({
emitRecord: emitSpy,
emitStats: noop,
configuration: { defaultPrivacyLevel: DefaultPrivacyLevel.ALLOW, ...configuration } as RumConfiguration,
lifeCycle,
viewHistory: {
findView: () => ({ id: FAKE_VIEW_ID, startClocks: {} }),
} as any,
})
}
function newView() {
lifeCycle.notify(LifeCycleEventType.VIEW_CREATED, {
startClocks: { relative: 0, timeStamp: 0 },
} as ViewCreatedEvent)
}
function getEmittedRecordCount(): number {
return emitSpy.calls.allArgs().length
}
function getEmittedRecords(): BrowserRecord[] {
const changeDecoder = createChangeDecoder()
const decodedRecords: BrowserRecord[] = []
for (const [record] of emitSpy.calls.allArgs()) {
if (
record.type === RecordType.Change ||
(record.type === RecordType.FullSnapshot && record.format === SnapshotFormat.Change)
) {
decodedRecords.push(changeDecoder.decode(record))
} else {
decodedRecords.push(record)
}
}
return decodedRecords
}
})
export function getLastIncrementalSnapshotData<T extends BrowserIncrementalSnapshotRecord['data']>(
records: BrowserRecord[],
source: IncrementalSource
): T {
const record = findLast(
records,
(record): record is BrowserIncrementalSnapshotRecord & { data: T } =>
record.type === RecordType.IncrementalSnapshot && record.data.source === source
)
expect(record).toBeTruthy(`Could not find IncrementalSnapshot/${source} in ${records.length} records`)
return record!.data
}
function isChangeOfType<T extends ChangeType>(changeType: T, change: Change): change is Extract<Change, [T, ...any[]]> {
return change[0] === changeType
}
export function getLastChangeOfType<T extends ChangeType>(
changeType: T,
records: BrowserRecord[]
): Extract<Change, [T, ...any[]]> {
for (let i = records.length - 1; i >= 0; i--) {
const record = records[i]
if (record.type !== RecordType.Change) {
continue
}
for (const change of record.data) {
if (isChangeOfType(changeType, change)) {
return change
}
}
}
throw new Error(`Could not find Change of type ${changeType} in ${records.length} records`)
}
function findNodeId(records: BrowserRecord[], predicate: (change: AddNodeChange) => boolean): number {
for (const record of records) {
const isChangeRecord =
record.type === RecordType.Change ||
(record.type === RecordType.FullSnapshot && record.format === SnapshotFormat.Change)
if (!isChangeRecord) {
continue
}
for (const change of record.data) {
if (!isChangeOfType(ChangeType.AddNode, change)) {
continue
}
const [, ...addMutations] = change
return addMutations.findIndex(predicate)
}
}
return -1
}