SPB Git

Repository Public MIT

DownloadTransport.swift 10.6 KB 223 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraLocal/Sources/DownloadTransport.swift10// Module           : Packages11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2113// Last Modified    : 2026-11-2214//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import AstraCore89import Foundation9091/// The head of an HTTP response and its body as it arrives.92public struct DownloadResponse: Sendable {93    public var status: Int94    /// Header names in lowercase.95    public var headers: [String: String]96    public var body: AsyncThrowingStream<Data, Error>97    /// Called by the consumer after it has written `n` bytes, so a transport can apply backpressure. Optional.98    public var consumed: (@Sendable (Int) -> Void)?99    public init(status: Int, headers: [String: String] = [:], body: AsyncThrowingStream<Data, Error>, consumed: (@Sendable (Int) -> Void)? = nil) {100        self.status = status; self.body = body; self.consumed = consumed101        self.headers = Dictionary(headers.map { ($0.key.lowercased(), $0.value) }, uniquingKeysWith: { a, _ in a })102    }103}104105/// The only door the download coordinator uses to reach the network. Tests replace it with a local fake server.106public protocol DownloadTransport: Sendable {107    /// Sends `request` and returns as soon as the response head is known. Cancelling the calling task, or dropping the body, cancels the transfer.108    func open(_ request: URLRequest) async throws -> DownloadResponse109}110111/// URLSession-backed transport. It uses a **foreground** session with data tasks: bytes are appended to the partial file as they arrive,112/// which is what makes exact Range resume and size capping possible. Transfers stop when iOS suspends the app and resume from the113/// partial file afterwards; this is not a background (`URLSessionConfiguration.background`) session.114public final class URLSessionDownloadTransport: NSObject, DownloadTransport, URLSessionDataDelegate, @unchecked Sendable {115    private final class State: @unchecked Sendable {116        var head: CheckedContinuation<DownloadResponse, Error>?117        let stream: AsyncThrowingStream<Data, Error>118        let body: AsyncThrowingStream<Data, Error>.Continuation119        var buffered = 0120        var suspended = false121        init() { (stream, body) = AsyncThrowingStream<Data, Error>.makeStream(bufferingPolicy: .unbounded) }122    }123124    private let lock = NSLock()125    private var states: [Int: State] = [:]126    private var session: URLSession!127    private let highWater = 32 << 20, lowWater = 8 << 20128    /// Times a transfer was paused because the consumer fell behind (diagnostics).129    private(set) var suspensions = 0130131    public init(configuration: URLSessionConfiguration? = nil) {132        super.init()133        let c = configuration ?? {134            let c = URLSessionConfiguration.ephemeral135            c.timeoutIntervalForRequest = 60136            c.timeoutIntervalForResource = 7 * 24 * 3600137            c.urlCache = nil138            c.httpCookieStorage = nil139            c.httpShouldSetCookies = false140            c.waitsForConnectivity = false141            c.httpMaximumConnectionsPerHost = 4142            return c143        }()144        let queue = OperationQueue(); queue.maxConcurrentOperationCount = 1145        // A queue created here defaults to background quality of service, which the system throttles hard (CPU and network) on a busy device.146        queue.qualityOfService = .userInitiated147        session = URLSession(configuration: c, delegate: self, delegateQueue: queue)148    }149150    deinit { session?.invalidateAndCancel() }151152    public func open(_ request: URLRequest) async throws -> DownloadResponse {153        var request = request154        request.cachePolicy = .reloadIgnoringLocalCacheData155        let task = session.dataTask(with: request)156        let state = State()157        state.body.onTermination = { _ in task.cancel() }158        return try await withTaskCancellationHandler {159            try await withCheckedThrowingContinuation { continuation in160                state.head = continuation161                lock.withLock { states[task.taskIdentifier] = state }162                task.resume()163            }164        } onCancel: { task.cancel() }165    }166167    private func state(_ task: URLSessionTask) -> State? { lock.withLock { states[task.taskIdentifier] } }168169    // The Hub redirects large files to a CDN: keep the byte range, never forward credentials to another host.170    public func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest,171                           completionHandler: @escaping @Sendable (URLRequest?) -> Void) {172        var next = request173        let original = task.originalRequest174        if let range = original?.value(forHTTPHeaderField: "Range") { next.setValue(range, forHTTPHeaderField: "Range") }175        next.setValue("identity", forHTTPHeaderField: "Accept-Encoding")176        if next.url?.host != original?.url?.host { next.setValue(nil, forHTTPHeaderField: "Authorization") }177        guard next.url?.scheme == "https" || EndpointPolicy.isLocalHost(next.url?.host ?? "") else { completionHandler(nil); return }178        completionHandler(next)179    }180181    public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse,182                           completionHandler: @escaping @Sendable (URLSession.ResponseDisposition) -> Void) {183        guard let state = state(dataTask), let http = response as? HTTPURLResponse else { completionHandler(.cancel); return }184        var headers: [String: String] = [:]185        for (k, v) in http.allHeaderFields { if let k = k as? String, let v = v as? String { headers[k] = v } }186        let head = lock.withLock { () -> CheckedContinuation<DownloadResponse, Error>? in defer { state.head = nil }; return state.head }187        head?.resume(returning: DownloadResponse(status: http.statusCode, headers: headers, body: state.stream, consumed: { [weak self, weak dataTask] n in188            guard let self, let dataTask else { return }189            let resume = self.lock.withLock { () -> Bool in190                state.buffered = max(0, state.buffered - n)191                if state.suspended, state.buffered < self.lowWater { state.suspended = false; return true }192                return false193            }194            if resume { dataTask.resume() }195        }))196        completionHandler(.allow)197    }198199    public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {200        guard let state = state(dataTask) else { return }201        state.body.yield(data)202        let suspend = lock.withLock { () -> Bool in203            state.buffered += data.count204            if !state.suspended, state.buffered > highWater { state.suspended = true; suspensions += 1; return true }205            return false206        }207        if suspend { dataTask.suspend() }208    }209210    public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {211        let state = lock.withLock { states.removeValue(forKey: task.taskIdentifier) }212        guard let state else { return }213        let head = lock.withLock { () -> CheckedContinuation<DownloadResponse, Error>? in defer { state.head = nil }; return state.head }214        if let error {215            head?.resume(throwing: error)216            state.body.finish(throwing: error)217        } else {218            head?.resume(throwing: URLError(.badServerResponse))219            state.body.finish()220        }221    }222}223
Files main
Menu

Theme