SPB Git

Repository Public

SSEParser.swift 4.2 KB 112 lines swift

1// SP Notes Core2// File: Sources/SPNotesAPI/SSEParser.swift3// Description: Incremental server-sent events parser: bytes in (any chunking), events out. Handles LF, CRLF and CR4//              line ends, multi-line data, comments, and the `[DONE]` terminator of the backend.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910/// One dispatched server-sent event.11public struct SSEEvent: Equatable, Sendable {12    /// The `event:` field (`message` when absent).13    public var event: String14    /// The `data:` lines joined with `\n`.15    public var data: String16    /// The last `id:` seen on the stream, if any.17    public var id: String?1819    public init(event: String = "message", data: String, id: String? = nil) {20        self.event = event21        self.data = data22        self.id = id23    }2425    /// `data: [DONE]` — the terminator the backend sends before closing an AI stream.26    public var isDone: Bool { data == "[DONE]" }27}2829/// Byte-level SSE parser. Text is decoded one complete line at a time, so a network chunk may end anywhere, including30/// in the middle of a UTF-8 sequence or between the `\r` and the `\n` of a line end.31public struct SSEParser: Sendable {32    private var line: [UInt8] = []33    private var dataLines: [String] = []34    private var hasData = false35    private var eventName = ""36    private var lastID: String?37    private var previousWasCR = false38    private var atStreamStart = true3940    public init() { line.reserveCapacity(1024) }4142    /// Feeds a chunk and returns the events it completes, in order.43    public mutating func feed<S: Sequence>(_ bytes: S) -> [SSEEvent] where S.Element == UInt8 {44        var out: [SSEEvent] = []45        for byte in bytes { if let event = feed(byte: byte) { out.append(event) } }46        return out47    }4849    /// Feeds one byte; returns an event when this byte completes one.50    public mutating func feed(byte: UInt8) -> SSEEvent? {51        switch byte {52        case 0x0A:53            if previousWasCR { previousWasCR = false; return nil }   // the LF of a CRLF: the line already ended54            return endLine()55        case 0x0D:56            previousWasCR = true57            return endLine()58        default:59            previousWasCR = false60            line.append(byte)61            return nil62        }63    }6465    /// Call when the stream ends: flushes an unterminated last line and a pending event (tolerance for servers that66    /// close right after `data: [DONE]` without the final blank line).67    public mutating func finish() -> SSEEvent? {68        if !line.isEmpty, let event = endLine() { return event }69        return dispatch()70    }7172    // MARK: private7374    private mutating func endLine() -> SSEEvent? {75        defer { line.removeAll(keepingCapacity: true) }76        if atStreamStart {77            atStreamStart = false78            if line.starts(with: [0xEF, 0xBB, 0xBF]) { line.removeFirst(3) }   // byte order mark79        }80        if line.isEmpty { return dispatch() }81        if line[0] == 0x3A { return nil }                                      // comment / heartbeat82        let name: ArraySlice<UInt8>83        var value: ArraySlice<UInt8>84        if let colon = line.firstIndex(of: 0x3A) {85            name = line[..<colon]86            value = line[(colon + 1)...]87            if value.first == 0x20 { value = value.dropFirst() }88        } else {89            name = line[...]90            value = []91        }92        switch String(decoding: name, as: UTF8.self) {93        case "data":94            dataLines.append(String(decoding: value, as: UTF8.self))95            hasData = true96        case "event":97            eventName = String(decoding: value, as: UTF8.self)98        case "id":99            if !value.contains(0) { lastID = String(decoding: value, as: UTF8.self) }100        default:101            break                                                              // "retry" and unknown fields102        }103        return nil104    }105106    private mutating func dispatch() -> SSEEvent? {107        defer { dataLines.removeAll(keepingCapacity: true); hasData = false; eventName = "" }108        guard hasData else { return nil }109        return SSEEvent(event: eventName.isEmpty ? "message" : eventName, data: dataLines.joined(separator: "\n"), id: lastID)110    }111}112
Files main
Menu

Theme