Class: Rack::IdempotencyKey::MemoryStore

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/idempotency_key/memory_store.rb

Constant Summary collapse

DEFAULT_EXPIRATION =

5 minutes in seconds

300

Instance Method Summary collapse

Constructor Details

#initialize(expires_in: DEFAULT_EXPIRATION) ⇒ MemoryStore

Returns a new instance of MemoryStore.



8
9
10
11
12
# File 'lib/rack/idempotency_key/memory_store.rb', line 8

def initialize(expires_in: DEFAULT_EXPIRATION)
  @store      = {}
  @expires_in = expires_in
  @mutex      = Mutex.new
end

Instance Method Details

#get(key) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/rack/idempotency_key/memory_store.rb', line 14

def get(key)
  mutex.synchronize do
    value = store[key]
    return if value.nil?

    if expired?(value[:expires_at])
      store.delete(key)
      return
    end

    value[:value]
  end
end

#set(key, value, ttl: expires_in) ⇒ Object



28
29
30
31
32
33
34
35
# File 'lib/rack/idempotency_key/memory_store.rb', line 28

def set(key, value, ttl: expires_in)
  mutex.synchronize do
    store[key] ||= { value: value, expires_at: Time.now.utc + ttl }
    raise Rack::IdempotencyKey::ConflictError if store[key][:value] != value
  end

  get(key)
end

#unset(key) ⇒ Object



37
38
39
# File 'lib/rack/idempotency_key/memory_store.rb', line 37

def unset(key)
  mutex.synchronize { store.delete(key) }
end