Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

WebSocketRPC.swift

869 lines31.7 KB

1import Foundation
2import OSLog
3​
4public protocol WebSocketConnection: Sendable {
5 func send(_ data: Data) async throws
6 func receive() async throws -> Data
7 func close() async
8}
9​
10public protocol WebSocketConnecting: Sendable {
11 func connect(to url: URL) async throws -> any WebSocketConnection
13​
14public enum WebSocketHandshakeRequest {
15 public static let perMessageDeflateOffer = "permessage-deflate; client_max_window_bits"
16​
17 /// URLSessionWebSocketTask accepts a URLRequest for its opening handshake.
18 /// It does not expose the 101 response headers or negotiated extensions,
19 /// so callers can know that compression was offered, not prove that a
20 /// particular connection accepted it.
21 public static func make(
22 url: URL,
23 offersPerMessageDeflate: Bool = true
24 ) -> URLRequest {
25 var request = URLRequest(url: url)
26 if offersPerMessageDeflate {
27 request.setValue(
28 perMessageDeflateOffer,
29 forHTTPHeaderField: "Sec-WebSocket-Extensions"
30 )
31 }
32 return request
33 }
35​
36public struct URLSessionWebSocketConnector: WebSocketConnecting {
37 private let session: URLSession
38 private let offersPerMessageDeflate: Bool
39​
40 public init(
41 session: URLSession = .shared,
42 offersPerMessageDeflate: Bool = true
43 ) {
44 self.session = session
45 self.offersPerMessageDeflate = offersPerMessageDeflate
46 }
47​
48 public func connect(to url: URL) async throws -> any WebSocketConnection {
49 let request = WebSocketHandshakeRequest.make(
50 url: url,
51 offersPerMessageDeflate: offersPerMessageDeflate
52 )
53 let connection = URLSessionWebSocketConnection(session: session, request: request)
54 await connection.open()
55 return connection
56 }
58​
59private actor URLSessionWebSocketConnection: WebSocketConnection {
60 private let task: URLSessionWebSocketTask
61​
62 init(session: URLSession, request: URLRequest) {
63 task = session.webSocketTask(with: request)
64 }
65​
66 func open() {
67 task.resume()
68 }
69​
70 func send(_ data: Data) async throws {
71 try await task.send(.data(data))
72 }
73​
74 func receive() async throws -> Data {
75 switch try await task.receive() {
76 case let .data(data):
77 return data
78 case let .string(string):
79 guard let data = string.data(using: .utf8) else {
80 throw RPCError.protocolViolation("WebSocket text was not UTF-8.")
81 }
82 return data
83 @unknown default:
84 throw RPCError.protocolViolation("Unknown WebSocket message.")
85 }
86 }
87​
88 func close() {
89 task.cancel(with: .goingAway, reason: nil)
90 }
92​
93public enum RPCError: LocalizedError, Sendable {
94 case connectionUnavailable
95 case disconnected
96 case responseTimedOut
97 case remote(String)
98 case protocolViolation(String)
99​
100 public var errorDescription: String? {
101 switch self {
102 case .connectionUnavailable:
103 "The live command connection is unavailable."
104 case .disconnected: "The environment disconnected."
105 case .responseTimedOut: "The environment did not answer the command in time."
106 case let .remote(message): message
107 case let .protocolViolation(message): message
108 }
109 }
111​
112private struct RPCRequestEnvelope: Encodable, Sendable {
113 let _tag = "Request"
114 let id: Int
115 let tag: String
116 let payload: JSONValue
117 let headers: [[String]]
119​
120private struct RPCControlEnvelope: Encodable, Sendable {
121 let _tag: String
122 let requestId: Int?
123​
124 init(_ tag: String, requestID: Int? = nil) {
125 _tag = tag
126 requestId = requestID
127 }
129​
130private struct RPCResponseEnvelope: Decodable, Sendable {
131 struct Exit: Decodable, Sendable {
132 struct Cause: Decodable, Sendable {
133 let _tag: String
134 let error: JSONValue?
135 let defect: JSONValue?
136 }
137​
138 let _tag: String
139 let value: JSONValue?
140 let cause: [Cause]?
141 }
142​
143 let _tag: String
144 let requestId: Int?
145 let values: [JSONValue]?
146 let exit: Exit?
147 let defect: JSONValue?
149​
150/// Implements Effect RPC's JSON socket framing. Subscriptions survive
151/// reconnects; unary calls that crossed a broken connection fail rather than
152/// being replayed, because replaying a command could duplicate side effects.
153public actor WebSocketRPCClient {
154 public typealias EndpointProvider = @Sendable () async throws -> URL
155​
156 private static let logger = Logger(
157 subsystem: "com.t3tools.t3code",
158 category: "WebSocketRPC"
159 )
160​
161 private struct UnaryRequest {
162 let envelope: RPCRequestEnvelope
163 var sent: Bool
164 var connectionWaitTask: Task<Void, Never>?
165 var sendDeadlineTask: Task<Void, Never>?
166 var responseDeadlineTask: Task<Void, Never>?
167 let resume: @Sendable (Result<JSONValue, Error>) -> Void
168 }
169​
170 private enum SubscriptionYieldResult: Sendable {
171 case enqueued
172 case dropped
173 case terminated
174 }
175​
176 private struct Subscription {
177 let tag: String
178 let payload: JSONValue
179 let reconnect: Bool
180 var requestID: Int?
181 /// The connection that assigned `requestID`. Request IDs are reissued
182 /// after reconnects, so an Interrupt is only valid on this connection.
183 var requestConnectionID: UUID?
184 let yield: @Sendable (JSONValue) -> SubscriptionYieldResult
185 let finish: @Sendable (Error?) -> Void
186 }
187​
188 private struct ConnectionAttempt: Sendable {
189 let connector: any WebSocketConnecting
190 let endpointProvider: EndpointProvider
191 }
192​
193 /// Long-lived tasks retain this box, never the client. Each actor hop
194 /// briefly promotes the weak reference, then releases it before the next
195 /// socket receive or reconnect wait.
196 private final class WeakOwner: @unchecked Sendable {
197 weak var value: WebSocketRPCClient?
198​
199 init(_ value: WebSocketRPCClient) {
200 self.value = value
201 }
202​
203 func connectionAttempt(loopID: UUID) async -> ConnectionAttempt? {
204 guard let value else { return nil }
205 return await value.connectionAttempt(loopID: loopID)
206 }
207​
208 func isCurrentConnectionLoop(_ loopID: UUID) async -> Bool {
209 guard let value else { return false }
210 return await value.isCurrentConnectionLoop(loopID)
211 }
212​
213 func installConnection(
214 _ connection: any WebSocketConnection,
215 loopID: UUID
216 ) async -> UUID? {
217 guard let value else { return nil }
218 return await value.installConnection(connection, loopID: loopID)
219 }
220​
221 func ownsConnection(loopID: UUID, connectionID: UUID) async -> Bool {
222 guard let value else { return false }
223 return await value.ownsConnection(loopID: loopID, connectionID: connectionID)
224 }
225​
226 func handle(_ data: Data, connectionID: UUID) async throws -> Bool {
227 guard let value else { return false }
228 return try await value.handle(data, expectedConnectionID: connectionID)
229 }
230​
231 func disconnected(connectionID: UUID) async -> Bool {
232 guard let value else { return false }
233 return await value.disconnected(expectedConnectionID: connectionID)
234 }
235​
236 func finishConnectionLoop(_ loopID: UUID) async {
237 guard let value else { return }
238 await value.finishConnectionLoop(loopID)
239 }
240​
241 func sendKeepalive(connectionID: UUID) async -> Bool {
242 guard let value else { return false }
243 return await value.sendKeepalive(expectedConnectionID: connectionID)
244 }
245​
246 func reconnectDelay(failureCount: Int, loopID: UUID) async -> Duration? {
247 guard let value else { return nil }
248 return await value.reconnectDelay(failureCount: failureCount, loopID: loopID)
249 }
250 }
251​
252 private let connector: any WebSocketConnecting
253 private let endpointProvider: EndpointProvider
254 private let connectionWaitTimeout: Duration
255 private let responseTimeout: Duration
256 private let keepaliveInterval: Duration
257 private let subscriptionBufferLimit: Int
258 private let reconnectBackoff: @Sendable (Int) -> Duration
259 private var connection: (any WebSocketConnection)?
260 private var connectionID: UUID?
261 private var loopTask: Task<Void, Never>?
262 private var loopID: UUID?
263 private var keepaliveTask: Task<Void, Never>?
264 private var desired = false
265 private var nextRequestID = 1
266 private var unary: [Int: UnaryRequest] = [:]
267 private var subscriptions: [UUID: Subscription] = [:]
268 private var subscriptionByRequestID: [Int: UUID] = [:]
269 private var awaitingKeepaliveResponse = false
270​
271 public init(
272 connector: any WebSocketConnecting = URLSessionWebSocketConnector(),
273 connectionWaitTimeout: Duration = .seconds(4),
274 responseTimeout: Duration = .seconds(30),
275 keepaliveInterval: Duration = .seconds(5),
276 subscriptionBufferLimit: Int = 128,
277 reconnectBackoff: @escaping @Sendable (Int) -> Duration = { failureCount in
278 // Jitter desynchronizes reconnects across environments so a
279 // server restart doesn't trigger simultaneous ticket mints.
280 let backoff = min(5.0, 0.35 * pow(1.7, Double(failureCount - 1)))
281 return .seconds(backoff * Double.random(in: 0.5...1.0))
282 },
283 endpointProvider: @escaping EndpointProvider
284 ) {
285 self.connector = connector
286 self.connectionWaitTimeout = connectionWaitTimeout
287 self.responseTimeout = responseTimeout
288 self.keepaliveInterval = keepaliveInterval > .zero ? keepaliveInterval : .seconds(5)
289 self.subscriptionBufferLimit = max(1, subscriptionBufferLimit)
290 self.reconnectBackoff = reconnectBackoff
291 self.endpointProvider = endpointProvider
292 }
293​
294 deinit {
295 loopTask?.cancel()
296 keepaliveTask?.cancel()
297 }
298​
299 public func start() {
300 desired = true
301 guard loopTask == nil else { return }
302 let id = UUID()
303 loopID = id
304 let owner = WeakOwner(self)
305 loopTask = Task {
306 await Self.connectionLoop(owner: owner, id: id)
307 }
308 }
309​
310 public func isConnected() -> Bool {
311 connection != nil
312 }
313​
314 /// Replaces a socket after suspension without replaying sent commands.
315 /// Resumable subscriptions survive; one-shot owners choose their next cursor.
316 public func reconnect() async {
317 guard desired else { return }
318 loopID = nil
319 loopTask?.cancel()
320 loopTask = nil
321 await disconnected()
322 start()
323 }
324​
325 public func stop() async {
326 let closingConnection = connection
327 desired = false
328 loopID = nil
329 loopTask?.cancel()
330 loopTask = nil
331 keepaliveTask?.cancel()
332 keepaliveTask = nil
333 awaitingKeepaliveResponse = false
334 connection = nil
335 connectionID = nil
336 failUnary(RPCError.disconnected, includingUnsent: true)
337 let active = Array(subscriptions.values)
338 subscriptions.removeAll()
339 subscriptionByRequestID.removeAll()
340 active.forEach { $0.finish(RPCError.disconnected) }
341 // Publish the stopped state before suspension. A new start while the
342 // old socket closes owns independent state and must survive this call.
343 await closingConnection?.close()
344 }
345​
346 public func request<Result: Decodable & Sendable>(
347 _ tag: String,
348 payload: JSONValue = .object([:]),
349 as type: Result.Type
350 ) async throws -> Result {
351 let raw = try await requestRaw(tag, payload: payload)
352 return try raw.decode(type)
353 }
354​
355 public func request(
356 _ tag: String,
357 payload: JSONValue = .object([:])
358 ) async throws {
359 _ = try await requestRaw(tag, payload: payload)
360 }
361​
362 public func subscribe<Value: Decodable & Sendable>(
363 _ tag: String,
364 payload: JSONValue = .object([:]),
365 reconnect: Bool = true,
366 as type: Value.Type
367 ) -> AsyncThrowingStream<Value, Error> {
368 let subscriptionID = UUID()
369 return AsyncThrowingStream(bufferingPolicy: .bufferingOldest(subscriptionBufferLimit)) {
370 continuation in
371 subscriptions[subscriptionID] = Subscription(
372 tag: tag,
373 payload: payload,
374 reconnect: reconnect,
375 requestID: nil,
376 yield: { value in
377 do {
378 switch continuation.yield(try value.decode(type)) {
379 case .enqueued:
380 return .enqueued
381 case .dropped:
382 return .dropped
383 case .terminated:
384 return .terminated
385 @unknown default:
386 return .dropped
387 }
388 } catch {
389 continuation.finish(throwing: error)
390 return .terminated
391 }
392 },
393 finish: { error in
394 if let error {
395 continuation.finish(throwing: error)
396 } else {
397 continuation.finish()
398 }
399 }
400 )
401 continuation.onTermination = { @Sendable _ in
402 Task { await self.removeSubscription(subscriptionID) }
403 }
404 if connection != nil {
405 Task { await self.sendSubscription(subscriptionID) }
406 }
407 start()
408 }
409 }
410​
411 private func requestRaw(_ tag: String, payload: JSONValue) async throws -> JSONValue {
412 start()
413 let id = allocateRequestID()
414 let envelope = RPCRequestEnvelope(
415 id: id,
416 tag: tag,
417 payload: payload,
418 headers: []
419 )
420 return try await withTaskCancellationHandler {
421 try await withCheckedThrowingContinuation { continuation in
422 // If cancellation won the race before onCancel could observe
423 // an installed request, complete locally and never send it.
424 guard !Task.isCancelled else {
425 continuation.resume(throwing: CancellationError())
426 return
427 }
428 unary[id] = UnaryRequest(
429 envelope: envelope,
430 sent: false,
431 connectionWaitTask: nil,
432 sendDeadlineTask: nil,
433 responseDeadlineTask: nil,
434 resume: { continuation.resume(with: $0) }
435 )
436 installUnaryDeadlines(id)
437 if connection != nil {
438 Task { await self.sendUnary(id) }
439 }
440 }
441 } onCancel: {
442 Task { await self.cancelUnary(id) }
443 }
444 }
445​
446 private static func connectionLoop(owner: WeakOwner, id loopID: UUID) async {
447 var retry = 0
448 while await owner.isCurrentConnectionLoop(loopID), !Task.isCancelled {
449 var openedID: UUID?
450 var openedConnection: (any WebSocketConnection)?
451 do {
452 guard let attempt = await owner.connectionAttempt(loopID: loopID) else { break }
453 let url = try await attempt.endpointProvider()
454 guard await owner.isCurrentConnectionLoop(loopID), !Task.isCancelled else { break }
455 let opened = try await attempt.connector.connect(to: url)
456 openedConnection = opened
457 guard await owner.isCurrentConnectionLoop(loopID), !Task.isCancelled else {
458 await opened.close()
459 break
460 }
461 guard let id = await owner.installConnection(opened, loopID: loopID) else {
462 await opened.close()
463 guard await owner.isCurrentConnectionLoop(loopID), !Task.isCancelled else {
464 break
465 }
466 throw RPCError.disconnected
467 }
468 openedID = id
469 logger.info("WebSocket connection installed")
470 try await withTaskCancellationHandler {
471 while await owner.ownsConnection(loopID: loopID, connectionID: id),
472 !Task.isCancelled {
473 let data = try await opened.receive()
474 guard try await owner.handle(data, connectionID: id) else {
475 throw RPCError.disconnected
476 }
477 // URLSession's `resume()` does not expose a completed
478 // WebSocket handshake. A valid inbound frame is the
479 // first proof that the connection is actually usable.
480 retry = 0
481 }
482 } onCancel: {
483 Task { await opened.close() }
484 }
485 if !(await owner.disconnected(connectionID: id)) {
486 await opened.close()
487 }
488 guard await owner.isCurrentConnectionLoop(loopID), !Task.isCancelled else { break }
489 } catch {
490 logger.warning(
491 "WebSocket connection failed: \(String(describing: error), privacy: .private)"
492 )
493 if let openedID {
494 if !(await owner.disconnected(connectionID: openedID)) {
495 await openedConnection?.close()
496 }
497 } else {
498 await openedConnection?.close()
499 }
500 guard await owner.isCurrentConnectionLoop(loopID), !Task.isCancelled else { break }
501 retry += 1
502 guard let delay = await owner.reconnectDelay(
503 failureCount: retry,
504 loopID: loopID
505 ) else { break }
506 try? await Task.sleep(for: delay)
507 }
508 }
509 await owner.finishConnectionLoop(loopID)
510 }
511​
512 private func connectionAttempt(loopID: UUID) -> ConnectionAttempt? {
513 guard isCurrentConnectionLoop(loopID) else { return nil }
514 return ConnectionAttempt(connector: connector, endpointProvider: endpointProvider)
515 }
516​
517 private func reconnectDelay(failureCount: Int, loopID: UUID) -> Duration? {
518 guard isCurrentConnectionLoop(loopID) else { return nil }
519 return reconnectBackoff(failureCount)
520 }
521​
522 private func installConnection(
523 _ opened: any WebSocketConnection,
524 loopID: UUID
525 ) async -> UUID? {
526 guard isCurrentConnectionLoop(loopID), !Task.isCancelled else { return nil }
527 let id = UUID()
528 connection = opened
529 connectionID = id
530 await connected()
531 // Sending queued work during setup is actor-reentrant. A send failure
532 // can discard this socket before setup completes.
533 guard isCurrentConnectionLoop(loopID), connectionID == id else { return nil }
534 return id
535 }
536​
537 private func ownsConnection(loopID: UUID, connectionID: UUID) -> Bool {
538 isCurrentConnectionLoop(loopID) && self.connectionID == connectionID
539 }
540​
541 private func finishConnectionLoop(_ loopID: UUID) {
542 guard self.loopID == loopID else { return }
543 self.loopID = nil
544 loopTask = nil
545 }
546​
547 private func isCurrentConnectionLoop(_ id: UUID) -> Bool {
548 desired && loopID == id
549 }
550​
551 private func connected() async {
552 keepaliveTask?.cancel()
553 if let connectionID {
554 let owner = WeakOwner(self)
555 let interval = keepaliveInterval
556 keepaliveTask = Task {
557 await Self.keepaliveLoop(owner: owner, connectionID: connectionID, interval: interval)
558 }
559 }
560 // Snapshot the keys: the sends suspend, and reentrant completions or
561 // failures mutate these dictionaries mid-iteration.
562 for id in Array(unary.keys) {
563 await sendUnary(id)
564 }
565 subscriptionByRequestID.removeAll()
566 for id in Array(subscriptions.keys) {
567 await sendSubscription(id)
568 }
569 }
570​
571 @discardableResult
572 private func disconnected(expectedConnectionID: UUID? = nil) async -> Bool {
573 if let expectedConnectionID, connectionID != expectedConnectionID {
574 return false
575 }
576 let closingConnection = connection
577 keepaliveTask?.cancel()
578 keepaliveTask = nil
579 awaitingKeepaliveResponse = false
580 connection = nil
581 connectionID = nil
582 Self.logger.info("WebSocket connection closed")
583 failUnary(RPCError.disconnected, includingUnsent: false)
584 subscriptionByRequestID.removeAll()
585 let oneShotSubscriptions = subscriptions.filter { !$0.value.reconnect }
586 for (id, subscription) in oneShotSubscriptions {
587 subscriptions.removeValue(forKey: id)
588 subscription.finish(RPCError.disconnected)
589 }
590 for id in Array(subscriptions.keys) {
591 subscriptions[id]?.requestID = nil
592 subscriptions[id]?.requestConnectionID = nil
593 }
594 await closingConnection?.close()
595 return true
596 }
597​
598 private func handle(_ data: Data, expectedConnectionID: UUID) async throws -> Bool {
599 guard connectionID == expectedConnectionID else { return false }
600 let response = try JSONDecoder.t3.decode(RPCResponseEnvelope.self, from: data)
601 awaitingKeepaliveResponse = false
602 try await handle(response)
603 return connectionID == expectedConnectionID
604 }
605​
606 private func handle(_ response: RPCResponseEnvelope) async throws {
607 switch response._tag {
608 case "Pong":
609 return
610 case "Chunk":
611 guard let requestID = response.requestId,
612 let subscriptionID = subscriptionByRequestID[requestID],
613 let subscription = subscriptions[subscriptionID]
614 else { return }
615 for value in response.values ?? [] {
616 switch subscription.yield(value) {
617 case .enqueued:
618 continue
619 case .dropped:
620 let error = RPCError.protocolViolation(
621 "The live stream exceeded its buffered event limit."
622 )
623 if !subscription.reconnect {
624 subscriptionByRequestID.removeValue(forKey: requestID)
625 subscriptions.removeValue(forKey: subscriptionID)
626 subscription.finish(error)
627 }
628 throw error
629 case .terminated:
630 await removeSubscription(subscriptionID)
631 return
632 }
633 }
634 try await sendControl("Ack", requestID: requestID)
635 case "Exit":
636 guard let requestID = response.requestId, let exit = response.exit else { return }
637 if unary[requestID] != nil {
638 if exit._tag == "Success" {
639 completeUnary(requestID, with: .success(exit.value ?? .null))
640 } else {
641 completeUnary(requestID, with: .failure(remoteError(exit)))
642 }
643 return
644 }
645 guard let subscriptionID = subscriptionByRequestID.removeValue(forKey: requestID),
646 let subscription = subscriptions.removeValue(forKey: subscriptionID)
647 else { return }
648 subscription.finish(exit._tag == "Success" ? nil : remoteError(exit))
649 case "Defect", "ClientProtocolError":
650 throw RPCError.remote(
651 response.defect?.stringValue ?? "The server reported an RPC protocol error."
652 )
653 default:
654 throw RPCError.protocolViolation("Unknown RPC response \(response._tag).")
655 }
656 }
657​
658 private func sendUnary(_ id: Int) async {
659 guard let connection,
660 let connectionID,
661 var request = unary[id],
662 !request.sent else { return }
663 // Actor methods are reentrant at the send below. Record that this
664 // command crossed the socket boundary first so a concurrent
665 // disconnect fails it instead of replaying an ambiguous mutation.
666 request.sent = true
667 unary[id] = request
668 startUnarySendDeadline(id, connectionID: connectionID)
669 do {
670 try await connection.send(JSONEncoder.t3.encode(request.envelope))
671 startUnaryResponseDeadline(id)
672 } catch {
673 // A response, disconnect, or stop may have completed the request
674 // while send was suspended. Only its current owner may resume it.
675 completeUnary(id, with: .failure(RPCError.disconnected))
676 await disconnected(expectedConnectionID: connectionID)
677 }
678 }
679​
680 private func sendSubscription(_ subscriptionID: UUID) async {
681 guard let connection,
682 let connectionID,
683 var subscription = subscriptions[subscriptionID],
684 subscription.requestID == nil else { return }
685 let requestID = allocateRequestID()
686 let envelope = RPCRequestEnvelope(
687 id: requestID,
688 tag: subscription.tag,
689 payload: subscription.payload,
690 headers: []
691 )
692 // Install ownership before suspending in send. A very fast response can
693 // otherwise arrive before the request is routable, while termination
694 // during the send must be able to remove the exact in-flight mapping.
695 subscription.requestID = requestID
696 subscription.requestConnectionID = connectionID
697 subscriptions[subscriptionID] = subscription
698 subscriptionByRequestID[requestID] = subscriptionID
699 do {
700 try await connection.send(JSONEncoder.t3.encode(envelope))
701 } catch {
702 // Retain the subscription for the next socket, but make the send
703 // failure visible to the connection loop by closing this socket.
704 await disconnected(expectedConnectionID: connectionID)
705 }
706 }
707​
708 private func removeSubscription(_ id: UUID) async {
709 guard let subscription = subscriptions.removeValue(forKey: id) else { return }
710 if let requestID = subscription.requestID {
711 subscriptionByRequestID.removeValue(forKey: requestID)
712 // A termination racing a reconnect must not interrupt whichever
713 // subscription now owns this request ID on the new connection.
714 if subscription.requestConnectionID == connectionID {
715 try? await sendControl("Interrupt", requestID: requestID)
716 }
717 }
718 }
719​
720 private static func keepaliveLoop(
721 owner: WeakOwner,
722 connectionID: UUID,
723 interval: Duration
724 ) async {
725 while !Task.isCancelled {
726 try? await Task.sleep(for: interval)
727 guard !Task.isCancelled,
728 await owner.sendKeepalive(connectionID: connectionID) else { return }
729 }
730 }
731​
732 private func sendKeepalive(expectedConnectionID: UUID) async -> Bool {
733 guard desired, connectionID == expectedConnectionID, connection != nil else {
734 return false
735 }
736 if awaitingKeepaliveResponse {
737 await disconnected(expectedConnectionID: expectedConnectionID)
738 return false
739 }
740 do {
741 awaitingKeepaliveResponse = true
742 try await sendControl("Ping", requestID: nil)
743 return connectionID == expectedConnectionID
744 } catch {
745 return false
746 }
747 }
748​
749 private func sendControl(_ tag: String, requestID: Int?) async throws {
750 guard let connection, let connectionID else { throw RPCError.disconnected }
751 do {
752 try await connection.send(
753 JSONEncoder.t3.encode(RPCControlEnvelope(tag, requestID: requestID))
754 )
755 } catch {
756 await disconnected(expectedConnectionID: connectionID)
757 throw RPCError.disconnected
758 }
759 }
760​
761 private func failUnary(_ error: Error, includingUnsent: Bool) {
762 let failedIDs = unary.compactMap { id, request in
763 includingUnsent || request.sent ? id : nil
764 }
765 for id in failedIDs {
766 completeUnary(id, with: .failure(error))
767 }
768 }
769​
770 private func failUnaryIfUnsent(_ id: Int) {
771 guard let request = unary[id], !request.sent else { return }
772 completeUnary(id, with: .failure(RPCError.connectionUnavailable))
773 }
774​
775 private func installUnaryDeadlines(_ id: Int) {
776 guard var request = unary[id] else { return }
777 let connectionWaitTimeout = connectionWaitTimeout
778 request.connectionWaitTask = Task { [weak self] in
779 do {
780 try await Task.sleep(for: connectionWaitTimeout)
781 } catch {
782 return
783 }
784 await self?.failUnaryIfUnsent(id)
785 }
786 unary[id] = request
787 }
788​
789 private func startUnaryResponseDeadline(_ id: Int) {
790 guard var request = unary[id], request.sent else { return }
791 request.connectionWaitTask?.cancel()
792 request.connectionWaitTask = nil
793 request.sendDeadlineTask?.cancel()
794 request.sendDeadlineTask = nil
795 let responseTimeout = responseTimeout
796 request.responseDeadlineTask = Task { [weak self] in
797 do {
798 try await Task.sleep(for: responseTimeout)
799 } catch {
800 return
801 }
802 await self?.failUnaryOnResponseDeadline(id)
803 }
804 unary[id] = request
805 }
806​
807 private func startUnarySendDeadline(_ id: Int, connectionID: UUID) {
808 guard var request = unary[id], request.sent else { return }
809 request.connectionWaitTask?.cancel()
810 request.connectionWaitTask = nil
811 let sendTimeout = responseTimeout
812 request.sendDeadlineTask = Task { [weak self] in
813 do {
814 try await Task.sleep(for: sendTimeout)
815 } catch {
816 return
817 }
818 await self?.failUnaryOnSendDeadline(id, connectionID: connectionID)
819 }
820 unary[id] = request
821 }
822​
823 private func failUnaryOnSendDeadline(_ id: Int, connectionID: UUID) async {
824 guard let request = unary[id],
825 request.sent,
826 request.responseDeadlineTask == nil else { return }
827 completeUnary(id, with: .failure(RPCError.responseTimedOut))
828 await disconnected(expectedConnectionID: connectionID)
829 }
830​
831 private func failUnaryOnResponseDeadline(_ id: Int) async {
832 guard let request = unary[id] else { return }
833 let sent = request.sent
834 completeUnary(id, with: .failure(RPCError.responseTimedOut))
835 if sent {
836 try? await sendControl("Interrupt", requestID: id)
837 }
838 }
839​
840 private func cancelUnary(_ id: Int) async {
841 guard let request = unary[id] else { return }
842 let sent = request.sent
843 completeUnary(id, with: .failure(CancellationError()))
844 if sent {
845 try? await sendControl("Interrupt", requestID: id)
846 }
847 }
848​
849 private func completeUnary(_ id: Int, with result: Result<JSONValue, Error>) {
850 guard let request = unary.removeValue(forKey: id) else { return }
851 request.connectionWaitTask?.cancel()
852 request.sendDeadlineTask?.cancel()
853 request.responseDeadlineTask?.cancel()
854 request.resume(result)
855 }
856​
857 private func remoteError(_ exit: RPCResponseEnvelope.Exit) -> RPCError {
858 let value = exit.cause?.first?.error
859 let message = value?["message"]?.stringValue
860 ?? value?["detail"]?.stringValue
861 ?? "The environment rejected the RPC request."
862 return .remote(message)
863 }
864​
865 private func allocateRequestID() -> Int {
866 defer { nextRequestID += 1 }
867 return nextRequestID
868 }