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

♻️ [Logs] reorganise some components #2519

Merged
merged 6 commits into from
Dec 8, 2023
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
97 changes: 8 additions & 89 deletions packages/logs/src/boot/startLogs.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,12 @@
import type { Context, TelemetryEvent, RawError, Observable, PageExitEvent } from '@datadog/browser-core'
import {
sendToExtension,
createPageExitObservable,
TelemetryService,
willSyntheticsInjectRum,
canUseEventBridge,
getEventBridge,
startTelemetry,
startBatchWithReplica,
isTelemetryReplicationAllowed,
ErrorSource,
addTelemetryConfiguration,
addTelemetryDebug,
createIdentityEncoder,
} from '@datadog/browser-core'
import { startLogsSessionManager, startLogsSessionManagerStub } from '../domain/logsSessionManager'
import type { LogsConfiguration, LogsInitConfiguration } from '../domain/configuration'
import { serializeLogsConfiguration } from '../domain/configuration'
import { startLogsAssembly, getRUMInternalContext } from '../domain/assembly'
import { startLogsAssembly } from '../domain/assembly'
import { startConsoleCollection } from '../domain/console/consoleCollection'
import { startReportCollection } from '../domain/report/reportCollection'
import { startNetworkErrorCollection } from '../domain/networkError/networkErrorCollection'
Expand All @@ -27,8 +16,9 @@ import { startLoggerCollection } from '../domain/logger/loggerCollection'
import type { CommonContext } from '../rawLogsEvent.types'
import { startLogsBatch } from '../transport/startLogsBatch'
import { startLogsBridge } from '../transport/startLogsBridge'
import { StatusType } from '../domain/logger'
import { startInternalContext } from '../domain/internalContext'
import { startReportError } from '../domain/reportError'
import { startLogsTelemetry } from '../domain/logsTelemetry'

export function startLogs(
initConfiguration: LogsInitConfiguration,
Expand All @@ -40,45 +30,22 @@ export function startLogs(

lifeCycle.subscribe(LifeCycleEventType.LOG_COLLECTED, (log) => sendToExtension('logs', log))

const reportError = (error: RawError) => {
lifeCycle.notify(LifeCycleEventType.RAW_LOG_COLLECTED, {
rawLogsEvent: {
message: error.message,
date: error.startClocks.timeStamp,
origin: ErrorSource.AGENT,
status: StatusType.error,
},
})
addTelemetryDebug('Error reported to customer', { 'error.message': error.message })
}
const reportError = startReportError(lifeCycle)
const pageExitObservable = createPageExitObservable(configuration)

const session =
configuration.sessionStoreStrategyType && !canUseEventBridge() && !willSyntheticsInjectRum()
? startLogsSessionManager(configuration)
: startLogsSessionManagerStub(configuration)

const { telemetry, stop: stopLogsTelemetry } = startLogsTelemetry(
const { stop: stopLogsTelemetry } = startLogsTelemetry(
initConfiguration,
configuration,
reportError,
pageExitObservable,
session.expireObservable
session
)
cleanupTasks.push(() => stopLogsTelemetry())
telemetry.setContextProvider(() => ({
application: {
id: getRUMInternalContext()?.application_id,
},
session: {
id: session.findTrackedSession()?.id,
},
view: {
id: (getRUMInternalContext()?.view as Context)?.id,
},
action: {
id: (getRUMInternalContext()?.user_action as Context)?.id,
},
}))

startNetworkErrorCollection(configuration, lifeCycle)
startRuntimeErrorCollection(configuration, lifeCycle)
Expand All @@ -89,19 +56,12 @@ export function startLogs(
startLogsAssembly(session, configuration, lifeCycle, buildCommonContext, reportError)

if (!canUseEventBridge()) {
const { stop: stopLogsBatch } = startLogsBatch(
configuration,
lifeCycle,
reportError,
pageExitObservable,
session.expireObservable
)
const { stop: stopLogsBatch } = startLogsBatch(configuration, lifeCycle, reportError, pageExitObservable, session)
cleanupTasks.push(() => stopLogsBatch())
} else {
startLogsBridge(lifeCycle)
}

addTelemetryConfiguration(serializeLogsConfiguration(initConfiguration))
const internalContext = startInternalContext(session)

return {
Expand All @@ -112,44 +72,3 @@ export function startLogs(
},
}
}

function startLogsTelemetry(
configuration: LogsConfiguration,
reportError: (error: RawError) => void,
pageExitObservable: Observable<PageExitEvent>,
sessionExpireObservable: Observable<void>
) {
const telemetry = startTelemetry(TelemetryService.LOGS, configuration)
const cleanupTasks: Array<() => void> = []
if (canUseEventBridge()) {
const bridge = getEventBridge<'internal_telemetry', TelemetryEvent>()!
const telemetrySubscription = telemetry.observable.subscribe((event) => bridge.send('internal_telemetry', event))
cleanupTasks.push(() => telemetrySubscription.unsubscribe())
} else {
const telemetryBatch = startBatchWithReplica(
configuration,
{
endpoint: configuration.rumEndpointBuilder,
encoder: createIdentityEncoder(),
},
configuration.replica && {
endpoint: configuration.replica.rumEndpointBuilder,
encoder: createIdentityEncoder(),
},
reportError,
pageExitObservable,
sessionExpireObservable
)
cleanupTasks.push(() => telemetryBatch.stop())
const telemetrySubscription = telemetry.observable.subscribe((event) =>
telemetryBatch.add(event, isTelemetryReplicationAllowed(configuration))
)
cleanupTasks.push(() => telemetrySubscription.unsubscribe())
}
return {
telemetry,
stop: () => {
cleanupTasks.forEach((task) => task())
},
}
}
84 changes: 4 additions & 80 deletions packages/logs/src/domain/assembly.spec.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,10 @@
import type { Context, RelativeTime, TelemetryEvent, TimeStamp } from '@datadog/browser-core'
import {
Observable,
TelemetryService,
startTelemetry,
ErrorSource,
ONE_MINUTE,
getTimeStamp,
noop,
} from '@datadog/browser-core'
import type { Context, RelativeTime, TimeStamp } from '@datadog/browser-core'
import { Observable, ErrorSource, ONE_MINUTE, getTimeStamp, noop } from '@datadog/browser-core'
import type { Clock } from '@datadog/browser-core/test'
import { mockClock, cleanupSyntheticsWorkerValues, mockSyntheticsWorkerValues } from '@datadog/browser-core/test'
import { mockClock } from '@datadog/browser-core/test'
import type { LogsEvent } from '../logsEvent.types'
import type { CommonContext } from '../rawLogsEvent.types'
import { getRUMInternalContext, resetRUMInternalContext, startLogsAssembly } from './assembly'
import { startLogsAssembly } from './assembly'
import { validateAndBuildLogsConfiguration } from './configuration'
import { Logger, StatusType } from './logger'
import type { LogsSessionManager } from './logsSessionManager'
Expand Down Expand Up @@ -527,71 +519,3 @@ describe('logs limitation', () => {
)
})
})

describe('getRUMInternalContext', () => {
afterEach(() => {
delete window.DD_RUM
delete window.DD_RUM_SYNTHETICS
resetRUMInternalContext()
})

it('returns undefined if no RUM instance is present', () => {
expect(getRUMInternalContext()).toBeUndefined()
})

it('returns undefined if the global variable does not have a `getInternalContext` method', () => {
window.DD_RUM = {} as any
expect(getRUMInternalContext()).toBeUndefined()
})

it('returns the internal context from the `getInternalContext` method', () => {
window.DD_RUM = {
getInternalContext: () => ({ foo: 'bar' }),
}
expect(getRUMInternalContext()).toEqual({ foo: 'bar' })
})

describe('when RUM is injected by Synthetics', () => {
let telemetrySpy: jasmine.Spy<(event: TelemetryEvent) => void>

beforeEach(() => {
mockSyntheticsWorkerValues({ injectsRum: true, publicId: 'test-id', resultId: 'result-id' })
const telemetry = startTelemetry(
TelemetryService.LOGS,
validateAndBuildLogsConfiguration({ ...initConfiguration, telemetrySampleRate: 100 })!
)
telemetrySpy = jasmine.createSpy()
telemetry.observable.subscribe(telemetrySpy)
})

afterEach(() => {
cleanupSyntheticsWorkerValues()
})

it('uses the global variable created when the synthetics worker is injecting RUM', () => {
window.DD_RUM_SYNTHETICS = {
getInternalContext: () => ({ foo: 'bar' }),
}
expect(getRUMInternalContext()).toEqual({ foo: 'bar' })
})

it('adds a telemetry debug event when RUM has not been injected yet', () => {
getRUMInternalContext()
expect(telemetrySpy.calls.mostRecent().args[0].telemetry).toEqual(
jasmine.objectContaining({
message: 'Logs sent before RUM is injected by the synthetics worker',
status: 'debug',
type: 'log',
testId: 'test-id',
resultId: 'result-id',
})
)
})

it('adds the telemetry debug event only once', () => {
getRUMInternalContext()
getRUMInternalContext()
expect(telemetrySpy).toHaveBeenCalledTimes(1)
})
})
})
54 changes: 3 additions & 51 deletions packages/logs/src/domain/assembly.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,12 @@
import type { Context, EventRateLimiter, RawError, RelativeTime } from '@datadog/browser-core'
import {
getSyntheticsResultId,
getSyntheticsTestId,
addTelemetryDebug,
willSyntheticsInjectRum,
ErrorSource,
combine,
createEventRateLimiter,
getRelativeTime,
isEmptyObject,
} from '@datadog/browser-core'
import type { EventRateLimiter, RawError } from '@datadog/browser-core'
import { ErrorSource, combine, createEventRateLimiter, getRelativeTime, isEmptyObject } from '@datadog/browser-core'
import type { CommonContext } from '../rawLogsEvent.types'
import type { LogsConfiguration } from './configuration'
import type { LifeCycle } from './lifeCycle'
import { LifeCycleEventType } from './lifeCycle'
import { STATUSES } from './logger'
import type { LogsSessionManager } from './logsSessionManager'
import { getRUMInternalContext } from './rumInternalContext'

export function startLogsAssembly(
sessionManager: LogsSessionManager,
Expand Down Expand Up @@ -67,42 +58,3 @@ export function startLogsAssembly(
}
)
}

interface Rum {
getInternalContext?: (startTime?: RelativeTime) => Context | undefined
}

interface BrowserWindow {
DD_RUM?: Rum
DD_RUM_SYNTHETICS?: Rum
}

let logsSentBeforeRumInjectionTelemetryAdded = false

export function getRUMInternalContext(startTime?: RelativeTime): Context | undefined {
const browserWindow = window as BrowserWindow

if (willSyntheticsInjectRum()) {
const context = getInternalContextFromRumGlobal(browserWindow.DD_RUM_SYNTHETICS)
if (!context && !logsSentBeforeRumInjectionTelemetryAdded) {
logsSentBeforeRumInjectionTelemetryAdded = true
addTelemetryDebug('Logs sent before RUM is injected by the synthetics worker', {
testId: getSyntheticsTestId(),
resultId: getSyntheticsResultId(),
})
}
return context
}

return getInternalContextFromRumGlobal(browserWindow.DD_RUM)

function getInternalContextFromRumGlobal(rumGlobal?: Rum): Context | undefined {
if (rumGlobal && rumGlobal.getInternalContext) {
return rumGlobal.getInternalContext(startTime)
}
}
}

export function resetRUMInternalContext() {
logsSentBeforeRumInjectionTelemetryAdded = false
}
72 changes: 72 additions & 0 deletions packages/logs/src/domain/logsTelemetry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import type { RawError, Observable, PageExitEvent, TelemetryEvent, Context } from '@datadog/browser-core'
import {
startTelemetry,
TelemetryService,
canUseEventBridge,
getEventBridge,
startBatchWithReplica,
createIdentityEncoder,
isTelemetryReplicationAllowed,
addTelemetryConfiguration,
} from '@datadog/browser-core'
import type { LogsConfiguration, LogsInitConfiguration } from './configuration'
import { getRUMInternalContext } from './rumInternalContext'
import type { LogsSessionManager } from './logsSessionManager'
import { serializeLogsConfiguration } from './configuration'

export function startLogsTelemetry(
initConfiguration: LogsInitConfiguration,
configuration: LogsConfiguration,
reportError: (error: RawError) => void,
pageExitObservable: Observable<PageExitEvent>,
session: LogsSessionManager
) {
const telemetry = startTelemetry(TelemetryService.LOGS, configuration)
telemetry.setContextProvider(() => ({
application: {
id: getRUMInternalContext()?.application_id,
},
session: {
id: session.findTrackedSession()?.id,
},
view: {
id: (getRUMInternalContext()?.view as Context)?.id,
},
action: {
id: (getRUMInternalContext()?.user_action as Context)?.id,
},
}))
const cleanupTasks: Array<() => void> = []
if (canUseEventBridge()) {
const bridge = getEventBridge<'internal_telemetry', TelemetryEvent>()!
const telemetrySubscription = telemetry.observable.subscribe((event) => bridge.send('internal_telemetry', event))
cleanupTasks.push(() => telemetrySubscription.unsubscribe())
} else {
const telemetryBatch = startBatchWithReplica(
configuration,
{
endpoint: configuration.rumEndpointBuilder,
encoder: createIdentityEncoder(),
},
configuration.replica && {
endpoint: configuration.replica.rumEndpointBuilder,
encoder: createIdentityEncoder(),
},
reportError,
pageExitObservable,
session.expireObservable
)
cleanupTasks.push(() => telemetryBatch.stop())
const telemetrySubscription = telemetry.observable.subscribe((event) =>
telemetryBatch.add(event, isTelemetryReplicationAllowed(configuration))
)
cleanupTasks.push(() => telemetrySubscription.unsubscribe())
}
addTelemetryConfiguration(serializeLogsConfiguration(initConfiguration))
return {
telemetry,
stop: () => {
cleanupTasks.forEach((task) => task())
},
}
}
Loading