SPB Git

Repository Public

VQSSE.swift 3.2 KB 71 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantKit/Core/VQSSE.swift3// Description: Reader of the server's event streams (sync stream, generation streams).4import Foundation56/// One server-sent event. The VQuant server writes every payload as one line of JSON and repeats the event name in7/// the payload (`"type"`), so `name` is the SSE `event:` field when present and `type` otherwise.8public struct VQSSEEvent: Sendable, Equatable {9    /// `event:` field, else the payload's `type`, else "message".10    public var name: String11    /// `id:` field of generation streams (position in the job's log).12    public var id: Int?13    public var json: VQJSON14    public init(name: String, id: Int? = nil, json: VQJSON) { self.name = name; self.id = id; self.json = json }15}1617/// Incremental parser. It works on arbitrary chunks, accepts `\n`, `\r\n` and `\r` line ends, skips comment18/// heartbeats (`: ping`), and dispatches at each `data:` line — it does not depend on the blank separator line, which19/// some line readers (`URLSession.AsyncBytes.lines`) drop.20public struct VQSSEParser: Sendable {21    private var buffer: [UInt8] = []22    private var pendingName: String?23    private var pendingId: Int?24    private var lastWasCR = false25    /// `data:` lines that were not JSON (counted, skipped).26    public private(set) var malformed = 027    /// Comment lines seen (heartbeats) — lets a client watch that the stream is alive.28    public private(set) var heartbeats = 02930    public init() {}3132    public mutating func feed(_ chunk: Data) -> [VQSSEEvent] {33        var out: [VQSSEEvent] = []34        for byte in chunk {35            if byte == 0x0A {36                if lastWasCR { lastWasCR = false; continue }37                if let e = line() { out.append(e) }38            } else if byte == 0x0D {39                lastWasCR = true40                if let e = line() { out.append(e) }41            } else {42                lastWasCR = false43                buffer.append(byte)44            }45        }46        return out47    }4849    public mutating func feed(line text: String) -> VQSSEEvent? { feed(Data((text + "\n").utf8)).first }5051    private mutating func line() -> VQSSEEvent? {52        defer { buffer.removeAll(keepingCapacity: true) }53        if buffer.isEmpty { pendingName = nil; return nil }   // blank line: end of an event54        let text = String(decoding: buffer, as: UTF8.self)55        if text.hasPrefix(":") { heartbeats += 1; return nil }56        func value(_ prefix: String) -> String? {57            guard text.hasPrefix(prefix) else { return nil }58            var v = text.dropFirst(prefix.count)59            if v.first == " " { v = v.dropFirst() }60            return String(v)61        }62        if let v = value("event:") { pendingName = v; return nil }63        if let v = value("id:") { pendingId = Int(v.trimmingCharacters(in: .whitespaces)); return nil }64        guard let payload = value("data:") else { return nil }65        let id = pendingId; pendingId = nil66        let name = pendingName; pendingName = nil67        guard let json = try? VQJSON.parse(payload) else { malformed += 1; return nil }68        return VQSSEEvent(name: name ?? json["type"]?.stringValue ?? "message", id: id, json: json)69    }70}71
Files main
Menu

Theme