@@ -14,11 +14,11 @@ class Stream
14
14
:subscribe_labels => SUBSCRIBE_LABELS
15
15
}
16
16
17
- EVENTS = %w( message raw_message connecting connect disconnect reconnect error )
17
+ EVENTS = %w( message raw_message connecting connect disconnect reconnect error timeout )
18
18
19
19
MAX_RECONNECT_INTERVAL = 300
20
20
21
- attr_accessor :heartbeat_timeout , :heartbeat_interval , :cursor , :auto_reconnect
21
+ attr_accessor :heartbeat_timeout , :heartbeat_interval , :cursor , :auto_reconnect , :last_update
22
22
23
23
def initialize ( server , endpoint , cursor = nil )
24
24
@endpoint = check_endpoint ( endpoint )
@@ -27,6 +27,9 @@ def initialize(server, endpoint, cursor = nil)
27
27
@handlers = { }
28
28
@auto_reconnect = true
29
29
@connection_attempts = 0
30
+ @heartbeat_interval = 10
31
+ @heartbeat_timeout = 300
32
+ @last_update = nil
30
33
31
34
@handlers [ :error ] = proc { |e | puts "ERROR: #{ e } " }
32
35
end
@@ -51,11 +54,14 @@ def connect
51
54
52
55
@ws . on ( :open ) do |e |
53
56
@handlers [ :connect ] &.call
57
+ @last_update = Time . now
58
+ start_heartbeat_timer
54
59
end
55
60
56
61
@ws . on ( :message ) do |msg |
57
62
@reconnecting = false
58
63
@connection_attempts = 0
64
+ @last_update = Time . now
59
65
60
66
data = msg . data . pack ( 'C*' )
61
67
@handlers [ :raw_message ] &.call ( data )
@@ -110,6 +116,20 @@ def disconnect
110
116
111
117
alias close disconnect
112
118
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
+
113
133
EVENTS . each do |event |
114
134
define_method "on_#{ event } " do |&block |
115
135
@handlers [ event . to_sym ] = block
0 commit comments