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
22 changes: 1 addition & 21 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -46,26 +46,6 @@ jobs:
path: verify/artifacts/
if-no-files-found: ignore

fast-swift:
runs-on: macos-15
timeout-minutes: 20
steps:
- uses: actions/checkout@v4
- uses: maxim-lobanov/setup-xcode@v1
with:
xcode-version: '16.4'
- uses: oven-sh/setup-bun@v2
with:
bun-version: 1.2.19
- run: bun install --frozen-lockfile
- run: bun verify fast-swift # no-op until Package.swift exists (Task 18)
- uses: actions/upload-artifact@v4
if: failure()
with:
name: verify-artifacts-fast-swift
path: verify/artifacts/
if-no-files-found: ignore

# Release builds with the JS bundle embedded (no Metro), test mode on.
# Native outputs are cached on native inputs only, so a JS-only change re-bundles but reuses the native build.
e2e-android-bare:
Expand Down Expand Up @@ -200,7 +180,7 @@ jobs:
if-no-files-found: ignore

budget:
needs: [static-fast, fast-swift, e2e-android-bare, e2e-ios-bare] # every other job; extend when jobs are added
needs: [static-fast, e2e-android-bare, e2e-ios-bare] # every other job; extend when jobs are added
if: always()
runs-on: ubuntu-latest
timeout-minutes: 5
Expand Down
11 changes: 10 additions & 1 deletion android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ def getExtOrIntegerDefault(name) {

// 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 {
namespace "com.margelo.nitro.callstack.otel"
Expand All @@ -29,6 +31,9 @@ android {
minSdkVersion getExtOrIntegerDefault("minSdkVersion")
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 {
cmake {
Expand Down Expand Up @@ -95,8 +100,12 @@ 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"

implementation platform("io.opentelemetry:opentelemetry-bom:1.68.0")
// 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.
Expand Down
11 changes: 11 additions & 0 deletions android/consumer-rules.pro
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Guarded by the minified Expo release e2e (Task 28): 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.** { *; }
2 changes: 1 addition & 1 deletion android/gradle.properties
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
ReactNativeOpenTelemetry_kotlinVersion=2.1.21
ReactNativeOpenTelemetry_minSdkVersion=24
ReactNativeOpenTelemetry_minSdkVersion=26
ReactNativeOpenTelemetry_targetSdkVersion=36
ReactNativeOpenTelemetry_compileSdkVersion=36
ReactNativeOpenTelemetry_ndkVersion=27.1.12297006
77 changes: 77 additions & 0 deletions android/src/main/java/com/callstack/otel/RNOtel.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
package com.callstack.otel

import android.app.Application
import android.content.Context
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ProcessLifecycleOwner
import com.callstack.otel.core.CoreConfig
import com.callstack.otel.core.InitResult
import com.callstack.otel.core.OtelCore
import com.margelo.nitro.callstack.otel.BuildConfig
import io.opentelemetry.api.OpenTelemetry
import io.opentelemetry.api.trace.Span
import io.opentelemetry.api.trace.Tracer
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()
}
})
}
}
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()
}
30 changes: 30 additions & 0 deletions android/src/main/java/com/callstack/otel/RNOtelConfig.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
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()
}

fun export(block: Export.() -> Unit) {
export = Export().apply(block)
}

internal fun toCore() = CoreConfig(
serviceName = serviceName,
serviceVersion = serviceVersion,
resourceAttributes = Attributes.builder().apply { resourceAttributes.forEach { (k, v) -> put(k, v) } }.build(),
exportUrl = export.url,
exportHeaders = export.headers,
)
}
31 changes: 31 additions & 0 deletions android/src/main/java/com/callstack/otel/core/Attributes.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.callstack.otel.core

import com.margelo.nitro.callstack.otel.AttrValue
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) {
val k = a.key
when (val v = a.value) {
is AttrValue.Fifth -> b.put(k, v.value)
is AttrValue.First -> b.put(k, v.value)
is AttrValue.Sixth -> if (isLong(v.value)) b.put(k, v.value.toLong()) else b.put(k, v.value)
is AttrValue.Third -> b.put(AttributeKey.stringArrayKey(k), v.value.toList())
is AttrValue.Second -> b.put(AttributeKey.booleanArrayKey(k), v.value.toList())
is AttrValue.Fourth ->
if (v.value.all(::isLong)) b.put(AttributeKey.longArrayKey(k), v.value.map { it.toLong() })
else b.put(AttributeKey.doubleArrayKey(k), v.value.toList())
}
}
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()
15 changes: 15 additions & 0 deletions android/src/main/java/com/callstack/otel/core/CoreConfig.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.callstack.otel.core

import io.opentelemetry.api.common.Attributes

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)
14 changes: 14 additions & 0 deletions android/src/main/java/com/callstack/otel/core/Endpoint.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
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]"
}
return null
}
83 changes: 83 additions & 0 deletions android/src/main/java/com/callstack/otel/core/JsSpanData.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
package com.callstack.otel.core

import com.margelo.nitro.callstack.otel.SeamSpan
import com.margelo.nitro.callstack.otel.SeamSpanContext
import io.opentelemetry.api.trace.SpanContext
import io.opentelemetry.api.trace.SpanKind
import io.opentelemetry.api.trace.StatusCode
import io.opentelemetry.api.trace.TraceFlags
import io.opentelemetry.api.trace.TraceState
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.sdk.common.InstrumentationLibraryInfo
import io.opentelemetry.sdk.common.InstrumentationScopeInfo
import io.opentelemetry.sdk.resources.Resource
import io.opentelemetry.sdk.trace.ReadableSpan
import io.opentelemetry.sdk.trace.data.EventData
import io.opentelemetry.sdk.trace.data.LinkData
import io.opentelemetry.sdk.trace.data.SpanData
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())
}
return b.build()
}

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)) } }
private val linkList by lazy { span.links.map { LinkData.create(contextOf(it.context), attributesOf(it.attributes)) } }
private val statusData by lazy {
StatusData.create(StatusCode.values().getOrElse(span.status.code.toInt()) { StatusCode.UNSET }, span.status.message.orEmpty())
}
private val scope by lazy {
InstrumentationScopeInfo.builder(span.scope.name)
.apply { span.scope.version?.let(::setVersion); span.scope.schemaUrl?.let(::setSchemaUrl) }
.setAttributes(attributesOf(span.scope.attributes))
.build()
}

override fun getName() = span.name
override fun getKind() = spanKind
override fun getSpanContext() = context
override fun getParentSpanContext() = parent
override fun getStatus() = statusData
override fun getStartEpochNanos() = epochNanos(span.start)
override fun getEndEpochNanos() = epochNanos(span.end)
override fun getAttributes() = attrs
override fun getEvents() = eventList
override fun getLinks() = linkList
override fun hasEnded() = true
override fun getTotalRecordedEvents() = span.events.size
override fun getTotalRecordedLinks() = span.links.size
override fun getTotalAttributeCount() = span.attributes.size
override fun getInstrumentationScopeInfo() = scope
@Deprecated("otel-java deprecated API; still abstract on both interfaces")
override fun getInstrumentationLibraryInfo(): InstrumentationLibraryInfo =
@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)
}
Loading