Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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');

Expand All @@ -33,6 +34,7 @@ beforeEach(() => {
jest.clearAllMocks();
BufferSingleton.onInitialization();
baseErrorHandlerCalled = false;
baseConsoleErrorCalled = false;
originalErrorHandler = ErrorUtils.getGlobalHandler();
ErrorUtils.setGlobalHandler(baseErrorHandler);
originalConsoleError = console.error;
Expand Down Expand Up @@ -692,3 +694,148 @@ 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 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);
});

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<void>((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);
});
});
4 changes: 4 additions & 0 deletions packages/core/src/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
96 changes: 69 additions & 27 deletions packages/core/src/rum/instrumentation/DdRumErrorTracking.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,16 @@ import { ErrorSource } from '../../types';
import { executeWithDelay } from '../../utils/jsUtils';
import { DdRum } from '../DdRum';

type RumErrorReporter = Pick<typeof DdRum, 'addError'>;

/**
* 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
Expand All @@ -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(
Expand All @@ -47,7 +52,7 @@ export class DdRumErrorTracking {
return;
}

if (ErrorUtils) {
if (typeof ErrorUtils !== 'undefined') {
DdRumErrorTracking.defaultErrorHandler = ErrorUtils.getGlobalHandler();
DdRumErrorTracking.defaultConsoleError = console.error;

Expand All @@ -68,34 +73,43 @@ 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 () => {
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;
}
});
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;
}
}, 50)
);
};

static onConsoleError = (...params: unknown[]): void => {
if (DdRumErrorTracking.isInDefaultErrorHandler) {
return;
}
this.reportSafely(() => this.reportConsoleError(...params)).then(() => {
DdRumErrorTracking.defaultConsoleError.apply(console, params);
});
};

private static reportConsoleError = (
...params: unknown[]
): Promise<void> => {
let stack: string = ERROR_EMPTY_STACKTRACE;
let errorName: string = ERROR_DEFAULT_NAME;
for (let i = 0; i < params.length; i += 1) {
Expand Down Expand Up @@ -129,9 +143,32 @@ export class DdRumErrorTracking {
})
.join(' ');

this.reportError(message, ErrorSource.CONSOLE, stack).then(() => {
DdRumErrorTracking.defaultConsoleError.apply(console, params);
});
return this.reportError(message, ErrorSource.CONSOLE, stack);
};

/** Fatal errors wait for the native update; other reporting has a stall cap. */
private static reportSafely = async (
report: () => Promise<void>,
waitForCompletion = false
): Promise<void> => {
let timeout: ReturnType<typeof setTimeout> | undefined;
try {
const pending = Promise.resolve(report()).catch(() => undefined);
if (waitForCompletion) {
await pending;
return;
}
await Promise.race([
pending,
new Promise<void>(resolve => {
timeout = setTimeout(resolve, 50);
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
})
]);
} catch {
// A reporter can throw before returning a promise.
} finally {
clearTimeout(timeout);
}
};

private static reportError = (
Expand All @@ -140,6 +177,11 @@ export class DdRumErrorTracking {
stacktrace: string,
context: object = {}
): Promise<void> => {
return DdRum.addError(message, source, stacktrace, context);
return (DdRumErrorTracking.reporter ?? DdRum).addError(
message,
source,
stacktrace,
context
);
};
}
4 changes: 3 additions & 1 deletion packages/react-native-vega/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand All @@ -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
Expand Down
35 changes: 35 additions & 0 deletions packages/react-native-vega/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,38 @@ 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. 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
and include paths described above. It verifies signal-handler registration
without intentionally crashing the test process.
Loading