Class: Lutaml::Store::Cache

Inherits:
Object
  • Object
show all
Defined in:
lib/lutaml/store/cache.rb

Defined Under Namespace

Classes: Entry

Constant Summary collapse

DEFAULT_MAX_SIZE =
1000

Instance Method Summary collapse

Constructor Details

#initialize(max_size: DEFAULT_MAX_SIZE, ttl: nil) ⇒ Cache

Returns a new instance of Cache.



10
11
12
13
14
15
16
# File 'lib/lutaml/store/cache.rb', line 10

def initialize(max_size: DEFAULT_MAX_SIZE, ttl: nil)
  @max_size = max_size
  @ttl = ttl
  @data = {}
  @access_order = []
  @mutex = Mutex.new
end

Instance Method Details

#cleanup_expiredObject



81
82
83
84
85
86
87
88
89
90
# File 'lib/lutaml/store/cache.rb', line 81

def cleanup_expired
  @mutex.synchronize do
    expired_keys = @data.select { |_, entry| expired?(entry) }.keys
    expired_keys.each do |key|
      @data.delete(key)
      @access_order.delete(key)
    end
    expired_keys.size
  end
end

#clearObject



59
60
61
62
63
64
# File 'lib/lutaml/store/cache.rb', line 59

def clear
  @mutex.synchronize do
    @data.clear
    @access_order.clear
  end
end

#delete(key) ⇒ Object



41
42
43
44
45
46
47
48
49
50
# File 'lib/lutaml/store/cache.rb', line 41

def delete(key)
  @mutex.synchronize do
    if @data.delete(key)
      @access_order.delete(key)
      true
    else
      false
    end
  end
end

#exists?(key) ⇒ Boolean

Returns:

  • (Boolean)


52
53
54
55
56
57
# File 'lib/lutaml/store/cache.rb', line 52

def exists?(key)
  @mutex.synchronize do
    entry = @data[key]
    entry && !expired?(entry)
  end
end

#get(key) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/lutaml/store/cache.rb', line 18

def get(key)
  @mutex.synchronize do
    entry = @data[key]
    return nil unless entry
    return nil if expired?(entry)

    @access_order.delete(key)
    @access_order << key
    entry.value
  end
end

#set(key, value) ⇒ Object



30
31
32
33
34
35
36
37
38
39
# File 'lib/lutaml/store/cache.rb', line 30

def set(key, value)
  @mutex.synchronize do
    @access_order.delete(key) if @data.key?(key)

    @data[key] = Entry.new(value: value, timestamp: Time.now)
    @access_order << key

    evict_lru while @data.size > @max_size
  end
end

#sizeObject



66
67
68
# File 'lib/lutaml/store/cache.rb', line 66

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

#statsObject



70
71
72
73
74
75
76
77
78
79
# File 'lib/lutaml/store/cache.rb', line 70

def stats
  @mutex.synchronize do
    {
      size: @data.size,
      max_size: @max_size,
      ttl: @ttl,
      keys: @data.keys
    }
  end
end