Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

⚗️[RUM-2889] Bootstrap custom vital APIs #2591

Merged
merged 8 commits into from
Feb 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import type {
RumLongTaskEvent,
RumResourceEvent,
RumViewEvent,
RumVitalEvent,
} from '../../../../../../packages/rum-core/src/rumEvent.types'
import type { SdkEvent } from '../../../sdkEvent'
import { isTelemetryEvent, isLogEvent, isRumEvent } from '../../../sdkEvent'
Expand All @@ -32,6 +33,7 @@ const RUM_EVENT_TYPE_COLOR = {
view: 'blue',
resource: 'cyan',
telemetry: 'teal',
vital: 'orange',
}

const LOG_STATUS_COLOR = {
Expand Down Expand Up @@ -260,6 +262,8 @@ export const EventDescription = React.memo(({ event }: { event: SdkEvent }) => {
return <ResourceDescription event={event} />
case 'action':
return <ActionDescription event={event} />
case 'vital':
return <VitalDescription event={event} />
}
} else if (isLogEvent(event)) {
return <LogDescription event={event} />
Expand Down Expand Up @@ -322,6 +326,17 @@ function LongTaskDescription({ event }: { event: RumLongTaskEvent }) {
)
}

function VitalDescription({ event }: { event: RumVitalEvent }) {
const vitalName = Object.keys(event.vital.custom!)[0]
const vitalValue = event.vital.custom![vitalName]
return (
<>
Custom <Emphasis>{event.vital.type}</Emphasis> vital: <Emphasis>{vitalName}</Emphasis> of{' '}
<Emphasis>{vitalValue}</Emphasis>
</>
)
}

function ErrorDescription({ event }: { event: RumErrorEvent }) {
return (
<>
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/tools/experimentalFeatures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export enum ExperimentalFeature {
DISABLE_REPLAY_INLINE_CSS = 'disable_replay_inline_css',
WRITABLE_RESOURCE_GRAPHQL = 'writable_resource_graphql',
TRACKING_CONSENT = 'tracking_consent',
CUSTOM_VITALS = 'custom_vitals',
}

const enabledExperimentalFeatures: Set<ExperimentalFeature> = new Set()
Expand Down
24 changes: 24 additions & 0 deletions packages/rum-core/src/boot/preStartRum.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -510,6 +510,30 @@ describe('preStartRum', () => {
strategy.init(DEFAULT_INIT_CONFIGURATION)
expect(addFeatureFlagEvaluationSpy).toHaveBeenCalledOnceWith(key, value)
})

it('startDurationVital', () => {
const startDurationVitalSpy = jasmine.createSpy()
doStartRumSpy.and.returnValue({
startDurationVital: startDurationVitalSpy,
} as unknown as StartRumResult)

const vitalStart = { name: 'timing', startClocks: clocksNow() }
strategy.startDurationVital(vitalStart)
strategy.init(DEFAULT_INIT_CONFIGURATION)
expect(startDurationVitalSpy).toHaveBeenCalledOnceWith(vitalStart)
})

it('stopDurationVital', () => {
const stopDurationVitalSpy = jasmine.createSpy()
doStartRumSpy.and.returnValue({
stopDurationVital: stopDurationVitalSpy,
} as unknown as StartRumResult)

const vitalStop = { name: 'timing', stopClocks: clocksNow() }
strategy.stopDurationVital(vitalStop)
strategy.init(DEFAULT_INIT_CONFIGURATION)
expect(stopDurationVitalSpy).toHaveBeenCalledOnceWith(vitalStop)
})
})

describe('tracking consent', () => {
Expand Down
8 changes: 8 additions & 0 deletions packages/rum-core/src/boot/preStartRum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,14 @@ export function createPreStartStrategy(
addFeatureFlagEvaluation(key, value) {
bufferApiCalls.add((startRumResult) => startRumResult.addFeatureFlagEvaluation(key, value))
},

startDurationVital(vitalStart) {
bufferApiCalls.add((startRumResult) => startRumResult.startDurationVital(vitalStart))
},

stopDurationVital(vitalStart) {
bufferApiCalls.add((startRumResult) => startRumResult.stopDurationVital(vitalStart))
},
}
}

Expand Down
63 changes: 63 additions & 0 deletions packages/rum-core/src/boot/rumPublicApi.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import type { RelativeTime, Context, DeflateWorker, CustomerDataTrackerManager } from '@datadog/browser-core'
import {
addExperimentalFeatures,
ExperimentalFeature,
resetExperimentalFeatures,
ONE_SECOND,
display,
DefaultPrivacyLevel,
Expand All @@ -25,6 +28,8 @@ const noopStartRum = (): ReturnType<StartRum> => ({
viewContexts: {} as any,
session: {} as any,
stopSession: () => undefined,
startDurationVital: () => undefined,
stopDurationVital: () => undefined,
stop: () => undefined,
})
const DEFAULT_INIT_CONFIGURATION = { applicationId: 'xxx', clientToken: 'xxx' }
Expand Down Expand Up @@ -270,9 +275,11 @@ describe('rum public api', () => {

it('should generate a handling stack', () => {
rumPublicApi.init(DEFAULT_INIT_CONFIGURATION)

function triggerError() {
rumPublicApi.addError(new Error('message'))
}

triggerError()
expect(addErrorSpy).toHaveBeenCalledTimes(1)
const stacktrace = addErrorSpy.calls.argsFor(0)[0].handlingStack
Expand Down Expand Up @@ -714,6 +721,62 @@ describe('rum public api', () => {
})
})

describe('startDurationVital', () => {
afterEach(() => {
resetExperimentalFeatures()
})

it('should not expose startDurationVital when ff is disabled', () => {
const rumPublicApi = makeRumPublicApi(noopStartRum, noopRecorderApi)
rumPublicApi.init(DEFAULT_INIT_CONFIGURATION)
expect((rumPublicApi as any).startDurationVital).toBeUndefined()
})

it('should call startDurationVital on the startRum result when ff is enabled', () => {
addExperimentalFeatures([ExperimentalFeature.CUSTOM_VITALS])
const startDurationVitalSpy = jasmine.createSpy()
const rumPublicApi = makeRumPublicApi(
() => ({
...noopStartRum(),
startDurationVital: startDurationVitalSpy,
}),
noopRecorderApi
)
rumPublicApi.init(DEFAULT_INIT_CONFIGURATION)
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
;(rumPublicApi as any).startDurationVital('foo')
expect(startDurationVitalSpy).toHaveBeenCalledWith({ name: 'foo', startClocks: jasmine.any(Object) })
})
})

describe('stopDurationVital', () => {
afterEach(() => {
resetExperimentalFeatures()
})

it('should not expose stopDurationVital when ff is disabled', () => {
const rumPublicApi = makeRumPublicApi(noopStartRum, noopRecorderApi)
rumPublicApi.init(DEFAULT_INIT_CONFIGURATION)
expect((rumPublicApi as any).stopDurationVital).toBeUndefined()
})

it('should call stopDurationVital on the startRum result when ff is enabled', () => {
addExperimentalFeatures([ExperimentalFeature.CUSTOM_VITALS])
const stopDurationVitalSpy = jasmine.createSpy()
const rumPublicApi = makeRumPublicApi(
() => ({
...noopStartRum(),
stopDurationVital: stopDurationVitalSpy,
}),
noopRecorderApi
)
rumPublicApi.init(DEFAULT_INIT_CONFIGURATION)
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
;(rumPublicApi as any).stopDurationVital('foo')
expect(stopDurationVitalSpy).toHaveBeenCalledWith({ name: 'foo', stopClocks: jasmine.any(Object) })
})
})

it('should provide sdk version', () => {
const rumPublicApi = makeRumPublicApi(noopStartRum, noopRecorderApi)
expect(rumPublicApi.version).toBe('test')
Expand Down
19 changes: 19 additions & 0 deletions packages/rum-core/src/boot/rumPublicApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import type {
TrackingConsent,
} from '@datadog/browser-core'
import {
isExperimentalFeatureEnabled,
ExperimentalFeature,
CustomerDataType,
assign,
createContextManager,
Expand Down Expand Up @@ -82,6 +84,8 @@ export interface Strategy {
addAction: StartRumResult['addAction']
addError: StartRumResult['addError']
addFeatureFlagEvaluation: StartRumResult['addFeatureFlagEvaluation']
startDurationVital: StartRumResult['startDurationVital']
stopDurationVital: StartRumResult['stopDurationVital']
}

export function makeRumPublicApi(startRumImpl: StartRum, recorderApi: RecorderApi, options: RumPublicApiOptions = {}) {
Expand All @@ -102,6 +106,21 @@ export function makeRumPublicApi(startRumImpl: StartRum, recorderApi: RecorderAp
trackingConsentState,

(initConfiguration, configuration, deflateWorker, initialViewOptions) => {
if (isExperimentalFeatureEnabled(ExperimentalFeature.CUSTOM_VITALS)) {
;(rumPublicApi as any).startDurationVital = monitor((name: string) => {
strategy.startDurationVital({
name: sanitize(name)!,
startClocks: clocksNow(),
})
})
;(rumPublicApi as any).stopDurationVital = monitor((name: string) => {
strategy.stopDurationVital({
name: sanitize(name)!,
stopClocks: clocksNow(),
})
})
}

if (initConfiguration.storeContextsAcrossPages) {
storeContextManager(configuration, globalContextManager, RUM_STORAGE_KEY, CustomerDataType.GlobalContext)
storeContextManager(configuration, userContextManager, RUM_STORAGE_KEY, CustomerDataType.User)
Expand Down
4 changes: 4 additions & 0 deletions packages/rum-core/src/boot/startRum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import { startCustomerDataTelemetry } from '../domain/startCustomerDataTelemetry
import { startPageStateHistory } from '../domain/contexts/pageStateHistory'
import type { CommonContext } from '../domain/contexts/commonContext'
import { startDisplayContext } from '../domain/contexts/displayContext'
import { startVitalCollection } from '../domain/vital/vitalCollection'
import type { RecorderApi } from './rumPublicApi'

export type StartRum = typeof startRum
Expand Down Expand Up @@ -169,6 +170,7 @@ export function startRum(
const { stop: stopPerformanceCollection } = startPerformanceCollection(lifeCycle, configuration)
cleanupTasks.push(stopPerformanceCollection)

const vitalCollection = startVitalCollection(lifeCycle)
const internalContext = startInternalContext(
configuration.applicationId,
session,
Expand All @@ -188,6 +190,8 @@ export function startRum(
session,
stopSession: () => session.expire(),
getInternalContext: internalContext.get,
startDurationVital: vitalCollection.startDurationVital,
stopDurationVital: vitalCollection.stopDurationVital,
stop: () => {
cleanupTasks.forEach((task) => task())
},
Expand Down
1 change: 1 addition & 0 deletions packages/rum-core/src/domain/assembly.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ export function startRumAssembly(
VIEW_MODIFIABLE_FIELD_PATHS
),
[RumEventType.LONG_TASK]: assign({}, USER_CUSTOMIZABLE_FIELD_PATHS, VIEW_MODIFIABLE_FIELD_PATHS),
[RumEventType.VITAL]: assign({}, USER_CUSTOMIZABLE_FIELD_PATHS, VIEW_MODIFIABLE_FIELD_PATHS),
}
const eventRateLimiters = {
[RumEventType.ERROR]: createEventRateLimiter(
Expand Down
11 changes: 6 additions & 5 deletions packages/rum-core/src/domain/trackEventCounts.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,12 @@ describe('trackEventCounts', () => {
notifyCollectedRawRumEvent({ type: RumEventType.LONG_TASK })
expect(eventCounts.longTaskCount).toBe(1)
})

it("doesn't track views", () => {
const { eventCounts } = trackEventCounts({ lifeCycle, isChildEvent: () => true })
notifyCollectedRawRumEvent({ type: RumEventType.VIEW })
expect(objectValues(eventCounts as unknown as { [key: string]: number }).every((value) => value === 0)).toBe(true)
;[RumEventType.VIEW, RumEventType.VITAL].forEach((eventType) => {
bcaudan marked this conversation as resolved.
Show resolved Hide resolved
it(`doesn't track ${eventType} events`, () => {
const { eventCounts } = trackEventCounts({ lifeCycle, isChildEvent: () => true })
notifyCollectedRawRumEvent({ type: eventType })
expect(objectValues(eventCounts as unknown as { [key: string]: number }).every((value) => value === 0)).toBe(true)
})
})

it('tracks actions', () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/rum-core/src/domain/trackEventCounts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export function trackEventCounts({
}

const subscription = lifeCycle.subscribe(LifeCycleEventType.RUM_EVENT_COLLECTED, (event): void => {
if (event.type === 'view' || !isChildEvent(event)) {
if (event.type === 'view' || event.type === 'vital' || !isChildEvent(event)) {
return
}
switch (event.type) {
Expand Down
98 changes: 98 additions & 0 deletions packages/rum-core/src/domain/vital/vitalCollection.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { clocksNow } from '@datadog/browser-core'
import type { TestSetupBuilder } from '../../../test'
import { setup } from '../../../test'
import type { RawRumVitalEvent } from '../../rawRumEvent.types'
import { VitalType, RumEventType } from '../../rawRumEvent.types'
import { startVitalCollection } from './vitalCollection'

describe('vitalCollection', () => {
let setupBuilder: TestSetupBuilder
let vitalCollection: ReturnType<typeof startVitalCollection>

beforeEach(() => {
setupBuilder = setup()
.withFakeClock()
.beforeBuild(({ lifeCycle }) => {
vitalCollection = startVitalCollection(lifeCycle)
})
})

describe('custom duration', () => {
it('should create duration vital from start/stop API', () => {
const { rawRumEvents, clock } = setupBuilder.build()

vitalCollection.startDurationVital({ name: 'foo', startClocks: clocksNow() })
clock.tick(100)
vitalCollection.stopDurationVital({ name: 'foo', stopClocks: clocksNow() })

expect(rawRumEvents.length).toBe(1)
expect((rawRumEvents[0].rawRumEvent as RawRumVitalEvent).vital.custom.foo).toBe(100)
})

it('should not create duration vital without calling the stop API', () => {
const { rawRumEvents } = setupBuilder.build()

vitalCollection.startDurationVital({ name: 'foo', startClocks: clocksNow() })

expect(rawRumEvents.length).toBe(0)
})

it('should not create duration vital without calling the start API', () => {
const { rawRumEvents } = setupBuilder.build()

vitalCollection.stopDurationVital({ name: 'foo', stopClocks: clocksNow() })

expect(rawRumEvents.length).toBe(0)
})

it('should create multiple duration vitals from start/stop API', () => {
const { rawRumEvents, clock } = setupBuilder.build()

vitalCollection.startDurationVital({ name: 'foo', startClocks: clocksNow() })
clock.tick(100)
vitalCollection.startDurationVital({ name: 'bar', startClocks: clocksNow() })
clock.tick(100)
vitalCollection.stopDurationVital({ name: 'bar', stopClocks: clocksNow() })
clock.tick(100)
vitalCollection.stopDurationVital({ name: 'foo', stopClocks: clocksNow() })

expect(rawRumEvents.length).toBe(2)
expect((rawRumEvents[0].rawRumEvent as RawRumVitalEvent).vital.custom.bar).toBe(100)
expect((rawRumEvents[1].rawRumEvent as RawRumVitalEvent).vital.custom.foo).toBe(300)
})

it('should discard a previous start with the same name', () => {
const { rawRumEvents, clock } = setupBuilder.build()

vitalCollection.startDurationVital({ name: 'foo', startClocks: clocksNow() })
clock.tick(100)
vitalCollection.startDurationVital({ name: 'foo', startClocks: clocksNow() })
clock.tick(100)
vitalCollection.stopDurationVital({ name: 'foo', stopClocks: clocksNow() })

expect(rawRumEvents.length).toBe(1)
expect((rawRumEvents[0].rawRumEvent as RawRumVitalEvent).vital.custom.foo).toBe(100)
})
})

it('should collect raw rum event from duration vital', () => {
const { rawRumEvents } = setupBuilder.build()

vitalCollection.startDurationVital({ name: 'foo', startClocks: clocksNow() })
vitalCollection.stopDurationVital({ name: 'foo', stopClocks: clocksNow() })

expect(rawRumEvents[0].startTime).toEqual(jasmine.any(Number))
expect(rawRumEvents[0].rawRumEvent).toEqual({
date: jasmine.any(Number),
vital: {
id: jasmine.any(String),
type: VitalType.DURATION,
custom: {
foo: 0,
},
},
type: RumEventType.VITAL,
})
expect(rawRumEvents[0].domainContext).toEqual({})
})
})
Loading