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
2 changes: 2 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
node_modules
example
example-new-architecture
example-vega
packages/react-native-vega/build
benchmarks
dist
lib
Expand Down
11 changes: 11 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,17 @@ buck-out/

# bob build files
lib/
dist/
buildinfo.json
CMakeUserPresets.json
**/CMakeCache.txt
**/CMakeFiles/
**/compile_commands.json
**/.cmake/
**/.cxx/

# Vega example app
/example-vega/

# fastlane
#
Expand Down
2 changes: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ The SDK runs inside thousands of customer apps, on top of the native iOS and And

This is a monorepo built with yarn 3 workspaces and lerna. All packages share one version, set in `lerna.json`.

While private, `@datadog/mobile-react-native-vega` uses the shared base version with a `-beta` suffix. `update-version.sh` maintains that suffix and keeps its core peer dependency aligned. Remove this exception when preparing Vega for public release.

| Path | npm package | What it is |
|---|---|---|
| `packages/core` | `@datadog/mobile-react-native` | The SDK: RUM, Logs, Trace, Flags, `DatadogProvider`, the Metro plugin, and the iOS/Android bridges |
Expand Down
7 changes: 7 additions & 0 deletions packages/core/internal/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/*
* 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.
*/

export * from '../lib/typescript/internal';
9 changes: 9 additions & 0 deletions packages/core/internal/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/*
* 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.
*/

// Keep this folder without a package.json so exports-aware Metro uses the
// parent package's exports map. Legacy Metro follows this source entry instead.
export * from '../src/internal';
6 changes: 0 additions & 6 deletions packages/core/internal/package.json

This file was deleted.

1 change: 1 addition & 0 deletions packages/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"main": "lib/commonjs/index",
"files": [
"src/**",
"internal",
"lib/**",
"scripts/**",
"android/build.gradle",
Expand Down
46 changes: 34 additions & 12 deletions packages/core/src/__tests__/wrapperImportSafety.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,23 +73,45 @@ describe('SDK wrappers are import-safe', () => {
it('importing the internal entry performs no native lookup', () => {
expect(requireCountingLookups('../internal').lookups).toEqual([]);
});

it('importing the legacy internal entry performs no native lookup', () => {
expect(requireCountingLookups('../../internal').lookups).toEqual([]);
});

it('the legacy internal entry shares resource tracking state with core', () => {
jest.isolateModules(() => {
// eslint-disable-next-line global-require, @typescript-eslint/no-var-requires
const { callWithoutResourceTracking } = require('../../internal');
const { isResourceTrackingDisabled } = jest.requireActual(
'../rum/instrumentation/resourceTracking/requestProxy/common/FetchProxyState'
);

expect(isResourceTrackingDisabled()).toBe(false);
callWithoutResourceTracking(() => {
expect(isResourceTrackingDisabled()).toBe(true);
});
expect(isResourceTrackingDisabled()).toBe(false);
});
});
});

describe('SDK wrappers do not rely on Proxy', () => {
// Older Android JSC and Hermes versions supported by the SDK lack Proxy.
it.each(['../sdk/DdSdkInternal', '../index', '../internal'])(
'importing %s works without Proxy',
modulePath => {
const g = globalThis as Record<string, unknown>;
const originalProxy = g.Proxy;
try {
delete g.Proxy;
expect(() => requireCountingLookups(modulePath)).not.toThrow();
} finally {
g.Proxy = originalProxy;
}
it.each([
'../sdk/DdSdkInternal',
'../index',
'../internal',
'../../internal'
])('importing %s works without Proxy', modulePath => {
const g = globalThis as Record<string, unknown>;
const originalProxy = g.Proxy;
try {
delete g.Proxy;
expect(() => requireCountingLookups(modulePath)).not.toThrow();
} finally {
g.Proxy = originalProxy;
}
);
});

it('DdSdkWrapper forwards every method to the native module', () => {
jest.isolateModules(() => {
Expand Down
3 changes: 3 additions & 0 deletions packages/core/src/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ export { buildConfigurationFromPartialConfiguration } from './config/async/async
export { DdSdkNativeConfiguration } from './config/features/CoreConfigurationNative';
export { RUM_DEFAULTS } from './config/features/RumConfiguration';
export { adaptLongTaskThreshold } from './utils/longTasksUtils';
export { getGlobalInstance } from './utils/singletonUtils';
export { version } from './version';
export { AccountInfoSingleton } from './sdk/AccountInfoSingleton/AccountInfoSingleton';
export { AttributesSingleton } from './sdk/AttributesSingleton/AttributesSingleton';
Expand All @@ -30,3 +31,5 @@ export type { LogsNativeConfiguration } from './config/features/LogsConfiguratio
export type { RumNativeConfiguration } from './config/features/RumConfigurationNative';
export type { TraceNativeConfiguration } from './config/features/TraceConfigurationNative';
export type { InitializationModeForTelemetry } from './config/types/InitializationModeForTelemetry';

export { callWithoutResourceTracking } from './rum/instrumentation/resourceTracking/requestProxy/common/FetchProxyState';
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@ import { InternalLog } from '../../../../../InternalLog';
import { SdkVerbosity } from '../../../../../config/types';
import { extractGraphQLErrors } from '../../graphql/graphqlUtils';
import { getErrorData } from '../XHRProxy/xhrUtils';
import { callOriginalFetch } from '../common/FetchProxyState';
import {
callOriginalFetch,
isResourceTrackingDisabled
} from '../common/FetchProxyState';
import type { RequestContext } from '../common/RequestContext';
import { createRequestContext, getResourceKey } from '../common/RequestContext';
import { ResourceReporter } from '../common/ResourceReporter';
Expand Down Expand Up @@ -64,6 +67,11 @@ export class FetchProxy extends RequestProxy {
this.originalFetch = originalFetch;

const installedFetch: typeof fetch = (input, init) => {
if (isResourceTrackingDisabled()) {
return callOriginalFetch(() =>
originalFetch.call(this.providers.fetchGlobal, input, init)
);
}
return trackFetch({
input,
init,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
DATADOG_GRAPH_QL_OPERATION_TYPE_HEADER
} from '../../../graphql/graphqlHeaders';
import { compileHeaderCaptureConfig } from '../../../headerCapture/compileHeaderConfig';
import { callWithoutResourceTracking } from '../../common/FetchProxyState';
import type { ResourceReporter } from '../../common/ResourceReporter';
import type { RUMResource } from '../../interfaces/RumResource';
import { FetchProxy } from '../FetchProxy';
Expand Down Expand Up @@ -111,6 +112,29 @@ const createProxy = ({
};

describe('FetchProxy', () => {
it('restores tracking after an excluded request throws synchronously', async () => {
const response = createResponse();
const originalFetch = jest
.fn()
.mockImplementationOnce(() => {
throw new Error('network unavailable');
})
.mockResolvedValue(response);
const reportResource = jest.fn();
const { fetchGlobal, proxy } = createProxy({
originalFetch,
reportResource
});
proxy.onTrackingStart(getOptions());
expect(() =>
callWithoutResourceTracking(() =>
fetchGlobal.fetch('https://api.example.com/upload')
)
).toThrow('network unavailable');
await fetchGlobal.fetch('https://api.example.com/upload');
expect(reportResource).toHaveBeenCalledTimes(1);
});

it('reports a successful Fetch resource without replacing the response', async () => {
const response = createResponse({
status: 201,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ import {
DATADOG_GRAPH_QL_VARIABLES_HEADER
} from '../../../graphql/graphqlHeaders';
import { compileHeaderCaptureConfig } from '../../../headerCapture/compileHeaderConfig';
import { callWithoutResourceTracking } from '../../common/FetchProxyState';
import { ResourceReporter } from '../../common/ResourceReporter';
import { XHRProxy } from '../XHRProxy';
import {
Expand Down Expand Up @@ -145,6 +146,32 @@ afterEach(() => {
});

describe('XHRProxy', () => {
it('excludes an SDK upload through XHR-backed fetch and still tracks app requests', async () => {
xhrProxy.onTrackingStart({
tracingSamplingRate: 100,
firstPartyHostsRegexMap: []
});
const url = 'https://proxy.example.com/upload';
const sdkXhr = new XMLHttpRequestMock();
callWithoutResourceTracking(() => {
sdkXhr.open('POST', url);
sdkXhr.send();
});
sdkXhr.notifyResponseArrived();
sdkXhr.complete(202, 'ok');
await flushPromises();
expect(DdNativeRum.startResource).not.toHaveBeenCalled();
expect(DdNativeRum.stopResource).not.toHaveBeenCalled();
const appXhr = new XMLHttpRequestMock();
appXhr.open('POST', url);
appXhr.send();
appXhr.notifyResponseArrived();
appXhr.complete(200, 'ok');
await flushPromises();
expect(DdNativeRum.startResource).toHaveBeenCalledTimes(1);
expect(DdNativeRum.stopResource).toHaveBeenCalledTimes(1);
});

describe('resource interception', () => {
it('intercepts XHR request when startTracking() + XHR.open() + XHR.send()', async () => {
// GIVEN
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,40 @@
* Copyright 2016-Present Datadog, Inc.
*/

let fetchProxyCallDepth = 0;
import { getGlobalInstance } from '../../../../../utils/singletonUtils';

const state = getGlobalInstance(
'com.datadog.reactnative.rum.resource_tracking.fetch_proxy_state',
() => ({ fetchProxyCallDepth: 0, resourceTrackingDisabledDepth: 0 })
);

/**
* Calls the original Fetch implementation while marking its synchronous work.
* XHR-backed Fetch implementations create and send their XMLHttpRequest before
* returning a Promise, so the XHR proxy can avoid reporting that request twice.
*/
export const callOriginalFetch = <T>(callback: () => T): T => {
fetchProxyCallDepth += 1;
state.fetchProxyCallDepth += 1;
try {
return callback();
} finally {
fetchProxyCallDepth -= 1;
state.fetchProxyCallDepth -= 1;
}
};

export const isRunningWithinFetchProxy = (): boolean => {
return fetchProxyCallDepth > 0;
return state.fetchProxyCallDepth > 0;
};

/** Excludes only the requests started synchronously by this callback. */
export const callWithoutResourceTracking = <T>(callback: () => T): T => {
state.resourceTrackingDisabledDepth += 1;
try {
return callOriginalFetch(callback);
} finally {
state.resourceTrackingDisabledDepth -= 1;
}
};

export const isResourceTrackingDisabled = (): boolean =>
state.resourceTrackingDisabledDepth > 0;
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* 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.
*/

type TrackingStateModule = typeof import('../FetchProxyState');

const loadStateCopy = (): TrackingStateModule => {
let copy!: TrackingStateModule;
jest.isolateModules(() => {
copy = jest.requireActual('../FetchProxyState');
});
return copy;
};

describe('FetchProxyState across module copies', () => {
it('shares upload exclusion and XHR suppression with another core copy', () => {
const first = loadStateCopy();
const second = loadStateCopy();
expect(first).not.toBe(second);

first.callWithoutResourceTracking(() => {
expect(second.isResourceTrackingDisabled()).toBe(true);
expect(second.isRunningWithinFetchProxy()).toBe(true);
});

expect(second.isResourceTrackingDisabled()).toBe(false);
expect(second.isRunningWithinFetchProxy()).toBe(false);
});

it('shares the Fetch depth without excluding ordinary Fetch resources', () => {
const first = loadStateCopy();
const second = loadStateCopy();

first.callOriginalFetch(() => {
expect(second.isRunningWithinFetchProxy()).toBe(true);
expect(second.isResourceTrackingDisabled()).toBe(false);
});

expect(second.isRunningWithinFetchProxy()).toBe(false);
});

it('restores shared depths after nested calls throw across copies', () => {
const first = loadStateCopy();
const second = loadStateCopy();

first.callWithoutResourceTracking(() => {
expect(() =>
second.callWithoutResourceTracking(() => {
throw new Error('request failed');
})
).toThrow('request failed');
expect(second.isResourceTrackingDisabled()).toBe(true);
expect(second.isRunningWithinFetchProxy()).toBe(true);
});

expect(first.isResourceTrackingDisabled()).toBe(false);
expect(second.isResourceTrackingDisabled()).toBe(false);
expect(first.isRunningWithinFetchProxy()).toBe(false);
expect(second.isRunningWithinFetchProxy()).toBe(false);
});
});
Loading