15
15
import Foundation
16
16
private import FirebaseCoreInternal
17
17
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.
18
24
final class AsyncWebSocket : NSObject , @unchecked Sendable , URLSessionWebSocketDelegate {
19
25
private let webSocketTask : URLSessionWebSocketTask
20
26
private let stream : AsyncThrowingStream < URLSessionWebSocketTask . Message , Error >
@@ -33,19 +39,24 @@ final class AsyncWebSocket: NSObject, @unchecked Sendable, URLSessionWebSocketDe
33
39
disconnect ( )
34
40
}
35
41
42
+ /// Starts a connection to the backend, returning a stream for the websocket responses.
36
43
func connect( ) -> AsyncThrowingStream < URLSessionWebSocketTask . Message , Error > {
37
44
webSocketTask. resume ( )
38
45
closeError. withLock { $0 = nil }
39
46
startReceiving ( )
40
47
return stream
41
48
}
42
49
50
+ /// Closes the websocket, if it's not already closed.
43
51
func disconnect( ) {
44
52
if closeError. value ( ) != nil { return }
45
53
46
54
close ( code: . goingAway, reason: nil )
47
55
}
48
56
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.
49
60
func send( _ message: URLSessionWebSocketTask . Message ) async throws {
50
61
if let closeError = closeError. value ( ) {
51
62
throw closeError
@@ -95,6 +106,10 @@ private extension URLSessionWebSocketTask {
95
106
}
96
107
}
97
108
109
+ /// The websocket was closed.
110
+ ///
111
+ /// See the `closeReason` for why, or the `errorCode` for the corresponding
112
+ /// `URLSessionWebSocketTask.CloseCode`.
98
113
struct WebSocketClosedError : Error , Sendable , CustomNSError {
99
114
let closeCode : URLSessionWebSocketTask . CloseCode
100
115
let closeReason : String
0 commit comments