Class: MonoVM::Whois::Transport::Middleware::Cache

Inherits:
Middleware::Base
  • Object
show all
Defined in:
lib/monovm/whois/transport/middleware/cache.rb

Overview

Remembers responses for a short while.

Registries rate-limit, and a bulk check of a list that happens to contain the same name twice should not pay for it twice. The TTL is deliberately short by default: registration data changes, and a stale "available" is the expensive kind of wrong.

Only successful responses are cached. A failure is never remembered — a transient timeout would otherwise poison every later lookup of that name.

Constant Summary collapse

DEFAULT_TTL =
300.0
DEFAULT_MAX_ENTRIES =
1_000

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, ttl: DEFAULT_TTL, max_entries: DEFAULT_MAX_ENTRIES, clock: nil) ⇒ Cache

Returns a new instance of Cache.

Parameters:

  • ttl (Float) (defaults to: DEFAULT_TTL)

    seconds an entry stays fresh

  • max_entries (Integer) (defaults to: DEFAULT_MAX_ENTRIES)

    cap on retained entries; oldest evicted first

  • clock (#call) (defaults to: nil)

    monotonic seconds, injectable so specs need no sleeps



27
28
29
30
31
32
33
34
# File 'lib/monovm/whois/transport/middleware/cache.rb', line 27

def initialize(app, ttl: DEFAULT_TTL, max_entries: DEFAULT_MAX_ENTRIES, clock: nil)
  @ttl = ttl
  @max_entries = max_entries
  @clock = clock || -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }
  @entries = {}
  @mutex = Mutex.new
  super(app)
end

Instance Attribute Details

#max_entriesObject (readonly)

Returns the value of attribute max_entries.



22
23
24
# File 'lib/monovm/whois/transport/middleware/cache.rb', line 22

def max_entries
  @max_entries
end

#ttlObject (readonly)

Returns the value of attribute ttl.



22
23
24
# File 'lib/monovm/whois/transport/middleware/cache.rb', line 22

def ttl
  @ttl
end

Instance Method Details

#clearObject



52
53
54
55
# File 'lib/monovm/whois/transport/middleware/cache.rb', line 52

def clear
  @mutex.synchronize { @entries.clear }
  self
end

#fetch(query:, endpoint:) ⇒ Object



36
37
38
39
40
41
42
43
44
45
# File 'lib/monovm/whois/transport/middleware/cache.rb', line 36

def fetch(query:, endpoint:)
  key = [endpoint.uri, query]

  cached = read(key)
  return cached if cached

  response = app.fetch(query: query, endpoint: endpoint)
  write(key, response)
  response
end

#sizeInteger

Returns how many fresh entries are held.

Returns:

  • (Integer)

    how many fresh entries are held



48
49
50
# File 'lib/monovm/whois/transport/middleware/cache.rb', line 48

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