Class: Bolt::Plugin::Cache

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(reference, plugin_cache_file, default_config) ⇒ Cache

Returns a new instance of Cache.



12
13
14
15
16
# File 'lib/bolt/plugin/cache.rb', line 12

def initialize(reference, plugin_cache_file, default_config)
  @reference = reference
  @plugin_cache_file = plugin_cache_file
  @default_config = default_config
end

Instance Attribute Details

#default_configObject (readonly)

Returns the value of attribute default_config.



10
11
12
# File 'lib/bolt/plugin/cache.rb', line 10

def default_config
  @default_config
end

#idObject (readonly)

Returns the value of attribute id.



10
11
12
# File 'lib/bolt/plugin/cache.rb', line 10

def id
  @id
end

#plugin_cache_fileObject (readonly)

Returns the value of attribute plugin_cache_file.



10
11
12
# File 'lib/bolt/plugin/cache.rb', line 10

def plugin_cache_file
  @plugin_cache_file
end

#referenceObject (readonly)

Returns the value of attribute reference.



10
11
12
# File 'lib/bolt/plugin/cache.rb', line 10

def reference
  @reference
end

Instance Method Details

#read_and_clean_cacheObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/bolt/plugin/cache.rb', line 18

def read_and_clean_cache
  return if ttl == 0
  validate

  # Luckily we don't need to use a serious hash algorithm
  require 'digest/bubblebabble'
  r = reference.reject { |k, _| k == '_cache' }.sort.to_s
  @id = Digest::SHA2.bubblebabble(r)[0..20]

  unmodified = true
  # First remove any cache entries past their ttl
  # This prevents removing plugins from leaving orphaned cache entries
  cache.delete_if do |_, entry|
    expired = Time.now - Time.parse(entry['mtime']) >= entry['ttl']
    unmodified = false if expired
    expired
  end
  File.write(plugin_cache_file, cache.to_json) unless cache.empty? || unmodified

  cache.dig(id, 'result')
end

#validateObject



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/bolt/plugin/cache.rb', line 52

def validate
  # The default cache `plugin-cache` will be validated by the config
  # validator
  return if reference['_cache'].nil?
  r = reference['_cache']
  unless r.is_a?(Hash)
    raise Bolt::ValidationError,
          "_cache must be a Hash, received #{r.class}: #{r.inspect}"
  end

  unless r.key?('ttl')
    raise Bolt::ValidationError, "_cache must set 'ttl' key."
  end

  unless r['ttl'] >= 0
    raise Bolt::ValidationError, "'ttl' key under '_cache' must be a minimum of 0."
  end
end

#write_cache(result) ⇒ Object



44
45
46
47
48
49
50
# File 'lib/bolt/plugin/cache.rb', line 44

def write_cache(result)
  cache.merge!({ id => { 'result' => result,
                         'mtime' => Time.now,
                         'ttl' => ttl } })
  FileUtils.touch(plugin_cache_file)
  File.write(plugin_cache_file, cache.to_json)
end