-
Notifications
You must be signed in to change notification settings - Fork 190
Expand file tree
/
Copy pathpreStartRum.ts
More file actions
378 lines (314 loc) · 12.5 KB
/
Copy pathpreStartRum.ts
File metadata and controls
378 lines (314 loc) · 12.5 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
import type {
TrackingConsentState,
DeflateWorker,
Context,
Telemetry,
TimeStamp,
SessionManager,
} from '@datadog/browser-core'
import {
BufferedObservable,
display,
canUseEventBridge,
displayAlreadyInitializedError,
willSyntheticsInjectRum,
noop,
timeStampNow,
clocksNow,
getEventBridge,
initFeatureFlags,
addTelemetryConfiguration,
CustomerContextKey,
buildAccountContextManager,
buildGlobalContextManager,
buildUserContextManager,
bufferContextCalls,
monitorError,
sanitize,
startSessionManager,
startSessionManagerStub,
startTelemetry,
TelemetryService,
mockable,
isWorkerEnvironment,
startTelemetrySessionContext,
addTelemetryDebug,
} from '@datadog/browser-core'
import type { Hooks } from '../domain/hooks'
import { createHooks } from '../domain/hooks'
import type { RumConfiguration, RumInitConfiguration } from '../domain/configuration'
import {
fetchAndApplyRemoteConfiguration,
getRemoteConfiguration,
getRemoteConfigurationId,
validateAndBuildRumConfiguration,
serializeRumConfiguration,
} from '../domain/configuration'
import type { ViewOptions } from '../domain/view/trackViews'
import type { FeatureOperationOptions, FailureReason } from '../domain/vital/vitalCollection'
import { callPluginsMethod } from '../domain/plugins'
import { startTrackingConsentContext } from '../domain/contexts/trackingConsentContext'
import type { StartRumResult } from './startRum'
import type { RumPublicApiOptions, Strategy } from './rumPublicApi'
export type DoStartRum = (
configuration: RumConfiguration,
sessionManager: SessionManager,
deflateWorker: DeflateWorker | undefined,
initialViewOptions: ViewOptions | undefined,
telemetry: Telemetry,
hooks: Hooks
) => StartRumResult
export function createPreStartStrategy(
{ ignoreInitIfSyntheticsWillInjectRum = true, startDeflateWorker }: RumPublicApiOptions,
trackingConsentState: TrackingConsentState,
doStartRum: DoStartRum
): Strategy {
const BUFFER_LIMIT = 500
const bufferApiCalls = new BufferedObservable<(startRumResult: StartRumResult) => void>(BUFFER_LIMIT, (count) => {
// monitor-until: 2026-10-14
addTelemetryDebug('preStartRum buffer data lost', { count })
})
// TODO next major: remove the globalContextManager, userContextManager and accountContextManager from preStartStrategy and use an empty context instead
const globalContext = buildGlobalContextManager()
bufferContextCalls(globalContext, CustomerContextKey.globalContext, bufferApiCalls)
const userContext = buildUserContextManager()
bufferContextCalls(userContext, CustomerContextKey.userContext, bufferApiCalls)
const accountContext = buildAccountContextManager()
bufferContextCalls(accountContext, CustomerContextKey.accountContext, bufferApiCalls)
let firstStartViewCall:
| { options: ViewOptions | undefined; callback: (startRumResult: StartRumResult) => void }
| undefined
let deflateWorker: DeflateWorker | undefined
let cachedInitConfiguration: RumInitConfiguration | undefined
let cachedConfiguration: RumConfiguration | undefined
let sessionManager: SessionManager | undefined
let telemetry: Telemetry | undefined
const hooks = createHooks()
const trackingConsentStateSubscription = trackingConsentState.observable.subscribe(tryStartRum)
const emptyContext: Context = {}
let started = false
function tryStartRum() {
if (started || !cachedInitConfiguration || !cachedConfiguration || !sessionManager || !telemetry) {
return
}
trackingConsentStateSubscription.unsubscribe()
let initialViewOptions: ViewOptions | undefined
if (cachedConfiguration.trackViewsManually) {
if (!firstStartViewCall) {
return
}
// An initial view is always created when starting RUM.
// When tracking views automatically, any startView call before RUM start creates an extra
// view.
// When tracking views manually, we use the ViewOptions from the first startView call as the
// initial view options, and we skip the actual startView callback so we don't create an extra
// view.
initialViewOptions = firstStartViewCall.options
}
const callbackToSkip = cachedConfiguration.trackViewsManually ? firstStartViewCall?.callback : undefined
const startRumResult = doStartRum(
cachedConfiguration,
sessionManager,
deflateWorker,
initialViewOptions,
telemetry,
hooks
)
started = true
bufferApiCalls.subscribe((callback) => {
if (callback !== callbackToSkip) {
callback(startRumResult)
}
})
bufferApiCalls.unbuffer()
}
function doInit(initConfiguration: RumInitConfiguration, errorStack?: string) {
const eventBridgeAvailable = canUseEventBridge()
if (eventBridgeAvailable) {
initConfiguration = overrideInitConfigurationForBridge(initConfiguration)
}
// Update the exposed initConfiguration to reflect the bridge and remote configuration overrides
cachedInitConfiguration = initConfiguration
if (cachedConfiguration) {
displayAlreadyInitializedError('DD_RUM', initConfiguration)
return
}
const configuration = validateAndBuildRumConfiguration(initConfiguration, errorStack)
if (!configuration) {
return
}
if (configuration.compressIntakeRequests && !eventBridgeAvailable && startDeflateWorker) {
deflateWorker = startDeflateWorker(
configuration,
'Datadog RUM',
// Worker initialization can fail asynchronously, especially in Firefox where even CSP
// issues are reported asynchronously. For now, the SDK will continue its execution even if
// data won't be sent to Datadog. We could improve this behavior in the future.
noop
)
if (!deflateWorker) {
// `startDeflateWorker` should have logged an error message explaining the issue
return
}
}
cachedConfiguration = configuration
trackingConsentState.tryToInit(configuration.trackingConsent)
trackingConsentState.onGrantedOnce(() => {
startTrackingConsentContext(hooks, trackingConsentState)
telemetry = mockable(startTelemetry)(TelemetryService.RUM, configuration, hooks)
if (isWorkerEnvironment) {
display.warn('The RUM SDK is not supported in a web or service worker environment.')
return
}
const sessionManagerPromise = canUseEventBridge()
? startSessionManagerStub()
: mockable(startSessionManager)(configuration, trackingConsentState)
void sessionManagerPromise
.then((newSessionManager) => {
if (!newSessionManager) {
return
}
sessionManager = newSessionManager
startTelemetrySessionContext(hooks, sessionManager, { application: { id: configuration.applicationId } })
addTelemetryConfiguration(serializeRumConfiguration(initConfiguration))
tryStartRum()
})
.catch(monitorError)
})
}
const addOperationStepVital = (
name: string,
stepType: 'start' | 'end',
options?: FeatureOperationOptions,
failureReason?: FailureReason
) => {
bufferApiCalls.notify((startRumResult) =>
startRumResult.addOperationStepVital(
sanitize(name)!,
stepType,
sanitize(options) as FeatureOperationOptions,
sanitize(failureReason) as FailureReason | undefined
)
)
}
const strategy: Strategy = {
init(initConfiguration, publicApi, errorStack) {
if (!initConfiguration) {
display.error('Missing configuration')
return
}
// Set the experimental feature flags as early as possible, so we can use them in most places
initFeatureFlags(initConfiguration.enableExperimentalFeatures)
// Expose the initial configuration regardless of initialization success.
cachedInitConfiguration = initConfiguration
// If we are in a Synthetics test configured to automatically inject a RUM instance, we want
// to completely discard the customer application RUM instance by ignoring their init() call.
// But, we should not ignore the init() call from the Synthetics-injected RUM instance, so the
// internal `ignoreInitIfSyntheticsWillInjectRum` option is here to bypass this condition.
if (ignoreInitIfSyntheticsWillInjectRum && willSyntheticsInjectRum()) {
return
}
callPluginsMethod(initConfiguration.plugins, 'onInit', { initConfiguration, publicApi })
const hasRemoteConfiguration = getRemoteConfigurationId(initConfiguration)
if (hasRemoteConfiguration) {
const supportedContextManagers = { user: userContext, context: globalContext }
const isSyncLoading = !!initConfiguration.remoteConfigurationId || !!initConfiguration.remoteConfiguration?.sync
if (isSyncLoading) {
fetchAndApplyRemoteConfiguration(initConfiguration, supportedContextManagers)
.then((resolvedInitConfiguration) => {
if (resolvedInitConfiguration) {
doInit(resolvedInitConfiguration, errorStack)
}
})
.catch(monitorError)
} else {
doInit(getRemoteConfiguration(initConfiguration, supportedContextManagers), errorStack)
}
} else {
doInit(initConfiguration, errorStack)
}
},
get initConfiguration() {
return cachedInitConfiguration
},
getInternalContext: noop as () => undefined,
stopSession: noop,
addTiming(name, time = timeStampNow()) {
bufferApiCalls.notify((startRumResult) => startRumResult.addTiming(name, time))
},
setLoadingTime: ((callTimestamp: TimeStamp) => {
bufferApiCalls.notify((startRumResult) => startRumResult.setLoadingTime(callTimestamp))
}) as Strategy['setLoadingTime'],
startView(options, startClocks = clocksNow()) {
const callback = (startRumResult: StartRumResult) => {
startRumResult.startView(options, startClocks)
}
bufferApiCalls.notify(callback)
if (!firstStartViewCall) {
firstStartViewCall = { options, callback }
tryStartRum()
}
},
setViewName(name) {
bufferApiCalls.notify((startRumResult) => startRumResult.setViewName(name))
},
// View context APIs
setViewContext(context) {
bufferApiCalls.notify((startRumResult) => startRumResult.setViewContext(context))
},
setViewContextProperty(key, value) {
bufferApiCalls.notify((startRumResult) => startRumResult.setViewContextProperty(key, value))
},
getViewContext: () => emptyContext,
globalContext,
userContext,
accountContext,
addAction(action) {
bufferApiCalls.notify((startRumResult) => startRumResult.addAction(action))
},
startAction(name, options) {
const startClocks = clocksNow()
bufferApiCalls.notify((startRumResult) => startRumResult.startAction(name, options, startClocks))
},
stopAction(name, options) {
const stopClocks = clocksNow()
bufferApiCalls.notify((startRumResult) => startRumResult.stopAction(name, options, stopClocks))
},
startResource(url, options) {
const startClocks = clocksNow()
bufferApiCalls.notify((startRumResult) => startRumResult.startResource(url, options, startClocks))
},
stopResource(url, options) {
const stopClocks = clocksNow()
bufferApiCalls.notify((startRumResult) => startRumResult.stopResource(url, options, stopClocks))
},
addError(providedError) {
bufferApiCalls.notify((startRumResult) => startRumResult.addError(providedError))
},
addFeatureFlagEvaluation(key, value) {
bufferApiCalls.notify((startRumResult) => startRumResult.addFeatureFlagEvaluation(key, value))
},
startDurationVital(name, options) {
const startClocks = clocksNow()
bufferApiCalls.notify((startRumResult) => startRumResult.startDurationVital(name, options, startClocks))
},
stopDurationVital(name, options) {
const stopClocks = clocksNow()
bufferApiCalls.notify((startRumResult) => startRumResult.stopDurationVital(name, options, stopClocks))
},
addDurationVital(vital) {
bufferApiCalls.notify((startRumResult) => startRumResult.addDurationVital(vital))
},
addOperationStepVital,
}
return strategy
}
function overrideInitConfigurationForBridge(initConfiguration: RumInitConfiguration): RumInitConfiguration {
return {
...initConfiguration,
applicationId: '00000000-aaaa-0000-aaaa-000000000000',
clientToken: 'empty',
sessionSampleRate: 100,
defaultPrivacyLevel: initConfiguration.defaultPrivacyLevel ?? getEventBridge()?.getPrivacyLevel(),
}
}