Module: Ration::SSE

Defined in:
lib/ration/sse.rb

Constant Summary collapse

DEFAULT_ID_FROM =
->(event) { event[:id] }

Class Method Summary collapse

Class Method Details

.comment(text = '') ⇒ Object



39
40
41
42
# File 'lib/ration/sse.rb', line 39

def comment(text = '')
  ensure_no_newline!(text.to_s, 'comment')
  ": #{text}\n\n"
end

.event(data:, event: nil, id: nil, retry_ms: nil) ⇒ Object

Raises:

  • (ArgumentError)


8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/ration/sse.rb', line 8

def event(data:, event: nil, id: nil, retry_ms: nil)
  raise ArgumentError, 'data is required' if data.nil?

  lines = []

  if event
    ensure_field_value_safe!(event.to_s, 'event')
    lines << "event: #{event}"
  end

  if id
    ensure_field_value_safe!(id.to_s, 'id')
    lines << "id: #{id}"
  end

  unless retry_ms.nil?
    unless retry_ms.is_a?(Integer) && retry_ms >= 0
      raise ArgumentError, 'retry_ms must be a non-negative Integer'
    end

    lines << "retry: #{retry_ms}"
  end

  payload = data.is_a?(String) ? data : data.to_json
  payload.split("\n", -1).each do |line|
    lines << "data: #{line}"
  end

  lines.join("\n") + "\n\n"
end

.pingObject



44
45
46
# File 'lib/ration/sse.rb', line 44

def ping
  ": ping\n\n"
end

.stream(subscription, output, heartbeat: 15, since: nil, id_from: DEFAULT_ID_FROM) ⇒ Object

Raises:

  • (ArgumentError)


48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/ration/sse.rb', line 48

def stream(
  subscription,
  output,
  heartbeat: 15,
  since:     nil,
  id_from:   DEFAULT_ID_FROM
)
  raise ArgumentError, 'block required' unless block_given?

  last = since

  subscription.each_event(timeout: heartbeat) do |event|
    if event.nil?
      output << ping if heartbeat
      next
    end

    if last
      id = id_from.call(event)
      next if id.nil? || id <= last

      last = id
    end

    framed = yield(event)
    output << framed if framed
  end

  last
end