SPB Git

Repository Public

IdentityError.swift 10.1 KB 225 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : MacLustr Identity9// File             : sdk/swift/Sources/MacLustrIdentityCore/IdentityError.swift10// Module           : MacLustrIdentityCore11// Repository       : https://git.spboucher.ai/maclustr-identity12// Project Website  : https://identity.spboucher.ai13// Created          : 2026-12-0114// Last Modified    : 2026-12-0115//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author           : Simon-Pierre Boucher21// Position         : Professor of Finance22// Institution      : Université du Québec en Outaouais (UQO)23// Department       : Département des sciences administratives24// Organization     : SP Boucher25//26// Website          : https://spboucher.ai27// Git              : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General          : info@spboucher.ai34// Professional     : contact@spboucher.ai35// Direct           : simon@spboucher.ai36// Research         : research@spboucher.ai37// Development      : dev@spboucher.ai38// Support          : support@spboucher.ai39// Security/Admin   : admin@spboucher.ai40// Notifications    : notifications@spboucher.ai41//42// Preferred Contact: admin@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification   : Public67// Distribution     : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License          : None specified (no license file in this repository)81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788// Typed errors of the SDK.89import Foundation9091/// An error returned by the API: `{"error": {"type", "code", "message", "param", "request_id"}}`.92public struct APIError: Equatable, Sendable, Decodable {93    /// HTTP status code.94    public var status: Int95    /// Error family, for example `invalid_request_error`, `authentication_error`, `conflict_error`, `rate_limit_error`.96    public var type: String97    /// Stable machine-readable code, for example `invalid_client_secret`, `sandbox_no_real_documents`.98    public var code: String99    /// Developer-facing message in English. Not meant to be shown to the person.100    public var message: String101    public var param: String?102    /// Identifier to quote when reporting a problem.103    public var requestID: String?104    /// Seconds to wait before trying again, from the `Retry-After` header (429 `rate_limited`, 503 `service_unavailable`).105    public var retryAfter: TimeInterval?106107    public init(status: Int, type: String, code: String, message: String, param: String? = nil, requestID: String? = nil, retryAfter: TimeInterval? = nil) {108        self.status = status; self.type = type; self.code = code; self.message = message; self.param = param; self.requestID = requestID109        self.retryAfter = retryAfter110    }111112    private enum CodingKeys: String, CodingKey { case type, code, message, param, requestID = "request_id" }113114    public init(from decoder: Decoder) throws {115        let c = try decoder.container(keyedBy: CodingKeys.self)116        status = 0117        // Only `code` is required; a field of an unexpected type is ignored rather than failing the whole envelope.118        type = (try? c.decodeIfPresent(String.self, forKey: .type)) ?? "api_error"119        code = try c.decode(String.self, forKey: .code)120        message = (try? c.decodeIfPresent(String.self, forKey: .message)) ?? ""121        param = (try? c.decodeIfPresent(String.self, forKey: .param)) ?? nil122        requestID = (try? c.decodeIfPresent(String.self, forKey: .requestID)) ?? nil123        retryAfter = nil124    }125126    /// 429 codes that are quotas of the session, not a per-minute rate: waiting a few seconds does not clear them.127    public static let quotaCodes: Set<String> = ["too_many_uploads", "too_many_challenges", "daily_session_limit"]128}129130public enum IdentityError: Error, Equatable, Sendable {131    /// The service answered with an error envelope.132    case api(APIError)133    /// The request did not reach the service (offline, timeout, TLS failure…). The associated value is a short technical description.134    case network(String)135    /// The service answered with something that is not the expected JSON.136    case invalidResponse(status: Int)137    /// The task was cancelled.138    case cancelled139    /// The hosted URL, session id, client secret or base URL is malformed, or the base URL is not https.140    case invalidSessionURL141    /// The session has expired; the app's backend must create a new one.142    case sessionExpired143    /// The person refused camera access.144    case cameraDenied145    /// No usable camera on this device.146    case cameraUnavailable147    /// The camera failed while capturing.148    case captureFailed(String)149150    /// The API error code, when the error comes from the service.151    public var code: String? {152        if case .api(let e) = self { return e.code }153        return nil154    }155156    /// True when retrying the same call later can succeed (network failure, rate limit, server error).157    /// A quota of the session (`too_many_uploads`, `too_many_challenges`) is not retryable.158    public var isRetryable: Bool {159        switch self {160        case .network: return true161        case .api(let e): return (e.status == 429 && !APIError.quotaCodes.contains(e.code)) || e.status >= 500162        case .invalidResponse(let status): return status >= 500163        default: return false164        }165    }166167    /// Seconds the service asked to wait before the next attempt (`Retry-After`), when it said so.168    public var retryAfter: TimeInterval? {169        if case .api(let e) = self { return e.retryAfter }170        return nil171    }172173    /// True when the session can no longer move (expired, cancelled, decided): the flow must reload its state.174    public var isSessionStateConflict: Bool {175        guard case .api(let e) = self, e.status == 409 else { return false }176        return e.code == "invalid_session_state" || e.code == "session_not_cancellable"177    }178179    /// True when the session credentials are rejected: nothing more can be done with this session.180    public var isAuthenticationFailure: Bool {181        if case .api(let e) = self { return e.status == 401 }182        return false183    }184185    /// Maps any thrown error to an `IdentityError`.186    public static func wrap(_ error: Error) -> IdentityError {187        if let e = error as? IdentityError { return e }188        if error is CancellationError { return .cancelled }189        if let u = error as? URLError {190            return u.code == .cancelled ? .cancelled : .network("URLError \(u.code.rawValue)")191        }192        let ns = error as NSError193        if ns.domain == NSURLErrorDomain { return ns.code == NSURLErrorCancelled ? .cancelled : .network("URLError \(ns.code)") }194        return .network(String(describing: Swift.type(of: error)))195    }196197    /// Builds the error for a non-2xx response.198    static func from(status: Int, body: Data, headers: [AnyHashable: Any] = [:]) -> IdentityError {199        struct Envelope: Decodable { let error: APIError }200        if var e = (try? JSONDecoder().decode(Envelope.self, from: body))?.error {201            e.status = status202            e.retryAfter = parseRetryAfter(header(headers, "Retry-After"))203            if e.requestID == nil { e.requestID = header(headers, "Request-Id") }204            return .api(e)205        }206        return .invalidResponse(status: status)207    }208209    private static func header(_ headers: [AnyHashable: Any], _ name: String) -> String? {210        for (k, v) in headers { if let k = k as? String, k.caseInsensitiveCompare(name) == .orderedSame { return v as? String } }211        return nil212    }213214    /// Parses `Retry-After` (delta seconds or HTTP date) into seconds.215    static func parseRetryAfter(_ value: String?, now: Date = Date()) -> TimeInterval? {216        guard let value = value?.trimmingCharacters(in: .whitespaces), !value.isEmpty else { return nil }217        if let n = Double(value) { return n.isFinite ? max(0, n) : nil }218        let f = DateFormatter()219        f.locale = Locale(identifier: "en_US_POSIX")220        f.timeZone = TimeZone(identifier: "GMT")221        f.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz"222        return f.date(from: value).map { max(0, $0.timeIntervalSince(now)) }223    }224}225
Files main
Menu

Theme