SPB Git

Repository Public License

ProviderHTTP.swift 15.6 KB 302 lines swift

1import Diagnostics2import Foundation34// MARK: - Policy56/// Bounded retries with exponential backoff and jitter. Applied only to failures that happen before a response is7/// accepted: once a 2xx head has arrived nothing is ever resent, so a retry can never duplicate streamed output or8/// a billed request.9public struct RetryPolicy: Sendable, Hashable, Codable {10    /// Total tries, the first one included. `1` disables retries.11    public var maxAttempts: Int12    public var baseDelay: TimeInterval13    /// Cap on a computed backoff delay.14    public var maxDelay: TimeInterval15    /// A server `Retry-After` longer than this is not waited for: the error is reported with the delay instead.16    public var maxRetryAfter: TimeInterval1718    public init(maxAttempts: Int = 3, baseDelay: TimeInterval = 0.5, maxDelay: TimeInterval = 8, maxRetryAfter: TimeInterval = 30) {19        self.maxAttempts = max(1, maxAttempts); self.baseDelay = max(0, baseDelay)20        self.maxDelay = max(0, maxDelay); self.maxRetryAfter = max(0, maxRetryAfter)21    }2223    public static let `default` = RetryPolicy()24    public static let none = RetryPolicy(maxAttempts: 1)2526    /// The wait before the next try, or `nil` when there must be none.27    /// - Parameters:28    ///   - failedAttempts: tries that have failed so far (1 after the first failure).29    ///   - retryAfter: the server's `Retry-After`, when it sent one.30    ///   - random: a uniform value in `0..<1` (the jitter source).31    public func delay(failedAttempts: Int, retryAfter: TimeInterval?, random: Double) -> TimeInterval? {32        guard failedAttempts >= 1, failedAttempts < maxAttempts else { return nil }33        if let retryAfter, retryAfter > maxRetryAfter { return nil }34        let exponential = min(maxDelay, baseDelay * pow(2, Double(failedAttempts - 1)))35        // Equal jitter: half the delay is fixed, half is random, so clients do not retry in step.36        let jittered = exponential * (0.5 + 0.5 * min(max(random, 0), 1))37        return max(retryAfter ?? 0, jittered)38    }3940    static func saneDelay(_ seconds: Double) -> TimeInterval? {41        guard !seconds.isNaN else { return nil }42        return min(86_400, max(0, seconds))43    }44}4546public struct ProviderTimeouts: Sendable, Hashable, Codable {47    /// Idle timeout of short JSON requests (model list, connection test).48    public var request: TimeInterval49    /// Longest silence tolerated on a streaming response, time to first byte included. Reasoning models can stay50    /// quiet for a long time before the first token.51    public var streamIdle: TimeInterval5253    public init(request: TimeInterval = 30, streamIdle: TimeInterval = 300) {54        self.request = request; self.streamIdle = streamIdle55    }56}5758/// Everything a provider needs from the outside world. Tests replace the transport, the sleeper and the jitter.59public struct ProviderEnvironment: Sendable {60    public var transport: any HTTPTransport61    public var retry: RetryPolicy62    public var timeouts: ProviderTimeouts63    public var sleep: @Sendable (TimeInterval) async throws -> Void64    /// Uniform in `0..<1`.65    public var random: @Sendable () -> Double66    /// Receives every line this module logs (already free of secrets). For tests and an in-app diagnostics view.67    public var logObserver: (@Sendable (String) -> Void)?6869    public init(transport: any HTTPTransport = URLSessionTransport(), retry: RetryPolicy = .default, timeouts: ProviderTimeouts = ProviderTimeouts(),70                sleep: @escaping @Sendable (TimeInterval) async throws -> Void = { try await Task.sleep(nanoseconds: UInt64(max(0, $0) * 1_000_000_000)) },71                random: @escaping @Sendable () -> Double = { Double.random(in: 0..<1) },72                logObserver: (@Sendable (String) -> Void)? = nil) {73        self.transport = transport; self.retry = retry; self.timeouts = timeouts74        self.sleep = sleep; self.random = random; self.logObserver = logObserver75    }7677    /// Logs a line that must not contain user content. Secrets of the request in flight are scrubbed regardless.78    func log(_ message: String, secrets: [String] = []) {79        let line = SecretScrubber.scrub(message, secrets: secrets)80        Log.agent.info("\(line, privacy: .public)")81        logObserver?(line)82    }83}8485/// Reads the API key at request time, so a key the user just changed is used without rebuilding the provider.86public typealias KeySource = @Sendable () async throws -> String?8788func resolveKey(_ source: KeySource, family: ProviderFamily, required: Bool) async throws -> String? {89    let raw: String?90    do { raw = try await source() } catch let error as ProviderError { throw error } catch {91        // The store failed (locked device, Keychain error): the key may well exist, so this is not "add a key".92        throw ProviderError.configuration("The saved \(family.displayName) key could not be read. Unlock the device and try again.")93    }94    let key = raw?.trimmingCharacters(in: .whitespacesAndNewlines)95    if let key, !key.isEmpty { return key }96    if required { throw ProviderError.missingKey(provider: family.displayName) }97    return nil98}99100// MARK: - Error bodies101102/// The fields providers put in an error response, whatever the envelope.103struct ProviderErrorBody: Sendable, Equatable {104    var code: String?105    var message: String?106    var param: String?107108    static func parse(_ data: Data) -> ProviderErrorBody {109        // Not JSON (an HTML gateway page, a plain-text proxy error): the raw body is never surfaced.110        guard let json = JSONValue.parse(data) else { return ProviderErrorBody() }111        return parse(json)112    }113114    static func parse(_ json: JSONValue) -> ProviderErrorBody {115        var out = ProviderErrorBody()116        let error = json["error"] ?? json117        if let text = error.stringValue {   // {"error": "<message>"} (Ollama, some gateways)118            out.message = text119            out.code = json["code"]?.stringValue120            return out121        }122        var codes: [String] = []123        for key in ["code", "type", "status"] {124            if let text = error[key]?.stringValue, !text.isEmpty { codes.append(text) } else if let number = error[key]?.intValue { codes.append(String(number)) }125        }126        if let metadata = error["metadata"] {   // OpenRouter passes the upstream provider's code through here127            for key in ["error_type", "provider_code"] { if let text = metadata[key]?.stringValue, !text.isEmpty { codes.append(text) } }128            if let reasons = metadata["reasons"]?.arrayValue, !reasons.isEmpty { codes.append("moderation") }129        }130        out.code = codes.isEmpty ? nil : codes.joined(separator: " ")131        out.message = error["message"]?.stringValue ?? json["message"]?.stringValue ?? json["detail"]?.stringValue132        out.param = error["param"]?.stringValue133        return out134    }135}136137/// Recognises "this parameter is not supported" answers, so the request can be sent again without it.138enum UnsupportedParameter {139    static func detect(status: Int, body: ProviderErrorBody, candidates: [String]) -> String? {140        guard status == 400 || status == 422 else { return nil }141        let message = (body.message ?? "").lowercased()142        let code = (body.code ?? "").lowercased()143        let complains = code.contains("unsupported_parameter") || code.contains("unsupported_value") || code.contains("unknown_parameter")144            || ["unsupported parameter", "unsupported value", "not supported", "does not support", "unknown parameter", "unrecognized",145                "extra inputs are not permitted", "extra fields not permitted", "unexpected keyword", "is not allowed", "not permitted",146                "is unsupported", "only supported", "may not be specified", "deprecated"].contains(where: message.contains)147        guard complains else { return nil }148        if let param = body.param?.lowercased() {149            for name in candidates where param == name.lowercased() || param.hasPrefix(name.lowercased() + ".") { return name }150        }151        // Longest names first so "max_completion_tokens" is not mistaken for "max_tokens".152        for name in candidates.sorted(by: { $0.count > $1.count }) {153            let pattern = #"(^|[^a-z0-9_])"# + NSRegularExpression.escapedPattern(for: name.lowercased()) + #"([^a-z0-9_]|$)"#154            if message.range(of: pattern, options: .regularExpression) != nil { return name }155        }156        return nil157    }158}159160// MARK: - HTTP161162struct ProviderHTTP: Sendable {163    let family: ProviderFamily164    let environment: ProviderEnvironment165166    /// A non-2xx answer, kept structured until the caller has had a chance to adjust the request.167    struct Failure: Error {168        var status: Int169        var body: ProviderErrorBody170        var retryAfter: TimeInterval?171172        func mapped(model: String?, secrets: [String]) -> ProviderError {173            let message = body.message.map { SecretScrubber.scrub($0, secrets: secrets) }174            return SecretScrubber.scrub(.http(status: status, code: body.code, message: message, retryAfter: retryAfter, model: model), secrets: secrets)175        }176    }177178    static func request(_ url: URL, method: String = "GET", headers: [String: String], body: JSONValue? = nil, timeout: TimeInterval) -> URLRequest {179        var request = URLRequest(url: url)180        request.httpMethod = method181        request.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData182        request.timeoutInterval = timeout183        request.httpShouldHandleCookies = false184        for (name, value) in headers { request.setValue(value, forHTTPHeaderField: name) }185        if let body {186            request.httpBody = body.data187            request.setValue("application/json", forHTTPHeaderField: "Content-Type")188        }189        return request190    }191192    /// Runs `attempt` until it succeeds, fails with something that must not be retried, or the policy is exhausted.193    /// A `Failure` is rethrown as is; anything else is rethrown as a scrubbed `ProviderError`.194    private func withRetries<T: Sendable>(_ what: String, model: String?, secrets: [String],195                                          _ attempt: @Sendable () async throws -> T) async throws -> T {196        var failed = 0197        while true {198            try Task.checkCancellation()199            do {200                return try await attempt()201            } catch {202                if Task.isCancelled { throw ProviderError.cancelled }203                let failure = error as? Failure204                let mapped = failure?.mapped(model: model, secrets: secrets) ?? SecretScrubber.scrub(.wrap(error), secrets: secrets)205                failed += 1206                guard mapped.isRetryable,207                      let delay = environment.retry.delay(failedAttempts: failed, retryAfter: failure?.retryAfter, random: environment.random()) else {208                    environment.log("\(family.rawValue) \(what) failed: \(mapped.title) (attempt \(failed))", secrets: secrets)209                    if let failure { throw failure }210                    throw mapped211                }212                environment.log("\(family.rawValue) \(what) retry \(failed) in \(String(format: "%.2f", delay)) s: \(mapped.title)", secrets: secrets)213                do { try await environment.sleep(delay) } catch { throw ProviderError.cancelled }214            }215        }216    }217218    /// A JSON request (model list, key check), retried per policy.219    func json(_ request: URLRequest, model: String? = nil, secrets: [String]) async throws -> JSONValue {220        let transport = environment.transport221        do {222            return try await withRetries("request", model: model, secrets: secrets) {223                let (data, response) = try await transport.data(for: request)224                guard (200..<300).contains(response.statusCode) else {225                    throw Failure(status: response.statusCode, body: .parse(data), retryAfter: response.retryAfter)226                }227                guard let json = JSONValue.parse(data) else { throw ProviderError.malformedResponse("the provider did not answer with JSON.") }228                return json229            }230        } catch let failure as Failure {231            throw failure.mapped(model: model, secrets: secrets)232        }233    }234235    /// Opens a streaming request, retried per policy until a 2xx head arrives. Throws `Failure` for a non-2xx answer236    /// that was not (or no longer) retried.237    func open(_ request: URLRequest, model: String, secrets: [String]) async throws -> AsyncThrowingStream<Data, Error> {238        let transport = environment.transport239        let stream = try await withRetries("stream", model: model, secrets: secrets) {240            let (response, body) = try await transport.bytes(for: request)241            guard (200..<300).contains(response.statusCode) else {242                var collected = Data()243                do { for try await chunk in body { collected.append(chunk); if collected.count > 64_000 { break } } } catch {}244                throw Failure(status: response.statusCode, body: .parse(collected), retryAfter: response.retryAfter)245            }246            return body247        }248        environment.log("\(family.rawValue) stream opened for model \(model)", secrets: secrets)249        return stream250    }251252    /// Opens a streaming request whose body may be adjusted when the provider refuses a parameter (at most253    /// `maxAdjustments` times). `adjust` returns `true` when it changed the body and the request should be sent again.254    func openAdjusting(body initial: [String: JSONValue], model: String, secrets: [String], maxAdjustments: Int = 3,255                       makeRequest: (JSONValue) -> URLRequest,256                       adjust: (Failure, inout [String: JSONValue]) -> Bool) async throws -> AsyncThrowingStream<Data, Error> {257        var body = initial258        var adjustments = 0259        while true {260            do {261                return try await open(makeRequest(.object(body)), model: model, secrets: secrets)262            } catch let failure as Failure {263                if adjustments < maxAdjustments, adjust(failure, &body) {264                    adjustments += 1265                    environment.log("\(family.rawValue) request adjusted after HTTP \(failure.status) (\(adjustments))", secrets: secrets)266                    continue267                }268                throw failure.mapped(model: model, secrets: secrets)269            }270        }271    }272}273274// MARK: - Event streams275276typealias EventContinuation = AsyncThrowingStream<ChatEvent, Error>.Continuation277278/// Collects the credentials a stream used, so its final error can be scrubbed of them.279final class SecretBox: @unchecked Sendable {280    private let lock = NSLock()281    private var stored: [String] = []282    func add(_ secret: String?) { if let secret, !secret.isEmpty { lock.withLock { stored.append(secret) } } }283    var values: [String] { lock.withLock { stored } }284}285286/// Builds the stream every provider returns: the work runs in a child task that is cancelled the moment the consumer287/// stops (task cancellation or a dropped stream), which in turn cancels the HTTP request.288func makeEventStream(secrets: SecretBox, _ body: @escaping @Sendable (EventContinuation) async throws -> Void) -> AsyncThrowingStream<ChatEvent, Error> {289    AsyncThrowingStream(bufferingPolicy: .unbounded) { continuation in290        let task = Task {291            do {292                try await body(continuation)293                if Task.isCancelled { continuation.finish(throwing: ProviderError.cancelled) } else { continuation.finish() }294            } catch {295                if Task.isCancelled { continuation.finish(throwing: ProviderError.cancelled); return }296                continuation.finish(throwing: SecretScrubber.scrub(.wrap(error), secrets: secrets.values))297            }298        }299        continuation.onTermination = { _ in task.cancel() }300    }301}302
Files main
Menu

Theme