Skip to content

Commit

Permalink
Merge pull request #6 from GandalftheGUI/ian_remillard/remove_keys_af…
Browse files Browse the repository at this point in the history
…ter_last_lock_released

Add 'Time To Live' to mitigate potential memory leak
  • Loading branch information
nickelser authored Oct 5, 2018
2 parents af1c476 + ca46f5f commit 0423eb9
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 7 deletions.
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
7 changes: 4 additions & 3 deletions lib/suo/client/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ class Base
acquisition_timeout: 0.1,
acquisition_delay: 0.01,
stale_lock_expiration: 3600,
resources: 1
resources: 1,
ttl: 60,
}.freeze

BLANK_STR = "".freeze
Expand Down Expand Up @@ -64,7 +65,7 @@ def refresh(token)

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

Expand All @@ -81,7 +82,7 @@ def unlock(token)
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
Expand Down
8 changes: 6 additions & 2 deletions lib/suo/client/memcached.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,12 @@ def get
@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)
Expand Down
8 changes: 6 additions & 2 deletions lib/suo/client/redis.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,13 @@ def get
[@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
Expand Down

0 comments on commit 0423eb9

Please sign in to comment.