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::ConnectionNotEstablished,
    ::ActiveRecord::ConnectionTimeoutError,
    ::ActiveRecord::JDBCError,
    ::ActiveRecord::StatementInvalid,
    Mysql::Error,
    Mysql2::Error,
    PG::Error,
    PGError,
    SQLite3::Exception
]

Instance Method Summary collapse

Instance Method Details

#check_database_is_connectedObject



68
69
70
71
# File 'lib/rpush/daemon/store/active_record/reconnectable.rb', line 68

def check_database_is_connected
  # Simply asking the adapter for the connection state is not sufficient.
  Rpush::Client::ActiveRecord::Notification.exists?
end

#database_connection_lostObject



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/rpush/daemon/store/active_record/reconnectable.rb', line 46

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



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

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

#sleep_to_avoid_thrashingObject



73
74
75
# File 'lib/rpush/daemon/store/active_record/reconnectable.rb', line 73

def sleep_to_avoid_thrashing
  sleep 2
end

#with_database_reconnect_and_retryObject



35
36
37
38
39
40
41
42
43
44
# File 'lib/rpush/daemon/store/active_record/reconnectable.rb', line 35

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