Repository Public
1import Foundation23/// One dispatched Server-Sent Event.4public struct SSEMessage: Sendable, Equatable {5 public var id: String?6 public var event: String7 public var data: String8 public var retryMilliseconds: Int?9}1011/// Incremental parser of the `text/event-stream` format (WHATWG HTML §9.2.6). Feed it raw bytes; it yields complete12/// messages. Comments (`: ping`) are reported through `sawComment` so that the caller can track the heartbeat.13/// `URLSession.AsyncBytes.lines` cannot be used for SSE: it drops the empty lines that delimit events.14public struct SSEParser: Sendable {15 private var line: [UInt8] = []16 private var lastWasCR = false17 private var event = ""18 private var data: [String] = []19 private var id: String?20 private var retry: Int?21 private var hasField = false22 public private(set) var commentCount = 02324 public init() {}2526 public mutating func feed(_ bytes: some Sequence<UInt8>) -> [SSEMessage] {27 var out: [SSEMessage] = []28 for b in bytes {29 if let m = feed(b) { out.append(m) }30 }31 return out32 }3334 public mutating func feed(_ byte: UInt8) -> SSEMessage? {35 if byte == 0x0A { // LF36 if lastWasCR { lastWasCR = false; return nil } // CRLF: already handled at CR37 return endLine()38 }39 lastWasCR = false40 if byte == 0x0D { lastWasCR = true; return endLine() }41 line.append(byte)42 return nil43 }4445 private mutating func endLine() -> SSEMessage? {46 defer { line.removeAll(keepingCapacity: true) }47 if line.isEmpty { return dispatch() }48 if line[0] == 0x3A { commentCount += 1; return nil } // ":" comment49 let text = String(decoding: line, as: UTF8.self)50 let field: Substring, value: Substring51 if let i = text.firstIndex(of: ":") {52 field = text[..<i]53 var v = text[text.index(after: i)...]54 if v.first == " " { v = v.dropFirst() }55 value = v56 } else {57 field = Substring(text); value = ""58 }59 switch field {60 case "event": event = String(value); hasField = true61 case "data": data.append(String(value)); hasField = true62 case "id": if !value.contains("\0") { id = String(value); hasField = true }63 case "retry": if let n = Int(value) { retry = n; hasField = true }64 default: break65 }66 return nil67 }6869 private mutating func dispatch() -> SSEMessage? {70 defer { event = ""; data = []; id = nil; retry = nil; hasField = false }71 guard hasField else { return nil }72 if data.isEmpty && retry == nil && event.isEmpty { return nil }73 return SSEMessage(id: id, event: event.isEmpty ? "message" : event, data: data.joined(separator: "\n"), retryMilliseconds: retry)74 }75}7677/// Exponential backoff with full jitter.78public struct Backoff: Sendable {79 public var base: TimeInterval80 public var cap: TimeInterval81 public init(base: TimeInterval = 0.5, cap: TimeInterval = 30) { self.base = base; self.cap = cap }8283 /// Delay before retry number `attempt` (1-based): uniformly random in `[ceiling/2, ceiling]`84 /// where `ceiling = min(cap, base * 2^(attempt-1))`.85 public func delay(attempt: Int, random: Double = Double.random(in: 0..<1)) -> TimeInterval {86 let ceiling = min(cap, base * pow(2, Double(max(0, attempt - 1))))87 return ceiling / 2 + (ceiling / 2) * random88 }89}90