From 400543bc4b232070791bd26de5632df5a1eee0f5 Mon Sep 17 00:00:00 2001 From: "carlos.nogueira" Date: Wed, 25 Nov 2026 13:33:46 +0000 Subject: [PATCH 1/2] [RUM-20338] Add Vega crash reporting and app metadata --- .../DdRumErrorTracking.test.tsx | 82 +++++++++++++++ packages/core/src/internal.ts | 4 + .../instrumentation/DdRumErrorTracking.tsx | 63 +++++++++--- packages/react-native-vega/CMakeLists.txt | 4 +- packages/react-native-vega/README.md | 33 +++++++ .../__tests__/ApplicationMetadata.test.ts | 99 +++++++++++++++++++ .../__tests__/DdLogsVega.test.ts | 7 +- .../__tests__/DdRumVega.test.ts | 18 +++- .../__tests__/ErrorContext.test.ts | 98 ++++++++++++++++++ .../__tests__/ErrorTracking.test.ts | 29 ++++++ .../__tests__/importSafety.test.ts | 14 +++ .../CrashReportingConfiguration.cpp | 52 ++++++++++ .../CrashReportingConfiguration.h | 19 ++++ .../turbo-modules/DatadogGlobalState.cpp | 11 +++ .../kepler/turbo-modules/DatadogGlobalState.h | 5 + .../src/ApplicationMetadata.ts | 66 +++++++++++++ packages/react-native-vega/src/DdLogsVega.ts | 3 +- packages/react-native-vega/src/DdRumVega.ts | 3 +- .../react-native-vega/src/ErrorContext.ts | 15 +++ .../react-native-vega/src/ErrorTracking.ts | 23 +++++ .../react-native-vega/tests/CMakeLists.txt | 57 +++++++---- .../tests/CrashReportingConfigurationTest.cpp | 80 +++++++++++++++ 22 files changed, 746 insertions(+), 39 deletions(-) create mode 100644 packages/react-native-vega/__tests__/ApplicationMetadata.test.ts create mode 100644 packages/react-native-vega/__tests__/ErrorContext.test.ts create mode 100644 packages/react-native-vega/__tests__/ErrorTracking.test.ts create mode 100644 packages/react-native-vega/kepler/turbo-modules/CrashReportingConfiguration.cpp create mode 100644 packages/react-native-vega/kepler/turbo-modules/CrashReportingConfiguration.h create mode 100644 packages/react-native-vega/src/ApplicationMetadata.ts create mode 100644 packages/react-native-vega/src/ErrorContext.ts create mode 100644 packages/react-native-vega/src/ErrorTracking.ts create mode 100644 packages/react-native-vega/tests/CrashReportingConfigurationTest.cpp diff --git a/packages/core/src/__tests__/rum/instrumentation/DdRumErrorTracking.test.tsx b/packages/core/src/__tests__/rum/instrumentation/DdRumErrorTracking.test.tsx index 2fbcba61f..05effa321 100644 --- a/packages/core/src/__tests__/rum/instrumentation/DdRumErrorTracking.test.tsx +++ b/packages/core/src/__tests__/rum/instrumentation/DdRumErrorTracking.test.tsx @@ -692,3 +692,85 @@ class RNErrorHandlerMock { console.error(...params); }; } + +it.each(['throw', 'reject'] as const)( + 'M chain previous handlers W injected reporter %s', + async failure => { + const reporter = { + addError: jest.fn(() => + failure === 'throw' + ? (() => { + throw Error('reporter'); + })() + : Promise.reject(Error('reporter')) + ) + }; + DdRumErrorTracking.startTracking(reporter); + DdRumErrorTracking.onGlobalError(Error('app error'), true); + DdRumErrorTracking.onConsoleError('console error'); + await flushPromises(); + expect(reporter.addError).toHaveBeenCalledTimes(2); + expect(baseErrorHandlerCalled).toBe(true); + expect(baseConsoleErrorCalled).toBe(true); + } +); + +it('M bound reporting W injected reporter never resolves', async () => { + jest.useFakeTimers(); + try { + DdRumErrorTracking.startTracking({ + addError: () => new Promise(() => undefined) + }); + DdRumErrorTracking.onGlobalError(Error('app error'), true); + await jest.advanceTimersByTimeAsync(50); + expect(baseErrorHandlerCalled).toBe(true); + } finally { + jest.useRealTimers(); + } +}); + +it('M replace reporter W tracking already started without wrapping handlers twice', async () => { + const first = { addError: jest.fn(() => Promise.resolve()) }; + const second = { addError: jest.fn(() => Promise.resolve()) }; + DdRumErrorTracking.startTracking(first); + const handler = ErrorUtils.getGlobalHandler(); + const consoleHandler = console.error; + DdRumErrorTracking.startTracking(second); + expect(ErrorUtils.getGlobalHandler()).toBe(handler); + expect(console.error).toBe(consoleHandler); + DdRumErrorTracking.onGlobalError(Error('app error')); + await flushPromises(); + expect(second.addError).toHaveBeenCalledTimes(1); + expect(first.addError).not.toHaveBeenCalled(); +}); + +it('M remain safe W ErrorUtils is unavailable', () => { + const previous = global.ErrorUtils; + try { + Object.defineProperty(global, 'ErrorUtils', { + configurable: true, + value: undefined + }); + expect(() => DdRumErrorTracking.startTracking()).not.toThrow(); + expect(console.error).toBe(baseConsoleError); + } finally { + Object.defineProperty(global, 'ErrorUtils', { + configurable: true, + value: previous + }); + } +}); + +it('M chain previous handlers W error properties throw during encoding', async () => { + const error = Object.defineProperty({}, 'message', { + get: () => { + throw Error('getter'); + } + }); + DdRumErrorTracking.startTracking(); + DdRumErrorTracking.onGlobalError(error, true); + DdRumErrorTracking.onConsoleError(error); + await flushPromises(); + expect(baseErrorHandlerCalled).toBe(true); + expect(baseConsoleErrorCalled).toBe(true); +}); diff --git a/packages/core/src/internal.ts b/packages/core/src/internal.ts index 425901668..2dad98ce7 100644 --- a/packages/core/src/internal.ts +++ b/packages/core/src/internal.ts @@ -33,3 +33,7 @@ export type { TraceNativeConfiguration } from './config/features/TraceConfigurat export type { InitializationModeForTelemetry } from './config/types/InitializationModeForTelemetry'; export { callWithoutResourceTracking } from './rum/instrumentation/resourceTracking/requestProxy/common/FetchProxyState'; + +export { DdAttributes } from './DdAttributes'; +export { debugId } from './metro/debugIdResolver'; +export { DdRumErrorTracking } from './rum/instrumentation/DdRumErrorTracking'; diff --git a/packages/core/src/rum/instrumentation/DdRumErrorTracking.tsx b/packages/core/src/rum/instrumentation/DdRumErrorTracking.tsx index 9cf1f540c..3c567f2dd 100644 --- a/packages/core/src/rum/instrumentation/DdRumErrorTracking.tsx +++ b/packages/core/src/rum/instrumentation/DdRumErrorTracking.tsx @@ -20,12 +20,16 @@ import { ErrorSource } from '../../types'; import { executeWithDelay } from '../../utils/jsUtils'; import { DdRum } from '../DdRum'; +type RumErrorReporter = Pick; + /** * Provides RUM auto-instrumentation feature to track errors as RUM events. */ export class DdRumErrorTracking { private static isTracking = false; + private static reporter?: RumErrorReporter; + private static isInDefaultErrorHandler = false; // eslint-disable-next-line @@ -37,7 +41,8 @@ export class DdRumErrorTracking { /** * Starts tracking errors and sends a RUM Error event every time an error is detected. */ - static startTracking(): void { + static startTracking(reporter: RumErrorReporter = DdRum): void { + DdRumErrorTracking.reporter = reporter; // extra safety to avoid wrapping the Error handler twice if (DdRumErrorTracking.isTracking) { InternalLog.log( @@ -47,7 +52,7 @@ export class DdRumErrorTracking { return; } - if (ErrorUtils) { + if (typeof ErrorUtils !== 'undefined') { DdRumErrorTracking.defaultErrorHandler = ErrorUtils.getGlobalHandler(); DdRumErrorTracking.defaultConsoleError = console.error; @@ -68,12 +73,17 @@ export class DdRumErrorTracking { } static onGlobalError = (error: any, isFatal?: boolean): void => { - const message = getErrorMessage(error); - const stacktrace = getErrorStackTrace(error); - this.reportError(message, ErrorSource.SOURCE, stacktrace, { - '_dd.error.is_crash': isFatal, - '_dd.error.raw': errorEncoder.encode(error) - }).then(async () => { + this.reportSafely(() => + this.reportError( + getErrorMessage(error), + ErrorSource.SOURCE, + getErrorStackTrace(error), + { + '_dd.error.is_crash': isFatal, + '_dd.error.raw': errorEncoder.encode(error) + } + ) + ).then(async () => { DdRumErrorTracking.isInDefaultErrorHandler = true; try { // On real iOS devices, the crash context is not updated soon @@ -95,7 +105,14 @@ export class DdRumErrorTracking { if (DdRumErrorTracking.isInDefaultErrorHandler) { return; } + this.reportSafely(() => this.reportConsoleError(...params)).then(() => { + DdRumErrorTracking.defaultConsoleError.apply(console, params); + }); + }; + private static reportConsoleError = ( + ...params: unknown[] + ): Promise => { let stack: string = ERROR_EMPTY_STACKTRACE; let errorName: string = ERROR_DEFAULT_NAME; for (let i = 0; i < params.length; i += 1) { @@ -129,9 +146,26 @@ export class DdRumErrorTracking { }) .join(' '); - this.reportError(message, ErrorSource.CONSOLE, stack).then(() => { - DdRumErrorTracking.defaultConsoleError.apply(console, params); - }); + return this.reportError(message, ErrorSource.CONSOLE, stack); + }; + + /** A failed or stalled SDK reporter must not suppress the previous handler. */ + private static reportSafely = async ( + report: () => Promise + ): Promise => { + let timeout: ReturnType | undefined; + try { + await Promise.race([ + Promise.resolve(report()).catch(() => undefined), + new Promise(resolve => { + timeout = setTimeout(resolve, 50); + }) + ]); + } catch { + // A reporter can throw before returning a promise. + } finally { + clearTimeout(timeout); + } }; private static reportError = ( @@ -140,6 +174,11 @@ export class DdRumErrorTracking { stacktrace: string, context: object = {} ): Promise => { - return DdRum.addError(message, source, stacktrace, context); + return (DdRumErrorTracking.reporter ?? DdRum).addError( + message, + source, + stacktrace, + context + ); }; } diff --git a/packages/react-native-vega/CMakeLists.txt b/packages/react-native-vega/CMakeLists.txt index 335bfe990..4667494d6 100644 --- a/packages/react-native-vega/CMakeLists.txt +++ b/packages/react-native-vega/CMakeLists.txt @@ -34,7 +34,7 @@ set(DD_UUID_USE_DEFAULT OFF CACHE BOOL "" FORCE) set(DD_UUID_SRC "${CMAKE_CURRENT_SOURCE_DIR}/kepler/turbo-modules/uuid_urandom.cpp" CACHE STRING "" FORCE) set(DD_HTTP_CLIENT "none" CACHE STRING "" FORCE) set(DD_BUILD_SHARED OFF CACHE BOOL "" FORCE) -set(DD_CRASH_MODE "noop" CACHE STRING "" FORCE) +set(DD_CRASH_MODE "inprocess" CACHE STRING "" FORCE) include(FetchContent) if(DEFINED Datadog_SOURCE_DIR) @@ -52,6 +52,7 @@ include(cmake/DatadogLoggingCompatibility.cmake) datadog_vega_patch_logging_registration("${datadog_SOURCE_DIR}") set(HEADERS + kepler/turbo-modules/CrashReportingConfiguration.h kepler/turbo-modules/generated/DdRumSpec.h kepler/turbo-modules/DdRum.h kepler/turbo-modules/RumBridge.h @@ -68,6 +69,7 @@ set(HEADERS ) set(SOURCES + kepler/turbo-modules/CrashReportingConfiguration.cpp kepler/turbo-modules/generated/DdRumSpec.cpp kepler/turbo-modules/DdRum.cpp kepler/turbo-modules/generated/DdLogsSpec.cpp diff --git a/packages/react-native-vega/README.md b/packages/react-native-vega/README.md index 33d66891b..1ef9b8766 100644 --- a/packages/react-native-vega/README.md +++ b/packages/react-native-vega/README.md @@ -108,3 +108,36 @@ Set `VEGA_TEST_LOGGING_CONFIGURATION=ON` in the host test CMake configuration to build the actual SDK and test failed registration, repeated configuration, and logging-only attributes. This uses the same compatibility source as Vega builds and requires the SDK and include paths described above. + +## Crash reporting and application metadata + +Native builds include the in-process crash backend. Setup registers it only when +RUM is configured with a valid application ID and `nativeCrashReportEnabled` is +`true`. Native crash capture is disabled by default. The C++ SDK installs its +handler once per process; this is a setup setting, not a runtime toggle. + +RUM errors and logs with error details include the React Native source type and +the bundle Debug ID, when available. Use the core Metro configuration to generate +that Debug ID and upload the matching source map. Ordinary logs keep their +existing attributes. + +The initializer added in RUM-20335 must use these configuration hooks: + +- `buildApplicationMetadata(configuration)` resolves service and version defaults + from the platform's existing `DeviceInfoModule` constants. Explicit `service` + and `version` values take precedence. It applies `versionSuffix` once and keeps + the SDK version separate. If app details are unavailable, the service defaults + to `vega` and the app version stays unset. +- `configureApplicationMetadata(coreConfig, additionalConfiguration)` sets native + source, SDK version, and app version before `Core::Create`. +- `configureCrashReporting(core, rumConfiguration)` runs after RUM registration + and before `Core::Start`, alongside the logging configuration hook. +- `configureErrorTracking(configuration)` enables shared JavaScript error tracking + with the Vega RUM reporter when `rumConfiguration.trackErrors` is `true`. + Importing the package does not install handlers. SDK reporting failures do not + prevent the app's existing error and console handlers from running. + +These hooks keep initialization and provider setup in RUM-20335. Host native +coverage can be enabled with `VEGA_TEST_CRASH_CONFIGURATION=ON`, using the SDK +and include paths described above. It verifies signal-handler registration +without intentionally crashing the test process. diff --git a/packages/react-native-vega/__tests__/ApplicationMetadata.test.ts b/packages/react-native-vega/__tests__/ApplicationMetadata.test.ts new file mode 100644 index 000000000..ec7aabdbc --- /dev/null +++ b/packages/react-native-vega/__tests__/ApplicationMetadata.test.ts @@ -0,0 +1,99 @@ +/* + * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. + * This product includes software developed at Datadog (https://www.datadoghq.com/). + * Copyright 2016-Present Datadog, Inc. + */ + +import { version } from '@datadog/mobile-react-native/internal'; + +import { buildApplicationMetadata } from '../src/ApplicationMetadata'; + +const mockGet = jest.fn(); +jest.mock('@amazon-devices/keplerscript-turbomodule-api', () => ({ + TurboModuleRegistry: { get: (...args: unknown[]) => mockGet(...args) } +})); + +describe('Vega application metadata', () => { + beforeEach(() => jest.resetAllMocks()); + it('reads app defaults and keeps the SDK version separate', () => { + mockGet.mockReturnValue({ + getConstants: () => ({ bundleId: 'example.app', appVersion: '2.1' }) + }); + const result = buildApplicationMetadata({ + versionSuffix: 'beta', + additionalConfiguration: { keep: true } + }); + expect(mockGet).toHaveBeenCalledWith('DeviceInfoModule'); + expect(result.service).toBe('example.app'); + expect(result.version).toBe('2.1'); + expect(result.additionalConfiguration).toEqual({ + keep: true, + '_dd.source': 'react-native', + '_dd.sdk_version': version, + '_dd.version': '2.1-beta' + }); + }); + it('respects overrides without looking up platform metadata', () => { + const input = Object.freeze({ + service: 'custom-service', + version: '4.2', + versionSuffix: 'preview', + additionalConfiguration: Object.freeze({ + '_dd.version': 'stale', + '_dd.version_suffix': '-stale' + }) + }); + const first = buildApplicationMetadata(input); + const second = buildApplicationMetadata(first); + expect(mockGet).not.toHaveBeenCalled(); + expect(second.service).toBe('custom-service'); + expect(second.additionalConfiguration['_dd.version']).toBe( + '4.2-preview' + ); + expect( + second.additionalConfiguration['_dd.version_suffix'] + ).toBeUndefined(); + expect(input.additionalConfiguration['_dd.version']).toBe('stale'); + }); + it.each([ + null, + {}, + { + getConstants: () => ({ bundleId: 'unknown', appVersion: 'unknown' }) + }, + { getConstants: () => ({ bundleId: ' ', appVersion: 42 }) }, + { + getConstants: () => { + throw Error('unavailable'); + } + } + ])( + 'keeps setup usable when platform details are unavailable: %p', + native => { + mockGet.mockReturnValue(native); + const result = buildApplicationMetadata({}); + expect(result.service).toBe('vega'); + expect(result.version).toBeUndefined(); + expect( + result.additionalConfiguration['_dd.version'] + ).toBeUndefined(); + expect(result.additionalConfiguration['_dd.sdk_version']).toBe( + version + ); + } + ); + it('keeps explicit values when a platform lookup fails', () => { + mockGet.mockImplementation(() => { + throw Error('lookup'); + }); + const result = buildApplicationMetadata({ + service: 'custom', + versionSuffix: 'beta' + }); + expect(result.service).toBe('custom'); + expect(result.version).toBeUndefined(); + expect(result.additionalConfiguration['_dd.version_suffix']).toBe( + '-beta' + ); + }); +}); diff --git a/packages/react-native-vega/__tests__/DdLogsVega.test.ts b/packages/react-native-vega/__tests__/DdLogsVega.test.ts index de4783daf..433a9dbc6 100644 --- a/packages/react-native-vega/__tests__/DdLogsVega.test.ts +++ b/packages/react-native-vega/__tests__/DdLogsVega.test.ts @@ -67,7 +67,8 @@ describe('Vega logs', () => { 'stack', { custom: true, - '_dd.error.fingerprint': 'group' + '_dd.error.fingerprint': 'group', + '_dd.error.source_type': 'react-native' } ); expect(context).toEqual({ custom: true }); @@ -81,7 +82,7 @@ describe('Vega logs', () => { '', '', 'stack', - {} + { '_dd.error.source_type': 'react-native' } ); }); it('accepts a source-only error overload without shifting attributes', async () => { @@ -100,7 +101,7 @@ describe('Vega logs', () => { '', '', '', - {} + { '_dd.error.source_type': 'react-native' } ); }); it('ignores missing, throwing, and rejecting native modules', async () => { diff --git a/packages/react-native-vega/__tests__/DdRumVega.test.ts b/packages/react-native-vega/__tests__/DdRumVega.test.ts index 794798552..a2e3dc04b 100644 --- a/packages/react-native-vega/__tests__/DdRumVega.test.ts +++ b/packages/react-native-vega/__tests__/DdRumVega.test.ts @@ -80,7 +80,14 @@ describe('Vega manual RUM APIs', () => { [ 'addError', ['message', 'SOURCE', 'stack'], - ['message', 'SOURCE', 'stack', {}, 1234, ''] + [ + 'message', + 'SOURCE', + 'stack', + { '_dd.error.source_type': 'react-native' }, + 1234, + '' + ] ], [ 'startView', @@ -95,7 +102,14 @@ describe('Vega manual RUM APIs', () => { [ 'addError', ['message', 'NETWORK', 'stack', context, 99, 'group'], - ['message', 'NETWORK', 'stack', context, 99, 'group'] + [ + 'message', + 'NETWORK', + 'stack', + { ...context, '_dd.error.source_type': 'react-native' }, + 99, + 'group' + ] ], ['addViewAttributes', [context], [context]], ['removeViewAttribute', ['key'], ['key']], diff --git a/packages/react-native-vega/__tests__/ErrorContext.test.ts b/packages/react-native-vega/__tests__/ErrorContext.test.ts new file mode 100644 index 000000000..30ffa26c3 --- /dev/null +++ b/packages/react-native-vega/__tests__/ErrorContext.test.ts @@ -0,0 +1,98 @@ +/* + * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. + * This product includes software developed at Datadog (https://www.datadoghq.com/). + * Copyright 2016-Present Datadog, Inc. + */ + +import type { ErrorSource } from '@datadog/mobile-react-native'; + +import { DdLogs } from '../src/DdLogsVega'; +import { DdRum } from '../src/DdRumVega'; + +let mockDebugId: string | undefined = 'bundle-debug-id'; +const mockGet = jest.fn(); +const mockRum = { addError: jest.fn() }; +const mockLogs = { log: jest.fn() }; +jest.mock('../../core/src/metro/debugIdResolver', () => ({ + get debugId() { + return mockDebugId; + } +})); +jest.mock('@amazon-devices/keplerscript-turbomodule-api', () => ({ + TurboModuleRegistry: { get: (...args: unknown[]) => mockGet(...args) } +})); + +describe('Vega error symbolication metadata', () => { + beforeEach(() => { + jest.clearAllMocks(); + mockDebugId = 'bundle-debug-id'; + mockGet.mockImplementation(name => + name === 'DdRum' ? mockRum : mockLogs + ); + }); + it('enriches RUM errors without changing application attributes', async () => { + const context = Object.freeze({ + keep: true, + '_dd.error.source_type': 'other', + '_dd.debug_id': 'other' + }); + await DdRum.addError( + 'error', + 'SOURCE' as ErrorSource, + 'stack', + context, + 42 + ); + expect(mockRum.addError).toHaveBeenCalledWith( + 'error', + 'SOURCE', + 'stack', + { + keep: true, + '_dd.error.source_type': 'react-native', + '_dd.debug_id': 'bundle-debug-id' + }, + 42, + '' + ); + expect(context['_dd.debug_id']).toBe('other'); + }); + it.each(['debug', 'info', 'warn', 'error'] as const)( + 'enriches %s error logs', + async level => { + await DdLogs[level]('message', 'TypeError', 'error', 'stack', { + keep: true + }); + expect(mockLogs.log).toHaveBeenCalledWith( + level, + 'message', + 'TypeError', + 'error', + 'stack', + { + keep: true, + '_dd.error.source_type': 'react-native', + '_dd.debug_id': 'bundle-debug-id' + } + ); + } + ); + it('does not turn an ordinary log into an error log', async () => { + await DdLogs.info('message', { keep: true }); + expect(mockLogs.log).toHaveBeenCalledWith( + 'info', + 'message', + '', + '', + '', + { keep: true } + ); + }); + it('keeps errors usable without a bundle Debug ID', async () => { + mockDebugId = undefined; + await DdRum.addError('error', 'SOURCE' as ErrorSource, 'stack'); + expect(mockRum.addError.mock.calls[0][3]).toEqual({ + '_dd.error.source_type': 'react-native' + }); + }); +}); diff --git a/packages/react-native-vega/__tests__/ErrorTracking.test.ts b/packages/react-native-vega/__tests__/ErrorTracking.test.ts new file mode 100644 index 000000000..c054eeb5d --- /dev/null +++ b/packages/react-native-vega/__tests__/ErrorTracking.test.ts @@ -0,0 +1,29 @@ +/* + * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. + * This product includes software developed at Datadog (https://www.datadoghq.com/). + * Copyright 2016-Present Datadog, Inc. + */ + +import { DdRumErrorTracking } from '@datadog/mobile-react-native/internal'; + +import { DdRum } from '../src/DdRumVega'; +import { configureErrorTracking } from '../src/ErrorTracking'; + +it('starts automatic errors only when enabled in RUM settings', () => { + const start = jest + .spyOn(DdRumErrorTracking, 'startTracking') + .mockImplementation(() => undefined); + configureErrorTracking({}); + configureErrorTracking({ rumConfiguration: {} }); + configureErrorTracking({ rumConfiguration: { trackErrors: false } }); + configureErrorTracking({ + trackErrors: true, + rumConfiguration: { trackErrors: false } + }); + expect(start).not.toHaveBeenCalled(); + configureErrorTracking({ rumConfiguration: { trackErrors: true } }); + expect(start).toHaveBeenCalledWith(DdRum); + configureErrorTracking({ trackErrors: true }); + expect(start).toHaveBeenCalledTimes(2); + start.mockRestore(); +}); diff --git a/packages/react-native-vega/__tests__/importSafety.test.ts b/packages/react-native-vega/__tests__/importSafety.test.ts index aa69cd4d9..c565e5e80 100644 --- a/packages/react-native-vega/__tests__/importSafety.test.ts +++ b/packages/react-native-vega/__tests__/importSafety.test.ts @@ -21,6 +21,20 @@ describe('Vega transport import safety', () => { expect(mockGet).not.toHaveBeenCalled(); }); + it('does not look up metadata or install error handlers when importing setup hooks', () => { + const handler = ErrorUtils.getGlobalHandler(); + const consoleHandler = console.error; + jest.isolateModules(() => { + // eslint-disable-next-line global-require, @typescript-eslint/no-var-requires + require('../src/ApplicationMetadata'); + // eslint-disable-next-line global-require, @typescript-eslint/no-var-requires + require('../src/ErrorTracking'); + }); + expect(mockGet).not.toHaveBeenCalled(); + expect(ErrorUtils.getGlobalHandler()).toBe(handler); + expect(console.error).toBe(consoleHandler); + }); + it('resolves the transport module only when requested', () => { const native = { httpResponse: jest.fn() }; mockGet.mockReturnValueOnce(native); diff --git a/packages/react-native-vega/kepler/turbo-modules/CrashReportingConfiguration.cpp b/packages/react-native-vega/kepler/turbo-modules/CrashReportingConfiguration.cpp new file mode 100644 index 000000000..bd438ee29 --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/CrashReportingConfiguration.cpp @@ -0,0 +1,52 @@ +// Unless explicitly stated otherwise all files in this repository are licensed +// under the Apache License Version 2.0. +// +// This product includes software developed at Datadog +// (https://www.datadoghq.com/). Copyright 2016-Present Datadog, Inc. + +#include "CrashReportingConfiguration.h" +#include "DatadogGlobalState.h" +#include "datadog/crash_reporting.hpp" +#include "datadog/uuid.hpp" + +using namespace com::amazon::kepler::turbomodule; + +namespace datadog_rn_vega { +namespace { +std::string stringField(const JSObject &object, const std::string &key) { + const auto it = object.find(key); + if (it == object.end()) + return {}; + const auto value = std::get_if(&it->second); + return value ? *value : std::string(); +} +} // namespace + +void configureApplicationMetadata(datadog::CoreConfig &configuration, + const JSObject &additionalConfiguration) { + configuration.Internal_SetSource("react-native"); + const auto sdkVersion = + stringField(additionalConfiguration, "_dd.sdk_version"); + const auto version = stringField(additionalConfiguration, "_dd.version"); + if (!sdkVersion.empty()) + configuration.Internal_SetSdkVersion(sdkVersion); + if (!version.empty()) + configuration.SetVersion(version); +} + +void configureCrashReporting(const std::shared_ptr &core, + const JSObject &rumConfiguration) { + const auto entry = rumConfiguration.find("nativeCrashReportEnabled"); + const auto enabled = entry == rumConfiguration.end() + ? nullptr + : std::get_if(&entry->second); + const auto applicationId = + datadog::UUID::Parse(stringField(rumConfiguration, "applicationId")); + auto &state = DatadogGlobalState::getInstance(); + if (!core || !enabled || !*enabled || !state.getRum() || !applicationId || + *applicationId == datadog::UUID::Zero || state.getCrashReporting()) + return; + state.setCrashReporting(datadog::CrashReporting::Register(core)); +} + +} // namespace datadog_rn_vega diff --git a/packages/react-native-vega/kepler/turbo-modules/CrashReportingConfiguration.h b/packages/react-native-vega/kepler/turbo-modules/CrashReportingConfiguration.h new file mode 100644 index 000000000..4b72b0ad1 --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/CrashReportingConfiguration.h @@ -0,0 +1,19 @@ +// Unless explicitly stated otherwise all files in this repository are licensed +// under the Apache License Version 2.0. +// +// This product includes software developed at Datadog +// (https://www.datadoghq.com/). Copyright 2016-Present Datadog, Inc. + +#pragma once + +#include "datadog/core.hpp" +#include + +namespace datadog_rn_vega { +void configureCrashReporting( + const std::shared_ptr &core, + const com::amazon::kepler::turbomodule::JSObject &rumConfiguration); +void configureApplicationMetadata( + datadog::CoreConfig &configuration, + const com::amazon::kepler::turbomodule::JSObject &additionalConfiguration); +} // namespace datadog_rn_vega diff --git a/packages/react-native-vega/kepler/turbo-modules/DatadogGlobalState.cpp b/packages/react-native-vega/kepler/turbo-modules/DatadogGlobalState.cpp index d9996a02f..854375f3f 100644 --- a/packages/react-native-vega/kepler/turbo-modules/DatadogGlobalState.cpp +++ b/packages/react-native-vega/kepler/turbo-modules/DatadogGlobalState.cpp @@ -53,8 +53,19 @@ std::shared_ptr DatadogGlobalState::getLogger() { return logger_; } +void DatadogGlobalState::setCrashReporting(std::shared_ptr value) { + std::lock_guard lock(mutex_); + crashReporting_ = std::move(value); +} + +std::shared_ptr DatadogGlobalState::getCrashReporting() { + std::lock_guard lock(mutex_); + return crashReporting_; +} + void DatadogGlobalState::reset() { std::lock_guard lock(mutex_); + crashReporting_.reset(); logger_.reset(); logging_.reset(); rum_.reset(); diff --git a/packages/react-native-vega/kepler/turbo-modules/DatadogGlobalState.h b/packages/react-native-vega/kepler/turbo-modules/DatadogGlobalState.h index dc7554e0c..51c25d061 100644 --- a/packages/react-native-vega/kepler/turbo-modules/DatadogGlobalState.h +++ b/packages/react-native-vega/kepler/turbo-modules/DatadogGlobalState.h @@ -10,6 +10,7 @@ #include #include "datadog/core.hpp" +#include "datadog/crash_reporting.hpp" #include "datadog/rum.hpp" #include "datadog/logging.hpp" @@ -35,6 +36,9 @@ class DatadogGlobalState { void setLogger(std::shared_ptr logger); std::shared_ptr getLogger(); + void setCrashReporting(std::shared_ptr crashReporting); + std::shared_ptr getCrashReporting(); + /** Clears the core and all registered feature pointers. */ void reset(); @@ -45,6 +49,7 @@ class DatadogGlobalState { std::mutex mutex_; std::shared_ptr core_; + std::shared_ptr crashReporting_; std::shared_ptr rum_; std::shared_ptr logging_; std::shared_ptr logger_; diff --git a/packages/react-native-vega/src/ApplicationMetadata.ts b/packages/react-native-vega/src/ApplicationMetadata.ts new file mode 100644 index 000000000..ce13ac069 --- /dev/null +++ b/packages/react-native-vega/src/ApplicationMetadata.ts @@ -0,0 +1,66 @@ +/* + * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. + * This product includes software developed at Datadog (https://www.datadoghq.com/). + * Copyright 2016-Present Datadog, Inc. + */ + +import type { KeplerTurboModule } from '@amazon-devices/keplerscript-turbomodule-api'; +import { TurboModuleRegistry } from '@amazon-devices/keplerscript-turbomodule-api'; +import { version as sdkVersion } from '@datadog/mobile-react-native/internal'; + +interface DeviceInfo extends KeplerTurboModule { + getConstants(): { bundleId?: unknown; appVersion?: unknown }; +} + +type MetadataConfiguration = { + service?: string; + version?: string; + versionSuffix?: string; + additionalConfiguration?: Record; +}; +const nonBlank = (value: unknown): string | undefined => + typeof value === 'string' && value.trim() ? value.trim() : undefined; +const platformValue = (value: unknown): string | undefined => { + const text = nonBlank(value); + return text?.toLowerCase() === 'unknown' ? undefined : text; +}; + +/** Reads existing platform constants on use, with no device-info npm dependency. */ +export const buildApplicationMetadata = ( + configuration: T +) => { + let service = nonBlank(configuration.service); + let version = nonBlank(configuration.version); + if (!service || !version) { + try { + const constants = TurboModuleRegistry.get( + 'DeviceInfoModule' + )?.getConstants(); + service ??= platformValue(constants?.bundleId); + version ??= platformValue(constants?.appVersion); + } catch { + // Missing platform metadata must not prevent SDK setup. + } + } + const additionalConfiguration = { + ...configuration.additionalConfiguration, + '_dd.source': 'react-native', + '_dd.sdk_version': sdkVersion + } as Record; + delete additionalConfiguration['_dd.version']; + delete additionalConfiguration['_dd.version_suffix']; + const suffix = nonBlank(configuration.versionSuffix); + if (version) { + additionalConfiguration['_dd.version'] = `${version}${ + suffix ? `-${suffix}` : '' + }`; + } else if (suffix) { + additionalConfiguration['_dd.version_suffix'] = `-${suffix}`; + } + return { + ...configuration, + service: service ?? 'vega', + version, + additionalConfiguration + }; +}; diff --git a/packages/react-native-vega/src/DdLogsVega.ts b/packages/react-native-vega/src/DdLogsVega.ts index 7fd26c790..98a53a329 100644 --- a/packages/react-native-vega/src/DdLogsVega.ts +++ b/packages/react-native-vega/src/DdLogsVega.ts @@ -6,6 +6,7 @@ import type { ErrorSource } from '@datadog/mobile-react-native'; +import { errorContext } from './ErrorContext'; import { callNative } from './callNative'; import { getNativeDdLogs } from './turbo-modules/NativeDdLogs'; @@ -54,7 +55,7 @@ class DdLogsVega { ); } const errorArgs = args as LogWithErrorArguments; - const context = { ...errorArgs[4] }; + const context = errorContext(errorArgs[4] ?? {}); if (errorArgs[5]) { Object.assign(context, { '_dd.error.fingerprint': errorArgs[5] diff --git a/packages/react-native-vega/src/DdRumVega.ts b/packages/react-native-vega/src/DdRumVega.ts index 9f99da405..251dfd83d 100644 --- a/packages/react-native-vega/src/DdRumVega.ts +++ b/packages/react-native-vega/src/DdRumVega.ts @@ -9,6 +9,7 @@ import type { FeatureOperationFailure } from '@datadog/mobile-react-native'; +import { errorContext } from './ErrorContext'; import { callNative } from './callNative'; import { getNativeDdRum } from './turbo-modules/NativeDdRum'; import type { DdRum as NativeDdRum } from './turbo-modules/NativeDdRum'; @@ -115,7 +116,7 @@ class DdRumVega { message, source, stacktrace, - context, + errorContext(context), timestampMs, fingerprint ) diff --git a/packages/react-native-vega/src/ErrorContext.ts b/packages/react-native-vega/src/ErrorContext.ts new file mode 100644 index 000000000..882305853 --- /dev/null +++ b/packages/react-native-vega/src/ErrorContext.ts @@ -0,0 +1,15 @@ +/* + * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. + * This product includes software developed at Datadog (https://www.datadoghq.com/). + * Copyright 2016-Present Datadog, Inc. + */ + +import { DdAttributes, debugId } from '@datadog/mobile-react-native/internal'; + +export const errorContext = (context: object): Record => ({ + ...context, + [DdAttributes.errorSourceType]: 'react-native', + ...(typeof debugId === 'string' && debugId + ? { [DdAttributes.debugId]: debugId } + : {}) +}); diff --git a/packages/react-native-vega/src/ErrorTracking.ts b/packages/react-native-vega/src/ErrorTracking.ts new file mode 100644 index 000000000..8dfa4ddde --- /dev/null +++ b/packages/react-native-vega/src/ErrorTracking.ts @@ -0,0 +1,23 @@ +/* + * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. + * This product includes software developed at Datadog (https://www.datadoghq.com/). + * Copyright 2016-Present Datadog, Inc. + */ + +import { DdRumErrorTracking } from '@datadog/mobile-react-native/internal'; + +import { DdRum } from './DdRumVega'; + +/** Called by SDK setup after configuring RUM. Defaults match core's trackErrors=false. */ +export const configureErrorTracking = (configuration: { + rumConfiguration?: { trackErrors?: boolean }; + trackErrors?: boolean; +}): void => { + const enabled = + configuration.rumConfiguration?.trackErrors ?? + configuration.trackErrors ?? + false; + if (enabled) { + DdRumErrorTracking.startTracking(DdRum); + } +}; diff --git a/packages/react-native-vega/tests/CMakeLists.txt b/packages/react-native-vega/tests/CMakeLists.txt index ecd97c6fa..74aa31c40 100644 --- a/packages/react-native-vega/tests/CMakeLists.txt +++ b/packages/react-native-vega/tests/CMakeLists.txt @@ -43,15 +43,16 @@ if(DATADOG_CPP_SOURCE_DIR AND KEPLER_INCLUDE_DIR AND NODE_API_INCLUDE_DIR) add_test(NAME AttributeConverter COMMAND AttributeConverterTest) endif() -# Exercise logger registration against the actual pinned SDK, including its -# compatibility patch. Opt in because this builds the complete SDK on the host. +# Exercise feature registration against the actual pinned SDK. Opt in because +# this builds the complete SDK on the host. option(VEGA_TEST_LOGGING_CONFIGURATION "Build real SDK logging registration tests" OFF) -if(VEGA_TEST_LOGGING_CONFIGURATION) +option(VEGA_TEST_CRASH_CONFIGURATION "Build real SDK crash registration tests" OFF) +if(VEGA_TEST_LOGGING_CONFIGURATION OR VEGA_TEST_CRASH_CONFIGURATION) if(NOT DATADOG_CPP_SOURCE_DIR OR NOT KEPLER_INCLUDE_DIR OR NOT NODE_API_INCLUDE_DIR) - message(FATAL_ERROR "Logging configuration tests require the SDK and Kepler/Node include paths") + message(FATAL_ERROR "Feature configuration tests require the SDK and Kepler/Node include paths") endif() set(DD_BUILD_SHARED OFF CACHE BOOL "" FORCE) - set(DD_CRASH_MODE "noop" CACHE STRING "" FORCE) + set(DD_CRASH_MODE "inprocess" CACHE STRING "" FORCE) set(DD_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) set(DD_BUILD_TESTING OFF CACHE BOOL "" FORCE) set(DD_BUILD_TOOLS OFF CACHE BOOL "" FORCE) @@ -60,18 +61,36 @@ if(VEGA_TEST_LOGGING_CONFIGURATION) add_subdirectory("${DATADOG_CPP_SOURCE_DIR}" datadog) include(../cmake/DatadogLoggingCompatibility.cmake) datadog_vega_patch_logging_registration("${DATADOG_CPP_SOURCE_DIR}") - add_executable(LoggingConfigurationTest - LoggingConfigurationTest.cpp - ../kepler/turbo-modules/LoggingConfiguration.cpp - ../kepler/turbo-modules/DatadogGlobalState.cpp) - target_compile_features(LoggingConfigurationTest PRIVATE cxx_std_17) - target_compile_definitions(LoggingConfigurationTest PRIVATE NDEBUG) - target_include_directories(LoggingConfigurationTest PRIVATE - ../kepler/turbo-modules - ${KEPLER_INCLUDE_DIR} - ${KEPLER_INCLUDE_DIR}/Kepler/turbomodule - ${NODE_API_INCLUDE_DIR}) - target_link_libraries(LoggingConfigurationTest PRIVATE Datadog::sdk) - add_test(NAME LoggingConfiguration COMMAND LoggingConfigurationTest "${CMAKE_CURRENT_BINARY_DIR}/logging-test-data") - set_tests_properties(LoggingConfiguration PROPERTIES TIMEOUT 10) + if(VEGA_TEST_LOGGING_CONFIGURATION) + add_executable(LoggingConfigurationTest + LoggingConfigurationTest.cpp + ../kepler/turbo-modules/LoggingConfiguration.cpp + ../kepler/turbo-modules/DatadogGlobalState.cpp) + target_compile_features(LoggingConfigurationTest PRIVATE cxx_std_17) + target_compile_definitions(LoggingConfigurationTest PRIVATE NDEBUG) + target_include_directories(LoggingConfigurationTest PRIVATE + ../kepler/turbo-modules + ${KEPLER_INCLUDE_DIR} + ${KEPLER_INCLUDE_DIR}/Kepler/turbomodule + ${NODE_API_INCLUDE_DIR}) + target_link_libraries(LoggingConfigurationTest PRIVATE Datadog::sdk) + add_test(NAME LoggingConfiguration COMMAND LoggingConfigurationTest "${CMAKE_CURRENT_BINARY_DIR}/logging-test-data") + set_tests_properties(LoggingConfiguration PROPERTIES TIMEOUT 10) + endif() + if(VEGA_TEST_CRASH_CONFIGURATION) + add_executable(CrashReportingConfigurationTest + CrashReportingConfigurationTest.cpp + ../kepler/turbo-modules/CrashReportingConfiguration.cpp + ../kepler/turbo-modules/DatadogGlobalState.cpp) + target_compile_features(CrashReportingConfigurationTest PRIVATE cxx_std_17) + target_compile_definitions(CrashReportingConfigurationTest PRIVATE NDEBUG) + target_include_directories(CrashReportingConfigurationTest PRIVATE + ../kepler/turbo-modules + ${KEPLER_INCLUDE_DIR} + ${KEPLER_INCLUDE_DIR}/Kepler/turbomodule + ${NODE_API_INCLUDE_DIR}) + target_link_libraries(CrashReportingConfigurationTest PRIVATE Datadog::sdk) + add_test(NAME CrashReportingConfiguration COMMAND CrashReportingConfigurationTest "${CMAKE_CURRENT_BINARY_DIR}/crash-test-data") + set_tests_properties(CrashReportingConfiguration PROPERTIES TIMEOUT 10) + endif() endif() diff --git a/packages/react-native-vega/tests/CrashReportingConfigurationTest.cpp b/packages/react-native-vega/tests/CrashReportingConfigurationTest.cpp new file mode 100644 index 000000000..eaf041b9a --- /dev/null +++ b/packages/react-native-vega/tests/CrashReportingConfigurationTest.cpp @@ -0,0 +1,80 @@ +// Unless explicitly stated otherwise all files in this repository are licensed +// under the Apache License Version 2.0. +// +// This product includes software developed at Datadog +// (https://www.datadoghq.com/). Copyright 2016-Present Datadog, Inc. + +#include "CrashReportingConfiguration.h" +#include "DatadogGlobalState.h" +#include "datadog/uuid.hpp" + +#include +#include +#include +#include + +using namespace datadog_rn_vega; +using namespace com::amazon::kepler::turbomodule; + +void check(bool condition, const char *message) { + if (!condition) { + std::cerr << message << std::endl; + std::exit(1); + } +} + +int main(int argc, char **argv) { + check(argc == 2, "test storage directory required"); + std::filesystem::create_directories(argv[1]); + datadog::CoreConfig config("test-token", "example.app", "test"); + config.SetApplicationStoragePath(argv[1]); + configureApplicationMetadata(config, + {{"_dd.version", std::string("2.1-beta")}, + {"_dd.sdk_version", std::string("3.13.0")}}); + auto core = + datadog::Core::Create(config, datadog::TrackingConsent::Pending); + auto &state = DatadogGlobalState::getInstance(); + const auto id = datadog::UUID::Random().ToString(); + JSObject enabled{{"applicationId", id}, {"nativeCrashReportEnabled", true}}; + struct sigaction original { + }, current{}; + check(sigaction(SIGSEGV, nullptr, &original) == 0, + "cannot read signal disposition"); + configureCrashReporting(core, enabled); + check(!state.getCrashReporting(), "registered crashes without RUM"); + state.setRum(datadog::Rum::Register(core, datadog::RumConfig(id))); + for (const auto &settings : + {JSObject{}, JSObject{{"applicationId", id}}, + JSObject{{"applicationId", id}, {"nativeCrashReportEnabled", false}}, + JSObject{{"applicationId", id}, + {"nativeCrashReportEnabled", std::string("true")}}, + JSObject{{"applicationId", std::string("invalid")}, + {"nativeCrashReportEnabled", true}}, + JSObject{{"applicationId", datadog::UUID::Zero.ToString()}, + {"nativeCrashReportEnabled", true}}}) { + configureCrashReporting(core, settings); + check(!state.getCrashReporting(), + "disabled or invalid RUM settings registered crashes"); + check(sigaction(SIGSEGV, nullptr, ¤t) == 0, + "cannot read signal disposition"); + check(current.sa_sigaction == original.sa_sigaction, + "disabled setting installed a signal handler"); + } + configureCrashReporting(nullptr, enabled); + check(!state.getCrashReporting(), "null core registered crashes"); + configureCrashReporting(core, enabled); + auto crashReporting = state.getCrashReporting(); + check(bool(crashReporting), "enabled setting did not register crashes"); + check(sigaction(SIGSEGV, nullptr, ¤t) == 0, + "cannot read signal disposition"); + check(current.sa_sigaction != original.sa_sigaction, + "in-process crash handler was not installed"); + configureCrashReporting(core, enabled); + check(state.getCrashReporting() == crashReporting, + "repeated configuration replaced the crash feature"); + check(core->Start(), "configured core did not start"); + core->Stop(); + state.reset(); + check(!state.getCrashReporting(), "reset retained the crash interface"); + std::cout << "Native crash configuration tests passed" << std::endl; +} From df00f6d50982a207167a62e91b4e1096829da138 Mon Sep 17 00:00:00 2001 From: "carlos.nogueira" Date: Thu, 26 Nov 2026 10:51:47 +0000 Subject: [PATCH 2/2] [RUM-20338] Preserve fatal error reporting order --- .../DdRumErrorTracking.test.tsx | 93 ++++++++++++++++--- .../instrumentation/DdRumErrorTracking.tsx | 59 ++++++------ packages/react-native-vega/README.md | 6 +- 3 files changed, 114 insertions(+), 44 deletions(-) diff --git a/packages/core/src/__tests__/rum/instrumentation/DdRumErrorTracking.test.tsx b/packages/core/src/__tests__/rum/instrumentation/DdRumErrorTracking.test.tsx index 05effa321..9de427ac7 100644 --- a/packages/core/src/__tests__/rum/instrumentation/DdRumErrorTracking.test.tsx +++ b/packages/core/src/__tests__/rum/instrumentation/DdRumErrorTracking.test.tsx @@ -9,6 +9,7 @@ import { NativeModules } from 'react-native'; import type { DdNativeRumType } from '../../../nativeModulesTypes'; import { DdRumErrorTracking } from '../../../rum/instrumentation/DdRumErrorTracking'; import { BufferSingleton } from '../../../sdk/DatadogProvider/Buffer/BufferSingleton'; +import * as jsUtils from '../../../utils/jsUtils'; jest.mock('../../../utils/jsUtils'); @@ -33,6 +34,7 @@ beforeEach(() => { jest.clearAllMocks(); BufferSingleton.onInitialization(); baseErrorHandlerCalled = false; + baseConsoleErrorCalled = false; originalErrorHandler = ErrorUtils.getGlobalHandler(); ErrorUtils.setGlobalHandler(baseErrorHandler); originalConsoleError = console.error; @@ -715,20 +717,6 @@ it.each(['throw', 'reject'] as const)( } ); -it('M bound reporting W injected reporter never resolves', async () => { - jest.useFakeTimers(); - try { - DdRumErrorTracking.startTracking({ - addError: () => new Promise(() => undefined) - }); - DdRumErrorTracking.onGlobalError(Error('app error'), true); - await jest.advanceTimersByTimeAsync(50); - expect(baseErrorHandlerCalled).toBe(true); - } finally { - jest.useRealTimers(); - } -}); - it('M replace reporter W tracking already started without wrapping handlers twice', async () => { const first = { addError: jest.fn(() => Promise.resolve()) }; const second = { addError: jest.fn(() => Promise.resolve()) }; @@ -774,3 +762,80 @@ it('M chain previous handlers W error properties throw during encoding', async ( expect(baseErrorHandlerCalled).toBe(true); expect(baseConsoleErrorCalled).toBe(true); }); + +describe('error-handler timing with the real crash delay', () => { + beforeEach(() => { + jest.useFakeTimers(); + jest.spyOn(jsUtils, 'executeWithDelay').mockImplementation( + jest.requireActual('../../../utils/jsUtils').executeWithDelay + ); + }); + afterEach(() => { + jest.restoreAllMocks(); + jest.useRealTimers(); + }); + + it.each(['resolve', 'reject'] as const)( + 'waits for fatal reporting to %s before starting the crash delay', + async outcome => { + let settle!: () => void; + const pending = new Promise((resolve, reject) => { + settle = + outcome === 'resolve' + ? resolve + : () => reject(Error('native')); + }); + const reporter = { + addError: jest.fn().mockResolvedValue(undefined) + }; + reporter.addError.mockReturnValueOnce(pending); + DdRumErrorTracking.startTracking(reporter); + DdRumErrorTracking.onGlobalError(Error('fatal'), true); + + await jest.advanceTimersByTimeAsync(250); + expect(baseErrorHandlerCalled).toBe(false); + console.error('while native reporting is pending'); + await jest.advanceTimersByTimeAsync(0); + expect(baseConsoleErrorCalled).toBe(true); + + baseConsoleErrorCalled = false; + settle(); + await jest.advanceTimersByTimeAsync(49); + expect(baseErrorHandlerCalled).toBe(false); + console.error('during the crash-context delay'); + await jest.advanceTimersByTimeAsync(0); + expect(baseConsoleErrorCalled).toBe(true); + await jest.advanceTimersByTimeAsync(1); + expect(baseErrorHandlerCalled).toBe(true); + expect(reporter.addError).toHaveBeenCalledTimes(3); + expect(jest.getTimerCount()).toBe(0); + } + ); + + it.each([false, undefined])( + 'bounds a stalled non-fatal report and preserves the crash delay: %p', + async isFatal => { + DdRumErrorTracking.startTracking({ + addError: () => new Promise(() => undefined) + }); + DdRumErrorTracking.onGlobalError(Error('non-fatal'), isFatal); + await jest.advanceTimersByTimeAsync(99); + expect(baseErrorHandlerCalled).toBe(false); + await jest.advanceTimersByTimeAsync(1); + expect(baseErrorHandlerCalled).toBe(true); + expect(jest.getTimerCount()).toBe(0); + } + ); + + it('forwards console errors when SDK reporting never resolves', async () => { + DdRumErrorTracking.startTracking({ + addError: () => new Promise(() => undefined) + }); + console.error('console error'); + await jest.advanceTimersByTimeAsync(49); + expect(baseConsoleErrorCalled).toBe(false); + await jest.advanceTimersByTimeAsync(1); + expect(baseConsoleErrorCalled).toBe(true); + expect(jest.getTimerCount()).toBe(0); + }); +}); diff --git a/packages/core/src/rum/instrumentation/DdRumErrorTracking.tsx b/packages/core/src/rum/instrumentation/DdRumErrorTracking.tsx index 3c567f2dd..1fe1b3d59 100644 --- a/packages/core/src/rum/instrumentation/DdRumErrorTracking.tsx +++ b/packages/core/src/rum/instrumentation/DdRumErrorTracking.tsx @@ -73,32 +73,29 @@ export class DdRumErrorTracking { } static onGlobalError = (error: any, isFatal?: boolean): void => { - this.reportSafely(() => - this.reportError( - getErrorMessage(error), - ErrorSource.SOURCE, - getErrorStackTrace(error), - { - '_dd.error.is_crash': isFatal, - '_dd.error.raw': errorEncoder.encode(error) + this.reportSafely( + () => + this.reportError( + getErrorMessage(error), + ErrorSource.SOURCE, + getErrorStackTrace(error), + { + '_dd.error.is_crash': isFatal, + '_dd.error.raw': errorEncoder.encode(error) + } + ), + isFatal + ).then(() => + // The native update must settle before this crash-context delay. + executeWithDelay(() => { + DdRumErrorTracking.isInDefaultErrorHandler = true; + try { + DdRumErrorTracking.defaultErrorHandler(error, isFatal); + } finally { + DdRumErrorTracking.isInDefaultErrorHandler = false; } - ) - ).then(async () => { - DdRumErrorTracking.isInDefaultErrorHandler = true; - try { - // On real iOS devices, the crash context is not updated soon - // enough for the view update to contain the crash. - // Waiting for 50ms has low impact and ensures the crash context - // is updated before actually crashing the app. - await executeWithDelay( - () => - DdRumErrorTracking.defaultErrorHandler(error, isFatal), - 50 - ); - } finally { - DdRumErrorTracking.isInDefaultErrorHandler = false; - } - }); + }, 50) + ); }; static onConsoleError = (...params: unknown[]): void => { @@ -149,14 +146,20 @@ export class DdRumErrorTracking { return this.reportError(message, ErrorSource.CONSOLE, stack); }; - /** A failed or stalled SDK reporter must not suppress the previous handler. */ + /** Fatal errors wait for the native update; other reporting has a stall cap. */ private static reportSafely = async ( - report: () => Promise + report: () => Promise, + waitForCompletion = false ): Promise => { let timeout: ReturnType | undefined; try { + const pending = Promise.resolve(report()).catch(() => undefined); + if (waitForCompletion) { + await pending; + return; + } await Promise.race([ - Promise.resolve(report()).catch(() => undefined), + pending, new Promise(resolve => { timeout = setTimeout(resolve, 50); }) diff --git a/packages/react-native-vega/README.md b/packages/react-native-vega/README.md index 1ef9b8766..bd9ab2b68 100644 --- a/packages/react-native-vega/README.md +++ b/packages/react-native-vega/README.md @@ -134,8 +134,10 @@ The initializer added in RUM-20335 must use these configuration hooks: and before `Core::Start`, alongside the logging configuration hook. - `configureErrorTracking(configuration)` enables shared JavaScript error tracking with the Vega RUM reporter when `rumConfiguration.trackErrors` is `true`. - Importing the package does not install handlers. SDK reporting failures do not - prevent the app's existing error and console handlers from running. + Importing the package does not install handlers. Fatal errors wait for native + reporting to settle before the crash-context delay and the app's error handler. + Non-fatal and console reporting have a timeout. Reporting failures still reach + the app's existing handlers. These hooks keep initialization and provider setup in RUM-20335. Host native coverage can be enabled with `VEGA_TEST_CRASH_CONFIGURATION=ON`, using the SDK