Class: Schematic::LocalCache
- Inherits:
-
Object
- Object
- Schematic::LocalCache
- Includes:
- CacheProvider
- Defined in:
- lib/schematic/cache.rb
Defined Under Namespace
Classes: CacheEntry
Constant Summary collapse
- DEFAULT_MAX_SIZE =
1000- DEFAULT_TTL =
seconds
5.0
Instance Method Summary collapse
- #delete(key) ⇒ Object
- #delete_missing(keys_to_keep, scope:) ⇒ Object
- #get(key) ⇒ Object
-
#initialize(max_size: DEFAULT_MAX_SIZE, ttl: DEFAULT_TTL) ⇒ LocalCache
constructor
A new instance of LocalCache.
- #set(key, value, ttl: nil) ⇒ Object
- #size ⇒ Object
- #stop ⇒ Object
Constructor Details
#initialize(max_size: DEFAULT_MAX_SIZE, ttl: DEFAULT_TTL) ⇒ LocalCache
Returns a new instance of LocalCache.
31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/schematic/cache.rb', line 31 def initialize(max_size: DEFAULT_MAX_SIZE, ttl: DEFAULT_TTL) @max_size = max_size @ttl = ttl # Ruby's Hash maintains insertion order, so we use it as an ordered map. # Re-inserting a key moves it to the end, giving us O(1) LRU touch. @cache = {} # key => CacheEntry (insertion order = LRU order) @mutex = Mutex.new @stopped = false start_cleanup if @max_size.positive? && @ttl.positive? end |
Instance Method Details
#delete(key) ⇒ Object
72 73 74 75 76 |
# File 'lib/schematic/cache.rb', line 72 def delete(key) @mutex.synchronize do @cache.delete(key) end end |
#delete_missing(keys_to_keep, scope:) ⇒ Object
78 79 80 81 82 83 |
# File 'lib/schematic/cache.rb', line 78 def delete_missing(keys_to_keep, scope:) keep_set = keys_to_keep.to_set @mutex.synchronize do @cache.delete_if { |k, _| k.start_with?(scope) && !keep_set.include?(k) } end end |
#get(key) ⇒ Object
43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/schematic/cache.rb', line 43 def get(key) @mutex.synchronize do entry = @cache[key] return nil unless entry if entry.expired? @cache.delete(key) return nil end touch(key) entry.value end end |
#set(key, value, ttl: nil) ⇒ Object
57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
# File 'lib/schematic/cache.rb', line 57 def set(key, value, ttl: nil) @mutex.synchronize do effective_ttl = ttl || @ttl return if @max_size <= 0 if @cache.key?(key) @cache.delete(key) @cache[key] = CacheEntry.new(value, effective_ttl) else evict_lru while @cache.size >= @max_size @cache[key] = CacheEntry.new(value, effective_ttl) end end end |
#size ⇒ Object
85 86 87 |
# File 'lib/schematic/cache.rb', line 85 def size @mutex.synchronize { @cache.size } end |
#stop ⇒ Object
89 90 91 |
# File 'lib/schematic/cache.rb', line 89 def stop @mutex.synchronize { @stopped = true } end |