SPB Git

Repository Public

VQTransport.swift 10.1 KB 194 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantKit/Core/VQTransport.swift3// Description: The only seam between the package and the network: a request description and a two-method protocol4//              that each app adapts to its own APIClient. The package never builds a URL or touches a token.5import Foundation67public enum VQHTTPMethod: String, Sendable, Hashable { case get = "GET", post = "POST", put = "PUT", patch = "PATCH", delete = "DELETE" }89/// A request relative to the VQuant server. The transport adds the base URL, `Authorization: Bearer vqn_…` and10/// `X-VQ-Client`, and must not add an `Origin` header.11public struct VQRequest: Sendable, Hashable {12    public var method: VQHTTPMethod13    /// Absolute path, already percent-encoded per segment (use `VQRequest.segment(_:)`), e.g. `/api/v2/objects/note/abc`.14    public var path: String15    /// Query items in order; values are raw (the transport percent-encodes them, `+` included).16    public var query: [VQQueryItem]17    /// JSON body (UTF-8). `nil` on GET; non-GET requests without a body send `{}`.18    public var body: Data?19    public var timeout: TimeInterval20    /// `text/event-stream` for streams.21    public var accept: String?22    /// `Content-Type` of `body`; nil = `application/json` (every request except the multipart dataset upload).23    public var contentType: String?2425    public init(_ method: VQHTTPMethod, _ path: String, query: [VQQueryItem] = [], body: VQJSON? = nil, timeout: TimeInterval = 30, accept: String? = nil) {26        self.method = method; self.path = path; self.query = query; self.timeout = timeout; self.accept = accept27        self.body = body.map { $0.data() } ?? (method == .get ? nil : Data("{}".utf8))28    }2930    public static func get(_ path: String, _ query: [VQQueryItem] = [], timeout: TimeInterval = 30) -> VQRequest { VQRequest(.get, path, query: query, timeout: timeout) }3132    /// A request whose body is not JSON (the multipart dataset upload).33    public static func raw(_ method: VQHTTPMethod, _ path: String, query: [VQQueryItem] = [], body: Data, contentType: String, timeout: TimeInterval = 30) -> VQRequest {34        var r = VQRequest(method, path, query: query, timeout: timeout)35        r.body = body; r.contentType = contentType36        return r37    }3839    /// Percent-encodes one path segment (ticker symbols such as `^GSPC` or `BRK-B`, identifiers).40    public static func segment(_ s: String) -> String {41        var allowed = CharacterSet.alphanumerics; allowed.insert(charactersIn: "-._~")42        return s.addingPercentEncoding(withAllowedCharacters: allowed) ?? s43    }44}4546public struct VQQueryItem: Sendable, Hashable {47    public var name: String48    public var value: String49    public init(_ name: String, _ value: String) { self.name = name; self.value = value }50    /// Drops the item when the value is nil.51    public static func optional(_ name: String, _ value: String?) -> [VQQueryItem] { value.map { [VQQueryItem(name, $0)] } ?? [] }52}5354public struct VQResponse: Sendable {55    public var data: Data56    public var http: HTTPURLResponse57    public init(data: Data, http: HTTPURLResponse) { self.data = data; self.http = http }58    public var status: Int { http.statusCode }59}6061/// An open response whose body arrives in chunks (server-sent events). Chunk boundaries are arbitrary; a transport62/// that reads line by line yields each line **followed by "\n"**.63public struct VQByteStream: Sendable {64    public var http: HTTPURLResponse65    public var chunks: AsyncThrowingStream<Data, Error>66    public init(http: HTTPURLResponse, chunks: AsyncThrowingStream<Data, Error>) { self.http = http; self.chunks = chunks }67}6869/// What the package needs from an app. Both methods return the response **whatever its status** (the package reads70/// 409 bodies, `Retry-After`, `x-vq-locked`); they throw only when no HTTP response was obtained.71///72/// Adapters live in the apps (a few lines each, see docs/INTEGRATION.md); `VQURLSessionTransport` is a complete73/// implementation for apps that prefer to hand the package a token provider.74public protocol VQTransport: Sendable {75    func send(_ request: VQRequest) async throws -> VQResponse76    func stream(_ request: VQRequest) async throws -> VQByteStream77}7879/// The package's error vocabulary.80public struct VQError: Error, Sendable, Equatable, LocalizedError {81    public enum Kind: Sendable, Equatable {82        /// no HTTP response (offline, DNS, TLS, timeout)83        case network84        /// 401 — with `x-vq-locked: 1` the session of this device is dead (`isLocked`)85        case unauthorized86        case forbidden          // 403 (also a PUT of a server-only kind)87        case notFound           // 40488        case conflict           // 409 — `current` holds the stored envelope for object writes89        case tooLarge           // 41390        case rateLimited        // 429 — `retryAfter`91        case rejected           // 400 / 422 validation92        case unavailable        // 502 / 503 (provider failed or not configured)93        case server             // other 5xx94        case decoding           // the body is not JSON95    }96    public var kind: Kind97    public var status: Int98    /// The server's own sentence or code (`{ "error": … }`), or a description of the network failure.99    public var message: String100    public var isLocked: Bool101    public var retryAfter: TimeInterval?102    /// The parsed error body (e.g. `current` of a 409, `providers` of a data error, `status` of `not_running`).103    public var body: VQJSON?104105    public init(_ kind: Kind, status: Int = 0, message: String, isLocked: Bool = false, retryAfter: TimeInterval? = nil, body: VQJSON? = nil) {106        self.kind = kind; self.status = status; self.message = message; self.isLocked = isLocked; self.retryAfter = retryAfter; self.body = body107    }108    public var errorDescription: String? { message }109    /// Worth retrying later without changing the request.110    public var isTransient: Bool { kind == .network || kind == .rateLimited || kind == .server || kind == .unavailable }111112    public static func from(_ response: VQResponse) -> VQError? { from(status: response.status, http: response.http, data: response.data) }113114    public static func from(status: Int, http: HTTPURLResponse, data: Data) -> VQError? {115        guard !(200..<300).contains(status) else { return nil }116        let body = try? VQJSON.parse(data)117        let said = body?["error"]?.stringValue ?? body?["message"]?.stringValue118        let retry = http.value(forHTTPHeaderField: "Retry-After").flatMap(TimeInterval.init)119        let kind: Kind120        switch status {121        case 401: kind = .unauthorized122        case 403: kind = .forbidden123        case 404: kind = .notFound124        case 409: kind = .conflict125        case 413: kind = .tooLarge126        case 429: kind = .rateLimited127        case 400, 422: kind = .rejected128        case 502, 503: kind = .unavailable129        default: kind = status >= 500 ? .server : .rejected130        }131        return VQError(kind, status: status, message: said ?? "HTTP \(status)", isLocked: status == 401 && http.value(forHTTPHeaderField: "x-vq-locked") == "1", retryAfter: retry, body: body)132    }133134    public static func network(_ error: Error) -> VQError {135        if let e = error as? VQError { return e }136        return VQError(.network, message: (error as? LocalizedError)?.errorDescription ?? String(describing: error))137    }138}139140/// Typed requests over a `VQTransport`: status check, JSON parsing, error mapping. Cheap to copy.141public struct VQClient: Sendable {142    public let transport: any VQTransport143    public init(transport: any VQTransport) { self.transport = transport }144145    /// The body of a 2xx answer; anything else is thrown as a `VQError`. Cancellation is rethrown as `CancellationError`.146    @discardableResult147    public func data(_ request: VQRequest) async throws -> Data {148        let response: VQResponse149        do { response = try await transport.send(request) }150        catch is CancellationError { throw CancellationError() }151        catch let e as URLError where e.code == .cancelled { throw CancellationError() }152        catch { throw VQError.network(error) }153        if let e = VQError.from(response) { throw e }154        return response.data155    }156157    public func json(_ request: VQRequest) async throws -> VQJSON {158        let d = try await data(request)159        do { return try VQJSON.parse(d) } catch { throw VQError(.decoding, status: 200, message: "The server sent an answer that is not JSON (\(request.path)).") }160    }161162    public func decode<T: VQJSONDecodable>(_ request: VQRequest, as type: T.Type = T.self) async throws -> T { T(json: try await json(request)) }163164    /// Opens a server-sent event stream; a non-2xx status is read and thrown as a `VQError`.165    public func events(_ request: VQRequest) async throws -> AsyncThrowingStream<VQSSEEvent, Error> {166        var r = request167        r.accept = "text/event-stream"168        let open: VQByteStream169        do { open = try await transport.stream(r) }170        catch is CancellationError { throw CancellationError() }171        catch let e as URLError where e.code == .cancelled { throw CancellationError() }172        catch { throw VQError.network(error) }173        if !(200..<300).contains(open.http.statusCode) {174            var body = Data()175            do { for try await chunk in open.chunks { body.append(chunk); if body.count > 8_000 { break } } } catch {}176            throw VQError.from(status: open.http.statusCode, http: open.http, data: body) ?? VQError(.server, status: open.http.statusCode, message: "HTTP \(open.http.statusCode)")177        }178        let chunks = open.chunks179        return AsyncThrowingStream { continuation in180            let task = Task {181                var parser = VQSSEParser()182                do {183                    for try await chunk in chunks {184                        for event in parser.feed(chunk) { continuation.yield(event) }185                    }186                    continuation.finish()187                } catch is CancellationError { continuation.finish() }188                catch { continuation.finish(throwing: VQError.network(error)) }189            }190            continuation.onTermination = { _ in task.cancel() }191        }192    }193}194
Files main
Menu

Theme