diff --git a/packages/react-native-vega/CMakeLists.txt b/packages/react-native-vega/CMakeLists.txt index e7d6c159c..335bfe990 100644 --- a/packages/react-native-vega/CMakeLists.txt +++ b/packages/react-native-vega/CMakeLists.txt @@ -48,22 +48,31 @@ else() ) endif() FetchContent_MakeAvailable(Datadog) +include(cmake/DatadogLoggingCompatibility.cmake) +datadog_vega_patch_logging_registration("${datadog_SOURCE_DIR}") set(HEADERS kepler/turbo-modules/generated/DdRumSpec.h kepler/turbo-modules/DdRum.h kepler/turbo-modules/RumBridge.h + kepler/turbo-modules/generated/DdLogsSpec.h + kepler/turbo-modules/DdLogs.h + kepler/turbo-modules/LoggingConfiguration.h 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/FeatureAttributes.h kepler/turbo-modules/HttpJsProxy.h ) set(SOURCES kepler/turbo-modules/generated/DdRumSpec.cpp kepler/turbo-modules/DdRum.cpp + kepler/turbo-modules/generated/DdLogsSpec.cpp + kepler/turbo-modules/DdLogs.cpp + kepler/turbo-modules/LoggingConfiguration.cpp kepler/turbo-modules/generated/DdSdkSpec.cpp kepler/turbo-modules/DdSdk.cpp kepler/turbo-modules/EnumParsers.cpp diff --git a/packages/react-native-vega/README.md b/packages/react-native-vega/README.md index 6507fc803..33d66891b 100644 --- a/packages/react-native-vega/README.md +++ b/packages/react-native-vega/README.md @@ -47,7 +47,8 @@ continuous actions, start and stop resources, report errors, update view attributes, stop a session, report full app display, and track feature operations. `DdSdkReactNative.addAttribute`, `addAttributes`, `removeAttribute`, and -`removeAttributes` update global RUM attributes and the shared JavaScript context. +`removeAttributes` update global RUM and logging attributes and the shared +JavaScript context. They also work when only logging is enabled. View attributes take precedence over global attributes until removed or the view ends. JSON-compatible values retain their types, including nested objects, arrays, numbers, booleans, and null. Singular attribute calls wrap the value for @@ -74,3 +75,36 @@ containing `Kepler/` and `JsonContainer/`), and `NODE_API_INCLUDE_DIR` to the te CMake configuration. Keep platform system headers separate from those roots when building on macOS. The default host test command still runs the transport tests without these SDK dependencies. + +`DdLogs` forwards debug, info, warn and error logs, with optional error kind, +message, stack and attributes. `DdSdkReactNative` supports setting, updating and +clearing user/account information. Native failures leave JavaScript context +unchanged and do not reject into application code. + +The native initializer must call `configureLogging(core, logsConfiguration)` +when a logs configuration is present, before starting the core. The logger uses +`bundleLogsWithRum` to control RUM correlation (defaults to `true`). Initialization +is added separately; importing these APIs does not initialize the SDK. Logs are +ignored until the native logger has been configured. + +The optional log `source` argument does not change the C++ logger's source. +Custom fingerprints are kept in attributes but do not control native error +grouping in C++ SDK 0.7.0. Error symbolication and JavaScript error enrichment +are added separately. + +Anonymous user attributes are supported through `addUserExtraInfo`, matching +core. Account attributes require an account ID to be set first. + +### Logging registration compatibility + +C++ SDK 0.7.0 returns non-null no-op objects when logging registration fails. +Vega builds compile a private copy of that source with nullable failure returns, +so failed registrations leave logging disabled. Repeated configuration keeps the +working logger. The dependency checkout is never edited, including when using +`Datadog_SOURCE_DIR`. The build rejects unexpected SDK versions or source changes +so this adjustment is reviewed when the C++ SDK is upgraded. + +Set `VEGA_TEST_LOGGING_CONFIGURATION=ON` in the host test CMake configuration to +build the actual SDK and test failed registration, repeated configuration, and +logging-only attributes. This uses the same compatibility source as Vega builds +and requires the SDK and include paths described above. diff --git a/packages/react-native-vega/__tests__/DdLogsVega.test.ts b/packages/react-native-vega/__tests__/DdLogsVega.test.ts new file mode 100644 index 000000000..de4783daf --- /dev/null +++ b/packages/react-native-vega/__tests__/DdLogsVega.test.ts @@ -0,0 +1,119 @@ +/* + * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. + * This product includes software developed at Datadog (https://www.datadoghq.com/). + * Copyright 2016-Present Datadog, Inc. + */ + +import type { ErrorSource } from '@datadog/mobile-react-native'; + +import { DdLogs } from '../src/DdLogsVega'; + +const mockNative = { log: jest.fn() }; +const mockGet = jest.fn(); +jest.mock('@amazon-devices/keplerscript-turbomodule-api', () => ({ + TurboModuleRegistry: { get: (...args: unknown[]) => mockGet(...args) } +})); + +describe('Vega logs', () => { + beforeEach(() => { + jest.clearAllMocks(); + mockGet.mockReturnValue(mockNative); + }); + it.each(['debug', 'info', 'warn', 'error'] as const)( + 'forwards %s logs and attributes', + async level => { + const context = { + count: 3, + enabled: false, + nested: { value: null } + }; + await DdLogs[level]('message', context); + expect(mockNative.log).toHaveBeenCalledWith( + level, + 'message', + '', + '', + '', + context + ); + await DdLogs[level]('default context'); + expect(mockNative.log).toHaveBeenLastCalledWith( + level, + 'default context', + '', + '', + '', + {} + ); + } + ); + it.each(['debug', 'info', 'warn', 'error'] as const)( + 'forwards %s error details without changing caller attributes', + async level => { + const context = Object.freeze({ custom: true }); + await DdLogs[level]( + 'message', + 'TypeError', + 'failure', + 'stack', + context, + 'group' + ); + expect(mockNative.log).toHaveBeenCalledWith( + level, + 'message', + 'TypeError', + 'failure', + 'stack', + { + custom: true, + '_dd.error.fingerprint': 'group' + } + ); + expect(context).toEqual({ custom: true }); + } + ); + it('handles error overloads with missing optional fields', async () => { + await DdLogs.error('message', undefined, undefined, 'stack'); + expect(mockNative.log).toHaveBeenCalledWith( + 'error', + 'message', + '', + '', + 'stack', + {} + ); + }); + it('accepts a source-only error overload without shifting attributes', async () => { + await DdLogs.error( + 'message', + undefined, + undefined, + undefined, + undefined, + undefined, + 'SOURCE' as ErrorSource + ); + expect(mockNative.log).toHaveBeenCalledWith( + 'error', + 'message', + '', + '', + '', + {} + ); + }); + it('ignores missing, throwing, and rejecting native modules', async () => { + mockGet.mockReturnValueOnce(null).mockImplementationOnce(() => { + throw Error('lookup'); + }); + await expect(DdLogs.info('message')).resolves.toBeUndefined(); + await expect(DdLogs.info('message')).resolves.toBeUndefined(); + mockNative.log.mockImplementationOnce(() => { + throw Error('call'); + }); + await expect(DdLogs.info('message')).resolves.toBeUndefined(); + mockNative.log.mockRejectedValueOnce(Error('rejected')); + await expect(DdLogs.info('message')).resolves.toBeUndefined(); + }); +}); diff --git a/packages/react-native-vega/__tests__/DdSdkContext.test.ts b/packages/react-native-vega/__tests__/DdSdkContext.test.ts new file mode 100644 index 000000000..243b1e377 --- /dev/null +++ b/packages/react-native-vega/__tests__/DdSdkContext.test.ts @@ -0,0 +1,203 @@ +/* + * 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 { + AccountInfoSingleton, + AttributesSingleton, + UserInfoSingleton +} from '@datadog/mobile-react-native/internal'; + +import { DdSdkReactNative } from '../src/DdSdkReactNativeVega'; + +const mockNative = { + addAttribute: jest.fn(), + removeAttribute: jest.fn(), + addAttributes: jest.fn(), + removeAttributes: jest.fn(), + setUserInfo: jest.fn(), + clearUserInfo: jest.fn(), + addUserExtraInfo: jest.fn(), + setAccountInfo: jest.fn(), + clearAccountInfo: jest.fn(), + addAccountExtraInfo: jest.fn() +}; +const mockGet = jest.fn(); +jest.mock('@amazon-devices/keplerscript-turbomodule-api', () => ({ + TurboModuleRegistry: { get: (...args: unknown[]) => mockGet(...args) } +})); + +describe('Vega user and account context', () => { + beforeEach(() => { + jest.clearAllMocks(); + mockGet.mockReturnValue(mockNative); + UserInfoSingleton.reset(); + AttributesSingleton.reset(); + AccountInfoSingleton.reset(); + }); + it('sets, merges, replaces and clears user context', async () => { + const user = { + id: 'user', + name: 'name', + email: 'user@example.com', + extraInfo: { count: 1, keep: false } + }; + await DdSdkReactNative.setUserInfo(user); + expect(mockNative.setUserInfo).toHaveBeenCalledWith(user); + expect(UserInfoSingleton.getInstance().getUserInfo()).toEqual(user); + const extra = { count: 2, nested: { array: [null, true, 3] } }; + await DdSdkReactNative.addUserExtraInfo(extra); + expect(mockNative.addUserExtraInfo).toHaveBeenCalledWith(extra); + expect( + UserInfoSingleton.getInstance().getUserInfo()?.extraInfo + ).toEqual({ ...user.extraInfo, ...extra }); + await DdSdkReactNative.setUserInfo({ id: 'replacement' }); + expect(UserInfoSingleton.getInstance().getUserInfo()).toEqual({ + id: 'replacement' + }); + await DdSdkReactNative.clearUserInfo(); + expect(mockNative.clearUserInfo).toHaveBeenCalledTimes(1); + expect(UserInfoSingleton.getInstance().getUserInfo()).toBeUndefined(); + }); + it('sets, merges, replaces and clears account context', async () => { + const account = { + id: 'account', + name: 'team', + extraInfo: { plan: 'free' } + }; + await DdSdkReactNative.setAccountInfo(account); + expect(mockNative.setAccountInfo).toHaveBeenCalledWith(account); + await DdSdkReactNative.addAccountExtraInfo({ + plan: 'paid', + active: true + }); + expect(mockNative.addAccountExtraInfo).toHaveBeenCalledWith({ + plan: 'paid', + active: true + }); + expect( + AccountInfoSingleton.getInstance().getAccountInfo()?.extraInfo + ).toEqual({ plan: 'paid', active: true }); + await DdSdkReactNative.setAccountInfo({ id: 'replacement' }); + expect(AccountInfoSingleton.getInstance().getAccountInfo()).toEqual({ + id: 'replacement' + }); + await DdSdkReactNative.clearAccountInfo(); + expect(mockNative.clearAccountInfo).toHaveBeenCalledTimes(1); + expect( + AccountInfoSingleton.getInstance().getAccountInfo() + ).toBeUndefined(); + }); + it('ignores invalid IDs and account extra info without an account', async () => { + await DdSdkReactNative.setUserInfo({ id: '' }); + await DdSdkReactNative.setAccountInfo({ id: '' }); + await DdSdkReactNative.addAccountExtraInfo({ value: 1 }); + expect(mockGet).not.toHaveBeenCalled(); + }); + it('merges anonymous user attributes without requiring a user ID', async () => { + await DdSdkReactNative.addUserExtraInfo({ + plan: 'free', + enabled: false + }); + await DdSdkReactNative.addUserExtraInfo({ + plan: 'paid', + nested: { values: [1, null] } + }); + expect(mockNative.addUserExtraInfo).toHaveBeenNthCalledWith(1, { + plan: 'free', + enabled: false + }); + expect(mockNative.addUserExtraInfo).toHaveBeenNthCalledWith(2, { + plan: 'paid', + nested: { values: [1, null] } + }); + expect(UserInfoSingleton.getInstance().getUserInfo()).toEqual({ + extraInfo: { + plan: 'paid', + enabled: false, + nested: { values: [1, null] } + } + }); + }); + it('does not update anonymous user attributes when native rejects them', async () => { + mockNative.addUserExtraInfo.mockResolvedValueOnce(false); + await DdSdkReactNative.addUserExtraInfo({ plan: 'free' }); + expect(mockNative.addUserExtraInfo).toHaveBeenCalledWith({ + plan: 'free' + }); + expect(UserInfoSingleton.getInstance().getUserInfo()).toBeUndefined(); + }); + it('does not mutate account information owned by the application', async () => { + const account = Object.freeze({ + id: 'account', + extraInfo: { plan: 'free' } + }); + await DdSdkReactNative.setAccountInfo(account); + await DdSdkReactNative.addAccountExtraInfo({ plan: 'paid' }); + expect(account.extraInfo).toEqual({ plan: 'free' }); + expect( + AccountInfoSingleton.getInstance().getAccountInfo()?.extraInfo + ).toEqual({ plan: 'paid' }); + }); + it('retains the identity sent to native while awaiting its response', async () => { + let complete: (value: boolean) => void = () => undefined; + mockNative.setUserInfo.mockReturnValueOnce( + new Promise(resolve => { + complete = resolve; + }) + ); + const user = { id: 'original' }; + const update = DdSdkReactNative.setUserInfo(user); + user.id = 'changed'; + complete(true); + await update; + expect(mockNative.setUserInfo).toHaveBeenLastCalledWith({ + id: 'original' + }); + expect(UserInfoSingleton.getInstance().getUserInfo()?.id).toBe( + 'original' + ); + }); + it('keeps global, user and account context independent', async () => { + await DdSdkReactNative.addAttribute('plan', 'paid'); + await DdSdkReactNative.setUserInfo({ id: 'user' }); + await DdSdkReactNative.setAccountInfo({ id: 'account' }); + await DdSdkReactNative.addAttributes({ + nested: { value: [true, null] } + }); + await DdSdkReactNative.clearUserInfo(); + await DdSdkReactNative.removeAttribute('plan'); + expect(AttributesSingleton.getInstance().getAttributes()).toEqual({ + nested: { value: [true, null] } + }); + expect(UserInfoSingleton.getInstance().getUserInfo()).toBeUndefined(); + expect(AccountInfoSingleton.getInstance().getAccountInfo()?.id).toBe( + 'account' + ); + expect(mockNative.addAttribute).toHaveBeenCalledWith('plan', { + value: 'paid' + }); + expect(mockNative.removeAttribute).toHaveBeenCalledWith('plan'); + }); + it('keeps JavaScript context unchanged when native fails', async () => { + await DdSdkReactNative.setUserInfo({ id: 'user' }); + await DdSdkReactNative.setAccountInfo({ id: 'account' }); + mockNative.clearUserInfo.mockResolvedValueOnce(false); + mockNative.clearAccountInfo.mockRejectedValueOnce(Error('bridge')); + await DdSdkReactNative.clearUserInfo(); + await DdSdkReactNative.clearAccountInfo(); + expect(UserInfoSingleton.getInstance().getUserInfo()?.id).toBe('user'); + expect(AccountInfoSingleton.getInstance().getAccountInfo()?.id).toBe( + 'account' + ); + mockGet.mockReturnValue(null); + await DdSdkReactNative.setUserInfo({ id: 'replacement' }); + await DdSdkReactNative.setAccountInfo({ id: 'replacement' }); + expect(UserInfoSingleton.getInstance().getUserInfo()?.id).toBe('user'); + expect(AccountInfoSingleton.getInstance().getAccountInfo()?.id).toBe( + 'account' + ); + }); +}); diff --git a/packages/react-native-vega/cmake/DatadogLoggingCompatibility.cmake b/packages/react-native-vega/cmake/DatadogLoggingCompatibility.cmake new file mode 100644 index 000000000..9192c58c3 --- /dev/null +++ b/packages/react-native-vega/cmake/DatadogLoggingCompatibility.cmake @@ -0,0 +1,38 @@ +# 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. + +# SDK 0.7.0 returns non-null no-op logging handles on registration failure. +# Compile a private nullable copy so the bridge can distinguish failure without +# modifying the dependency checkout (including Datadog_SOURCE_DIR overrides). +function(datadog_vega_patch_logging_registration sdk_source_dir) + get_directory_property(sdk_version DIRECTORY "${sdk_source_dir}" DEFINITION ddsdkcpp_VERSION) + if(NOT sdk_version STREQUAL "0.7.0") + message(FATAL_ERROR "Vega logging compatibility requires dd-sdk-cpp 0.7.0; review this patch when changing SDK versions") + endif() + set(original "${sdk_source_dir}/src/datadog/cpp/logging.cpp") + file(READ "${original}" source) + set(noop "return std::make_shared(Logging::PrivateCtorTag{});") + string(REGEX MATCHALL "return std::make_shared[(]Logging::PrivateCtorTag[{][}][)]" matches "${source}") + list(LENGTH matches match_count) + if(NOT match_count EQUAL 2) + message(FATAL_ERROR "Unexpected dd-sdk-cpp logging registration implementation; refusing to apply the Vega compatibility patch") + endif() + string(REPLACE "${noop}" "return nullptr;" patched "${source}") + if(patched MATCHES "return std::make_shared[(]Logging::PrivateCtorTag[{][}][)]") + message(FATAL_ERROR "Cannot replace the dd-sdk-cpp no-op logging returns; refusing to use an unpatched SDK") + endif() + set(copy "${CMAKE_CURRENT_BINARY_DIR}/datadog-compat/logging.cpp") + file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/datadog-compat") + file(WRITE "${copy}" "${patched}") + get_target_property(sources ddsdkcpp SOURCES) + list(FIND sources "datadog/cpp/logging.cpp" source_index) + if(source_index EQUAL -1) + message(FATAL_ERROR "Cannot locate the dd-sdk-cpp logging source to apply the Vega compatibility patch") + endif() + list(REMOVE_AT sources ${source_index}) + list(APPEND sources "${copy}") + set_property(TARGET ddsdkcpp PROPERTY SOURCES "${sources}") +endfunction() diff --git a/packages/react-native-vega/kepler/AutoLinkInit.cpp b/packages/react-native-vega/kepler/AutoLinkInit.cpp index f7b68dfe8..3bd69ae31 100644 --- a/packages/react-native-vega/kepler/AutoLinkInit.cpp +++ b/packages/react-native-vega/kepler/AutoLinkInit.cpp @@ -6,12 +6,14 @@ #include #include "turbo-modules/DdSdk.h" +#include "turbo-modules/DdLogs.h" #include "turbo-modules/DdRum.h" extern "C" { __attribute__((visibility("default"))) void autoLinkKeplerTurboModulesV1() noexcept { KEPLER_REGISTER_TURBO_MODULE(DdSdkTurboModule, DdSdk); + KEPLER_REGISTER_TURBO_MODULE(DdLogsTurboModule, DdLogs); KEPLER_REGISTER_TURBO_MODULE(DdRumTurboModule, DdRum); } } diff --git a/packages/react-native-vega/kepler/turbo-modules/DatadogGlobalState.cpp b/packages/react-native-vega/kepler/turbo-modules/DatadogGlobalState.cpp index 8e70e4ca7..d9996a02f 100644 --- a/packages/react-native-vega/kepler/turbo-modules/DatadogGlobalState.cpp +++ b/packages/react-native-vega/kepler/turbo-modules/DatadogGlobalState.cpp @@ -33,8 +33,30 @@ std::shared_ptr DatadogGlobalState::getRum() { return rum_; } +void DatadogGlobalState::setLogging(std::shared_ptr logging) { + std::lock_guard lock(mutex_); + logging_ = std::move(logging); +} + +std::shared_ptr DatadogGlobalState::getLogging() { + std::lock_guard lock(mutex_); + return logging_; +} + +void DatadogGlobalState::setLogger(std::shared_ptr logger) { + std::lock_guard lock(mutex_); + logger_ = std::move(logger); +} + +std::shared_ptr DatadogGlobalState::getLogger() { + std::lock_guard lock(mutex_); + return logger_; +} + void DatadogGlobalState::reset() { std::lock_guard lock(mutex_); + logger_.reset(); + logging_.reset(); rum_.reset(); core_.reset(); } diff --git a/packages/react-native-vega/kepler/turbo-modules/DatadogGlobalState.h b/packages/react-native-vega/kepler/turbo-modules/DatadogGlobalState.h index 4946830d7..dc7554e0c 100644 --- a/packages/react-native-vega/kepler/turbo-modules/DatadogGlobalState.h +++ b/packages/react-native-vega/kepler/turbo-modules/DatadogGlobalState.h @@ -11,6 +11,7 @@ #include "datadog/core.hpp" #include "datadog/rum.hpp" +#include "datadog/logging.hpp" namespace datadog_rn_vega { @@ -29,6 +30,11 @@ class DatadogGlobalState { void setRum(std::shared_ptr rum); std::shared_ptr getRum(); + void setLogging(std::shared_ptr logging); + std::shared_ptr getLogging(); + void setLogger(std::shared_ptr logger); + std::shared_ptr getLogger(); + /** Clears the core and all registered feature pointers. */ void reset(); @@ -40,6 +46,8 @@ class DatadogGlobalState { std::mutex mutex_; std::shared_ptr core_; std::shared_ptr rum_; + std::shared_ptr logging_; + std::shared_ptr logger_; }; } // namespace datadog_rn_vega diff --git a/packages/react-native-vega/kepler/turbo-modules/DdLogs.cpp b/packages/react-native-vega/kepler/turbo-modules/DdLogs.cpp new file mode 100644 index 000000000..23947ab12 --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/DdLogs.cpp @@ -0,0 +1,48 @@ +// 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 "DdLogs.h" +#include "AttributeConverter.h" +#include "DatadogGlobalState.h" + +using namespace com::amazon::kepler::turbomodule; + +namespace DdLogsTurboModule { + +Promise DdLogs::log(std::string level, std::string message, + std::string errorKind, std::string errorMessage, + std::string stacktrace, JSObject context) { + return Promise([=](const std::shared_ptr &promise) { + try { + auto logger = + datadog_rn_vega::DatadogGlobalState::getInstance().getLogger(); + if (!logger) { + promise->resolve(false); + return; + } + const auto attributes = + datadog_rn_vega::jsObjectToAttribute(context); + const datadog::LogError error{errorMessage, errorKind, stacktrace}; + if (level == "debug") { + logger->Debug(message, error, attributes); + } else if (level == "info") { + logger->Info(message, error, attributes); + } else if (level == "warn") { + logger->Warn(message, error, attributes); + } else if (level == "error") { + logger->Error(message, error, attributes); + } else { + promise->resolve(false); + return; + } + promise->resolve(true); + } catch (...) { + promise->resolve(false); + } + }); +} + +} // namespace DdLogsTurboModule diff --git a/packages/react-native-vega/kepler/turbo-modules/DdLogs.h b/packages/react-native-vega/kepler/turbo-modules/DdLogs.h new file mode 100644 index 000000000..c6e2413db --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/DdLogs.h @@ -0,0 +1,21 @@ +// 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/DdLogsSpec.h" + +namespace DdLogsTurboModule { + +class DdLogs : public DdLogsSpec { + public: + com::amazon::kepler::turbomodule::Promise + log(std::string level, std::string message, std::string errorKind, + std::string errorMessage, std::string stacktrace, + com::amazon::kepler::turbomodule::JSObject context) override; +}; + +} // namespace DdLogsTurboModule diff --git a/packages/react-native-vega/kepler/turbo-modules/DdSdk.cpp b/packages/react-native-vega/kepler/turbo-modules/DdSdk.cpp index cc4c13fa8..8f8fb860a 100644 --- a/packages/react-native-vega/kepler/turbo-modules/DdSdk.cpp +++ b/packages/react-native-vega/kepler/turbo-modules/DdSdk.cpp @@ -6,39 +6,86 @@ #include "DdSdk.h" #include "AttributeConverter.h" +#include "DatadogGlobalState.h" +#include "FeatureAttributes.h" #include "HttpJsProxy.h" -#include "RumBridge.h" using namespace com::amazon::kepler::turbomodule; namespace DdSdkTurboModule { +namespace { +template Promise withCore(Operation operation) { + return Promise([operation](const std::shared_ptr &promise) { + try { + auto core = + datadog_rn_vega::DatadogGlobalState::getInstance().getCore(); + if (!core) { + promise->resolve(false); + return; + } + operation(*core); + promise->resolve(true); + } catch (...) { + promise->resolve(false); + } + }); +} + +std::string stringField(const JSObject &object, const std::string &key) { + const auto entry = object.find(key); + if (entry == object.end()) + return {}; + const auto value = std::get_if(&entry->second); + return value ? *value : std::string(); +} + +datadog::Attribute extraInfo(const JSObject &object) { + const auto entry = object.find("extraInfo"); + if (entry != object.end()) { + const auto value = std::get_if(&entry->second); + if (value) + return datadog_rn_vega::jsObjectToAttribute(*value); + } + return datadog::Attribute::Object(); +} +template Promise withFeatures(Operation operation) { + return Promise([operation](const std::shared_ptr &promise) { + try { + promise->resolve(datadog_rn_vega::applyToFeatures(operation)); + } catch (...) { + promise->resolve(false); + } + }); +} +} // namespace + DdSdk::DdSdk() = default; Promise DdSdk::addAttribute(std::string key, JSObject value) { - return datadog_rn_vega::withRum([=](datadog::Rum &rum) { - rum.AddAttribute(key, - datadog_rn_vega::jsWrappedValueToAttribute(value)); + return withFeatures([=](auto &feature) { + feature.AddAttribute(key, + datadog_rn_vega::jsWrappedValueToAttribute(value)); }); } Promise DdSdk::removeAttribute(std::string key) { - return datadog_rn_vega::withRum( - [=](datadog::Rum &rum) { rum.RemoveAttribute(key); }); + return withFeatures([=](auto &feature) { feature.RemoveAttribute(key); }); } Promise DdSdk::addAttributes(JSObject attributes) { - return datadog_rn_vega::withRum([=](datadog::Rum &rum) { + return withFeatures([=](auto &feature) { for (const auto &[key, value] : attributes) { - rum.AddAttribute(key, datadog_rn_vega::jsValueToAttribute(value)); + feature.AddAttribute(key, + datadog_rn_vega::jsValueToAttribute(value)); } }); } Promise DdSdk::removeAttributes(std::vector keys) { - return datadog_rn_vega::withRum([=](datadog::Rum &rum) { + return withFeatures([=](auto &feature) { for (const auto &key : keys) { - rum.RemoveAttribute(key); + feature.RemoveAttribute(key); } }); } @@ -79,4 +126,38 @@ Promise DdSdk::httpResponse(std::string requestId, double statusCode) { }); } +Promise DdSdk::setUserInfo(JSObject info) { + return withCore([info](datadog::Core &core) { + core.SetUserInfo(stringField(info, "id"), stringField(info, "name"), + stringField(info, "email"), extraInfo(info)); + }); +} + +Promise DdSdk::clearUserInfo() { + return withCore([](datadog::Core &core) { core.ClearUserInfo(); }); +} + +Promise DdSdk::addUserExtraInfo(JSObject info) { + return withCore([info](datadog::Core &core) { + core.AddUserExtraInfo(datadog_rn_vega::jsObjectToAttribute(info)); + }); +} + +Promise DdSdk::setAccountInfo(JSObject info) { + return withCore([info](datadog::Core &core) { + core.SetAccountInfo(stringField(info, "id"), stringField(info, "name"), + extraInfo(info)); + }); +} + +Promise DdSdk::clearAccountInfo() { + return withCore([](datadog::Core &core) { core.ClearAccountInfo(); }); +} + +Promise DdSdk::addAccountExtraInfo(JSObject info) { + return withCore([info](datadog::Core &core) { + core.AddAccountExtraInfo(datadog_rn_vega::jsObjectToAttribute(info)); + }); +} + } // namespace DdSdkTurboModule diff --git a/packages/react-native-vega/kepler/turbo-modules/DdSdk.h b/packages/react-native-vega/kepler/turbo-modules/DdSdk.h index d19b63b5f..740a61e10 100644 --- a/packages/react-native-vega/kepler/turbo-modules/DdSdk.h +++ b/packages/react-native-vega/kepler/turbo-modules/DdSdk.h @@ -24,6 +24,17 @@ class DdSdk : public DdSdkSpec { com::amazon::kepler::turbomodule::JSObject attributes) override; com::amazon::kepler::turbomodule::Promise removeAttributes(std::vector keys) override; + com::amazon::kepler::turbomodule::Promise + setUserInfo(com::amazon::kepler::turbomodule::JSObject info) override; + com::amazon::kepler::turbomodule::Promise clearUserInfo() override; + com::amazon::kepler::turbomodule::Promise + addUserExtraInfo(com::amazon::kepler::turbomodule::JSObject info) override; + com::amazon::kepler::turbomodule::Promise + setAccountInfo(com::amazon::kepler::turbomodule::JSObject info) override; + com::amazon::kepler::turbomodule::Promise clearAccountInfo() override; + com::amazon::kepler::turbomodule::Promise addAccountExtraInfo( + com::amazon::kepler::turbomodule::JSObject info) override; + com::amazon::kepler::turbomodule::Promise startHttpProxy() override; com::amazon::kepler::turbomodule::Promise stopHttpProxy() override; com::amazon::kepler::turbomodule::Promise diff --git a/packages/react-native-vega/kepler/turbo-modules/FeatureAttributes.h b/packages/react-native-vega/kepler/turbo-modules/FeatureAttributes.h new file mode 100644 index 000000000..509f54f9c --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/FeatureAttributes.h @@ -0,0 +1,24 @@ +// Unless explicitly stated otherwise all files in this repository are licensed +// under the Apache License Version 2.0. +// +// This product includes software developed at Datadog +// (https://www.datadoghq.com/). Copyright 2016-Present Datadog, Inc. + +#pragma once + +#include "DatadogGlobalState.h" + +namespace datadog_rn_vega { + +template bool applyToFeatures(Operation operation) { + auto &state = DatadogGlobalState::getInstance(); + auto rum = state.getRum(); + auto logging = state.getLogging(); + if (rum) + operation(*rum); + if (logging) + operation(*logging); + return bool(rum) || bool(logging); +} + +} // namespace datadog_rn_vega diff --git a/packages/react-native-vega/kepler/turbo-modules/LoggingConfiguration.cpp b/packages/react-native-vega/kepler/turbo-modules/LoggingConfiguration.cpp new file mode 100644 index 000000000..da969b528 --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/LoggingConfiguration.cpp @@ -0,0 +1,36 @@ +// 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 "LoggingConfiguration.h" +#include "DatadogGlobalState.h" +#include "datadog/logging.hpp" + +namespace datadog_rn_vega { + +void configureLogging( + const std::shared_ptr &core, + const com::amazon::kepler::turbomodule::JSObject &configuration) { + if (!core) + return; + auto &state = DatadogGlobalState::getInstance(); + if (state.getLogging()) + return; + auto logging = datadog::Logging::Register(core); + if (!logging) + return; + datadog::LoggerConfig config; + config.SetName("react-native"); + const auto entry = configuration.find("bundleLogsWithRum"); + const auto enrich = entry == configuration.end() + ? nullptr + : std::get_if(&entry->second); + config.SetEnrichWithRumContext(enrich ? *enrich : true); + auto logger = logging->CreateLogger(config); + state.setLogging(logging); + state.setLogger(logger); +} + +} // namespace datadog_rn_vega diff --git a/packages/react-native-vega/kepler/turbo-modules/LoggingConfiguration.h b/packages/react-native-vega/kepler/turbo-modules/LoggingConfiguration.h new file mode 100644 index 000000000..b18fb414a --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/LoggingConfiguration.h @@ -0,0 +1,19 @@ +// Unless explicitly stated otherwise all files in this repository are licensed +// under the Apache License Version 2.0. +// +// This product includes software developed at Datadog +// (https://www.datadoghq.com/). Copyright 2016-Present Datadog, Inc. + +#pragma once + +#include "datadog/core.hpp" +#include + +namespace datadog_rn_vega { + +// Call before Core::Start, and only when a logs configuration is present. +void configureLogging( + const std::shared_ptr &core, + const com::amazon::kepler::turbomodule::JSObject &configuration); + +} // namespace datadog_rn_vega diff --git a/packages/react-native-vega/kepler/turbo-modules/generated/DdLogsSpec.cpp b/packages/react-native-vega/kepler/turbo-modules/generated/DdLogsSpec.cpp new file mode 100644 index 000000000..db097d573 --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/generated/DdLogsSpec.cpp @@ -0,0 +1,25 @@ +/** + * 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 "DdLogsSpec.h" + +using namespace com::amazon::kepler::turbomodule; + +namespace DdLogsTurboModule { + +DdLogsSpec::DdLogsSpec() : KeplerTurboModule("DdLogs") {} + +DdLogsSpec::~DdLogsSpec() = default; + +void DdLogsSpec::aggregateMethods( + MethodAggregator &methodAggregator) const noexcept { + methodAggregator.addMethod("log", &DdLogsSpec::log); +} + +} // namespace DdLogsTurboModule diff --git a/packages/react-native-vega/kepler/turbo-modules/generated/DdLogsSpec.h b/packages/react-native-vega/kepler/turbo-modules/generated/DdLogsSpec.h new file mode 100644 index 000000000..e958f7d3b --- /dev/null +++ b/packages/react-native-vega/kepler/turbo-modules/generated/DdLogsSpec.h @@ -0,0 +1,43 @@ +/** + * This code was generated by the Kepler Codegen tool. + * + * Do not edit this file as changes may cause incorrect behavior and will be + * lost when the code is regenerated. + * + * @generated by GenerateModuleSpecH.js + */ + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace DdLogsTurboModule { + +class DdLogsSpec : public com::amazon::kepler::turbomodule::KeplerTurboModule { + protected: + DdLogsSpec(); + virtual ~DdLogsSpec() = 0; + + public: + void aggregateMethods( + com::amazon::kepler::turbomodule::MethodAggregator + &methodAggregator) const noexcept override; + + virtual com::amazon::kepler::turbomodule::Promise + log(std::string level, std::string message, std::string errorKind, + std::string errorMessage, std::string stacktrace, + com::amazon::kepler::turbomodule::JSObject context) = 0; +}; + +} // namespace DdLogsTurboModule 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 0e4dd8636..118fbc60c 100644 --- a/packages/react-native-vega/kepler/turbo-modules/generated/DdSdkSpec.cpp +++ b/packages/react-native-vega/kepler/turbo-modules/generated/DdSdkSpec.cpp @@ -24,6 +24,15 @@ void DdSdkSpec::aggregateMethods( methodAggregator.addMethod("addAttributes", &DdSdkSpec::addAttributes); methodAggregator.addMethod("removeAttributes", &DdSdkSpec::removeAttributes); + methodAggregator.addMethod("setUserInfo", &DdSdkSpec::setUserInfo); + methodAggregator.addMethod("clearUserInfo", &DdSdkSpec::clearUserInfo); + methodAggregator.addMethod("addUserExtraInfo", + &DdSdkSpec::addUserExtraInfo); + methodAggregator.addMethod("setAccountInfo", &DdSdkSpec::setAccountInfo); + methodAggregator.addMethod("clearAccountInfo", + &DdSdkSpec::clearAccountInfo); + methodAggregator.addMethod("addAccountExtraInfo", + &DdSdkSpec::addAccountExtraInfo); 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 909e792a8..b32906645 100644 --- a/packages/react-native-vega/kepler/turbo-modules/generated/DdSdkSpec.h +++ b/packages/react-native-vega/kepler/turbo-modules/generated/DdSdkSpec.h @@ -43,6 +43,16 @@ class DdSdkSpec : public com::amazon::kepler::turbomodule::KeplerTurboModule { addAttributes(com::amazon::kepler::turbomodule::JSObject attributes) = 0; virtual com::amazon::kepler::turbomodule::Promise removeAttributes(std::vector keys) = 0; + virtual com::amazon::kepler::turbomodule::Promise + setUserInfo(com::amazon::kepler::turbomodule::JSObject info) = 0; + virtual com::amazon::kepler::turbomodule::Promise clearUserInfo() = 0; + virtual com::amazon::kepler::turbomodule::Promise + addUserExtraInfo(com::amazon::kepler::turbomodule::JSObject info) = 0; + virtual com::amazon::kepler::turbomodule::Promise + setAccountInfo(com::amazon::kepler::turbomodule::JSObject info) = 0; + virtual com::amazon::kepler::turbomodule::Promise clearAccountInfo() = 0; + virtual com::amazon::kepler::turbomodule::Promise + addAccountExtraInfo(com::amazon::kepler::turbomodule::JSObject info) = 0; virtual com::amazon::kepler::turbomodule::Promise startHttpProxy() = 0; virtual com::amazon::kepler::turbomodule::Promise stopHttpProxy() = 0; virtual com::amazon::kepler::turbomodule::Promise diff --git a/packages/react-native-vega/package.json b/packages/react-native-vega/package.json index dfc12dbd2..a438ddc5c 100644 --- a/packages/react-native-vega/package.json +++ b/packages/react-native-vega/package.json @@ -31,6 +31,7 @@ "kepler/turbo-modules/*.h", "kepler/turbo-modules/generated/**", "CMakeLists.txt", + "cmake/**", "react-native.config.js" ], "types": "lib/typescript/index.d.ts", @@ -44,7 +45,7 @@ "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 && keplerscript-turbomodule-api codegen src/turbo-modules/NativeDdRum.ts -o kepler/turbo-modules/ --namespace DdRumTurboModule --className DdRum", + "codegen": "keplerscript-turbomodule-api codegen src/turbo-modules/NativeDdSdk.ts -o kepler/turbo-modules/ --namespace DdSdkTurboModule --className DdSdk && keplerscript-turbomodule-api codegen src/turbo-modules/NativeDdRum.ts -o kepler/turbo-modules/ --namespace DdRumTurboModule --className DdRum && keplerscript-turbomodule-api codegen src/turbo-modules/NativeDdLogs.ts -o kepler/turbo-modules/ --namespace DdLogsTurboModule --className DdLogs", "test:native": "cmake -S tests -B build/host-tests && cmake --build build/host-tests && ctest --test-dir build/host-tests --output-on-failure" }, "dependencies": { diff --git a/packages/react-native-vega/src/DdLogsVega.ts b/packages/react-native-vega/src/DdLogsVega.ts new file mode 100644 index 000000000..7fd26c790 --- /dev/null +++ b/packages/react-native-vega/src/DdLogsVega.ts @@ -0,0 +1,75 @@ +/* + * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. + * This product includes software developed at Datadog (https://www.datadoghq.com/). + * Copyright 2016-Present Datadog, Inc. + */ + +import type { ErrorSource } from '@datadog/mobile-react-native'; + +import { callNative } from './callNative'; +import { getNativeDdLogs } from './turbo-modules/NativeDdLogs'; + +type LogArguments = [message: string, context?: object]; +type LogWithErrorArguments = [ + message: string, + errorKind?: string, + errorMessage?: string, + stacktrace?: string, + context?: object, + fingerprint?: string, + source?: ErrorSource +]; +type LogLevel = 'debug' | 'info' | 'warn' | 'error'; + +class DdLogsVega { + debug = (...args: LogArguments | LogWithErrorArguments): Promise => + this.send('debug', args); + info = (...args: LogArguments | LogWithErrorArguments): Promise => + this.send('info', args); + warn = (...args: LogArguments | LogWithErrorArguments): Promise => + this.send('warn', args); + error = (...args: LogArguments | LogWithErrorArguments): Promise => + this.send('error', args); + + private send = async ( + level: LogLevel, + args: LogArguments | LogWithErrorArguments + ): Promise => { + await callNative(getNativeDdLogs, native => { + const hasError = + typeof args[1] === 'string' || + typeof args[2] === 'string' || + typeof args[3] === 'string' || + args[4] != null || + typeof args[5] === 'string' || + typeof args[6] === 'string'; + if (!hasError) { + return native.log( + level, + args[0], + '', + '', + '', + (args[1] as object) ?? {} + ); + } + const errorArgs = args as LogWithErrorArguments; + const context = { ...errorArgs[4] }; + if (errorArgs[5]) { + Object.assign(context, { + '_dd.error.fingerprint': errorArgs[5] + }); + } + return native.log( + level, + args[0], + errorArgs[1] ?? '', + errorArgs[2] ?? '', + errorArgs[3] ?? '', + context + ); + }); + }; +} + +export const DdLogs = new DdLogsVega(); diff --git a/packages/react-native-vega/src/DdSdkReactNativeVega.ts b/packages/react-native-vega/src/DdSdkReactNativeVega.ts index 508acb176..b03d45ca0 100644 --- a/packages/react-native-vega/src/DdSdkReactNativeVega.ts +++ b/packages/react-native-vega/src/DdSdkReactNativeVega.ts @@ -4,12 +4,24 @@ * Copyright 2016-Present Datadog, Inc. */ -import { AttributesSingleton } from '@datadog/mobile-react-native/internal'; +import { + AttributesSingleton, + UserInfoSingleton, + AccountInfoSingleton +} from '@datadog/mobile-react-native/internal'; import type { Attributes } from '@datadog/mobile-react-native/internal'; import { callNative } from './callNative'; import { getNativeDdSdk } from './turbo-modules/NativeDdSdk'; +type UserInfo = { + id: string; + name?: string; + email?: string; + extraInfo?: Record; +}; +type AccountInfo = Omit; + /** Global attributes for future events; SDK initialization is added separately. */ export class DdSdkReactNative { static addAttribute = async ( @@ -54,4 +66,71 @@ export class DdSdkReactNative { AttributesSingleton.getInstance().removeAttributes(keys); } }; + static setUserInfo = async (info: UserInfo): Promise => { + if (typeof info?.id !== 'string' || !info.id) { + return; + } + const snapshot = { ...info }; + if ( + await callNative(getNativeDdSdk, native => + native.setUserInfo(snapshot) + ) + ) { + UserInfoSingleton.getInstance().setUserInfo(snapshot); + } + }; + static clearUserInfo = async (): Promise => { + if ( + await callNative(getNativeDdSdk, native => native.clearUserInfo()) + ) { + UserInfoSingleton.getInstance().clearUserInfo(); + } + }; + static addUserExtraInfo = async ( + info: Record + ): Promise => { + if ( + await callNative(getNativeDdSdk, native => + native.addUserExtraInfo(info) + ) + ) { + UserInfoSingleton.getInstance().addUserExtraInfo(info); + } + }; + static setAccountInfo = async (info: AccountInfo): Promise => { + if (typeof info?.id !== 'string' || !info.id) { + return; + } + const snapshot = { ...info }; + if ( + await callNative(getNativeDdSdk, native => + native.setAccountInfo(snapshot) + ) + ) { + AccountInfoSingleton.getInstance().setAccountInfo(snapshot); + } + }; + static clearAccountInfo = async (): Promise => { + if ( + await callNative(getNativeDdSdk, native => + native.clearAccountInfo() + ) + ) { + AccountInfoSingleton.getInstance().clearAccountInfo(); + } + }; + static addAccountExtraInfo = async ( + info: Record + ): Promise => { + if (!AccountInfoSingleton.getInstance().getAccountInfo()) { + return; + } + if ( + await callNative(getNativeDdSdk, native => + native.addAccountExtraInfo(info) + ) + ) { + AccountInfoSingleton.getInstance().addAccountExtraInfo(info); + } + }; } diff --git a/packages/react-native-vega/src/index.ts b/packages/react-native-vega/src/index.ts index eb5473d93..37ed2edd1 100644 --- a/packages/react-native-vega/src/index.ts +++ b/packages/react-native-vega/src/index.ts @@ -7,3 +7,4 @@ export { startHttpProxy } from './HttpProxy'; export { DdRum } from './DdRumVega'; export { DdSdkReactNative } from './DdSdkReactNativeVega'; +export { DdLogs } from './DdLogsVega'; diff --git a/packages/react-native-vega/src/turbo-modules/NativeDdLogs.ts b/packages/react-native-vega/src/turbo-modules/NativeDdLogs.ts new file mode 100644 index 000000000..2bed09eb0 --- /dev/null +++ b/packages/react-native-vega/src/turbo-modules/NativeDdLogs.ts @@ -0,0 +1,24 @@ +/* + * Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0. + * This product includes software developed at Datadog (https://www.datadoghq.com/). + * Copyright 2016-Present Datadog, Inc. + */ + +// Kepler codegen requires Object for arbitrary bridge dictionaries. +/* eslint-disable @typescript-eslint/ban-types */ +import type { KeplerTurboModule } from '@amazon-devices/keplerscript-turbomodule-api'; +import { TurboModuleRegistry } from '@amazon-devices/keplerscript-turbomodule-api'; + +export interface DdLogs extends KeplerTurboModule { + log( + level: string, + message: string, + errorKind: string, + errorMessage: string, + stacktrace: string, + context: Object + ): Promise; +} + +export const getNativeDdLogs = (): DdLogs | null => + TurboModuleRegistry.get('DdLogs') ?? null; diff --git a/packages/react-native-vega/src/turbo-modules/NativeDdSdk.ts b/packages/react-native-vega/src/turbo-modules/NativeDdSdk.ts index 3cc5c1e9f..b0d5a9147 100644 --- a/packages/react-native-vega/src/turbo-modules/NativeDdSdk.ts +++ b/packages/react-native-vega/src/turbo-modules/NativeDdSdk.ts @@ -13,6 +13,12 @@ export interface DdSdk extends KeplerTurboModule { removeAttribute(key: string): Promise; addAttributes(attributes: Object): Promise; removeAttributes(keys: string[]): Promise; + setUserInfo(info: Object): Promise; + clearUserInfo(): Promise; + addUserExtraInfo(info: Object): Promise; + setAccountInfo(info: Object): Promise; + clearAccountInfo(): Promise; + addAccountExtraInfo(info: Object): Promise; startHttpProxy(): Promise; stopHttpProxy(): Promise; httpResponse(requestId: string, statusCode: number): Promise; diff --git a/packages/react-native-vega/tests/CMakeLists.txt b/packages/react-native-vega/tests/CMakeLists.txt index 0ba678da1..ecd97c6fa 100644 --- a/packages/react-native-vega/tests/CMakeLists.txt +++ b/packages/react-native-vega/tests/CMakeLists.txt @@ -42,3 +42,36 @@ if(DATADOG_CPP_SOURCE_DIR AND KEPLER_INCLUDE_DIR AND NODE_API_INCLUDE_DIR) ${NODE_API_INCLUDE_DIR}) add_test(NAME AttributeConverter COMMAND AttributeConverterTest) endif() + +# Exercise logger registration against the actual pinned SDK, including its +# compatibility patch. Opt in because this builds the complete SDK on the host. +option(VEGA_TEST_LOGGING_CONFIGURATION "Build real SDK logging registration tests" OFF) +if(VEGA_TEST_LOGGING_CONFIGURATION) + if(NOT DATADOG_CPP_SOURCE_DIR OR NOT KEPLER_INCLUDE_DIR OR NOT NODE_API_INCLUDE_DIR) + message(FATAL_ERROR "Logging configuration tests require the SDK and Kepler/Node include paths") + endif() + set(DD_BUILD_SHARED OFF CACHE BOOL "" FORCE) + set(DD_CRASH_MODE "noop" CACHE STRING "" FORCE) + set(DD_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE) + set(DD_BUILD_TESTING OFF CACHE BOOL "" FORCE) + set(DD_BUILD_TOOLS OFF CACHE BOOL "" FORCE) + set(DD_BUILD_INSTALL OFF CACHE BOOL "" FORCE) + set(DD_BUILD_PACKAGE OFF CACHE BOOL "" FORCE) + add_subdirectory("${DATADOG_CPP_SOURCE_DIR}" datadog) + include(../cmake/DatadogLoggingCompatibility.cmake) + datadog_vega_patch_logging_registration("${DATADOG_CPP_SOURCE_DIR}") + add_executable(LoggingConfigurationTest + LoggingConfigurationTest.cpp + ../kepler/turbo-modules/LoggingConfiguration.cpp + ../kepler/turbo-modules/DatadogGlobalState.cpp) + target_compile_features(LoggingConfigurationTest PRIVATE cxx_std_17) + target_compile_definitions(LoggingConfigurationTest PRIVATE NDEBUG) + target_include_directories(LoggingConfigurationTest PRIVATE + ../kepler/turbo-modules + ${KEPLER_INCLUDE_DIR} + ${KEPLER_INCLUDE_DIR}/Kepler/turbomodule + ${NODE_API_INCLUDE_DIR}) + target_link_libraries(LoggingConfigurationTest PRIVATE Datadog::sdk) + add_test(NAME LoggingConfiguration COMMAND LoggingConfigurationTest "${CMAKE_CURRENT_BINARY_DIR}/logging-test-data") + set_tests_properties(LoggingConfiguration PROPERTIES TIMEOUT 10) +endif() diff --git a/packages/react-native-vega/tests/LoggingConfigurationTest.cpp b/packages/react-native-vega/tests/LoggingConfigurationTest.cpp new file mode 100644 index 000000000..5a21a9f34 --- /dev/null +++ b/packages/react-native-vega/tests/LoggingConfigurationTest.cpp @@ -0,0 +1,97 @@ +// 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 +#include +#include + +#include "FeatureAttributes.h" +#include "LoggingConfiguration.h" + +using namespace datadog_rn_vega; + +void check(bool condition, const char *message) { + if (!condition) { + std::cerr << message << std::endl; + std::exit(1); + } +} + +bool addAttribute() { + return applyToFeatures([](auto &feature) { + feature.AddAttribute("enabled", datadog::Attribute::Bool(true)); + }); +} + +int main(int argc, char **argv) { + check(argc == 2, "test data directory is required"); + const std::filesystem::path directory(argv[1]); + std::filesystem::create_directories(directory); + auto &state = DatadogGlobalState::getInstance(); + auto createCore = [&](const std::string &name) { + std::filesystem::create_directories(directory / name); + datadog::CoreConfig config("test-token", "test-service", "test"); + config.SetApplicationStoragePath((directory / name).string()); + return datadog::Core::Create(config, datadog::TrackingConsent::Pending); + }; + auto expectDisabled = [&] { + check(!state.getLogging(), + "failed registration stored a logging feature"); + check(!state.getLogger(), "failed registration stored a logger"); + check(!addAttribute(), + "failed registration accepted logging-only attributes"); + }; + + configureLogging(nullptr, {}); + expectDisabled(); + + datadog::CoreConfig invalid("", "test-service", "test"); + configureLogging( + datadog::Core::Create(invalid, datadog::TrackingConsent::Pending), {}); + expectDisabled(); + + const auto blocked = directory / "storage-file"; + std::ofstream(blocked) << "not a directory"; + datadog::CoreConfig storageFailure("test-token", "test-service", "test"); + storageFailure.SetApplicationStoragePath(blocked.string()); + configureLogging(datadog::Core::Create(storageFailure, + datadog::TrackingConsent::Pending), + {}); + expectDisabled(); + + auto registered = createCore("already-registered"); + auto externalLogging = datadog::Logging::Register(registered); + check(bool(externalLogging), "test setup could not register logging"); + configureLogging(registered, {}); + expectDisabled(); + + check(registered->Start(), "test setup could not start core"); + configureLogging(registered, {}); + expectDisabled(); + registered->Stop(); + + auto core = createCore("working"); + configureLogging(core, {}); + auto logging = state.getLogging(); + auto logger = state.getLogger(); + check(bool(logging) && bool(logger), + "valid logging registration was not published"); + check(addAttribute(), "logging-only attributes were not accepted"); + configureLogging(core, {{"bundleLogsWithRum", false}}); + check(state.getLogging() == logging, + "repeat configuration replaced working logging"); + check(state.getLogger() == logger, + "repeat configuration replaced working logger"); + check(core->Start(), "configured logging could not start"); + configureLogging(core, {}); + check(state.getLogger() == logger, + "configuration after start replaced working logger"); + core->Stop(); + state.reset(); + expectDisabled(); + std::cout << "Logging configuration tests passed" << std::endl; +}