Skip to content

Commit

Permalink
fix: Websocket error broadcast for unsubscribed ID (#506)
Browse files Browse the repository at this point in the history
  • Loading branch information
calvincestari authored Oct 16, 2024
1 parent f7d83fc commit cdce4f9
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 13 deletions.
8 changes: 4 additions & 4 deletions Tests/ApolloTests/WebSocket/WebSocketTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,8 @@ class WebSocketTests: XCTestCase {
subject.cancel()
}

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

let subject = client.subscribe(subscription: MockSubscription<ReviewAddedData>()) { result in
defer { expectation.fulfill() }
Expand All @@ -133,10 +133,10 @@ class WebSocketTests: XCTestCase {
}
}
}


// Message data below has missing 'id' and should notify all subscribers of the error
let message : JSONEncodableDictionary = [
"type": "data",
"id": "2", // subscribing on id = 1, i.e. expecting error when receiving id = 2
"payload": [
"data": [
"reviewAdded": [
Expand Down
24 changes: 15 additions & 9 deletions apollo-ios/Sources/ApolloWebSocket/WebSocketTransport.swift
Original file line number Diff line number Diff line change
Expand Up @@ -193,10 +193,21 @@ public class WebSocketTransport {
}

switch messageType {
case .data,
.next,
.error:
if let id = parseHandler.id, let responseHandler = subscribers[id] {
case .data, .next, .error:
guard let id = parseHandler.id else {
let websocketError = WebSocketError(
payload: parseHandler.payload,
error: parseHandler.error,
kind: .unprocessedMessage(text)
)
self.notifyErrorAllHandlers(websocketError)

break
}

// If we have a handler ID but no subscriber exists for that ID then the
// subscriber probably unsubscribed.
if let responseHandler = subscribers[id] {
if let payload = parseHandler.payload {
responseHandler(.success(payload))
} else if let error = parseHandler.error {
Expand All @@ -207,11 +218,6 @@ public class WebSocketTransport {
kind: .neitherErrorNorPayloadReceived)
responseHandler(.failure(websocketError))
}
} else {
let websocketError = WebSocketError(payload: parseHandler.payload,
error: parseHandler.error,
kind: .unprocessedMessage(text))
self.notifyErrorAllHandlers(websocketError)
}
case .complete:
if let id = parseHandler.id {
Expand Down

0 comments on commit cdce4f9

Please sign in to comment.