diff --git a/android/build.gradle b/android/build.gradle index ede1486..ecd4cab 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -18,6 +18,8 @@ def getExtOrIntegerDefault(name) { // Test mode is a build flag, never API: -PotelTestMode=true (or otelTestMode=true in the app's gradle.properties). def otelTestMode = (findProperty("otelTestMode") ?: "false").toString() == "true" +// telemetry.distro.version = the npm package version +def otelDistroVersion = new groovy.json.JsonSlurper().parse(file("../package.json")).version android { namespace "com.margelo.nitro.callstack.otel" @@ -29,6 +31,9 @@ android { minSdkVersion getExtOrIntegerDefault("minSdkVersion") targetSdkVersion getExtOrIntegerDefault("targetSdkVersion") buildConfigField "boolean", "OTEL_TEST_MODE", otelTestMode.toString() + buildConfigField "String", "OTEL_DISTRO_VERSION", "\"${otelDistroVersion}\"" + // apps that minify (Expo's release default) need these + consumerProguardFiles "consumer-rules.pro" externalNativeBuild { cmake { @@ -47,6 +52,11 @@ android { cmake { path "CMakeLists.txt" } } + // the pure Kotlin core (also compiled and tested on the JVM by android/core-jvm) + sourceSets { + main { java.srcDirs += "src/core/kotlin" } + } + packagingOptions { excludes = [ "META-INF", @@ -95,8 +105,12 @@ repositories { dependencies { implementation "com.facebook.react:react-android" implementation project(":react-native-nitro-modules") + // ProcessLifecycleOwner: background flush on ON_STOP (same version React Native already resolves) + implementation "androidx.lifecycle:lifecycle-process:2.6.2" - implementation platform("io.opentelemetry:opentelemetry-bom:1.68.0") + // RNOtel's public signatures expose Tracer, Span and Context: the API is part of ours + api platform("io.opentelemetry:opentelemetry-bom:1.68.0") + api "io.opentelemetry:opentelemetry-api" implementation "io.opentelemetry:opentelemetry-sdk" // The OkHttp sender runs on React Native's own OkHttp (every okhttp3 member the 1.68 sender uses exists in 4.9.2); // excluding it keeps otel-java from pulling the app up to OkHttp 5. diff --git a/android/consumer-rules.pro b/android/consumer-rules.pro new file mode 100644 index 0000000..6f1650f --- /dev/null +++ b/android/consumer-rules.pro @@ -0,0 +1,11 @@ +# Guarded by the minified Expo release e2e (Task 28): recheck these rules on every otel-java bump. +# otel-java references optional, compile-only classes it never loads at runtime here (no autoconfigure, no incubator, +# annotations only); R8 in a minifying app fails on them as missing. +-dontwarn com.google.auto.value.** +-dontwarn com.google.errorprone.annotations.** +-dontwarn io.opentelemetry.api.incubator.** +-dontwarn io.opentelemetry.sdk.autoconfigure.spi.** + +# otel-java's ResourceMarshaler reaches Resource/ResourceBuilder entity methods by reflection (EntityUtil) on every +# export; renamed or merged, the export throws and nothing is sent. +-keep class io.opentelemetry.sdk.resources.** { *; } diff --git a/android/core-jvm/build.gradle.kts b/android/core-jvm/build.gradle.kts new file mode 100644 index 0000000..97f267c --- /dev/null +++ b/android/core-jvm/build.gradle.kts @@ -0,0 +1,25 @@ +plugins { + kotlin("jvm") version "2.1.21" +} + +kotlin { jvmToolchain(17) } + +sourceSets.main { kotlin.srcDir("../src/core/kotlin") } + +dependencies { + implementation(platform("io.opentelemetry:opentelemetry-bom:1.68.0")) + implementation("io.opentelemetry:opentelemetry-sdk") + // No OkHttp exclusion here: the JVM tests run otel-java's own OkHttp 5; devices run React Native's 4.9.2. + implementation("io.opentelemetry:opentelemetry-exporter-otlp") + testImplementation(kotlin("test")) + testImplementation("com.google.code.gson:gson:2.11.0") +} + +tasks.test { + useJUnitPlatform() + // fast-jvm passes the live collector URL; the export test fails without it. + environment("VERIFY_COLLECTOR", System.getenv("VERIFY_COLLECTOR") ?: "") + environment("VERIFY_FIXTURES", file("../../verify/fixtures").absolutePath) + outputs.upToDateWhen { false } + testLogging { events("passed", "failed", "skipped"); exceptionFormat = org.gradle.api.tasks.testing.logging.TestExceptionFormat.FULL } +} diff --git a/android/core-jvm/gradle/wrapper/gradle-wrapper.jar b/android/core-jvm/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..d997cfc Binary files /dev/null and b/android/core-jvm/gradle/wrapper/gradle-wrapper.jar differ diff --git a/android/core-jvm/gradle/wrapper/gradle-wrapper.properties b/android/core-jvm/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..c61a118 --- /dev/null +++ b/android/core-jvm/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/android/core-jvm/gradlew b/android/core-jvm/gradlew new file mode 100755 index 0000000..739907d --- /dev/null +++ b/android/core-jvm/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/2d6327017519d23b96af35865dc997fcb544fb40/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/android/core-jvm/settings.gradle.kts b/android/core-jvm/settings.gradle.kts new file mode 100644 index 0000000..ef0b79b --- /dev/null +++ b/android/core-jvm/settings.gradle.kts @@ -0,0 +1,6 @@ +// JVM-only project over android/src/core: the pure Kotlin core, tested without Android or Nitro. +rootProject.name = "core-jvm" + +dependencyResolutionManagement { + repositories { mavenCentral() } +} diff --git a/android/core-jvm/src/test/kotlin/AttributesTest.kt b/android/core-jvm/src/test/kotlin/AttributesTest.kt new file mode 100644 index 0000000..afc174f --- /dev/null +++ b/android/core-jvm/src/test/kotlin/AttributesTest.kt @@ -0,0 +1,32 @@ +import com.callstack.otel.core.AttrValue +import com.callstack.otel.core.SeamAttribute +import com.callstack.otel.core.attributesOf +import io.opentelemetry.api.common.AttributeKey.doubleArrayKey +import io.opentelemetry.api.common.AttributeKey.doubleKey +import io.opentelemetry.api.common.AttributeKey.longArrayKey +import io.opentelemetry.api.common.AttributeKey.longKey +import kotlin.test.Test +import kotlin.test.assertEquals + +class AttributesTest { + private fun num(v: Double) = attributesOf(listOf(SeamAttribute("k", AttrValue.Num(v)))) + + @Test fun wholeIsLong() = assertEquals(1L, num(1.0).get(longKey("k"))) + @Test fun fractionIsDouble() = assertEquals(1.5, num(1.5).get(doubleKey("k"))) + @Test fun bigWholeIsLong() = assertEquals(9007199254740994L, num(9.007199254740994E15).get(longKey("k"))) + @Test fun nanIsDouble() = assertEquals(Double.NaN, num(Double.NaN).get(doubleKey("k"))) + @Test fun infIsDouble() = assertEquals(Double.NEGATIVE_INFINITY, num(Double.NEGATIVE_INFINITY).get(doubleKey("k"))) + // C28: Number.isInteger(-0) is true, so -0 is intValue 0 (the reviewed odd-attributes contract) + @Test fun negZeroIsLong() = assertEquals(0L, num(-0.0).get(longKey("k"))) + @Test fun beyondLongIsDouble() = assertEquals(1e19, num(1e19).get(doubleKey("k"))) + + @Test fun wholeArrayIsLongArray() { + val a = attributesOf(listOf(SeamAttribute("k", AttrValue.Nums(listOf(1.0, 2.0))))) + assertEquals(listOf(1L, 2L), a.get(longArrayKey("k"))) + } + + @Test fun mixedArrayIsDoubleArray() { + val a = attributesOf(listOf(SeamAttribute("k", AttrValue.Nums(listOf(1.0, 2.5))))) + assertEquals(listOf(1.0, 2.5), a.get(doubleArrayKey("k"))) + } +} diff --git a/android/core-jvm/src/test/kotlin/EndpointTest.kt b/android/core-jvm/src/test/kotlin/EndpointTest.kt new file mode 100644 index 0000000..a492da9 --- /dev/null +++ b/android/core-jvm/src/test/kotlin/EndpointTest.kt @@ -0,0 +1,15 @@ +import com.callstack.otel.core.validateExportUrl +import kotlin.test.Test +import kotlin.test.assertNotNull +import kotlin.test.assertNull + +class EndpointTest { + @Test fun acceptsUnderscoreHostsLikeIosAndWeb() { + for (u in listOf("http://otel_collector:4318", "http://otel_collector", "https://user:pw@otel_collector:4318/x")) { + assertNull(validateExportUrl(u), u) + } + for (u in listOf("not a url", "ftp://h:21", "http://", "http://:4318", "http://user@:4318")) { + assertNotNull(validateExportUrl(u), u) + } + } +} diff --git a/android/core-jvm/src/test/kotlin/FixtureExportTest.kt b/android/core-jvm/src/test/kotlin/FixtureExportTest.kt new file mode 100644 index 0000000..39eca47 --- /dev/null +++ b/android/core-jvm/src/test/kotlin/FixtureExportTest.kt @@ -0,0 +1,37 @@ +import com.callstack.otel.core.OtelCore +import java.io.File +import java.net.URI +import java.net.http.HttpClient +import java.net.http.HttpRequest +import java.net.http.HttpResponse +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +/** Every seam fixture through the core into the live collector; fast-jvm compares the `android` artifacts in Node. */ +class FixtureExportTest { + private val collector = System.getenv("VERIFY_COLLECTOR").orEmpty() + private val http = HttpClient.newBuilder().version(HttpClient.Version.HTTP_1_1).build() // Node http ignores h2c upgrades + + private fun control(path: String, body: String = "{}") { + val req = HttpRequest.newBuilder(URI("$collector/_verify/$path")) + .POST(HttpRequest.BodyPublishers.ofString(body)).timeout(java.time.Duration.ofSeconds(30)).header("content-type", "application/json").build() + val res = http.send(req, HttpResponse.BodyHandlers.ofString()) + assertEquals(200, res.statusCode(), "collector $path: ${res.body()}") + } + + @Test fun everyFixtureExports() { + assertTrue(collector.isNotEmpty(), "VERIFY_COLLECTOR is not set: run through `bun verify fast-jvm`") + val fixtures = File(System.getenv("VERIFY_FIXTURES")).listFiles { f -> f.name.endsWith(".handoff.json") }!!.sorted() + assertTrue(fixtures.isNotEmpty()) + for (f in fixtures) { + val name = f.name.removeSuffix(".handoff.json") + val (config, spans) = FixtureJson.parse(f.readText(), "$collector/v1/traces") + control("begin", """{"scenario":"$name","platform":"android"}""") + val core = OtelCore(config, testMode = true) + core.handOff(spans) + assertTrue(core.flush(10_000), "$name: flush timed out") + control("end") + } + } +} diff --git a/android/core-jvm/src/test/kotlin/FixtureJson.kt b/android/core-jvm/src/test/kotlin/FixtureJson.kt new file mode 100644 index 0000000..edc492f --- /dev/null +++ b/android/core-jvm/src/test/kotlin/FixtureJson.kt @@ -0,0 +1,81 @@ +import com.callstack.otel.core.AttrValue +import com.callstack.otel.core.CoreConfig +import com.callstack.otel.core.HrTime +import com.callstack.otel.core.SeamAttribute +import com.callstack.otel.core.SeamEvent +import com.callstack.otel.core.SeamLink +import com.callstack.otel.core.SeamScope +import com.callstack.otel.core.SeamSpan +import com.callstack.otel.core.SeamSpanContext +import com.callstack.otel.core.SeamStatus +import com.google.gson.JsonElement +import com.google.gson.JsonObject +import com.google.gson.JsonParser + +/** Test reader for verify/fixtures/.handoff.json; NaN, ±Infinity and -0 arrive as {"$num": ""}. */ +object FixtureJson { + fun parse(json: String, exportUrl: String): Pair> { + val root = JsonParser.parseString(json).asJsonObject + val c = root["config"].asJsonObject + val config = CoreConfig( + serviceName = c["serviceName"].asString, + serviceVersion = c.str("serviceVersion"), + resourceAttributes = attrs(c["resourceAttributes"]), + exportUrl = c["exportUrl"].asString.replace("", exportUrl), + exportHeaders = attrs(c["exportHeaders"]).associate { it.key to (it.value as AttrValue.Str).value }, + ) + return config to root["spans"].asJsonArray.map { span(it.asJsonObject) } + } + + private fun JsonObject.str(k: String) = get(k)?.takeUnless { it.isJsonNull }?.asString + + private fun num(e: JsonElement): Double = + if (e.isJsonObject) e.asJsonObject["\$num"].asString.let { if (it == "-0") -0.0 else it.toDouble() } else e.asDouble + + private fun time(e: JsonElement) = HrTime.of(e.asJsonArray.map(::num).toDoubleArray()) + + private fun value(e: JsonElement): AttrValue { + if (e.isJsonArray) { + val a = e.asJsonArray.toList() + val first = a.firstOrNull() ?: return AttrValue.Bools(emptyList()) + return when { + first.isJsonPrimitive && first.asJsonPrimitive.isString -> AttrValue.Strs(a.map { it.asString }) + first.isJsonPrimitive && first.asJsonPrimitive.isBoolean -> AttrValue.Bools(a.map { it.asBoolean }) + else -> AttrValue.Nums(a.map(::num)) + } + } + if (e.isJsonPrimitive && e.asJsonPrimitive.isString) return AttrValue.Str(e.asString) + if (e.isJsonPrimitive && e.asJsonPrimitive.isBoolean) return AttrValue.Bool(e.asBoolean) + return AttrValue.Num(num(e)) + } + + private fun attrs(e: JsonElement) = + e.asJsonArray.map { it.asJsonObject.let { a -> SeamAttribute(a["key"].asString, value(a["value"])) } } + + private fun ctx(o: JsonObject) = + SeamSpanContext(o["traceId"].asString, o["spanId"].asString, o["traceFlags"].asInt, o.str("traceState")) + + private fun span(o: JsonObject): SeamSpan { + val scope = o["scope"].asJsonObject + val status = o["status"].asJsonObject + return SeamSpan( + context = ctx(o["context"].asJsonObject), + parentSpanId = o.str("parentSpanId"), + name = o["name"].asString, + kind = o["kind"].asInt, + start = time(o["start"]), + end = time(o["end"]), + attributes = attrs(o["attributes"]), + events = o["events"].asJsonArray.map { + val ev = it.asJsonObject + SeamEvent(ev["name"].asString, time(ev["time"]), attrs(ev["attributes"])) + }, + links = o["links"].asJsonArray.map { + val l = it.asJsonObject + SeamLink(ctx(l["context"].asJsonObject), attrs(l["attributes"])) + }, + status = SeamStatus(status["code"].asInt, status.str("message")), + scope = SeamScope(scope["name"].asString, scope.str("version"), scope.str("schemaUrl"), attrs(scope["attributes"])), + ) + } +} diff --git a/android/core-jvm/src/test/kotlin/InitTest.kt b/android/core-jvm/src/test/kotlin/InitTest.kt new file mode 100644 index 0000000..472c557 --- /dev/null +++ b/android/core-jvm/src/test/kotlin/InitTest.kt @@ -0,0 +1,71 @@ +import com.callstack.otel.core.AttrValue +import com.callstack.otel.core.CoreConfig +import com.callstack.otel.core.OtelCore +import com.callstack.otel.core.SeamAttribute +import io.opentelemetry.api.common.AttributeKey +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNotNull +import kotlin.test.assertNull +import kotlin.test.assertSame +import kotlin.test.assertTrue + +class InitTest { + private val ok = CoreConfig("first", "1.0", emptyList(), "http://127.0.0.1:1", mapOf("x-api-key" to "test")) + @BeforeTest @AfterTest fun reset() = OtelCore.resetForTest() + + @Test fun initializeTwiceKeepsTheFirstConfig() { + val a = OtelCore.initialize(ok, testMode = true) + assertNull(a.error); assertFalse(a.alreadyInitialized) + val core = OtelCore.instance + val b = OtelCore.initialize(ok.copy(serviceName = "second"), testMode = true) + assertTrue(b.alreadyInitialized); assertNull(b.error) + assertSame(core, OtelCore.instance) + assertEquals("first", core!!.resource.getAttribute(AttributeKey.stringKey("service.name"))) + } + + @Test fun invalidUrlReturnsAnErrorAndNeverThrows() { + for (u in listOf("not a url", "ftp://h", "http://", "", "http:///x")) { + OtelCore.resetForTest() + val r = OtelCore.initialize(ok.copy(exportUrl = u), testMode = true) + assertNotNull(r.error, u); assertNull(OtelCore.instance) + } + } + + @Test fun aFailedInitIsSticky() { + val first = OtelCore.initialize(ok.copy(exportUrl = "not a url"), testMode = true) + val again = OtelCore.initialize(ok, testMode = true) + assertEquals(first.error, again.error) + assertNull(OtelCore.instance) + } + + @Test fun initializeWithoutConfigIsAnErrorButNotSticky() { + assertNotNull(OtelCore.initialize(null, testMode = true).error) + val r = OtelCore.initialize(ok, testMode = true) + assertNull(r.error); assertFalse(r.alreadyInitialized) + assertNotNull(OtelCore.instance) + } + + @Test fun initializeWithoutConfigAfterInitIsAlreadyInitialized() { + OtelCore.initialize(ok, testMode = true) + val r = OtelCore.initialize(null, testMode = true) + assertTrue(r.alreadyInitialized); assertNull(r.error) + } + + @Test fun distroAttributesOutsideTestModeOnly() { + val prod = OtelCore(ok, testMode = false, distroVersion = "9.9.9").resource + assertEquals("react-native-open-telemetry", prod.getAttribute(AttributeKey.stringKey("telemetry.distro.name"))) + assertEquals("9.9.9", prod.getAttribute(AttributeKey.stringKey("telemetry.distro.version"))) + val test = OtelCore(ok, testMode = true, distroVersion = "9.9.9").resource + assertNull(test.getAttribute(AttributeKey.stringKey("telemetry.distro.name"))) + assertNull(test.getAttribute(AttributeKey.stringKey("telemetry.sdk.name"))) + } + + @Test fun resourceAttributesAreKept() { + val c = ok.copy(resourceAttributes = listOf(SeamAttribute("k", AttrValue.Str("v")))) + assertEquals("v", OtelCore(c, testMode = true).resource.getAttribute(AttributeKey.stringKey("k"))) + } +} diff --git a/android/core-jvm/src/test/kotlin/ParentingTest.kt b/android/core-jvm/src/test/kotlin/ParentingTest.kt new file mode 100644 index 0000000..c5beea7 --- /dev/null +++ b/android/core-jvm/src/test/kotlin/ParentingTest.kt @@ -0,0 +1,48 @@ +import com.callstack.otel.core.* +import io.opentelemetry.api.trace.Span +import io.opentelemetry.context.Context +import io.opentelemetry.sdk.trace.ReadableSpan +import io.opentelemetry.sdk.trace.SdkTracerProvider +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue + +class ParentingTest { + private val tracer = SdkTracerProvider.builder().addSpanProcessor(SimpleSpanProcessor.create(object : io.opentelemetry.sdk.trace.export.SpanExporter { + override fun export(spans: Collection) = io.opentelemetry.sdk.common.CompletableResultCode.ofSuccess() + override fun flush() = io.opentelemetry.sdk.common.CompletableResultCode.ofSuccess() + override fun shutdown() = io.opentelemetry.sdk.common.CompletableResultCode.ofSuccess() + })).build().get("t") + private val tp = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01" + + private fun child(ctx: Context) = tracer.spanBuilder("c").setParent(ctx).startSpan() as ReadableSpan + + @Test fun roundTrip() { + val s = tracer.spanBuilder("p").startSpan() + assertEquals(s.spanContext.traceId, traceparentOf(s).split("-")[1]) + assertEquals(traceparentOf(s), traceparentOf(Span.fromContext(contextFrom(traceparentOf(s))))) + assertEquals(tp, traceparentOf(Span.fromContext(contextFrom(tp)))) + } + + @Test fun childHasParentIdAndIsNotRemote() { + val d = child(contextFrom(tp)).toSpanData() + assertEquals("b7ad6b7169203331", d.parentSpanId) + assertEquals("0af7651916cd43dd8448eb211c80319c", d.traceId) + assertFalse(d.parentSpanContext.isRemote) + } + + @Test fun invalidInputYieldsRoot() { + listOf("garbage", "", "ff-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01", + "01-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01", + "00-0AF7651916CD43DD8448EB211C80319C-b7ad6b7169203331-01", + "00-00000000000000000000000000000000-b7ad6b7169203331-01", + "00-0af7651916cd43dd8448eb211c80319c-0000000000000000-01", + "00-0af7-b7ad6b7169203331-01", "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-zz", + ).forEach { + assertEquals(Context.root(), contextFrom(it), it) + assertFalse(child(contextFrom(it)).toSpanData().parentSpanContext.isValid) + } + } +} diff --git a/android/core-jvm/src/test/kotlin/TraceStateTest.kt b/android/core-jvm/src/test/kotlin/TraceStateTest.kt new file mode 100644 index 0000000..8dd84e8 --- /dev/null +++ b/android/core-jvm/src/test/kotlin/TraceStateTest.kt @@ -0,0 +1,15 @@ +import com.callstack.otel.core.* +import io.opentelemetry.sdk.resources.Resource +import kotlin.test.Test +import kotlin.test.assertEquals + +class TraceStateTest { + @Test fun multiEntryTraceStateKeepsItsOrder() { + val h = HrTime(1.0, 0.0) + val span = SeamSpan( + SeamSpanContext("0a".padEnd(32, '1'), "0a".padEnd(16, '2'), 1, "a=1,b=2"), null, "s", 0, h, h, + emptyList(), emptyList(), emptyList(), SeamStatus(0, null), SeamScope("t", null, null, emptyList()), + ) + assertEquals("a=1,b=2", JsSpanData(span, Resource.empty()).spanContext.traceState.asMap().entries.joinToString(",") { "${it.key}=${it.value}" }) + } +} diff --git a/android/gradle.properties b/android/gradle.properties index dc55b22..c315c79 100644 --- a/android/gradle.properties +++ b/android/gradle.properties @@ -1,5 +1,5 @@ ReactNativeOpenTelemetry_kotlinVersion=2.1.21 -ReactNativeOpenTelemetry_minSdkVersion=24 +ReactNativeOpenTelemetry_minSdkVersion=26 ReactNativeOpenTelemetry_targetSdkVersion=36 ReactNativeOpenTelemetry_compileSdkVersion=36 ReactNativeOpenTelemetry_ndkVersion=27.1.12297006 diff --git a/android/src/core/kotlin/com/callstack/otel/core/Attributes.kt b/android/src/core/kotlin/com/callstack/otel/core/Attributes.kt new file mode 100644 index 0000000..7108ad5 --- /dev/null +++ b/android/src/core/kotlin/com/callstack/otel/core/Attributes.kt @@ -0,0 +1,25 @@ +package com.callstack.otel.core + +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: List): Attributes { + val b = Attributes.builder() + for ((k, v) in list) { + when (v) { + is AttrValue.Str -> b.put(k, v.value) + is AttrValue.Bool -> b.put(k, v.value) + is AttrValue.Num -> if (isLong(v.value)) b.put(k, v.value.toLong()) else b.put(k, v.value) + is AttrValue.Strs -> b.put(AttributeKey.stringArrayKey(k), v.value) + is AttrValue.Bools -> b.put(AttributeKey.booleanArrayKey(k), v.value) + is AttrValue.Nums -> + if (v.value.all(::isLong)) b.put(AttributeKey.longArrayKey(k), v.value.map { it.toLong() }) + else b.put(AttributeKey.doubleArrayKey(k), v.value) + } + } + return b.build() +} diff --git a/android/src/core/kotlin/com/callstack/otel/core/CoreConfig.kt b/android/src/core/kotlin/com/callstack/otel/core/CoreConfig.kt new file mode 100644 index 0000000..ff539dd --- /dev/null +++ b/android/src/core/kotlin/com/callstack/otel/core/CoreConfig.kt @@ -0,0 +1,13 @@ +package com.callstack.otel.core + +data class CoreConfig( + val serviceName: String, + val serviceVersion: String? = null, + val resourceAttributes: List = emptyList(), + /** 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/core/kotlin/com/callstack/otel/core/Endpoint.kt b/android/src/core/kotlin/com/callstack/otel/core/Endpoint.kt new file mode 100644 index 0000000..78d190f --- /dev/null +++ b/android/src/core/kotlin/com/callstack/otel/core/Endpoint.kt @@ -0,0 +1,14 @@ +package com.callstack.otel.core + +import java.net.URI + +/** Eager check (D8), no exporter built: http(s) scheme and a host. Returns an error message or null. */ +internal fun validateExportUrl(url: String): String? { + val u = try { URI(url) } catch (e: Exception) { return "invalid exportUrl: ${e.message}" } + // URI.host is null for a host it rejects as a hostname, like `otel_collector`, which iOS and web accept + val host = u.host ?: u.rawAuthority?.substringAfterLast('@')?.substringBefore(':') + if (u.scheme?.lowercase() !in setOf("http", "https") || host.isNullOrEmpty()) { + return "invalid exportUrl \"$url\": expected http(s)://host[:port]" + } + return null +} diff --git a/android/src/core/kotlin/com/callstack/otel/core/JsSpanData.kt b/android/src/core/kotlin/com/callstack/otel/core/JsSpanData.kt new file mode 100644 index 0000000..89f5aef --- /dev/null +++ b/android/src/core/kotlin/com/callstack/otel/core/JsSpanData.kt @@ -0,0 +1,81 @@ +package com.callstack.otel.core + +import io.opentelemetry.api.trace.SpanContext +import io.opentelemetry.api.trace.SpanKind +import io.opentelemetry.api.trace.StatusCode +import io.opentelemetry.api.trace.TraceFlags +import io.opentelemetry.api.trace.TraceState +import io.opentelemetry.api.common.AttributeKey +import io.opentelemetry.sdk.common.InstrumentationLibraryInfo +import io.opentelemetry.sdk.common.InstrumentationScopeInfo +import io.opentelemetry.sdk.resources.Resource +import io.opentelemetry.sdk.trace.ReadableSpan +import io.opentelemetry.sdk.trace.data.EventData +import io.opentelemetry.sdk.trace.data.LinkData +import io.opentelemetry.sdk.trace.data.SpanData +import io.opentelemetry.sdk.trace.data.StatusData + +private fun traceState(s: String?): TraceState { + if (s.isNullOrEmpty()) return TraceState.getDefault() + val b = TraceState.builder() + // the builder puts each new entry first, so add the W3C list back to front + for (kv in s.split(',').asReversed()) { + val i = kv.indexOf('=') + if (i > 0) b.put(kv.substring(0, i).trim(), kv.substring(i + 1).trim()) + } + return b.build() +} + +private fun contextOf(c: SeamSpanContext): SpanContext = + SpanContext.create(c.traceId, c.spanId, TraceFlags.fromByte(c.traceFlags.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) { SpanKind.INTERNAL } } + private val attrs by lazy { attributesOf(span.attributes) } + private val eventList by lazy { span.events.map { EventData.create(it.time.epochNanos, it.name, attributesOf(it.attributes)) } } + private val linkList by lazy { span.links.map { LinkData.create(contextOf(it.context), attributesOf(it.attributes)) } } + private val statusData by lazy { + StatusData.create(StatusCode.values().getOrElse(span.status.code) { StatusCode.UNSET }, span.status.message.orEmpty()) + } + private val scope by lazy { + InstrumentationScopeInfo.builder(span.scope.name) + .apply { span.scope.version?.let(::setVersion); span.scope.schemaUrl?.let(::setSchemaUrl) } + .setAttributes(attributesOf(span.scope.attributes)) + .build() + } + + override fun getName() = span.name + override fun getKind() = spanKind + override fun getSpanContext() = context + override fun getParentSpanContext() = parent + override fun getStatus() = statusData + override fun getStartEpochNanos() = span.start.epochNanos + override fun getEndEpochNanos() = span.end.epochNanos + override fun getAttributes() = attrs + override fun getEvents() = eventList + override fun getLinks() = linkList + override fun hasEnded() = true + override fun getTotalRecordedEvents() = span.events.size + override fun getTotalRecordedLinks() = span.links.size + override fun getTotalAttributeCount() = span.attributes.size + override fun getInstrumentationScopeInfo() = scope + @Deprecated("otel-java deprecated API; still abstract on both interfaces") + override fun getInstrumentationLibraryInfo(): InstrumentationLibraryInfo = + @Suppress("DEPRECATION") InstrumentationLibraryInfo.create(scope.name, scope.version, scope.schemaUrl) + override fun getResource() = resource + + // ReadableSpan: frozen, nothing to mutate + override fun toSpanData(): SpanData = this + override fun getLatencyNanos() = endEpochNanos - startEpochNanos + override fun getAttribute(key: AttributeKey): T? = attrs.get(key) +} diff --git a/android/src/core/kotlin/com/callstack/otel/core/OtelCore.kt b/android/src/core/kotlin/com/callstack/otel/core/OtelCore.kt new file mode 100644 index 0000000..27d23c8 --- /dev/null +++ b/android/src/core/kotlin/com/callstack/otel/core/OtelCore.kt @@ -0,0 +1,96 @@ +package com.callstack.otel.core + +import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter +import io.opentelemetry.sdk.common.CompletableResultCode +import io.opentelemetry.sdk.trace.data.SpanData +import io.opentelemetry.sdk.trace.export.SpanExporter +import io.opentelemetry.sdk.resources.Resource +import io.opentelemetry.sdk.trace.IdGenerator +import io.opentelemetry.sdk.trace.SdkTracerProvider +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() + override fun generateTraceId() = "0b" + t.incrementAndGet().toString().padStart(30, '0') + override fun generateSpanId() = "0b" + s.incrementAndGet().toString().padStart(14, '0') +} + +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) + override fun flush(): CompletableResultCode = d.flush() + override fun shutdown(): CompletableResultCode = d.shutdown() +} + +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( + attributesOf(config.resourceAttributes).toBuilder() + .put("service.name", config.serviceName) + .apply { config.serviceVersion?.let { put("service.version", it) } } + .apply { + if (!testMode) { + put("telemetry.distro.name", DISTRO_NAME) + put("telemetry.distro.version", distroVersion) + } + } + .build(), + ), + ) + + private val bsp = BatchSpanProcessor.builder( + LazyExporter { + 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 (Task 27) + ).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: List) { + for (s in spans) bsp.onEnd(JsSpanData(s, resource)) + } + + fun flush(timeoutMs: Long): Boolean = tracerProvider.forceFlush().join(timeoutMs, TimeUnit.MILLISECONDS).isSuccess + + companion object { + private var state: InitResult? = null + @Volatile var instance: OtelCore? = null + private set + + /** + * Idempotent. The first result sticks, a failed one too (R16): 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") + val err = validateExportUrl(config.exportUrl) + val result = InitResult(false, testMode, err) + if (err == null) { + try { instance = OtelCore(config, testMode, distroVersion) } catch (e: Exception) { + return InitResult(false, testMode, "init failed: ${e.message}").also { state = it } + } + } + state = result + return result + } + + @Synchronized internal fun resetForTest() { state = null; instance = null } + } +} diff --git a/android/src/core/kotlin/com/callstack/otel/core/Parenting.kt b/android/src/core/kotlin/com/callstack/otel/core/Parenting.kt new file mode 100644 index 0000000..5a975d0 --- /dev/null +++ b/android/src/core/kotlin/com/callstack/otel/core/Parenting.kt @@ -0,0 +1,24 @@ +package com.callstack.otel.core + +import io.opentelemetry.api.trace.Span +import io.opentelemetry.api.trace.SpanContext +import io.opentelemetry.api.trace.TraceFlags +import io.opentelemetry.api.trace.TraceState +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 + val sc = SpanContext.create(traceId, spanId, TraceFlags.fromHex(flags, 0), TraceState.getDefault()) + return if (sc.isValid) Context.root().with(Span.wrap(sc)) else Context.root() +} + +fun traceparentOf(span: Span): String = + span.spanContext.let { "00-${it.traceId}-${it.spanId}-${it.traceFlags.asHex()}" } diff --git a/android/src/core/kotlin/com/callstack/otel/core/SeamModel.kt b/android/src/core/kotlin/com/callstack/otel/core/SeamModel.kt new file mode 100644 index 0000000..c57a599 --- /dev/null +++ b/android/src/core/kotlin/com/callstack/otel/core/SeamModel.kt @@ -0,0 +1,44 @@ +package com.callstack.otel.core + +// Mirrors the Nitro seam (src/native/Otel.nitro.ts) without Nitro types; the Android adapter converts. + +/** OTel HrTime `[seconds, nanos]`. */ +data class HrTime(val seconds: Double, val nanos: Double) { + val epochNanos: Long get() = seconds.toLong() * 1_000_000_000L + nanos.toLong() + + companion object { + /** Never throws on the JS thread: missing elements read as 0. */ + fun of(a: DoubleArray) = HrTime(a.getOrElse(0) { 0.0 }, a.getOrElse(1) { 0.0 }) + } +} + +sealed class AttrValue { + data class Str(val value: String) : AttrValue() + data class Bool(val value: Boolean) : AttrValue() + data class Num(val value: Double) : AttrValue() + data class Strs(val value: List) : AttrValue() + data class Bools(val value: List) : AttrValue() + data class Nums(val value: List) : AttrValue() +} + +data class SeamAttribute(val key: String, val value: AttrValue) +data class SeamSpanContext(val traceId: String, val spanId: String, val traceFlags: Int, val traceState: String? = null) +data class SeamEvent(val name: String, val time: HrTime, val attributes: List) +data class SeamLink(val context: SeamSpanContext, val attributes: List) +data class SeamScope(val name: String, val version: String?, val schemaUrl: String?, val attributes: List) +data class SeamStatus(val code: Int, val message: String?) + +data class SeamSpan( + val context: SeamSpanContext, + val parentSpanId: String?, + val name: String, + /** `@opentelemetry/api` SpanKind (INTERNAL = 0). */ + val kind: Int, + val start: HrTime, + val end: HrTime, + val attributes: List, + val events: List, + val links: List, + val status: SeamStatus, + val scope: SeamScope, +) diff --git a/android/src/main/java/com/callstack/otel/RNOtel.kt b/android/src/main/java/com/callstack/otel/RNOtel.kt new file mode 100644 index 0000000..eb047d9 --- /dev/null +++ b/android/src/main/java/com/callstack/otel/RNOtel.kt @@ -0,0 +1,77 @@ +package com.callstack.otel + +import android.app.Application +import android.content.Context +import android.os.Build +import android.os.Handler +import android.os.Looper +import android.util.Log +import androidx.lifecycle.DefaultLifecycleObserver +import androidx.lifecycle.LifecycleOwner +import androidx.lifecycle.ProcessLifecycleOwner +import com.callstack.otel.core.CoreConfig +import com.callstack.otel.core.InitResult +import com.callstack.otel.core.OtelCore +import com.margelo.nitro.callstack.otel.BuildConfig +import io.opentelemetry.api.OpenTelemetry +import io.opentelemetry.api.trace.Span +import io.opentelemetry.api.trace.Tracer +import io.opentelemetry.context.Context as OtelContext +import java.io.File +import java.util.concurrent.atomic.AtomicBoolean + +/** Public native API (spec §4.3/§4.4). Test mode comes from the build (`-PotelTestMode=true`), never from here. */ +object RNOtel { + private const val TAG = "RNOtel" + private val observing = AtomicBoolean() + + /** Native-first init from `Application.onCreate`. No-op outside the main process; never throws. */ + @JvmStatic + fun start(context: Context, block: RNOtelConfig.() -> Unit) { + try { + val app = context.applicationContext + if (processName() != app.packageName) return + val r = initialize(RNOtelConfig().apply(block).toCore()) + // alreadyInitialized: a repeat call; a sticky failure was logged by the first one + if (r.error != null && !r.alreadyInitialized) Log.e(TAG, "init failed; telemetry is off: ${r.error}") + } catch (e: Exception) { + Log.e(TAG, "init failed; telemetry is off", e) + } + } + + /** One path for native-first and JS-fallback init. The exporter (OkHttp) is built on first export, on the BSP thread. */ + internal fun initialize(config: CoreConfig?): InitResult { + val r = OtelCore.initialize(config, BuildConfig.OTEL_TEST_MODE, BuildConfig.OTEL_DISTRO_VERSION) + if (OtelCore.instance != null && observing.compareAndSet(false, true)) { + Handler(Looper.getMainLooper()).post { + ProcessLifecycleOwner.get().lifecycle.addObserver(object : DefaultLifecycleObserver { + // forceFlush only signals the BSP worker: asynchronous, never join() on the main thread + override fun onStop(owner: LifecycleOwner) { + OtelCore.instance?.tracerProvider?.forceFlush() + } + }) + } + } + return r + } + + /** A tracer on the native provider; a no-op tracer before (or without) a successful init. */ + @JvmStatic + @JvmOverloads + fun tracer(name: String, version: String? = null): Tracer { + val provider = OtelCore.instance?.tracerProvider ?: OpenTelemetry.noop().tracerProvider + return provider.tracerBuilder(name).apply { version?.let(::setInstrumentationVersion) }.build() + } + + /** W3C traceparent -> explicit, non-remote parent context; invalid input -> root. */ + @JvmStatic + fun contextFrom(traceparent: String): OtelContext = com.callstack.otel.core.contextFrom(traceparent) + + @JvmStatic + fun traceparentOf(span: Span): String = com.callstack.otel.core.traceparentOf(span) + + // Application.getProcessName() is API 28+; minSdk is 26. + private fun processName(): String = + if (Build.VERSION.SDK_INT >= 28) Application.getProcessName() + else File("/proc/self/cmdline").readText().substringBefore('\u0000').trim() +} diff --git a/android/src/main/java/com/callstack/otel/RNOtelConfig.kt b/android/src/main/java/com/callstack/otel/RNOtelConfig.kt new file mode 100644 index 0000000..971aa2a --- /dev/null +++ b/android/src/main/java/com/callstack/otel/RNOtelConfig.kt @@ -0,0 +1,31 @@ +package com.callstack.otel + +import com.callstack.otel.core.AttrValue +import com.callstack.otel.core.CoreConfig +import com.callstack.otel.core.SeamAttribute + +/** Native-first config (spec §4.4): `RNOtel.start(this) { serviceName = …; export { url = … } }`. */ +class RNOtelConfig { + var serviceName: String = "" + var serviceVersion: String? = null + var resourceAttributes: Map = emptyMap() + private var export = Export() + + class Export { + /** The OTLP/HTTP traces endpoint (e.g. `https://collector:4318/v1/traces`), used as given. */ + var url: String = "" + var headers: Map = emptyMap() + } + + fun export(block: Export.() -> Unit) { + export = Export().apply(block) + } + + internal fun toCore() = CoreConfig( + serviceName = serviceName, + serviceVersion = serviceVersion, + resourceAttributes = resourceAttributes.map { (k, v) -> SeamAttribute(k, AttrValue.Str(v)) }, + exportUrl = export.url, + exportHeaders = export.headers, + ) +} 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 9aff250..3566ca2 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 @@ -1,29 +1,78 @@ package com.margelo.nitro.callstack.otel -import android.util.Log import androidx.annotation.Keep +import com.callstack.otel.RNOtel +import com.callstack.otel.core.CoreConfig +import com.callstack.otel.core.HrTime +import com.callstack.otel.core.OtelCore import com.facebook.proguard.annotations.DoNotStrip import com.margelo.nitro.core.Promise -import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import com.callstack.otel.core.AttrValue as CoreValue +import com.callstack.otel.core.SeamAttribute as CoreAttribute +import com.callstack.otel.core.SeamEvent as CoreEvent +import com.callstack.otel.core.SeamLink as CoreLink +import com.callstack.otel.core.SeamScope as CoreScope +import com.callstack.otel.core.SeamSpan as CoreSpan +import com.callstack.otel.core.SeamSpanContext as CoreSpanContext +import com.callstack.otel.core.SeamStatus as CoreStatus -/** Tracer-bullet stub (Task 7): proves the seam and the otel-java link; the real adapter is Task 24. */ +/** The seam, mapped 1:1 onto the Kotlin core. */ // Constructed from JNI by name (ReactNativeOpenTelemetryOnLoad.cpp): keep it through R8. @DoNotStrip @Keep class HybridOtel : HybridOtelSpec() { override fun initialize(config: SeamConfig?): SeamInitResult { - // Touch otel-java + its OkHttp sender so a broken dependency fails here, not in Task 24. - OtlpHttpSpanExporter.builder().build().shutdown() - return SeamInitResult(alreadyInitialized = false, testMode = BuildConfig.OTEL_TEST_MODE, error = null) + val r = RNOtel.initialize(config?.let { + CoreConfig( + serviceName = it.serviceName, + serviceVersion = it.serviceVersion, + resourceAttributes = attrs(it.resourceAttributes), + exportUrl = it.exportUrl, + exportHeaders = it.exportHeaders.mapNotNull { h -> h.value.asFifthOrNull()?.let { v -> h.key to v } }.toMap(), + ) + }) + return SeamInitResult(r.alreadyInitialized, r.testMode, r.error) } + /** JS thread: copy the structs and enqueue; SpanData is built on the export thread. */ override fun handOff(spans: Array) { - Log.i( - "RNOtel", - "RNOtel handOff spans=${spans.size} attrs=${spans.sumOf { it.attributes.size }} " + - "events=${spans.sumOf { it.events.size }} links=${spans.sumOf { it.links.size }}", - ) + OtelCore.instance?.handOff(spans.map(::span)) } - override fun flush(timeoutMs: Double): Promise = Promise.resolved(Unit) + // 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 + } + + private val io = CoroutineScope(Dispatchers.IO) + + private fun span(s: SeamSpan) = CoreSpan( + context = ctx(s.context), + parentSpanId = s.parentSpanId, + name = s.name, + kind = s.kind.toInt(), + start = HrTime.of(s.start), + end = HrTime.of(s.end), + attributes = attrs(s.attributes), + events = s.events.map { CoreEvent(it.name, HrTime.of(it.time), attrs(it.attributes)) }, + links = s.links.map { CoreLink(ctx(it.context), attrs(it.attributes)) }, + status = CoreStatus(s.status.code.toInt(), s.status.message), + scope = CoreScope(s.scope.name, s.scope.version, s.scope.schemaUrl, attrs(s.scope.attributes)), + ) + + private fun ctx(c: SeamSpanContext) = CoreSpanContext(c.traceId, c.spanId, c.traceFlags.toInt(), c.traceState) + + private fun attrs(a: Array) = a.map { CoreAttribute(it.key, value(it.value)) } + + private fun value(v: AttrValue): CoreValue = when (v) { + is AttrValue.First -> CoreValue.Bool(v.value) + is AttrValue.Second -> CoreValue.Bools(v.value.asList()) + is AttrValue.Third -> CoreValue.Strs(v.value.asList()) + is AttrValue.Fourth -> CoreValue.Nums(v.value.asList()) + is AttrValue.Fifth -> CoreValue.Str(v.value) + is AttrValue.Sixth -> CoreValue.Num(v.value) + } } diff --git a/package.json b/package.json index dcc3295..9d6f011 100644 --- a/package.json +++ b/package.json @@ -52,6 +52,7 @@ "metro", "!ios/build", "!android/build", + "!android/core-jvm", "!android/gradle", "!android/gradlew", "!android/gradlew.bat", diff --git a/verify/expected/async-generator.android.otlp.json b/verify/expected/async-generator.android.otlp.json new file mode 100644 index 0000000..cbf84fd --- /dev/null +++ b/verify/expected/async-generator.android.otlp.json @@ -0,0 +1,79 @@ +{ + "resourceSpans": [ + { + "resource": { + "attributes": [ + { + "key": "service.name", + "value": { + "stringValue": "verify" + } + } + ] + }, + "scopeSpans": [ + { + "scope": { + "name": "verify" + }, + "spans": [ + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000001", + "name": "root", + "kind": 1, + "startTimeUnixNano": "1767225600000000000", + "endTimeUnixNano": "1767225600000060000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000002", + "parentSpanId": "0a00000000000001", + "name": "gen.0", + "kind": 1, + "startTimeUnixNano": "1767225600000010000", + "endTimeUnixNano": "1767225600000011000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000003", + "parentSpanId": "0a00000000000001", + "name": "loop.0", + "kind": 1, + "startTimeUnixNano": "1767225600000020000", + "endTimeUnixNano": "1767225600000021000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000004", + "parentSpanId": "0a00000000000001", + "name": "gen.1", + "kind": 1, + "startTimeUnixNano": "1767225600000030000", + "endTimeUnixNano": "1767225600000031000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000005", + "parentSpanId": "0a00000000000001", + "name": "loop.1", + "kind": 1, + "startTimeUnixNano": "1767225600000040000", + "endTimeUnixNano": "1767225600000041000", + "status": {}, + "flags": 257 + } + ] + } + ] + } + ] +} diff --git a/verify/expected/background-flush.android.otlp.json b/verify/expected/background-flush.android.otlp.json new file mode 100644 index 0000000..75f8271 --- /dev/null +++ b/verify/expected/background-flush.android.otlp.json @@ -0,0 +1,35 @@ +{ + "resourceSpans": [ + { + "resource": { + "attributes": [ + { + "key": "service.name", + "value": { + "stringValue": "verify" + } + } + ] + }, + "scopeSpans": [ + { + "scope": { + "name": "verify" + }, + "spans": [ + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000001", + "name": "before_background", + "kind": 1, + "startTimeUnixNano": "1767225600000000000", + "endTimeUnixNano": "1767225600000010000", + "status": {}, + "flags": 257 + } + ] + } + ] + } + ] +} diff --git a/verify/expected/batching-shared-queue.android.otlp.json b/verify/expected/batching-shared-queue.android.otlp.json new file mode 100644 index 0000000..0b41dc0 --- /dev/null +++ b/verify/expected/batching-shared-queue.android.otlp.json @@ -0,0 +1,67 @@ +{ + "resourceSpans": [ + { + "resource": { + "attributes": [ + { + "key": "service.name", + "value": { + "stringValue": "verify" + } + } + ] + }, + "scopeSpans": [ + { + "scope": { + "name": "verify" + }, + "spans": [ + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000001", + "name": "h1", + "kind": 1, + "startTimeUnixNano": "1767225600000000000", + "endTimeUnixNano": "1767225600000001000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000002", + "spanId": "0a00000000000002", + "name": "h2", + "kind": 1, + "startTimeUnixNano": "1767225600000002000", + "endTimeUnixNano": "1767225600000003000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000003", + "parentSpanId": "0a00000000000001", + "name": "h1.work", + "kind": 1, + "startTimeUnixNano": "1767225600000010000", + "endTimeUnixNano": "1767225600000011000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000004", + "parentSpanId": "0a00000000000001", + "name": "h2.work", + "kind": 1, + "startTimeUnixNano": "1767225600000020000", + "endTimeUnixNano": "1767225600000021000", + "status": {}, + "flags": 257 + } + ] + } + ] + } + ] +} diff --git a/verify/expected/captured-then.android.otlp.json b/verify/expected/captured-then.android.otlp.json new file mode 100644 index 0000000..b57eb7e --- /dev/null +++ b/verify/expected/captured-then.android.otlp.json @@ -0,0 +1,56 @@ +{ + "resourceSpans": [ + { + "resource": { + "attributes": [ + { + "key": "service.name", + "value": { + "stringValue": "verify" + } + } + ] + }, + "scopeSpans": [ + { + "scope": { + "name": "verify" + }, + "spans": [ + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000001", + "name": "parent", + "kind": 1, + "startTimeUnixNano": "1767225600000000000", + "endTimeUnixNano": "1767225600000030000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000002", + "parentSpanId": "0a00000000000001", + "name": "kept", + "kind": 1, + "startTimeUnixNano": "1767225600000010000", + "endTimeUnixNano": "1767225600000011000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000002", + "spanId": "0a00000000000003", + "name": "lost", + "kind": 1, + "startTimeUnixNano": "1767225600000020000", + "endTimeUnixNano": "1767225600000021000", + "status": {}, + "flags": 257 + } + ] + } + ] + } + ] +} diff --git a/verify/expected/collector-down.android.otlp.json b/verify/expected/collector-down.android.otlp.json new file mode 100644 index 0000000..367c32e --- /dev/null +++ b/verify/expected/collector-down.android.otlp.json @@ -0,0 +1,35 @@ +{ + "resourceSpans": [ + { + "resource": { + "attributes": [ + { + "key": "service.name", + "value": { + "stringValue": "verify" + } + } + ] + }, + "scopeSpans": [ + { + "scope": { + "name": "verify" + }, + "spans": [ + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000001", + "name": "work", + "kind": 1, + "startTimeUnixNano": "1767225600000000000", + "endTimeUnixNano": "1767225600000010000", + "status": {}, + "flags": 257 + } + ] + } + ] + } + ] +} diff --git a/verify/expected/concurrent-interleaved.android.otlp.json b/verify/expected/concurrent-interleaved.android.otlp.json new file mode 100644 index 0000000..3428488 --- /dev/null +++ b/verify/expected/concurrent-interleaved.android.otlp.json @@ -0,0 +1,99 @@ +{ + "resourceSpans": [ + { + "resource": { + "attributes": [ + { + "key": "service.name", + "value": { + "stringValue": "verify" + } + } + ] + }, + "scopeSpans": [ + { + "scope": { + "name": "verify" + }, + "spans": [ + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000001", + "name": "a", + "kind": 1, + "startTimeUnixNano": "1767225600000000000", + "endTimeUnixNano": "1767225600000030000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000002", + "spanId": "0a00000000000002", + "name": "b", + "kind": 1, + "startTimeUnixNano": "1767225600000001000", + "endTimeUnixNano": "1767225600000031000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000003", + "parentSpanId": "0a00000000000001", + "name": "a.1", + "kind": 1, + "startTimeUnixNano": "1767225600000010000", + "endTimeUnixNano": "1767225600000011000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000002", + "spanId": "0a00000000000004", + "parentSpanId": "0a00000000000002", + "name": "b.1", + "kind": 1, + "startTimeUnixNano": "1767225600000011000", + "endTimeUnixNano": "1767225600000012000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000005", + "parentSpanId": "0a00000000000001", + "name": "a.2", + "kind": 1, + "startTimeUnixNano": "1767225600000020000", + "endTimeUnixNano": "1767225600000021000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000002", + "spanId": "0a00000000000006", + "parentSpanId": "0a00000000000002", + "name": "b.2", + "kind": 1, + "startTimeUnixNano": "1767225600000021000", + "endTimeUnixNano": "1767225600000022000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000003", + "spanId": "0a00000000000007", + "name": "after.all", + "kind": 1, + "startTimeUnixNano": "1767225600000040000", + "endTimeUnixNano": "1767225600000041000", + "status": {}, + "flags": 257 + } + ] + } + ] + } + ] +} diff --git a/verify/expected/cross-js-to-native.android.otlp.json b/verify/expected/cross-js-to-native.android.otlp.json new file mode 100644 index 0000000..184d55b --- /dev/null +++ b/verify/expected/cross-js-to-native.android.otlp.json @@ -0,0 +1,53 @@ +{ + "resourceSpans": [ + { + "resource": { + "attributes": [ + { + "key": "service.name", + "value": { + "stringValue": "verify" + } + } + ] + }, + "scopeSpans": [ + { + "scope": { + "name": "verify" + }, + "spans": [ + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000001", + "name": "js.parent", + "kind": 1, + "startTimeUnixNano": "1767225600000000000", + "endTimeUnixNano": "1767225600000300000", + "status": {}, + "flags": 257 + } + ] + }, + { + "scope": { + "name": "test-native" + }, + "spans": [ + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0b00000000000001", + "parentSpanId": "0a00000000000001", + "name": "native.work", + "kind": 1, + "startTimeUnixNano": "1767225600000100000", + "endTimeUnixNano": "1767225600000200000", + "status": {}, + "flags": 257 + } + ] + } + ] + } + ] +} diff --git a/verify/expected/cross-native-to-js.android.otlp.json b/verify/expected/cross-native-to-js.android.otlp.json new file mode 100644 index 0000000..fe18d38 --- /dev/null +++ b/verify/expected/cross-native-to-js.android.otlp.json @@ -0,0 +1,53 @@ +{ + "resourceSpans": [ + { + "resource": { + "attributes": [ + { + "key": "service.name", + "value": { + "stringValue": "verify" + } + } + ] + }, + "scopeSpans": [ + { + "scope": { + "name": "test-native" + }, + "spans": [ + { + "traceId": "0b000000000000000000000000000001", + "spanId": "0b00000000000001", + "name": "native.work", + "kind": 1, + "startTimeUnixNano": "1767225600000000000", + "endTimeUnixNano": "1767225600000100000", + "status": {}, + "flags": 257 + } + ] + }, + { + "scope": { + "name": "verify" + }, + "spans": [ + { + "traceId": "0b000000000000000000000000000001", + "spanId": "0a00000000000001", + "parentSpanId": "0b00000000000001", + "name": "js.after_native", + "kind": 1, + "startTimeUnixNano": "1767225600000200000", + "endTimeUnixNano": "1767225600000300000", + "status": {}, + "flags": 257 + } + ] + } + ] + } + ] +} diff --git a/verify/expected/error-in-callback.android.otlp.json b/verify/expected/error-in-callback.android.otlp.json new file mode 100644 index 0000000..22eccaa --- /dev/null +++ b/verify/expected/error-in-callback.android.otlp.json @@ -0,0 +1,67 @@ +{ + "resourceSpans": [ + { + "resource": { + "attributes": [ + { + "key": "service.name", + "value": { + "stringValue": "verify" + } + } + ] + }, + "scopeSpans": [ + { + "scope": { + "name": "verify" + }, + "spans": [ + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000001", + "name": "parent", + "kind": 1, + "startTimeUnixNano": "1767225600000000000", + "endTimeUnixNano": "1767225600000040000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000002", + "parentSpanId": "0a00000000000001", + "name": "throws", + "kind": 1, + "startTimeUnixNano": "1767225600000010000", + "endTimeUnixNano": "1767225600000011000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000002", + "spanId": "0a00000000000003", + "name": "root.next", + "kind": 1, + "startTimeUnixNano": "1767225600000030000", + "endTimeUnixNano": "1767225600000031000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000004", + "parentSpanId": "0a00000000000001", + "name": "caught", + "kind": 1, + "startTimeUnixNano": "1767225600000020000", + "endTimeUnixNano": "1767225600000021000", + "status": {}, + "flags": 257 + } + ] + } + ] + } + ] +} diff --git a/verify/expected/event-emitter-listener.android.otlp.json b/verify/expected/event-emitter-listener.android.otlp.json new file mode 100644 index 0000000..71f62e7 --- /dev/null +++ b/verify/expected/event-emitter-listener.android.otlp.json @@ -0,0 +1,46 @@ +{ + "resourceSpans": [ + { + "resource": { + "attributes": [ + { + "key": "service.name", + "value": { + "stringValue": "verify" + } + } + ] + }, + "scopeSpans": [ + { + "scope": { + "name": "verify" + }, + "spans": [ + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000001", + "name": "emit", + "kind": 1, + "startTimeUnixNano": "1767225600000000000", + "endTimeUnixNano": "1767225600000020000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000002", + "parentSpanId": "0a00000000000001", + "name": "listener", + "kind": 1, + "startTimeUnixNano": "1767225600000010000", + "endTimeUnixNano": "1767225600000011000", + "status": {}, + "flags": 257 + } + ] + } + ] + } + ] +} diff --git a/verify/expected/export-headers.android.otlp.json b/verify/expected/export-headers.android.otlp.json new file mode 100644 index 0000000..09465b2 --- /dev/null +++ b/verify/expected/export-headers.android.otlp.json @@ -0,0 +1,35 @@ +{ + "resourceSpans": [ + { + "resource": { + "attributes": [ + { + "key": "service.name", + "value": { + "stringValue": "verify" + } + } + ] + }, + "scopeSpans": [ + { + "scope": { + "name": "verify" + }, + "spans": [ + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000001", + "name": "headers", + "kind": 1, + "startTimeUnixNano": "1767225600000000000", + "endTimeUnixNano": "1767225600000010000", + "status": {}, + "flags": 257 + } + ] + } + ] + } + ] +} diff --git a/verify/expected/flush-after-reload.android.otlp.json b/verify/expected/flush-after-reload.android.otlp.json new file mode 100644 index 0000000..2c9cf5f --- /dev/null +++ b/verify/expected/flush-after-reload.android.otlp.json @@ -0,0 +1,35 @@ +{ + "resourceSpans": [ + { + "resource": { + "attributes": [ + { + "key": "service.name", + "value": { + "stringValue": "verify" + } + } + ] + }, + "scopeSpans": [ + { + "scope": { + "name": "verify" + }, + "spans": [ + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000001", + "name": "before_reload", + "kind": 1, + "startTimeUnixNano": "1767225600000000000", + "endTimeUnixNano": "1767225600000010000", + "status": {}, + "flags": 257 + } + ] + } + ] + } + ] +} diff --git a/verify/expected/handoff-basic.android.otlp.json b/verify/expected/handoff-basic.android.otlp.json new file mode 100644 index 0000000..6876639 --- /dev/null +++ b/verify/expected/handoff-basic.android.otlp.json @@ -0,0 +1,43 @@ +{ + "resourceSpans": [ + { + "resource": { + "attributes": [ + { + "key": "service.name", + "value": { + "stringValue": "verify" + } + } + ] + }, + "scopeSpans": [ + { + "scope": { + "name": "verify" + }, + "spans": [ + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000001", + "name": "root", + "kind": 1, + "startTimeUnixNano": "1767225600000000000", + "endTimeUnixNano": "1767225600000100000", + "attributes": [ + { + "key": "app.step", + "value": { + "stringValue": "one" + } + } + ], + "status": {}, + "flags": 257 + } + ] + } + ] + } + ] +} diff --git a/verify/expected/interval-new-root.android.otlp.json b/verify/expected/interval-new-root.android.otlp.json new file mode 100644 index 0000000..3923a1e --- /dev/null +++ b/verify/expected/interval-new-root.android.otlp.json @@ -0,0 +1,66 @@ +{ + "resourceSpans": [ + { + "resource": { + "attributes": [ + { + "key": "service.name", + "value": { + "stringValue": "verify" + } + } + ] + }, + "scopeSpans": [ + { + "scope": { + "name": "verify" + }, + "spans": [ + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000001", + "name": "tap", + "kind": 1, + "startTimeUnixNano": "1767225600000000000", + "endTimeUnixNano": "1767225600000400000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000002", + "spanId": "0a00000000000002", + "name": "tick", + "kind": 1, + "startTimeUnixNano": "1767225600000100000", + "endTimeUnixNano": "1767225600000101000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000003", + "spanId": "0a00000000000003", + "name": "tick", + "kind": 1, + "startTimeUnixNano": "1767225600000200000", + "endTimeUnixNano": "1767225600000201000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000004", + "parentSpanId": "0a00000000000001", + "name": "load", + "kind": 1, + "startTimeUnixNano": "1767225600000300000", + "endTimeUnixNano": "1767225600000301000", + "status": {}, + "flags": 257 + } + ] + } + ] + } + ] +} diff --git a/verify/expected/native-init-failure.android.otlp.json b/verify/expected/native-init-failure.android.otlp.json new file mode 100644 index 0000000..0efd939 --- /dev/null +++ b/verify/expected/native-init-failure.android.otlp.json @@ -0,0 +1,3 @@ +{ + "resourceSpans": [] +} diff --git a/verify/expected/nest-after-await.android.otlp.json b/verify/expected/nest-after-await.android.otlp.json new file mode 100644 index 0000000..611ade2 --- /dev/null +++ b/verify/expected/nest-after-await.android.otlp.json @@ -0,0 +1,46 @@ +{ + "resourceSpans": [ + { + "resource": { + "attributes": [ + { + "key": "service.name", + "value": { + "stringValue": "verify" + } + } + ] + }, + "scopeSpans": [ + { + "scope": { + "name": "verify" + }, + "spans": [ + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000001", + "name": "parent", + "kind": 1, + "startTimeUnixNano": "1767225600000000000", + "endTimeUnixNano": "1767225600000030000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000002", + "parentSpanId": "0a00000000000001", + "name": "child", + "kind": 1, + "startTimeUnixNano": "1767225600000010000", + "endTimeUnixNano": "1767225600000020000", + "status": {}, + "flags": 257 + } + ] + } + ] + } + ] +} diff --git a/verify/expected/nest-promise-all-race.android.otlp.json b/verify/expected/nest-promise-all-race.android.otlp.json new file mode 100644 index 0000000..57ceef3 --- /dev/null +++ b/verify/expected/nest-promise-all-race.android.otlp.json @@ -0,0 +1,90 @@ +{ + "resourceSpans": [ + { + "resource": { + "attributes": [ + { + "key": "service.name", + "value": { + "stringValue": "verify" + } + } + ] + }, + "scopeSpans": [ + { + "scope": { + "name": "verify" + }, + "spans": [ + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000001", + "name": "root", + "kind": 1, + "startTimeUnixNano": "1767225600000000000", + "endTimeUnixNano": "1767225600000060000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000002", + "parentSpanId": "0a00000000000001", + "name": "all.a", + "kind": 1, + "startTimeUnixNano": "1767225600000010000", + "endTimeUnixNano": "1767225600000011000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000003", + "parentSpanId": "0a00000000000001", + "name": "all.b", + "kind": 1, + "startTimeUnixNano": "1767225600000020000", + "endTimeUnixNano": "1767225600000021000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000004", + "parentSpanId": "0a00000000000001", + "name": "race.a", + "kind": 1, + "startTimeUnixNano": "1767225600000030000", + "endTimeUnixNano": "1767225600000031000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000005", + "parentSpanId": "0a00000000000001", + "name": "race.b", + "kind": 1, + "startTimeUnixNano": "1767225600000040000", + "endTimeUnixNano": "1767225600000041000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000006", + "parentSpanId": "0a00000000000001", + "name": "after", + "kind": 1, + "startTimeUnixNano": "1767225600000050000", + "endTimeUnixNano": "1767225600000051000", + "status": {}, + "flags": 257 + } + ] + } + ] + } + ] +} diff --git a/verify/expected/nest-raf.android.otlp.json b/verify/expected/nest-raf.android.otlp.json new file mode 100644 index 0000000..947dddf --- /dev/null +++ b/verify/expected/nest-raf.android.otlp.json @@ -0,0 +1,46 @@ +{ + "resourceSpans": [ + { + "resource": { + "attributes": [ + { + "key": "service.name", + "value": { + "stringValue": "verify" + } + } + ] + }, + "scopeSpans": [ + { + "scope": { + "name": "verify" + }, + "spans": [ + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000001", + "name": "root", + "kind": 1, + "startTimeUnixNano": "1767225600000000000", + "endTimeUnixNano": "1767225600000020000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000002", + "parentSpanId": "0a00000000000001", + "name": "frame", + "kind": 1, + "startTimeUnixNano": "1767225600000010000", + "endTimeUnixNano": "1767225600000011000", + "status": {}, + "flags": 257 + } + ] + } + ] + } + ] +} diff --git a/verify/expected/nest-timers-microtasks.android.otlp.json b/verify/expected/nest-timers-microtasks.android.otlp.json new file mode 100644 index 0000000..c730379 --- /dev/null +++ b/verify/expected/nest-timers-microtasks.android.otlp.json @@ -0,0 +1,90 @@ +{ + "resourceSpans": [ + { + "resource": { + "attributes": [ + { + "key": "service.name", + "value": { + "stringValue": "verify" + } + } + ] + }, + "scopeSpans": [ + { + "scope": { + "name": "verify" + }, + "spans": [ + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000001", + "name": "root", + "kind": 1, + "startTimeUnixNano": "1767225600000000000", + "endTimeUnixNano": "1767225600000050000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000002", + "parentSpanId": "0a00000000000001", + "name": "timeout", + "kind": 1, + "startTimeUnixNano": "1767225600000010000", + "endTimeUnixNano": "1767225600000011000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000003", + "parentSpanId": "0a00000000000001", + "name": "immediate", + "kind": 1, + "startTimeUnixNano": "1767225600000020000", + "endTimeUnixNano": "1767225600000021000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000004", + "parentSpanId": "0a00000000000001", + "name": "microtask", + "kind": 1, + "startTimeUnixNano": "1767225600000030000", + "endTimeUnixNano": "1767225600000031000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000005", + "parentSpanId": "0a00000000000001", + "name": "timeout.microtask", + "kind": 1, + "startTimeUnixNano": "1767225600000040000", + "endTimeUnixNano": "1767225600000041000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000006", + "parentSpanId": "0a00000000000001", + "name": "after.end", + "kind": 1, + "startTimeUnixNano": "1767225600000060000", + "endTimeUnixNano": "1767225600000061000", + "status": {}, + "flags": 257 + } + ] + } + ] + } + ] +} diff --git a/verify/expected/never-settling-promise.android.otlp.json b/verify/expected/never-settling-promise.android.otlp.json new file mode 100644 index 0000000..a71e213 --- /dev/null +++ b/verify/expected/never-settling-promise.android.otlp.json @@ -0,0 +1,66 @@ +{ + "resourceSpans": [ + { + "resource": { + "attributes": [ + { + "key": "service.name", + "value": { + "stringValue": "verify" + } + } + ] + }, + "scopeSpans": [ + { + "scope": { + "name": "verify" + }, + "spans": [ + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000001", + "name": "parent", + "kind": 1, + "startTimeUnixNano": "1767225600000000000", + "endTimeUnixNano": "1767225600000020000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000002", + "parentSpanId": "0a00000000000001", + "name": "child", + "kind": 1, + "startTimeUnixNano": "1767225600000010000", + "endTimeUnixNano": "1767225600000011000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000002", + "spanId": "0a00000000000003", + "name": "later.await", + "kind": 1, + "startTimeUnixNano": "1767225600000030000", + "endTimeUnixNano": "1767225600000031000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000003", + "spanId": "0a00000000000004", + "name": "later.timeout", + "kind": 1, + "startTimeUnixNano": "1767225600000040000", + "endTimeUnixNano": "1767225600000041000", + "status": {}, + "flags": 257 + } + ] + } + ] + } + ] +} diff --git a/verify/expected/odd-attributes.android.otlp.json b/verify/expected/odd-attributes.android.otlp.json new file mode 100644 index 0000000..b82c28d --- /dev/null +++ b/verify/expected/odd-attributes.android.otlp.json @@ -0,0 +1,67 @@ +{ + "resourceSpans": [ + { + "resource": { + "attributes": [ + { + "key": "service.name", + "value": { + "stringValue": "verify" + } + } + ] + }, + "scopeSpans": [ + { + "scope": { + "name": "verify" + }, + "spans": [ + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000001", + "name": "odd", + "kind": 1, + "startTimeUnixNano": "1767225600000000000", + "endTimeUnixNano": "1767225600000010000", + "attributes": [ + { + "key": "big", + "value": { + "intValue": "9007199254740994" + } + }, + { + "key": "empty", + "value": { + "arrayValue": {} + } + }, + { + "key": "inf", + "value": { + "doubleValue": "Infinity" + } + }, + { + "key": "nan", + "value": { + "doubleValue": "NaN" + } + }, + { + "key": "negZero", + "value": { + "intValue": "0" + } + } + ], + "status": {}, + "flags": 257 + } + ] + } + ] + } + ] +} diff --git a/verify/expected/rich-span.android.otlp.json b/verify/expected/rich-span.android.otlp.json new file mode 100644 index 0000000..7f3f8c4 --- /dev/null +++ b/verify/expected/rich-span.android.otlp.json @@ -0,0 +1,191 @@ +{ + "resourceSpans": [ + { + "resource": { + "attributes": [ + { + "key": "service.name", + "value": { + "stringValue": "verify" + } + } + ] + }, + "scopeSpans": [ + { + "scope": { + "name": "verify.rich", + "version": "1.2.3", + "attributes": [ + { + "key": "scope.key", + "value": { + "stringValue": "scope-value" + } + } + ] + }, + "spans": [ + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000001", + "name": "rich", + "kind": 3, + "startTimeUnixNano": "1767225600000000000", + "endTimeUnixNano": "1767225600000100000", + "attributes": [ + { + "key": "bool", + "value": { + "boolValue": true + } + }, + { + "key": "bools", + "value": { + "arrayValue": { + "values": [ + { + "boolValue": true + }, + { + "boolValue": false + } + ] + } + } + }, + { + "key": "double", + "value": { + "doubleValue": 1.5 + } + }, + { + "key": "doubles", + "value": { + "arrayValue": { + "values": [ + { + "doubleValue": 1.5 + }, + { + "doubleValue": 2.5 + } + ] + } + } + }, + { + "key": "int", + "value": { + "intValue": "42" + } + }, + { + "key": "ints", + "value": { + "arrayValue": { + "values": [ + { + "intValue": "1" + }, + { + "intValue": "2" + }, + { + "intValue": "3" + } + ] + } + } + }, + { + "key": "str", + "value": { + "stringValue": "zażółć 🚀" + } + }, + { + "key": "strs", + "value": { + "arrayValue": { + "values": [ + { + "stringValue": "a" + }, + { + "stringValue": "b" + } + ] + } + } + } + ], + "events": [ + { + "timeUnixNano": "1767225600000010000", + "name": "first", + "attributes": [ + { + "key": "event.key", + "value": { + "stringValue": "e1" + } + }, + { + "key": "event.n", + "value": { + "intValue": "1" + } + } + ] + }, + { + "timeUnixNano": "1767225600000020000", + "name": "second", + "attributes": [ + { + "key": "event.ok", + "value": { + "boolValue": true + } + } + ] + } + ], + "links": [ + { + "traceId": "0f111111111111111111111111111111", + "spanId": "0f22222222222222", + "traceState": "k=v", + "attributes": [ + { + "key": "link.key", + "value": { + "stringValue": "link-value" + } + }, + { + "key": "link.n", + "value": { + "intValue": "7" + } + } + ], + "flags": 257 + } + ], + "status": { + "message": "boom", + "code": 2 + }, + "flags": 257 + } + ], + "schemaUrl": "https://opentelemetry.io/schemas/1.40.0" + } + ] + } + ] +} diff --git a/verify/expected/root-no-leak.android.otlp.json b/verify/expected/root-no-leak.android.otlp.json new file mode 100644 index 0000000..b72d020 --- /dev/null +++ b/verify/expected/root-no-leak.android.otlp.json @@ -0,0 +1,76 @@ +{ + "resourceSpans": [ + { + "resource": { + "attributes": [ + { + "key": "service.name", + "value": { + "stringValue": "verify" + } + } + ] + }, + "scopeSpans": [ + { + "scope": { + "name": "verify" + }, + "spans": [ + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000001", + "name": "scoped", + "kind": 1, + "startTimeUnixNano": "1767225600000000000", + "endTimeUnixNano": "1767225600000020000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000002", + "parentSpanId": "0a00000000000001", + "name": "scoped.child", + "kind": 1, + "startTimeUnixNano": "1767225600000010000", + "endTimeUnixNano": "1767225600000011000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000002", + "spanId": "0a00000000000003", + "name": "after.sync", + "kind": 1, + "startTimeUnixNano": "1767225600000030000", + "endTimeUnixNano": "1767225600000031000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000003", + "spanId": "0a00000000000004", + "name": "after.await", + "kind": 1, + "startTimeUnixNano": "1767225600000040000", + "endTimeUnixNano": "1767225600000041000", + "status": {}, + "flags": 257 + }, + { + "traceId": "0a000000000000000000000000000004", + "spanId": "0a00000000000005", + "name": "after.timeout", + "kind": 1, + "startTimeUnixNano": "1767225600000050000", + "endTimeUnixNano": "1767225600000051000", + "status": {}, + "flags": 257 + } + ] + } + ] + } + ] +} diff --git a/verify/harness/nativeReplay.ts b/verify/harness/nativeReplay.ts new file mode 100644 index 0000000..2b9d633 --- /dev/null +++ b/verify/harness/nativeReplay.ts @@ -0,0 +1,49 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import {spawn} from 'node:child_process'; +import {startCollector} from './collector'; +import {compareToExpected, type Platform} from './compare'; + +const root = path.join(import.meta.dirname, '..', '..'); +const artifacts = path.join(root, 'verify', 'artifacts'); + +// The collector must keep serving while the native tests run, so no spawnSync (ctx.sh) here. +const run = (cmd: string, args: string[], cwd: string, env: NodeJS.ProcessEnv) => + new Promise((ok, fail) => + spawn(cmd, args, {cwd, env, stdio: 'inherit'}).on('error', fail) + .on('exit', (c, sig) => (c === 0 ? ok() : fail(new Error(`${cmd} exited ${c ?? sig}`)))), + ); + +/** + * Replays every verify/fixtures/.handoff.json through a native core: starts a collector on a free port, runs + * `cmd` with VERIFY_COLLECTOR set, then compares each `..otlp.json` artifact (shape first). + */ +export async function replayFixtures(platform: Platform, cmd: string, args: string[], cwd: string) { + const names = fs.readdirSync(path.join(root, 'verify', 'fixtures')) + .filter(f => f.endsWith('.handoff.json')) + .map(f => f.slice(0, -'.handoff.json'.length)) + .sort(); + for (const n of names) fs.rmSync(path.join(artifacts, `${n}.${platform}.otlp.json`), {force: true}); + const collector = await startCollector({port: 0}); + try { + // TRACEPARENT unset: opentelemetry-swift adopts it as the parent of every root span (VERIFY.md). + await run(cmd, args, cwd, {...process.env, TRACEPARENT: undefined, VERIFY_COLLECTOR: collector.url}); + } finally { + await collector.close(); + } + const failed: string[] = []; + for (const n of names) { + const f = path.join(artifacts, `${n}.${platform}.otlp.json`); + if (!fs.existsSync(f)) throw new Error(`${n}: the ${platform} test exported nothing (missing ${f})`); + const {ok, report} = compareToExpected(n, platform, JSON.parse(fs.readFileSync(f, 'utf8'))); + if (report) console.log(report); + if (!ok) failed.push(n); + } + // R11: configured export headers reach the collector + const raw = path.join(artifacts, 'raw', `export-headers.${platform}`); + const hdr = fs.readdirSync(raw).filter(f => f.endsWith('.headers.json')); + if (!hdr.length || !hdr.every(f => JSON.parse(fs.readFileSync(path.join(raw, f), 'utf8'))['x-api-key'] === 'test')) + failed.push('export-headers (x-api-key: test missing in headers.json)'); + if (failed.length) throw new Error(`${platform} mismatch: ${failed.join(', ')}`); + return names.length; +} diff --git a/verify/stages/fast-jvm.ts b/verify/stages/fast-jvm.ts new file mode 100644 index 0000000..248ad2a --- /dev/null +++ b/verify/stages/fast-jvm.ts @@ -0,0 +1,16 @@ +import path from 'node:path'; +import type {Stage} from '../run'; +import {replayFixtures} from '../harness/nativeReplay'; + +const stage: Stage = { + name: 'fast-jvm', + order: 25, + e2e: false, + async run() { + const cwd = path.join(import.meta.dirname, '..', '..', 'android', 'core-jvm'); + const n = await replayFixtures('android', './gradlew', ['test', '--console=plain', '-q'], cwd); + console.log(`fast-jvm: ${n} fixtures match their android files`); + }, +}; + +export default stage;