Repository Public
1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/Ops/ServerSentEvents.swift3// Description: Incremental parser of a `text/event-stream` body (the alerts stream and the research-job log stream are SSE).4// Pure: bytes or lines in, events out. The connection itself is not opened here — `HTTPTransport` answers whole5// bodies; the apps poll the equivalent REST reads, or feed `URLSession.bytes(for:)` of the request built by6// `AlertsAPI.streamRequest()` / `ResearchAPI.logStreamRequest(_:after:)` into this parser.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation1112public struct ServerSentEvent: Sendable, Equatable {13 /** `message` when the stream names none. */14 public let event: String15 public let data: String16 /** The last `id:` seen (sent back as `Last-Event-ID` on reconnection). */17 public let id: String?18 /** The server's `retry:` advice in milliseconds, when this event block carried one. */19 public let retryMs: Int?20}2122public struct ServerSentEventParser: Sendable {23 private var buffer = Data()24 private var event = "", data: [String] = [], lastId: String?, retry: Int?25 public init() {}2627 /** The id to send as `Last-Event-ID` when reconnecting. */28 public var lastEventId: String? { lastId }2930 /** Feed a chunk of the body; returns the events it completed. */31 public mutating func feed(_ chunk: Data) -> [ServerSentEvent] {32 buffer.append(chunk)33 var out: [ServerSentEvent] = []34 while let nl = buffer.firstIndex(where: { $0 == 0x0a || $0 == 0x0d }) {35 // a CR at the very end may be the first half of CRLF: wait for the next chunk36 if buffer[nl] == 0x0d, nl == buffer.index(before: buffer.endIndex) { break }37 let line = String(decoding: buffer[buffer.startIndex..<nl], as: UTF8.self)38 var next = buffer.index(after: nl)39 if buffer[nl] == 0x0d, next < buffer.endIndex, buffer[next] == 0x0a { next = buffer.index(after: next) }40 buffer = Data(buffer[next...])41 if let e = feed(line: line) { out.append(e) }42 }43 return out44 }4546 /** Feed one line without its terminator (what `URLSession.AsyncBytes.lines` yields… except that it swallows empty lines: prefer `feed(_:)` on bytes). */47 public mutating func feed(line: String) -> ServerSentEvent? {48 if line.isEmpty {49 defer { event = ""; data = []; retry = nil }50 // a block without data (a lone `retry:` or comment) dispatches nothing51 return data.isEmpty ? nil : ServerSentEvent(event: event.isEmpty ? "message" : event, data: data.joined(separator: "\n"), id: lastId, retryMs: retry)52 }53 if line.hasPrefix(":") { return nil }54 let field: Substring, value: Substring55 if let colon = line.firstIndex(of: ":") {56 field = line[..<colon]57 var v = line[line.index(after: colon)...]58 if v.hasPrefix(" ") { v = v.dropFirst() }59 value = v60 } else { field = Substring(line); value = "" }61 switch field {62 case "event": event = String(value)63 case "data": data.append(String(value))64 case "id": if !value.contains("\0") { lastId = String(value) }65 case "retry": if let n = Int(value), n >= 0 { retry = n }66 default: break67 }68 return nil69 }70}71