Class: Caddy::Cache

Inherits:
Object
  • Object
show all
Defined in:
lib/caddy/cache.rb

Constant Summary collapse

DEFAULT_REFRESH_INTERVAL =
60
REFRESH_INTERVAL_JITTER_PCT =
0.15

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ Cache

Returns a new instance of Cache.



9
10
11
12
13
14
# File 'lib/caddy/cache.rb', line 9

def initialize(key)
  @task = nil
  @refresh_interval = DEFAULT_REFRESH_INTERVAL
  @cache = nil
  @key = key
end

Instance Attribute Details

#error_handlerObject

Returns the value of attribute error_handler.



7
8
9
# File 'lib/caddy/cache.rb', line 7

def error_handler
  @error_handler
end

#refresh_intervalObject

Returns the value of attribute refresh_interval.



7
8
9
# File 'lib/caddy/cache.rb', line 7

def refresh_interval
  @refresh_interval
end

#refresherObject

Returns the value of attribute refresher.



7
8
9
# File 'lib/caddy/cache.rb', line 7

def refresher
  @refresher
end

Instance Method Details

#[](k) ⇒ Object



16
17
18
# File 'lib/caddy/cache.rb', line 16

def [](k)
  cache[k]
end

#cacheObject



20
21
22
23
24
25
# File 'lib/caddy/cache.rb', line 20

def cache
  raise "Please run `Caddy.start` before attempting to access the cache" unless @task && @task.running?
  raise "Caddy cache access of :#{@key} before initial load; allow some more time for your app to start up" unless @cache

  @cache
end

#startObject



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/caddy/cache.rb', line 27

def start
  unless refresher && refresher.respond_to?(:call)
    raise "Please set your cache refresher via `Caddy[:#{@key}].refresher = -> { <code that returns a value> }`"
  end

  raise "`Caddy[:#{@key}].refresh_interval` must be > 0" unless refresh_interval > 0

  jitter_amount = [0.1, refresh_interval * REFRESH_INTERVAL_JITTER_PCT].max
  interval = refresh_interval + rand(-jitter_amount...jitter_amount)
  timeout_interval = [interval - 1, 0.1].max

  stop # stop any existing task from running

  @task = Concurrent::TimerTask.new(
    run_now: true,
    execution_interval: interval,
    timeout_interval: timeout_interval
  ) do
    begin
      @cache = refresher.call.freeze
    rescue
      raise
    end
  end

  @task.add_observer(Caddy::TaskObserver.new(error_handler, @key))
  @task.execute

  @task.running?
end

#stopObject



58
59
60
# File 'lib/caddy/cache.rb', line 58

def stop
  @task.shutdown if @task && @task.running?
end