Skip to content
Merged
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
12 changes: 1 addition & 11 deletions ReactNativeOpenTelemetry.podspec
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ require "json"

package = JSON.parse(File.read(File.join(__dir__, "package.json")))

# The Nitro adapter (Swift with C++ interop) over the pure Swift core pod (spec §4.2).
Pod::Spec.new do |s|
s.name = "ReactNativeOpenTelemetry"
s.version = package["version"]
Expand All @@ -16,16 +15,11 @@ Pod::Spec.new do |s|

s.source_files = ["ios/Adapter/**/*.swift"]

# The core pod uses spm_dependency, so in a static-library build React Native's spm.rb builds it straight into the
# products root, and rewrites the app's module map path to match, but not this pod's: CocoaPods still points it at
# `<root>/ReactNativeOpenTelemetryCore/ReactNativeOpenTelemetryCore.modulemap`. Forward that path to the real map, and
# search the root for the core's swiftmodule. Unused (and harmless) with frameworks.
# ponytail: drop when RN's spm.rb rewrites pod-target xcconfigs too.
core_map = '${PODS_CONFIGURATION_BUILD_DIR}/ReactNativeOpenTelemetryCore/ReactNativeOpenTelemetryCore.modulemap'
s.script_phase = {
:name => 'Forward the core module map',
:execution_position => :before_compile,
:always_out_of_date => '1', # no inputs: run every build on purpose (silences the Xcode warning)
:always_out_of_date => '1',
:script => %Q{set -e
if [ -f "${PODS_CONFIGURATION_BUILD_DIR}/ReactNativeOpenTelemetryCore.modulemap" ]; then
mkdir -p "${PODS_CONFIGURATION_BUILD_DIR}/ReactNativeOpenTelemetryCore"
Expand All @@ -34,17 +28,13 @@ fi
},
}
s.pod_target_xcconfig = {
# `package` declarations of the core are shared through one Swift package name.
'OTHER_SWIFT_FLAGS' => '$(inherited) -package-name ReactNativeOpenTelemetry',
'SWIFT_INCLUDE_PATHS' => '$(inherited) "${PODS_CONFIGURATION_BUILD_DIR}"',
}

# Adds nitrogen/generated/ios/** and nitrogen/generated/shared/**.
load 'nitrogen/generated/ios/ReactNativeOpenTelemetry+autolinking.rb'
add_nitrogen_files(s)

# JsReadableSpan imports opentelemetry-swift too. No spm_dependency here (it would move this pod's module map, see
# above): the core pod's SwiftPM products are built into the products root, which SWIFT_INCLUDE_PATHS searches.
s.dependency 'ReactNativeOpenTelemetryCore', s.version.to_s
s.dependency 'React-jsi'
s.dependency 'React-callinvoker'
Expand Down
7 changes: 0 additions & 7 deletions android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@ def getExtOrIntegerDefault(name) {
return getExtOrDefault(name).toInteger()
}

// Test mode is a build flag, never API: -PotelTestMode=true (or otelTestMode=true in the app's gradle.properties).
def otelTestMode = (findProperty("otelTestMode") ?: "false").toString() == "true"
// telemetry.distro.version = the npm package version
def otelDistroVersion = new groovy.json.JsonSlurper().parse(file("../package.json")).version

android {
Expand All @@ -32,7 +30,6 @@ android {
targetSdkVersion getExtOrIntegerDefault("targetSdkVersion")
buildConfigField "boolean", "OTEL_TEST_MODE", otelTestMode.toString()
buildConfigField "String", "OTEL_DISTRO_VERSION", "\"${otelDistroVersion}\""
// apps that minify (Expo's release default) need these
consumerProguardFiles "consumer-rules.pro"

externalNativeBuild {
Expand Down Expand Up @@ -100,15 +97,11 @@ repositories {
dependencies {
implementation "com.facebook.react:react-android"
implementation project(":react-native-nitro-modules")
// ProcessLifecycleOwner: background flush on ON_STOP (same version React Native already resolves)
implementation "androidx.lifecycle:lifecycle-process:2.6.2"

// RNOtel's public signatures expose Tracer, Span and Context: the API is part of ours
api platform("io.opentelemetry:opentelemetry-bom:1.68.0")
api "io.opentelemetry:opentelemetry-api"
implementation "io.opentelemetry:opentelemetry-sdk"
// The OkHttp sender runs on React Native's own OkHttp (every okhttp3 member the 1.68 sender uses exists in 4.9.2);
// excluding it keeps otel-java from pulling the app up to OkHttp 5.
implementation("io.opentelemetry:opentelemetry-exporter-otlp") {
exclude group: "com.squareup.okhttp3", module: "okhttp"
}
Expand Down
5 changes: 0 additions & 5 deletions android/consumer-rules.pro
Original file line number Diff line number Diff line change
@@ -1,11 +1,6 @@
# Guarded by the minified Expo release e2e: recheck these rules on every otel-java bump.
# otel-java references optional, compile-only classes it never loads at runtime here (no autoconfigure, no incubator,
# annotations only); R8 in a minifying app fails on them as missing.
-dontwarn com.google.auto.value.**
-dontwarn com.google.errorprone.annotations.**
-dontwarn io.opentelemetry.api.incubator.**
-dontwarn io.opentelemetry.sdk.autoconfigure.spi.**

# otel-java's ResourceMarshaler reaches Resource/ResourceBuilder entity methods by reflection (EntityUtil) on every
# export; renamed or merged, the export throws and nothing is sent.
-keep class io.opentelemetry.sdk.resources.** { *; }
6 changes: 0 additions & 6 deletions android/fix-prefab.gradle
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
tasks.configureEach { task ->
// Make sure that we generate our prefab publication file only after having built the native library
// so that not a header publication file, but a full configuration publication will be generated, which
// will include the .so file

def prefabConfigurePattern = ~/^prefab(.+)ConfigurePackage$/
def matcher = task.name =~ prefabConfigurePattern
Expand Down Expand Up @@ -29,9 +26,6 @@ afterEvaluate {
}

def variants = proj.android.hasProperty('applicationVariants') ? proj.android.applicationVariants : proj.android.libraryVariants
// Touch the prefab_config.json files to ensure that in ExternalNativeJsonGenerator.kt we will re-trigger the prefab CLI to
// generate a libnameConfig.cmake file that will contain our native library (.so).
// See this condition: https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:build-system/gradle-core/src/main/java/com/android/build/gradle/tasks/ExternalNativeJsonGenerator.kt;l=207-219?q=createPrefabBuildSystemGlue
variants.all { variant ->
def variantName = variant.name
abis.each { abi ->
Expand Down
8 changes: 0 additions & 8 deletions android/src/main/java/com/callstack/otel/RNOtel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -20,32 +20,27 @@ import io.opentelemetry.context.Context as OtelContext
import java.io.File
import java.util.concurrent.atomic.AtomicBoolean

/** Public native API (spec §4.3/§4.4). Test mode comes from the build (`-PotelTestMode=true`), never from here. */
object RNOtel {
private const val TAG = "RNOtel"
private val observing = AtomicBoolean()

/** Native-first init from `Application.onCreate`. No-op outside the main process; never throws. */
@JvmStatic
fun start(context: Context, block: RNOtelConfig.() -> Unit) {
try {
val app = context.applicationContext
if (processName() != app.packageName) return
val r = initialize(RNOtelConfig().apply(block).toCore())
// alreadyInitialized: a repeat call; a sticky failure was logged by the first one
if (r.error != null && !r.alreadyInitialized) Log.e(TAG, "init failed; telemetry is off: ${r.error}")
} catch (e: Exception) {
Log.e(TAG, "init failed; telemetry is off", e)
}
}

/** One path for native-first and JS-fallback init. The exporter (OkHttp) is built on first export, on the BSP thread. */
internal fun initialize(config: CoreConfig?): InitResult {
val r = OtelCore.initialize(config, BuildConfig.OTEL_TEST_MODE, BuildConfig.OTEL_DISTRO_VERSION)
if (OtelCore.instance != null && observing.compareAndSet(false, true)) {
Handler(Looper.getMainLooper()).post {
ProcessLifecycleOwner.get().lifecycle.addObserver(object : DefaultLifecycleObserver {
// forceFlush only signals the BSP worker: asynchronous, never join() on the main thread
override fun onStop(owner: LifecycleOwner) {
OtelCore.instance?.tracerProvider?.forceFlush()
}
Expand All @@ -55,22 +50,19 @@ object RNOtel {
return r
}

/** A tracer on the native provider; a no-op tracer before (or without) a successful init. */
@JvmStatic
@JvmOverloads
fun tracer(name: String, version: String? = null): Tracer {
val provider = OtelCore.instance?.tracerProvider ?: OpenTelemetry.noop().tracerProvider
return provider.tracerBuilder(name).apply { version?.let(::setInstrumentationVersion) }.build()
}

/** W3C traceparent -> explicit, non-remote parent context; invalid input -> root. */
@JvmStatic
fun contextFrom(traceparent: String): OtelContext = com.callstack.otel.core.contextFrom(traceparent)

@JvmStatic
fun traceparentOf(span: Span): String = com.callstack.otel.core.traceparentOf(span)

// Application.getProcessName() is API 28+; minSdk is 26.
private fun processName(): String =
if (Build.VERSION.SDK_INT >= 28) Application.getProcessName()
else File("/proc/self/cmdline").readText().substringBefore('\u0000').trim()
Expand Down
2 changes: 0 additions & 2 deletions android/src/main/java/com/callstack/otel/RNOtelConfig.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,13 @@ package com.callstack.otel
import com.callstack.otel.core.CoreConfig
import io.opentelemetry.api.common.Attributes

/** Native-first config (spec §4.4): `RNOtel.start(this) { serviceName = …; export { url = … } }`. */
class RNOtelConfig {
var serviceName: String = ""
var serviceVersion: String? = null
var resourceAttributes: Map<String, String> = emptyMap()
private var export = Export()

class Export {
/** The OTLP/HTTP traces endpoint (e.g. `https://collector:4318/v1/traces`), used as given. */
var url: String = ""
var headers: Map<String, String> = emptyMap()
}
Expand Down
3 changes: 0 additions & 3 deletions android/src/main/java/com/callstack/otel/core/Attributes.kt
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,8 @@ import com.margelo.nitro.callstack.otel.SeamAttribute
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.api.common.Attributes

// Number.isInteger(v): whole and finite (-0 included). Long.MAX_VALUE as Double is 2^63, hence the exclusive bound.
private fun isLong(v: Double) = v == Math.rint(v) && v >= -9.223372036854775807E18 && v < 9.223372036854775807E18

/** JS numbers become `long` iff Number.isInteger (and they fit), else `double`; the same rule on JS, Kotlin, Swift. */
fun attributesOf(list: Array<SeamAttribute>): Attributes {
val b = Attributes.builder()
for (a in list) {
Expand All @@ -27,5 +25,4 @@ fun attributesOf(list: Array<SeamAttribute>): Attributes {
return b.build()
}

/** An `HrTime` `[seconds, nanos]` as epoch nanos. Never throws on the JS thread: missing elements read as 0. */
fun epochNanos(t: DoubleArray): Long = t.getOrElse(0) { 0.0 }.toLong() * 1_000_000_000L + t.getOrElse(1) { 0.0 }.toLong()
2 changes: 0 additions & 2 deletions android/src/main/java/com/callstack/otel/core/CoreConfig.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,8 @@ data class CoreConfig(
val serviceName: String,
val serviceVersion: String? = null,
val resourceAttributes: Attributes = Attributes.empty(),
/** The OTLP/HTTP traces endpoint, used as given. */
val exportUrl: String,
val exportHeaders: Map<String, String> = emptyMap(),
)

/** Mirrors the seam's `SeamInitResult`. */
data class InitResult(val alreadyInitialized: Boolean, val testMode: Boolean, val error: String? = null)
2 changes: 0 additions & 2 deletions android/src/main/java/com/callstack/otel/core/Endpoint.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@ package com.callstack.otel.core

import java.net.URI

/** Eager check (D8), no exporter built: http(s) scheme and a host. Returns an error message or null. */
internal fun validateExportUrl(url: String): String? {
val u = try { URI(url) } catch (e: Exception) { return "invalid exportUrl: ${e.message}" }
// URI.host is null for a host it rejects as a hostname, like `otel_collector`, which iOS and web accept
val host = u.host ?: u.rawAuthority?.substringAfterLast('@')?.substringBefore(':')
if (u.scheme?.lowercase() !in setOf("http", "https") || host.isNullOrEmpty()) {
return "invalid exportUrl \"$url\": expected http(s)://host[:port]"
Expand Down
7 changes: 0 additions & 7 deletions android/src/main/java/com/callstack/otel/core/JsSpanData.kt
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import io.opentelemetry.sdk.trace.data.StatusData
private fun traceState(s: String?): TraceState {
if (s.isNullOrEmpty()) return TraceState.getDefault()
val b = TraceState.builder()
// the builder puts each new entry first, so add the W3C list back to front
for (kv in s.split(',').asReversed()) {
val i = kv.indexOf('=')
if (i > 0) b.put(kv.substring(0, i).trim(), kv.substring(i + 1).trim())
Expand All @@ -31,17 +30,12 @@ private fun traceState(s: String?): TraceState {
private fun contextOf(c: SeamSpanContext): SpanContext =
SpanContext.create(c.traceId, c.spanId, TraceFlags.fromByte(c.traceFlags.toInt().toByte()), traceState(c.traceState))

/**
* A finished JS span handed over the seam: the frozen [ReadableSpan] the native BatchSpanProcessor queues, and the
* [SpanData] it exports. Everything but the span context is computed lazily, on first access from the export thread.
*/
class JsSpanData(private val span: SeamSpan, private val resource: Resource) : ReadableSpan, SpanData {
private val context by lazy { contextOf(span.context) }
private val parent by lazy {
span.parentSpanId?.let { SpanContext.create(span.context.traceId, it, context.traceFlags, context.traceState) }
?: SpanContext.getInvalid()
}
// API SpanKind and Java SpanKind share their order (INTERNAL, SERVER, CLIENT, PRODUCER, CONSUMER); OTLP's +1 is the exporter's job.
private val spanKind by lazy { SpanKind.values().getOrElse(span.kind.toInt()) { SpanKind.INTERNAL } }
private val attrs by lazy { attributesOf(span.attributes) }
private val eventList by lazy { span.events.map { EventData.create(epochNanos(it.time), it.name, attributesOf(it.attributes)) } }
Expand Down Expand Up @@ -76,7 +70,6 @@ class JsSpanData(private val span: SeamSpan, private val resource: Resource) : R
@Suppress("DEPRECATION") InstrumentationLibraryInfo.create(scope.name, scope.version, scope.schemaUrl)
override fun getResource() = resource

// ReadableSpan: frozen, nothing to mutate
override fun toSpanData(): SpanData = this
override fun getLatencyNanos() = endEpochNanos - startEpochNanos
override fun <T : Any?> getAttribute(key: AttributeKey<T>): T? = attrs.get(key)
Expand Down
10 changes: 0 additions & 10 deletions android/src/main/java/com/callstack/otel/core/OtelCore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import io.opentelemetry.sdk.trace.export.BatchSpanProcessor
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicLong

/** Test mode: `0b…` IDs, the native counterpart of JS `sequentialIds('0a')`. */
private class SequentialIds : IdGenerator {
private val t = AtomicLong()
private val s = AtomicLong()
Expand All @@ -22,7 +21,6 @@ private class SequentialIds : IdGenerator {

const val DISTRO_NAME = "react-native-open-telemetry"

/** Built on first export (the export thread), so init on the main thread never constructs an HTTP client. */
private class LazyExporter(private val build: () -> SpanExporter) : SpanExporter {
private val d by lazy(build)
override fun export(spans: Collection<SpanData>) = d.export(spans)
Expand All @@ -31,7 +29,6 @@ private class LazyExporter(private val build: () -> SpanExporter) : SpanExporter
}

class OtelCore(config: CoreConfig, testMode: Boolean = false, distroVersion: String = "unknown") {
/** The one resource of the app; in test mode built from config only (no `telemetry.*`). */
val resource: Resource = (if (testMode) Resource.empty() else Resource.getDefault()).merge(
Resource.create(
config.resourceAttributes.toBuilder()
Expand All @@ -52,17 +49,14 @@ class OtelCore(config: CoreConfig, testMode: Boolean = false, distroVersion: Str
OtlpHttpSpanExporter.builder().setEndpoint(config.exportUrl)
.apply { config.exportHeaders.forEach { (k, v) -> addHeader(k, v) } }.build()
},
// test mode: no timed export within a device test, so only flush and background export send
).apply { if (testMode) setScheduleDelay(120, TimeUnit.SECONDS) }.build()

/** The native TracerProvider; JS spans join its batch processor. */
val tracerProvider: SdkTracerProvider = SdkTracerProvider.builder()
.setResource(resource)
.addSpanProcessor(bsp)
.apply { if (testMode) setIdGenerator(SequentialIds()) }
.build()

/** JS-thread work: wrap and enqueue only; SpanData is built on the export thread. */
fun handOff(spans: Array<SeamSpan>) {
for (s in spans) bsp.onEnd(JsSpanData(s, resource))
}
Expand All @@ -74,10 +68,6 @@ class OtelCore(config: CoreConfig, testMode: Boolean = false, distroVersion: Str
@Volatile var instance: OtelCore? = null
private set

/**
* Idempotent. The first result sticks, a failed one too: later calls never retry. A call without config
* before any init is an error but is not remembered, so the real init can still follow.
*/
@Synchronized fun initialize(config: CoreConfig?, testMode: Boolean = false, distroVersion: String = "unknown"): InitResult {
state?.let { return it.copy(alreadyInitialized = true) }
if (config == null) return InitResult(false, testMode, "not initialized: no config")
Expand Down
5 changes: 0 additions & 5 deletions android/src/main/java/com/callstack/otel/core/Parenting.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,6 @@ import io.opentelemetry.context.Context

private val TRACEPARENT = Regex("^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$")

/**
* W3C traceparent -> Context holding a NON-remote parent (spec §4.3).
* Not W3CTraceContextPropagator.extract: that yields isRemote=true.
* Invalid input (incl. all-zero ids) -> Context.root(); never throws.
*/
fun contextFrom(traceparent: String): Context {
val m = TRACEPARENT.matchEntire(traceparent) ?: return Context.root()
val (traceId, spanId, flags) = m.destructured
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ import com.margelo.nitro.core.Promise
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers

/** The seam: the core reads Nitro's structs directly. */
// Constructed from JNI by name (ReactNativeOpenTelemetryOnLoad.cpp): keep it through R8.
@DoNotStrip
@Keep
class HybridOtel : HybridOtelSpec() {
Expand All @@ -28,12 +26,10 @@ class HybridOtel : HybridOtelSpec() {
return SeamInitResult(r.alreadyInitialized, r.testMode, r.error)
}

/** JS thread: enqueue only; SpanData is built on the export thread. */
override fun handOff(spans: Array<SeamSpan>) {
OtelCore.instance?.handOff(spans)
}

// Off the JS and main threads (the join blocks, so on IO); resolves even when native never initialized.
override fun flush(timeoutMs: Double): Promise<Unit> = Promise.async(io) {
OtelCore.instance?.flush(timeoutMs.toLong())
Unit
Expand Down
5 changes: 0 additions & 5 deletions app.plugin.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,14 @@
// Expo config plugin: `"plugins": ["react-native-open-telemetry"]`. It does one thing. Autolinking links one podspec per
// package (the Nitro adapter), and the adapter needs the pure Swift core pod beside it, so this adds
// `pod 'ReactNativeOpenTelemetryCore'` to the generated Podfile. Bare apps add the same line by hand (README).
const path = require('path');

const POD = "pod 'ReactNativeOpenTelemetryCore'";

/** Adds the core pod to the first app target; idempotent. */
function addCorePod(podfile, podPath) {
if (podfile.includes(POD)) return podfile;
const out = podfile.replace(/^(target '.+' do\n)/m, `$1 ${POD}, :path => '${podPath}'\n`);
if (out === podfile) throw new Error('react-native-open-telemetry: no `target ... do` in the Podfile; add the core pod by hand');
return out;
}

// The app's own `expo`, not one beside this file: a linked or pnpm-installed package has none of its own.
const configPlugins = config =>
require(require.resolve('expo/config-plugins', {paths: [config._internal?.projectRoot ?? process.cwd(), __dirname]}));

Expand Down
Loading
Loading