Repository Public License
1import Foundation23/// All network I/O of this module goes through a transport, so tests never touch the internet and the app can4/// supply its own session (proxy settings, a private-mode session).5public protocol HTTPTransport: Sendable {6 /// Sends a request and returns the whole body.7 func data(for request: URLRequest) async throws -> (Data, HTTPURLResponse)89 /// Sends a request and returns the response head as soon as it arrives, then the body in chunks of any size10 /// (chunk boundaries carry no meaning). Terminating the stream, or cancelling the task that iterates it, must11 /// cancel the underlying request.12 func bytes(for request: URLRequest) async throws -> (HTTPURLResponse, AsyncThrowingStream<Data, Error>)13}1415/// Refuses redirects that change host or downgrade to plain HTTP: `URLSession` would otherwise forward custom16/// headers such as `x-api-key` to wherever a response points.17final class SameOriginRedirectPolicy: NSObject, URLSessionTaskDelegate, Sendable {18 func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,19 newRequest request: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void) {20 completionHandler(Self.allows(from: response.url ?? task.originalRequest?.url, to: request.url) ? request : nil)21 }2223 static func allows(from: URL?, to: URL?) -> Bool {24 guard let from, let to, let fromHost = from.host?.lowercased(), let toHost = to.host?.lowercased(), fromHost == toHost else { return false }25 let fromScheme = from.scheme?.lowercased(), toScheme = to.scheme?.lowercased()26 if fromScheme == "https", toScheme != "https" { return false }27 // Same host: the port may change only together with the scheme (http:80 → https:443).28 return (from.port ?? -1) == (to.port ?? -1) || fromScheme != toScheme29 }30}3132/// The production transport: an ephemeral `URLSession` with no cookies and no cache.33public struct URLSessionTransport: HTTPTransport {34 private let session: URLSession3536 /// Longest a whole response may take. A long agentic answer can stream for many minutes.37 public static let totalTimeout: TimeInterval = 3_6003839 public static func defaultConfiguration() -> URLSessionConfiguration {40 let configuration = URLSessionConfiguration.ephemeral41 configuration.timeoutIntervalForResource = totalTimeout42 configuration.httpCookieStorage = nil43 configuration.urlCache = nil44 configuration.httpShouldSetCookies = false45 configuration.waitsForConnectivity = false46 configuration.httpAdditionalHeaders = ["User-Agent": ProviderKit.applicationName.replacingOccurrences(of: " ", with: "")]47 return configuration48 }4950 public init(configuration: URLSessionConfiguration? = nil) {51 session = URLSession(configuration: configuration ?? Self.defaultConfiguration(), delegate: SameOriginRedirectPolicy(), delegateQueue: nil)52 }5354 public func data(for request: URLRequest) async throws -> (Data, HTTPURLResponse) {55 let (data, response) = try await session.data(for: request)56 guard let http = response as? HTTPURLResponse else { throw ProviderError.network("The server did not answer over HTTP.") }57 return (data, http)58 }5960 public func bytes(for request: URLRequest) async throws -> (HTTPURLResponse, AsyncThrowingStream<Data, Error>) {61 let (bytes, response) = try await session.bytes(for: request)62 guard let http = response as? HTTPURLResponse else { throw ProviderError.network("The server did not answer over HTTP.") }63 let (stream, continuation) = AsyncThrowingStream<Data, Error>.makeStream(bufferingPolicy: .unbounded)64 // Cancelling this task cancels the iteration of `bytes`, which cancels the URLSession data task.65 let pump = Task {66 do {67 // Flush at each line end so a server-sent event is delivered as soon as it is complete.68 var buffer = Data()69 buffer.reserveCapacity(4_096)70 for try await byte in bytes {71 buffer.append(byte)72 if byte == 0x0A || buffer.count >= 16_384 {73 continuation.yield(buffer)74 buffer.removeAll(keepingCapacity: true)75 }76 }77 if !buffer.isEmpty { continuation.yield(buffer) }78 continuation.finish()79 } catch {80 continuation.finish(throwing: error)81 }82 }83 continuation.onTermination = { _ in pump.cancel() }84 return (http, stream)85 }86}8788extension HTTPURLResponse {89 /// `Retry-After` in seconds (delta or HTTP date), or `retry-after-ms`. Clamped to one day.90 var retryAfter: TimeInterval? {91 if let raw = value(forHTTPHeaderField: "retry-after")?.trimmingCharacters(in: .whitespaces) {92 if let seconds = Double(raw) { return RetryPolicy.saneDelay(seconds) }93 let formatter = DateFormatter()94 formatter.locale = Locale(identifier: "en_US_POSIX")95 formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz"96 if let date = formatter.date(from: raw) { return RetryPolicy.saneDelay(date.timeIntervalSinceNow) }97 }98 if let milliseconds = value(forHTTPHeaderField: "retry-after-ms").flatMap(Double.init) { return RetryPolicy.saneDelay(milliseconds / 1_000) }99 return nil100 }101}102