redis_locker 0.1.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/.gitignore +12 -0
- data/.gitlab-ci.yml +9 -0
- data/.rspec +3 -0
- data/.rubocop.yml +13 -0
- data/CODE_OF_CONDUCT.md +84 -0
- data/Gemfile +12 -0
- data/LICENSE.txt +21 -0
- data/README.md +145 -0
- data/Rakefile +12 -0
- data/bin/console +15 -0
- data/bin/setup +8 -0
- data/lib/redis_locker.rb +100 -0
- data/lib/redis_locker/configuration.rb +11 -0
- data/lib/redis_locker/errors.rb +24 -0
- data/lib/redis_locker/locker.rb +69 -0
- data/lib/redis_locker/method_locker.rb +35 -0
- data/lib/redis_locker/model_locker.rb +40 -0
- data/lib/redis_locker/redis_connection.rb +11 -0
- data/lib/redis_locker/version.rb +5 -0
- data/redis_locker.gemspec +38 -0
- metadata +106 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: d65d73a33f9940ac20c1daa5cd0456f3dbe104954f65d10bb6b155a07ed59d23
|
4
|
+
data.tar.gz: 72a8d2215a4106ee6a225c8d3f0fe7b2062efbdb63aa2ea11e5638e416a25343
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: 56d93a48263cc57c359b92050da054437a0e129a64070a443ea21be014643ea0fbbfba7390295517d24c226a141236535baaef0b8c21b2259f8eb7a078ca5061
|
7
|
+
data.tar.gz: e0c95badb1d3988b1f43f317a3685e8e8229fa2f1dace17b165ab153829008a236c67465e7ba06e1ac4eac5ff6a43c4550f1fe8abb0f65a4e9fe1da90a94311b
|
data/.gitignore
ADDED
data/.gitlab-ci.yml
ADDED
data/.rspec
ADDED
data/.rubocop.yml
ADDED
data/CODE_OF_CONDUCT.md
ADDED
@@ -0,0 +1,84 @@
|
|
1
|
+
# Contributor Covenant Code of Conduct
|
2
|
+
|
3
|
+
## Our Pledge
|
4
|
+
|
5
|
+
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
|
6
|
+
|
7
|
+
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
|
8
|
+
|
9
|
+
## Our Standards
|
10
|
+
|
11
|
+
Examples of behavior that contributes to a positive environment for our community include:
|
12
|
+
|
13
|
+
* Demonstrating empathy and kindness toward other people
|
14
|
+
* Being respectful of differing opinions, viewpoints, and experiences
|
15
|
+
* Giving and gracefully accepting constructive feedback
|
16
|
+
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
|
17
|
+
* Focusing on what is best not just for us as individuals, but for the overall community
|
18
|
+
|
19
|
+
Examples of unacceptable behavior include:
|
20
|
+
|
21
|
+
* The use of sexualized language or imagery, and sexual attention or
|
22
|
+
advances of any kind
|
23
|
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
24
|
+
* Public or private harassment
|
25
|
+
* Publishing others' private information, such as a physical or email
|
26
|
+
address, without their explicit permission
|
27
|
+
* Other conduct which could reasonably be considered inappropriate in a
|
28
|
+
professional setting
|
29
|
+
|
30
|
+
## Enforcement Responsibilities
|
31
|
+
|
32
|
+
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
|
33
|
+
|
34
|
+
Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
|
35
|
+
|
36
|
+
## Scope
|
37
|
+
|
38
|
+
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
|
39
|
+
|
40
|
+
## Enforcement
|
41
|
+
|
42
|
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at wegrzycki_. All complaints will be reviewed and investigated promptly and fairly.
|
43
|
+
|
44
|
+
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
|
45
|
+
|
46
|
+
## Enforcement Guidelines
|
47
|
+
|
48
|
+
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
|
49
|
+
|
50
|
+
### 1. Correction
|
51
|
+
|
52
|
+
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
|
53
|
+
|
54
|
+
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
|
55
|
+
|
56
|
+
### 2. Warning
|
57
|
+
|
58
|
+
**Community Impact**: A violation through a single incident or series of actions.
|
59
|
+
|
60
|
+
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
|
61
|
+
|
62
|
+
### 3. Temporary Ban
|
63
|
+
|
64
|
+
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
|
65
|
+
|
66
|
+
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
|
67
|
+
|
68
|
+
### 4. Permanent Ban
|
69
|
+
|
70
|
+
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
|
71
|
+
|
72
|
+
**Consequence**: A permanent ban from any sort of public interaction within the community.
|
73
|
+
|
74
|
+
## Attribution
|
75
|
+
|
76
|
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
|
77
|
+
available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
78
|
+
|
79
|
+
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
|
80
|
+
|
81
|
+
[homepage]: https://www.contributor-covenant.org
|
82
|
+
|
83
|
+
For answers to common questions about this code of conduct, see the FAQ at
|
84
|
+
https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
|
data/Gemfile
ADDED
data/LICENSE.txt
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
The MIT License (MIT)
|
2
|
+
|
3
|
+
Copyright (c) 2021 wegrzycki_
|
4
|
+
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
7
|
+
in the Software without restriction, including without limitation the rights
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
10
|
+
furnished to do so, subject to the following conditions:
|
11
|
+
|
12
|
+
The above copyright notice and this permission notice shall be included in
|
13
|
+
all copies or substantial portions of the Software.
|
14
|
+
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
21
|
+
THE SOFTWARE.
|
data/README.md
ADDED
@@ -0,0 +1,145 @@
|
|
1
|
+
# RedisLocker
|
2
|
+
|
3
|
+
RedisLocker is a gem which provides locking system with redis backend.
|
4
|
+
|
5
|
+
## Installation
|
6
|
+
|
7
|
+
Add this line to your application's Gemfile:
|
8
|
+
|
9
|
+
```ruby
|
10
|
+
gem 'redis_locker'
|
11
|
+
```
|
12
|
+
|
13
|
+
And then execute:
|
14
|
+
|
15
|
+
$ bundle install
|
16
|
+
|
17
|
+
Or install it yourself as:
|
18
|
+
|
19
|
+
$ gem install redis_locker
|
20
|
+
|
21
|
+
## Usage
|
22
|
+
|
23
|
+
Main idea of RedisLocker is to provide simple interface for blocking models and its methods.
|
24
|
+
### Configuration
|
25
|
+
RedisLocker needs redis obviously so you have to pass redis connection with `configure` block
|
26
|
+
```Ruby
|
27
|
+
RedisLocker.configure do |config|
|
28
|
+
config.redis_connection = Redis.new
|
29
|
+
end
|
30
|
+
```
|
31
|
+
above snippet has to be called before you start using redis lock so eg. if you're using Ruby on Rails you can place it in `application.rb`
|
32
|
+
### Model
|
33
|
+
A model in RedisLocker is any class that implements `id` method. To make model RedisLockable you have to include RedisLocker in your class
|
34
|
+
```ruby
|
35
|
+
class MyModel
|
36
|
+
include RedisLocker
|
37
|
+
end
|
38
|
+
```
|
39
|
+
Every lock is internally identified by model's `id` thus if you will lock model with id=10, then model with id=11 will be unlocked but every other instance with id=10 will be locked.
|
40
|
+
|
41
|
+
### Locking
|
42
|
+
RedisLocker has two types of locks: `model_lock` and `method_lock`. Important thing is that every `method_lock` creates `model_lock`.
|
43
|
+
#### High Level Api
|
44
|
+
High Level Api is provided by instance method `with_redis_lock` and two class methods `lock_every_method_call` and `lock_method`.
|
45
|
+
##### `with_redis_lock`
|
46
|
+
`with_redis_lock` is an api to deal with model locks. It locks an object, then executes passed block and after that unlocks object
|
47
|
+
```ruby
|
48
|
+
some_redis_lockable_object.with_redis_lock do
|
49
|
+
some_task
|
50
|
+
end
|
51
|
+
```
|
52
|
+
If there will be another `with_redis_lock` called then second call will fail.
|
53
|
+
|
54
|
+
##### `lock_method`
|
55
|
+
`lock_method` internally wraps method to `with_redis_lock` call every time when it's called.
|
56
|
+
```ruby
|
57
|
+
class Model
|
58
|
+
include RedisLocker
|
59
|
+
lock_method :some_method
|
60
|
+
def id
|
61
|
+
10
|
62
|
+
end
|
63
|
+
def some_method
|
64
|
+
#sth
|
65
|
+
end
|
66
|
+
end
|
67
|
+
```
|
68
|
+
Code above creates `method_lock` for `:some_method` and `model_lock` for `Model` with id=10 every time when `some_method` is called
|
69
|
+
##### `lock_every_method_call`
|
70
|
+
It effectively does same thing as adding `lock_method` for every method in Model class except method passed as excluded methods.
|
71
|
+
```ruby
|
72
|
+
class Model
|
73
|
+
include RedisLocker
|
74
|
+
lock_every method_call except: [:id, :initialize, :not_locked_method]
|
75
|
+
def id
|
76
|
+
10
|
77
|
+
end
|
78
|
+
def locked_method
|
79
|
+
#sth
|
80
|
+
end
|
81
|
+
def not_locked_method
|
82
|
+
#sth
|
83
|
+
end
|
84
|
+
end
|
85
|
+
```
|
86
|
+
Default excluded methods are `id` and `initialize`
|
87
|
+
##### Additional options
|
88
|
+
Every high level api method accepts same options: `:strategy`, `:retry_interval` and `:retry_count`. Unless you're using `:retry` startegy, `:retry_count` and `:retry_interval` will be ignored
|
89
|
+
###### `:strategy`
|
90
|
+
`:strategy` tells RedisLocker what to do when locked action is tried to be performed, default strategy is `:exception`.\
|
91
|
+
Exception ( `strategy: :exception` ) strategy raises `RedisLocker::Errors::Locked` when another lock on resource is present.\
|
92
|
+
Retry ( `strategy: :retry` ) strategy tries `:retry_count + 1` times to execute code with `:retry_interval` between tries.
|
93
|
+
```ruby
|
94
|
+
class Model
|
95
|
+
lock_method :some_method, strategy: :retry, retry_count: 2, retry_interval: 1
|
96
|
+
# rest of class omitted
|
97
|
+
end
|
98
|
+
```
|
99
|
+
above snippet after `some_method` was called tries to execute `some_method`, when lock occurs it will try two times with 1 second interval. If lock will be still present then it will raise `RedisLocker::Errors::Locked`\
|
100
|
+
Silently die ( `strategy: :silently_die` ) strategy returns false if lock occurs
|
101
|
+
#### Low level api
|
102
|
+
RedisLocker provides also low level api which allows to manualy locking and unlocking models, which can be helpful sometimes but shouldn't be used with good reason
|
103
|
+
##### lock
|
104
|
+
`lock` method locks model and returns `true` if model was locked successfuly or `false` if model is already locked
|
105
|
+
##### lock!
|
106
|
+
`lock!` method does same thing as `lock` but if model was locked already it raises `RedisLocker::Errors::AlreadyLocked` error
|
107
|
+
##### unlock
|
108
|
+
`unlock` unlocks object if there is lock and returns `true`, otherwise returns `false`
|
109
|
+
##### locked?
|
110
|
+
`locked?` returns if object is locked
|
111
|
+
|
112
|
+
You can mix low level and high level api
|
113
|
+
```ruby
|
114
|
+
some_model.lock
|
115
|
+
```
|
116
|
+
then if you try in another place
|
117
|
+
```ruby
|
118
|
+
some_model.with_redis_lock strategy: :exception do
|
119
|
+
#sth
|
120
|
+
end
|
121
|
+
```
|
122
|
+
### releasing all locks
|
123
|
+
When you or someone else messed up with locks which are still present in redis you can use `RedisLocker.release_locks!` which removes all locks in redis.
|
124
|
+
It will raise exception because `some_model` is locked. But you will be able to call some locked method because there is no lock on any specific method.
|
125
|
+
### Extending RedisLocker
|
126
|
+
You can write own locker by inheriting from `RedisLocker::Locker`, you have to implement `lock`, `lock!`, `locked?` and `unlock` methods. `RedisLocker::Locker` provides unique `@instance_hash` to sign locks and `with_redis_lock` method with implemented `:exception`, `:retry` and `:silently_die` strategies. You aren't forced to use Redis to store locks, if you want to you have to include `RedisLocker::RedisConnection` module which provides `redis` method to access redis connection. Otherwise you have to write own storing logic eg. using DB, own store engine or even files.
|
127
|
+
|
128
|
+
|
129
|
+
## Development
|
130
|
+
|
131
|
+
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
|
132
|
+
|
133
|
+
To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
|
134
|
+
|
135
|
+
## Contributing
|
136
|
+
|
137
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/rwegrzyniak/redis_locker. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/rwegrzyniak/redis_locker/blob/master/CODE_OF_CONDUCT.md).
|
138
|
+
|
139
|
+
## License
|
140
|
+
|
141
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
142
|
+
|
143
|
+
## Code of Conduct
|
144
|
+
|
145
|
+
Everyone interacting in the RedisLocker project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/rwegrzyniak/redis_locker/blob/master/CODE_OF_CONDUCT.md).
|
data/Rakefile
ADDED
data/bin/console
ADDED
@@ -0,0 +1,15 @@
|
|
1
|
+
#!/usr/bin/env ruby
|
2
|
+
# frozen_string_literal: true
|
3
|
+
|
4
|
+
require "bundler/setup"
|
5
|
+
require "redis_locker"
|
6
|
+
|
7
|
+
# You can add fixtures and/or initialization code here to make experimenting
|
8
|
+
# with your gem easier. You can also use a different console, if you like.
|
9
|
+
|
10
|
+
# (If you use this, don't forget to add pry to your Gemfile!)
|
11
|
+
# require "pry"
|
12
|
+
# Pry.start
|
13
|
+
|
14
|
+
require "irb"
|
15
|
+
IRB.start(__FILE__)
|
data/bin/setup
ADDED
data/lib/redis_locker.rb
ADDED
@@ -0,0 +1,100 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
#
|
3
|
+
require "zeitwerk"
|
4
|
+
|
5
|
+
module RedisLocker
|
6
|
+
STRATEGIES = %i[exception retry silently_die].freeze
|
7
|
+
DEFAULT_RETRY_COUNT = 3
|
8
|
+
DEFAULT_RETRY_INTERVAL = 1
|
9
|
+
MODEL_LOCK_STRING = "model_lock"
|
10
|
+
DEFAULT_STRATEGY = :exception
|
11
|
+
DEFAULT_EXCLUDED_METHODS = %i[id initialize].freeze
|
12
|
+
class << self
|
13
|
+
def configuration
|
14
|
+
@configuration ||= Configuration.new
|
15
|
+
end
|
16
|
+
|
17
|
+
def configure
|
18
|
+
yield(configuration)
|
19
|
+
end
|
20
|
+
|
21
|
+
def release_locks!
|
22
|
+
configuration.redis_connection.del(configuration.redis_connection.keys("LOCKER:*"))
|
23
|
+
end
|
24
|
+
|
25
|
+
|
26
|
+
end
|
27
|
+
|
28
|
+
def self.included(base_klass)
|
29
|
+
base_klass.extend(ClassMethods)
|
30
|
+
base_klass.include(InstanceMethods)
|
31
|
+
interceptor = const_set("#{base_klass.name}Interceptor", Module.new)
|
32
|
+
interceptor.class_eval do
|
33
|
+
def initialize(*args, **opts, &block)
|
34
|
+
@model_locker = RedisLocker::ModelLocker.new(self)
|
35
|
+
@method_lockers = {}
|
36
|
+
super(*args, **opts, &block)
|
37
|
+
end
|
38
|
+
end
|
39
|
+
base_klass.prepend interceptor
|
40
|
+
end
|
41
|
+
|
42
|
+
module ClassMethods
|
43
|
+
def lock_every_method_call(strategy: DEFAULT_STRATEGY, retry_count: DEFAULT_RETRY_COUNT, retry_interval: DEFAULT_RETRY_INTERVAL,
|
44
|
+
exclude: DEFAULT_EXCLUDED_METHODS)
|
45
|
+
interceptor = const_get("#{name}Interceptor")
|
46
|
+
self.define_singleton_method(:method_added) do |method|
|
47
|
+
return super(method) if exclude.include? method
|
48
|
+
|
49
|
+
interceptor.define_method(method) do |*args, **opts, &block|
|
50
|
+
returned_value = nil
|
51
|
+
method_locker(method).with_redis_lock strategy: strategy, retry_count: retry_count, retry_interval: retry_interval do
|
52
|
+
returned_value = super(*args, **opts, &block)
|
53
|
+
end
|
54
|
+
returned_value
|
55
|
+
end
|
56
|
+
end
|
57
|
+
end
|
58
|
+
|
59
|
+
def lock_method(method, strategy: DEFAULT_STRATEGY, retry_count: DEFAULT_RETRY_COUNT, retry_interval: DEFAULT_RETRY_INTERVAL)
|
60
|
+
interceptor = const_get("#{name}Interceptor")
|
61
|
+
interceptor.define_method(method) do |*args, **opts, &block|
|
62
|
+
returned_value = nil
|
63
|
+
method_locker(method).with_redis_lock strategy: strategy, retry_count: retry_count, retry_interval: retry_interval do
|
64
|
+
returned_value = super(*args, **opts, &block)
|
65
|
+
end
|
66
|
+
returned_value
|
67
|
+
end
|
68
|
+
end
|
69
|
+
end
|
70
|
+
|
71
|
+
module InstanceMethods
|
72
|
+
def method_locker(method)
|
73
|
+
@method_lockers[method] ||= RedisLocker::MethodLocker.new(@model_locker, method)
|
74
|
+
end
|
75
|
+
|
76
|
+
def lock
|
77
|
+
@model_locker.lock
|
78
|
+
end
|
79
|
+
|
80
|
+
def lock!
|
81
|
+
@model_locker.lock!
|
82
|
+
end
|
83
|
+
|
84
|
+
def unlock
|
85
|
+
@model_locker.unlock
|
86
|
+
end
|
87
|
+
|
88
|
+
def with_redis_lock(strategy: RedisLocker::DEFAULT_STRATEGY, retry_count: RedisLocker::DEFAULT_RETRY_COUNT,
|
89
|
+
retry_interval: RedisLocker::DEFAULT_RETRY_INTERVAL, &block)
|
90
|
+
@model_locker.with_redis_lock(strategy: strategy, retry_count: retry_count, retry_interval: retry_interval, &block)
|
91
|
+
end
|
92
|
+
end
|
93
|
+
|
94
|
+
|
95
|
+
|
96
|
+
end
|
97
|
+
|
98
|
+
loader = Zeitwerk::Loader.for_gem
|
99
|
+
loader.setup
|
100
|
+
loader.eager_load
|
@@ -0,0 +1,24 @@
|
|
1
|
+
module RedisLocker
|
2
|
+
module Errors
|
3
|
+
|
4
|
+
class Error < StandardError; end
|
5
|
+
|
6
|
+
class NotModel < Error
|
7
|
+
def message
|
8
|
+
"Model doesn't have id method"
|
9
|
+
end
|
10
|
+
end
|
11
|
+
|
12
|
+
class AlreadyLocked < Error; end
|
13
|
+
|
14
|
+
class ModelLocked < Error; end
|
15
|
+
|
16
|
+
class NotValidRedisConnection < Error; end
|
17
|
+
|
18
|
+
class UnknownStrategy < Error; end
|
19
|
+
|
20
|
+
class Locked < Error; end
|
21
|
+
|
22
|
+
class MaxRetryCountAchieved < Error; end
|
23
|
+
end
|
24
|
+
end
|
@@ -0,0 +1,69 @@
|
|
1
|
+
module RedisLocker
|
2
|
+
class Locker
|
3
|
+
NULL_SET_VALUE = -420
|
4
|
+
def initialize(*_args)
|
5
|
+
raise Errors::KeyStringNotSet unless @key_string.is_a?(String)
|
6
|
+
|
7
|
+
setup_redis_set
|
8
|
+
loop do
|
9
|
+
@instance_hash = rand(36**8).to_s(36)
|
10
|
+
break unless redis.sismember(@key_string, @instance_hash)
|
11
|
+
end
|
12
|
+
end
|
13
|
+
|
14
|
+
def lock
|
15
|
+
raise NotImplementedError, '#lock has to be implemented'
|
16
|
+
end
|
17
|
+
|
18
|
+
def lock!
|
19
|
+
raise NotImplementedError, '#lock! has to be implemented'
|
20
|
+
end
|
21
|
+
|
22
|
+
def locked?
|
23
|
+
raise NotImplementedError, '#locked? has to be implemented'
|
24
|
+
end
|
25
|
+
|
26
|
+
def unlock
|
27
|
+
raise NotImplementedError, '#unlock has to be implemented'
|
28
|
+
end
|
29
|
+
|
30
|
+
def with_redis_lock(strategy: RedisLocker::DEFAULT_STRATEGY, retry_count: RedisLocker::DEFAULT_RETRY_COUNT,
|
31
|
+
retry_interval: RedisLocker::DEFAULT_RETRY_INTERVAL, &block)
|
32
|
+
raise Errors::UnknownStrategy unless RedisLocker::STRATEGIES.include? strategy
|
33
|
+
|
34
|
+
return respond_to_lock(strategy: strategy, retry_count: retry_count, retry_interval: retry_interval, &block) if locked?
|
35
|
+
|
36
|
+
lock_result = strategy == :exception ? lock! : lock # delegates throwing exception to lock!
|
37
|
+
return unless lock_result
|
38
|
+
|
39
|
+
begin
|
40
|
+
yield if block
|
41
|
+
rescue Exception => e
|
42
|
+
unlock
|
43
|
+
raise e
|
44
|
+
end
|
45
|
+
unlock # unlock returns true if everything is ok
|
46
|
+
end
|
47
|
+
|
48
|
+
private
|
49
|
+
|
50
|
+
def respond_to_lock(**args, &block)
|
51
|
+
raise Errors::Locked if args[:strategy] == :exception
|
52
|
+
return false if args[:strategy] == :silently_die
|
53
|
+
|
54
|
+
# otherwise strategy is retry
|
55
|
+
args[:retry_count] -= 1
|
56
|
+
raise Errors::MaxRetryCountAchieved if args[:retry_count].negative?
|
57
|
+
|
58
|
+
sleep(args[:retry_interval])
|
59
|
+
with_redis_lock(**args, &block)
|
60
|
+
end
|
61
|
+
|
62
|
+
def setup_redis_set
|
63
|
+
return if redis.exists?(@key_string)
|
64
|
+
|
65
|
+
redis.sadd(@key_string, NULL_SET_VALUE)
|
66
|
+
end
|
67
|
+
|
68
|
+
end
|
69
|
+
end
|
@@ -0,0 +1,35 @@
|
|
1
|
+
module RedisLocker
|
2
|
+
class MethodLocker < RedisLocker::Locker
|
3
|
+
include RedisConnection
|
4
|
+
|
5
|
+
def initialize(model_locker, method_name)
|
6
|
+
@model_locker = model_locker
|
7
|
+
@key_string = "LOCKER:#{model_locker.key_string}:#{method_name}"
|
8
|
+
super
|
9
|
+
end
|
10
|
+
|
11
|
+
def lock
|
12
|
+
return false if locked?
|
13
|
+
|
14
|
+
@model_locker.lock
|
15
|
+
redis.sadd(@key_string, @instance_hash)
|
16
|
+
end
|
17
|
+
|
18
|
+
def lock!
|
19
|
+
raise Errors::AlreadyLocked if locked?
|
20
|
+
|
21
|
+
@model_locker.lock
|
22
|
+
lock
|
23
|
+
end
|
24
|
+
|
25
|
+
def locked?
|
26
|
+
redis.scard(@key_string) > 1
|
27
|
+
end
|
28
|
+
|
29
|
+
def unlock
|
30
|
+
return true unless locked?
|
31
|
+
|
32
|
+
(redis.srem(@key_string, @instance_hash) && @model_locker.unlock)
|
33
|
+
end
|
34
|
+
end
|
35
|
+
end
|
@@ -0,0 +1,40 @@
|
|
1
|
+
module RedisLocker
|
2
|
+
class ModelLocker < RedisLocker::Locker
|
3
|
+
include RedisConnection
|
4
|
+
|
5
|
+
attr_reader :key_string
|
6
|
+
|
7
|
+
|
8
|
+
def initialize(model_instance)
|
9
|
+
raise Errors::NotModel unless model_instance.respond_to?(:id)
|
10
|
+
|
11
|
+
@key_string = "LOCKER:#{model_instance.class}:#{model_instance.id}"
|
12
|
+
super
|
13
|
+
end
|
14
|
+
|
15
|
+
def lock
|
16
|
+
return false if locked?
|
17
|
+
|
18
|
+
redis.sadd(@key_string, @instance_hash)
|
19
|
+
end
|
20
|
+
|
21
|
+
def lock!
|
22
|
+
raise Errors::AlreadyLocked if locked?
|
23
|
+
|
24
|
+
lock
|
25
|
+
end
|
26
|
+
|
27
|
+
def locked?
|
28
|
+
redis.scard(@key_string) > 1 # it has to have NULL_SET_VALUE, otherwise redis will free key
|
29
|
+
end
|
30
|
+
|
31
|
+
def unlock
|
32
|
+
return true unless locked?
|
33
|
+
|
34
|
+
redis.srem(@key_string, @instance_hash)
|
35
|
+
end
|
36
|
+
|
37
|
+
private
|
38
|
+
|
39
|
+
end
|
40
|
+
end
|
@@ -0,0 +1,38 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative "lib/redis_locker/version"
|
4
|
+
|
5
|
+
Gem::Specification.new do |spec|
|
6
|
+
spec.name = "redis_locker"
|
7
|
+
spec.version = RedisLocker::VERSION
|
8
|
+
spec.authors = ["Rafał Węgrzyniak"]
|
9
|
+
spec.email = ["wegrzyniak.rafal0@gmail.com"]
|
10
|
+
|
11
|
+
spec.summary = "redis locker gem allows to lock model methods to prevent concurent execution"
|
12
|
+
spec.license = "MIT"
|
13
|
+
spec.required_ruby_version = Gem::Requirement.new(">= 2.4.0")
|
14
|
+
|
15
|
+
# spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
|
16
|
+
|
17
|
+
# spec.metadata["homepage_uri"] = ''
|
18
|
+
spec.metadata["source_code_uri"] = "https://github.com/rwegrzyniak/redis_locker"
|
19
|
+
# spec.metadata["changelog_uri"] = "TODO: Put your gem's CHANGELOG.md URL here."
|
20
|
+
|
21
|
+
# Specify which files should be added to the gem when it is released.
|
22
|
+
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
|
23
|
+
spec.files = Dir.chdir(File.expand_path(__dir__)) do
|
24
|
+
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
|
25
|
+
end
|
26
|
+
spec.bindir = "exe"
|
27
|
+
spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
|
28
|
+
spec.require_paths = ["lib"]
|
29
|
+
spec.add_runtime_dependency "zeitwerk"
|
30
|
+
spec.add_runtime_dependency "redis"
|
31
|
+
spec.add_development_dependency "mock_redis"
|
32
|
+
|
33
|
+
# Uncomment to register a new dependency of your gem
|
34
|
+
# spec.add_dependency "example-gem", "~> 1.0"
|
35
|
+
|
36
|
+
# For more information and examples about making a new gem, checkout our
|
37
|
+
# guide at: https://bundler.io/guides/creating_gem.html
|
38
|
+
end
|
metadata
ADDED
@@ -0,0 +1,106 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: redis_locker
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 0.1.0
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- Rafał Węgrzyniak
|
8
|
+
autorequire:
|
9
|
+
bindir: exe
|
10
|
+
cert_chain: []
|
11
|
+
date: 2021-03-09 00:00:00.000000000 Z
|
12
|
+
dependencies:
|
13
|
+
- !ruby/object:Gem::Dependency
|
14
|
+
name: zeitwerk
|
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: redis
|
29
|
+
requirement: !ruby/object:Gem::Requirement
|
30
|
+
requirements:
|
31
|
+
- - ">="
|
32
|
+
- !ruby/object:Gem::Version
|
33
|
+
version: '0'
|
34
|
+
type: :runtime
|
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: mock_redis
|
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:
|
56
|
+
email:
|
57
|
+
- wegrzyniak.rafal0@gmail.com
|
58
|
+
executables: []
|
59
|
+
extensions: []
|
60
|
+
extra_rdoc_files: []
|
61
|
+
files:
|
62
|
+
- ".gitignore"
|
63
|
+
- ".gitlab-ci.yml"
|
64
|
+
- ".rspec"
|
65
|
+
- ".rubocop.yml"
|
66
|
+
- CODE_OF_CONDUCT.md
|
67
|
+
- Gemfile
|
68
|
+
- LICENSE.txt
|
69
|
+
- README.md
|
70
|
+
- Rakefile
|
71
|
+
- bin/console
|
72
|
+
- bin/setup
|
73
|
+
- lib/redis_locker.rb
|
74
|
+
- lib/redis_locker/configuration.rb
|
75
|
+
- lib/redis_locker/errors.rb
|
76
|
+
- lib/redis_locker/locker.rb
|
77
|
+
- lib/redis_locker/method_locker.rb
|
78
|
+
- lib/redis_locker/model_locker.rb
|
79
|
+
- lib/redis_locker/redis_connection.rb
|
80
|
+
- lib/redis_locker/version.rb
|
81
|
+
- redis_locker.gemspec
|
82
|
+
homepage:
|
83
|
+
licenses:
|
84
|
+
- MIT
|
85
|
+
metadata:
|
86
|
+
source_code_uri: https://github.com/rwegrzyniak/redis_locker
|
87
|
+
post_install_message:
|
88
|
+
rdoc_options: []
|
89
|
+
require_paths:
|
90
|
+
- lib
|
91
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
92
|
+
requirements:
|
93
|
+
- - ">="
|
94
|
+
- !ruby/object:Gem::Version
|
95
|
+
version: 2.4.0
|
96
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
97
|
+
requirements:
|
98
|
+
- - ">="
|
99
|
+
- !ruby/object:Gem::Version
|
100
|
+
version: '0'
|
101
|
+
requirements: []
|
102
|
+
rubygems_version: 3.1.4
|
103
|
+
signing_key:
|
104
|
+
specification_version: 4
|
105
|
+
summary: redis locker gem allows to lock model methods to prevent concurent execution
|
106
|
+
test_files: []
|