|
| 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 | +} |
0 commit comments