Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -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]
)
47 changes: 26 additions & 21 deletions ReactNativeOpenTelemetry.podspec
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand All @@ -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
# `<root>/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)
Expand Down
37 changes: 37 additions & 0 deletions ReactNativeOpenTelemetryCore.podspec
Original file line number Diff line number Diff line change
@@ -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 => '<package dir>'`.
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
25 changes: 25 additions & 0 deletions app.plugin.js
Original file line number Diff line number Diff line change
@@ -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;
59 changes: 43 additions & 16 deletions ios/Adapter/HybridOtel.swift
Original file line number Diff line number Diff line change
@@ -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<Void> {
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)
}
}
}
20 changes: 20 additions & 0 deletions ios/Core/Attributes.swift
Original file line number Diff line number Diff line change
@@ -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
}
20 changes: 20 additions & 0 deletions ios/Core/CoreConfig.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package struct CoreConfig {
var serviceName: String
var serviceVersion: String? = nil
var resourceAttributes: [CoreAttribute] = []
/// The OTLP/HTTP traces endpoint, used as given.
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
}
11 changes: 11 additions & 0 deletions ios/Core/Endpoint.swift
Original file line number Diff line number Diff line change
@@ -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
}
106 changes: 106 additions & 0 deletions ios/Core/OtelCore.swift
Original file line number Diff line number Diff line change
@@ -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: 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 } }
}
Loading