Class: Rodauth::OAuth::TtlStore
- Inherits:
-
Object
- Object
- Rodauth::OAuth::TtlStore
- Defined in:
- lib/rodauth/oauth/ttl_store.rb
Overview
The TTL store is a data structure which keeps data by a key, and with a time-to-live. It is specifically designed for data which is static, i.e. for a certain key in a sufficiently large span, the value will be the same.
Because of that, synchronizations around reads do not exist, while write synchronizations will be short-circuited by a read.
Constant Summary collapse
- DEFAULT_TTL =
default TTL is one day
60 * 60 * 24
Instance Method Summary collapse
- #[](key) ⇒ Object
-
#initialize ⇒ TtlStore
constructor
A new instance of TtlStore.
- #set(key, &block) ⇒ Object
- #uncache(key) ⇒ Object
Constructor Details
#initialize ⇒ TtlStore
Returns a new instance of TtlStore.
14 15 16 17 |
# File 'lib/rodauth/oauth/ttl_store.rb', line 14 def initialize @store_mutex = Mutex.new @store = {} end |
Instance Method Details
#[](key) ⇒ Object
19 20 21 |
# File 'lib/rodauth/oauth/ttl_store.rb', line 19 def [](key) lookup(key, now) end |
#set(key, &block) ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/rodauth/oauth/ttl_store.rb', line 23 def set(key, &block) @store_mutex.synchronize do # short circuit return @store[key][:payload] if @store[key] && @store[key][:ttl] < now end payload, ttl = block.call return payload unless ttl @store_mutex.synchronize do # given that the block call triggers network, and two requests for the same key be processed # at the same time, this ensures the first one wins. return @store[key][:payload] if @store[key] && @store[key][:ttl] < now @store[key] = { payload: payload, ttl: (ttl || (now + DEFAULT_TTL)) } end @store[key][:payload] end |
#uncache(key) ⇒ Object
43 44 45 46 47 |
# File 'lib/rodauth/oauth/ttl_store.rb', line 43 def uncache(key) @store_mutex.synchronize do @store.delete(key) end end |