Class: SemanticCache::Stores::Memory
- Inherits:
-
Object
- Object
- SemanticCache::Stores::Memory
- Includes:
- MonitorMixin
- Defined in:
- lib/semantic_cache/stores/memory.rb
Overview
Thread-safe in-memory cache store. Good for development, testing, and single-process apps.
Options:
max_size: Maximum number of entries to keep. When exceeded, the oldest
entry (by created_at) is evicted. nil = unlimited.
Instance Method Summary collapse
-
#clear ⇒ Object
Delete all entries.
-
#delete(key) ⇒ Object
Delete a specific entry by key.
-
#entries ⇒ Object
Retrieve all non-expired entries.
-
#initialize(max_size: nil, **_options) ⇒ Memory
constructor
A new instance of Memory.
-
#invalidate_by_tags(tags) ⇒ Object
Delete all entries matching the given tags.
-
#size ⇒ Object
Number of entries in the store.
-
#write(key, entry) ⇒ Object
Store a cache entry.
Constructor Details
#initialize(max_size: nil, **_options) ⇒ Memory
Returns a new instance of Memory.
16 17 18 19 20 21 |
# File 'lib/semantic_cache/stores/memory.rb', line 16 def initialize(max_size: nil, **) super() @data = {} @tags_index = Hash.new { |h, k| h[k] = Set.new } @max_size = max_size end |
Instance Method Details
#clear ⇒ Object
Delete all entries.
61 62 63 64 65 66 |
# File 'lib/semantic_cache/stores/memory.rb', line 61 def clear synchronize do @data.clear @tags_index.clear end end |
#delete(key) ⇒ Object
Delete a specific entry by key.
42 43 44 45 46 47 |
# File 'lib/semantic_cache/stores/memory.rb', line 42 def delete(key) synchronize do entry = @data.delete(key) entry&.&.each { |tag| @tags_index[tag].delete(key) } end end |
#entries ⇒ Object
Retrieve all non-expired entries. Returns an Array of Entry objects.
34 35 36 37 38 39 |
# File 'lib/semantic_cache/stores/memory.rb', line 34 def entries synchronize do cleanup_expired! @data.values end end |
#invalidate_by_tags(tags) ⇒ Object
Delete all entries matching the given tags.
50 51 52 53 54 55 56 57 58 |
# File 'lib/semantic_cache/stores/memory.rb', line 50 def () synchronize do Array().each do |tag| keys = @tags_index[tag].to_a keys.each { |key| @data.delete(key) } @tags_index.delete(tag) end end end |
#size ⇒ Object
Number of entries in the store.
69 70 71 72 73 74 |
# File 'lib/semantic_cache/stores/memory.rb', line 69 def size synchronize do cleanup_expired! @data.size end end |
#write(key, entry) ⇒ Object
Store a cache entry. Evicts the oldest entry if max_size is reached.
24 25 26 27 28 29 30 |
# File 'lib/semantic_cache/stores/memory.rb', line 24 def write(key, entry) synchronize do evict_oldest! if @max_size && @data.size >= @max_size && !@data.key?(key) @data[key] = entry entry..each { |tag| @tags_index[tag].add(key) } end end |