SPB Git

Repository Public License

ProviderError.swift 12.3 KB 231 lines swift

1import Diagnostics2import Foundation34/// Every failure this module reports. Messages are written for the user; text that came from a provider has passed5/// through `Redactor` and through an exact-match scrub of the key in use, so no case can carry a credential.6public enum ProviderError: Error, Sendable, Hashable, LocalizedError, CustomStringConvertible {7    /// The configuration needs an API key and none is stored.8    case missingKey(provider: String)9    /// HTTP 401: the provider rejected the key.10    case invalidKey(String?)11    /// HTTP 403: the key is valid but not allowed to do this.12    case forbidden(String?)13    case rateLimited(retryAfter: TimeInterval?, message: String?)14    /// No credit or quota left on the account.15    case quotaExceeded(String?)16    case modelNotFound(model: String)17    case contextTooLong(String?)18    case contentFiltered(String?)19    /// HTTP 400/422 that is none of the above.20    case invalidRequest(String)21    case overloaded(String?)22    case server(status: Int, message: String?)23    case network(String)24    case timeout25    /// A plain-HTTP endpoint that the HTTPS rule does not allow.26    case insecureEndpoint(String)27    /// The response could not be read (bad JSON, a stream that ended early).28    case malformedResponse(String)29    case unsupported(String)30    /// An on-device model failed or is unavailable.31    case local(String)32    /// A limit of the configuration itself (requests per minute, monthly budget) stopped the request before it was sent.33    case limitExceeded(String)34    /// The configuration is unusable (unknown id, missing base URL, unreadable secret store).35    case configuration(String)36    case cancelled3738    public var title: String {39        switch self {40        case .missingKey: "No API key"41        case .invalidKey: "Key rejected"42        case .forbidden: "Not allowed"43        case .rateLimited: "Rate limited"44        case .quotaExceeded: "Out of credit"45        case .modelNotFound: "Model unavailable"46        case .contextTooLong: "Too much content"47        case .contentFiltered: "Blocked by the provider"48        case .invalidRequest: "Request rejected"49        case .overloaded: "Provider overloaded"50        case .server: "Provider error"51        case .network: "Network problem"52        case .timeout: "Timed out"53        case .insecureEndpoint: "Insecure endpoint"54        case .malformedResponse: "Unexpected response"55        case .unsupported: "Not supported"56        case .local: "On-device model"57        case .limitExceeded: "Limit reached"58        case .configuration: "Provider not set up"59        case .cancelled: "Stopped"60        }61    }6263    public var message: String {64        switch self {65        case .missingKey(let provider): "Add your \(provider) API key in Settings to use this provider."66        case .invalidKey(let detail): detail ?? "The provider rejected this API key. Check it or replace it."67        case .forbidden(let detail): detail ?? "This key is not allowed to use that model or feature."68        case .rateLimited(let after, let detail):69            if let after, after.isFinite, after > 0 { "The provider is rate limiting this key. Try again in \(Int(min(after, 86_400).rounded(.up))) s." }70            else { detail ?? "The provider is rate limiting this key. Try again shortly." }71        case .quotaExceeded(let detail): detail ?? "This account has no remaining credit or quota."72        case .modelNotFound(let model): "The provider does not offer “\(model)” to this key."73        case .contextTooLong(let detail): detail ?? "The request no longer fits in this model's context window. Share less content or start a new conversation."74        case .contentFiltered(let detail): detail ?? "The provider declined to answer this request."75        case .invalidRequest(let detail): detail76        case .overloaded(let detail): detail ?? "The provider is overloaded right now. Try again in a moment."77        case .server(let status, let detail): detail ?? "The provider returned an error (HTTP \(status))."78        case .network(let detail): detail79        case .timeout: "The provider took too long to answer."80        case .insecureEndpoint(let detail): detail81        case .malformedResponse(let detail): "The response could not be read: \(detail)"82        case .unsupported(let detail): detail83        case .local(let detail): detail84        case .limitExceeded(let detail): detail85        case .configuration(let detail): detail86        case .cancelled: "Generation was stopped."87        }88    }8990    public var errorDescription: String? { message }91    public var description: String { "\(title): \(message)" }9293    /// Whether sending the same request again may succeed. Auth, validation and quota failures never are.94    public var isRetryable: Bool {95        switch self {96        case .rateLimited, .overloaded, .timeout: true97        case .network: !requestMayHaveBeenAccepted98        case .server(let status, _): status >= 50099        default: false100        }101    }102103    /// The server's own `Retry-After`, when it sent one.104    public var retryAfter: TimeInterval? {105        if case .rateLimited(let after, _) = self { return after }106        return nil107    }108109    public static let connectionLost = ProviderError.network("The connection was lost while the answer was arriving.")110    public static let connectionClosedEarly = ProviderError.malformedResponse("the connection closed before the answer was complete.")111112    /// A connection that dropped mid-response: the provider may have processed (and billed) the request, so it is113    /// never resent automatically.114    var requestMayHaveBeenAccepted: Bool { self == .connectionLost }115116    // MARK: Wrapping117118    /// Turns any error into a `ProviderError`. Text from outside this module is redacted and shortened.119    public static func wrap(_ error: Error) -> ProviderError {120        if let known = error as? ProviderError { return known }121        if error is CancellationError { return .cancelled }122        if let url = error as? URLError {123            switch url.code {124            case .cancelled: return .cancelled125            case .timedOut: return .timeout126            case .notConnectedToInternet, .dataNotAllowed: return .network("This device is offline.")127            case .networkConnectionLost: return .connectionLost128            case .cannotFindHost, .cannotConnectToHost, .dnsLookupFailed: return .network("The server could not be reached.")129            case .secureConnectionFailed, .serverCertificateUntrusted, .serverCertificateHasBadDate, .serverCertificateNotYetValid,130                 .serverCertificateHasUnknownRoot, .clientCertificateRejected:131                return .network("A secure connection to the server could not be established.")132            case .appTransportSecurityRequiresSecureConnection:133                return .insecureEndpoint("The system blocked this plain-HTTP connection.")134            default: return .network("The network request failed (\(url.code.rawValue)).")135            }136        }137        if (error as NSError).domain == NSURLErrorDomain { return .network("The network request failed (\((error as NSError).code)).") }138        let text = (error as? LocalizedError)?.errorDescription ?? String(describing: type(of: error))139        return .configuration(String(Redactor.redact(text).prefix(300)))140    }141142    // MARK: HTTP mapping143144    /// Maps an HTTP failure to a typed error. `code` is the provider's machine-readable error type, `message` its145    /// human text; both are optional because gateways answer with anything.146    public static func http(status: Int, code: String?, message: String?, retryAfter: TimeInterval?, model: String?) -> ProviderError {147        let lowered = ((code ?? "") + " " + (message ?? "")).lowercased()148        // Redact first, cut second: a key straddling the cut would otherwise fall below the pattern lengths.149        let clean = message.map { String(Redactor.redact(String($0.prefix(4_000))).prefix(400)) }.flatMap { $0.isEmpty ? nil : $0 }150        switch status {151        case 401: return .invalidKey(clean)152        case 402: return .quotaExceeded(clean)153        case 403:154            if lowered.contains("moderation") || lowered.contains("flagged") { return .contentFiltered(clean) }155            return .forbidden(clean)156        case 404:157            if let model, lowered.contains("model") || code == "not_found_error" { return .modelNotFound(model: model) }158            return .invalidRequest(clean ?? "The endpoint was not found (HTTP 404). Check the base URL.")159        case 408: return .timeout160        case 413: return .contextTooLong(clean)161        case 429:162            if lowered.contains("insufficient_quota") || lowered.contains("billing") || lowered.contains("credit") { return .quotaExceeded(clean) }163            return .rateLimited(retryAfter: retryAfter, message: clean)164        case 400, 422:165            if lowered.contains("context_length") || lowered.contains("context window") || lowered.contains("maximum context")166                || lowered.contains("too many tokens") || saysPromptIsTooLong(lowered) { return .contextTooLong(clean) }167            if let model, lowered.contains("model_not_found") || lowered.contains("not a valid model") { return .modelNotFound(model: model) }168            if lowered.contains("content_policy") || lowered.contains("content management") { return .contentFiltered(clean) }169            return .invalidRequest(clean ?? "The provider rejected the request (HTTP \(status)).")170        case 503, 529: return .overloaded(clean)171        default: return .server(status: status, message: clean)172        }173    }174175    private static func saysPromptIsTooLong(_ lowered: String) -> Bool {176        lowered.range(of: #"(prompt|input|context|conversation|request|messages?|content|text)\b[^.]{0,40}\btoo (long|large)"#,177                      options: .regularExpression) != nil178    }179180    /// The same error with `transform` applied to every piece of free text it carries.181    func mapText(_ transform: (String) -> String) -> ProviderError {182        func optional(_ text: String?) -> String? { text.map(transform) }183        switch self {184        case .missingKey, .timeout, .cancelled: return self185        case .invalidKey(let m): return .invalidKey(optional(m))186        case .forbidden(let m): return .forbidden(optional(m))187        case .rateLimited(let after, let m): return .rateLimited(retryAfter: after, message: optional(m))188        case .quotaExceeded(let m): return .quotaExceeded(optional(m))189        case .modelNotFound(let model): return .modelNotFound(model: transform(model))190        case .contextTooLong(let m): return .contextTooLong(optional(m))191        case .contentFiltered(let m): return .contentFiltered(optional(m))192        case .invalidRequest(let m): return .invalidRequest(transform(m))193        case .overloaded(let m): return .overloaded(optional(m))194        case .server(let status, let m): return .server(status: status, message: optional(m))195        case .network(let m): return .network(transform(m))196        case .insecureEndpoint(let m): return .insecureEndpoint(transform(m))197        case .malformedResponse(let m): return .malformedResponse(transform(m))198        case .unsupported(let m): return .unsupported(transform(m))199        case .local(let m): return .local(transform(m))200        case .limitExceeded(let m): return .limitExceeded(transform(m))201        case .configuration(let m): return .configuration(transform(m))202        }203    }204}205206/// Removes the credentials of the request in flight from text, whatever their shape.207///208/// `Redactor` recognises credentials by pattern; a key for a self-hosted server can be any string, so the exact209/// values used by the request are removed first.210enum SecretScrubber {211    static let mask = "‹redacted›"212213    static func scrub(_ text: String, secrets: [String]) -> String {214        var out = text215        for secret in secrets where secret.count >= 4 { out = out.replacingOccurrences(of: secret, with: mask) }216        // A message cut to a fixed length can end in the middle of a secret: mask a trailing fragment of one too.217        for secret in secrets where secret.count >= 8 {218            var length = min(secret.count - 1, out.count)219            while length >= 6 {220                if out.hasSuffix(secret.prefix(length)) { out = String(out.dropLast(length)) + mask; break }221                length -= 1222            }223        }224        return Redactor.redact(out)225    }226227    static func scrub(_ error: ProviderError, secrets: [String]) -> ProviderError {228        error.mapText { scrub($0, secrets: secrets) }229    }230}231
Files main
Menu

Theme