Class: TesoteSdk::CacheBackend

Inherits:
Object
  • Object
show all
Defined in:
lib/tesote_sdk/transport.rb

Overview

Minimal LRU + TTL cache. Duck-typed: any object responding to #read(key) and #write(key, value, ttl:) can be passed via :cache_backend.

Defined Under Namespace

Classes: Entry

Instance Method Summary collapse

Constructor Details

#initialize(max_size: 256) ⇒ CacheBackend

Returns a new instance of CacheBackend.



18
19
20
21
22
# File 'lib/tesote_sdk/transport.rb', line 18

def initialize(max_size: 256)
  @max_size = max_size
  @data = {}
  @mutex = Mutex.new
end

Instance Method Details

#clearObject



46
47
48
# File 'lib/tesote_sdk/transport.rb', line 46

def clear
  @mutex.synchronize { @data.clear }
end

#read(key) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/tesote_sdk/transport.rb', line 24

def read(key)
  @mutex.synchronize do
    entry = @data.delete(key)
    return nil if entry.nil?
    if entry.expires_at < monotonic_now
      return nil
    end

    @data[key] = entry
    entry.value
  end
end

#write(key, value, ttl:) ⇒ Object



37
38
39
40
41
42
43
44
# File 'lib/tesote_sdk/transport.rb', line 37

def write(key, value, ttl:)
  @mutex.synchronize do
    @data.delete(key)
    @data[key] = Entry.new(value, monotonic_now + ttl)
    @data.shift while @data.size > @max_size
    value
  end
end