diff --git a/ReactNativeOpenTelemetry.podspec b/ReactNativeOpenTelemetry.podspec index 069c881..2a411f6 100644 --- a/ReactNativeOpenTelemetry.podspec +++ b/ReactNativeOpenTelemetry.podspec @@ -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"] @@ -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 - # `/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" @@ -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' diff --git a/android/build.gradle b/android/build.gradle index 0ce563d..ed16a06 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -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 { @@ -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 { @@ -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" } diff --git a/android/consumer-rules.pro b/android/consumer-rules.pro index 180211e..d7e6054 100644 --- a/android/consumer-rules.pro +++ b/android/consumer-rules.pro @@ -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.** { *; } diff --git a/android/fix-prefab.gradle b/android/fix-prefab.gradle index d6c010e..d53c16e 100644 --- a/android/fix-prefab.gradle +++ b/android/fix-prefab.gradle @@ -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 @@ -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 -> diff --git a/android/src/main/java/com/callstack/otel/RNOtel.kt b/android/src/main/java/com/callstack/otel/RNOtel.kt index eb047d9..6eaffe8 100644 --- a/android/src/main/java/com/callstack/otel/RNOtel.kt +++ b/android/src/main/java/com/callstack/otel/RNOtel.kt @@ -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() } @@ -55,7 +50,6 @@ 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 { @@ -63,14 +57,12 @@ object RNOtel { 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() diff --git a/android/src/main/java/com/callstack/otel/RNOtelConfig.kt b/android/src/main/java/com/callstack/otel/RNOtelConfig.kt index ee450d8..290e12b 100644 --- a/android/src/main/java/com/callstack/otel/RNOtelConfig.kt +++ b/android/src/main/java/com/callstack/otel/RNOtelConfig.kt @@ -3,7 +3,6 @@ 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 @@ -11,7 +10,6 @@ class RNOtelConfig { 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 = emptyMap() } diff --git a/android/src/main/java/com/callstack/otel/core/Attributes.kt b/android/src/main/java/com/callstack/otel/core/Attributes.kt index a697da2..9dd0956 100644 --- a/android/src/main/java/com/callstack/otel/core/Attributes.kt +++ b/android/src/main/java/com/callstack/otel/core/Attributes.kt @@ -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): Attributes { val b = Attributes.builder() for (a in list) { @@ -27,5 +25,4 @@ fun attributesOf(list: Array): 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() diff --git a/android/src/main/java/com/callstack/otel/core/CoreConfig.kt b/android/src/main/java/com/callstack/otel/core/CoreConfig.kt index e665768..72efd7a 100644 --- a/android/src/main/java/com/callstack/otel/core/CoreConfig.kt +++ b/android/src/main/java/com/callstack/otel/core/CoreConfig.kt @@ -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 = emptyMap(), ) -/** Mirrors the seam's `SeamInitResult`. */ data class InitResult(val alreadyInitialized: Boolean, val testMode: Boolean, val error: String? = null) diff --git a/android/src/main/java/com/callstack/otel/core/Endpoint.kt b/android/src/main/java/com/callstack/otel/core/Endpoint.kt index 78d190f..2ce4059 100644 --- a/android/src/main/java/com/callstack/otel/core/Endpoint.kt +++ b/android/src/main/java/com/callstack/otel/core/Endpoint.kt @@ -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]" diff --git a/android/src/main/java/com/callstack/otel/core/JsSpanData.kt b/android/src/main/java/com/callstack/otel/core/JsSpanData.kt index ca466c2..faf584f 100644 --- a/android/src/main/java/com/callstack/otel/core/JsSpanData.kt +++ b/android/src/main/java/com/callstack/otel/core/JsSpanData.kt @@ -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()) @@ -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)) } } @@ -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 getAttribute(key: AttributeKey): T? = attrs.get(key) diff --git a/android/src/main/java/com/callstack/otel/core/OtelCore.kt b/android/src/main/java/com/callstack/otel/core/OtelCore.kt index 436795e..daabaa8 100644 --- a/android/src/main/java/com/callstack/otel/core/OtelCore.kt +++ b/android/src/main/java/com/callstack/otel/core/OtelCore.kt @@ -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() @@ -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) = d.export(spans) @@ -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() @@ -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) { for (s in spans) bsp.onEnd(JsSpanData(s, resource)) } @@ -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") diff --git a/android/src/main/java/com/callstack/otel/core/Parenting.kt b/android/src/main/java/com/callstack/otel/core/Parenting.kt index 5a975d0..4f59d35 100644 --- a/android/src/main/java/com/callstack/otel/core/Parenting.kt +++ b/android/src/main/java/com/callstack/otel/core/Parenting.kt @@ -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 diff --git a/android/src/main/java/com/margelo/nitro/callstack/otel/HybridOtel.kt b/android/src/main/java/com/margelo/nitro/callstack/otel/HybridOtel.kt index b85088d..803ff29 100644 --- a/android/src/main/java/com/margelo/nitro/callstack/otel/HybridOtel.kt +++ b/android/src/main/java/com/margelo/nitro/callstack/otel/HybridOtel.kt @@ -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() { @@ -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) { 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 = Promise.async(io) { OtelCore.instance?.flush(timeoutMs.toLong()) Unit diff --git a/app.plugin.js b/app.plugin.js index 0aff954..b7d333b 100644 --- a/app.plugin.js +++ b/app.plugin.js @@ -1,11 +1,7 @@ -// 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`); @@ -13,7 +9,6 @@ function addCorePod(podfile, podPath) { 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]})); diff --git a/docs/superpowers/specs/2026-11-10-rn-otel-design.md b/docs/superpowers/specs/2026-11-10-rn-otel-design.md index 4cdb42b..ecdfd39 100644 --- a/docs/superpowers/specs/2026-11-10-rn-otel-design.md +++ b/docs/superpowers/specs/2026-11-10-rn-otel-design.md @@ -1,15 +1,6 @@ # React Native OpenTelemetry SDK — v0 design -Date: 2026-11-10 · Status: reviewed (builder check + 3-member council), awaiting author approval -Author: Adam Horodyski (with Claude) - -The existing code in this repo (v0.2.0) was a scratch approach. This design starts over; -nothing in `src/`, `android/`, `ios/` needs to be preserved, though the example app and -`example/collector/` can be reused. - -Decisions are marked **(decided)** when the author made them, **(Claude's call)** when they -were proposed by Claude and not explicitly confirmed. Builders may revisit Claude's calls. -Section 13 lists every Claude's call in one place. +Status: implemented in v0. Author: Adam Horodyski (with Claude). --- @@ -27,7 +18,7 @@ Android) with a web story through the same API. It should: React-idiomatic APIs and auto-instrumentations are the long-term UX goal, but **not v0**. -### v0 goal (decided) +### v0 goal A vertical slice: everything essential to set the SDK up and get telemetry, **with correct nesting**, to a collector — on iOS, Android and web. @@ -43,7 +34,7 @@ nesting**, to a collector — on iOS, Android and web. - Web: same JS call, upstream browser SDK, direct export. - An AI-native verification pipeline (section 9). -**Non-goals (v0)** — see the v1 backlog (section 11). +**Non-goals (v0)** — see the v1 backlog (section 10). - Auto-instrumentations (press, network, navigation, lifecycle, render, long tasks). - React-specific APIs (hooks, providers, `trace()` helpers, `'use trace'`). - Sessions, sampling config, disk buffering, runtime header updates, enable/consent switch. @@ -63,7 +54,7 @@ nesting**, to a collector — on iOS, Android and web. ## 3. Constraints and context - RN New Architecture, Hermes. Research was done against RN 0.84–0.88 / Hermes V1. - Minimum supported RN version: **0.88**, the version every PR tests (decided). No older + Minimum supported RN version: **0.88**, the version every PR tests. No older React Native is tested. - Upstream versions at time of writing: `@opentelemetry/api` 1.10, OTel JS stable 3.1.x / experimental 0.301.x (`@opentelemetry/sdk-trace` replaced `sdk-trace-base`/`-web` in 3.0), @@ -73,12 +64,10 @@ nesting**, to a collector — on iOS, Android and web. and document it; `react-native-nitro-modules` is a peer dependency the app installs. - Bare RN and Expo must both work. Expo config plugins only run in `expo prebuild`, so nothing essential may depend on a plugin. -- opentelemetry-swift appears to be distributed via SwiftPM only (no podspec at repo - root — reported by a reviewer, builder to confirm). The pod must pull it via - `spm_dependency` (RN ≥ 0.75) or vendor it; verify with Xcode 27.0, static frameworks and - Nitro's Swift/C++ interop. +- opentelemetry-swift is distributed via SwiftPM only; the core pod pulls it via + `spm_dependency`. -## 4. Architecture (decided) +## 4. Architecture Code sketches in this document are **illustrative**: they show intent and shape, not exact signatures. Diagrams are Mermaid. @@ -116,14 +105,14 @@ flowchart TB | upstream, reused as-is | `@opentelemetry/api`, `sdk-trace`, otel-java, opentelemetry-swift, exporters | | ours | ContextManager patch, hand-off processor, Nitro adapters, pure native core, Metro helper | -### 4.1 Where spans live (decided: "option C") +### 4.1 Where spans live - **JS spans live in the stock JS SDK** (`@opentelemetry/sdk-trace` `TracerProvider`) on both mobile and web, so all upstream JS primitives work unchanged: `SpanProcessor`, `Sampler`, `InMemorySpanExporter`, `registerInstrumentations`. - **Native spans live in the native SDK** and never pass through JS. - Parent/child relationships across sides are carried purely by IDs (`traceId`, `parentSpanId`); the backend rebuilds the tree regardless of which side exported a span. -- **Hand-off entry point (Claude's call, from review):** JS spans enter native at the +- **Hand-off entry point:** JS spans enter native at the **batching/export stage**, as native `SpanData` (Java: implement the `SpanData` interface; Swift: construct the `SpanData` struct), enqueued into the native batch processor / exporter. They are **not** faked as live native spans (otel-java's @@ -132,7 +121,7 @@ flowchart TB processed by JS processors. Anything that must apply to all spans (v1 data-shaping specs) is implemented as a native exporter wrapper, which does see both. The repo's history (commit `fe4d4b8`, removed `exportTraces`) has an earlier Kotlin version of the conversion. -- **Hand-off cadence (Claude's call, revised in council review 2026-11-21):** one +- **Hand-off cadence:** one **synchronous void** Nitro call per ended span from our JS `SpanProcessor.onEnd`, but the seam is **batch-shaped**: `handOff(spans: SeamSpan[])`, called with one span in v0. If measurement later says to batch (e.g. microtask coalescing), that is a JS-only change: no @@ -196,22 +185,22 @@ class NativeHandOffProcessor implements SpanProcessor { two pods: pure-Swift `ReactNativeOpenTelemetryCore` (`ios/Core` + `RNOtel`) and the Nitro adapter pod that depends on it. Autolinking links one podspec per package, so apps add `pod 'ReactNativeOpenTelemetryCore', :path => '../node_modules/react-native-open-telemetry'` to their Podfile.)* -- **v0 uses otel-java directly, not opentelemetry-android** (Claude's call): otel-java is +- **v0 uses otel-java directly, not opentelemetry-android**: otel-java is stable; opentelemetry-android is alpha, adds desugaring/AGP constraints, and v0 needs none of its instrumentation. Add it with v1 lifecycle work. Watch OkHttp version alignment with RN's own OkHttp. -- The **Nitro spec uses only OTel-neutral shapes** (decided): `SpanContext` +- The **Nitro spec uses only OTel-neutral shapes**: `SpanContext` `{traceId, spanId, traceFlags, traceState}`, span kind, status, typed attribute values, times, events, links, instrumentation scope (name, version, `schemaUrl`). No Java/Swift types. - Kotlin/Swift is the starting implementation; parts may move to C++ later (opentelemetry-cpp was evaluated: stable, but heavy for mobile — libcurl + protobuf + abseil — and has no mobile instrumentation). The seam rule keeps that move invisible. -- Nitro is kept (decided earlier) for Swift/Kotlin without an ObjC++ shim, typed attribute +- Nitro is kept for Swift/Kotlin without an ObjC++ shim, typed attribute value variants, and zero-copy `ArrayBuffer`. Keep the v0 spec **callback-free**: no native→JS callbacks or event emitters. ### 4.3 The seam in detail (v0) -Exact shapes are the builder's, within the seam rule. A sketch of the Nitro spec: +A sketch of the Nitro spec: ```ts // illustrative: src/specs/Otel.nitro.ts @@ -260,7 +249,6 @@ OTel data model. (`spanBuilder.setParent(...)`), `isRemote = false`. Never rely on native thread-local "current context". v0 ships a small public native helper (Kotlin + Swift) so app native code can do this, plus a test-only HybridObject in the example app that exercises it. - **(Claude's call.)** - **Native → JS**: native returns the `SpanContext` of a native span; JS wraps it as a non-recording parent (`trace.wrapSpanContext`) and starts children under it. @@ -297,37 +285,37 @@ OTel data model. }); context.with(childCtx, () => tracer.startSpan('js.after_native').end()); // child of B ``` -- **Sampling (v0 default, Claude's call):** `ParentBased(AlwaysOn)` on both sides; both +- **Sampling (v0 default):** `ParentBased(AlwaysOn)` on both sides; both honor the `traceFlags` passed across, so a non-sampled parent never yields shipped children on the other side. Configurable sampling is v1. -- **Resource identity (Claude's call):** one resource, owned by native. JS spans exported by +- **Resource identity:** one resource, owned by native. JS spans exported by native carry it; JS does not add its own `telemetry.sdk.*` values. Our SDK identifies itself with the semantic-convention distro attributes `telemetry.distro.name` / `telemetry.distro.version` (`telemetry.sdk.*` stays otel-java / opentelemetry-swift's). Carry `schemaUrl` for resource and scope. -- **Clock (Claude's call, simplified in council review and again in v0 implementation):** both +- **Clock:** both sides use wall-clock epoch time. JS keeps upstream `sdk-trace` timing: each span starts at `Date.now()` and measures its duration with `performance.now()`; there is no extra JS offset (sdk-trace 3.1 has no time-source hook). Error between JS and native siblings is under 1 ms; scenarios use explicit timestamps, so test output is unaffected. -- **Before native is ready / failures (Claude's call):** no pre-init buffer. `initialize` +- **Before native is ready / failures:** no pre-init buffer. `initialize` runs synchronously inside `startReactNativeSdk` before the JS provider is registered, so no span can end before native is ready; spans started earlier come from the API's no-op provider. Native init failure, or a missing native module (Expo Go), is reported once, loudly (`console.error`), and `startReactNativeSdk` returns a working no-op handle. The SDK never throws into the app. -- **Multiple runtimes (Claude's call):** one native singleton; `initialize` is safe under +- **Multiple runtimes:** one native singleton; `initialize` is safe under concurrent calls; each JS runtime has its own hand-off. Per-runtime attributes are out of scope for v0. -### 4.4 Configuration (decided: "option A", with JS fallback) +### 4.4 Configuration - **Mobile, preferred**: config lives in **one native init call** in `MainApplication.onCreate` / `AppDelegate` (endpoint, static headers, service name/version, resource attributes). Native starts before JS (needed later for app start and early crashes). Guard Android init to the main process. -- **Mobile, fallback (decided)**: `startReactNativeSdk(config)` initializes native itself +- **Mobile, fallback**: `startReactNativeSdk(config)` initializes native itself when no native init happened (Sentry does the same). This is the path for Expo managed - apps without a config plugin; it loses only pre-JS capture. Prior art: §14 P7. + apps without a config plugin; it loses only pre-JS capture. Prior art: §12 P7. - When native init did happen, `startReactNativeSdk({...})` attaches; JS export config is ignored with one warning. - Returns `{ tracerProvider, forceFlush(), shutdown() }`, the names OTel JS uses on every @@ -383,41 +371,39 @@ const { withOtel } = require('react-native-open-telemetry/metro'); module.exports = withOtel(getDefaultConfig(__dirname)); ``` -### 4.5 Naming (decided) +### 4.5 Naming 1. Semantic conventions first, with `schemaUrl` set on tracers. Runtime code imports only the stable `@opentelemetry/semantic-conventions` entry; incubating keys are inlined as constants (Metro doesn't tree-shake, so `/incubating` would ship every key). 2. Instrumentation scope (tracer name + version) identifies which component produced a span. 3. Only concepts with no convention get custom names, prefixed `com.callstack.*` - (OTel naming guidance: reverse-domain prefix; `otel.*` is reserved). **Prefix is - Claude's call.** + (OTel naming guidance: reverse-domain prefix; `otel.*` is reserved). Package name: `react-native-open-telemetry` (subpath `/metro`). Entry function: -`startReactNativeSdk`, on web too. **(decided)** +`startReactNativeSdk`, on web too. -## 5. Trace model (decided; most of it lands with v1 instrumentations) +## 5. Trace model Recorded so v0 primitives don't preclude it: - Spans nest by **cause and effect**, not by temporal overlap. - One trace per trigger (a tap, a navigation, a timer). Session and screen are attributes, never parent spans. - Renders caused by several interactions get **links** to each cause, not a parent. - **(Claude's call.)** - Work with lost context may be attributed by time window in v1, but must be visibly - marked as heuristic. **(Claude's call.)** + marked as heuristic. -## 6. Context propagation (decided) +## 6. Context propagation ### 6.1 Mechanism 1. **Runtime patch.** Our `ContextManager` **extends upstream `StackContextManager`** from - `@opentelemetry/sdk-trace` (Claude's call: reuse, don't reimplement) and adds wrappers on + `@opentelemetry/sdk-trace` and adds wrappers on `Promise.prototype.then`, `setTimeout`, `setImmediate`, `queueMicrotask`, `requestAnimationFrame`: capture the active context when a callback is scheduled, restore it when it runs, restore the previous one after. RN's Babel preset compiles `await` to `Promise.resolve(x).then(...)`, so `await` is covered. The spike's `runtime.js` is the reference. `context.setGlobalContextManager` is called once, before any API use. - Prior art: zone.js, async-listener (§14 P1–P3). - **ROOT fast path (council review):** every wrapper restores in `finally`, so each job + Prior art: zone.js, async-listener (§12 P1–P3). + **ROOT fast path:** every wrapper restores in `finally`, so each job taken from the microtask or timer queue starts at ROOT; a callback registered at ROOT can use the original `then` unwrapped. Most `then` calls in an app (startup, data libraries) happen with no span active, so this removes most of the patch's cost. @@ -459,22 +445,21 @@ Recorded so v0 primitives don't preclude it: 2. **Install order.** The patch must run before React / the scheduler capture `queueMicrotask`/`setImmediate`. Ship a Metro helper `withOtel(metroConfig)` that adds the SDK's setup module via `serializer.getModulesRunBeforeMainModule` — plugin-free, and - it works for Expo Router where users have no "first line" (Claude's call). Code that + it works for Expo Router where users have no "first line". Code that captured `then` before the patch runs at ROOT (loses parent). 3. **Idempotent under fast refresh**: a marker on `globalThis` prevents stacking wrappers. 4. **Startup probe**: an `await` probe compiled like app code (Metro transforms `node_modules`). If context does not survive `await` (e.g. `unstable_preserveAsync` on a future Hermes with commit `a9d054c8c9`, or a web bundle without async downleveling), log loudly and set `com.callstack.context.degraded=true` as an attribute of the JS tracers' - **instrumentation scope** (Claude's call: a diagnostic about the SDK, not about the - work). Not a resource attribute: with native-first init the resource is built before JS + **instrumentation scope** (a diagnostic about the SDK, not about the work). Not a resource attribute: with native-first init the resource is built before JS runs the probe. 5. **Explicit API**: none of our own. Edge cases use upstream `@opentelemetry/api`: `context.with(trace.setSpan(...), fn)`, `context.bind(ctx, fn)`, and documented `context.with(ROOT_CONTEXT, …)` for init code. Our instrumentations bind context explicitly and don't depend on the global patch. -### 6.2 Wrong-parent policy (decided) +### 6.2 Wrong-parent policy The spike showed the patch **can** produce wrong parents through shared queues: a queue flushed once (React's scheduler, `InteractionManager`, debounce/throttle, store notifiers) runs everyone's work in the context of whoever enqueued first (spike scenario `h_batching`: @@ -487,9 +472,7 @@ attaching to that tap's trace. instead of inheriting the context that registered the interval. No link in v0 (links for ticks come with v1 render links). - A callback that runs after its parent ended is still that parent's causal child and is - attached to it; backends show it after the parent's end. (An earlier staleness rule that - turned old parents into links was cut in council review: custom, no precedent, and it - required wrapping every tracer.) + attached to it; backends show it after the parent's end. - The batching scenario stays in the suite as a documented-exception case with its own expected output, not as a silent failure. @@ -511,10 +494,10 @@ unctx-style form gives wrong parents; a correct "swap" form exists but adds noth async is downleveled; kept as a v1 opt-in). Future: an `AsyncContext` slot when an engine ships TC39 AsyncContext (Stage 2). -## 7. Web (decided) +## 7. Web Same `@opentelemetry/api` surface and the same ContextManager; spans live in the JS SDK and -export directly from JS. **Changed in v0 implementation:** web +export directly from JS. Web builds its own `sdk-trace` `TracerProvider` + `BatchSpanProcessor` + upstream `@opentelemetry/exporter-trace-otlp-proto` (fetch), not `startBrowserSdk`. Why: browser-sdk 0.9.1 takes no `idGenerator` (no `0a` test-mode IDs, so no exact web goldens), @@ -527,7 +510,7 @@ re-registers our context manager if another one took the global slot. The packag Web is bundled with Metro (Expo web), with the same `withOtel` from `/metro` as mobile. Browsers run `await` natively, which bypasses the patched `then`. **Decided:** web apps compile `async` down in their bundler — the same mechanism RN uses by default, and what -Angular requires for zone.js (§14 P4). `babel-preset-expo` keeps native `async` on web, so the +Angular requires for zone.js (§12 P4). `babel-preset-expo` keeps native `async` on web, so the app adds `@babel/plugin-transform-async-to-generator` and `@babel/plugin-transform-async-generator-functions` for the web platform in `babel.config.js` (README). Without them, the probe reports degraded (lost parents after `await`, never wrong). @@ -543,7 +526,7 @@ module.exports = api => { }; ``` -## 8. v0 scope and sequencing (decided scope; sequencing is Claude's call) +## 8. v0 scope Scope: 1. Native init on Android and iOS (otel-java, opentelemetry-swift): resource, OTLP/HTTP @@ -559,24 +542,7 @@ Scope: native; plus a second concurrent trace that shares nothing with the first. On web (no native side): the JS root, the child after `await`, and the concurrent trace. -Sequencing (from review; council review 2026-11-21 added step 0): -0. **Tracer bullet:** the real example app with Nitro stubs and the real native - dependencies linked on both platforms, `handOff` echoing one fixture, and one - `nest-after-await` e2e test per platform. Proves the seam compiles, the native SDKs link, - and the e2e tooling can drive the app, before parallel work builds on it. -1. **First milestone: the context patch in a real RN app** (real Hermes, RN's timers, - Promise, scheduler) with real `sdk-trace` spans. Scenarios include - React batching, intervals, thrown errors in callbacks, EventEmitter - listeners. The spike only used a stand-in Hermes host. -2. JS-only slice asserting on output with the fake collector. -3. The seam on one platform, with shared payload fixtures and an early device e2e; then - port to the second platform. -4. Expected-file goldens and parity check on both platforms. -5. Web. - -Each step is defined by the list of scenario names that must pass (9.3). - -## 9. Verification (decided) +## 9. Verification Principle: we trust upstream SDKs; we verify **our output**. Everything ends in a fake collector and is compared to expected exporter output. These are output tests, not unit @@ -590,12 +556,12 @@ tests: they don't care about internals, so internals can be rewritten freely. IDs, not the generic protobuf JSON base64 mapping). Plain equality; valid OTLP that can be POSTed to a collector or viewed in Jaeger as-is. **One file per scenario for every platform** (JS, web, Android, iOS): OTLP is standardized and every platform must report the same. - Prior art: Collector goldens, upstream test hooks (§14 P17–P19). + Prior art: Collector goldens, upstream test hooks (§12 P17–P19). - **Spec first:** the expected file is written (agent drafts, human reviews) before the code that makes it pass. With explicit timestamps and sequential IDs, exact values are predictable. `bun verify --update` writes actual output as a draft to review. - Determinism in **test mode**, enabled by a **build flag** in the example/test apps, never a - public runtime switch (Claude's call). JS: `process.env.OTEL_TEST_MODE` inlined at bundle + public runtime switch. JS: `process.env.OTEL_TEST_MODE` inlined at bundle time; native: Gradle property `otelTestMode` / `OTEL_TEST_MODE=1` at `pod install`. Same flag for the bare and Expo apps; no test fields in the public API or the seam config: - **explicit timestamps**: v0 scenarios create all spans themselves, so they pass @@ -612,8 +578,8 @@ tests: they don't care about internals, so internals can be rewritten freely. - concurrency scenarios are serialized deterministically (JS is single-threaded; native spans in scenarios are started synchronously from JS). - **Parity by construction**: every platform compares against the same file, so they agree - with each other. Files are drafted with `--update` and reviewed (council review: - hand-writing 30+ exact OTLP trees puts the bugs in the expected files). The one exception + with each other. Files are drafted with `--update` and reviewed (hand-writing + 30+ exact OTLP trees puts the bugs in the expected files). The one exception is iOS, in a single function of the compare step: opentelemetry-swift 2.6 rounds times (above) and its OTLP encoder never writes span/link `flags`, span/link `traceState` or the scope `schemaUrl`, so those are not compared on iOS (no encoder reimplementation, see @@ -659,13 +625,13 @@ A failure, as an agent sees it: scenario: verify/scenarios/nest-after-await.ts ``` -### 9.2 Layers and runners (decided) +### 9.2 Layers and runners The same scenarios run in every layer, fastest first. | Layer | Runner | Covers | When | |---|---|---|---| | JS (Node) | **Jest** + `babel-jest` + `@react-native/babel-preset` | context patch, hand-off (fake Nitro module) | every iteration | -| E2E: iOS, Android, web | **[`e2e`](https://www.npmjs.com/package/e2e)** (agent-device for mobile, Playwright for web) | everything for real: Nitro glue, both init paths, threading, reload, failure paths, browser SDK, Metro helper (matrix in 9.4) | **every PR** once the seam exists (decided) | +| E2E: iOS, Android, web | **[`e2e`](https://www.npmjs.com/package/e2e)** (agent-device for mobile, Playwright for web) | everything for real: Nitro glue, both init paths, threading, reload, failure paths, browser SDK, Metro helper (matrix in 9.4) | **every PR** once the seam exists | - **Why Jest:** it compiles scenarios the way RN does (`await` → `.then`). Bun's test runner and Vitest keep native `await`, which bypasses the context patch and makes results wrong @@ -727,16 +693,15 @@ flowchart LR of 9.4). `bun verify` runs stages 1–2; `bun verify --e2e` adds stage 3 locally. 3. Failures print minimal structured diffs (scenario, span, field, expected vs actual, file paths); raw payloads saved to `verify/artifacts/`. -4. **Milestones are lists of scenario names** (section 8). A milestone is done when its - scenarios pass; every earlier scenario keeps passing because `bun verify` runs them all. - Scenarios not built yet are marked pending (`test.todo`), never deleted. +4. `bun verify` runs every scenario, so earlier guarantees keep passing. A scenario not + built yet is marked pending (`test.todo`). 5. **Protection:** `verify/` is behind `CODEOWNERS`, so an expected file can't be edited to make a test pass without the author's review. 6. The Nitro spec can't import vendor types (anti-goal, section 2): it is TypeScript, so `tsc` fails on any `io.opentelemetry.*` import; no separate check. 7. `VERIFY.md` explains layers and failure meanings; `CLAUDE.md` points to it. -### 9.4 The full pipeline (decided) +### 9.4 The full pipeline Everything below is automated; nothing needs a person except reviewing expected files. ```mermaid @@ -772,7 +737,7 @@ once its PR pipeline is green. No release workflow. ### 9.5 Not covered in v0 - **Performance** (hand-off cost, patch overhead, low-end devices, Kotlin vs C++ adapter): - not measured in CI; the v1 spike (section 11). + not measured in CI; the v1 spike (section 10). - **Memory retention** (a never-settling promise keeping its span alive): output tests can't see it; add a `WeakRef` + `--expose-gc` check if it becomes a concern. - **Multiple JS runtimes**: one native singleton is designed for, not tested. @@ -793,13 +758,7 @@ Left out until needed: | Release gate on real telemetry (a dogfood app reporting through the SDK) | a real app uses the SDK | | `unstable_preserveAsync` device build | a Hermes release ships commit `a9d054c8c9` | -## 10. Left to the builder -- Repo/package layout beyond 4.2, package manager specifics, exact Nitro spec types, - minimum RN version, CI provider setup, whether to batch hand-offs (measure first; the - seam is already array-shaped). -- Whether the fake collector is in-process or a sidecar, as long as it's hermetic. - -## 11. v1 backlog +## 10. v1 backlog - Spike: Nitro call cost on Android, Kotlin vs C++ HybridObject; context patch overhead on a low-end Android device (spike numbers are from an M-series Mac). - Instrumentations: press (JSX-runtime wrapping of `onPress`, trace root at native touch @@ -822,14 +781,12 @@ Left out until needed: - Expo config plugin (optional, thin, for native-first init), errors/crashes, logs, metrics. - Native → JS callbacks (avoided in v0 because of Nitro reload hazards). -## 12. Research and evidence +## 11. Research and evidence - Context spike (Node + real Hermes 260318099.0.7): the runtime patch passed all scenarios except captured `then` (lost parent) and **batching (wrong parent — see 6.2)**; overhead ~0.15–0.3 µs per await on an M-series Mac. The naive await plugin gave wrong parents (ROOT work seen as an interaction). Native `await` on current Hermes still calls a patched - `then`; Hermes main commit `a9d054c8c9` will change that. Harness (session-temporary — - copy into the repo): - `/private/tmp/claude-501/-Users-adhorodyski-Developer-react-native-open-telemetry/e321df1e-f712-420e-9844-452905422c0b/scratchpad/spike-context/` + `then`; Hermes main commit `a9d054c8c9` will change that. - Prior art: Sentry RN (JS spans + native envelope transport, native init with JS fallback, no async context), Embrace RN (OTel API facade over native spans, async `spanContext`, stack context only), OTel demo RN app (`StackContextManager`, CORS-regex hack), @@ -837,39 +794,12 @@ Left out until needed: - Precedent for the runtime patch: zone.js `patchThen` (Angular), async-listener (Node, pre-`async_hooks`). - Upstream code reuse estimate: ~4% of running code is ours (~3.7k of ~89k lines). -- Review: builder check + council (OTel-upstream, RN/native, skeptic) on 2026-11-10. - CI shape (pre-commit static checks, release only from fully green commits, staged release) adapted from [Kun Chen on validation categories](https://x.com/kunchenguid/status/2122391325081579618) (2026-11-16); the full device matrix stays on every PR by decision. -## 13. Claude's calls (for the author to check) -1. `com.callstack.*` attribute prefix. -2. Pure Kotlin/Swift core modules, and the shared-sources layout (4.2). -3. otel-java directly in v0 instead of opentelemetry-android. -4. JS spans enter native at the batching/export stage; native custom processors don't see - JS spans (4.1). -5. One sync void hand-off call per ended span through an array-shaped seam; native - conversion off the JS thread (4.1). -6. `HrTime` `[seconds, nanos]` for times; int-vs-double rule (4.3). -7. Public native parenting helper + test-only HybridObject (4.3). -8. Default sampling `ParentBased(AlwaysOn)` on both sides, honoring `traceFlags` (4.3). -9. One native-owned resource; JS adds no `telemetry.sdk.*`; SDK identity via - `telemetry.distro.*` (4.3). -10. Clock: upstream sdk-trace timing (start at `Date.now()`, `performance.now()` durations) (4.3). -11. No pre-init buffer; init failure → one error and a no-op handle, never a throw; - multi-runtime handling (4.3, 4.4). -12. Context manager extends upstream `StackContextManager`; Metro `withOtel` helper for - install order; ROOT fast path; degraded flag as a scope attribute (6.1). -13. Trace-model rules: links for multi-cause renders, marked heuristic attribution (5). -14. Sequencing, with the real-RN-app context milestone first (8). -15. Test mode as a build flag; explicit whole-µs timestamps in scenarios; attribute/event - sorting; one expected file for all platforms (9.1). -16. Native cores proven by device e2e against the same expected files (9.2). -17. One endpoint meaning on every platform (the traces endpoint, used as given); returned handle `{ tracerProvider, forceFlush, shutdown }` (4.4). -18. No performance or compliance jobs in CI: the upstream OTLP exporters own the wire format; `example/collector/` runs the official Collector by hand (9.4). - -## 14. Prior art and proof +## 12. Prior art and proof Every custom solution in this design, with the upstream or industry precedent it follows. Links are permalinks to the commit read during research (2026-11-10). "Ours" means no @@ -888,15 +818,11 @@ direct precedent was found; treat those as the highest-risk parts. | P9 | int vs double rule on native (4.3) | OTel JS OTLP transformer: `Number.isInteger` → `intValue` | [otlp-transformer `internal.ts`](https://github.com/open-telemetry/opentelemetry-js/blob/ee0bd33cac8bb245a3d83fc2b8ba0b07534b8efd/experimental/packages/otlp-transformer/src/common/internal.ts#L76) | | P10 | Explicit parent across threads, never thread-local (4.3) | OTel API `setParent` on span builders; standard practice for cross-thread propagation | [Java `SpanBuilder.setParent`](https://github.com/open-telemetry/opentelemetry-java/blob/fecfb6d83f356906368f620053a2c7cc786110ac/api/all/src/main/java/io/opentelemetry/api/trace/SpanBuilder.java) | | P11 | Links instead of parents for batched/multi-cause work; interval ticks as new roots (5, 6.2) | OTel spec: links represent batched operations; React notes it can't attribute batched updates without AsyncContext | [Spec: Links between spans](https://github.com/open-telemetry/opentelemetry-specification/blob/a03fa4e26b3982da42aa0010aaebcd9f694cb037/specification/overview.md#L207-L214) · [React `ReactFiberAsyncAction.js`](https://github.com/facebook/react/blob/fe719f77ba3e4b5fb3ebe13787bfbd0ed911da19/packages/react-reconciler/src/ReactFiberAsyncAction.js#L42) | -| P12 | *(removed: the staleness rule was cut in council review, see 6.2)* | | | -| P13 | *(removed: the pre-init buffer was cut in council review, see 4.3)* | | | -| P14 | *(Superseded: upstream timing kept, no offset.)* Clock offset `Date.now() - performance.now()`, recomputed on foreground (4.3) | OTel JS derives span times from `performance.timeOrigin` + `performance.now()`; Sentry RN guards an unreliable `performance.timeOrigin` | [Sentry `timeOrigin` guard](https://github.com/getsentry/sentry-react-native/blob/794a52a9e80ca0a7c4ee005264cd9cd3ee1533de/packages/core/src/js/sdk.tsx#L76-L80) | | P15 | Custom names under a reverse-domain prefix, never `otel.*` (4.5) | OTel naming guidance | [naming.md: app developers](https://github.com/open-telemetry/semantic-conventions/blob/2d91ead21027a8a58fbb7488b12d80238e7c0ac5/docs/general/naming.md#L183-L187) · [`otel.*` reserved](https://github.com/open-telemetry/semantic-conventions/blob/2d91ead21027a8a58fbb7488b12d80238e7c0ac5/docs/general/naming.md#L217-L227) | | P16 | Option names mirror `startBrowserSdk`; invalid config returns a no-op SDK instead of throwing (4.4) | OTel Browser SIG browser SDK | [browser-sdk README](https://github.com/open-telemetry/opentelemetry-browser/tree/main/packages/sdk) | | P17 | Exact expected-output files (goldens) for traces (9.1) | OTel Collector tests compare traces against golden files | [collector-contrib `pkg/golden`](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/c64840337cf400792cb684037ed998428b268197/pkg/golden) · [`ptracetest` compare options](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/c64840337cf400792cb684037ed998428b268197/pkg/pdatatest/ptracetest/options.go#L102-L149) | | P18 | Deterministic test mode: ID generators + clock (9.1) | Upstream SDK hooks and test utilities | [JS `idGenerator`](https://github.com/open-telemetry/opentelemetry-js/blob/ee0bd33cac8bb245a3d83fc2b8ba0b07534b8efd/packages/sdk-trace/src/types.ts#L29) · [Java `setClock` / `setIdGenerator`](https://github.com/open-telemetry/opentelemetry-java/blob/fecfb6d83f356906368f620053a2c7cc786110ac/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkTracerProviderBuilder.java#L58-L74) · [Java `TestClock`](https://github.com/open-telemetry/opentelemetry-java/blob/fecfb6d83f356906368f620053a2c7cc786110ac/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/time/TestClock.java) · [Swift `with(clock:)` / `with(idGenerator:)`](https://github.com/open-telemetry/opentelemetry-swift/blob/d573e7c20a874bc4ac5649fd32643369d8d8d7d9/Sources/OpenTelemetrySdk/Trace/TracerProviderBuilder.swift#L19-L27) | | P19 | Expected files in OTLP/JSON with hex IDs (9.1) | OTLP specification, JSON encoding | [OTLP spec: JSON Protobuf Encoding](https://github.com/open-telemetry/opentelemetry-proto/blob/main/docs/specification.md#json-protobuf-encoding) | | P20 | Protected expected files (9.3) | GitHub `CODEOWNERS` | [About code owners](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners) | -| P21 | *(removed: the mutant meta-check was cut from v0, see 9.3)* | | | | P22 | Hermetic fake collector decoding the official protos (9.2) | Official OTLP protobuf definitions | [opentelemetry-proto](https://github.com/open-telemetry/opentelemetry-proto) | | P23 | Native core + thin Nitro adapter; on iOS a Nitro-free core pod (4.2) | **Ours**: no direct precedent found in the RN OTel SDKs reviewed | — | diff --git a/example-expo/babel.config.js b/example-expo/babel.config.js index 12d0ab8..8e6530c 100644 --- a/example-expo/babel.config.js +++ b/example-expo/babel.config.js @@ -1,8 +1,6 @@ -// 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'], diff --git a/example-expo/index.js b/example-expo/index.js index 96fc759..2ffd51e 100644 --- a/example-expo/index.js +++ b/example-expo/index.js @@ -3,13 +3,11 @@ 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. 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 + headers: {'x-api-key': 'test'}, }, }); diff --git a/example-expo/metro.config.js b/example-expo/metro.config.js index 90d159a..ed8e57b 100644 --- a/example-expo/metro.config.js +++ b/example-expo/metro.config.js @@ -5,21 +5,17 @@ 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')} diff --git a/example-expo/nitro-stub.web.ts b/example-expo/nitro-stub.web.ts index 612c024..8813b90 100644 --- a/example-expo/nitro-stub.web.ts +++ b/example-expo/nitro-stub.web.ts @@ -1,4 +1,3 @@ -// Web has no Nitro: no HybridObject is registered, so getOtel() is undefined and scenarios get no `native`. export const NitroModules = { hasHybridObject: () => false, createHybridObject: () => undefined, diff --git a/example-expo/plugins/withOtelExample.js b/example-expo/plugins/withOtelExample.js index 0dac383..12121b4 100644 --- a/example-expo/plugins/withOtelExample.js +++ b/example-expo/plugins/withOtelExample.js @@ -1,32 +1,21 @@ 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: what the bare example's native projects carry by hand, applied at `expo prebuild`. The Core - * pod 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'}); diff --git a/example-expo/react-native.config.js b/example-expo/react-native.config.js index 6cfd93e..338e28c 100644 --- a/example-expo/react-native.config.js +++ b/example-expo/react-native.config.js @@ -1,6 +1,5 @@ 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, '..')}, diff --git a/example/Gemfile b/example/Gemfile index 5151523..3406f6b 100644 --- a/example/Gemfile +++ b/example/Gemfile @@ -1,15 +1,12 @@ source 'https://rubygems.org' -# You may use http://rbenv.org/ or https://rvm.io/ to install and use this version ruby ">= 2.6.10" -# Exclude problematic versions of cocoapods and activesupport that causes build failures. gem 'cocoapods', '>= 1.13', '!= 1.15.0', '!= 1.15.1' gem 'activesupport', '>= 6.1.7.5', '!= 7.1.0' gem 'xcodeproj', '< 1.26.0' gem 'concurrent-ruby', '< 1.3.4' -# Ruby 3.4.0 has removed some libraries from the standard library. gem 'bigdecimal' gem 'logger' gem 'benchmark' diff --git a/example/android/app/build.gradle b/example/android/app/build.gradle index 82171b5..a207a94 100644 --- a/example/android/app/build.gradle +++ b/example/android/app/build.gradle @@ -2,74 +2,12 @@ apply plugin: "com.android.application" apply plugin: "org.jetbrains.kotlin.android" apply plugin: "com.facebook.react" -/** - * This is the configuration block to customize your React Native Android app. - * By default you don't need to apply any configuration, just uncomment the lines you need. - */ react { - /* Folders */ - // The root of your project, i.e. where "package.json" lives. Default is '../..' - // root = file("../../") - // The folder where the react-native NPM package is. Default is ../../node_modules/react-native - // reactNativeDir = file("../../node_modules/react-native") - // The folder where the react-native Codegen package is. Default is ../../node_modules/@react-native/codegen - // codegenDir = file("../../node_modules/@react-native/codegen") - // The cli.js file which is the React Native CLI entrypoint. Default is ../../node_modules/react-native/cli.js - // cliFile = file("../../node_modules/react-native/cli.js") - - /* Variants */ - // The list of variants to that are debuggable. For those we're going to - // skip the bundling of the JS bundle and the assets. Default is "debug", "debugOptimized". - // If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants. - // debuggableVariants = ["liteDebug", "liteDebugOptimized", "prodDebug", "prodDebugOptimized"] - - /* Bundling */ - // A list containing the node command and its flags. Default is just 'node'. - // nodeExecutableAndArgs = ["node"] - // - // The command to run when bundling. By default is 'bundle' - // bundleCommand = "ram-bundle" - // - // The path to the CLI configuration file. Default is empty. - // bundleConfig = file(../rn-cli.config.js) - // - // The name of the generated asset file containing your JS bundle - // bundleAssetName = "MyApplication.android.bundle" - // - // The entry file for bundle generation. Default is 'index.android.js' or 'index.js' - // entryFile = file("../js/MyApplication.android.js") - // - // A list of extra flags to pass to the 'bundle' commands. - // See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle - // extraPackagerArgs = [] - - /* Hermes Commands */ - // The hermes compiler command to run. By default it is 'hermesc' - // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc" - // - // The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map" - // hermesFlags = ["-O", "-output-source-map"] - - /* Autolinking */ autolinkLibrariesWithApp() } -/** - * Set this to true to Run Proguard on Release builds to minify the Java bytecode. - */ def enableProguardInReleaseBuilds = false -/** - * The preferred build flavor of JavaScriptCore (JSC) - * - * For example, to use the international variant, you can use: - * `def jscFlavor = io.github.react-native-community:jsc-android-intl:2026004.+` - * - * The international variant includes ICU i18n library and necessary data - * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that - * give correct results when using with locales other than en-US. Note that - * this variant is about 6MiB larger per architecture than default. - */ def jscFlavor = 'io.github.react-native-community:jsc-android:2026004.+' android { @@ -84,7 +22,6 @@ 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 { @@ -100,8 +37,6 @@ android { signingConfig signingConfigs.debug } release { - // Caution! In production, you need to generate your own keystore file. - // see https://reactnative.dev/docs/signed-apk-android. signingConfig signingConfigs.debug minifyEnabled enableProguardInReleaseBuilds proguardFiles getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro" @@ -109,15 +44,12 @@ 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") if (hermesEnabled.toBoolean()) { diff --git a/example/android/app/src/main/java/opentelemetry/example/MainApplication.kt b/example/android/app/src/main/java/opentelemetry/example/MainApplication.kt index 18e4858..6a0b9c8 100644 --- a/example/android/app/src/main/java/opentelemetry/example/MainApplication.kt +++ b/example/android/app/src/main/java/opentelemetry/example/MainApplication.kt @@ -8,21 +8,18 @@ import com.facebook.react.ReactNativeApplicationEntryPoint.loadReactNative import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost class MainApplication : Application(), ReactApplication { - override val reactHost: ReactHost by lazy { getDefaultReactHost( context = applicationContext, packageList = PackageList(this).packages.apply { - // Packages that cannot be autolinked yet can be added manually here, for example: - // add(MyReactNativePackage()) }, ) } override fun onCreate() { super.onCreate() - startOtel() // native-first init, before React Native (OtelInit.kt) + startOtel() loadReactNative(this) } } diff --git a/example/android/gradle.properties b/example/android/gradle.properties index 50a0ed6..2821a7d 100644 --- a/example/android/gradle.properties +++ b/example/android/gradle.properties @@ -1,49 +1,16 @@ -# Project-wide Gradle settings. -# IDE (e.g. Android Studio) users: -# Gradle settings configured through the IDE *will override* -# any settings specified in this file. -# For more details on how to configure your build environment visit -# http://www.gradle.org/docs/current/userguide/build_environment.html - -# Specifies the JVM arguments used for the daemon process. -# The setting is particularly useful for tweaking memory settings. -# Default value: -Xmx512m -XX:MaxMetaspaceSize=256m org.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m -# When configured, Gradle will run in incubating parallel mode. -# This option should only be used with decoupled projects. More details, visit -# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects -# org.gradle.parallel=true - -# AndroidX package structure to make it clearer which packages are bundled with the -# Android operating system, and which are packaged with your app's APK -# https://developer.android.com/topic/libraries/support-library/androidx-rn android.useAndroidX=true -# Use this property to specify which architecture you want to build. -# You can also override it from the CLI using -# ./gradlew -PreactNativeArchitectures=x86_64 reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64 -# Use this property to enable support to the new architecture. -# This will allow you to use TurboModules and the Fabric render in -# your application. You should enable this flag either if you want -# to write custom TurboModules/Fabric components OR use libraries that -# are providing them. newArchEnabled=true -# Use this property to enable or disable the Hermes JS engine. -# If set to false, you will be using JSC instead. hermesEnabled=true -# Use this property to enable edge-to-edge display support. -# This allows your app to draw behind system bars for an immersive UI. -# Note: Only works with ReactActivity and should not be used with custom Activity. edgeToEdgeEnabled=true -# Opt out of built-in kotlin and new DSL behavior that ships with AGP 9. -# Starting from AGP 10.x these opt outs will be removed. android.builtInKotlin=false android.newDsl=false \ No newline at end of file diff --git a/example/index.js b/example/index.js index 9b73932..f7176a1 100644 --- a/example/index.js +++ b/example/index.js @@ -1,6 +1,3 @@ -/** - * @format - */ import { AppRegistry } from 'react-native'; import App from './App'; diff --git a/example/inlineTestMode.js b/example/inlineTestMode.js index ff88a20..1a357a9 100644 --- a/example/inlineTestMode.js +++ b/example/inlineTestMode.js @@ -1,4 +1,3 @@ -// 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'})) @@ -7,4 +6,4 @@ const inlineTestMode = ({types: t}) => { return {visitor: {MemberExpression: visit, OptionalMemberExpression: visit}}; }; -module.exports = inlineTestMode; // also used by example-expo/babel.config.js +module.exports = inlineTestMode; diff --git a/example/ios/Podfile b/example/ios/Podfile index de414f0..2fea0da 100644 --- a/example/ios/Podfile +++ b/example/ios/Podfile @@ -1,4 +1,3 @@ -# Resolve react_native_pods.rb with node to allow for hoisting require Pod::Executable.execute_command('node', ['-p', 'require.resolve( "react-native/scripts/react_native_pods.rb", @@ -15,13 +14,11 @@ 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. pod 'ReactNativeOpenTelemetryCore', :path => '../..' config = use_native_modules! use_react_native!( :path => config[:reactNativePath], - # An absolute path to your application root. :app_path => "#{Pod::Config.instance.installation_root}/.." ) @@ -30,9 +27,7 @@ target 'OpenTelemetryExample' do installer, config[:reactNativePath], :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| diff --git a/example/metro.config.js b/example/metro.config.js index 8459676..4004d4e 100644 --- a/example/metro.config.js +++ b/example/metro.config.js @@ -4,23 +4,18 @@ const {withOtel} = require('../metro'); const root = path.resolve(__dirname, '..'); const own = p => path.join(__dirname, 'node_modules', p); -// The repo root has its own (dev) 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, '\\$&'); /** @type {import('@react-native/metro-config').MetroConfig} */ 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 (its package exports -> lib/) and the scenarios, fixtures and harness under verify/ watchFolders: [root, path.join(root, 'verify')], resolver: { nodeModulesPaths: [path.join(__dirname, 'node_modules'), path.join(root, 'node_modules')], blockList: single.map(m => new RegExp(`^${escape(path.join(root, 'node_modules', m))}[/\\\\].*`)), - // the app consumes the package as published: exports -> lib/ (build it with `bun run prepare`) extraNodeModules: {...Object.fromEntries(single.map(m => [m, own(m)])), 'react-native-open-telemetry': root}, }, }; -// wrap the merged config: wrapping only `config` would drop the default InitializeCore entry module.exports = withOtel(mergeConfig(getDefaultConfig(__dirname), config)); diff --git a/example/modules/test-native/TestNative.podspec b/example/modules/test-native/TestNative.podspec index aac2e5f..a677e54 100644 --- a/example/modules/test-native/TestNative.podspec +++ b/example/modules/test-native/TestNative.podspec @@ -1,4 +1,3 @@ -# Example-only Nitro module: app native code using the public RNOtel API. Pod::Spec.new do |s| s.name = "TestNative" s.version = "0.0.0" @@ -10,14 +9,12 @@ Pod::Spec.new do |s| s.source = { :git => "https://github.com/callstack/react-native-open-telemetry.git" } s.source_files = ["ios/**/*.swift"] - # static libraries: the core and its SwiftPM modules land in the products root (see ReactNativeOpenTelemetry.podspec) s.pod_target_xcconfig = { 'SWIFT_INCLUDE_PATHS' => '$(inherited) "${PODS_CONFIGURATION_BUILD_DIR}"' } load 'nitrogen/generated/ios/TestNative+autolinking.rb' add_nitrogen_files(s) s.dependency 'ReactNativeOpenTelemetryCore' - # builds after the adapter pod, whose script phase forwards the core's module map (static libraries) s.dependency 'ReactNativeOpenTelemetry' s.dependency 'React-jsi' s.dependency 'React-callinvoker' diff --git a/example/modules/test-native/android/build.gradle b/example/modules/test-native/android/build.gradle index 8002e79..9ea6701 100644 --- a/example/modules/test-native/android/build.gradle +++ b/example/modules/test-native/android/build.gradle @@ -1,4 +1,3 @@ -// Example-only Nitro module. Versions follow the app (rootProject.ext), as autolinked libraries do. apply plugin: "com.android.library" apply plugin: "org.jetbrains.kotlin.android" apply from: "../nitrogen/generated/android/TestNative+autolinking.gradle" @@ -26,7 +25,6 @@ android { cmake { path "CMakeLists.txt" } } - // the app and react-native-nitro-modules ship these packagingOptions { excludes = ["META-INF", "META-INF/**", "**/libc++_shared.so", "**/libNitroModules.so", "**/libfbjni.so", "**/libjsi.so", "**/libreactnative.so"] @@ -44,6 +42,5 @@ android { dependencies { implementation "com.facebook.react:react-android" implementation project(":react-native-nitro-modules") - // RNOtel (and, through it, the otel API) implementation project(":react-native-open-telemetry") } diff --git a/example/modules/test-native/android/src/main/java/com/margelo/nitro/callstack/testnative/HybridTestNative.kt b/example/modules/test-native/android/src/main/java/com/margelo/nitro/callstack/testnative/HybridTestNative.kt index e1a8089..3ee6482 100644 --- a/example/modules/test-native/android/src/main/java/com/margelo/nitro/callstack/testnative/HybridTestNative.kt +++ b/example/modules/test-native/android/src/main/java/com/margelo/nitro/callstack/testnative/HybridTestNative.kt @@ -7,14 +7,12 @@ import com.facebook.react.ReactApplication import com.margelo.nitro.NitroModules import java.util.concurrent.TimeUnit -/** App native code using the public helpers (spec §4.3): explicit parent from a traceparent, B's traceparent back to JS. */ -// Constructed from JNI by name (TestNativeOnLoad.cpp): keep it through R8. @DoNotStrip @Keep class HybridTestNative : HybridTestNativeSpec() { override fun doWork(traceparent: String, start: DoubleArray, end: DoubleArray): String { val span = RNOtel.tracer("test-native").spanBuilder("native.work") - .setParent(RNOtel.contextFrom(traceparent)) // explicit, never thread-local; '' -> a root + .setParent(RNOtel.contextFrom(traceparent)) .setStartTimestamp(nanos(start), TimeUnit.NANOSECONDS) .startSpan() span.end(nanos(end), TimeUnit.NANOSECONDS) diff --git a/example/modules/test-native/ios/HybridTestNative.swift b/example/modules/test-native/ios/HybridTestNative.swift index e82c4e9..fe87609 100644 --- a/example/modules/test-native/ios/HybridTestNative.swift +++ b/example/modules/test-native/ios/HybridTestNative.swift @@ -4,11 +4,9 @@ import OpenTelemetryApi import React import ReactNativeOpenTelemetryCore -/// App native code using the public helpers (spec §4.3): explicit parent from a traceparent, B's traceparent back to JS. class HybridTestNative: HybridTestNativeSpec { func doWork(traceparent: String, start: [Double], end: [Double]) throws -> String { let b = RNOtel.tracer("test-native").spanBuilder(spanName: "native.work").setStartTime(time: date(start)) - // explicit, never thread-local; '' -> a root if let parent = RNOtel.contextFrom(traceparent: traceparent) { b.setParent(parent) } else { b.setNoParent() } let span = b.startSpan() span.end(time: date(end)) diff --git a/example/modules/test-native/react-native.config.js b/example/modules/test-native/react-native.config.js index 4c7beef..c36ba55 100644 --- a/example/modules/test-native/react-native.config.js +++ b/example/modules/test-native/react-native.config.js @@ -1,4 +1,3 @@ -// Autolinked by example/react-native.config.js; native code and nitrogen/generated are wired by the podspec and build.gradle. module.exports = { dependency: { platforms: { diff --git a/example/modules/test-native/src/TestNative.nitro.ts b/example/modules/test-native/src/TestNative.nitro.ts index 6b996d0..0c919fb 100644 --- a/example/modules/test-native/src/TestNative.nitro.ts +++ b/example/modules/test-native/src/TestNative.nitro.ts @@ -1,9 +1,6 @@ import type {HybridObject} from 'react-native-nitro-modules'; -/** Example-only: app native code that parents its spans with the public `RNOtel` helpers. */ export interface TestNative extends HybridObject<{ios: 'swift'; android: 'kotlin'}> { - /** Starts and ends `native.work` under `traceparent` ('' = a root) at `start`/`end` ([s, ns]), returns its traceparent. */ doWork(traceparent: string, start: number[], end: number[]): string; - /** Reloads the JS app natively, as OTA updaters do; `DevSettings.reload()` is a no-op in release. */ reload(): void; } diff --git a/example/react-native.config.js b/example/react-native.config.js index d2e79fc..16f1f1a 100644 --- a/example/react-native.config.js +++ b/example/react-native.config.js @@ -1,6 +1,5 @@ const path = require('path'); -// Autolink the library from the repo root and the example-only TestNative module (no npm dependency needed). module.exports = { dependencies: { 'react-native-open-telemetry': {root: path.join(__dirname, '..')}, diff --git a/example/src/ScenariosScreen.tsx b/example/src/ScenariosScreen.tsx index 2a3c6dd..f0c0f74 100644 --- a/example/src/ScenariosScreen.tsx +++ b/example/src/ScenariosScreen.tsx @@ -1,25 +1,20 @@ import {useEffect, useState} from 'react'; import {Pressable, ScrollView, StyleSheet, Text, View} from 'react-native'; import {NitroModules} from 'react-native-nitro-modules'; -// the package's entry imports its setup (context patch); withOtel keeps this import out of inline requires import {startReactNativeSdk} from 'react-native-open-telemetry'; import {getOtel} from '../../src/native/otel'; import {at} from '../../verify/harness/scenario'; import {allScenarios} from '../../verify/scenarios'; import type {TestNative} from '../modules/test-native/src/TestNative.nitro'; -// Failure scenarios whose e2e test decides when, or whether, anything flushes. const NO_FLUSH = new Set(['collector-down', 'flush-after-reload', 'background-flush']); const TEST_MODE = process.env.OTEL_TEST_MODE === '1'; -// fast-refresh-idempotent: the patched functions as first seen; `??=` keeps them across re-evaluations of -// this module, so a refresh that stacked the patch shows `changed`. The e2e edit counts in `__otelRefreshes`. const g = globalThis as any; g.__otelFirstPatch ??= {then: Promise.prototype.then, setTimeout: g.setTimeout}; const patchIdentity = () => `${g.__otelFirstPatch.then === Promise.prototype.then && g.__otelFirstPatch.setTimeout === g.setTimeout ? 'same' : 'changed'} refreshes=${g.__otelRefreshes ?? 0}`; -// Native-first: MainApplication / AppDelegate ran RNOtel.start (collector URL there); attach and export through the native core. async function runScenario(name: string) { const s = allScenarios().find(x => x.name === name)!; const sdk = startReactNativeSdk(); @@ -41,7 +36,6 @@ export function ScenariosScreen() { setTestMode(otel ? `native testMode=${otel.initialize().testMode}` : 'native: no HybridObject'); }, []); - // The run starts after the commit that removed the previous scenario-done, so a stale marker never satisfies a wait. const [running, setRunning] = useState(null); useEffect(() => { if (!running) return; @@ -51,7 +45,6 @@ export function ScenariosScreen() { ).finally(() => setRunning(null)); }, [running]); - // test-mode only: each resolved forceFlush shows `flush-done-`, so a wait never matches a stale one const [flushes, setFlushes] = useState(0); const flush = () => startReactNativeSdk().forceFlush().then(() => setFlushes(n => n + 1)); diff --git a/ios/Adapter/HybridOtel.swift b/ios/Adapter/HybridOtel.swift index ff2d298..a41a06f 100644 --- a/ios/Adapter/HybridOtel.swift +++ b/ios/Adapter/HybridOtel.swift @@ -2,8 +2,6 @@ import Foundation import NitroModules import ReactNativeOpenTelemetryCore -/// The seam: JS spans are wrapped as otel `ReadableSpan`s here and queued in the core (pod `ReactNativeOpenTelemetryCore`, -/// spec §4.2). The core stays free of Nitro's C++-backed types, so the app's AppDelegate can import it without C++ interop. class HybridOtel: HybridOtelSpec { func initialize(config: SeamConfig?) throws -> SeamInitResult { let r = RNOtel.initialize(config.map { @@ -15,13 +13,11 @@ class HybridOtel: HybridOtelSpec { return SeamInitResult(alreadyInitialized: r.alreadyInitialized, testMode: r.testMode, error: r.error) } - /// JS thread: wrap and enqueue; SpanData is built on the export queue. func handOff(spans: [SeamSpan]) throws { guard let core = OtelCore.instance else { return } core.handOff(spans.map { JsReadableSpan($0, resource: core.resource) }) } - /// Off the JS thread (the flush blocks a global queue); resolves even when native never initialized. func flush(timeoutMs: Double) throws -> Promise { Promise.parallel { _ = OtelCore.instance?.flush(timeoutMs: timeoutMs) } } diff --git a/ios/Adapter/JsReadableSpan.swift b/ios/Adapter/JsReadableSpan.swift index e501ac5..ee3eea3 100644 --- a/ios/Adapter/JsReadableSpan.swift +++ b/ios/Adapter/JsReadableSpan.swift @@ -3,13 +3,10 @@ import NitroModules import OpenTelemetryApi import OpenTelemetrySdk -/// Never traps on the JS thread (Int(Double) does on NaN or out of range). func int(_ d: Double) -> Int { Int(exactly: d.rounded(.towardZero)) ?? 0 } -// Number.isInteger(v): whole and finite (-0 included). Int64.max as Double is 2^63, hence the exclusive bound. private func isLong(_ v: Double) -> Bool { v == v.rounded() && v >= -9.223372036854775807E18 && v < 9.223372036854775807E18 } -/// JS numbers become `int` iff Number.isInteger (and they fit), else `double`; the same rule on JS and Kotlin. func attributes(of list: [SeamAttribute]) -> [String: AttributeValue] { var out = [String: AttributeValue](minimumCapacity: list.count) for a in list { @@ -25,13 +22,10 @@ func attributes(of list: [SeamAttribute]) -> [String: AttributeValue] { return out } -/// OTel HrTime `[seconds, nanos]`; missing elements read as 0. `Date` holds a Double of seconds, so whole µs -/// come back on a ~256 ns grid (verify/VERIFY.md). private func date(_ t: [Double]) -> Date { Date(timeIntervalSince1970: (t.count > 0 ? t[0] : 0) + (t.count > 1 ? t[1] : 0) / 1e9) } -/// R21/C5: Swift's SpanKind cases are not in API order, so map the API value explicitly. Unknown -> INTERNAL. private func spanKind(_ k: Int) -> SpanKind { switch k { case 1: return .server @@ -42,7 +36,6 @@ private func spanKind(_ k: Int) -> SpanKind { } } -/// API SpanStatusCode (UNSET 0, OK 1, ERROR 2). Unknown -> UNSET. private func statusOf(_ s: SeamStatus) -> Status { switch int(s.code) { case 1: return .ok @@ -65,18 +58,11 @@ private func spanContext(_ c: SeamSpanContext) -> SpanContext { traceFlags: TraceFlags(fromByte: UInt8(truncatingIfNeeded: int(c.traceFlags))), traceState: traceState(c.traceState)) } -/// Fixed clock: a JS span is already over, nothing here may read the wall clock. private final class FixedClock: Clock { let now: Date init(now: Date) { self.now = now } } -/** - * A finished JS span handed over the seam: the frozen `ReadableSpan` the native BatchSpanProcessor queues. It - * keeps Nitro's struct; only the span context is built on the JS thread (onEnd checks `sampled`), `toSpanData()` runs - * on the BSP worker. SpanData has no public initializer, so it is built through the SDK's own `SpanSdk`, the public - * factory upstream uses. - */ final class JsReadableSpan: ReadableSpan, @unchecked Sendable { private let span: SeamSpan private let resource: Resource @@ -93,7 +79,6 @@ final class JsReadableSpan: ReadableSpan, @unchecked Sendable { var hasEnded: Bool { true } var latency: TimeInterval { date(span.end).timeIntervalSince(date(span.start)) } var description: String { "JsReadableSpan{\(span.name)}" } - // frozen: setters and mutators are no-ops var name: String { get { span.name } set {} } var status: Status { get { statusOf(span.status) } set {} } var instrumentationScopeInfo: InstrumentationScopeInfo { diff --git a/ios/Core/CoreConfig.swift b/ios/Core/CoreConfig.swift index 43366d4..ec56d95 100644 --- a/ios/Core/CoreConfig.swift +++ b/ios/Core/CoreConfig.swift @@ -4,7 +4,6 @@ package struct CoreConfig { var serviceName: String var serviceVersion: String? = nil var resourceAttributes: [String: AttributeValue] = [:] - /// The OTLP/HTTP traces endpoint, used as given. var exportUrl: String var exportHeaders: [String: String] = [:] package init(serviceName: String, serviceVersion: String? = nil, resourceAttributes: [String: AttributeValue] = [:], @@ -14,7 +13,6 @@ package struct CoreConfig { } } -/// Mirrors the seam's `SeamInitResult`. package struct InitResult: Equatable { package var alreadyInitialized: Bool package var testMode: Bool diff --git a/ios/Core/Endpoint.swift b/ios/Core/Endpoint.swift index 6bc8412..dbae3ed 100644 --- a/ios/Core/Endpoint.swift +++ b/ios/Core/Endpoint.swift @@ -1,7 +1,5 @@ import Foundation -/// Eager check (D8/D9), no exporter built. `URL(string: "not a url")` succeeds on current Foundation, so the scheme -/// and host are checked explicitly. Returns an error message or nil. func validateExportUrl(_ url: String) -> String? { guard let u = URL(string: url), let scheme = u.scheme?.lowercased(), ["http", "https"].contains(scheme), !(u.host ?? "").isEmpty else { diff --git a/ios/Core/OtelCore.swift b/ios/Core/OtelCore.swift index 2cf6b5d..bdad4d1 100644 --- a/ios/Core/OtelCore.swift +++ b/ios/Core/OtelCore.swift @@ -3,7 +3,6 @@ import OpenTelemetryApi import OpenTelemetryProtocolExporterHttp import OpenTelemetrySdk -/// Test mode: `0b…` IDs, the native counterpart of JS `sequentialIds('0a')`. private final class SequentialIds: IdGenerator, @unchecked Sendable { private let lock = NSLock() private var t = 0 @@ -15,7 +14,6 @@ private final class SequentialIds: IdGenerator, @unchecked Sendable { let distroName = "react-native-open-telemetry" -/// Built on first export (the export queue), so init on the main thread never constructs an HTTP client. private final class LazyExporter: SpanExporter, @unchecked Sendable { private let lock = NSLock() private var built: OtlpHttpTraceExporter? @@ -37,9 +35,7 @@ private final class LazyExporter: SpanExporter, @unchecked Sendable { } package final class OtelCore { - /// The one resource of the app; in test mode built from config only (no `telemetry.*`). package let resource: Resource - /// The native TracerProvider; JS spans join its batch processor. let tracerProvider: TracerProviderSdk private let bsp: BatchSpanProcessor private let exporter: LazyExporter @@ -54,29 +50,20 @@ package final class OtelCore { } resource = testMode ? Resource(attributes: attrs) : Resource().merging(other: Resource(attributes: attrs)) - // Upstream sends `envVarHeaders ?? config headers`: passing ours there (even empty) means exactly these headers, - // never OTEL_EXPORTER_OTLP_HEADERS. Upstream's default gzip stays on. exporter = LazyExporter { URL(string: config.exportUrl).map { OtlpHttpTraceExporter(endpoint: $0, envVarHeaders: config.exportHeaders.map { ($0.key, $0.value) }) } } - // test mode: no timed export within a device test, so only flush and background export send - bsp = BatchSpanProcessor(spanExporter: exporter, scheduleDelay: testMode ? 120 : 5) // 5 s: upstream's default + bsp = BatchSpanProcessor(spanExporter: exporter, scheduleDelay: testMode ? 120 : 5) let b = TracerProviderBuilder().with(resource: resource).add(spanProcessor: bsp) tracerProvider = (testMode ? b.with(idGenerator: SequentialIds()) : b).build() } - /// JS-thread work: enqueue finished spans; the adapter's wrappers build SpanData on the export queue. package func handOff(_ spans: [ReadableSpan]) { for s in spans { bsp.onEnd(span: s) } } - /// Blocks the caller up to `timeoutMs`. True when nothing is left unsent: the exporter requeues a failed batch, - /// and its `flush` retries it. - // ponytail: upstream BatchWorker race: if its timer thread has just taken the queue but not yet scheduled the - // export, forceFlush finds nothing and returns before that batch is sent (true while in flight). TracerProviderSdk - // forceFlush goes through the same worker; fix upstream or track in-flight spans if flush-after-reload needs it. package func flush(timeoutMs: Double) -> Bool { let deadline = Date().addingTimeInterval(timeoutMs / 1000) bsp.forceFlush(timeout: timeoutMs / 1000) @@ -87,8 +74,6 @@ package final class OtelCore { private static var state: InitResult? package private(set) static var instance: OtelCore? - /// 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. @discardableResult package static func initialize(_ config: CoreConfig?, testMode: Bool = false, distroVersion: String = "unknown") -> InitResult { lock.withLock { diff --git a/ios/Core/Parenting.swift b/ios/Core/Parenting.swift index ec26af6..2a94ae3 100644 --- a/ios/Core/Parenting.swift +++ b/ios/Core/Parenting.swift @@ -3,11 +3,7 @@ import OpenTelemetryApi private let traceparentRegex = try! NSRegularExpression(pattern: "^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$") -/// W3C traceparent -> a NON-remote parent `SpanContext` (spec §4.3). In opentelemetry-swift the explicit parent is a -/// `SpanContext`: pass it to `SpanBuilder.setParent(_:)`; nil means "no parent" (`setNoParent()`), i.e. a root. -/// Not W3CTraceContextPropagator.extract: that yields isRemote=true. Invalid input (incl. all-zero ids) -> nil; never throws. func contextFrom(traceparent: String) -> SpanContext? { - // `$` matches before a trailing newline, so match the whole string explicitly. let range = NSRange(traceparent.startIndex..., in: traceparent) guard let m = traceparentRegex.firstMatch(in: traceparent, range: range), m.range == range, let t = Range(m.range(at: 1), in: traceparent), let s = Range(m.range(at: 2), in: traceparent), diff --git a/ios/RNOtel/RNOtelConfig.swift b/ios/RNOtel/RNOtelConfig.swift index 304e8cb..454794b 100644 --- a/ios/RNOtel/RNOtelConfig.swift +++ b/ios/RNOtel/RNOtelConfig.swift @@ -1,6 +1,5 @@ import OpenTelemetryApi -/// Native-first config (spec §4.4): `RNOtel.start { c in c.serviceName = …; c.export = .init(url: …) }`. public final class RNOtelConfig { public var serviceName = "" public var serviceVersion: String? @@ -8,7 +7,6 @@ public final class RNOtelConfig { public var export = Export(url: "") public struct Export { - /// The OTLP/HTTP traces endpoint (e.g. `https://collector:4318/v1/traces`), used as given. public var url: String public var headers: [String: String] public init(url: String, headers: [String: String] = [:]) { self.url = url; self.headers = headers } diff --git a/metro/__tests__/withOtel.test.js b/metro/__tests__/withOtel.test.js index 76780c0..4333d9f 100644 --- a/metro/__tests__/withOtel.test.js +++ b/metro/__tests__/withOtel.test.js @@ -1,6 +1,5 @@ const {withOtel} = require('..'); -// Stubbed so the test does not depend on a built lib/ (self-reference via `exports`). const SETUP = '/pkg/lib/module/setup.js'; const run = config => withOtel(config, {setupPath: SETUP}).serializer.getModulesRunBeforeMainModule('/app/index.js'); const CORE = '/rn/Libraries/Core/InitializeCore.js'; diff --git a/metro/index.js b/metro/index.js index 0f4ef4e..3dbed17 100644 --- a/metro/index.js +++ b/metro/index.js @@ -1,17 +1,8 @@ const PACKAGE = 'react-native-open-telemetry'; -/** - * Metro helper: runs the SDK's setup (context patch) before the app. - * Appending to `getModulesRunBeforeMainModule` puts it after RN's InitializeCore and before any app module. - * Metro only runs such an entry if it is already in the bundle graph; `src/index.ts` imports `./setup` for that. - * The package is also excluded from inline requires (`nonInlinedRequires`): an inlined import whose only use is - * platform-dead code (e.g. inside `Platform.OS === 'android'` on iOS) would otherwise drop the package, and setup, - * from a release graph. - */ function withOtel(config, {setupPath = require.resolve('react-native-open-telemetry/setup')} = {}) { const serializer = config.serializer ?? {}; const original = serializer.getModulesRunBeforeMainModule; - // without it Metro would run only our setup before the app, and drop RN's InitializeCore if (typeof original !== 'function') { throw new Error( `${PACKAGE}/metro: apply withOtel to the merged config: withOtel(mergeConfig(getDefaultConfig(__dirname), config))`, diff --git a/react-native.config.js b/react-native.config.js index 964ae82..bb65396 100644 --- a/react-native.config.js +++ b/react-native.config.js @@ -1,8 +1,3 @@ -// https://github.com/react-native-community/cli/blob/main/docs/dependencies.md -// Nitro: the native code and nitrogen/generated are wired by android/build.gradle and the podspec. -// Two podspecs sit at the root; autolinking links only the Nitro adapter (apps add the Core pod). podspecPath says -// which; RN CLI 20.2 and Expo 58 do not read it yet (CLI: the first `*.podspec` glob hit; Expo: the first sorted, both -// ReactNativeOpenTelemetry.podspec today). module.exports = { dependency: { platforms: { diff --git a/src/context/RNContextManager.ts b/src/context/RNContextManager.ts index 66f2257..2036d61 100644 --- a/src/context/RNContextManager.ts +++ b/src/context/RNContextManager.ts @@ -1,9 +1,7 @@ import type {Context} from '@opentelemetry/api'; import {StackContextManager} from '@opentelemetry/sdk-trace'; -/** StackContextManager plus a raw enter/leave primitive for the patch wrappers (§6.1). */ export class RNContextManager extends StackContextManager { - /** Makes `ctx` active and returns the previous context; the caller restores it with another swap. */ swap(ctx: Context): Context { const prev = this._currentContext; this._currentContext = ctx; diff --git a/src/context/__tests__/patch.test.ts b/src/context/__tests__/patch.test.ts index 16991a4..3d353ec 100644 --- a/src/context/__tests__/patch.test.ts +++ b/src/context/__tests__/patch.test.ts @@ -2,7 +2,6 @@ import {ROOT_CONTEXT, createContextKey} from '@opentelemetry/api'; import {RNContextManager} from '../RNContextManager'; import {installContextPatch} from '../patch'; -// Spy installed before the patch: it stands in for the original `then` and records what reaches it. const realThen = Promise.prototype.then; const seen: unknown[] = []; Promise.prototype.then = function (this: Promise, ok?: any, err?: any) { diff --git a/src/context/__tests__/probe.test.ts b/src/context/__tests__/probe.test.ts index 713c005..cb0beaf 100644 --- a/src/context/__tests__/probe.test.ts +++ b/src/context/__tests__/probe.test.ts @@ -2,12 +2,10 @@ import {context} from '@opentelemetry/api'; import {DEGRADED_ATTR, probeAsyncContext, scopeAttributes} from '../probe'; import '../../setup'; -// Built with `new Function` so it stays native async whichever Babel config compiled this file. const nativeStep = new Function('context', 'return (async () => { await null; return context.active(); })')(context); test('probe resolves true when then is patched and false when async is native', async () => { const err = jest.spyOn(console, 'error').mockImplementation(() => {}); - // a `.then` chain goes through the patched Promise.prototype.then expect(await probeAsyncContext(() => Promise.resolve().then(() => context.active()))).toBe(true); expect(scopeAttributes()).toEqual({}); expect(err).not.toHaveBeenCalled(); diff --git a/src/context/patch.ts b/src/context/patch.ts index 9a895b3..783a2aa 100644 --- a/src/context/patch.ts +++ b/src/context/patch.ts @@ -5,24 +5,17 @@ export const MARKER = Symbol.for('com.callstack.otel.patched'); const TIMERS = ['setTimeout', 'setImmediate', 'queueMicrotask', 'requestAnimationFrame'] as const; type Fn = (...args: any[]) => any; -/** Holds the pre-patch functions and the singleton, so a second install (fast refresh, a second SDK copy) is a no-op. */ export type PatchMarker = { then: typeof Promise.prototype.then; setInterval: Fn; contextManager: RNContextManager; } & Partial>; -/** - * Carries the active context from where a callback is scheduled to where it runs (§6.1). - * At ROOT the original is called unwrapped (every wrapper restores in `finally`, so jobs start at ROOT). - * `setInterval` ticks run in ROOT_CONTEXT (§6.2). - */ export function installContextPatch(cm: RNContextManager): void { const g = globalThis as any; if (g[MARKER]) return; const marker: PatchMarker = {then: Promise.prototype.then, setInterval: g.setInterval, contextManager: cm}; - // fixed arity: `then` callbacks take one argument const wrap = (ctx: Context, fn: Fn) => function (this: unknown, v: unknown) { const prev = cm.swap(ctx); @@ -32,7 +25,6 @@ export function installContextPatch(cm: RNContextManager): void { cm.swap(prev); } }; - // timers forward extra arguments const wrapArgs = (ctx: Context, fn: Fn) => function (this: unknown, ...args: unknown[]) { const prev = cm.swap(ctx); @@ -56,7 +48,7 @@ export function installContextPatch(cm: RNContextManager): void { for (const name of TIMERS) { const orig: Fn | undefined = g[name]; - if (typeof orig !== 'function') continue; // rAF is absent in Node, setImmediate on web + if (typeof orig !== 'function') continue; marker[name] = orig; g[name] = function (cb: unknown, ...rest: unknown[]) { const ctx = cm.active(); diff --git a/src/context/probe.ts b/src/context/probe.ts index fcb1b31..a420bf4 100644 --- a/src/context/probe.ts +++ b/src/context/probe.ts @@ -5,16 +5,11 @@ export {DEGRADED_ATTR, scopeAttributes} from './scope'; const KEY = createContextKey('com.callstack.probe'); -// `await` here only keeps the context if the bundler downleveled async to generators (then the patched `then` runs). const defaultStep = async (): Promise => { await null; return context.active(); }; -/** - * Startup probe (§6.1.4): does the active context survive `await`? On failure, logs once and flags the SDK's tracers - * as degraded. `step` is injectable for tests. - */ export async function probeAsyncContext(step: () => Promise = defaultStep): Promise { const after = await context.with(context.active().setValue(KEY, true), step); const ok = after.getValue(KEY) === true; diff --git a/src/context/scope.ts b/src/context/scope.ts index b9100a2..2e1aeb9 100644 --- a/src/context/scope.ts +++ b/src/context/scope.ts @@ -3,13 +3,10 @@ import type {Attributes, Tracer} from '@opentelemetry/api'; export const DEGRADED_ATTR = 'com.callstack.context.degraded'; let degraded = false; -// ponytail: one entry per tracer; tracers are few and long-lived const stamped = new Map<{attributes?: Attributes}, Attributes>(); -/** Scope attributes every SDK tracer carries: the degraded flag once the startup probe has failed (§6.1.4). */ export const scopeAttributes = (): Attributes => (degraded ? {[DEGRADED_ATTR]: true} : {}); -/** Called by the probe on failure; tracers stamped earlier get the flag too. */ export function markDegraded(): boolean { if (degraded) return false; degraded = true; @@ -17,13 +14,8 @@ export function markDegraded(): boolean { return true; } -/** - * sdk-trace 3.1 has no API for scope attributes, but its OTLP exporter and our seam read them off - * `tracer.instrumentationScope` at runtime. Every tracer the SDK hands out goes through here (mobile and web). - */ export function stampScope(tracer: T, extra: Attributes = {}): T { const scope = (tracer as unknown as {instrumentationScope?: {attributes?: Attributes}}).instrumentationScope; - // an upstream change or a foreign tracer: no scope attributes, but never throw into the app if (typeof scope !== 'object' || scope === null) return tracer; const merged = {...stamped.get(scope), ...extra}; stamped.set(scope, merged); diff --git a/src/handoff/NativeHandOffProcessor.ts b/src/handoff/NativeHandOffProcessor.ts index c57bdf8..e8dd56d 100644 --- a/src/handoff/NativeHandOffProcessor.ts +++ b/src/handoff/NativeHandOffProcessor.ts @@ -3,7 +3,6 @@ import type {ReadableSpan, SpanProcessor} from '@opentelemetry/sdk-trace'; import type {Otel} from '../native/Otel.nitro'; import {toSeamSpan} from './toSeamSpan'; -/** No buffer (spec §4.3): every sampled span goes straight to native. */ export class NativeHandOffProcessor implements SpanProcessor { private reported = false; constructor(private readonly native: Otel) {} @@ -13,7 +12,6 @@ export class NativeHandOffProcessor implements SpanProcessor { try { this.native.handOff([toSeamSpan(span)]); } catch (e) { - // never into the app; one report, not one per span if (!this.reported) diag.error('handOff failed, dropping spans', e); this.reported = true; } diff --git a/src/handoff/toSeamSpan.ts b/src/handoff/toSeamSpan.ts index ef19da2..e304ba5 100644 --- a/src/handoff/toSeamSpan.ts +++ b/src/handoff/toSeamSpan.ts @@ -3,12 +3,10 @@ import type {ReadableSpan} from '@opentelemetry/sdk-trace'; import type {AttrValue, SeamAttribute, SeamSpan, SeamSpanContext} from '../native/Otel.nitro'; const PRIMS = ['string', 'number', 'boolean']; -// Seam-representable: a primitive, or a homogeneous array of one primitive type, no nulls (empty is fine). const seamValue = (v: unknown): v is AttrValue => PRIMS.includes(typeof v) || (Array.isArray(v) && v.every(x => PRIMS.includes(typeof x) && typeof x === typeof v[0])); -// Insertion order; anything the seam cannot carry (null, undefined, objects, bytes, mixed arrays) is dropped. export const attrs = (a: Attributes | undefined): SeamAttribute[] => { const out: SeamAttribute[] = []; for (const key in a) { @@ -26,7 +24,6 @@ const ctxOf = (c: SpanContext): SeamSpanContext => { export function toSeamSpan(span: ReadableSpan): SeamSpan { const parent = span.parentSpanContext?.spanId; const {version, schemaUrl} = span.instrumentationScope; - // sdk-trace 3.1's InstrumentationScope type has no attributes, but exporters read them at runtime. const scopeAttrs = (span.instrumentationScope as {attributes?: Attributes}).attributes; return { context: ctxOf(span.spanContext()), diff --git a/src/index.ts b/src/index.ts index 02b1579..3e2c500 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,3 @@ -// Side effect: keeps ./setup in the bundle graph so Metro's runBeforeMainModule entry can run it. import './setup'; export {startReactNativeSdk} from './sdk/start'; diff --git a/src/index.web.ts b/src/index.web.ts index eb40174..9614616 100644 --- a/src/index.web.ts +++ b/src/index.web.ts @@ -1,4 +1,3 @@ -// Side effect: registers the context manager and patch before the app runs. import './setup'; export {startReactNativeSdk} from './sdk/start.web'; diff --git a/src/internal/testMode.ts b/src/internal/testMode.ts index f15afa7..92f9a43 100644 --- a/src/internal/testMode.ts +++ b/src/internal/testMode.ts @@ -1,7 +1,5 @@ import type {IdGenerator} from '@opentelemetry/sdk-trace'; -// The plain `process.env.OTEL_TEST_MODE` form is what a Babel plugin inlines at bundle time; a browser bundle without -// it has no `process`, hence the catch. export const isTestModeBuild = (): boolean => { try { return process.env.OTEL_TEST_MODE === '1'; diff --git a/src/native/Otel.nitro.ts b/src/native/Otel.nitro.ts index 375f412..51bf454 100644 --- a/src/native/Otel.nitro.ts +++ b/src/native/Otel.nitro.ts @@ -1,6 +1,5 @@ import type {HybridObject} from 'react-native-nitro-modules'; -// ponytail: Nitro rejects tuples in Swift (swiftlang/swift#75865); number[] of length 2, same JS shape as OTel HrTime. export type HrTime = number[]; export interface SeamSpanContext { traceId: string; spanId: string; traceFlags: number; traceState?: string } export type AttrValue = string | number | boolean | string[] | number[] | boolean[]; @@ -10,7 +9,6 @@ export interface SeamLink { context: SeamSpanContext; attributes: SeamAttribute[ export interface SeamScope { name: string; version?: string; schemaUrl?: string; attributes: SeamAttribute[] } export interface SeamStatus { code: number; message?: string } export interface SeamSpan { - // @opentelemetry/api SpanKind (INTERNAL=0); OTLP kind = this + 1, native converts. context: SeamSpanContext; parentSpanId?: string; name: string; kind: number; start: HrTime; end: HrTime; attributes: SeamAttribute[]; events: SeamEvent[]; links: SeamLink[]; status: SeamStatus; scope: SeamScope; diff --git a/src/native/otel.ts b/src/native/otel.ts index 154873a..e2e7618 100644 --- a/src/native/otel.ts +++ b/src/native/otel.ts @@ -1,7 +1,6 @@ import {NitroModules} from 'react-native-nitro-modules'; import type {Otel} from './Otel.nitro'; -/** undefined when the HybridObject isn't registered (web, Jest, Expo Go); a constructor failure throws. */ export function getOtel(): Otel | undefined { return NitroModules.hasHybridObject('Otel') ? NitroModules.createHybridObject('Otel') : undefined; } diff --git a/src/sdk/__tests__/start.test.ts b/src/sdk/__tests__/start.test.ts index 06c630d..76f50b5 100644 --- a/src/sdk/__tests__/start.test.ts +++ b/src/sdk/__tests__/start.test.ts @@ -49,7 +49,7 @@ test('attaches when native is initialized', () => { const {calls, spans} = fakeOtel({initialized: true}); const h = startReactNativeSdk(CONFIG); expect(calls).toHaveLength(1); - expect(warn).toHaveBeenCalledTimes(1); // exportConfig ignored + expect(warn).toHaveBeenCalledTimes(1); h.tracerProvider.getTracer('t').startSpan('s').end(); expect(spans.map(s => s.name)).toEqual(['s']); expect(err).not.toHaveBeenCalled(); @@ -133,7 +133,6 @@ test('second call returns the first handle with one warning', () => { expect(startReactNativeSdk()).toBe(h); expect(startReactNativeSdk()).toBe(h); expect(warn).toHaveBeenCalledTimes(1); - // a fast-refresh re-evaluation of the SDK module still returns it jest.isolateModules(() => expect(require('../start').startReactNativeSdk()).toBe(h)); }); diff --git a/src/sdk/__tests__/start.web.test.ts b/src/sdk/__tests__/start.web.test.ts index 63ee388..1692c38 100644 --- a/src/sdk/__tests__/start.web.test.ts +++ b/src/sdk/__tests__/start.web.test.ts @@ -1,6 +1,3 @@ -/** - * @jest-environment jsdom - */ import {context, ROOT_CONTEXT, trace, type ProxyTracerProvider} from '@opentelemetry/api'; import {InMemorySpanExporter, SimpleSpanProcessor} from '@opentelemetry/sdk-trace'; import {MARKER} from '../../context/patch'; @@ -10,10 +7,8 @@ import {startReactNativeSdk} from '../start.web'; const CONFIG = {serviceName: 'shop', exportConfig: {url: 'https://c.example.com:4318/v1/traces', headers: {'x-api-key': 'k'}}}; -// jsdom lacks TextEncoder (every browser has it); the proto serializer needs it. (globalThis as any).TextEncoder ??= require('util').TextEncoder; -// Jest 30 always adds the `node` condition to require(); load the exporter's browser (fetch) build as a web bundler would. jest.mock('@opentelemetry/exporter-trace-otlp-proto', () => jest.requireActual(require.resolve('@opentelemetry/exporter-trace-otlp-proto').replace(/index\.cjs$/, 'platform/browser/index.cjs')), ); diff --git a/src/sdk/config.ts b/src/sdk/config.ts index 665becc..267836f 100644 --- a/src/sdk/config.ts +++ b/src/sdk/config.ts @@ -5,7 +5,6 @@ export interface SdkConfig { serviceName?: string; serviceVersion?: string; resourceAttributes?: Attributes; - /** `url` is the OTLP/HTTP traces endpoint, used as given (e.g. `https://collector:4318/v1/traces`, §4.4). */ exportConfig?: {url: string; headers?: Record}; spanProcessors?: SpanProcessor[]; } diff --git a/src/sdk/noop.ts b/src/sdk/noop.ts index 55f2661..58f0d76 100644 --- a/src/sdk/noop.ts +++ b/src/sdk/noop.ts @@ -1,7 +1,6 @@ import {ProxyTracerProvider} from '@opentelemetry/api'; import type {SdkHandle} from './config'; -/** A delegate-less proxy hands out no-op tracers. */ export const noopHandle = (): SdkHandle => ({ tracerProvider: new ProxyTracerProvider(), forceFlush: async () => {}, diff --git a/src/sdk/shared.ts b/src/sdk/shared.ts index 1a9c25e..bfc850b 100644 --- a/src/sdk/shared.ts +++ b/src/sdk/shared.ts @@ -8,7 +8,6 @@ import {noopHandle} from './noop'; export const TAG = '[react-native-open-telemetry]'; -/** Stamps every tracer, makes `provider` the global one, starts the probe; returns the handle. */ export function register(provider: TracerProvider): SdkHandle { const getTracer = provider.getTracer.bind(provider); provider.getTracer = (name, version, options) => stampScope(getTracer(name, version, options)); @@ -23,10 +22,8 @@ export function register(provider: TracerProvider): SdkHandle { }; } -// On the marker (globalThis), so a fast-refresh re-evaluation of this module still finds the first handle. type Marker = PatchMarker & {handle?: SdkHandle; warned?: boolean}; -/** D10: the first call's handle wins; later calls get it back with one warning. Never throws. */ export function startOnce(start: (config?: SdkConfig) => SdkHandle, config?: SdkConfig): SdkHandle { const m: Marker = (globalThis as any)[MARKER]; if (m.handle) { diff --git a/src/sdk/start.ts b/src/sdk/start.ts index a370f9d..1966085 100644 --- a/src/sdk/start.ts +++ b/src/sdk/start.ts @@ -10,7 +10,6 @@ import type {SdkConfig, SdkHandle} from './config'; import {noopHandle} from './noop'; import {register, startOnce, TAG} from './shared'; -/** Undefined unless there is enough to initialize native; native then reports the missing config. */ function toSeamConfig(c: SdkConfig): SeamConfig | undefined { if (!c.serviceName || !c.exportConfig?.url) return undefined; return { @@ -37,7 +36,6 @@ function start(config: SdkConfig | undefined): SdkHandle { const seam = config && toSeamConfig(config); const result = native.initialize(seam); if (result.error) { - // alreadyInitialized: a failed native-first init sticks and native already reported it, once if (result.alreadyInitialized) return noopHandle(); if (config && !seam) { console.error(`${TAG} serviceName and exportConfig.url are required to initialize native; telemetry is off.`); @@ -50,7 +48,6 @@ function start(config: SdkConfig | undefined): SdkHandle { console.warn(`${TAG} native was initialized first; the JS exportConfig is ignored.`); } - // Resource is empty: native owns it. Sampler: upstream default ParentBased(AlwaysOn). Timing: upstream (§4.3 Clock). const provider = new TracerProvider({ resource: emptyResource(), ...(result.testMode ? {idGenerator: sequentialIds('0a')} : {}), @@ -59,5 +56,4 @@ function start(config: SdkConfig | undefined): SdkHandle { return register(provider); } -/** Attaches to native, or initializes it from `config` (§4.4). Never throws: failures give one error and a no-op handle. */ export const startReactNativeSdk = (config?: SdkConfig): SdkHandle => startOnce(start, config); diff --git a/src/sdk/start.web.ts b/src/sdk/start.web.ts index 8fb23b7..341dcf3 100644 --- a/src/sdk/start.web.ts +++ b/src/sdk/start.web.ts @@ -8,7 +8,6 @@ import type {SdkConfig, SdkHandle} from './config'; import {noopHandle} from './noop'; import {register, startOnce, TAG} from './shared'; -/** Eager check, like native's: http(s) scheme and a host. */ function isHttpUrl(url: string): boolean { try { const u = new URL(url); @@ -29,7 +28,6 @@ function start(config: SdkConfig | undefined): SdkHandle { } const testMode = isTestModeBuild(); const {serviceName, serviceVersion, resourceAttributes, exportConfig, spanProcessors = []} = config; - // JS owns the resource on web: no telemetry.sdk.* (§4.3), distro only outside test mode (goldens). const resource = resourceFromAttributes({ ...resourceAttributes, 'service.name': serviceName, @@ -46,5 +44,4 @@ function start(config: SdkConfig | undefined): SdkHandle { ); } -/** Web: spans export straight from JS over OTLP/proto (§7). Never throws: failures give one error and a no-op handle. */ export const startReactNativeSdk = (config?: SdkConfig): SdkHandle => startOnce(start, config); diff --git a/src/setup.ts b/src/setup.ts index 86fd7b8..21263ee 100644 --- a/src/setup.ts +++ b/src/setup.ts @@ -2,12 +2,9 @@ import {context} from '@opentelemetry/api'; import {RNContextManager} from './context/RNContextManager'; import {MARKER, installContextPatch, type PatchMarker} from './context/patch'; -// Runs before the app (the Metro helper). Reuse the marker's singleton so a re-evaluation (fast refresh, -// a second copy of the SDK) never makes a second context manager. const existing: PatchMarker | undefined = (globalThis as any)[MARKER]; export const contextManager: RNContextManager = existing?.contextManager ?? new RNContextManager().enable(); installContextPatch(contextManager); -// On a re-evaluation our own manager is already registered; only a foreign one is an error. if (!context.setGlobalContextManager(contextManager) && !existing) { console.error('[react-native-open-telemetry] another context manager is already registered; spans may not nest.'); } diff --git a/verify/e2e/background-flush.e2e.ts b/verify/e2e/background-flush.e2e.ts index d0ebb74..accb28b 100644 --- a/verify/e2e/background-flush.e2e.ts +++ b/verify/e2e/background-flush.e2e.ts @@ -2,8 +2,6 @@ import {execFileSync} from 'node:child_process'; import {expect} from 'e2e'; import {bundleIdOf, clearDeviceLog, expectScenario, MOBILE, platformOf, tapFlush, test, until} from './harness'; -// Spans handed off right before the app goes to background are exported without forceFlush() (§9.4). Test mode has -// no timed export (scheduleDelay 120 s), so within the wait only the background hook can have sent them. test('background-flush', {platforms: MOBILE}, async ({app, screen, collector, device, target}) => { const {deviceId} = device.unstable_raw; const android = platformOf(target) === 'android'; @@ -12,15 +10,11 @@ test('background-flush', {platforms: MOBILE}, async ({app, screen, collector, de if (android) await clearDeviceLog('android', deviceId); await device.home(); if (!(await until(() => collector.received() > 0, 15_000))) throw new Error('nothing exported within 15 s of going to background'); - // back in the foreground the app answers a tap at once: the background flush left the main thread free - // foreground only (app.open() relaunches). A CI simulator's `simctl launch` can outlast agent-device's 15 s - // xcrun timeout; the flush runs off the main thread (RNOtel.swift), so one retry, then the 2 s tap still proves it. const open = () => device.openApp(bundleIdOf(target)); await open().catch(open); await tapFlush(screen, 1, 2_000); }, }); - // and Android recorded no ANR for the app if (android) expect(execFileSync('adb', ['-s', deviceId, 'logcat', '-d', '-b', 'events', '-s', 'am_anr'], {encoding: 'utf8'})).not.toContain( bundleIdOf(target), diff --git a/verify/e2e/collector-down.e2e.ts b/verify/e2e/collector-down.e2e.ts index 1c983c9..e99fb34 100644 --- a/verify/e2e/collector-down.e2e.ts +++ b/verify/e2e/collector-down.e2e.ts @@ -1,18 +1,12 @@ import {anyTarget, expectScenario, platformOf, tapFlush} from './harness'; -// Collector down (§9.4): the app does not block, and the span arrives exactly once when the collector is back. -// Android: otel-java retries a 503 inside the export. iOS: opentelemetry-swift does not retry; it requeues the failed -// batch in memory and resends it on the next export or flush, so the test flushes until the refusals are used up. -// Web: the OTel JS exporter retries a 503 inside the export (backoff 1 s x1.5, ±20 %): three refusals take up to 5.7 s. anyTarget('collector-down', async ({app, screen, collector, target}) => { await expectScenario('collector-down', target, {app, screen, collector}, { - afterBegin: () => collector.refuse(503, 3), // after begin, which clears refusals (F15) + afterBegin: () => collector.refuse(503, 3), afterDone: async () => { - // the app never waits on the collector: each forceFlush resolves within the native flush timeout (5 s), - // on web once the exporter's own retries are done const timeout = platformOf(target) === 'web' ? 10_000 : 6_000; for (let n = 1; n <= 3; n++) await tapFlush(screen, n, timeout); - await new Promise(r => setTimeout(r, 1_000)); // a late duplicate (iOS requeue) would now count against "once" + await new Promise(r => setTimeout(r, 1_000)); }, }); }); diff --git a/verify/e2e/e2e.config.ts b/verify/e2e/e2e.config.ts index 173e0ca..ab64b61 100644 --- a/verify/e2e/e2e.config.ts +++ b/verify/e2e/e2e.config.ts @@ -4,18 +4,16 @@ import {web} from '@e2e-dev/web'; const bundleId = 'opentelemetry.example'; const example = '../../example'; -// Expo prebuild app (JS-fallback init): same scenarios, same expected files const expo = '../../example-expo'; export default { projectId: 'react-native-open-telemetry', tests: '*.e2e.ts', - // one collector port: targets must not run at once workers: 1, - retries: process.env.VERIFY_E2E_DRAFT === '1' ? 0 : 1, // a retry would pass against its own fresh draft + retries: process.env.VERIFY_E2E_DRAFT === '1' ? 0 : 1, timeout: 180_000, launchTimeout: 120_000, - actionTimeout: 90_000, // CI simulators answer installs and taps slowly + actionTimeout: 90_000, targets: [ { name: 'android-bare', @@ -49,8 +47,6 @@ export default { appPath: process.env.E2E_IOS_EXPO_APP ?? `${expo}/ios/build/Build/Products/Release-iphonesimulator/OpenTelemetryExpo.app`, }, }, - // The Expo app's Metro web export (react-native-web), exporting with the web SDK. - // The runner exports it in test mode (lib/ first: `bun run prepare`) and serves it with `expo serve`. { name: 'web', engine: web({browser: 'chromium'}), @@ -66,7 +62,6 @@ export default { }, }, }, - // Dev builds (Debug + Metro), local only: fast-refresh-idempotent. See VERIFY.md. ...(process.env.E2E_DEV === '1' ? [ { diff --git a/verify/e2e/export-headers.e2e.ts b/verify/e2e/export-headers.e2e.ts index d4d374d..8e6e4d6 100644 --- a/verify/e2e/export-headers.e2e.ts +++ b/verify/e2e/export-headers.e2e.ts @@ -3,7 +3,6 @@ import path from 'node:path'; import {expect} from 'e2e'; import {anyTarget, expectScenario} from './harness'; -// the app's init headers (x-api-key: test) reach the collector on every export request. anyTarget('export-headers', async ({app, screen, collector, target}) => { await expectScenario('export-headers', target, {app, screen, collector}); const raw = path.join(import.meta.dirname, '..', 'artifacts', 'raw', `export-headers.${target.split('-')[0]}`); diff --git a/verify/e2e/fast-refresh-idempotent.e2e.ts b/verify/e2e/fast-refresh-idempotent.e2e.ts index 6ab19ae..6504189 100644 --- a/verify/e2e/fast-refresh-idempotent.e2e.ts +++ b/verify/e2e/fast-refresh-idempotent.e2e.ts @@ -3,12 +3,8 @@ import path from 'node:path'; import {expect} from 'e2e'; import {expectScenario, MOBILE, test} from './harness'; -// The module withOtel runs before the app: it installs the patch on every evaluation. const SETUP = path.join(import.meta.dirname, '..', '..', 'lib', 'module', 'setup.js'); -// Fast refresh does not stack the context patch (§6.1.3, §9.4). Dev builds + Metro only (E2E_DEV=1, `*-dev` targets). -// Each edit of setup.js makes Metro hot-update it, so it re-evaluates and runs installContextPatch again; the edit -// counts re-evaluations in `__otelRefreshes`. `patch-identity` compares `then`/`setTimeout` with their first values. test('fast-refresh-idempotent', {platforms: MOBILE}, async ({app, screen, collector, target}) => { test.skip(!target.endsWith('-dev'), 'needs a dev build and Metro (E2E_DEV=1)'); const original = fs.readFileSync(SETUP, 'utf8'); @@ -17,10 +13,8 @@ test('fast-refresh-idempotent', {platforms: MOBILE}, async ({app, screen, collec await expect(screen.getByTestId('patch-identity')).toHaveText('same refreshes=0', {timeout: 60_000}); for (const n of [1, 2]) { fs.writeFileSync(SETUP, `${original}\nglobalThis.__otelRefreshes = (globalThis.__otelRefreshes ?? 0) + 1; // refresh ${n}\n`); - // `same` with the count: a hot update (a full reload would reset the count) and no stacked wrappers await expect(screen.getByTestId('patch-identity')).toHaveText(`same refreshes=${n}`, {timeout: 30_000}); } - // and the nesting still holds: the same output as nest-after-await's expected file await expectScenario('nest-after-await', target, {app, screen, collector}, {launch: async () => {}}); } finally { fs.writeFileSync(SETUP, original); diff --git a/verify/e2e/flush-after-reload.e2e.ts b/verify/e2e/flush-after-reload.e2e.ts index 819937c..f1a3452 100644 --- a/verify/e2e/flush-after-reload.e2e.ts +++ b/verify/e2e/flush-after-reload.e2e.ts @@ -1,14 +1,10 @@ import {expect} from 'e2e'; import {expectScenario, MOBILE, tapFlush, test} from './harness'; -// forceFlush() across a JS reload (§9.4): the span handed off before the reload is still queued in native (JS keeps -// no buffer); after the reload a new JS SDK attaches and its forceFlush() resolves within 5 s and sends it exactly once. -// Test mode has no timed export (scheduleDelay 120 s), so only that flush can have sent it. test('flush-after-reload', {platforms: MOBILE}, async ({app, screen, collector, target}) => { await expectScenario('flush-after-reload', target, {app, screen, collector}, { afterDone: async () => { - await screen.getByTestId('reload').tap(); // native reload (TestNative), test-mode builds only - // the reloaded JS app starts over: the done marker is gone + await screen.getByTestId('reload').tap(); await expect(screen.getByTestId('scenario-done')).toBeHidden({timeout: 15_000}); await tapFlush(screen, 1, 5_000); }, diff --git a/verify/e2e/harness.ts b/verify/e2e/harness.ts index fac72f9..8a7d39d 100644 --- a/verify/e2e/harness.ts +++ b/verify/e2e/harness.ts @@ -5,14 +5,11 @@ import {test as webBase} from '@e2e-dev/web'; import {describe, expect, type App, type Screen} from 'e2e'; import type {Target} from '../harness/scenario'; -// Device runs compare to the reviewed expected files of their platform (native-first); never rewrite them. if (process.env.VERIFY_UPDATE === '1') throw new Error('verify/e2e is compare-only: unset VERIFY_UPDATE (`bun verify --update --e2e` already does)'); const verifyDir = path.join(import.meta.dirname, '..'); process.env.VERIFY_DIR = verifyDir; -// ponytail: e2e loads files as ESM; the CJS-style harness modules (all in verify/harness/) read __dirname. -// Give them that one value; drop when the harness moves to import.meta.dirname. (globalThis as any).__dirname ??= path.join(verifyDir, 'harness'); const {startCollector} = await import('../harness/collector'); @@ -20,22 +17,16 @@ const {compareToExpected} = await import('../harness/compare'); export const {allScenarios} = await import('../scenarios'); type Collector = Awaited>; -/** Test-mode override of the Android example's export URL (OtelInit.kt), written by native-init-failure.e2e.ts. */ export const ANDROID_EXPORT_URL_FILE = '/sdcard/Android/data/opentelemetry.example/files/otel-export-url'; -/** Must match the example apps' native init URLs (OtelInit.kt, AppDelegate.swift). */ export const COLLECTOR_PORT = 4318; -/** Must match e2e.config.ts: the bare example, or the Expo app (`*-expo`). */ export const bundleIdOf = (targetName: string) => (targetName.endsWith('-expo') ? 'opentelemetry.example.expo' : 'opentelemetry.example'); -/** `android-bare` -> `android`; `web` stays `web`. */ export const platformOf = (targetName: string) => targetName.split('-')[0] as 'android' | 'ios' | 'web'; -/** Platforms of the targets `test` runs on; a test on web goes through `webTest` or `anyTarget`. */ export const MOBILE = ['android', 'ios']; -// One collector per worker. Each chain below declares it; a target runs only one chain's tests (`platforms`). const collector = [ async ({}, use: (c: Collector) => Promise) => { const c = await startCollector({port: COLLECTOR_PORT, artifactsDir: path.join(verifyDir, 'artifacts')}); @@ -45,7 +36,6 @@ const collector = [ {scope: 'worker'}, ] as const; -/** Web targets (`web`): a fresh browser context per test; `platform` is the target name. */ export const webTest = webBase.extend<{target: string}, {collector: Collector}>({ collector, target: async ({platform}, use) => { @@ -53,24 +43,19 @@ export const webTest = webBase.extend<{target: string}, {collector: Collector}>( }, }); -/** Device targets: installs the app once per worker. Pass `{platforms: MOBILE}`: its fixtures name `device`. */ export const test = mobileBase.extend<{target: string}, {collector: Collector; installed: void}>({ collector, installed: [ async ({device}, use) => { const {app} = await device.installApp(); - // a killed native-init-failure run must not leave its bad export URL behind for later launches if (device.unstable_raw.session.includes('android')) execFileSync('adb', ['-s', device.unstable_raw.deviceId, 'shell', `rm -f ${ANDROID_EXPORT_URL_FILE}`]); - // Warm-up launch: on Android the first relaunch right after an install can fail with - // "remained foreground after close", and a test retry does not re-run this worker fixture. await device.openApp(app); await device.closeApp(); await use(); }, {scope: 'worker', auto: true}, ], - // ponytail: the target name is read off the agent-device session name (`e2e--`); swap for a runner API when e2e exposes one target: async ({device}, use) => { await use(device.unstable_raw.session.replace(/^e2e-/, '').replace(/-\d+$/, '')); }, @@ -78,7 +63,6 @@ export const test = mobileBase.extend<{target: string}, {collector: Collector; i type Fixtures = {app: App; screen: Screen; collector: Collector; target: string}; -/** Registers `body` on device targets (`test`, title as is) and on web (`webTest`, as `web › `: titles are unique). */ export function anyTarget(title: string, body: (f: Fixtures) => Promise<void>) { test(title, {platforms: MOBILE}, async ({app, screen, collector, target}) => body({app, screen, collector, target})); describe('web', {platforms: ['web']}, () => @@ -86,19 +70,13 @@ export function anyTarget(title: string, body: (f: Fixtures) => Promise<void>) { ); } -/** Steps the failure scenarios add around the tap-and-compare. */ export type ScenarioSteps = { - /** Replaces the cold start, e.g. to relaunch with launch arguments. */ launch?: () => Promise<void>; - /** After `collector.begin` (which clears refusals, F15). */ afterBegin?: () => void; - /** How long `scenario-done` may take after the tap. */ doneTimeout?: number; - /** After `scenario-done`, before the collector's output is read. */ afterDone?: () => Promise<void>; }; -/** Taps `scenario-<name>`, waits for `scenario-done`, compares what the collector got. */ export async function expectScenario( name: string, target: string, @@ -108,7 +86,6 @@ export async function expectScenario( const s = allScenarios().find(x => x.name === name); if (!s) throw new Error(`unknown scenario ${name}`); test.skip(!s.targets.includes(platformOf(target)) && !s.targets.includes(target as Target), `${name} does not run on ${target}`); - // cold start per scenario: no SDK state or ID counters carried over await (steps.launch ? steps.launch() : app.restart()); collector.begin(name, platformOf(target)); @@ -121,31 +98,23 @@ export async function expectScenario( } finally { actual = await collector.end(); } - // every app exports through the native core (bare: native-first init, Expo: JS-fallback init), so one expected - // file per scenario proves both init paths equivalent. - // VERIFY_E2E_DRAFT=1 writes a missing expected file and still fails (review it, then rerun) const r = compareToExpected(name, platformOf(target), actual, {draft: process.env.VERIFY_E2E_DRAFT === '1'}); if (!r.ok) throw new Error('\n' + r.report); } -/** Taps the test-mode `flush` button (a JS `forceFlush()`) for the `n`th time and waits until it resolved. */ export async function tapFlush(screen: Screen, n: number, timeout = 10_000) { await screen.getByTestId('flush').tap(); await expect(screen.getByTestId(`flush-done-${n}`)).toBeVisible({timeout}); } -/** Polls until `ok()` or the timeout; false on timeout. */ export async function until(ok: () => boolean, timeoutMs: number): Promise<boolean> { const end = Date.now() + timeoutMs; while (!ok() && Date.now() < end) await new Promise(r => setTimeout(r, 250)); return ok(); } -// The SDK's own lines: native (`RNOtel` tag / NSLog prefix) and JS (`[react-native-open-telemetry]`, ReactNativeJS). -// iOS: `log show` takes ~60 s per call on a CI runner, so lines are captured live by a `log stream` started in clearDeviceLog. const iosStreams = new Map<string, {lines: string[]}>(); -/** Device log lines containing `needle`, logged after the last clearDeviceLog (Android: logcat since the clear; iOS: the live stream). */ export function deviceLog(platform: 'android' | 'ios', deviceId: string, needle: string): string[] { const out = platform === 'android' @@ -154,7 +123,6 @@ export function deviceLog(platform: 'android' | 'ios', deviceId: string, needle: return out.split('\n').filter(l => l.includes(needle)); } -/** Starts a fresh log window for deviceLog (Android: every logcat buffer, events too). */ export async function clearDeviceLog(platform: 'android' | 'ios', deviceId: string): Promise<void> { if (platform === 'android') execFileSync('adb', ['-s', deviceId, 'logcat', '-b', 'all', '-c']); else { @@ -162,7 +130,6 @@ export async function clearDeviceLog(platform: 'android' | 'ios', deviceId: stri iosStreams.set(deviceId, state); const child = spawn( 'xcrun', - // --timeout: the stream ends on its own even when the worker dies without an 'exit' event (a killed run) ['simctl', 'spawn', deviceId, 'log', 'stream', '--timeout', '3m', '--style', 'compact', '--level', 'info', '--predicate', 'process == "OpenTelemetryExample" AND (eventMessage CONTAINS "RNOtel" OR eventMessage CONTAINS "[react-native-open-telemetry]")'], {stdio: ['ignore', 'pipe', 'ignore']}, @@ -172,6 +139,6 @@ export async function clearDeviceLog(platform: 'android' | 'ios', deviceId: stri child.unref(); (child.stdout as any).unref?.(); process.on('exit', () => child.kill()); - await new Promise(r => setTimeout(r, 3_000)); // let the stream attach before the tap + await new Promise(r => setTimeout(r, 3_000)); } } diff --git a/verify/e2e/native-init-failure.e2e.ts b/verify/e2e/native-init-failure.e2e.ts index a6b3626..98bcf34 100644 --- a/verify/e2e/native-init-failure.e2e.ts +++ b/verify/e2e/native-init-failure.e2e.ts @@ -3,16 +3,10 @@ import {expect} from 'e2e'; import {ANDROID_EXPORT_URL_FILE, clearDeviceLog, deviceLog, expectScenario, MOBILE, platformOf, test, until} from './harness'; const BAD_URL = 'not a url'; -// Android: Application.onCreate cannot see launch arguments, so the example reads this file instead (test mode only). -// The app creates the directory itself (getExternalFilesDir on every test-mode launch, e.g. the harness warm-up), -// and the harness's install fixture removes a file a killed run left behind. const ANDROID_FILE = ANDROID_EXPORT_URL_FILE; -// Native init failure (§4.4, §9.4): the example's native-first init gets an invalid export URL. The SDK reports it -// exactly once, the app keeps running on a no-op SDK, the no-op forceFlush() resolves (scenario-done), and nothing -// is exported (the expected file is empty). test('native-init-failure', {platforms: MOBILE}, async ({app, screen, collector, device, target}) => { - const platform = platformOf(target) as 'android' | 'ios'; // MOBILE only + const platform = platformOf(target) as 'android' | 'ios'; const {deviceId} = device.unstable_raw; const shell = (cmd: string) => execFileSync('adb', ['-s', deviceId, 'shell', cmd]); try { @@ -20,7 +14,7 @@ test('native-init-failure', {platforms: MOBILE}, async ({app, screen, collector, launch: async () => { await clearDeviceLog(platform, deviceId); if (platform === 'android') { - shell(`echo '${BAD_URL}' > ${ANDROID_FILE} && chmod 644 ${ANDROID_FILE}`); // the app's own dir; 644 so it may read a shell-owned file + shell(`echo '${BAD_URL}' > ${ANDROID_FILE} && chmod 644 ${ANDROID_FILE}`); await device.openApp('opentelemetry.example', {relaunch: true}); } else { await device.openApp('opentelemetry.example', {relaunch: true, launchArguments: [`--otel-export-url=${BAD_URL}`]}); @@ -29,7 +23,7 @@ test('native-init-failure', {platforms: MOBILE}, async ({app, screen, collector, }); const lines = () => deviceLog(platform, deviceId, 'telemetry is off'); await until(() => lines().length > 0, 10_000); - await new Promise(r => setTimeout(r, 2_000)); // a second report would be in by now + await new Promise(r => setTimeout(r, 2_000)); expect(lines()).toHaveLength(1); } finally { if (platform === 'android') shell(`rm -f ${ANDROID_FILE}`); diff --git a/verify/e2e/native-test-mode.e2e.ts b/verify/e2e/native-test-mode.e2e.ts index 356c447..d3c027a 100644 --- a/verify/e2e/native-test-mode.e2e.ts +++ b/verify/e2e/native-test-mode.e2e.ts @@ -3,5 +3,5 @@ import {MOBILE, test} from './harness'; test('native test mode reaches initialize', {platforms: MOBILE}, async ({app, screen}) => { await app.open(); - await expect(screen.getByTestId('native-test-mode')).toHaveText('native testMode=true', {timeout: 30_000}); // a CI simulator's first read can outlast the 5 s default + await expect(screen.getByTestId('native-test-mode')).toHaveText('native testMode=true', {timeout: 30_000}); }); diff --git a/verify/e2e/scenarios.e2e.ts b/verify/e2e/scenarios.e2e.ts index a6d6c9a..0c80a98 100644 --- a/verify/e2e/scenarios.e2e.ts +++ b/verify/e2e/scenarios.e2e.ts @@ -1,6 +1,5 @@ import {allScenarios, anyTarget, expectScenario} from './harness'; -/** Scenarios with their own e2e file (they need more than tap-and-compare). */ const OWN_FILE = new Set([ 'collector-down', 'native-init-failure', @@ -10,7 +9,6 @@ const OWN_FILE = new Set([ 'export-headers', ]); -// expectScenario skips targets a scenario does not list for (const s of allScenarios().filter(s => s.runners.includes('e2e') && !s.pending && !OWN_FILE.has(s.name))) { anyTarget(s.name, async ({app, screen, collector, target}) => { await expectScenario(s.name, target, {app, screen, collector}); diff --git a/verify/harness/collector.ts b/verify/harness/collector.ts index 1aae8ec..3db691e 100644 --- a/verify/harness/collector.ts +++ b/verify/harness/collector.ts @@ -10,7 +10,6 @@ export type Collector = { begin(scenario: string, platform: string): void; end(): Promise<OtlpJson>; refuse(status: number, count: number): void; - /** Export requests accepted since `begin`. */ received(): number; close(): Promise<void>; }; @@ -41,7 +40,6 @@ export async function startCollector( res.end(payload === undefined ? undefined : JSON.stringify(payload)); }; try { - // opentelemetry-swift gzips by default; the raw/ files keep the decoded body if (req.headers['content-encoding'] === 'gzip') body = zlib.gunzipSync(body); const route = `${req.method} ${req.url?.split('?')[0]}`; if (req.method === 'OPTIONS') return send(204); diff --git a/verify/harness/normalize.ts b/verify/harness/normalize.ts index a71e1af..769b188 100644 --- a/verify/harness/normalize.ts +++ b/verify/harness/normalize.ts @@ -1,6 +1,5 @@ import type {OtlpJson} from './otlpJson'; -// key-order independent: attributes sorted by key before comparing const canon = (x: any) => JSON.stringify( x && x.attributes @@ -41,7 +40,6 @@ function sortSpan(s: any) { return o; } -/** Merge equal resources/scopes, sort for determinism. Values are never changed. */ export function normalize(requests: OtlpJson[]): OtlpJson { const resources: any[] = []; for (const req of requests) diff --git a/verify/harness/otlpJson.ts b/verify/harness/otlpJson.ts index 49f661d..40688bd 100644 --- a/verify/harness/otlpJson.ts +++ b/verify/harness/otlpJson.ts @@ -17,7 +17,6 @@ export const decodeRequest = (buf: Uint8Array): ExportTraceServiceRequest => const ID_KEYS = ['traceId', 'spanId', 'parentSpanId']; -// Hex id strings (OTLP/JSON) -> bytes, so fromObject does not base64-decode them. function idsToBytes(v: any): any { if (Array.isArray(v)) return v.map(idsToBytes); if (v && typeof v === 'object' && !(v instanceof Uint8Array)) { @@ -35,7 +34,6 @@ function idsToBytes(v: any): any { function format(v: any, key?: string): any { if (Array.isArray(v)) return v.map(x => format(x)); if (v instanceof Uint8Array) { - // ids are hex, any other bytes (AnyValue.bytesValue) are base64 per proto3 JSON if (key && ID_KEYS.includes(key)) return v.length ? Buffer.from(v).toString('hex') : undefined; return Buffer.from(v).toString('base64'); @@ -53,11 +51,6 @@ function format(v: any, key?: string): any { return v; } -/** - * Proto3 JSON: hex ids, int64 as decimal strings, enums as numbers, defaults omitted, - * NaN/Infinity as strings. Accepts protobuf-decoded objects or OTLP/JSON (hex ids). - * -0 stays -0 in the returned object; JSON.stringify writes it as 0. - */ export function toOtlpJson(req: ExportTraceServiceRequest): OtlpJson { const obj = Req.toObject(Req.fromObject(idsToBytes(req)), { longs: String, diff --git a/verify/jest/handoff.test.ts b/verify/jest/handoff.test.ts index d22febc..b6bdd4c 100644 --- a/verify/jest/handoff.test.ts +++ b/verify/jest/handoff.test.ts @@ -33,7 +33,6 @@ describe('NativeHandOffProcessor', () => { const calls: SeamSpan[][] = []; const native = {handOff: (s: SeamSpan[]) => void calls.push(s)} as unknown as Otel; const provider = new TracerProvider({ - // recorded (so processors see it) but traceFlags stay 0 sampler: {shouldSample: () => ({decision: SamplingDecision.RECORD}), toString: () => 'record-only'}, spanProcessors: [new NativeHandOffProcessor(native)], }); diff --git a/verify/jest/jest.scenarios.config.js b/verify/jest/jest.scenarios.config.js index 7758500..e2f07c8 100644 --- a/verify/jest/jest.scenarios.config.js +++ b/verify/jest/jest.scenarios.config.js @@ -1,4 +1,3 @@ -// Needs NODE_OPTIONS=--experimental-vm-modules (OTLP node transport uses dynamic import()): run via `bun run test`. module.exports = { displayName: 'scenarios', rootDir: '../..', diff --git a/verify/run.ts b/verify/run.ts index 598e11b..3a422c7 100644 --- a/verify/run.ts +++ b/verify/run.ts @@ -26,7 +26,6 @@ const ctx: Ctx = { if (ctx.update) process.env.VERIFY_UPDATE = '1'; -// generate verify/scenarios/index.ts from the folder const sc = readdirSync(join(import.meta.dirname, 'scenarios')).filter(f => f.endsWith('.ts') && f !== 'index.ts').sort(); const id = (f: string) => f.slice(0, -3).replace(/-(.)/g, (_, c) => c.toUpperCase()); const indexFile = join(import.meta.dirname, 'scenarios', 'index.ts'); diff --git a/verify/scenarios/async-generator.ts b/verify/scenarios/async-generator.ts index d7d59a8..9403076 100644 --- a/verify/scenarios/async-generator.ts +++ b/verify/scenarios/async-generator.ts @@ -1,6 +1,5 @@ import {scenario} from '../harness/scenario'; -/** Async generator bodies and the `for await` loop consuming them stay children of the active span (§6.1). */ export default scenario( 'async-generator', async ({tracer, at}) => { diff --git a/verify/scenarios/background-flush.ts b/verify/scenarios/background-flush.ts index c52646d..3acde9e 100644 --- a/verify/scenarios/background-flush.ts +++ b/verify/scenarios/background-flush.ts @@ -1,9 +1,5 @@ import {scenario} from '../harness/scenario'; -/** - * Background flush (§9.4): run this and background the app immediately. The span arrives without - * `forceFlush()`, exactly once; no ANR on Android. - */ export default scenario( 'background-flush', async ({tracer, at}) => { diff --git a/verify/scenarios/batching-shared-queue.ts b/verify/scenarios/batching-shared-queue.ts index 097fb46..24f9ee8 100644 --- a/verify/scenarios/batching-shared-queue.ts +++ b/verify/scenarios/batching-shared-queue.ts @@ -1,9 +1,5 @@ import {scenario} from '../harness/scenario'; -/** - * Documented exception (§6.2): a shared queue flushed once runs everyone's work in the context of the first - * enqueuer. `h2.work` is recorded under `h1` (the spike's `h_batching`); this file pins that wrong parent. - */ export default scenario( 'batching-shared-queue', async ({tracer, at}) => { diff --git a/verify/scenarios/captured-then.ts b/verify/scenarios/captured-then.ts index 74aa18e..b5bf8f7 100644 --- a/verify/scenarios/captured-then.ts +++ b/verify/scenarios/captured-then.ts @@ -1,10 +1,5 @@ import {scenario} from '../harness/scenario'; -/** - * Documented exception (§6.1 install order): code holding the `then` captured before the patch ran - * loses the parent and starts a new root; the patched `then` keeps it. - * The pre-patch `then` is read from the patch marker (the patch stores the originals there). - */ export default scenario( 'captured-then', async ({tracer, at}) => { diff --git a/verify/scenarios/collector-down.ts b/verify/scenarios/collector-down.ts index 34e54a4..fc2c3d1 100644 --- a/verify/scenarios/collector-down.ts +++ b/verify/scenarios/collector-down.ts @@ -1,10 +1,5 @@ import {scenario} from '../harness/scenario'; -/** - * Collector down (§9.4 failure scenarios): the e2e test makes the collector `refuse(503, 3)`. - * The app does not block or crash (`scenario-done` within 2 s) and, once the collector accepts again, - * the span arrives exactly once. - */ export default scenario( 'collector-down', async ({tracer, at}) => { diff --git a/verify/scenarios/concurrent-interleaved.ts b/verify/scenarios/concurrent-interleaved.ts index 92a4624..53a63ee 100644 --- a/verify/scenarios/concurrent-interleaved.ts +++ b/verify/scenarios/concurrent-interleaved.ts @@ -1,7 +1,5 @@ import {scenario} from '../harness/scenario'; -/** Two async jobs interleaving on the same queues keep their own parents; neither leaks into the other (§6.1, §6.2); - * work after the join is a new root. */ export default scenario( 'concurrent-interleaved', async ({tracer, at}) => { @@ -15,7 +13,6 @@ export default scenario( span.end(at(t + 30)); }); await Promise.all([job('a', 0), job('b', 1)]); - // back at ROOT after the join: guards the ROOT fast path (§6.1) tracer.startSpan('after.all', {startTime: at(40)}).end(at(41)); }, ); diff --git a/verify/scenarios/cross-js-to-native.ts b/verify/scenarios/cross-js-to-native.ts index ddaba99..81c744d 100644 --- a/verify/scenarios/cross-js-to-native.ts +++ b/verify/scenarios/cross-js-to-native.ts @@ -1,11 +1,5 @@ import {scenario} from '../harness/scenario'; -/** - * A native span started from JS is a child of the active JS span. - * Steps: JS span `js.parent` active → `ctx.native.doWork(traceparent, start, end)` starts and ends native - * `native.work` with `contextFrom(traceparent)` as parent. Proof: one trace, `native.work` (a `0b…` id) - * has `js.parent` as parent. - */ export default scenario( 'cross-js-to-native', async ({tracer, at, native}) => { diff --git a/verify/scenarios/cross-native-to-js.ts b/verify/scenarios/cross-native-to-js.ts index 2861045..d4bfe88 100644 --- a/verify/scenarios/cross-native-to-js.ts +++ b/verify/scenarios/cross-native-to-js.ts @@ -1,12 +1,6 @@ import {context, trace} from '@opentelemetry/api'; import {scenario} from '../harness/scenario'; -/** - * A JS span started under a native span's context is its child. - * Steps: at ROOT, `ctx.native.doWork('', …)` starts and ends root `native.work` and returns its traceparent → - * JS starts `js.after_native` under `trace.wrapSpanContext(<that context>)` (non-remote, spec §4.3). - * Proof: one trace, `js.after_native` has `native.work` as parent. - */ export default scenario( 'cross-native-to-js', async ({tracer, at, native}) => { diff --git a/verify/scenarios/error-in-callback.ts b/verify/scenarios/error-in-callback.ts index 5067199..d86a07e 100644 --- a/verify/scenarios/error-in-callback.ts +++ b/verify/scenarios/error-in-callback.ts @@ -1,9 +1,5 @@ import {scenario} from '../harness/scenario'; -/** - * A callback that throws still restores the previous context (wrappers restore in `finally`, §6.1): - * its `.catch` stays a child, and the next job registered at ROOT runs at ROOT. - */ export default scenario( 'error-in-callback', async ({tracer, at}) => { @@ -14,7 +10,6 @@ export default scenario( }); return {parent, caught: failed.catch(() => tracer.startSpan('caught', {startTime: at(20)}).end(at(21)))}; }); - // registered at ROOT, runs right after the throwing callback const next = Promise.resolve().then(() => tracer.startSpan('root.next', {startTime: at(30)}).end(at(31))); await Promise.all([caught, next]); parent.end(at(40)); diff --git a/verify/scenarios/event-emitter-listener.ts b/verify/scenarios/event-emitter-listener.ts index e23f2b3..6d74079 100644 --- a/verify/scenarios/event-emitter-listener.ts +++ b/verify/scenarios/event-emitter-listener.ts @@ -1,10 +1,8 @@ import {scenario} from '../harness/scenario'; -/** A span started in a `DeviceEventEmitter` listener is a child of the caller's span when emitted synchronously from JS (Hermes). */ export default scenario( 'event-emitter-listener', async ({tracer, at}) => { - // lazy: the module list is also loaded by Jest, which has no react-native runtime const {DeviceEventEmitter} = require('react-native') as typeof import('react-native'); const sub = DeviceEventEmitter.addListener('verify.event', () => tracer.startSpan('listener', {startTime: at(10)}).end(at(11)), diff --git a/verify/scenarios/export-headers.ts b/verify/scenarios/export-headers.ts index f2da091..7780762 100644 --- a/verify/scenarios/export-headers.ts +++ b/verify/scenarios/export-headers.ts @@ -1,9 +1,5 @@ import {scenario} from '../harness/scenario'; -/** - * Configured export headers are sent on every export request: the collector's `<n>.headers.json` for this - * scenario contains `x-api-key: test` (every example app's init sets it; verify/e2e/export-headers.e2e.ts asserts it). - */ export default scenario( 'export-headers', async ({tracer, at}) => { diff --git a/verify/scenarios/fast-refresh-idempotent.ts b/verify/scenarios/fast-refresh-idempotent.ts index 8e4d433..3ff485a 100644 --- a/verify/scenarios/fast-refresh-idempotent.ts +++ b/verify/scenarios/fast-refresh-idempotent.ts @@ -1,12 +1,4 @@ import {scenario} from '../harness/scenario'; import nestAfterAwait from './nest-after-await'; -/** - * Fast refresh does not stack the context patch (§6.1.3). Stacked wrappers would still give the same - * parents, so the output alone cannot fail; the proof is: - * (a) `Promise.prototype.then` and `setTimeout` are the same functions before and after two fast refreshes - * (identity read via the `Symbol.for('com.callstack.otel.patched')` marker), and - * (b) the refresh edit re-evaluates the patch module (otherwise (a) holds trivially). - * The `nest-after-await` body then still gives its usual output (one `child` under `parent`). - */ export default scenario('fast-refresh-idempotent', nestAfterAwait.run, {runners: ['e2e'], targets: ['android', 'ios']}); diff --git a/verify/scenarios/flush-after-reload.ts b/verify/scenarios/flush-after-reload.ts index 0ff7f09..8583a18 100644 --- a/verify/scenarios/flush-after-reload.ts +++ b/verify/scenarios/flush-after-reload.ts @@ -1,9 +1,5 @@ import {scenario} from '../harness/scenario'; -/** - * `flush()` across a JS reload (§9.4): run this, reload JS, call `forceFlush()`. It resolves within - * 5 s without blocking the main thread, and the span arrives exactly once. - */ export default scenario( 'flush-after-reload', async ({tracer, at}) => { diff --git a/verify/scenarios/interval-new-root.ts b/verify/scenarios/interval-new-root.ts index 44e6ea8..a20363d 100644 --- a/verify/scenarios/interval-new-root.ts +++ b/verify/scenarios/interval-new-root.ts @@ -1,9 +1,5 @@ import {scenario} from '../harness/scenario'; -/** - * Documented exception (§6.2): `setInterval` ticks run in ROOT_CONTEXT, so a poller started inside a tap - * starts a new root per tick instead of attaching to the tap. Work after `await` in the tap stays its child. - */ export default scenario( 'interval-new-root', async ({tracer, at}) => { diff --git a/verify/scenarios/native-init-failure.ts b/verify/scenarios/native-init-failure.ts index ddef766..a854119 100644 --- a/verify/scenarios/native-init-failure.ts +++ b/verify/scenarios/native-init-failure.ts @@ -1,14 +1,9 @@ import {scenario} from '../harness/scenario'; -/** - * Native init failure (§4, §9.4): a build whose `exportUrl` is `not a url`. The SDK logs exactly one - * error, the app keeps running on a no-op SDK, `forceFlush()` resolves, and no span is exported. - */ export default scenario( 'native-init-failure', async ({tracer, at}) => { tracer.startSpan('dropped', {startTime: at(0)}).end(at(10)); }, - // bare only: the bad URL goes to the bare example's native init; the Expo app has none (it inits from JS) {runners: ['e2e'], targets: ['android-bare', 'ios-bare']}, ); diff --git a/verify/scenarios/nest-after-await.ts b/verify/scenarios/nest-after-await.ts index c05939b..e9a47dd 100644 --- a/verify/scenarios/nest-after-await.ts +++ b/verify/scenarios/nest-after-await.ts @@ -1,6 +1,5 @@ import {scenario} from '../harness/scenario'; -/** A span started after `await` is a child of the span active before it (§6.1). */ export default scenario( 'nest-after-await', async ({tracer, at}) => { diff --git a/verify/scenarios/nest-promise-all-race.ts b/verify/scenarios/nest-promise-all-race.ts index 89d52e1..b573718 100644 --- a/verify/scenarios/nest-promise-all-race.ts +++ b/verify/scenarios/nest-promise-all-race.ts @@ -1,6 +1,5 @@ import {scenario} from '../harness/scenario'; -/** Branches of Promise.all and Promise.race, and the code after them, stay children of the active span (§6.1). */ export default scenario( 'nest-promise-all-race', async ({tracer, at}) => { @@ -10,7 +9,6 @@ export default scenario( }; await tracer.startActiveSpan('root', {startTime: at(0)}, async root => { await Promise.all([step('all.a', 10), step('all.b', 20)]); - // race.b takes as many ticks as race.a, so it ends before `after` and before the export await Promise.race([step('race.a', 30), step('race.b', 40)]); tracer.startSpan('after', {startTime: at(50)}).end(at(51)); root.end(at(60)); diff --git a/verify/scenarios/nest-raf.ts b/verify/scenarios/nest-raf.ts index e48d67c..5892713 100644 --- a/verify/scenarios/nest-raf.ts +++ b/verify/scenarios/nest-raf.ts @@ -1,6 +1,5 @@ import {scenario} from '../harness/scenario'; -/** A `requestAnimationFrame` callback runs in the context it was scheduled in (§6.1). Node has no rAF: e2e only. */ export default scenario( 'nest-raf', async ({tracer, at}) => { diff --git a/verify/scenarios/nest-timers-microtasks.ts b/verify/scenarios/nest-timers-microtasks.ts index 977f4fc..4fa0e3c 100644 --- a/verify/scenarios/nest-timers-microtasks.ts +++ b/verify/scenarios/nest-timers-microtasks.ts @@ -1,9 +1,5 @@ import {scenario} from '../harness/scenario'; -/** - * Callbacks of setTimeout, setImmediate and queueMicrotask run in the context they were scheduled in (§6.1). - * requestAnimationFrame is patched too but missing in Node, so it is left out to keep one shape for every runner. - */ export default scenario( 'nest-timers-microtasks', async ({tracer, at}) => { @@ -16,13 +12,10 @@ export default scenario( }), ); await inCallback(cb => setTimeout(cb, 0), 'timeout', 10); - // browsers have no setImmediate: there the step is one more setTimeout, so every runner keeps one shape await inCallback(cb => (typeof setImmediate === 'function' ? setImmediate(cb) : setTimeout(cb, 0)), 'immediate', 20); await inCallback(cb => queueMicrotask(cb), 'microtask', 30); - // scheduled from inside a callback: the context is carried twice await inCallback(cb => setTimeout(() => queueMicrotask(cb), 0), 'timeout.microtask', 40); root.end(at(50)); - // a callback that runs after its parent ended is still its child (§6.2) await inCallback(cb => setTimeout(cb, 0), 'after.end', 60); }); }, diff --git a/verify/scenarios/never-settling-promise.ts b/verify/scenarios/never-settling-promise.ts index 3b6f678..75db5cd 100644 --- a/verify/scenarios/never-settling-promise.ts +++ b/verify/scenarios/never-settling-promise.ts @@ -1,6 +1,5 @@ import {scenario} from '../harness/scenario'; -/** A promise that never settles inside a span does not leak that span into later work (§9.2). */ export default scenario( 'never-settling-promise', async ({tracer, at}) => { diff --git a/verify/scenarios/root-no-leak.ts b/verify/scenarios/root-no-leak.ts index ede92db..a9259e9 100644 --- a/verify/scenarios/root-no-leak.ts +++ b/verify/scenarios/root-no-leak.ts @@ -1,9 +1,5 @@ import {scenario} from '../harness/scenario'; -/** - * Once a span's async work is done, nothing after it inherits that span: work at ROOT starts new roots, - * including callbacks registered at ROOT that take the unwrapped fast path (§6.1 ROOT fast path). - */ export default scenario( 'root-no-leak', async ({tracer, at}) => { diff --git a/verify/static/packContents.ts b/verify/static/packContents.ts index d16d8bb..907df22 100644 --- a/verify/static/packContents.ts +++ b/verify/static/packContents.ts @@ -1,6 +1,5 @@ export const REQUIRED = ['package.json', 'lib/', 'src/', 'nitrogen/', 'metro/', 'android/', 'ios/', 'ReactNativeOpenTelemetry.podspec', 'ReactNativeOpenTelemetryCore.podspec', 'app.plugin.js', 'react-native.config.js']; -/** Returns the required paths missing from the `npm pack --dry-run --json` file list. */ export function packContents(list: string[], required: string[] = REQUIRED): string[] { return required.filter(r => r.endsWith('/') ? !list.some(p => p.startsWith(r)) : !list.includes(r),