Skip to content
Merged
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
5 changes: 0 additions & 5 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,3 @@ android/generated
.superpowers/
verify/artifacts/
verify/e2e/.e2e/

# SwiftPM (Package.swift: ios/Core tests)
.build/
.swiftpm/
/Package.resolved
49 changes: 28 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,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
# `<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'])

# 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)
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;
31 changes: 15 additions & 16 deletions ios/Adapter/HybridOtel.swift
Original file line number Diff line number Diff line change
@@ -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<Void> {
return Promise.resolved()
Promise.parallel { _ = OtelCore.instance?.flush(timeoutMs: timeoutMs) }
}
}
146 changes: 146 additions & 0 deletions ios/Adapter/JsReadableSpan.swift
Original file line number Diff line number Diff line change
@@ -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[..<i].trimmingCharacters(in: .whitespaces),
value: kv[kv.index(after: i)...].trimmingCharacters(in: .whitespaces))
}
return TraceState(entries: entries) ?? TraceState()
}

private func spanContext(_ c: SeamSpanContext) -> 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) {}
}
22 changes: 22 additions & 0 deletions ios/Core/CoreConfig.swift
Original file line number Diff line number Diff line change
@@ -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
}
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
}
Loading