Class: HTTPClient::LRUCache

Inherits:
Object
  • Object
show all
Defined in:
lib/httpclient/lru_cache.rb

Defined Under Namespace

Classes: Datum

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ LRUCache

Returns a new instance of LRUCache.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/httpclient/lru_cache.rb', line 14

def initialize(opts={})
  @mutex = Mutex.new

  @max_size = Integer(opts[:max_size] || 100)
  @ttl = Float(opts[:ttl] || 0)
  @soft_ttl = Float(opts[:soft_ttl] || 0)
  @retry_delay = Float(opts[:retry_delay] || 0)

  raise "max_size must not be negative" if @max_size < 0
  raise "ttl must not be negative" if @ttl < 0
  raise "soft_ttl must not be negative" if @soft_ttl < 0
  raise "retry_delay must not be negative" if @retry_delay < 0

  # we don't use thread safe variant, as we're doing thread safety ourselves
  @data = LruRedux::Cache.new(@max_size)
end

Instance Attribute Details

#max_sizeObject (readonly)

Returns the value of attribute max_size.



12
13
14
# File 'lib/httpclient/lru_cache.rb', line 12

def max_size
  @max_size
end

#retry_delayObject (readonly)

Returns the value of attribute retry_delay.



12
13
14
# File 'lib/httpclient/lru_cache.rb', line 12

def retry_delay
  @retry_delay
end

#soft_ttlObject (readonly)

Returns the value of attribute soft_ttl.



12
13
14
# File 'lib/httpclient/lru_cache.rb', line 12

def soft_ttl
  @soft_ttl
end

#ttlObject (readonly)

Returns the value of attribute ttl.



12
13
14
# File 'lib/httpclient/lru_cache.rb', line 12

def ttl
  @ttl
end

Instance Method Details

#fetch(key) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/httpclient/lru_cache.rb', line 31

def fetch(key)
  # for now, this means that DNS resolving is single-threaded
  @mutex.synchronize do
    datum = @data[key]
    if datum.nil?
      store(key, value = yield)
    elsif datum.expired?
      @data.delete(key)
      store(key, value = yield)
    elsif datum.soft_expired?
      begin
        store(key, value = yield)
      rescue RuntimeError => e
        datum.soft_expiration = (Time.now + retry_delay) if retry_delay > 0
        datum.value
      end
    else
      datum.value
    end
  end
end