xtool.git
Publicgit clone https://git.maproj.org/xtool.gitxtool.git / Sources / XKit / HTTPClientProtocol / HTTPClientProtocol.swift
HTTPClientProtocol.swift167 lines · 5.3 KiBRaw
| 1 | // |
| 2 | // HTTPClientProtocol.swift |
| 3 | // |
| 4 | // |
| 5 | // Created by Kabir Oberai on 05/05/21. |
| 6 | // |
| 7 | |
| 8 | import Foundation |
| 9 | import OpenAPIRuntime |
| 10 | import Dependencies |
| 11 | import HTTPTypes |
| 12 | |
| 13 | public typealias HTTPRequest = HTTPTypes.HTTPRequest |
| 14 | public typealias HTTPResponse = HTTPTypes.HTTPResponse |
| 15 | public typealias HTTPBody = OpenAPIRuntime.HTTPBody |
| 16 | |
| 17 | public protocol HTTPClientProtocol: Sendable { |
| 18 | var asOpenAPITransport: ClientTransport { get } |
| 19 | |
| 20 | func makeWebSocket(url: URL) async throws -> WebSocketSession |
| 21 | |
| 22 | func withEphemeralClient<T>( |
| 23 | perform: (any HTTPClientProtocol) async throws -> T |
| 24 | ) async throws -> T |
| 25 | } |
| 26 | |
| 27 | extension HTTPClientProtocol { |
| 28 | public func send( |
| 29 | _ request: HTTPRequest, |
| 30 | body: HTTPBody? = nil |
| 31 | ) async throws -> (response: HTTPResponse, body: HTTPBody?) { |
| 32 | let transport = asOpenAPITransport |
| 33 | let request = request |
| 34 | var baseComponents = URLComponents() |
| 35 | baseComponents.scheme = request.scheme |
| 36 | baseComponents.host = request.authority |
| 37 | return try await transport.send( |
| 38 | request, |
| 39 | body: body, |
| 40 | baseURL: baseComponents.url!, |
| 41 | operationID: "dummy" |
| 42 | ) |
| 43 | } |
| 44 | |
| 45 | public func makeRequest( |
| 46 | _ request: HTTPRequest, |
| 47 | body: Data? = nil, |
| 48 | requireHTTPSuccess: Bool = true, |
| 49 | onProgress: @isolated(any) (Double?) -> Void = { _ in } |
| 50 | ) async throws -> (response: HTTPResponse, body: Data) { |
| 51 | await onProgress(0) |
| 52 | let (response, responseBody) = try await send(request, body: body.map { HTTPBody($0) }) |
| 53 | guard !requireHTTPSuccess || ![.clientError, .serverError].contains(response.status.kind) else { |
| 54 | let errorBody = (try? await responseBody.collect()) ?? Data() |
| 55 | throw HTTPResponseError( |
| 56 | method: request.method, |
| 57 | url: "\(request.scheme ?? "https")://\(request.authority ?? "")\(request.path ?? "")", |
| 58 | status: response.status, |
| 59 | // we don't use `decoding:as:` because we want to validate the UTF8 |
| 60 | body: String(data: errorBody, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) |
| 61 | ) |
| 62 | } |
| 63 | return (response, try await responseBody.collect(onProgress: onProgress)) |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | extension HTTPBody? { |
| 68 | fileprivate func collect( |
| 69 | onProgress: @isolated(any) (Double?) -> Void = { _ in } |
| 70 | ) async throws -> Data { |
| 71 | try await self?.collect(onProgress: onProgress) ?? Data() |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | extension HTTPBody { |
| 76 | fileprivate func collect( |
| 77 | onProgress: @isolated(any) (Double?) -> Void |
| 78 | ) async throws -> Data { |
| 79 | switch self.length { |
| 80 | case .unknown: |
| 81 | return try await self.reduce(into: Data()) { $0 += $1 } |
| 82 | case .known(let length): |
| 83 | var data = Data(capacity: Int(length)) |
| 84 | let total = Double(length) |
| 85 | for try await chunk in self { |
| 86 | data += chunk |
| 87 | await onProgress(Swift.min(Double(data.count) / total, 1)) |
| 88 | } |
| 89 | return data |
| 90 | } |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | public struct HTTPResponseError: Error, LocalizedError, Sendable, CustomStringConvertible { |
| 95 | public let method: HTTPRequest.Method |
| 96 | public let url: String |
| 97 | public let status: HTTPResponse.Status |
| 98 | public let body: String? |
| 99 | |
| 100 | public var description: String { |
| 101 | var description = "\(method.rawValue) \(url) failed: HTTP \(status.code)" |
| 102 | if !status.reasonPhrase.isEmpty { |
| 103 | description += " \(status.reasonPhrase)" |
| 104 | } |
| 105 | if let body, !body.isEmpty { |
| 106 | description += ". Details:\n\(body)" |
| 107 | } |
| 108 | return description |
| 109 | } |
| 110 | |
| 111 | public var errorDescription: String? { description } |
| 112 | } |
| 113 | |
| 114 | private struct UnimplementedHTTPClient: HTTPClientProtocol, ClientTransport { |
| 115 | public var asOpenAPITransport: ClientTransport { self } |
| 116 | |
| 117 | func send( |
| 118 | _ request: HTTPRequest, |
| 119 | body: HTTPBody?, |
| 120 | baseURL: URL, |
| 121 | operationID: String |
| 122 | ) async throws -> (HTTPResponse, HTTPBody?) { |
| 123 | let closure: (HTTPRequest, HTTPBody?, URL, String) async throws -> (HTTPResponse, HTTPBody?) = unimplemented() |
| 124 | return try await closure(request, body, baseURL, operationID) |
| 125 | } |
| 126 | |
| 127 | func makeRequest( |
| 128 | _ request: HTTPRequest, |
| 129 | onProgress: sending @isolated(any) (Double?) -> Void |
| 130 | ) async throws -> HTTPResponse { |
| 131 | let closure: () throws -> HTTPResponse = unimplemented() |
| 132 | return try closure() |
| 133 | } |
| 134 | |
| 135 | func withEphemeralClient<T>( |
| 136 | perform: (any HTTPClientProtocol) async throws -> T |
| 137 | ) async throws -> T { |
| 138 | try await perform(self) |
| 139 | } |
| 140 | |
| 141 | public func makeWebSocket(url: URL) async throws -> any WebSocketSession { |
| 142 | let closure: (URL) async throws -> any WebSocketSession = unimplemented() |
| 143 | return try await closure(url) |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | public enum HTTPClientDependencyKey: TestDependencyKey { |
| 148 | public static let testValue: HTTPClientProtocol = UnimplementedHTTPClient() |
| 149 | } |
| 150 | |
| 151 | extension DependencyValues { |
| 152 | public var httpClient: HTTPClientProtocol { |
| 153 | get { self[HTTPClientDependencyKey.self] } |
| 154 | set { self[HTTPClientDependencyKey.self] = newValue } |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | public protocol WebSocketSession: Sendable { |
| 159 | func receive() async throws -> WebSocketMessage |
| 160 | func send(_ message: WebSocketMessage) async throws |
| 161 | func close() |
| 162 | } |
| 163 | |
| 164 | public enum WebSocketMessage: Sendable { |
| 165 | case text(String) |
| 166 | case data(Data) |
| 167 | } |