SPB Git

Repository Public

Support.swift 15.1 KB 332 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraWallet/Support.swift8// Module           : Qyvora Wallet9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0413//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import QyvoraMath43import QyvoraRecovery44import QyvoraNetworking4546/// The single door to the network. Every client of the service is built on it, so that:47/// - cold mode is enforced in one place (`send` throws `NetworkError.offline` before anything leaves the device);48/// - at most `maxConcurrent` requests are in flight (public APIs are shared resources);49/// - requests to one public host start at least `spacing` apart (public indexers throttle bursts);50/// - HTTP 429 answers pause that host (honouring `Retry-After` up to a minute) and are retried a few times — unless51///   another endpoint serves the same data: the host is then left alone for a while and the request fails over at once52///   (waiting on a host that rate-limits, then tarpits, cost tens of seconds per request burst).53final class GatedTransport: HTTPTransport, @unchecked Sendable {54    static let maxConcurrent = 455    static let retryDelays: [Duration] = [.seconds(2), .seconds(5), .seconds(12)]56    /// How long a host that rate-limited or did not answer is left alone when another endpoint can serve the request;57    /// doubled at each consecutive failure up to `maximumRest`.58    static let rest: Duration = .seconds(30)59    static let maximumRest: Duration = .seconds(300)60    /// Minimum time between two request starts to the same https host.61    static let spacing: Duration = .milliseconds(200)6263    private let inner: any HTTPTransport64    private let sleep: @Sendable (Duration) async -> Void65    private let lock = NSLock()66    private var offline = false67    private var inFlight = 068    private var waiters: [CheckedContinuation<Void, Never>] = []69    private var sent = 070    /// Earliest start of the next request, per host.71    private var nextStart: [String: ContinuousClock.Instant] = [:]72    /// Sets of hosts that serve the same data (the endpoints configured for one network).73    private var alternatives: [Set<String>] = []74    /// Hosts left alone after a rate limit or a failure: until when, how many failures in a row, and whether the single75    /// request that tests the host again is in flight.76    private var resting: [String: (until: ContinuousClock.Instant, strikes: Int, probing: Bool)] = [:]77    /// Requests in flight, per host, so that those sent to a host that starts resting are given up at once instead of78    /// waiting for its time-out (a public endpoint that rate-limits often stops answering the requests already sent).79    private var inFlightTasks: [String: [UInt64: Task<(Data, HTTPURLResponse), any Error>]] = [:]80    private var abandoned: Set<UInt64> = []81    private var nextRequestID: UInt64 = 08283    init(inner: any HTTPTransport, sleep: @escaping @Sendable (Duration) async -> Void) {84        self.inner = inner85        self.sleep = sleep86    }8788    /// A pause through the injected clock (tests do not wait).89    func wait(_ duration: Duration) async { await sleep(duration) }9091    func setOffline(_ value: Bool) { lock.withLock { offline = value } }9293    /// Declares which hosts can stand in for each other. Resets what was learnt about resting hosts.94    func setAlternatives(_ groups: [Set<String>]) {95        lock.withLock {96            alternatives = groups97            resting = [:]98        }99    }100101    private enum Admission { case send, probe, skip }102103    /// Whether a request to `host` goes out. A resting host is skipped while another endpoint of its group is not104    /// resting; when its rest is over, one request tests it and the others keep going elsewhere until it answers.105    private func admit(_ host: String) -> Admission {106        lock.withLock {107            guard let state = resting[host] else { return .send }108            guard hasAwakeAlternative(host) else { return .send }109            if state.probing || ContinuousClock.now < state.until { return .skip }110            resting[host] = (state.until, state.strikes, true)111            return .probe112        }113    }114115    /// Must be called with the lock held.116    private func hasAwakeAlternative(_ host: String) -> Bool {117        let now = ContinuousClock.now118        return alternatives.contains { group in119            group.contains(host) && group.contains { other in120                guard other != host else { return false }121                guard let state = resting[other] else { return true }122                return !state.probing && now >= state.until123            }124        }125    }126127    /// Records the outcome of a request. Returns true when the host was put to rest because another endpoint can128    /// serve its group (the caller then gives the failure back at once instead of retrying the same host).129    private func settle(_ host: String, failed: Bool, retryAfter: Duration? = nil) -> Bool {130        lock.withLock {131            guard failed else {132                resting[host] = nil133                return false134            }135            let strikes = (resting[host]?.strikes ?? 0) + 1136            guard hasAwakeAlternative(host) else {137                // nobody else can serve the request: the host is not left alone, the caller waits and retries it138                if resting[host] != nil { resting[host] = (ContinuousClock.now, strikes, false) }139                return false140            }141            var pause = Self.rest * (1 << min(strikes - 1, 4))142            if let retryAfter, retryAfter > pause { pause = retryAfter }143            resting[host] = (ContinuousClock.now + min(pause, Self.maximumRest), strikes, false)144            // what is still on its way to this host is given up: the callers go to the other endpoint now145            for (id, task) in inFlightTasks[host] ?? [:] {146                abandoned.insert(id)147                task.cancel()148            }149            return true150        }151    }152153    private func track(_ host: String, _ task: Task<(Data, HTTPURLResponse), any Error>) -> UInt64 {154        lock.withLock {155            nextRequestID += 1156            inFlightTasks[host, default: [:]][nextRequestID] = task157            return nextRequestID158        }159    }160161    /// Forgets a finished request. Returns true when it was given up because its host started resting.162    private func untrack(_ host: String, _ id: UInt64) -> Bool {163        lock.withLock {164            inFlightTasks[host]?[id] = nil165            return abandoned.remove(id) != nil166        }167    }168169    /// The answer given for a request that is not sent, or given up: HTTP 429, as if the host had refused it.170    private static func refused(_ request: URLRequest) -> (Data, HTTPURLResponse)? {171        guard let url = request.url, let response = HTTPURLResponse(url: url, statusCode: 429, httpVersion: "HTTP/1.1", headerFields: nil) else { return nil }172        return (Data(), response)173    }174175    var isOffline: Bool { lock.withLock { offline } }176    /// Requests that actually reached the inner transport (diagnostics and tests).177    var requestCount: Int { lock.withLock { sent } }178179    private func acquire() async {180        await withCheckedContinuation { (c: CheckedContinuation<Void, Never>) in181            let resumeNow: Bool = lock.withLock {182                if inFlight < Self.maxConcurrent {183                    inFlight += 1184                    return true185                }186                waiters.append(c)187                return false188            }189            if resumeNow { c.resume() }190        }191    }192193    private func release() {194        let next: CheckedContinuation<Void, Never>? = lock.withLock {195            if waiters.isEmpty {196                inFlight -= 1197                return nil198            }199            return waiters.removeFirst()200        }201        next?.resume()202    }203204    /// Reserves the next start slot of the host and returns how long to wait for it.205    private func reserveSlot(_ host: String, spaced: Bool) -> Duration {206        lock.withLock {207            let now = ContinuousClock.now208            let start = max(now, nextStart[host] ?? now)209            nextStart[host] = start + (spaced ? Self.spacing : .zero)210            return start - now211        }212    }213214    private func pause(_ host: String, for delay: Duration) {215        lock.withLock {216            let until = ContinuousClock.now + delay217            if (nextStart[host] ?? until) <= until { nextStart[host] = until }218        }219    }220221    func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {222        var attempt = 0223        let host = request.url?.host ?? ""224        // a node on the user's own network (http is only accepted for local hosts) is not throttled225        let spaced = request.url?.scheme == "https"226        while true {227            if isOffline { throw NetworkError.offline }228            // not sent: the host rate-limited or failed a moment ago and another endpoint serves the same data229            let admission = admit(host)230            if admission == .skip, let refused = Self.refused(request) { return refused }231            let wait = reserveSlot(host, spaced: spaced)232            if wait > .zero { await sleep(wait) }233            await acquire()234            // the host may have started resting while this request waited for its turn235            // (a request admitted as the one that tests a host again keeps that role)236            if admission == .send, wait > .zero, admit(host) == .skip, let refused = Self.refused(request) {237                release()238                return refused239            }240            let result: Result<(Data, HTTPURLResponse), any Error>241            // checked again after the wait: cold mode may have been switched on meanwhile242            if isOffline {243                result = .failure(NetworkError.offline)244            } else {245                lock.withLock { sent += 1 }246                let inner = inner247                let task = Task { try await inner.send(request) }248                let id = track(host, task)249                result = await withTaskCancellationHandler { await task.result } onCancel: { task.cancel() }250                if untrack(host, id), let refused = Self.refused(request) {251                    release()252                    return refused253                }254            }255            release()256            let data: Data, response: HTTPURLResponse257            switch result {258            case .success(let answer): (data, response) = answer259            case .failure(let error):260                // no answer at all (timeout, connection refused…): the host rests when another one can take over261                if !(error is NetworkError), !(error is CancellationError) { _ = settle(host, failed: true) }262                throw error263            }264            var retryAfter: Duration?265            if let header = response.value(forHTTPHeaderField: "Retry-After"), let seconds = Int(header), seconds > 0 {266                retryAfter = .seconds(min(seconds, 60))267            }268            let limited = response.statusCode == 429269            if settle(host, failed: limited, retryAfter: retryAfter) { return (data, response) }270            if limited, attempt < Self.retryDelays.count {271                let delay = retryAfter ?? Self.retryDelays[attempt]272                pause(host, for: delay)273                attempt += 1274                continue275            }276            return (data, response)277        }278    }279}280281/// Runs `work` over `items` with at most `limit` tasks at a time; results keep the order of `items`.282func boundedMap<T: Sendable, R: Sendable>(_ items: [T], limit: Int = GatedTransport.maxConcurrent,283                                          _ work: @escaping @Sendable (T) async throws -> R) async throws -> [R] {284    guard !items.isEmpty else { return [] }285    return try await withThrowingTaskGroup(of: (Int, R).self) { group in286        var results = [R?](repeating: nil, count: items.count)287        var next = 0288        func add(_ group: inout ThrowingTaskGroup<(Int, R), any Error>) {289            let i = next290            let item = items[i]291            next += 1292            group.addTask { (i, try await work(item)) }293        }294        while next < min(limit, items.count) { add(&group) }295        while let (i, r) = try await group.next() {296            results[i] = r297            if next < items.count { add(&group) }298        }299        return results.compactMap { $0 }300    }301}302303extension QRExport {304    /// Frames the UTF-8 bytes of `text` with the Recovery module's `QRChunker` (`qyv1:<index>/<total>:<checksum>:<base64url>`).305    static func make(text: String) throws(WalletError) -> QRExport {306        do {307            return QRExport(text: text, frames: try QRChunker.split(Bytes(text.utf8)))308        } catch {309            throw WalletError.invalidPayload("This content is too large to be shown as QR codes.")310        }311    }312313    /// Accepts either a complete set of QR frames (any order) or one plain text.314    static func text(from input: [String]) throws(WalletError) -> String {315        guard let first = input.first else { throw WalletError.invalidPayload("empty") }316        if input.count == 1, !first.hasPrefix(QRChunker.prefix + ":") { return first.trimmingCharacters(in: .whitespacesAndNewlines) }317        let bytes: Bytes318        do {319            bytes = try QRAssembler.assemble(input)320        } catch {321            switch error {322            case .incomplete(let missing): throw WalletError.invalidPayload("\(missing.count) QR frame(s) are missing.")323            case .checksumMismatch: throw WalletError.invalidPayload("The QR frames do not reassemble (checksum mismatch).")324            case .mixedSet, .conflictingDuplicate: throw WalletError.invalidPayload("The QR frames belong to different payloads.")325            default: throw WalletError.invalidPayload("Not a QYVORA QR frame.")326            }327        }328        guard let text = String(validating: bytes, as: UTF8.self) else { throw WalletError.invalidPayload("The payload is not text.") }329        return text330    }331}332
Files main
Menu

Theme