-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathURLSessionTask.swift
1427 lines (1265 loc) · 60.9 KB
/
URLSessionTask.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
// Foundation/URLSession/URLSessionTask.swift - URLSession API
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
///
/// URLSession API code.
/// - SeeAlso: URLSession.swift
///
// -----------------------------------------------------------------------------
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import SwiftFoundation
#else
import Foundation
#endif
private class Bag<Element> {
var values: [Element] = []
}
/// A cancelable object that refers to the lifetime
/// of processing a given request.
open class URLSessionTask : NSObject, NSCopying, @unchecked Sendable {
// These properties aren't heeded in swift-corelibs-foundation, but we may heed them in the future. They exist for source compatibility.
open var countOfBytesClientExpectsToReceive: Int64 = NSURLSessionTransferSizeUnknown {
didSet { updateProgress() }
}
open var countOfBytesClientExpectsToSend: Int64 = NSURLSessionTransferSizeUnknown {
didSet { updateProgress() }
}
/* On platforms with NS_CURL_XFERINFOFUNCTION_SUPPORTED not set, the progress instance returned will be functional, but may not have continuous updates as bytes are sent or received. */
open private(set) var progress = Progress(totalUnitCount: -1)
func updateProgress() {
self.workQueue.async {
let progress = self.progress
switch self.state {
case .canceling: fallthrough
case .completed:
let total = progress.totalUnitCount
let finalTotal = total < 0 ? 1 : total
progress.totalUnitCount = finalTotal
progress.completedUnitCount = finalTotal
default:
let toBeSent: Int64?
if let bodyLength = try? self.knownBody?.getBodyLength() {
toBeSent = Int64(clamping: bodyLength)
} else if self.countOfBytesExpectedToSend > 0 {
toBeSent = Int64(clamping: self.countOfBytesExpectedToSend)
} else if self.countOfBytesClientExpectsToSend != NSURLSessionTransferSizeUnknown && self.countOfBytesClientExpectsToSend > 0 {
toBeSent = Int64(clamping: self.countOfBytesClientExpectsToSend)
} else {
toBeSent = nil
}
let sent = self.countOfBytesSent
let toBeReceived: Int64?
if self.countOfBytesExpectedToReceive > 0 {
toBeReceived = Int64(clamping: self.countOfBytesClientExpectsToReceive)
} else if self.countOfBytesClientExpectsToReceive != NSURLSessionTransferSizeUnknown && self.countOfBytesClientExpectsToReceive > 0 {
toBeReceived = Int64(clamping: self.countOfBytesClientExpectsToReceive)
} else {
toBeReceived = nil
}
let received = self.countOfBytesReceived
progress.completedUnitCount = sent.addingReportingOverflow(received).partialValue
if let toBeSent = toBeSent, let toBeReceived = toBeReceived {
progress.totalUnitCount = toBeSent.addingReportingOverflow(toBeReceived).partialValue
} else {
progress.totalUnitCount = -1
}
}
}
}
// We're not going to heed this one. If someone is setting it in Linux code, they may be relying on behavior that isn't there; warn.
@available(*, deprecated, message: "swift-corelibs-foundation does not support background URLSession instances, and this property is documented to have no effect when set on tasks created from non-background URLSession instances. Modifying this property has no effect in swift-corelibs-foundation and shouldn't be relied upon; resume tasks at the appropriate time instead.")
open var earliestBeginDate: Date? = nil
/// How many times the task has been suspended, 0 indicating a running task.
internal var suspendCount = 1
internal var actualSession: URLSession? { return session as? URLSession }
internal var session: URLSessionProtocol! //change to nil when task completes
private var _taskDelegate: URLSessionTaskDelegate?
open var delegate: URLSessionTaskDelegate? {
get {
if let _taskDelegate { return _taskDelegate }
return self.actualSession?.delegate as? URLSessionTaskDelegate
}
set {
guard !self.hasTriggeredResume else {
fatalError("Cannot set task delegate after resumption")
}
_taskDelegate = newValue
}
}
internal var _callCompletionHandlerInline = false
fileprivate enum ProtocolState {
case toBeCreated
case awaitingCacheReply(Bag<(URLProtocol?) -> Void>)
case existing(URLProtocol)
case invalidated
}
fileprivate let _protocolLock = NSLock() // protects:
fileprivate var _protocolStorage: ProtocolState = .toBeCreated
internal var _lastCredentialUsedFromStorageDuringAuthentication: (protectionSpace: URLProtectionSpace, credential: URLCredential)?
private var _protocolClass: URLProtocol.Type? {
guard let request = currentRequest else { fatalError("A protocol class was requested, but we do not have a current request") }
let protocolClasses = session.configuration.protocolClasses ?? []
if let urlProtocolClass = URLProtocol.getProtocolClass(protocols: protocolClasses, request: request) {
guard let urlProtocol = urlProtocolClass as? URLProtocol.Type else { fatalError("A protocol class specified in the URLSessionConfiguration's .protocolClasses array was not a URLProtocol subclass: \(urlProtocolClass)") }
return urlProtocol
} else {
let protocolClasses = URLProtocol.getProtocols() ?? []
if let urlProtocolClass = URLProtocol.getProtocolClass(protocols: protocolClasses, request: request) {
guard let urlProtocol = urlProtocolClass as? URLProtocol.Type else { fatalError("A protocol class registered with URLProtocol.register… was not a URLProtocol subclass: \(urlProtocolClass)") }
return urlProtocol
}
}
return nil
}
func _getProtocol(_ callback: @escaping (URLProtocol?) -> Void) {
_protocolLock.lock() // Must be balanced below, before we call out ⬇
switch _protocolStorage {
case .toBeCreated:
guard let protocolClass = self._protocolClass else {
_protocolLock.unlock() // Balances above ⬆
callback(nil)
break
}
if let cache = session.configuration.urlCache, let me = self as? URLSessionDataTask {
let bag: Bag<(URLProtocol?) -> Void> = Bag()
bag.values.append(callback)
_protocolStorage = .awaitingCacheReply(bag)
_protocolLock.unlock() // Balances above ⬆
cache.getCachedResponse(for: me) { (response) in
let urlProtocol = protocolClass.init(task: self, cachedResponse: response, client: nil)
self._satisfyProtocolRequest(with: urlProtocol)
}
} else {
let urlProtocol = protocolClass.init(task: self, cachedResponse: nil, client: nil)
_protocolStorage = .existing(urlProtocol)
_protocolLock.unlock() // Balances above ⬆
callback(urlProtocol)
}
case .awaitingCacheReply(let bag):
bag.values.append(callback)
_protocolLock.unlock() // Balances above ⬆
case .existing(let urlProtocol):
_protocolLock.unlock() // Balances above ⬆
callback(urlProtocol)
case .invalidated:
_protocolLock.unlock() // Balances above ⬆
callback(nil)
}
}
func _satisfyProtocolRequest(with urlProtocol: URLProtocol) {
_protocolLock.lock() // Must be balanced below, before we call out ⬇
switch _protocolStorage {
case .toBeCreated:
_protocolStorage = .existing(urlProtocol)
_protocolLock.unlock() // Balances above ⬆
case .awaitingCacheReply(let bag):
_protocolStorage = .existing(urlProtocol)
_protocolLock.unlock() // Balances above ⬆
for callback in bag.values {
callback(urlProtocol)
}
case .existing(_): fallthrough
case .invalidated:
_protocolLock.unlock() // Balances above ⬆
}
}
func _invalidateProtocol() {
_protocolLock.performLocked {
_protocolStorage = .invalidated
}
}
internal var knownBody: _Body?
func getBody(completion: @escaping (_Body) -> Void) {
if let body = knownBody {
completion(body)
return
}
if let session = actualSession, let delegate = self.delegate {
nonisolated(unsafe) let nonisolatedCompletion = completion
delegate.urlSession(session, task: self) { (stream) in
if let stream = stream {
nonisolatedCompletion(.stream(stream))
} else {
nonisolatedCompletion(.none)
}
}
} else {
completion(.none)
}
}
private let syncQ = DispatchQueue(label: "org.swift.URLSessionTask.SyncQ")
private var hasTriggeredResume: Bool = false
internal var isSuspendedAfterResume: Bool {
return self.syncQ.sync { return self.hasTriggeredResume } && self.state == .suspended
}
/// All operations must run on this queue.
internal let workQueue: DispatchQueue
public override init() {
// Darwin Foundation oddly allows calling this initializer, even though
// such a task is quite broken -- it doesn't have a session. And calling
// e.g. `taskIdentifier` will crash.
//
// We set up the bare minimum for init to work, but don't care too much
// about things crashing later.
session = _MissingURLSession()
taskIdentifier = 0
originalRequest = nil
knownBody = URLSessionTask._Body.none
workQueue = DispatchQueue(label: "URLSessionTask.notused.0")
super.init()
}
/// Create a data task. If there is a httpBody in the URLRequest, use that as a parameter
internal convenience init(session: URLSession, request: URLRequest, taskIdentifier: Int) {
if let bodyData = request.httpBody, !bodyData.isEmpty {
self.init(session: session, request: request, taskIdentifier: taskIdentifier, body: _Body.data(createDispatchData(bodyData)))
} else if let bodyStream = request.httpBodyStream {
self.init(session: session, request: request, taskIdentifier: taskIdentifier, body: _Body.stream(bodyStream))
} else {
self.init(session: session, request: request, taskIdentifier: taskIdentifier, body: _Body.none)
}
}
internal init(session: URLSession, request: URLRequest, taskIdentifier: Int, body: _Body?) {
self.session = session
/* make sure we're actually having a serial queue as it's used for synchronization */
self.workQueue = DispatchQueue.init(label: "org.swift.URLSessionTask.WorkQueue", target: session.workQueue)
self.taskIdentifier = taskIdentifier
self.originalRequest = request
self.knownBody = body
super.init()
self.currentRequest = request
self.progress.cancellationHandler = { [weak self] in
self?.cancel()
}
}
deinit {
//TODO: Do we remove the EasyHandle from the session here? This might run on the wrong thread / queue.
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone?) -> Any {
return self
}
/// An identifier for this task, assigned by and unique to the owning session
open internal(set) var taskIdentifier: Int
/// May be nil if this is a stream task
/*@NSCopying*/ open private(set) var originalRequest: URLRequest?
/// If there's an authentication failure, we'd need to create a new request with the credentials supplied by the user
var authRequest: URLRequest? = nil
/// Authentication failure count
fileprivate var previousFailureCount = 0
/// May differ from originalRequest due to http server redirection
/*@NSCopying*/ open internal(set) var currentRequest: URLRequest? {
get {
return self.syncQ.sync { return self._currentRequest }
}
set {
self.syncQ.sync { self._currentRequest = newValue }
}
}
fileprivate var _currentRequest: URLRequest? = nil
/*@NSCopying*/ open internal(set) var response: URLResponse? {
get {
return self.syncQ.sync { return self._response }
}
set {
self.syncQ.sync { self._response = newValue }
}
}
fileprivate var _response: URLResponse? = nil
/* Byte count properties may be zero if no body is expected,
* or URLSessionTransferSizeUnknown if it is not possible
* to know how many bytes will be transferred.
*/
/// Number of body bytes already received
open internal(set) var countOfBytesReceived: Int64 {
get {
return self.syncQ.sync { return self._countOfBytesReceived }
}
set {
self.syncQ.sync { self._countOfBytesReceived = newValue }
updateProgress()
}
}
fileprivate var _countOfBytesReceived: Int64 = 0
/// Number of body bytes already sent */
open internal(set) var countOfBytesSent: Int64 {
get {
return self.syncQ.sync { return self._countOfBytesSent }
}
set {
self.syncQ.sync { self._countOfBytesSent = newValue }
updateProgress()
}
}
fileprivate var _countOfBytesSent: Int64 = 0
/// Number of body bytes we expect to send, derived from the Content-Length of the HTTP request */
open internal(set) var countOfBytesExpectedToSend: Int64 = 0 {
didSet { updateProgress() }
}
/// Number of bytes we expect to receive, usually derived from the Content-Length header of an HTTP response. */
open internal(set) var countOfBytesExpectedToReceive: Int64 = 0 {
didSet { updateProgress() }
}
/// The taskDescription property is available for the developer to
/// provide a descriptive label for the task.
open var taskDescription: String?
/* -cancel returns immediately, but marks a task as being canceled.
* The task will signal -URLSession:task:didCompleteWithError: with an
* error value of { NSURLErrorDomain, NSURLErrorCancelled }. In some
* cases, the task may signal other work before it acknowledges the
* cancellation. -cancel may be sent to a task that has been suspended.
*/
open func cancel() {
workQueue.sync {
let canceled = self.syncQ.sync { () -> Bool in
guard self._state == .running || self._state == .suspended else { return true }
self._state = .canceling
return false
}
guard !canceled else { return }
self._getProtocol { (urlProtocol) in
// The combination of locking in getProtocol and dispatching to the work queue let us use the normally non-Sendable URLProtocol
nonisolated(unsafe) let urlProtocol = urlProtocol
self.workQueue.async {
var info = [NSLocalizedDescriptionKey: "\(URLError.Code.cancelled)" as Any]
if let url = self.originalRequest?.url {
info[NSURLErrorFailingURLErrorKey] = url
info[NSURLErrorFailingURLStringErrorKey] = url.absoluteString
}
let urlError = URLError(_nsError: NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: info))
self.error = urlError
if let urlProtocol = urlProtocol {
urlProtocol.stopLoading()
urlProtocol.client?.urlProtocol(urlProtocol, didFailWithError: urlError)
}
}
}
}
}
/*
* The current state of the task within the session.
*/
open fileprivate(set) var state: URLSessionTask.State {
get {
return self.syncQ.sync { self._state }
}
set {
self.syncQ.sync { self._state = newValue }
}
}
fileprivate var _state: URLSessionTask.State = .suspended
/*
* The error, if any, delivered via -URLSession:task:didCompleteWithError:
* This property will be nil in the event that no error occurred.
*/
/*@NSCopying*/ open internal(set) var error: Error?
/// Suspend the task.
///
/// Suspending a task will prevent the URLSession from continuing to
/// load data. There may still be delegate calls made on behalf of
/// this task (for instance, to report data received while suspending)
/// but no further transmissions will be made on behalf of the task
/// until -resume is sent. The timeout timer associated with the task
/// will be disabled while a task is suspended. -suspend and -resume are
/// nestable.
open func suspend() {
// suspend / resume is implemented simply by adding / removing the task's
// easy handle fromt he session's multi-handle.
//
// This might result in slightly different behaviour than the Darwin Foundation
// implementation, but it'll be difficult to get complete parity anyhow.
// Too many things depend on timeout on the wire etc.
//
// TODO: It may be worth looking into starting over a task that gets
// resumed. The Darwin Foundation documentation states that that's what
// it does for anything but download tasks.
// We perform the increment and call to `updateTaskState()`
// synchronous, to make sure the `state` is updated when this method
// returns, but the actual suspend will be done asynchronous to avoid
// dead-locks.
workQueue.sync {
guard self.state != .canceling && self.state != .completed else { return }
self.suspendCount += 1
guard self.suspendCount < Int.max else { fatalError("Task suspended too many times \(Int.max).") }
self.updateTaskState()
if self.suspendCount == 1 {
self._getProtocol { (urlProtocol) in
// The combination of locking in getProtocol and dispatching to the work queue let us use the normally non-Sendable URLProtocol
nonisolated(unsafe) let urlProtocol = urlProtocol
self.workQueue.async {
urlProtocol?.stopLoading()
}
}
}
}
}
/// Resume the task.
///
/// - SeeAlso: `suspend()`
open func resume() {
workQueue.sync {
guard self.state != .canceling && self.state != .completed else { return }
if self.suspendCount > 0 { self.suspendCount -= 1 }
self.updateTaskState()
if self.suspendCount == 0 {
self.hasTriggeredResume = true
self._getProtocol { (urlProtocol) in
// The combination of locking in getProtocol and dispatching to the work queue let us use the normally non-Sendable URLProtocol
nonisolated(unsafe) let urlProtocol = urlProtocol
self.workQueue.async {
if let _protocol = urlProtocol {
_protocol.startLoading()
}
else if self.error == nil {
var userInfo: [String: Any] = [NSLocalizedDescriptionKey: "unsupported URL"]
if let url = self.originalRequest?.url {
userInfo[NSURLErrorFailingURLErrorKey] = url
userInfo[NSURLErrorFailingURLStringErrorKey] = url.absoluteString
}
let urlError = URLError(_nsError: NSError(domain: NSURLErrorDomain,
code: NSURLErrorUnsupportedURL,
userInfo: userInfo))
self.error = urlError
_ProtocolClient().urlProtocol(task: self, didFailWithError: urlError)
}
}
}
}
}
}
/// The priority of the task.
///
/// Sets a scaling factor for the priority of the task. The scaling factor is a
/// value between 0.0 and 1.0 (inclusive), where 0.0 is considered the lowest
/// priority and 1.0 is considered the highest.
///
/// The priority is a hint and not a hard requirement of task performance. The
/// priority of a task may be changed using this API at any time, but not all
/// protocols support this; in these cases, the last priority that took effect
/// will be used.
///
/// If no priority is specified, the task will operate with the default priority
/// as defined by the constant URLSessionTask.defaultPriority. Two additional
/// priority levels are provided: URLSessionTask.lowPriority and
/// URLSessionTask.highPriority, but use is not restricted to these.
open var priority: Float {
get {
return self.workQueue.sync { return self._priority }
}
set {
self.workQueue.sync { self._priority = newValue }
}
}
fileprivate var _priority: Float = URLSessionTask.defaultPriority
}
extension URLSessionTask {
public enum State : Int, Sendable {
/// The task is currently being serviced by the session
case running
case suspended
/// The task has been told to cancel. The session will receive a URLSession:task:didCompleteWithError: message.
case canceling
/// The task has completed and the session will receive no more delegate notifications
case completed
}
}
extension URLSessionTask : ProgressReporting {}
extension URLSessionTask {
/// Updates the (public) state based on private / internal state.
///
/// - Note: This must be called on the `workQueue`.
internal func updateTaskState() {
func calculateState() -> URLSessionTask.State {
if suspendCount == 0 {
return .running
} else {
return .suspended
}
}
state = calculateState()
}
}
internal extension URLSessionTask {
enum _Body {
case none
case data(DispatchData)
/// Body data is read from the given file URL
case file(URL)
case stream(InputStream)
}
}
internal extension URLSessionTask._Body {
enum _Error : Error {
case fileForBodyDataNotFound
}
/// - Returns: The body length, or `nil` for no body (e.g. `GET` request).
func getBodyLength() throws -> UInt64? {
switch self {
case .none:
return 0
case .data(let d):
return UInt64(d.count)
/// Body data is read from the given file URL
case .file(let fileURL):
guard let s = try FileManager.default.attributesOfItem(atPath: fileURL.path)[.size] as? NSNumber else {
throw _Error.fileForBodyDataNotFound
}
return s.uint64Value
case .stream:
return nil
}
}
}
fileprivate func errorCode(fileSystemError error: Error) -> Int {
func fromCocoaErrorCode(_ code: Int) -> Int {
switch code {
case CocoaError.fileReadNoSuchFile.rawValue:
return NSURLErrorFileDoesNotExist
case CocoaError.fileReadNoPermission.rawValue:
return NSURLErrorNoPermissionsToReadFile
default:
return NSURLErrorUnknown
}
}
switch error {
case let e as NSError where e.domain == NSCocoaErrorDomain:
return fromCocoaErrorCode(e.code)
default:
return NSURLErrorUnknown
}
}
extension URLSessionTask {
/// The default URL session task priority, used implicitly for any task you
/// have not prioritized. The floating point value of this constant is 0.5.
public static let defaultPriority: Float = 0.5
/// A low URL session task priority, with a floating point value above the
/// minimum of 0 and below the default value.
public static let lowPriority: Float = 0.25
/// A high URL session task priority, with a floating point value above the
/// default value and below the maximum of 1.0.
public static let highPriority: Float = 0.75
}
/*
* An URLSessionDataTask does not provide any additional
* functionality over an URLSessionTask and its presence is merely
* to provide lexical differentiation from download and upload tasks.
*/
open class URLSessionDataTask : URLSessionTask, @unchecked Sendable {
}
/*
* An URLSessionUploadTask does not currently provide any additional
* functionality over an URLSessionDataTask. All delegate messages
* that may be sent referencing an URLSessionDataTask equally apply
* to URLSessionUploadTasks.
*/
open class URLSessionUploadTask : URLSessionDataTask, @unchecked Sendable {
}
/*
* URLSessionDownloadTask is a task that represents a download to
* local storage.
*/
open class URLSessionDownloadTask : URLSessionTask, @unchecked Sendable {
var createdFromInvalidResumeData = false
// If a task is created from invalid resume data, prevent attempting creation of the protocol object.
override func _getProtocol(_ callback: @escaping (URLProtocol?) -> Void) {
if createdFromInvalidResumeData {
callback(nil)
} else {
super._getProtocol(callback)
}
}
internal var fileLength = -1.0
/* Cancel the download (and calls the superclass -cancel). If
* conditions will allow for resuming the download in the future, the
* callback will be called with an opaque data blob, which may be used
* with -downloadTaskWithResumeData: to attempt to resume the download.
* If resume data cannot be created, the completion handler will be
* called with nil resumeData.
*/
open func cancel(byProducingResumeData completionHandler: @escaping (Data?) -> Void) {
super.cancel()
/*
* In Objective-C, this method relies on an Apple-maintained XPC process
* to manage the bookmarking of partially downloaded data. Therefore, the
* original behavior cannot be directly ported, here.
*
* Instead, we just call the completionHandler directly.
*/
completionHandler(nil)
}
}
/*
* A URLSessionWebSocketTask is a task that allows clients to connect to servers supporting
* WebSocket. The task will perform the HTTP handshake to upgrade the connection
* and once the WebSocket handshake is successful, the client can read and write
* messages that will be framed using the WebSocket protocol by the framework.
*/
open class URLSessionWebSocketTask : URLSessionTask, @unchecked Sendable {
public enum CloseCode : Int, Sendable {
case invalid = 0
case normalClosure = 1000
case goingAway = 1001
case protocolError = 1002
case unsupportedData = 1003
case noStatusReceived = 1005
case abnormalClosure = 1006
case invalidFramePayloadData = 1007
case policyViolation = 1008
case messageTooBig = 1009
case mandatoryExtensionMissing = 1010
case internalServerError = 1011
case tlsHandshakeFailure = 1015
}
public enum Message : Sendable {
case data(Data)
case string(String)
}
internal var handshakeCompleted = false {
didSet {
doPendingWork()
}
}
private var taskError: Error? = nil {
didSet {
doPendingWork()
}
}
open override var error: Error? {
didSet {
doPendingWork()
}
}
private var sendBuffer = [(Message, @Sendable (Error?) -> Void)]()
private var receiveBuffer = [Message]()
private var receiveCompletionHandlers = [@Sendable (Result<Message, Error>) -> Void]()
private var pongCompletionHandlers = [@Sendable (Error?) -> Void]()
private var closeMessage: (CloseCode, Data)? = nil
internal var protocolPicked: String? = nil
func appendReceivedMessage(_ message: Message) {
workQueue.async {
self.receiveBuffer.append(message)
self.doPendingWork()
}
}
func noteReceivedPong() {
workQueue.async {
guard !self.pongCompletionHandlers.isEmpty else {
self.close(code: .protocolError, reason: nil)
return
}
let completionHandler = self.pongCompletionHandlers.removeFirst()
completionHandler(nil)
}
}
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
open func sendPing() async throws {
let _: Void = try await withCheckedThrowingContinuation { continuation in
sendPing { error in
if let error {
continuation.resume(throwing: error)
} else {
continuation.resume(returning: ())
}
}
}
}
open func sendPing(pongReceiveHandler: @Sendable @escaping (Error?) -> Void) {
self.workQueue.async {
self._getProtocol { urlProtocol in
// The combination of locking in getProtocol and dispatching to the work queue let us use the normally non-Sendable URLProtocol
nonisolated(unsafe) let urlProtocol = urlProtocol
self.workQueue.async {
if let webSocketProtocol = urlProtocol as? _WebSocketURLProtocol {
do {
try webSocketProtocol.sendWebSocketData(Data(), flags: [.ping])
self.pongCompletionHandlers.append(pongReceiveHandler)
} catch {
pongReceiveHandler(error)
}
} else {
let disconnectedError = URLError(_nsError: NSError(domain: NSURLErrorDomain,
code: NSURLErrorNetworkConnectionLost))
pongReceiveHandler(disconnectedError)
}
}
}
}
}
override open func cancel() {
cancel(with: .invalid, reason: nil)
}
open func cancel(with closeCode: CloseCode, reason: Data?) {
close(code: closeCode, reason: reason)
}
open var maximumMessageSize: Int = 1 * 1024 * 1024
open private(set) var closeCode: CloseCode = .invalid
open private(set) var closeReason: Data? = nil
internal func close(code: CloseCode, reason: Data?) {
workQueue.async {
// If we've already errored out in some way, no need to re-close.
if self.taskError != nil { return }
self.closeCode = code
self.closeReason = reason
self.taskError = URLError(_nsError: NSError(domain: NSURLErrorDomain,
code: NSURLErrorNetworkConnectionLost))
self.closeMessage = (code, reason ?? Data())
self.doPendingWork()
}
}
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public func send(_ message: Message) async throws -> Void {
let _: Void = try await withCheckedThrowingContinuation { continuation in
send(message) { error in
if let error {
continuation.resume(throwing: error)
} else {
continuation.resume(returning: ())
}
}
}
}
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public func send(_ message: Message, completionHandler: @Sendable @escaping (Error?) -> Void) {
self.workQueue.async {
self.sendBuffer.append((message, completionHandler))
self.doPendingWork()
}
}
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public func receive() async throws -> Message {
try await withCheckedThrowingContinuation { continuation in
receive() { result in
continuation.resume(with: result)
}
}
}
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public func receive(completionHandler: @Sendable @escaping (Result<Message, Error>) -> Void) {
self.workQueue.async {
self.receiveCompletionHandlers.append(completionHandler)
self.doPendingWork()
}
}
private func doPendingWork() {
self.workQueue.async {
let session = self.session as! URLSession
if let taskError = self.taskError ?? self.error {
for (_, handler) in self.sendBuffer {
session.delegateQueue.addOperation {
handler(taskError)
}
}
self.sendBuffer.removeAll()
for handler in self.receiveCompletionHandlers {
session.delegateQueue.addOperation {
handler(.failure(taskError))
}
}
self.receiveCompletionHandlers.removeAll()
for handler in self.pongCompletionHandlers {
session.delegateQueue.addOperation {
handler(taskError)
}
}
self.pongCompletionHandlers.removeAll()
self._getProtocol { urlProtocol in
// The combination of locking in getProtocol and dispatching to the work queue let us use the normally non-Sendable URLProtocol
nonisolated(unsafe) let urlProtocol = urlProtocol
self.workQueue.async {
if self.handshakeCompleted && self.state != .completed {
if let webSocketProtocol = urlProtocol as? _WebSocketURLProtocol {
if let closeMessage = self.closeMessage {
self.closeMessage = nil
var closeData = Data([UInt8(closeMessage.0.rawValue >> 8), UInt8(closeMessage.0.rawValue & 0xFF)])
closeData.append(contentsOf: closeMessage.1)
try? webSocketProtocol.sendWebSocketData(closeData, flags: [.close])
}
}
}
}
}
} else {
self._getProtocol { urlProtocol in
// The combination of locking in getProtocol and dispatching to the work queue let us use the normally non-Sendable URLProtocol
nonisolated(unsafe) let urlProtocol = urlProtocol
self.workQueue.async {
if self.handshakeCompleted {
if let webSocketProtocol = urlProtocol as? _WebSocketURLProtocol {
while !self.sendBuffer.isEmpty {
let (message, completionHandler) = self.sendBuffer.removeFirst()
do {
switch message {
case .data(let data):
try webSocketProtocol.sendWebSocketData(data, flags: [.binary])
case .string(let str):
try webSocketProtocol.sendWebSocketData(str.data(using: .utf8)!, flags: [.text])
}
completionHandler(nil)
} catch {
completionHandler(error)
}
}
if let closeMessage = self.closeMessage {
self.closeMessage = nil
var closeData = Data([UInt8(closeMessage.0.rawValue >> 8), UInt8(closeMessage.0.rawValue & 0xFF)])
closeData.append(contentsOf: closeMessage.1)
try? webSocketProtocol.sendWebSocketData(closeData, flags: [.close])
}
}
}
while !self.receiveBuffer.isEmpty && !self.receiveCompletionHandlers.isEmpty {
let message = self.receiveBuffer.removeFirst()
let handler = self.receiveCompletionHandlers.removeFirst()
handler(.success(message))
}
}
}
}
}
}
override open func resume() {
guard _EasyHandle.supportsWebSockets else {
workQueue.async {
var userInfo: [String: Any] = [NSLocalizedDescriptionKey: "WebSockets not supported by libcurl"]
if let url = self.originalRequest?.url {
userInfo[NSURLErrorFailingURLErrorKey] = url
userInfo[NSURLErrorFailingURLStringErrorKey] = url.absoluteString
}
let urlError = URLError(_nsError: NSError(domain: NSURLErrorDomain,
code: NSURLErrorUnsupportedURL,
userInfo: userInfo))
self.error = urlError
_ProtocolClient().urlProtocol(task: self, didFailWithError: urlError)
}
return
}
super.resume()
}
internal static var supportsWebSockets: Bool {
_EasyHandle.supportsWebSockets
}
}
public protocol URLSessionWebSocketDelegate : URLSessionTaskDelegate {
func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?)
func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?)
}
extension URLSessionWebSocketDelegate {
func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didOpenWithProtocol protocol: String?) {}
func urlSession(_ session: URLSession, webSocketTask: URLSessionWebSocketTask, didCloseWith closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) {}
}
/*
* An URLSessionStreamTask provides an interface to perform reads
* and writes to a TCP/IP stream created via URLSession. This task
* may be explicitly created from an URLSession, or created as a
* result of the appropriate disposition response to a
* -URLSession:dataTask:didReceiveResponse: delegate message.
*
* URLSessionStreamTask can be used to perform asynchronous reads
* and writes. Reads and writes are enquened and executed serially,
* with the completion handler being invoked on the sessions delegate
* queuee. If an error occurs, or the task is canceled, all
* outstanding read and write calls will have their completion
* handlers invoked with an appropriate error.
*
* It is also possible to create InputStream and OutputStream
* instances from an URLSessionTask by sending
* -captureStreams to the task. All outstanding read and writess are
* completed before the streams are created. Once the streams are
* delivered to the session delegate, the task is considered complete
* and will receive no more messages. These streams are
* disassociated from the underlying session.
*/
open class URLSessionStreamTask : URLSessionTask, @unchecked Sendable {
/* Read minBytes, or at most maxBytes bytes and invoke the completion
* handler on the sessions delegate queue with the data or an error.
* If an error occurs, any outstanding reads will also fail, and new
* read requests will error out immediately.
*/
@available(*, unavailable, message: "URLSessionStreamTask is not available in swift-corelibs-foundation")