From 8c0885e780c9e598e00f4ee5c3d6cab7d8c982be Mon Sep 17 00:00:00 2001 From: Adam Horodyski Date: Wed, 25 Nov 2026 04:55:27 +0100 Subject: [PATCH 1/4] feat(ios): Swift core over opentelemetry-swift, Nitro adapter, two pods and the Expo config plugin Layer 3 of the v0 stack (squashed from v0-impl, PR #20): - core (ios/Core): seam spans built into SpanData, config, endpoint and headers (envVarHeaders, gzip), explicit parenting, sticky init (R16) - adapter: HybridOtel and the public RNOtel helpers (RNOtel.start native-first init) - ReactNativeOpenTelemetryCore pod + the Nitro adapter pod (R24); app.plugin.js adds the Core pod line for Expo - Package.swift + verify stage fast-swift: every hand-off fixture through the Swift core, compared to *.ios.otlp.json - static: the Swift packageVersion must match package.json Co-Authored-By: Claude Opus 5.5 --- Package.swift | 29 +++ ReactNativeOpenTelemetry.podspec | 47 +++-- ReactNativeOpenTelemetryCore.podspec | 37 ++++ app.plugin.js | 25 +++ ios/Adapter/HybridOtel.swift | 59 ++++-- ios/Core/Attributes.swift | 20 ++ ios/Core/CoreConfig.swift | 20 ++ ios/Core/Endpoint.swift | 18 ++ ios/Core/OtelCore.swift | 106 ++++++++++ ios/Core/Parenting.swift | 24 +++ ios/Core/SeamModel.swift | 97 +++++++++ ios/Core/SpanDataBuilder.swift | 114 +++++++++++ ios/CoreTests/AttributesTests.swift | 40 ++++ ios/CoreTests/EndpointTests.swift | 11 ++ ios/CoreTests/FixtureExportTests.swift | 41 ++++ ios/CoreTests/FixtureJson.swift | 85 ++++++++ ios/CoreTests/InitTests.swift | 74 +++++++ ios/CoreTests/ParentingTests.swift | 49 +++++ ios/CoreTests/TimeRoundTripTests.swift | 37 ++++ ios/RNOtel/RNOtel.swift | 61 ++++++ ios/RNOtel/RNOtelConfig.swift | 22 +++ package.json | 5 + react-native.config.js | 5 +- verify/expected/async-generator.ios.otlp.json | 74 +++++++ .../expected/background-flush.ios.otlp.json | 34 ++++ .../batching-shared-queue.ios.otlp.json | 63 ++++++ verify/expected/captured-then.ios.otlp.json | 53 +++++ verify/expected/collector-down.ios.otlp.json | 34 ++++ .../concurrent-interleaved.ios.otlp.json | 92 +++++++++ .../expected/cross-js-to-native.ios.otlp.json | 51 +++++ .../expected/cross-native-to-js.ios.otlp.json | 51 +++++ .../expected/error-in-callback.ios.otlp.json | 63 ++++++ .../event-emitter-listener.ios.otlp.json | 44 +++++ verify/expected/export-headers.ios.otlp.json | 34 ++++ .../expected/flush-after-reload.ios.otlp.json | 34 ++++ verify/expected/handoff-basic.ios.otlp.json | 42 ++++ .../expected/interval-new-root.ios.otlp.json | 62 ++++++ .../native-init-failure.ios.otlp.json | 3 + .../expected/nest-after-await.ios.otlp.json | 44 +++++ .../nest-promise-all-race.ios.otlp.json | 84 ++++++++ verify/expected/nest-raf.ios.otlp.json | 44 +++++ .../nest-timers-microtasks.ios.otlp.json | 84 ++++++++ .../never-settling-promise.ios.otlp.json | 62 ++++++ verify/expected/odd-attributes.ios.otlp.json | 66 +++++++ verify/expected/rich-span.ios.otlp.json | 187 ++++++++++++++++++ verify/expected/root-no-leak.ios.otlp.json | 71 +++++++ verify/expected/smoke-js.ios.otlp.json | 34 ++++ verify/stages/fast-swift.ts | 9 +- verify/stages/static.ts | 7 + verify/static/expoPlugin.test.ts | 13 ++ verify/static/packContents.test.ts | 2 +- verify/static/packContents.ts | 2 +- 52 files changed, 2425 insertions(+), 44 deletions(-) create mode 100644 Package.swift create mode 100644 ReactNativeOpenTelemetryCore.podspec create mode 100644 app.plugin.js create mode 100644 ios/Core/Attributes.swift create mode 100644 ios/Core/CoreConfig.swift create mode 100644 ios/Core/Endpoint.swift create mode 100644 ios/Core/OtelCore.swift create mode 100644 ios/Core/Parenting.swift create mode 100644 ios/Core/SeamModel.swift create mode 100644 ios/Core/SpanDataBuilder.swift create mode 100644 ios/CoreTests/AttributesTests.swift create mode 100644 ios/CoreTests/EndpointTests.swift create mode 100644 ios/CoreTests/FixtureExportTests.swift create mode 100644 ios/CoreTests/FixtureJson.swift create mode 100644 ios/CoreTests/InitTests.swift create mode 100644 ios/CoreTests/ParentingTests.swift create mode 100644 ios/CoreTests/TimeRoundTripTests.swift create mode 100644 ios/RNOtel/RNOtel.swift create mode 100644 ios/RNOtel/RNOtelConfig.swift create mode 100644 verify/expected/async-generator.ios.otlp.json create mode 100644 verify/expected/background-flush.ios.otlp.json create mode 100644 verify/expected/batching-shared-queue.ios.otlp.json create mode 100644 verify/expected/captured-then.ios.otlp.json create mode 100644 verify/expected/collector-down.ios.otlp.json create mode 100644 verify/expected/concurrent-interleaved.ios.otlp.json create mode 100644 verify/expected/cross-js-to-native.ios.otlp.json create mode 100644 verify/expected/cross-native-to-js.ios.otlp.json create mode 100644 verify/expected/error-in-callback.ios.otlp.json create mode 100644 verify/expected/event-emitter-listener.ios.otlp.json create mode 100644 verify/expected/export-headers.ios.otlp.json create mode 100644 verify/expected/flush-after-reload.ios.otlp.json create mode 100644 verify/expected/handoff-basic.ios.otlp.json create mode 100644 verify/expected/interval-new-root.ios.otlp.json create mode 100644 verify/expected/native-init-failure.ios.otlp.json create mode 100644 verify/expected/nest-after-await.ios.otlp.json create mode 100644 verify/expected/nest-promise-all-race.ios.otlp.json create mode 100644 verify/expected/nest-raf.ios.otlp.json create mode 100644 verify/expected/nest-timers-microtasks.ios.otlp.json create mode 100644 verify/expected/never-settling-promise.ios.otlp.json create mode 100644 verify/expected/odd-attributes.ios.otlp.json create mode 100644 verify/expected/rich-span.ios.otlp.json create mode 100644 verify/expected/root-no-leak.ios.otlp.json create mode 100644 verify/expected/smoke-js.ios.otlp.json create mode 100644 verify/static/expoPlugin.test.ts diff --git a/Package.swift b/Package.swift new file mode 100644 index 0000000..56b99c0 --- /dev/null +++ b/Package.swift @@ -0,0 +1,29 @@ +// swift-tools-version:6.0 +// The pure Swift core (ios/Core) and its tests, for `swift test` on the host (`bun verify fast-swift`). +// Apps never use this: CocoaPods builds ios/Core from ReactNativeOpenTelemetryCore.podspec, with the same opentelemetry-swift versions. +import Foundation +import PackageDescription + +// ios/CoreTests is not in the npm package (package.json `files`), so the test target exists only in the repo. +let hasTests = FileManager.default.fileExists(atPath: URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("ios/CoreTests").path) + +let package = Package( + name: "ReactNativeOpenTelemetry", + platforms: [.iOS(.v15), .macOS(.v12)], + products: [.library(name: "OtelCore", targets: ["OtelCore"])], + dependencies: [ + .package(url: "https://github.com/open-telemetry/opentelemetry-swift", .upToNextMinor(from: "2.6.0")), + .package(url: "https://github.com/open-telemetry/opentelemetry-swift-core", .upToNextMinor(from: "2.6.0")), + ], + targets: [ + .target( + name: "OtelCore", + dependencies: [ + .product(name: "OpenTelemetryProtocolExporterHTTP", package: "opentelemetry-swift"), + .product(name: "OpenTelemetrySdk", package: "opentelemetry-swift-core"), + ], + path: "ios/Core" + ), + ] + (hasTests ? [.testTarget(name: "OtelCoreTests", dependencies: ["OtelCore"], path: "ios/CoreTests")] : []), + swiftLanguageModes: [.v5] +) diff --git a/ReactNativeOpenTelemetry.podspec b/ReactNativeOpenTelemetry.podspec index 85d382e..a24c888 100644 --- a/ReactNativeOpenTelemetry.podspec +++ b/ReactNativeOpenTelemetry.podspec @@ -2,6 +2,7 @@ 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 (R24, spec §4.2). Pod::Spec.new do |s| s.name = "ReactNativeOpenTelemetry" s.version = package["version"] @@ -13,32 +14,36 @@ Pod::Spec.new do |s| s.platforms = { :ios => min_ios_version_supported } s.source = { :git => "https://github.com/callstack/react-native-open-telemetry.git", :tag => "#{s.version}" } - s.source_files = [ - "ios/Core/**/*.swift", - "ios/Adapter/**/*.swift", - ] - - # Test mode is a build flag, never API: `OTEL_TEST_MODE=1 pod install`. - if ENV['OTEL_TEST_MODE'] == '1' - s.pod_target_xcconfig = { - 'SWIFT_ACTIVE_COMPILATION_CONDITIONS' => '$(inherited) OTEL_TEST_MODE', - } - end + 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) + :script => %Q{set -e +if [ -f "${PODS_CONFIGURATION_BUILD_DIR}/ReactNativeOpenTelemetryCore.modulemap" ]; then + mkdir -p "${PODS_CONFIGURATION_BUILD_DIR}/ReactNativeOpenTelemetryCore" + echo 'extern module ReactNativeOpenTelemetryCore "../ReactNativeOpenTelemetryCore.modulemap"' > "#{core_map}" +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) - # opentelemetry-swift 2.6 moved OpenTelemetryApi/OpenTelemetrySdk into opentelemetry-swift-core. - spm_dependency(s, - url: 'https://github.com/open-telemetry/opentelemetry-swift', - requirement: { kind: 'upToNextMinorVersion', minimumVersion: '2.6.0' }, - products: ['OpenTelemetryProtocolExporterHTTP']) - spm_dependency(s, - url: 'https://github.com/open-telemetry/opentelemetry-swift-core', - requirement: { kind: 'upToNextMinorVersion', minimumVersion: '2.6.0' }, - products: ['OpenTelemetrySdk']) - + s.dependency 'ReactNativeOpenTelemetryCore', s.version.to_s s.dependency 'React-jsi' s.dependency 'React-callinvoker' install_modules_dependencies(s) diff --git a/ReactNativeOpenTelemetryCore.podspec b/ReactNativeOpenTelemetryCore.podspec new file mode 100644 index 0000000..f206f85 --- /dev/null +++ b/ReactNativeOpenTelemetryCore.podspec @@ -0,0 +1,37 @@ +require "json" + +package = JSON.parse(File.read(File.join(__dir__, "package.json"))) + +# Pure Swift (R24): the core and the public `RNOtel` API, no Nitro and no C++ interop, so an app's Swift +# `AppDelegate` can `import ReactNativeOpenTelemetryCore`. The Nitro adapter pod (ReactNativeOpenTelemetry) depends on it. +# Autolinking links one podspec per package: apps add `pod 'ReactNativeOpenTelemetryCore', :path => ''`. +Pod::Spec.new do |s| + s.name = "ReactNativeOpenTelemetryCore" + s.version = package["version"] + s.summary = package["description"] + s.homepage = package["homepage"] + s.license = package["license"] + s.authors = package["author"] + + s.platforms = { :ios => min_ios_version_supported } + s.source = { :git => "https://github.com/callstack/react-native-open-telemetry.git", :tag => "#{s.version}" } + s.swift_version = "5.0" + + s.source_files = ["ios/Core/**/*.swift", "ios/RNOtel/**/*.swift"] + + # `package` declarations are shared with the adapter pod through one Swift package name. + # Test mode is a build flag, never API: `OTEL_TEST_MODE=1 pod install`. + s.pod_target_xcconfig = { + 'OTHER_SWIFT_FLAGS' => '$(inherited) -package-name ReactNativeOpenTelemetry', + }.merge(ENV['OTEL_TEST_MODE'] == '1' ? { 'SWIFT_ACTIVE_COMPILATION_CONDITIONS' => '$(inherited) OTEL_TEST_MODE' } : {}) + + # opentelemetry-swift 2.6 moved OpenTelemetryApi/OpenTelemetrySdk into opentelemetry-swift-core. + spm_dependency(s, + url: 'https://github.com/open-telemetry/opentelemetry-swift', + requirement: { kind: 'upToNextMinorVersion', minimumVersion: '2.6.0' }, + products: ['OpenTelemetryProtocolExporterHTTP']) + spm_dependency(s, + url: 'https://github.com/open-telemetry/opentelemetry-swift-core', + requirement: { kind: 'upToNextMinorVersion', minimumVersion: '2.6.0' }, + products: ['OpenTelemetrySdk']) +end diff --git a/app.plugin.js b/app.plugin.js new file mode 100644 index 0000000..0aff954 --- /dev/null +++ b/app.plugin.js @@ -0,0 +1,25 @@ +// Expo config plugin: `"plugins": ["react-native-open-telemetry"]`. It does one thing. Autolinking links one podspec per +// package (the Nitro adapter), and the adapter needs the pure Swift core pod beside it, so this adds +// `pod 'ReactNativeOpenTelemetryCore'` to the generated Podfile. Bare apps add the same line by hand (README). +const path = require('path'); + +const POD = "pod 'ReactNativeOpenTelemetryCore'"; + +/** Adds the core pod to the first app target; idempotent. */ +function addCorePod(podfile, podPath) { + if (podfile.includes(POD)) return podfile; + const out = podfile.replace(/^(target '.+' do\n)/m, `$1 ${POD}, :path => '${podPath}'\n`); + if (out === podfile) throw new Error('react-native-open-telemetry: no `target ... do` in the Podfile; add the core pod by hand'); + return out; +} + +// The app's own `expo`, not one beside this file: a linked or pnpm-installed package has none of its own. +const configPlugins = config => + require(require.resolve('expo/config-plugins', {paths: [config._internal?.projectRoot ?? process.cwd(), __dirname]})); + +module.exports = config => + configPlugins(config).withPodfile(config, c => { + c.modResults.contents = addCorePod(c.modResults.contents, path.relative(c.modRequest.platformProjectRoot, __dirname)); + return c; + }); +module.exports.addCorePod = addCorePod; diff --git a/ios/Adapter/HybridOtel.swift b/ios/Adapter/HybridOtel.swift index 1bfe68e..07ca847 100644 --- a/ios/Adapter/HybridOtel.swift +++ b/ios/Adapter/HybridOtel.swift @@ -1,29 +1,56 @@ import Foundation import NitroModules -import OpenTelemetryProtocolExporterHttp -import OpenTelemetrySdk +import ReactNativeOpenTelemetryCore -/// Tracer-bullet stub (Task 7): proves the seam and the opentelemetry-swift link; the real adapter is Task 25. +/// The seam, mapped 1:1 onto the Swift core (pod `ReactNativeOpenTelemetryCore`, R24). class HybridOtel: HybridOtelSpec { func initialize(config: SeamConfig?) throws -> SeamInitResult { - // Touch opentelemetry-swift so a broken package link fails here, not in Task 25. - OtlpHttpTraceExporter().shutdown() - #if OTEL_TEST_MODE - let testMode = true - #else - let testMode = false - #endif - return SeamInitResult(alreadyInitialized: false, testMode: testMode, error: nil) + let r = RNOtel.initialize(config.map { + CoreConfig(serviceName: $0.serviceName, serviceVersion: $0.serviceVersion, + resourceAttributes: attrs($0.resourceAttributes), exportUrl: $0.exportUrl, + exportHeaders: Dictionary($0.exportHeaders.compactMap { h in h.value.asType(String.self).map { (h.key, $0) } }, + uniquingKeysWith: { _, last in last })) + }) + return SeamInitResult(alreadyInitialized: r.alreadyInitialized, testMode: r.testMode, error: r.error) } + /// JS thread: copy the structs and enqueue; SpanData is built on the export queue. func handOff(spans: [SeamSpan]) throws { - let attrs = spans.reduce(0) { $0 + $1.attributes.count } - let events = spans.reduce(0) { $0 + $1.events.count } - let links = spans.reduce(0) { $0 + $1.links.count } - NSLog("%@", "RNOtel handOff spans=\(spans.count) attrs=\(attrs) events=\(events) links=\(links)") + OtelCore.instance?.handOff(spans.map(span)) } + /// Off the JS thread (the flush blocks a global queue); resolves even when native never initialized. func flush(timeoutMs: Double) throws -> Promise { - return Promise.resolved() + Promise.parallel { _ = OtelCore.instance?.flush(timeoutMs: timeoutMs) } + } + + private func span(_ s: SeamSpan) -> CoreSpan { + CoreSpan(context: ctx(s.context), parentSpanId: s.parentSpanId, name: s.name, kind: int(s.kind), + start: HrTime(s.start), end: HrTime(s.end), attributes: attrs(s.attributes), + events: s.events.map { CoreEvent(name: $0.name, time: HrTime($0.time), attributes: attrs($0.attributes)) }, + links: s.links.map { CoreLink(context: ctx($0.context), attributes: attrs($0.attributes)) }, + status: CoreStatus(code: int(s.status.code), message: s.status.message), + scope: CoreScope(name: s.scope.name, version: s.scope.version, schemaUrl: s.scope.schemaUrl, + attributes: attrs(s.scope.attributes))) + } + + private func ctx(_ c: SeamSpanContext) -> CoreSpanContext { + CoreSpanContext(traceId: c.traceId, spanId: c.spanId, traceFlags: int(c.traceFlags), traceState: c.traceState) + } + + /// Never traps on the JS thread (Int(Double) does on NaN or out of range). + private func int(_ d: Double) -> Int { Int(exactly: d.rounded(.towardZero)) ?? 0 } + + private func attrs(_ a: [SeamAttribute]) -> [CoreAttribute] { a.map { CoreAttribute(key: $0.key, value: value($0.value)) } } + + private func value(_ v: AttrValue) -> CoreValue { + switch v { + case let .first(b): return .bool(b) + case let .second(b): return .bools(b) + case let .third(s): return .strings(s) + case let .fourth(n): return .numbers(n) + case let .fifth(s): return .string(s) + case let .sixth(n): return .number(n) + } } } diff --git a/ios/Core/Attributes.swift b/ios/Core/Attributes.swift new file mode 100644 index 0000000..78fd018 --- /dev/null +++ b/ios/Core/Attributes.swift @@ -0,0 +1,20 @@ +import OpenTelemetryApi + +// 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, Kotlin, Swift. +func attributes(of list: [CoreAttribute]) -> [String: AttributeValue] { + var out = [String: AttributeValue](minimumCapacity: list.count) + for a in list { + switch a.value { + case let .string(v): out[a.key] = .string(v) + case let .bool(v): out[a.key] = .bool(v) + case let .number(v): out[a.key] = isLong(v) ? .int(Int(v)) : .double(v) + case let .strings(v): out[a.key] = .stringArray(v) + case let .bools(v): out[a.key] = .boolArray(v) + case let .numbers(v): out[a.key] = v.allSatisfy(isLong) ? .intArray(v.map { Int($0) }) : .doubleArray(v) + } + } + return out +} diff --git a/ios/Core/CoreConfig.swift b/ios/Core/CoreConfig.swift new file mode 100644 index 0000000..b5ce3dd --- /dev/null +++ b/ios/Core/CoreConfig.swift @@ -0,0 +1,20 @@ +package struct CoreConfig { + var serviceName: String + var serviceVersion: String? = nil + var resourceAttributes: [CoreAttribute] = [] + /// Base URL; see `tracesUrl`. + var exportUrl: String + var exportHeaders: [String: String] = [:] + package init(serviceName: String, serviceVersion: String? = nil, resourceAttributes: [CoreAttribute] = [], + exportUrl: String, exportHeaders: [String: String] = [:]) { + self.serviceName = serviceName; self.serviceVersion = serviceVersion; self.resourceAttributes = resourceAttributes + self.exportUrl = exportUrl; self.exportHeaders = exportHeaders + } +} + +/// Mirrors the seam's `SeamInitResult`. +package struct InitResult: Equatable { + package var alreadyInitialized: Bool + package var testMode: Bool + package var error: String? = nil +} diff --git a/ios/Core/Endpoint.swift b/ios/Core/Endpoint.swift new file mode 100644 index 0000000..7f2628a --- /dev/null +++ b/ios/Core/Endpoint.swift @@ -0,0 +1,18 @@ +import Foundation + +/// Base URL -> traces endpoint: `/v1/traces` is appended unless already present (same rule as JS and Android). +func tracesUrl(_ exportUrl: String) -> String { + var base = Substring(exportUrl) + while base.hasSuffix("/") { base = base.dropLast() } + return base.hasSuffix("/v1/traces") ? String(base) : base + "/v1/traces" +} + +/// 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 { + return "invalid exportUrl \"\(url)\": expected http(s)://host[:port]" + } + return nil +} diff --git a/ios/Core/OtelCore.swift b/ios/Core/OtelCore.swift new file mode 100644 index 0000000..2c22b4e --- /dev/null +++ b/ios/Core/OtelCore.swift @@ -0,0 +1,106 @@ +import Foundation +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 + private var s = 0 + private func pad(_ n: Int, _ w: Int) -> String { "0b" + String(repeating: "0", count: w - String(n).count) + String(n) } + func generateTraceId() -> TraceId { lock.withLock { t += 1; return TraceId(fromHexString: pad(t, 30)) } } + func generateSpanId() -> SpanId { lock.withLock { s += 1; return SpanId(fromHexString: pad(s, 14)) } } +} + +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? + private let build: () -> OtlpHttpTraceExporter? + init(_ build: @escaping () -> OtlpHttpTraceExporter?) { self.build = build } + private var d: OtlpHttpTraceExporter? { lock.withLock { if built == nil { built = build() }; return built } } + func export(spans: [SpanData], explicitTimeout: TimeInterval?) -> SpanExporterResultCode { d?.export(spans: spans, explicitTimeout: explicitTimeout) ?? .failure } + func flush(explicitTimeout: TimeInterval?) -> SpanExporterResultCode { d?.flush(explicitTimeout: explicitTimeout) ?? .failure } + func shutdown(explicitTimeout: TimeInterval?) { d?.shutdown(explicitTimeout: explicitTimeout) } + func export(spans: [SpanData], explicitTimeout: TimeInterval?) async -> SpanExporterResultCode { + guard let d else { return .failure } + return await d.export(spans: spans, explicitTimeout: explicitTimeout) + } + func flush(explicitTimeout: TimeInterval?) async -> SpanExporterResultCode { + guard let d else { return .failure } + return await d.flush(explicitTimeout: explicitTimeout) + } + func shutdown(explicitTimeout: TimeInterval?) async { await d?.shutdown(explicitTimeout: explicitTimeout) } +} + +package final class OtelCore { + /// The one resource of the app; in test mode built from config only (no `telemetry.*`). + let resource: Resource + /// The native TracerProvider; JS spans join its batch processor. + let tracerProvider: TracerProviderSdk + private let bsp: BatchSpanProcessor + private let exporter: LazyExporter + + init(config: CoreConfig, testMode: Bool = false, distroVersion: String = "unknown") { + var attrs = attributes(of: config.resourceAttributes) + attrs["service.name"] = .string(config.serviceName) + if let v = config.serviceVersion { attrs["service.version"] = .string(v) } + if !testMode { + attrs["telemetry.distro.name"] = .string(distroName) + attrs["telemetry.distro.version"] = .string(distroVersion) + } + 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: tracesUrl(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 (Task 27) + bsp = BatchSpanProcessor(spanExporter: exporter, scheduleDelay: testMode ? 120 : 5) // 5 s: upstream's default + let b = TracerProviderBuilder().with(resource: resource).add(spanProcessor: bsp) + tracerProvider = (testMode ? b.with(idGenerator: SequentialIds()) : b).build() + } + + /// JS-thread work: wrap and enqueue only; SpanData is built on the export queue. + package func handOff(_ spans: [CoreSpan]) { + for s in spans { bsp.onEnd(span: JsReadableSpan(s, resource: resource)) } + } + + /// 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) + return exporter.flush(explicitTimeout: max(deadline.timeIntervalSinceNow, 0.001)) == .success + } + + private static let lock = NSLock() + private static var state: InitResult? + package private(set) static var instance: OtelCore? + + /// 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. + @discardableResult + package static func initialize(_ config: CoreConfig?, testMode: Bool = false, distroVersion: String = "unknown") -> InitResult { + lock.withLock { + if var s = state { s.alreadyInitialized = true; return s } + guard let config else { return InitResult(alreadyInitialized: false, testMode: testMode, error: "not initialized: no config") } + let err = validateExportUrl(config.exportUrl) + let result = InitResult(alreadyInitialized: false, testMode: testMode, error: err) + if err == nil { instance = OtelCore(config: config, testMode: testMode, distroVersion: distroVersion) } + state = result + return result + } + } + + static func resetForTest() { lock.withLock { state = nil; instance = nil } } +} diff --git a/ios/Core/Parenting.swift b/ios/Core/Parenting.swift new file mode 100644 index 0000000..ec26af6 --- /dev/null +++ b/ios/Core/Parenting.swift @@ -0,0 +1,24 @@ +import Foundation +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), + let f = Range(m.range(at: 3), in: traceparent) else { return nil } + let sc = SpanContext.create(traceId: TraceId(fromHexString: String(traceparent[t])), + spanId: SpanId(fromHexString: String(traceparent[s])), + traceFlags: TraceFlags(fromHexString: String(traceparent[f])), + traceState: TraceState()) + return sc.isValid ? sc : nil +} + +func traceparent(of c: SpanContext) -> String { + "00-\(c.traceId.hexString)-\(c.spanId.hexString)-\(c.traceFlags.hexString)" +} diff --git a/ios/Core/SeamModel.swift b/ios/Core/SeamModel.swift new file mode 100644 index 0000000..6f5d957 --- /dev/null +++ b/ios/Core/SeamModel.swift @@ -0,0 +1,97 @@ +import Foundation + +// Mirrors the Nitro seam (src/native/Otel.nitro.ts) without Nitro types; the iOS adapter converts. +// `package` access: the adapter pod (ReactNativeOpenTelemetry, Nitro) builds these across modules (R24); apps never see +// them. Swift synthesizes only internal memberwise initializers, hence the explicit ones. + +/// OTel HrTime `[seconds, nanos]`. +package struct HrTime { + let seconds: Double + let nanos: Double + + /// Never traps on the JS thread: missing elements read as 0 (C4). + package init(_ a: [Double]) { + seconds = a.count > 0 ? a[0] : 0 + nanos = a.count > 1 ? a[1] : 0 + } + + /// R22: `Date` holds a Double of seconds, so whole µs come back on a ~256 ns grid (verify/VERIFY.md). + var date: Date { Date(timeIntervalSince1970: seconds + nanos / 1e9) } +} + +package enum CoreValue { + case string(String) + case bool(Bool) + case number(Double) + case strings([String]) + case bools([Bool]) + case numbers([Double]) +} + +package struct CoreAttribute { + let key: String + let value: CoreValue + package init(key: String, value: CoreValue) { self.key = key; self.value = value } +} + +package struct CoreSpanContext { + let traceId: String + let spanId: String + let traceFlags: Int + var traceState: String? = nil + package init(traceId: String, spanId: String, traceFlags: Int, traceState: String? = nil) { + self.traceId = traceId; self.spanId = spanId; self.traceFlags = traceFlags; self.traceState = traceState + } +} + +package struct CoreEvent { + let name: String + let time: HrTime + let attributes: [CoreAttribute] + package init(name: String, time: HrTime, attributes: [CoreAttribute]) { + self.name = name; self.time = time; self.attributes = attributes + } +} + +package struct CoreLink { + let context: CoreSpanContext + let attributes: [CoreAttribute] + package init(context: CoreSpanContext, attributes: [CoreAttribute]) { self.context = context; self.attributes = attributes } +} + +package struct CoreScope { + let name: String + let version: String? + let schemaUrl: String? + let attributes: [CoreAttribute] + package init(name: String, version: String?, schemaUrl: String?, attributes: [CoreAttribute]) { + self.name = name; self.version = version; self.schemaUrl = schemaUrl; self.attributes = attributes + } +} + +package struct CoreStatus { + let code: Int + let message: String? + package init(code: Int, message: String?) { self.code = code; self.message = message } +} + +package struct CoreSpan { + let context: CoreSpanContext + let parentSpanId: String? + let name: String + /// `@opentelemetry/api` SpanKind (INTERNAL = 0). + let kind: Int + let start: HrTime + let end: HrTime + let attributes: [CoreAttribute] + let events: [CoreEvent] + let links: [CoreLink] + let status: CoreStatus + let scope: CoreScope + package init(context: CoreSpanContext, parentSpanId: String?, name: String, kind: Int, start: HrTime, end: HrTime, + attributes: [CoreAttribute], events: [CoreEvent], links: [CoreLink], status: CoreStatus, scope: CoreScope) { + self.context = context; self.parentSpanId = parentSpanId; self.name = name; self.kind = kind; self.start = start + self.end = end; self.attributes = attributes; self.events = events; self.links = links; self.status = status + self.scope = scope + } +} diff --git a/ios/Core/SpanDataBuilder.swift b/ios/Core/SpanDataBuilder.swift new file mode 100644 index 0000000..1fab4d8 --- /dev/null +++ b/ios/Core/SpanDataBuilder.swift @@ -0,0 +1,114 @@ +import Foundation +import OpenTelemetryApi +import OpenTelemetrySdk + +/// R21/C5: Swift's SpanKind cases are not in API order, so map the API value explicitly. Unknown -> INTERNAL. +func spanKind(_ k: Int) -> SpanKind { + switch k { + case 1: return .server + case 2: return .client + case 3: return .producer + case 4: return .consumer + default: return .internal + } +} + +/// API SpanStatusCode (UNSET 0, OK 1, ERROR 2). Unknown -> UNSET. +private func statusOf(_ s: CoreStatus) -> Status { + switch s.code { + case 1: return .ok + case 2: return .error(description: s.message ?? "") + default: return .unset + } +} + +private func traceState(_ s: String?) -> TraceState { + let entries = (s ?? "").split(separator: ",").compactMap { kv -> TraceState.Entry? in + guard let i = kv.firstIndex(of: "=") else { return nil } + return TraceState.Entry(key: kv[.. SpanContext { + SpanContext.create(traceId: TraceId(fromHexString: c.traceId), spanId: SpanId(fromHexString: c.spanId), + traceFlags: TraceFlags(fromByte: UInt8(truncatingIfNeeded: 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 (R19): the frozen `ReadableSpan` the native BatchSpanProcessor queues. + * 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: CoreSpan + private let resource: Resource + let context: SpanContext + + init(_ span: CoreSpan, resource: Resource) { + self.span = span + self.resource = resource + context = spanContext(span.context) + } + + var kind: SpanKind { spanKind(span.kind) } + var isRecording: Bool { false } + var hasEnded: Bool { true } + var latency: TimeInterval { span.end.date.timeIntervalSince(span.start.date) } + 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 { + InstrumentationScopeInfo(name: span.scope.name, version: span.scope.version, schemaUrl: span.scope.schemaUrl, + attributes: attributes(of: span.scope.attributes)) + } + + func getAttributes() -> [String: AttributeValue] { attributes(of: span.attributes) } + + func toSpanData() -> SpanData { + let attrs = getAttributes() + var dict = AttributesDictionary(capacity: max(attrs.count, 1)) + dict.updateValues(attributes: attrs) + let links = span.links.map { SpanData.Link(context: spanContext($0.context), attributes: attributes(of: $0.attributes)) } + let parent = span.parentSpanId.map { + SpanContext.create(traceId: context.traceId, spanId: SpanId(fromHexString: $0), traceFlags: context.traceFlags, traceState: context.traceState) + } + let end = span.end.date + let limits = SpanLimits() + .settingEventCountLimit(UInt(max(span.events.count, 1))) + .settingLinkCountLimit(UInt(max(links.count, 1))) + let sdk = SpanSdk.startSpan(context: context, name: span.name, instrumentationScopeInfo: instrumentationScopeInfo, + kind: kind, parentContext: parent, hasRemoteParent: false, spanLimits: limits, + spanProcessor: MultiSpanProcessor(spanProcessors: []), clock: FixedClock(now: end), + resource: resource, attributes: dict, links: links, totalRecordedLinks: links.count, + startTime: span.start.date) + for e in span.events { + sdk.addEvent(name: e.name, attributes: attributes(of: e.attributes), timestamp: e.time.date) + } + sdk.status = status + sdk.end(time: end) + return sdk.toSpanData() + } + + func setAttribute(key: String, value: AttributeValue?) {} + func setAttributes(_ attributes: [String: AttributeValue]) {} + func addEvent(name: String) {} + func addEvent(name: String, timestamp: Date) {} + func addEvent(name: String, attributes: [String: AttributeValue]) {} + func addEvent(name: String, attributes: [String: AttributeValue], timestamp: Date) {} + func addLink(spanContext: SpanContext, attributes: [String: AttributeValue]) {} + func recordException(_ exception: SpanException) {} + func recordException(_ exception: SpanException, timestamp: Date) {} + func recordException(_ exception: SpanException, attributes: [String: AttributeValue]) {} + func recordException(_ exception: SpanException, attributes: [String: AttributeValue], timestamp: Date) {} + func end() {} + func end(time: Date) {} +} diff --git a/ios/CoreTests/AttributesTests.swift b/ios/CoreTests/AttributesTests.swift new file mode 100644 index 0000000..8705edf --- /dev/null +++ b/ios/CoreTests/AttributesTests.swift @@ -0,0 +1,40 @@ +import OpenTelemetryApi +import XCTest +@testable import OtelCore + +final class AttributesTests: XCTestCase { + private func num(_ v: Double) -> AttributeValue? { attributes(of: [CoreAttribute(key: "k", value: .number(v))])["k"] } + + func testWholeIsLong() { XCTAssertEqual(num(1.0), .int(1)) } + func testFractionIsDouble() { XCTAssertEqual(num(1.5), .double(1.5)) } + func testBigWholeIsLong() { XCTAssertEqual(num(9.007199254740994E15), .int(9_007_199_254_740_994)) } + func testNanIsDouble() { + guard case let .double(d) = num(.nan) else { return XCTFail("not a double") } + XCTAssertTrue(d.isNaN) + } + func testInfIsDouble() { XCTAssertEqual(num(-.infinity), .double(-.infinity)) } + // C28: Number.isInteger(-0) is true, so -0 is intValue 0 (the reviewed odd-attributes contract) + func testNegZeroIsLong() { XCTAssertEqual(num(-0.0), .int(0)) } + func testBeyondLongIsDouble() { XCTAssertEqual(num(1e19), .double(1e19)) } + // 2^63 is the first double past Int64.max: Int(2^63) would trap + func testTwoTo63IsDouble() { XCTAssertEqual(num(9.223372036854775807E18), .double(9.223372036854775807E18)) } + + func testWholeArrayIsLongArray() { + XCTAssertEqual(attributes(of: [CoreAttribute(key: "k", value: .numbers([1, 2]))])["k"], .intArray([1, 2])) + } + + func testMixedArrayIsDoubleArray() { + XCTAssertEqual(attributes(of: [CoreAttribute(key: "k", value: .numbers([1, 2.5]))])["k"], .doubleArray([1, 2.5])) + } + + // C4: a short HrTime never traps on the JS thread + func testShortHrTimeReadsZero() { + XCTAssertEqual(HrTime([]).seconds, 0) + XCTAssertEqual(HrTime([5]).nanos, 0) + } + + // R21/C5: Swift's SpanKind cases are not in API order; map by value + func testKindByValue() { + XCTAssertEqual([0, 1, 2, 3, 4, 9, -1].map(spanKind), [.internal, .server, .client, .producer, .consumer, .internal, .internal]) + } +} diff --git a/ios/CoreTests/EndpointTests.swift b/ios/CoreTests/EndpointTests.swift new file mode 100644 index 0000000..99db45e --- /dev/null +++ b/ios/CoreTests/EndpointTests.swift @@ -0,0 +1,11 @@ +import XCTest +@testable import OtelCore + +final class EndpointTests: XCTestCase { + func testAppendsTracesPathUnlessPresent() { + for u in ["http://h:4318", "http://h:4318/", "http://h:4318/v1/traces", "http://h:4318/v1/traces/"] { + XCTAssertEqual(tracesUrl(u), "http://h:4318/v1/traces", u) + } + XCTAssertEqual(tracesUrl("http://h/base"), "http://h/base/v1/traces") + } +} diff --git a/ios/CoreTests/FixtureExportTests.swift b/ios/CoreTests/FixtureExportTests.swift new file mode 100644 index 0000000..f90075b --- /dev/null +++ b/ios/CoreTests/FixtureExportTests.swift @@ -0,0 +1,41 @@ +import Foundation +import XCTest +@testable import OtelCore + +/// Every seam fixture through the core into the live collector; fast-swift compares the `ios` artifacts in Node. +final class FixtureExportTests: XCTestCase { + private let collector = ProcessInfo.processInfo.environment["VERIFY_COLLECTOR"] ?? "" + private let fixtures = URL(fileURLWithPath: #filePath).deletingLastPathComponent() + .appendingPathComponent("../../verify/fixtures").standardizedFileURL + + private func control(_ path: String, _ body: [String: String] = [:]) throws { + var req = URLRequest(url: URL(string: "\(collector)/_verify/\(path)")!, timeoutInterval: 30) + req.httpMethod = "POST" + req.setValue("application/json", forHTTPHeaderField: "content-type") + req.httpBody = try JSONSerialization.data(withJSONObject: body) + let done = DispatchSemaphore(value: 0) + var status = 0 + URLSession.shared.dataTask(with: req) { _, res, _ in + status = (res as? HTTPURLResponse)?.statusCode ?? 0 + done.signal() + }.resume() + done.wait() + XCTAssertEqual(status, 200, "collector \(path)") + } + + func testEveryFixtureExports() throws { + try XCTSkipIf(collector.isEmpty, "VERIFY_COLLECTOR is not set: run through `bun verify fast-swift`") + let files = try FileManager.default.contentsOfDirectory(atPath: fixtures.path) + .filter { $0.hasSuffix(".handoff.json") }.sorted() + XCTAssertFalse(files.isEmpty) + for f in files { + let name = String(f.dropLast(".handoff.json".count)) + let (config, spans) = try FixtureJson.parse(Data(contentsOf: fixtures.appendingPathComponent(f)), exportUrl: collector) + try control("begin", ["scenario": name, "platform": "ios"]) + let core = OtelCore(config: config, testMode: true) + core.handOff(spans) + XCTAssertTrue(core.flush(timeoutMs: 10_000), "\(name): flush failed") + try control("end") + } + } +} diff --git a/ios/CoreTests/FixtureJson.swift b/ios/CoreTests/FixtureJson.swift new file mode 100644 index 0000000..54419eb --- /dev/null +++ b/ios/CoreTests/FixtureJson.swift @@ -0,0 +1,85 @@ +import Foundation +@testable import OtelCore + +/// Test reader for verify/fixtures/.handoff.json; NaN, ±Infinity and -0 arrive as {"$num": ""}. +enum FixtureJson { + static func parse(_ data: Data, exportUrl: String) throws -> (CoreConfig, [CoreSpan]) { + let root = try JSONSerialization.jsonObject(with: data) as! [String: Any] + let c = root["config"] as! [String: Any] + let config = CoreConfig( + serviceName: c["serviceName"] as! String, + serviceVersion: c["serviceVersion"] as? String, + resourceAttributes: attrs(c["resourceAttributes"]), + exportUrl: (c["exportUrl"] as! String).replacingOccurrences(of: "", with: exportUrl), + exportHeaders: Dictionary(attrs(c["exportHeaders"]).map { a -> (String, String) in + guard case let .string(v) = a.value else { fatalError("header \(a.key) is not a string") } + return (a.key, v) + }, uniquingKeysWith: { _, b in b }) + ) + return (config, (root["spans"] as! [[String: Any]]).map(span)) + } + + private static func isBool(_ v: Any) -> Bool { + guard let n = v as? NSNumber else { return false } + return CFGetTypeID(n) == CFBooleanGetTypeID() + } + + private static func num(_ v: Any) -> Double { + if let o = v as? [String: Any], let s = o["$num"] as? String { + switch s { + case "-0": return -0.0 + case "NaN": return .nan + case "Infinity": return .infinity + case "-Infinity": return -.infinity + default: fatalError("unknown $num \(s)") + } + } + return (v as! NSNumber).doubleValue + } + + private static func time(_ v: Any?) -> HrTime { HrTime((v as! [Any]).map(num)) } + + private static func value(_ v: Any) -> CoreValue { + if let a = v as? [Any] { + guard let first = a.first else { return .bools([]) } + if first is String { return .strings(a.map { $0 as! String }) } + if isBool(first) { return .bools(a.map { ($0 as! NSNumber).boolValue }) } + return .numbers(a.map(num)) + } + if let s = v as? String { return .string(s) } + if isBool(v) { return .bool((v as! NSNumber).boolValue) } + return .number(num(v)) + } + + private static func attrs(_ v: Any?) -> [CoreAttribute] { + (v as? [[String: Any]] ?? []).map { CoreAttribute(key: $0["key"] as! String, value: value($0["value"]!)) } + } + + private static func ctx(_ o: [String: Any]) -> CoreSpanContext { + CoreSpanContext(traceId: o["traceId"] as! String, spanId: o["spanId"] as! String, + traceFlags: (o["traceFlags"] as! NSNumber).intValue, traceState: o["traceState"] as? String) + } + + private static func span(_ o: [String: Any]) -> CoreSpan { + let scope = o["scope"] as! [String: Any] + let status = o["status"] as! [String: Any] + return CoreSpan( + context: ctx(o["context"] as! [String: Any]), + parentSpanId: o["parentSpanId"] as? String, + name: o["name"] as! String, + kind: (o["kind"] as! NSNumber).intValue, + start: time(o["start"]), + end: time(o["end"]), + attributes: attrs(o["attributes"]), + events: (o["events"] as! [[String: Any]]).map { + CoreEvent(name: $0["name"] as! String, time: time($0["time"]), attributes: attrs($0["attributes"])) + }, + links: (o["links"] as! [[String: Any]]).map { + CoreLink(context: ctx($0["context"] as! [String: Any]), attributes: attrs($0["attributes"])) + }, + status: CoreStatus(code: (status["code"] as! NSNumber).intValue, message: status["message"] as? String), + scope: CoreScope(name: scope["name"] as! String, version: scope["version"] as? String, + schemaUrl: scope["schemaUrl"] as? String, attributes: attrs(scope["attributes"])) + ) + } +} diff --git a/ios/CoreTests/InitTests.swift b/ios/CoreTests/InitTests.swift new file mode 100644 index 0000000..1fbbcf8 --- /dev/null +++ b/ios/CoreTests/InitTests.swift @@ -0,0 +1,74 @@ +import XCTest +import OpenTelemetrySdk +@testable import OtelCore + +final class InitTests: XCTestCase { + private let ok = CoreConfig(serviceName: "first", serviceVersion: "1.0", exportUrl: "http://127.0.0.1:1", exportHeaders: ["x-api-key": "test"]) + private func name(_ c: OtelCore?) -> String? { c?.resource.attributes["service.name"]?.description } + override func setUp() { OtelCore.resetForTest() } + override func tearDown() { OtelCore.resetForTest() } + + func testInitializeTwiceKeepsTheFirstConfig() { + let a = OtelCore.initialize(ok, testMode: true) + XCTAssertNil(a.error); XCTAssertFalse(a.alreadyInitialized) + let core = OtelCore.instance + var second = ok; second.serviceName = "second" + let b = OtelCore.initialize(second, testMode: true) + XCTAssertTrue(b.alreadyInitialized); XCTAssertNil(b.error) + XCTAssertTrue(core === OtelCore.instance) + XCTAssertEqual(name(core), "first") + } + + func testInvalidUrlReturnsAnErrorAndNeverThrows() { + for u in ["not a url", "ftp://h", "http://", "", "http:///x"] { + OtelCore.resetForTest() + var c = ok; c.exportUrl = u + XCTAssertNotNil(OtelCore.initialize(c, testMode: true).error, u) + XCTAssertNil(OtelCore.instance) + } + } + + func testAFailedInitIsSticky() { + var bad = ok; bad.exportUrl = "not a url" + let first = OtelCore.initialize(bad, testMode: true) + let again = OtelCore.initialize(ok, testMode: true) + XCTAssertEqual(first.error, again.error) + XCTAssertTrue(again.alreadyInitialized) + XCTAssertNil(OtelCore.instance) + } + + func testInitializeWithoutConfigIsAnErrorButNotSticky() { + XCTAssertNotNil(OtelCore.initialize(nil, testMode: true).error) + let r = OtelCore.initialize(ok, testMode: true) + XCTAssertNil(r.error); XCTAssertFalse(r.alreadyInitialized) + XCTAssertNotNil(OtelCore.instance) + } + + func testInitializeWithoutConfigAfterInitIsAlreadyInitialized() { + OtelCore.initialize(ok, testMode: true) + let r = OtelCore.initialize(nil, testMode: true) + XCTAssertTrue(r.alreadyInitialized); XCTAssertNil(r.error) + } + + func testConcurrentInitializeCreatesOneCore() { + DispatchQueue.concurrentPerform(iterations: 50) { _ in _ = OtelCore.initialize(ok, testMode: true) } + let core = OtelCore.instance + XCTAssertNotNil(core) + XCTAssertTrue(OtelCore.initialize(ok, testMode: true).alreadyInitialized) + XCTAssertTrue(core === OtelCore.instance) + } + + func testDistroAttributesOutsideTestModeOnly() { + let prod = OtelCore(config: ok, testMode: false, distroVersion: "9.9.9").resource.attributes + XCTAssertEqual(prod["telemetry.distro.name"]?.description, "react-native-open-telemetry") + XCTAssertEqual(prod["telemetry.distro.version"]?.description, "9.9.9") + let test = OtelCore(config: ok, testMode: true, distroVersion: "9.9.9").resource.attributes + XCTAssertNil(test["telemetry.distro.name"]) + XCTAssertNil(test["telemetry.sdk.name"]) + } + + func testResourceAttributesAreKept() { + var c = ok; c.resourceAttributes = [CoreAttribute(key: "k", value: .string("v"))] + XCTAssertEqual(OtelCore(config: c, testMode: true).resource.attributes["k"]?.description, "v") + } +} diff --git a/ios/CoreTests/ParentingTests.swift b/ios/CoreTests/ParentingTests.swift new file mode 100644 index 0000000..e2a2226 --- /dev/null +++ b/ios/CoreTests/ParentingTests.swift @@ -0,0 +1,49 @@ +import XCTest +import OpenTelemetryApi +import OpenTelemetrySdk +@testable import OtelCore + +final class ParentingTests: XCTestCase { + private var tracer: Tracer! + private let tp = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01" + + override func setUp() { + // upstream's TracerProvider adopts a TRACEPARENT env var as the parent of every root span + unsetenv("TRACEPARENT") + tracer = TracerProviderBuilder().build().get(instrumentationName: "t") + } + + private func child(_ parent: SpanContext?) -> SpanData { + let b = tracer.spanBuilder(spanName: "c") + if let parent { b.setParent(parent) } else { b.setNoParent() } + return (b.startSpan() as! ReadableSpan).toSpanData() + } + + func testRoundTrip() { + let s = tracer.spanBuilder(spanName: "p").startSpan() + let t = traceparent(of: s.context) + XCTAssertEqual(s.context.traceId.hexString, String(t.split(separator: "-")[1])) + XCTAssertEqual(t, traceparent(of: contextFrom(traceparent: t)!)) + XCTAssertEqual(tp, traceparent(of: contextFrom(traceparent: tp)!)) + } + + func testChildHasParentIdAndIsNotRemote() { + let d = child(contextFrom(traceparent: tp)) + XCTAssertEqual(d.parentSpanId?.hexString, "b7ad6b7169203331") + XCTAssertEqual(d.traceId.hexString, "0af7651916cd43dd8448eb211c80319c") + XCTAssertFalse(d.hasRemoteParent) + } + + func testInvalidInputYieldsRoot() { + for s in ["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", + "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01\n"] { + XCTAssertNil(contextFrom(traceparent: s), s) + XCTAssertNil(child(contextFrom(traceparent: s)).parentSpanId, s) + } + } +} diff --git a/ios/CoreTests/TimeRoundTripTests.swift b/ios/CoreTests/TimeRoundTripTests.swift new file mode 100644 index 0000000..70d6bd0 --- /dev/null +++ b/ios/CoreTests/TimeRoundTripTests.swift @@ -0,0 +1,37 @@ +import OpenTelemetryApi +import OpenTelemetryProtocolExporterCommon +import OpenTelemetrySdk +import XCTest +@testable import OtelCore + +/// R22/F8: opentelemetry-swift keeps times as `Date` and exports `UInt64(timeIntervalSince1970 * 1e9)`, so +/// whole-µs seam times cannot come back exact. This documents the floor; the drafted `ios` files record the +/// quantized values as emitted. +final class TimeRoundTripTests: XCTestCase { + private let base: UInt64 = 1_767_225_600_000_000_000 + private func at(_ us: UInt64) -> HrTime { HrTime([Double(1_767_225_600 + us / 1_000_000), Double(us % 1_000_000 * 1000)]) } + + private func exported(_ t: HrTime) -> UInt64 { + let span = CoreSpan(context: CoreSpanContext(traceId: "0a000000000000000000000000000001", spanId: "0a00000000000001", traceFlags: 1), + parentSpanId: nil, name: "t", kind: 0, start: t, end: t, attributes: [], events: [], links: [], + status: CoreStatus(code: 0, message: nil), scope: CoreScope(name: "t", version: nil, schemaUrl: nil, attributes: [])) + return SpanAdapter.toProtoSpan(spanData: JsReadableSpan(span, resource: Resource(attributes: [:])).toSpanData()).startTimeUnixNano + } + + func testWholeMicrosecondsQuantizeWithinTheDateFloor() { + var maxErr: Int64 = 0 + var exact = 0 + let samples = Array(0 ... 10_000) + [1_000_000_000] + for us in samples { + let want = base + UInt64(us) * 1000 + let got = exported(at(UInt64(us))) + let err = Int64(bitPattern: got &- want) + maxErr = max(maxErr, abs(err)) + if err == 0 { exact += 1 } + } + print("TimeRoundTrip: max |error| \(maxErr) ns, \(exact)/\(samples.count) exact") + // the exported value is a double near 1.77e18, whose grid is 256 ns + XCTAssertLessThanOrEqual(maxErr, 256) + XCTAssertLessThan(exact, samples.count, "times came back exact: R22 no longer holds, revisit the floor in VERIFY.md") + } +} diff --git a/ios/RNOtel/RNOtel.swift b/ios/RNOtel/RNOtel.swift new file mode 100644 index 0000000..5c931fe --- /dev/null +++ b/ios/RNOtel/RNOtel.swift @@ -0,0 +1,61 @@ +import Foundation +import OpenTelemetryApi +import UIKit + +/// `package.json` version, reported as `telemetry.distro.version`; the static stage checks it matches. +let packageVersion = "0.2.0" + +/// Public native API (spec §4.3/§4.4). Test mode comes from the build (`OTEL_TEST_MODE=1 pod install`), never from here. +public enum RNOtel { + #if OTEL_TEST_MODE + static let testMode = true + #else + static let testMode = false + #endif + + /// Native-first init from `AppDelegate`, before React Native. Never throws; an error is logged once. + public static func start(_ configure: (RNOtelConfig) -> Void) { + let c = RNOtelConfig() + configure(c) + let r = initialize(c.toCore()) + // alreadyInitialized: a repeat call; a sticky failure was logged by the first one + if let err = r.error, !r.alreadyInitialized { NSLog("RNOtel init failed; telemetry is off: %@", err) } + } + + private static var observer: NSObjectProtocol? + private static let lock = NSLock() + + /// One path for native-first and JS-fallback init. The exporter is built on first export, off the main thread. + package static func initialize(_ config: CoreConfig?) -> InitResult { + let r = OtelCore.initialize(config, testMode: testMode, distroVersion: packageVersion) + if let core = OtelCore.instance { lock.withLock { if observer == nil { observer = flushOnBackground(core) } } } + return r + } + + /// Exports what is queued when the app goes to the background, inside a background task so iOS lets it finish. + /// The flush blocks a global queue, never the main thread. + private static func flushOnBackground(_ core: OtelCore) -> NSObjectProtocol { + NotificationCenter.default.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: .main) { _ in + let app = UIApplication.shared + var task = UIBackgroundTaskIdentifier.invalid + // begin/end/expiration all run on the main thread, so `task` needs no lock + let end = { if task != .invalid { app.endBackgroundTask(task); task = .invalid } } + task = app.beginBackgroundTask(withName: "RNOtel flush", expirationHandler: end) + DispatchQueue.global(qos: .utility).async { + _ = core.flush(timeoutMs: 10_000) + DispatchQueue.main.async(execute: end) + } + } + } + + /// A tracer on the native provider; a no-op tracer before (or without) a successful init. + public static func tracer(_ name: String, version: String? = nil) -> any Tracer { + guard let p = OtelCore.instance?.tracerProvider else { return DefaultTracer.instance } + return p.get(instrumentationName: name, instrumentationVersion: version) + } + + /// W3C traceparent -> explicit, non-remote parent `SpanContext` for `setParent(_:)`; invalid input -> nil (a root). + public static func contextFrom(traceparent: String) -> SpanContext? { ReactNativeOpenTelemetryCore.contextFrom(traceparent: traceparent) } + + public static func traceparentOf(_ span: any Span) -> String { traceparent(of: span.context) } +} diff --git a/ios/RNOtel/RNOtelConfig.swift b/ios/RNOtel/RNOtelConfig.swift new file mode 100644 index 0000000..4b72fa3 --- /dev/null +++ b/ios/RNOtel/RNOtelConfig.swift @@ -0,0 +1,22 @@ +/// 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? + public var resourceAttributes: [String: String] = [:] + public var export = Export(url: "") + + public struct Export { + /// OTLP base URL; `/v1/traces` is appended unless present. + public var url: String + public var headers: [String: String] + public init(url: String, headers: [String: String] = [:]) { self.url = url; self.headers = headers } + } + + init() {} + + func toCore() -> CoreConfig { + CoreConfig(serviceName: serviceName, serviceVersion: serviceVersion, + resourceAttributes: resourceAttributes.map { CoreAttribute(key: $0.key, value: .string($0.value)) }, + exportUrl: export.url, exportHeaders: export.headers) + } +} diff --git a/package.json b/package.json index 9d6f011..a614939 100644 --- a/package.json +++ b/package.json @@ -34,6 +34,7 @@ "default": "./lib/module/index.js" }, "./metro": "./metro/index.js", + "./app.plugin.js": "./app.plugin.js", "./setup": { "types": "./lib/typescript/src/setup.d.ts", "default": "./lib/module/setup.js" @@ -48,11 +49,15 @@ "ios", "Package.swift", "ReactNativeOpenTelemetry.podspec", + "ReactNativeOpenTelemetryCore.podspec", "nitro.json", "metro", + "app.plugin.js", + "react-native.config.js", "!ios/build", "!android/build", "!android/core-jvm", + "!ios/CoreTests", "!android/gradle", "!android/gradlew", "!android/gradlew.bat", diff --git a/react-native.config.js b/react-native.config.js index 4942891..83a51ab 100644 --- a/react-native.config.js +++ b/react-native.config.js @@ -1,9 +1,12 @@ // 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, R24). 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: { - ios: {}, + ios: {podspecPath: 'ReactNativeOpenTelemetry.podspec'}, android: {}, }, }, diff --git a/verify/expected/async-generator.ios.otlp.json b/verify/expected/async-generator.ios.otlp.json new file mode 100644 index 0000000..2de36e5 --- /dev/null +++ b/verify/expected/async-generator.ios.otlp.json @@ -0,0 +1,74 @@ +{ + "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": "1767225600000060160", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000002", + "parentSpanId": "0a00000000000001", + "name": "gen.0", + "kind": 1, + "startTimeUnixNano": "1767225600000009984", + "endTimeUnixNano": "1767225600000011008", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000003", + "parentSpanId": "0a00000000000001", + "name": "loop.0", + "kind": 1, + "startTimeUnixNano": "1767225600000019968", + "endTimeUnixNano": "1767225600000020992", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000004", + "parentSpanId": "0a00000000000001", + "name": "gen.1", + "kind": 1, + "startTimeUnixNano": "1767225600000029952", + "endTimeUnixNano": "1767225600000030976", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000005", + "parentSpanId": "0a00000000000001", + "name": "loop.1", + "kind": 1, + "startTimeUnixNano": "1767225600000039936", + "endTimeUnixNano": "1767225600000040960", + "status": {} + } + ] + } + ] + } + ] +} diff --git a/verify/expected/background-flush.ios.otlp.json b/verify/expected/background-flush.ios.otlp.json new file mode 100644 index 0000000..d697f82 --- /dev/null +++ b/verify/expected/background-flush.ios.otlp.json @@ -0,0 +1,34 @@ +{ + "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": "1767225600000009984", + "status": {} + } + ] + } + ] + } + ] +} diff --git a/verify/expected/batching-shared-queue.ios.otlp.json b/verify/expected/batching-shared-queue.ios.otlp.json new file mode 100644 index 0000000..aa5fd24 --- /dev/null +++ b/verify/expected/batching-shared-queue.ios.otlp.json @@ -0,0 +1,63 @@ +{ + "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": "1767225600000001024", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000002", + "spanId": "0a00000000000002", + "name": "h2", + "kind": 1, + "startTimeUnixNano": "1767225600000001792", + "endTimeUnixNano": "1767225600000003072", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000003", + "parentSpanId": "0a00000000000001", + "name": "h1.work", + "kind": 1, + "startTimeUnixNano": "1767225600000009984", + "endTimeUnixNano": "1767225600000011008", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000004", + "parentSpanId": "0a00000000000001", + "name": "h2.work", + "kind": 1, + "startTimeUnixNano": "1767225600000019968", + "endTimeUnixNano": "1767225600000020992", + "status": {} + } + ] + } + ] + } + ] +} diff --git a/verify/expected/captured-then.ios.otlp.json b/verify/expected/captured-then.ios.otlp.json new file mode 100644 index 0000000..e4c96d7 --- /dev/null +++ b/verify/expected/captured-then.ios.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": "parent", + "kind": 1, + "startTimeUnixNano": "1767225600000000000", + "endTimeUnixNano": "1767225600000029952", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000002", + "parentSpanId": "0a00000000000001", + "name": "kept", + "kind": 1, + "startTimeUnixNano": "1767225600000009984", + "endTimeUnixNano": "1767225600000011008", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000002", + "spanId": "0a00000000000003", + "name": "lost", + "kind": 1, + "startTimeUnixNano": "1767225600000019968", + "endTimeUnixNano": "1767225600000020992", + "status": {} + } + ] + } + ] + } + ] +} diff --git a/verify/expected/collector-down.ios.otlp.json b/verify/expected/collector-down.ios.otlp.json new file mode 100644 index 0000000..693713a --- /dev/null +++ b/verify/expected/collector-down.ios.otlp.json @@ -0,0 +1,34 @@ +{ + "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": "1767225600000009984", + "status": {} + } + ] + } + ] + } + ] +} diff --git a/verify/expected/concurrent-interleaved.ios.otlp.json b/verify/expected/concurrent-interleaved.ios.otlp.json new file mode 100644 index 0000000..00a0eea --- /dev/null +++ b/verify/expected/concurrent-interleaved.ios.otlp.json @@ -0,0 +1,92 @@ +{ + "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": "1767225600000029952", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000002", + "spanId": "0a00000000000002", + "name": "b", + "kind": 1, + "startTimeUnixNano": "1767225600000001024", + "endTimeUnixNano": "1767225600000030976", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000003", + "parentSpanId": "0a00000000000001", + "name": "a.1", + "kind": 1, + "startTimeUnixNano": "1767225600000009984", + "endTimeUnixNano": "1767225600000011008", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000002", + "spanId": "0a00000000000004", + "parentSpanId": "0a00000000000002", + "name": "b.1", + "kind": 1, + "startTimeUnixNano": "1767225600000011008", + "endTimeUnixNano": "1767225600000012032", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000005", + "parentSpanId": "0a00000000000001", + "name": "a.2", + "kind": 1, + "startTimeUnixNano": "1767225600000019968", + "endTimeUnixNano": "1767225600000020992", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000002", + "spanId": "0a00000000000006", + "parentSpanId": "0a00000000000002", + "name": "b.2", + "kind": 1, + "startTimeUnixNano": "1767225600000020992", + "endTimeUnixNano": "1767225600000022016", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000003", + "spanId": "0a00000000000007", + "name": "after.all", + "kind": 1, + "startTimeUnixNano": "1767225600000039936", + "endTimeUnixNano": "1767225600000040960", + "status": {} + } + ] + } + ] + } + ] +} diff --git a/verify/expected/cross-js-to-native.ios.otlp.json b/verify/expected/cross-js-to-native.ios.otlp.json new file mode 100644 index 0000000..c0de431 --- /dev/null +++ b/verify/expected/cross-js-to-native.ios.otlp.json @@ -0,0 +1,51 @@ +{ + "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": "1767225600000300032", + "status": {} + } + ] + }, + { + "scope": { + "name": "test-native" + }, + "spans": [ + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0b00000000000001", + "parentSpanId": "0a00000000000001", + "name": "native.work", + "kind": 1, + "startTimeUnixNano": "1767225600000099840", + "endTimeUnixNano": "1767225600000199936", + "status": {} + } + ] + } + ] + } + ] +} diff --git a/verify/expected/cross-native-to-js.ios.otlp.json b/verify/expected/cross-native-to-js.ios.otlp.json new file mode 100644 index 0000000..a77c195 --- /dev/null +++ b/verify/expected/cross-native-to-js.ios.otlp.json @@ -0,0 +1,51 @@ +{ + "resourceSpans": [ + { + "resource": { + "attributes": [ + { + "key": "service.name", + "value": { + "stringValue": "verify" + } + } + ] + }, + "scopeSpans": [ + { + "scope": { + "name": "verify" + }, + "spans": [ + { + "traceId": "0b000000000000000000000000000001", + "spanId": "0a00000000000001", + "parentSpanId": "0b00000000000001", + "name": "js.after_native", + "kind": 1, + "startTimeUnixNano": "1767225600000199936", + "endTimeUnixNano": "1767225600000300032", + "status": {} + } + ] + }, + { + "scope": { + "name": "test-native" + }, + "spans": [ + { + "traceId": "0b000000000000000000000000000001", + "spanId": "0b00000000000001", + "name": "native.work", + "kind": 1, + "startTimeUnixNano": "1767225600000000000", + "endTimeUnixNano": "1767225600000099840", + "status": {} + } + ] + } + ] + } + ] +} diff --git a/verify/expected/error-in-callback.ios.otlp.json b/verify/expected/error-in-callback.ios.otlp.json new file mode 100644 index 0000000..d33bfd1 --- /dev/null +++ b/verify/expected/error-in-callback.ios.otlp.json @@ -0,0 +1,63 @@ +{ + "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": "1767225600000039936", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000002", + "parentSpanId": "0a00000000000001", + "name": "throws", + "kind": 1, + "startTimeUnixNano": "1767225600000009984", + "endTimeUnixNano": "1767225600000011008", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000002", + "spanId": "0a00000000000003", + "name": "root.next", + "kind": 1, + "startTimeUnixNano": "1767225600000029952", + "endTimeUnixNano": "1767225600000030976", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000004", + "parentSpanId": "0a00000000000001", + "name": "caught", + "kind": 1, + "startTimeUnixNano": "1767225600000019968", + "endTimeUnixNano": "1767225600000020992", + "status": {} + } + ] + } + ] + } + ] +} diff --git a/verify/expected/event-emitter-listener.ios.otlp.json b/verify/expected/event-emitter-listener.ios.otlp.json new file mode 100644 index 0000000..2dfddfc --- /dev/null +++ b/verify/expected/event-emitter-listener.ios.otlp.json @@ -0,0 +1,44 @@ +{ + "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": "1767225600000019968", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000002", + "parentSpanId": "0a00000000000001", + "name": "listener", + "kind": 1, + "startTimeUnixNano": "1767225600000009984", + "endTimeUnixNano": "1767225600000011008", + "status": {} + } + ] + } + ] + } + ] +} diff --git a/verify/expected/export-headers.ios.otlp.json b/verify/expected/export-headers.ios.otlp.json new file mode 100644 index 0000000..f5daea6 --- /dev/null +++ b/verify/expected/export-headers.ios.otlp.json @@ -0,0 +1,34 @@ +{ + "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": "1767225600000009984", + "status": {} + } + ] + } + ] + } + ] +} diff --git a/verify/expected/flush-after-reload.ios.otlp.json b/verify/expected/flush-after-reload.ios.otlp.json new file mode 100644 index 0000000..09877f1 --- /dev/null +++ b/verify/expected/flush-after-reload.ios.otlp.json @@ -0,0 +1,34 @@ +{ + "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": "1767225600000009984", + "status": {} + } + ] + } + ] + } + ] +} diff --git a/verify/expected/handoff-basic.ios.otlp.json b/verify/expected/handoff-basic.ios.otlp.json new file mode 100644 index 0000000..a71b84e --- /dev/null +++ b/verify/expected/handoff-basic.ios.otlp.json @@ -0,0 +1,42 @@ +{ + "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": "1767225600000099840", + "attributes": [ + { + "key": "app.step", + "value": { + "stringValue": "one" + } + } + ], + "status": {} + } + ] + } + ] + } + ] +} diff --git a/verify/expected/interval-new-root.ios.otlp.json b/verify/expected/interval-new-root.ios.otlp.json new file mode 100644 index 0000000..9da980a --- /dev/null +++ b/verify/expected/interval-new-root.ios.otlp.json @@ -0,0 +1,62 @@ +{ + "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": "1767225600000400128", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000002", + "spanId": "0a00000000000002", + "name": "tick", + "kind": 1, + "startTimeUnixNano": "1767225600000099840", + "endTimeUnixNano": "1767225600000101120", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000003", + "spanId": "0a00000000000003", + "name": "tick", + "kind": 1, + "startTimeUnixNano": "1767225600000199936", + "endTimeUnixNano": "1767225600000200960", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000004", + "parentSpanId": "0a00000000000001", + "name": "load", + "kind": 1, + "startTimeUnixNano": "1767225600000300032", + "endTimeUnixNano": "1767225600000300800", + "status": {} + } + ] + } + ] + } + ] +} diff --git a/verify/expected/native-init-failure.ios.otlp.json b/verify/expected/native-init-failure.ios.otlp.json new file mode 100644 index 0000000..0efd939 --- /dev/null +++ b/verify/expected/native-init-failure.ios.otlp.json @@ -0,0 +1,3 @@ +{ + "resourceSpans": [] +} diff --git a/verify/expected/nest-after-await.ios.otlp.json b/verify/expected/nest-after-await.ios.otlp.json new file mode 100644 index 0000000..dbc627d --- /dev/null +++ b/verify/expected/nest-after-await.ios.otlp.json @@ -0,0 +1,44 @@ +{ + "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": "1767225600000029952", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000002", + "parentSpanId": "0a00000000000001", + "name": "child", + "kind": 1, + "startTimeUnixNano": "1767225600000009984", + "endTimeUnixNano": "1767225600000019968", + "status": {} + } + ] + } + ] + } + ] +} diff --git a/verify/expected/nest-promise-all-race.ios.otlp.json b/verify/expected/nest-promise-all-race.ios.otlp.json new file mode 100644 index 0000000..788695b --- /dev/null +++ b/verify/expected/nest-promise-all-race.ios.otlp.json @@ -0,0 +1,84 @@ +{ + "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": "1767225600000060160", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000002", + "parentSpanId": "0a00000000000001", + "name": "all.a", + "kind": 1, + "startTimeUnixNano": "1767225600000009984", + "endTimeUnixNano": "1767225600000011008", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000003", + "parentSpanId": "0a00000000000001", + "name": "all.b", + "kind": 1, + "startTimeUnixNano": "1767225600000019968", + "endTimeUnixNano": "1767225600000020992", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000004", + "parentSpanId": "0a00000000000001", + "name": "race.a", + "kind": 1, + "startTimeUnixNano": "1767225600000029952", + "endTimeUnixNano": "1767225600000030976", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000005", + "parentSpanId": "0a00000000000001", + "name": "race.b", + "kind": 1, + "startTimeUnixNano": "1767225600000039936", + "endTimeUnixNano": "1767225600000040960", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000006", + "parentSpanId": "0a00000000000001", + "name": "after", + "kind": 1, + "startTimeUnixNano": "1767225600000050176", + "endTimeUnixNano": "1767225600000050944", + "status": {} + } + ] + } + ] + } + ] +} diff --git a/verify/expected/nest-raf.ios.otlp.json b/verify/expected/nest-raf.ios.otlp.json new file mode 100644 index 0000000..c247a10 --- /dev/null +++ b/verify/expected/nest-raf.ios.otlp.json @@ -0,0 +1,44 @@ +{ + "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": "1767225600000019968", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000002", + "parentSpanId": "0a00000000000001", + "name": "frame", + "kind": 1, + "startTimeUnixNano": "1767225600000009984", + "endTimeUnixNano": "1767225600000011008", + "status": {} + } + ] + } + ] + } + ] +} diff --git a/verify/expected/nest-timers-microtasks.ios.otlp.json b/verify/expected/nest-timers-microtasks.ios.otlp.json new file mode 100644 index 0000000..ca0a0b3 --- /dev/null +++ b/verify/expected/nest-timers-microtasks.ios.otlp.json @@ -0,0 +1,84 @@ +{ + "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": "1767225600000050176", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000002", + "parentSpanId": "0a00000000000001", + "name": "timeout", + "kind": 1, + "startTimeUnixNano": "1767225600000009984", + "endTimeUnixNano": "1767225600000011008", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000003", + "parentSpanId": "0a00000000000001", + "name": "immediate", + "kind": 1, + "startTimeUnixNano": "1767225600000019968", + "endTimeUnixNano": "1767225600000020992", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000004", + "parentSpanId": "0a00000000000001", + "name": "microtask", + "kind": 1, + "startTimeUnixNano": "1767225600000029952", + "endTimeUnixNano": "1767225600000030976", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000005", + "parentSpanId": "0a00000000000001", + "name": "timeout.microtask", + "kind": 1, + "startTimeUnixNano": "1767225600000039936", + "endTimeUnixNano": "1767225600000040960", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000006", + "parentSpanId": "0a00000000000001", + "name": "after.end", + "kind": 1, + "startTimeUnixNano": "1767225600000060160", + "endTimeUnixNano": "1767225600000060928", + "status": {} + } + ] + } + ] + } + ] +} diff --git a/verify/expected/never-settling-promise.ios.otlp.json b/verify/expected/never-settling-promise.ios.otlp.json new file mode 100644 index 0000000..7fa1586 --- /dev/null +++ b/verify/expected/never-settling-promise.ios.otlp.json @@ -0,0 +1,62 @@ +{ + "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": "1767225600000019968", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000002", + "parentSpanId": "0a00000000000001", + "name": "child", + "kind": 1, + "startTimeUnixNano": "1767225600000009984", + "endTimeUnixNano": "1767225600000011008", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000002", + "spanId": "0a00000000000003", + "name": "later.await", + "kind": 1, + "startTimeUnixNano": "1767225600000029952", + "endTimeUnixNano": "1767225600000030976", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000003", + "spanId": "0a00000000000004", + "name": "later.timeout", + "kind": 1, + "startTimeUnixNano": "1767225600000039936", + "endTimeUnixNano": "1767225600000040960", + "status": {} + } + ] + } + ] + } + ] +} diff --git a/verify/expected/odd-attributes.ios.otlp.json b/verify/expected/odd-attributes.ios.otlp.json new file mode 100644 index 0000000..5110ca6 --- /dev/null +++ b/verify/expected/odd-attributes.ios.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": "odd", + "kind": 1, + "startTimeUnixNano": "1767225600000000000", + "endTimeUnixNano": "1767225600000009984", + "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": {} + } + ] + } + ] + } + ] +} diff --git a/verify/expected/rich-span.ios.otlp.json b/verify/expected/rich-span.ios.otlp.json new file mode 100644 index 0000000..61ff887 --- /dev/null +++ b/verify/expected/rich-span.ios.otlp.json @@ -0,0 +1,187 @@ +{ + "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": "1767225600000099840", + "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": "1767225600000009984", + "name": "first", + "attributes": [ + { + "key": "event.key", + "value": { + "stringValue": "e1" + } + }, + { + "key": "event.n", + "value": { + "intValue": "1" + } + } + ] + }, + { + "timeUnixNano": "1767225600000019968", + "name": "second", + "attributes": [ + { + "key": "event.ok", + "value": { + "boolValue": true + } + } + ] + } + ], + "links": [ + { + "traceId": "0f111111111111111111111111111111", + "spanId": "0f22222222222222", + "attributes": [ + { + "key": "link.key", + "value": { + "stringValue": "link-value" + } + }, + { + "key": "link.n", + "value": { + "intValue": "7" + } + } + ] + } + ], + "status": { + "message": "boom", + "code": 2 + } + } + ] + } + ] + } + ] +} diff --git a/verify/expected/root-no-leak.ios.otlp.json b/verify/expected/root-no-leak.ios.otlp.json new file mode 100644 index 0000000..2e0b2be --- /dev/null +++ b/verify/expected/root-no-leak.ios.otlp.json @@ -0,0 +1,71 @@ +{ + "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": "1767225600000019968", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000002", + "parentSpanId": "0a00000000000001", + "name": "scoped.child", + "kind": 1, + "startTimeUnixNano": "1767225600000009984", + "endTimeUnixNano": "1767225600000011008", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000002", + "spanId": "0a00000000000003", + "name": "after.sync", + "kind": 1, + "startTimeUnixNano": "1767225600000029952", + "endTimeUnixNano": "1767225600000030976", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000003", + "spanId": "0a00000000000004", + "name": "after.await", + "kind": 1, + "startTimeUnixNano": "1767225600000039936", + "endTimeUnixNano": "1767225600000040960", + "status": {} + }, + { + "traceId": "0a000000000000000000000000000004", + "spanId": "0a00000000000005", + "name": "after.timeout", + "kind": 1, + "startTimeUnixNano": "1767225600000050176", + "endTimeUnixNano": "1767225600000050944", + "status": {} + } + ] + } + ] + } + ] +} diff --git a/verify/expected/smoke-js.ios.otlp.json b/verify/expected/smoke-js.ios.otlp.json new file mode 100644 index 0000000..18cebea --- /dev/null +++ b/verify/expected/smoke-js.ios.otlp.json @@ -0,0 +1,34 @@ +{ + "resourceSpans": [ + { + "resource": { + "attributes": [ + { + "key": "service.name", + "value": { + "stringValue": "verify" + } + } + ] + }, + "scopeSpans": [ + { + "scope": { + "name": "verify" + }, + "spans": [ + { + "traceId": "0a000000000000000000000000000001", + "spanId": "0a00000000000001", + "name": "smoke", + "kind": 1, + "startTimeUnixNano": "1767225600000000000", + "endTimeUnixNano": "1767225600000001024", + "status": {} + } + ] + } + ] + } + ] +} diff --git a/verify/stages/fast-swift.ts b/verify/stages/fast-swift.ts index 44c5fc9..1a21f77 100644 --- a/verify/stages/fast-swift.ts +++ b/verify/stages/fast-swift.ts @@ -1,14 +1,15 @@ -import {existsSync} from 'node:fs'; +import path from 'node:path'; import type {Stage} from '../run'; +import {replayFixtures} from '../harness/nativeReplay'; const stage: Stage = { name: 'fast-swift', order: 30, e2e: false, - run({sh}) { + async run() { if (process.platform !== 'darwin') return void console.log('skipped: not macOS'); - if (!existsSync('Package.swift')) return void console.log('skipped: no Package.swift'); - sh(['swift', 'test']); + const n = await replayFixtures('ios', 'swift', ['test'], path.join(import.meta.dirname, '..', '..')); + console.log(`fast-swift: ${n} fixtures match their ios files`); }, }; diff --git a/verify/stages/static.ts b/verify/stages/static.ts index 16cdf20..07c29e9 100644 --- a/verify/stages/static.ts +++ b/verify/stages/static.ts @@ -1,4 +1,6 @@ import type {Stage} from '../run'; +import fs from 'node:fs'; +import path from 'node:path'; import {packContents, REQUIRED} from '../static/packContents'; const stage: Stage = { @@ -18,6 +20,11 @@ const stage: Stage = { const list: string[] = JSON.parse(out)[0].files.map((f: {path: string}) => f.path); const missing = packContents(list, REQUIRED); if (missing.length) throw new Error(`npm pack is missing: ${missing.join(', ')}`); + // iOS has no build-time access to package.json (Android reads it in Gradle): the Swift constant must match. + const root = path.join(import.meta.dirname, '..', '..'); + const {version} = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8')); + if (!fs.readFileSync(path.join(root, 'ios', 'RNOtel', 'RNOtel.swift'), 'utf8').includes(`let packageVersion = "${version}"`)) + throw new Error(`ios/RNOtel/RNOtel.swift: set packageVersion to "${version}" (package.json)`); sh(['bunx', 'jest', '--selectProjects', 'harness']); }, }; diff --git a/verify/static/expoPlugin.test.ts b/verify/static/expoPlugin.test.ts new file mode 100644 index 0000000..7c5a233 --- /dev/null +++ b/verify/static/expoPlugin.test.ts @@ -0,0 +1,13 @@ +const {addCorePod} = require('../../app.plugin'); + +const podfile = "platform :ios, '15.1'\n\ntarget 'App' do\n use_expo_modules!\nend\n"; + +test('adds the core pod to the app target, once', () => { + const out = addCorePod(podfile, '../node_modules/react-native-open-telemetry'); + expect(out).toContain("target 'App' do\n pod 'ReactNativeOpenTelemetryCore', :path => '../node_modules/react-native-open-telemetry'\n"); + expect(addCorePod(out, 'x')).toBe(out); +}); + +test('throws when there is no target to add it to', () => { + expect(() => addCorePod("platform :ios, '15.1'\n", 'x')).toThrow(/by hand/); +}); diff --git a/verify/static/packContents.test.ts b/verify/static/packContents.test.ts index 5a5394e..981b408 100644 --- a/verify/static/packContents.test.ts +++ b/verify/static/packContents.test.ts @@ -1,6 +1,6 @@ import {packContents} from './packContents'; -const complete = ['package.json', 'lib/module/index.js', 'src/index.ts', 'nitrogen/generated/x.hpp', 'metro/index.js', 'android/build.gradle', 'ios/Adapter/HybridOtel.swift', 'ReactNativeOpenTelemetry.podspec']; +const complete = ['package.json', 'lib/module/index.js', 'src/index.ts', 'nitrogen/generated/x.hpp', 'metro/index.js', 'android/build.gradle', 'ios/Adapter/HybridOtel.swift', 'Package.swift', 'ReactNativeOpenTelemetry.podspec', 'ReactNativeOpenTelemetryCore.podspec', 'app.plugin.js', 'react-native.config.js']; test('reports missing nitrogen/', () => { expect(packContents(complete.filter(p => !p.startsWith('nitrogen/')))).toEqual(['nitrogen/']); diff --git a/verify/static/packContents.ts b/verify/static/packContents.ts index dddbfec..63ea7eb 100644 --- a/verify/static/packContents.ts +++ b/verify/static/packContents.ts @@ -1,4 +1,4 @@ -export const REQUIRED = ['package.json', 'lib/', 'src/', 'nitrogen/', 'metro/', 'android/', 'ios/', 'ReactNativeOpenTelemetry.podspec']; +export const REQUIRED = ['package.json', 'lib/', 'src/', 'nitrogen/', 'metro/', 'android/', 'ios/', 'Package.swift', '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[] { From db6cac7b372263b67b285068b795ab27e29b59de Mon Sep 17 00:00:00 2001 From: Adam Horodyski Date: Wed, 25 Nov 2026 13:50:53 +0100 Subject: [PATCH 2/4] fix(ios): start the background flush on willResignActive Under CPU load a backgrounded app can be starved for ~15 s despite its background task: the export request stalls until the app is reopened, which is the background-flush e2e failure on CI. Reproduced locally under load (about half of first attempts failed, 14.8 s stalls); with willResignActive 12 of 12 passed first try. Co-Authored-By: Claude Opus 5.5 --- ios/RNOtel/RNOtel.swift | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/ios/RNOtel/RNOtel.swift b/ios/RNOtel/RNOtel.swift index 5c931fe..aed3221 100644 --- a/ios/RNOtel/RNOtel.swift +++ b/ios/RNOtel/RNOtel.swift @@ -32,10 +32,13 @@ public enum RNOtel { return r } - /// Exports what is queued when the app goes to the background, inside a background task so iOS lets it finish. - /// The flush blocks a global queue, never the main thread. + /// Exports what is queued when the app is about to go to the background, inside a background task so iOS lets it + /// finish. The flush blocks a global queue, never the main thread. + /// Starts on `willResignActive`, not `didEnterBackground`: once backgrounded, a loaded system can starve the app for + /// 15 s and more despite the background task (seen on CI simulators: the export stalls until the app is reopened). + /// It also fires for transient interruptions (Control Center, a call); an extra flush there is harmless. private static func flushOnBackground(_ core: OtelCore) -> NSObjectProtocol { - NotificationCenter.default.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: .main) { _ in + NotificationCenter.default.addObserver(forName: UIApplication.willResignActiveNotification, object: nil, queue: .main) { _ in let app = UIApplication.shared var task = UIBackgroundTaskIdentifier.invalid // begin/end/expiration all run on the main thread, so `task` needs no lock From 66902d7a5a0d192aef285099048651d1dbfe2090 Mon Sep 17 00:00:00 2001 From: Adam Horodyski Date: Wed, 25 Nov 2026 19:36:41 +0100 Subject: [PATCH 3/4] fix(ios)!: the export URL is the traces endpoint, used as given Drops `tracesUrl` and its test, matching JS and Android: `export.url` goes to the OTLP exporter unchanged. The fixture replay passes the collector's `/v1/traces` URL. Co-Authored-By: Claude Opus 5.5 --- ios/Core/CoreConfig.swift | 2 +- ios/Core/Endpoint.swift | 7 ------- ios/Core/OtelCore.swift | 2 +- ios/CoreTests/EndpointTests.swift | 11 ----------- ios/CoreTests/FixtureExportTests.swift | 2 +- ios/RNOtel/RNOtelConfig.swift | 2 +- 6 files changed, 4 insertions(+), 22 deletions(-) delete mode 100644 ios/CoreTests/EndpointTests.swift diff --git a/ios/Core/CoreConfig.swift b/ios/Core/CoreConfig.swift index b5ce3dd..615c126 100644 --- a/ios/Core/CoreConfig.swift +++ b/ios/Core/CoreConfig.swift @@ -2,7 +2,7 @@ package struct CoreConfig { var serviceName: String var serviceVersion: String? = nil var resourceAttributes: [CoreAttribute] = [] - /// Base URL; see `tracesUrl`. + /// The OTLP/HTTP traces endpoint, used as given. var exportUrl: String var exportHeaders: [String: String] = [:] package init(serviceName: String, serviceVersion: String? = nil, resourceAttributes: [CoreAttribute] = [], diff --git a/ios/Core/Endpoint.swift b/ios/Core/Endpoint.swift index 7f2628a..6bc8412 100644 --- a/ios/Core/Endpoint.swift +++ b/ios/Core/Endpoint.swift @@ -1,12 +1,5 @@ import Foundation -/// Base URL -> traces endpoint: `/v1/traces` is appended unless already present (same rule as JS and Android). -func tracesUrl(_ exportUrl: String) -> String { - var base = Substring(exportUrl) - while base.hasSuffix("/") { base = base.dropLast() } - return base.hasSuffix("/v1/traces") ? String(base) : base + "/v1/traces" -} - /// 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? { diff --git a/ios/Core/OtelCore.swift b/ios/Core/OtelCore.swift index 2c22b4e..c1e5552 100644 --- a/ios/Core/OtelCore.swift +++ b/ios/Core/OtelCore.swift @@ -57,7 +57,7 @@ package final class OtelCore { // 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: tracesUrl(config.exportUrl)).map { + URL(string: config.exportUrl).map { OtlpHttpTraceExporter(endpoint: $0, envVarHeaders: config.exportHeaders.map { ($0.key, $0.value) }) } } diff --git a/ios/CoreTests/EndpointTests.swift b/ios/CoreTests/EndpointTests.swift deleted file mode 100644 index 99db45e..0000000 --- a/ios/CoreTests/EndpointTests.swift +++ /dev/null @@ -1,11 +0,0 @@ -import XCTest -@testable import OtelCore - -final class EndpointTests: XCTestCase { - func testAppendsTracesPathUnlessPresent() { - for u in ["http://h:4318", "http://h:4318/", "http://h:4318/v1/traces", "http://h:4318/v1/traces/"] { - XCTAssertEqual(tracesUrl(u), "http://h:4318/v1/traces", u) - } - XCTAssertEqual(tracesUrl("http://h/base"), "http://h/base/v1/traces") - } -} diff --git a/ios/CoreTests/FixtureExportTests.swift b/ios/CoreTests/FixtureExportTests.swift index f90075b..6d39cc6 100644 --- a/ios/CoreTests/FixtureExportTests.swift +++ b/ios/CoreTests/FixtureExportTests.swift @@ -30,7 +30,7 @@ final class FixtureExportTests: XCTestCase { XCTAssertFalse(files.isEmpty) for f in files { let name = String(f.dropLast(".handoff.json".count)) - let (config, spans) = try FixtureJson.parse(Data(contentsOf: fixtures.appendingPathComponent(f)), exportUrl: collector) + let (config, spans) = try FixtureJson.parse(Data(contentsOf: fixtures.appendingPathComponent(f)), exportUrl: collector + "/v1/traces") try control("begin", ["scenario": name, "platform": "ios"]) let core = OtelCore(config: config, testMode: true) core.handOff(spans) diff --git a/ios/RNOtel/RNOtelConfig.swift b/ios/RNOtel/RNOtelConfig.swift index 4b72fa3..ea436bf 100644 --- a/ios/RNOtel/RNOtelConfig.swift +++ b/ios/RNOtel/RNOtelConfig.swift @@ -6,7 +6,7 @@ public final class RNOtelConfig { public var export = Export(url: "") public struct Export { - /// OTLP base URL; `/v1/traces` is appended unless present. + /// 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 } From 4644baf19f37491015cbaa9c489d7700ac95dd42 Mon Sep 17 00:00:00 2001 From: Adam Horodyski Date: Wed, 25 Nov 2026 19:55:36 +0100 Subject: [PATCH 4/4] test(ios): drop the smoke-js golden with its scenario Co-Authored-By: Claude Opus 5.5 --- verify/expected/smoke-js.ios.otlp.json | 34 -------------------------- 1 file changed, 34 deletions(-) delete mode 100644 verify/expected/smoke-js.ios.otlp.json diff --git a/verify/expected/smoke-js.ios.otlp.json b/verify/expected/smoke-js.ios.otlp.json deleted file mode 100644 index 18cebea..0000000 --- a/verify/expected/smoke-js.ios.otlp.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "resourceSpans": [ - { - "resource": { - "attributes": [ - { - "key": "service.name", - "value": { - "stringValue": "verify" - } - } - ] - }, - "scopeSpans": [ - { - "scope": { - "name": "verify" - }, - "spans": [ - { - "traceId": "0a000000000000000000000000000001", - "spanId": "0a00000000000001", - "name": "smoke", - "kind": 1, - "startTimeUnixNano": "1767225600000000000", - "endTimeUnixNano": "1767225600000001024", - "status": {} - } - ] - } - ] - } - ] -}