diff --git a/README.md b/README.md index 4f2420c..4a3923f 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,15 @@ suo.lock do |token| end ``` +### Time To Live + +```ruby +Suo::Client::Redis.new("bar_resource", ttl: 60) #ttl in seconds +``` + +A key representing a set of lockable resources is removed once the last resource lock is released and the `ttl` time runs out. When another lock is acquired and the key has been removed the key has to be recreated. + + ## TODO - more race condition tests diff --git a/lib/suo/client/base.rb b/lib/suo/client/base.rb index 7f37355..c439575 100644 --- a/lib/suo/client/base.rb +++ b/lib/suo/client/base.rb @@ -5,7 +5,8 @@ module Suo acquisition_timeout: 0.1, acquisition_delay: 0.01, stale_lock_expiration: 3600, - resources: 1 + resources: 1, + ttl: 60, }.freeze BLANK_STR = "".freeze @@ -64,7 +65,7 @@ module Suo refresh_lock(cleared_locks, token) - break if set(serialize_locks(cleared_locks), cas) + break if set(serialize_locks(cleared_locks), cas, expire: cleared_locks.empty?) end end @@ -81,7 +82,7 @@ module Suo acquisition_lock = remove_lock(cleared_locks, token) break unless acquisition_lock - break if set(serialize_locks(cleared_locks), cas) + break if set(serialize_locks(cleared_locks), cas, expire: cleared_locks.empty?) end rescue LockClientError => _ # rubocop:disable Lint/HandleExceptions # ignore - assume success due to optimistic locking diff --git a/lib/suo/client/memcached.rb b/lib/suo/client/memcached.rb index 83b37b6..09f5aa7 100644 --- a/lib/suo/client/memcached.rb +++ b/lib/suo/client/memcached.rb @@ -16,8 +16,12 @@ module Suo @client.get_cas(@key) end - def set(newval, cas) - @client.set_cas(@key, newval, cas) + def set(newval, cas, expire: false) + if expire + @client.set_cas(@key, newval, cas, @options[:ttl]) + else + @client.set_cas(@key, newval, cas) + end end def initial_set(val = BLANK_STR) diff --git a/lib/suo/client/redis.rb b/lib/suo/client/redis.rb index b13119e..7bd740a 100644 --- a/lib/suo/client/redis.rb +++ b/lib/suo/client/redis.rb @@ -18,9 +18,13 @@ module Suo [@client.get(@key), nil] end - def set(newval, _) + def set(newval, _, expire: false) ret = @client.multi do |multi| - multi.set(@key, newval) + if expire + multi.setex(@key, @options[:ttl], newval) + else + multi.set(@key, newval) + end end ret && ret[0] == OK_STR