Class: Mistri::SSE
- Inherits:
-
Object
- Object
- Mistri::SSE
- Defined in:
- lib/mistri/sse.rb
Overview
An incremental Server-Sent Events decoder. Feed it raw socket fragments in any chunking; it buffers partial lines across fragments and yields each complete "data:" record as a parsed Hash.
The decode is deliberately tolerant of what the provider APIs actually send: one single-line JSON object per "data:" record. "event:", "id:", comment, and blank lines are ignored (the event name is duplicated inside the data payload), OpenAI's "[DONE]" sentinel is dropped, and a record that fails to parse is skipped rather than killing a live stream.
Instance Method Summary collapse
- #feed(fragment) ⇒ Object
-
#finish ⇒ Object
Flush a trailing record that arrived without a final newline.
-
#initialize ⇒ SSE
constructor
A new instance of SSE.
Constructor Details
#initialize ⇒ SSE
Returns a new instance of SSE.
16 17 18 |
# File 'lib/mistri/sse.rb', line 16 def initialize @buffer = +"" end |
Instance Method Details
#feed(fragment) ⇒ Object
20 21 22 23 24 25 26 27 |
# File 'lib/mistri/sse.rb', line 20 def feed(fragment, &) @buffer << fragment while (newline = @buffer.index("\n")) line = @buffer.slice!(0, newline + 1) decode(line.chomp, &) end nil end |
#finish ⇒ Object
Flush a trailing record that arrived without a final newline.
30 31 32 33 34 |
# File 'lib/mistri/sse.rb', line 30 def finish(&) decode(@buffer.chomp, &) unless @buffer.empty? @buffer.clear nil end |