forked from steipete/CodexBar
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProviderHTTPClient.swift
More file actions
270 lines (235 loc) · 9.99 KB
/
Copy pathProviderHTTPClient.swift
File metadata and controls
270 lines (235 loc) · 9.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif
public protocol ProviderHTTPTransport: Sendable {
func data(for request: URLRequest) async throws -> (Data, URLResponse)
}
#if !os(Linux)
extension URLSession: ProviderHTTPTransport {}
#endif
extension URLSession {
public func response(for request: URLRequest) async throws -> ProviderHTTPResponse {
let (data, response) = try await self.data(for: request)
guard let httpResponse = response as? HTTPURLResponse else {
throw URLError(.badServerResponse)
}
return ProviderHTTPResponse(data: data, response: httpResponse)
}
}
public struct ProviderHTTPResponse: Sendable {
public let data: Data
public let response: HTTPURLResponse
public init(data: Data, response: HTTPURLResponse) {
self.data = data
self.response = response
}
public var statusCode: Int {
self.response.statusCode
}
}
public struct ProviderHTTPRetryPolicy: Sendable {
public let maxRetries: Int
public let retryableStatusCodes: Set<Int>
public let retryableURLErrorCodes: Set<URLError.Code>
public let retryableMethods: Set<String>
public let baseDelaySeconds: TimeInterval
public let maxDelaySeconds: TimeInterval
public init(
maxRetries: Int,
retryableStatusCodes: Set<Int> = [408, 429, 500, 502, 503, 504],
retryableURLErrorCodes: Set<URLError.Code> = [
.timedOut,
.networkConnectionLost,
.cannotConnectToHost,
.cannotFindHost,
.dnsLookupFailed,
],
retryableMethods: Set<String> = ["GET", "HEAD", "OPTIONS"],
baseDelaySeconds: TimeInterval = 1,
maxDelaySeconds: TimeInterval = 10)
{
self.maxRetries = max(0, maxRetries)
self.retryableStatusCodes = retryableStatusCodes
self.retryableURLErrorCodes = retryableURLErrorCodes
self.retryableMethods = retryableMethods
self.baseDelaySeconds = max(0, baseDelaySeconds)
self.maxDelaySeconds = max(0, maxDelaySeconds)
}
public static let disabled = ProviderHTTPRetryPolicy(
maxRetries: 0,
retryableStatusCodes: [],
retryableURLErrorCodes: [],
baseDelaySeconds: 0,
maxDelaySeconds: 0)
public static let transientIdempotent = ProviderHTTPRetryPolicy(maxRetries: 1)
func shouldRetry(request: URLRequest, attempt: Int, statusCode: Int) -> Bool {
self.canRetry(request: request, attempt: attempt)
&& self.retryableStatusCodes.contains(statusCode)
}
func shouldRetry(request: URLRequest, attempt: Int, error: Error) -> Bool {
guard self.canRetry(request: request, attempt: attempt) else { return false }
guard let urlError = error as? URLError else { return false }
return self.retryableURLErrorCodes.contains(urlError.code)
}
func delaySeconds(attempt: Int, response: HTTPURLResponse?) -> TimeInterval {
if let retryAfter = response?.value(forHTTPHeaderField: "Retry-After"),
let seconds = TimeInterval(retryAfter.trimmingCharacters(in: .whitespacesAndNewlines)),
seconds >= 0
{
return min(seconds, self.maxDelaySeconds)
}
guard self.baseDelaySeconds > 0 else { return 0 }
let multiplier = pow(2, Double(max(0, attempt)))
return min(self.baseDelaySeconds * multiplier, self.maxDelaySeconds)
}
private func canRetry(request: URLRequest, attempt: Int) -> Bool {
guard attempt < self.maxRetries else { return false }
let method = request.httpMethod?.uppercased() ?? "GET"
return self.retryableMethods.contains(method)
}
}
public struct ProviderHTTPTransportHandler: ProviderHTTPTransport {
private let handler: @Sendable (URLRequest) async throws -> (Data, URLResponse)
public init(_ handler: @escaping @Sendable (URLRequest) async throws -> (Data, URLResponse)) {
self.handler = handler
}
public func data(for request: URLRequest) async throws -> (Data, URLResponse) {
try await self.handler(request)
}
}
extension ProviderHTTPTransport {
public func response(for request: URLRequest) async throws -> ProviderHTTPResponse {
try await self.response(for: request, retryPolicy: .disabled)
}
public func response(
for request: URLRequest,
retryPolicy: ProviderHTTPRetryPolicy) async throws -> ProviderHTTPResponse
{
var attempt = 0
while true {
do {
let (data, response) = try await self.data(for: request)
guard let httpResponse = response as? HTTPURLResponse else {
throw URLError(.badServerResponse)
}
let providerResponse = ProviderHTTPResponse(data: data, response: httpResponse)
guard retryPolicy.shouldRetry(
request: request,
attempt: attempt,
statusCode: providerResponse.statusCode)
else {
return providerResponse
}
try await Self.sleepBeforeRetry(policy: retryPolicy, attempt: attempt, response: httpResponse)
attempt += 1
} catch {
guard retryPolicy.shouldRetry(request: request, attempt: attempt, error: error) else {
throw error
}
try await Self.sleepBeforeRetry(policy: retryPolicy, attempt: attempt, response: nil)
attempt += 1
}
}
}
private static func sleepBeforeRetry(
policy: ProviderHTTPRetryPolicy,
attempt: Int,
response: HTTPURLResponse?) async throws
{
let delay = policy.delaySeconds(attempt: attempt, response: response)
guard delay > 0 else { return }
try await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000))
}
}
public final class ProviderHTTPClient: ProviderHTTPTransport, @unchecked Sendable {
public static let shared = ProviderHTTPClient(session: ProviderHTTPClient.sharedSession())
private let lock = NSLock()
private var session: URLSession
public init(session: URLSession? = nil) {
self.session = session ?? Self.redirectGuardedSession()
}
/// Rebuilds the underlying session so all subsequent requests use the given proxy.
/// Passing `nil` reverts to a direct (system-proxy) session.
public func applyProxyConfiguration(_ config: ProxyConfiguration?) {
let newSession = Self.redirectGuardedSession(configuration: Self.defaultConfiguration(proxy: config))
let previous = self.lock.withLock { () -> URLSession in
let previous = self.session
self.session = newSession
return previous
}
previous.finishTasksAndInvalidate()
}
static func defaultConfiguration(proxy: ProxyConfiguration? = nil) -> URLSessionConfiguration {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 30
configuration.timeoutIntervalForResource = 90
#if !os(Linux)
configuration.waitsForConnectivity = false
#endif
if let proxy {
configuration.connectionProxyDictionary = proxy.connectionProxyDictionary()
}
return configuration
}
private static func sharedSession() -> URLSession {
if self.isRunningTests {
// XCTest URLProtocol.registerClass stubs only intercept URLSession.shared on macOS.
return .shared
}
return self.redirectGuardedSession()
}
static func redirectGuardedSession(
configuration: URLSessionConfiguration = ProviderHTTPClient.defaultConfiguration()) -> URLSession
{
URLSession(
configuration: configuration,
delegate: ProviderHTTPRedirectGuardDelegate(),
delegateQueue: nil)
}
private static var isRunningTests: Bool {
let environment = ProcessInfo.processInfo.environment
if environment["XCTestConfigurationFilePath"] != nil || environment["XCTestBundlePath"] != nil {
return true
}
if ProcessInfo.processInfo.processName.lowercased().contains("xctest") {
return true
}
return CommandLine.arguments.contains { $0.lowercased().contains(".xctest") }
}
public func data(for request: URLRequest) async throws -> (Data, URLResponse) {
let session = self.lock.withLock { self.session }
return try await session.data(for: request)
}
}
final class ProviderHTTPRedirectGuardDelegate: NSObject, URLSessionTaskDelegate, @unchecked Sendable {
func urlSession(
_: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection _: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping @Sendable (URLRequest?) -> Void)
{
completionHandler(Self.guardedRedirectRequest(originalURL: task.originalRequest?.url, redirectRequest: request))
}
static func guardedRedirectRequest(originalURL: URL?, redirectRequest request: URLRequest) -> URLRequest? {
guard let originalURL, let redirectedURL = request.url else { return nil }
guard originalURL.scheme?.caseInsensitiveCompare("https") == .orderedSame else { return nil }
guard redirectedURL.scheme?.caseInsensitiveCompare("https") == .orderedSame else { return nil }
guard self.isSameOrigin(originalURL, redirectedURL) else { return nil }
return request
}
private static func isSameOrigin(_ lhs: URL, _ rhs: URL) -> Bool {
lhs.scheme?.lowercased() == rhs.scheme?.lowercased()
&& lhs.host?.lowercased() == rhs.host?.lowercased()
&& self.normalizedPort(lhs) == self.normalizedPort(rhs)
}
private static func normalizedPort(_ url: URL) -> Int? {
if let port = url.port { return port }
switch url.scheme?.lowercased() {
case "http": return 80
case "https": return 443
default: return nil
}
}
}