import Foundation public struct IPCSubscription: Sendable { public let events: AsyncThrowingStream private let channel: SocketChannel private let task: Task init(events: AsyncThrowingStream, channel: SocketChannel, task: Task) { self.events = events self.channel = channel self.task = task } public func cancel() async { task.cancel() await channel.close() await task.value } } public actor IPCClient { public let socketPath: String private var channels: [UUID: SocketChannel] = [:] public init(socketPath: String? = nil) throws { self.socketPath = try socketPath ?? IPCSocketPath.resolve() _ = try SocketAddress(self.socketPath) } public func request(_ request: IPCRequest) async throws -> IPCResponse { guard request.command != "subscribe" else { throw IPCTransportError.protocolViolation( String(localized: "Use subscribe(topics:) to receive events.", bundle: .module)) } let (id, channel) = try openChannel() do { try await channel.connect(path: socketPath) try await channel.write(IPCCodec.encode(request)) guard let line = try await channel.readLine() else { throw IPCTransportError.closed } let response = try IPCCodec.decode(IPCResponse.self, from: line) try Self.validateResponse(response, id: request.id) await channel.close() channels.removeValue(forKey: id) return response } catch { await channel.close() channels.removeValue(forKey: id) throw error } } public func subscribe(topics: [IPCTopic] = []) async throws -> IPCSubscription { let request = IPCRequest(command: "subscribe", args: topics.map(\.rawValue)) let (id, channel) = try openChannel() do { try await channel.connect(path: socketPath) try await channel.write(IPCCodec.encode(request)) guard let line = try await channel.readLine() else { throw IPCTransportError.closed } let response = try IPCCodec.decode(IPCResponse.self, from: line) try Self.validateResponse(response, id: request.id) if let error = response.error { throw error } let (events, continuation) = AsyncThrowingStream.makeStream( bufferingPolicy: .bufferingOldest(128)) let task = Task { [weak self] in do { while let line = try await channel.readLine() { let message = try IPCCodec.decode(JSONValue.self, from: line) if case .object(let fields) = message, fields["ok"] != nil { let response = try IPCCodec.decode(IPCResponse.self, from: line) try Self.validateResponse(response, id: request.id) if let error = response.error { throw error } throw IPCTransportError.protocolViolation( String(localized: "Expected an event, not another response.", bundle: .module)) } let event = try IPCCodec.decode(IPCEvent.self, from: line) guard event.v == IPCProtocol.version else { throw IPCTransportError.protocolViolation( String(localized: "Unsupported event version: \(event.v)", bundle: .module)) } switch continuation.yield(event) { case .enqueued: break case .dropped: throw IPCError( code: "slow_subscriber", message: String( localized: "The event consumer fell behind. Reconnect and query the current state.", bundle: .module)) case .terminated: await channel.close() await self?.removeChannel(id) return @unknown default: preconditionFailure("Unknown stream yield result") } } continuation.finish() } catch { if Task.isCancelled { continuation.finish() } else { continuation.finish(throwing: error) } } await channel.close() await self?.removeChannel(id) } continuation.onTermination = { _ in task.cancel() Task { await channel.close() } } return IPCSubscription(events: events, channel: channel, task: task) } catch { await channel.close() channels.removeValue(forKey: id) throw error } } public func close() async { let channels = Array(channels.values) self.channels.removeAll() for channel in channels { await channel.close() } } private func openChannel() throws -> (UUID, SocketChannel) { let id = UUID() let channel = SocketChannel(descriptor: try makeSocket()) channels[id] = channel return (id, channel) } private func removeChannel(_ id: UUID) { channels.removeValue(forKey: id) } private static func validateResponse(_ response: IPCResponse, id: IPCRequestID) throws { guard response.v == IPCProtocol.version else { throw IPCTransportError.protocolViolation( String(localized: "Unsupported response version: \(response.v)", bundle: .module)) } guard response.id == id else { throw IPCTransportError.protocolViolation( String(localized: "The response ID does not match the request.", bundle: .module)) } } }