Class: CodeToQuery::Performance::Cache

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

Overview

Intelligent caching system for query results and parsed intents

Direct Known Subclasses

IntentCache, QueryCache

Defined Under Namespace

Classes: RailsCacheAdapter

Constant Summary collapse

DEFAULT_TTL =

1 hour

3600
MAX_CACHE_SIZE =
1000

Instance Method Summary collapse

Constructor Details

#initialize(config = {}) ⇒ Cache

Returns a new instance of Cache.



12
13
14
15
16
17
18
# File 'lib/code_to_query/performance/cache.rb', line 12

def initialize(config = {})
  @config = config
  @cache_store = build_cache_store
  @hit_count = 0
  @miss_count = 0
  @size_limit = config[:max_size] || MAX_CACHE_SIZE
end

Instance Method Details

#clearObject



67
68
69
70
71
# File 'lib/code_to_query/performance/cache.rb', line 67

def clear
  @cache_store.clear
  @hit_count = 0
  @miss_count = 0
end

#delete(key) ⇒ Object



62
63
64
65
# File 'lib/code_to_query/performance/cache.rb', line 62

def delete(key)
  cache_key = normalize_key(key)
  @cache_store.delete(cache_key)
end

#get(key, &block) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/code_to_query/performance/cache.rb', line 20

def get(key, &block)
  cache_key = normalize_key(key)

  if (cached_value = @cache_store[cache_key])
    @hit_count += 1
    # update access metadata for LRU
    if cached_value.is_a?(Hash)
      cached_value[:access_count] = (cached_value[:access_count] || 0) + 1
      cached_value[:last_access_at] = Time.now
    end
    return cached_value[:data] if cached_value[:expires_at] > Time.now

    # Expired entry
    @cache_store.delete(cache_key)
  end

  @miss_count += 1

  return nil unless block_given?

  # Generate new value
  value = block.call
  set(key, value)
  value
end

#hit_rateObject



83
84
85
86
87
88
# File 'lib/code_to_query/performance/cache.rb', line 83

def hit_rate
  total_requests = @hit_count + @miss_count
  return 0.0 if total_requests.zero?

  (@hit_count.to_f / total_requests * 100).round(2)
end

#set(key, value, ttl: DEFAULT_TTL) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/code_to_query/performance/cache.rb', line 46

def set(key, value, ttl: DEFAULT_TTL)
  cache_key = normalize_key(key)

  # Evict if at size limit
  evict_if_needed

  @cache_store[cache_key] = {
    data: value,
    created_at: Time.now,
    expires_at: Time.now + ttl,
    access_count: 0
  }

  value
end

#statsObject



73
74
75
76
77
78
79
80
81
# File 'lib/code_to_query/performance/cache.rb', line 73

def stats
  {
    size: @cache_store.size,
    hits: @hit_count,
    misses: @miss_count,
    hit_rate: hit_rate,
    memory_usage: calculate_memory_usage
  }
end