Module: Cybertrain::SSE

Defined in:
cybertrain/http/sse.rb

Overview

Server-Sent Events formatting (the text/event-stream format of the HTML standard): one event per call, ready for Cybertrain::Sink#write.

Examples:

stream do |out|
  out.write(Cybertrain::SSE.event(JSON.generate({ "price" => 12 }), event: "tick", id: "7"))
end

Class Method Summary collapse

Class Method Details

.event(data, event: "", id: "", retry_ms: 0) ⇒ String

One event: event:, id: and retry: lines when given, then one data: line per line of data (a CR, LF or CRLF in it starts a new data: line, so the payload cannot end the event early), then the blank line.

Parameters:

  • data (String)
  • event (String) (defaults to: "") —

    the event type (“” for the default message)

  • id (String) (defaults to: "") —

    the last-event id the browser sends back on reconnect

  • retry_ms (Integer) (defaults to: 0) —

    the reconnection delay, 0 to leave it out

Returns:

  • (String)

Raises:

  • (ArgumentError) —

    when event or id holds a CR or LF



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'cybertrain/http/sse.rb', line 21

def self.event(data, event: "", id: "", retry_ms: 0)
  SSE.check_field("event", event)
  SSE.check_field("id", id)
  out = +""
  unless event.empty?
    out << "event: "
    out << event
    out << "\n"
  end
  unless id.empty?
    out << "id: "
    out << id
    out << "\n"
  end
  if retry_ms > 0
    out << "retry: "
    out << retry_ms.to_s
    out << "\n"
  end
  # Returned and appended, never filled through a parameter: a buffer
  # appended to directly loses what helpers append to it (NOTES rule 66).
  out << SSE.data_lines(data.to_s)
  out << "\n"
  out
end