23 Commits

Author SHA1 Message Date
Nick Elser
155a3ac40c release v0.2.2 2015-04-13 21:45:47 -07:00
Nick Elser
10d3ab09cf handle invalid lock data 2015-04-13 21:40:54 -07:00
Nick Elser
2724ec6d9d add another test case for the nil refresh case 2015-04-13 21:32:01 -07:00
Nick Elser
185327f59c fix documentation and add another test for refresh 2015-04-13 21:21:45 -07:00
Nick Elser
c8a972da31 more tests for (still not great) refresh method 2015-04-13 20:29:23 -07:00
Nick Elser
7591c08a28 avoid name collision for locks method 2015-04-13 20:29:03 -07:00
Nick Elser
1dee338e16 slightly more coverage 2015-04-13 19:42:50 -07:00
Nick Elser
900c723043 only report to codeclimate when credentials passed in 2015-04-13 19:37:58 -07:00
Nick Elser
6e2afdf80a add tests for refresh and slight refactor 2015-04-13 19:37:49 -07:00
Nick Elser
49a9757d44 fix refresh token 2015-04-13 19:37:34 -07:00
Nick Elser
754d7d8faf report test coverage 2015-04-13 10:12:26 -07:00
Nick Elser
857fc63378 release 0.2.1 2015-04-12 23:45:09 -07:00
Nick Elser
bb6762bbc6 ret is not always an array 2015-04-12 23:45:00 -07:00
Nick Elser
f0977c89f2 remove redundant require file 2015-04-12 23:03:54 -07:00
Nick Elser
4d5c96309f some style fixes 2015-04-12 22:54:53 -07:00
Nick Elser
8d6061b137 rename some tests, fix rare edge condition 2015-04-12 22:49:02 -07:00
Nick Elser
ce0a4d8d86 release 0.2.0 2015-04-12 22:33:19 -07:00
Nick Elser
1fd769eec2 refactor class methods into instance methods 2015-04-12 22:32:51 -07:00
Nick Elser
37be5ae27b bump version, update changelog 2015-04-12 20:58:18 -07:00
Nick Elser
a1a226fb59 account for variabilities in test memcached 2015-04-12 20:57:52 -07:00
Nick Elser
8d7ddaf35a move logic around loop counts to a more reasonable location 2015-04-12 20:57:29 -07:00
Nick Elser
1aacc0c1a1 properly throw lock LockClientError 2015-04-12 20:47:35 -07:00
Nick Elser
8166c6b51d specify ruby version 2015-04-12 19:53:47 -07:00
13 changed files with 504 additions and 270 deletions

View File

@@ -1,3 +1,23 @@
## 0.2.2
- Fix bug with refresh - typo would've prevented real use.
- Clean up code.
- Improve documentation a bit.
- 100% test coverage.
## 0.2.1
- Fix bug when dealing with real-world Redis error conditions.
## 0.2.0
- Refactor class methods into instance methods to simplify implementation.
- Increase thread safety with Memcached implementation.
## 0.1.3
- Properly throw Suo::LockClientError when the connection itself fails (Memcache server not reachable, etc.)
## 0.1.2 ## 0.1.2
- Fix retry_timeout to properly use the full time (was being calculated incorrectly). - Fix retry_timeout to properly use the full time (was being calculated incorrectly).

View File

@@ -1,4 +1,4 @@
# Suo [![Build Status](https://travis-ci.org/nickelser/suo.svg?branch=master)](https://travis-ci.org/nickelser/suo) [![Gem Version](https://badge.fury.io/rb/suo.svg)](http://badge.fury.io/rb/suo) # Suo [![Build Status](https://travis-ci.org/nickelser/suo.svg?branch=master)](https://travis-ci.org/nickelser/suo) [![Code Climate](https://codeclimate.com/github/nickelser/suo/badges/gpa.svg)](https://codeclimate.com/github/nickelser/suo) [![Test Coverage](https://codeclimate.com/github/nickelser/suo/badges/coverage.svg)](https://codeclimate.com/github/nickelser/suo) [![Gem Version](https://badge.fury.io/rb/suo.svg)](http://badge.fury.io/rb/suo)
:lock: Distributed semaphores using Memcached or Redis in Ruby. :lock: Distributed semaphores using Memcached or Redis in Ruby.
@@ -31,16 +31,45 @@ suo.lock("some_key") do
@puppies.pet! @puppies.pet!
end end
2.times do Thread.new { suo.lock("other_key", 2) { puts "One"; sleep 2 } }
Thread.new do Thread.new { suo.lock("other_key", 2) { puts "Two"; sleep 2 } }
# second argument is the number of resources - so this will run twice Thread.new { suo.lock("other_key", 2) { puts "Three" } }
suo.lock("other_key", 2, timeout: 0.5) { puts "Will run twice!" }
# will print "One" "Two", but not "Three", as there are only 2 resources
# custom acquisition timeouts (time to acquire)
suo = Suo::Client::Memcached.new(client: some_dalli_client, acquisition_timeout: 1) # in seconds
# manually locking/unlocking
# the return value from lock without a block is a unique token valid only for the current lock
# which must be unlocked manually
lock = suo.lock("a_key")
foo.baz!
suo.unlock("a_key", lock)
# custom stale lock expiration (cleaning of dead locks)
suo = Suo::Client::Redis.new(client: some_redis_client, stale_lock_expiration: 60*5)
```
### Stale locks
"Stale locks" - those acquired more than `stale_lock_expiration` (defaulting to 3600 or one hour) ago - are automatically cleared during any operation on the key (`lock`, `unlock`, `refresh`). The `locked?` method will not return true if only stale locks exist, but will not modify the key itself.
To re-acquire a lock in the middle of a block, you can use the refresh method on client.
```ruby
suo = Suo::Client::Redis.new
# lock is the same token as seen in the manual example, above
suo.lock("foo") do |lock|
5.times do
baz.bar!
suo.refresh("foo", lock)
end end
end end
``` ```
## TODO ## TODO
- better stale key handling (refresh blocks)
- more race condition tests - more race condition tests
## History ## History

View File

@@ -1,2 +1,16 @@
require "securerandom"
require "monitor"
require "dalli"
require "dalli/cas/client"
require "redis"
require "msgpack"
require "suo/version" require "suo/version"
require "suo/clients"
require "suo/errors"
require "suo/client/base"
require "suo/client/memcached"
require "suo/client/redis"

View File

@@ -2,206 +2,187 @@ module Suo
module Client module Client
class Base class Base
DEFAULT_OPTIONS = { DEFAULT_OPTIONS = {
retry_timeout: 0.1, acquisition_timeout: 0.1,
retry_delay: 0.01, acquisition_delay: 0.01,
stale_lock_expiration: 3600 stale_lock_expiration: 3600
}.freeze }.freeze
attr_accessor :client
include MonitorMixin
def initialize(options = {}) def initialize(options = {})
@options = self.class.merge_defaults(options) fail "Client required" unless options[:client]
@options = DEFAULT_OPTIONS.merge(options)
@retry_count = (@options[:acquisition_timeout] / @options[:acquisition_delay].to_f).ceil
@client = @options[:client]
super()
end end
def lock(key, resources = 1, options = {}) def lock(key, resources = 1)
options = self.class.merge_defaults(@options.merge(options)) token = acquire_lock(key, resources)
token = self.class.lock(key, resources, options)
if token if block_given? && token
begin begin
yield if block_given? yield(token)
ensure ensure
self.class.unlock(key, token, options) unlock(key, token)
end end
true
else else
false token
end end
end end
def locked?(key, resources = 1) def locked?(key, resources = 1)
self.class.locked?(key, resources, @options) locks(key).size >= resources
end end
class << self def locks(key)
def lock(key, resources = 1, options = {}) val, _ = get(key)
options = merge_defaults(options) cleared_locks = deserialize_and_clear_locks(val)
acquisition_token = nil
token = SecureRandom.base64(16)
retry_with_timeout(key, options) do cleared_locks
val, cas = get(key, options) end
if val.nil? def refresh(key, acquisition_token)
set_initial(key, options) retry_with_timeout(key) do
next val, cas = get(key)
end
locks = deserialize_and_clear_locks(val, options) if val.nil?
initial_set(key)
if locks.size < resources next
add_lock(locks, token)
newval = serialize_locks(locks)
if set(key, newval, cas, options)
acquisition_token = token
break
end
end
end end
acquisition_token cleared_locks = deserialize_and_clear_locks(val)
refresh_lock(cleared_locks, acquisition_token)
break if set(key, serialize_locks(cleared_locks), cas)
end end
end
def locked?(key, resources = 1, options = {}) def unlock(key, acquisition_token)
locks(key, options).size >= resources return unless acquisition_token
retry_with_timeout(key) do
val, cas = get(key)
break if val.nil?
cleared_locks = deserialize_and_clear_locks(val)
acquisition_lock = remove_lock(cleared_locks, acquisition_token)
break unless acquisition_lock
break if set(key, serialize_locks(cleared_locks), cas)
end end
rescue LockClientError => _ # rubocop:disable Lint/HandleExceptions
# ignore - assume success due to optimistic locking
end
def locks(key, options) def clear(key) # rubocop:disable Lint/UnusedMethodArgument
options = merge_defaults(options) fail NotImplementedError
val, _ = get(key, options) end
locks = deserialize_locks(val)
locks private
end
def refresh(key, acquisition_token, options = {}) def acquire_lock(key, resources = 1)
options = merge_defaults(options) acquisition_token = nil
token = SecureRandom.base64(16)
retry_with_timeout(key, options) do retry_with_timeout(key) do
val, cas = get(key, options) val, cas = get(key)
if val.nil? if val.nil?
set_initial(key, options) initial_set(key)
next next
end
cleared_locks = deserialize_and_clear_locks(val)
if cleared_locks.size < resources
add_lock(cleared_locks, token)
newval = serialize_locks(cleared_locks)
if set(key, newval, cas)
acquisition_token = token
break
end end
locks = deserialize_and_clear_locks(val, options)
refresh_lock(locks, acquisition_token)
break if set(key, serialize_locks(locks), cas, options)
end end
end end
def unlock(key, acquisition_token, options = {}) acquisition_token
options = merge_defaults(options) end
return unless acquisition_token def get(key) # rubocop:disable Lint/UnusedMethodArgument
fail NotImplementedError
end
retry_with_timeout(key, options) do def set(key, newval, cas) # rubocop:disable Lint/UnusedMethodArgument
val, cas = get(key, options) fail NotImplementedError
end
break if val.nil? def initial_set(key, val = "") # rubocop:disable Lint/UnusedMethodArgument
fail NotImplementedError
end
locks = deserialize_and_clear_locks(val, options) def synchronize(key) # rubocop:disable Lint/UnusedMethodArgument
mon_synchronize { yield }
end
acquisition_lock = remove_lock(locks, acquisition_token) def retry_with_timeout(key)
start = Time.now.to_f
break unless acquisition_lock @retry_count.times do
break if set(key, serialize_locks(locks), cas, options) now = Time.now.to_f
break if now - start > @options[:acquisition_timeout]
synchronize(key) do
yield
end end
rescue FailedToAcquireLock => _ # rubocop:disable Lint/HandleExceptions
# ignore - assume success due to optimistic locking sleep(rand(@options[:acquisition_delay] * 1000).to_f / 1000)
end end
rescue => _
raise LockClientError
end
def clear(key, options = {}) # rubocop:disable Lint/UnusedMethodArgument def serialize_locks(locks)
fail NotImplementedError MessagePack.pack(locks.map { |time, token| [time.to_f, token] })
end
def deserialize_and_clear_locks(val)
clear_expired_locks(deserialize_locks(val))
end
def deserialize_locks(val)
unpacked = (val.nil? || val == "") ? [] : MessagePack.unpack(val)
unpacked.map do |time, token|
[Time.at(time), token]
end end
rescue EOFError, MessagePack::MalformedFormatError => _
[]
end
def merge_defaults(options = {}) def clear_expired_locks(locks)
options = self::DEFAULT_OPTIONS.merge(options) expired = Time.now - @options[:stale_lock_expiration]
locks.reject { |time, _| time < expired }
end
fail "Client required" unless options[:client] def add_lock(locks, token, time = Time.now.to_f)
locks << [time, token]
end
options[:retry_count] = (options[:retry_timeout] / options[:retry_delay].to_f).ceil def remove_lock(locks, acquisition_token)
lock = locks.find { |_, token| token == acquisition_token }
locks.delete(lock)
end
options def refresh_lock(locks, acquisition_token)
end remove_lock(locks, acquisition_token)
add_lock(locks, acquisition_token)
private
def get(key, options) # rubocop:disable Lint/UnusedMethodArgument
fail NotImplementedError
end
def set(key, newval, oldval, options) # rubocop:disable Lint/UnusedMethodArgument
fail NotImplementedError
end
def set_initial(key, options) # rubocop:disable Lint/UnusedMethodArgument
fail NotImplementedError
end
def synchronize(key, options)
yield(key, options)
end
def retry_with_timeout(key, options)
start = Time.now.to_f
options[:retry_count].times do
if options[:retry_timeout]
now = Time.now.to_f
break if now - start > options[:retry_timeout]
end
synchronize(key, options) do
yield
end
sleep(rand(options[:retry_delay] * 1000).to_f / 1000)
end
rescue => _
raise FailedToAcquireLock
end
def serialize_locks(locks)
MessagePack.pack(locks.map { |time, token| [time.to_f, token] })
end
def deserialize_and_clear_locks(val, options)
clear_expired_locks(deserialize_locks(val), options)
end
def deserialize_locks(val)
unpacked = (val.nil? || val == "") ? [] : MessagePack.unpack(val)
unpacked.map do |time, token|
[Time.at(time), token]
end
rescue EOFError => _
[]
end
def clear_expired_locks(locks, options)
expired = Time.now - options[:stale_lock_expiration]
locks.reject { |time, _| time < expired }
end
def add_lock(locks, token)
locks << [Time.now.to_f, token]
end
def remove_lock(locks, acquisition_token)
lock = locks.find { |_, token| token == acquisition_token }
locks.delete(lock)
end
def refresh_lock(locks, acquisition_token)
remove_lock(locks, acquisition_token)
add_lock(locks, token)
end
end end
end end
end end

View File

@@ -1,7 +0,0 @@
module Suo
module Client
module Errors
class FailedToAcquireLock < StandardError; end
end
end
end

View File

@@ -6,25 +6,22 @@ module Suo
super super
end end
class << self def clear(key)
def clear(key, options = {}) @client.delete(key)
options = merge_defaults(options) end
options[:client].delete(key)
end
private private
def get(key, options) def get(key)
options[:client].get_cas(key) @client.get_cas(key)
end end
def set(key, newval, cas, options) def set(key, newval, cas)
options[:client].set_cas(key, newval, cas) @client.set_cas(key, newval, cas)
end end
def set_initial(key, options) def initial_set(key, val = "")
options[:client].set(key, "") @client.set(key, val)
end
end end
end end
end end

View File

@@ -6,37 +6,34 @@ module Suo
super super
end end
class << self def clear(key)
def clear(key, options = {}) @client.del(key)
options = merge_defaults(options) end
options[:client].del(key)
private
def get(key)
[@client.get(key), nil]
end
def set(key, newval, _)
ret = @client.multi do |multi|
multi.set(key, newval)
end end
private ret && ret[0] == "OK"
end
def get(key, options) def synchronize(key)
[options[:client].get(key), nil] @client.watch(key) do
yield
end end
ensure
@client.unwatch
end
def set(key, newval, _, options) def initial_set(key, val = "")
ret = options[:client].multi do |multi| @client.set(key, val)
multi.set(key, newval)
end
ret[0] == "OK"
end
def synchronize(key, options)
options[:client].watch(key) do
yield
end
ensure
options[:client].unwatch
end
def set_initial(key, options)
options[:client].set(key, "")
end
end end
end end
end end

View File

@@ -1,14 +0,0 @@
require "securerandom"
require "monitor"
require "dalli"
require "dalli/cas/client"
require "redis"
require "msgpack"
require "suo/client/errors"
require "suo/client/base"
require "suo/client/memcached"
require "suo/client/redis"

3
lib/suo/errors.rb Normal file
View File

@@ -0,0 +1,3 @@
module Suo
class LockClientError < StandardError; end
end

View File

@@ -1,3 +1,3 @@
module Suo module Suo
VERSION = "0.1.2" VERSION = "0.2.2"
end end

View File

@@ -20,6 +20,8 @@ Gem::Specification.new do |spec|
spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"] spec.require_paths = ["lib"]
spec.required_ruby_version = "~> 2.0"
spec.add_dependency "dalli" spec.add_dependency "dalli"
spec.add_dependency "redis" spec.add_dependency "redis"
spec.add_dependency "msgpack" spec.add_dependency "msgpack"
@@ -28,4 +30,5 @@ Gem::Specification.new do |spec|
spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rubocop", "~> 0.30.0" spec.add_development_dependency "rubocop", "~> 0.30.0"
spec.add_development_dependency "minitest", "~> 5.5.0" spec.add_development_dependency "minitest", "~> 5.5.0"
spec.add_development_dependency "codeclimate-test-reporter", "~> 0.4.7"
end end

View File

@@ -3,56 +3,76 @@ require "test_helper"
TEST_KEY = "suo_test_key".freeze TEST_KEY = "suo_test_key".freeze
module ClientTests module ClientTests
def test_requires_client def client(options)
exception = assert_raises(RuntimeError) do @client.class.new(options.merge(client: @client.client))
@klass.lock(TEST_KEY, 1)
end
assert_equal "Client required", exception.message
end end
def test_class_single_resource_locking def test_throws_failed_error_on_bad_client
lock1 = @klass.lock(TEST_KEY, 1, client: @klass_client) assert_raises(Suo::LockClientError) do
client = @client.class.new(client: {})
client.lock(TEST_KEY, 1)
end
end
def test_single_resource_locking
lock1 = @client.lock(TEST_KEY, 1)
refute_nil lock1 refute_nil lock1
locked = @klass.locked?(TEST_KEY, 1, client: @klass_client) locked = @client.locked?(TEST_KEY, 1)
assert_equal true, locked assert_equal true, locked
lock2 = @klass.lock(TEST_KEY, 1, client: @klass_client) lock2 = @client.lock(TEST_KEY, 1)
assert_nil lock2 assert_nil lock2
@klass.unlock(TEST_KEY, lock1, client: @klass_client) @client.unlock(TEST_KEY, lock1)
locked = @klass.locked?(TEST_KEY, 1, client: @klass_client) locked = @client.locked?(TEST_KEY, 1)
assert_equal false, locked assert_equal false, locked
end end
def test_class_multiple_resource_locking def test_empty_lock_on_invalid_data
lock1 = @klass.lock(TEST_KEY, 2, client: @klass_client) @client.send(:initial_set, TEST_KEY, "bad value")
locked = @client.locked?(TEST_KEY)
assert_equal false, locked
end
def test_clear
lock1 = @client.lock(TEST_KEY, 1)
refute_nil lock1 refute_nil lock1
locked = @klass.locked?(TEST_KEY, 2, client: @klass_client) @client.clear(TEST_KEY)
assert_equal false, locked
lock2 = @klass.lock(TEST_KEY, 2, client: @klass_client) locked = @client.locked?(TEST_KEY, 1)
refute_nil lock2
locked = @klass.locked?(TEST_KEY, 2, client: @klass_client)
assert_equal true, locked
@klass.unlock(TEST_KEY, lock1, client: @klass_client)
locked = @klass.locked?(TEST_KEY, 1, client: @klass_client)
assert_equal true, locked
@klass.unlock(TEST_KEY, lock2, client: @klass_client)
locked = @klass.locked?(TEST_KEY, 1, client: @klass_client)
assert_equal false, locked assert_equal false, locked
end end
def test_instance_single_resource_locking def test_multiple_resource_locking
lock1 = @client.lock(TEST_KEY, 2)
refute_nil lock1
locked = @client.locked?(TEST_KEY, 2)
assert_equal false, locked
lock2 = @client.lock(TEST_KEY, 2)
refute_nil lock2
locked = @client.locked?(TEST_KEY, 2)
assert_equal true, locked
@client.unlock(TEST_KEY, lock1)
locked = @client.locked?(TEST_KEY, 1)
assert_equal true, locked
@client.unlock(TEST_KEY, lock2)
locked = @client.locked?(TEST_KEY, 1)
assert_equal false, locked
end
def test_block_single_resource_locking
locked = false locked = false
@client.lock(TEST_KEY, 1) { locked = true } @client.lock(TEST_KEY, 1) { locked = true }
@@ -60,23 +80,48 @@ module ClientTests
assert_equal true, locked assert_equal true, locked
end end
def test_instance_unlocks_on_exception def test_block_unlocks_on_exception
assert_raises(RuntimeError) do assert_raises(RuntimeError) do
@client.lock(TEST_KEY, 1) { fail "Test" } @client.lock(TEST_KEY, 1) { fail "Test" }
end end
locked = @klass.locked?(TEST_KEY, 1, client: @klass_client) locked = @client.locked?(TEST_KEY, 1)
assert_equal false, locked assert_equal false, locked
end end
def test_instance_multiple_resource_locking def test_readme_example
output = Queue.new
threads = []
threads << Thread.new { @client.lock(TEST_KEY, 2) { output << "One"; sleep 0.5 } }
threads << Thread.new { @client.lock(TEST_KEY, 2) { output << "Two"; sleep 0.5 } }
sleep 0.1
threads << Thread.new { @client.lock(TEST_KEY, 2) { output << "Three" } }
threads.map(&:join)
ret = []
ret << output.pop
ret << output.pop
ret.sort!
assert_equal 0, output.size
assert_equal %w(One Two), ret
assert_equal false, @client.locked?(TEST_KEY)
end
def test_block_multiple_resource_locking
success_counter = Queue.new success_counter = Queue.new
failure_counter = Queue.new failure_counter = Queue.new
client = client(acquisition_timeout: 0.9)
100.times.map do |i| 100.times.map do |i|
Thread.new do Thread.new do
success = @client.lock(TEST_KEY, 50, retry_timeout: 0.5) do success = client.lock(TEST_KEY, 50) do
sleep(2) sleep(3)
success_counter << i success_counter << i
end end
@@ -86,15 +131,18 @@ module ClientTests
assert_equal 50, success_counter.size assert_equal 50, success_counter.size
assert_equal 50, failure_counter.size assert_equal 50, failure_counter.size
assert_equal false, client.locked?(TEST_KEY)
end end
def test_instance_multiple_resource_locking_longer_timeout def test_block_multiple_resource_locking_longer_timeout
success_counter = Queue.new success_counter = Queue.new
failure_counter = Queue.new failure_counter = Queue.new
client = client(acquisition_timeout: 3)
100.times.map do |i| 100.times.map do |i|
Thread.new do Thread.new do
success = @client.lock(TEST_KEY, 50, retry_timeout: 2) do success = client.lock(TEST_KEY, 50) do
sleep(0.5) sleep(0.5)
success_counter << i success_counter << i
end end
@@ -105,17 +153,176 @@ module ClientTests
assert_equal 100, success_counter.size assert_equal 100, success_counter.size
assert_equal 0, failure_counter.size assert_equal 0, failure_counter.size
assert_equal false, client.locked?(TEST_KEY)
end
def test_unstale_lock_acquisition
success_counter = Queue.new
failure_counter = Queue.new
client = client(stale_lock_expiration: 0.5)
t1 = Thread.new { client.lock(TEST_KEY) { sleep 0.6; success_counter << 1 } }
sleep 0.3
t2 = Thread.new do
locked = client.lock(TEST_KEY) { success_counter << 1 }
failure_counter << 1 unless locked
end
[t1, t2].map(&:join)
assert_equal 1, success_counter.size
assert_equal 1, failure_counter.size
assert_equal false, client.locked?(TEST_KEY)
end
def test_stale_lock_acquisition
success_counter = Queue.new
failure_counter = Queue.new
client = client(stale_lock_expiration: 0.5)
t1 = Thread.new { client.lock(TEST_KEY) { sleep 0.6; success_counter << 1 } }
sleep 0.55
t2 = Thread.new do
locked = client.lock(TEST_KEY) { success_counter << 1 }
failure_counter << 1 unless locked
end
[t1, t2].map(&:join)
assert_equal 2, success_counter.size
assert_equal 0, failure_counter.size
assert_equal false, client.locked?(TEST_KEY)
end
def test_refresh
client = client(stale_lock_expiration: 0.5)
lock1 = client.lock(TEST_KEY)
assert_equal true, client.locked?(TEST_KEY)
client.refresh(TEST_KEY, lock1)
assert_equal true, client.locked?(TEST_KEY)
sleep 0.55
assert_equal false, client.locked?(TEST_KEY)
lock2 = client.lock(TEST_KEY)
client.refresh(TEST_KEY, lock1)
assert_equal true, client.locked?(TEST_KEY)
client.unlock(TEST_KEY, lock1)
# edge case with refresh lock in the middle
assert_equal true, client.locked?(TEST_KEY)
client.clear(TEST_KEY)
assert_equal false, client.locked?(TEST_KEY)
client.refresh(TEST_KEY, lock2)
assert_equal true, client.locked?(TEST_KEY)
client.unlock(TEST_KEY, lock2)
# now finally unlocked
assert_equal false, client.locked?(TEST_KEY)
end
def test_block_refresh
success_counter = Queue.new
failure_counter = Queue.new
client = client(stale_lock_expiration: 0.5)
t1 = Thread.new do
client.lock(TEST_KEY) do |token|
sleep 0.6
client.refresh(TEST_KEY, token)
sleep 1
success_counter << 1
end
end
t2 = Thread.new do
sleep 0.8
locked = client.lock(TEST_KEY) { success_counter << 1 }
failure_counter << 1 unless locked
end
[t1, t2].map(&:join)
assert_equal 1, success_counter.size
assert_equal 1, failure_counter.size
assert_equal false, client.locked?(TEST_KEY)
end
def test_refresh_multi
success_counter = Queue.new
failure_counter = Queue.new
client = client(stale_lock_expiration: 0.5)
t1 = Thread.new do
client.lock(TEST_KEY, 2) do |token|
sleep 0.4
client.refresh(TEST_KEY, token)
success_counter << 1
sleep 0.5
end
end
t2 = Thread.new do
sleep 0.55
locked = client.lock(TEST_KEY, 2) do
success_counter << 1
sleep 0.5
end
failure_counter << 1 unless locked
end
t3 = Thread.new do
sleep 0.75
locked = client.lock(TEST_KEY, 2) { success_counter << 1 }
failure_counter << 1 unless locked
end
[t1, t2, t3].map(&:join)
assert_equal 2, success_counter.size
assert_equal 1, failure_counter.size
assert_equal false, client.locked?(TEST_KEY)
end end
end end
class TestBaseClient < Minitest::Test class TestBaseClient < Minitest::Test
def setup def setup
@klass = Suo::Client::Base @client = Suo::Client::Base.new(client: {})
end end
def test_not_implemented def test_not_implemented
assert_raises(NotImplementedError) do assert_raises(NotImplementedError) do
@klass.send(:get, TEST_KEY, {}) @client.send(:get, TEST_KEY)
end
assert_raises(NotImplementedError) do
@client.send(:set, TEST_KEY, "", "")
end
assert_raises(NotImplementedError) do
@client.send(:initial_set, TEST_KEY)
end
assert_raises(NotImplementedError) do
@client.send(:clear, TEST_KEY)
end end
end end
end end
@@ -124,13 +331,13 @@ class TestMemcachedClient < Minitest::Test
include ClientTests include ClientTests
def setup def setup
@klass = Suo::Client::Memcached @dalli = Dalli::Client.new("127.0.0.1:11211")
@client = @klass.new @client = Suo::Client::Memcached.new
@klass_client = Dalli::Client.new("127.0.0.1:11211") teardown
end end
def teardown def teardown
@klass_client.delete(TEST_KEY) @dalli.delete(TEST_KEY)
end end
end end
@@ -138,13 +345,13 @@ class TestRedisClient < Minitest::Test
include ClientTests include ClientTests
def setup def setup
@klass = Suo::Client::Redis @redis = Redis.new
@client = @klass.new @client = Suo::Client::Redis.new
@klass_client = Redis.new teardown
end end
def teardown def teardown
@klass_client.del(TEST_KEY) @redis.del(TEST_KEY)
end end
end end

View File

@@ -1,9 +1,13 @@
$LOAD_PATH.unshift File.expand_path("../../lib", __FILE__) $LOAD_PATH.unshift File.expand_path("../../lib", __FILE__)
if ENV["CODECLIMATE_REPO_TOKEN"]
require "codeclimate-test-reporter"
CodeClimate::TestReporter.start
end
require "suo" require "suo"
require "thread" require "thread"
require "minitest/autorun" require "minitest/autorun"
require "minitest/benchmark" require "minitest/benchmark"
ENV["SUO_TEST"] = "true" ENV["SUO_TEST"] = "true"