Module: Rpush::Daemon::Store::ActiveRecord::Reconnectable

Included in:
Rpush::Daemon::Store::ActiveRecord
Defined in:
lib/rpush/daemon/store/active_record/reconnectable.rb

Constant Summary collapse

ADAPTER_ERRORS =
[::ActiveRecord::StatementInvalid, PGError, PG::Error,
Mysql::Error, Mysql2::Error, ::ActiveRecord::JDBCError,
SQLite3::Exception, ::ActiveRecord::ConnectionTimeoutError]

Instance Method Summary collapse

Instance Method Details

#check_database_is_connectedObject


60
61
62
63
# File 'lib/rpush/daemon/store/active_record/reconnectable.rb', line 60

def check_database_is_connected  # Simply asking the adapter for the connection state is not sufficient.

  Rpush::Client::ActiveRecord::Notification.count
end

#database_connection_lostObject


38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/rpush/daemon/store/active_record/reconnectable.rb', line 38

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

#reconnect_databaseObject


55
56
57
58
# File 'lib/rpush/daemon/store/active_record/reconnectable.rb', line 55

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

#sleep_to_avoid_thrashingObject


65
66
67
# File 'lib/rpush/daemon/store/active_record/reconnectable.rb', line 65

def sleep_to_avoid_thrashing
  sleep 2
end

#with_database_reconnect_and_retryObject


27
28
29
30
31
32
33
34
35
36
# File 'lib/rpush/daemon/store/active_record/reconnectable.rb', line 27

def with_database_reconnect_and_retry
  ::ActiveRecord::Base.connection_pool.with_connection do
    yield
  end
rescue *ADAPTER_ERRORS => e
  Rpush.logger.error(e)
  sleep_to_avoid_thrashing
  database_connection_lost
  retry
end