Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Chat9// File : SPChat-iOS/Core/Streaming/SSEParser.swift10// Description : Incremental Server-Sent Events parser (bytes in, events11// out) and the AsyncSequence built on URLSession bytes.12// Module : SPChat-iOS13// Repository : https://git.spboucher.ai/sp-chat-ios14// Created : 2026-11-1915// Last Modified : 2026-11-1916//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author : Simon-Pierre Boucher22// Position : Professor of Finance23// Institution : Université du Québec en Outaouais (UQO)24// Department : Département des sciences administratives25// Organization : SP Boucher26//27// Website : https://spboucher.ai28// Git : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General : info@spboucher.ai35// Professional : contact@spboucher.ai36// Direct : simon@spboucher.ai37// Research : research@spboucher.ai38// Development : dev@spboucher.ai39// Support : support@spboucher.ai40// Security/Admin : admin@spboucher.ai41// Notifications : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification : Public68// Distribution : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License : None specified (no license file in this repository)82// Maintainer : Simon-Pierre Boucher83// Technical Contact: dev@spboucher.ai84//85// =============================================================================86// END OF SP BOUCHER SOURCE HEADER87// =============================================================================8889import Foundation90import os9192struct SSEEvent: Equatable, Sendable {93 var event: String94 var data: String95 /// The `id:` field. The backend numbers the events of a run; the last index seen is what a reconnection resumes from.96 var id: Int?97}9899/// Byte-level SSE parser. Handles LF and CRLF line endings, multi-line `data:`, comments (heartbeats) and events100/// split across network chunks at any byte.101struct SSEParser: Sendable {102 enum Output: Equatable, Sendable {103 case event(SSEEvent)104 /// A comment line (`: ping`): proof that the connection is alive.105 case heartbeat106 }107 private var line: [UInt8] = []108 private var event = "message"109 private var data: [String] = []110 private var id: Int?111 private var sawField = false112113 init() { line.reserveCapacity(4096) }114115 mutating func feed(_ byte: UInt8) -> Output? {116 if byte != 0x0A { line.append(byte); return nil }117 if line.last == 0x0D { line.removeLast() }118 defer { line.removeAll(keepingCapacity: true) }119 if line.isEmpty { return dispatch() }120 if line[0] == 0x3A { return .heartbeat } // ":" comment121 let text = String(decoding: line, as: UTF8.self)122 let field: Substring, value: Substring123 if let colon = text.firstIndex(of: ":") {124 field = text[..<colon]125 var v = text[text.index(after: colon)...]126 if v.first == " " { v = v.dropFirst() }127 value = v128 } else { field = Substring(text); value = "" }129 sawField = true130 switch field {131 case "event": event = String(value)132 case "data": data.append(String(value))133 case "id": id = Int(value.trimmingCharacters(in: .whitespaces))134 default: break // "retry" and unknown fields are ignored135 }136 return nil137 }138139 mutating func feed<S: Sequence>(_ bytes: S) -> [Output] where S.Element == UInt8 {140 var out: [Output] = []141 for b in bytes { if let o = feed(b) { out.append(o) } }142 return out143 }144145 private mutating func dispatch() -> Output? {146 defer { event = "message"; data.removeAll(keepingCapacity: true); id = nil; sawField = false }147 guard sawField, !data.isEmpty else { return nil }148 return .event(SSEEvent(event: event, data: data.joined(separator: "\n"), id: id))149 }150}151152/// One decoded element of a generation stream.153struct StreamItem: Sendable, Equatable {154 var index: Int?155 var event: ChatStreamEvent156}157158enum SSEStream {159 /// Silence after which the connection is considered dead. The server sends a comment every 15 s; iOS does not160 /// always surface an error when the radio drops, so the watchdog ends the read and the caller re-attaches.161 static let silenceLimit: Duration = .seconds(45)162163 /// Raw events of any `text/event-stream` response (lens, arena, sync feed), decoded off the main actor. Same164 /// watchdog as `items`: prolonged silence ends the sequence with an error so the caller can reconnect.165 static func events(from bytes: URLSession.AsyncBytes, silenceLimit: Duration = SSEStream.silenceLimit) -> AsyncThrowingStream<SSEEvent, Error> {166 AsyncThrowingStream(bufferingPolicy: .unbounded) { continuation in167 let lastActivity = OSAllocatedUnfairLock(initialState: ContinuousClock.now)168 let reader = Task.detached(priority: .userInitiated) {169 var parser = SSEParser()170 do {171 for try await byte in bytes {172 guard let out = parser.feed(byte) else { continue }173 lastActivity.withLock { $0 = .now }174 if case .event(let e) = out { continuation.yield(e) }175 }176 continuation.finish()177 } catch { continuation.finish(throwing: error) }178 }179 let watchdog = Task.detached(priority: .utility) {180 while !Task.isCancelled {181 try? await Task.sleep(for: .seconds(5))182 if ContinuousClock.now - lastActivity.withLock({ $0 }) > silenceLimit { reader.cancel(); continuation.finish(throwing: URLError(.timedOut)); return }183 }184 }185 continuation.onTermination = { _ in reader.cancel(); watchdog.cancel() }186 }187 }188189 /// Turns the bytes of a `text/event-stream` response into decoded chat events, off the main actor.190 /// The sequence finishes when the server closes the stream, and throws on transport errors or prolonged silence.191 static func items(from bytes: URLSession.AsyncBytes, silenceLimit: Duration = SSEStream.silenceLimit) -> AsyncThrowingStream<StreamItem, Error> {192 AsyncThrowingStream(bufferingPolicy: .unbounded) { continuation in193 let lastActivity = OSAllocatedUnfairLock(initialState: ContinuousClock.now)194 let reader = Task.detached(priority: .userInitiated) {195 var parser = SSEParser()196 do {197 for try await byte in bytes {198 guard let out = parser.feed(byte) else { continue }199 lastActivity.withLock { $0 = .now }200 if case .event(let e) = out { continuation.yield(StreamItem(index: e.id, event: ChatStreamEvent(sse: e))) }201 }202 continuation.finish()203 } catch {204 continuation.finish(throwing: error)205 }206 }207 let watchdog = Task.detached(priority: .utility) {208 while !Task.isCancelled {209 try? await Task.sleep(for: .seconds(5))210 if ContinuousClock.now - lastActivity.withLock({ $0 }) > silenceLimit {211 reader.cancel()212 continuation.finish(throwing: URLError(.timedOut))213 return214 }215 }216 }217 continuation.onTermination = { _ in reader.cancel(); watchdog.cancel() }218 }219 }220}221