-
Notifications
You must be signed in to change notification settings - Fork 749
Expand file tree
/
Copy pathHTTPNetworkTransport.swift
More file actions
471 lines (412 loc) · 21.1 KB
/
HTTPNetworkTransport.swift
File metadata and controls
471 lines (412 loc) · 21.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
import Foundation
/// Empty base protocol to allow multiple sub-protocols to just use a single parameter.
public protocol HTTPNetworkTransportDelegate: class {}
/// Methods which will be called prior to a request being sent to the server.
public protocol HTTPNetworkTransportPreflightDelegate: HTTPNetworkTransportDelegate {
/// Called when a request is about to send, to validate that it should be sent.
/// Good for early-exiting if your user is not logged in, for example.
///
/// - Parameters:
/// - networkTransport: The network transport which wants to send a request
/// - request: The request, BEFORE it has been modified by `willSend`
/// - Returns: True if the request should proceed, false if not.
func networkTransport(_ networkTransport: HTTPNetworkTransport, shouldSend request: URLRequest) -> Bool
/// Called when a request is about to send. Allows last minute modification of any properties on the request,
///
///
/// - Parameters:
/// - networkTransport: The network transport which is about to send a request
/// - request: The request, as an `inout` variable for modification
func networkTransport(_ networkTransport: HTTPNetworkTransport, willSend request: inout URLRequest)
}
// MARK: -
/// Methods which will be called after some kind of response has been received to a `URLSessionTask`.
public protocol HTTPNetworkTransportTaskCompletedDelegate: HTTPNetworkTransportDelegate {
/// A callback to allow hooking in URL session responses for things like logging and examining headers.
/// NOTE: This will call back on whatever thread the URL session calls back on, which is never the main thread. Call `DispatchQueue.main.async` before touching your UI!
///
/// - Parameters:
/// - networkTransport: The network transport that completed a task
/// - request: The request which was completed by the task
/// - data: [optional] Any data received. Passed through from `URLSession`.
/// - response: [optional] Any response received. Passed through from `URLSession`.
/// - error: [optional] Any error received. Passed through from `URLSession`.
func networkTransport(_ networkTransport: HTTPNetworkTransport,
didCompleteRawTaskForRequest request: URLRequest,
withData data: Data?,
response: URLResponse?,
error: Error?)
}
// MARK: -
/// Methods which will be called if an error is receieved at the network level.
public protocol HTTPNetworkTransportRetryDelegate: HTTPNetworkTransportDelegate {
/// Called when an error has been received after a request has been sent to the server to see if an operation should be retried or not.
/// NOTE: Don't just call the `continueHandler` with `.retry` all the time, or you can potentially wind up in an infinite loop of errors
///
/// - Parameters:
/// - networkTransport: The network transport which received the error
/// - error: The received error
/// - request: The URLRequest which generated the error
/// - response: [Optional] Any response received when the error was generated
/// - continueHandler: A closure indicating whether the operation should be retried. Asyncrhonous to allow for re-authentication or other async operations to complete.
func networkTransport(_ networkTransport: HTTPNetworkTransport,
receivedError error: Error,
for request: URLRequest,
response: URLResponse?,
continueHandler: @escaping (_ action: HTTPNetworkTransport.ContinueAction) -> Void)
}
// MARK: -
/// Methods which will be called after some kind of response has been received and it contains GraphQLErrors.
public protocol HTTPNetworkTransportGraphQLErrorDelegate: HTTPNetworkTransportDelegate {
/// Called when response contains one or more GraphQL errors.
///
/// NOTE: The mere presence of a GraphQL error does not necessarily mean a request failed!
/// GraphQL is design to allow partial success/failures to return, so make sure
/// you're validating the *type* of error you're getting in this before deciding whether to retry or not.
///
/// ALSO NOTE: Don't just call the `retryHandler` with `true` all the time, or you can
/// potentially wind up in an infinite loop of errors
///
/// - Parameters:
/// - networkTransport: The network transport which received the error
/// - errors: The received GraphQL errors
/// - retryHandler: A closure indicating whether the operation should be retried. Asyncrhonous to allow for re-authentication or other async operations to complete.
func networkTransport(_ networkTransport: HTTPNetworkTransport,
receivedGraphQLErrors errors: [GraphQLError],
retryHandler: @escaping (_ shouldRetry: Bool) -> Void)
}
// MARK: -
/// A network transport that uses HTTP POST requests to send GraphQL operations to a server, and that uses `URLSession` as the networking implementation.
public class HTTPNetworkTransport {
/// The action to take when retrying
public enum ContinueAction {
/// Directly retry the action
case retry
/// Fail with the specified error.
case fail(_ error: Error)
}
let url: URL
let client: URLSessionClient
let serializationFormat = JSONSerializationFormat.self
let useGETForQueries: Bool
let enableAutoPersistedQueries: Bool
let useGETForPersistedQueryRetry: Bool
private let requestCreator: RequestCreator
private let sendOperationIdentifiers: Bool
/// A delegate which can conform to any or all of `HTTPNetworkTransportPreflightDelegate`, `HTTPNetworkTransportTaskCompletedDelegate`, and `HTTPNetworkTransportRetryDelegate`.
public weak var delegate: HTTPNetworkTransportDelegate?
public lazy var clientName = HTTPNetworkTransport.defaultClientName
public lazy var clientVersion = HTTPNetworkTransport.defaultClientVersion
/// Creates a network transport with the specified server URL and session configuration.
///
/// - Parameters:
/// - url: The URL of a GraphQL server to connect to.
/// - client: The client to handle URL Session calls.
/// - sendOperationIdentifiers: Whether to send operation identifiers rather than full operation text, for use with servers that support query persistence. Defaults to false.
/// - useGETForQueries: If query operation should be sent using GET instead of POST. Defaults to false.
/// - enableAutoPersistedQueries: Whether to send persistedQuery extension. QueryDocument will be absent at 1st request, retry with QueryDocument if server respond PersistedQueryNotFound or PersistedQueryNotSupport. Defaults to false.
/// - useGETForPersistedQueryRetry: Whether to retry persistedQuery request with HttpGetMethod. Defaults to false.
public init(url: URL,
client: URLSessionClient = URLSessionClient(),
sendOperationIdentifiers: Bool = false,
useGETForQueries: Bool = false,
enableAutoPersistedQueries: Bool = false,
useGETForPersistedQueryRetry: Bool = false,
requestCreator: RequestCreator = ApolloRequestCreator()) {
self.url = url
self.client = client
self.sendOperationIdentifiers = sendOperationIdentifiers
self.useGETForQueries = useGETForQueries
self.enableAutoPersistedQueries = enableAutoPersistedQueries
self.useGETForPersistedQueryRetry = useGETForPersistedQueryRetry
self.requestCreator = requestCreator
}
private func send<Operation: GraphQLOperation>(operation: Operation,
isPersistedQueryRetry: Bool,
files: [GraphQLFile]?,
completionHandler: @escaping (_ results: Result<GraphQLResponse<Operation.Data>, Error>) -> Void) -> Cancellable {
let request: URLRequest
do {
request = try self.createRequest(for: operation,
isPersistedQueryRetry: isPersistedQueryRetry,
files: files)
} catch {
completionHandler(.failure(error))
return EmptyCancellable()
}
let task = self.client.sendRequest(request, rawTaskCompletionHandler: { [weak self] data, response, error in
self?.rawTaskCompleted(request: request, data: data, response: response, error: error)
}, completion: { [weak self] result in
guard let self = self else {
// None of the rest of this really matters
return
}
switch result {
case .failure(let error):
self.handleErrorOrRetry(operation: operation,
files: files,
error: error,
for: request,
response: nil,
completionHandler: completionHandler)
case .success(let (data, httpResponse)):
guard httpResponse.apollo.isSuccessful == true else {
let unsuccessfulError = GraphQLHTTPResponseError(body: data,
response: httpResponse,
kind: .errorResponse)
self.handleErrorOrRetry(operation: operation,
files: files,
error: unsuccessfulError,
for: request,
response: httpResponse,
completionHandler: completionHandler)
return
}
do {
guard let body = try self.serializationFormat.deserialize(data: data) as? JSONObject else {
throw GraphQLHTTPResponseError(body: data, response: httpResponse, kind: .invalidResponse)
}
let graphQLResponse = GraphQLResponse(operation: operation, body: body)
if let errors = graphQLResponse.parseErrorsOnlyFast() {
// Handle specific errors from response
self.handleGraphQLErrorsIfNeeded(operation: operation,
files: files,
for: request,
body: body,
errors: errors,
completionHandler: completionHandler)
} else {
completionHandler(.success(graphQLResponse))
}
} catch let parsingError {
self.handleErrorOrRetry(operation: operation,
files: files,
error: parsingError,
for: request,
response: httpResponse,
completionHandler: completionHandler)
}
}
})
// Task is resumed by underlying framework
return task
}
private func handleGraphQLErrorsOrComplete<Operation: GraphQLOperation>(operation: Operation,
files: [GraphQLFile]?,
response: GraphQLResponse<Operation.Data>,
completionHandler: @escaping (_ result: Result<GraphQLResponse<Operation.Data>, Error>) -> Void) {
guard
let delegate = self.delegate as? HTTPNetworkTransportGraphQLErrorDelegate,
let graphQLErrors = response.parseErrorsOnlyFast(),
graphQLErrors.apollo.isNotEmpty else {
completionHandler(.success(response))
return
}
delegate.networkTransport(self, receivedGraphQLErrors: graphQLErrors, retryHandler: { [weak self] shouldRetry in
guard let self = self else {
// None of the rest of this really matters
return
}
guard shouldRetry else {
completionHandler(.success(response))
return
}
_ = self.send(operation: operation,
isPersistedQueryRetry: self.enableAutoPersistedQueries,
files: files,
completionHandler: completionHandler)
})
}
private func handleGraphQLErrorsIfNeeded<Operation: GraphQLOperation>(operation: Operation,
files: [GraphQLFile]?,
for request: URLRequest,
body: JSONObject,
errors: [GraphQLError],
completionHandler: @escaping (_ results: Result<GraphQLResponse<Operation.Data>, Error>) -> Void) {
let errorMessages = errors.compactMap { $0.message }
if self.enableAutoPersistedQueries,
errorMessages.contains("PersistedQueryNotFound") {
// We need to retry this with the full body.
_ = self.send(operation: operation,
isPersistedQueryRetry: true,
files: nil,
completionHandler: completionHandler)
} else {
// Pass the response on to the rest of the chain
let response = GraphQLResponse(operation: operation, body: body)
handleGraphQLErrorsOrComplete(operation: operation, files: files, response: response, completionHandler: completionHandler)
}
}
private func handleErrorOrRetry<Operation: GraphQLOperation>(operation: Operation,
files: [GraphQLFile]?,
error: Error,
for request: URLRequest,
response: URLResponse?,
completionHandler: @escaping (_ result: Result<GraphQLResponse<Operation.Data>, Error>) -> Void) {
guard
let delegate = self.delegate,
let retrier = delegate as? HTTPNetworkTransportRetryDelegate else {
completionHandler(.failure(error))
return
}
retrier.networkTransport(
self,
receivedError: error,
for: request,
response: response,
continueHandler: { [weak self] (action: HTTPNetworkTransport.ContinueAction) in
guard let self = self else {
// None of the rest of this really matters
return
}
switch action {
case .retry:
_ = self.send(operation: operation,
isPersistedQueryRetry: self.enableAutoPersistedQueries,
files: files,
completionHandler: completionHandler)
case .fail(let error):
completionHandler(.failure(error))
}
})
}
private func rawTaskCompleted(request: URLRequest,
data: Data?,
response: URLResponse?,
error: Error?) {
guard
let delegate = self.delegate,
let taskDelegate = delegate as? HTTPNetworkTransportTaskCompletedDelegate else {
return
}
taskDelegate.networkTransport(self,
didCompleteRawTaskForRequest: request,
withData: data,
response: response,
error: error)
}
private func createRequest<Operation: GraphQLOperation>(for operation: Operation,
isPersistedQueryRetry: Bool,
files: [GraphQLFile]?) throws -> URLRequest {
let useGetMethod: Bool
let sendQueryDocument: Bool
let autoPersistQueries: Bool
switch operation.operationType {
case .query:
if isPersistedQueryRetry {
useGetMethod = self.useGETForPersistedQueryRetry
sendQueryDocument = true
autoPersistQueries = true
} else {
useGetMethod = self.useGETForQueries || (self.enableAutoPersistedQueries && self.useGETForPersistedQueryRetry)
sendQueryDocument = !self.enableAutoPersistedQueries
autoPersistQueries = self.enableAutoPersistedQueries
}
case .mutation:
useGetMethod = false
if isPersistedQueryRetry {
sendQueryDocument = true
autoPersistQueries = true
} else {
sendQueryDocument = !self.enableAutoPersistedQueries
autoPersistQueries = self.enableAutoPersistedQueries
}
default:
useGetMethod = false
sendQueryDocument = true
autoPersistQueries = false
}
return try self.createRequest(for: operation,
files: files,
httpMethod: useGetMethod ? .GET : .POST,
sendQueryDocument: sendQueryDocument,
autoPersistQueries: autoPersistQueries)
}
private func createRequest<Operation: GraphQLOperation>(for operation: Operation,
files: [GraphQLFile]?,
httpMethod: GraphQLHTTPMethod,
sendQueryDocument: Bool,
autoPersistQueries: Bool) throws -> URLRequest {
let body = self.requestCreator.requestBody(for: operation,
sendOperationIdentifiers: self.sendOperationIdentifiers,
sendQueryDocument: sendQueryDocument,
autoPersistQuery: autoPersistQueries)
var request = URLRequest(url: self.url)
self.addApolloClientHeaders(to: &request)
// We default to json, but this can be changed below if needed.
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
switch httpMethod {
case .GET:
let transformer = GraphQLGETTransformer(body: body, url: self.url)
if let urlForGet = transformer.createGetURL() {
request = URLRequest(url: urlForGet)
request.httpMethod = GraphQLHTTPMethod.GET.rawValue
} else {
throw GraphQLHTTPRequestError.serializedQueryParamsMessageError
}
case .POST:
do {
if
let files = files,
files.apollo.isNotEmpty {
let formData = try requestCreator.requestMultipartFormData(
for: operation,
files: files,
sendOperationIdentifiers: self.sendOperationIdentifiers,
serializationFormat: self.serializationFormat,
manualBoundary: nil)
request.setValue("multipart/form-data; boundary=\(formData.boundary)", forHTTPHeaderField: "Content-Type")
request.httpBody = try formData.encode()
} else {
request.httpBody = try serializationFormat.serialize(value: body)
}
request.httpMethod = GraphQLHTTPMethod.POST.rawValue
} catch {
throw GraphQLHTTPRequestError.serializedBodyMessageError
}
}
request.setValue(operation.operationName, forHTTPHeaderField: "X-APOLLO-OPERATION-NAME")
if let operationID = operation.operationIdentifier {
request.setValue(operationID, forHTTPHeaderField: "X-APOLLO-OPERATION-ID")
}
// If there's a delegate, do a pre-flight check and allow modifications to the request.
if
let delegate = self.delegate,
let preflightDelegate = delegate as? HTTPNetworkTransportPreflightDelegate {
guard preflightDelegate.networkTransport(self, shouldSend: request) else {
throw GraphQLHTTPRequestError.cancelledByDelegate
}
preflightDelegate.networkTransport(self, willSend: &request)
}
return request
}
}
// MARK: - NetworkTransport conformance
extension HTTPNetworkTransport: NetworkTransport {
public func send<Operation: GraphQLOperation>(operation: Operation, completionHandler: @escaping (_ result: Result<GraphQLResponse<Operation.Data>, Error>) -> Void) -> Cancellable {
return send(operation: operation,
isPersistedQueryRetry: false,
files: nil,
completionHandler: completionHandler)
}
}
// MARK: - UploadingNetworkTransport conformance
extension HTTPNetworkTransport: UploadingNetworkTransport {
public func upload<Operation: GraphQLOperation>(operation: Operation,
files: [GraphQLFile],
completionHandler: @escaping (_ result: Result<GraphQLResponse<Operation.Data>, Error>) -> Void) -> Cancellable {
return send(operation: operation,
isPersistedQueryRetry: false,
files: files,
completionHandler: completionHandler)
}
}
// MARK: - Equatable conformance
extension HTTPNetworkTransport: Equatable {
public static func ==(lhs: HTTPNetworkTransport, rhs: HTTPNetworkTransport) -> Bool {
return lhs.url == rhs.url
&& lhs.client == rhs.client
&& lhs.sendOperationIdentifiers == rhs.sendOperationIdentifiers
&& lhs.useGETForQueries == rhs.useGETForQueries
}
}