Skip to content

Commit e63f03c

Browse files
committed
Merge branch 'heartbeat'
# Conflicts: # lib/skyfall/stream.rb
2 parents b6762fd + 8283c29 commit e63f03c

File tree

1 file changed

+22
-2
lines changed

1 file changed

+22
-2
lines changed

lib/skyfall/stream.rb

+22-2
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,11 @@ class Stream
1414
:subscribe_labels => SUBSCRIBE_LABELS
1515
}
1616

17-
EVENTS = %w(message raw_message connecting connect disconnect reconnect error)
17+
EVENTS = %w(message raw_message connecting connect disconnect reconnect error timeout)
1818

1919
MAX_RECONNECT_INTERVAL = 300
2020

21-
attr_accessor :heartbeat_timeout, :heartbeat_interval, :cursor, :auto_reconnect
21+
attr_accessor :heartbeat_timeout, :heartbeat_interval, :cursor, :auto_reconnect, :last_update
2222

2323
def initialize(server, endpoint, cursor = nil)
2424
@endpoint = check_endpoint(endpoint)
@@ -27,6 +27,9 @@ def initialize(server, endpoint, cursor = nil)
2727
@handlers = {}
2828
@auto_reconnect = true
2929
@connection_attempts = 0
30+
@heartbeat_interval = 10
31+
@heartbeat_timeout = 300
32+
@last_update = nil
3033

3134
@handlers[:error] = proc { |e| puts "ERROR: #{e}" }
3235
end
@@ -51,11 +54,14 @@ def connect
5154

5255
@ws.on(:open) do |e|
5356
@handlers[:connect]&.call
57+
@last_update = Time.now
58+
start_heartbeat_timer
5459
end
5560

5661
@ws.on(:message) do |msg|
5762
@reconnecting = false
5863
@connection_attempts = 0
64+
@last_update = Time.now
5965

6066
data = msg.data.pack('C*')
6167
@handlers[:raw_message]&.call(data)
@@ -110,6 +116,20 @@ def disconnect
110116

111117
alias close disconnect
112118

119+
def start_heartbeat_timer
120+
return if @timer || @heartbeat_interval.to_f <= 0 || @heartbeat_timeout.to_f <= 0
121+
122+
@timer = EM::PeriodicTimer.new(@heartbeat_interval) do
123+
next if @ws.nil? || @heartbeat_timeout.to_f <= 0
124+
time_passed = Time.now - @last_update
125+
126+
if time_passed > @heartbeat_timeout
127+
@handlers[:timeout]&.call
128+
reconnect
129+
end
130+
end
131+
end
132+
113133
EVENTS.each do |event|
114134
define_method "on_#{event}" do |&block|
115135
@handlers[event.to_sym] = block

0 commit comments

Comments
 (0)