-
Notifications
You must be signed in to change notification settings - Fork 171
Expand file tree
/
Copy pathformatValidation.ts
More file actions
91 lines (83 loc) · 2.67 KB
/
formatValidation.ts
File metadata and controls
91 lines (83 loc) · 2.67 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
import ajv from 'ajv'
import { registerCleanupTask } from '@datadog/browser-core/test'
import type { TimeStamp, Context } from '@datadog/browser-core'
import { combine } from '@datadog/browser-core'
import type { CommonProperties } from '@datadog/browser-rum-core'
import type { LifeCycle, RawRumEventCollectedData } from '../src/domain/lifeCycle'
import { LifeCycleEventType } from '../src/domain/lifeCycle'
import type { RawRumEvent } from '../src/rawRumEvent.types'
import { allJsonSchemas } from './allJsonSchemas'
export function collectAndValidateRawRumEvents(lifeCycle: LifeCycle) {
const rawRumEvents: Array<RawRumEventCollectedData<RawRumEvent>> = []
const subscription = lifeCycle.subscribe(LifeCycleEventType.RAW_RUM_EVENT_COLLECTED, (data) => {
rawRumEvents.push(data)
validateRumEventFormat(data.rawRumEvent)
})
registerCleanupTask(() => {
subscription.unsubscribe()
})
return rawRumEvents
}
function validateRumEventFormat(rawRumEvent: RawRumEvent) {
const fakeId = '00000000-aaaa-0000-aaaa-000000000000'
const fakeContext: Partial<CommonProperties> = {
_dd: {
format_version: 2,
drift: 0,
configuration: {
session_sample_rate: 40,
session_replay_sample_rate: 60,
profiling_sample_rate: 0,
},
},
application: {
id: fakeId,
},
date: 0 as TimeStamp,
source: 'browser',
session: {
id: fakeId,
type: 'user',
},
view: {
id: fakeId,
referrer: '',
url: 'fake url',
},
connectivity: {
status: 'connected',
interfaces: ['wifi'],
effective_type: '4g',
},
context: {},
}
validateRumFormat(combine(fakeContext as CommonProperties & Context, rawRumEvent))
}
function validateRumFormat(rumEvent: Context) {
const instance = new ajv({
allErrors: true,
})
instance.addSchema(allJsonSchemas)
void instance.validate('rum-events-schema.json', rumEvent)
if (instance.errors) {
const errors = instance.errors
.map((error) => {
let message = error.message
if (error.keyword === 'const') {
message += ` ${formatAllowedValues([error.params.allowedValue])}`
}
if (error.keyword === 'enum') {
message += ` ${formatAllowedValues(error.params.allowedValues)}`
}
if (error.keyword === 'additionalProperties') {
message += ` ${formatAllowedValues([error.params.additionalProperty])}`
}
return ` event${error.instancePath || ''} ${message}`
})
.join('\n')
fail(`Invalid RUM event format:\n${errors}`)
}
}
function formatAllowedValues(allowedValues: string[]) {
return allowedValues.map((v) => `'${v}'`).join(', ')
}