Module: Rapns::Daemon::DatabaseReconnectable

Included in:
DeliveryHandler, Feeder
Defined in:
lib/rapns/daemon/database_reconnectable.rb

Constant Summary collapse

ADAPTER_ERRORS =
[ActiveRecord::StatementInvalid, PGError, Mysql::Error, Mysql2::Error]

Instance Method Summary collapse

Instance Method Details

#check_database_is_connectedObject



42
43
44
45
# File 'lib/rapns/daemon/database_reconnectable.rb', line 42

def check_database_is_connected
  # Simply asking the adapter for the connection state is not sufficient.
  Rapns::Notification.count
end

#database_connection_lostObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/rapns/daemon/database_reconnectable.rb', line 20

def database_connection_lost
  Rapns::Daemon.logger.warn("[#{name}] Lost connection to database, reconnecting...")
  attempts = 0
  loop do
    begin
      Rapns::Daemon.logger.warn("[#{name}] Attempt #{attempts += 1}")
      reconnect_database
      check_database_is_connected
      break
    rescue *ADAPTER_ERRORS => e
      Rapns::Daemon.logger.error(e, :airbrake_notify => false)
      sleep_to_avoid_thrashing
    end
  end
  Rapns::Daemon.logger.warn("[#{name}] Database reconnected")
end

#reconnect_databaseObject



37
38
39
40
# File 'lib/rapns/daemon/database_reconnectable.rb', line 37

def reconnect_database
  ActiveRecord::Base.clear_all_connections!
  ActiveRecord::Base.establish_connection
end

#sleep_to_avoid_thrashingObject



47
48
49
# File 'lib/rapns/daemon/database_reconnectable.rb', line 47

def sleep_to_avoid_thrashing
  sleep 2
end

#with_database_reconnect_and_retryObject



10
11
12
13
14
15
16
17
18
# File 'lib/rapns/daemon/database_reconnectable.rb', line 10

def with_database_reconnect_and_retry
  begin
    yield
  rescue *ADAPTER_ERRORS => e
    Rapns::Daemon.logger.error(e)
    database_connection_lost
    retry
  end
end