Class: TocDoc::Cache::MemoryStore

Inherits:
Object
  • Object
show all
Defined in:
lib/toc_doc/cache/memory_store.rb

Overview

A thread-safe, in-memory response cache with per-entry TTL.

Uses lazy expiration: expired entries are evicted on +#read+, not via a background sweep. The key space is bounded by the number of distinct API URLs, so the overhead is negligible for typical gem usage.

Compatible with the ActiveSupport::Cache::Store interface for the methods it implements (+read+, +write+, +delete+, +clear+).

Examples:

store = TocDoc::Cache::MemoryStore.new(default_ttl: 60)
store.write('key', 'value', expires_in: 30)
store.read('key')   #=> 'value'

Instance Method Summary collapse

Constructor Details

#initialize(default_ttl: 300) ⇒ MemoryStore

Returns a new instance of MemoryStore.

Parameters:

  • default_ttl (Numeric) (defaults to: 300)

    default TTL in seconds (default: 300)



22
23
24
25
26
# File 'lib/toc_doc/cache/memory_store.rb', line 22

def initialize(default_ttl: 300)
  @default_ttl = default_ttl
  @store = {}
  @monitor = Monitor.new
end

Instance Method Details

#clear

This method returns an undefined value.

Removes all entries from the store.



76
77
78
# File 'lib/toc_doc/cache/memory_store.rb', line 76

def clear
  @monitor.synchronize { @store.clear }
end

#delete(key)

This method returns an undefined value.

Deletes the entry for +key+.

Parameters:

  • key (String)


69
70
71
# File 'lib/toc_doc/cache/memory_store.rb', line 69

def delete(key)
  @monitor.synchronize { @store.delete(key) }
end

#read(key) ⇒ Object?

Reads the value stored under +key+.

Returns +nil+ when the key is absent or has expired (and evicts the entry in the latter case).

Parameters:

  • key (String)

Returns:

  • (Object, nil)


35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/toc_doc/cache/memory_store.rb', line 35

def read(key)
  @monitor.synchronize do
    entry = @store[key]
    return nil unless entry

    if Process.clock_gettime(Process::CLOCK_MONOTONIC) > entry[:expires_at]
      @store.delete(key)
      return nil
    end

    entry[:value]
  end
end

#write(key, value, expires_in: @default_ttl) ⇒ Object

Stores +value+ under +key+ with the given TTL.

Parameters:

  • key (String)
  • value (Object)
  • expires_in (Numeric) (defaults to: @default_ttl)

    TTL in seconds; falls back to +default_ttl+

Returns:

  • (Object)

    the stored value



55
56
57
58
59
60
61
62
63
# File 'lib/toc_doc/cache/memory_store.rb', line 55

def write(key, value, expires_in: @default_ttl)
  @monitor.synchronize do
    @store[key] = {
      value: value,
      expires_at: Process.clock_gettime(Process::CLOCK_MONOTONIC) + expires_in
    }
    value
  end
end