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] = []
/// Base URL; see `tracesUrl`.
var exportUrl: String
var exportHeaders: [String: String] = [:]
package init(serviceName: String, serviceVersion: String? = nil, resourceAttributes: [CoreAttribute] = [],
exportUrl: String, exportHeaders: [String: String] = [:]) {
self.serviceName = serviceName; self.serviceVersion = serviceVersion; self.resourceAttributes = resourceAttributes
self.exportUrl = exportUrl; self.exportHeaders = exportHeaders
}
}

/// Mirrors the seam's `SeamInitResult`.
package struct InitResult: Equatable {
package var alreadyInitialized: Bool
package var testMode: Bool
package var error: String? = nil
}
18 changes: 18 additions & 0 deletions ios/Core/Endpoint.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import Foundation

/// Base URL -> traces endpoint: `/v1/traces` is appended unless already present (same rule as JS and Android).
func tracesUrl(_ exportUrl: String) -> String {
var base = Substring(exportUrl)
while base.hasSuffix("/") { base = base.dropLast() }
return base.hasSuffix("/v1/traces") ? String(base) : base + "/v1/traces"
}

/// Eager check (D8/D9), no exporter built. `URL(string: "not a url")` succeeds on current Foundation, so the scheme
/// and host are checked explicitly. Returns an error message or nil.
func validateExportUrl(_ url: String) -> String? {
guard let u = URL(string: url), let scheme = u.scheme?.lowercased(), ["http", "https"].contains(scheme),
!(u.host ?? "").isEmpty else {
return "invalid exportUrl \"\(url)\": expected http(s)://host[:port]"
}
return nil
}
Loading