Class: SSHKit::Backend::ConnectionPool::Cache

Inherits:
Object
  • Object
show all
Defined in:
lib/sshkit/backends/connection_pool/cache.rb

Overview

A Cache holds connections for a given key. Each connection is stored along with an expiration time so that its idle duration can be measured.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, idle_timeout, closer) ⇒ Cache

Returns a new instance of Cache.



6
7
8
9
10
11
12
# File 'lib/sshkit/backends/connection_pool/cache.rb', line 6

def initialize(key, idle_timeout, closer)
  @key = key
  @connections = []
  @connections.extend(MonitorMixin)
  @idle_timeout = idle_timeout
  @closer = closer
end

Instance Attribute Details

#keyObject

Returns the value of attribute key.



4
5
6
# File 'lib/sshkit/backends/connection_pool/cache.rb', line 4

def key
  @key
end

Instance Method Details

#clearObject

Close all connections and completely clear the cache.



52
53
54
55
56
57
# File 'lib/sshkit/backends/connection_pool/cache.rb', line 52

def clear
  connections.synchronize do
    connections.map(&:last).each(&closer)
    connections.clear
  end
end

#evictObject

Close and remove any connections in this Cache that have been idle for too long.



36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/sshkit/backends/connection_pool/cache.rb', line 36

def evict
  # Peek at the first connection to see if it is still fresh. If so, we can
  # return right away without needing to use `synchronize`.
  first_expires_at, _first_conn = connections.first
  return if (first_expires_at.nil? || fresh?(first_expires_at))

  connections.synchronize do
    fresh, stale = connections.partition do |expires_at, conn|
      fresh?(expires_at) && !closed?(conn)
    end
    connections.replace(fresh)
    stale.each { |_, conn| closer.call(conn) }
  end
end

#popObject

Remove and return a fresh connection from this Cache. Returns ‘nil` if the Cache is empty or if all existing connections have gone stale.



16
17
18
19
20
21
22
# File 'lib/sshkit/backends/connection_pool/cache.rb', line 16

def pop
  connections.synchronize do
    evict
    _, connection = connections.pop
    connection
  end
end

#push(conn) ⇒ Object

Return a connection to this Cache.



25
26
27
28
29
30
31
32
# File 'lib/sshkit/backends/connection_pool/cache.rb', line 25

def push(conn)
  # No need to cache if the connection has already been closed.
  return if closed?(conn)

  connections.synchronize do
    connections.push([Time.now + idle_timeout, conn])
  end
end

#same_key?(other_key) ⇒ Boolean

Returns:

  • (Boolean)


59
60
61
# File 'lib/sshkit/backends/connection_pool/cache.rb', line 59

def same_key?(other_key)
  key == other_key
end