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
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2020-2022 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
//
//===----------------------------------------------------------------------===//
import _Concurrency
import Foundation
import struct TSCUtility.Versioning
#if canImport(FoundationNetworking)
// FIXME: this brings OpenSSL dependency on Linux and needs to be replaced with `swift-server/async-http-client` package
import FoundationNetworking
#endif
final class URLSessionHTTPClient: Sendable {
private let dataSession: URLSession
private let downloadSession: URLSession
private let dataTaskManager: DataTaskManager
private let downloadTaskManager: DownloadTaskManager
init(configuration: URLSessionConfiguration = .default) {
let dataDelegateQueue = OperationQueue()
dataDelegateQueue.name = "org.swift.swiftpm.urlsession-http-client-data-delegate"
dataDelegateQueue.maxConcurrentOperationCount = 1
self.dataTaskManager = DataTaskManager()
self.dataSession = URLSession(
configuration: configuration,
delegate: self.dataTaskManager,
delegateQueue: dataDelegateQueue
)
let downloadDelegateQueue = OperationQueue()
downloadDelegateQueue.name = "org.swift.swiftpm.urlsession-http-client-download-delegate"
downloadDelegateQueue.maxConcurrentOperationCount = 1
self.downloadTaskManager = DownloadTaskManager()
self.downloadSession = URLSession(
configuration: configuration,
delegate: self.downloadTaskManager,
delegateQueue: downloadDelegateQueue
)
}
deinit {
dataSession.finishTasksAndInvalidate()
downloadSession.finishTasksAndInvalidate()
}
@Sendable
func execute(
_ request: HTTPClient.Request,
progress: HTTPClient.ProgressHandler? = nil
) async throws -> LegacyHTTPClient.Response {
try await withCheckedThrowingContinuation { continuation in
let urlRequest = URLRequest(request)
let task: URLSessionTask
switch request.kind {
case .generic:
let dataTask = self.dataSession.dataTask(with: urlRequest)
self.dataTaskManager.register(
task: dataTask,
urlRequest: urlRequest,
authorizationProvider: request.options.authorizationProvider,
progress: progress,
completion: { continuation.resume(with: $0) }
)
task = dataTask
case .download(_, let destination):
let downloadTask = self.downloadSession.downloadTask(with: urlRequest)
self.downloadTaskManager.register(
task: downloadTask,
urlRequest: urlRequest,
// FIXME: always using synchronous filesystem, because `URLSessionDownloadDelegate`
// needs temporary files to moved out of temporary locations synchronously in delegate callbacks.
fileSystem: localFileSystem,
destination: destination,
progress: progress,
completion: { continuation.resume(with: $0) }
)
task = downloadTask
}
task.resume()
}
}
@Sendable
public func execute(
_ request: LegacyHTTPClient.Request,
progress: LegacyHTTPClient.ProgressHandler?,
completion: @escaping LegacyHTTPClient.CompletionHandler
) {
let urlRequest = URLRequest(request)
let task: URLSessionTask
switch request.kind {
case .generic:
let dataTask = self.dataSession.dataTask(with: urlRequest)
self.dataTaskManager.register(
task: dataTask,
urlRequest: urlRequest,
authorizationProvider: request.options.authorizationProvider,
progress: progress,
completion: completion
)
task = dataTask
case .download(let fileSystem, let destination):
let downloadTask = self.downloadSession.downloadTask(with: urlRequest)
self.downloadTaskManager.register(
task: downloadTask,
urlRequest: urlRequest,
fileSystem: fileSystem,
destination: destination,
progress: progress,
completion: completion
)
task = downloadTask
}
task.resume()
}
}
private final class DataTaskManager: NSObject, URLSessionDataDelegate {
private let tasks = ThreadSafeKeyValueStore<Int, DataTask>()
func register(
task: URLSessionDataTask,
urlRequest: URLRequest,
authorizationProvider: LegacyHTTPClientConfiguration.AuthorizationProvider?,
progress: LegacyHTTPClient.ProgressHandler?,
completion: @escaping LegacyHTTPClient.CompletionHandler
) {
self.tasks[task.taskIdentifier] = DataTask(
task: task,
progressHandler: progress,
dataTaskManager: self,
completionHandler: completion,
authorizationProvider: authorizationProvider
)
}
public func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void
) {
guard var task = self.tasks[dataTask.taskIdentifier] else {
return completionHandler(.cancel)
}
task.response = response as? HTTPURLResponse
task.expectedContentLength = response.expectedContentLength
self.tasks[dataTask.taskIdentifier] = task
do {
try task.progressHandler?(0, response.expectedContentLength)
completionHandler(.allow)
} catch {
completionHandler(.cancel)
}
}
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
guard var task = self.tasks[dataTask.taskIdentifier] else {
return
}
if task.buffer != nil {
task.buffer?.append(data)
} else {
task.buffer = data
}
self.tasks[dataTask.taskIdentifier] = task
do {
// safe since created in the line above
try task.progressHandler?(Int64(task.buffer?.count ?? 0), task.expectedContentLength)
} catch {
task.task.cancel()
}
}
public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
guard let task = self.tasks.removeValue(forKey: task.taskIdentifier) else {
return
}
if let error {
task.completionHandler(.failure(error))
} else if let response = task.response {
task.completionHandler(.success(response.response(body: task.buffer)))
} else {
task.completionHandler(.failure(HTTPClientError.invalidResponse))
}
}
public func urlSession(
_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void
) {
// Don't remove task from dictionary because we want to resume it later
guard let task = self.tasks[task.taskIdentifier] else {
return
}
var request = request
// Set `Authorization` header for the redirected request
if let redirectURL = request.url, let authorization = task.authorizationProvider?(redirectURL),
request.value(forHTTPHeaderField: "Authorization") == nil
{
request.addValue(authorization, forHTTPHeaderField: "Authorization")
}
completionHandler(request)
}
struct DataTask: Sendable {
let task: URLSessionDataTask
let completionHandler: LegacyHTTPClient.CompletionHandler
/// A strong reference to keep the `DataTaskManager` alive so it can handle the callbacks from the
/// `URLSession`.
///
/// See comment on `WeakDataTaskManager`.
let dataTaskManager: DataTaskManager
let progressHandler: LegacyHTTPClient.ProgressHandler?
let authorizationProvider: LegacyHTTPClientConfiguration.AuthorizationProvider?
var response: HTTPURLResponse?
var expectedContentLength: Int64?
var buffer: Data?
init(
task: URLSessionDataTask,
progressHandler: LegacyHTTPClient.ProgressHandler?,
dataTaskManager: DataTaskManager,
completionHandler: @escaping LegacyHTTPClient.CompletionHandler,
authorizationProvider: LegacyHTTPClientConfiguration.AuthorizationProvider?
) {
self.task = task
self.progressHandler = progressHandler
self.dataTaskManager = dataTaskManager
self.completionHandler = completionHandler
self.authorizationProvider = authorizationProvider
}
}
}
private final class DownloadTaskManager: NSObject, URLSessionDownloadDelegate {
private let tasks = ThreadSafeKeyValueStore<Int, DownloadTask>()
func register(
task: URLSessionDownloadTask,
urlRequest: URLRequest,
fileSystem: FileSystem,
destination: AbsolutePath,
progress: LegacyHTTPClient.ProgressHandler?,
completion: @escaping LegacyHTTPClient.CompletionHandler
) {
self.tasks[task.taskIdentifier] = DownloadTask(
task: task,
fileSystem: fileSystem,
destination: destination,
downloadTaskManager: self,
progressHandler: progress,
completionHandler: completion
)
}
func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64
) {
guard let task = self.tasks[downloadTask.taskIdentifier] else {
return
}
let totalBytesToDownload = totalBytesExpectedToWrite != NSURLSessionTransferSizeUnknown ?
totalBytesExpectedToWrite : nil
do {
try task.progressHandler?(totalBytesWritten, totalBytesToDownload)
} catch {
task.task.cancel()
}
}
func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL
) {
guard var task = self.tasks[downloadTask.taskIdentifier] else {
return
}
do {
let path = try AbsolutePath(validating: location.path)
// Always using synchronous `localFileSystem` here since `URLSession` requires temporary `location`
// to be moved from synchronously. Otherwise the file will be immediately cleaned up after returning
// from this delegate method.
try task.fileSystem.move(from: path, to: task.destination)
} catch {
task.moveFileError = error
self.tasks[downloadTask.taskIdentifier] = task
}
}
public func urlSession(
_ session: URLSession,
task downloadTask: URLSessionTask,
didCompleteWithError error: Error?
) {
guard let task = self.tasks.removeValue(forKey: downloadTask.taskIdentifier) else {
return
}
do {
if let error {
throw HTTPClientError.downloadError(error.interpolationDescription)
} else if let error = task.moveFileError {
throw error
} else if let response = downloadTask.response as? HTTPURLResponse {
task.completionHandler(.success(response.response(body: nil)))
} else {
throw HTTPClientError.invalidResponse
}
} catch {
task.completionHandler(.failure(error))
}
}
struct DownloadTask: Sendable {
let task: URLSessionDownloadTask
let fileSystem: FileSystem
let destination: AbsolutePath
let progressHandler: LegacyHTTPClient.ProgressHandler?
let completionHandler: LegacyHTTPClient.CompletionHandler
var moveFileError: Error?
init(
task: URLSessionDownloadTask,
fileSystem: FileSystem,
destination: AbsolutePath,
downloadTaskManager: DownloadTaskManager,
progressHandler: LegacyHTTPClient.ProgressHandler?,
completionHandler: @escaping LegacyHTTPClient.CompletionHandler
) {
self.task = task
self.fileSystem = fileSystem
self.destination = destination
self.progressHandler = progressHandler
self.completionHandler = completionHandler
}
}
}
extension URLRequest {
init(_ request: LegacyHTTPClient.Request) {
self.init(url: request.url)
self.httpMethod = request.method.string
request.headers.forEach { header in
self.addValue(header.value, forHTTPHeaderField: header.name)
}
self.httpBody = request.body
if let interval = request.options.timeout?.timeInterval() {
self.timeoutInterval = interval
}
}
init(_ request: HTTPClient.Request) {
self.init(url: request.url)
self.httpMethod = request.method.string
request.headers.forEach { header in
self.addValue(header.value, forHTTPHeaderField: header.name)
}
self.httpBody = request.body
if let interval = request.options.timeout?.timeInterval() {
self.timeoutInterval = interval
}
}
}
extension HTTPURLResponse {
fileprivate func response(body: Data?) -> HTTPClientResponse {
let headers = HTTPClientHeaders(self.allHeaderFields.map { header in
.init(name: "\(header.key)", value: "\(header.value)")
})
return HTTPClientResponse(
statusCode: self.statusCode,
statusText: Self.localizedString(forStatusCode: self.statusCode),
headers: headers,
body: body
)
}
}
|