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-2203] Forward replay records to the bridge #2470

Merged
merged 17 commits into from Mar 5, 2024
Merged
2 changes: 2 additions & 0 deletions packages/core/src/index.ts
Expand Up @@ -57,6 +57,8 @@ export {
createHttpRequest,
canUseEventBridge,
getEventBridge,
bridgeSupports,
BridgeCapability,
startBatchWithReplica,
createFlushController,
FlushEvent,
Expand Down
66 changes: 51 additions & 15 deletions packages/core/src/transport/eventBridge.spec.ts
@@ -1,30 +1,28 @@
import { deleteEventBridgeStub, initEventBridgeStub } from '../../test'
import { getEventBridge, canUseEventBridge } from './eventBridge'
import { initEventBridgeStub } from '../../test'
import { DefaultPrivacyLevel } from '../domain/configuration'
import type { DatadogEventBridge } from './eventBridge'
import { getEventBridge, canUseEventBridge, BridgeCapability, bridgeSupports } from './eventBridge'

describe('canUseEventBridge', () => {
const allowedWebViewHosts = ['foo.bar']

afterEach(() => {
deleteEventBridgeStub()
})

it('should detect when the bridge is present and the webView host is allowed', () => {
initEventBridgeStub(allowedWebViewHosts)
initEventBridgeStub({ allowedWebViewHosts })
expect(canUseEventBridge('foo.bar')).toBeTrue()
expect(canUseEventBridge('baz.foo.bar')).toBeTrue()
expect(canUseEventBridge('www.foo.bar')).toBeTrue()
expect(canUseEventBridge('www.qux.foo.bar')).toBeTrue()
})

it('should not detect when the bridge is present and the webView host is not allowed', () => {
initEventBridgeStub(allowedWebViewHosts)
initEventBridgeStub({ allowedWebViewHosts })
expect(canUseEventBridge('foo.com')).toBeFalse()
expect(canUseEventBridge('foo.bar.baz')).toBeFalse()
expect(canUseEventBridge('bazfoo.bar')).toBeFalse()
})

it('should not detect when the bridge on the parent domain if only the subdomain is allowed', () => {
initEventBridgeStub(['baz.foo.bar'])
initEventBridgeStub({ allowedWebViewHosts: ['baz.foo.bar'] })
expect(canUseEventBridge('foo.bar')).toBeFalse()
})

Expand All @@ -33,23 +31,61 @@ describe('canUseEventBridge', () => {
})
})

describe('getEventBridge', () => {
describe('event bridge send', () => {
let sendSpy: jasmine.Spy<(msg: string) => void>

beforeEach(() => {
const eventBridgeStub = initEventBridgeStub()
sendSpy = spyOn(eventBridgeStub, 'send')
})

afterEach(() => {
deleteEventBridgeStub()
})

it('event bridge should serialize sent events', () => {
it('should serialize sent events without view', () => {
const eventBridge = getEventBridge()!

eventBridge.send('view', { foo: 'bar' })

expect(sendSpy).toHaveBeenCalledOnceWith('{"eventType":"view","event":{"foo":"bar"}}')
})

it('should serialize sent events with view', () => {
const eventBridge = getEventBridge()!

eventBridge.send('view', { foo: 'bar' }, '123')

expect(sendSpy).toHaveBeenCalledOnceWith('{"eventType":"view","event":{"foo":"bar"},"view":{"id":"123"}}')
})
})

describe('event bridge getPrivacyLevel', () => {
let eventBridgeStub: DatadogEventBridge
const bridgePrivacyLevel = DefaultPrivacyLevel.MASK

beforeEach(() => {
eventBridgeStub = initEventBridgeStub({ privacyLevel: bridgePrivacyLevel })
})

it('should return the privacy level', () => {
const eventBridge = getEventBridge()!

expect(eventBridge.getPrivacyLevel()).toEqual(bridgePrivacyLevel)
})

it('should return undefined if getPrivacyLevel not present in the bridge', () => {
delete eventBridgeStub.getPrivacyLevel
const eventBridge = getEventBridge()!

expect(eventBridge.getPrivacyLevel()).toBeUndefined()
})

describe('bridgeSupports', () => {
it('should returns true when the bridge supports a capability', () => {
initEventBridgeStub({ capabilities: [BridgeCapability.RECORDS] })
expect(bridgeSupports(BridgeCapability.RECORDS)).toBeTrue()
})

it('should returns false when the bridge does not support a capability', () => {
initEventBridgeStub({ capabilities: [] })
expect(bridgeSupports(BridgeCapability.RECORDS)).toBeFalse()
})
})
})
24 changes: 21 additions & 3 deletions packages/core/src/transport/eventBridge.ts
@@ -1,15 +1,21 @@
import { endsWith } from '../tools/utils/polyfills'
import { endsWith, includes } from '../tools/utils/polyfills'
import { getGlobalObject } from '../tools/getGlobalObject'

export interface BrowserWindowWithEventBridge extends Window {
DatadogEventBridge?: DatadogEventBridge
}

export interface DatadogEventBridge {
getCapabilities?(): string
getPrivacyLevel?(): string
getAllowedWebViewHosts(): string
send(msg: string): void
}

export const enum BridgeCapability {
RECORDS = 'records',
}

export function getEventBridge<T, E>() {
const eventBridgeGlobal = getEventBridgeGlobal()

Expand All @@ -18,15 +24,27 @@ export function getEventBridge<T, E>() {
}

return {
getCapabilities() {
return JSON.parse(eventBridgeGlobal.getCapabilities?.() || '[]') as BridgeCapability[]
},
getPrivacyLevel() {
return eventBridgeGlobal.getPrivacyLevel?.()
},
getAllowedWebViewHosts() {
return JSON.parse(eventBridgeGlobal.getAllowedWebViewHosts()) as string[]
},
send(eventType: T, event: E) {
eventBridgeGlobal.send(JSON.stringify({ eventType, event }))
send(eventType: T, event: E, viewId?: string) {
const view = viewId ? { id: viewId } : undefined
eventBridgeGlobal.send(JSON.stringify({ eventType, event, view }))
},
}
}

export function bridgeSupports(capability: BridgeCapability): boolean {
const bridge = getEventBridge()
return !!bridge && includes(bridge.getCapabilities(), capability)
}

export function canUseEventBridge(currentHost = getGlobalObject<Window>().location?.hostname): boolean {
const bridge = getEventBridge()
return (
Expand Down
9 changes: 8 additions & 1 deletion packages/core/src/transport/index.ts
@@ -1,4 +1,11 @@
export { HttpRequest, createHttpRequest, Payload, RetryInfo } from './httpRequest'
export { canUseEventBridge, getEventBridge, BrowserWindowWithEventBridge } from './eventBridge'
export {
canUseEventBridge,
bridgeSupports,
getEventBridge,
BridgeCapability,
BrowserWindowWithEventBridge,
DatadogEventBridge,
} from './eventBridge'
export { startBatchWithReplica } from './startBatchWithReplica'
export { createFlushController, FlushController, FlushEvent, FlushReason } from './flushController'
24 changes: 17 additions & 7 deletions packages/core/test/emulate/eventBridge.ts
@@ -1,14 +1,24 @@
import type { BrowserWindowWithEventBridge } from '../../src/transport'
import { DefaultPrivacyLevel } from '../../src/domain/configuration'
import { BridgeCapability } from '../../src/transport'
import type { BrowserWindowWithEventBridge, DatadogEventBridge } from '../../src/transport'
import { registerCleanupTask } from '../registerCleanupTask'

export function initEventBridgeStub(allowedWebViewHosts: string[] = [window.location.hostname]) {
const eventBridgeStub = {
export function initEventBridgeStub({
allowedWebViewHosts = [window.location.hostname],
privacyLevel = DefaultPrivacyLevel.MASK,
capabilities = [BridgeCapability.RECORDS],
}: { allowedWebViewHosts?: string[]; privacyLevel?: DefaultPrivacyLevel; capabilities?: BridgeCapability[] } = {}) {
const eventBridgeStub: DatadogEventBridge = {
send: (_msg: string) => undefined,
getAllowedWebViewHosts: () => JSON.stringify(allowedWebViewHosts),
getCapabilities: () => JSON.stringify(capabilities),
getPrivacyLevel: () => privacyLevel,
}

;(window as BrowserWindowWithEventBridge).DatadogEventBridge = eventBridgeStub
return eventBridgeStub
}

export function deleteEventBridgeStub() {
delete (window as BrowserWindowWithEventBridge).DatadogEventBridge
registerCleanupTask(() => {
delete (window as BrowserWindowWithEventBridge).DatadogEventBridge
})
return eventBridgeStub
}
12 changes: 1 addition & 11 deletions packages/logs/src/boot/preStartLogs.spec.ts
@@ -1,10 +1,4 @@
import {
mockClock,
type Clock,
deleteEventBridgeStub,
initEventBridgeStub,
mockExperimentalFeatures,
} from '@datadog/browser-core/test'
import { mockClock, type Clock, initEventBridgeStub, mockExperimentalFeatures } from '@datadog/browser-core/test'
import type { TimeStamp, TrackingConsentState } from '@datadog/browser-core'
import {
ExperimentalFeature,
Expand Down Expand Up @@ -110,10 +104,6 @@ describe('preStartLogs', () => {
initEventBridgeStub()
})

afterEach(() => {
deleteEventBridgeStub()
})

it('init should accept empty client token', () => {
const hybridInitConfiguration: HybridInitConfiguration = {}
strategy.init(hybridInitConfiguration as LogsInitConfiguration)
Expand Down
2 changes: 0 additions & 2 deletions packages/logs/src/boot/startLogs.spec.ts
Expand Up @@ -14,7 +14,6 @@ import type { Request } from '@datadog/browser-core/test'
import {
interceptRequests,
stubEndpointBuilder,
deleteEventBridgeStub,
initEventBridgeStub,
cleanupSyntheticsWorkerValues,
mockSyntheticsWorkerValues,
Expand Down Expand Up @@ -76,7 +75,6 @@ describe('logs', () => {

afterEach(() => {
delete window.DD_RUM
deleteEventBridgeStub()
stopSessionManager()
interceptor.restore()
})
Expand Down
46 changes: 32 additions & 14 deletions packages/rum-core/src/boot/preStartRum.spec.ts
Expand Up @@ -8,11 +8,11 @@ import {
TrackingConsent,
ExperimentalFeature,
createTrackingConsentState,
DefaultPrivacyLevel,
} from '@datadog/browser-core'
import type { Clock } from '@datadog/browser-core/test'
import {
cleanupSyntheticsWorkerValues,
deleteEventBridgeStub,
initEventBridgeStub,
mockClock,
mockExperimentalFeatures,
Expand Down Expand Up @@ -101,27 +101,49 @@ describe('preStartRum', () => {
})

describe('if event bridge present', () => {
beforeEach(() => {
initEventBridgeStub()
})

afterEach(() => {
deleteEventBridgeStub()
})

it('init should accept empty application id and client token', () => {
initEventBridgeStub()
const hybridInitConfiguration: HybridInitConfiguration = {}
strategy.init(hybridInitConfiguration as RumInitConfiguration)
expect(display.error).not.toHaveBeenCalled()
})

it('init should force session sample rate to 100', () => {
it('should force session sample rate to 100', () => {
initEventBridgeStub()
const invalidConfiguration: HybridInitConfiguration = { sessionSampleRate: 50 }
strategy.init(invalidConfiguration as RumInitConfiguration)
expect(strategy.initConfiguration?.sessionSampleRate).toEqual(100)
})

it('should set the default privacy level received from the bridge if the not provided in the init configuration', () => {
amortemousque marked this conversation as resolved.
Show resolved Hide resolved
initEventBridgeStub({ privacyLevel: DefaultPrivacyLevel.ALLOW })
const hybridInitConfiguration: HybridInitConfiguration = {}
strategy.init(hybridInitConfiguration as RumInitConfiguration)
expect((strategy.initConfiguration as RumInitConfiguration)?.defaultPrivacyLevel).toEqual(
DefaultPrivacyLevel.ALLOW
)
})

it('should set the default privacy level from the init configuration if provided', () => {
initEventBridgeStub({ privacyLevel: DefaultPrivacyLevel.ALLOW })
const hybridInitConfiguration: HybridInitConfiguration = { defaultPrivacyLevel: DefaultPrivacyLevel.MASK }
strategy.init(hybridInitConfiguration as RumInitConfiguration)
expect((strategy.initConfiguration as RumInitConfiguration)?.defaultPrivacyLevel).toEqual(
hybridInitConfiguration.defaultPrivacyLevel
)
})

it('should set the default privacy level to "mask" if not provided in init configuration nor the bridge', () => {
initEventBridgeStub({ privacyLevel: undefined })
const hybridInitConfiguration: HybridInitConfiguration = {}
strategy.init(hybridInitConfiguration as RumInitConfiguration)
expect((strategy.initConfiguration as RumInitConfiguration)?.defaultPrivacyLevel).toEqual(
DefaultPrivacyLevel.MASK
)
})

it('should initialize even if session cannot be handled', () => {
initEventBridgeStub()
spyOnProperty(document, 'cookie', 'get').and.returnValue('')
strategy.init(DEFAULT_INIT_CONFIGURATION)
expect(doStartRumSpy).toHaveBeenCalled()
Expand Down Expand Up @@ -195,10 +217,6 @@ describe('preStartRum', () => {
)
})

afterEach(() => {
deleteEventBridgeStub()
})

describe('with compressIntakeRequests: false', () => {
it('does not create a deflate worker', () => {
strategy.init(DEFAULT_INIT_CONFIGURATION)
Expand Down
2 changes: 2 additions & 0 deletions packages/rum-core/src/boot/preStartRum.ts
Expand Up @@ -8,6 +8,7 @@ import {
timeStampNow,
clocksNow,
assign,
getEventBridge,
} from '@datadog/browser-core'
import type { TrackingConsentState, DeflateWorker } from '@datadog/browser-core'
import {
Expand Down Expand Up @@ -179,5 +180,6 @@ function overrideInitConfigurationForBridge(initConfiguration: RumInitConfigurat
applicationId: '00000000-aaaa-0000-aaaa-000000000000',
clientToken: 'empty',
sessionSampleRate: 100,
defaultPrivacyLevel: initConfiguration.defaultPrivacyLevel ?? getEventBridge()?.getPrivacyLevel(),
})
}
2 changes: 1 addition & 1 deletion packages/rum-core/src/boot/rumPublicApi.spec.ts
@@ -1,6 +1,5 @@
import type { RelativeTime, Context, DeflateWorker, CustomerDataTrackerManager, TimeStamp } from '@datadog/browser-core'
import {
timeStampToClocks,
clocksNow,
addExperimentalFeatures,
ExperimentalFeature,
Expand All @@ -10,6 +9,7 @@ import {
DefaultPrivacyLevel,
removeStorageListeners,
CustomerDataCompressionStatus,
timeStampToClocks,
} from '@datadog/browser-core'
import { cleanupSyntheticsWorkerValues } from '@datadog/browser-core/test'
import type { TestSetupBuilder } from '../../test'
Expand Down
13 changes: 5 additions & 8 deletions packages/rum-core/src/boot/startRum.spec.ts
Expand Up @@ -12,12 +12,7 @@ import {
createTrackingConsentState,
TrackingConsent,
} from '@datadog/browser-core'
import {
createNewEvent,
interceptRequests,
initEventBridgeStub,
deleteEventBridgeStub,
} from '@datadog/browser-core/test'
import { createNewEvent, interceptRequests, initEventBridgeStub } from '@datadog/browser-core/test'
import type { RumSessionManagerMock, TestSetupBuilder } from '../../test'
import { createPerformanceEntry, createRumSessionManagerMock, noopRecorderApi, setup } from '../../test'
import { RumPerformanceEntryType } from '../browser/performanceCollection'
Expand Down Expand Up @@ -332,7 +327,6 @@ describe('view events', () => {
})

afterEach(() => {
deleteEventBridgeStub()
stopSessionManager()
interceptor.restore()
})
Expand Down Expand Up @@ -371,7 +365,10 @@ describe('view events', () => {
clock.tick(VIEW_DURATION)
window.dispatchEvent(createNewEvent('beforeunload'))

const lastBridgeMessage = JSON.parse(sendSpy.calls.mostRecent().args[0]) as { eventType: 'rum'; event: RumEvent }
const lastBridgeMessage = JSON.parse(sendSpy.calls.mostRecent().args[0]) as {
eventType: 'rum'
event: RumEvent
}
expect(lastBridgeMessage.event.type).toBe('view')
expect(lastBridgeMessage.event.view.time_spent).toBe(toServerDuration(VIEW_DURATION))
})
Expand Down