2525
2626 private var initialized = false
2727 private var initResult : InitPayloadResult ?
28- private var subscriptionTasks = [ String : Task < Void , any Error > ] ( )
28+ private var executionTasks = [ String : Task < Void , any Error > ] ( )
2929
3030 /// Create a new server
3131 ///
5353 }
5454
5555 deinit {
56- subscriptionTasks . values. forEach { $0. cancel ( ) }
56+ executionTasks . values. forEach { $0. cancel ( ) }
5757 }
5858
5959 /// Listen and react to the provided async sequence of client messages. This function will block until the stream is completed.
@@ -133,22 +133,26 @@ where
133133 }
134134
135135 let id = subscribeRequest. id
136- if subscriptionTasks [ id] != nil {
137- try await error ( . subscriberAlreadyExists( id: id) )
138- }
139-
140136 let graphQLRequest = subscribeRequest. payload
141137
142- var isStreaming = false
138+ let isStreaming : Bool
143139 do {
144140 isStreaming = try graphQLRequest. isSubscription ( )
145141 } catch {
146142 try await sendError ( error, id: id)
147143 return
148144 }
149145
150- if isStreaming {
151- subscriptionTasks [ id] = Task {
146+ guard executionTasks [ id] == nil else {
147+ try await self . error ( . subscriberAlreadyExists( id: id) )
148+ return
149+ }
150+ executionTasks [ id] = Task {
151+ defer {
152+ executionTasks. removeValue ( forKey: id)
153+ }
154+
155+ if isStreaming {
152156 do {
153157 let stream = try await onSubscribe ( graphQLRequest, initResult)
154158 for try await event in stream {
@@ -157,19 +161,16 @@ where
157161 }
158162 } catch {
159163 try await sendError ( error, id: id)
160- subscriptionTasks. removeValue ( forKey: id)
161- throw error
162164 }
163165 try await self . sendComplete ( id: id)
164- subscriptionTasks. removeValue ( forKey: id)
165- }
166- } else {
167- do {
168- let result = try await onExecute ( graphQLRequest, initResult)
169- try await sendNext ( result, id: id)
170- try await sendComplete ( id: id)
171- } catch {
172- try await sendError ( error, id: id)
166+ } else {
167+ do {
168+ let result = try await onExecute ( graphQLRequest, initResult)
169+ try await sendNext ( result, id: id)
170+ try await sendComplete ( id: id)
171+ } catch {
172+ try await sendError ( error, id: id)
173+ }
173174 }
174175 }
175176 }
@@ -181,9 +182,9 @@ where
181182 }
182183
183184 let id = completeRequest. id
184- if let task = subscriptionTasks [ id] {
185+ if let task = executionTasks [ id] {
185186 task. cancel ( )
186- subscriptionTasks . removeValue ( forKey: id)
187+ executionTasks . removeValue ( forKey: id)
187188 }
188189 try await onOperationComplete ( id)
189190 }
0 commit comments