Class: Idempo::ResponseStore

Inherits:
Object
  • Object
show all
Defined in:
lib/idempo/response_store.rb

Defined Under Namespace

Classes: ExpiryHandle, StoredResponse

Instance Method Summary collapse

Constructor Details

#initializeResponseStore

Returns a new instance of ResponseStore.



5
6
7
8
# File 'lib/idempo/response_store.rb', line 5

def initialize
  @values = {}
  @expiries = []
end

Instance Method Details

#lookup(key) ⇒ Object



19
20
21
22
23
24
25
26
# File 'lib/idempo/response_store.rb', line 19

def lookup(key)
  prune
  stored = @values[key]
  return unless stored
  return stored.payload if stored.expire_at > Process.clock_gettime(Process::CLOCK_MONOTONIC)
  @values.delete(key)
  nil
end

#pruneObject



28
29
30
31
32
33
34
# File 'lib/idempo/response_store.rb', line 28

def prune
  now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  items_to_delete = remove_lower_than(@expiries, now, &:expire_at)
  items_to_delete.each do |expiry_handle|
    @values.delete(expiry_handle.key) if @values[expiry_handle.key] && @values[expiry_handle.key].expire_at < now
  end
end

#save(key, value, expire_in) ⇒ Object



10
11
12
13
14
15
16
17
# File 'lib/idempo/response_store.rb', line 10

def save(key, value, expire_in)
  prune
  exp = expire_in + Process.clock_gettime(Process::CLOCK_MONOTONIC)
  res = StoredResponse.new(key, exp, value)
  expiry_handle = ExpiryHandle.new(key, exp)
  binary_insert(@expiries, expiry_handle, &:expire_at)
  @values[key] = res
end