Class: Sidekiq::PgHelpers::Middleware::ConnectionRecovery

Inherits:
Object
  • Object
show all
Defined in:
lib/sidekiq/pg_helpers/middleware/connection_recovery.rb

Instance Method Summary collapse

Constructor Details

#initializeConnectionRecovery

Returns a new instance of ConnectionRecovery.



8
9
10
# File 'lib/sidekiq/pg_helpers/middleware/connection_recovery.rb', line 8

def initialize
  @reconnection_attempts = 0
end

Instance Method Details

#call(*args) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/sidekiq/pg_helpers/middleware/connection_recovery.rb', line 12

def call(*args)
  yield
rescue PG::ConnectionBad, PG::UnableToSend => e
  if @reconnection_attempts >= 4
    Sidekiq.logger.error "Unable to re-establish Postgres connection after five attempts, giving up"
    raise
  end

  Sidekiq.logger.warn "Received #{e.class}, disconnecting and cleaning up our Postgres connection before re-trying"

  # Probably due to an abrupt disconnection: https://devcenter.heroku.com/articles/postgres-logs-errors#pgerror-ssl-syscall-error-eof-detected
  # The next time we access an ActiveRecord connection, it should automatically check out a fresh connection to replace this one
  connection = ActiveRecord::Base.connection
  connection.disconnect!
  ActiveRecord::Base.connection_pool.remove(connection)

  # Ensure we get a fresh connection the next time we access an activerecord object
  ActiveRecord::Base.clear_active_connections!

  @reconnection_attempts += 1
  retry
end