Class: Terret::OpenRouter::SSE::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/terret/openrouter/sse.rb

Overview

Incremental server-sent-events parser. Fed raw transport chunks with boundaries wherever the network put them; yields one data payload per event (multi-line data joined per the SSE spec). Comment lines and non-data fields are ignored — OpenRouter uses comments as keep-alives.

Instance Method Summary collapse

Constructor Details

#initialize ⇒ Parser

Returns a new instance of Parser.



11
12
13
14
# File 'lib/terret/openrouter/sse.rb', line 11

def initialize
  @buffer = +""
  @data = []
end

Instance Method Details

#feed(chunk) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/terret/openrouter/sse.rb', line 16

def feed(chunk)
  @buffer << chunk
  while (line, rest = @buffer.split("\n", 2)) && rest
    @buffer = rest
    line.chomp!("\r")
    if line.empty?
      yield @data.join("\n") unless @data.empty?
      @data.clear
    elsif line.start_with?("data:")
      @data << line.delete_prefix("data:").sub(/\A /, "")
    end
  end
  nil
end