Skip to content

Commit 51ef350

Browse files
adhorodyskiclaude
andauthored
v0 [5/7]: iOS — Swift core, Nitro adapter, two pods, Expo config plugin (#23)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 1b433d1 commit 51ef350

41 files changed

Lines changed: 1908 additions & 46 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.gitignore‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -89,8 +89,3 @@ android/generated
8989
.superpowers/
9090
verify/artifacts/
9191
verify/e2e/.e2e/
92-
93-
# SwiftPM (Package.swift: ios/Core tests)
94-
.build/
95-
.swiftpm/
96-
/Package.resolved

‎ReactNativeOpenTelemetry.podspec‎

Lines changed: 28 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ require "json"
22

33
package = JSON.parse(File.read(File.join(__dir__, "package.json")))
44

5+
# The Nitro adapter (Swift with C++ interop) over the pure Swift core pod (R24, spec §4.2).
56
Pod::Spec.new do |s|
67
s.name = "ReactNativeOpenTelemetry"
78
s.version = package["version"]
@@ -13,32 +14,38 @@ Pod::Spec.new do |s|
1314
s.platforms = { :ios => min_ios_version_supported }
1415
s.source = { :git => "https://github.com/callstack/react-native-open-telemetry.git", :tag => "#{s.version}" }
1516

16-
s.source_files = [
17-
"ios/Core/**/*.swift",
18-
"ios/Adapter/**/*.swift",
19-
]
20-
21-
# Test mode is a build flag, never API: `OTEL_TEST_MODE=1 pod install`.
22-
if ENV['OTEL_TEST_MODE'] == '1'
23-
s.pod_target_xcconfig = {
24-
'SWIFT_ACTIVE_COMPILATION_CONDITIONS' => '$(inherited) OTEL_TEST_MODE',
25-
}
26-
end
17+
s.source_files = ["ios/Adapter/**/*.swift"]
18+
19+
# The core pod uses spm_dependency, so in a static-library build React Native's spm.rb builds it straight into the
20+
# products root, and rewrites the app's module map path to match, but not this pod's: CocoaPods still points it at
21+
# `<root>/ReactNativeOpenTelemetryCore/ReactNativeOpenTelemetryCore.modulemap`. Forward that path to the real map, and
22+
# search the root for the core's swiftmodule. Unused (and harmless) with frameworks.
23+
# ponytail: drop when RN's spm.rb rewrites pod-target xcconfigs too.
24+
core_map = '${PODS_CONFIGURATION_BUILD_DIR}/ReactNativeOpenTelemetryCore/ReactNativeOpenTelemetryCore.modulemap'
25+
s.script_phase = {
26+
:name => 'Forward the core module map',
27+
:execution_position => :before_compile,
28+
:always_out_of_date => '1', # no inputs: run every build on purpose (silences the Xcode warning)
29+
:script => %Q{set -e
30+
if [ -f "${PODS_CONFIGURATION_BUILD_DIR}/ReactNativeOpenTelemetryCore.modulemap" ]; then
31+
mkdir -p "${PODS_CONFIGURATION_BUILD_DIR}/ReactNativeOpenTelemetryCore"
32+
echo 'extern module ReactNativeOpenTelemetryCore "../ReactNativeOpenTelemetryCore.modulemap"' > "#{core_map}"
33+
fi
34+
},
35+
}
36+
s.pod_target_xcconfig = {
37+
# `package` declarations of the core are shared through one Swift package name.
38+
'OTHER_SWIFT_FLAGS' => '$(inherited) -package-name ReactNativeOpenTelemetry',
39+
'SWIFT_INCLUDE_PATHS' => '$(inherited) "${PODS_CONFIGURATION_BUILD_DIR}"',
40+
}
2741

2842
# Adds nitrogen/generated/ios/** and nitrogen/generated/shared/**.
2943
load 'nitrogen/generated/ios/ReactNativeOpenTelemetry+autolinking.rb'
3044
add_nitrogen_files(s)
3145

32-
# opentelemetry-swift 2.6 moved OpenTelemetryApi/OpenTelemetrySdk into opentelemetry-swift-core.
33-
spm_dependency(s,
34-
url: 'https://github.com/open-telemetry/opentelemetry-swift',
35-
requirement: { kind: 'upToNextMinorVersion', minimumVersion: '2.6.0' },
36-
products: ['OpenTelemetryProtocolExporterHTTP'])
37-
spm_dependency(s,
38-
url: 'https://github.com/open-telemetry/opentelemetry-swift-core',
39-
requirement: { kind: 'upToNextMinorVersion', minimumVersion: '2.6.0' },
40-
products: ['OpenTelemetrySdk'])
41-
46+
# JsReadableSpan imports opentelemetry-swift too. No spm_dependency here (it would move this pod's module map, see
47+
# above): the core pod's SwiftPM products are built into the products root, which SWIFT_INCLUDE_PATHS searches.
48+
s.dependency 'ReactNativeOpenTelemetryCore', s.version.to_s
4249
s.dependency 'React-jsi'
4350
s.dependency 'React-callinvoker'
4451
install_modules_dependencies(s)
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
require "json"
2+
3+
package = JSON.parse(File.read(File.join(__dir__, "package.json")))
4+
5+
# Pure Swift (R24): the core and the public `RNOtel` API, no Nitro and no C++ interop, so an app's Swift
6+
# `AppDelegate` can `import ReactNativeOpenTelemetryCore`. The Nitro adapter pod (ReactNativeOpenTelemetry) depends on it.
7+
# Autolinking links one podspec per package: apps add `pod 'ReactNativeOpenTelemetryCore', :path => '<package dir>'`.
8+
Pod::Spec.new do |s|
9+
s.name = "ReactNativeOpenTelemetryCore"
10+
s.version = package["version"]
11+
s.summary = package["description"]
12+
s.homepage = package["homepage"]
13+
s.license = package["license"]
14+
s.authors = package["author"]
15+
16+
s.platforms = { :ios => min_ios_version_supported }
17+
s.source = { :git => "https://github.com/callstack/react-native-open-telemetry.git", :tag => "#{s.version}" }
18+
s.swift_version = "5.0"
19+
20+
s.source_files = ["ios/Core/**/*.swift", "ios/RNOtel/**/*.swift"]
21+
22+
# `package` declarations are shared with the adapter pod through one Swift package name.
23+
# Test mode is a build flag, never API: `OTEL_TEST_MODE=1 pod install`.
24+
s.pod_target_xcconfig = {
25+
'OTHER_SWIFT_FLAGS' => '$(inherited) -package-name ReactNativeOpenTelemetry',
26+
}.merge(ENV['OTEL_TEST_MODE'] == '1' ? { 'SWIFT_ACTIVE_COMPILATION_CONDITIONS' => '$(inherited) OTEL_TEST_MODE' } : {})
27+
28+
# opentelemetry-swift 2.6 moved OpenTelemetryApi/OpenTelemetrySdk into opentelemetry-swift-core.
29+
spm_dependency(s,
30+
url: 'https://github.com/open-telemetry/opentelemetry-swift',
31+
requirement: { kind: 'upToNextMinorVersion', minimumVersion: '2.6.0' },
32+
products: ['OpenTelemetryProtocolExporterHTTP'])
33+
spm_dependency(s,
34+
url: 'https://github.com/open-telemetry/opentelemetry-swift-core',
35+
requirement: { kind: 'upToNextMinorVersion', minimumVersion: '2.6.0' },
36+
products: ['OpenTelemetrySdk'])
37+
end

‎app.plugin.js‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Expo config plugin: `"plugins": ["react-native-open-telemetry"]`. It does one thing. Autolinking links one podspec per
2+
// package (the Nitro adapter), and the adapter needs the pure Swift core pod beside it, so this adds
3+
// `pod 'ReactNativeOpenTelemetryCore'` to the generated Podfile. Bare apps add the same line by hand (README).
4+
const path = require('path');
5+
6+
const POD = "pod 'ReactNativeOpenTelemetryCore'";
7+
8+
/** Adds the core pod to the first app target; idempotent. */
9+
function addCorePod(podfile, podPath) {
10+
if (podfile.includes(POD)) return podfile;
11+
const out = podfile.replace(/^(target '.+' do\n)/m, `$1 ${POD}, :path => '${podPath}'\n`);
12+
if (out === podfile) throw new Error('react-native-open-telemetry: no `target ... do` in the Podfile; add the core pod by hand');
13+
return out;
14+
}
15+
16+
// The app's own `expo`, not one beside this file: a linked or pnpm-installed package has none of its own.
17+
const configPlugins = config =>
18+
require(require.resolve('expo/config-plugins', {paths: [config._internal?.projectRoot ?? process.cwd(), __dirname]}));
19+
20+
module.exports = config =>
21+
configPlugins(config).withPodfile(config, c => {
22+
c.modResults.contents = addCorePod(c.modResults.contents, path.relative(c.modRequest.platformProjectRoot, __dirname));
23+
return c;
24+
});
25+
module.exports.addCorePod = addCorePod;

‎ios/Adapter/HybridOtel.swift‎

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,28 @@
11
import Foundation
22
import NitroModules
3-
import OpenTelemetryProtocolExporterHttp
4-
import OpenTelemetrySdk
3+
import ReactNativeOpenTelemetryCore
54

6-
/// Tracer-bullet stub (Task 7): proves the seam and the opentelemetry-swift link; the real adapter is Task 25.
5+
/// The seam: JS spans are wrapped as otel `ReadableSpan`s here and queued in the core (pod `ReactNativeOpenTelemetryCore`,
6+
/// R24). The core stays free of Nitro's C++-backed types, so the app's AppDelegate can import it without C++ interop.
77
class HybridOtel: HybridOtelSpec {
88
func initialize(config: SeamConfig?) throws -> SeamInitResult {
9-
// Touch opentelemetry-swift so a broken package link fails here, not in Task 25.
10-
OtlpHttpTraceExporter().shutdown()
11-
#if OTEL_TEST_MODE
12-
let testMode = true
13-
#else
14-
let testMode = false
15-
#endif
16-
return SeamInitResult(alreadyInitialized: false, testMode: testMode, error: nil)
9+
let r = RNOtel.initialize(config.map {
10+
CoreConfig(serviceName: $0.serviceName, serviceVersion: $0.serviceVersion,
11+
resourceAttributes: attributes(of: $0.resourceAttributes), exportUrl: $0.exportUrl,
12+
exportHeaders: Dictionary($0.exportHeaders.compactMap { h in h.value.asType(String.self).map { (h.key, $0) } },
13+
uniquingKeysWith: { _, last in last }))
14+
})
15+
return SeamInitResult(alreadyInitialized: r.alreadyInitialized, testMode: r.testMode, error: r.error)
1716
}
1817

18+
/// JS thread: wrap and enqueue; SpanData is built on the export queue.
1919
func handOff(spans: [SeamSpan]) throws {
20-
let attrs = spans.reduce(0) { $0 + $1.attributes.count }
21-
let events = spans.reduce(0) { $0 + $1.events.count }
22-
let links = spans.reduce(0) { $0 + $1.links.count }
23-
NSLog("%@", "RNOtel handOff spans=\(spans.count) attrs=\(attrs) events=\(events) links=\(links)")
20+
guard let core = OtelCore.instance else { return }
21+
core.handOff(spans.map { JsReadableSpan($0, resource: core.resource) })
2422
}
2523

24+
/// Off the JS thread (the flush blocks a global queue); resolves even when native never initialized.
2625
func flush(timeoutMs: Double) throws -> Promise<Void> {
27-
return Promise.resolved()
26+
Promise.parallel { _ = OtelCore.instance?.flush(timeoutMs: timeoutMs) }
2827
}
2928
}

‎ios/Adapter/JsReadableSpan.swift‎

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
import Foundation
2+
import NitroModules
3+
import OpenTelemetryApi
4+
import OpenTelemetrySdk
5+
6+
/// Never traps on the JS thread (Int(Double) does on NaN or out of range).
7+
func int(_ d: Double) -> Int { Int(exactly: d.rounded(.towardZero)) ?? 0 }
8+
9+
// Number.isInteger(v): whole and finite (-0 included). Int64.max as Double is 2^63, hence the exclusive bound.
10+
private func isLong(_ v: Double) -> Bool { v == v.rounded() && v >= -9.223372036854775807E18 && v < 9.223372036854775807E18 }
11+
12+
/// JS numbers become `int` iff Number.isInteger (and they fit), else `double`; the same rule on JS and Kotlin.
13+
func attributes(of list: [SeamAttribute]) -> [String: AttributeValue] {
14+
var out = [String: AttributeValue](minimumCapacity: list.count)
15+
for a in list {
16+
switch a.value {
17+
case let .first(v): out[a.key] = .bool(v)
18+
case let .second(v): out[a.key] = .boolArray(v)
19+
case let .third(v): out[a.key] = .stringArray(v)
20+
case let .fourth(v): out[a.key] = v.allSatisfy(isLong) ? .intArray(v.map { Int($0) }) : .doubleArray(v)
21+
case let .fifth(v): out[a.key] = .string(v)
22+
case let .sixth(v): out[a.key] = isLong(v) ? .int(Int(v)) : .double(v)
23+
}
24+
}
25+
return out
26+
}
27+
28+
/// OTel HrTime `[seconds, nanos]`; missing elements read as 0 (C4). R22: `Date` holds a Double of seconds, so whole µs
29+
/// come back on a ~256 ns grid (verify/VERIFY.md).
30+
private func date(_ t: [Double]) -> Date {
31+
Date(timeIntervalSince1970: (t.count > 0 ? t[0] : 0) + (t.count > 1 ? t[1] : 0) / 1e9)
32+
}
33+
34+
/// R21/C5: Swift's SpanKind cases are not in API order, so map the API value explicitly. Unknown -> INTERNAL.
35+
private func spanKind(_ k: Int) -> SpanKind {
36+
switch k {
37+
case 1: return .server
38+
case 2: return .client
39+
case 3: return .producer
40+
case 4: return .consumer
41+
default: return .internal
42+
}
43+
}
44+
45+
/// API SpanStatusCode (UNSET 0, OK 1, ERROR 2). Unknown -> UNSET.
46+
private func statusOf(_ s: SeamStatus) -> Status {
47+
switch int(s.code) {
48+
case 1: return .ok
49+
case 2: return .error(description: s.message ?? "")
50+
default: return .unset
51+
}
52+
}
53+
54+
private func traceState(_ s: String?) -> TraceState {
55+
let entries = (s ?? "").split(separator: ",").compactMap { kv -> TraceState.Entry? in
56+
guard let i = kv.firstIndex(of: "=") else { return nil }
57+
return TraceState.Entry(key: kv[..<i].trimmingCharacters(in: .whitespaces),
58+
value: kv[kv.index(after: i)...].trimmingCharacters(in: .whitespaces))
59+
}
60+
return TraceState(entries: entries) ?? TraceState()
61+
}
62+
63+
private func spanContext(_ c: SeamSpanContext) -> SpanContext {
64+
SpanContext.create(traceId: TraceId(fromHexString: c.traceId), spanId: SpanId(fromHexString: c.spanId),
65+
traceFlags: TraceFlags(fromByte: UInt8(truncatingIfNeeded: int(c.traceFlags))), traceState: traceState(c.traceState))
66+
}
67+
68+
/// Fixed clock: a JS span is already over, nothing here may read the wall clock.
69+
private final class FixedClock: Clock {
70+
let now: Date
71+
init(now: Date) { self.now = now }
72+
}
73+
74+
/**
75+
* A finished JS span handed over the seam (R19): the frozen `ReadableSpan` the native BatchSpanProcessor queues. It
76+
* keeps Nitro's struct; only the span context is built on the JS thread (onEnd checks `sampled`), `toSpanData()` runs
77+
* on the BSP worker. SpanData has no public initializer, so it is built through the SDK's own `SpanSdk`, the public
78+
* factory upstream uses.
79+
*/
80+
final class JsReadableSpan: ReadableSpan, @unchecked Sendable {
81+
private let span: SeamSpan
82+
private let resource: Resource
83+
let context: SpanContext
84+
85+
init(_ span: SeamSpan, resource: Resource) {
86+
self.span = span
87+
self.resource = resource
88+
context = spanContext(span.context)
89+
}
90+
91+
var kind: SpanKind { spanKind(int(span.kind)) }
92+
var isRecording: Bool { false }
93+
var hasEnded: Bool { true }
94+
var latency: TimeInterval { date(span.end).timeIntervalSince(date(span.start)) }
95+
var description: String { "JsReadableSpan{\(span.name)}" }
96+
// frozen: setters and mutators are no-ops
97+
var name: String { get { span.name } set {} }
98+
var status: Status { get { statusOf(span.status) } set {} }
99+
var instrumentationScopeInfo: InstrumentationScopeInfo {
100+
let scope = span.scope
101+
return InstrumentationScopeInfo(name: scope.name, version: scope.version, schemaUrl: scope.schemaUrl,
102+
attributes: attributes(of: scope.attributes))
103+
}
104+
105+
func getAttributes() -> [String: AttributeValue] { attributes(of: span.attributes) }
106+
107+
func toSpanData() -> SpanData {
108+
let attrs = getAttributes()
109+
var dict = AttributesDictionary(capacity: max(attrs.count, 1))
110+
dict.updateValues(attributes: attrs)
111+
let links = span.links.map { SpanData.Link(context: spanContext($0.context), attributes: attributes(of: $0.attributes)) }
112+
let events = span.events
113+
let parent = span.parentSpanId.map {
114+
SpanContext.create(traceId: context.traceId, spanId: SpanId(fromHexString: $0), traceFlags: context.traceFlags, traceState: context.traceState)
115+
}
116+
let end = date(span.end)
117+
let limits = SpanLimits()
118+
.settingEventCountLimit(UInt(max(events.count, 1)))
119+
.settingLinkCountLimit(UInt(max(links.count, 1)))
120+
let sdk = SpanSdk.startSpan(context: context, name: span.name, instrumentationScopeInfo: instrumentationScopeInfo,
121+
kind: kind, parentContext: parent, hasRemoteParent: false, spanLimits: limits,
122+
spanProcessor: MultiSpanProcessor(spanProcessors: []), clock: FixedClock(now: end),
123+
resource: resource, attributes: dict, links: links, totalRecordedLinks: links.count,
124+
startTime: date(span.start))
125+
for e in events {
126+
sdk.addEvent(name: e.name, attributes: attributes(of: e.attributes), timestamp: date(e.time))
127+
}
128+
sdk.status = status
129+
sdk.end(time: end)
130+
return sdk.toSpanData()
131+
}
132+
133+
func setAttribute(key: String, value: AttributeValue?) {}
134+
func setAttributes(_ attributes: [String: AttributeValue]) {}
135+
func addEvent(name: String) {}
136+
func addEvent(name: String, timestamp: Date) {}
137+
func addEvent(name: String, attributes: [String: AttributeValue]) {}
138+
func addEvent(name: String, attributes: [String: AttributeValue], timestamp: Date) {}
139+
func addLink(spanContext: SpanContext, attributes: [String: AttributeValue]) {}
140+
func recordException(_ exception: SpanException) {}
141+
func recordException(_ exception: SpanException, timestamp: Date) {}
142+
func recordException(_ exception: SpanException, attributes: [String: AttributeValue]) {}
143+
func recordException(_ exception: SpanException, attributes: [String: AttributeValue], timestamp: Date) {}
144+
func end() {}
145+
func end(time: Date) {}
146+
}

‎ios/Core/CoreConfig.swift‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import OpenTelemetryApi
2+
3+
package struct CoreConfig {
4+
var serviceName: String
5+
var serviceVersion: String? = nil
6+
var resourceAttributes: [String: AttributeValue] = [:]
7+
/// The OTLP/HTTP traces endpoint, used as given.
8+
var exportUrl: String
9+
var exportHeaders: [String: String] = [:]
10+
package init(serviceName: String, serviceVersion: String? = nil, resourceAttributes: [String: AttributeValue] = [:],
11+
exportUrl: String, exportHeaders: [String: String] = [:]) {
12+
self.serviceName = serviceName; self.serviceVersion = serviceVersion; self.resourceAttributes = resourceAttributes
13+
self.exportUrl = exportUrl; self.exportHeaders = exportHeaders
14+
}
15+
}
16+
17+
/// Mirrors the seam's `SeamInitResult`.
18+
package struct InitResult: Equatable {
19+
package var alreadyInitialized: Bool
20+
package var testMode: Bool
21+
package var error: String? = nil
22+
}

‎ios/Core/Endpoint.swift‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import Foundation
2+
3+
/// Eager check (D8/D9), no exporter built. `URL(string: "not a url")` succeeds on current Foundation, so the scheme
4+
/// and host are checked explicitly. Returns an error message or nil.
5+
func validateExportUrl(_ url: String) -> String? {
6+
guard let u = URL(string: url), let scheme = u.scheme?.lowercased(), ["http", "https"].contains(scheme),
7+
!(u.host ?? "").isEmpty else {
8+
return "invalid exportUrl \"\(url)\": expected http(s)://host[:port]"
9+
}
10+
return nil
11+
}

0 commit comments

Comments
 (0)