redis_queued_locks 0.0.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 612f9339ffba6231bcfe2277af85e2225346f6166eb5bb77da0f507beaeae888
4
+ data.tar.gz: 35229b1d26a17a9c46e39e565d11ec416ca0e173f57360765c064327ffa6390a
5
+ SHA512:
6
+ metadata.gz: 1fdb43047ee4b3ac72d28a244ddc9cb4d6b363ff3aa3852b3cc27cbb77ab0a159ef1a45e7eb13f4e4407449fc7b7383e1aac1775f5f739e6ae2e2fcacc5ced46
7
+ data.tar.gz: 2fbf7fb572005090140ccc9a972e4d84d5be0b1a9a2154fc37c1b04f2dcf44abb06ec6e530c1fa36be0f7ddb3795615f6d7626a224a9d3f3fe913cbf3362734f
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format progress
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,35 @@
1
+ inherit_gem:
2
+ armitage-rubocop:
3
+ - lib/rubocop.general.yml
4
+ - lib/rubocop.rake.yml
5
+ - lib/rubocop.rspec.yml
6
+
7
+ AllCops:
8
+ TargetRubyVersion: 3.2
9
+ NewCops: enable
10
+ Include:
11
+ - lib/**/*.rb
12
+ - spec/**/*.rb
13
+ - Gemfile
14
+ - Rakefile
15
+ - redis_queued_locks.gemspec
16
+ - bin/console
17
+
18
+ Metrics/ParameterLists:
19
+ Enabled: false
20
+
21
+ Metrics/BlockLength:
22
+ Enabled: false
23
+
24
+ Lint/EmptyBlock:
25
+ Exclude:
26
+ - spec/**/*.rb
27
+
28
+ Gemspec/DevelopmentDependencies:
29
+ EnforcedStyle: Gemfile
30
+
31
+ Metrics/AbcSize:
32
+ Enabled: false
33
+
34
+ Metrics/CyclomaticComplexity:
35
+ Enabled: false
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 3.2.2
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.0.0] - 2024-02-25
4
+
5
+ - Initial release
@@ -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 iamdaiver@gmail.com. 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/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2024 Rustam Ibragimov
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,3 @@
1
+ # RedisQueuedLocks
2
+
3
+ Distributed lock implementation with "lock acquisition queue" capabilities based on the Redis Database.
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require 'rubocop/rake_task'
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ # @api private
4
+ # @since 0.1.0
5
+ module RedisQueuedLocks::Acquier::Delay
6
+ # @param retry_delay [Integer] In milliseconds
7
+ # @param retry_jitter [Integer] In milliseconds
8
+ # @return [void]
9
+ #
10
+ # @api private
11
+ # @since 0.1.0
12
+ def delay_execution(retry_delay, retry_jitter)
13
+ delay = (retry_delay + rand(retry_jitter)) / 1_000
14
+ sleep(delay)
15
+ end
16
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ # @api private
4
+ # @since 0.1.0
5
+ module RedisQueuedLocks::Acquier::Expire
6
+ # @param redis [RedisClient]
7
+ # @param lock_key [String]
8
+ # @param block [Block]
9
+ # @return [void]
10
+ #
11
+ # @api private
12
+ # @since 0.1.0
13
+ def yield_with_expire(redis, lock_key, &block)
14
+ yield if block_given?
15
+ ensure
16
+ redis.call('EXPIRE', lock_key, '0')
17
+ end
18
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ # @api private
4
+ # @since 0.1.0
5
+ module RedisQueuedLocks::Acquier::Release
6
+ # Realease the lock: clear the lock queue and expire the lock.
7
+ #
8
+ # @param redis [RedisClient]
9
+ # @param lock_key [String]
10
+ # @param lock_key_queue [String]
11
+ # @return [void]
12
+ #
13
+ # @api private
14
+ # @since 0.1.0
15
+ def fully_release_lock(redis, lock_key, lock_key_queue)
16
+ redis.multi do |transact|
17
+ transact.call('ZREMRANGEBYSCORE', lock_key_queue, '-inf', '+inf')
18
+ transact.call('EXPIRE', lock_key, '0')
19
+ end
20
+ end
21
+
22
+ # Release all locks: clear all lock queus and expire all locks.
23
+ #
24
+ # @param redis [RedisClient]
25
+ # @param batch_size [Integer]
26
+ # @return [void]
27
+ #
28
+ # @api private
29
+ # @since 0.1.0
30
+ def fully_release_all_locks(redis, batch_size)
31
+ # Step A: release all queus and their related locks
32
+ redis.scan('MATCH', RedisQueuedLocks::Resource::LOCK_QUEUE_PATTERN) do |lock_queue|
33
+ redis.pipelined do |pipeline|
34
+ pipeline.call('ZREMRANGEBYSCORE', lock_queue, '-inf', '+inf')
35
+ pipeline.call('EXPIRE', RedisQueuedLocks::Resource.lock_key_from_queue(lock_queue))
36
+ end
37
+ end
38
+
39
+ # Step B: release all locks
40
+ redis.pipelined do |pipeline|
41
+ redis.scan('MATCH', RedisQueuedLocks::Resource::LOCK_PATTERN) do |lock_key|
42
+ pipeline.call('EXPIRE', lock_key, '0')
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,148 @@
1
+ # frozen_string_literal: true
2
+
3
+ # @api private
4
+ # @since 0.1.0
5
+ module RedisQueuedLocks::Acquier::Try
6
+ # @param redis [RedisClient]
7
+ # @param lock_key [String]
8
+ # @param lock_key_queue [String]
9
+ # @param acquier_id [String]
10
+ # @param acquier_position [Numeric]
11
+ # @param ttl [Integer]
12
+ # @param queue_ttl [Integer]
13
+ # @return [Hash<Symbol,Any>] Format: { ok: true/false, result: Symbol|Hash<Symbol,Any> }
14
+ #
15
+ # @api private
16
+ # @since 0.1.0
17
+ # rubocop:disable Metrics/MethodLength, Metrics/PerceivedComplexity
18
+ def try_to_lock(redis, lock_key, lock_key_queue, acquier_id, acquier_position, ttl, queue_ttl)
19
+ # Step X: intermediate invocation results
20
+ inter_result = nil
21
+ timestamp = nil
22
+
23
+ # Step 0: watch the lock key changes (and discard acquirement if lock is already acquired)
24
+ result = redis.multi(watch: [lock_key]) do |transact|
25
+ # Step 1: add an acquier to the lock acquirement queue
26
+ res = redis.call('ZADD', lock_key_queue, 'NX', acquier_position, acquier_id)
27
+
28
+ RedisQueuedLocks.debug(
29
+ "Step №1: добавление в очередь (#{acquier_id}). [ZADD to the queue: #{res}]"
30
+ )
31
+
32
+ # Step 2.1: drop expired acquiers from the lock queue
33
+ res = redis.call(
34
+ 'ZREMRANGEBYSCORE',
35
+ lock_key_queue,
36
+ '-inf',
37
+ RedisQueuedLocks::Resource.acquier_dead_score(queue_ttl)
38
+ )
39
+
40
+ RedisQueuedLocks.debug(
41
+ "Step №2: дропаем из очереди просроченных ожидающих. [ZREMRANGE: #{res}]"
42
+ )
43
+
44
+ # Step 3: get the actual acquier waiting in the queue
45
+ waiting_acquier = Array(redis.call('ZRANGE', lock_key_queue, '0', '0')).first
46
+
47
+ RedisQueuedLocks.debug(
48
+ "Step №3: какой процесс в очереди сейчас ждет. " \
49
+ "[ZRANGE <следующий процесс>: #{waiting_acquier} :: <текущий процесс>: #{acquier_id}]"
50
+ )
51
+
52
+ # Step 4: check the actual acquier: is it ours? are we aready to lock?
53
+ unless waiting_acquier == acquier_id
54
+ # Step ROLLBACK 1.1: our time hasn't come yet. retry!
55
+
56
+ RedisQueuedLocks.debug(
57
+ "Step ROLLBACK №1: не одинаковые ключи. выходим. " \
58
+ "[Ждет: #{waiting_acquier}. А нужен: #{acquier_id}]"
59
+ )
60
+
61
+ inter_result = :acquier_is_not_first_in_queue
62
+ else
63
+ # NOTE: our time has come! let's try to acquire the lock!
64
+
65
+ # Step 5: check if the our lock is already acquired
66
+ locked_by_acquier = redis.call('HGET', lock_key, 'acq_id')
67
+
68
+ RedisQueuedLocks.debug(
69
+ "Ste №5: Ищем требуемый лок. " \
70
+ "[HGET<#{lock_key}>: " \
71
+ "#{(locked_by_acquier == nil) ? 'не занят' : "занят процессом <#{locked_by_acquier}>"}"
72
+ )
73
+
74
+ if locked_by_acquier
75
+ # Step ROLLBACK 2: required lock is stil acquired. retry!
76
+
77
+ RedisQueuedLocks.debug(
78
+ "Step ROLLBACK №2: Ключ уже занят. Ничего не делаем. " \
79
+ "[Занят процессом: #{locked_by_acquier}]"
80
+ )
81
+
82
+ inter_result = :lock_is_still_acquired
83
+ else
84
+ # NOTE: required lock is free and ready to be acquired! acquire!
85
+
86
+ # Step 6.1: remove our acquier from waiting queue
87
+ transact.call('ZPOPMIN', lock_key_queue, '1')
88
+
89
+ RedisQueuedLocks.debug(
90
+ 'Step №4: Забираем наш текущий процесс из очереди. [ZPOPMIN]'
91
+ )
92
+
93
+ RedisQueuedLocks.debug(
94
+ "===> <FINAL> Step №6: закрепляем лок за процессом [HSET<#{lock_key}>: #{acquier_id}]"
95
+ )
96
+
97
+ # Step 6.2: acquire a lock and store an info about the acquier
98
+ transact.call('HSET', lock_key, 'acq_id', acquier_id, 'ts', (timestamp = Time.now.to_i))
99
+
100
+ # Step 6.3: set the lock expiration time in order to prevent "infinite locks"
101
+ transact.call('PEXPIRE', lock_key, ttl) # NOTE: in seconds
102
+ end
103
+ end
104
+ end
105
+
106
+ # Step 7: Analyze the aquirement attempt:
107
+ case
108
+ when inter_result == :lock_is_still_acquired || inter_result == :acquier_is_not_first_in_queue
109
+ # Step 7.a: lock is still acquired by another process => failed to acquire
110
+ { ok: false, result: inter_result }
111
+ when result == nil || (result.is_a?(::Array) && result.empty?)
112
+ # Step 7.b: lock is already acquired durign the acquire race => failed to acquire
113
+ { ok: false, result: :lock_is_acquired_during_acquire_race }
114
+ when result.is_a?(::Array) && result.size == 3 # NOTE: 3 is a count of lock commands
115
+ # TODO:
116
+ # => (!) analyze the command result and do actions with the depending on it;
117
+ # => (*) at this moment we accept that all comamnds are completed successfully;
118
+ # => (!) need to analyze:
119
+ # 1. zpopmin should return our process (array with <acq_id> and <score>)
120
+ # 2. hset should return 2 (lock key is added to the redis db with 2 fields)
121
+ # 3. pexpire should return 1 (expiration time is successfully applied)
122
+
123
+ # Step 7.c: locked! :) let's go! => successfully acquired
124
+ { ok: true, result: { lock_key: lock_key, acq_id: acquier_id, ts: timestamp, ttl: ttl } }
125
+ else
126
+ # Ste 7.d: unknown behaviour :thinking:
127
+ { ok: false, result: :unknown }
128
+ end
129
+ end
130
+ # rubocop:enable Metrics/MethodLength, Metrics/PerceivedComplexity
131
+
132
+ # @param redis [RedisClient]
133
+ # @param lock_key_queue [String]
134
+ # @param acquier_id [String]
135
+ # @return [Hash<Symbol,Any>] Format: { ok: true/false, result: Any }
136
+ #
137
+ # @api private
138
+ # @since 0.1.0
139
+ def dequeue_from_lock_queue(redis, lock_key_queue, acquier_id)
140
+ result = redis.call('ZREM', lock_key_queue, acquier_id)
141
+
142
+ RedisQueuedLocks.debug(
143
+ "Step ~ [СМЕРТЬ ПРОЦЕССА]: [#{acquier_id} :: #{lock_key_queue}] РЕЗУЛЬТАТ: #{result}"
144
+ )
145
+
146
+ { ok: true, result: result }
147
+ end
148
+ end
@@ -0,0 +1,194 @@
1
+ # frozen_string_literal: true
2
+
3
+ # @api private
4
+ # @since 0.1.0
5
+ module RedisQueuedLocks::Acquier
6
+ require_relative 'acquier/try'
7
+ require_relative 'acquier/delay'
8
+ require_relative 'acquier/expire'
9
+ require_relative 'acquier/release'
10
+
11
+ # @since 0.1.0
12
+ extend Try
13
+ # @since 0.1.0
14
+ extend Delay
15
+ # @since 0.1.0
16
+ extend Expire
17
+ # @since 0.1.0
18
+ extend Release
19
+
20
+ # @return [Integer]
21
+ # Redis expiration deviation in milliseconds:
22
+ # -> 1 millisecond: for Redis's deviation;
23
+ # -> 1 millisecond: for RubyVM's processing deviation;
24
+ #
25
+ # @api private
26
+ # @since 0.1.0
27
+ REDIS_EXPIRATION_DEVIATION = 2 # NOTE: milliseconds
28
+
29
+ class << self
30
+ # @param redis [RedisClient]
31
+ # Redis connection client.
32
+ # @param lock_name [String]
33
+ # Lock name to be acquier.
34
+ # @option process_id [Integer,String]
35
+ # The process that want to acquire the lock.
36
+ # @option thread_id [Integer,String]
37
+ # The process's thread that want to acquire the lock.
38
+ # @option ttl [Integer]
39
+ # Lock's time to live (in milliseconds).
40
+ # @option queue_ttl [Integer]
41
+ # ?
42
+ # @option timeout [Integer]
43
+ # Time period whe should try to acquire the lock (in seconds).
44
+ # @option retry_count [Integer]
45
+ # How many times we should try to acquire a lock.
46
+ # @option retry_delay [Integer]
47
+ # A time-interval between the each retry (in milliseconds).
48
+ # @option retry_jitter [Integer]
49
+ # Time-shift range for retry-delay (in milliseconds).
50
+ # @param [Block]
51
+ # A block of code that should be executed after the successfully acquired lock.
52
+ # @return [Hash<Symbol,Any>]
53
+ # Format: { ok: true/false, result: Any }
54
+ #
55
+ # @api private
56
+ # @since 0.1.0
57
+ # rubocop:disable Metrics/MethodLength
58
+ def acquire_lock!(
59
+ redis,
60
+ lock_name,
61
+ process_id:,
62
+ thread_id:,
63
+ ttl:,
64
+ queue_ttl:,
65
+ timeout:,
66
+ retry_count:,
67
+ retry_delay:,
68
+ retry_jitter:,
69
+ &block
70
+ )
71
+ # Step 1: prepare lock requirements (generate lock name, calc lock ttl, etc).
72
+ acquier_id = RedisQueuedLocks::Resource.acquier_identifier(process_id, thread_id)
73
+ lock_ttl = ttl + REDIS_EXPIRATION_DEVIATION
74
+ lock_key = RedisQueuedLocks::Resource.prepare_lock_key(lock_name)
75
+ lock_key_queue = RedisQueuedLocks::Resource.prepare_lock_queue(lock_name)
76
+ acquier_position = RedisQueuedLocks::Resource.calc_initial_acquier_position
77
+
78
+ # Step X: intermediate result observer
79
+ acq_process = { lock_info: {}, should_try: true, tries: 0, acquired: false, result: nil }
80
+ acq_dequeue = -> { dequeue_from_lock_queue(redis, lock_key_queue, acquier_id) }
81
+
82
+ # Step 2: try to lock with timeout
83
+ with_timeout(timeout, lock_key, on_timeout: acq_dequeue) do
84
+ # Step 2.1: caclically try to obtain the lock
85
+ while acq_process[:should_try]
86
+ try_to_lock(
87
+ redis,
88
+ lock_key,
89
+ lock_key_queue,
90
+ acquier_id,
91
+ acquier_position,
92
+ lock_ttl,
93
+ queue_ttl
94
+ ) => { ok:, result: }
95
+
96
+ # Step X: save the intermediate results to the result observer
97
+ acq_process[:result] = result
98
+
99
+ # Step 2.1: analyze an acquirement attempt
100
+ if ok
101
+ # Step 2.1.a: successfully acquired => build the result
102
+ acq_process[:lock_info] = result
103
+ acq_process[:acquired] = true
104
+ acq_process[:should_try] = false
105
+ else
106
+ # Step 2.1.b: failed acquirement => retry
107
+ acq_process[:tries] += 1
108
+
109
+ if acq_process[:tries] >= retry_count
110
+ # NOTE: reached the retry limit => quit from the loop
111
+ acq_process[:should_try] = false
112
+ # NOTE: reached the retry limit => dequeue from the lock queue
113
+ acq_dequeue.call
114
+ else
115
+ # NOTE:
116
+ # delay the exceution in order to prevent chaotic attempts
117
+ # and to allow other processes and threads to obtain the lock too.
118
+ delay_execution(retry_delay, retry_jitter)
119
+ end
120
+ end
121
+ end
122
+ end
123
+
124
+ # Step 3: analyze acquirement result
125
+ if acq_process[:acquired]
126
+ # Step 3.a: acquired successfully => run logic or return the result of acquirement
127
+ if block_given?
128
+ yield_with_expire(redis, lock_key, &block)
129
+ else
130
+ { ok: true, result: acq_process[:lock_info] }
131
+ end
132
+ else
133
+ # Step 3.b: lock is not acquired:
134
+ # => drop itslef from the queue and return the reason of the failed acquirement
135
+ { ok: false, result: acq_process[:result] }
136
+ end
137
+ end
138
+ # rubocop:enable Metrics/MethodLength
139
+
140
+ # Release the concrete lock:
141
+ # - 1. clear lock queue: al; related processes released
142
+ # from the lock aquierment and should retry;
143
+ # - 2. delete the lock: drop lock key from Redis;
144
+ # It is safe because the lock obtain logic is transactional and
145
+ # watches the original lock for changes.
146
+ #
147
+ # @param redis [RedisClient] Redis connection client.
148
+ # @param lock_name [String] The lock name that should be released.
149
+ # @return [Hash<Symbol,Any>] Format: { ok: true/false, result: Any }
150
+ #
151
+ # @api private
152
+ # @since 0.1.0
153
+ def release_lock!(redis, lock_name)
154
+ lock_key = RedisQueuedLocks::Resource.prepare_lock_key(lock_name)
155
+ lock_key_queue = RedisQueuedLocks::Resource.prepare_lock_queue(lock_name)
156
+
157
+ result = fully_release_lock(redis, lock_key, lock_key_queue)
158
+ { ok: true, result: result }
159
+ end
160
+
161
+ # Release all locks:
162
+ # - 1. clear all lock queus: drop them all from Redis database by the lock queue pattern;
163
+ # - 2. delete all locks: drop lock keys from Redis by the lock key pattern;
164
+ #
165
+ # @param redis [RedisClient] Redis connection client.
166
+ # @param batch_size [Integer] The number of lock keys that should be released in a time.
167
+ # @return [Hash<Symbol,Any>] Format: { ok: true/false, result: Any }
168
+ #
169
+ # @api private
170
+ # @since 0.1.0
171
+ def release_all_locks!(redis, batch_size)
172
+ result = fully_release_all_locks(redis, batch_size)
173
+ { ok: true, result: result }
174
+ end
175
+
176
+ private
177
+
178
+ # @param timeout [Integer] Time period after which the logic will fail with timeout error.
179
+ # @param lock_key [String] Lock name.
180
+ # @option on_timeout [Proc,NilClass] Callback invoked on Timeout::Error.
181
+ # @return [Any]
182
+ #
183
+ # @api private
184
+ # @since 0.1.0
185
+ def with_timeout(timeout, lock_key, on_timeout: nil, &block)
186
+ ::Timeout.timeout(timeout, &block)
187
+ rescue ::Timeout::Error
188
+ on_timeout.call unless on_timeout == nil
189
+ raise(RedisQueuedLocks::LockAcquiermentTimeoutError, <<~ERROR_MESSAGE.strip)
190
+ Failed to acquire the lock "#{lock_key}" for the given timeout (#{timeout} seconds).
191
+ ERROR_MESSAGE
192
+ end
193
+ end
194
+ end
@@ -0,0 +1,120 @@
1
+ # frozen_string_literal: true
2
+
3
+ # @api public
4
+ # @since 0.1.0
5
+ class RedisQueuedLocks::Client
6
+ # @since 0.1.0
7
+ include Qonfig::Configurable
8
+
9
+ configuration do
10
+ setting :retry_count, 3
11
+ setting :retry_delay, 200 # NOTE: milliseconds
12
+ setting :retry_jitter, 50 # NOTE: milliseconds
13
+ setting :acquire_timeout, 10 # NOTE: seconds
14
+ setting :exp_precision, 1 # NOTE: milliseconds
15
+ setting :default_lock_ttl, 10_000 # NOTE: milliseconds
16
+ setting :default_queue_ttl, 5 # NOTE: seconds
17
+ setting :lock_release_batch_size, 100
18
+
19
+ # TODO: setting :logger, Logger.new(IO::NULL)
20
+ # TODO: setting :debug, true/false
21
+
22
+ validate 'retry_count', :integer
23
+ validate 'retry_delay', :integer
24
+ validate 'retry_jitter', :integer
25
+ validate 'acquire_timeout', :integer
26
+ validate 'exp_precision', :integer
27
+ validate 'default_lock_tt', :integer
28
+ validate 'default_queue_ttl', :integer
29
+ validate 'lock_release_batch_size', :integer
30
+ end
31
+
32
+ # @return [RedisClient]
33
+ #
34
+ # @api private
35
+ # @since 0.1.0
36
+ attr_reader :redis_client
37
+
38
+ # @param redis_client [RedisClient]
39
+ # Redis connection manager, which will be used for the lock acquierment and distribution.
40
+ # It should be an instance of RedisClient.
41
+ # @param configs [Block]
42
+ # Custom configs for in-runtime configuration.
43
+ # @return [void]
44
+ #
45
+ # @api public
46
+ # @since 0.1.0
47
+ def initialize(redis_client, &configs)
48
+ configure(&configs)
49
+ @redis_client = redis_client
50
+ end
51
+
52
+ # @param lock_name [String]
53
+ # Lock name to be acquier.
54
+ # @option process_id [Integer,String]
55
+ # The process that want to acquire the lock.
56
+ # @option thread_id [Integer,String]
57
+ # The process's thread that want to acquire the lock.
58
+ # @option ttl [Integer]
59
+ # Lock's time to live (in milliseconds).
60
+ # @option queue_ttl [Integer]
61
+ # ?
62
+ # @option timeout [Integer]
63
+ # Time period whe should try to acquire the lock (in seconds).
64
+ # @option retry_count [Integer]
65
+ # How many times we should try to acquire a lock.
66
+ # @option retry_delay [Integer]
67
+ # A time-interval between the each retry (in milliseconds).
68
+ # @option retry_jitter [Integer]
69
+ # Time-shift range for retry-delay (in milliseconds).
70
+ # @param [Block]
71
+ # A block of code that should be executed after the successfully acquired lock.
72
+ # @return [Hash<Symbol,Any>]
73
+ # Format: { ok: true/false, result: Symbol/Hash }.
74
+ #
75
+ # @api public
76
+ # @since 0.1.0
77
+ def lock(
78
+ lock_name,
79
+ process_id: RedisQueuedLocks::Resource.get_process_id,
80
+ thread_id: RedisQueuedLocks::Resource.get_thread_id,
81
+ ttl: config[:default_lock_ttl],
82
+ queue_ttl: config[:default_queue_ttl],
83
+ timeout: config[:acquire_timeout],
84
+ retry_count: config[:retry_count],
85
+ retry_delay: config[:retry_delay],
86
+ retry_jitter: config[:retry_jitter],
87
+ &block
88
+ )
89
+ RedisQueuedLocks::Acquier.acquire_lock!(
90
+ redis_client,
91
+ lock_name,
92
+ process_id:,
93
+ thread_id:,
94
+ ttl:,
95
+ queue_ttl:,
96
+ timeout:,
97
+ retry_count:,
98
+ retry_delay:,
99
+ retry_jitter:,
100
+ &block
101
+ )
102
+ end
103
+
104
+ # @param lock_name [String] The lock name that should be released.
105
+ # @return [?]
106
+ #
107
+ # @api public
108
+ # @since 0.1.0
109
+ def unlock(lock_name)
110
+ RedisQueuedLocks::Acquier.release_lock!(redis_client, lock_name)
111
+ end
112
+
113
+ # @return [?]
114
+ #
115
+ # @api public
116
+ # @since 0.1.0
117
+ def clear_locks(batch_size: config[:lock_release_batch_size])
118
+ RedisQueuedLocks::Acquier.release_all_locks!(redis_client, batch_size)
119
+ end
120
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ # @api private
4
+ # @since 0.1.0
5
+ module RedisQueuedLocks::Debugger::Interface
6
+ # @param message [String]
7
+ # @return [void]
8
+ #
9
+ # @api private
10
+ # @since 0.1.0
11
+ def debug(message)
12
+ RedisQueuedLocks::Debugger.debug(message)
13
+ end
14
+
15
+ # @return [void]
16
+ #
17
+ # @api private
18
+ # @since 0.1.0
19
+ def enable_debugger!
20
+ RedisQueuedLocks::Debugger.enable!
21
+ end
22
+
23
+ # @return [void]
24
+ #
25
+ # @api private
26
+ # @since 0.1.0
27
+ def disable_debugger!
28
+ RedisQueuedLocks::Debugger.disable!
29
+ end
30
+ end
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ # @api private
4
+ # @since 0.1.0
5
+ module RedisQueuedLocks::Debugger
6
+ require_relative 'debugger/interface'
7
+
8
+ # @return [String]
9
+ #
10
+ # @api private
11
+ # @since 0.1.0
12
+ DEBUG_ENABLED_METHOD = <<~METHOD_DECLARATION.strip.freeze
13
+ def debug(message) = STDOUT.write_nonblock("#\{message}\n")
14
+ METHOD_DECLARATION
15
+
16
+ # @return [String]
17
+ #
18
+ # @api private
19
+ # @since 0.1.0
20
+ DEBUG_DISABLED_MEHTOD = <<~METHOD_DECLARATION.strip.freeze
21
+ def debug(message); end
22
+ METHOD_DECLARATION
23
+
24
+ class << self
25
+ # @api private
26
+ # @since 0.1.0
27
+ instance_variable_set(:@enabled, false)
28
+
29
+ # @return [void]
30
+ #
31
+ # @api private
32
+ # @since 0.1.0
33
+ def enable!
34
+ @enabled = true
35
+ eval(DEBUG_ENABLED_METHOD)
36
+ end
37
+
38
+ # @return [void]
39
+ #
40
+ # @api private
41
+ # @since 0.1.0
42
+ def disable!
43
+ @enabled = false
44
+ eval(DEBUG_DISABLED_MEHTOD)
45
+ end
46
+
47
+ # @return [Boolean]
48
+ #
49
+ # @api private
50
+ # @since 0.1.0
51
+ def enabled?
52
+ @enabled
53
+ end
54
+
55
+ # @param message [String]
56
+ # @return [void]
57
+ #
58
+ # @api private
59
+ # @since 0.1.0
60
+ def debug(message); end
61
+ end
62
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RedisQueuedLocks
4
+ # @api public
5
+ # @since 0.1.0
6
+ Error = Class.new(::StandardError)
7
+
8
+ # @api public
9
+ # @since 0.1.0
10
+ ArgumentError = Class.new(::ArgumentError)
11
+
12
+ # @api public
13
+ # @since 0.1.0
14
+ LockAcquiermentTimeoutError = Class.new(Error)
15
+
16
+ # @api public
17
+ # @since 0.1.0
18
+ LockAcquiermentLimitError = Class.new(Error)
19
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ # @api private
4
+ # @since 0.1.0
5
+ module RedisQueuedLocks::Instrumentation
6
+ end
@@ -0,0 +1,90 @@
1
+ # frozen_string_literal: true
2
+
3
+ # @api private
4
+ # @since 0.1.0
5
+ module RedisQueuedLocks::Resource
6
+ # @return [String]
7
+ #
8
+ # @api private
9
+ # @since 0.1.0
10
+ LOCK_PATTERN = 'rql:lock:*'
11
+
12
+ # @return [String]
13
+ #
14
+ # @api private
15
+ # @since 0.1.0
16
+ LOCK_QUEUE_PATTERN = 'rql:lock_queue:*'
17
+
18
+ class << self
19
+ # @param process_id [Integer,String]
20
+ # @param thread_id [Integer,String]
21
+ # @return [String]
22
+ #
23
+ # @api private
24
+ # @since 0.1.0
25
+ def acquier_identifier(process_id = get_process_id, thread_id = get_thread_id)
26
+ "rql:acq:#{process_id}/#{thread_id}"
27
+ end
28
+
29
+ # @param lock_name [String]
30
+ # @return [String]
31
+ #
32
+ # @api private
33
+ # @since 0.1.0
34
+ def prepare_lock_key(lock_name)
35
+ "rql:lock:#{lock_name}"
36
+ end
37
+
38
+ # @param lock_name [String]
39
+ # @return [String]
40
+ #
41
+ # @api private
42
+ # @since 0.1.0
43
+ def prepare_lock_queue(lock_name)
44
+ "rql:lock_queue:#{lock_name}"
45
+ end
46
+
47
+ # @return [Integer] Redis's <Set> score that is calculated from the time (epoch) as an integer.
48
+ #
49
+ # @api private
50
+ # @since 0.1.0
51
+ def calc_initial_acquier_position
52
+ Time.now.to_i
53
+ end
54
+
55
+ # @param queue_ttl [Integer] In seconds
56
+ # @return [Integer] Redis's <Set> score barrier before wich all other acquiers are removed.
57
+ #
58
+ # @api private
59
+ # @since 0.1.0
60
+ def acquier_dead_score(queue_ttl)
61
+ Time.now.to_i - queue_ttl
62
+ end
63
+
64
+ # @param lock_queue [String]
65
+ # @return [String]
66
+ #
67
+ # @api private
68
+ # @since 0.1.0
69
+ def lock_key_from_queue(lock_queue)
70
+ # NOTE: 15 is a start position of the lock name
71
+ "rql:lock:#{lock_queue[15..]}"
72
+ end
73
+
74
+ # @return [Integer]
75
+ #
76
+ # @api private
77
+ # @since 0.1.0
78
+ def get_thread_id
79
+ ::Thread.current.object_id
80
+ end
81
+
82
+ # @return [Integer]
83
+ #
84
+ # @api private
85
+ # @since 0.1.0
86
+ def get_process_id
87
+ ::Process.pid
88
+ end
89
+ end
90
+ end
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RedisQueuedLocks
4
+ # @return [String]
5
+ #
6
+ # @api public
7
+ # @since 0.0.0
8
+ VERSION = '0.0.0'
9
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'redis-client'
4
+ require 'qonfig'
5
+ require 'timeout'
6
+
7
+ # @api public
8
+ # @since 0.1.0
9
+ module RedisQueuedLocks
10
+ require_relative 'redis_queued_locks/version'
11
+ require_relative 'redis_queued_locks/errors'
12
+ require_relative 'redis_queued_locks/debugger'
13
+ require_relative 'redis_queued_locks/resource'
14
+ require_relative 'redis_queued_locks/acquier'
15
+ require_relative 'redis_queued_locks/instrumentation'
16
+ require_relative 'redis_queued_locks/client'
17
+
18
+ # @since 0.1.0
19
+ extend RedisQueuedLocks::Debugger::Interface
20
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/redis_queued_locks/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.required_ruby_version = '>= 3.2.0'
7
+
8
+ spec.name = 'redis_queued_locks'
9
+ spec.version = RedisQueuedLocks::VERSION
10
+ spec.authors = ['Rustam Ibragimov']
11
+ spec.email = ['iamdaiver@gmail.com']
12
+
13
+ spec.summary = 'Queued distributed locks based on Redis.'
14
+ spec.description = 'Distributed lock implementation with "lock acquisition queue" ' \
15
+ 'capabilities based on the Redis Database.'
16
+ spec.homepage = 'https://github.com/0exp/redis_queued_locks'
17
+ spec.license = 'MIT'
18
+
19
+ spec.metadata['homepage_uri'] = spec.homepage
20
+ spec.metadata['source_code_uri'] = "#{spec.homepage}/blob/master"
21
+ spec.metadata['changelog_uri'] = "#{spec.homepage}/blob/master/CHANGELOG.md"
22
+
23
+ spec.files = Dir.chdir(__dir__) do
24
+ `git ls-files -z`.split("\x0").reject do |f|
25
+ (File.expand_path(f) == __FILE__) ||
26
+ f.start_with?(*%w[bin/ test/ spec/ features/ .git appveyor Gemfile])
27
+ end
28
+ end
29
+
30
+ spec.bindir = 'exe'
31
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
32
+ spec.require_paths = ['lib']
33
+
34
+ spec.add_dependency 'redis-client', '~> 0.20'
35
+ spec.add_dependency 'qonfig', '~> 0.28'
36
+ end
metadata ADDED
@@ -0,0 +1,97 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: redis_queued_locks
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.0
5
+ platform: ruby
6
+ authors:
7
+ - Rustam Ibragimov
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2024-02-25 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: redis-client
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '0.20'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '0.20'
27
+ - !ruby/object:Gem::Dependency
28
+ name: qonfig
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '0.28'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '0.28'
41
+ description: Distributed lock implementation with "lock acquisition queue" capabilities
42
+ based on the Redis Database.
43
+ email:
44
+ - iamdaiver@gmail.com
45
+ executables: []
46
+ extensions: []
47
+ extra_rdoc_files: []
48
+ files:
49
+ - ".rspec"
50
+ - ".rubocop.yml"
51
+ - ".ruby-version"
52
+ - CHANGELOG.md
53
+ - CODE_OF_CONDUCT.md
54
+ - LICENSE.txt
55
+ - README.md
56
+ - Rakefile
57
+ - lib/redis_queued_locks.rb
58
+ - lib/redis_queued_locks/acquier.rb
59
+ - lib/redis_queued_locks/acquier/delay.rb
60
+ - lib/redis_queued_locks/acquier/expire.rb
61
+ - lib/redis_queued_locks/acquier/release.rb
62
+ - lib/redis_queued_locks/acquier/try.rb
63
+ - lib/redis_queued_locks/client.rb
64
+ - lib/redis_queued_locks/debugger.rb
65
+ - lib/redis_queued_locks/debugger/interface.rb
66
+ - lib/redis_queued_locks/errors.rb
67
+ - lib/redis_queued_locks/instrumentation.rb
68
+ - lib/redis_queued_locks/resource.rb
69
+ - lib/redis_queued_locks/version.rb
70
+ - redis_queued_locks.gemspec
71
+ homepage: https://github.com/0exp/redis_queued_locks
72
+ licenses:
73
+ - MIT
74
+ metadata:
75
+ homepage_uri: https://github.com/0exp/redis_queued_locks
76
+ source_code_uri: https://github.com/0exp/redis_queued_locks/blob/master
77
+ changelog_uri: https://github.com/0exp/redis_queued_locks/blob/master/CHANGELOG.md
78
+ post_install_message:
79
+ rdoc_options: []
80
+ require_paths:
81
+ - lib
82
+ required_ruby_version: !ruby/object:Gem::Requirement
83
+ requirements:
84
+ - - ">="
85
+ - !ruby/object:Gem::Version
86
+ version: 3.2.0
87
+ required_rubygems_version: !ruby/object:Gem::Requirement
88
+ requirements:
89
+ - - ">="
90
+ - !ruby/object:Gem::Version
91
+ version: '0'
92
+ requirements: []
93
+ rubygems_version: 3.5.3
94
+ signing_key:
95
+ specification_version: 4
96
+ summary: Queued distributed locks based on Redis.
97
+ test_files: []