Skip to content

Commit

Permalink
Merge pull request #14 from unstoppablefi/try_fix_regular_crasher
Browse files Browse the repository at this point in the history
add a queue to make sure we access only from one thread
  • Loading branch information
terhechte authored Feb 8, 2023
2 parents 65d53c2 + d23e334 commit 75154d6
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions Sources/SwiftGraphQL/HTTP+WebSockets.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ public class GraphQLSocket<S: GraphQLEnabledSocket> {
}
private var queue: [(GraphQLSocket) -> Void] = []
private var subscriptions: [String: (GraphQLSocketMessage) -> Void] = [:]
private let subscriptionsQueue = DispatchQueue(label: "GraphQLSubscriptionsQueue")

private var decoder = JSONDecoder()
private var encoder = JSONEncoder()
Expand Down Expand Up @@ -131,7 +132,9 @@ public class GraphQLSocket<S: GraphQLEnabledSocket> {
case .next, .error, .complete, .data:
guard let id = message.id else { return false }
message.originalData = data
self?.subscriptions[id]?(message)
self?.subscriptionsQueue.schedule {
self?.subscriptions[id]?(message)
}
case .connection_terminate, .connection_error:
self?.restart(errorHandler: errorHandler)
return true
Expand Down Expand Up @@ -272,21 +275,20 @@ public class GraphQLSocket<S: GraphQLEnabledSocket> {
socket?.send(message: messageData, errorHandler: {
eventHandler(.failure(.subscribeFailed($0)))
})
subscriptions[id] = { message in
let handler: (GraphQLSocketMessage) -> Void = { message in
switch message.type {
case .next, .data:
do {
if let originalData = message.originalData {

#if DEBUG
#if targetEnvironment(simulator)
if let originalData = message.originalData {
// write the response out. A given subscription can have multiple responses.
let debugTime = DispatchTime.now().uptimeNanoseconds
let url = URL(fileURLWithPath: "/tmp/subscription_response_\(id)_\(debugTime).json")
try? originalData.write(to: url)
}
#endif
#endif
}
let result = try GraphQLResult(webSocketMessage: message, with: selection)
eventHandler(.success(result))
} catch {
Expand All @@ -310,6 +312,9 @@ public class GraphQLSocket<S: GraphQLEnabledSocket> {
}

}
subscriptionsQueue.schedule { [weak self] in
self?.subscriptions[id] = handler
}
} catch {
eventHandler(.failure(.failedToEncodeSelection(error)))
}
Expand All @@ -334,7 +339,9 @@ public class GraphQLSocket<S: GraphQLEnabledSocket> {
}

private func complete(id: String) {
subscriptions[id] = nil
subscriptionsQueue.schedule { [weak self] in
self?.subscriptions[id] = nil
}
let message = Message.complete(id: id)
let messageData = try! encoder.encode(message)
socket?.send(message: messageData, errorHandler: { _ in })
Expand Down

0 comments on commit 75154d6

Please sign in to comment.