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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
288 changes: 274 additions & 14 deletions .github/workflows/ci.yml

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions example-expo/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# CNG: generated by `expo prebuild`
/android
/ios
.expo/
10 changes: 10 additions & 0 deletions example-expo/app.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"expo": {
"name": "OpenTelemetryExpo",
"slug": "opentelemetry-example-expo",
"version": "1.0.0",
"ios": {"bundleIdentifier": "opentelemetry.example.expo"},
"android": {"package": "opentelemetry.example.expo"},
"plugins": ["react-native-open-telemetry", "./plugins/withOtelExample"]
}
}
14 changes: 14 additions & 0 deletions example-expo/babel.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// The bare example's inline OTEL_TEST_MODE plugin (test mode is a bundle-time flag).
const inlineTestMode = require('../example/inlineTestMode');

module.exports = api => {
// babel-preset-expo keeps native async on web, which the context patch cannot see through: lower it (README)
const web = api.caller(c => c?.platform === 'web');
return {
presets: ['babel-preset-expo'],
plugins: [
inlineTestMode,
...(web ? ['@babel/plugin-transform-async-generator-functions', '@babel/plugin-transform-async-to-generator'] : []),
],
};
};
1,070 changes: 1,070 additions & 0 deletions example-expo/bun.lock

Large diffs are not rendered by default.

16 changes: 16 additions & 0 deletions example-expo/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import {registerRootComponent} from 'expo';
import {Platform} from 'react-native';
import {startReactNativeSdk} from 'react-native-open-telemetry';
import {ScenariosScreen} from '../example/src/ScenariosScreen';

// JS-fallback init: no native init in this app, so this call initializes native from the config (spec §4.4).
// No serviceVersion: the test-mode resource is service.name only (R2). Same collector and headers as the bare app.
startReactNativeSdk({
serviceName: 'verify',
exportConfig: {
url: Platform.OS === 'android' ? 'http://10.0.2.2:4318/v1/traces' : 'http://localhost:4318/v1/traces',
headers: {'x-api-key': 'test'}, // asserted by verify/e2e/export-headers.e2e.ts
},
});

registerRootComponent(ScenariosScreen);
30 changes: 30 additions & 0 deletions example-expo/metro.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const path = require('path');
const {getDefaultConfig} = require('expo/metro-config');
const {mergeConfig} = require('@expo/metro/metro-config');
const {withOtel} = require('../metro');

const root = path.resolve(__dirname, '..');
const own = p => path.join(__dirname, 'node_modules', p);
// The repo root and the bare example have their own copies of these; the app must use exactly one.
const single = ['react', 'react-native', 'react-native-nitro-modules', '@react-native'];
const escape = s => s.replace(/[/\-\\^$*+?.()|[\]{}]/g, '\\$&');
const block = dir => single.map(m => new RegExp(`^${escape(path.join(dir, 'node_modules', m))}[/\\\\].*`));

const config = {
// babel.config.js inlines OTEL_TEST_MODE; keep test-mode and normal transforms in separate caches
cacheVersion: `otel-test-mode=${process.env.OTEL_TEST_MODE ?? ''}`,
// the library (exports -> lib/), the bare example's ScenariosScreen and verify/
watchFolders: [root],
resolver: {
nodeModulesPaths: [path.join(__dirname, 'node_modules'), path.join(root, 'node_modules')],
blockList: [...block(root), ...block(path.join(root, 'example'))],
extraNodeModules: {...Object.fromEntries(single.map(m => [m, own(m)])), 'react-native-open-telemetry': root},
// web has no Nitro: ScenariosScreen's HybridObject lookups find none
resolveRequest: (ctx, name, platform) =>
platform === 'web' && name === 'react-native-nitro-modules'
? {type: 'sourceFile', filePath: path.join(__dirname, 'nitro-stub.web.ts')}
: ctx.resolveRequest(ctx, name, platform),
},
};

module.exports = withOtel(mergeConfig(getDefaultConfig(__dirname), config));
5 changes: 5 additions & 0 deletions example-expo/nitro-stub.web.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// Web has no Nitro: no HybridObject is registered, so getOtel() is undefined and scenarios get no `native`.
export const NitroModules = {
hasHybridObject: () => false,
createHybridObject: () => undefined,
};
20 changes: 20 additions & 0 deletions example-expo/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "react-native-open-telemetry-example-expo",
"version": "0.0.1",
"private": true,
"main": "index.js",
"scripts": {
"postinstall": "test -e node_modules/react-native-open-telemetry || ln -sfn ../.. node_modules/react-native-open-telemetry",
"prebuild": "expo prebuild --clean --no-install",
"web:e2e": "expo export -p web --clear && expo serve --port 4173"
},
"dependencies": {
"@expo/metro-runtime": "~58.0.17",
"expo": "58.0.26",
"react": "19.3.0",
"react-dom": "19.3.0",
"react-native": "0.88.1",
"react-native-nitro-modules": "0.37.2",
"react-native-web": "^0.21.4"
}
}
36 changes: 36 additions & 0 deletions example-expo/plugins/withOtelExample.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const {withAndroidManifest, withAppBuildGradle, withGradleProperties} = require('expo/config-plugins');

// Same as the bare example's app/build.gradle: the bundle task sees only this app's dir, so a change to the package
// (lib/, src/), the scenarios or OTEL_TEST_MODE would otherwise leave the old bundle in the APK.
const BUNDLE_INPUTS = `
// withOtelExample: rebundle when lib/, src/, verify/ or OTEL_TEST_MODE change
tasks.matching { it.name.startsWith("createBundle") }.configureEach {
inputs.property("otelTestMode", System.getenv("OTEL_TEST_MODE") ?: "")
inputs.files(fileTree("../../..") { include "lib/**", "src/**", "verify/scenarios/**", "verify/harness/*.ts" })
}
`;

/**
* Example-only (Task 28): what the bare example's native projects carry by hand, applied at `expo prebuild`. The Core
* pod (R24) comes from the package's own plugin (`react-native-open-telemetry` in app.json), as in a real Expo app.
*/
module.exports = config => {
config = withAppBuildGradle(config, c => {
if (!c.modResults.contents.includes('withOtelExample: rebundle')) c.modResults.contents += BUNDLE_INPUTS;
return c;
});
// EXAMPLE-ONLY, DO NOT COPY: app-wide cleartext so the e2e collector (plain http, also with test mode off) is reachable.
// ponytail: any host, not only 10.0.2.2 like the bare app's network_security_config. None of this file is what a real
// Expo app needs; it needs only the package's plugin.
config = withAndroidManifest(config, c => {
c.modResults.manifest.application[0].$['android:usesCleartextTraffic'] = 'true';
return c;
});
// Test mode is a build flag: `OTEL_TEST_MODE=1 expo prebuild` (Android); iOS takes it at `OTEL_TEST_MODE=1 pod install`.
if (process.env.OTEL_TEST_MODE === '1')
config = withGradleProperties(config, c => {
c.modResults.push({type: 'property', key: 'otelTestMode', value: 'true'});
return c;
});
return config;
};
9 changes: 9 additions & 0 deletions example-expo/react-native.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const path = require('path');

// Autolink the library from the repo root and the bare example's TestNative module (no npm dependency needed).
module.exports = {
dependencies: {
'react-native-open-telemetry': {root: path.join(__dirname, '..')},
'react-native-test-native': {root: path.join(__dirname, '../example/modules/test-native')},
},
};
9 changes: 9 additions & 0 deletions example/android/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ android {
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
// test mode is a build flag (-PotelTestMode=true); MainApplication reads test-only overrides only then
buildConfigField "boolean", "OTEL_TEST_MODE", ((findProperty("otelTestMode") ?: "false").toString() == "true").toString()
}
signingConfigs {
debug {
Expand All @@ -107,6 +109,13 @@ android {
}
}

// The bundle task's inputs are example/ only. It also bundles the package (lib/, src/) and the verify scenarios, and
// babel.config.js inlines OTEL_TEST_MODE: without these, a change there or a test-mode switch reuses the old bundle.
tasks.matching { it.name.startsWith("createBundle") }.configureEach {
inputs.property("otelTestMode", System.getenv("OTEL_TEST_MODE") ?: "")
inputs.files(fileTree("../../..") { include "lib/**", "src/**", "verify/scenarios/**", "verify/harness/*.ts" })
}

dependencies {
// The version of react-native is set by the React Native Gradle Plugin
implementation("com.facebook.react:react-android")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ class MainApplication : Application(), ReactApplication {

override fun onCreate() {
super.onCreate()
startOtel() // native-first init, before React Native (OtelInit.kt)
loadReactNative(this)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package opentelemetry.example

import android.app.Application
import com.callstack.otel.RNOtel
import java.io.File

/**
* Native-first init, called from MainApplication.onCreate before React Native. Its own file so the nightly
* (verify/nightly/app.sh) can add it unchanged to a freshly generated app at another RN version.
* No serviceVersion: the test-mode resource is service.name only (R2).
*/
internal fun Application.startOtel() {
RNOtel.start(this) {
serviceName = "verify"
export {
url = testExportUrl() ?: "http://10.0.2.2:4318/v1/traces" // the e2e collector on the host
headers = mapOf("x-api-key" to "test") // asserted by verify/e2e/export-headers.e2e.ts
}
}
// compile check: the otel API is part of RNOtel's public surface (a no-op tracer is cheap to build)
RNOtel.tracer("opentelemetry.example")
}

/**
* Test-mode builds only: verify/e2e/native-init-failure.e2e.ts overrides the URL. Application.onCreate cannot see
* launch arguments (they reach the Activity), so the test writes this file with adb and removes it afterwards.
*/
private fun Application.testExportUrl(): String? =
if (!BuildConfig.OTEL_TEST_MODE) null
else File(getExternalFilesDir(null), "otel-export-url").takeIf { it.exists() }?.readText()?.trim()
2 changes: 1 addition & 1 deletion example/android/build.gradle
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
buildscript {
ext {
buildToolsVersion = "37.0.0"
minSdkVersion = 24
minSdkVersion = 26
compileSdkVersion = 37
targetSdkVersion = 36
ndkVersion = "27.1.12297006"
Expand Down
9 changes: 1 addition & 8 deletions example/babel.config.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,4 @@
// Test mode is a build flag: inline process.env.OTEL_TEST_MODE at bundle time (e2e builds set it to 1).
const inlineTestMode = ({types: t}) => {
const visit = p => {
if (p.get('object').matchesPattern('process.env') && t.isIdentifier(p.node.property, {name: 'OTEL_TEST_MODE'}))
p.replaceWith(process.env.OTEL_TEST_MODE == null ? t.identifier('undefined') : t.stringLiteral(process.env.OTEL_TEST_MODE));
};
return {visitor: {MemberExpression: visit, OptionalMemberExpression: visit}};
};
const inlineTestMode = require('./inlineTestMode');

module.exports = {
presets: ['module:@react-native/babel-preset'],
Expand Down
10 changes: 10 additions & 0 deletions example/inlineTestMode.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// Test mode is a build flag: inline process.env.OTEL_TEST_MODE at bundle time (e2e builds set it to 1).
const inlineTestMode = ({types: t}) => {
const visit = p => {
if (p.get('object').matchesPattern('process.env') && t.isIdentifier(p.node.property, {name: 'OTEL_TEST_MODE'}))
p.replaceWith(process.env.OTEL_TEST_MODE == null ? t.identifier('undefined') : t.stringLiteral(process.env.OTEL_TEST_MODE));
};
return {visitor: {MemberExpression: visit, OptionalMemberExpression: visit}};
};

module.exports = inlineTestMode; // also used by example-expo/babel.config.js
26 changes: 25 additions & 1 deletion example/ios/OpenTelemetryExample/AppDelegate.swift
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import ReactNativeOpenTelemetryCore
import UIKit

@main
Expand All @@ -6,6 +7,29 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
) -> Bool {
true
startOtel()
return true
}
}

// otel-init: verify/nightly/app.sh appends this line and everything below it to a freshly generated AppDelegate.swift.
/// Native-first init, before React Native. No serviceVersion: the test-mode resource is service.name only (R2).
func startOtel() {
RNOtel.start { c in
c.serviceName = "verify"
// the e2e collector on the host; asserted by verify/e2e/export-headers.e2e.ts
c.export = .init(url: testExportUrl() ?? "http://localhost:4318/v1/traces", headers: ["x-api-key": "test"])
}
// compile check: the otel API is part of RNOtel's public surface (a no-op tracer is cheap to build)
_ = RNOtel.tracer("opentelemetry.example")
}

/// Test-mode builds only: verify/e2e/native-init-failure.e2e.ts launches with `--otel-export-url=<url>`.
private func testExportUrl() -> String? {
#if OTEL_TEST_MODE
let prefix = "--otel-export-url="
return ProcessInfo.processInfo.arguments.first { $0.hasPrefix(prefix) }.map { String($0.dropFirst(prefix.count)) }
#else
return nil
#endif
}
11 changes: 11 additions & 0 deletions example/ios/Podfile
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ if linkage != nil
end

target 'OpenTelemetryExample' do
# Autolinking links only the Nitro pod; the pure Swift core pod (RNOtel, imported by AppDelegate) is declared here (R24).
pod 'ReactNativeOpenTelemetryCore', :path => '../..'
config = use_native_modules!

use_react_native!(
Expand All @@ -30,5 +32,14 @@ target 'OpenTelemetryExample' do
:mac_catalyst_enabled => false,
# :ccache_enabled => true
)
# Test mode reaches the app target too: AppDelegate reads test-only launch arguments under `#if OTEL_TEST_MODE`.
if ENV['OTEL_TEST_MODE'] == '1'
installer.aggregate_targets.each do |t|
t.xcconfigs.each do |name, xc|
xc.attributes['SWIFT_ACTIVE_COMPILATION_CONDITIONS'] = '$(inherited) OTEL_TEST_MODE'
xc.save_as(t.xcconfig_path(name))
end
end
end
end
end
41 changes: 39 additions & 2 deletions example/ios/Podfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1789,9 +1789,38 @@ PODS:
- ReactCodegen
- ReactCommon/turbomodule/core
- ReactNativeDependencies
- ReactNativeOpenTelemetryCore (= 0.2.0)
- Yoga
- ReactNativeOpenTelemetryCore (0.2.0)
- SocketRocket (0.7.1):
- ReactNativeDependencies
- TestNative (0.0.0):
- hermes-engine
- NitroModules
- RCTRequired
- RCTTypeSafety
- React-bridging
- React-callinvoker
- React-Core
- React-Core-prebuilt
- React-cxxstableapi
- React-debug
- React-Fabric
- React-featureflags
- React-graphics
- React-ImageManager
- React-jsi
- React-NativeModulesApple
- React-RCTFabric
- React-renderercss
- React-rendererdebug
- React-utils
- ReactCodegen
- ReactCommon/turbomodule/core
- ReactNativeDependencies
- ReactNativeOpenTelemetry
- ReactNativeOpenTelemetryCore
- Yoga
- Yoga (0.0.0):
- React-Core-prebuilt

Expand Down Expand Up @@ -1883,7 +1912,9 @@ DEPENDENCIES:
- ReactCommon/turbomodule/core (from `../node_modules/react-native/ReactCommon`)
- ReactNativeDependencies (from `../node_modules/react-native/third-party-podspecs/ReactNativeDependencies.podspec`)
- ReactNativeOpenTelemetry (from `../..`)
- ReactNativeOpenTelemetryCore (from `../..`)
- SocketRocket (from `build/rndeps-facades/SocketRocket`)
- TestNative (from `../modules/test-native`)
- Yoga (from `build/rncore-facades/Yoga`)

EXTERNAL SOURCES:
Expand Down Expand Up @@ -2060,8 +2091,12 @@ EXTERNAL SOURCES:
:podspec: "../node_modules/react-native/third-party-podspecs/ReactNativeDependencies.podspec"
ReactNativeOpenTelemetry:
:path: "../.."
ReactNativeOpenTelemetryCore:
:path: "../.."
SocketRocket:
:path: build/rndeps-facades/SocketRocket
TestNative:
:path: "../modules/test-native"
Yoga:
:path: build/rncore-facades/Yoga

Expand Down Expand Up @@ -2151,10 +2186,12 @@ SPEC CHECKSUMS:
ReactCodegen: 3840312f5071bb6b953b35a029c5c6dcf06b435e
ReactCommon: b63ce798b898ed77c6cfdeb80b18080161f52ed5
ReactNativeDependencies: a5164c3ebbe90d992022b5d9cbabbf770a6d7d05
ReactNativeOpenTelemetry: 41460d3f8f1e8fd6922cb815c46fb80c4843bd03
ReactNativeOpenTelemetry: ca8cf471e09f5c90d61a9105e163ee8a4f66160d
ReactNativeOpenTelemetryCore: b9b1d5e27b1df7d86e4937554d2c9152e85df541
SocketRocket: 37aec555668fb852ec12e3c0de59a86ca58f0871
TestNative: 256fa8cff013c95afd55f46437705c7387ad6b16
Yoga: d1c536142c5ff8ec8cd856ab2a7c227a1d875c8e

PODFILE CHECKSUM: 2f80b8c0e897d23dcb020369108758aff0cbef0e
PODFILE CHECKSUM: bc90526914a3954cc63e80dcd3edb75bde6b4a2a

COCOAPODS: 1.17.0
Loading
Loading