Class: RailVerdict::Intelligence::Cache

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

Constant Summary collapse

MAX_TOTAL_BYTES =
10 * 1024 * 1024

Instance Method Summary collapse

Constructor Details

#initialize(root:, enabled: false) ⇒ Cache

Returns a new instance of Cache.



13
14
15
16
17
# File 'lib/rail_verdict/intelligence/cache.rb', line 13

def initialize(root:, enabled: false)
  @root = root.to_s
  @enabled = enabled
  @dir = File.join(@root, ".railverdict", "cache", "ai")
end

Instance Method Details

#enabled?Boolean

Returns:

  • (Boolean)


19
20
21
# File 'lib/rail_verdict/intelligence/cache.rb', line 19

def enabled?
  @enabled
end

#key_for(fingerprint:, context_hash:, provider:, model:, prompt_version:, schema_version:) ⇒ Object



23
24
25
# File 'lib/rail_verdict/intelligence/cache.rb', line 23

def key_for(fingerprint:, context_hash:, provider:, model:, prompt_version:, schema_version:)
  Digest::SHA256.hexdigest([fingerprint, context_hash, provider, model, prompt_version, schema_version].join("|"))
end

#read(key) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/rail_verdict/intelligence/cache.rb', line 27

def read(key)
  return nil unless @enabled

  path = File.join(@dir, "#{key}.json")
  return nil unless File.file?(path)

  data = JSON.parse(File.read(path))
  AIAnalysis.from_hash(data)
rescue StandardError
  nil
end

#write(key, analysis) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/rail_verdict/intelligence/cache.rb', line 39

def write(key, analysis)
  return unless @enabled

  FileUtils.mkdir_p(@dir)
  path = File.join(@dir, "#{key}.json")
  tmp = Tempfile.new(["ai-cache", ".json"], @dir)
  begin
    tmp.write(JSON.generate(analysis.to_h))
    tmp.flush
    tmp.fsync
    File.chmod(0o600, tmp.path)
    File.rename(tmp.path, path)
    File.chmod(0o600, path) rescue nil
    enforce_size_limit
  ensure
    tmp.close rescue nil
    File.unlink(tmp.path) rescue nil
  end
end