From b7f9bc1bbf78f48d320c42b105c0b8adb46561fc Mon Sep 17 00:00:00 2001 From: "carlos.nogueira" Date: Fri, 13 Nov 2026 16:50:54 +0000 Subject: [PATCH 1/5] Ignore local Vega app and native build artifacts --- .eslintignore | 2 ++ .gitignore | 11 +++++++++++ 2 files changed, 13 insertions(+) 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 # From 4fb3cbe535d3e00a70f938025bab268709fcb004 Mon Sep 17 00:00:00 2001 From: "carlos.nogueira" Date: Fri, 13 Nov 2026 16:51:08 +0000 Subject: [PATCH 2/5] Add private Vega native foundation and HTTP transport --- packages/react-native-vega/CMakeLists.txt | 90 +++++++++ packages/react-native-vega/README.md | 32 +++ .../__tests__/HttpProxy.test.ts | 189 ++++++++++++++++++ .../InternalResourceTracking.test.ts | 69 +++++++ .../__tests__/importSafety.test.ts | 32 +++ packages/react-native-vega/babel.config.js | 3 + .../react-native-vega/kepler/AutoLinkInit.cpp | 15 ++ .../turbo-modules/AttributeConverter.cpp | 69 +++++++ .../kepler/turbo-modules/AttributeConverter.h | 40 ++++ .../turbo-modules/DatadogGlobalState.cpp | 42 ++++ .../kepler/turbo-modules/DatadogGlobalState.h | 45 +++++ .../kepler/turbo-modules/DdSdk.cpp | 45 +++++ .../kepler/turbo-modules/DdSdk.h | 23 +++ .../kepler/turbo-modules/EnumParsers.cpp | 105 ++++++++++ .../kepler/turbo-modules/EnumParsers.h | 29 +++ .../kepler/turbo-modules/HttpJsProxy.cpp | 118 +++++++++++ .../kepler/turbo-modules/HttpJsProxy.h | 86 ++++++++ .../turbo-modules/generated/DdSdkSpec.cpp | 26 +++ .../turbo-modules/generated/DdSdkSpec.h | 42 ++++ .../turbo-modules/http_js_proxy_client.cpp | 55 +++++ .../kepler/turbo-modules/uuid_urandom.cpp | 37 ++++ packages/react-native-vega/package.json | 91 +++++++++ .../react-native-vega/react-native.config.js | 16 ++ packages/react-native-vega/src/HttpProxy.ts | 88 ++++++++ .../src/InternalResourceTracking.ts | 100 +++++++++ packages/react-native-vega/src/index.ts | 7 + .../src/turbo-modules/NativeDdSdk.ts | 16 ++ .../react-native-vega/tests/CMakeLists.txt | 18 ++ .../tests/HttpJsProxyTest.cpp | 112 +++++++++++ .../react-native-vega/tsconfig.build.json | 4 + packages/react-native-vega/tsconfig.json | 4 + yarn.lock | 62 ++++++ 32 files changed, 1710 insertions(+) create mode 100644 packages/react-native-vega/CMakeLists.txt create mode 100644 packages/react-native-vega/README.md create mode 100644 packages/react-native-vega/__tests__/HttpProxy.test.ts create mode 100644 packages/react-native-vega/__tests__/InternalResourceTracking.test.ts create mode 100644 packages/react-native-vega/__tests__/importSafety.test.ts create mode 100644 packages/react-native-vega/babel.config.js create mode 100644 packages/react-native-vega/kepler/AutoLinkInit.cpp create mode 100644 packages/react-native-vega/kepler/turbo-modules/AttributeConverter.cpp create mode 100644 packages/react-native-vega/kepler/turbo-modules/AttributeConverter.h create mode 100644 packages/react-native-vega/kepler/turbo-modules/DatadogGlobalState.cpp create mode 100644 packages/react-native-vega/kepler/turbo-modules/DatadogGlobalState.h create mode 100644 packages/react-native-vega/kepler/turbo-modules/DdSdk.cpp create mode 100644 packages/react-native-vega/kepler/turbo-modules/DdSdk.h create mode 100644 packages/react-native-vega/kepler/turbo-modules/EnumParsers.cpp create mode 100644 packages/react-native-vega/kepler/turbo-modules/EnumParsers.h create mode 100644 packages/react-native-vega/kepler/turbo-modules/HttpJsProxy.cpp create mode 100644 packages/react-native-vega/kepler/turbo-modules/HttpJsProxy.h create mode 100644 packages/react-native-vega/kepler/turbo-modules/generated/DdSdkSpec.cpp create mode 100644 packages/react-native-vega/kepler/turbo-modules/generated/DdSdkSpec.h create mode 100644 packages/react-native-vega/kepler/turbo-modules/http_js_proxy_client.cpp create mode 100644 packages/react-native-vega/kepler/turbo-modules/uuid_urandom.cpp create mode 100644 packages/react-native-vega/package.json create mode 100644 packages/react-native-vega/react-native.config.js create mode 100644 packages/react-native-vega/src/HttpProxy.ts create mode 100644 packages/react-native-vega/src/InternalResourceTracking.ts create mode 100644 packages/react-native-vega/src/index.ts create mode 100644 packages/react-native-vega/src/turbo-modules/NativeDdSdk.ts create mode 100644 packages/react-native-vega/tests/CMakeLists.txt create mode 100644 packages/react-native-vega/tests/HttpJsProxyTest.cpp create mode 100644 packages/react-native-vega/tsconfig.build.json create mode 100644 packages/react-native-vega/tsconfig.json 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..d525555ee --- /dev/null +++ b/packages/react-native-vega/README.md @@ -0,0 +1,32 @@ +# 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. +Native modules are resolved on use, keeping package imports safe on other +platforms. + +Run the transport tests with: + +```sh +yarn workspace @datadog/mobile-react-native-vega test --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..98f87e5a5 --- /dev/null +++ b/packages/react-native-vega/__tests__/HttpProxy.test.ts @@ -0,0 +1,189 @@ +/* + * 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 { startHttpProxy } from '../src/HttpProxy'; +import { patchCoreRumResourceTracking } from '../src/InternalResourceTracking'; +import { getNativeDdSdk } from '../src/turbo-modules/NativeDdSdk'; + +const mockAddListener = jest.fn(); +const mockRemove = jest.fn(); +const mockHttpResponse = jest.fn(); +const mockStartHttpProxy = 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 + })) +})); + +interface HttpRequestEvent { + requestId: string; + url: string; + headers: string; + body: string; +} + +describe('HttpProxy', () => { + let requestListener: (event: HttpRequestEvent) => Promise; + let fetchMock: jest.Mock; + + 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 () => { + 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: '{}' + } + ); + expect(mockHttpResponse).toHaveBeenCalledWith('request-id', 202); + }); + + it('suppresses the matching resource while the SDK upload is active', async () => { + let resolveFetch: (response: { status: number }) => void = () => + undefined; + fetchMock.mockReturnValue( + new Promise(resolve => { + resolveFetch = resolve; + }) + ); + await startHttpProxy(); + + const url = 'https://browser-intake-datadoghq.com/api/v2/rum'; + const request = requestListener({ + requestId: 'request-id', + url, + headers: '', + body: '{}' + }); + const startResource = jest.fn().mockResolvedValue(undefined); + const stopResource = jest.fn().mockResolvedValue(undefined); + const rum = { startResource, stopResource }; + patchCoreRumResourceTracking(rum); + + await rum.startResource('sdk-resource', 'POST', url); + resolveFetch({ status: 202 }); + await request; + await rum.stopResource('sdk-resource', 202, 'xhr'); + + expect(startResource).not.toHaveBeenCalled(); + expect(stopResource).not.toHaveBeenCalled(); + }); + + it('stops identifying a URL as internal when an upload fails', async () => { + fetchMock.mockRejectedValue(new Error('network failure')); + await startHttpProxy(); + + await requestListener({ + requestId: 'request-id', + url: 'https://proxy.example.com/upload', + headers: '', + body: '{}' + }); + + const startResource = jest.fn().mockResolvedValue(undefined); + const rum = { + startResource, + stopResource: jest.fn().mockResolvedValue(undefined) + }; + patchCoreRumResourceTracking(rum); + await rum.startResource( + 'customer-resource', + 'POST', + 'https://proxy.example.com/upload' + ); + + expect(startResource).toHaveBeenCalled(); + expect(mockHttpResponse).toHaveBeenCalledWith('request-id', 0); + }); + + it('removes the request listener when stopped', async () => { + const stop = await startHttpProxy(); + stop(); + expect(mockRemove).toHaveBeenCalledTimes(1); + }); + + it('contains failures when returning a response to native', async () => { + mockHttpResponse.mockRejectedValueOnce(new Error('native unavailable')); + 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); + await expect(startHttpProxy()).resolves.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'); + }); + await expect(startHttpProxy()).resolves.toEqual(expect.any(Function)); + expect(mockAddListener).not.toHaveBeenCalled(); + }); + + it('contains listener registration failures', async () => { + mockAddListener.mockImplementationOnce(() => { + throw new Error('event emitter unavailable'); + }); + await expect(startHttpProxy()).resolves.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(); + }); + await startHttpProxy(); + expect(mockStartHttpProxy).toHaveBeenCalledTimes(1); + }); + + it('removes the listener if the native handshake fails', async () => { + mockStartHttpProxy.mockRejectedValueOnce( + new Error('native transport unavailable') + ); + await expect(startHttpProxy()).resolves.toEqual(expect.any(Function)); + expect(mockRemove).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/react-native-vega/__tests__/InternalResourceTracking.test.ts b/packages/react-native-vega/__tests__/InternalResourceTracking.test.ts new file mode 100644 index 000000000..762ac03c6 --- /dev/null +++ b/packages/react-native-vega/__tests__/InternalResourceTracking.test.ts @@ -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. + */ + +import { + patchCoreRumResourceTracking, + trackInternalResource +} from '../src/InternalResourceTracking'; + +describe('InternalResourceTracking', () => { + it('suppresses SDK-owned resources by exact URL and resource key', async () => { + const startResource = jest.fn().mockResolvedValue(undefined); + const stopResource = jest.fn().mockResolvedValue(undefined); + const rum = { startResource, stopResource }; + patchCoreRumResourceTracking(rum); + + const url = 'https://proxy.example.com/upload'; + const stopTracking = trackInternalResource(url); + + await rum.startResource('sdk-resource', 'POST', url); + await rum.stopResource('sdk-resource', 202, 'xhr'); + await rum.startResource( + 'customer-resource', + 'GET', + 'https://api.example.com/data' + ); + await rum.stopResource('customer-resource', 200, 'xhr'); + + stopTracking(); + + expect(startResource).toHaveBeenCalledTimes(1); + expect(startResource).toHaveBeenCalledWith( + 'customer-resource', + 'GET', + 'https://api.example.com/data', + undefined, + undefined + ); + expect(stopResource).toHaveBeenCalledTimes(1); + expect(stopResource).toHaveBeenCalledWith( + 'customer-resource', + 200, + 'xhr', + undefined, + undefined, + undefined, + undefined + ); + }); + + it('forwards the same URL after the SDK upload completes', async () => { + const startResource = jest.fn().mockResolvedValue(undefined); + const rum = { + startResource, + stopResource: jest.fn().mockResolvedValue(undefined) + }; + patchCoreRumResourceTracking(rum); + + const url = 'https://browser-intake-datadoghq.com/api/v2/rum'; + const stopTracking = trackInternalResource(url); + stopTracking(); + + await rum.startResource('customer-resource', 'POST', url); + + expect(startResource).toHaveBeenCalled(); + }); +}); 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..b07b121ac --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/DdSdk.cpp @@ -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. + +#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::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..566f0d44e --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/DdSdk.h @@ -0,0 +1,23 @@ +// Unless explicitly stated otherwise all files in this repository are licensed +// under the Apache License Version 2.0. +// +// This product includes software developed at Datadog +// (https://www.datadoghq.com/). Copyright 2016-Present Datadog, Inc. + +#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 + 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..784769e39 --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/HttpJsProxy.cpp @@ -0,0 +1,118 @@ +// 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); +} + +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(); + { + std::lock_guard lock(mutex_); + requestId = std::to_string(nextRequestId_++); + pending_[requestId] = pending; + } + + // 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_) { + std::lock_guard lock(mutex_); + pending_.erase(requestId); + return {false, false, 0}; + } + 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 + } + 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..431ab604f --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/HttpJsProxy.h @@ -0,0 +1,86 @@ +// 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; + 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; + + 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..c392a75e3 --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/generated/DdSdkSpec.cpp @@ -0,0 +1,26 @@ +/** + * 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("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..4be134f44 --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/generated/DdSdkSpec.h @@ -0,0 +1,42 @@ +/** + * 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 + 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..2b98c02bc --- /dev/null +++ b/packages/react-native-vega/package.json @@ -0,0 +1,91 @@ +{ + "name": "@datadog/mobile-react-native-vega", + "version": "3.11.0-vega.0", + "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": "public" + }, + "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", + "react": ">=16.13.1", + "react-native": ">=0.63.4 <1.0" + }, + "devDependencies": { + "react-native-builder-bob": "0.26.0" + }, + "jest": { + "preset": "react-native", + "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..6fc29a43e --- /dev/null +++ b/packages/react-native-vega/src/HttpProxy.ts @@ -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. + */ + +import { NativeEventEmitter } from 'react-native'; + +import { trackInternalResource } from './InternalResourceTracking'; +import { getNativeDdSdk } from './turbo-modules/NativeDdSdk'; + +/** + * Listens for HTTP request events emitted by the C++ SDK's upload thread + * and forwards them using fetch(). Sends the HTTP status code back to C++ + * via DdSdk.httpResponse(). + * + * Await startHttpProxy() before starting native uploads so the listener is ready. + */ +export async function startHttpProxy(): Promise<() => void> { + let cleanup = () => undefined as void; + try { + const nativeSdk = getNativeDdSdk(); + if (!nativeSdk) { + return () => undefined; + } + const emitter = new NativeEventEmitter(); + + const subscription = emitter.addListener( + 'ddHttpRequest', + async (event: { + requestId: string; + url: string; + headers: string; + body: string; + }) => { + let statusCode = 0; + try { + // Parse headers from wire format ("Key: Value\nKey2: Value2\n") + const headerLines = event.headers + .split('\n') + .filter(line => line.includes(':')); + const headersInit: Record = {}; + for (const line of headerLines) { + const colonIdx = line.indexOf(':'); + const key = line.substring(0, colonIdx).trim(); + const value = line.substring(colonIdx + 1).trim(); + headersInit[key] = value; + } + + const stopTracking = trackInternalResource(event.url); + try { + const response = await fetch(event.url, { + method: 'POST', + headers: headersInit, + body: event.body + }); + statusCode = response.status; + } finally { + stopTracking(); + } + } catch (error) { + // Network errors are reported as status 0 so C++ treats them as retryable. + statusCode = 0; + } + + try { + await nativeSdk.httpResponse(event.requestId, statusCode); + } catch (error) { + // If httpResponse fails, the C++ side times out and retries. + } + } + ); + + cleanup = () => { + try { + subscription.remove(); + } catch { + // Cleanup must not interrupt the host app's teardown. + } + }; + await nativeSdk.startHttpProxy(); + return cleanup; + } catch { + // Native transport can be unavailable while the host app is starting. + cleanup(); + return () => undefined; + } +} diff --git a/packages/react-native-vega/src/InternalResourceTracking.ts b/packages/react-native-vega/src/InternalResourceTracking.ts new file mode 100644 index 000000000..4486a0916 --- /dev/null +++ b/packages/react-native-vega/src/InternalResourceTracking.ts @@ -0,0 +1,100 @@ +/* + * 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. + */ + +interface CoreRumResourceBridge { + startResource( + key: string, + method: string, + url: string, + context?: object, + timestampMs?: number + ): Promise; + stopResource( + key: string, + statusCode: number, + kind: string, + size?: number, + context?: object, + timestampMs?: number, + resourceContext?: XMLHttpRequest + ): Promise; +} + +const activeUrls = new Map(); +const ignoredResourceKeys = new Set(); +const patchedRumInstances = new WeakSet(); + +export const trackInternalResource = (url: string): (() => void) => { + activeUrls.set(url, (activeUrls.get(url) ?? 0) + 1); + let isActive = true; + + return () => { + if (!isActive) { + return; + } + isActive = false; + + const activeCount = activeUrls.get(url) ?? 0; + if (activeCount <= 1) { + activeUrls.delete(url); + } else { + activeUrls.set(url, activeCount - 1); + } + }; +}; + +export const patchCoreRumResourceTracking = ( + rum: CoreRumResourceBridge +): void => { + if (patchedRumInstances.has(rum)) { + return; + } + patchedRumInstances.add(rum); + + const originalStartResource = rum.startResource; + const originalStopResource = rum.stopResource; + + rum.startResource = (key, method, url, context, timestampMs) => { + if (activeUrls.has(url)) { + ignoredResourceKeys.add(key); + return Promise.resolve(); + } + + return originalStartResource.call( + rum, + key, + method, + url, + context, + timestampMs + ); + }; + + rum.stopResource = ( + key, + statusCode, + kind, + size, + context, + timestampMs, + resourceContext + ) => { + if (ignoredResourceKeys.delete(key)) { + return Promise.resolve(); + } + + return originalStopResource.call( + rum, + key, + statusCode, + kind, + size, + context, + timestampMs, + resourceContext + ); + }; +}; 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..c133b70b8 --- /dev/null +++ b/packages/react-native-vega/src/turbo-modules/NativeDdSdk.ts @@ -0,0 +1,16 @@ +/* + * 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; + 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..293385f00 --- /dev/null +++ b/packages/react-native-vega/tests/HttpJsProxyTest.cpp @@ -0,0 +1,112 @@ +// 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({}); + assert(!bridge.sendRequest("url", "", emptyBody).success); + + 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); +} 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/yarn.lock b/yarn.lock index 4105777dc..8ee7281c5 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,19 @@ __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 + 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 +9807,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 +18786,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" From b16f0b6c6319c45e279ae76af860293b90324c6a Mon Sep 17 00:00:00 2001 From: "carlos.nogueira" Date: Mon, 23 Nov 2026 15:41:10 +0000 Subject: [PATCH 3/5] Fix Vega upload lifecycle, tracking, and packaging --- packages/core/internal/package.json | 3 +- packages/core/package.json | 3 + packages/core/src/internal.ts | 2 + .../requestProxy/FetchProxy/FetchProxy.ts | 10 +- .../FetchProxy/__tests__/FetchProxy.test.ts | 24 +++ .../XHRProxy/__tests__/XHRProxy.test.ts | 27 +++ .../requestProxy/common/FetchProxyState.ts | 14 ++ packages/react-native-vega/README.md | 10 +- .../__tests__/HttpProxy.test.ts | 192 +++++++++++++----- .../InternalResourceTracking.test.ts | 69 ------- .../kepler/turbo-modules/DdSdk.cpp | 7 + .../kepler/turbo-modules/DdSdk.h | 1 + .../kepler/turbo-modules/HttpJsProxy.cpp | 59 ++++-- .../kepler/turbo-modules/HttpJsProxy.h | 2 + .../turbo-modules/generated/DdSdkSpec.cpp | 1 + .../turbo-modules/generated/DdSdkSpec.h | 1 + packages/react-native-vega/package.json | 8 +- packages/react-native-vega/src/HttpProxy.ts | 173 ++++++++++------ .../src/InternalResourceTracking.ts | 100 --------- .../src/turbo-modules/NativeDdSdk.ts | 1 + .../tests/HttpJsProxyTest.cpp | 37 ++++ update-version.sh | 13 ++ yarn.lock | 1 + 23 files changed, 448 insertions(+), 310 deletions(-) delete mode 100644 packages/react-native-vega/__tests__/InternalResourceTracking.test.ts delete mode 100644 packages/react-native-vega/src/InternalResourceTracking.ts diff --git a/packages/core/internal/package.json b/packages/core/internal/package.json index 72d3e86c4..cc05c31cf 100644 --- a/packages/core/internal/package.json +++ b/packages/core/internal/package.json @@ -1,6 +1,7 @@ { "private": true, + "react-native": "../src/internal", "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..4169f890e 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", @@ -40,11 +41,13 @@ "module": "lib/module/index", "exports": { ".": { + "react-native": "./src/index.tsx", "import": "./lib/module/index.js", "require": "./lib/commonjs/index.js", "types": "./lib/typescript/index.d.ts" }, "./internal": { + "react-native": "./src/internal.ts", "import": "./lib/module/internal.js", "require": "./lib/commonjs/internal.js", "types": "./lib/typescript/internal.d.ts" diff --git a/packages/core/src/internal.ts b/packages/core/src/internal.ts index e13a3bbfb..60e9b420e 100644 --- a/packages/core/src/internal.ts +++ b/packages/core/src/internal.ts @@ -30,3 +30,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..26a1de0c4 100644 --- a/packages/core/src/rum/instrumentation/resourceTracking/requestProxy/common/FetchProxyState.ts +++ b/packages/core/src/rum/instrumentation/resourceTracking/requestProxy/common/FetchProxyState.ts @@ -5,6 +5,7 @@ */ let fetchProxyCallDepth = 0; +let resourceTrackingDisabledDepth = 0; /** * Calls the original Fetch implementation while marking its synchronous work. @@ -23,3 +24,16 @@ export const callOriginalFetch = (callback: () => T): T => { export const isRunningWithinFetchProxy = (): boolean => { return fetchProxyCallDepth > 0; }; + +/** Excludes only the requests started synchronously by this callback. */ +export const callWithoutResourceTracking = (callback: () => T): T => { + resourceTrackingDisabledDepth += 1; + try { + return callOriginalFetch(callback); + } finally { + resourceTrackingDisabledDepth -= 1; + } +}; + +export const isResourceTrackingDisabled = (): boolean => + resourceTrackingDisabledDepth > 0; diff --git a/packages/react-native-vega/README.md b/packages/react-native-vega/README.md index d525555ee..2275c49c7 100644 --- a/packages/react-native-vega/README.md +++ b/packages/react-native-vega/README.md @@ -8,13 +8,19 @@ 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. 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. +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 workspace @datadog/mobile-react-native-vega test --runInBand --watchman=false +yarn test --runTestsByPath packages/react-native-vega/__tests__/*.test.ts --runInBand --watchman=false yarn workspace @datadog/mobile-react-native-vega test:native ``` diff --git a/packages/react-native-vega/__tests__/HttpProxy.test.ts b/packages/react-native-vega/__tests__/HttpProxy.test.ts index 98f87e5a5..fac8c7855 100644 --- a/packages/react-native-vega/__tests__/HttpProxy.test.ts +++ b/packages/react-native-vega/__tests__/HttpProxy.test.ts @@ -4,14 +4,16 @@ * 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 { patchCoreRumResourceTracking } from '../src/InternalResourceTracking'; 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, @@ -23,7 +25,8 @@ jest.mock('react-native/Libraries/EventEmitter/NativeEventEmitter', () => ({ jest.mock('../src/turbo-modules/NativeDdSdk', () => ({ getNativeDdSdk: jest.fn(() => ({ httpResponse: mockHttpResponse, - startHttpProxy: mockStartHttpProxy + startHttpProxy: mockStartHttpProxy, + stopHttpProxy: mockStopHttpProxy })) })); @@ -37,6 +40,14 @@ interface HttpRequestEvent { 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(); @@ -49,7 +60,7 @@ describe('HttpProxy', () => { }); it('forwards an SDK upload without adding private HTTP headers', async () => { - await startHttpProxy(); + stop = await startHttpProxy(); await requestListener({ requestId: 'request-id', @@ -63,79 +74,150 @@ describe('HttpProxy', () => { { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: '{}' + body: '{}', + signal: expect.any(Object) } ); expect(mockHttpResponse).toHaveBeenCalledWith('request-id', 202); }); - it('suppresses the matching resource while the SDK upload is active', async () => { - let resolveFetch: (response: { status: number }) => void = () => - undefined; - fetchMock.mockReturnValue( + 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 => { - resolveFetch = resolve; + resolveUpload = resolve; }) ); - await startHttpProxy(); - - const url = 'https://browser-intake-datadoghq.com/api/v2/rum'; - const request = requestListener({ - requestId: 'request-id', - url, - headers: '', - body: '{}' + proxy.onTrackingStart({ + tracingSamplingRate: 100, + firstPartyHostsRegexMap: [] }); - const startResource = jest.fn().mockResolvedValue(undefined); - const stopResource = jest.fn().mockResolvedValue(undefined); - const rum = { startResource, stopResource }; - patchCoreRumResourceTracking(rum); - - await rum.startResource('sdk-resource', 'POST', url); - resolveFetch({ status: 202 }); - await request; - await rum.stopResource('sdk-resource', 202, 'xhr'); - - expect(startResource).not.toHaveBeenCalled(); - expect(stopResource).not.toHaveBeenCalled(); + 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('stops identifying a URL as internal when an upload fails', async () => { + it('reports network failures as retryable', async () => { fetchMock.mockRejectedValue(new Error('network failure')); - await startHttpProxy(); - + stop = await startHttpProxy(); await requestListener({ requestId: 'request-id', url: 'https://proxy.example.com/upload', headers: '', body: '{}' }); - - const startResource = jest.fn().mockResolvedValue(undefined); - const rum = { - startResource, - stopResource: jest.fn().mockResolvedValue(undefined) - }; - patchCoreRumResourceTracking(rum); - await rum.startResource( - 'customer-resource', - 'POST', - 'https://proxy.example.com/upload' - ); - - expect(startResource).toHaveBeenCalled(); expect(mockHttpResponse).toHaveBeenCalledWith('request-id', 0); }); it('removes the request listener when stopped', async () => { - const stop = await startHttpProxy(); + 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('cancels in-flight fetches and ignores late responses after 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; stop(); + expect(signal.aborted).toBe(true); + resolveFetch({ status: 202 }); + await request; + expect(mockHttpResponse).not.toHaveBeenCalled(); + }); + + 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')); - await startHttpProxy(); + stop = await startHttpProxy(); await expect( requestListener({ requestId: 'failed-response', @@ -148,7 +230,8 @@ describe('HttpProxy', () => { it('does not start a proxy when the native module is unavailable', async () => { (getNativeDdSdk as jest.Mock).mockReturnValueOnce(null); - await expect(startHttpProxy()).resolves.toEqual(expect.any(Function)); + stop = await startHttpProxy(); + expect(stop).toEqual(expect.any(Function)); expect(mockAddListener).not.toHaveBeenCalled(); }); @@ -156,7 +239,8 @@ describe('HttpProxy', () => { (getNativeDdSdk as jest.Mock).mockImplementationOnce(() => { throw new Error('native module failed to load'); }); - await expect(startHttpProxy()).resolves.toEqual(expect.any(Function)); + stop = await startHttpProxy(); + expect(stop).toEqual(expect.any(Function)); expect(mockAddListener).not.toHaveBeenCalled(); }); @@ -164,7 +248,8 @@ describe('HttpProxy', () => { mockAddListener.mockImplementationOnce(() => { throw new Error('event emitter unavailable'); }); - await expect(startHttpProxy()).resolves.toEqual(expect.any(Function)); + stop = await startHttpProxy(); + expect(stop).toEqual(expect.any(Function)); }); it('registers the JS listener before enabling native uploads', async () => { @@ -175,7 +260,7 @@ describe('HttpProxy', () => { ); return Promise.resolve(); }); - await startHttpProxy(); + stop = await startHttpProxy(); expect(mockStartHttpProxy).toHaveBeenCalledTimes(1); }); @@ -183,7 +268,8 @@ describe('HttpProxy', () => { mockStartHttpProxy.mockRejectedValueOnce( new Error('native transport unavailable') ); - await expect(startHttpProxy()).resolves.toEqual(expect.any(Function)); + stop = await startHttpProxy(); + expect(stop).toEqual(expect.any(Function)); expect(mockRemove).toHaveBeenCalledTimes(1); }); }); diff --git a/packages/react-native-vega/__tests__/InternalResourceTracking.test.ts b/packages/react-native-vega/__tests__/InternalResourceTracking.test.ts deleted file mode 100644 index 762ac03c6..000000000 --- a/packages/react-native-vega/__tests__/InternalResourceTracking.test.ts +++ /dev/null @@ -1,69 +0,0 @@ -/* - * 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 { - patchCoreRumResourceTracking, - trackInternalResource -} from '../src/InternalResourceTracking'; - -describe('InternalResourceTracking', () => { - it('suppresses SDK-owned resources by exact URL and resource key', async () => { - const startResource = jest.fn().mockResolvedValue(undefined); - const stopResource = jest.fn().mockResolvedValue(undefined); - const rum = { startResource, stopResource }; - patchCoreRumResourceTracking(rum); - - const url = 'https://proxy.example.com/upload'; - const stopTracking = trackInternalResource(url); - - await rum.startResource('sdk-resource', 'POST', url); - await rum.stopResource('sdk-resource', 202, 'xhr'); - await rum.startResource( - 'customer-resource', - 'GET', - 'https://api.example.com/data' - ); - await rum.stopResource('customer-resource', 200, 'xhr'); - - stopTracking(); - - expect(startResource).toHaveBeenCalledTimes(1); - expect(startResource).toHaveBeenCalledWith( - 'customer-resource', - 'GET', - 'https://api.example.com/data', - undefined, - undefined - ); - expect(stopResource).toHaveBeenCalledTimes(1); - expect(stopResource).toHaveBeenCalledWith( - 'customer-resource', - 200, - 'xhr', - undefined, - undefined, - undefined, - undefined - ); - }); - - it('forwards the same URL after the SDK upload completes', async () => { - const startResource = jest.fn().mockResolvedValue(undefined); - const rum = { - startResource, - stopResource: jest.fn().mockResolvedValue(undefined) - }; - patchCoreRumResourceTracking(rum); - - const url = 'https://browser-intake-datadoghq.com/api/v2/rum'; - const stopTracking = trackInternalResource(url); - stopTracking(); - - await rum.startResource('customer-resource', 'POST', url); - - expect(startResource).toHaveBeenCalled(); - }); -}); diff --git a/packages/react-native-vega/kepler/turbo-modules/DdSdk.cpp b/packages/react-native-vega/kepler/turbo-modules/DdSdk.cpp index b07b121ac..d8b43b47f 100644 --- a/packages/react-native-vega/kepler/turbo-modules/DdSdk.cpp +++ b/packages/react-native-vega/kepler/turbo-modules/DdSdk.cpp @@ -33,6 +33,13 @@ 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) { diff --git a/packages/react-native-vega/kepler/turbo-modules/DdSdk.h b/packages/react-native-vega/kepler/turbo-modules/DdSdk.h index 566f0d44e..687793672 100644 --- a/packages/react-native-vega/kepler/turbo-modules/DdSdk.h +++ b/packages/react-native-vega/kepler/turbo-modules/DdSdk.h @@ -16,6 +16,7 @@ class DdSdk : public DdSdkSpec { ~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; }; diff --git a/packages/react-native-vega/kepler/turbo-modules/HttpJsProxy.cpp b/packages/react-native-vega/kepler/turbo-modules/HttpJsProxy.cpp index 784769e39..4edd02016 100644 --- a/packages/react-native-vega/kepler/turbo-modules/HttpJsProxy.cpp +++ b/packages/react-native-vega/kepler/turbo-modules/HttpJsProxy.cpp @@ -14,7 +14,7 @@ namespace datadog_rn_vega { static const size_t BODY_WRITER_EOF = 0; static const size_t BODY_WRITER_ABORT = 0xffffffff; -HttpRequestBridge& HttpRequestBridge::getInstance() { +HttpRequestBridge &HttpRequestBridge::getInstance() { static HttpRequestBridge instance; return instance; } @@ -22,17 +22,35 @@ HttpRequestBridge& HttpRequestBridge::getInstance() { 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) { +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_EOF) + break; if (n == BODY_WRITER_ABORT || n > chunk.size()) { return {false, false, 0}; } @@ -42,21 +60,19 @@ HttpProxyResult HttpRequestBridge::sendRequest( // Create a pending request with unique ID std::string requestId; auto pending = std::make_shared(); - { - std::lock_guard lock(mutex_); - requestId = std::to_string(nextRequestId_++); - pending_[requestId] = pending; - } - // 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. + // module is destroyed. Never hold this lock while waiting for a JS + // response. { std::lock_guard emitterLock(emitterMutex_); if (!emitFn_) { - std::lock_guard lock(mutex_); - pending_.erase(requestId); return {false, false, 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 (...) { @@ -70,14 +86,16 @@ HttpProxyResult HttpRequestBridge::sendRequest( int statusCode; { std::unique_lock lock(pending->mutex); - bool ok = pending->cv.wait_for( - lock, std::chrono::seconds(30), - [&] { return pending->completed; }); + 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 + return {false, true, 0}; // timeout → retryable + } + if (pending->cancelled) { + return {false, false, 0}; } statusCode = pending->status_code; } @@ -88,12 +106,13 @@ HttpProxyResult HttpRequestBridge::sendRequest( } if (statusCode == 0) { - return {false, true, 0}; // fetch() failed → retryable + return {false, true, 0}; // fetch() failed → retryable } return {true, false, statusCode}; } -void HttpRequestBridge::onResponse(const std::string& requestId, int statusCode) { +void HttpRequestBridge::onResponse(const std::string &requestId, + int statusCode) { std::shared_ptr pending; { std::lock_guard lock(mutex_); @@ -115,4 +134,4 @@ void HttpRequestBridge::onResponse(const std::string& requestId, int statusCode) pending->cv.notify_one(); } -} // namespace datadog_rn_vega +} // 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 index 431ab604f..4126ee7da 100644 --- a/packages/react-native-vega/kepler/turbo-modules/HttpJsProxy.h +++ b/packages/react-native-vega/kepler/turbo-modules/HttpJsProxy.h @@ -23,6 +23,7 @@ struct PendingHttpRequest { std::mutex mutex; std::condition_variable cv; bool completed = false; + bool cancelled = false; int status_code = 0; }; @@ -58,6 +59,7 @@ class HttpRequestBridge { */ using BodyWriter = std::function; + // Replacing or clearing the emitter also cancels its pending requests. void setEmitFunction(EmitFn fn); /** diff --git a/packages/react-native-vega/kepler/turbo-modules/generated/DdSdkSpec.cpp b/packages/react-native-vega/kepler/turbo-modules/generated/DdSdkSpec.cpp index c392a75e3..caf5a13bc 100644 --- a/packages/react-native-vega/kepler/turbo-modules/generated/DdSdkSpec.cpp +++ b/packages/react-native-vega/kepler/turbo-modules/generated/DdSdkSpec.cpp @@ -20,6 +20,7 @@ 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); } diff --git a/packages/react-native-vega/kepler/turbo-modules/generated/DdSdkSpec.h b/packages/react-native-vega/kepler/turbo-modules/generated/DdSdkSpec.h index 4be134f44..905f5f57c 100644 --- a/packages/react-native-vega/kepler/turbo-modules/generated/DdSdkSpec.h +++ b/packages/react-native-vega/kepler/turbo-modules/generated/DdSdkSpec.h @@ -35,6 +35,7 @@ class DdSdkSpec : public com::amazon::kepler::turbomodule::KeplerTurboModule { &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; }; diff --git a/packages/react-native-vega/package.json b/packages/react-native-vega/package.json index 2b98c02bc..13d5ae47f 100644 --- a/packages/react-native-vega/package.json +++ b/packages/react-native-vega/package.json @@ -1,6 +1,6 @@ { "name": "@datadog/mobile-react-native-vega", - "version": "3.11.0-vega.0", + "version": "3.13.0-beta", "private": true, "description": "Datadog native bridge for Amazon Vega SDK apps", "keywords": [ @@ -38,7 +38,7 @@ "source": "src/index", "module": "lib/module/index", "publishConfig": { - "access": "public" + "access": "restricted" }, "scripts": { "test": "jest", @@ -52,6 +52,7 @@ }, "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" }, @@ -60,6 +61,9 @@ }, "jest": { "preset": "react-native", + "moduleNameMapper": { + "^@datadog/mobile-react-native/internal$": "/../core/src/internal.ts" + }, "modulePathIgnorePatterns": [ "/lib/" ], diff --git a/packages/react-native-vega/src/HttpProxy.ts b/packages/react-native-vega/src/HttpProxy.ts index 6fc29a43e..2e80838b6 100644 --- a/packages/react-native-vega/src/HttpProxy.ts +++ b/packages/react-native-vega/src/HttpProxy.ts @@ -4,85 +4,134 @@ * Copyright 2016-Present Datadog, Inc. */ +import { callWithoutResourceTracking } from '@datadog/mobile-react-native/internal'; import { NativeEventEmitter } from 'react-native'; -import { trackInternalResource } from './InternalResourceTracking'; +import type { DdSdk } from './turbo-modules/NativeDdSdk'; import { getNativeDdSdk } from './turbo-modules/NativeDdSdk'; +let activeCleanup: (() => void) | undefined; +let operations = Promise.resolve(); + +const enqueue = (operation: () => Promise): Promise => { + const result = operations.then(operation); + operations = result.catch(() => undefined); + return result; +}; + /** - * Listens for HTTP request events emitted by the C++ SDK's upload thread - * and forwards them using fetch(). Sends the HTTP status code back to C++ - * via DdSdk.httpResponse(). - * - * Await startHttpProxy() before starting native uploads so the listener is ready. + * 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> { - let cleanup = () => undefined as void; - try { - const nativeSdk = getNativeDdSdk(); - if (!nativeSdk) { - return () => undefined; + activeCleanup?.(); + let active = true; + let nativeSdk: DdSdk | null = null; + let subscription: { remove(): void } | undefined; + const requests = new Set(); + + const cleanup = () => { + if (!active) { + return; + } + active = false; + if (activeCleanup === cleanup) { + 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. } - const emitter = new NativeEventEmitter(); + requests.forEach(request => { + try { + request.abort(); + } catch { + // Some Fetch implementations do not support cancellation. + } + }); + requests.clear(); + }; + activeCleanup = cleanup; - const subscription = emitter.addListener( - 'ddHttpRequest', - async (event: { - requestId: string; - url: string; - headers: string; - body: string; - }) => { - let statusCode = 0; - try { - // Parse headers from wire format ("Key: Value\nKey2: Value2\n") - const headerLines = event.headers - .split('\n') - .filter(line => line.includes(':')); - const headersInit: Record = {}; - for (const line of headerLines) { - const colonIdx = line.indexOf(':'); - const key = line.substring(0, colonIdx).trim(); - const value = line.substring(colonIdx + 1).trim(); - headersInit[key] = value; + 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; } - - const stopTracking = trackInternalResource(event.url); + let statusCode = 0; + let controller: AbortController | undefined; try { - const response = await fetch(event.url, { - method: 'POST', - headers: headersInit, - body: event.body + 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(); + } }); + if (typeof AbortController !== 'undefined') { + controller = new AbortController(); + requests.add(controller); + } + const response = await callWithoutResourceTracking(() => + fetch(event.url, { + method: 'POST', + headers, + body: event.body, + ...(controller + ? { signal: controller.signal } + : {}) + }) + ); statusCode = response.status; + } catch { + // Status 0 makes network failures retryable in native. } finally { - stopTracking(); + if (controller) { + requests.delete(controller); + } + } + if (active) { + try { + await sdk.httpResponse(event.requestId, statusCode); + } catch { + // Native times out or teardown cancels the waiter. + } } - } catch (error) { - // Network errors are reported as status 0 so C++ treats them as retryable. - statusCode = 0; - } - - try { - await nativeSdk.httpResponse(event.requestId, statusCode); - } catch (error) { - // If httpResponse fails, the C++ side times out and retries. } - } - ); - - cleanup = () => { - try { - subscription.remove(); - } catch { - // Cleanup must not interrupt the host app's teardown. - } - }; - await nativeSdk.startHttpProxy(); - return cleanup; + ); + await sdk.startHttpProxy(); + }); } catch { - // Native transport can be unavailable while the host app is starting. cleanup(); - return () => undefined; } + return cleanup; } diff --git a/packages/react-native-vega/src/InternalResourceTracking.ts b/packages/react-native-vega/src/InternalResourceTracking.ts deleted file mode 100644 index 4486a0916..000000000 --- a/packages/react-native-vega/src/InternalResourceTracking.ts +++ /dev/null @@ -1,100 +0,0 @@ -/* - * 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. - */ - -interface CoreRumResourceBridge { - startResource( - key: string, - method: string, - url: string, - context?: object, - timestampMs?: number - ): Promise; - stopResource( - key: string, - statusCode: number, - kind: string, - size?: number, - context?: object, - timestampMs?: number, - resourceContext?: XMLHttpRequest - ): Promise; -} - -const activeUrls = new Map(); -const ignoredResourceKeys = new Set(); -const patchedRumInstances = new WeakSet(); - -export const trackInternalResource = (url: string): (() => void) => { - activeUrls.set(url, (activeUrls.get(url) ?? 0) + 1); - let isActive = true; - - return () => { - if (!isActive) { - return; - } - isActive = false; - - const activeCount = activeUrls.get(url) ?? 0; - if (activeCount <= 1) { - activeUrls.delete(url); - } else { - activeUrls.set(url, activeCount - 1); - } - }; -}; - -export const patchCoreRumResourceTracking = ( - rum: CoreRumResourceBridge -): void => { - if (patchedRumInstances.has(rum)) { - return; - } - patchedRumInstances.add(rum); - - const originalStartResource = rum.startResource; - const originalStopResource = rum.stopResource; - - rum.startResource = (key, method, url, context, timestampMs) => { - if (activeUrls.has(url)) { - ignoredResourceKeys.add(key); - return Promise.resolve(); - } - - return originalStartResource.call( - rum, - key, - method, - url, - context, - timestampMs - ); - }; - - rum.stopResource = ( - key, - statusCode, - kind, - size, - context, - timestampMs, - resourceContext - ) => { - if (ignoredResourceKeys.delete(key)) { - return Promise.resolve(); - } - - return originalStopResource.call( - rum, - key, - statusCode, - kind, - size, - context, - timestampMs, - resourceContext - ); - }; -}; diff --git a/packages/react-native-vega/src/turbo-modules/NativeDdSdk.ts b/packages/react-native-vega/src/turbo-modules/NativeDdSdk.ts index c133b70b8..8d3106dac 100644 --- a/packages/react-native-vega/src/turbo-modules/NativeDdSdk.ts +++ b/packages/react-native-vega/src/turbo-modules/NativeDdSdk.ts @@ -9,6 +9,7 @@ import { TurboModuleRegistry } from '@amazon-devices/keplerscript-turbomodule-ap export interface DdSdk extends KeplerTurboModule { startHttpProxy(): Promise; + stopHttpProxy(): Promise; httpResponse(requestId: string, statusCode: number): Promise; } diff --git a/packages/react-native-vega/tests/HttpJsProxyTest.cpp b/packages/react-native-vega/tests/HttpJsProxyTest.cpp index 293385f00..351a155c7 100644 --- a/packages/react-native-vega/tests/HttpJsProxyTest.cpp +++ b/packages/react-native-vega/tests/HttpJsProxyTest.cpp @@ -109,4 +109,41 @@ int main() { 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/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 8ee7281c5..08b7229c4 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2148,6 +2148,7 @@ __metadata: 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 From e3f87b0d7b02bf3d56ad5603930ca6f7c512186e Mon Sep 17 00:00:00 2001 From: "carlos.nogueira" Date: Mon, 23 Nov 2026 17:26:37 +0000 Subject: [PATCH 4/5] Fix Vega transport retries and legacy package resolution --- AGENTS.md | 2 + packages/core/internal/index.d.ts | 7 +++ packages/core/internal/index.js | 9 ++++ packages/core/internal/package.json | 7 --- packages/core/package.json | 2 - .../src/__tests__/wrapperImportSafety.test.ts | 46 ++++++++++++++----- .../__tests__/HttpProxy.test.ts | 4 +- .../kepler/turbo-modules/HttpJsProxy.cpp | 5 +- packages/react-native-vega/src/HttpProxy.ts | 12 ++--- .../tests/HttpJsProxyTest.cpp | 7 +-- 10 files changed, 67 insertions(+), 34 deletions(-) create mode 100644 packages/core/internal/index.d.ts create mode 100644 packages/core/internal/index.js delete mode 100644 packages/core/internal/package.json 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 cc05c31cf..000000000 --- a/packages/core/internal/package.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "private": true, - "react-native": "../src/internal", - "main": "../lib/commonjs/internal.js", - "module": "../lib/module/internal.js", - "types": "../lib/typescript/internal.d.ts" -} diff --git a/packages/core/package.json b/packages/core/package.json index 4169f890e..a8fa33d1c 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -41,13 +41,11 @@ "module": "lib/module/index", "exports": { ".": { - "react-native": "./src/index.tsx", "import": "./lib/module/index.js", "require": "./lib/commonjs/index.js", "types": "./lib/typescript/index.d.ts" }, "./internal": { - "react-native": "./src/internal.ts", "import": "./lib/module/internal.js", "require": "./lib/commonjs/internal.js", "types": "./lib/typescript/internal.d.ts" 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/react-native-vega/__tests__/HttpProxy.test.ts b/packages/react-native-vega/__tests__/HttpProxy.test.ts index fac8c7855..c3e9c4d95 100644 --- a/packages/react-native-vega/__tests__/HttpProxy.test.ts +++ b/packages/react-native-vega/__tests__/HttpProxy.test.ts @@ -164,7 +164,7 @@ describe('HttpProxy', () => { expect(fetchMock).not.toHaveBeenCalled(); }); - it('cancels in-flight fetches and ignores late responses after cleanup', async () => { + it('cancels in-flight fetches and forwards completed responses during cleanup', async () => { let resolveFetch!: (response: { status: number }) => void; fetchMock.mockReturnValue( new Promise(resolve => { @@ -183,7 +183,7 @@ describe('HttpProxy', () => { expect(signal.aborted).toBe(true); resolveFetch({ status: 202 }); await request; - expect(mockHttpResponse).not.toHaveBeenCalled(); + expect(mockHttpResponse).toHaveBeenCalledWith('pending', 202); }); it('serializes overlapping starts and stops', async () => { diff --git a/packages/react-native-vega/kepler/turbo-modules/HttpJsProxy.cpp b/packages/react-native-vega/kepler/turbo-modules/HttpJsProxy.cpp index 4edd02016..b3543c49a 100644 --- a/packages/react-native-vega/kepler/turbo-modules/HttpJsProxy.cpp +++ b/packages/react-native-vega/kepler/turbo-modules/HttpJsProxy.cpp @@ -66,7 +66,8 @@ HttpProxyResult HttpRequestBridge::sendRequest(const char *url, { std::lock_guard emitterLock(emitterMutex_); if (!emitFn_) { - return {false, false, 0}; + // Transport unavailability must retain the batch for a later retry. + return {false, true, 0}; } { std::lock_guard lock(mutex_); @@ -95,7 +96,7 @@ HttpProxyResult HttpRequestBridge::sendRequest(const char *url, return {false, true, 0}; // timeout → retryable } if (pending->cancelled) { - return {false, false, 0}; + return {false, true, 0}; } statusCode = pending->status_code; } diff --git a/packages/react-native-vega/src/HttpProxy.ts b/packages/react-native-vega/src/HttpProxy.ts index 2e80838b6..55d25d090 100644 --- a/packages/react-native-vega/src/HttpProxy.ts +++ b/packages/react-native-vega/src/HttpProxy.ts @@ -119,12 +119,12 @@ export async function startHttpProxy(): Promise<() => void> { requests.delete(controller); } } - if (active) { - try { - await sdk.httpResponse(event.requestId, statusCode); - } catch { - // Native times out or teardown cancels the waiter. - } + 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. } } ); diff --git a/packages/react-native-vega/tests/HttpJsProxyTest.cpp b/packages/react-native-vega/tests/HttpJsProxyTest.cpp index 351a155c7..5474df719 100644 --- a/packages/react-native-vega/tests/HttpJsProxyTest.cpp +++ b/packages/react-native-vega/tests/HttpJsProxyTest.cpp @@ -22,7 +22,8 @@ int main() { auto &bridge = HttpRequestBridge::getInstance(); auto emptyBody = [](char *, size_t) { return size_t{0}; }; bridge.setEmitFunction({}); - assert(!bridge.sendRequest("url", "", emptyBody).success); + 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) { @@ -134,9 +135,9 @@ int main() { assert(request.wait_for(std::chrono::seconds(1)) == std::future_status::ready); auto cancelled = request.get(); - assert(!cancelled.success && !cancelled.retryable); + assert(!cancelled.success && cancelled.retryable); } - assert(!bridge.sendRequest("url", "", emptyBody).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. From 9360b2dcb2a34359dbcaa55a018fca9fa564741d Mon Sep 17 00:00:00 2001 From: "carlos.nogueira" Date: Mon, 23 Nov 2026 18:41:55 +0000 Subject: [PATCH 5/5] Share Vega transport state and bound upload requests --- packages/core/src/internal.ts | 1 + .../requestProxy/common/FetchProxyState.ts | 20 +- .../common/__tests__/FetchProxyState.test.ts | 63 ++++++ packages/react-native-vega/README.md | 4 +- .../__tests__/HttpProxy.test.ts | 210 +++++++++++++++++- packages/react-native-vega/src/HttpProxy.ts | 105 ++++++--- 6 files changed, 364 insertions(+), 39 deletions(-) create mode 100644 packages/core/src/rum/instrumentation/resourceTracking/requestProxy/common/__tests__/FetchProxyState.test.ts diff --git a/packages/core/src/internal.ts b/packages/core/src/internal.ts index 60e9b420e..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'; 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 26a1de0c4..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,8 +4,12 @@ * Copyright 2016-Present Datadog, Inc. */ -let fetchProxyCallDepth = 0; -let resourceTrackingDisabledDepth = 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. @@ -13,27 +17,27 @@ let resourceTrackingDisabledDepth = 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 => { - resourceTrackingDisabledDepth += 1; + state.resourceTrackingDisabledDepth += 1; try { return callOriginalFetch(callback); } finally { - resourceTrackingDisabledDepth -= 1; + state.resourceTrackingDisabledDepth -= 1; } }; export const isResourceTrackingDisabled = (): boolean => - resourceTrackingDisabledDepth > 0; + 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/README.md b/packages/react-native-vega/README.md index 2275c49c7..4a13533d2 100644 --- a/packages/react-native-vega/README.md +++ b/packages/react-native-vega/README.md @@ -10,7 +10,9 @@ separately. 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. SDK uploads bypass automatic Fetch and XHR resource tracking without +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 diff --git a/packages/react-native-vega/__tests__/HttpProxy.test.ts b/packages/react-native-vega/__tests__/HttpProxy.test.ts index c3e9c4d95..518ce07eb 100644 --- a/packages/react-native-vega/__tests__/HttpProxy.test.ts +++ b/packages/react-native-vega/__tests__/HttpProxy.test.ts @@ -37,6 +37,17 @@ interface HttpRequestEvent { 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; @@ -164,6 +175,201 @@ describe('HttpProxy', () => { 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( @@ -179,9 +385,11 @@ describe('HttpProxy', () => { 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); - resolveFetch({ status: 202 }); await request; expect(mockHttpResponse).toHaveBeenCalledWith('pending', 202); }); diff --git a/packages/react-native-vega/src/HttpProxy.ts b/packages/react-native-vega/src/HttpProxy.ts index 55d25d090..a95761d40 100644 --- a/packages/react-native-vega/src/HttpProxy.ts +++ b/packages/react-native-vega/src/HttpProxy.ts @@ -4,18 +4,75 @@ * Copyright 2016-Present Datadog, Inc. */ -import { callWithoutResourceTracking } from '@datadog/mobile-react-native/internal'; +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'; -let activeCleanup: (() => void) | undefined; -let operations = Promise.resolve(); +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 = operations.then(operation); - operations = result.catch(() => undefined); + const result = lifecycle.operations.then(operation); + lifecycle.operations = result.catch(() => undefined); return result; }; @@ -25,19 +82,19 @@ const enqueue = (operation: () => Promise): Promise => { * previous session; its cleanup cannot stop the replacement session. */ export async function startHttpProxy(): Promise<() => void> { - activeCleanup?.(); + lifecycle.activeCleanup?.(); let active = true; let nativeSdk: DdSdk | null = null; let subscription: { remove(): void } | undefined; - const requests = new Set(); + const requests = new Set<() => void>(); const cleanup = () => { if (!active) { return; } active = false; - if (activeCleanup === cleanup) { - activeCleanup = undefined; + if (lifecycle.activeCleanup === cleanup) { + lifecycle.activeCleanup = undefined; } // Queue teardown before a replacement session can enable its emitter. enqueue(async () => { @@ -54,14 +111,14 @@ export async function startHttpProxy(): Promise<() => void> { } requests.forEach(request => { try { - request.abort(); + request(); } catch { // Some Fetch implementations do not support cancellation. } }); requests.clear(); }; - activeCleanup = cleanup; + lifecycle.activeCleanup = cleanup; try { await enqueue(async () => { @@ -86,7 +143,6 @@ export async function startHttpProxy(): Promise<() => void> { return; } let statusCode = 0; - let controller: AbortController | undefined; try { const headers: Record = {}; event.headers.split('\n').forEach(line => { @@ -97,27 +153,18 @@ export async function startHttpProxy(): Promise<() => void> { ] = line.substring(colon + 1).trim(); } }); - if (typeof AbortController !== 'undefined') { - controller = new AbortController(); - requests.add(controller); - } - const response = await callWithoutResourceTracking(() => - fetch(event.url, { + const response = await fetchWithDeadline( + event.url, + { method: 'POST', headers, - body: event.body, - ...(controller - ? { signal: controller.signal } - : {}) - }) + body: event.body + }, + requests ); - statusCode = response.status; + statusCode = response?.status ?? 0; } catch { - // Status 0 makes network failures retryable in native. - } finally { - if (controller) { - requests.delete(controller); - } + // Status 0 makes network errors and timeouts retryable. } try { // Native arbitrates response versus cancellation and