|
| 1 | +import NIO |
| 2 | +import Logging |
| 3 | + |
| 4 | +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) |
| 5 | +extension HTTPClient { |
| 6 | +#if compiler(>=6.0) |
| 7 | + /// Start & automatically shut down a new ``HTTPClient``. |
| 8 | + /// |
| 9 | + /// This method allows to start & automatically dispose of a ``HTTPClient`` following the principle of Structured Concurrency. |
| 10 | + /// The ``HTTPClient`` is guaranteed to be shut down upon return, whether `body` throws or not. |
| 11 | + /// |
| 12 | + /// This may be particularly useful if you cannot use the shared singleton (``HTTPClient/shared``). |
| 13 | + public static func withHTTPClient<Return>( |
| 14 | + eventLoopGroup: any EventLoopGroup = HTTPClient.defaultEventLoopGroup, |
| 15 | + configuration: Configuration = Configuration(), |
| 16 | + backgroundActivityLogger: Logger? = nil, |
| 17 | + isolation: isolated (any Actor)? = #isolation, |
| 18 | + _ body: (HTTPClient) async throws -> Return |
| 19 | + ) async throws -> Return { |
| 20 | + let logger = (backgroundActivityLogger ?? HTTPClient.loggingDisabled) |
| 21 | + let httpClient = HTTPClient( |
| 22 | + eventLoopGroup: eventLoopGroup, |
| 23 | + configuration: configuration, |
| 24 | + backgroundActivityLogger: logger |
| 25 | + ) |
| 26 | + return try await asyncDo { |
| 27 | + try await body(httpClient) |
| 28 | + } finally: { _ in |
| 29 | + try await httpClient.shutdown() |
| 30 | + } |
| 31 | + } |
| 32 | +#else |
| 33 | + /// Start & automatically shut down a new ``HTTPClient``. |
| 34 | + /// |
| 35 | + /// This method allows to start & automatically dispose of a ``HTTPClient`` following the principle of Structured Concurrency. |
| 36 | + /// The ``HTTPClient`` is guaranteed to be shut down upon return, whether `body` throws or not. |
| 37 | + /// |
| 38 | + /// This may be particularly useful if you cannot use the shared singleton (``HTTPClient/shared``). |
| 39 | + public static func withHTTPClient<Return: Sendable>( |
| 40 | + eventLoopGroup: any EventLoopGroup = HTTPClient.defaultEventLoopGroup, |
| 41 | + configuration: Configuration = Configuration(), |
| 42 | + backgroundActivityLogger: Logger? = nil, |
| 43 | + _ body: (HTTPClient) async throws -> Return |
| 44 | + ) async throws -> Return { |
| 45 | + let logger = (backgroundActivityLogger ?? HTTPClient.loggingDisabled) |
| 46 | + let httpClient = HTTPClient( |
| 47 | + eventLoopGroup: eventLoopGroup, |
| 48 | + configuration: configuration, |
| 49 | + backgroundActivityLogger: logger |
| 50 | + ) |
| 51 | + return try await asyncDo { |
| 52 | + try await body(httpClient) |
| 53 | + } finally: { _ in |
| 54 | + try await httpClient.shutdown() |
| 55 | + } |
| 56 | + } |
| 57 | +#endif |
| 58 | +} |
0 commit comments