redis_locks 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: e54f88975c7c22202a262495733bef3bbf25384b
4
+ data.tar.gz: dd6f4a948434588a31ec2086b0bce9e90fb29680
5
+ SHA512:
6
+ metadata.gz: 9c96f4d857b9461508678e335797dda5ffa2b625902ea43621b4af3c1b0efa59b10fd9c71448880dbef58abd2f8354afca7e4f7f9acc82ab435670fef506466f
7
+ data.tar.gz: ac7146e7944e074836d66eef2f12e908b637194151812ac9c96b689944ad66c5264f4029afb1612bae807e1eac0e2ddcb191715dd968efb19540752c2028837a
data/.gitignore ADDED
@@ -0,0 +1,36 @@
1
+ *.gem
2
+ *.rbc
3
+ /.config
4
+ /coverage/
5
+ /InstalledFiles
6
+ /pkg/
7
+ /spec/reports/
8
+ /spec/examples.txt
9
+ /test/tmp/
10
+ /test/version_tmp/
11
+ /tmp/
12
+
13
+ ## Specific to RubyMotion:
14
+ .dat*
15
+ .repl_history
16
+ build/
17
+
18
+ ## Documentation cache and generated files:
19
+ /.yardoc/
20
+ /_yardoc/
21
+ /doc/
22
+ /rdoc/
23
+
24
+ ## Environment normalization:
25
+ /.bundle/
26
+ /vendor/bundle
27
+ /lib/bundler/man/
28
+
29
+ # for a library or gem, you might want to ignore these files since the code is
30
+ # intended to run in multiple environments; otherwise, check them in:
31
+ # Gemfile.lock
32
+ # .ruby-version
33
+ # .ruby-gemset
34
+
35
+ # unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
36
+ .rvmrc
data/Gemfile ADDED
@@ -0,0 +1,12 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Declare your gem's dependencies in cached_counts.gemspec.
4
+ # Bundler will treat runtime dependencies like base dependencies, and
5
+ # development dependencies will be added by default to the :development group.
6
+ gemspec
7
+
8
+ # Declare any dependencies that are still in development here instead of in
9
+ # your gemspec. These might include edge Rails or gems from your path or
10
+ # Git. Remember to move these dependencies to your gemspec before releasing
11
+ # your gem to rubygems.org.
12
+ gem 'pry', group: [:development, :test]
data/Gemfile.lock ADDED
@@ -0,0 +1,44 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ redis_locks (0.0.1)
5
+ redis
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ coderay (1.1.1)
11
+ diff-lcs (1.2.5)
12
+ method_source (0.8.2)
13
+ pry (0.10.3)
14
+ coderay (~> 1.1.0)
15
+ method_source (~> 0.8.1)
16
+ slop (~> 3.4)
17
+ rake (11.1.2)
18
+ redis (3.2.2)
19
+ rspec (3.4.0)
20
+ rspec-core (~> 3.4.0)
21
+ rspec-expectations (~> 3.4.0)
22
+ rspec-mocks (~> 3.4.0)
23
+ rspec-core (3.4.4)
24
+ rspec-support (~> 3.4.0)
25
+ rspec-expectations (3.4.0)
26
+ diff-lcs (>= 1.2.0, < 2.0)
27
+ rspec-support (~> 3.4.0)
28
+ rspec-mocks (3.4.1)
29
+ diff-lcs (>= 1.2.0, < 2.0)
30
+ rspec-support (~> 3.4.0)
31
+ rspec-support (3.4.1)
32
+ slop (3.6.0)
33
+
34
+ PLATFORMS
35
+ ruby
36
+
37
+ DEPENDENCIES
38
+ pry
39
+ rake
40
+ redis_locks!
41
+ rspec
42
+
43
+ BUNDLED WITH
44
+ 1.11.2
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,89 @@
1
+ # redis-locks
2
+ Various locking utilities for Ruby using Redis.
3
+
4
+ All classes are designed to work with Ruby clients distributed across multiple
5
+ processes and/or machines, but assume a single Redis master for correctness.
6
+
7
+ Works with Redis 2.6+.
8
+
9
+ # Utilities
10
+
11
+ ## RedisLocks::Mutex
12
+
13
+ A simple mutex using `setnx`.
14
+
15
+ ```ruby
16
+ require 'redis'
17
+ require 'redis_locks'
18
+
19
+ lock = RedisLocks::Mutex.new('my_key', redis: Redis.new)
20
+
21
+ # high-level use
22
+ lock.lock! do
23
+ # something that can only be done by one process at a time
24
+ end
25
+
26
+ # lower-level options
27
+ lock.lock # acquires lock & returns true
28
+ lock.lock # returns false, lock was not acquired
29
+ lock.unlock # now lock can be acquired again
30
+ ```
31
+
32
+ Supports lock expiry via `expires_in`/`expires_at` arguments to the constructor.
33
+ By default, locks expire after 24 hours.
34
+
35
+
36
+ ## RedisLocks::Semaphore
37
+
38
+ A semaphore implemented with Lua and `lpop`/`blpop`.
39
+
40
+ Supports multiple resources, waits to acquire a resource, and timeouts.
41
+
42
+ ```ruby
43
+ require 'redis'
44
+ require 'redis_locks'
45
+
46
+ semaphore = RedisLocks::Semaphore.new('my_key', redis: Redis.new, resources: 2)
47
+
48
+ # high-level use
49
+ semaphore.lock! do
50
+ # something that can be done by at most two processes at a time
51
+ end
52
+
53
+ # will wait indefinitely for a resource to be free, if necessary (this
54
+ # counter-intuitive use of zero values reflects that of Redis' `blpop`)
55
+ semaphore.lock!(timeout: 0) { }
56
+
57
+ # will wait up to 1 second for a resource to be free
58
+ semaphore.lock!(timeout: 1) { }
59
+
60
+ # lower-level options
61
+ semaphore.lock # acquires resource & returns true
62
+ semaphore.lock # acquires another resource & returns true
63
+ semaphore.lock # returns false, no resources remain
64
+ semaphore.unlock # frees a resource
65
+ ```
66
+
67
+ Supports expiry via `stale_client_timeout` argument to the constructor.
68
+ By default, clients are timed out after 24 hours.
69
+
70
+ ## RedisLocks::TokenBucket
71
+
72
+ A [token-bucket](https://en.wikipedia.org/wiki/Token_bucket) rate limiter implemented with Lua.
73
+
74
+ ```ruby
75
+ require 'redis'
76
+ require 'redis_locks'
77
+
78
+ # allows up to two calls to `take`/`take!` every five seconds
79
+ limiter = RedisLocks::TokenBucket.new('my_key', redis: Redis.new, period: 5, number: 2)
80
+
81
+ 2.times { limiter.take! }
82
+
83
+ limiter.take # false if zero microseconds have passed, true otherwise (in which case a new token has become available)
84
+ limiter.take! # raises RateLimitExceeded
85
+
86
+ sleep(5)
87
+
88
+ limiter.take # true
89
+ ```
data/Rakefile ADDED
@@ -0,0 +1,16 @@
1
+ begin
2
+ require 'bundler/setup'
3
+ rescue LoadError
4
+ puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
5
+ end
6
+
7
+ require 'rdoc/task'
8
+ RDoc::Task.new do |rdoc|
9
+ rdoc.main = "README.md"
10
+ rdoc.rdoc_files.include("README.md", "lib/**/*.rb")
11
+ end
12
+
13
+ require 'rspec/core/rake_task'
14
+ RSpec::Core::RakeTask.new('spec')
15
+
16
+ task :default => :spec
@@ -0,0 +1,9 @@
1
+ require 'redis_locks/version'
2
+ require 'redis_locks/resource_unavailable'
3
+ require 'redis_locks/evalsha_or_eval'
4
+ require 'redis_locks/mutex'
5
+ require 'redis_locks/semaphore'
6
+ require 'redis_locks/token_bucket'
7
+
8
+ module RedisLocks
9
+ end
@@ -0,0 +1,15 @@
1
+ module RedisLocks
2
+
3
+ # This ensures that each Lua script is evaluated at most once; after it has
4
+ # been evaluated, we will be able to call it just by passing its digest.
5
+ def self.evalsha_or_eval(redis:, script:, digest:, keys: [], args: [])
6
+ redis.evalsha digest, keys, args
7
+ rescue Redis::CommandError => e
8
+ if e.message.start_with?('NOSCRIPT')
9
+ redis.eval script, keys, args
10
+ else
11
+ raise
12
+ end
13
+ end
14
+
15
+ end
@@ -0,0 +1,66 @@
1
+ module RedisLocks
2
+ class AlreadyLocked < ResourceUnavailable
3
+ def initialize(key)
4
+ super("Key [#{key}] already locked!")
5
+ end
6
+ end
7
+
8
+ class Mutex
9
+
10
+ NAMESPACE = "mutex"
11
+
12
+ def initialize(key, redis:, expires_in: 86400, expires_at: nil)
13
+ @key = "#{NAMESPACE}:#{key}"
14
+ @redis = redis
15
+ @expires_at = (expires_at.to_i if expires_at) || (Time.now.utc.to_i + expires_in)
16
+ end
17
+
18
+ def lock(&block)
19
+ now = Time.now.utc.to_i
20
+ locked = false
21
+
22
+ if @redis.setnx(@key, @expires_at)
23
+ @redis.expire(@key, @expires_at - now)
24
+ locked = true
25
+ else # it was locked
26
+ if (old_value = @redis.get(@key)).to_i <= now
27
+ # lock has expired
28
+ if @redis.getset_value(@key, @expires_at) == old_value
29
+ locked = true
30
+ end
31
+ end
32
+ end
33
+
34
+ return false unless locked
35
+
36
+ return_or_yield(&block)
37
+ end
38
+
39
+ def lock!(&block)
40
+ locked = lock
41
+ raise AlreadyLocked.new(@key) unless locked
42
+ return_or_yield(&block)
43
+ end
44
+
45
+ # only delete the key if it's still valid, and will be for another 2 seconds
46
+ def unlock
47
+ if Time.now.utc.to_i - 2 < @expires_at
48
+ @redis.del(@key)
49
+ end
50
+ end
51
+
52
+ private
53
+
54
+ def return_or_yield
55
+ return_value = true
56
+ if block_given?
57
+ begin
58
+ return_value = yield
59
+ ensure
60
+ unlock
61
+ end
62
+ end
63
+ return_value
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,4 @@
1
+ module RedisLocks
2
+ class ResourceUnavailable < RuntimeError
3
+ end
4
+ end
@@ -0,0 +1,199 @@
1
+ # Adapted from https://github.com/dv/redis-semaphore - switched to use Lua
2
+ # instead of broken mutex implementation, see issue #23 on GitHub.
3
+ #
4
+ # Options we don't use were removed for simplicity.
5
+ #
6
+ # Original copyright (C) 2011 by David Verhasselt (david@crowdway.com)
7
+ #
8
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ # of this software and associated documentation files (the "Software"), to deal
10
+ # in the Software without restriction, including without limitation the rights
11
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ # copies of the Software, and to permit persons to whom the Software is
13
+ # furnished to do so, subject to the following conditions:
14
+ #
15
+ # The above copyright notice and this permission notice shall be included in
16
+ # all copies or substantial portions of the Software.
17
+ #
18
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24
+ # THE SOFTWARE.
25
+ #
26
+ require 'digest'
27
+
28
+ module RedisLocks
29
+ class SemaphoreUnavailable < ResourceUnavailable
30
+ def initialize(key, resources)
31
+ super("Key [#{key}] has 0/#{resources} resources available!")
32
+ end
33
+ end
34
+
35
+ class Semaphore
36
+
37
+ NAMESPACE = "semaphore-lua"
38
+
39
+ # Removes stale locks, then ensures that all resources which aren't locked
40
+ # are marked as available.
41
+ SETUP_SCRIPT = <<-LUA
42
+ local avail_key = KEYS[1]
43
+ local grabbed_key = KEYS[2]
44
+
45
+ local expected_resources = tonumber(ARGV[1])
46
+ local stale_before = tonumber(ARGV[2])
47
+
48
+ redis.call('zremrangebyscore', grabbed_key, -1, stale_before)
49
+
50
+ local found_resources = redis.call('llen', avail_key) + redis.call('zcard', grabbed_key)
51
+ if found_resources < expected_resources then
52
+ for i=1,(expected_resources - found_resources) do
53
+ redis.call('rpush', avail_key, 1)
54
+ end
55
+ end
56
+ LUA
57
+
58
+ SETUP_DIGEST = Digest::SHA1.hexdigest(SETUP_SCRIPT)
59
+
60
+ # `resources` is the number of clients allowed to lock the semaphore
61
+ # concurrently.
62
+ #
63
+ # `stale_client_timeout` is the threshold of time before we assume that
64
+ # something has gone terribly wrong with a client and we invalidate its lock.
65
+ def initialize(key, redis:, resources: 1, stale_client_timeout: 86400)
66
+ @key = key
67
+ @resource_count = resources.to_i
68
+ @stale_client_timeout = stale_client_timeout.to_f
69
+ @redis = redis
70
+ @tokens = []
71
+
72
+ raise ArgumentError.new("Lock key is required") if @key.nil? || @key.empty?
73
+ raise ArgumentError.new("resources must be > 0") unless @resource_count > 0
74
+ raise ArgumentError.new("stale_client_timeout must be > 0") unless @stale_client_timeout > 0
75
+ end
76
+
77
+ # Forcefully clear the lock. Be careful!
78
+ def delete!
79
+ @redis.del(available_key)
80
+ @redis.del(grabbed_key)
81
+ @tokens = []
82
+ end
83
+
84
+ # Acquire a resource from the semaphore, if available. Returns false if no
85
+ # resources are available.
86
+ #
87
+ # `timeout` is how long to wait, blocking, until a resource is available.
88
+ # The default is nil, meaning don't block. A timeout of zero means block forever.
89
+ # (This is a bit weird, but corresponds to how blpop uses timeout values.)
90
+ #
91
+ # If passed a block, if a resource is available, runs the block and then
92
+ # unlocks.
93
+ #
94
+ # If called without a block, if a resource is available, returns a token.
95
+ # Caller is then responsible for unlocking the token.
96
+ #
97
+ # This isn't atomic--if the process dies, we could remove something from the
98
+ # available queue without adding it to the grabbed set--but that's ok, the
99
+ # semaphore will recover just as if this was a stale client that left its
100
+ # token in the grabbed set forever.
101
+ def lock(timeout: nil, &block)
102
+ ensure_exists_and_release_stale_locks!
103
+
104
+ success =
105
+ if timeout
106
+ !@redis.blpop(available_key, timeout.to_i).nil?
107
+ else
108
+ !@redis.lpop(available_key).nil?
109
+ end
110
+
111
+ return false unless success
112
+
113
+ token = SecureRandom.hex(16)
114
+ @tokens.push(token)
115
+ @redis.zadd(grabbed_key, epoch_f, token)
116
+
117
+ return_or_yield(token, &block)
118
+ end
119
+
120
+ def wait(timeout: 0, &block)
121
+ lock(timeout: timeout, &block)
122
+ end
123
+
124
+ def lock!(timeout: nil, &block)
125
+ token = lock(timeout: timeout)
126
+ raise SemaphoreUnavailable.new(@key, @resource_count) unless token
127
+ return_or_yield(token, &block)
128
+ end
129
+
130
+ def wait!(timeout: 0, &block)
131
+ lock!(timeout: timeout, &block)
132
+ end
133
+
134
+ # Release a resource back to the semaphore. Should normally be called with an
135
+ # explicit token.
136
+ #
137
+ # This isn't atomic--if the process dies, we could remove something from the
138
+ # blocked set without adding it to the available queue--but that's ok, the
139
+ # semaphore will recover just as if this was a stale client that left its
140
+ # token in the grabbed set forever.
141
+ def unlock(token = @tokens.pop)
142
+ return unless token
143
+
144
+ removed = @redis.zrem grabbed_key, token
145
+ if removed
146
+ @redis.lpush available_key, 1
147
+ end
148
+
149
+ removed
150
+ end
151
+ alias_method :signal, :unlock
152
+
153
+ private
154
+
155
+ def return_or_yield(token)
156
+ return_value = token
157
+ if block_given?
158
+ begin
159
+ return_value = yield token
160
+ ensure
161
+ unlock(token)
162
+ end
163
+ end
164
+ return_value
165
+ end
166
+
167
+ def ensure_exists_and_release_stale_locks!
168
+ RedisLocks.evalsha_or_eval(
169
+ redis: @redis,
170
+ script: SETUP_SCRIPT,
171
+ digest: SETUP_DIGEST,
172
+ keys: [available_key, grabbed_key],
173
+ args: [@resource_count, stale_before]
174
+ )
175
+ end
176
+
177
+ def namespaced_key(variable)
178
+ "#{NAMESPACE}:#{@key}:#{variable}"
179
+ end
180
+
181
+ def available_key
182
+ @available_key ||= namespaced_key('AVAILABLE')
183
+ end
184
+
185
+ def grabbed_key
186
+ @grabbed_key ||= namespaced_key('GRABBED')
187
+ end
188
+
189
+ def stale_before
190
+ epoch_f - @stale_client_timeout
191
+ end
192
+
193
+ def epoch_f
194
+ epoch_i, microseconds = @redis.time
195
+ epoch_i + microseconds.to_f / 1_000_000
196
+ end
197
+
198
+ end
199
+ end
@@ -0,0 +1,69 @@
1
+ require 'digest'
2
+
3
+ module RedisLocks
4
+ class RateLimitExceeded < ResourceUnavailable
5
+ def initialize(key, rps)
6
+ super("Rate limit of #{rps}/second on [#{key}] exceeded!")
7
+ end
8
+ end
9
+
10
+ class TokenBucket
11
+
12
+ NAMESPACE = "token-bucket"
13
+
14
+ SCRIPT = <<-LUA
15
+ local epoch = tonumber(ARGV[1])
16
+ local rps = tonumber(ARGV[2])
17
+ local burst = tonumber(ARGV[3])
18
+ local key = KEYS[1]
19
+
20
+ local token = 1.0 / rps
21
+ local t = redis.call('get', key)
22
+ if not t then
23
+ t = epoch
24
+ else
25
+ t = tonumber(t)
26
+ end
27
+
28
+ if t < epoch then
29
+ t = epoch
30
+ elseif t > (epoch + (burst * token)) then
31
+ return 0
32
+ end
33
+
34
+ redis.call('set', key, t + token)
35
+ return 1
36
+ LUA
37
+
38
+ DIGEST = Digest::SHA1.hexdigest(SCRIPT)
39
+
40
+ # `number` tokens are added to the bucket every `period` seconds (up to a
41
+ # max of `number` tokens being available). Each time a resource is used, a
42
+ # token is removed from the bucket; if no tokens are available, no resource
43
+ # may be used.
44
+ def initialize(key, redis:, period: 1, number: 1)
45
+ @key = "#{NAMESPACE}:#{key}".freeze
46
+ @rps = number.to_f / period.to_i
47
+ @burst = number.to_i
48
+ @redis = redis
49
+ end
50
+
51
+ def take
52
+ epoch_i, microseconds = @redis.time
53
+ epoch_f = epoch_i + (microseconds.to_f/1_000_000)
54
+ took = RedisLocks.evalsha_or_eval(
55
+ redis: @redis,
56
+ script: SCRIPT,
57
+ digest: DIGEST,
58
+ keys: [@key],
59
+ args: [epoch_f, @rps, @burst]
60
+ )
61
+ took == 1
62
+ end
63
+
64
+ def take!
65
+ raise RateLimitExceeded.new(@key, @rps) unless take
66
+ end
67
+
68
+ end
69
+ end
@@ -0,0 +1,3 @@
1
+ module RedisLocks
2
+ VERSION = '0.0.1'
3
+ end
@@ -0,0 +1,26 @@
1
+ $:.push File.expand_path("../lib", __FILE__)
2
+
3
+ # Maintain your gem's version:
4
+ require "redis_locks/version"
5
+
6
+ # Describe your gem and declare its dependencies:
7
+ Gem::Specification.new do |s|
8
+ s.name = "redis_locks"
9
+ s.version = RedisLocks::VERSION
10
+ s.authors = ["Academia.edu"]
11
+ s.email = ["david@academia.edu"]
12
+ s.homepage = "https://github.com/academia-edu/redis_locks"
13
+ s.summary = "Various locking utilities for Ruby using Redis"
14
+ s.description = "Various locking utilities for Ruby using Redis, including a mutex, a semaphore, and a token bucket rate limiter"
15
+ s.license = "MIT"
16
+
17
+ s.files = `git ls-files`.split("\n")
18
+ s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
19
+ s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
20
+ s.require_paths = ["lib"]
21
+
22
+ s.add_dependency "redis"
23
+
24
+ s.add_development_dependency "rspec"
25
+ s.add_development_dependency "rake"
26
+ end
@@ -0,0 +1,61 @@
1
+ require 'spec_helper'
2
+
3
+ describe RedisLocks::Mutex do
4
+ let(:mutex) {
5
+ RedisLocks::Mutex.new(
6
+ 'testmutex',
7
+ redis: $redis
8
+ )
9
+ }
10
+
11
+ it 'allows locking' do
12
+ expect(mutex.lock).to be_truthy
13
+ end
14
+
15
+ it 'allows locking via lock!' do
16
+ expect { mutex.lock! }.not_to raise_error
17
+ end
18
+
19
+ it 'runs block' do
20
+ ran = false
21
+ mutex.lock { ran = true }
22
+ expect(ran).to be_truthy
23
+ end
24
+
25
+ it 'runs two blocks successively' do
26
+ ran = 0
27
+ mutex.lock { ran += 1 }
28
+ mutex.lock { ran += 1 }
29
+ expect(ran).to eq(2)
30
+ end
31
+
32
+ context 'when locked' do
33
+ before do
34
+ mutex.lock!
35
+ end
36
+
37
+ it 'does not allow locking again' do
38
+ expect(mutex.lock).to be_falsey
39
+ end
40
+
41
+ it 'does not run block' do
42
+ ran = false
43
+ mutex.lock { ran = true }
44
+ expect(ran).to be_falsey
45
+ end
46
+
47
+ it 'raises error on lock!' do
48
+ expect { mutex.lock! }.to raise_error(RedisLocks::AlreadyLocked)
49
+ end
50
+
51
+ context 'and then unlocked' do
52
+ before do
53
+ mutex.unlock
54
+ end
55
+
56
+ it 'allows locking' do
57
+ expect(mutex.lock).to be_truthy
58
+ end
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,130 @@
1
+ require 'spec_helper'
2
+
3
+ describe RedisLocks::Semaphore do
4
+ context 'with one resource' do
5
+ let(:semaphore) {
6
+ RedisLocks::Semaphore.new(
7
+ 'testsemaphore',
8
+ redis: $redis,
9
+ resources: 1
10
+ )
11
+ }
12
+
13
+ it 'allows locking' do
14
+ expect(semaphore.lock).to be_truthy
15
+ end
16
+
17
+ it 'allows locking via lock!' do
18
+ expect { semaphore.lock! }.not_to raise_error
19
+ end
20
+
21
+ it 'allows locking with timeout' do
22
+ expect(semaphore.lock timeout: 1).to be_truthy
23
+ end
24
+
25
+ it 'allows locking with infinite timeout' do
26
+ expect(semaphore.lock timeout: 0).to be_truthy
27
+ end
28
+
29
+ it 'runs block' do
30
+ ran = false
31
+ semaphore.lock { ran = true }
32
+ expect(ran).to be_truthy
33
+ end
34
+
35
+ it 'runs two blocks successively' do
36
+ ran = 0
37
+ semaphore.lock { ran += 1 }
38
+ semaphore.lock { ran += 1 }
39
+ expect(ran).to eq(2)
40
+ end
41
+
42
+ context 'when locked' do
43
+ before do
44
+ @token = semaphore.lock!
45
+ end
46
+
47
+ it 'does not allow locking again' do
48
+ expect(semaphore.lock).to be_falsey
49
+ end
50
+
51
+ it 'does not allow locking with timeout' do
52
+ expect(semaphore.lock timeout: 1).to be_falsey
53
+ end
54
+
55
+ it 'waits forever with infinite timeout' do
56
+ t = Thread.new do
57
+ semaphore.lock timeout: 0
58
+ end
59
+
60
+ sleep(2)
61
+ expect(t).to be_alive
62
+ t.kill
63
+ end
64
+
65
+ it 'does not run block' do
66
+ ran = false
67
+ semaphore.lock { ran = true }
68
+ expect(ran).to be_falsey
69
+ end
70
+
71
+ it 'raises error on lock!' do
72
+ expect { semaphore.lock! }.to raise_error(RedisLocks::SemaphoreUnavailable)
73
+ end
74
+
75
+ context 'and then unlocked' do
76
+ before do
77
+ semaphore.unlock @token
78
+ end
79
+
80
+ it 'allows locking' do
81
+ expect(semaphore.lock).to be_truthy
82
+ end
83
+ end
84
+ end
85
+ end
86
+
87
+ context 'with two resources' do
88
+ let(:semaphore) {
89
+ RedisLocks::Semaphore.new(
90
+ 'testsem',
91
+ redis: $redis,
92
+ resources: 2
93
+ )
94
+ }
95
+
96
+ it 'allows locking' do
97
+ expect(semaphore.lock).to be_truthy
98
+ end
99
+
100
+ context 'after one lock' do
101
+ before do
102
+ @token = semaphore.lock
103
+ end
104
+
105
+ it 'allows locking again' do
106
+ expect(semaphore.lock).to be_truthy
107
+ end
108
+
109
+ context 'after another lock' do
110
+ before do
111
+ semaphore.lock
112
+ end
113
+
114
+ it 'does not allow locking a third time' do
115
+ expect(semaphore.lock).to be_falsey
116
+ end
117
+
118
+ context 'after releasing first lock' do
119
+ before do
120
+ semaphore.unlock @token
121
+ end
122
+
123
+ it 'allows locking' do
124
+ expect(semaphore.lock).to be_truthy
125
+ end
126
+ end
127
+ end
128
+ end
129
+ end
130
+ end
@@ -0,0 +1,58 @@
1
+ require 'spec_helper'
2
+
3
+ describe RedisLocks::TokenBucket do
4
+ context 'with two tokens per each two seconds' do
5
+ let(:bucket) {
6
+ RedisLocks::TokenBucket.new(
7
+ "testbucket",
8
+ redis: $redis,
9
+ period: 2,
10
+ number: 2
11
+ )
12
+ }
13
+
14
+ it 'allows resource to be used' do
15
+ expect(bucket.take).to be_truthy
16
+ end
17
+
18
+ it 'allows resource to be used via take!' do
19
+ expect { bucket.take! }.not_to raise_error
20
+ end
21
+
22
+ context 'with one resource used' do
23
+ before do
24
+ bucket.take!
25
+ end
26
+
27
+ it 'allows another resource to be used' do
28
+ expect(bucket.take).to be_truthy
29
+ end
30
+ end
31
+
32
+ context 'with all resources used' do
33
+ before do
34
+ # three rather than two because the microseconds since the first
35
+ # execution will allow another token to become available
36
+ 3.times { bucket.take! }
37
+ end
38
+
39
+ it 'does not allow another resource to be used' do
40
+ expect(bucket.take).to be_falsey
41
+ end
42
+
43
+ it 'raises error on take!' do
44
+ expect { bucket.take! }.to raise_error(RedisLocks::RateLimitExceeded)
45
+ end
46
+
47
+ context 'after waiting' do
48
+ before do
49
+ sleep(2)
50
+ end
51
+
52
+ it 'allows another resource to be taken' do
53
+ expect(bucket.take).to be_truthy
54
+ end
55
+ end
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,16 @@
1
+ require 'rubygems'
2
+ require 'bundler/setup'
3
+ require 'pry'
4
+ require 'redis'
5
+ require 'redis_locks'
6
+ require 'thread'
7
+
8
+ $redis = Redis.new(db: ENV['REDIS_LOCKS_SPEC_DB'] || 15)
9
+
10
+ raise "#{$redis.inspect} is non-empty!" if $redis.keys.any?
11
+
12
+ RSpec.configure do |config|
13
+ config.after(:each) do
14
+ $redis.flushdb
15
+ end
16
+ end
metadata ADDED
@@ -0,0 +1,110 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: redis_locks
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Academia.edu
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2016-05-15 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: redis
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rspec
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ description: Various locking utilities for Ruby using Redis, including a mutex, a
56
+ semaphore, and a token bucket rate limiter
57
+ email:
58
+ - david@academia.edu
59
+ executables: []
60
+ extensions: []
61
+ extra_rdoc_files: []
62
+ files:
63
+ - ".gitignore"
64
+ - Gemfile
65
+ - Gemfile.lock
66
+ - LICENSE
67
+ - README.md
68
+ - Rakefile
69
+ - lib/redis_locks.rb
70
+ - lib/redis_locks/evalsha_or_eval.rb
71
+ - lib/redis_locks/mutex.rb
72
+ - lib/redis_locks/resource_unavailable.rb
73
+ - lib/redis_locks/semaphore.rb
74
+ - lib/redis_locks/token_bucket.rb
75
+ - lib/redis_locks/version.rb
76
+ - redis_locks.gemspec
77
+ - spec/redis_locks/mutex_spec.rb
78
+ - spec/redis_locks/semaphore_spec.rb
79
+ - spec/redis_locks/token_bucket_spec.rb
80
+ - spec/spec_helper.rb
81
+ homepage: https://github.com/academia-edu/redis_locks
82
+ licenses:
83
+ - MIT
84
+ metadata: {}
85
+ post_install_message:
86
+ rdoc_options: []
87
+ require_paths:
88
+ - lib
89
+ required_ruby_version: !ruby/object:Gem::Requirement
90
+ requirements:
91
+ - - ">="
92
+ - !ruby/object:Gem::Version
93
+ version: '0'
94
+ required_rubygems_version: !ruby/object:Gem::Requirement
95
+ requirements:
96
+ - - ">="
97
+ - !ruby/object:Gem::Version
98
+ version: '0'
99
+ requirements: []
100
+ rubyforge_project:
101
+ rubygems_version: 2.4.5.1
102
+ signing_key:
103
+ specification_version: 4
104
+ summary: Various locking utilities for Ruby using Redis
105
+ test_files:
106
+ - spec/redis_locks/mutex_spec.rb
107
+ - spec/redis_locks/semaphore_spec.rb
108
+ - spec/redis_locks/token_bucket_spec.rb
109
+ - spec/spec_helper.rb
110
+ has_rdoc: