-
Notifications
You must be signed in to change notification settings - Fork 1.4k
refactor http client #3255
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+359
−177
Merged
refactor http client #3255
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -25,13 +25,24 @@ import CRT | |
#endif | ||
|
||
public protocol HTTPClientProtocol { | ||
func execute(_ request: HTTPClientRequest, callback: @escaping (Result<HTTPClientResponse, Error>) -> Void) | ||
typealias ProgressHandler = (_ bytesReceived: Int64, _ totalBytes: Int64?) -> Void | ||
typealias CompletionHandler = (Result<HTTPClientResponse, Error>) -> Void | ||
|
||
/// Execute an HTTP request asynchronously | ||
/// | ||
/// - Parameters: | ||
/// - request: The `HTTPClientRequest` to perform. | ||
/// - callback: A closure to be notified of the completion of the request. | ||
func execute(_ request: HTTPClientRequest, | ||
progress: ProgressHandler?, | ||
completion: @escaping CompletionHandler) | ||
} | ||
|
||
public enum HTTPClientError: Error, Equatable { | ||
case invalidResponse | ||
case badResponseStatusCode(Int) | ||
case circuitBreakerTriggered | ||
case responseTooLarge(Int64) | ||
} | ||
|
||
// MARK: - HTTPClient | ||
|
@@ -40,7 +51,7 @@ public struct HTTPClient: HTTPClientProtocol { | |
public typealias Configuration = HTTPClientConfiguration | ||
public typealias Request = HTTPClientRequest | ||
public typealias Response = HTTPClientResponse | ||
public typealias Handler = (Request, @escaping (Result<Response, Error>) -> Void) -> Void | ||
public typealias Handler = (Request, ProgressHandler?, @escaping (Result<Response, Error>) -> Void) -> Void | ||
|
||
public var configuration: HTTPClientConfiguration | ||
private let diagnosticsEngine: DiagnosticsEngine? | ||
|
@@ -57,7 +68,7 @@ public struct HTTPClient: HTTPClientProtocol { | |
self.underlying = handler ?? URLSessionHTTPClient().execute | ||
} | ||
|
||
public func execute(_ request: Request, callback: @escaping (Result<Response, Error>) -> Void) { | ||
public func execute(_ request: Request, progress: ProgressHandler? = nil, completion: @escaping CompletionHandler) { | ||
// merge configuration | ||
var request = request | ||
if request.options.callbackQueue == nil { | ||
|
@@ -72,6 +83,9 @@ public struct HTTPClient: HTTPClientProtocol { | |
if request.options.timeout == nil { | ||
request.options.timeout = self.configuration.requestTimeout | ||
} | ||
if request.options.authorizationProvider == nil { | ||
request.options.authorizationProvider = self.configuration.authorizationProvider | ||
} | ||
// add additional headers | ||
if let additionalHeaders = self.configuration.requestHeaders { | ||
additionalHeaders.forEach { | ||
|
@@ -81,43 +95,68 @@ public struct HTTPClient: HTTPClientProtocol { | |
if request.options.addUserAgent, !request.headers.contains("User-Agent") { | ||
request.headers.add(name: "User-Agent", value: "SwiftPackageManager/\(SwiftVersion.currentVersion.displayString)") | ||
} | ||
if let authorization = request.options.authorizationProvider?(request.url), !request.headers.contains("Authorization") { | ||
request.headers.add(name: "Authorization", value: authorization) | ||
} | ||
// execute | ||
self._execute(request: request, requestNumber: 0) { result in | ||
let callbackQueue = request.options.callbackQueue ?? self.configuration.callbackQueue | ||
callbackQueue.async { | ||
callback(result) | ||
let callbackQueue = request.options.callbackQueue ?? self.configuration.callbackQueue | ||
self._execute( | ||
request: request, requestNumber: 0, | ||
progress: progress.map { handler in | ||
{ received, expected in | ||
callbackQueue.async { | ||
handler(received, expected) | ||
} | ||
} | ||
}, | ||
completion: { result in | ||
callbackQueue.async { | ||
completion(result) | ||
} | ||
} | ||
} | ||
) | ||
} | ||
|
||
private func _execute(request: Request, requestNumber: Int, callback: @escaping (Result<Response, Error>) -> Void) { | ||
private func _execute(request: Request, requestNumber: Int, progress: ProgressHandler?, completion: @escaping CompletionHandler) { | ||
if self.shouldCircuitBreak(request: request) { | ||
diagnosticsEngine?.emit(warning: "Circuit breaker triggered for \(request.url)") | ||
return callback(.failure(HTTPClientError.circuitBreakerTriggered)) | ||
return completion(.failure(HTTPClientError.circuitBreakerTriggered)) | ||
} | ||
|
||
self.underlying(request) { result in | ||
switch result { | ||
case .failure(let error): | ||
callback(.failure(error)) | ||
case .success(let response): | ||
// record host errors for circuit breaker | ||
self.recordErrorIfNecessary(response: response, request: request) | ||
// handle retry strategy | ||
if let retryDelay = self.shouldRetry(response: response, request: request, requestNumber: requestNumber) { | ||
self.diagnosticsEngine?.emit(warning: "\(request.url) failed, retrying in \(retryDelay)") | ||
// TODO: dedicated retry queue? | ||
return self.configuration.callbackQueue.asyncAfter(deadline: .now() + retryDelay) { | ||
self._execute(request: request, requestNumber: requestNumber + 1, callback: callback) | ||
self.underlying( | ||
request, | ||
{ received, expected in | ||
if let max = request.options.maximumResponseSizeInBytes { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @yim-lee this is to better support "maximumResponseSizeInBytes" at the response buffering time |
||
guard received < max else { | ||
// FIXME: cancel the request? | ||
return completion(.failure(HTTPClientError.responseTooLarge(received))) | ||
} | ||
} | ||
// check for valid response codes | ||
if let validResponseCodes = request.options.validResponseCodes, !validResponseCodes.contains(response.statusCode) { | ||
return callback(.failure(HTTPClientError.badResponseStatusCode(response.statusCode))) | ||
progress?(received, expected) | ||
}, | ||
{ result in | ||
switch result { | ||
case .failure(let error): | ||
completion(.failure(error)) | ||
case .success(let response): | ||
// record host errors for circuit breaker | ||
self.recordErrorIfNecessary(response: response, request: request) | ||
// handle retry strategy | ||
if let retryDelay = self.shouldRetry(response: response, request: request, requestNumber: requestNumber) { | ||
self.diagnosticsEngine?.emit(warning: "\(request.url) failed, retrying in \(retryDelay)") | ||
// TODO: dedicated retry queue? | ||
return self.configuration.callbackQueue.asyncAfter(deadline: .now() + retryDelay) { | ||
self._execute(request: request, requestNumber: requestNumber + 1, progress: progress, completion: completion) | ||
} | ||
} | ||
// check for valid response codes | ||
if let validResponseCodes = request.options.validResponseCodes, !validResponseCodes.contains(response.statusCode) { | ||
return completion(.failure(HTTPClientError.badResponseStatusCode(response.statusCode))) | ||
} | ||
completion(.success(response)) | ||
} | ||
callback(.success(response)) | ||
} | ||
} | ||
) | ||
} | ||
|
||
private func shouldRetry(response: Response, request: Request, requestNumber: Int) -> DispatchTimeInterval? { | ||
|
@@ -179,39 +218,43 @@ public struct HTTPClient: HTTPClientProtocol { | |
} | ||
|
||
public extension HTTPClient { | ||
func head(_ url: URL, headers: HTTPClientHeaders = .init(), options: Request.Options = .init(), callback: @escaping (Result<Response, Error>) -> Void) { | ||
self.execute(Request(method: .head, url: url, headers: headers, body: nil, options: options), callback: callback) | ||
func head(_ url: URL, headers: HTTPClientHeaders = .init(), options: Request.Options = .init(), completion: @escaping (Result<Response, Error>) -> Void) { | ||
self.execute(Request(method: .head, url: url, headers: headers, body: nil, options: options), completion: completion) | ||
} | ||
|
||
func get(_ url: URL, headers: HTTPClientHeaders = .init(), options: Request.Options = .init(), callback: @escaping (Result<Response, Error>) -> Void) { | ||
self.execute(Request(method: .get, url: url, headers: headers, body: nil, options: options), callback: callback) | ||
func get(_ url: URL, headers: HTTPClientHeaders = .init(), options: Request.Options = .init(), completion: @escaping (Result<Response, Error>) -> Void) { | ||
self.execute(Request(method: .get, url: url, headers: headers, body: nil, options: options), completion: completion) | ||
} | ||
|
||
func put(_ url: URL, body: Data?, headers: HTTPClientHeaders = .init(), options: Request.Options = .init(), callback: @escaping (Result<Response, Error>) -> Void) { | ||
self.execute(Request(method: .put, url: url, headers: headers, body: body, options: options), callback: callback) | ||
func put(_ url: URL, body: Data?, headers: HTTPClientHeaders = .init(), options: Request.Options = .init(), completion: @escaping (Result<Response, Error>) -> Void) { | ||
self.execute(Request(method: .put, url: url, headers: headers, body: body, options: options), completion: completion) | ||
} | ||
|
||
func post(_ url: URL, body: Data?, headers: HTTPClientHeaders = .init(), options: Request.Options = .init(), callback: @escaping (Result<Response, Error>) -> Void) { | ||
self.execute(Request(method: .post, url: url, headers: headers, body: body, options: options), callback: callback) | ||
func post(_ url: URL, body: Data?, headers: HTTPClientHeaders = .init(), options: Request.Options = .init(), completion: @escaping (Result<Response, Error>) -> Void) { | ||
self.execute(Request(method: .post, url: url, headers: headers, body: body, options: options), completion: completion) | ||
} | ||
|
||
func delete(_ url: URL, headers: HTTPClientHeaders = .init(), options: Request.Options = .init(), callback: @escaping (Result<Response, Error>) -> Void) { | ||
self.execute(Request(method: .delete, url: url, headers: headers, body: nil, options: options), callback: callback) | ||
func delete(_ url: URL, headers: HTTPClientHeaders = .init(), options: Request.Options = .init(), completion: @escaping (Result<Response, Error>) -> Void) { | ||
self.execute(Request(method: .delete, url: url, headers: headers, body: nil, options: options), completion: completion) | ||
} | ||
} | ||
|
||
// MARK: - HTTPClientConfiguration | ||
|
||
public typealias HTTPClientAuthorizationProvider = (URL) -> String? | ||
|
||
public struct HTTPClientConfiguration { | ||
public var requestHeaders: HTTPClientHeaders? | ||
public var requestTimeout: DispatchTimeInterval? | ||
public var authorizationProvider: HTTPClientAuthorizationProvider? | ||
public var retryStrategy: HTTPClientRetryStrategy? | ||
public var circuitBreakerStrategy: HTTPClientCircuitBreakerStrategy? | ||
public var callbackQueue: DispatchQueue | ||
|
||
public init() { | ||
self.requestHeaders = .none | ||
self.requestTimeout = .none | ||
self.authorizationProvider = .none | ||
self.retryStrategy = .none | ||
self.circuitBreakerStrategy = .none | ||
self.callbackQueue = .global() | ||
|
@@ -259,6 +302,8 @@ public struct HTTPClientRequest { | |
public var addUserAgent: Bool | ||
public var validResponseCodes: [Int]? | ||
public var timeout: DispatchTimeInterval? | ||
public var maximumResponseSizeInBytes: Int64? | ||
public var authorizationProvider: HTTPClientAuthorizationProvider? | ||
public var retryStrategy: HTTPClientRetryStrategy? | ||
public var circuitBreakerStrategy: HTTPClientCircuitBreakerStrategy? | ||
public var callbackQueue: DispatchQueue? | ||
|
@@ -267,6 +312,8 @@ public struct HTTPClientRequest { | |
self.addUserAgent = true | ||
self.validResponseCodes = .none | ||
self.timeout = .none | ||
self.maximumResponseSizeInBytes = .none | ||
self.authorizationProvider = .none | ||
self.retryStrategy = .none | ||
self.circuitBreakerStrategy = .none | ||
self.callbackQueue = .none | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@neonichu ptal 👀