import Foundation import Synchronization import os public enum DetectionTraceOutcome: String, Sendable { case flushed, dropped } public protocol DetectionTraceSource: Sendable { func begin() -> DetectionTrace } /// Delivery holds protect later siblings; queued holds protect the delay until the first flush. public final class DetectionTrace: Sendable, Equatable { private typealias Completion = @Sendable (DetectionTraceOutcome) -> Void private struct State { var completion: Completion? var deliveries = 0 var queuedEvents = 0 mutating func takeCompletion(ifUnowned: Bool = false) -> Completion? { guard !ifUnowned || (deliveries == 0 && queuedEvents == 0) else { return nil } defer { completion = nil } return completion } } public let startedAt: UInt64 private let state: Mutex public init(startedAt: UInt64, completion: @escaping @Sendable (DetectionTraceOutcome) -> Void) { self.startedAt = startedAt self.state = Mutex(State(completion: completion)) } public func retainDelivery() { state.withLock { if $0.completion != nil { $0.deliveries += 1 } } } public func releaseDelivery() { let finish = state.withLock { state in guard state.completion != nil else { return Completion?.none } precondition(state.deliveries > 0) state.deliveries -= 1 return state.takeCompletion(ifUnowned: true) } finish?(.dropped) } public func enqueue() { state.withLock { if $0.completion != nil { $0.queuedEvents += 1 } } } public func dequeue(_ outcome: DetectionTraceOutcome) { let finish = state.withLock { state in guard state.completion != nil else { return Completion?.none } precondition(state.queuedEvents > 0) state.queuedEvents -= 1 return state.takeCompletion(ifUnowned: outcome == .dropped) } finish?(outcome) } public func dropIfUnowned() { let finish = state.withLock { $0.takeCompletion(ifUnowned: true) } finish?(.dropped) } public func finish(_ outcome: DetectionTraceOutcome) { let finish = state.withLock { $0.takeCompletion() } finish?(outcome) } public static func == (lhs: DetectionTrace, rhs: DetectionTrace) -> Bool { lhs === rhs } deinit { finish(.dropped) } } public final class SignpostDetectionTraceSource: DetectionTraceSource { public init() {} public func begin() -> DetectionTrace { let startedAt = DispatchTime.now().uptimeNanoseconds let interval = ParcelSignposts.beginIfEnabled(.detect) return DetectionTrace(startedAt: startedAt) { outcome in ParcelSignposts.endIfStarted(.detect, interval, value: outcome == .flushed ? 0 : 1) } } }