Modern Apps git

xtool.git

Public
git clone https://git.maproj.org/xtool.git
main ▾

xtool.git / Sources / XKit / HTTPClientProtocol / HTTPClientProtocol.swift

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