Skip to content

Commit

Permalink
Add keepalive SQL query to Notifier (#1423)
Browse files Browse the repository at this point in the history
  • Loading branch information
bensheldon authored Jul 15, 2024
1 parent 3841852 commit 2dcb518
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
7 changes: 7 additions & 0 deletions lib/good_job/notifier.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ class Notifier
RECONNECT_INTERVAL = 5
# Number of consecutive connection errors before reporting an error
CONNECTION_ERRORS_REPORTING_THRESHOLD = 6
# Interval for emitting a noop SQL query to keep the connection alive
KEEPALIVE_INTERVAL = 10

# Connection errors that will wait {RECONNECT_INTERVAL} before reconnecting
CONNECTION_ERRORS = %w[
Expand Down Expand Up @@ -78,6 +80,7 @@ def initialize(*recipients, enable_listening: true, capsule: GoodJob.capsule, ex
@enable_listening = enable_listening
@task = nil
@capsule = capsule
@last_keepalive_time = Time.current

start
self.class.instances << self
Expand Down Expand Up @@ -269,6 +272,10 @@ def wait_for_notify
raw_connection.wait_for_notify(WAIT_INTERVAL) do |channel, _pid, payload|
yield(channel, payload)
end
if Time.current - @last_keepalive_time >= KEEPALIVE_INTERVAL
raw_connection.async_exec("SELECT 1")
@last_keepalive_time = Time.current
end
elsif @enable_listening && raw_connection.respond_to?(:jdbc_connection)
raw_connection.execute_query("SELECT 1")
notifications = raw_connection.jdbc_connection.getNotifications
Expand Down
14 changes: 14 additions & 0 deletions spec/lib/good_job/notifier_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,20 @@

notifier.shutdown
end

it 'executes a noop SQL query every 10 seconds to keep the connection alive' do
stub_const("GoodJob::Notifier::KEEPALIVE_INTERVAL", 0.1)
stub_const("GoodJob::Notifier::WAIT_INTERVAL", 0.1)

notifier = described_class.new(enable_listening: true)
original_keepalive = notifier.instance_variable_get(:@last_keepalive_time)

expect(notifier).to be_listening(timeout: 2)
sleep 0.2
expect(notifier.instance_variable_get(:@last_keepalive_time)).to be > original_keepalive

notifier.shutdown
end
end

describe '#shutdown' do
Expand Down

0 comments on commit 2dcb518

Please sign in to comment.