Skip to content

Commit 6678be2

Browse files
committed
Add docs to AsyncWebSocket
1 parent 8b32ed4 commit 6678be2

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

FirebaseAI/Sources/Types/Internal/Live/AsyncWebSocket.swift

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,12 @@
1515
import Foundation
1616
private import FirebaseCoreInternal
1717

18+
/// Async API for interacting with web sockets.
19+
///
20+
/// Internally, this just wraps around a `URLSessionWebSocketTask`, and provides a more async friendly
21+
/// interface for sending and consuming data from it.
22+
///
23+
/// Also surfaces a more fine-grained ``WebSocketClosedError`` for when the web socket is closed.
1824
final class AsyncWebSocket: NSObject, @unchecked Sendable, URLSessionWebSocketDelegate {
1925
private let webSocketTask: URLSessionWebSocketTask
2026
private let stream: AsyncThrowingStream<URLSessionWebSocketTask.Message, Error>
@@ -33,19 +39,24 @@ final class AsyncWebSocket: NSObject, @unchecked Sendable, URLSessionWebSocketDe
3339
disconnect()
3440
}
3541

42+
/// Starts a connection to the backend, returning a stream for the websocket responses.
3643
func connect() -> AsyncThrowingStream<URLSessionWebSocketTask.Message, Error> {
3744
webSocketTask.resume()
3845
closeError.withLock { $0 = nil }
3946
startReceiving()
4047
return stream
4148
}
4249

50+
/// Closes the websocket, if it's not already closed.
4351
func disconnect() {
4452
if closeError.value() != nil { return }
4553

4654
close(code: .goingAway, reason: nil)
4755
}
4856

57+
/// Sends a message to the server, through the websocket.
58+
///
59+
/// If the web socket is closed, this method will throw the error it was closed with.
4960
func send(_ message: URLSessionWebSocketTask.Message) async throws {
5061
if let closeError = closeError.value() {
5162
throw closeError
@@ -95,6 +106,10 @@ private extension URLSessionWebSocketTask {
95106
}
96107
}
97108

109+
/// The websocket was closed.
110+
///
111+
/// See the `closeReason` for why, or the `errorCode` for the corresponding
112+
/// `URLSessionWebSocketTask.CloseCode`.
98113
struct WebSocketClosedError: Error, Sendable, CustomNSError {
99114
let closeCode: URLSessionWebSocketTask.CloseCode
100115
let closeReason: String

0 commit comments

Comments
 (0)