|
| 1 | +// Copyright 2025 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +import Foundation |
| 16 | + |
| 17 | +final class AsyncWebSocket: NSObject, @unchecked Sendable, URLSessionWebSocketDelegate { |
| 18 | + private let webSocketTask: URLSessionWebSocketTask |
| 19 | + private let stream: AsyncThrowingStream<URLSessionWebSocketTask.Message, Error> |
| 20 | + private let continuation: AsyncThrowingStream<URLSessionWebSocketTask.Message, Error>.Continuation |
| 21 | + private var continuationFinished = false |
| 22 | + private let continuationLock = NSLock() |
| 23 | + |
| 24 | + private var _isConnected = false |
| 25 | + private let isConnectedLock = NSLock() |
| 26 | + private(set) var isConnected: Bool { |
| 27 | + get { isConnectedLock.withLock { _isConnected } } |
| 28 | + set { isConnectedLock.withLock { _isConnected = newValue } } |
| 29 | + } |
| 30 | + |
| 31 | + init(urlSession: URLSession = GenAIURLSession.default, urlRequest: URLRequest) { |
| 32 | + webSocketTask = urlSession.webSocketTask(with: urlRequest) |
| 33 | + (stream, continuation) = AsyncThrowingStream<URLSessionWebSocketTask.Message, Error> |
| 34 | + .makeStream() |
| 35 | + } |
| 36 | + |
| 37 | + deinit { |
| 38 | + webSocketTask.cancel(with: .goingAway, reason: nil) |
| 39 | + } |
| 40 | + |
| 41 | + func connect() -> AsyncThrowingStream<URLSessionWebSocketTask.Message, Error> { |
| 42 | + webSocketTask.resume() |
| 43 | + isConnected = true |
| 44 | + startReceiving() |
| 45 | + return stream |
| 46 | + } |
| 47 | + |
| 48 | + func disconnect() { |
| 49 | + webSocketTask.cancel(with: .goingAway, reason: nil) |
| 50 | + isConnected = false |
| 51 | + continuationLock.withLock { |
| 52 | + self.continuation.finish() |
| 53 | + self.continuationFinished = true |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + func send(_ message: URLSessionWebSocketTask.Message) async throws { |
| 58 | + // TODO: Throw error if socket already closed |
| 59 | + try await webSocketTask.send(message) |
| 60 | + } |
| 61 | + |
| 62 | + private func startReceiving() { |
| 63 | + Task { |
| 64 | + while !Task.isCancelled && self.webSocketTask.isOpen && self.isConnected { |
| 65 | + let message = try await webSocketTask.receive() |
| 66 | + // TODO: Check continuationFinished before yielding. Use the same thread for NSLock. |
| 67 | + continuation.yield(message) |
| 68 | + } |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + func urlSession(_ session: URLSession, |
| 73 | + webSocketTask: URLSessionWebSocketTask, |
| 74 | + didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, |
| 75 | + reason: Data?) { |
| 76 | + continuationLock.withLock { |
| 77 | + guard !continuationFinished else { return } |
| 78 | + continuation.finish() |
| 79 | + continuationFinished = true |
| 80 | + } |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +private extension URLSessionWebSocketTask { |
| 85 | + var isOpen: Bool { |
| 86 | + return closeCode == .invalid |
| 87 | + } |
| 88 | +} |
| 89 | + |
| 90 | +struct WebSocketClosedError: Error, Sendable, CustomNSError { |
| 91 | + let closeCode: URLSessionWebSocketTask.CloseCode |
| 92 | + let closeReason: String |
| 93 | + |
| 94 | + init(closeCode: URLSessionWebSocketTask.CloseCode, closeReason: Data?) { |
| 95 | + self.closeCode = closeCode |
| 96 | + self.closeReason = closeReason |
| 97 | + .flatMap { String(data: $0, encoding: .utf8) } ?? "Unknown reason." |
| 98 | + } |
| 99 | + |
| 100 | + var errorCode: Int { closeCode.rawValue } |
| 101 | + |
| 102 | + var errorUserInfo: [String: Any] { |
| 103 | + [ |
| 104 | + NSLocalizedDescriptionKey: "WebSocket closed with code \(closeCode.rawValue). Reason: \(closeReason)", |
| 105 | + ] |
| 106 | + } |
| 107 | +} |
0 commit comments