Class: Llmp::Cache
- Inherits:
-
Object
- Object
- Llmp::Cache
- Defined in:
- lib/llmp/cache.rb
Instance Method Summary collapse
- #cache_path(key) ⇒ Object
- #fetch(yaml_content, input_data, force: false) ⇒ Object
-
#initialize ⇒ Cache
constructor
A new instance of Cache.
- #key_for(yaml_content, input_data) ⇒ Object
- #lock_path(key) ⇒ Object
Constructor Details
#initialize ⇒ Cache
Returns a new instance of Cache.
10 11 12 13 14 |
# File 'lib/llmp/cache.rb', line 10 def initialize @cache = Runcom::Cache.new('llmp') @cache_dir = @cache.passive.to_s FileUtils.mkdir_p(@cache_dir) end |
Instance Method Details
#cache_path(key) ⇒ Object
20 21 22 |
# File 'lib/llmp/cache.rb', line 20 def cache_path(key) File.join(@cache_dir, "#{key}.json") end |
#fetch(yaml_content, input_data, force: false) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/llmp/cache.rb', line 28 def fetch(yaml_content, input_data, force: false) key = key_for(yaml_content, input_data) path = cache_path(key) lock_file = lock_path(key) File.open(lock_file, File::CREAT | File::RDWR) do |lf| lf.flock(File::LOCK_EX) # Check cache only if not forced if !force && File.exist?(path) cached = JSON.parse(File.read(path), symbolize_names: true) return cached[:output] end # Cache miss or forced - compute and store atomically output = yield File.write(path, JSON.pretty_generate({ output: })) output end end |
#key_for(yaml_content, input_data) ⇒ Object
16 17 18 |
# File 'lib/llmp/cache.rb', line 16 def key_for(yaml_content, input_data) Digest::SHA256.hexdigest(yaml_content + input_data) end |
#lock_path(key) ⇒ Object
24 25 26 |
# File 'lib/llmp/cache.rb', line 24 def lock_path(key) File.join(@cache_dir, "#{key}.lock") end |