diff --git a/package.json b/package.json index 03bd932871..8578f96af1 100644 --- a/package.json +++ b/package.json @@ -46,7 +46,7 @@ "woke": "scripts/cli woke" }, "devDependencies": { - "@datadog/rum-events-format": "DataDog/rum-events-format#commit=748d7fe6d0e36624b7ea64e26731e43e347637b5", + "@datadog/rum-events-format": "DataDog/rum-events-format#commit=79c264a627e2ebba7182e5d088aad84124de23c8", "@eslint/js": "10.0.1", "@microsoft/api-extractor": "7.60.1", "@oxc-project/runtime": "0.152.0", diff --git a/packages/browser-debugger/README.md b/packages/browser-debugger/README.md index 05850e62aa..b0db07f0b2 100644 --- a/packages/browser-debugger/README.md +++ b/packages/browser-debugger/README.md @@ -47,6 +47,18 @@ If you set `version` for version-specific probe targeting, use an immutable depl When the [RUM Browser SDK][4] is loaded on the page, the first hit of each probe creates a RUM custom action named `probe: ()`. For probes evaluated at function entry, the action lasts until the instrumented function returns or throws. For probes evaluated at function exit, the action is a point in time at the function exit. The action's context includes the probe, the ID of the snapshot sent for that hit, and the outcome (`return` or `throw`, with the error type). Only hits that pass sampling and the probe condition count. To disable this, set `trackProbeHitsAsRumActions: false` in `init()`. +## Exception Replay + +Exception Replay captures the arguments and `this` of the instrumented functions an error passes through, and shows them on the error's stack frames in Error Tracking, without adding probes. It requires the [RUM Browser SDK][4], at the same version as the Live Debugger SDK: + +1. Build your application with the Live Debugger build plugin's [`exceptionReplay`][8] option. +2. Load the RUM Browser SDK, or its async loading snippet, before you call `DD_DEBUGGER.init()`. With npm, importing `@datadog/browser-rum` is enough. You don't need to change your RUM configuration: `DD_DEBUGGER.init()` adds Exception Replay to the RUM Browser SDK, whether or not RUM is already initialized. +3. Initialize the Live Debugger SDK as shown in [Usage](#usage). It must send to the same Datadog site and organization as the RUM Browser SDK, or Error Tracking can't find the snapshots of RUM errors. + +The SDK captures the three innermost instrumented frames of an exception as it's thrown. It only sends them as snapshots once RUM sends the error, after `beforeSend` and the event rate limits. It doesn't capture anything in sessions that RUM doesn't track, or before tracking consent is granted. Snapshots are linked to frames by their position in `error.stack`, so a `beforeSend` that removes or reorders frames there can show them on the wrong frames. An error with the same type and innermost instrumented function is reported with snapshots at most once an hour. Values of variables and properties with sensitive names, such as `password` or `token`, are redacted. Local variables aren't captured. + +To limit the time spent on the main thread, Exception Replay captures at most 10 exceptions per second, and spends at most 25 ms per second on average capturing them. When a capture takes longer, capturing pauses until the time is made up. These limits are separate from `maxSnapshotsPerSecondGlobally`, which only applies to probes. + ## Troubleshooting Need help? Contact [Datadog Support][3]. @@ -60,3 +72,4 @@ Need help? Contact [Datadog Support][3]. [5]: https://github.com/DataDog/build-plugins/tree/master/packages/plugins/live-debugger [6]: https://github.com/DataDog/build-plugins/tree/master/packages/plugins/live-debugger#source-maps [7]: https://github.com/DataDog/build-plugins/tree/master/packages/plugins/live-debugger#limitations-during-preview +[8]: https://github.com/DataDog/build-plugins/tree/master/packages/plugins/live-debugger#livedebuggerexceptionreplay diff --git a/packages/browser-debugger/package.json b/packages/browser-debugger/package.json index e6353452ed..8c6d873bd0 100644 --- a/packages/browser-debugger/package.json +++ b/packages/browser-debugger/package.json @@ -18,6 +18,9 @@ "build:bundle": "node ../../scripts/build/build-package.ts --bundle datadog-debugger.js", "prepack": "yarn build" }, + "devDependencies": { + "@datadog/browser-rum-core": "workspace:*" + }, "dependencies": { "@datadog/browser-core": "workspace:*", "@datadog/js-core": "workspace:*" diff --git a/packages/browser-debugger/src/domain/api.ts b/packages/browser-debugger/src/domain/api.ts index d382c5cb21..383328887e 100644 --- a/packages/browser-debugger/src/domain/api.ts +++ b/packages/browser-debugger/src/domain/api.ts @@ -6,7 +6,7 @@ import { monitorError } from '@datadog/js-core/monitor' import { buildDebugIdByUrl, buildTag, mergeArrays } from '@datadog/browser-core' import type { BrowserWindow, DebuggerInitConfiguration } from '../entries/main' import { capture, captureFields } from './capture' -import type { CaptureContext } from './capture' +import type { CaptureContext, CaptureOptions } from './capture' import type { InitializedProbe } from './probes' import { checkConditionErrorBudget, @@ -23,6 +23,7 @@ import { evaluateProbeMessage } from './template' import { evaluateProbeCondition, isConditionEvaluationError } from './condition' import { display } from './display' import { formatThrowable } from './error' +import type { Throwable } from './error' import { evaluateCaptureExpressions } from './captureExpressions' import { addExitProbeRumAction, startProbeRumAction, stopProbeRumAction } from './rumAction' @@ -434,11 +435,84 @@ function queueDebuggerSnapshot(result: ActiveEntry): void { recordProbeEventSent(probe) } +/** + * A snapshot that no probe produced: Exception Replay captures one for each instrumented frame an + * exception leaves (see `exceptionReplay.ts`). + */ +export interface ExceptionSnapshot { + id: string + exceptionId: string + timestamp: number + message: string + location: { type: string; method: string } + stack: StackFrame[] + arguments: Record + throwable: Throwable +} + +/** + * Whether snapshots can be sent, which requires `DD_DEBUGGER.init()` to have been called. + */ +export function isDebuggerTransportInitialized(): boolean { + return debuggerBatch !== undefined && debuggerConfig !== undefined +} + +/** + * Queue an Exception Replay snapshot for delivery via the debugger's own transport. Does nothing + * until `DD_DEBUGGER.init()` has been called. + */ +export function queueExceptionSnapshot(snapshot: ExceptionSnapshot): void { + if (!debuggerBatch || !debuggerConfig) { + return + } + + const version = globalObj.DD_DEBUGGER!.version + const debugIds = buildDebugIdByUrl(collectStackFrameUrls(snapshot.throwable.stacktrace, snapshot.stack)) + + debuggerBatch.add({ + message: snapshot.message, + service: debuggerConfig.service, + ddtags: getDebuggerDDtags(version), + _dd: (debugIds ? { debug_ids: debugIds } : undefined) as ContextValue, + logger: { + name: snapshot.location.type, + method: snapshot.location.method, + version, + thread_name: threadName, + }, + debugger: { + snapshot: { + id: snapshot.id, + // Marks the snapshot as an Exception Replay snapshot in the Datadog UI + exceptionId: snapshot.exceptionId, + timestamp: snapshot.timestamp, + probe: { + // No probe produced the snapshot, so like the tracers' Exception Replay, give it a probe + // ID of its own + id: generateUUID(), + version: 0, + location: snapshot.location, + }, + stack: snapshot.stack, + language: 'javascript', + captures: { + return: { arguments: snapshot.arguments, throwable: snapshot.throwable }, + } as ContextValue, + }, + }, + }) +} + function buildSnapshotDebugIds(result: ActiveEntry) { + return buildDebugIdByUrl(collectStackFrameUrls(result.return?.throwable?.stacktrace, result.stack)) +} + +function collectStackFrameUrls(...stacks: Array): string[] { const urls: string[] = [] - appendStackFrameUrls(urls, result.return?.throwable?.stacktrace) - appendStackFrameUrls(urls, result.stack) - return buildDebugIdByUrl(urls) + for (const stack of stacks) { + appendStackFrameUrls(urls, stack) + } + return urls } function appendStackFrameUrls(urls: string[], stack: StackFrame[] | undefined): void { @@ -451,10 +525,13 @@ function appendStackFrameUrls(urls: string[], stack: StackFrame[] | undefined): } } -function captureArguments( +/** + * Capture a function's arguments, along with its receiver as `this` unless it's the global object. + */ +export function captureArguments( args: Record, self: any, - captureOptions: InitializedProbe['capture'], + captureOptions: CaptureOptions, captureCtx: CaptureContext ): Record { const fields = captureFields(args, captureOptions, captureCtx) diff --git a/packages/browser-debugger/src/domain/capture.spec.ts b/packages/browser-debugger/src/domain/capture.spec.ts index 8ff598a20a..969cabd147 100644 --- a/packages/browser-debugger/src/domain/capture.spec.ts +++ b/packages/browser-debugger/src/domain/capture.spec.ts @@ -793,3 +793,109 @@ describe('capture timeout', () => { expect(result.field2).toEqual({ type: 'Object', notCapturedReason: 'timeout' }) }) }) + +describe('capture redaction', () => { + const defaultOpts = {} + + function redactingContext(): CaptureContext { + return { deadline: Infinity, timedOut: false, redact: true } + } + + it('should redact the values of fields named after sensitive identifiers', () => { + const result = captureFields( + { password: 'hunter2', apiKey: 'abc', 'X-Csrf-Token': 'def', session: { id: 1 }, username: 'alice' }, + defaultOpts, + redactingContext() + ) + + expect(result).toEqual({ + password: { type: 'string', notCapturedReason: 'redactedIdent' }, + apiKey: { type: 'string', notCapturedReason: 'redactedIdent' }, + 'X-Csrf-Token': { type: 'string', notCapturedReason: 'redactedIdent' }, + session: { type: 'Object', notCapturedReason: 'redactedIdent' }, + username: { type: 'string', value: 'alice' }, + }) + }) + + it('should redact nested fields', () => { + const result = capture({ user: { name: 'alice', token: 'abc' } }, defaultOpts, redactingContext()) + + expect(result.fields!.user.fields).toEqual({ + name: { type: 'string', value: 'alice' }, + token: { type: 'string', notCapturedReason: 'redactedIdent' }, + }) + }) + + it('should redact the values of map entries with sensitive string keys', () => { + const result = capture( + new Map([ + ['Authorization', 'Bearer abc'], + [1, 'one'], + ]), + defaultOpts, + redactingContext() + ) + + expect(result.entries).toEqual([ + [ + { type: 'string', value: 'Authorization' }, + { type: 'string', notCapturedReason: 'redactedIdent' }, + ], + [ + { type: 'number', value: '1' }, + { type: 'string', value: 'one' }, + ], + ]) + }) + + it('should redact the values of fields and map entries with sensitive symbol keys', () => { + const passwordKey = Symbol('password') + const tokenKey = Symbol('token') + + expect( + captureFields({ [passwordKey]: 'hunter2', [Symbol('name')]: 'alice' }, defaultOpts, redactingContext()) + ).toEqual({ + password: { type: 'string', notCapturedReason: 'redactedIdent' }, + name: { type: 'string', value: 'alice' }, + }) + expect(capture(new Map([[tokenKey, 'abc']]), defaultOpts, redactingContext()).entries).toEqual([ + [jasmine.objectContaining({ type: 'symbol' }), { type: 'string', notCapturedReason: 'redactedIdent' }], + ]) + }) + + it('should not use the constructor name of a redacted object', () => { + expect(captureFields({ password: { constructor: { name: 'hunter2' } } }, defaultOpts, redactingContext())).toEqual({ + password: { type: 'Object', notCapturedReason: 'redactedIdent' }, + }) + }) + + it('should not read a redacted field twice', () => { + const getter = jasmine.createSpy('getter').and.returnValue('hunter2') + const obj = {} + Object.defineProperty(obj, 'password', { get: getter, enumerable: true }) + + captureFields(obj, defaultOpts, redactingContext()) + + expect(getter).toHaveBeenCalledTimes(1) + }) + + it('should report a redacted field whose getter throws', () => { + const obj = {} + Object.defineProperty(obj, 'password', { + get: () => { + throw new Error('boom') + }, + enumerable: true, + }) + + expect(captureFields(obj, defaultOpts, redactingContext())).toEqual({ + password: { notCapturedReason: 'redactedIdent' }, + }) + }) + + it('should not redact unless the context asks for it', () => { + const result = captureFields({ password: 'hunter2' }, defaultOpts, { deadline: Infinity, timedOut: false }) + + expect(result).toEqual({ password: { type: 'string', value: 'hunter2' } }) + }) +}) diff --git a/packages/browser-debugger/src/domain/capture.ts b/packages/browser-debugger/src/domain/capture.ts index 6197dc1125..aab285ab64 100644 --- a/packages/browser-debugger/src/domain/capture.ts +++ b/packages/browser-debugger/src/domain/capture.ts @@ -1,4 +1,5 @@ import { getConstructorName, isError } from '@datadog/browser-core' +import { isRedactedIdentifier } from './redaction' export interface CaptureOptions { maxReferenceDepth?: number @@ -26,6 +27,11 @@ export interface CapturedValue { export interface CaptureContext { deadline: number timedOut: boolean + /** + * Whether to redact the values of properties and map entries named after a sensitive identifier + * (see {@link isRedactedIdentifier}). + */ + redact?: boolean } // Prefer replaceAll to replace because it's ~20% faster in this hot code path. @@ -321,16 +327,10 @@ function captureObjectPropertiesFields( const keyName = typeof key === 'symbol' ? key.description || key.toString() : keyStr.includes('.') ? replaceDots(keyStr) : keyStr - fields[keyName] = captureProperty( - obj, - key, - depth, - maxReferenceDepth, - maxCollectionSize, - maxFieldCount, - maxLength, - ctx - ) + fields[keyName] = + ctx.redact && isRedactedKey(key) + ? captureRedactedProperty(obj, key) + : captureProperty(obj, key, depth, maxReferenceDepth, maxCollectionSize, maxFieldCount, maxLength, ctx) } return fields @@ -424,7 +424,9 @@ function captureMap( } entries.push([ captureValue(key, depth + 1, maxReferenceDepth, maxCollectionSize, maxFieldCount, maxLength, ctx), - captureValue(value, depth + 1, maxReferenceDepth, maxCollectionSize, maxFieldCount, maxLength, ctx), + ctx.redact && isRedactedKey(key) + ? captureRedactedValue(value) + : captureValue(value, depth + 1, maxReferenceDepth, maxCollectionSize, maxFieldCount, maxLength, ctx), ]) count++ } @@ -547,6 +549,37 @@ function captureProperty( } } +// Symbol keys are captured under their description, so they're redacted by it too +function isRedactedKey(key: unknown): boolean { + if (typeof key === 'symbol') { + return key.description !== undefined && isRedactedIdentifier(key.description) + } + return typeof key === 'string' && isRedactedIdentifier(key) +} + +function captureRedactedProperty(obj: any, property: string | symbol): CapturedValue { + try { + return captureRedactedValue(obj[property]) + } catch { + return { notCapturedReason: 'redactedIdent' } + } +} + +function captureRedactedValue(value: unknown): CapturedValue { + let type: string + if (value === null) { + type = 'null' + } else if (typeof value === 'object') { + // Not the constructor name, which a redacted object controls, as in `{ constructor: { name } }` + type = Array.isArray(value) ? 'Array' : 'Object' + } else if (typeof value === 'function') { + type = 'Function' + } else { + type = typeof value + } + return { type, notCapturedReason: 'redactedIdent' } +} + function captureOptionalProperty( obj: any, property: string | symbol, diff --git a/packages/browser-debugger/src/domain/exceptionReplay.spec.ts b/packages/browser-debugger/src/domain/exceptionReplay.spec.ts new file mode 100644 index 0000000000..07c3df3b42 --- /dev/null +++ b/packages/browser-debugger/src/domain/exceptionReplay.spec.ts @@ -0,0 +1,703 @@ +import { computeStackTrace } from '@datadog/browser-core' +import { mockClock, registerCleanupTask } from '@datadog/browser-core/test' +import type { Clock } from '@datadog/browser-core/test' +import type { BrowserWindow } from '../entries/main' +import { initDebuggerTransport, resetDebuggerTransport } from './api' +import { + collectExceptionReplay, + onCatch, + registerExceptionReplayPlugin, + resetExceptionReplay, + sendExceptionReplay, + startExceptionReplay, +} from './exceptionReplay' +import { checkGlobalSnapshotBudget, clearProbes } from './probes' + +const browserWindow = window as BrowserWindow + +interface SentSnapshot { + id: string + exceptionId: string + probe: { location: { type: string; method: string } } + captures: { return: { arguments: Record; throwable: { message: string } } } +} + +describe('exceptionReplay', () => { + let mockBatchAdd: jasmine.Spy + + function initTransport(overrides: Record = {}) { + resetDebuggerTransport() + initDebuggerTransport( + { service: 'test-service', env: 'test-env', ...overrides } as any, + { add: mockBatchAdd } as any + ) + } + + // The functions below stand in for instrumented code: the build plugin calls `$dd_catch` from the + // catch block it wraps around each function body, then rethrows. + + function throwingFunction(value: number, secret?: string) { + try { + throw new Error(`boom ${value}`) + } catch (e) { + onCatch('src/throwing.ts;throwingFunction', e, undefined, { value, secret }) + throw e + } + } + + function callingFunction(a: number, b: number) { + try { + return throwingFunction(a + b) + } catch (e) { + onCatch('src/calling.ts;callingFunction', e, undefined, { a, b }) + throw e + } + } + + function outerFunction() { + try { + return callingFunction(1, 2) + } catch (e) { + onCatch('src/outer.ts;outerFunction', e, undefined, {}) + throw e + } + } + + function outermostFunction() { + try { + return outerFunction() + } catch (e) { + onCatch('src/outermost.ts;outermostFunction', e, undefined, {}) + throw e + } + } + + // Reading its argument advances the clock, like a capture that takes `ms` and can't be interrupted + function slowFunction(clock: Clock, ms: number) { + const args = { + get value() { + clock.tick(ms) + return 1 + }, + } + try { + throw new Error('slow') + } catch (e) { + onCatch('src/slow.ts;slowFunction', e, undefined, args) + throw e + } + } + + function catchError(fn: () => unknown): unknown { + let error: unknown + try { + fn() + } catch (e) { + error = e + } + expect(error).toBeDefined() + return error + } + + // Like RUM: assemble the error event, then collect it + function reportError(error: unknown) { + const attributes = collectExceptionReplay(error) + sendExceptionReplay(error) + return attributes + } + + // Whether, once an async function resumes from an `await` that rejects, its stack shows the + // function awaiting it on the line of its `await`. Chrome and Edge 80 (V8 8.0) only show it after + // an `await` that fulfills. + async function hasAsyncCallersOnAwaitLine(): Promise { + async function resumedFunction() { + try { + await Promise.reject(new Error()) + return [] + } catch { + return computeStackTrace(new Error()).stack + } + } + async function awaitingCaller() { + return [computeStackTrace(new Error()).stack[0].line, await resumedFunction()] as const + } + const [awaitLine, resumedFrames] = await awaitingCaller() + return resumedFrames.some((frame) => frame.func?.includes('awaitingCaller') && frame.line === awaitLine) + } + + function stackIndexOf(error: unknown, functionName: string): number { + return computeStackTrace(error).stack.findIndex((frame) => frame.func?.includes(functionName)) + } + + function sentSnapshots(): SentSnapshot[] { + return mockBatchAdd.calls + .allArgs() + .map(([payload]) => (payload as { debugger: { snapshot: SentSnapshot } }).debugger.snapshot) + } + + beforeEach(() => { + clearProbes() + mockBatchAdd = jasmine.createSpy('batchAdd') + initTransport() + ;(window as any).DD_DEBUGGER = { version: '0.0.1' } + registerExceptionReplayPlugin(() => true) + startExceptionReplay() + + registerCleanupTask(() => { + delete (window as any).DD_DEBUGGER + resetExceptionReplay() + resetDebuggerTransport() + clearProbes() + }) + }) + + describe('catch hook installation', () => { + beforeEach(() => { + resetExceptionReplay() + }) + + it('should install the catch hook once the plugin is registered and the debugger is started', () => { + registerExceptionReplayPlugin(() => true) + expect(browserWindow.$dd_catch).toBeUndefined() + + startExceptionReplay() + expect(browserWindow.$dd_catch).toBe(onCatch) + }) + + it('should install the catch hook when the debugger starts before the plugin is registered', () => { + startExceptionReplay() + expect(browserWindow.$dd_catch).toBeUndefined() + + registerExceptionReplayPlugin(() => true) + expect(browserWindow.$dd_catch).toBe(onCatch) + }) + }) + + it('should send a snapshot for each captured frame, and link them to the reported error', () => { + const error = catchError(() => callingFunction(1, 2)) + + const attributes = reportError(error)! + + expect(attributes.frames.map(({ index }) => index)).toEqual([ + stackIndexOf(error, 'throwingFunction'), + stackIndexOf(error, 'callingFunction'), + ]) + const snapshots = sentSnapshots() + expect(snapshots.map(({ id }) => id)).toEqual(attributes.frames.map(({ snapshotId }) => snapshotId)) + expect(snapshots.map(({ exceptionId }) => exceptionId)).toEqual([attributes.exceptionId, attributes.exceptionId]) + }) + + it('should capture the arguments of each frame', () => { + const error = catchError(() => callingFunction(1, 2)) + + reportError(error) + + const [throwingSnapshot, callingSnapshot] = sentSnapshots() + expect(throwingSnapshot.probe.location).toEqual({ type: 'src/throwing.ts', method: 'throwingFunction' }) + expect(throwingSnapshot.captures.return.arguments.value).toEqual({ type: 'number', value: '3' }) + expect(throwingSnapshot.captures.return.throwable.message).toBe('boom 3') + expect(callingSnapshot.probe.location).toEqual({ type: 'src/calling.ts', method: 'callingFunction' }) + expect(callingSnapshot.captures.return.arguments).toEqual( + jasmine.objectContaining({ a: { type: 'number', value: '1' }, b: { type: 'number', value: '2' } }) + ) + }) + + it('should send snapshots in the same envelope as probe snapshots', () => { + const error = catchError(() => throwingFunction(1)) + + reportError(error) + + const payload = mockBatchAdd.calls.mostRecent().args[0] + expect(payload).toEqual( + jasmine.objectContaining({ + message: 'Error: boom 1', + service: 'test-service', + ddtags: jasmine.stringContaining('env:test-env'), + logger: jasmine.objectContaining({ name: 'src/throwing.ts', method: 'throwingFunction', version: '0.0.1' }), + }) + ) + expect(payload.debugger.snapshot).toEqual( + jasmine.objectContaining({ + language: 'javascript', + probe: { id: jasmine.any(String), version: 0, location: jasmine.any(Object) }, + stack: jasmine.arrayContaining([ + jasmine.objectContaining({ function: jasmine.stringContaining('throwingFunction') }), + ]), + }) + ) + }) + + it('should redact sensitive arguments', () => { + const error = catchError(() => throwingFunction(1, 'hunter2')) + + reportError(error) + + expect(sentSnapshots()[0].captures.return.arguments.secret).toEqual({ + type: 'string', + notCapturedReason: 'redactedIdent', + }) + }) + + it('should only capture the three innermost frames', () => { + const error = catchError(outermostFunction) + + const attributes = reportError(error)! + + expect(attributes.frames.map(({ index }) => index)).toEqual([ + stackIndexOf(error, 'throwingFunction'), + stackIndexOf(error, 'callingFunction'), + stackIndexOf(error, 'outerFunction'), + ]) + }) + + it('should capture async functions', async () => { + async function asyncThrowingFunction() { + try { + await Promise.resolve() + throw new Error('async boom') + } catch (e) { + onCatch('src/async.ts;asyncThrowingFunction', e, undefined, {}) + throw e + } + } + + const error = await asyncThrowingFunction().then( + () => undefined, + (e: unknown) => e + ) + + const attributes = reportError(error)! + + // The error is created in `asyncThrowingFunction`, so its frame is the innermost one. Some + // browsers, like Safari 14, leave the function's name out of the stack after an `await`. + expect(attributes.frames[0].index).toBe(0) + }) + + it('should capture an async function awaiting a callee that throws before its first await', async () => { + async function asyncCallee(value: number) { + try { + if (value > 0) { + throw new Error('boom') + } + await Promise.resolve() + } catch (e) { + onCatch('src/async.ts;asyncCallee', e, undefined, { value }) + throw e + } + } + async function asyncCaller() { + try { + await asyncCallee(1) + } catch (e) { + onCatch('src/async.ts;asyncCaller', e, undefined, {}) + throw e + } + } + let error: unknown + async function awaitingFunction() { + try { + await asyncCaller() + } catch (e) { + error = e + } + } + + await awaitingFunction() + const attributes = reportError(error)! + + const indexes = attributes.frames.map(({ index }) => index) + // `asyncCallee` throws before its first `await`, so its frame is the innermost one. Once + // `asyncCaller` resumes, its stack shows `awaitingFunction` as an async frame located at the + // `await`, while the error's stack has it at the call. Browsers that don't show it on that line, + // or don't show it at all, leave `asyncCaller` without a snapshot, but never put it elsewhere. + if (await hasAsyncCallersOnAwaitLine()) { + expect(indexes).toEqual([0, 1]) + } else { + expect([[0], [0, 1]]).toContain(indexes) + } + }) + + it('should not link a function without callers to an unrelated frame of the same script', async () => { + function rejectLater() { + return new Promise((_, reject) => { + setTimeout(function timerCallback() { + reject(new Error('boom')) + }) + }) + } + async function awaitingFunction() { + try { + await rejectLater() + } catch (e) { + onCatch('src/async.ts;awaitingFunction', e, undefined, {}) + throw e + } + } + + // Not awaited, so `awaitingFunction` has no callers once it resumes + const error = await new Promise((resolve) => { + awaitingFunction().catch(resolve) + }) + + // The error's only frame is `timerCallback`, from the same script as `awaitingFunction` + expect(reportError(error)).toBeUndefined() + }) + + it('should not link an unnamed function without callers to a named frame of the same script', async () => { + function rejectLater() { + return new Promise((_, reject) => { + setTimeout(function timerCallback() { + reject(new Error('boom')) + }) + }) + } + + // An anonymous function defined after `timerCallback`, with no callers once it resumes + const error = await new Promise((resolve) => { + ;(async () => { + try { + await rejectLater() + } catch (e) { + onCatch('src/async.ts;', e, undefined, {}) + throw e + } + })().catch(resolve) + }) + + expect(reportError(error)).toBeUndefined() + }) + + it('should not send snapshots for exceptions that are not reported', () => { + catchError(() => callingFunction(1, 2)) + + expect(mockBatchAdd).not.toHaveBeenCalled() + }) + + it('should only send snapshots once RUM collects the error event', () => { + const error = catchError(() => callingFunction(1, 2)) + + const attributes = collectExceptionReplay(error)! + expect(mockBatchAdd).not.toHaveBeenCalled() + + sendExceptionReplay(error) + expect(sentSnapshots().map(({ id }) => id)).toEqual(attributes.frames.map(({ snapshotId }) => snapshotId)) + }) + + it('should not send snapshots for an error event that RUM drops', () => { + const dropped = catchError(() => throwingFunction(1)) + expect(collectExceptionReplay(dropped)).toBeDefined() + + expect(mockBatchAdd).not.toHaveBeenCalled() + // The fingerprint wasn't reported, so it isn't cooling down + expect(reportError(catchError(() => throwingFunction(2)))).toBeDefined() + }) + + it('should send the snapshots of an error once RUM collects it, after dropping it once', () => { + const error = catchError(() => throwingFunction(1)) + const attributes = collectExceptionReplay(error)! + + expect(reportError(error)).toBe(attributes) + expect(sentSnapshots().map(({ id }) => id)).toEqual(attributes.frames.map(({ snapshotId }) => snapshotId)) + }) + + it('should not send the snapshots of a dropped error once another error with its fingerprint is reported', () => { + const dropped = catchError(() => throwingFunction(1)) + expect(collectExceptionReplay(dropped)).toBeDefined() + expect(reportError(catchError(() => throwingFunction(2)))).toBeDefined() + mockBatchAdd.calls.reset() + + expect(reportError(dropped)).toBeUndefined() + expect(mockBatchAdd).not.toHaveBeenCalled() + }) + + it('should not capture exceptions in sessions that RUM does not track', () => { + resetExceptionReplay() + registerExceptionReplayPlugin(() => false) + startExceptionReplay() + + expect(reportError(catchError(() => throwingFunction(1)))).toBeUndefined() + }) + + it('should stop capturing frames once RUM stops tracking the session', () => { + let tracked = true + resetExceptionReplay() + registerExceptionReplayPlugin(() => tracked) + startExceptionReplay() + + function withdrawingFunction() { + try { + throwingFunction(1) + } catch (e) { + tracked = false + onCatch('src/withdrawing.ts;withdrawingFunction', e, undefined, {}) + throw e + } + } + + const error = catchError(withdrawingFunction) + tracked = true + + expect(reportError(error)!.frames.length).toBe(1) + }) + + it('should discard the snapshots of errors reported once RUM stops tracking the session', () => { + let tracked = true + resetExceptionReplay() + registerExceptionReplayPlugin(() => tracked) + startExceptionReplay() + const assembledError = catchError(() => throwingFunction(1)) + const reassembledError = catchError(() => throwingFunction(2)) + const capturedError = catchError(() => throwingFunction(3)) + expect(collectExceptionReplay(assembledError)).toBeDefined() + expect(collectExceptionReplay(reassembledError)).toBeDefined() + + tracked = false + expect(collectExceptionReplay(reassembledError)).toBeUndefined() + expect(collectExceptionReplay(capturedError)).toBeUndefined() + sendExceptionReplay(assembledError) + + tracked = true + sendExceptionReplay(reassembledError) + expect(reportError(assembledError)).toBeUndefined() + expect(reportError(capturedError)).toBeUndefined() + expect(mockBatchAdd).not.toHaveBeenCalled() + }) + + it('should not link a frame to another function called from the same call site', () => { + let created: Error | undefined + function createError() { + created = new Error('boom') + } + function rethrowError() { + try { + throw created! + } catch (e) { + onCatch('src/rethrow.ts;rethrowError', e, undefined, {}) + throw e + } + } + + const error = catchError(() => { + // Both functions have the same callers + for (const fn of [createError, rethrowError]) { + fn() + } + }) + + expect(reportError(error)).toBeUndefined() + }) + + it('should reuse the same snapshots when an error is reported twice', () => { + const error = catchError(() => callingFunction(1, 2)) + + const attributes = reportError(error) + const callCount = mockBatchAdd.calls.count() + + expect(reportError(error)).toBe(attributes) + expect(mockBatchAdd.calls.count()).toBe(callCount) + }) + + it('should stop capturing frames once the exception is reported', () => { + let error: unknown + function reportingFunction() { + try { + throwingFunction(1) + } catch (e) { + error = e + reportError(e) + onCatch('src/reporting.ts;reportingFunction', e, undefined, {}) + } + } + + reportingFunction() + + expect(reportError(error)!.frames.length).toBe(1) + expect(mockBatchAdd).toHaveBeenCalledTimes(1) + }) + + it('should return undefined for errors without captured frames', () => { + expect(reportError(new Error('not thrown through instrumented code'))).toBeUndefined() + expect(reportError(undefined)).toBeUndefined() + }) + + it('should ignore exceptions thrown by instrumented code that runs while capturing a frame', () => { + let nestedArgumentReads = 0 + function rethrowingFunction(error: unknown) { + try { + throw error + } catch (e) { + onCatch('src/rethrowing.ts;rethrowingFunction', e, undefined, { + get value() { + nestedArgumentReads++ + return 1 + }, + }) + throw e + } + } + function throwingFunctionWithGetter() { + const error = new Error('boom') + try { + throw error + } catch (e) { + // Capturing this argument runs instrumented code that throws the same error again + onCatch('src/getter.ts;throwingFunctionWithGetter', e, undefined, { + get value() { + catchError(() => rethrowingFunction(error)) + return 1 + }, + }) + throw e + } + } + + const error = catchError(throwingFunctionWithGetter) + + expect(nestedArgumentReads).toBe(0) + expect(reportError(error)!.frames.length).toBe(1) + }) + + it('should not capture thrown objects that are not errors', () => { + // RUM doesn't report the stack of an object that isn't an `Error`, even if it has one + const thrown = { message: 'boom', stack: new Error('boom').stack } + + onCatch('src/throwing.ts;throwingFunction', thrown, undefined, {}) + + expect(reportError(thrown)).toBeUndefined() + }) + + it('should ignore thrown values that are not objects', () => { + expect(() => onCatch('src/throwing.ts;throwingFunction', 'boom', undefined, {})).not.toThrow() + + expect(reportError('boom')).toBeUndefined() + }) + + it('should skip frames that are not in the error stack', () => { + const preparedError = new Error('created before being thrown') + function rethrowingFunction() { + try { + throw preparedError + } catch (e) { + onCatch('src/rethrowing.ts;rethrowingFunction', e, undefined, {}) + throw e + } + } + + const error = catchError(rethrowingFunction) + + expect(reportError(error)).toBeUndefined() + expect(mockBatchAdd).not.toHaveBeenCalled() + }) + + it('should not report snapshots when the debugger transport is not initialized', () => { + const error = catchError(() => throwingFunction(1)) + resetDebuggerTransport() + + expect(reportError(error)).toBeUndefined() + }) + + it('should neither use nor be limited by the snapshot budget of probes', () => { + initTransport({ maxSnapshotsPerSecondGlobally: 1 }) + const error = catchError(() => callingFunction(1, 2)) + + expect(reportError(error)!.frames.length).toBe(2) + expect(checkGlobalSnapshotBudget(performance.now(), true)).toBeTrue() + }) + + it('should not capture an exception with the same fingerprint for an hour after reporting it', () => { + const clock = mockClock() + + reportError(catchError(() => throwingFunction(1))) + expect(reportError(catchError(() => throwingFunction(2)))).toBeUndefined() + + clock.tick(60 * 60 * 1000 + 1) + expect(reportError(catchError(() => throwingFunction(3)))).toBeDefined() + }) + + it('should only report one of the exceptions with the same fingerprint captured before either is reported', () => { + const first = catchError(() => throwingFunction(1)) + const second = catchError(() => throwingFunction(2)) + + expect(reportError(first)).toBeDefined() + expect(reportError(second)).toBeUndefined() + expect(mockBatchAdd).toHaveBeenCalledTimes(1) + }) + + it('should keep capturing an exception that was never reported', () => { + catchError(() => throwingFunction(1)) + + expect(reportError(catchError(() => throwingFunction(2)))).toBeDefined() + }) + + it('should limit the number of exceptions captured per second', () => { + const clock = mockClock() + function typeErrorFunction() { + try { + throw new TypeError('boom') + } catch (e) { + onCatch('src/type-error.ts;typeErrorFunction', e, undefined, {}) + throw e + } + } + const errors = Array.from({ length: 11 }, (_, i) => catchError(() => throwingFunction(i))) + + expect(reportError(errors[10])).toBeUndefined() + expect(reportError(errors[9])).toBeDefined() + expect(reportError(catchError(typeErrorFunction))).toBeUndefined() + + clock.tick(1001) + expect(reportError(catchError(typeErrorFunction))).toBeDefined() + }) + + it('should stop capturing the frames of an exception once the capture time budget is used up', () => { + const clock = mockClock() + function callingSlowFunction() { + try { + return slowFunction(clock, 30) + } catch (e) { + onCatch('src/calling-slow.ts;callingSlowFunction', e, undefined, {}) + throw e + } + } + + expect(reportError(catchError(callingSlowFunction))!.frames.length).toBe(1) + }) + + it('should charge the capture time budget when capturing throws', () => { + const clock = mockClock() + const args = new Proxy( + {}, + { + ownKeys() { + clock.tick(75) + throw new Error('ownKeys') + }, + } + ) + function throwingWhileCapturing() { + try { + throw new Error('boom') + } catch (e) { + onCatch('src/proxy.ts;throwingWhileCapturing', e, undefined, args) + throw e + } + } + + catchError(throwingWhileCapturing) + clock.tick(1500) + + expect(reportError(catchError(() => throwingFunction(1)))).toBeUndefined() + }) + + it('should pause capturing until the time spent beyond the capture time budget is made up', () => { + const clock = mockClock() + // 75 ms puts the 25 ms budget 50 ms in debt, which takes 2 s to make up + expect(reportError(catchError(() => slowFunction(clock, 75)))).toBeDefined() + + clock.tick(1500) + expect(reportError(catchError(() => throwingFunction(1)))).toBeUndefined() + + clock.tick(600) + expect(reportError(catchError(() => throwingFunction(2)))).toBeDefined() + }) +}) diff --git a/packages/browser-debugger/src/domain/exceptionReplay.ts b/packages/browser-debugger/src/domain/exceptionReplay.ts new file mode 100644 index 0000000000..362d9969df --- /dev/null +++ b/packages/browser-debugger/src/domain/exceptionReplay.ts @@ -0,0 +1,469 @@ +import { globalObject, generateUUID } from '@datadog/js-core/util' +import { timeStampNow } from '@datadog/js-core/time' +import { monitorError } from '@datadog/js-core/monitor' +import { computeStackTrace, isError } from '@datadog/browser-core' +import type { StackTrace } from '@datadog/browser-core' +import type { BrowserWindow } from '../entries/main' +import { captureArguments, isDebuggerTransportInitialized, queueExceptionSnapshot } from './api' +import type { ExceptionSnapshot } from './api' +import type { CaptureContext } from './capture' +import { formatThrowable, formatUnknownError, safeReadErrorProperty } from './error' +import { mapStackFrames } from './stacktrace' + +// Like the Java tracer, only capture the innermost frames, which are closest to the cause. +const MAX_FRAMES_PER_EXCEPTION = 3 + +// Exceptions are captured as they're thrown, before it's known whether they will be reported, so +// cap the work for code that throws and catches a lot of exceptions. These limits are separate from +// the probes' snapshot budget, so neither feature can use up the other's. +const MAX_EXCEPTIONS_CAPTURED_PER_SECOND = 10 + +// Capturing blocks the main thread, so also cap the time it takes. The deadline can't interrupt +// everything, such as reading the property names of a huge object, so time spent beyond the budget +// is carried over, and capturing pauses until the budget recovers. +const CAPTURE_BUDGET_MS_PER_SECOND = 25 + +// Like the tracers, report snapshots for a given exception fingerprint at most once an hour. +const FINGERPRINT_COOLDOWN_MS = 60 * 60 * 1000 +const MAX_FINGERPRINTS = 1000 + +const SNAPSHOT_TIMEOUT_MS = 10 + +/** + * Links the snapshots of a reported exception to its RUM error event. + */ +export interface ExceptionReplayAttributes { + exceptionId: string + /** + * Frames with a snapshot, innermost first. `index` is the frame's position in the error's stack, + * as parsed by `computeStackTrace`, which is how RUM formats the error event's `error.stack`. + */ + frames: Array<{ index: number; snapshotId: string }> +} + +interface CapturedFrame { + functionId: string + timestamp: number + arguments: Record + // Created in `onCatch`, so its stack starts with `onCatch`, followed by the instrumented function + callStack: Error +} + +interface CapturedException { + fingerprint: string + frames: CapturedFrame[] + // Set when the exception is first reported, so reporting it again reuses the same snapshots + attributes?: ExceptionReplayAttributes | null + // Snapshots of a reported exception, until RUM collects its error event + pendingSnapshots?: ExceptionSnapshot[] +} + +let capturedExceptions = new WeakMap() +let lastReportByFingerprint = new Map() +let captureWindowStart = -Infinity +let capturesInWindow = 0 +let captureBudgetMs = CAPTURE_BUDGET_MS_PER_SECOND +let captureBudgetUpdatedAt = -Infinity +let pluginRegistered = false +let debuggerStarted = false +let catchInProgress = false +let isSessionTracked: () => boolean = () => true + +/** + * Called when the Exception Replay plugin is registered on the RUM Browser SDK. + * + * @param isTracked - Whether RUM tracks the current session + */ +export function registerExceptionReplayPlugin(isTracked: () => boolean): void { + pluginRegistered = true + isSessionTracked = isTracked + installCatchHook() +} + +/** + * Called when the Live Debugger SDK is initialized, which provides the transport for snapshots. + */ +export function startExceptionReplay(): void { + debuggerStarted = true + installCatchHook() +} + +export function resetExceptionReplay(): void { + capturedExceptions = new WeakMap() + lastReportByFingerprint = new Map() + captureWindowStart = -Infinity + capturesInWindow = 0 + captureBudgetMs = CAPTURE_BUDGET_MS_PER_SECOND + captureBudgetUpdatedAt = -Infinity + pluginRegistered = false + debuggerStarted = false + isSessionTracked = () => true + delete (globalObject as BrowserWindow).$dd_catch +} + +// Instrumented code only calls `$dd_catch` once it's defined, so Exception Replay costs nothing +// until both the plugin and the transport are there. +function installCatchHook(): void { + if (pluginRegistered && debuggerStarted) { + ;(globalObject as BrowserWindow).$dd_catch = onCatch + } +} + +/** + * Called by instrumented code built with Exception Replay enabled, for every exception that leaves + * an instrumented function, whether or not a probe is active. An exception reaches the innermost + * function first. + * + * Captures the arguments of the function's frame, and keeps them with the exception until RUM + * reports it (see {@link collectExceptionReplay}). The captures of exceptions that are never + * reported are garbage collected with them. + * + * Never throws: it runs in the instrumented function's catch block, before the exception is + * rethrown. + * + * @param functionId - ID of the instrumented function + * @param error - The thrown value + * @param self - The 'this' context + * @param args - Function arguments + */ +export function onCatch(functionId: string, error: unknown, self: unknown, args: Record = {}): void { + // Capturing reads application values, whose getters can run instrumented code that throws. Those + // exceptions come from the capture itself, so they're ignored. + if (catchInProgress) { + return + } + catchInProgress = true + try { + // RUM only reports the stack of errors, which their snapshots are linked to + if (!isError(error)) { + return + } + + let exception = capturedExceptions.get(error) + if (exception === undefined) { + exception = startCapture(functionId, error) + capturedExceptions.set(error, exception) + } + + if (!exception || exception.attributes !== undefined || exception.frames.length >= MAX_FRAMES_PER_EXCEPTION) { + return + } + + // Tracking can stop while the exception propagates, or before it's rethrown + if (!isSessionTracked()) { + return + } + + const start = performance.now() + const budgetMs = refillCaptureBudget(start) + if (budgetMs <= 0) { + return + } + + const captureCtx: CaptureContext = { + deadline: start + Math.min(SNAPSHOT_TIMEOUT_MS, budgetMs), + timedOut: false, + // Unlike probes, Exception Replay captures data nobody asked for, so redact sensitive names + redact: true, + } + try { + exception.frames.push({ + functionId, + timestamp: timeStampNow(), + arguments: captureArguments(args, self, {}, captureCtx), + callStack: new Error(), + }) + } finally { + // Charge the time actually spent, which can go past the deadline, even if capturing threw + captureBudgetMs -= performance.now() - start + } + } catch (e) { + monitorError(e) + } finally { + catchInProgress = false + } +} + +function startCapture(functionId: string, error: Error): CapturedException | false { + const now = performance.now() + // The innermost instrumented function is the first one to see the exception + const fingerprint = `${safeReadErrorProperty(error, 'name') ?? ''};${functionId}` + + if (isCoolingDown(fingerprint, now)) { + return false + } + + // RUM doesn't report the errors of the sessions it doesn't track + if (!isSessionTracked()) { + return false + } + + if (refillCaptureBudget(now) <= 0) { + return false + } + + if (now - captureWindowStart > 1000) { + captureWindowStart = now + capturesInWindow = 0 + } + if (capturesInWindow >= MAX_EXCEPTIONS_CAPTURED_PER_SECOND) { + return false + } + capturesInWindow++ + + return { fingerprint, frames: [] } +} + +// Adds the budget earned since the last update, up to one second's worth, and returns the budget +function refillCaptureBudget(now: number): number { + captureBudgetMs = Math.min( + CAPTURE_BUDGET_MS_PER_SECOND, + captureBudgetMs + ((now - captureBudgetUpdatedAt) * CAPTURE_BUDGET_MS_PER_SECOND) / 1000 + ) + captureBudgetUpdatedAt = now + return captureBudgetMs +} + +/** + * Called when RUM assembles an error event. Prepares the snapshots captured for the exception, and + * returns the attributes linking them to the event, or undefined if it has none. The snapshots are + * only sent once RUM collects the event (see {@link sendExceptionReplay}). + */ +export function collectExceptionReplay(error: unknown): ExceptionReplayAttributes | undefined { + try { + if (!isObject(error)) { + return + } + + const exception = capturedExceptions.get(error) + if (!exception) { + return + } + + // Tracking can stop after the exception is captured, and the event bridge's session stays + // tracked, so RUM can still report the error. Its captures are then discarded. + if (!isSessionTracked()) { + capturedExceptions.set(error, false) + return + } + + // The error was assembled before but RUM dropped it, and another exception with the same + // fingerprint has been reported since + if (exception.pendingSnapshots && isCoolingDown(exception.fingerprint, performance.now())) { + exception.pendingSnapshots = undefined + exception.attributes = null + } + + if (exception.attributes === undefined) { + exception.attributes = prepareSnapshots(error, exception) + } + return exception.attributes ?? undefined + } catch (e) { + monitorError(e) + } +} + +/** + * Called when RUM collects an error event, once `beforeSend` and the event rate limits have let it + * through. Sends the snapshots prepared for the exception, so errors that RUM drops send none. + */ +export function sendExceptionReplay(error: unknown): void { + try { + if (!isObject(error)) { + return + } + + const exception = capturedExceptions.get(error) + if (!exception || !exception.pendingSnapshots) { + return + } + + // Tracking can also stop once the event is assembled, as in `beforeSend` + if (!isSessionTracked()) { + capturedExceptions.set(error, false) + return + } + + const snapshots = exception.pendingSnapshots + exception.pendingSnapshots = undefined + for (const snapshot of snapshots) { + queueExceptionSnapshot(snapshot) + } + recordReport(exception.fingerprint) + } catch (e) { + monitorError(e) + } +} + +function prepareSnapshots(error: object, exception: CapturedException): ExceptionReplayAttributes | null { + const capturedFrames = exception.frames + // Release the captures: the exception can't capture more frames once it's reported + exception.frames = [] + + // Another exception with the same fingerprint may have been reported since this one was captured + if (isCoolingDown(exception.fingerprint, performance.now()) || !isDebuggerTransportInitialized()) { + return null + } + + const errorFrames = computeStackTrace(error).stack + const exceptionId = generateUUID() + const message = formatUnknownError(error) + const throwable = formatThrowable(error) + const frames: ExceptionReplayAttributes['frames'] = [] + const snapshots: ExceptionSnapshot[] = [] + + let fromIndex = 0 + for (const frame of capturedFrames) { + const callFrames = computeStackTrace(frame.callStack).stack + const index = findFrameIndex(errorFrames, callFrames, fromIndex) + if (index === undefined) { + continue + } + + const snapshotId = generateUUID() + const separatorIndex = frame.functionId.lastIndexOf(';') + snapshots.push({ + id: snapshotId, + exceptionId, + timestamp: frame.timestamp, + message, + location: { + type: frame.functionId.slice(0, separatorIndex), + method: frame.functionId.slice(separatorIndex + 1), + }, + stack: mapStackFrames(callFrames, 1), + arguments: frame.arguments, + throwable, + }) + frames.push({ index, snapshotId }) + fromIndex = index + 1 + } + + if (frames.length === 0) { + return null + } + + exception.pendingSnapshots = snapshots + return { exceptionId, frames } +} + +function isCoolingDown(fingerprint: string, now: number): boolean { + const lastReport = lastReportByFingerprint.get(fingerprint) + return lastReport !== undefined && now - lastReport < FINGERPRINT_COOLDOWN_MS +} + +function recordReport(fingerprint: string): void { + // Re-insert the fingerprint so the map stays ordered by report time, oldest first + lastReportByFingerprint.delete(fingerprint) + lastReportByFingerprint.set(fingerprint, performance.now()) + if (lastReportByFingerprint.size > MAX_FINGERPRINTS) { + lastReportByFingerprint.delete(lastReportByFingerprint.keys().next().value!) + } +} + +/** + * Find the index, in the error's stack, of the instrumented function that captured `callFrames`. + * + * `callFrames` is the stack captured in `onCatch`: `onCatch` itself, then the instrumented + * function, then its callers. The callers are still paused at the call sites they were at when the + * exception was thrown, so they're the frames that follow the function in the error's stack. The + * function's own frame differs, as it has moved to its catch block, so only its URL is compared, and + * its name when both frames have one: functions called from the same call site have the same callers. + * + * Both stacks can be truncated (V8 keeps 10 frames by default), so only the callers present in both + * are compared. A function without callers has nothing to compare, so its frame in the error's stack + * must also look like the same function. + */ +type StackFrame = StackTrace['stack'][number] + +function findFrameIndex( + errorFrames: StackTrace['stack'], + callFrames: StackTrace['stack'], + fromIndex: number +): number | undefined { + const functionFrame = callFrames[1] + if (!functionFrame?.url) { + return + } + + const functionName = getFunctionName(functionFrame) + const callers = callFrames.slice(2) + for (let index = fromIndex; index < errorFrames.length; index++) { + const errorFunctionName = getFunctionName(errorFrames[index]) + if ( + errorFrames[index].url !== functionFrame.url || + (errorFunctionName !== undefined && functionName !== undefined && errorFunctionName !== functionName) + ) { + continue + } + + const comparedCount = Math.min(callers.length, errorFrames.length - index - 1) + if (callers.length > 0) { + // A function with callers needs at least one of them in the error's stack to confirm the match + if (comparedCount === 0) { + continue + } + } else if (index !== errorFrames.length - 1 || !isSameFunction(errorFrames[index], functionFrame)) { + // A function without callers is at the bottom of both stacks + continue + } + + let matches = true + for (let i = 0; i < comparedCount && matches; i++) { + matches = isSameLocation(callers[i], errorFrames[index + 1 + i]) + } + if (matches) { + return index + } + } +} + +// After an `await`, the stack shows a caller as an async frame located at the `await` instead of the +// call, as in `async main` (Chrome) or `async*main` (Firefox), so only its line can be compared. An +// anonymous caller is just `async` in Chrome. +const ASYNC_FRAME_PREFIX = /^async(?:[ *]|$)/ + +function isSameLocation(a: StackFrame, b: StackFrame): boolean { + if (a.url !== b.url || a.line !== b.line) { + return false + } + if (a.column === b.column) { + return true + } + // Without the column, the line could hold several functions, as in a minified bundle + const aName = getFunctionName(a) + const bName = getFunctionName(b) + return (isAsyncFrame(a) || isAsyncFrame(b)) && (aName === undefined || bName === undefined || aName === bName) +} + +function isAsyncFrame(frame: StackFrame): boolean { + return frame.func !== undefined && ASYNC_FRAME_PREFIX.test(frame.func) +} + +// Compares function names, so a frame with a name and one without are from different functions. +// When neither has one, the frame from the error's stack must come first: it's where the function +// threw or called a callee, before reaching its catch block. Two unnamed functions of the same script +// can still be mistaken for each other. +function isSameFunction(errorFrame: StackFrame, functionFrame: StackFrame): boolean { + const errorFunction = getFunctionName(errorFrame) + const functionName = getFunctionName(functionFrame) + if (errorFunction !== undefined || functionName !== undefined) { + return errorFunction === functionName + } + return ( + errorFrame.line !== undefined && + functionFrame.line !== undefined && + (errorFrame.line < functionFrame.line || + (errorFrame.line === functionFrame.line && (errorFrame.column ?? 0) < (functionFrame.column ?? 0))) + ) +} + +function getFunctionName(frame: StackFrame): string | undefined { + const name = frame.func?.replace(ASYNC_FRAME_PREFIX, '') + // `computeStackTrace` names unknown functions `?` + return name && name !== '?' ? name : undefined +} + +function isObject(value: unknown): value is object { + return (typeof value === 'object' && value !== null) || typeof value === 'function' +} diff --git a/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts b/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts new file mode 100644 index 0000000000..acf8fdf2b6 --- /dev/null +++ b/packages/browser-debugger/src/domain/exceptionReplayPlugin.spec.ts @@ -0,0 +1,254 @@ +import { SKIPPED } from '@datadog/js-core/assembly' +import { registerCleanupTask } from '@datadog/browser-core/test' +import type { RumPlugin, RumPluginOnInitOptions, RumPublicApi } from '@datadog/browser-rum-core' +import type { BrowserWindow } from '../entries/main' +import { initDebuggerTransport, resetDebuggerTransport } from './api' +import { display } from './display' +import { onCatch, resetExceptionReplay, startExceptionReplay } from './exceptionReplay' +import type { RumGlobal } from './exceptionReplayPlugin' +import { addExceptionReplayPluginToRum, exceptionReplayPlugin } from './exceptionReplayPlugin' +import { clearProbes } from './probes' + +type AssembleHook = Parameters[0] +type EventCollectedHook = Parameters[0] + +describe('exceptionReplayPlugin', () => { + let assembleHook: AssembleHook + let eventCollectedHook: EventCollectedHook + let batchAdd: jasmine.Spy + + function initPlugin({ + isSessionTracked = true, + rumStarted = true, + isTrackingConsentGranted = true, + }: { isSessionTracked?: boolean; rumStarted?: boolean; isTrackingConsentGranted?: boolean } = {}) { + const registerAssembleEventHook = jasmine.createSpy('registerAssembleEventHook') + const registerEventCollectedHook = jasmine.createSpy('registerEventCollectedHook') + const plugin = exceptionReplayPlugin() + plugin.onInit({ + publicApi: { getInternalContext: () => (isSessionTracked ? {} : undefined) }, + isTrackingConsentGranted: () => isTrackingConsentGranted, + registerAssembleEventHook, + registerEventCollectedHook, + }) + if (rumStarted) { + plugin.onRumStart() + } + assembleHook = registerAssembleEventHook.calls.mostRecent().args[0] + eventCollectedHook = registerEventCollectedHook.calls.mostRecent().args[0] + } + + function assemble(eventType: string, error: unknown) { + return assembleHook({ eventType, domainContext: { error } } as unknown as Parameters[0]) + } + + function collect(eventType: string, error: unknown) { + eventCollectedHook({ eventType, domainContext: { error } } as unknown as Parameters[0]) + } + + function throwingFunction() { + try { + throw new Error('boom') + } catch (e) { + onCatch('src/throwing.ts;throwingFunction', e, undefined, {}) + throw e + } + } + + function catchError(fn: () => unknown): unknown { + let error: unknown + try { + fn() + } catch (e) { + error = e + } + return error + } + + beforeEach(() => { + clearProbes() + batchAdd = jasmine.createSpy('batchAdd') + initDebuggerTransport({ service: 'test-service' } as any, { add: batchAdd } as any) + ;(window as any).DD_DEBUGGER = { version: '0.0.1' } + startExceptionReplay() + + registerCleanupTask(() => { + delete (window as any).DD_DEBUGGER + resetExceptionReplay() + resetDebuggerTransport() + clearProbes() + }) + }) + + it('should be compatible with the RUM Browser SDK plugin type', () => { + const plugin: RumPlugin = exceptionReplayPlugin() + + expect(plugin.name).toBe('exception-replay') + }) + + it('should install the catch hook when initialized', () => { + expect((window as BrowserWindow).$dd_catch).toBeUndefined() + + initPlugin() + + expect((window as BrowserWindow).$dd_catch).toBe(onCatch) + }) + + it('should link the snapshots of a reported error to its RUM event', () => { + initPlugin() + const error = catchError(throwingFunction) + + expect(assemble('error', error)).toEqual({ + type: 'error', + error: { debug_info_captured: 'true' }, + _dd: { + exception_replay: { + exception_id: jasmine.any(String), + frames: [{ index: 0, snapshot_id: jasmine.any(String) }], + }, + }, + }) + }) + + it('should send the snapshots once RUM collects the error event', () => { + initPlugin() + const error = catchError(throwingFunction) + assemble('error', error) + expect(batchAdd).not.toHaveBeenCalled() + + collect('error', error) + + expect(batchAdd).toHaveBeenCalledTimes(1) + }) + + it('should not capture errors in sessions that RUM does not track', () => { + initPlugin({ isSessionTracked: false }) + const error = catchError(throwingFunction) + + expect(assemble('error', error)).toBe(SKIPPED) + }) + + it('should capture errors thrown before RUM starts, as their session is not known yet', () => { + initPlugin({ isSessionTracked: false, rumStarted: false }) + const error = catchError(throwingFunction) + + expect(assemble('error', error)).not.toBe(SKIPPED) + }) + + it('should not capture errors thrown before RUM starts while tracking consent is not granted', () => { + initPlugin({ rumStarted: false, isTrackingConsentGranted: false }) + const error = catchError(throwingFunction) + + expect(assemble('error', error)).toBe(SKIPPED) + }) + + it('should not capture errors once tracking consent is withdrawn, even if the session is still tracked', () => { + // The event bridge's session stays tracked when consent is withdrawn + initPlugin({ isTrackingConsentGranted: false }) + const error = catchError(throwingFunction) + + expect(assemble('error', error)).toBe(SKIPPED) + }) + + it('should not start with a RUM Browser SDK that does not tell whether tracking consent is granted', () => { + const displaySpy = spyOn(display, 'warn') + + exceptionReplayPlugin().onInit({ + publicApi: { getInternalContext: () => ({}) }, + registerAssembleEventHook: jasmine.createSpy('registerAssembleEventHook'), + registerEventCollectedHook: jasmine.createSpy('registerEventCollectedHook'), + }) + + expect(displaySpy).toHaveBeenCalled() + expect((window as BrowserWindow).$dd_catch).toBeUndefined() + }) + + it('should not start with a RUM Browser SDK that lacks the event collected hook', () => { + const displaySpy = spyOn(display, 'warn') + + exceptionReplayPlugin().onInit({ + publicApi: { getInternalContext: () => ({}) }, + registerAssembleEventHook: jasmine.createSpy('registerAssembleEventHook'), + isTrackingConsentGranted: () => true, + }) + + expect(displaySpy).toHaveBeenCalled() + expect((window as BrowserWindow).$dd_catch).toBeUndefined() + }) + + it('should skip errors without snapshots', () => { + initPlugin() + + expect(assemble('error', new Error('not thrown through instrumented code'))).toBe(SKIPPED) + }) + + it('should skip other event types', () => { + initPlugin() + const error = catchError(throwingFunction) + + expect(assemble('action', error)).toBe(SKIPPED) + }) +}) + +describe('addExceptionReplayPluginToRum', () => { + const rumWindow = window as { DD_RUM?: RumGlobal } + + beforeEach(() => { + const originalRum = rumWindow.DD_RUM + delete rumWindow.DD_RUM + + registerCleanupTask(() => { + rumWindow.DD_RUM = originalRum + }) + }) + + it('should be compatible with the RUM Browser SDK public API', () => { + // Fails to compile if the RUM Browser SDK's public API stops matching what the plugin uses + const isCompatible: RumPublicApi extends Required ? true : false = true + + expect(isCompatible).toBeTrue() + }) + + it('should add the plugin to RUM', () => { + const addPlugin = jasmine.createSpy('addPlugin') + rumWindow.DD_RUM = { onReady: (callback) => callback(), addPlugin } + + addExceptionReplayPluginToRum() + + expect(addPlugin).toHaveBeenCalledOnceWith(jasmine.objectContaining({ name: 'exception-replay' })) + }) + + it('should wait for RUM to load when it uses the async loading snippet', () => { + const queuedCallbacks: Array<() => void> = [] + rumWindow.DD_RUM = { + onReady: (callback) => { + queuedCallbacks.push(callback) + }, + } + addExceptionReplayPluginToRum() + + // Like the RUM Browser SDK when it loads: replace the snippet, then run its queued callbacks + const addPlugin = jasmine.createSpy('addPlugin') + rumWindow.DD_RUM = { onReady: (callback) => callback(), addPlugin } + queuedCallbacks.forEach((callback) => callback()) + + expect(addPlugin).toHaveBeenCalledTimes(1) + }) + + it('should warn when the RUM Browser SDK is too old to add plugins after init', () => { + const displaySpy = spyOn(display, 'warn') + rumWindow.DD_RUM = { onReady: (callback) => callback() } + + addExceptionReplayPluginToRum() + + expect(displaySpy).toHaveBeenCalled() + }) + + it('should do nothing without the RUM Browser SDK', () => { + const displaySpy = spyOn(display, 'warn') + + addExceptionReplayPluginToRum() + + expect(displaySpy).not.toHaveBeenCalled() + }) +}) diff --git a/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts b/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts new file mode 100644 index 0000000000..8318786c70 --- /dev/null +++ b/packages/browser-debugger/src/domain/exceptionReplayPlugin.ts @@ -0,0 +1,141 @@ +import { SKIPPED } from '@datadog/js-core/assembly' +import { globalObject } from '@datadog/js-core/util' +import { display } from './display' +import { collectExceptionReplay, registerExceptionReplayPlugin, sendExceptionReplay } from './exceptionReplay' + +// The plugin is typed structurally, rather than with the RUM Browser SDK's `RumPlugin` type, so that +// the Live Debugger SDK doesn't depend on the RUM Browser SDK. + +interface EventHookParams { + eventType: string + domainContext: object +} + +// eslint-disable-next-line @typescript-eslint/consistent-type-definitions -- `type` is needed for implicit index signature compatibility with RUM event types +type ExceptionReplayEventAttributes = { + type: 'error' + error: { debug_info_captured: 'true' } + _dd: { + exception_replay: { + exception_id: string + frames: Array<{ index: number; snapshot_id: string }> + } + } +} + +type AssembleEventHook = (params: EventHookParams) => ExceptionReplayEventAttributes | SKIPPED +type EventCollectedHook = (params: EventHookParams) => void + +interface ExceptionReplayPluginOnInitOptions { + publicApi: { getInternalContext: () => object | undefined } + registerAssembleEventHook: (callback: AssembleEventHook) => unknown + // Missing from RUM Browser SDK versions older than this plugin + registerEventCollectedHook?: (callback: EventCollectedHook) => unknown + isTrackingConsentGranted?: () => boolean +} + +/** + * Exception Replay plugin for the RUM Browser SDK. Compatible with the RUM Browser SDK's `RumPlugin`. + */ +export interface ExceptionReplayPlugin { + name: string + onInit(options: ExceptionReplayPluginOnInitOptions): void + onRumStart(): void +} + +export interface RumGlobal { + // The async loading snippet also defines it, and queues the callbacks until the SDK loads + onReady?: (callback: () => void) => void + // Missing from RUM Browser SDK versions older than this plugin + addPlugin?: (plugin: ExceptionReplayPlugin) => void +} + +interface BrowserWindow { + DD_RUM?: RumGlobal +} + +/** + * Add the Exception Replay plugin to the RUM Browser SDK on the page, once it has loaded. Called by + * `DD_DEBUGGER.init()`, so customers don't have to change their RUM configuration. + * + * Does nothing if the RUM Browser SDK isn't on the page, since the Live Debugger SDK also works + * without it. + */ +export function addExceptionReplayPluginToRum(): void { + ;(globalObject as BrowserWindow).DD_RUM?.onReady?.(() => { + const rum = (globalObject as BrowserWindow).DD_RUM + if (!rum?.addPlugin) { + display.warn('Exception Replay requires a version of the RUM Browser SDK that matches the Live Debugger SDK.') + return + } + rum.addPlugin(exceptionReplayPlugin()) + }) +} + +/** + * Create the Exception Replay plugin for the RUM Browser SDK. + * + * When an application built with the Live Debugger build plugin's `exceptionReplay` option throws, + * the Live Debugger SDK captures the arguments of the instrumented functions the exception passes + * through. When RUM reports the error, this plugin links those captures to the RUM error event, and + * sends them as snapshots once the event passes `beforeSend` and the event rate limits, so Error + * Tracking can show them on the error's stack frames. + * + * Exception Replay only starts once RUM has called the plugin's `onInit` and `DD_DEBUGGER.init()` is + * called. It doesn't capture anything in sessions that RUM doesn't track, or before tracking consent + * is granted. + */ +export function exceptionReplayPlugin(): ExceptionReplayPlugin { + let rumStarted = false + + return { + name: 'exception-replay', + onInit({ publicApi, registerAssembleEventHook, registerEventCollectedHook, isTrackingConsentGranted }) { + if (!registerEventCollectedHook || !isTrackingConsentGranted) { + display.warn('Exception Replay requires a version of the RUM Browser SDK that matches the Live Debugger SDK.') + return + } + + // Until RUM starts, its session isn't known yet, and RUM reports the errors it buffered once + // it starts, so they're captured, unless RUM is waiting for tracking consent. Consent is + // still checked once RUM starts: the event bridge's session outlives it. + registerExceptionReplayPlugin( + () => isTrackingConsentGranted() && (!rumStarted || publicApi.getInternalContext() !== undefined) + ) + + registerAssembleEventHook(({ eventType, domainContext }) => { + if (eventType !== 'error') { + return SKIPPED + } + + const attributes = collectExceptionReplay('error' in domainContext ? domainContext.error : undefined) + if (!attributes) { + return SKIPPED + } + + return { + type: 'error', + error: { + // Error Tracking reads this flag as a string, as backend tracers set it on spans + debug_info_captured: 'true', + }, + _dd: { + exception_replay: { + exception_id: attributes.exceptionId, + frames: attributes.frames.map(({ index, snapshotId }) => ({ index, snapshot_id: snapshotId })), + }, + }, + } + }) + + registerEventCollectedHook(({ eventType, domainContext }) => { + if (eventType === 'error' && 'error' in domainContext) { + sendExceptionReplay(domainContext.error) + } + }) + }, + onRumStart() { + rumStarted = true + }, + } +} diff --git a/packages/browser-debugger/src/domain/redaction.spec.ts b/packages/browser-debugger/src/domain/redaction.spec.ts new file mode 100644 index 0000000000..ab32c3d77e --- /dev/null +++ b/packages/browser-debugger/src/domain/redaction.spec.ts @@ -0,0 +1,25 @@ +import { isRedactedIdentifier } from './redaction' + +describe('isRedactedIdentifier', () => { + it('should match sensitive identifiers', () => { + expect(isRedactedIdentifier('password')).toBeTrue() + expect(isRedactedIdentifier('token')).toBeTrue() + expect(isRedactedIdentifier('ssn')).toBeTrue() + }) + + it('should ignore case and separators', () => { + expect(isRedactedIdentifier('apiKey')).toBeTrue() + expect(isRedactedIdentifier('api_key')).toBeTrue() + expect(isRedactedIdentifier('X-Api-Key')).toBeTrue() + expect(isRedactedIdentifier('$password')).toBeTrue() + expect(isRedactedIdentifier('@session.id')).toBeTrue() + expect(isRedactedIdentifier(' Authorization ')).toBeTrue() + }) + + it('should not match other identifiers', () => { + expect(isRedactedIdentifier('username')).toBeFalse() + expect(isRedactedIdentifier('passwordHint')).toBeFalse() + expect(isRedactedIdentifier('tokens')).toBeFalse() + expect(isRedactedIdentifier('')).toBeFalse() + }) +}) diff --git a/packages/browser-debugger/src/domain/redaction.ts b/packages/browser-debugger/src/domain/redaction.ts new file mode 100644 index 0000000000..39902936fc --- /dev/null +++ b/packages/browser-debugger/src/domain/redaction.ts @@ -0,0 +1,30 @@ +// Identifiers whose values are never captured, normalized by `normalizeIdentifier`. This is the +// list the Datadog tracers redact in Dynamic Instrumentation and Exception Replay snapshots. +const REDACTED_IDENTIFIERS = new Set( + ( + '2fa accesstoken aiohttpsession apikey apisecret apisignature appkey applicationkey auth authorization ' + + 'authtoken ccnumber certificatepin cipher clientid clientsecret connectionstring connectsid cookie ' + + 'credentials creditcard csrf csrftoken cvv databaseurl dburl encryptionkey encryptionkeyid geolocation ' + + 'gpgkey ipaddress jti jwt licensekey masterkey mysqlpwd nonce oauth oauthtoken otp passhash passwd ' + + 'password passwordb pemfile pgpkey phpsessid pin pincode pkcs8 privatekey publickey pwd recaptchakey ' + + 'refreshtoken routingnumber salt secret secretkey secrettoken securityanswer securitycode ' + + 'securityquestion serviceaccountcredentials session sessionid sessionkey setcookie signature ' + + 'signaturekey sshkey ssn symfony token transactionid twiliotoken usersession voterid xapikey xauthtoken ' + + 'xcsrftoken xforwardedfor xrealip xsrf xsrftoken' + ).split(' ') +) + +const IDENTIFIER_SEPARATORS = /[-_@$.]/g + +/** + * Whether the value of a variable, argument, property or map entry with this name must be redacted + * from snapshots. Matching ignores case and the `-`, `_`, `@`, `$` and `.` separators, so + * `api_key`, `apiKey` and `X-Api-Key` all match `apikey`. + */ +export function isRedactedIdentifier(name: string): boolean { + return REDACTED_IDENTIFIERS.has(normalizeIdentifier(name)) +} + +function normalizeIdentifier(name: string): string { + return name.trim().toLowerCase().replace(IDENTIFIER_SEPARATORS, '') +} diff --git a/packages/browser-debugger/src/domain/stacktrace.ts b/packages/browser-debugger/src/domain/stacktrace.ts index b582a6632e..1bc3064c38 100644 --- a/packages/browser-debugger/src/domain/stacktrace.ts +++ b/packages/browser-debugger/src/domain/stacktrace.ts @@ -47,7 +47,14 @@ function mapStackFrame(frame: StackTrace['stack'][number]): StackFrame | undefin } } -function mapStackFrames(stack: StackTrace['stack'], skipFrames = 0): StackFrame[] { +/** + * Map frames parsed by `computeStackTrace` to snapshot stack frames, dropping frames without a location + * + * @param stack - Frames parsed by `computeStackTrace` + * @param skipFrames - Number of frames to skip from the top of the stack (default: 0) + * @returns Array of stack frames + */ +export function mapStackFrames(stack: StackTrace['stack'], skipFrames = 0): StackFrame[] { return stack.reduce((result, frame, index) => { if (index < skipFrames) { return result diff --git a/packages/browser-debugger/src/entries/main.spec.ts b/packages/browser-debugger/src/entries/main.spec.ts index 5a21ea36c9..a3c45e870b 100644 --- a/packages/browser-debugger/src/entries/main.spec.ts +++ b/packages/browser-debugger/src/entries/main.spec.ts @@ -3,6 +3,8 @@ import { registerCleanupTask, replaceMockableWithSpy } from '@datadog/browser-co import { initDebuggerTransport } from '../domain/api' import { startDeliveryApiPolling } from '../domain/deliveryApi' import { display } from '../domain/display' +import { registerExceptionReplayPlugin, resetExceptionReplay, startExceptionReplay } from '../domain/exceptionReplay' +import { addExceptionReplayPluginToRum } from '../domain/exceptionReplayPlugin' import { startDebuggerBatch } from '../transport/startDebuggerBatch' import type { BrowserWindow, DebuggerBuildMetadata, DebuggerInitConfiguration } from './main' import { datadogDebugger } from './main' @@ -33,6 +35,7 @@ describe('datadogDebugger', () => { delete browserWindow.$dd_return delete browserWindow.$dd_throw delete browserWindow.$dd_probes + resetExceptionReplay() }) }) @@ -44,6 +47,34 @@ describe('datadogDebugger', () => { }) }) + it('should start Exception Replay and add its plugin to RUM on init', () => { + mockInitDependencies() + const startExceptionReplaySpy = replaceMockableWithSpy(startExceptionReplay) + const addExceptionReplayPluginToRumSpy = replaceMockableWithSpy(addExceptionReplayPluginToRum) + + datadogDebugger.init(INIT_CONFIGURATION) + + expect(startExceptionReplaySpy).toHaveBeenCalled() + expect(addExceptionReplayPluginToRumSpy).toHaveBeenCalled() + }) + + it('should install the Exception Replay catch hook on init once the plugin is registered', () => { + mockInitDependencies() + registerExceptionReplayPlugin(() => true) + + datadogDebugger.init(INIT_CONFIGURATION) + + expect(browserWindow.$dd_catch).toBeDefined() + }) + + it('should not install the Exception Replay catch hook on init without the plugin', () => { + mockInitDependencies() + + datadogDebugger.init(INIT_CONFIGURATION) + + expect(browserWindow.$dd_catch).toBeUndefined() + }) + it('should default the init version from build-plugin metadata', async () => { browserWindow.__DD_LIVE_DEBUGGER_BUILD__ = { version: 'build-version' } const { initTransportSpy, startDeliveryApiPollingSpy } = mockInitDependencies() diff --git a/packages/browser-debugger/src/entries/main.ts b/packages/browser-debugger/src/entries/main.ts index 77e796838a..5122f88b1a 100644 --- a/packages/browser-debugger/src/entries/main.ts +++ b/packages/browser-debugger/src/entries/main.ts @@ -13,6 +13,9 @@ import type { Site } from '@datadog/js-core/transport' import { initDebuggerTransport, onEntry, onReturn, onThrow } from '../domain/api' import { startDeliveryApiPolling } from '../domain/deliveryApi' import { display } from '../domain/display' +import type { onCatch } from '../domain/exceptionReplay' +import { startExceptionReplay } from '../domain/exceptionReplay' +import { addExceptionReplayPluginToRum } from '../domain/exceptionReplayPlugin' import { getProbes } from '../domain/probes' import { startDebuggerBatch } from '../transport/startDebuggerBatch' @@ -182,6 +185,7 @@ export interface BrowserWindow { $dd_return?: typeof onReturn $dd_throw?: typeof onThrow $dd_probes?: typeof getProbes + $dd_catch?: typeof onCatch } function getBuildMetadataString(key: keyof DebuggerBuildMetadata): string | undefined { @@ -232,6 +236,8 @@ function makeDebuggerPublicApi(): DatadogDebugger { debuggerGlobal.$dd_return = onReturn debuggerGlobal.$dd_throw = onThrow debuggerGlobal.$dd_probes = getProbes + mockable(startExceptionReplay)() + mockable(addExceptionReplayPluginToRum)() mockable(startDeliveryApiPolling)({ service: resolvedConfiguration.service, diff --git a/packages/browser-rum-core/src/boot/preStartRum.spec.ts b/packages/browser-rum-core/src/boot/preStartRum.spec.ts index a5d3e013ce..2617b54141 100644 --- a/packages/browser-rum-core/src/boot/preStartRum.spec.ts +++ b/packages/browser-rum-core/src/boot/preStartRum.spec.ts @@ -28,7 +28,7 @@ import { import type { RumInitConfiguration } from '../domain/configuration' import type { ViewOptions } from '../domain/view/trackViews' import { ActionType, VitalType } from '../rawRumEvent.types' -import type { RumPlugin } from '../domain/plugins' +import type { RumPlugin, RumPluginOnInitOptions } from '../domain/plugins' import type { AssembleHookParams } from '../domain/hooks' import type { ManualAction } from '../domain/action/trackManualActions' import type { RumPublicApi, RumPublicApiOptions, Strategy } from './rumPublicApi' @@ -616,6 +616,20 @@ describe('preStartRum', () => { }) describe('plugins', () => { + it('tells plugins whether tracking consent is granted, including when it was set before init()', () => { + const plugin = { name: 'a', onInit: jasmine.createSpy() } + const trackingConsentState = createTrackingConsentState() + const { strategy } = createPreStartStrategyWithDefaults({ trackingConsentState }) + + trackingConsentState.update(TrackingConsent.NOT_GRANTED) + strategy.init({ ...DEFAULT_INIT_CONFIGURATION, plugins: [plugin] }, PUBLIC_API) + const { isTrackingConsentGranted } = plugin.onInit.calls.mostRecent().args[0] as RumPluginOnInitOptions + expect(isTrackingConsentGranted()).toBeFalse() + + trackingConsentState.update(TrackingConsent.GRANTED) + expect(isTrackingConsentGranted()).toBeTrue() + }) + it('calls the onInit method on provided plugins', () => { const plugin = { name: 'a', onInit: jasmine.createSpy() } const { strategy } = createPreStartStrategyWithDefaults() @@ -626,6 +640,8 @@ describe('preStartRum', () => { jasmine.objectContaining({ initConfiguration, publicApi: PUBLIC_API, + registerAssembleEventHook: jasmine.any(Function), + registerEventCollectedHook: jasmine.any(Function), }) ) }) diff --git a/packages/browser-rum-core/src/boot/preStartRum.ts b/packages/browser-rum-core/src/boot/preStartRum.ts index 1109dd373b..ed55c1e714 100644 --- a/packages/browser-rum-core/src/boot/preStartRum.ts +++ b/packages/browser-rum-core/src/boot/preStartRum.ts @@ -368,6 +368,8 @@ export function createPreStartStrategy( initConfiguration, publicApi, registerAssembleEventHook: hooks.assembleEvent.register, + registerEventCollectedHook: hooks.eventCollected.register, + isTrackingConsentGranted: trackingConsentState.isGranted, } const shouldContinue = callPluginsOnInit(initConfiguration.plugins, onInitOptions) diff --git a/packages/browser-rum-core/src/domain/assembly.spec.ts b/packages/browser-rum-core/src/domain/assembly.spec.ts index f50667be8f..db1ce8b96e 100644 --- a/packages/browser-rum-core/src/domain/assembly.spec.ts +++ b/packages/browser-rum-core/src/domain/assembly.spec.ts @@ -1,6 +1,6 @@ import { ONE_MINUTE, relativeToClocks } from '@datadog/js-core/time' import type { TimeStamp, ClocksState, RelativeTime } from '@datadog/js-core/time' -import { SKIPPED } from '@datadog/js-core/assembly' +import { DISCARDED, SKIPPED } from '@datadog/js-core/assembly' import type { SessionManager } from '@datadog/browser-core' import { display, startGlobalContext, startTabContext } from '@datadog/browser-core' import type { Clock } from '@datadog/browser-core/test' @@ -791,6 +791,73 @@ describe('rum assembly', () => { }) }) + describe('eventCollected hook', () => { + it('is triggered with the event type and domain context', () => { + const { lifeCycle, hooks } = setupAssemblyTestWithDefaults() + const eventCollectedSpy = jasmine.createSpy('eventCollected') + hooks.eventCollected.register(eventCollectedSpy) + const domainContext = { error: new Error('boom') } as RumEventDomainContext + + notifyRawRumEvent(lifeCycle, { rawRumEvent: createRawRumEvent(RumEventType.ERROR), domainContext }) + + expect(eventCollectedSpy).toHaveBeenCalledOnceWith({ + eventType: RumEventType.ERROR, + domainContext, + }) + }) + + it('is triggered before the event is dispatched', () => { + const { lifeCycle, hooks } = setupAssemblyTestWithDefaults() + const calls: string[] = [] + hooks.eventCollected.register(() => { + calls.push('eventCollected') + }) + const subscription = lifeCycle.subscribe(LifeCycleEventType.RUM_EVENT_COLLECTED, () => { + calls.push('RUM_EVENT_COLLECTED') + }) + registerCleanupTask(() => subscription.unsubscribe()) + + notifyRawRumEvent(lifeCycle, { rawRumEvent: createRawRumEvent(RumEventType.ERROR) }) + + expect(calls).toEqual(['eventCollected', 'RUM_EVENT_COLLECTED']) + }) + + it('calls every callback, even after one returns DISCARDED', () => { + const { lifeCycle, hooks, serverRumEvents } = setupAssemblyTestWithDefaults() + const eventCollectedSpy = jasmine.createSpy('eventCollected') + hooks.eventCollected.register(() => DISCARDED) + hooks.eventCollected.register(eventCollectedSpy) + + notifyRawRumEvent(lifeCycle, { rawRumEvent: createRawRumEvent(RumEventType.ERROR) }) + + expect(eventCollectedSpy).toHaveBeenCalledTimes(1) + expect(serverRumEvents.length).toBe(1) + }) + + it('is not triggered for events dismissed by beforeSend', () => { + const { lifeCycle, hooks } = setupAssemblyTestWithDefaults({ + partialConfiguration: { beforeSend: () => false }, + }) + const eventCollectedSpy = jasmine.createSpy('eventCollected') + hooks.eventCollected.register(eventCollectedSpy) + + notifyRawRumEvent(lifeCycle, { rawRumEvent: createRawRumEvent(RumEventType.ERROR) }) + + expect(eventCollectedSpy).not.toHaveBeenCalled() + }) + + it('is not triggered for events over the rate limit', () => { + const { lifeCycle, hooks } = setupAssemblyTestWithDefaults({ eventRateLimit: 1 }) + const eventCollectedSpy = jasmine.createSpy('eventCollected') + hooks.eventCollected.register(eventCollectedSpy) + + notifyRawRumEvent(lifeCycle, { rawRumEvent: createRawRumEvent(RumEventType.ERROR) }) + notifyRawRumEvent(lifeCycle, { rawRumEvent: createRawRumEvent(RumEventType.ERROR) }) + + expect(eventCollectedSpy).toHaveBeenCalledTimes(1) + }) + }) + describe('event generation condition', () => { it('when tracked, it should generate event', () => { const { lifeCycle, serverRumEvents } = setupAssemblyTestWithDefaults() diff --git a/packages/browser-rum-core/src/domain/assembly.ts b/packages/browser-rum-core/src/domain/assembly.ts index df2ec75793..e12f75a620 100644 --- a/packages/browser-rum-core/src/domain/assembly.ts +++ b/packages/browser-rum-core/src/domain/assembly.ts @@ -102,6 +102,7 @@ export function startRumAssembly( if (isEmptyObject(serverRumEvent.context!)) { delete serverRumEvent.context } + hooks.eventCollected.trigger({ eventType: serverRumEvent.type, domainContext }) lifeCycle.notify(LifeCycleEventType.RUM_EVENT_COLLECTED, serverRumEvent) } } diff --git a/packages/browser-rum-core/src/domain/hooks.ts b/packages/browser-rum-core/src/domain/hooks.ts index aa218a9f6e..4abc896b4d 100644 --- a/packages/browser-rum-core/src/domain/hooks.ts +++ b/packages/browser-rum-core/src/domain/hooks.ts @@ -2,6 +2,7 @@ import type { Duration, RelativeTime } from '@datadog/js-core/time' import type { TelemetryEvent } from '@datadog/browser-core' import { createHook } from '@datadog/js-core/assembly' import type { Hook } from '@datadog/js-core/assembly' +import { Observable } from '@datadog/js-core/util' import type { RecursivePartial } from '@datadog/js-core/util' import type { RumEvent } from '../rumEvent.types' import type { RawRumEvent } from '../rawRumEvent.types' @@ -29,10 +30,25 @@ export interface AssembleHookParams { export type AssembleHook = Hook export type AssembleTelemetryHook = Hook<{ startTime: RelativeTime }, DefaultTelemetryEventAttributes> +// Unlike AssembleHookParams, the domain context isn't DeepReadonly: checking that it fits recurses +// through the DOM types it holds, which the declaration build rejects as excessively deep. +export interface EventCollectedHookParams { + readonly eventType: RumEvent['type'] + readonly domainContext: RumEventDomainContext +} + +// Unlike the assemble hooks, callbacks can't discard the event, which is about to be sent, so every +// callback is called, whatever the others return. +export interface EventCollectedHook { + register(this: void, callback: (params: EventCollectedHookParams) => void): { unregister: () => void } + trigger(this: void, params: EventCollectedHookParams): void +} + export interface Hooks { assembleEventDefaults: AssembleHook assembleTelemetry: AssembleTelemetryHook assembleEvent: AssembleHook + eventCollected: EventCollectedHook } export function createHooks(): Hooks { @@ -40,5 +56,19 @@ export function createHooks(): Hooks { assembleEventDefaults: createHook(), assembleTelemetry: createHook(), assembleEvent: createHook(), + eventCollected: createEventCollectedHook(), + } +} + +function createEventCollectedHook(): EventCollectedHook { + const observable = new Observable() + return { + register(callback) { + const { unsubscribe } = observable.subscribe(callback) + return { unregister: unsubscribe } + }, + trigger(params) { + observable.notify(params) + }, } } diff --git a/packages/browser-rum-core/src/domain/plugins.ts b/packages/browser-rum-core/src/domain/plugins.ts index 171c7ea1d2..6a4a968b7f 100644 --- a/packages/browser-rum-core/src/domain/plugins.ts +++ b/packages/browser-rum-core/src/domain/plugins.ts @@ -2,7 +2,7 @@ import { isThenable } from '@datadog/browser-core' import type { RumPublicApi } from '../boot/rumPublicApi' import type { StartRumResult } from '../boot/startRum' import type { RumInitConfiguration } from './configuration' -import type { AssembleHook } from './hooks' +import type { AssembleHook, EventCollectedHook } from './hooks' /** * onInit plugin API options. @@ -18,6 +18,17 @@ export interface RumPluginOnInitOptions { * assembled, including events buffered during the pre-start phase. */ registerAssembleEventHook: AssembleHook['register'] + /** + * Register a callback invoked when a RUM event is collected, once `beforeSend` and the event rate + * limits have let it through, right before it is sent. Plugins can use it to send data related to + * an event only if the event itself is sent. + */ + registerEventCollectedHook: EventCollectedHook['register'] + /** + * Whether tracking consent is granted, whether it was set with the `trackingConsent` init option + * or with `setTrackingConsent()`, including before init(). RUM doesn't start until it is. + */ + isTrackingConsentGranted: () => boolean } /** diff --git a/packages/browser-rum-core/src/rumEvent.types.ts b/packages/browser-rum-core/src/rumEvent.types.ts index 91f869f8ec..3fcf9de2dd 100644 --- a/packages/browser-rum-core/src/rumEvent.types.ts +++ b/packages/browser-rum-core/src/rumEvent.types.ts @@ -496,6 +496,10 @@ export type RumErrorEvent = CommonProperties & * Time since application start when error happened (in milliseconds) */ readonly time_since_app_start?: number + /** + * Whether Exception Replay captured snapshots for this error. A string rather than a boolean, to match the `error.debug_info_captured` span tag that Error Tracking reads for backend errors + */ + readonly debug_info_captured?: 'true' [k: string]: unknown } /** @@ -546,6 +550,30 @@ export type RumErrorEvent = CommonProperties & id: string [k: string]: unknown }[] + /** + * Exception Replay snapshots captured for the stack frames of the error + */ + exception_replay?: { + /** + * UUID of the captured exception, also set as `exceptionId` on each of its snapshots + */ + exception_id: string + /** + * Stack frames of the error that have a snapshot, from the innermost frame outwards + */ + frames: { + /** + * Index of the frame in `error.stack`, starting at 0 for the innermost frame + */ + index: number + /** + * UUID of the Live Debugger snapshot captured for the frame + */ + snapshot_id: string + [k: string]: unknown + }[] + [k: string]: unknown + } [k: string]: unknown } [k: string]: unknown diff --git a/test/e2e/scenario/debugger.scenario.ts b/test/e2e/scenario/debugger.scenario.ts index 1c8963f0a6..cdc670cb57 100644 --- a/test/e2e/scenario/debugger.scenario.ts +++ b/test/e2e/scenario/debugger.scenario.ts @@ -1,7 +1,7 @@ /* eslint-disable @typescript-eslint/no-unsafe-call, camelcase */ import { test, expect } from '@playwright/test' import type { Page } from '@playwright/test' -import { createTest, microfrontendSetup } from '../lib/framework' +import { createTest, html, microfrontendSetup } from '../lib/framework' const DEBUGGER_POLL_INTERVAL = 1_000 const PROBE_WAIT_TIMEOUT = 30_000 @@ -168,6 +168,30 @@ async function injectThrowingFunction(page: Page) { await waitForProbe(page, 'TestModule;throwingFunction') } +// Instrumented code is loaded from a script, so its stack frames have a URL. Code evaluated by +// Playwright has none, so Exception Replay can't locate its frames. +const EXCEPTION_REPLAY_BODY = html` + +` + test.describe('debugger', () => { createTest('send debugger snapshot when instrumented function is called') .withDebugger() @@ -648,4 +672,75 @@ test.describe('debugger', () => { outcome: 'return', }) }) + + createTest('link Exception Replay snapshots to the RUM error event') + .withRum() + .withDebugger() + .withBody(EXCEPTION_REPLAY_BODY) + .run(async ({ intakeRegistry, flushEvents, page }) => { + await page.evaluate(() => { + try { + ;(window as any).callingFunction(1) + } catch (error) { + window.DD_RUM!.addError(error) + } + }) + + await flushEvents() + + expect(intakeRegistry.rumErrorEvents).toHaveLength(1) + const errorEvent = intakeRegistry.rumErrorEvents[0] + expect((errorEvent.error as any).debug_info_captured).toBe('true') + const exceptionReplay = (errorEvent._dd as any).exception_replay + const stackFrames = errorEvent.error.stack!.split('\n').slice(1) + expect( + exceptionReplay.frames.map(({ index }: { index: number }) => stackFrames[index].trim().split(' ')[1]) + ).toEqual(['throwingFunction', 'callingFunction']) + + const snapshots = intakeRegistry.debuggerEvents.map( + (event) => + (event.debugger as any).snapshot as { + id: string + exceptionId: string + probe: { location: unknown } + captures: { return: { arguments: Record } } + } + ) + expect(snapshots.map(({ id }) => id)).toEqual( + exceptionReplay.frames.map(({ snapshot_id }: { snapshot_id: string }) => snapshot_id) + ) + expect(snapshots.map(({ exceptionId }) => exceptionId)).toEqual([ + exceptionReplay.exception_id, + exceptionReplay.exception_id, + ]) + expect(snapshots[0].probe.location).toEqual({ type: 'src/throwing.ts', method: 'throwingFunction' }) + expect(snapshots[0].captures.return.arguments.count).toEqual({ type: 'number', value: '2' }) + expect(snapshots[0].captures.return.arguments.token).toEqual({ + type: 'string', + notCapturedReason: 'redactedIdent', + }) + expect(snapshots[1].captures.return.arguments.count).toEqual({ type: 'number', value: '1' }) + }) + + createTest('do not send Exception Replay snapshots for errors dismissed by beforeSend') + .withRum() + .withRumInit((configuration) => { + window.DD_RUM!.init({ ...configuration, beforeSend: (event) => event.type !== 'error' }) + }) + .withDebugger() + .withBody(EXCEPTION_REPLAY_BODY) + .run(async ({ intakeRegistry, flushEvents, page }) => { + await page.evaluate(() => { + try { + ;(window as any).callingFunction(1) + } catch (error) { + window.DD_RUM!.addError(error) + } + }) + + await flushEvents() + + expect(intakeRegistry.rumErrorEvents).toHaveLength(0) + expect(intakeRegistry.debuggerEvents).toHaveLength(0) + }) }) diff --git a/yarn.lock b/yarn.lock index 733e2c9810..3371963ec0 100644 --- a/yarn.lock +++ b/yarn.lock @@ -484,6 +484,7 @@ __metadata: resolution: "@datadog/browser-debugger@workspace:packages/browser-debugger" dependencies: "@datadog/browser-core": "workspace:*" + "@datadog/browser-rum-core": "workspace:*" "@datadog/js-core": "workspace:*" languageName: unknown linkType: soft @@ -749,10 +750,10 @@ __metadata: languageName: unknown linkType: soft -"@datadog/rum-events-format@DataDog/rum-events-format#commit=748d7fe6d0e36624b7ea64e26731e43e347637b5": +"@datadog/rum-events-format@DataDog/rum-events-format#commit=79c264a627e2ebba7182e5d088aad84124de23c8": version: 0.0.0 - resolution: "@datadog/rum-events-format@https://github.com/DataDog/rum-events-format.git#commit=748d7fe6d0e36624b7ea64e26731e43e347637b5" - checksum: 10c0/3426d4a433ed7055d1ba8421e3cef6f5e6576d9c354c4613314cdda894cc28b32718f5f86a2801efa32057f2f3612772d72571d9226acbf79dd52e17d2c8d0ae + resolution: "@datadog/rum-events-format@https://github.com/DataDog/rum-events-format.git#commit=79c264a627e2ebba7182e5d088aad84124de23c8" + checksum: 10c0/8e8ff2092f23e5389a403c3ff9b61f5ff3a348e9bd366ce62709421b53906b5b5292fac00798a743ed29e43301d9e528a63d87edebd139ca0fe12547bd1581ee languageName: node linkType: hard @@ -6332,7 +6333,7 @@ __metadata: version: 0.0.0-use.local resolution: "browser-sdk@workspace:." dependencies: - "@datadog/rum-events-format": "DataDog/rum-events-format#commit=748d7fe6d0e36624b7ea64e26731e43e347637b5" + "@datadog/rum-events-format": "DataDog/rum-events-format#commit=79c264a627e2ebba7182e5d088aad84124de23c8" "@eslint/js": "npm:10.0.1" "@microsoft/api-extractor": "npm:7.60.1" "@oxc-project/runtime": "npm:0.152.0"