Class: Cybertrain::Sse::Parser
- Inherits:
-
Object
- Object
- Cybertrain::Sse::Parser
- Defined in:
- cybertrain/sse.rb
Overview
The incremental parser. Feed it chunks as they arrive (cut anywhere: mid-line, between a CR and its LF, inside a multi-byte character; it works on bytes and cuts lines only at CR, LF or CRLF); each complete event is yielded. A line is processed as soon as its terminator arrives, so a long line costs time linear in its length.
Rules: a leading UTF-8 BOM is ignored; a line starting with “:” is a
comment; a line without “:” is a field with an empty value; one space
after the colon is dropped; unknown fields are ignored; id holding a
NUL is ignored; retry counts only when it is all ASCII digits (more
than fifteen digits are bounded to 999999999999999); a blank line
dispatches the event unless no data line was seen.
feed and finish yield, so they hold no rescue or ensure
(spikes/NOTES.md rules 32/45): when the block raises, the event it
was given is already consumed and the rest of that chunk is not parsed.
The parser sets no limit on a line or on an event’s data; the
request’s deadline bounds the stream in time, not in memory. With
binary chunks event_data is binary: the caller sets the encoding.
Instance Method Summary collapse
-
#feed(chunk) {|event| ... }
Parses one chunk.
-
#finish {|event| ... }
Ends the stream: a final line without a terminator is read, and an event that was not closed by a blank line is yielded (when it has data).
Instance Method Details
#feed(chunk) {|event| ... }
This method returns an undefined value.
Parses one chunk.
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 |
# File 'cybertrain/sse.rb', line 84 def feed(chunk) n = chunk.bytesize start = 0 i = 0 while i < n b = chunk.getbyte(i) if @skip_lf @skip_lf = false if b == 10 i += 1 start = i next end end if b == 10 || b == 13 @line << chunk.byteslice(start, i - start) if i > start @skip_lf = (b == 13) i += 1 start = i if line_done yield take_event end else i += 1 end end @line << chunk.byteslice(start, n - start) if n > start nil end |
#finish {|event| ... }
This method returns an undefined value.
Ends the stream: a final line without a terminator is read, and an event that was not closed by a blank line is yielded (when it has data). Leaves the parser ready for a new stream.
120 121 122 123 124 125 126 127 128 129 |
# File 'cybertrain/sse.rb', line 120 def finish if @line.bytesize > 0 line_done end if @has_data yield take_event end reset_stream nil end |