diff --git a/packages/browser-rum-angular/src/domain/angularPlugin.spec.ts b/packages/browser-rum-angular/src/domain/angularPlugin.spec.ts index a60e437340..74762b76f5 100644 --- a/packages/browser-rum-angular/src/domain/angularPlugin.spec.ts +++ b/packages/browser-rum-angular/src/domain/angularPlugin.spec.ts @@ -1,8 +1,13 @@ import { VERSION } from '@angular/core' -import { toMajorVersionIntegration } from '@datadog/browser-core' -import type { RumInitConfiguration, RumPluginOnInitOptions, RumPublicApi } from '@datadog/browser-rum-core' -import { registerCleanupTask } from '../../../browser-core/test' -import { angularPlugin, onRumInit, onRumStart, resetAngularPlugin } from './angularPlugin' +import { display, toMajorVersionIntegration } from '@datadog/browser-core' +import type { + RumInitConfiguration, + RumPluginOnInitOptions, + RumPublicApi, + StartRumResult, +} from '@datadog/browser-rum-core' +import { registerCleanupTask, waitNextMicrotask } from '../../../browser-core/test' +import { addAngularErrorWhenReady, angularPlugin, resetAngularPlugin, startAngularViewWhenReady } from './angularPlugin' const PUBLIC_API = {} as RumPublicApi const INIT_CONFIGURATION = {} as RumInitConfiguration @@ -25,38 +30,95 @@ describe('angularPlugin', () => { ) }) - it('calls callbacks registered with onRumInit during onInit', () => { - const callbackSpy = jasmine.createSpy() - const pluginConfiguration = {} - onRumInit(callbackSpy) - - expect(callbackSpy).not.toHaveBeenCalled() - + function callOnInit(configuration = { router: true }, startViewSpy = jasmine.createSpy()) { // eslint-disable-next-line @typescript-eslint/no-floating-promises -- onInit never returns a promise for this plugin - angularPlugin(pluginConfiguration).onInit!({ - publicApi: PUBLIC_API, - initConfiguration: INIT_CONFIGURATION, + angularPlugin(configuration).onInit!({ + publicApi: { startView: startViewSpy } as unknown as RumPublicApi, + initConfiguration: { ...INIT_CONFIGURATION }, } as RumPluginOnInitOptions) + return startViewSpy + } + + function fakeError(id: number) { + return { error: id } as unknown as Parameters>[0] + } - expect(callbackSpy).toHaveBeenCalledTimes(1) - expect(callbackSpy.calls.mostRecent().args[0]).toBe(pluginConfiguration) - expect(callbackSpy.calls.mostRecent().args[1]).toBe(PUBLIC_API) + it('starts views queued before onInit, in order', async () => { + startAngularViewWhenReady({ name: '/a', url: '/a' }) + startAngularViewWhenReady({ name: '/b', url: '/b' }) + + const startViewSpy = callOnInit() + await waitNextMicrotask() + + expect(startViewSpy.calls.allArgs()).toEqual([[{ name: '/a', url: '/a' }], [{ name: '/b', url: '/b' }]]) }) - it('calls callbacks immediately if onInit was already invoked', () => { - const callbackSpy = jasmine.createSpy() - const pluginConfiguration = {} - // eslint-disable-next-line @typescript-eslint/no-floating-promises -- onInit never returns a promise for this plugin - angularPlugin(pluginConfiguration).onInit!({ - publicApi: PUBLIC_API, - initConfiguration: INIT_CONFIGURATION, - } as RumPluginOnInitOptions) + it('starts views immediately after onInit', async () => { + const startViewSpy = callOnInit() + await waitNextMicrotask() + + startAngularViewWhenReady({ name: '/a', url: '/a' }) + + expect(startViewSpy).toHaveBeenCalledOnceWith({ name: '/a', url: '/a' }) + }) + + it('starts each view once when onInit runs several times', async () => { + const startViewSpy = callOnInit() + callOnInit(undefined, startViewSpy) + await waitNextMicrotask() + + startAngularViewWhenReady({ name: '/a', url: '/a' }) + + expect(startViewSpy).toHaveBeenCalledOnceWith({ name: '/a', url: '/a' }) + }) + + it('does not start views and warns when router is disabled', async () => { + const warnSpy = spyOn(display, 'warn') + startAngularViewWhenReady({ name: '/a', url: '/a' }) + + const startViewSpy = callOnInit({ router: false }) + await waitNextMicrotask() + + expect(startViewSpy).not.toHaveBeenCalled() + expect(warnSpy).toHaveBeenCalledOnceWith( + '`router: true` is missing from the angular plugin configuration, the view will not be tracked.' + ) + }) + + it('keeps only the 500 most recent views before onInit', async () => { + for (let i = 0; i < 501; i++) { + startAngularViewWhenReady({ name: `/${i}` }) + } + + const startViewSpy = callOnInit() + await waitNextMicrotask() + + expect(startViewSpy).toHaveBeenCalledTimes(500) + expect(startViewSpy.calls.first().args[0]).toEqual({ name: '/1' }) + }) + + it('adds errors queued before onRumStart, then adds new errors immediately', async () => { + addAngularErrorWhenReady(fakeError(1)) + const addErrorSpy = jasmine.createSpy() - onRumInit(callbackSpy) + angularPlugin().onRumStart!({ addError: addErrorSpy }) + await waitNextMicrotask() + addAngularErrorWhenReady(fakeError(2)) - expect(callbackSpy).toHaveBeenCalledTimes(1) - expect(callbackSpy.calls.mostRecent().args[0]).toBe(pluginConfiguration) - expect(callbackSpy.calls.mostRecent().args[1]).toBe(PUBLIC_API) + expect(addErrorSpy.calls.allArgs()).toEqual([[fakeError(1)], [fakeError(2)]]) + }) + + it('keeps only the 500 most recent errors before onRumStart', async () => { + for (let i = 0; i < 501; i++) { + addAngularErrorWhenReady(fakeError(i)) + } + const addErrorSpy = jasmine.createSpy() + + angularPlugin().onRumStart!({ addError: addErrorSpy }) + await waitNextMicrotask() + + expect(addErrorSpy).toHaveBeenCalledTimes(500) + expect(addErrorSpy.calls.first().args[0]).toEqual(fakeError(1)) }) it('enforce manual view tracking when router is enabled', () => { @@ -91,24 +153,4 @@ describe('angularPlugin', () => { integrations: [toMajorVersionIntegration('angular', VERSION.major)], }) }) - - it('calls onRumStart subscribers during onRumStart', () => { - const callbackSpy = jasmine.createSpy() - const addErrorSpy = jasmine.createSpy() - onRumStart(callbackSpy) - - angularPlugin().onRumStart!({ addError: addErrorSpy }) - - expect(callbackSpy).toHaveBeenCalledWith(addErrorSpy) - }) - - it('calls onRumStart subscribers immediately if already started', () => { - const addErrorSpy = jasmine.createSpy() - angularPlugin().onRumStart!({ addError: addErrorSpy }) - - const callbackSpy = jasmine.createSpy() - onRumStart(callbackSpy) - - expect(callbackSpy).toHaveBeenCalledWith(addErrorSpy) - }) }) diff --git a/packages/browser-rum-angular/src/domain/angularPlugin.ts b/packages/browser-rum-angular/src/domain/angularPlugin.ts index 5bdc0e7ef5..f9115a64d4 100644 --- a/packages/browser-rum-angular/src/domain/angularPlugin.ts +++ b/packages/browser-rum-angular/src/domain/angularPlugin.ts @@ -1,16 +1,29 @@ import { VERSION } from '@angular/core' -import { toIntegrations, toMajorVersionIntegration } from '@datadog/browser-core' -import type { RumPlugin, RumPublicApi, StartRumResult } from '@datadog/browser-rum-core' +import { callMonitored } from '@datadog/js-core/monitor' +import { BufferedObservable } from '@datadog/js-core/util' +import type { Subscription } from '@datadog/js-core/util' +import { display, toIntegrations, toMajorVersionIntegration } from '@datadog/browser-core' +import type { RumPlugin, StartRumResult, ViewOptions } from '@datadog/browser-rum-core' -type InitSubscriber = (configuration: AngularPluginConfiguration, rumPublicApi: RumPublicApi) => void -type StartSubscriber = (addError: StartRumResult['addError']) => void +type ErrorPayload = Parameters>[0] -let globalPublicApi: RumPublicApi | undefined -let globalConfiguration: AngularPluginConfiguration | undefined -let globalAddError: StartRumResult['addError'] | undefined +// RUM may start late, or never (e.g. during server-side rendering). Until then, buffer plain data +// rather than callbacks, which would retain the scope they were created in (router, app...), and +// cap the buffers like the core SDK pre-start buffer. +const BUFFER_LIMIT = 500 -const onRumInitSubscribers: InitSubscriber[] = [] -const onRumStartSubscribers: StartSubscriber[] = [] +let views: BufferedObservable | undefined +let errors: BufferedObservable | undefined +// onInit may run several times (e.g. init retried after an invalid configuration): keep a single view subscriber +let viewSubscription: Subscription | undefined + +function getViews() { + return (views ??= new BufferedObservable(BUFFER_LIMIT)) +} + +function getErrors() { + return (errors ??= new BufferedObservable(BUFFER_LIMIT)) +} /** * Angular plugin configuration. @@ -47,21 +60,23 @@ export function angularPlugin(configuration: AngularPluginConfiguration = {}): R return { name: 'angular', onInit({ publicApi, initConfiguration }) { - globalPublicApi = publicApi - globalConfiguration = configuration - for (const subscriber of onRumInitSubscribers) { - subscriber(globalConfiguration, globalPublicApi) - } + viewSubscription?.unsubscribe() + viewSubscription = getViews().subscribe((view) => { + if (!configuration.router) { + display.warn('`router: true` is missing from the angular plugin configuration, the view will not be tracked.') + return + } + publicApi.startView(view) + }) + getViews().unbuffer() if (configuration.router) { initConfiguration.trackViewsManually = true } }, onRumStart({ addError }) { - globalAddError = addError if (addError) { - for (const subscriber of onRumStartSubscribers) { - subscriber(addError) - } + getErrors().subscribe((error) => callMonitored(() => addError(error))) + getErrors().unbuffer() } }, getConfigurationTelemetry() { @@ -74,26 +89,17 @@ export function angularPlugin(configuration: AngularPluginConfiguration = {}): R } satisfies RumPlugin } -export function onRumInit(callback: InitSubscriber) { - if (globalConfiguration && globalPublicApi) { - callback(globalConfiguration, globalPublicApi) - } else { - onRumInitSubscribers.push(callback) - } +export function startAngularViewWhenReady(view: ViewOptions) { + getViews().notify(view) } -export function onRumStart(callback: StartSubscriber) { - if (globalAddError) { - callback(globalAddError) - } else { - onRumStartSubscribers.push(callback) - } +export function addAngularErrorWhenReady(error: ErrorPayload) { + getErrors().notify(error) } export function resetAngularPlugin() { - globalPublicApi = undefined - globalConfiguration = undefined - globalAddError = undefined - onRumInitSubscribers.length = 0 - onRumStartSubscribers.length = 0 + viewSubscription?.unsubscribe() + viewSubscription = undefined + views = undefined + errors = undefined } diff --git a/packages/browser-rum-angular/src/domain/angularRouter/provideDatadogRouter.ts b/packages/browser-rum-angular/src/domain/angularRouter/provideDatadogRouter.ts index 034c2b2755..4f0f904dee 100644 --- a/packages/browser-rum-angular/src/domain/angularRouter/provideDatadogRouter.ts +++ b/packages/browser-rum-angular/src/domain/angularRouter/provideDatadogRouter.ts @@ -2,7 +2,8 @@ import type { EnvironmentProviders } from '@angular/core' import { ENVIRONMENT_INITIALIZER, inject, makeEnvironmentProviders } from '@angular/core' import { GuardsCheckEnd, Router } from '@angular/router' import { filter } from 'rxjs' -import { startAngularView } from './startAngularView' +import { startAngularViewWhenReady } from '../angularPlugin' +import { computeViewName } from './startAngularView' /** * Angular provider that subscribes to Router events and starts a new RUM view @@ -54,8 +55,7 @@ export function provideDatadogRouter(): EnvironmentProviders { } currentPath = path - const root = event.state.root - startAngularView(root, url) + startAngularViewWhenReady({ name: computeViewName(event.state.root), url }) }) } }, diff --git a/packages/browser-rum-angular/src/domain/angularRouter/startAngularView.ts b/packages/browser-rum-angular/src/domain/angularRouter/startAngularView.ts index 6ae835d9ba..45999c2bba 100644 --- a/packages/browser-rum-angular/src/domain/angularRouter/startAngularView.ts +++ b/packages/browser-rum-angular/src/domain/angularRouter/startAngularView.ts @@ -1,22 +1,7 @@ -import { display } from '@datadog/browser-core' -import { onRumInit } from '../angularPlugin' import type { RouteSnapshot } from './types' const PRIMARY_OUTLET = 'primary' -export function startAngularView(root: RouteSnapshot, url: string) { - onRumInit((configuration, rumPublicApi) => { - if (!configuration.router) { - display.warn('`router: true` is missing from the angular plugin configuration, the view will not be tracked.') - return - } - - const viewName = computeViewName(root) - - rumPublicApi.startView({ name: viewName, url }) - }) -} - export function computeViewName(root: RouteSnapshot): string { const segments: string[] = [] let current: RouteSnapshot | undefined = root diff --git a/packages/browser-rum-angular/src/domain/error/addAngularError.spec.ts b/packages/browser-rum-angular/src/domain/error/addAngularError.spec.ts index a5a5a3879c..da842f52b5 100644 --- a/packages/browser-rum-angular/src/domain/error/addAngularError.spec.ts +++ b/packages/browser-rum-angular/src/domain/error/addAngularError.spec.ts @@ -2,9 +2,9 @@ import { initializeAngularPlugin } from '../../../test/initializeAngularPlugin' import { addAngularError } from './addAngularError' describe('addAngularError', () => { - it('delegates the error to addError', () => { + it('delegates the error to addError', async () => { const addErrorSpy = jasmine.createSpy() - initializeAngularPlugin({ + await initializeAngularPlugin({ addError: addErrorSpy, }) const originalError = new Error('error message') @@ -21,9 +21,9 @@ describe('addAngularError', () => { }) }) - it('should merge dd_context from the original error with angular error context', () => { + it('should merge dd_context from the original error with angular error context', async () => { const addErrorSpy = jasmine.createSpy() - initializeAngularPlugin({ + await initializeAngularPlugin({ addError: addErrorSpy, }) const originalError = new Error('error message') @@ -43,9 +43,9 @@ describe('addAngularError', () => { ) }) - it('handles non-Error values', () => { + it('handles non-Error values', async () => { const addErrorSpy = jasmine.createSpy() - initializeAngularPlugin({ + await initializeAngularPlugin({ addError: addErrorSpy, }) @@ -60,4 +60,20 @@ describe('addAngularError', () => { }) ) }) + + it('does not throw when reading dd_context throws', async () => { + const addErrorSpy = jasmine.createSpy() + await initializeAngularPlugin({ + addError: addErrorSpy, + }) + const originalError = new Error('error message') + Object.defineProperty(originalError, 'dd_context', { + get() { + throw new Error('dd_context getter error') + }, + }) + + expect(() => addAngularError(originalError)).not.toThrow() + expect(addErrorSpy).not.toHaveBeenCalled() + }) }) diff --git a/packages/browser-rum-angular/src/domain/error/addAngularError.ts b/packages/browser-rum-angular/src/domain/error/addAngularError.ts index d13b3e7030..ac93f7e084 100644 --- a/packages/browser-rum-angular/src/domain/error/addAngularError.ts +++ b/packages/browser-rum-angular/src/domain/error/addAngularError.ts @@ -2,7 +2,7 @@ import type { Context } from '@datadog/js-core/util' import { clocksNow } from '@datadog/js-core/time' import { callMonitored } from '@datadog/js-core/monitor' import { createHandlingStack } from '@datadog/browser-core' -import { onRumStart } from '../angularPlugin' +import { addAngularErrorWhenReady } from '../angularPlugin' /** * Add an Angular error to the RUM session. @@ -25,17 +25,15 @@ import { onRumStart } from '../angularPlugin' export function addAngularError(error: unknown) { const handlingStack = createHandlingStack('angular error') const startClocks = clocksNow() - onRumStart((addError) => { - callMonitored(() => { - addError({ - error, - handlingStack, - startClocks, - context: { - ...(typeof error === 'object' && error !== null ? (error as { dd_context?: Context }).dd_context : undefined), - framework: 'angular', - }, - }) + callMonitored(() => { + addAngularErrorWhenReady({ + error, + handlingStack, + startClocks, + context: { + ...(typeof error === 'object' && error !== null ? (error as { dd_context?: Context }).dd_context : undefined), + framework: 'angular', + }, }) }) } diff --git a/packages/browser-rum-angular/src/domain/error/provideDatadogErrorHandler.spec.ts b/packages/browser-rum-angular/src/domain/error/provideDatadogErrorHandler.spec.ts index 7118728b34..ab77e79793 100644 --- a/packages/browser-rum-angular/src/domain/error/provideDatadogErrorHandler.spec.ts +++ b/packages/browser-rum-angular/src/domain/error/provideDatadogErrorHandler.spec.ts @@ -9,9 +9,9 @@ function createErrorHandler(): ErrorHandler { } describe('provideDatadogErrorHandler', () => { - it('provides an ErrorHandler that reports errors to Datadog', () => { + it('provides an ErrorHandler that reports errors to Datadog', async () => { const addErrorSpy = jasmine.createSpy() - initializeAngularPlugin({ addError: addErrorSpy }) + await initializeAngularPlugin({ addError: addErrorSpy }) spyOn(console, 'error') // Mute console.errors const handler = createErrorHandler() @@ -20,8 +20,8 @@ describe('provideDatadogErrorHandler', () => { expect(addErrorSpy).toHaveBeenCalled() }) - it('still logs the error to the console via default ErrorHandler', () => { - initializeAngularPlugin() + it('still logs the error to the console via default ErrorHandler', async () => { + await initializeAngularPlugin() const consoleErrorSpy = spyOn(console, 'error') const handler = createErrorHandler() diff --git a/packages/browser-rum-angular/test/initializeAngularPlugin.ts b/packages/browser-rum-angular/test/initializeAngularPlugin.ts index ea742bac97..511cb35322 100644 --- a/packages/browser-rum-angular/test/initializeAngularPlugin.ts +++ b/packages/browser-rum-angular/test/initializeAngularPlugin.ts @@ -6,9 +6,9 @@ import type { } from '@datadog/browser-rum-core' import { noop } from '@datadog/js-core/util' import { angularPlugin, resetAngularPlugin } from '../src/domain/angularPlugin' -import { registerCleanupTask } from '../../browser-core/test' +import { registerCleanupTask, waitNextMicrotask } from '../../browser-core/test' -export function initializeAngularPlugin({ +export async function initializeAngularPlugin({ addError = noop, }: { addError?: StartRumResult['addError'] @@ -26,4 +26,7 @@ export function initializeAngularPlugin({ registerCleanupTask(() => { resetAngularPlugin() }) + + // Buffered views and errors are replayed, and new ones delivered, after a microtask + await waitNextMicrotask() }