-
Notifications
You must be signed in to change notification settings - Fork 120
/
Copy pathHTTPClient.swift
1268 lines (1155 loc) · 57.4 KB
/
HTTPClient.swift
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===----------------------------------------------------------------------===//
//
// This source file is part of the AsyncHTTPClient open source project
//
// Copyright (c) 2018-2019 Apple Inc. and the AsyncHTTPClient project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of AsyncHTTPClient project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Atomics
import Foundation
import Logging
import NIOConcurrencyHelpers
import NIOCore
import NIOHTTP1
import NIOHTTPCompression
import NIOPosix
import NIOSSL
import NIOTLS
import NIOTransportServices
extension Logger {
private func requestInfo(_ request: HTTPClient.Request) -> Logger.Metadata.Value {
return "\(request.method) \(request.url)"
}
func attachingRequestInformation(_ request: HTTPClient.Request, requestID: Int) -> Logger {
var modified = self
modified[metadataKey: "ahc-prev-request"] = nil
modified[metadataKey: "ahc-request-id"] = "\(requestID)"
return modified
}
}
let globalRequestID = ManagedAtomic(0)
/// HTTPClient class provides API for request execution.
///
/// Example:
///
/// ```swift
/// HTTPClient.shared.get(url: "https://swift.org", deadline: .now() + .seconds(1)).whenComplete { result in
/// switch result {
/// case .failure(let error):
/// // process error
/// case .success(let response):
/// if let response.status == .ok {
/// // handle response
/// } else {
/// // handle remote error
/// }
/// }
/// }
/// ```
public class HTTPClient {
/// The `EventLoopGroup` in use by this ``HTTPClient``.
///
/// All HTTP transactions will occur on loops owned by this group.
public let eventLoopGroup: EventLoopGroup
let configuration: Configuration
let poolManager: HTTPConnectionPool.Manager
/// Shared thread pool used for file IO. It is lazily created on first access of ``Task/fileIOThreadPool``.
private var fileIOThreadPool: NIOThreadPool?
private let fileIOThreadPoolLock = NIOLock()
private var state: State
private let stateLock = NIOLock()
private let canBeShutDown: Bool
static let loggingDisabled = Logger(label: "AHC-do-not-log", factory: { _ in SwiftLogNoOpLogHandler() })
/// Create an ``HTTPClient`` with specified `EventLoopGroup` provider and configuration.
///
/// - parameters:
/// - eventLoopGroupProvider: Specify how `EventLoopGroup` will be created.
/// - configuration: Client configuration.
public convenience init(eventLoopGroupProvider: EventLoopGroupProvider,
configuration: Configuration = Configuration()) {
self.init(eventLoopGroupProvider: eventLoopGroupProvider,
configuration: configuration,
backgroundActivityLogger: HTTPClient.loggingDisabled)
}
/// Create an ``HTTPClient`` with specified `EventLoopGroup` and configuration.
///
/// - parameters:
/// - eventLoopGroupProvider: Specify how `EventLoopGroup` will be created.
/// - configuration: Client configuration.
public convenience init(eventLoopGroup: EventLoopGroup = HTTPClient.defaultEventLoopGroup,
configuration: Configuration = Configuration()) {
self.init(eventLoopGroupProvider: .shared(eventLoopGroup),
configuration: configuration,
backgroundActivityLogger: HTTPClient.loggingDisabled)
}
/// Create an ``HTTPClient`` with specified `EventLoopGroup` provider and configuration.
///
/// - parameters:
/// - eventLoopGroupProvider: Specify how `EventLoopGroup` will be created.
/// - configuration: Client configuration.
public convenience init(eventLoopGroupProvider: EventLoopGroupProvider,
configuration: Configuration = Configuration(),
backgroundActivityLogger: Logger) {
let eventLoopGroup: any EventLoopGroup
switch eventLoopGroupProvider {
case .shared(let group):
eventLoopGroup = group
default: // handle `.createNew` without a deprecation warning
eventLoopGroup = HTTPClient.defaultEventLoopGroup
}
self.init(eventLoopGroup: eventLoopGroup,
configuration: configuration,
backgroundActivityLogger: backgroundActivityLogger)
}
/// Create an ``HTTPClient`` with specified `EventLoopGroup` and configuration.
///
/// - parameters:
/// - eventLoopGroup: The `EventLoopGroup` that the ``HTTPClient`` will use.
/// - configuration: Client configuration.
/// - backgroundActivityLogger: The `Logger` that will be used to log background any activity that's not associated with a request.
public convenience init(eventLoopGroup: any EventLoopGroup = HTTPClient.defaultEventLoopGroup,
configuration: Configuration = Configuration(),
backgroundActivityLogger: Logger) {
self.init(eventLoopGroup: eventLoopGroup,
configuration: configuration,
backgroundActivityLogger: backgroundActivityLogger,
canBeShutDown: true)
}
internal required init(eventLoopGroup: EventLoopGroup,
configuration: Configuration = Configuration(),
backgroundActivityLogger: Logger,
canBeShutDown: Bool) {
self.canBeShutDown = canBeShutDown
self.eventLoopGroup = eventLoopGroup
self.configuration = configuration
self.poolManager = HTTPConnectionPool.Manager(
eventLoopGroup: self.eventLoopGroup,
configuration: self.configuration,
backgroundActivityLogger: backgroundActivityLogger
)
self.state = .upAndRunning
}
deinit {
debugOnly {
// We want to crash only in debug mode.
switch self.state {
case .shutDown:
break
case .shuttingDown:
preconditionFailure("""
This state should be totally unreachable. While the HTTPClient is shutting down a \
reference cycle should exist, that prevents it from deinit.
""")
case .upAndRunning:
preconditionFailure("""
Client not shut down before the deinit. Please call client.shutdown() when no \
longer needed. Otherwise memory will leak.
""")
}
}
}
/// Shuts down the client and `EventLoopGroup` if it was created by the client.
///
/// This method blocks the thread indefinitely, prefer using ``shutdown()-96ayw``.
@available(*, noasync, message: "syncShutdown() can block indefinitely, prefer shutdown()", renamed: "shutdown()")
public func syncShutdown() throws {
try self.syncShutdown(requiresCleanClose: false)
}
/// Shuts down the client and `EventLoopGroup` if it was created by the client.
///
/// - parameters:
/// - requiresCleanClose: Determine if the client should throw when it is shutdown in a non-clean state
///
/// - Note:
/// The `requiresCleanClose` will let the client do additional checks about its internal consistency on shutdown and
/// throw the appropriate error if needed. For instance, if its internal connection pool has any non-released connections,
/// this indicate shutdown was called too early before tasks were completed or explicitly canceled.
/// In general, setting this parameter to `true` should make it easier and faster to catch related programming errors.
func syncShutdown(requiresCleanClose: Bool) throws {
if let eventLoop = MultiThreadedEventLoopGroup.currentEventLoop {
preconditionFailure("""
BUG DETECTED: syncShutdown() must not be called when on an EventLoop.
Calling syncShutdown() on any EventLoop can lead to deadlocks.
Current eventLoop: \(eventLoop)
""")
}
let errorStorageLock = NIOLock()
let errorStorage: UnsafeMutableTransferBox<Error?> = .init(nil)
let continuation = DispatchWorkItem {}
self.shutdown(requiresCleanClose: requiresCleanClose, queue: DispatchQueue(label: "async-http-client.shutdown")) { error in
if let error = error {
errorStorageLock.withLock {
errorStorage.wrappedValue = error
}
}
continuation.perform()
}
continuation.wait()
try errorStorageLock.withLock {
if let error = errorStorage.wrappedValue {
throw error
}
}
}
/// Shuts down the client and event loop gracefully.
///
/// This function is clearly an outlier in that it uses a completion
/// callback instead of an EventLoopFuture. The reason for that is that NIO's EventLoopFutures will call back on an event loop.
/// The virtue of this function is to shut the event loop down. To work around that we call back on a DispatchQueue
/// instead.
@preconcurrency public func shutdown(
queue: DispatchQueue = .global(),
_ callback: @Sendable @escaping (Error?) -> Void
) {
self.shutdown(requiresCleanClose: false, queue: queue, callback)
}
/// Shuts down the ``HTTPClient`` and releases its resources.
public func shutdown() -> EventLoopFuture<Void> {
let promise = self.eventLoopGroup.any().makePromise(of: Void.self)
self.shutdown(queue: .global()) { error in
if let error = error {
promise.fail(error)
} else {
promise.succeed(())
}
}
return promise.futureResult
}
private func shutdown(requiresCleanClose: Bool, queue: DispatchQueue, _ callback: @escaping ShutdownCallback) {
guard self.canBeShutDown else {
queue.async {
callback(HTTPClientError.shutdownUnsupported)
}
return
}
do {
try self.stateLock.withLock {
guard case .upAndRunning = self.state else {
throw HTTPClientError.alreadyShutdown
}
self.state = .shuttingDown(requiresCleanClose: requiresCleanClose, callback: callback)
}
} catch {
callback(error)
return
}
let promise = self.eventLoopGroup.any().makePromise(of: Bool.self)
self.poolManager.shutdown(promise: promise)
promise.futureResult.whenComplete { result in
switch result {
case .failure:
preconditionFailure("Shutting down the connection pool must not fail, ever.")
case .success(let unclean):
let (callback, uncleanError) = self.stateLock.withLock { () -> (ShutdownCallback, Error?) in
guard case .shuttingDown(let requiresClean, callback: let callback) = self.state else {
preconditionFailure("Why did the pool manager shut down, if it was not instructed to")
}
let error: Error? = (requiresClean && unclean) ? HTTPClientError.uncleanShutdown : nil
return (callback, error)
}
self.stateLock.withLock {
self.state = .shutDown
}
queue.async {
callback(uncleanError)
}
}
}
}
private func makeOrGetFileIOThreadPool() -> NIOThreadPool {
self.fileIOThreadPoolLock.withLock {
guard let fileIOThreadPool = self.fileIOThreadPool else {
return NIOThreadPool.singleton
}
return fileIOThreadPool
}
}
/// Execute `GET` request using specified URL.
///
/// - parameters:
/// - url: Remote URL.
/// - deadline: Point in time by which the request must complete.
public func get(url: String, deadline: NIODeadline? = nil) -> EventLoopFuture<Response> {
return self.get(url: url, deadline: deadline, logger: HTTPClient.loggingDisabled)
}
/// Execute `GET` request using specified URL.
///
/// - parameters:
/// - url: Remote URL.
/// - deadline: Point in time by which the request must complete.
/// - logger: The logger to use for this request.
public func get(url: String, deadline: NIODeadline? = nil, logger: Logger) -> EventLoopFuture<Response> {
return self.execute(.GET, url: url, deadline: deadline, logger: logger)
}
/// Execute `POST` request using specified URL.
///
/// - parameters:
/// - url: Remote URL.
/// - body: Request body.
/// - deadline: Point in time by which the request must complete.
public func post(url: String, body: Body? = nil, deadline: NIODeadline? = nil) -> EventLoopFuture<Response> {
return self.post(url: url, body: body, deadline: deadline, logger: HTTPClient.loggingDisabled)
}
/// Execute `POST` request using specified URL.
///
/// - parameters:
/// - url: Remote URL.
/// - body: Request body.
/// - deadline: Point in time by which the request must complete.
/// - logger: The logger to use for this request.
public func post(url: String, body: Body? = nil, deadline: NIODeadline? = nil, logger: Logger) -> EventLoopFuture<Response> {
return self.execute(.POST, url: url, body: body, deadline: deadline, logger: logger)
}
/// Execute `PATCH` request using specified URL.
///
/// - parameters:
/// - url: Remote URL.
/// - body: Request body.
/// - deadline: Point in time by which the request must complete.
public func patch(url: String, body: Body? = nil, deadline: NIODeadline? = nil) -> EventLoopFuture<Response> {
return self.patch(url: url, body: body, deadline: deadline, logger: HTTPClient.loggingDisabled)
}
/// Execute `PATCH` request using specified URL.
///
/// - parameters:
/// - url: Remote URL.
/// - body: Request body.
/// - deadline: Point in time by which the request must complete.
/// - logger: The logger to use for this request.
public func patch(url: String, body: Body? = nil, deadline: NIODeadline? = nil, logger: Logger) -> EventLoopFuture<Response> {
return self.execute(.PATCH, url: url, body: body, deadline: deadline, logger: logger)
}
/// Execute `PUT` request using specified URL.
///
/// - parameters:
/// - url: Remote URL.
/// - body: Request body.
/// - deadline: Point in time by which the request must complete.
public func put(url: String, body: Body? = nil, deadline: NIODeadline? = nil) -> EventLoopFuture<Response> {
return self.put(url: url, body: body, deadline: deadline, logger: HTTPClient.loggingDisabled)
}
/// Execute `PUT` request using specified URL.
///
/// - parameters:
/// - url: Remote URL.
/// - body: Request body.
/// - deadline: Point in time by which the request must complete.
/// - logger: The logger to use for this request.
public func put(url: String, body: Body? = nil, deadline: NIODeadline? = nil, logger: Logger) -> EventLoopFuture<Response> {
return self.execute(.PUT, url: url, body: body, deadline: deadline, logger: logger)
}
/// Execute `DELETE` request using specified URL.
///
/// - parameters:
/// - url: Remote URL.
/// - deadline: The time when the request must have been completed by.
public func delete(url: String, deadline: NIODeadline? = nil) -> EventLoopFuture<Response> {
return self.delete(url: url, deadline: deadline, logger: HTTPClient.loggingDisabled)
}
/// Execute `DELETE` request using specified URL.
///
/// - parameters:
/// - url: Remote URL.
/// - deadline: The time when the request must have been completed by.
/// - logger: The logger to use for this request.
public func delete(url: String, deadline: NIODeadline? = nil, logger: Logger) -> EventLoopFuture<Response> {
return self.execute(.DELETE, url: url, deadline: deadline, logger: logger)
}
/// Execute arbitrary HTTP request using specified URL.
///
/// - parameters:
/// - method: Request method.
/// - url: Request url.
/// - body: Request body.
/// - deadline: Point in time by which the request must complete.
/// - logger: The logger to use for this request.
public func execute(_ method: HTTPMethod = .GET, url: String, body: Body? = nil, deadline: NIODeadline? = nil, logger: Logger? = nil) -> EventLoopFuture<Response> {
do {
let request = try Request(url: url, method: method, body: body)
return self.execute(request: request, deadline: deadline, logger: logger ?? HTTPClient.loggingDisabled)
} catch {
return self.eventLoopGroup.any().makeFailedFuture(error)
}
}
/// Execute arbitrary HTTP+UNIX request to a unix domain socket path, using the specified URL as the request to send to the server.
///
/// - parameters:
/// - method: Request method.
/// - socketPath: The path to the unix domain socket to connect to.
/// - urlPath: The URL path and query that will be sent to the server.
/// - body: Request body.
/// - deadline: Point in time by which the request must complete.
/// - logger: The logger to use for this request.
public func execute(_ method: HTTPMethod = .GET, socketPath: String, urlPath: String, body: Body? = nil, deadline: NIODeadline? = nil, logger: Logger? = nil) -> EventLoopFuture<Response> {
do {
guard let url = URL(httpURLWithSocketPath: socketPath, uri: urlPath) else {
throw HTTPClientError.invalidURL
}
let request = try Request(url: url, method: method, body: body)
return self.execute(request: request, deadline: deadline, logger: logger ?? HTTPClient.loggingDisabled)
} catch {
return self.eventLoopGroup.any().makeFailedFuture(error)
}
}
/// Execute arbitrary HTTPS+UNIX request to a unix domain socket path over TLS, using the specified URL as the request to send to the server.
///
/// - parameters:
/// - method: Request method.
/// - secureSocketPath: The path to the unix domain socket to connect to.
/// - urlPath: The URL path and query that will be sent to the server.
/// - body: Request body.
/// - deadline: Point in time by which the request must complete.
/// - logger: The logger to use for this request.
public func execute(_ method: HTTPMethod = .GET, secureSocketPath: String, urlPath: String, body: Body? = nil, deadline: NIODeadline? = nil, logger: Logger? = nil) -> EventLoopFuture<Response> {
do {
guard let url = URL(httpsURLWithSocketPath: secureSocketPath, uri: urlPath) else {
throw HTTPClientError.invalidURL
}
let request = try Request(url: url, method: method, body: body)
return self.execute(request: request, deadline: deadline, logger: logger ?? HTTPClient.loggingDisabled)
} catch {
return self.eventLoopGroup.any().makeFailedFuture(error)
}
}
/// Execute arbitrary HTTP request using specified URL.
///
/// - parameters:
/// - request: HTTP request to execute.
/// - deadline: Point in time by which the request must complete.
public func execute(request: Request, deadline: NIODeadline? = nil) -> EventLoopFuture<Response> {
return self.execute(request: request, deadline: deadline, logger: HTTPClient.loggingDisabled)
}
/// Execute arbitrary HTTP request using specified URL.
///
/// - parameters:
/// - request: HTTP request to execute.
/// - deadline: Point in time by which the request must complete.
/// - logger: The logger to use for this request.
public func execute(request: Request, deadline: NIODeadline? = nil, logger: Logger) -> EventLoopFuture<Response> {
let accumulator = ResponseAccumulator(request: request)
return self.execute(request: request, delegate: accumulator, deadline: deadline, logger: logger).futureResult
}
/// Execute arbitrary HTTP request using specified URL.
///
/// - parameters:
/// - request: HTTP request to execute.
/// - eventLoop: NIO Event Loop preference.
/// - deadline: Point in time by which the request must complete.
public func execute(request: Request, eventLoop: EventLoopPreference, deadline: NIODeadline? = nil) -> EventLoopFuture<Response> {
return self.execute(request: request,
eventLoop: eventLoop,
deadline: deadline,
logger: HTTPClient.loggingDisabled)
}
/// Execute arbitrary HTTP request and handle response processing using provided delegate.
///
/// - parameters:
/// - request: HTTP request to execute.
/// - eventLoop: NIO Event Loop preference.
/// - deadline: Point in time by which the request must complete.
/// - logger: The logger to use for this request.
public func execute(request: Request,
eventLoop eventLoopPreference: EventLoopPreference,
deadline: NIODeadline? = nil,
logger: Logger?) -> EventLoopFuture<Response> {
let accumulator = ResponseAccumulator(request: request)
return self.execute(request: request, delegate: accumulator, eventLoop: eventLoopPreference, deadline: deadline, logger: logger).futureResult
}
/// Execute arbitrary HTTP request and handle response processing using provided delegate.
///
/// - parameters:
/// - request: HTTP request to execute.
/// - delegate: Delegate to process response parts.
/// - deadline: Point in time by which the request must complete.
public func execute<Delegate: HTTPClientResponseDelegate>(request: Request,
delegate: Delegate,
deadline: NIODeadline? = nil) -> Task<Delegate.Response> {
return self.execute(request: request, delegate: delegate, deadline: deadline, logger: HTTPClient.loggingDisabled)
}
/// Execute arbitrary HTTP request and handle response processing using provided delegate.
///
/// - parameters:
/// - request: HTTP request to execute.
/// - delegate: Delegate to process response parts.
/// - deadline: Point in time by which the request must complete.
/// - logger: The logger to use for this request.
public func execute<Delegate: HTTPClientResponseDelegate>(request: Request,
delegate: Delegate,
deadline: NIODeadline? = nil,
logger: Logger) -> Task<Delegate.Response> {
return self.execute(request: request, delegate: delegate, eventLoop: .indifferent, deadline: deadline, logger: logger)
}
/// Execute arbitrary HTTP request and handle response processing using provided delegate.
///
/// - parameters:
/// - request: HTTP request to execute.
/// - delegate: Delegate to process response parts.
/// - eventLoop: NIO Event Loop preference.
/// - deadline: Point in time by which the request must complete.
/// - logger: The logger to use for this request.
public func execute<Delegate: HTTPClientResponseDelegate>(request: Request,
delegate: Delegate,
eventLoop eventLoopPreference: EventLoopPreference,
deadline: NIODeadline? = nil) -> Task<Delegate.Response> {
return self.execute(request: request,
delegate: delegate,
eventLoop: eventLoopPreference,
deadline: deadline,
logger: HTTPClient.loggingDisabled)
}
/// Execute arbitrary HTTP request and handle response processing using provided delegate.
///
/// - parameters:
/// - request: HTTP request to execute.
/// - delegate: Delegate to process response parts.
/// - eventLoop: NIO Event Loop preference.
/// - deadline: Point in time by which the request must complete.
/// - logger: The logger to use for this request.
public func execute<Delegate: HTTPClientResponseDelegate>(
request: Request,
delegate: Delegate,
eventLoop eventLoopPreference: EventLoopPreference,
deadline: NIODeadline? = nil,
logger originalLogger: Logger?
) -> Task<Delegate.Response> {
self._execute(
request: request,
delegate: delegate,
eventLoop: eventLoopPreference,
deadline: deadline,
logger: originalLogger,
redirectState: RedirectState(
self.configuration.redirectConfiguration.mode,
initialURL: request.url.absoluteString
)
)
}
/// Execute arbitrary HTTP request and handle response processing using provided delegate.
///
/// - parameters:
/// - request: HTTP request to execute.
/// - delegate: Delegate to process response parts.
/// - eventLoop: NIO Event Loop preference.
/// - deadline: Point in time by which the request must complete.
/// - logger: The logger to use for this request.
func _execute<Delegate: HTTPClientResponseDelegate>(
request: Request,
delegate: Delegate,
eventLoop eventLoopPreference: EventLoopPreference,
deadline: NIODeadline? = nil,
logger originalLogger: Logger?,
redirectState: RedirectState?
) -> Task<Delegate.Response> {
let logger = (originalLogger ?? HTTPClient.loggingDisabled).attachingRequestInformation(request, requestID: globalRequestID.wrappingIncrementThenLoad(ordering: .relaxed))
let taskEL: EventLoop
switch eventLoopPreference.preference {
case .indifferent:
// if possible we want a connection on the current `EventLoop`
taskEL = self.eventLoopGroup.any()
case .delegate(on: let eventLoop):
precondition(self.eventLoopGroup.makeIterator().contains { $0 === eventLoop }, "Provided EventLoop must be part of clients EventLoopGroup.")
taskEL = eventLoop
case .delegateAndChannel(on: let eventLoop):
precondition(self.eventLoopGroup.makeIterator().contains { $0 === eventLoop }, "Provided EventLoop must be part of clients EventLoopGroup.")
taskEL = eventLoop
case .testOnly_exact(_, delegateOn: let delegateEL):
taskEL = delegateEL
}
logger.trace("selected EventLoop for task given the preference",
metadata: ["ahc-eventloop": "\(taskEL)",
"ahc-el-preference": "\(eventLoopPreference)"])
let failedTask: Task<Delegate.Response>? = self.stateLock.withLock {
switch self.state {
case .upAndRunning:
return nil
case .shuttingDown, .shutDown:
logger.debug("client is shutting down, failing request")
return Task<Delegate.Response>.failedTask(eventLoop: taskEL,
error: HTTPClientError.alreadyShutdown,
logger: logger,
makeOrGetFileIOThreadPool: self.makeOrGetFileIOThreadPool)
}
}
if let failedTask = failedTask {
return failedTask
}
let redirectHandler: RedirectHandler<Delegate.Response>? = {
guard let redirectState = redirectState else { return nil }
return .init(request: request, redirectState: redirectState) { newRequest, newRedirectState in
self._execute(
request: newRequest,
delegate: delegate,
eventLoop: eventLoopPreference,
deadline: deadline,
logger: logger,
redirectState: newRedirectState
)
}
}()
let task = Task<Delegate.Response>(eventLoop: taskEL, logger: logger, makeOrGetFileIOThreadPool: self.makeOrGetFileIOThreadPool)
do {
let requestBag = try RequestBag(
request: request,
eventLoopPreference: eventLoopPreference,
task: task,
redirectHandler: redirectHandler,
connectionDeadline: .now() + (self.configuration.timeout.connectionCreationTimeout),
requestOptions: .fromClientConfiguration(self.configuration),
delegate: delegate
)
var deadlineSchedule: Scheduled<Void>?
if let deadline = deadline {
deadlineSchedule = taskEL.scheduleTask(deadline: deadline) {
requestBag.deadlineExceeded()
}
task.promise.futureResult.whenComplete { _ in
deadlineSchedule?.cancel()
}
}
self.poolManager.executeRequest(requestBag)
} catch {
task.fail(with: error, delegateType: Delegate.self)
}
return task
}
/// ``HTTPClient`` configuration.
public struct Configuration {
/// TLS configuration, defaults to `TLSConfiguration.makeClientConfiguration()`.
public var tlsConfiguration: Optional<TLSConfiguration>
/// Sometimes it can be useful to connect to one host e.g. `x.example.com` but
/// request and validate the certificate chain as if we would connect to `y.example.com`.
/// ``dnsOverride`` allows to do just that by mapping host names which we will request and validate the certificate chain, to a different
/// host name which will be used to actually connect to.
///
/// **Example:** if ``dnsOverride`` is set to `["example.com": "localhost"]` and we execute a request with a
/// `url` of `https://example.com/`, the ``HTTPClient`` will actually open a connection to `localhost` instead of `example.com`.
/// ``HTTPClient`` will still request certificates from the server for `example.com` and validate them as if we would connect to `example.com`.
public var dnsOverride: [String: String] = [:]
/// Enables following 3xx redirects automatically.
///
/// Following redirects are supported:
/// - `301: Moved Permanently`
/// - `302: Found`
/// - `303: See Other`
/// - `304: Not Modified`
/// - `305: Use Proxy`
/// - `307: Temporary Redirect`
/// - `308: Permanent Redirect`
public var redirectConfiguration: RedirectConfiguration
/// Default client timeout, defaults to no ``Timeout-swift.struct/read`` timeout
/// and 10 seconds ``Timeout-swift.struct/connect`` timeout.
public var timeout: Timeout
/// Connection pool configuration.
public var connectionPool: ConnectionPool
/// Upstream proxy, defaults to no proxy.
public var proxy: Proxy?
/// Enables automatic body decompression. Supported algorithms are gzip and deflate.
public var decompression: Decompression
/// Ignore TLS unclean shutdown error, defaults to `false`.
@available(*, deprecated, message: "AsyncHTTPClient now correctly supports handling unexpected SSL connection drops. This property is ignored")
public var ignoreUncleanSSLShutdown: Bool {
get { false }
set {}
}
/// What HTTP versions to use.
///
/// Set to ``HTTPVersion-swift.struct/automatic`` by default which will use HTTP/2 if run over https and the server supports it, otherwise HTTP/1
public var httpVersion: HTTPVersion
/// Whether ``HTTPClient`` will let Network.framework sit in the `.waiting` state awaiting new network changes, or fail immediately. Defaults to `true`,
/// which is the recommended setting. Only set this to `false` when attempting to trigger a particular error path.
public var networkFrameworkWaitForConnectivity: Bool
/// The maximum number of times each connection can be used before it is replaced with a new one. Use `nil` (the default)
/// if no limit should be applied to each connection.
///
/// - Precondition: The value must be greater than zero.
public var maximumUsesPerConnection: Int? {
willSet {
if let newValue = newValue, newValue <= 0 {
fatalError("maximumUsesPerConnection must be greater than zero or nil")
}
}
}
public init(
tlsConfiguration: TLSConfiguration? = nil,
redirectConfiguration: RedirectConfiguration? = nil,
timeout: Timeout = Timeout(),
connectionPool: ConnectionPool = ConnectionPool(),
proxy: Proxy? = nil,
ignoreUncleanSSLShutdown: Bool = false,
decompression: Decompression = .disabled
) {
self.tlsConfiguration = tlsConfiguration
self.redirectConfiguration = redirectConfiguration ?? RedirectConfiguration()
self.timeout = timeout
self.connectionPool = connectionPool
self.proxy = proxy
self.decompression = decompression
self.httpVersion = .automatic
self.networkFrameworkWaitForConnectivity = true
}
public init(tlsConfiguration: TLSConfiguration? = nil,
redirectConfiguration: RedirectConfiguration? = nil,
timeout: Timeout = Timeout(),
proxy: Proxy? = nil,
ignoreUncleanSSLShutdown: Bool = false,
decompression: Decompression = .disabled) {
self.init(
tlsConfiguration: tlsConfiguration,
redirectConfiguration: redirectConfiguration,
timeout: timeout,
connectionPool: ConnectionPool(),
proxy: proxy,
ignoreUncleanSSLShutdown: ignoreUncleanSSLShutdown,
decompression: decompression
)
}
public init(certificateVerification: CertificateVerification,
redirectConfiguration: RedirectConfiguration? = nil,
timeout: Timeout = Timeout(),
maximumAllowedIdleTimeInConnectionPool: TimeAmount = .seconds(60),
proxy: Proxy? = nil,
ignoreUncleanSSLShutdown: Bool = false,
decompression: Decompression = .disabled) {
var tlsConfig = TLSConfiguration.makeClientConfiguration()
tlsConfig.certificateVerification = certificateVerification
self.init(tlsConfiguration: tlsConfig,
redirectConfiguration: redirectConfiguration,
timeout: timeout,
connectionPool: ConnectionPool(idleTimeout: maximumAllowedIdleTimeInConnectionPool),
proxy: proxy,
ignoreUncleanSSLShutdown: ignoreUncleanSSLShutdown,
decompression: decompression)
}
public init(certificateVerification: CertificateVerification,
redirectConfiguration: RedirectConfiguration? = nil,
timeout: Timeout = Timeout(),
connectionPool: TimeAmount = .seconds(60),
proxy: Proxy? = nil,
ignoreUncleanSSLShutdown: Bool = false,
decompression: Decompression = .disabled,
backgroundActivityLogger: Logger?) {
var tlsConfig = TLSConfiguration.makeClientConfiguration()
tlsConfig.certificateVerification = certificateVerification
self.init(tlsConfiguration: tlsConfig,
redirectConfiguration: redirectConfiguration,
timeout: timeout,
connectionPool: ConnectionPool(idleTimeout: connectionPool),
proxy: proxy,
ignoreUncleanSSLShutdown: ignoreUncleanSSLShutdown,
decompression: decompression)
}
public init(certificateVerification: CertificateVerification,
redirectConfiguration: RedirectConfiguration? = nil,
timeout: Timeout = Timeout(),
proxy: Proxy? = nil,
ignoreUncleanSSLShutdown: Bool = false,
decompression: Decompression = .disabled) {
self.init(
certificateVerification: certificateVerification,
redirectConfiguration: redirectConfiguration,
timeout: timeout,
maximumAllowedIdleTimeInConnectionPool: .seconds(60),
proxy: proxy,
ignoreUncleanSSLShutdown: ignoreUncleanSSLShutdown,
decompression: decompression
)
}
}
/// Specifies how `EventLoopGroup` will be created and establishes lifecycle ownership.
public enum EventLoopGroupProvider {
/// `EventLoopGroup` will be provided by the user. Owner of this group is responsible for its lifecycle.
case shared(EventLoopGroup)
/// The original intention of this was that ``HTTPClient`` would create and own its own `EventLoopGroup` to
/// facilitate use in programs that are not already using SwiftNIO.
/// Since https://github.com/apple/swift-nio/pull/2471 however, SwiftNIO does provide a global, shared singleton
/// `EventLoopGroup`s that we can use. ``HTTPClient`` is no longer able to create & own its own
/// `EventLoopGroup` which solves a whole host of issues around shutdown.
@available(*, deprecated, renamed: "singleton", message: "Please use the singleton EventLoopGroup explicitly")
case createNew
}
/// Specifies how the library will treat the event loop passed by the user.
public struct EventLoopPreference {
enum Preference {
/// Event Loop will be selected by the library.
case indifferent
/// The delegate will be run on the specified EventLoop (and the Channel if possible).
case delegate(on: EventLoop)
/// The delegate and the `Channel` will be run on the specified EventLoop.
case delegateAndChannel(on: EventLoop)
case testOnly_exact(channelOn: EventLoop, delegateOn: EventLoop)
}
var preference: Preference
init(_ preference: Preference) {
self.preference = preference
}
/// Event Loop will be selected by the library.
public static let indifferent = EventLoopPreference(.indifferent)
/// The delegate will be run on the specified EventLoop (and the Channel if possible).
///
/// This will call the configured delegate on `eventLoop` and will try to use a `Channel` on the same
/// `EventLoop` but will not establish a new network connection just to satisfy the `EventLoop` preference if
/// another existing connection on a different `EventLoop` is readily available from a connection pool.
public static func delegate(on eventLoop: EventLoop) -> EventLoopPreference {
return EventLoopPreference(.delegate(on: eventLoop))
}
/// The delegate and the `Channel` will be run on the specified EventLoop.
///
/// Use this for use-cases where you prefer a new connection to be established over re-using an existing
/// connection that might be on a different `EventLoop`.
public static func delegateAndChannel(on eventLoop: EventLoop) -> EventLoopPreference {
return EventLoopPreference(.delegateAndChannel(on: eventLoop))
}
}
/// Specifies decompression settings.
public enum Decompression: Sendable {
/// Decompression is disabled.
case disabled
/// Decompression is enabled.
case enabled(limit: NIOHTTPDecompression.DecompressionLimit)
}
typealias ShutdownCallback = @Sendable (Error?) -> Void
enum State {
case upAndRunning
case shuttingDown(requiresCleanClose: Bool, callback: ShutdownCallback)
case shutDown
}
}
extension HTTPClient.EventLoopGroupProvider {
/// Shares ``HTTPClient/defaultEventLoopGroup`` which is a singleton `EventLoopGroup` suitable for the platform.
public static var singleton: Self {
return .shared(HTTPClient.defaultEventLoopGroup)
}
}
extension HTTPClient {
/// Returns the default `EventLoopGroup` singleton, automatically selecting the best for the platform.
///
/// This will select the concrete `EventLoopGroup` depending which platform this is running on.
public static var defaultEventLoopGroup: EventLoopGroup {
#if canImport(Network)
if #available(OSX 10.14, iOS 12.0, tvOS 12.0, watchOS 6.0, *) {
return NIOTSEventLoopGroup.singleton
} else {
return MultiThreadedEventLoopGroup.singleton
}
#else
return MultiThreadedEventLoopGroup.singleton
#endif
}
}
extension HTTPClient.Configuration: Sendable {}
extension HTTPClient.EventLoopGroupProvider: Sendable {}
extension HTTPClient.EventLoopPreference: Sendable {}
// HTTPClient is thread-safe because its shared mutable state is protected through a lock
extension HTTPClient: @unchecked Sendable {}
extension HTTPClient.Configuration {
/// Timeout configuration.
public struct Timeout: Sendable {
/// Specifies connect timeout. If no connect timeout is given, a default 10 seconds timeout will be applied.
public var connect: TimeAmount?
/// Specifies read timeout.
public var read: TimeAmount?
/// Specifies the maximum amount of time without bytes being written by the client before closing the connection.
public var write: TimeAmount?
/// Internal connection creation timeout. Defaults the connect timeout to always contain a value.
var connectionCreationTimeout: TimeAmount {
self.connect ?? .seconds(10)
}
/// Create timeout.
///
/// - parameters:
/// - connect: `connect` timeout. Will default to 10 seconds, if no value is provided.
/// - read: `read` timeout.
public init(
connect: TimeAmount? = nil,
read: TimeAmount? = nil
) {
self.connect = connect
self.read = read
}
/// Create timeout.
///
/// - parameters:
/// - connect: `connect` timeout. Will default to 10 seconds, if no value is provided.
/// - read: `read` timeout.
/// - write: `write` timeout.
public init(
connect: TimeAmount? = nil,
read: TimeAmount? = nil,
write: TimeAmount
) {
self.connect = connect
self.read = read
self.write = write
}
}
/// Specifies redirect processing settings.
public struct RedirectConfiguration: Sendable {
enum Mode {
/// Redirects are not followed.
case disallow
/// Redirects are followed with a specified limit.
case follow(max: Int, allowCycles: Bool)
}
var mode: Mode
init() {
self.mode = .follow(max: 5, allowCycles: false)
}
init(configuration: Mode) {
self.mode = configuration
}
/// Redirects are not followed.
public static let disallow = RedirectConfiguration(configuration: .disallow)