Skip to content

Commit cdce4f9

Browse files
fix: Websocket error broadcast for unsubscribed ID (#506)
1 parent f7d83fc commit cdce4f9

File tree

2 files changed

+19
-13
lines changed

2 files changed

+19
-13
lines changed

Tests/ApolloTests/WebSocket/WebSocketTests.swift

+4-4
Original file line numberDiff line numberDiff line change
@@ -110,8 +110,8 @@ class WebSocketTests: XCTestCase {
110110
subject.cancel()
111111
}
112112

113-
func testLocalErrorUnknownId() throws {
114-
let expectation = self.expectation(description: "Unknown id for subscription")
113+
func testLocalErrorMissingId() throws {
114+
let expectation = self.expectation(description: "Missing id for subscription")
115115

116116
let subject = client.subscribe(subscription: MockSubscription<ReviewAddedData>()) { result in
117117
defer { expectation.fulfill() }
@@ -133,10 +133,10 @@ class WebSocketTests: XCTestCase {
133133
}
134134
}
135135
}
136-
136+
137+
// Message data below has missing 'id' and should notify all subscribers of the error
137138
let message : JSONEncodableDictionary = [
138139
"type": "data",
139-
"id": "2", // subscribing on id = 1, i.e. expecting error when receiving id = 2
140140
"payload": [
141141
"data": [
142142
"reviewAdded": [

apollo-ios/Sources/ApolloWebSocket/WebSocketTransport.swift

+15-9
Original file line numberDiff line numberDiff line change
@@ -193,10 +193,21 @@ public class WebSocketTransport {
193193
}
194194

195195
switch messageType {
196-
case .data,
197-
.next,
198-
.error:
199-
if let id = parseHandler.id, let responseHandler = subscribers[id] {
196+
case .data, .next, .error:
197+
guard let id = parseHandler.id else {
198+
let websocketError = WebSocketError(
199+
payload: parseHandler.payload,
200+
error: parseHandler.error,
201+
kind: .unprocessedMessage(text)
202+
)
203+
self.notifyErrorAllHandlers(websocketError)
204+
205+
break
206+
}
207+
208+
// If we have a handler ID but no subscriber exists for that ID then the
209+
// subscriber probably unsubscribed.
210+
if let responseHandler = subscribers[id] {
200211
if let payload = parseHandler.payload {
201212
responseHandler(.success(payload))
202213
} else if let error = parseHandler.error {
@@ -207,11 +218,6 @@ public class WebSocketTransport {
207218
kind: .neitherErrorNorPayloadReceived)
208219
responseHandler(.failure(websocketError))
209220
}
210-
} else {
211-
let websocketError = WebSocketError(payload: parseHandler.payload,
212-
error: parseHandler.error,
213-
kind: .unprocessedMessage(text))
214-
self.notifyErrorAllHandlers(websocketError)
215221
}
216222
case .complete:
217223
if let id = parseHandler.id {

0 commit comments

Comments
 (0)