SPB Git

Repository Public

SwapStream.swift 9.3 KB 169 lines swift

1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/Swap/SwapStream.swift3// Description: Server-sent events for the quote stream (GET /api/v1/swap/quote/stream): an incremental parser of the SSE wire4//              format, a small transport protocol (URLSession bytes in the apps, a scripted one in tests) and the entry point5//              `APIClient.serverSentEvents`, written as an extension so that API/APIClient.swift is untouched. Same rules as6//              every other request: the session cookie only to the configured origin, no cookie jar, no cache, no redirect.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation1112/** One event of a `text/event-stream` answer. */13public struct SwapSSEvent: Sendable, Hashable {14    /** The `event:` name; `message` when the block names none (the SSE default). */15    public let name: String16    /** The `data:` lines joined by a line feed. */17    public let data: String18    /** The reconnection delay the server suggests (`retry:`), milliseconds. */19    public let retry: Int?20    public init(name: String, data: String, retry: Int? = nil) { self.name = name; self.data = data; self.retry = retry }21}2223/** Incremental SSE parser: feed it bytes as they arrive, in chunks of any size. Comment lines (keep-alives) produce nothing. */24public struct SwapSSEParser: Sendable {25    private var buffer: [UInt8] = []26    private var name: String?27    private var data: [String] = []28    private var retry: Int?29    private var skipLineFeed = false30    /** A line longer than this is not a quote event: the stream is refused instead of growing without bound. */31    public static let maxLineBytes = 4 * 1024 * 10243233    public init() {}3435    public mutating func feed<S: Sequence>(_ bytes: S) throws -> [SwapSSEvent] where S.Element == UInt8 {36        var out: [SwapSSEvent] = []37        for b in bytes {38            if skipLineFeed { skipLineFeed = false; if b == 10 { continue } }39            if b == 10 || b == 13 {40                if b == 13 { skipLineFeed = true } // CR LF counts once41                if let e = line(String(decoding: buffer, as: UTF8.self)) { out.append(e) }42                buffer.removeAll(keepingCapacity: true)43            } else {44                buffer.append(b)45                guard buffer.count <= Self.maxLineBytes else { throw APIError(status: 200, code: "decoding", message: "a line of the event stream is too long") }46            }47        }48        return out49    }5051    private mutating func line(_ l: String) -> SwapSSEvent? {52        if l.isEmpty { // end of a block: dispatch only when it carried data (the SSE rule)53            defer { name = nil; data = []; retry = nil }54            return data.isEmpty ? nil : SwapSSEvent(name: name ?? "message", data: data.joined(separator: "\n"), retry: retry)55        }56        if l.hasPrefix(":") { return nil }57        let field: Substring, value: Substring58        if let c = l.firstIndex(of: ":") { field = l[..<c]; let rest = l[l.index(after: c)...]; value = rest.hasPrefix(" ") ? rest.dropFirst() : rest }59        else { field = Substring(l); value = "" }60        switch field {61        case "event": name = String(value)62        case "data": data.append(String(value))63        case "retry": retry = Int(value)64        default: break // `id` and unknown fields are not used by this API65        }66        return nil67    }68}6970/** What opens a streaming GET. The apps use `URLSessionEventStreamTransport`; tests script one. */71public protocol EventStreamTransport: Sendable {72    /** The response head, and the body as chunks of bytes until the server closes. Cancelling the consumer must close the connection. */73    func open(_ request: URLRequest) async throws -> (HTTPURLResponse, AsyncThrowingStream<Data, Error>)74}7576/** URLSession bytes without a cookie jar, without a cache, never following a redirect — the streaming twin of `URLSessionTransport`. */77public final class URLSessionEventStreamTransport: NSObject, EventStreamTransport, URLSessionTaskDelegate, @unchecked Sendable {78    private var session: URLSession!7980    public override init() {81        super.init()82        let c = URLSessionConfiguration.ephemeral83        c.httpCookieStorage = nil84        c.httpShouldSetCookies = false85        c.httpCookieAcceptPolicy = .never86        c.urlCache = nil87        c.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData88        c.urlCredentialStorage = nil89        c.tlsMinimumSupportedProtocolVersion = .TLSv1290        c.waitsForConnectivity = false91        c.timeoutIntervalForRequest = 45 // the server writes a keep-alive comment every 15 s92        c.timeoutIntervalForResource = 30093        session = URLSession(configuration: c, delegate: self, delegateQueue: nil)94    }9596    public func open(_ request: URLRequest) async throws -> (HTTPURLResponse, AsyncThrowingStream<Data, Error>) {97        let (bytes, response) = try await session.bytes(for: request)98        guard let http = response as? HTTPURLResponse else { throw APIError.offline("no HTTP answer") }99        if (300..<400).contains(http.statusCode) { throw APIError(status: http.statusCode, code: "refused_redirect", message: "the server answered with a redirect; it was not followed") }100        let stream = AsyncThrowingStream<Data, Error> { continuation in101            let task = Task {102                do {103                    var chunk = Data()104                    for try await b in bytes {105                        chunk.append(b)106                        if b == 10 { continuation.yield(chunk); chunk = Data() } // line by line: an event is shown as soon as it is complete107                    }108                    if !chunk.isEmpty { continuation.yield(chunk) }109                    continuation.finish()110                } catch { continuation.finish(throwing: error) }111            }112            continuation.onTermination = { _ in task.cancel() }113        }114        return (http, stream)115    }116117    public func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,118                           newRequest request: URLRequest) async -> URLRequest? { nil }119}120121public extension APIClient {122    /**123     Open a `text/event-stream` GET under /api/v1 and deliver its events until the server closes the stream. A refusal124     (`401`, `429 too_many_streams`, `400 bad_amount`…) is thrown as the server's `APIError`, exactly as for a JSON call.125     Cancelling the consuming task closes the connection (the server then releases its stream slot).126     */127    nonisolated func serverSentEvents(_ path: String, query: [String: String?] = [:], transport: EventStreamTransport) -> AsyncThrowingStream<SwapSSEvent, Error> {128        AsyncThrowingStream { continuation in129            let task = Task {130                do {131                    precondition(path.hasPrefix("/"), "API paths are absolute below /api/v1")132                    guard var c = URLComponents(url: configuration.origin, resolvingAgainstBaseURL: false) else { throw APIError(status: 0, code: "bad_url", message: "bad origin") }133                    c.percentEncodedPath = "/api/v1" + path134                    let items = query.compactMap { k, v in v.map { URLQueryItem(name: k, value: $0) } }.sorted { $0.name < $1.name }135                    if !items.isEmpty { c.queryItems = items }136                    guard let url = c.url else { throw APIError(status: 0, code: "bad_url", message: "bad path \(path)") }137                    var req = URLRequest(url: url)138                    req.httpMethod = "GET"139                    req.httpShouldHandleCookies = false140                    req.cachePolicy = .reloadIgnoringLocalAndRemoteCacheData141                    req.setValue(configuration.userAgent, forHTTPHeaderField: "User-Agent")142                    req.setValue("text/event-stream", forHTTPHeaderField: "Accept")143                    if let cookie = await cookieHeader() { req.setValue(cookie, forHTTPHeaderField: "Cookie") }144145                    let (http, body): (HTTPURLResponse, AsyncThrowingStream<Data, Error>)146                    do { (http, body) = try await transport.open(req) }147                    catch let e as APIError { throw e }148                    catch is CancellationError { throw CancellationError() }149                    catch let e as URLError where e.code == .cancelled { throw CancellationError() }150                    catch { throw APIError.offline(error.localizedDescription) }151152                    guard (200..<300).contains(http.statusCode) else {153                        var data = Data()154                        for try await chunk in body { data.append(chunk); if data.count > 65_536 { break } }155                        let j = try? APICoding.decoder().decode(JSONValue.self, from: data)156                        throw APIError(status: http.statusCode, code: j?["error"]?.stringValue ?? "error", message: j?["message"]?.stringValue ?? "error", data: j?["data"], body: j)157                    }158                    var parser = SwapSSEParser()159                    for try await chunk in body { for e in try parser.feed(chunk) { continuation.yield(e) } }160                    continuation.finish()161                }162                catch let e as URLError where e.code != .cancelled { continuation.finish(throwing: APIError.offline(e.localizedDescription)) }163                catch { continuation.finish(throwing: error) }164            }165            continuation.onTermination = { _ in task.cancel() }166        }167    }168}169
Files main
Menu

Theme