Files
Kymo/kymo/Core/Services/ServiceRequest.swift
T

69 lines
3.2 KiB
Swift

import Foundation
/// One short-lived authenticated connection. Every completion releases the timer and connection.
nonisolated enum ServiceRequest {
private static let requirement = CodeIdentity.requirement(at:
Bundle.main.bundleURL.appendingPathComponent("Contents/XPCServices/SMARTService.xpc"))
static func perform<Value: Sendable>(timeout: TimeInterval,
invoke: @escaping (SMARTServiceProtocol, @escaping @Sendable (Value?) -> Void) -> Void
) async -> Value? {
guard let requirement else { return nil }
let request = Pending<Value>()
return await withTaskCancellationHandler {
await withCheckedContinuation { continuation in
request.start(requirement: requirement, timeout: timeout, continuation: continuation, invoke: invoke)
}
} onCancel: { request.finish(nil) }
}
private final class Pending<Value: Sendable>: @unchecked Sendable {
private let lock = NSLock()
private var finished = false
private var continuation: CheckedContinuation<Value?, Never>?
private var connection: NSXPCConnection?
private var timer: DispatchSourceTimer?
func start(requirement: String, timeout: TimeInterval, continuation: CheckedContinuation<Value?, Never>,
invoke: (SMARTServiceProtocol, @escaping @Sendable (Value?) -> Void) -> Void) {
lock.lock()
guard !finished else { lock.unlock(); continuation.resume(returning: nil); return }
self.continuation = continuation
let connection = NSXPCConnection(serviceName: "cn.airnan.kymo.SMARTService")
self.connection = connection
connection.setCodeSigningRequirement(requirement)
connection.remoteObjectInterface = NSXPCInterface(with: SMARTServiceProtocol.self)
connection.invalidationHandler = { [weak self] in self?.finish(nil) }
connection.interruptionHandler = { [weak self] in self?.finish(nil) }
let timer = DispatchSource.makeTimerSource(queue: .global(qos: .utility))
self.timer = timer
timer.schedule(deadline: .now() + timeout)
timer.setEventHandler { [weak self] in self?.finish(nil) }
timer.resume()
connection.resume()
lock.unlock()
guard let proxy = connection.remoteObjectProxyWithErrorHandler({ [weak self] _ in self?.finish(nil) }) as? SMARTServiceProtocol else {
finish(nil); return
}
invoke(proxy) { [weak self] in self?.finish($0) }
}
func finish(_ value: Value?) {
lock.lock()
guard !finished else { lock.unlock(); return }
finished = true
let callback = continuation
let timer = timer
let connection = connection
continuation = nil; self.timer = nil; self.connection = nil
lock.unlock()
timer?.setEventHandler {}
timer?.cancel()
connection?.invalidationHandler = nil
connection?.interruptionHandler = nil
connection?.invalidate()
callback?.resume(returning: value)
}
}
}