diff --git a/.eslintignore b/.eslintignore index c0b6b5c6a..2a69cba19 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,6 +1,8 @@ node_modules example example-new-architecture +example-vega +packages/react-native-vega/build benchmarks dist lib diff --git a/.gitignore b/.gitignore index 8f2cbd836..59443f6aa 100644 --- a/.gitignore +++ b/.gitignore @@ -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 # diff --git a/AGENTS.md b/AGENTS.md index 5cd4754d0..d9514257c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 | diff --git a/packages/core/internal/index.d.ts b/packages/core/internal/index.d.ts new file mode 100644 index 000000000..76ed0c393 --- /dev/null +++ b/packages/core/internal/index.d.ts @@ -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'; diff --git a/packages/core/internal/index.js b/packages/core/internal/index.js new file mode 100644 index 000000000..11f04c7e2 --- /dev/null +++ b/packages/core/internal/index.js @@ -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'; diff --git a/packages/core/internal/package.json b/packages/core/internal/package.json deleted file mode 100644 index 72d3e86c4..000000000 --- a/packages/core/internal/package.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "private": true, - "main": "../lib/commonjs/internal.js", - "module": "../lib/module/internal.js", - "types": "../lib/typescript/internal.d.ts" -} \ No newline at end of file diff --git a/packages/core/package.json b/packages/core/package.json index a996e5cae..a8fa33d1c 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -18,6 +18,7 @@ "main": "lib/commonjs/index", "files": [ "src/**", + "internal", "lib/**", "scripts/**", "android/build.gradle", diff --git a/packages/core/src/__tests__/wrapperImportSafety.test.ts b/packages/core/src/__tests__/wrapperImportSafety.test.ts index 53d626ed1..c2e808882 100644 --- a/packages/core/src/__tests__/wrapperImportSafety.test.ts +++ b/packages/core/src/__tests__/wrapperImportSafety.test.ts @@ -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; - 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; + 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(() => { diff --git a/packages/core/src/internal.ts b/packages/core/src/internal.ts index e13a3bbfb..425901668 100644 --- a/packages/core/src/internal.ts +++ b/packages/core/src/internal.ts @@ -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'; @@ -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'; diff --git a/packages/core/src/rum/instrumentation/resourceTracking/requestProxy/FetchProxy/FetchProxy.ts b/packages/core/src/rum/instrumentation/resourceTracking/requestProxy/FetchProxy/FetchProxy.ts index 79b09d009..a1b22f9cd 100644 --- a/packages/core/src/rum/instrumentation/resourceTracking/requestProxy/FetchProxy/FetchProxy.ts +++ b/packages/core/src/rum/instrumentation/resourceTracking/requestProxy/FetchProxy/FetchProxy.ts @@ -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'; @@ -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, diff --git a/packages/core/src/rum/instrumentation/resourceTracking/requestProxy/FetchProxy/__tests__/FetchProxy.test.ts b/packages/core/src/rum/instrumentation/resourceTracking/requestProxy/FetchProxy/__tests__/FetchProxy.test.ts index 0027f944c..ae8435df9 100644 --- a/packages/core/src/rum/instrumentation/resourceTracking/requestProxy/FetchProxy/__tests__/FetchProxy.test.ts +++ b/packages/core/src/rum/instrumentation/resourceTracking/requestProxy/FetchProxy/__tests__/FetchProxy.test.ts @@ -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'; @@ -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, diff --git a/packages/core/src/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/__tests__/XHRProxy.test.ts b/packages/core/src/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/__tests__/XHRProxy.test.ts index 343bf7a43..5e1c6ef24 100644 --- a/packages/core/src/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/__tests__/XHRProxy.test.ts +++ b/packages/core/src/rum/instrumentation/resourceTracking/requestProxy/XHRProxy/__tests__/XHRProxy.test.ts @@ -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 { @@ -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 diff --git a/packages/core/src/rum/instrumentation/resourceTracking/requestProxy/common/FetchProxyState.ts b/packages/core/src/rum/instrumentation/resourceTracking/requestProxy/common/FetchProxyState.ts index b713591d2..aa87b13e2 100644 --- a/packages/core/src/rum/instrumentation/resourceTracking/requestProxy/common/FetchProxyState.ts +++ b/packages/core/src/rum/instrumentation/resourceTracking/requestProxy/common/FetchProxyState.ts @@ -4,7 +4,12 @@ * 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. @@ -12,14 +17,27 @@ let fetchProxyCallDepth = 0; * returning a Promise, so the XHR proxy can avoid reporting that request twice. */ export const callOriginalFetch = (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 = (callback: () => T): T => { + state.resourceTrackingDisabledDepth += 1; + try { + return callOriginalFetch(callback); + } finally { + state.resourceTrackingDisabledDepth -= 1; + } +}; + +export const isResourceTrackingDisabled = (): boolean => + state.resourceTrackingDisabledDepth > 0; diff --git a/packages/core/src/rum/instrumentation/resourceTracking/requestProxy/common/__tests__/FetchProxyState.test.ts b/packages/core/src/rum/instrumentation/resourceTracking/requestProxy/common/__tests__/FetchProxyState.test.ts new file mode 100644 index 000000000..30b1142ad --- /dev/null +++ b/packages/core/src/rum/instrumentation/resourceTracking/requestProxy/common/__tests__/FetchProxyState.test.ts @@ -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); + }); +}); diff --git a/packages/react-native-vega/CMakeLists.txt b/packages/react-native-vega/CMakeLists.txt new file mode 100644 index 000000000..25ac5d37b --- /dev/null +++ b/packages/react-native-vega/CMakeLists.txt @@ -0,0 +1,90 @@ +# 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. + +cmake_minimum_required(VERSION 3.15) + +project(DatadogVega + VERSION 1.0 + LANGUAGES CXX C) + +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) + +# Fail at compile time for unresolved symbols. +if(CMAKE_CXX_COMPILER_ID MATCHES "Clang") + add_link_options("LINKER:--no-undefined" "LINKER:-z,defs") +endif() + +if (CMAKE_SYSTEM_NAME STREQUAL Android) + add_compile_definitions(ANDROID) +endif() + +# dd-sdk-cpp integration +# Disable default UUID (Vega sysroot lacks libuuid) and use our /dev/urandom impl. +# Build dd-sdk-cpp without a built-in HTTP client (Vega sysroot lacks libcurl): with +# DD_HTTP_CLIENT=none the SDK is built as a static library with the IHttpClient symbols +# referenced but undefined, and we link our own JS-proxy implementation +# (http_js_proxy_client.cpp) into the DatadogVega turbo module below. +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) + +include(FetchContent) +if(DEFINED Datadog_SOURCE_DIR) + message(STATUS "Using local dd-sdk-cpp: ${Datadog_SOURCE_DIR}") + FetchContent_Declare(Datadog SOURCE_DIR ${Datadog_SOURCE_DIR}) +else() + message(STATUS "Fetching dd-sdk-cpp from GitHub") + FetchContent_Declare(Datadog + GIT_REPOSITORY https://github.com/DataDog/dd-sdk-cpp.git + GIT_TAG 0.7.0 + ) +endif() +FetchContent_MakeAvailable(Datadog) + +set(HEADERS + kepler/turbo-modules/generated/DdSdkSpec.h + kepler/turbo-modules/DdSdk.h + kepler/turbo-modules/EnumParsers.h + kepler/turbo-modules/AttributeConverter.h + kepler/turbo-modules/DatadogGlobalState.h + kepler/turbo-modules/HttpJsProxy.h +) + +set(SOURCES + kepler/turbo-modules/generated/DdSdkSpec.cpp + kepler/turbo-modules/DdSdk.cpp + kepler/turbo-modules/EnumParsers.cpp + kepler/turbo-modules/AttributeConverter.cpp + kepler/turbo-modules/DatadogGlobalState.cpp + kepler/turbo-modules/HttpJsProxy.cpp + kepler/turbo-modules/http_js_proxy_client.cpp + kepler/AutoLinkInit.cpp +) + +find_package(turbomoduleAPI CONFIG REQUIRED) + +kepler_add_turbo_module_library(DatadogVega SHARED ${HEADERS} ${SOURCES}) + +target_link_libraries(DatadogVega PRIVATE Datadog::sdk) + +# http_js_proxy_client.cpp provides dd-sdk-cpp's IHttpClient implementation (the SDK is +# built with DD_HTTP_CLIENT=none), so DatadogVega needs dd-sdk-cpp's internal headers +# (datadog/impl/core/http/client.hpp et al.) in addition to our own turbo-module headers. +target_include_directories(DatadogVega PRIVATE + ${datadog_SOURCE_DIR}/src + ${CMAKE_CURRENT_SOURCE_DIR}/kepler/turbo-modules +) + +if (CMAKE_SYSTEM_NAME STREQUAL Android) + target_link_libraries(DatadogVega PRIVATE android log) +endif() + +install(TARGETS DatadogVega) diff --git a/packages/react-native-vega/README.md b/packages/react-native-vega/README.md new file mode 100644 index 000000000..4a13533d2 --- /dev/null +++ b/packages/react-native-vega/README.md @@ -0,0 +1,40 @@ +# Datadog React Native SDK for Vega OS + +This private package provides the native bridge and HTTP transport for Vega OS. +The bridge uses the Datadog C++ SDK and Kepler TurboModules. Native upload +requests are forwarded through JavaScript `fetch`; responses are returned to the +native upload thread. SDK initialization and feature APIs will be added +separately. + +`startHttpProxy()` resolves to a cleanup function. Await it before starting the +native SDK so the JavaScript listener and native emitter are ready for uploads. +Starting again stops the previous session. Cleanup removes the listener, aborts +active fetches where supported, and disarms native uploads, waking any pending +requests. Uploads use a 25-second JavaScript deadline alongside native's +30-second response wait. Timeouts and cancellation keep batches eligible for +retry. SDK uploads bypass automatic Fetch and XHR resource tracking without +adding headers or excluding app requests to the same URL. + +Native modules are resolved on use, keeping package imports safe on other +platforms. This package follows the shared repository version with a `-beta` +suffix while remaining private and excluded from publishing. + +Run the transport tests with: + +```sh +yarn test --runTestsByPath packages/react-native-vega/__tests__/*.test.ts --runInBand --watchman=false +yarn workspace @datadog/mobile-react-native-vega test:native +``` + +Regenerate the native module bindings after changing the specification: + +```sh +yarn workspace @datadog/mobile-react-native-vega codegen +``` + +Build the native module with the Vega SDK installed: + +```sh +cd packages/react-native-vega +vega build -b Release +``` diff --git a/packages/react-native-vega/__tests__/HttpProxy.test.ts b/packages/react-native-vega/__tests__/HttpProxy.test.ts new file mode 100644 index 000000000..518ce07eb --- /dev/null +++ b/packages/react-native-vega/__tests__/HttpProxy.test.ts @@ -0,0 +1,483 @@ +/* + * 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 { FetchProxy } from '../../core/src/rum/instrumentation/resourceTracking/requestProxy/FetchProxy/FetchProxy'; +import type { ResourceReporter } from '../../core/src/rum/instrumentation/resourceTracking/requestProxy/common/ResourceReporter'; +import { startHttpProxy } from '../src/HttpProxy'; +import { getNativeDdSdk } from '../src/turbo-modules/NativeDdSdk'; + +const mockAddListener = jest.fn(); +const mockRemove = jest.fn(); +const mockHttpResponse = jest.fn(); +const mockStartHttpProxy = jest.fn(); +const mockStopHttpProxy = jest.fn(); + +jest.mock('react-native/Libraries/EventEmitter/NativeEventEmitter', () => ({ + __esModule: true, + default: jest.fn().mockImplementation(() => ({ + addListener: mockAddListener + })) +})); + +jest.mock('../src/turbo-modules/NativeDdSdk', () => ({ + getNativeDdSdk: jest.fn(() => ({ + httpResponse: mockHttpResponse, + startHttpProxy: mockStartHttpProxy, + stopHttpProxy: mockStopHttpProxy + })) +})); + +interface HttpRequestEvent { + requestId: string; + url: string; + headers: string; + body: string; +} + +const loadProxyCopy = (): typeof import('../src/HttpProxy') => { + let copy!: typeof import('../src/HttpProxy'); + jest.isolateModules(() => { + copy = jest.requireActual('../src/HttpProxy'); + }); + return copy; +}; + +const flushPromises = () => + new Promise(jest.requireActual('timers').setImmediate); + +describe('HttpProxy', () => { + let requestListener: (event: HttpRequestEvent) => Promise; + let fetchMock: jest.Mock; + let stop: (() => void) | undefined; + + afterEach(async () => { + stop?.(); + stop = undefined; + await Promise.resolve(); + await Promise.resolve(); + }); + + beforeEach(() => { + jest.clearAllMocks(); + mockAddListener.mockImplementation((_eventName, listener) => { + requestListener = listener; + return { remove: mockRemove }; + }); + fetchMock = jest.fn().mockResolvedValue({ status: 202 }); + global.fetch = fetchMock; + }); + + it('forwards an SDK upload without adding private HTTP headers', async () => { + stop = await startHttpProxy(); + + await requestListener({ + requestId: 'request-id', + url: 'https://browser-intake-datadoghq.com/api/v2/rum', + headers: 'Content-Type: application/json\n', + body: '{}' + }); + + expect(fetchMock).toHaveBeenCalledWith( + 'https://browser-intake-datadoghq.com/api/v2/rum', + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: '{}', + signal: expect.any(Object) + } + ); + expect(mockHttpResponse).toHaveBeenCalledWith('request-id', 202); + }); + + it('excludes SDK fetches with core tracking enabled, including custom intake URLs', async () => { + const reportResource = jest.fn(); + const proxy = new FetchProxy({ + fetchGlobal: globalThis, + headersType: Headers, + resourceReporter: ({ + reportResource + } as unknown) as ResourceReporter + }); + const response = { status: 202, headers: new Headers() }; + let resolveUpload!: (value: typeof response) => void; + fetchMock.mockResolvedValue(response).mockReturnValueOnce( + new Promise(resolve => { + resolveUpload = resolve; + }) + ); + proxy.onTrackingStart({ + tracingSamplingRate: 100, + firstPartyHostsRegexMap: [] + }); + try { + stop = await startHttpProxy(); + const url = 'https://proxy.example.com/upload'; + const upload = requestListener({ + requestId: 'sdk-upload', + url, + headers: '', + body: '{}' + }); + expect(reportResource).not.toHaveBeenCalled(); + await fetch(url); + expect(reportResource).toHaveBeenCalledTimes(1); + resolveUpload(response); + await upload; + expect(reportResource).toHaveBeenCalledTimes(1); + expect(mockHttpResponse).toHaveBeenCalledWith('sdk-upload', 202); + } finally { + proxy.onTrackingStop(); + } + }); + + it('reports network failures as retryable', async () => { + fetchMock.mockRejectedValue(new Error('network failure')); + stop = await startHttpProxy(); + await requestListener({ + requestId: 'request-id', + url: 'https://proxy.example.com/upload', + headers: '', + body: '{}' + }); + expect(mockHttpResponse).toHaveBeenCalledWith('request-id', 0); + }); + + it('removes the request listener when stopped', async () => { + stop = await startHttpProxy(); + stop(); + stop(); + await Promise.resolve(); + await Promise.resolve(); + expect(mockStopHttpProxy).toHaveBeenCalledTimes(1); + expect(mockRemove).toHaveBeenCalledTimes(1); + }); + + it('replaces an earlier listener and ignores stale cleanup and events', async () => { + const oldStop = await startHttpProxy(); + const oldListener = requestListener; + stop = await startHttpProxy(); + expect(mockRemove).toHaveBeenCalledTimes(1); + expect(mockStopHttpProxy).toHaveBeenCalledTimes(1); + expect(mockStopHttpProxy.mock.invocationCallOrder[0]).toBeLessThan( + mockStartHttpProxy.mock.invocationCallOrder[1] + ); + oldStop(); + await oldListener({ + requestId: 'stale', + url: 'url', + headers: '', + body: '' + }); + expect(mockRemove).toHaveBeenCalledTimes(1); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it('coordinates listeners and upload exclusion across duplicate package copies', async () => { + const listeners = new Set<(event: HttpRequestEvent) => Promise>(); + mockAddListener.mockImplementation((_eventName, listener) => { + listeners.add(listener); + return { + remove: () => { + listeners.delete(listener); + mockRemove(); + } + }; + }); + const first = loadProxyCopy(); + const second = loadProxyCopy(); + expect(first).not.toBe(second); + + const reportResource = jest.fn(); + const proxy = new FetchProxy({ + fetchGlobal: globalThis, + headersType: Headers, + resourceReporter: ({ + reportResource + } as unknown) as ResourceReporter + }); + fetchMock.mockResolvedValue({ status: 202, headers: new Headers() }); + proxy.onTrackingStart({ + tracingSamplingRate: 100, + firstPartyHostsRegexMap: [] + }); + const firstStop = await first.startHttpProxy(); + try { + stop = await second.startHttpProxy(); + expect(listeners.size).toBe(1); + expect(mockStopHttpProxy).toHaveBeenCalledTimes(1); + firstStop(); + expect(listeners.size).toBe(1); + expect(mockStopHttpProxy).toHaveBeenCalledTimes(1); + await Promise.all( + Array.from(listeners, listener => + listener({ + requestId: 'shared-upload', + url: 'https://proxy.example.com/upload', + headers: 'Content-Type: application/json\n', + body: '{}' + }) + ) + ); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(fetchMock.mock.calls[0][1].headers).toEqual({ + 'Content-Type': 'application/json' + }); + expect(reportResource).not.toHaveBeenCalled(); + await fetch('https://proxy.example.com/upload'); + expect(reportResource).toHaveBeenCalledTimes(1); + } finally { + firstStop(); + proxy.onTrackingStop(); + } + }); + + it('serializes a pending native handshake across duplicate package copies', async () => { + let resolveStart!: () => void; + mockStartHttpProxy.mockReturnValueOnce( + new Promise(resolve => { + resolveStart = resolve; + }) + ); + const first = loadProxyCopy(); + const second = loadProxyCopy(); + const firstStart = first.startHttpProxy(); + await flushPromises(); + const secondStart = second.startHttpProxy(); + try { + await flushPromises(); + expect(mockStartHttpProxy).toHaveBeenCalledTimes(1); + expect(mockStopHttpProxy).not.toHaveBeenCalled(); + } finally { + resolveStart(); + const firstStop = await firstStart; + stop = await secondStart; + firstStop(); + } + expect(mockStopHttpProxy).toHaveBeenCalledTimes(1); + expect(mockStopHttpProxy.mock.invocationCallOrder[0]).toBeLessThan( + mockStartHttpProxy.mock.invocationCallOrder[1] + ); + }); + + describe('request deadlines', () => { + beforeEach(() => jest.useFakeTimers()); + afterEach(() => jest.useRealTimers()); + + it.each([true, false])( + 'bounds a hanging fetch with AbortController available: %s', + async hasAbort => { + const g = (globalThis as unknown) as { + AbortController?: typeof AbortController; + }; + const originalAbort = g.AbortController; + if (!hasAbort) { + delete g.AbortController; + } + try { + fetchMock.mockReturnValue(new Promise(() => undefined)); + stop = await startHttpProxy(); + const request = requestListener({ + requestId: 'timeout', + url: 'url', + headers: '', + body: '' + }); + await jest.advanceTimersByTimeAsync(25_000); + expect(mockHttpResponse).toHaveBeenCalledWith('timeout', 0); + await request; + if (hasAbort) { + expect(fetchMock.mock.calls[0][1].signal.aborted).toBe( + true + ); + } + expect(jest.getTimerCount()).toBe(0); + } finally { + g.AbortController = originalAbort; + } + } + ); + + it('clears the deadline when a response completes', async () => { + stop = await startHttpProxy(); + await requestListener({ + requestId: 'complete', + url: 'url', + headers: '', + body: '' + }); + expect(mockHttpResponse).toHaveBeenCalledWith('complete', 202); + expect(jest.getTimerCount()).toBe(0); + await jest.advanceTimersByTimeAsync(30_000); + expect(mockHttpResponse).toHaveBeenCalledTimes(1); + }); + + it('settles a hanging request and clears its deadline when stopped', async () => { + fetchMock.mockReturnValue(new Promise(() => undefined)); + stop = await startHttpProxy(); + const request = requestListener({ + requestId: 'stopped', + url: 'url', + headers: '', + body: '' + }); + stop(); + await jest.advanceTimersByTimeAsync(0); + expect(mockHttpResponse).toHaveBeenCalledWith('stopped', 0); + await request; + expect(jest.getTimerCount()).toBe(0); + }); + + it.each(['resolve', 'reject'])( + 'ignores a late fetch %s after the deadline', + async outcome => { + let resolveFetch!: (response: { status: number }) => void; + let rejectFetch!: (error: Error) => void; + fetchMock.mockReturnValue( + new Promise((resolve, reject) => { + resolveFetch = resolve; + rejectFetch = reject; + }) + ); + const abort = jest.spyOn(AbortController.prototype, 'abort'); + try { + stop = await startHttpProxy(); + const request = requestListener({ + requestId: 'late', + url: 'url', + headers: '', + body: '' + }); + await jest.advanceTimersByTimeAsync(25_000); + expect(mockHttpResponse).toHaveBeenCalledWith('late', 0); + await request; + if (outcome === 'resolve') { + resolveFetch({ status: 202 }); + } else { + rejectFetch(new Error('late network failure')); + } + await jest.advanceTimersByTimeAsync(0); + stop(); + expect(abort).toHaveBeenCalledTimes(1); + expect(mockHttpResponse).toHaveBeenCalledTimes(1); + expect(jest.getTimerCount()).toBe(0); + } finally { + abort.mockRestore(); + } + } + ); + }); + + it('cancels in-flight fetches and forwards completed responses during cleanup', async () => { + let resolveFetch!: (response: { status: number }) => void; + fetchMock.mockReturnValue( + new Promise(resolve => { + resolveFetch = resolve; + }) + ); + stop = await startHttpProxy(); + const request = requestListener({ + requestId: 'pending', + url: 'url', + headers: '', + body: '' + }); + const signal = fetchMock.mock.calls[0][1].signal; + resolveFetch({ status: 202 }); + // Let the response win the race before cleanup runs its cancellation. + await Promise.resolve(); + stop(); + expect(signal.aborted).toBe(true); + await request; + expect(mockHttpResponse).toHaveBeenCalledWith('pending', 202); + }); + + it('serializes overlapping starts and stops', async () => { + let resolveStart!: () => void; + mockStartHttpProxy.mockReturnValueOnce( + new Promise(resolve => { + resolveStart = resolve; + }) + ); + const first = startHttpProxy(); + await Promise.resolve(); + const second = startHttpProxy(); + resolveStart(); + const oldStop = await first; + stop = await second; + oldStop(); + expect(mockRemove).toHaveBeenCalledTimes(1); + expect(mockStopHttpProxy).toHaveBeenCalledTimes(1); + expect(mockStartHttpProxy).toHaveBeenCalledTimes(2); + }); + + it('contains native teardown failures', async () => { + mockStopHttpProxy.mockRejectedValueOnce( + new Error('native unavailable') + ); + stop = await startHttpProxy(); + expect(() => stop?.()).not.toThrow(); + await Promise.resolve(); + await Promise.resolve(); + }); + + it('contains failures when returning a response to native', async () => { + mockHttpResponse.mockRejectedValueOnce(new Error('native unavailable')); + stop = await startHttpProxy(); + await expect( + requestListener({ + requestId: 'failed-response', + url: 'https://example.com/upload', + headers: '', + body: '{}' + }) + ).resolves.toBeUndefined(); + }); + + it('does not start a proxy when the native module is unavailable', async () => { + (getNativeDdSdk as jest.Mock).mockReturnValueOnce(null); + stop = await startHttpProxy(); + expect(stop).toEqual(expect.any(Function)); + expect(mockAddListener).not.toHaveBeenCalled(); + }); + + it('contains native module lookup failures', async () => { + (getNativeDdSdk as jest.Mock).mockImplementationOnce(() => { + throw new Error('native module failed to load'); + }); + stop = await startHttpProxy(); + expect(stop).toEqual(expect.any(Function)); + expect(mockAddListener).not.toHaveBeenCalled(); + }); + + it('contains listener registration failures', async () => { + mockAddListener.mockImplementationOnce(() => { + throw new Error('event emitter unavailable'); + }); + stop = await startHttpProxy(); + expect(stop).toEqual(expect.any(Function)); + }); + + it('registers the JS listener before enabling native uploads', async () => { + mockStartHttpProxy.mockImplementationOnce(() => { + expect(mockAddListener).toHaveBeenCalledWith( + 'ddHttpRequest', + expect.any(Function) + ); + return Promise.resolve(); + }); + stop = await startHttpProxy(); + expect(mockStartHttpProxy).toHaveBeenCalledTimes(1); + }); + + it('removes the listener if the native handshake fails', async () => { + mockStartHttpProxy.mockRejectedValueOnce( + new Error('native transport unavailable') + ); + stop = await startHttpProxy(); + expect(stop).toEqual(expect.any(Function)); + expect(mockRemove).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/react-native-vega/__tests__/importSafety.test.ts b/packages/react-native-vega/__tests__/importSafety.test.ts new file mode 100644 index 000000000..aa69cd4d9 --- /dev/null +++ b/packages/react-native-vega/__tests__/importSafety.test.ts @@ -0,0 +1,32 @@ +/* + * 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. + */ + +const mockGet = jest.fn(); + +jest.mock('@amazon-devices/keplerscript-turbomodule-api', () => ({ + TurboModuleRegistry: { get: (...args: unknown[]) => mockGet(...args) } +})); + +describe('Vega transport import safety', () => { + beforeEach(() => jest.clearAllMocks()); + + it('does not resolve a native module when importing the package', () => { + jest.isolateModules(() => { + // eslint-disable-next-line global-require, @typescript-eslint/no-var-requires + require('../src'); + }); + expect(mockGet).not.toHaveBeenCalled(); + }); + + it('resolves the transport module only when requested', () => { + const native = { httpResponse: jest.fn() }; + mockGet.mockReturnValueOnce(native); + // eslint-disable-next-line global-require, @typescript-eslint/no-var-requires + const { getNativeDdSdk } = require('../src/turbo-modules/NativeDdSdk'); + expect(getNativeDdSdk()).toBe(native); + expect(mockGet).toHaveBeenCalledWith('DdSdk'); + }); +}); diff --git a/packages/react-native-vega/babel.config.js b/packages/react-native-vega/babel.config.js new file mode 100644 index 000000000..990d54137 --- /dev/null +++ b/packages/react-native-vega/babel.config.js @@ -0,0 +1,3 @@ +module.exports = { + presets: ['module:@react-native/babel-preset'] +}; diff --git a/packages/react-native-vega/kepler/AutoLinkInit.cpp b/packages/react-native-vega/kepler/AutoLinkInit.cpp new file mode 100644 index 000000000..32b1e7764 --- /dev/null +++ b/packages/react-native-vega/kepler/AutoLinkInit.cpp @@ -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. + +#include +#include "turbo-modules/DdSdk.h" + +extern "C" { +__attribute__((visibility("default"))) void + autoLinkKeplerTurboModulesV1() noexcept { + KEPLER_REGISTER_TURBO_MODULE(DdSdkTurboModule, DdSdk); + } +} diff --git a/packages/react-native-vega/kepler/turbo-modules/AttributeConverter.cpp b/packages/react-native-vega/kepler/turbo-modules/AttributeConverter.cpp new file mode 100644 index 000000000..0ab6c9668 --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/AttributeConverter.cpp @@ -0,0 +1,69 @@ +// 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 "AttributeConverter.h" + +namespace datadog_rn_vega { + +using JSValue = com::amazon::kepler::turbomodule::JSValue; +using JSArray = com::amazon::kepler::turbomodule::JSArray; +using JSObject = com::amazon::kepler::turbomodule::JSObject; + +datadog::Attribute jsValueToAttribute(const JSValue& value) { + return std::visit( + [](const auto& v) -> datadog::Attribute { + using T = std::decay_t; + + if constexpr (std::is_same_v) { + return datadog::Attribute::Null(); + } else if constexpr (std::is_same_v) { + return datadog::Attribute::Bool(v); + } else if constexpr (std::is_same_v || + std::is_same_v || + std::is_same_v || + std::is_same_v) { + return datadog::Attribute::Int(static_cast(v)); + } else if constexpr (std::is_same_v || + std::is_same_v || + std::is_same_v) { + return datadog::Attribute::UInt(static_cast(v)); + } else if constexpr (std::is_same_v || + std::is_same_v) { + return datadog::Attribute::Double(static_cast(v)); + } else if constexpr (std::is_same_v) { + return datadog::Attribute::String(v); + } else if constexpr (std::is_same_v) { + datadog::Attribute arr = datadog::Attribute::Array(v.size()); + for (const JSValue& item : v) { + arr.ArrayPush(jsValueToAttribute(item)); + } + return arr; + } else if constexpr (std::is_same_v) { + return jsObjectToAttribute(v); + } else { + return datadog::Attribute::Null(); + } + }, + value); +} + +datadog::Attribute jsObjectToAttribute(const JSObject& object) { + datadog::Attribute attr = datadog::Attribute::Object(object.size()); + for (const auto& [key, val] : object) { + attr.SetObjectProperty(key, jsValueToAttribute(val)); + } + return attr; +} + +datadog::Attribute jsWrappedValueToAttribute(const JSObject& object) { + const auto value = object.find("value"); + if (value == object.end()) { + return jsObjectToAttribute(object); + } + return jsValueToAttribute(value->second); +} + +} // namespace datadog_rn_vega diff --git a/packages/react-native-vega/kepler/turbo-modules/AttributeConverter.h b/packages/react-native-vega/kepler/turbo-modules/AttributeConverter.h new file mode 100644 index 000000000..505c22377 --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/AttributeConverter.h @@ -0,0 +1,40 @@ +// 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 + +#include "datadog/attribute.hpp" + +namespace datadog_rn_vega { + +/** + * Converts a Kepler JSValue variant to a datadog::Attribute. + * + * JSValue = std::variant + */ +datadog::Attribute jsValueToAttribute( + const com::amazon::kepler::turbomodule::JSValue& value); + +/** + * Converts a Kepler JSObject (std::map) to a + * datadog::Attribute of type Object. Each entry in the map becomes a named + * property of the resulting Attribute. + */ +datadog::Attribute jsObjectToAttribute( + const com::amazon::kepler::turbomodule::JSObject& object); + +/** + * Converts the { value: ... } wrapper used by React Native's singular + * attribute APIs to the wrapped datadog::Attribute value. + */ +datadog::Attribute jsWrappedValueToAttribute( + const com::amazon::kepler::turbomodule::JSObject& object); + +} // 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 new file mode 100644 index 000000000..8e70e4ca7 --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/DatadogGlobalState.cpp @@ -0,0 +1,42 @@ +// 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 "DatadogGlobalState.h" + +namespace datadog_rn_vega { + +DatadogGlobalState& DatadogGlobalState::getInstance() { + static DatadogGlobalState instance; + return instance; +} + +void DatadogGlobalState::setCore(std::shared_ptr core) { + std::lock_guard lock(mutex_); + core_ = std::move(core); +} + +std::shared_ptr DatadogGlobalState::getCore() { + std::lock_guard lock(mutex_); + return core_; +} + +void DatadogGlobalState::setRum(std::shared_ptr rum) { + std::lock_guard lock(mutex_); + rum_ = std::move(rum); +} + +std::shared_ptr DatadogGlobalState::getRum() { + std::lock_guard lock(mutex_); + return rum_; +} + +void DatadogGlobalState::reset() { + std::lock_guard lock(mutex_); + rum_.reset(); + core_.reset(); +} + +} // namespace datadog_rn_vega diff --git a/packages/react-native-vega/kepler/turbo-modules/DatadogGlobalState.h b/packages/react-native-vega/kepler/turbo-modules/DatadogGlobalState.h new file mode 100644 index 000000000..4946830d7 --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/DatadogGlobalState.h @@ -0,0 +1,45 @@ +// 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 +#include + +#include "datadog/core.hpp" +#include "datadog/rum.hpp" + +namespace datadog_rn_vega { + +/** + * Thread-safe singleton that holds the Datadog Core and registered feature + * instances. They are initially null and must be set during initialization + * before use. + */ +class DatadogGlobalState { + public: + static DatadogGlobalState& getInstance(); + + void setCore(std::shared_ptr core); + std::shared_ptr getCore(); + + void setRum(std::shared_ptr rum); + std::shared_ptr getRum(); + + /** Clears the core and all registered feature pointers. */ + void reset(); + + private: + DatadogGlobalState() = default; + DatadogGlobalState(const DatadogGlobalState&) = delete; + DatadogGlobalState& operator=(const DatadogGlobalState&) = delete; + + std::mutex mutex_; + std::shared_ptr core_; + std::shared_ptr rum_; +}; + +} // namespace datadog_rn_vega diff --git a/packages/react-native-vega/kepler/turbo-modules/DdSdk.cpp b/packages/react-native-vega/kepler/turbo-modules/DdSdk.cpp new file mode 100644 index 000000000..d8b43b47f --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/DdSdk.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 "DdSdk.h" +#include "HttpJsProxy.h" + +using namespace com::amazon::kepler::turbomodule; + +namespace DdSdkTurboModule { + +DdSdk::DdSdk() = default; + +Promise DdSdk::startHttpProxy() { + return Promise([this](const std::shared_ptr &promise) { + datadog_rn_vega::HttpRequestBridge::getInstance().setEmitFunction( + [this](const std::string &requestId, const std::string &url, + const std::string &headers, const std::string &body) { + JSObject payload; + payload["requestId"] = requestId; + payload["url"] = url; + payload["headers"] = headers; + payload["body"] = body; + emit("ddHttpRequest", payload); + }); + promise->resolve(true); + }); +} + +DdSdk::~DdSdk() noexcept { + datadog_rn_vega::HttpRequestBridge::getInstance().setEmitFunction({}); +} + +Promise DdSdk::stopHttpProxy() { + return Promise([](const std::shared_ptr &promise) { + datadog_rn_vega::HttpRequestBridge::getInstance().setEmitFunction({}); + promise->resolve(true); + }); +} + +Promise DdSdk::httpResponse(std::string requestId, double statusCode) { + return Promise( + [requestId, statusCode](const std::shared_ptr &promise) { + datadog_rn_vega::HttpRequestBridge::getInstance().onResponse( + requestId, static_cast(statusCode)); + promise->resolve(true); + }); +} + +} // namespace DdSdkTurboModule diff --git a/packages/react-native-vega/kepler/turbo-modules/DdSdk.h b/packages/react-native-vega/kepler/turbo-modules/DdSdk.h new file mode 100644 index 000000000..687793672 --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/DdSdk.h @@ -0,0 +1,24 @@ +// 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 "generated/DdSdkSpec.h" + +namespace DdSdkTurboModule { + +class DdSdk : public DdSdkSpec { + public: + DdSdk(); + ~DdSdk() noexcept override; + + com::amazon::kepler::turbomodule::Promise startHttpProxy() override; + com::amazon::kepler::turbomodule::Promise stopHttpProxy() override; + com::amazon::kepler::turbomodule::Promise + httpResponse(std::string requestId, double statusCode) override; +}; + +} // namespace DdSdkTurboModule diff --git a/packages/react-native-vega/kepler/turbo-modules/EnumParsers.cpp b/packages/react-native-vega/kepler/turbo-modules/EnumParsers.cpp new file mode 100644 index 000000000..ba973b3f0 --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/EnumParsers.cpp @@ -0,0 +1,105 @@ +// 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 "EnumParsers.h" + +namespace datadog_rn_vega { + +datadog::RumActionType parseActionType(const std::string& type) { + if (type == "TAP") return datadog::RumActionType::Tap; + if (type == "SCROLL") return datadog::RumActionType::Scroll; + if (type == "SWIPE") return datadog::RumActionType::Swipe; + if (type == "BACK") return datadog::RumActionType::Custom; + if (type == "CUSTOM") return datadog::RumActionType::Custom; + if (type == "CLICK") return datadog::RumActionType::Click; + return datadog::RumActionType::Custom; +} + +datadog::RumResourceMethod parseResourceMethod(const std::string& method) { + if (method == "GET") return datadog::RumResourceMethod::Get; + if (method == "POST") return datadog::RumResourceMethod::Post; + if (method == "PUT") return datadog::RumResourceMethod::Put; + if (method == "DELETE") return datadog::RumResourceMethod::Delete; + if (method == "HEAD") return datadog::RumResourceMethod::Head; + if (method == "PATCH") return datadog::RumResourceMethod::Patch; + if (method == "OPTIONS") return datadog::RumResourceMethod::Options; + if (method == "CONNECT") return datadog::RumResourceMethod::Connect; + if (method == "TRACE") return datadog::RumResourceMethod::Trace; + return datadog::RumResourceMethod::Get; +} + +datadog::RumResourceType parseResourceType(const std::string& kind) { + if (kind == "xhr") return datadog::RumResourceType::Xhr; + if (kind == "fetch") return datadog::RumResourceType::Fetch; + if (kind == "document") return datadog::RumResourceType::Document; + if (kind == "image") return datadog::RumResourceType::Image; + if (kind == "font") return datadog::RumResourceType::Font; + if (kind == "css") return datadog::RumResourceType::Css; + if (kind == "js") return datadog::RumResourceType::Js; + if (kind == "media") return datadog::RumResourceType::Media; + if (kind == "beacon") return datadog::RumResourceType::Beacon; + if (kind == "native") return datadog::RumResourceType::Native; + if (kind == "other") return datadog::RumResourceType::Other; + return datadog::RumResourceType::Unknown; +} + +datadog::RumErrorSource parseErrorSource(const std::string& source) { + if (source == "NETWORK") return datadog::RumErrorSource::Network; + if (source == "SOURCE") return datadog::RumErrorSource::Source; + if (source == "CONSOLE") return datadog::RumErrorSource::Console; + if (source == "WEBVIEW") return datadog::RumErrorSource::Webview; + if (source == "CUSTOM") return datadog::RumErrorSource::Custom; + if (source == "LOGGER") return datadog::RumErrorSource::Logger; + if (source == "AGENT") return datadog::RumErrorSource::Agent; + if (source == "REPORT") return datadog::RumErrorSource::Report; + return datadog::RumErrorSource::Custom; +} + +datadog::RumOperationFailureReason parseOperationFailureReason( + const std::string& reason) { + if (reason == "ERROR") return datadog::RumOperationFailureReason::Error; + if (reason == "ABANDONED") + return datadog::RumOperationFailureReason::Abandoned; + return datadog::RumOperationFailureReason::Other; +} + +datadog::TrackingConsent parseTrackingConsent(const std::string& consent) { + if (consent == "granted") return datadog::TrackingConsent::Granted; + if (consent == "not_granted") return datadog::TrackingConsent::NotGranted; + return datadog::TrackingConsent::Pending; +} + +datadog::Site parseSite(const std::string& site) { + if (site == "US1") return datadog::Site::us1; + if (site == "US3") return datadog::Site::us3; + if (site == "US5") return datadog::Site::us5; + if (site == "EU1") return datadog::Site::eu1; + if (site == "AP1") return datadog::Site::ap1; + if (site == "AP2") return datadog::Site::ap2; + if (site == "US1_FED") return datadog::Site::us1_fed; + return datadog::Site::us1; +} + +datadog::BatchSize parseBatchSize(const std::string& size) { + if (size == "SMALL") return datadog::BatchSize::Small; + if (size == "LARGE") return datadog::BatchSize::Large; + return datadog::BatchSize::Medium; +} + +datadog::UploadFrequency parseUploadFrequency(const std::string& frequency) { + if (frequency == "RARE") return datadog::UploadFrequency::Rare; + if (frequency == "FREQUENT") return datadog::UploadFrequency::Frequent; + return datadog::UploadFrequency::Average; +} + +datadog::BatchProcessingLevel parseBatchProcessingLevel( + const std::string& level) { + if (level == "LOW") return datadog::BatchProcessingLevel::Low; + if (level == "HIGH") return datadog::BatchProcessingLevel::High; + return datadog::BatchProcessingLevel::Medium; +} + +} // namespace datadog_rn_vega diff --git a/packages/react-native-vega/kepler/turbo-modules/EnumParsers.h b/packages/react-native-vega/kepler/turbo-modules/EnumParsers.h new file mode 100644 index 000000000..b0f85fafb --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/EnumParsers.h @@ -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. + +#pragma once + +#include + +#include "datadog/core.hpp" +#include "datadog/rum.hpp" + +namespace datadog_rn_vega { + +datadog::RumActionType parseActionType(const std::string& type); +datadog::RumResourceMethod parseResourceMethod(const std::string& method); +datadog::RumResourceType parseResourceType(const std::string& kind); +datadog::RumErrorSource parseErrorSource(const std::string& source); +datadog::RumOperationFailureReason parseOperationFailureReason( + const std::string& reason); +datadog::TrackingConsent parseTrackingConsent(const std::string& consent); +datadog::Site parseSite(const std::string& site); +datadog::BatchSize parseBatchSize(const std::string& size); +datadog::UploadFrequency parseUploadFrequency(const std::string& frequency); +datadog::BatchProcessingLevel parseBatchProcessingLevel( + const std::string& level); + +} // namespace datadog_rn_vega diff --git a/packages/react-native-vega/kepler/turbo-modules/HttpJsProxy.cpp b/packages/react-native-vega/kepler/turbo-modules/HttpJsProxy.cpp new file mode 100644 index 000000000..b3543c49a --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/HttpJsProxy.cpp @@ -0,0 +1,138 @@ +// 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 "HttpJsProxy.h" + +#include +#include + +namespace datadog_rn_vega { + +static const size_t BODY_WRITER_EOF = 0; +static const size_t BODY_WRITER_ABORT = 0xffffffff; + +HttpRequestBridge &HttpRequestBridge::getInstance() { + static HttpRequestBridge instance; + return instance; +} + +void HttpRequestBridge::setEmitFunction(EmitFn fn) { + std::lock_guard lock(emitterMutex_); + emitFn_ = std::move(fn); + std::map> cancelled; + { + std::lock_guard pendingLock(mutex_); + cancelled.swap(pending_); + } + for (const auto &entry : cancelled) { + const auto &pending = entry.second; + { + std::lock_guard pendingLock(pending->mutex); + if (!pending->completed) { + pending->cancelled = true; + pending->completed = true; + } + } + pending->cv.notify_one(); + } +} + +HttpProxyResult HttpRequestBridge::sendRequest(const char *url, + const char *headers, + BodyWriter body_writer) { + + // Read the full body from the writer callback + std::vector chunk(64 * 1024); + std::string body; + while (true) { + size_t n = body_writer(chunk.data(), chunk.size()); + if (n == BODY_WRITER_EOF) + break; + if (n == BODY_WRITER_ABORT || n > chunk.size()) { + return {false, false, 0}; + } + body.append(chunk.data(), n); + } + + // Create a pending request with unique ID + std::string requestId; + auto pending = std::make_shared(); + // Clearing the emitter waits for an active emit to finish before the native + // module is destroyed. Never hold this lock while waiting for a JS + // response. + { + std::lock_guard emitterLock(emitterMutex_); + if (!emitFn_) { + // Transport unavailability must retain the batch for a later retry. + return {false, true, 0}; + } + { + std::lock_guard lock(mutex_); + requestId = std::to_string(nextRequestId_++); + pending_[requestId] = pending; + } + try { + emitFn_(requestId, std::string(url), std::string(headers), body); + } catch (...) { + std::lock_guard lock(mutex_); + pending_.erase(requestId); + return {false, true, 0}; + } + } + + // Block until JS responds (30s timeout) + int statusCode; + { + std::unique_lock lock(pending->mutex); + bool ok = pending->cv.wait_for(lock, std::chrono::seconds(30), + [&] { return pending->completed; }); + + if (!ok) { + std::lock_guard glock(mutex_); + pending_.erase(requestId); + return {false, true, 0}; // timeout → retryable + } + if (pending->cancelled) { + return {false, true, 0}; + } + statusCode = pending->status_code; + } + + { + std::lock_guard lock(mutex_); + pending_.erase(requestId); + } + + if (statusCode == 0) { + return {false, true, 0}; // fetch() failed → retryable + } + return {true, false, statusCode}; +} + +void HttpRequestBridge::onResponse(const std::string &requestId, + int statusCode) { + std::shared_ptr pending; + { + std::lock_guard lock(mutex_); + auto it = pending_.find(requestId); + if (it == pending_.end()) { + return; + } + pending = it->second; + } + + { + std::lock_guard lock(pending->mutex); + if (pending->completed) { + return; + } + pending->status_code = statusCode; + pending->completed = true; + } + pending->cv.notify_one(); +} + +} // namespace datadog_rn_vega diff --git a/packages/react-native-vega/kepler/turbo-modules/HttpJsProxy.h b/packages/react-native-vega/kepler/turbo-modules/HttpJsProxy.h new file mode 100644 index 000000000..4126ee7da --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/HttpJsProxy.h @@ -0,0 +1,88 @@ +// 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 +#include +#include +#include +#include +#include +#include + +namespace datadog_rn_vega { + +/** + * Holds a pending HTTP request that's waiting for a JS response. + */ +struct PendingHttpRequest { + std::mutex mutex; + std::condition_variable cv; + bool completed = false; + bool cancelled = false; + int status_code = 0; +}; + +/** + * Result of an HTTP request proxied through JS. + */ +struct HttpProxyResult { + bool success; // true if we got a response + bool retryable; // true if failure is transient (timeout, etc.) + int status_code; // HTTP status code (0 if no response) +}; + +/** + * Manages pending HTTP requests and their JS responses. + * Thread-safe singleton. + * + * Used by: + * - http_js_proxy_client.cpp: calls sendRequest() + * - DdSdk.cpp (our TurboModule): wires up emitFn and calls onResponse() + */ +class HttpRequestBridge { + public: + static HttpRequestBridge& getInstance(); + + using EmitFn = std::function; + + /** + * Body writer callback — reads chunks of request body. + * Returns number of bytes written, 0 for EOF, 0xffffffff for abort. + */ + using BodyWriter = std::function; + + // Replacing or clearing the emitter also cancels its pending requests. + void setEmitFunction(EmitFn fn); + + /** + * Called from the upload thread. Reads the full body, emits an HTTP + * request event to JS, and blocks until httpResponse() is called. + */ + HttpProxyResult sendRequest( + const char* url, const char* headers, BodyWriter body_writer); + + /** + * Called from JS thread via DdSdk.httpResponse(). + * Unblocks the waiting upload thread. + */ + void onResponse(const std::string& requestId, int statusCode); + + private: + HttpRequestBridge() = default; + + std::mutex mutex_; + std::mutex emitterMutex_; + EmitFn emitFn_; + uint64_t nextRequestId_ = 0; + std::map> pending_; +}; + +} // namespace datadog_rn_vega diff --git a/packages/react-native-vega/kepler/turbo-modules/generated/DdSdkSpec.cpp b/packages/react-native-vega/kepler/turbo-modules/generated/DdSdkSpec.cpp new file mode 100644 index 000000000..caf5a13bc --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/generated/DdSdkSpec.cpp @@ -0,0 +1,27 @@ +/** + * This code was generated by the Kepler Codegen tool. + * + * Do not edit this file as changes may cause incorrect behavior and will be + * lost when the code is regenerated. + * + * @generated by GenerateModuleSpecCpp.js + */ + +#include "DdSdkSpec.h" + +using namespace com::amazon::kepler::turbomodule; + +namespace DdSdkTurboModule { + +DdSdkSpec::DdSdkSpec() : KeplerTurboModule("DdSdk") {} + +DdSdkSpec::~DdSdkSpec() = default; + +void DdSdkSpec::aggregateMethods( + MethodAggregator &methodAggregator) const noexcept { + methodAggregator.addMethod("startHttpProxy", &DdSdkSpec::startHttpProxy); + methodAggregator.addMethod("stopHttpProxy", &DdSdkSpec::stopHttpProxy); + methodAggregator.addMethod("httpResponse", &DdSdkSpec::httpResponse); +} + +} // namespace DdSdkTurboModule diff --git a/packages/react-native-vega/kepler/turbo-modules/generated/DdSdkSpec.h b/packages/react-native-vega/kepler/turbo-modules/generated/DdSdkSpec.h new file mode 100644 index 000000000..905f5f57c --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/generated/DdSdkSpec.h @@ -0,0 +1,43 @@ +/** + * This code was generated by the Kepler Codegen tool. + * + * Do not edit this file as changes may cause incorrect behavior and will be + * lost when the code is regenerated. + * + * @generated by GenerateModuleSpecH.js + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace DdSdkTurboModule { + +class DdSdkSpec : public com::amazon::kepler::turbomodule::KeplerTurboModule { + protected: + DdSdkSpec(); + virtual ~DdSdkSpec() = 0; + + public: + void aggregateMethods( + com::amazon::kepler::turbomodule::MethodAggregator + &methodAggregator) const noexcept override; + + virtual com::amazon::kepler::turbomodule::Promise startHttpProxy() = 0; + virtual com::amazon::kepler::turbomodule::Promise stopHttpProxy() = 0; + virtual com::amazon::kepler::turbomodule::Promise + httpResponse(std::string requestId, double statusCode) = 0; +}; + +} // namespace DdSdkTurboModule diff --git a/packages/react-native-vega/kepler/turbo-modules/http_js_proxy_client.cpp b/packages/react-native-vega/kepler/turbo-modules/http_js_proxy_client.cpp new file mode 100644 index 000000000..04b8d46ea --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/http_js_proxy_client.cpp @@ -0,0 +1,55 @@ +// 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. + +// dd-sdk-cpp HTTP client implementation that proxies requests through JS. +// dd-sdk-cpp is built with DD_HTTP_CLIENT=none, so this file is compiled into the +// DatadogVega turbo module and provides the IHttpClient implementation (and the +// datadog::impl::Http::Init() entry point) that the SDK references but does not define. +// It includes dd-sdk-cpp internal headers, made available via target_include_directories. + +#include "datadog/impl/core/http/client.hpp" +#include "HttpJsProxy.h" + +namespace datadog::impl { + +class JsProxyHttpClient final : public IHttpClient { + public: + HttpResult Post( + const char* url, const char* headers, + HttpBodyWriter body_writer) override { + try { + auto result = datadog_rn_vega::HttpRequestBridge::getInstance() + .sendRequest(url, headers, std::move(body_writer)); + + if (result.success) { + return {HttpResultType::GotResponse, result.status_code}; + } + if (result.retryable) { + return {HttpResultType::GotNoResponse_Retryable, 0}; + } + return {HttpResultType::SentNoRequest, 0}; + } catch (...) { + return {HttpResultType::GotNoResponse_Retryable, 0}; + } + } +}; + +class JsProxyHttpSubsystem final : public IHttpSubsystem { + public: + std::string_view GetName() const override { return "js-proxy"; } + std::string_view GetVersion() const override { return "1.0.0"; } + + std::unique_ptr CreateClient() override { + return std::make_unique(); + } +}; + +std::unique_ptr Http::Init(const DiagnosticLogger& logger) { + (void)logger; + return std::make_unique(); +} + +} // namespace datadog::impl diff --git a/packages/react-native-vega/kepler/turbo-modules/uuid_urandom.cpp b/packages/react-native-vega/kepler/turbo-modules/uuid_urandom.cpp new file mode 100644 index 000000000..172dd15d8 --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/uuid_urandom.cpp @@ -0,0 +1,37 @@ +// 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. + +// Custom UUID implementation for Vega OS, which does not include libuuid. +// Reads 16 random bytes from /dev/urandom to generate UUIDs. + +#include "datadog/impl/core/platform/uuid.hpp" + +#include + +namespace datadog::platform { + +void UuidGenerate(uint8_t out[16]) { + FILE* f = std::fopen("/dev/urandom", "rb"); + if (f) { + const auto bytesRead = std::fread(out, 1, 16, f); + std::fclose(f); + if (bytesRead != 16) { + for (int i = 0; i < 16; ++i) out[i] = 0; + return; + } + + // Set version 4 (random) UUID bits per RFC 4122 + out[6] = (out[6] & 0x0F) | 0x40; // version 4 + out[8] = (out[8] & 0x3F) | 0x80; // variant 1 + } else { + // Fallback: zero-fill (should not happen on Vega OS) + for (int i = 0; i < 16; ++i) { + out[i] = 0; + } + } +} + +} // namespace datadog::platform diff --git a/packages/react-native-vega/package.json b/packages/react-native-vega/package.json new file mode 100644 index 000000000..13d5ae47f --- /dev/null +++ b/packages/react-native-vega/package.json @@ -0,0 +1,95 @@ +{ + "name": "@datadog/mobile-react-native-vega", + "version": "3.13.0-beta", + "private": true, + "description": "Datadog native bridge for Amazon Vega SDK apps", + "keywords": [ + "datadog", + "react-native", + "vega", + "amazon", + "tv" + ], + "author": "Datadog (https://github.com/DataDog)", + "homepage": "https://github.com/DataDog/dd-sdk-reactnative/packages/react-native-vega#readme", + "repository": { + "url": "https://github.com/DataDog/dd-sdk-reactnative", + "directory": "packages/react-native-vega" + }, + "bugs": { + "url": "https://github.com/DataDog/dd-sdk-reactnative/issues" + }, + "license": "Apache-2.0", + "main": "lib/commonjs/index", + "files": [ + "src/**", + "lib/commonjs/**", + "lib/module/**", + "lib/typescript/**", + "kepler/AutoLinkInit.cpp", + "kepler/turbo-modules/*.cpp", + "kepler/turbo-modules/*.h", + "kepler/turbo-modules/generated/**", + "CMakeLists.txt", + "react-native.config.js" + ], + "types": "lib/typescript/index.d.ts", + "react-native": "src/index", + "source": "src/index", + "module": "lib/module/index", + "publishConfig": { + "access": "restricted" + }, + "scripts": { + "test": "jest", + "lint": "eslint src __tests__", + "prepare": "bob build", + "codegen": "keplerscript-turbomodule-api codegen src/turbo-modules/NativeDdSdk.ts -o kepler/turbo-modules/ --namespace DdSdkTurboModule --className DdSdk", + "test:native": "cmake -S tests -B build/host-tests && cmake --build build/host-tests && ctest --test-dir build/host-tests --output-on-failure" + }, + "dependencies": { + "@amazon-devices/keplerscript-turbomodule-api": "1.2.5" + }, + "peerDependencies": { + "@amazon-devices/react-native-kepler": "^2.0.0", + "@datadog/mobile-react-native": "3.13.0", + "react": ">=16.13.1", + "react-native": ">=0.63.4 <1.0" + }, + "devDependencies": { + "react-native-builder-bob": "0.26.0" + }, + "jest": { + "preset": "react-native", + "moduleNameMapper": { + "^@datadog/mobile-react-native/internal$": "/../core/src/internal.ts" + }, + "modulePathIgnorePatterns": [ + "/lib/" + ], + "transformIgnorePatterns": [ + "jest-runner" + ] + }, + "kepler": { + "projectType": "turbomodule", + "targets": [ + "tv" + ] + }, + "react-native-builder-bob": { + "source": "src", + "output": "lib", + "targets": [ + "commonjs", + "module", + [ + "typescript", + { + "tsc": "./../../node_modules/.bin/tsc", + "project": "tsconfig.build.json" + } + ] + ] + } +} diff --git a/packages/react-native-vega/react-native.config.js b/packages/react-native-vega/react-native.config.js new file mode 100644 index 000000000..1dbcdab1e --- /dev/null +++ b/packages/react-native-vega/react-native.config.js @@ -0,0 +1,16 @@ +module.exports = { + dependency: { + platforms: { + kepler: { + autolink: { + 'com.datadog.reactnative.vega': { + libraryName: 'libDatadogVega.so', + provider: 'application', + linkDynamic: true, + turbomodules: ['DdSdk'] + } + } + } + } + } +}; diff --git a/packages/react-native-vega/src/HttpProxy.ts b/packages/react-native-vega/src/HttpProxy.ts new file mode 100644 index 000000000..a95761d40 --- /dev/null +++ b/packages/react-native-vega/src/HttpProxy.ts @@ -0,0 +1,184 @@ +/* + * 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 { + callWithoutResourceTracking, + getGlobalInstance +} from '@datadog/mobile-react-native/internal'; +import { NativeEventEmitter } from 'react-native'; + +import type { DdSdk } from './turbo-modules/NativeDdSdk'; +import { getNativeDdSdk } from './turbo-modules/NativeDdSdk'; + +interface HttpProxyLifecycle { + activeCleanup?: () => void; + operations: Promise; +} + +const lifecycle = getGlobalInstance( + 'com.datadog.reactnative.vega.http_proxy', + () => ({ operations: Promise.resolve() }) +); + +// Leave time to report a retryable failure before native's 30-second wait ends. +const HTTP_REQUEST_TIMEOUT_MS = 25_000; + +const fetchWithDeadline = async ( + url: string, + options: Parameters[1], + requests: Set<() => void> +): Promise => { + const controller = + typeof AbortController === 'undefined' + ? undefined + : new AbortController(); + let completeCancellation: () => void = () => undefined; + const cancellation = new Promise(resolve => { + completeCancellation = () => resolve(undefined); + }); + let cancelled = false; + const cancel = () => { + if (cancelled) { + return; + } + cancelled = true; + completeCancellation(); + try { + controller?.abort(); + } catch { + // Cancellation still settles if this Fetch cannot be aborted. + } + }; + const timeout = setTimeout(cancel, HTTP_REQUEST_TIMEOUT_MS); + requests.add(cancel); + try { + return await Promise.race([ + callWithoutResourceTracking(() => + fetch(url, { + ...options, + ...(controller ? { signal: controller.signal } : {}) + }) + ), + cancellation + ]); + } finally { + clearTimeout(timeout); + requests.delete(cancel); + } +}; + +const enqueue = (operation: () => Promise): Promise => { + const result = lifecycle.operations.then(operation); + lifecycle.operations = result.catch(() => undefined); + return result; +}; + +/** + * Forwards native uploads through fetch without recording them as RUM resources. + * Await startup before enabling native uploads. Starting again replaces the + * previous session; its cleanup cannot stop the replacement session. + */ +export async function startHttpProxy(): Promise<() => void> { + lifecycle.activeCleanup?.(); + let active = true; + let nativeSdk: DdSdk | null = null; + let subscription: { remove(): void } | undefined; + const requests = new Set<() => void>(); + + const cleanup = () => { + if (!active) { + return; + } + active = false; + if (lifecycle.activeCleanup === cleanup) { + lifecycle.activeCleanup = undefined; + } + // Queue teardown before a replacement session can enable its emitter. + enqueue(async () => { + try { + await nativeSdk?.stopHttpProxy(); + } catch { + // Teardown must not interrupt the host app. + } + }); + try { + subscription?.remove(); + } catch { + // The native module may already be unavailable. + } + requests.forEach(request => { + try { + request(); + } catch { + // Some Fetch implementations do not support cancellation. + } + }); + requests.clear(); + }; + lifecycle.activeCleanup = cleanup; + + try { + await enqueue(async () => { + if (!active) { + return; + } + nativeSdk = getNativeDdSdk(); + if (!nativeSdk) { + cleanup(); + return; + } + const sdk = nativeSdk; + subscription = new NativeEventEmitter().addListener( + 'ddHttpRequest', + async (event: { + requestId: string; + url: string; + headers: string; + body: string; + }) => { + if (!active) { + return; + } + let statusCode = 0; + try { + const headers: Record = {}; + event.headers.split('\n').forEach(line => { + const colon = line.indexOf(':'); + if (colon >= 0) { + headers[ + line.substring(0, colon).trim() + ] = line.substring(colon + 1).trim(); + } + }); + const response = await fetchWithDeadline( + event.url, + { + method: 'POST', + headers, + body: event.body + }, + requests + ); + statusCode = response?.status ?? 0; + } catch { + // Status 0 makes network errors and timeouts retryable. + } + try { + // Native arbitrates response versus cancellation and + // ignores IDs whose requests have already completed. + await sdk.httpResponse(event.requestId, statusCode); + } catch { + // Native times out or teardown cancels the waiter. + } + } + ); + await sdk.startHttpProxy(); + }); + } catch { + cleanup(); + } + return cleanup; +} diff --git a/packages/react-native-vega/src/index.ts b/packages/react-native-vega/src/index.ts new file mode 100644 index 000000000..4a21237d2 --- /dev/null +++ b/packages/react-native-vega/src/index.ts @@ -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 { startHttpProxy } from './HttpProxy'; diff --git a/packages/react-native-vega/src/turbo-modules/NativeDdSdk.ts b/packages/react-native-vega/src/turbo-modules/NativeDdSdk.ts new file mode 100644 index 000000000..8d3106dac --- /dev/null +++ b/packages/react-native-vega/src/turbo-modules/NativeDdSdk.ts @@ -0,0 +1,17 @@ +/* + * 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'; + +export interface DdSdk extends KeplerTurboModule { + startHttpProxy(): Promise; + stopHttpProxy(): Promise; + httpResponse(requestId: string, statusCode: number): Promise; +} + +export const getNativeDdSdk = (): DdSdk | null => + TurboModuleRegistry.get('DdSdk') ?? null; diff --git a/packages/react-native-vega/tests/CMakeLists.txt b/packages/react-native-vega/tests/CMakeLists.txt new file mode 100644 index 000000000..f75eca9b6 --- /dev/null +++ b/packages/react-native-vega/tests/CMakeLists.txt @@ -0,0 +1,18 @@ +# 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. + +cmake_minimum_required(VERSION 3.15) +project(VegaHttpProxyTests LANGUAGES CXX) +enable_testing() +find_package(Threads REQUIRED) + +add_executable(HttpJsProxyTest + HttpJsProxyTest.cpp + ../kepler/turbo-modules/HttpJsProxy.cpp) +target_compile_features(HttpJsProxyTest PRIVATE cxx_std_17) +target_link_libraries(HttpJsProxyTest PRIVATE Threads::Threads) +add_test(NAME HttpJsProxy COMMAND HttpJsProxyTest) +set_tests_properties(HttpJsProxy PROPERTIES TIMEOUT 10) diff --git a/packages/react-native-vega/tests/HttpJsProxyTest.cpp b/packages/react-native-vega/tests/HttpJsProxyTest.cpp new file mode 100644 index 000000000..5474df719 --- /dev/null +++ b/packages/react-native-vega/tests/HttpJsProxyTest.cpp @@ -0,0 +1,150 @@ +// 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 "../kepler/turbo-modules/HttpJsProxy.h" + +#ifdef NDEBUG +#undef NDEBUG +#endif +#include +#include +#include +#include +#include +#include + +using datadog_rn_vega::HttpRequestBridge; + +int main() { + auto &bridge = HttpRequestBridge::getInstance(); + auto emptyBody = [](char *, size_t) { return size_t{0}; }; + bridge.setEmitFunction({}); + auto unavailable = bridge.sendRequest("url", "", emptyBody); + assert(!unavailable.success && unavailable.retryable); + + bridge.setEmitFunction([&](const auto &id, const auto &url, + const auto &headers, const auto &body) { + assert(url == "https://example.com/upload"); + assert(headers == "Content-Type: application/json\n"); + assert(body == "{}"); + bridge.onResponse(id, 202); + bridge.onResponse(id, + 500); // A duplicate must not overwrite the result. + }); + auto result = bridge.sendRequest( + "https://example.com/upload", "Content-Type: application/json\n", + [written = false](char *buffer, size_t) mutable -> size_t { + if (written) + return 0; + written = true; + std::memcpy(buffer, "{}", 2); + return 2; + }); + assert(result.success && result.status_code == 202); + + bridge.setEmitFunction([&](const auto &id, const auto &, const auto &, + const auto &) { bridge.onResponse(id, 0); }); + result = bridge.sendRequest("url", "", emptyBody); + assert(!result.success && result.retryable); + + bridge.setEmitFunction( + [](const auto &, const auto &, const auto &, const auto &) { + throw std::runtime_error("emitter unavailable"); + }); + result = bridge.sendRequest("url", "", emptyBody); + assert(!result.success && result.retryable); + + bridge.setEmitFunction( + [](const auto &, const auto &, const auto &, const auto &) { + throw std::runtime_error("an aborted body must never be emitted"); + }); + result = bridge.sendRequest( + "url", "", [](char *, size_t) { return size_t{0xffffffff}; }); + assert(!result.success && !result.retryable); + result = bridge.sendRequest("url", "", + [](char *, size_t size) { return size + 1; }); + assert(!result.success && !result.retryable); + + bridge.setEmitFunction( + [&](const auto &id, const auto &url, const auto &, const auto &) { + bridge.onResponse(id, std::stoi(url)); + }); + std::vector> requests; + for (int status = 200; status < 220; ++status) { + requests.push_back(std::async(std::launch::async, [&, status] { + const auto request = bridge.sendRequest( + std::to_string(status).c_str(), "", emptyBody); + assert(request.success && request.status_code == status); + })); + } + for (auto &request : requests) + request.get(); + bridge.onResponse("unknown-request", 200); + bridge.setEmitFunction({}); + + std::promise entered; + std::promise release; + auto released = release.get_future().share(); + bridge.setEmitFunction( + [&](const auto &id, const auto &, const auto &, const auto &) { + entered.set_value(); + released.wait(); + bridge.onResponse(id, 202); + }); + auto sending = std::async(std::launch::async, [&] { + return bridge.sendRequest("url", "", emptyBody); + }); + entered.get_future().wait(); + std::promise clearing; + auto teardown = std::async(std::launch::async, [&] { + clearing.set_value(); + bridge.setEmitFunction({}); + }); + clearing.get_future().wait(); + assert(teardown.wait_for(std::chrono::milliseconds(20)) == + std::future_status::timeout); + release.set_value(); + assert(sending.get().status_code == 202); + teardown.get(); + assert(!bridge.sendRequest("url", "", emptyBody).success); + + // Stopping wakes every pending upload without waiting for the 30s timeout. + std::mutex idsMutex; + std::vector pendingIds; + std::promise allEmitted; + bridge.setEmitFunction( + [&](const auto &id, const auto &, const auto &, const auto &) { + std::lock_guard lock(idsMutex); + pendingIds.push_back(id); + if (pendingIds.size() == 3) + allEmitted.set_value(); + }); + std::vector> waiting; + for (int i = 0; i < 3; ++i) { + waiting.push_back(std::async(std::launch::async, [&] { + return bridge.sendRequest("url", "", emptyBody); + })); + } + allEmitted.get_future().wait(); + bridge.setEmitFunction({}); + bridge.setEmitFunction({}); // Repeated teardown is safe. + for (auto &request : waiting) { + assert(request.wait_for(std::chrono::seconds(1)) == + std::future_status::ready); + auto cancelled = request.get(); + assert(!cancelled.success && cancelled.retryable); + } + assert(bridge.sendRequest("url", "", emptyBody).retryable); + bridge.setEmitFunction( + [&](const auto &id, const auto &, const auto &, const auto &) { + // Responses from the stopped session cannot complete a new request. + for (const auto &oldId : pendingIds) + bridge.onResponse(oldId, 500); + bridge.onResponse(id, 201); + }); + assert(bridge.sendRequest("url", "", emptyBody).status_code == 201); + bridge.setEmitFunction({}); +} diff --git a/packages/react-native-vega/tsconfig.build.json b/packages/react-native-vega/tsconfig.build.json new file mode 100644 index 000000000..9bf5b455b --- /dev/null +++ b/packages/react-native-vega/tsconfig.build.json @@ -0,0 +1,4 @@ +{ + "extends": "./tsconfig", + "include": ["src"] +} diff --git a/packages/react-native-vega/tsconfig.json b/packages/react-native-vega/tsconfig.json new file mode 100644 index 000000000..996bfea4a --- /dev/null +++ b/packages/react-native-vega/tsconfig.json @@ -0,0 +1,4 @@ +{ + "extends": "../../tsconfig", + "include": ["src", "__tests__"] +} diff --git a/update-version.sh b/update-version.sh index 097fba0ee..3e85176b5 100755 --- a/update-version.sh +++ b/update-version.sh @@ -8,6 +8,19 @@ sed -i '' -e "s/\".*\"/\"$1\"/g" packages/core/android/src/main/kotlin/com/datad # Change version yarn run lerna version $1 --ignore-changes --no-git-tag-version --no-push + +# Keep Vega on the release version with a beta suffix. +node <<'NODE' +const fs = require('fs'); +const { version } = require('./lerna.json'); +const { version: coreVersion } = require('./packages/core/package.json'); +const packagePath = 'packages/react-native-vega/package.json'; +const vegaPackage = JSON.parse(fs.readFileSync(packagePath, 'utf8')); +vegaPackage.version = version.endsWith('-beta') ? version : `${version}-beta`; +vegaPackage.peerDependencies['@datadog/mobile-react-native'] = coreVersion; +fs.writeFileSync(packagePath, JSON.stringify(vegaPackage, null, 4) + '\n'); +NODE + yarn prepare # prepare packages diff --git a/yarn.lock b/yarn.lock index 4105777dc..08b7229c4 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5,6 +5,22 @@ __metadata: version: 6 cacheKey: 8 +"@amazon-devices/keplerscript-turbomodule-api@npm:1.2.5": + version: 1.2.5 + resolution: "@amazon-devices/keplerscript-turbomodule-api@npm:1.2.5" + dependencies: + "@babel/parser": ^7.20.0 + flow-parser: ^0.206.0 + invariant: ^2.2.4 + jscodeshift: ^0.14.0 + nullthrows: ^1.1.1 + yargs: ^17.7.2 + bin: + keplerscript-turbomodule-api: cli.js + checksum: ef9031c441f81025b1a2399d71a1730e104762f2b8eee2e93f55a7e882067df571d879438ab7870718201677bb1d37aff813fc48aa6d08fb8484631836cf03c7 + languageName: node + linkType: hard + "@antfu/install-pkg@npm:1.1.0": version: 1.1.0 resolution: "@antfu/install-pkg@npm:1.1.0" @@ -358,6 +374,17 @@ __metadata: languageName: node linkType: hard +"@babel/parser@npm:^7.20.0": + version: 7.29.7 + resolution: "@babel/parser@npm:7.29.7" + dependencies: + "@babel/types": ^7.29.7 + bin: + parser: ./bin/babel-parser.js + checksum: 56f4c32a371004d3becd0a960a85a3bba4ec4df73d5e202aa3fe6473328b243162c6be9a510be1c12ed1825f5ce9ff1ea5cc357298631e8acf2e5b8da9f5a961 + languageName: node + linkType: hard + "@babel/plugin-bugfix-firefox-class-in-computed-class-key@npm:^7.25.3, @babel/plugin-bugfix-firefox-class-in-computed-class-key@npm:^7.28.5": version: 7.28.5 resolution: "@babel/plugin-bugfix-firefox-class-in-computed-class-key@npm:7.28.5" @@ -2113,6 +2140,20 @@ __metadata: languageName: unknown linkType: soft +"@datadog/mobile-react-native-vega@workspace:packages/react-native-vega": + version: 0.0.0-use.local + resolution: "@datadog/mobile-react-native-vega@workspace:packages/react-native-vega" + dependencies: + "@amazon-devices/keplerscript-turbomodule-api": 1.2.5 + react-native-builder-bob: 0.26.0 + peerDependencies: + "@amazon-devices/react-native-kepler": ^2.0.0 + "@datadog/mobile-react-native": 3.13.0 + react: ">=16.13.1" + react-native: ">=0.63.4 <1.0" + languageName: unknown + linkType: soft + "@datadog/mobile-react-native-webview@workspace:packages/react-native-webview": version: 0.0.0-use.local resolution: "@datadog/mobile-react-native-webview@workspace:packages/react-native-webview" @@ -9767,6 +9808,13 @@ __metadata: languageName: node linkType: hard +"flow-parser@npm:^0.206.0": + version: 0.206.0 + resolution: "flow-parser@npm:0.206.0" + checksum: 1b87d87b59815b09852a6981543ad222da7f4d0e0c26702f9d5e0065174f5f64d2563db76d07a487c6b55e1979344e3845ac42929db70f77a82e8c9171a62a86 + languageName: node + linkType: hard + "follow-redirects@npm:1.16.0": version: 1.16.0 resolution: "follow-redirects@npm:1.16.0" @@ -18739,6 +18787,21 @@ __metadata: languageName: node linkType: hard +"yargs@npm:^17.7.2": + version: 17.7.3 + resolution: "yargs@npm:17.7.3" + dependencies: + cliui: ^8.0.1 + escalade: ^3.1.1 + get-caller-file: ^2.0.5 + require-directory: ^2.1.1 + string-width: ^4.2.3 + y18n: ^5.0.5 + yargs-parser: ^21.1.1 + checksum: 16fb2d4866f04aaf74f206d3df843e7a80b58a26fda47af29be51b27564c19966b1674c3acf679a26fdfa8a7e4b1b442a63cdab5db8cd3c57db7912f4473e343 + languageName: node + linkType: hard + "yazl@npm:^2.5.1": version: 2.5.1 resolution: "yazl@npm:2.5.1"