Adopt AHC's .shared singleton as the default Client (#39)

### Motivation

As a convenience when you don't need to create a custom AHC Client
instance, we provide a singleton client as the default. AHC added their
own `Client.shared` singleton, so let's adopt that and remove the
transport's internal singleton, which was used for the same purpose.

### Modifications

- Replaced the tranport's internal singleton with the AHC-provided one.
- Use Int64 directly and skip conversions now that AHC also uses Int64
for the body byte size.

### Result

- No internal singleton is created now, possibly avoiding having two AHC
singletons in a given process.
- Fixed a warning around Int/Int64 conversion.

### Test Plan

Unit tests still pass.
This commit is contained in:
Honza Dvorsky
2024-10-03 17:51:54 +02:00
committed by GitHub
parent abfe558a66
commit 7b96b1d08e
3 changed files with 15 additions and 15 deletions
@@ -62,26 +62,27 @@ public struct AsyncHTTPClientTransport: ClientTransport {
/// The HTTP client used for performing HTTP calls.
public var client: HTTPClient
/// The default shared HTTP client.
///
/// This is a workaround for the lack of a shared client
/// in AsyncHTTPClient. Do not use this value directly, outside of
/// the `Configuration.init(client:timeout:)` initializer, as it will
/// likely be removed in the future.
private static let sharedClient: HTTPClient = .init()
/// The default request timeout.
public var timeout: TimeAmount
/// Creates a new configuration with the specified client and timeout.
/// - Parameters:
/// - client: The underlying client used to perform HTTP operations.
/// Provide nil to use the shared internal client.
/// - timeout: The request timeout, defaults to 1 minute.
public init(client: HTTPClient? = nil, timeout: TimeAmount = .minutes(1)) {
self.client = client ?? Self.sharedClient
public init(client: HTTPClient = .shared, timeout: TimeAmount = .minutes(1)) {
self.client = client
self.timeout = timeout
}
/// Creates a new configuration with the specified client and timeout.
/// - Parameters:
/// - client: The underlying client used to perform HTTP operations.
/// Provide nil to use the shared client.
/// - timeout: The request timeout, defaults to 1 minute.
@available(*, deprecated, message: "Use the initializer with a non-optional client parameter.")
@_disfavoredOverload public init(client: HTTPClient? = nil, timeout: TimeAmount = .minutes(1)) {
self.init(client: client ?? .shared, timeout: timeout)
}
}
/// A request to be sent by the transport.
@@ -174,8 +175,7 @@ public struct AsyncHTTPClientTransport: ClientTransport {
let length: HTTPClientRequest.Body.Length
switch body.length {
case .unknown: length = .unknown
case .known(let count):
if let intValue = Int(exactly: count) { length = .known(intValue) } else { length = .unknown }
case .known(let count): length = .known(count)
}
clientRequest.body = .stream(body.map { .init(bytes: $0) }, length: length)
}