redis_queued_locks 1.23.1 → 1.24.0

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.
Files changed (58) hide show
  1. checksums.yaml +4 -4
  2. data/.claude/project-overview.md +70 -33
  3. data/.claude/rules/acquirer.md +6 -4
  4. data/.claude/rules/arguments.md +2 -2
  5. data/.claude/rules/git.md +1 -1
  6. data/.claude/rules/logic.md +5 -4
  7. data/.claude/rules/readme.md +40 -0
  8. data/.claude/rules/swarm.md +2 -2
  9. data/.claude/rules/tests.md +3 -2
  10. data/.claude/rules/type-checking.md +3 -2
  11. data/.claude/rules/visitors.md +3 -2
  12. data/.claude/skills/rql-code-review/SKILL.md +6 -3
  13. data/.claude/skills/rql-project-full-review/SKILL.md +171 -0
  14. data/.claude/skills/rql-project-full-review/templates/report.en.md +41 -0
  15. data/.claude/skills/rql-project-full-review/templates/report.ru.md +41 -0
  16. data/CHANGELOG.md +25 -10
  17. data/CLAUDE.md +7 -5
  18. data/README.md +381 -13
  19. data/lib/redis_queued_locks/acquirer/acquire_lock/dequeue_from_lock_queue.rb +60 -1
  20. data/lib/redis_queued_locks/acquirer/acquire_lock/try_to_lock/log_visitor.rb +38 -1
  21. data/lib/redis_queued_locks/acquirer/acquire_lock/try_to_lock.rb +31 -4
  22. data/lib/redis_queued_locks/acquirer/acquire_lock/with_acq_timeout.rb +6 -3
  23. data/lib/redis_queued_locks/acquirer/acquire_lock/yield_expire.rb +243 -35
  24. data/lib/redis_queued_locks/acquirer/acquire_lock.rb +93 -3
  25. data/lib/redis_queued_locks/acquirer/lock_series/try_to_lock_series.rb +27 -1
  26. data/lib/redis_queued_locks/acquirer/lock_series.rb +150 -14
  27. data/lib/redis_queued_locks/client.rb +96 -16
  28. data/lib/redis_queued_locks/config/dsl.rb +2 -0
  29. data/lib/redis_queued_locks/config.rb +35 -11
  30. data/lib/redis_queued_locks/errors.rb +11 -2
  31. data/lib/redis_queued_locks/lock_keeper/instr_visitor.rb +173 -0
  32. data/lib/redis_queued_locks/lock_keeper/lease.rb +434 -0
  33. data/lib/redis_queued_locks/lock_keeper/lock_lease.rb +106 -0
  34. data/lib/redis_queued_locks/lock_keeper/log_visitor.rb +187 -0
  35. data/lib/redis_queued_locks/lock_keeper.rb +1007 -0
  36. data/lib/redis_queued_locks/resource.rb +1 -1
  37. data/lib/redis_queued_locks/swarm/swarm_element/threaded.rb +2 -2
  38. data/lib/redis_queued_locks/utilities.rb +1 -15
  39. data/lib/redis_queued_locks/version.rb +2 -2
  40. data/lib/redis_queued_locks.rb +1 -0
  41. data/sig/redis_queued_locks/acquirer/acquire_lock/dequeue_from_lock_queue.rbs +14 -0
  42. data/sig/redis_queued_locks/acquirer/acquire_lock/try_to_lock/log_visitor.rbs +12 -0
  43. data/sig/redis_queued_locks/acquirer/acquire_lock/try_to_lock.rbs +2 -0
  44. data/sig/redis_queued_locks/acquirer/acquire_lock/yield_expire.rbs +30 -2
  45. data/sig/redis_queued_locks/acquirer/acquire_lock.rbs +6 -1
  46. data/sig/redis_queued_locks/acquirer/lock_series.rbs +12 -1
  47. data/sig/redis_queued_locks/client.rbs +14 -0
  48. data/sig/redis_queued_locks/config.rbs +15 -1
  49. data/sig/redis_queued_locks/errors.rbs +6 -0
  50. data/sig/redis_queued_locks/instrument/void_notifier.rbs +2 -2
  51. data/sig/redis_queued_locks/lock_keeper/instr_visitor.rbs +67 -0
  52. data/sig/redis_queued_locks/lock_keeper/lease.rbs +78 -0
  53. data/sig/redis_queued_locks/lock_keeper/lock_lease.rbs +19 -0
  54. data/sig/redis_queued_locks/lock_keeper/log_visitor.rbs +62 -0
  55. data/sig/redis_queued_locks/lock_keeper.rbs +108 -0
  56. data/sig/redis_queued_locks/utilities.rbs +0 -2
  57. data/sig/vendor/redis_client.rbs +1 -0
  58. metadata +15 -1
@@ -2,7 +2,7 @@
2
2
 
3
3
  # @api private
4
4
  # @since 1.7.0
5
- # @version 1.18.0
5
+ # @version 1.24.0
6
6
  module RedisQueuedLocks::Acquirer::AcquireLock::DequeueFromLockQueue
7
7
  require_relative 'dequeue_from_lock_queue/log_visitor'
8
8
 
@@ -50,4 +50,63 @@ module RedisQueuedLocks::Acquirer::AcquireLock::DequeueFromLockQueue
50
50
 
51
51
  { ok: true, result: result }
52
52
  end
53
+
54
+ # Releases the lock of an interrupted acquirement whose obtaining transaction can be applied by
55
+ # Redis without the reply (the acquirement timeout comes while the reply is read or right after
56
+ # it, before the lock is reported as obtained):
57
+ # - only the lock of the current acquirer is released (the transaction can be aborted: the lock
58
+ # can be held by another acquirer): write lock: the owner-checked release script, read lock:
59
+ # `ZREM` of the own reader + `DEL` of the own read lock data;
60
+ # - the lock index entry is kept (releases never touch the lock index);
61
+ # - logged as `expire_lock` (the requested mode is the held one: the obtaining transaction
62
+ # obtains the requested mode);
63
+ #
64
+ # @param redis [RedisClient]
65
+ # @param logger [::Logger,#debug]
66
+ # @param lock_key [String]
67
+ # @param rw_mode [Symbol]
68
+ # @param lock_readers_key [String] Registry of read lock holders.
69
+ # @param read_lock_key [String,NilClass] Read lock data of the current acquirer (read locks).
70
+ # @param queue_ttl [Integer]
71
+ # @param acquirer_id [String]
72
+ # @param host_id [String]
73
+ # @param access_strategy [Symbol]
74
+ # @param log_sampled [Boolean]
75
+ # @return [void]
76
+ #
77
+ # @api private
78
+ # @since 1.24.0
79
+ def release_unconfirmed_lock(
80
+ redis,
81
+ logger,
82
+ lock_key,
83
+ rw_mode,
84
+ lock_readers_key,
85
+ read_lock_key,
86
+ queue_ttl,
87
+ acquirer_id,
88
+ host_id,
89
+ access_strategy,
90
+ log_sampled
91
+ )
92
+ if rw_mode == :read
93
+ redis.multi do |transact|
94
+ transact.call('ZREM', lock_readers_key, acquirer_id)
95
+ transact.call('DEL', read_lock_key)
96
+ end
97
+ else
98
+ # NOTE: EVAL signature -> <lua script>, (number of keys), *(keys), *(arguments)
99
+ redis.call(
100
+ 'EVAL',
101
+ RedisQueuedLocks::Acquirer::AcquireLock::YieldExpire::RELEASE_OWN_LOCK,
102
+ 1,
103
+ lock_key,
104
+ acquirer_id
105
+ )
106
+ end
107
+
108
+ RedisQueuedLocks::Acquirer::AcquireLock::YieldExpire::LogVisitor.expire_lock(
109
+ logger, log_sampled, lock_key, queue_ttl, acquirer_id, host_id, access_strategy, rw_mode
110
+ )
111
+ end
53
112
  end
@@ -2,7 +2,7 @@
2
2
 
3
3
  # @api private
4
4
  # @since 1.7.0
5
- # @version 1.22.0
5
+ # @version 1.24.0
6
6
  # rubocop:disable Metrics/ModuleLength
7
7
  module RedisQueuedLocks::Acquirer::AcquireLock::TryToLock::LogVisitor
8
8
  # rubocop:disable Metrics/ClassLength
@@ -790,6 +790,43 @@ module RedisQueuedLocks::Acquirer::AcquireLock::TryToLock::LogVisitor
790
790
  end rescue nil
791
791
  end
792
792
 
793
+ # @param logger [::Logger,#debug]
794
+ # @param log_sampled [Boolean]
795
+ # @param log_lock_try [Boolean]
796
+ # @param lock_key [String]
797
+ # @param queue_ttl [Integer]
798
+ # @param acquirer_id [String]
799
+ # @param host_id [String]
800
+ # @param access_strategy [Symbol]
801
+ # @param rw_mode [Symbol]
802
+ # @return [void]
803
+ #
804
+ # @api private
805
+ # @since 1.24.0
806
+ def exit__reentrant_lock_is_changed(
807
+ logger,
808
+ log_sampled,
809
+ log_lock_try,
810
+ lock_key,
811
+ queue_ttl,
812
+ acquirer_id,
813
+ host_id,
814
+ access_strategy,
815
+ rw_mode
816
+ )
817
+ return unless log_sampled && log_lock_try
818
+
819
+ logger.debug do
820
+ "[redis_queued_locks.try_lock.exit__reentrant_lock_is_changed] " \
821
+ "lock_key => '#{lock_key}' " \
822
+ "queue_ttl => #{queue_ttl} " \
823
+ "acq_id => '#{acquirer_id}' " \
824
+ "hst_id => '#{host_id}' " \
825
+ "acs_strat => '#{access_strategy}' " \
826
+ "rw_mode => '#{rw_mode}'"
827
+ end rescue nil
828
+ end
829
+
793
830
  # @param logger [::Logger,#debug]
794
831
  # @param log_sampled [Boolean]
795
832
  # @param log_lock_try [Boolean]
@@ -52,7 +52,7 @@
52
52
  #
53
53
  # @api private
54
54
  # @since 1.0.0
55
- # @version 1.23.0
55
+ # @version 1.24.0
56
56
  # rubocop:disable Metrics/ModuleLength
57
57
  module RedisQueuedLocks::Acquirer::AcquireLock::TryToLock
58
58
  require_relative 'try_to_lock/log_visitor'
@@ -171,6 +171,17 @@ module RedisQueuedLocks::Acquirer::AcquireLock::TryToLock
171
171
  # @since 1.22.0
172
172
  MAX_DEAD_REQUEST_REMOVALS = 5
173
173
 
174
+ # How many times an attempt that is aborted by a change of the already held lock is repeated at
175
+ # once: an extension of the lock keeper changes the held lock (its ttl) during a reentrant
176
+ # attempt. It is not a failed acquirement: the lock is held, the next attempt sees the actual
177
+ # lock state. The limit protects from a key that is changed without pauses.
178
+ #
179
+ # @return [Integer]
180
+ #
181
+ # @api private
182
+ # @since 1.24.0
183
+ MAX_REENTRANT_EXTENSION_RETRIES = 5
184
+
174
185
  # @param redis [RedisClient]
175
186
  # @param logger [::Logger,#debug]
176
187
  # @param log_lock_try [Boolean]
@@ -202,13 +213,17 @@ module RedisQueuedLocks::Acquirer::AcquireLock::TryToLock
202
213
  # @param meta [NilClass,Hash<String|Symbol,Any>]
203
214
  # @param retry_attempt [Boolean]
204
215
  # The attempt is a retry (the previous attempt of the acquirement did not obtain the lock).
216
+ # @param acq_process [Hash<Symbol,Any>]
217
+ # The observer of the acquirement: the attempt sets `:lock_obtaining_sent` before the obtaining
218
+ # transaction is sent (an interrupted acquirement releases the lock of a transaction that can be
219
+ # applied by Redis without the reply, see `AcquireLock.acquire_lock`) and drops it at its start.
205
220
  # @param log_sampled [Boolean]
206
221
  # @param instr_sampled [Boolean]
207
222
  # @return [Hash<Symbol,Any>] Format: { ok: true/false, result: Symbol|Hash<Symbol,Any> }
208
223
  #
209
224
  # @api private
210
225
  # @since 1.0.0
211
- # @version 1.22.0
226
+ # @version 1.24.0
212
227
  # rubocop:disable Metrics/MethodLength
213
228
  def try_to_lock(
214
229
  redis,
@@ -234,9 +249,12 @@ module RedisQueuedLocks::Acquirer::AcquireLock::TryToLock
234
249
  access_strategy,
235
250
  meta,
236
251
  retry_attempt,
252
+ acq_process,
237
253
  log_sampled,
238
254
  instr_sampled
239
255
  )
256
+ # Step X: the obtaining transaction of the previous attempt is not sent anymore
257
+ acq_process[:lock_obtaining_sent] = false
240
258
  # Step X: intermediate invocation results
241
259
  # @type var inter_result: Symbol?
242
260
  inter_result = nil
@@ -566,6 +584,10 @@ module RedisQueuedLocks::Acquirer::AcquireLock::TryToLock
566
584
  queue_ttl, acquirer_id, host_id, access_strategy, rw_mode
567
585
  )
568
586
  end
587
+
588
+ # NOTE: an interruption after this point can leave the applied obtaining transaction
589
+ # without its reply: the acquirement releases this lock (see `@param acq_process`);
590
+ acq_process[:lock_obtaining_sent] = true if inter_result == :lock_obtaining
569
591
  end
570
592
  end
571
593
  rescue RedisQueuedLocks::LockAcquirementIntermediateTimeoutError,
@@ -657,8 +679,13 @@ module RedisQueuedLocks::Acquirer::AcquireLock::TryToLock
657
679
  { ok: false, result: :unknown }
658
680
  end
659
681
  elsif result == nil || (result.is_a?(::Array) && result.empty?)
660
- # NOTE: the lock key was changed durign an SPC logic execution
661
- { ok: false, result: :lock_is_acquired_during_acquire_race }
682
+ # NOTE: the lock key was changed durign an SPC logic execution (an extension of the lock
683
+ # keeper, for example): the attempt is repeated at once (see `AcquireLock`);
684
+ LogVisitor.exit__reentrant_lock_is_changed(
685
+ logger, log_sampled, log_lock_try, lock_key,
686
+ queue_ttl, acquirer_id, host_id, access_strategy, rw_mode
687
+ )
688
+ { ok: false, result: :reentrant_lock_is_changed_during_extension }
662
689
  else
663
690
  # NOTE: unknown behaviour :thinking:. this part is not reachable at the moment.
664
691
  { ok: false, result: :unknown }
@@ -16,7 +16,8 @@ module RedisQueuedLocks::Acquirer::AcquireLock::WithAcqTimeout
16
16
  # @param detailed_acq_timeout_error [Boolean]
17
17
  # Add additional error data about lock queue and required lock to the timeout error or not.
18
18
  # @option on_timeout [Proc,NilClass]
19
- # Callback invoked on Timeout::Error.
19
+ # Callback invoked on the timeout: `true` means that the acquirement is completed right before
20
+ # the timeout (the lock is obtained: no timeout error).
20
21
  # @yield Custom logic that should be invoked under the obtained lock.
21
22
  # @yieldreturn [Any]
22
23
  # @return [Any]
@@ -26,7 +27,7 @@ module RedisQueuedLocks::Acquirer::AcquireLock::WithAcqTimeout
26
27
  #
27
28
  # @api private
28
29
  # @since 1.0.0
29
- # @version 1.21.0
30
+ # @version 1.24.0
30
31
  def with_acq_timeout(
31
32
  redis,
32
33
  timeout,
@@ -39,9 +40,11 @@ module RedisQueuedLocks::Acquirer::AcquireLock::WithAcqTimeout
39
40
  )
40
41
  ::Timeout.timeout(timeout, RedisQueuedLocks::LockAcquirementIntermediateTimeoutError, &block)
41
42
  rescue RedisQueuedLocks::LockAcquirementIntermediateTimeoutError
43
+ # NOTE: the timeout can come right after the lock is obtained (in the same iteration of the
44
+ # acquirement): the acquirement is completed, not failed;
42
45
  if on_timeout != nil
43
46
  # @type var on_timeout: Proc
44
- on_timeout.call
47
+ return if on_timeout.call == true
45
48
  end
46
49
 
47
50
  if raise_errors
@@ -2,7 +2,7 @@
2
2
 
3
3
  # @api private
4
4
  # @since 1.3.0
5
- # @version 1.18.0
5
+ # @version 1.24.0
6
6
  # rubocop:disable Metrics/ModuleLength
7
7
  module RedisQueuedLocks::Acquirer::AcquireLock::YieldExpire
8
8
  require_relative 'yield_expire/log_visitor'
@@ -16,6 +16,31 @@ module RedisQueuedLocks::Acquirer::AcquireLock::YieldExpire
16
16
  return redis.call("PEXPIRE", KEYS[1], new_lock_pttl);
17
17
  LUA_SCRIPT
18
18
 
19
+ # Releases the write lock of the given acquirer only: an auto extended lock can be lost during
20
+ # the block of code (the hold limit, a stuck keeper, an explicit release), and the next owner
21
+ # of the lock should not lose it.
22
+ #
23
+ # @return [String]
24
+ #
25
+ # @api private
26
+ # @since 1.24.0
27
+ RELEASE_OWN_LOCK = <<~LUA_SCRIPT.strip.tr("\n", '').freeze
28
+ if redis.call("HGET", KEYS[1], "acq_id") ~= ARGV[1] then return 0 end;
29
+ return redis.call("EXPIRE", KEYS[1], 0);
30
+ LUA_SCRIPT
31
+
32
+ # Decreases the ttl of the write lock of the given acquirer only (see `RELEASE_OWN_LOCK`).
33
+ #
34
+ # @return [String]
35
+ #
36
+ # @api private
37
+ # @since 1.24.0
38
+ DECREASE_OWN_LOCK_PTTL = <<~LUA_SCRIPT.strip.tr("\n", '').freeze
39
+ if redis.call("HGET", KEYS[1], "acq_id") ~= ARGV[1] then return 0 end;
40
+ local new_lock_pttl = redis.call("PTTL", KEYS[1]) - ARGV[2];
41
+ return redis.call("PEXPIRE", KEYS[1], new_lock_pttl);
42
+ LUA_SCRIPT
43
+
19
44
  # @param redis [RedisClient] Redis connection.
20
45
  # @param logger [::Logger,#debug] Logger object.
21
46
  # @param lock_key [String] Obtained lock key that should be expired.
@@ -26,6 +51,7 @@ module RedisQueuedLocks::Acquirer::AcquireLock::YieldExpire
26
51
  # @param rw_mode [Symbol]
27
52
  # - The mode of the obtained lock (`:read` or `:write`);
28
53
  # - `:read` => only the read lock of the current acquirer is released/decreased;
54
+ # @param lock_name [String] Lock name (the member of the lock index).
29
55
  # @param acquirer_id [String] Acquirer identifier.
30
56
  # @param host_id [String] Host identifier.
31
57
  # @param access_strategy [Symbol] Lock obtaining strategy.
@@ -33,6 +59,8 @@ module RedisQueuedLocks::Acquirer::AcquireLock::YieldExpire
33
59
  # @param ttl_shift [Numeric] Lock's TTL shifting. Should affect block's ttl. In millisecodns.
34
60
  # @param ttl [Integer] Lock's time to live (in ms). A positive Integer.
35
61
  # @param queue_ttl [Integer] Lock request lifetime.
62
+ # @param lock_index_enabled [Boolean] Maintain the lock index.
63
+ # @param lock_index_grace_period [Integer] The lock index score margin (in milliseconds).
36
64
  # @param meta [NilClass,Hash<String|Symbol,Any>] Custom metadata wich is passed to the lock data;
37
65
  # @param log_sampled [Boolean] Should the logic be logged or not.
38
66
  # @param instr_sampled [Boolean] Should the logic be instrumented or not.
@@ -40,13 +68,24 @@ module RedisQueuedLocks::Acquirer::AcquireLock::YieldExpire
40
68
  # @param should_decrease [Boolean]
41
69
  # - Should decrease the lock TTL after the lock invocation;
42
70
  # - It is suitable for extendable reentrant locks;
71
+ # @param lock_keeper [RedisQueuedLocks::LockKeeper] The lock keeper of the client.
72
+ # @param auto_extend [Boolean] Keep the lock alive while the block of code is running.
73
+ # @param auto_extend_ttl [Integer,NilClass]
74
+ # How long the lock lives after an auto extension (in ms), `nil`: the lock ttl.
75
+ # @param max_hold_time_during_auto_extend [Integer,NilClass]
76
+ # The auto extension limit (in ms), `nil`: no limit.
77
+ # @param try_start_time [Integer] The start of the successful attempt (`clock_gettime`).
78
+ # @param instrumenter [#notify] See `RedisQueuedLocks::LockKeeper`.
79
+ # @param instrument [NilClass,Any] See `RedisQueuedLocks::LockKeeper`.
43
80
  # @yield Custom logic that should be invoked under the obtained lock.
81
+ # @yieldparam lease [RedisQueuedLocks::LockKeeper::LockLease]
82
+ # The lease of an auto extended block of code (only for a block with arguments).
44
83
  # @yieldreturn [Any]
45
84
  # @return [Any,NilClass] nil is returned when no block parametr is provided.
46
85
  #
47
86
  # @api private
48
87
  # @since 1.3.0
49
- # @version 1.21.0
88
+ # @version 1.24.0
50
89
  # rubocop:disable Metrics/MethodLength
51
90
  def yield_expire(
52
91
  redis,
@@ -55,6 +94,7 @@ module RedisQueuedLocks::Acquirer::AcquireLock::YieldExpire
55
94
  lock_readers_key,
56
95
  read_lock_key,
57
96
  rw_mode,
97
+ lock_name,
58
98
  acquirer_id,
59
99
  host_id,
60
100
  access_strategy,
@@ -62,49 +102,86 @@ module RedisQueuedLocks::Acquirer::AcquireLock::YieldExpire
62
102
  ttl_shift,
63
103
  ttl,
64
104
  queue_ttl,
105
+ lock_index_enabled,
106
+ lock_index_grace_period,
65
107
  meta,
66
108
  log_sampled,
67
109
  instr_sampled,
68
110
  should_expire,
69
111
  should_decrease,
112
+ lock_keeper,
113
+ auto_extend,
114
+ auto_extend_ttl,
115
+ max_hold_time_during_auto_extend,
116
+ try_start_time,
117
+ instrumenter,
118
+ instrument,
70
119
  &block
71
120
  )
72
121
  initial_time = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC, :millisecond)
122
+ # @type var lock_lease: RedisQueuedLocks::LockKeeper::Lease?
123
+ lock_lease = nil
124
+ # @type var lease_handle: RedisQueuedLocks::LockKeeper::LockLease?
125
+ lease_handle = nil
73
126
 
74
- if block_given?
75
- if timed
76
- # NOTE:
77
- # - steep is ignored cuz steep can not recognize `::Integer - ::Integer|::Float`
78
- # operation here for some mystical reason (it tryes to find overloadd `-` method for
79
- # integer and fails on it);
80
- # - so we need to ignore steep here at all and manually set the type of each
81
- # variable for the correct following variable type recognitions;
82
-
83
- # steep:ignore:start
84
- # @type var ttl: Integer
85
- # @type var ttl_shift: Float|Integer
86
- # @type var timeout: Float
87
- timeout = ((ttl - ttl_shift) / 1_000.0).yield_self do |time|
88
- # @type var time: Float
89
- # NOTE: time in <seconds> cuz Ruby's Timeout requires <seconds>
90
- (time < 0) ? 0.0 : time
127
+ if block
128
+ # NOTE: (auto extension) inside the `ensure` scope of the lock release: the lease of an
129
+ # interrupted method is dropped by the keeper (the released lock is not found);
130
+ if auto_extend
131
+ lock_lease = lock_keeper.keep(
132
+ [lock_key],
133
+ [lock_readers_key],
134
+ [read_lock_key],
135
+ [rw_mode],
136
+ [lock_name],
137
+ acquirer_id,
138
+ host_id,
139
+ try_start_time,
140
+ # NOTE: (auto extension) the lock lives `ttl` from the attempt (obtained or extended by
141
+ # it), except a reentrant lock that is not extended (`:work_through`): its remaining
142
+ # ttl is unknown (the outer logic can have spent it), so it is extended at once (`0`);
143
+ (should_expire || should_decrease) ? ttl : 0,
144
+ auto_extend_ttl || ttl,
145
+ max_hold_time_during_auto_extend,
146
+ lock_index_enabled,
147
+ lock_index_grace_period,
148
+ logger,
149
+ log_sampled,
150
+ instrumenter,
151
+ instr_sampled,
152
+ instrument
153
+ )
154
+ # NOTE: (auto extension) the block of code gets its lease when it takes an argument (no
155
+ # object for a block without arguments, a lambda without parameters gets no argument);
156
+ if block.arity != 0
157
+ lease_handle = RedisQueuedLocks::LockKeeper::LockLease.new(lock_keeper, lock_lease, redis)
91
158
  end
92
- # steep:ignore:end
159
+ end
93
160
 
161
+ if timed
94
162
  yield_with_timeout(
95
- timeout,
163
+ timed_block_budget(lock_lease ? max_hold_time_during_auto_extend : ttl, ttl_shift),
96
164
  lock_key,
97
165
  ttl,
166
+ max_hold_time_during_auto_extend,
167
+ lock_keeper,
168
+ lock_lease,
169
+ lease_handle,
98
170
  acquirer_id,
99
171
  host_id,
100
172
  meta,
101
173
  &block
102
174
  )
175
+ elsif lease_handle
176
+ yield(lease_handle)
103
177
  else
104
178
  yield
105
179
  end
106
180
  end
107
181
  ensure
182
+ # NOTE: (auto extension) the lock keeper should not report the released lock as a lost one;
183
+ lock_keeper.forget(lock_lease) if lock_lease
184
+
108
185
  if should_expire # TODO: comment all cases/examples when should_expire is true
109
186
  LogVisitor.expire_lock(
110
187
  logger, log_sampled, lock_key,
@@ -116,6 +193,9 @@ module RedisQueuedLocks::Acquirer::AcquireLock::YieldExpire
116
193
  transact.call('ZREM', lock_readers_key, acquirer_id)
117
194
  transact.call('DEL', read_lock_key)
118
195
  end
196
+ elsif lock_lease
197
+ # NOTE: EVAL signature -> <lua script>, (number of keys), *(keys), *(arguments)
198
+ redis.call('EVAL', RELEASE_OWN_LOCK, 1, lock_key, acquirer_id)
119
199
  else
120
200
  redis.call('EXPIRE', lock_key, '0')
121
201
  end
@@ -137,6 +217,8 @@ module RedisQueuedLocks::Acquirer::AcquireLock::YieldExpire
137
217
  # - XX => do nothing if the read lock is already expired and removed from the registry;
138
218
  # - the read lock data TTL is not decreased (it is not used without the read lock);
139
219
  redis.call('ZADD', lock_readers_key, 'XX', 'INCR', -decreased_ttl, acquirer_id)
220
+ elsif lock_lease
221
+ redis.call('EVAL', DECREASE_OWN_LOCK_PTTL, 1, lock_key, acquirer_id, decreased_ttl)
140
222
  else
141
223
  # NOTE:# NOTE: EVAL signature -> <lua script>, (number of keys), *(keys), *(arguments)
142
224
  redis.call('EVAL', DECREASE_LOCK_PTTL, 1, lock_key, decreased_ttl)
@@ -149,9 +231,38 @@ module RedisQueuedLocks::Acquirer::AcquireLock::YieldExpire
149
231
 
150
232
  private
151
233
 
152
- # @param timeout [Float]
234
+ # The time budget of a `timed` block of code.
235
+ #
236
+ # @param time_limit [Integer,NilClass]
237
+ # The limit of the block of code (in milliseconds), `nil`: no limit: the lock ttl or, for an
238
+ # auto extended lock, its hold limit.
239
+ # @param ttl_shift [Numeric] The time that is already spent from the limit (in milliseconds).
240
+ # @return [Float,NilClass] In seconds (Ruby's Timeout requires seconds), `nil`: no limit.
241
+ #
242
+ # @api private
243
+ # @since 1.24.0
244
+ def timed_block_budget(time_limit, ttl_shift)
245
+ return unless time_limit
246
+
247
+ # NOTE: steep is ignored cuz steep can not recognize `::Integer - ::Integer|::Float` operation
248
+ # here for some mystical reason (it tryes to find overloadd `-` method for integer and fails
249
+ # on it);
250
+
251
+ # steep:ignore:start
252
+ ((time_limit - ttl_shift) / 1_000.0).yield_self do |time|
253
+ (time < 0) ? 0.0 : time
254
+ end
255
+ # steep:ignore:end
256
+ end
257
+
258
+ # @param timeout [Float,NilClass] `nil`: no time limit (an auto extended lock without a limit).
153
259
  # @param lock_key [String]
154
260
  # @param lock_ttl [Integer]
261
+ # @param max_hold_time_during_auto_extend [Integer,NilClass]
262
+ # @param lock_keeper [RedisQueuedLocks::LockKeeper]
263
+ # @param lock_lease [RedisQueuedLocks::LockKeeper::Lease,NilClass]
264
+ # @param lease_handle [RedisQueuedLocks::LockKeeper::LockLease,NilClass]
265
+ # The argument of the block of code.
155
266
  # @param acquirer_id [String]
156
267
  # @param host_id [String]
157
268
  # @param meta [NilClass,Hash<Symbol|String,Any>]
@@ -161,11 +272,26 @@ module RedisQueuedLocks::Acquirer::AcquireLock::YieldExpire
161
272
  # @raise [RedisQueuedLocks::TimedLockTimeoutError]
162
273
  # @raise [RedisQueuedLocks::LockTtlTimeBudgetIsSpentError]
163
274
  # @raise [RedisQueuedLocks::TimedBlockExceedsLockTtlError]
275
+ # @raise [RedisQueuedLocks::TimedBlockExceedsMaxHoldTimeError]
276
+ # @raise [RedisQueuedLocks::TimedBlockLostLockError]
164
277
  #
165
278
  # @api private
166
279
  # @since 1.3.0
167
- # @version 1.23.1
168
- def yield_with_timeout(timeout, lock_key, lock_ttl, acquirer_id, host_id, meta, &block)
280
+ # @version 1.24.0
281
+ # rubocop:disable Metrics/MethodLength
282
+ def yield_with_timeout(
283
+ timeout,
284
+ lock_key,
285
+ lock_ttl,
286
+ max_hold_time_during_auto_extend,
287
+ lock_keeper,
288
+ lock_lease,
289
+ lease_handle,
290
+ acquirer_id,
291
+ host_id,
292
+ meta,
293
+ &block
294
+ )
169
295
  # NOTE: no budget left => the block is not invoked (`Timeout.timeout(0)` means "no timeout")
170
296
  if timeout == 0.0
171
297
  raise(
@@ -176,19 +302,101 @@ module RedisQueuedLocks::Acquirer::AcquireLock::YieldExpire
176
302
  "acq_id: \"#{acquirer_id}\", " \
177
303
  "hst_id: \"#{host_id}\")"
178
304
  )
179
- else
305
+ end
306
+
307
+ # @type var raised_error: Exception?
308
+ raised_error = nil
309
+
310
+ begin
180
311
  begin
181
- ::Timeout.timeout(timeout, RedisQueuedLocks::TimedLockIntermediateTimeoutError, &block)
182
- rescue RedisQueuedLocks::TimedLockIntermediateTimeoutError
183
- raise(
184
- RedisQueuedLocks::TimedBlockExceedsLockTtlError,
185
- "Passed <timed> block of code exceeded the lock TTL " \
186
- "(lock: \"#{lock_key}\", ttl: #{lock_ttl}, " \
187
- "meta: #{meta ? meta.inspect : '<no-meta>'}, " \
188
- "acq_id: \"#{acquirer_id}\", " \
189
- "hst_id: \"#{host_id}\")"
190
- )
312
+ # NOTE: (auto extension) the lock keeper interrupts the block of code from another thread
313
+ # (or through the fiber scheduler): the interruption period is limited by
314
+ # `#interrupt_timed_block` and `#forget`, both are inside the `rescue` scope: an internal
315
+ # error never reaches the application (an interruption that comes at the very end of the
316
+ # block is delivered in `#forget`);
317
+ lock_keeper.interrupt_timed_block(lock_lease) if lock_lease
318
+
319
+ if lock_lease&.interruptible?
320
+ # NOTE: (auto extension) the keeper interrupts the block at the hold limit too: the block
321
+ # can move the limit (`RedisQueuedLocks::LockKeeper::LockLease#hold_for`), a `Timeout`
322
+ # can not;
323
+ lease_handle ? yield(lease_handle) : yield
324
+ elsif lock_lease
325
+ # NOTE: (auto extension) a non-blocking fiber without a fiber scheduler that can
326
+ # interrupt it: its hold limit is a `Timeout` (a fiber scheduler implements it);
327
+ ::Timeout.timeout(timeout, RedisQueuedLocks::TimedLockIntermediateTimeoutError) do
328
+ lease_handle ? yield(lease_handle) : yield
329
+ end
330
+ else
331
+ ::Timeout.timeout(timeout, RedisQueuedLocks::TimedLockIntermediateTimeoutError, &block)
332
+ end
333
+ rescue RedisQueuedLocks::TimedLockIntermediateTimeoutError => error
334
+ # NOTE: (auto extension) an interruption of the fiber scheduler that has already come:
335
+ # `#forget` does not wait for it;
336
+ raised_error = error
337
+ raise
338
+ ensure
339
+ lock_keeper.forget(lock_lease, raised_error) if lock_lease
191
340
  end
341
+ rescue RedisQueuedLocks::TimedLockIntermediateTimeoutError => error
342
+ # NOTE: (auto extension) the interruption can come while `#forget` waits for the lock of the
343
+ # keeper: it is taken here, so the next `#forget` calls do not wait for it;
344
+ lock_keeper.forget(lock_lease, error) if lock_lease
345
+ raise_timed_block_error(
346
+ lock_key, lock_ttl, max_hold_time_during_auto_extend, lock_lease, acquirer_id, host_id, meta
347
+ )
348
+ end
349
+ end
350
+ # rubocop:enable Metrics/MethodLength
351
+
352
+ # @param lock_key [String]
353
+ # @param lock_ttl [Integer]
354
+ # @param max_hold_time_during_auto_extend [Integer,NilClass]
355
+ # @param lock_lease [RedisQueuedLocks::LockKeeper::Lease,NilClass]
356
+ # @param acquirer_id [String]
357
+ # @param host_id [String]
358
+ # @param meta [NilClass,Hash<Symbol|String,Any>]
359
+ # @return [void]
360
+ #
361
+ # @raise [RedisQueuedLocks::TimedBlockExceedsLockTtlError]
362
+ # @raise [RedisQueuedLocks::TimedBlockExceedsMaxHoldTimeError]
363
+ # @raise [RedisQueuedLocks::TimedBlockLostLockError]
364
+ #
365
+ # @api private
366
+ # @since 1.24.0
367
+ def raise_timed_block_error(
368
+ lock_key,
369
+ lock_ttl,
370
+ max_hold_time_during_auto_extend,
371
+ lock_lease,
372
+ acquirer_id,
373
+ host_id,
374
+ meta
375
+ )
376
+ lock_details =
377
+ "(lock: \"#{lock_key}\", ttl: #{lock_ttl}, " \
378
+ "meta: #{meta ? meta.inspect : '<no-meta>'}, " \
379
+ "acq_id: \"#{acquirer_id}\", " \
380
+ "hst_id: \"#{host_id}\")"
381
+
382
+ if lock_lease&.lost?
383
+ raise(
384
+ RedisQueuedLocks::TimedBlockLostLockError,
385
+ "The lock of the passed <timed> block of code is lost #{lock_details}"
386
+ )
387
+ elsif lock_lease
388
+ raise(
389
+ RedisQueuedLocks::TimedBlockExceedsMaxHoldTimeError,
390
+ "Passed <timed> block of code exceeded the max hold time of the lock " \
391
+ "(#{max_hold_time_during_auto_extend}" \
392
+ "#{', moved by the block of code' if lock_lease.hold_moved?}) " \
393
+ "#{lock_details}"
394
+ )
395
+ else
396
+ raise(
397
+ RedisQueuedLocks::TimedBlockExceedsLockTtlError,
398
+ "Passed <timed> block of code exceeded the lock TTL #{lock_details}"
399
+ )
192
400
  end
193
401
  end
194
402
  end