Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add keepalive SQL query to Notifier #1423

Merged
merged 1 commit into from
Jul 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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