diff --git a/.gitignore b/.gitignore index 062a0fc..84d2f30 100644 --- a/.gitignore +++ b/.gitignore @@ -89,8 +89,3 @@ android/generated .superpowers/ verify/artifacts/ verify/e2e/.e2e/ - -# SwiftPM (Package.swift: ios/Core tests) -.build/ -.swiftpm/ -/Package.resolved diff --git a/ReactNativeOpenTelemetry.podspec b/ReactNativeOpenTelemetry.podspec index 85d382e..3d761ab 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,38 @@ 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']) - + # JsReadableSpan imports opentelemetry-swift too. No spm_dependency here (it would move this pod's module map, see + # above): the core pod's SwiftPM products are built into the products root, which SWIFT_INCLUDE_PATHS searches. + s.dependency 'ReactNativeOpenTelemetryCore', s.version.to_s s.dependency 'React-jsi' s.dependency 'React-callinvoker' 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..63cba5b 100644 --- a/ios/Adapter/HybridOtel.swift +++ b/ios/Adapter/HybridOtel.swift @@ -1,29 +1,28 @@ 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: JS spans are wrapped as otel `ReadableSpan`s here and queued in the core (pod `ReactNativeOpenTelemetryCore`, +/// R24). The core stays free of Nitro's C++-backed types, so the app's AppDelegate can import it without C++ interop. class HybridOtel: HybridOtelSpec { func initialize(config: SeamConfig?) throws -> SeamInitResult { - // 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: attributes(of: $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: wrap 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)") + guard let core = OtelCore.instance else { return } + core.handOff(spans.map { JsReadableSpan($0, resource: core.resource) }) } + /// Off the JS thread (the flush blocks a global queue); resolves even when native never initialized. func flush(timeoutMs: Double) throws -> Promise { - return Promise.resolved() + Promise.parallel { _ = OtelCore.instance?.flush(timeoutMs: timeoutMs) } } } diff --git a/ios/Adapter/JsReadableSpan.swift b/ios/Adapter/JsReadableSpan.swift new file mode 100644 index 0000000..ce74197 --- /dev/null +++ b/ios/Adapter/JsReadableSpan.swift @@ -0,0 +1,146 @@ +import Foundation +import NitroModules +import OpenTelemetryApi +import OpenTelemetrySdk + +/// Never traps on the JS thread (Int(Double) does on NaN or out of range). +func int(_ d: Double) -> Int { Int(exactly: d.rounded(.towardZero)) ?? 0 } + +// Number.isInteger(v): whole and finite (-0 included). Int64.max as Double is 2^63, hence the exclusive bound. +private func isLong(_ v: Double) -> Bool { v == v.rounded() && v >= -9.223372036854775807E18 && v < 9.223372036854775807E18 } + +/// JS numbers become `int` iff Number.isInteger (and they fit), else `double`; the same rule on JS and Kotlin. +func attributes(of list: [SeamAttribute]) -> [String: AttributeValue] { + var out = [String: AttributeValue](minimumCapacity: list.count) + for a in list { + switch a.value { + case let .first(v): out[a.key] = .bool(v) + case let .second(v): out[a.key] = .boolArray(v) + case let .third(v): out[a.key] = .stringArray(v) + case let .fourth(v): out[a.key] = v.allSatisfy(isLong) ? .intArray(v.map { Int($0) }) : .doubleArray(v) + case let .fifth(v): out[a.key] = .string(v) + case let .sixth(v): out[a.key] = isLong(v) ? .int(Int(v)) : .double(v) + } + } + return out +} + +/// OTel HrTime `[seconds, nanos]`; missing elements read as 0 (C4). R22: `Date` holds a Double of seconds, so whole µs +/// come back on a ~256 ns grid (verify/VERIFY.md). +private func date(_ t: [Double]) -> Date { + Date(timeIntervalSince1970: (t.count > 0 ? t[0] : 0) + (t.count > 1 ? t[1] : 0) / 1e9) +} + +/// R21/C5: Swift's SpanKind cases are not in API order, so map the API value explicitly. Unknown -> INTERNAL. +private func spanKind(_ k: Int) -> SpanKind { + switch k { + case 1: return .server + 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: SeamStatus) -> Status { + switch int(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: int(c.traceFlags))), traceState: traceState(c.traceState)) +} + +/// Fixed clock: a JS span is already over, nothing here may read the wall clock. +private final class FixedClock: Clock { + let now: Date + init(now: Date) { self.now = now } +} + +/** + * A finished JS span handed over the seam (R19): the frozen `ReadableSpan` the native BatchSpanProcessor queues. It + * keeps Nitro's struct; only the span context is built on the JS thread (onEnd checks `sampled`), `toSpanData()` runs + * on the BSP worker. SpanData has no public initializer, so it is built through the SDK's own `SpanSdk`, the public + * factory upstream uses. + */ +final class JsReadableSpan: ReadableSpan, @unchecked Sendable { + private let span: SeamSpan + private let resource: Resource + let context: SpanContext + + init(_ span: SeamSpan, resource: Resource) { + self.span = span + self.resource = resource + context = spanContext(span.context) + } + + var kind: SpanKind { spanKind(int(span.kind)) } + var isRecording: Bool { false } + var hasEnded: Bool { true } + var latency: TimeInterval { date(span.end).timeIntervalSince(date(span.start)) } + var description: String { "JsReadableSpan{\(span.name)}" } + // frozen: setters and mutators are no-ops + var name: String { get { span.name } set {} } + var status: Status { get { statusOf(span.status) } set {} } + var instrumentationScopeInfo: InstrumentationScopeInfo { + let scope = span.scope + return InstrumentationScopeInfo(name: scope.name, version: scope.version, schemaUrl: scope.schemaUrl, + attributes: attributes(of: 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 events = span.events + let parent = span.parentSpanId.map { + SpanContext.create(traceId: context.traceId, spanId: SpanId(fromHexString: $0), traceFlags: context.traceFlags, traceState: context.traceState) + } + let end = date(span.end) + let limits = SpanLimits() + .settingEventCountLimit(UInt(max(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: date(span.start)) + for e in events { + sdk.addEvent(name: e.name, attributes: attributes(of: e.attributes), timestamp: date(e.time)) + } + 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/Core/CoreConfig.swift b/ios/Core/CoreConfig.swift new file mode 100644 index 0000000..43366d4 --- /dev/null +++ b/ios/Core/CoreConfig.swift @@ -0,0 +1,22 @@ +import OpenTelemetryApi + +package struct CoreConfig { + var serviceName: String + var serviceVersion: String? = nil + var resourceAttributes: [String: AttributeValue] = [:] + /// The OTLP/HTTP traces endpoint, used as given. + var exportUrl: String + var exportHeaders: [String: String] = [:] + package init(serviceName: String, serviceVersion: String? = nil, resourceAttributes: [String: AttributeValue] = [:], + 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..6bc8412 --- /dev/null +++ b/ios/Core/Endpoint.swift @@ -0,0 +1,11 @@ +import Foundation + +/// Eager check (D8/D9), no exporter built. `URL(string: "not a url")` succeeds on current Foundation, so the scheme +/// and host are checked explicitly. Returns an error message or nil. +func validateExportUrl(_ url: String) -> String? { + guard let u = URL(string: url), let scheme = u.scheme?.lowercased(), ["http", "https"].contains(scheme), + !(u.host ?? "").isEmpty else { + 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..aaa6f36 --- /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.*`). + package 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 = 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: 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: enqueue finished spans; the adapter's wrappers build SpanData on the export queue. + package func handOff(_ spans: [ReadableSpan]) { + for s in spans { bsp.onEnd(span: s) } + } + + /// Blocks the caller up to `timeoutMs`. True when nothing is left unsent: the exporter requeues a failed batch, + /// and its `flush` retries it. + // ponytail: upstream BatchWorker race: if its timer thread has just taken the queue but not yet scheduled the + // export, forceFlush finds nothing and returns before that batch is sent (true while in flight). TracerProviderSdk + // forceFlush goes through the same worker; fix upstream or track in-flight spans if flush-after-reload needs it. + package func flush(timeoutMs: Double) -> Bool { + let deadline = Date().addingTimeInterval(timeoutMs / 1000) + bsp.forceFlush(timeout: timeoutMs / 1000) + 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/RNOtel/RNOtel.swift b/ios/RNOtel/RNOtel.swift new file mode 100644 index 0000000..aed3221 --- /dev/null +++ b/ios/RNOtel/RNOtel.swift @@ -0,0 +1,64 @@ +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 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.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 + 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..304e8cb --- /dev/null +++ b/ios/RNOtel/RNOtelConfig.swift @@ -0,0 +1,24 @@ +import OpenTelemetryApi + +/// Native-first config (spec §4.4): `RNOtel.start { c in c.serviceName = …; c.export = .init(url: …) }`. +public final class RNOtelConfig { + public var serviceName = "" + public var serviceVersion: String? + public var resourceAttributes: [String: String] = [:] + public var export = Export(url: "") + + public struct Export { + /// The OTLP/HTTP traces endpoint (e.g. `https://collector:4318/v1/traces`), used as given. + public var url: String + public var headers: [String: String] + public init(url: String, headers: [String: String] = [:]) { self.url = url; self.headers = headers } + } + + init() {} + + func toCore() -> CoreConfig { + CoreConfig(serviceName: serviceName, serviceVersion: serviceVersion, + resourceAttributes: resourceAttributes.mapValues { .string($0) }, + exportUrl: export.url, exportHeaders: export.headers) + } +} diff --git a/package.json b/package.json index dcc3295..2b9274c 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" @@ -46,10 +47,12 @@ "nitrogen", "android", "ios", - "Package.swift", "ReactNativeOpenTelemetry.podspec", + "ReactNativeOpenTelemetryCore.podspec", "nitro.json", "metro", + "app.plugin.js", + "react-native.config.js", "!ios/build", "!android/build", "!android/gradle", 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/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..a2c0494 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', '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..d16d8bb 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/', '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[] {