SPB Git

Repository Public

HTTPTransport.swift 5.8 KB 140 lines swift

1import Foundation23/// A fully built HTTP request. Its textual descriptions mask credential headers.4public struct HTTPRequest: Sendable, Equatable, CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {5    public var url: URL6    public var method: String7    /// Header fields (names as sent).8    public var headers: [String: String]9    public var body: Data1011    public init(url: URL, method: String = "POST", headers: [String: String] = [:], body: Data = Data()) {12        self.url = url13        self.method = method14        self.headers = headers15        self.body = body16    }1718    private static let credentialHeaders: Set<String> = ["x-api-key", "authorization", "proxy-authorization", "api-key", "cookie"]1920    public var description: String {21        let shown = headers.keys.sorted().map { name in22            "\(name): \(Self.credentialHeaders.contains(name.lowercased()) ? "<redacted>" : headers[name] ?? "")"23        }24        return "HTTPRequest(\(method) \(url.absoluteString), headers: [\(shown.joined(separator: ", "))], body: \(body.count) bytes)"25    }26    public var debugDescription: String { description }27    public var customMirror: Mirror { Mirror(self, children: ["description": description], displayStyle: .struct) }28}2930/// A complete HTTP response.31public struct HTTPResponse: Sendable, Equatable {32    public var statusCode: Int33    public var headers: [String: String]34    public var body: Data3536    public init(statusCode: Int, headers: [String: String] = [:], body: Data = Data()) {37        self.statusCode = statusCode38        self.headers = headers39        self.body = body40    }4142    /// Case-insensitive header lookup.43    public func header(_ name: String) -> String? {44        let wanted = name.lowercased()45        return headers.first { $0.key.lowercased() == wanted }?.value46    }47}4849/// A response whose body arrives line by line (server-sent events).50public struct HTTPStreamResponse: Sendable {51    public var statusCode: Int52    public var headers: [String: String]53    /// Body lines, without terminators. Empty lines may be omitted.54    public var lines: AsyncThrowingStream<String, any Error>5556    public init(statusCode: Int, headers: [String: String] = [:], lines: AsyncThrowingStream<String, any Error>) {57        self.statusCode = statusCode58        self.headers = headers59        self.lines = lines60    }61}6263/// The only door to the network. Inject a mock in tests.64public protocol HTTPTransport: Sendable {65    /// Performs the request and returns the whole response.66    func send(_ request: HTTPRequest) async throws -> HTTPResponse67    /// Performs the request and streams the body by lines.68    /// The default implementation buffers ``send(_:)`` and splits its body.69    func streamLines(_ request: HTTPRequest) async throws -> HTTPStreamResponse70}7172extension HTTPTransport {73    public func streamLines(_ request: HTTPRequest) async throws -> HTTPStreamResponse {74        let response = try await send(request)75        let text = String(decoding: response.body, as: UTF8.self)76        let lines = text.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline).map(String.init)77        let stream = AsyncThrowingStream<String, any Error> { continuation in78            for line in lines { continuation.yield(line) }79            continuation.finish()80        }81        return HTTPStreamResponse(statusCode: response.statusCode, headers: response.headers, lines: stream)82    }83}8485/// Default transport backed by `URLSession` (ephemeral: no cookies, no cache, no credential storage).86public struct URLSessionTransport: HTTPTransport {87    private let session: URLSession8889    /// - Parameter timeout: request timeout in seconds.90    public init(timeout: TimeInterval = 600) {91        let configuration = URLSessionConfiguration.ephemeral92        configuration.timeoutIntervalForRequest = timeout93        configuration.httpCookieStorage = nil94        configuration.urlCredentialStorage = nil95        configuration.urlCache = nil96        self.session = URLSession(configuration: configuration)97    }9899    /// Uses a caller-provided session.100    public init(session: URLSession) { self.session = session }101102    private func urlRequest(_ request: HTTPRequest) -> URLRequest {103        var urlRequest = URLRequest(url: request.url)104        urlRequest.httpMethod = request.method105        urlRequest.httpBody = request.body106        for (name, value) in request.headers { urlRequest.setValue(value, forHTTPHeaderField: name) }107        return urlRequest108    }109110    private static func headers(of response: URLResponse) -> (Int, [String: String]) {111        guard let http = response as? HTTPURLResponse else { return (0, [:]) }112        var headers: [String: String] = [:]113        for (key, value) in http.allHeaderFields { headers[String(describing: key)] = String(describing: value) }114        return (http.statusCode, headers)115    }116117    public func send(_ request: HTTPRequest) async throws -> HTTPResponse {118        let (data, response) = try await session.data(for: urlRequest(request))119        let (status, headers) = Self.headers(of: response)120        return HTTPResponse(statusCode: status, headers: headers, body: data)121    }122123    public func streamLines(_ request: HTTPRequest) async throws -> HTTPStreamResponse {124        let (bytes, response) = try await session.bytes(for: urlRequest(request))125        let (status, headers) = Self.headers(of: response)126        let stream = AsyncThrowingStream<String, any Error> { continuation in127            let task = Task {128                do {129                    for try await line in bytes.lines { continuation.yield(line) }130                    continuation.finish()131                } catch {132                    continuation.finish(throwing: error)133                }134            }135            continuation.onTermination = { _ in task.cancel() }136        }137        return HTTPStreamResponse(statusCode: status, headers: headers, lines: stream)138    }139}140
Files main
Menu

Theme