Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Networking/SSE.swift3// Description: Reader of the server's event streams (one JSON object per `data:` line, numbered by a preceding `id:` line).4import Foundation56/// One event of a generation stream: its position in the job's log (absent on the stream's opening `job` frame) and its JSON.7public struct SSEFrame: Sendable, Equatable {8 public var id: Int?9 public var json: JSONValue10 public init(id: Int?, json: JSONValue) { self.id = id; self.json = json }11}1213/// The VQuant server writes each event as `id: <n>\ndata: <one-line JSON>\n\n` and keeps idle streams open with14/// `: ping` comments. The reader is line based and does not depend on blank separator lines (some byte-line readers drop them).15public struct SSEParser: Sendable {16 private var pendingId: Int?17 public private(set) var malformed = 018 public init() {}1920 public mutating func feed(_ line: String) -> SSEFrame? {21 if line.isEmpty || line.hasPrefix(":") { return nil }22 if line.hasPrefix("id:") {23 pendingId = Int(line.dropFirst(3).trimmingCharacters(in: .whitespaces))24 return nil25 }26 guard line.hasPrefix("data:") else { return nil }27 var payload = line.dropFirst(5)28 if payload.first == " " { payload = payload.dropFirst() }29 let id = pendingId; pendingId = nil30 guard let json = try? JSONValue.parse(Data(payload.utf8)) else { malformed += 1; return nil }31 return SSEFrame(id: id, json: json)32 }33}34