Skip to content

Commit e61e661

Browse files
committed
Retry if connection fails
1 parent dd4da0e commit e61e661

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

lib/action_cable/subscription_adapter/solid_cable.rb

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ def listener
3939
end
4040

4141
class Listener < ::ActionCable::SubscriptionAdapter::SubscriberMap
42+
CONNECTION_ERRORS = [ActiveRecord::ConnectionFailed]
4243
Stop = Class.new(Exception)
4344

4445
def initialize(event_loop)
@@ -51,11 +52,17 @@ def initialize(event_loop)
5152
# for specific sections of code, rather than acquired.
5253
@critical = Concurrent::Semaphore.new(0)
5354

55+
@reconnect_attempt = 0
56+
5457
@thread = Thread.new do
5558
Thread.current.name = "solid_cable_listener"
5659
Thread.current.report_on_exception = true
5760

58-
listen
61+
begin
62+
listen
63+
rescue *CONNECTION_ERRORS
64+
retry if retry_connecting?
65+
end
5966
end
6067
end
6168

@@ -107,6 +114,7 @@ def invoke_callback(*)
107114
private
108115
attr_reader :event_loop, :thread
109116
attr_writer :last_id
117+
attr_accessor :reconnect_attempt
110118

111119
def last_id
112120
@last_id ||= last_message_id
@@ -146,6 +154,22 @@ def with_polling_volume
146154
yield
147155
end
148156
end
157+
158+
def reconnect_attempts
159+
@reconnect_attempts ||= ::SolidCable.reconnect_attempts
160+
end
161+
162+
def retry_connecting?
163+
self.reconnect_attempt += 1
164+
165+
return false if reconnect_attempt > reconnect_attempts.size
166+
167+
sleep_t = reconnect_attempts[reconnect_attempt - 1]
168+
169+
sleep(sleep_t) if sleep_t > 0
170+
171+
true
172+
end
149173
end
150174
end
151175
end

lib/solid_cable.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,12 @@ def trim_chance
4848
2
4949
end
5050

51+
def reconnect_attempts
52+
attempts = cable_config.fetch(:reconnect_attempts, 1)
53+
attempts = Array.new(attempts, 0) if attempts.is_a?(Integer)
54+
attempts
55+
end
56+
5157
private
5258
def cable_config
5359
Rails.application.config_for("cable")

0 commit comments

Comments
 (0)