Skip to content

Commit

Permalink
Only check connectedness in StarscreamWebSocket
Browse files Browse the repository at this point in the history
This should hopefully be enough to prevent Starscream from silently
swallowing the continuation.
  • Loading branch information
fwcd committed Jul 24, 2024
1 parent 30918d3 commit b53defd
Showing 1 changed file with 3 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public final actor _StarscreamWebSocket: WebSocketProtocol, Starscream.WebSocket
private var webSocket: Starscream.WebSocket
private var connectHandlers: [(Result<Void, any Error>) -> Void] = []
private var binaryMessageHandlers: [(Data) -> Void] = []
private var isSending: Bool = false
private var isConnected: Bool = false

public init(url: URL) {
webSocket = Starscream.WebSocket(request: URLRequest(url: url))
Expand All @@ -22,6 +22,7 @@ public final actor _StarscreamWebSocket: WebSocketProtocol, Starscream.WebSocket
connectHandlers.append(continuation.resume(with:))
webSocket.connect()
}
isConnected = true
}

public func onBinary(_ handler: @escaping (Data) -> Void) throws {
Expand Down Expand Up @@ -56,18 +57,12 @@ public final actor _StarscreamWebSocket: WebSocketProtocol, Starscream.WebSocket
}

public func send(_ data: Data) async throws {
// We have to serialize all message sends, for which we need
// a flag (actor isolation is not sufficient to due reentrancy).
while isSending {
try await Task.sleep(for: .milliseconds(2))
}
guard isConnected else { throw WebSocketError.notConnectedYet }

isSending = true
log.trace("Sending binary message")
await withCheckedContinuation { continuation in
webSocket.write(data: data, completion: continuation.resume)
}
isSending = false
}
}
#endif

0 comments on commit b53defd

Please sign in to comment.