Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Packages/LocalChatNetworking/Sources/HTTPClient.swift3// Description: Thin async HTTP client over URLSession: JSON requests, byte streaming, timeouts and bearer authentication.4import Foundation56public enum HTTPClientError: LocalizedError, Sendable {7 case notHTTP8 case status(Int, message: String?)9 case decoding(String)10 public var errorDescription: String? {11 switch self {12 case .notHTTP: "The server did not answer with HTTP."13 case .status(let code, let message): message.map { "HTTP \(code): \($0)" } ?? "HTTP \(code)"14 case .decoding(let m): "Unexpected response: \(m)"15 }16 }17 public var statusCode: Int? { if case .status(let c, _) = self { c } else { nil } }18}1920public struct HTTPClient: Sendable {21 public let session: URLSession22 public var requestTimeout: TimeInterval23 public var userAgent: String2425 /// - Parameter streamTimeout: maximum silence between two chunks of a streamed answer (prompt evaluation on a remote node can be long).26 public init(requestTimeout: TimeInterval = 30, streamTimeout: TimeInterval = 600, userAgent: String = "LocalChat/1.0", session: URLSession? = nil) {27 self.requestTimeout = requestTimeout; self.userAgent = userAgent28 if let session { self.session = session } else {29 let config = URLSessionConfiguration.ephemeral30 config.timeoutIntervalForRequest = streamTimeout31 config.requestCachePolicy = .reloadIgnoringLocalCacheData32 config.httpCookieStorage = nil; config.urlCredentialStorage = nil; config.httpShouldSetCookies = false33 config.waitsForConnectivity = false34 self.session = URLSession(configuration: config)35 }36 }3738 public func request(_ method: String, _ url: URL, headers: [String: String] = [:], body: Data? = nil, bearer: String? = nil, timeout: TimeInterval? = nil) -> URLRequest {39 var r = URLRequest(url: url); r.httpMethod = method; r.httpBody = body40 r.timeoutInterval = timeout ?? requestTimeout41 r.setValue(userAgent, forHTTPHeaderField: "User-Agent")42 if body != nil { r.setValue("application/json", forHTTPHeaderField: "Content-Type") }43 if let bearer, !bearer.isEmpty { r.setValue("Bearer \(bearer)", forHTTPHeaderField: "Authorization") }44 for (k, v) in headers { r.setValue(v, forHTTPHeaderField: k) }45 return r46 }4748 /// Sends a request and returns the body whatever the status code.49 public func send(_ method: String, _ url: URL, headers: [String: String] = [:], body: Data? = nil, bearer: String? = nil, timeout: TimeInterval? = nil) async throws -> (data: Data, response: HTTPURLResponse) {50 let (data, response) = try await session.data(for: request(method, url, headers: headers, body: body, bearer: bearer, timeout: timeout))51 guard let http = response as? HTTPURLResponse else { throw HTTPClientError.notHTTP }52 return (data, http)53 }5455 /// Sends a request, requires a 2xx status and decodes the JSON body.56 public func json<T: Decodable>(_ type: T.Type, _ method: String, _ url: URL, headers: [String: String] = [:], body: Data? = nil, bearer: String? = nil, timeout: TimeInterval? = nil) async throws -> T {57 let (data, http) = try await send(method, url, headers: headers, body: body, bearer: bearer, timeout: timeout)58 guard (200..<300).contains(http.statusCode) else { throw HTTPClientError.status(http.statusCode, message: Self.errorMessage(data)) }59 do { return try JSONDecoder().decode(T.self, from: data) }60 catch { throw HTTPClientError.decoding(String(describing: error).prefix(300).description) }61 }6263 public func json<T: Decodable, B: Encodable>(_ type: T.Type, _ method: String, _ url: URL, encoding payload: B, bearer: String? = nil, timeout: TimeInterval? = nil) async throws -> T {64 try await json(type, method, url, body: try JSONEncoder().encode(payload), bearer: bearer, timeout: timeout)65 }6667 /// Opens a streamed response. Cancelling the calling task cancels the transfer.68 public func stream(_ method: String, _ url: URL, headers: [String: String] = [:], body: Data? = nil, bearer: String? = nil) async throws -> (bytes: URLSession.AsyncBytes, response: HTTPURLResponse) {69 var r = request(method, url, headers: headers, body: body, bearer: bearer, timeout: session.configuration.timeoutIntervalForRequest)70 r.setValue("text/event-stream", forHTTPHeaderField: "Accept")71 let (bytes, response) = try await session.bytes(for: r)72 guard let http = response as? HTTPURLResponse else { throw HTTPClientError.notHTTP }73 return (bytes, http)74 }7576 /// Extracts a human-readable message from an OpenAI-style error body (or the raw text when it is short).77 public static func errorMessage(_ data: Data) -> String? {78 if let envelope = try? JSONDecoder().decode(OpenAI.ErrorEnvelope.self, from: data) { return envelope.error.message }79 let text = String(decoding: data.prefix(300), as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)80 return text.isEmpty || text.hasPrefix("<") ? nil : text81 }82}83