module Sequel::ConnectionExpiration

Attributes

connection_expiration_random_delay[RW]

The maximum number of seconds that will be added as a random delay to the expiration timeout Defaults to 0 seconds (no random delay).

connection_expiration_timeout[RW]

The number of seconds that need to pass since connection creation before expiring a connection. Defaults to 14400 seconds (4 hours).

Public Class Methods

extended(pool) click to toggle source

Initialize the data structures used by this extension.

# File lib/sequel/extensions/connection_expiration.rb, line 46
def self.extended(pool)
  case pool.pool_type
  when :single, :sharded_single
    raise Error, "cannot load connection_expiration extension if using single or sharded_single connection pool"
  end

  pool.instance_exec do
    sync do
      @connection_expiration_timestamps ||= {}
      @connection_expiration_timeout ||= 14400
      @connection_expiration_random_delay ||= 0
    end
  end
end

Private Instance Methods

acquire(*a) click to toggle source

When acquiring a connection, check if the connection is expired. If it is expired, disconnect the connection, and retry with a new connection.

Calls superclass method
# File lib/sequel/extensions/connection_expiration.rb, line 79
def acquire(*a)
  conn = nil
  1.times do
    if (conn = super) &&
       (cet = sync{@connection_expiration_timestamps[conn]}) &&
       Sequel.elapsed_seconds_since(cet[0]) > cet[1]

      case pool_type
      when :sharded_threaded, :sharded_timed_queue
        sync{@allocated[a.last].delete(Sequel.current)}
      else
        sync{@allocated.delete(Sequel.current)}
      end

      disconnect_connection(conn)
      redo
    end
  end

  conn
end
disconnect_connection(conn) click to toggle source

Clean up expiration timestamps during disconnect.

Calls superclass method
# File lib/sequel/extensions/connection_expiration.rb, line 64
def disconnect_connection(conn)
  sync{@connection_expiration_timestamps.delete(conn)}
  super
end
make_new(*) click to toggle source

Record the time the connection was created.

Calls superclass method
# File lib/sequel/extensions/connection_expiration.rb, line 70
def make_new(*)
  conn = super
  @connection_expiration_timestamps[conn] = [Sequel.start_timer, @connection_expiration_timeout + (rand * @connection_expiration_random_delay)].freeze
  conn
end