SPB Git

Repository Public MIT

Transport.swift 11.5 KB 255 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Packages/AstraCore/Sources/Transport.swift10// Module           : Packages11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2113// Last Modified    : 2026-11-2114//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 Foundation8990/// The only door to the network. Adapters never touch URLSession directly, so every provider parser is testable from fixtures.91public protocol HTTPTransport: Sendable {92    func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse)93    /// Opens a streaming response. On a non-2xx status the lines are the error body.94    func stream(_ request: URLRequest) async throws -> (HTTPURLResponse, AsyncThrowingStream<String, Error>)95}9697public struct URLSessionTransport: HTTPTransport {98    private let session: URLSession99100    public init(configuration: URLSessionConfiguration? = nil) {101        let c = configuration ?? {102            let c = URLSessionConfiguration.ephemeral103            c.timeoutIntervalForRequest = 90104            c.timeoutIntervalForResource = 900105            c.httpCookieStorage = nil106            c.urlCache = nil107            c.httpShouldSetCookies = false108            c.waitsForConnectivity = false109            return c110        }()111        session = URLSession(configuration: c)112    }113114    public func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {115        do {116            let (data, response) = try await session.data(for: request)117            guard let http = response as? HTTPURLResponse else { throw AstraError.network("The server did not answer over HTTP.") }118            return (data, http)119        } catch { throw AstraError.wrap(error) }120    }121122    public func stream(_ request: URLRequest) async throws -> (HTTPURLResponse, AsyncThrowingStream<String, Error>) {123        do {124            let (bytes, response) = try await session.bytes(for: request)125            guard let http = response as? HTTPURLResponse else { throw AstraError.network("The server did not answer over HTTP.") }126            // A bounded buffer gives backpressure: a slow consumer suspends the reader instead of growing memory.127            let (stream, continuation) = AsyncThrowingStream<String, Error>.makeStream(bufferingPolicy: .unbounded)128            let task = Task {129                do {130                    // `bytes.lines` drops empty lines, which SSE needs as event separators: split manually.131                    var buffer = [UInt8](); buffer.reserveCapacity(4096)132                    for try await byte in bytes {133                        if byte == 0x0A {134                            if buffer.last == 0x0D { buffer.removeLast() }135                            continuation.yield(String(decoding: buffer, as: UTF8.self))136                            buffer.removeAll(keepingCapacity: true)137                        } else {138                            buffer.append(byte)139                            if buffer.count > 8_000_000 { throw AstraError.protocolViolation("A single stream line exceeded 8 MB.") }140                        }141                    }142                    if !buffer.isEmpty { continuation.yield(String(decoding: buffer, as: UTF8.self)) }143                    continuation.finish()144                } catch { continuation.finish(throwing: AstraError.wrap(error)) }145            }146            continuation.onTermination = { _ in task.cancel() }147            return (http, stream)148        } catch { throw AstraError.wrap(error) }149    }150}151152// MARK: - Server-sent events153154public struct SSEEvent: Sendable, Hashable {155    public var event: String?156    public var data: String157    public init(event: String? = nil, data: String) { self.event = event; self.data = data }158}159160/// Incremental server-sent-events parser (WHATWG rules: `data:` lines joined by newlines, blank line dispatches, `:` lines are comments).161public struct SSEParser: Sendable {162    private var event: String?163    private var data: [String] = []164    public private(set) var comments = 0165    public init() {}166167    /// Feeds one line (without its terminator); returns an event when a blank line completes one.168    public mutating func feed(_ line: String) -> SSEEvent? {169        if line.isEmpty {170            defer { event = nil; data.removeAll(keepingCapacity: true) }171            return data.isEmpty ? nil : SSEEvent(event: event, data: data.joined(separator: "\n"))172        }173        if line.hasPrefix(":") { comments += 1; return nil }174        let field: Substring, value: Substring175        if let colon = line.firstIndex(of: ":") {176            field = line[..<colon]177            var rest = line[line.index(after: colon)...]178            if rest.first == " " { rest = rest.dropFirst() }179            value = rest180        } else { field = Substring(line); value = "" }181        switch field {182        case "event": event = String(value)183        case "data": data.append(String(value))184        default: break185        }186        return nil187    }188189    /// Flushes an event left without its trailing blank line when the stream ends.190    public mutating func finish() -> SSEEvent? { feed("") }191}192193public extension HTTPURLResponse {194    func header(_ name: String) -> String? { value(forHTTPHeaderField: name) }195196    /// `Retry-After` in seconds (delta form or HTTP date), falling back to provider-specific reset headers.197    var retryAfter: TimeInterval? {198        if let raw = header("retry-after") {199            if let s = Double(raw) { return max(0, s) }200            let f = DateFormatter(); f.locale = Locale(identifier: "en_US_POSIX"); f.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz"201            if let d = f.date(from: raw) { return max(0, d.timeIntervalSinceNow) }202        }203        if let ms = header("retry-after-ms").flatMap(Double.init) { return max(0, ms / 1000) }204        return nil205    }206}207208/// Collects a streamed error body (bounded) so adapters can map it to a typed error.209public func collectBody(_ lines: AsyncThrowingStream<String, Error>, limit: Int = 64_000) async -> Data {210    var text = ""211    do { for try await line in lines { text += line + "\n"; if text.utf8.count > limit { break } } } catch {}212    return Data(text.utf8)213}214215// MARK: - Endpoint safety216217public enum EndpointPolicy {218    /// Validates a user-entered base URL. Plain HTTP is refused unless `allowInsecure` is set, and then only for hosts219    /// on the local network or loopback, which is what App Transport Security's local-networking exception permits.220    public static func validate(_ text: String, allowInsecure: Bool) throws -> URL {221        let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)222        guard let url = URL(string: trimmed), let scheme = url.scheme?.lowercased(), let host = url.host, !host.isEmpty else {223            throw AstraError.invalidRequest("Enter a full URL such as https://example.com/v1.")224        }225        guard url.user == nil, url.password == nil else {226            throw AstraError.invalidRequest("Do not put credentials in the URL; use the API key field.")227        }228        switch scheme {229        case "https": return url230        case "http":231            guard allowInsecure else {232                throw AstraError.insecureEndpoint("Plain HTTP sends your prompts and key unencrypted. Use https, or explicitly allow insecure HTTP for a server on your own network.")233            }234            guard isLocalHost(host) else {235                throw AstraError.insecureEndpoint("Plain HTTP is only allowed for servers on your local network. Use https for “\(host)”.")236            }237            return url238        default: throw AstraError.invalidRequest("Only https (or local http) endpoints are supported.")239        }240    }241242    public static func isLocalHost(_ host: String) -> Bool {243        let h = host.lowercased()244        if h == "localhost" || h.hasSuffix(".local") || h == "::1" || h == "[::1]" { return true }245        let parts = h.split(separator: ".").compactMap { Int($0) }246        guard parts.count == 4, parts.allSatisfy({ (0...255).contains($0) }) else { return false }247        if parts[0] == 10 || parts[0] == 127 { return true }248        if parts[0] == 192 && parts[1] == 168 { return true }249        if parts[0] == 172 && (16...31).contains(parts[1]) { return true }250        if parts[0] == 169 && parts[1] == 254 { return true }251        if parts[0] == 100 && (64...127).contains(parts[1]) { return true }   // CGNAT range used by private overlay networks252        return false253    }254}255
Files main
Menu

Theme