Open History to see the last commit
1import Foundation
2import Network
3import OSLog
4
5public protocol WebSocketConnection: Sendable {
6 func send(_ data: Data) async throws
7 func receive() async throws -> Data
8 func close() async
9}
10
11public protocol WebSocketConnecting: Sendable {
12 func connect(to url: URL) async throws -> any WebSocketConnection
13}
14
15public enum WebSocketHandshakeRequest {
16 public static let perMessageDeflateOffer = "permessage-deflate; client_max_window_bits"
17
18 /// URLSessionWebSocketTask accepts a URLRequest for its opening handshake.
19 /// It does not expose the 101 response headers or negotiated extensions,
20 /// so callers can know that compression was offered, not prove that a
21 /// particular connection accepted it.
22 public static func make(
23 url: URL,
24 offersPerMessageDeflate: Bool = true
25 ) -> URLRequest {
26 var request = URLRequest(url: url)
27 if offersPerMessageDeflate {
28 request.setValue(
29 perMessageDeflateOffer,
30 forHTTPHeaderField: "Sec-WebSocket-Extensions"
31 )
32 }
33 return request
34 }
35}
36
37public struct URLSessionWebSocketConnector: WebSocketConnecting {
38 private let session: URLSession
39 private let offersPerMessageDeflate: Bool
40
41 public init(
42 session: URLSession = .shared,
43 offersPerMessageDeflate: Bool = true
44 ) {
45 self.session = session
46 self.offersPerMessageDeflate = offersPerMessageDeflate
47 }
48
49 public func connect(to url: URL) async throws -> any WebSocketConnection {
50 let request = WebSocketHandshakeRequest.make(
51 url: url,
52 offersPerMessageDeflate: offersPerMessageDeflate
53 )
54 let connection = URLSessionWebSocketConnection(session: session, request: request)
55 await connection.open()
56 return connection
57 }
58}
59
60private actor URLSessionWebSocketConnection: WebSocketConnection {
61 private let task: URLSessionWebSocketTask
62
63 init(session: URLSession, request: URLRequest) {
64 task = session.webSocketTask(with: request)
65 }
66
67 func open() {
68 task.resume()
69 }
70
71 func send(_ data: Data) async throws {
72 try await task.send(.data(data))
73 }
74
75 func receive() async throws -> Data {
76 switch try await task.receive() {
77 case let .data(data):
78 return data
79 case let .string(string):
80 guard let data = string.data(using: .utf8) else {
81 throw RPCError.protocolViolation("WebSocket text was not UTF-8.")
82 }
83 return data
84 @unknown default:
85 throw RPCError.protocolViolation("Unknown WebSocket message.")
86 }
87 }
88
89 func close() {
90 task.cancel(with: .goingAway, reason: nil)
91 }
92}
93
94public enum RPCError: LocalizedError, Sendable {
95 case connectionUnavailable
96 case disconnected
97 case responseTimedOut
98 case remote(String)
99 case protocolViolation(String)
100
101 public var errorDescription: String? {
102 switch self {
103 case .connectionUnavailable:
104 "The live command connection is unavailable."
105 case .disconnected: "The environment disconnected."
106 case .responseTimedOut: "The environment did not answer the command in time."
107 case let .remote(message): message
108 case let .protocolViolation(message): message
109 }
110 }
111}
112
113private struct RPCRequestEnvelope: Encodable, Sendable {
114 let _tag = "Request"
115 let id: Int
116 let tag: String
117 let payload: JSONValue
118 let headers: [[String]]
119}
120
121private struct RPCControlEnvelope: Encodable, Sendable {
122 let _tag: String
123 let requestId: Int?
124
125 init(_ tag: String, requestID: Int? = nil) {
126 _tag = tag
127 requestId = requestID
128 }
129}
130
131private struct RPCResponseEnvelope: Decodable, Sendable {
132 struct Exit: Decodable, Sendable {
133 struct Cause: Decodable, Sendable {
134 let _tag: String
135 let error: JSONValue?
136 let defect: JSONValue?
137 }
138
139 let _tag: String
140 let value: JSONValue?
141 let cause: [Cause]?
142 }
143
144 let _tag: String
145 let requestId: Int?
146 let values: [JSONValue]?
147 let exit: Exit?
148 let defect: JSONValue?
149}
150
151/// Implements Effect RPC's JSON socket framing. Subscriptions survive
152/// reconnects; unary calls that crossed a broken connection fail rather than
153/// being replayed, because replaying a command could duplicate side effects.
154public actor WebSocketRPCClient {
155 public typealias EndpointProvider = @Sendable () async throws -> URL
156
157 public enum ResponseDeadline: Sendable, Equatable {
158 case standard
159 /// Setup can run until it completes, disconnects, or its caller cancels.
160 case none
161 }
162
163 private static let logger = Logger(
164 subsystem: "com.t3tools.t3code",
165 category: "WebSocketRPC"
166 )
167
168 private struct UnaryRequest {
169 let envelope: RPCRequestEnvelope
170 let responseDeadline: ResponseDeadline
171 var sent: Bool
172 var connectionWaitTask: Task<Void, Never>?
173 var sendDeadlineTask: Task<Void, Never>?
174 var responseDeadlineTask: Task<Void, Never>?
175 let resume: @Sendable (Result<JSONValue, Error>) -> Void
176 }
177
178 private enum SubscriptionYieldResult: Sendable {
179 case enqueued
180 case dropped
181 case terminated
182 }
183
184 private struct Subscription {
185 let tag: String
186 let payload: JSONValue
187 let reconnect: Bool
188 var requestID: Int?
189 /// The connection that assigned `requestID`. Request IDs are reissued
190 /// after reconnects, so an Interrupt is only valid on this connection.
191 var requestConnectionID: UUID?
192 let batchSize: Int
193 let yield: @Sendable ([JSONValue]) -> SubscriptionYieldResult
194 let finish: @Sendable (Error?) -> Void
195 }
196
197 private struct ConnectionAttempt: Sendable {
198 let connector: any WebSocketConnecting
199 let endpointProvider: EndpointProvider
200 }
201
202 /// Long-lived tasks retain this box, never the client. Each actor hop
203 /// briefly promotes the weak reference, then releases it before the next
204 /// socket receive or reconnect wait.
205 private final class WeakOwner: @unchecked Sendable {
206 weak var value: WebSocketRPCClient?
207
208 init(_ value: WebSocketRPCClient) {
209 self.value = value
210 }
211
212 func connectionAttempt(loopID: UUID) async -> ConnectionAttempt? {
213 guard let value else { return nil }
214 return await value.connectionAttempt(loopID: loopID)
215 }
216
217 func isCurrentConnectionLoop(_ loopID: UUID) async -> Bool {
218 guard let value else { return false }
219 return await value.isCurrentConnectionLoop(loopID)
220 }
221
222 func installConnection(
223 _ connection: any WebSocketConnection,
224 loopID: UUID
225 ) async -> UUID? {
226 guard let value else { return nil }
227 return await value.installConnection(connection, loopID: loopID)
228 }
229
230 func ownsConnection(loopID: UUID, connectionID: UUID) async -> Bool {
231 guard let value else { return false }
232 return await value.ownsConnection(loopID: loopID, connectionID: connectionID)
233 }
234
235 func handle(_ data: Data, connectionID: UUID) async throws -> Bool {
236 guard let value else { return false }
237 return try await value.handle(data, expectedConnectionID: connectionID)
238 }
239
240 func disconnected(connectionID: UUID, subscriptionError: RPCError? = nil) async -> Bool {
241 guard let value else { return false }
242 return await value.disconnected(
243 expectedConnectionID: connectionID,
244 subscriptionError: subscriptionError ?? .disconnected
245 )
246 }
247
248 func finishConnectionLoop(_ loopID: UUID) async {
249 guard let value else { return }
250 await value.finishConnectionLoop(loopID)
251 }
252
253 func sendKeepalive(connectionID: UUID) async -> Bool {
254 guard let value else { return false }
255 return await value.sendKeepalive(expectedConnectionID: connectionID)
256 }
257
258 func beginReconnectDelay(failureCount: Int, loopID: UUID) async -> Task<Bool, Never>? {
259 guard let value else { return nil }
260 return await value.beginReconnectDelay(failureCount: failureCount, loopID: loopID)
261 }
262 }
263
264 private let connector: any WebSocketConnecting
265 private let endpointProvider: EndpointProvider
266 private let connectionWaitTimeout: Duration
267 private let responseTimeout: Duration
268 private let responseDeadlineSleep: @Sendable (Duration) async throws -> Void
269 private let keepaliveInterval: Duration
270 private let subscriptionBufferLimit: Int
271 private let reconnectBackoff: @Sendable (Int) -> Duration
272 private var connection: (any WebSocketConnection)?
273 private var connectionID: UUID?
274 private var loopTask: Task<Void, Never>?
275 private var loopID: UUID?
276 /// The reconnect backoff currently sleeping, so a network path recovery
277 /// can cut it short. Cancelled only while the client is still desired.
278 private var backoffSleepTask: Task<Bool, Never>?
279 private var keepaliveTask: Task<Void, Never>?
280 private var pathMonitor: NWPathMonitor?
281 private var pathIsSatisfied: Bool?
282 private var desired = false
283 private var nextRequestID = 1
284 private var unary: [Int: UnaryRequest] = [:]
285 private var subscriptions: [UUID: Subscription] = [:]
286 private var subscriptionByRequestID: [Int: UUID] = [:]
287 private var awaitingKeepaliveResponse = false
288 private var connectionWaiters: [UUID: (previous: UUID?, continuation: CheckedContinuation<UUID, any Error>)] = [:]
289
290 public init(
291 connector: any WebSocketConnecting = URLSessionWebSocketConnector(),
292 connectionWaitTimeout: Duration = .seconds(4),
293 responseTimeout: Duration = .seconds(30),
294 responseDeadlineSleep: @escaping @Sendable (Duration) async throws -> Void = {
295 try await Task.sleep(for: $0)
296 },
297 keepaliveInterval: Duration = .seconds(5),
298 subscriptionBufferLimit: Int = 1_024,
299 reconnectBackoff: @escaping @Sendable (Int) -> Duration = { failureCount in
300 // Fast first retries, then a 30s cap. Every attempt mints an HTTP
301 // ticket, so a long outage must not hammer the ticket endpoint.
302 // Jitter desynchronizes reconnects across environments so a
303 // server restart doesn't trigger simultaneous ticket mints.
304 let backoff = min(30.0, 0.35 * pow(1.7, Double(failureCount - 1)))
305 return .seconds(backoff * Double.random(in: 0.5...1.0))
306 },
307 endpointProvider: @escaping EndpointProvider
308 ) {
309 self.connector = connector
310 self.connectionWaitTimeout = connectionWaitTimeout
311 self.responseTimeout = responseTimeout
312 self.responseDeadlineSleep = responseDeadlineSleep
313 self.keepaliveInterval = keepaliveInterval > .zero ? keepaliveInterval : .seconds(5)
314 self.subscriptionBufferLimit = max(1, subscriptionBufferLimit)
315 self.reconnectBackoff = reconnectBackoff
316 self.endpointProvider = endpointProvider
317 }
318
319 deinit {
320 loopTask?.cancel()
321 backoffSleepTask?.cancel()
322 keepaliveTask?.cancel()
323 pathMonitor?.cancel()
324 }
325
326 public func start() {
327 desired = true
328 startPathMonitor()
329 guard loopTask == nil else { return }
330 let id = UUID()
331 loopID = id
332 let owner = WeakOwner(self)
333 loopTask = Task {
334 await Self.connectionLoop(owner: owner, id: id)
335 }
336 }
337
338 public func isConnected() -> Bool {
339 connection != nil
340 }
341
342 public func currentConnectionID() -> UUID? {
343 connectionID
344 }
345
346 /// Waits without polling after a subscription cannot use its current socket.
347 public func waitForConnection(after previous: UUID?) async throws -> UUID {
348 try Task.checkCancellation()
349 if let connectionID, connectionID != previous { return connectionID }
350 guard desired else { throw RPCError.disconnected }
351 let waiterID = UUID()
352 return try await withTaskCancellationHandler {
353 try await withCheckedThrowingContinuation { continuation in
354 if Task.isCancelled {
355 continuation.resume(throwing: CancellationError())
356 } else {
357 connectionWaiters[waiterID] = (previous, continuation)
358 }
359 }
360 } onCancel: {
361 Task { await self.cancelConnectionWaiter(waiterID) }
362 }
363 }
364
365 private func cancelConnectionWaiter(_ id: UUID) {
366 connectionWaiters.removeValue(forKey: id)?.continuation.resume(throwing: CancellationError())
367 }
368
369 /// Replaces a socket after suspension without replaying sent commands.
370 /// Resumable subscriptions survive; one-shot owners choose their next cursor.
371 public func reconnect() async {
372 guard desired else { return }
373 loopID = nil
374 loopTask?.cancel()
375 loopTask = nil
376 await disconnected()
377 start()
378 }
379
380 public func stop() async {
381 let closingConnection = connection
382 desired = false
383 loopID = nil
384 loopTask?.cancel()
385 loopTask = nil
386 backoffSleepTask?.cancel()
387 backoffSleepTask = nil
388 pathMonitor?.cancel()
389 pathMonitor = nil
390 pathIsSatisfied = nil
391 keepaliveTask?.cancel()
392 keepaliveTask = nil
393 awaitingKeepaliveResponse = false
394 connection = nil
395 connectionID = nil
396 let waiting = connectionWaiters.values
397 connectionWaiters.removeAll()
398 waiting.forEach { $0.continuation.resume(throwing: RPCError.disconnected) }
399 failUnary(RPCError.disconnected, includingUnsent: true)
400 let active = Array(subscriptions.values)
401 subscriptions.removeAll()
402 subscriptionByRequestID.removeAll()
403 active.forEach { $0.finish(RPCError.disconnected) }
404 // Publish the stopped state before suspension. A new start while the
405 // old socket closes owns independent state and must survive this call.
406 await closingConnection?.close()
407 }
408
409 public func request<Result: Decodable & Sendable>(
410 _ tag: String,
411 payload: JSONValue = .object([:]),
412 responseDeadline: ResponseDeadline = .standard,
413 as type: Result.Type
414 ) async throws -> Result {
415 let raw = try await requestRaw(tag, payload: payload, responseDeadline: responseDeadline)
416 return try raw.decode(type)
417 }
418
419 public func request(
420 _ tag: String,
421 payload: JSONValue = .object([:])
422 ) async throws {
423 _ = try await requestRaw(tag, payload: payload, responseDeadline: .standard)
424 }
425
426 public func subscribe<Value: Decodable & Sendable>(
427 _ tag: String,
428 payload: JSONValue = .object([:]),
429 reconnect: Bool = true,
430 as type: Value.Type
431 ) -> AsyncThrowingStream<Value, Error> {
432 subscribe(tag, payload: payload, reconnect: reconnect, batchSize: 1) {
433 try $0[0].decode(type)
434 }
435 }
436
437 /// Preserve server batches for consumers that can apply several events at once.
438 /// The queue fits normal catch-up chunks. An overflow requests a resync
439 /// without acknowledging lost values. Enqueueing is not consumer progress,
440 /// so server acknowledgements alone cannot bound this queue.
441 public func subscribeBatches<Value: Decodable & Sendable>(
442 _ tag: String,
443 payload: JSONValue = .object([:]),
444 reconnect: Bool = true,
445 as type: Value.Type
446 ) -> AsyncThrowingStream<[Value], Error> {
447 subscribe(tag, payload: payload, reconnect: reconnect,
448 batchSize: min(64, subscriptionBufferLimit)) { values in
449 try values.map { try $0.decode(type) }
450 }
451 }
452
453 private func subscribe<Value: Sendable>(
454 _ tag: String,
455 payload: JSONValue,
456 reconnect: Bool,
457 batchSize: Int,
458 decode: @escaping @Sendable ([JSONValue]) throws -> Value
459 ) -> AsyncThrowingStream<Value, Error> {
460 let subscriptionID = UUID()
461 return AsyncThrowingStream(bufferingPolicy: .bufferingOldest(max(1, subscriptionBufferLimit / batchSize))) {
462 continuation in
463 subscriptions[subscriptionID] = Subscription(
464 tag: tag,
465 payload: payload,
466 reconnect: reconnect,
467 requestID: nil,
468 batchSize: batchSize,
469 yield: { value in
470 do {
471 switch continuation.yield(try decode(value)) {
472 case .enqueued:
473 return .enqueued
474 case .dropped:
475 return .dropped
476 case .terminated:
477 return .terminated
478 @unknown default:
479 return .dropped
480 }
481 } catch {
482 continuation.finish(throwing: error)
483 return .terminated
484 }
485 },
486 finish: { error in
487 if let error {
488 continuation.finish(throwing: error)
489 } else {
490 continuation.finish()
491 }
492 }
493 )
494 continuation.onTermination = { @Sendable [weak self] _ in
495 Task { await self?.removeSubscription(subscriptionID) }
496 }
497 if connection != nil {
498 Task { await self.sendSubscription(subscriptionID) }
499 }
500 start()
501 }
502 }
503
504 /// Registers the stream and its socket identity in one actor turn. A cold
505 /// subscriber must not mistake its first failed socket for a replacement.
506 public func subscribeOnCurrentConnection<Value: Decodable & Sendable>(
507 _ tag: String,
508 payload: JSONValue = .object([:]),
509 as type: Value.Type
510 ) async throws -> (events: AsyncThrowingStream<Value, Error>, connectionID: UUID) {
511 try await subscribeOnCurrentConnection {
512 subscribe(tag, payload: payload, reconnect: false, as: type)
513 }
514 }
515
516 public func subscribeBatchesOnCurrentConnection<Value: Decodable & Sendable>(
517 _ tag: String,
518 payload: JSONValue = .object([:]),
519 as type: Value.Type
520 ) async throws -> (events: AsyncThrowingStream<[Value], Error>, connectionID: UUID) {
521 try await subscribeOnCurrentConnection {
522 subscribeBatches(tag, payload: payload, reconnect: false, as: type)
523 }
524 }
525
526 private func subscribeOnCurrentConnection<Value: Sendable>(
527 makeStream: () -> AsyncThrowingStream<Value, Error>
528 ) async throws -> (events: AsyncThrowingStream<Value, Error>, connectionID: UUID) {
529 try Task.checkCancellation()
530 start()
531 while true {
532 try Task.checkCancellation()
533 if let id = connectionID {
534 return (makeStream(), id)
535 }
536 _ = try await waitForConnection(after: nil)
537 }
538 }
539
540 private func requestRaw(
541 _ tag: String, payload: JSONValue, responseDeadline: ResponseDeadline
542 ) async throws -> JSONValue {
543 start()
544 let id = allocateRequestID()
545 let envelope = RPCRequestEnvelope(
546 id: id,
547 tag: tag,
548 payload: payload,
549 headers: []
550 )
551 return try await withTaskCancellationHandler {
552 try await withCheckedThrowingContinuation { continuation in
553 // If cancellation won the race before onCancel could observe
554 // an installed request, complete locally and never send it.
555 guard !Task.isCancelled else {
556 continuation.resume(throwing: CancellationError())
557 return
558 }
559 unary[id] = UnaryRequest(
560 envelope: envelope,
561 responseDeadline: responseDeadline,
562 sent: false,
563 connectionWaitTask: nil,
564 sendDeadlineTask: nil,
565 responseDeadlineTask: nil,
566 resume: { continuation.resume(with: $0) }
567 )
568 installUnaryDeadlines(id)
569 if connection != nil {
570 Task { await self.sendUnary(id) }
571 }
572 }
573 } onCancel: {
574 Task { await self.cancelUnary(id) }
575 }
576 }
577
578 private static func connectionLoop(owner: WeakOwner, id loopID: UUID) async {
579 var retry = 0
580 while await owner.isCurrentConnectionLoop(loopID), !Task.isCancelled {
581 var openedID: UUID?
582 var openedConnection: (any WebSocketConnection)?
583 do {
584 guard let attempt = await owner.connectionAttempt(loopID: loopID) else { break }
585 let url = try await attempt.endpointProvider()
586 guard await owner.isCurrentConnectionLoop(loopID), !Task.isCancelled else { break }
587 let opened = try await attempt.connector.connect(to: url)
588 openedConnection = opened
589 guard await owner.isCurrentConnectionLoop(loopID), !Task.isCancelled else {
590 await opened.close()
591 break
592 }
593 guard let id = await owner.installConnection(opened, loopID: loopID) else {
594 await opened.close()
595 guard await owner.isCurrentConnectionLoop(loopID), !Task.isCancelled else {
596 break
597 }
598 throw RPCError.disconnected
599 }
600 openedID = id
601 logger.info("WebSocket connection installed")
602 try await withTaskCancellationHandler {
603 while await owner.ownsConnection(loopID: loopID, connectionID: id),
604 !Task.isCancelled {
605 let data = try await opened.receive()
606 guard try await owner.handle(data, connectionID: id) else {
607 throw RPCError.disconnected
608 }
609 // URLSession's `resume()` does not expose a completed
610 // WebSocket handshake. A valid inbound frame is the
611 // first proof that the connection is actually usable.
612 retry = 0
613 }
614 } onCancel: {
615 Task { await opened.close() }
616 }
617 if !(await owner.disconnected(connectionID: id)) {
618 await opened.close()
619 }
620 guard await owner.isCurrentConnectionLoop(loopID), !Task.isCancelled else { break }
621 } catch {
622 logger.warning(
623 "WebSocket connection failed: \(String(describing: error), privacy: .private)"
624 )
625 if let openedID {
626 let protocolError: RPCError?
627 if error is DecodingError {
628 protocolError = .protocolViolation("The server sent an invalid live response.")
629 } else if case let RPCError.protocolViolation(message) = error {
630 protocolError = .protocolViolation(message)
631 } else {
632 protocolError = nil
633 }
634 if !(await owner.disconnected(connectionID: openedID, subscriptionError: protocolError)) {
635 await openedConnection?.close()
636 }
637 } else {
638 await openedConnection?.close()
639 }
640 guard await owner.isCurrentConnectionLoop(loopID), !Task.isCancelled else { break }
641 retry += 1
642 guard let sleep = await owner.beginReconnectDelay(
643 failureCount: retry,
644 loopID: loopID
645 ) else { break }
646 // The sleep is a detached task so this wait does not retain
647 // the client. Cancelling this loop must still end it at once.
648 let interrupted = await withTaskCancellationHandler {
649 await sleep.value
650 } onCancel: {
651 sleep.cancel()
652 }
653 // A network path recovery cancels the sleep while this loop is
654 // still current. Retry immediately with fresh backoff.
655 if interrupted, await owner.isCurrentConnectionLoop(loopID) {
656 retry = 0
657 }
658 }
659 }
660 await owner.finishConnectionLoop(loopID)
661 }
662
663 private func connectionAttempt(loopID: UUID) -> ConnectionAttempt? {
664 guard isCurrentConnectionLoop(loopID) else { return nil }
665 return ConnectionAttempt(connector: connector, endpointProvider: endpointProvider)
666 }
667
668 /// Returns a sleeping task that resolves to `true` when it was cancelled
669 /// before the delay elapsed.
670 private func beginReconnectDelay(failureCount: Int, loopID: UUID) -> Task<Bool, Never>? {
671 guard isCurrentConnectionLoop(loopID) else { return nil }
672 let delay = reconnectBackoff(failureCount)
673 let sleep = Task.detached {
674 do {
675 try await Task.sleep(for: delay)
676 return false
677 } catch {
678 return true
679 }
680 }
681 backoffSleepTask = sleep
682 return sleep
683 }
684
685 private func startPathMonitor() {
686 guard pathMonitor == nil else { return }
687 let monitor = NWPathMonitor()
688 monitor.pathUpdateHandler = { @Sendable [weak self] path in
689 let isSatisfied = path.status == .satisfied
690 Task { await self?.pathStatusChanged(isSatisfied: isSatisfied) }
691 }
692 monitor.start(queue: .global(qos: .utility))
693 pathMonitor = monitor
694 }
695
696 /// Wakes a sleeping backoff when the network comes back. The first report
697 /// and later drops change nothing: only an unsatisfied-to-satisfied edge
698 /// while no socket is live is worth an immediate attempt.
699 private func pathStatusChanged(isSatisfied: Bool) {
700 let wasSatisfied = pathIsSatisfied
701 pathIsSatisfied = isSatisfied
702 guard isSatisfied, wasSatisfied == false, desired, connection == nil else { return }
703 backoffSleepTask?.cancel()
704 backoffSleepTask = nil
705 }
706
707 private func installConnection(
708 _ opened: any WebSocketConnection,
709 loopID: UUID
710 ) async -> UUID? {
711 guard isCurrentConnectionLoop(loopID), !Task.isCancelled else { return nil }
712 let id = UUID()
713 connection = opened
714 connectionID = id
715 await connected()
716 // Sending queued work during setup is actor-reentrant. A send failure
717 // can discard this socket before setup completes.
718 guard isCurrentConnectionLoop(loopID), connectionID == id else { return nil }
719 let ready = connectionWaiters.filter { $0.value.previous != id }
720 for (waiterID, waiter) in ready {
721 connectionWaiters.removeValue(forKey: waiterID)
722 waiter.continuation.resume(returning: id)
723 }
724 return id
725 }
726
727 private func ownsConnection(loopID: UUID, connectionID: UUID) -> Bool {
728 isCurrentConnectionLoop(loopID) && self.connectionID == connectionID
729 }
730
731 private func finishConnectionLoop(_ loopID: UUID) {
732 guard self.loopID == loopID else { return }
733 self.loopID = nil
734 loopTask = nil
735 }
736
737 private func isCurrentConnectionLoop(_ id: UUID) -> Bool {
738 desired && loopID == id
739 }
740
741 private func connected() async {
742 keepaliveTask?.cancel()
743 if let connectionID {
744 let owner = WeakOwner(self)
745 let interval = keepaliveInterval
746 keepaliveTask = Task {
747 await Self.keepaliveLoop(owner: owner, connectionID: connectionID, interval: interval)
748 }
749 }
750 // Snapshot the keys: the sends suspend, and reentrant completions or
751 // failures mutate these dictionaries mid-iteration.
752 for id in Array(unary.keys) {
753 await sendUnary(id)
754 }
755 subscriptionByRequestID.removeAll()
756 for id in Array(subscriptions.keys) {
757 await sendSubscription(id)
758 }
759 }
760
761 @discardableResult
762 private func disconnected(
763 expectedConnectionID: UUID? = nil,
764 subscriptionError: RPCError = .disconnected
765 ) async -> Bool {
766 if let expectedConnectionID, connectionID != expectedConnectionID {
767 return false
768 }
769 let closingConnection = connection
770 keepaliveTask?.cancel()
771 keepaliveTask = nil
772 awaitingKeepaliveResponse = false
773 connection = nil
774 connectionID = nil
775 Self.logger.info("WebSocket connection closed")
776 failUnary(RPCError.disconnected, includingUnsent: false)
777 subscriptionByRequestID.removeAll()
778 let oneShotSubscriptions = subscriptions.filter { !$0.value.reconnect }
779 for (id, subscription) in oneShotSubscriptions {
780 subscriptions.removeValue(forKey: id)
781 subscription.finish(subscriptionError)
782 }
783 for id in Array(subscriptions.keys) {
784 subscriptions[id]?.requestID = nil
785 subscriptions[id]?.requestConnectionID = nil
786 }
787 await closingConnection?.close()
788 return true
789 }
790
791 private func handle(_ data: Data, expectedConnectionID: UUID) async throws -> Bool {
792 guard connectionID == expectedConnectionID else { return false }
793 let response = try JSONDecoder.t3.decode(RPCResponseEnvelope.self, from: data)
794 awaitingKeepaliveResponse = false
795 try await handle(response)
796 return connectionID == expectedConnectionID
797 }
798
799 private func handle(_ response: RPCResponseEnvelope) async throws {
800 switch response._tag {
801 case "Pong":
802 return
803 case "Chunk":
804 guard let requestID = response.requestId,
805 let subscriptionID = subscriptionByRequestID[requestID],
806 let subscription = subscriptions[subscriptionID]
807 else { return }
808 let values = response.values ?? []
809 for start in stride(from: 0, to: values.count, by: subscription.batchSize) {
810 let end = min(start + subscription.batchSize, values.count)
811 switch subscription.yield(Array(values[start..<end])) {
812 case .enqueued:
813 continue
814 case .dropped:
815 let error = RPCError.protocolViolation(
816 "The live stream exceeded its buffered event limit."
817 )
818 if !subscription.reconnect {
819 subscriptionByRequestID.removeValue(forKey: requestID)
820 subscriptions.removeValue(forKey: subscriptionID)
821 subscription.finish(error)
822 }
823 throw error
824 case .terminated:
825 await removeSubscription(subscriptionID)
826 return
827 }
828 }
829 try await sendControl("Ack", requestID: requestID)
830 case "Exit":
831 guard let requestID = response.requestId, let exit = response.exit else { return }
832 if unary[requestID] != nil {
833 if exit._tag == "Success" {
834 completeUnary(requestID, with: .success(exit.value ?? .null))
835 } else {
836 completeUnary(requestID, with: .failure(remoteError(exit)))
837 }
838 return
839 }
840 guard let subscriptionID = subscriptionByRequestID.removeValue(forKey: requestID),
841 let subscription = subscriptions.removeValue(forKey: subscriptionID)
842 else { return }
843 if exit.cause?.contains(where: { $0._tag == "Die" }) == true {
844 subscription.finish(RPCError.protocolViolation("The server could not complete the live request."))
845 } else {
846 subscription.finish(exit._tag == "Success" ? nil : remoteError(exit))
847 }
848 case "Defect", "ClientProtocolError":
849 throw RPCError.protocolViolation("The server reported an RPC protocol error.")
850 default:
851 throw RPCError.protocolViolation("Unknown RPC response \(response._tag).")
852 }
853 }
854
855 private func sendUnary(_ id: Int) async {
856 guard let connection,
857 let connectionID,
858 var request = unary[id],
859 !request.sent else { return }
860 // Actor methods are reentrant at the send below. Record that this
861 // command crossed the socket boundary first so a concurrent
862 // disconnect fails it instead of replaying an ambiguous mutation.
863 request.sent = true
864 unary[id] = request
865 startUnarySendDeadline(id, connectionID: connectionID)
866 do {
867 try await connection.send(JSONEncoder.t3.encode(request.envelope))
868 startUnaryResponseDeadline(id)
869 } catch {
870 // A response, disconnect, or stop may have completed the request
871 // while send was suspended. Only its current owner may resume it.
872 completeUnary(id, with: .failure(RPCError.disconnected))
873 await disconnected(expectedConnectionID: connectionID)
874 }
875 }
876
877 private func sendSubscription(_ subscriptionID: UUID) async {
878 guard let connection,
879 let connectionID,
880 var subscription = subscriptions[subscriptionID],
881 subscription.requestID == nil else { return }
882 let requestID = allocateRequestID()
883 let envelope = RPCRequestEnvelope(
884 id: requestID,
885 tag: subscription.tag,
886 payload: subscription.payload,
887 headers: []
888 )
889 // Install ownership before suspending in send. A very fast response can
890 // otherwise arrive before the request is routable, while termination
891 // during the send must be able to remove the exact in-flight mapping.
892 subscription.requestID = requestID
893 subscription.requestConnectionID = connectionID
894 subscriptions[subscriptionID] = subscription
895 subscriptionByRequestID[requestID] = subscriptionID
896 do {
897 try await connection.send(JSONEncoder.t3.encode(envelope))
898 } catch {
899 // Retain the subscription for the next socket, but make the send
900 // failure visible to the connection loop by closing this socket.
901 await disconnected(expectedConnectionID: connectionID)
902 }
903 }
904
905 private func removeSubscription(_ id: UUID) async {
906 guard let subscription = subscriptions.removeValue(forKey: id) else { return }
907 if let requestID = subscription.requestID {
908 subscriptionByRequestID.removeValue(forKey: requestID)
909 // A termination racing a reconnect must not interrupt whichever
910 // subscription now owns this request ID on the new connection.
911 if subscription.requestConnectionID == connectionID {
912 try? await sendControl("Interrupt", requestID: requestID)
913 }
914 }
915 }
916
917 private static func keepaliveLoop(
918 owner: WeakOwner,
919 connectionID: UUID,
920 interval: Duration
921 ) async {
922 while !Task.isCancelled {
923 try? await Task.sleep(for: interval)
924 guard !Task.isCancelled,
925 await owner.sendKeepalive(connectionID: connectionID) else { return }
926 }
927 }
928
929 private func sendKeepalive(expectedConnectionID: UUID) async -> Bool {
930 guard desired, connectionID == expectedConnectionID, connection != nil else {
931 return false
932 }
933 if awaitingKeepaliveResponse {
934 await disconnected(expectedConnectionID: expectedConnectionID)
935 return false
936 }
937 do {
938 awaitingKeepaliveResponse = true
939 try await sendControl("Ping", requestID: nil)
940 return connectionID == expectedConnectionID
941 } catch {
942 return false
943 }
944 }
945
946 private func sendControl(_ tag: String, requestID: Int?) async throws {
947 guard let connection, let connectionID else { throw RPCError.disconnected }
948 do {
949 try await connection.send(
950 JSONEncoder.t3.encode(RPCControlEnvelope(tag, requestID: requestID))
951 )
952 } catch {
953 await disconnected(expectedConnectionID: connectionID)
954 throw RPCError.disconnected
955 }
956 }
957
958 private func failUnary(_ error: Error, includingUnsent: Bool) {
959 let failedIDs = unary.compactMap { id, request in
960 includingUnsent || request.sent ? id : nil
961 }
962 for id in failedIDs {
963 completeUnary(id, with: .failure(error))
964 }
965 }
966
967 private func failUnaryIfUnsent(_ id: Int) {
968 guard let request = unary[id], !request.sent else { return }
969 completeUnary(id, with: .failure(RPCError.connectionUnavailable))
970 }
971
972 private func installUnaryDeadlines(_ id: Int) {
973 guard var request = unary[id] else { return }
974 let connectionWaitTimeout = connectionWaitTimeout
975 request.connectionWaitTask = Task { [weak self] in
976 do {
977 try await Task.sleep(for: connectionWaitTimeout)
978 } catch {
979 return
980 }
981 await self?.failUnaryIfUnsent(id)
982 }
983 unary[id] = request
984 }
985
986 private func startUnaryResponseDeadline(_ id: Int) {
987 guard var request = unary[id], request.sent else { return }
988 request.connectionWaitTask?.cancel()
989 request.connectionWaitTask = nil
990 request.sendDeadlineTask?.cancel()
991 request.sendDeadlineTask = nil
992 guard request.responseDeadline == .standard else {
993 unary[id] = request
994 return
995 }
996 let responseTimeout = responseTimeout
997 let sleep = responseDeadlineSleep
998 request.responseDeadlineTask = Task { [weak self] in
999 do {
1000 try await sleep(responseTimeout)
1001 } catch {
1002 return
1003 }
1004 await self?.failUnaryOnResponseDeadline(id)
1005 }
1006 unary[id] = request
1007 }
1008
1009 private func startUnarySendDeadline(_ id: Int, connectionID: UUID) {
1010 guard var request = unary[id], request.sent else { return }
1011 request.connectionWaitTask?.cancel()
1012 request.connectionWaitTask = nil
1013 let sendTimeout = responseTimeout
1014 request.sendDeadlineTask = Task { [weak self] in
1015 do {
1016 try await Task.sleep(for: sendTimeout)
1017 } catch {
1018 return
1019 }
1020 await self?.failUnaryOnSendDeadline(id, connectionID: connectionID)
1021 }
1022 unary[id] = request
1023 }
1024
1025 private func failUnaryOnSendDeadline(_ id: Int, connectionID: UUID) async {
1026 guard let request = unary[id],
1027 request.sent,
1028 request.sendDeadlineTask != nil else { return }
1029 completeUnary(id, with: .failure(RPCError.responseTimedOut))
1030 await disconnected(expectedConnectionID: connectionID)
1031 }
1032
1033 private func failUnaryOnResponseDeadline(_ id: Int) async {
1034 guard let request = unary[id] else { return }
1035 let sent = request.sent
1036 completeUnary(id, with: .failure(RPCError.responseTimedOut))
1037 if sent {
1038 try? await sendControl("Interrupt", requestID: id)
1039 }
1040 }
1041
1042 private func cancelUnary(_ id: Int) async {
1043 guard let request = unary[id] else { return }
1044 let sent = request.sent
1045 completeUnary(id, with: .failure(CancellationError()))
1046 if sent {
1047 try? await sendControl("Interrupt", requestID: id)
1048 }
1049 }
1050
1051 private func completeUnary(_ id: Int, with result: Result<JSONValue, Error>) {
1052 guard let request = unary.removeValue(forKey: id) else { return }
1053 request.connectionWaitTask?.cancel()
1054 request.sendDeadlineTask?.cancel()
1055 request.responseDeadlineTask?.cancel()
1056 request.resume(result)
1057 }
1058
1059 private func remoteError(_ exit: RPCResponseEnvelope.Exit) -> RPCError {
1060 let value = exit.cause?.first?.error
1061 let message = value?["message"]?.stringValue
1062 ?? value?["detail"]?.stringValue
1063 ?? "The environment rejected the RPC request."
1064 return .remote(message)
1065 }
1066
1067 private func allocateRequestID() -> Int {
1068 defer { nextRequestID += 1 }
1069 return nextRequestID
1070 }
1071}