redis_queued_locks 1.23.0 → 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 -3
  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 +30 -9
  17. data/CLAUDE.md +7 -5
  18. data/README.md +390 -17
  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 +257 -32
  24. data/lib/redis_queued_locks/acquirer/acquire_lock.rb +103 -4
  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 +160 -15
  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 +19 -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 +12 -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.0.0
5
- # @version 1.23.0
5
+ # @version 1.24.0
6
6
  # rubocop:disable Metrics/ModuleLength
7
7
  # rubocop:disable Metrics/MethodLength
8
8
  # rubocop:disable Metrics/ClassLength
@@ -61,6 +61,15 @@ module RedisQueuedLocks::Acquirer::AcquireLock
61
61
  # (`0` is the same as `nil`: `Timeout.timeout(0)` sets no timeout).
62
62
  # @option timed [Boolean]
63
63
  # Limit the invocation time period of the passed block of code by the lock's TTL.
64
+ # @option auto_extend [Boolean]
65
+ # Keep the lock alive while the passed block of code is running: see `Client#lock`.
66
+ # @option auto_extend_ttl [Integer,NilClass]
67
+ # How long the lock lives after an auto extension (in milliseconds), `nil`: the lock ttl.
68
+ # @option max_hold_time_during_auto_extend [Integer,NilClass]
69
+ # The limit of the auto extension (in milliseconds), `nil`: no limit; the block of code can
70
+ # move it (`RedisQueuedLocks::LockKeeper::LockLease#hold_for`).
71
+ # @option lock_keeper [RedisQueuedLocks::LockKeeper]
72
+ # The lock keeper of the client.
64
73
  # @option retry_count [Integer,NilClass]
65
74
  # How many times we should try to acquire a lock. Nil means "infinite retries".
66
75
  # @option retry_delay [Integer]
@@ -74,7 +83,7 @@ module RedisQueuedLocks::Acquirer::AcquireLock
74
83
  # @option identity [String]
75
84
  # Unique acquire identifier that is also should be unique between processes and pods
76
85
  # on different machines. By default the uniq identity string is
77
- # represented as 10 bytes hexstr.
86
+ # a 16-character hex string (`SecureRandom.hex(8)`).
78
87
  # @option fail_fast [Boolean]
79
88
  # Should the required lock to be checked before the try and exit immidetly if lock is
80
89
  # already obtained.
@@ -186,6 +195,8 @@ module RedisQueuedLocks::Acquirer::AcquireLock
186
195
  # despite the enabled instrumentation sampling;
187
196
  # - makes sense when instrumentation sampling is enabled;
188
197
  # @yield A block of code that should be executed after the successfully acquired lock.
198
+ # @yieldparam lease [RedisQueuedLocks::LockKeeper::LockLease]
199
+ # The lease of an auto extended block of code (a block with arguments): see `Client#lock`.
189
200
  # @yieldreturn [Any]
190
201
  # @return [Hash<Symbol,Any>,yield]
191
202
  # - Format: { ok: true/false, result: Any }
@@ -193,7 +204,7 @@ module RedisQueuedLocks::Acquirer::AcquireLock
193
204
  #
194
205
  # @api private
195
206
  # @since 1.0.0
196
- # @version 1.23.0
207
+ # @version 1.24.0
197
208
  def acquire_lock(
198
209
  redis,
199
210
  lock_name,
@@ -207,6 +218,10 @@ module RedisQueuedLocks::Acquirer::AcquireLock
207
218
  lock_index_grace_period:,
208
219
  timeout:,
209
220
  timed:,
221
+ auto_extend:,
222
+ auto_extend_ttl:,
223
+ max_hold_time_during_auto_extend:,
224
+ lock_keeper:,
210
225
  retry_count:,
211
226
  retry_delay:,
212
227
  retry_jitter:,
@@ -312,6 +327,35 @@ module RedisQueuedLocks::Acquirer::AcquireLock
312
327
  )
313
328
  end
314
329
 
330
+ # Step 0.1: prevent :auto_extend_ttl and :max_hold_time_during_auto_extend incompatibilities
331
+ # (the same ranges as their config keys); the hold limit shorter than the lock ttl can not
332
+ # be reached: the lock is obtained for a longer time;
333
+ if auto_extend_ttl != nil && (!auto_extend_ttl.is_a?(::Integer) || auto_extend_ttl <= 0)
334
+ raise(
335
+ RedisQueuedLocks::ArgumentError,
336
+ "`:auto_extend_ttl` argument should be nil or a positive Integer, " \
337
+ "got #{auto_extend_ttl.inspect}."
338
+ )
339
+ end
340
+ if max_hold_time_during_auto_extend != nil &&
341
+ (!max_hold_time_during_auto_extend.is_a?(::Integer) ||
342
+ max_hold_time_during_auto_extend <= 0)
343
+ raise(
344
+ RedisQueuedLocks::ArgumentError,
345
+ "`:max_hold_time_during_auto_extend` argument should be nil or a positive Integer, " \
346
+ "got #{max_hold_time_during_auto_extend.inspect}."
347
+ )
348
+ end
349
+ if auto_extend && block_given? &&
350
+ max_hold_time_during_auto_extend && max_hold_time_during_auto_extend < ttl
351
+ raise(
352
+ RedisQueuedLocks::ArgumentError,
353
+ "`:max_hold_time_during_auto_extend` argument of an auto extended lock should not " \
354
+ "be less than `:ttl`, got #{max_hold_time_during_auto_extend.inspect} " \
355
+ "(ttl: #{ttl.inspect})."
356
+ )
357
+ end
358
+
315
359
  # Step 0.1: prevent :priority incompatibilities (the same range as its config key)
316
360
  # - a Symbol is a priority name of `config['lock_priorities']`: it is resolved to its
317
361
  # Integer priority (the lock request queues, the logs and the instrumentation use the
@@ -410,14 +454,33 @@ module RedisQueuedLocks::Acquirer::AcquireLock
410
454
  lock_info: {},
411
455
  should_try: true,
412
456
  tries: 0,
457
+ reentrant_retries: 0,
413
458
  acquired: false,
459
+ lock_obtaining_sent: false, # NOTE: see `try_to_lock`
414
460
  result: nil,
461
+ try_start_time: nil,
415
462
  acq_time: nil, # NOTE: in milliseconds
416
463
  hold_time: nil, # NOTE: in milliseconds
417
464
  rel_time: nil # NOTE: in milliseconds
418
465
  }
419
466
 
467
+ # NOTE: the cleanup of a failed acquirement (the timeout of `with_acq_timeout` and the
468
+ # failures of Step 2.2):
469
+ # - the lock is obtained right before the timeout: the acquirement is completed (`true`);
470
+ # - the obtaining transaction of an interrupted attempt can be applied by Redis without the
471
+ # reply (the timeout comes while the reply is read or before the lock is reported): this
472
+ # lock is released (owner-checked: it belongs to another acquirer when the transaction is
473
+ # aborted);
474
+ # - the lock request is dropped from the queue (`false`);
420
475
  acq_dequeue = proc do
476
+ next true if acq_process[:acquired]
477
+
478
+ if acq_process[:lock_obtaining_sent]
479
+ release_unconfirmed_lock(
480
+ redis, logger, lock_key, rw_mode, lock_readers_key, read_lock_key, queue_ttl,
481
+ acquirer_id, host_id, access_strategy, log_sampled
482
+ )
483
+ end
421
484
  dequeue_from_lock_queue(
422
485
  redis,
423
486
  logger,
@@ -432,6 +495,7 @@ module RedisQueuedLocks::Acquirer::AcquireLock
432
495
  log_sampled,
433
496
  instr_sampled
434
497
  )
498
+ false
435
499
  end
436
500
 
437
501
  LogVisitor.start_lock_obtaining(
@@ -439,6 +503,9 @@ module RedisQueuedLocks::Acquirer::AcquireLock
439
503
  queue_ttl, acquirer_id, host_id, access_strategy, rw_mode, priority
440
504
  )
441
505
 
506
+ # Step 1.1: (auto extension) the lock keeper should be ready before the lock is obtained
507
+ lock_keeper.start if auto_extend && block_given?
508
+
442
509
  # Step 2: try to lock with timeout
443
510
  # NOTE: the acquirement start time is defined out of the timeout block: the failed
444
511
  # acquirement reports the acquirement time too (Steps 3.b and 3.c);
@@ -472,6 +539,8 @@ module RedisQueuedLocks::Acquirer::AcquireLock
472
539
  )
473
540
  end
474
541
 
542
+ acq_process[:try_start_time] = clock_gettime
543
+
475
544
  # NOTE: (steep ignorance) pattern matching is not supported in steep
476
545
  # steep:ignore:start
477
546
  try_to_lock(
@@ -498,6 +567,7 @@ module RedisQueuedLocks::Acquirer::AcquireLock
498
567
  access_strategy,
499
568
  meta,
500
569
  acq_process[:tries] > 0, # NOTE: retry attempt (see "pre-check" in `try_to_lock`)
570
+ acq_process,
501
571
  log_sampled,
502
572
  instr_sampled
503
573
  ) => { ok:, result: }
@@ -575,6 +645,19 @@ module RedisQueuedLocks::Acquirer::AcquireLock
575
645
  else
576
646
  # @type var result: Symbol
577
647
 
648
+ # NOTE: the failed attempt has obtained nothing (an aborted obtaining transaction too)
649
+ acq_process[:lock_obtaining_sent] = false
650
+
651
+ # Step 2.1.b: the already held lock is changed during the reentrant attempt (an
652
+ # extension of the lock keeper, for example): the lock is not lost and the attempt
653
+ # has failed nothing: the next attempt is made at once (no delay, no spent try, no
654
+ # `fail_fast` failure) and it sees the actual lock state;
655
+ if result == :reentrant_lock_is_changed_during_extension &&
656
+ acq_process[:reentrant_retries] < TryToLock::MAX_REENTRANT_EXTENSION_RETRIES
657
+ acq_process[:reentrant_retries] += 1
658
+ next
659
+ end
660
+
578
661
  # Step 2.2: failed to acquire. anylize each case and act in accordance
579
662
  case acq_process[:result]
580
663
  when :fail_fast_no_try # Step 2.2.a: fail without try
@@ -662,8 +745,14 @@ module RedisQueuedLocks::Acquirer::AcquireLock
662
745
  begin
663
746
  yield_time = clock_gettime
664
747
 
748
+ # NOTE: the budget of a `timed` block (see `Resource::REDIS_TIMESHIFT_ERROR`):
749
+ # - the lock ttl starts inside the attempt (write: `EXEC` of the transaction,
750
+ # read: `TIME` of the lock state read), this moment is unknown on the client:
751
+ # the time is counted from the start of the successful attempt (it is
752
+ # earlier, the budget can only be shorter than the real lifetime of the lock);
753
+ # - the Redis time error is a margin: it decreases the budget;
665
754
  ttl_shift = (
666
- (yield_time - acq_process[:acq_end_time]) / 1_000.0 -
755
+ (yield_time - acq_process[:try_start_time]) / 1_000.0 +
667
756
  RedisQueuedLocks::Resource::REDIS_TIMESHIFT_ERROR
668
757
  ).ceil(2)
669
758
 
@@ -681,6 +770,7 @@ module RedisQueuedLocks::Acquirer::AcquireLock
681
770
  lock_readers_key,
682
771
  read_lock_key,
683
772
  acq_process[:held_rw_mode],
773
+ lock_name,
684
774
  acquirer_id,
685
775
  host_id,
686
776
  access_strategy,
@@ -688,11 +778,20 @@ module RedisQueuedLocks::Acquirer::AcquireLock
688
778
  ttl_shift,
689
779
  ttl,
690
780
  queue_ttl,
781
+ lock_index_enabled,
782
+ lock_index_grace_period,
691
783
  meta,
692
784
  log_sampled,
693
785
  instr_sampled,
694
786
  should_expire, # NOTE: should expire the lock after the block execution
695
787
  should_decrease, # NOTE: should decrease the lock ttl in reentrant locks?
788
+ lock_keeper,
789
+ auto_extend,
790
+ auto_extend_ttl,
791
+ max_hold_time_during_auto_extend,
792
+ acq_process[:try_start_time],
793
+ instrumenter,
794
+ instrument,
696
795
  &block
697
796
  )
698
797
  ensure
@@ -73,6 +73,7 @@ module RedisQueuedLocks::Acquirer::LockSeries::TryToLockSeries
73
73
  #
74
74
  # @api private
75
75
  # @since 1.23.0
76
+ # @version 1.24.0
76
77
  # rubocop:disable Metrics/MethodLength
77
78
  def try_to_lock_series(
78
79
  redis,
@@ -383,9 +384,34 @@ module RedisQueuedLocks::Acquirer::LockSeries::TryToLockSeries
383
384
  }
384
385
  elsif result == nil || (result.is_a?(::Array) && result.empty?)
385
386
  # Step 7.b: some lock state is changed during the acquire race => nothing is obtained
387
+ # - a series with reentrant locks: an extension of the lock keeper changes the held locks,
388
+ # the attempt is repeated at once (see `LockSeries.lock_series`); a real race is found
389
+ # by the repeated attempt;
386
390
  acq_process[:lock_processes] = nil
387
391
  acq_process[:held_rw_modes] = nil
388
- { ok: false, result: :lock_is_acquired_during_acquire_race, lock_name: nil, ready_locks: }
392
+ reentrant_lock_indexes = lock_processes.each_index.select do |index|
393
+ lock_processes[index] == :extendable_conflict_work_through ||
394
+ lock_processes[index] == :conflict_work_through
395
+ end
396
+
397
+ if reentrant_lock_indexes.empty?
398
+ { ok: false, result: :lock_is_acquired_during_acquire_race, lock_name: nil, ready_locks: }
399
+ else
400
+ if log_sampled && log_lock_try
401
+ reentrant_lock_indexes.each do |index|
402
+ LogVisitor.exit__reentrant_lock_is_changed(
403
+ logger, log_sampled, log_lock_try, lock_keys[index],
404
+ queue_ttl, acquirer_id, host_id, access_strategy, rw_mode
405
+ )
406
+ end
407
+ end
408
+ {
409
+ ok: false,
410
+ result: :reentrant_lock_is_changed_during_extension,
411
+ lock_name: nil,
412
+ ready_locks:
413
+ }
414
+ end
389
415
  else
390
416
  # Step 7.c (RW): the read lock can expire during the extension (the registry is not watched):
391
417
  # a transaction can not be rolled back, so the series releases its locks and retries;
@@ -18,7 +18,7 @@
18
18
  #
19
19
  # @api private
20
20
  # @since 1.23.0
21
- # @version 1.23.0
21
+ # @version 1.24.0
22
22
  # rubocop:disable Metrics/ModuleLength
23
23
  # rubocop:disable Metrics/ClassLength
24
24
  # rubocop:disable Metrics/BlockNesting
@@ -37,6 +37,13 @@ module RedisQueuedLocks::Acquirer::LockSeries
37
37
  # @since 1.23.0
38
38
  extend TryToLockSeries
39
39
 
40
+ # @return [Integer] See `RedisQueuedLocks::Acquirer::AcquireLock::TryToLock`.
41
+ #
42
+ # @api private
43
+ # @since 1.24.0
44
+ MAX_REENTRANT_EXTENSION_RETRIES =
45
+ RedisQueuedLocks::Acquirer::AcquireLock::TryToLock::MAX_REENTRANT_EXTENSION_RETRIES
46
+
40
47
  class << self
41
48
  # @param redis [RedisClient]
42
49
  # Redis connection client.
@@ -65,6 +72,15 @@ module RedisQueuedLocks::Acquirer::LockSeries
65
72
  # timeout" (`0` is the same as `nil`: `Timeout.timeout(0)` sets no timeout).
66
73
  # @option timed [Boolean]
67
74
  # Limit the invocation time period of the passed block of code by the `ttl`.
75
+ # @option auto_extend [Boolean]
76
+ # Keep the locks alive while the passed block of code is running: see `Client#lock`.
77
+ # @option auto_extend_ttl [Integer,NilClass]
78
+ # How long the lock lives after an auto extension (in milliseconds), `nil`: the `ttl`.
79
+ # @option max_hold_time_during_auto_extend [Integer,NilClass]
80
+ # The limit of the auto extension (in milliseconds), `nil`: no limit; the block of code can
81
+ # move it (`RedisQueuedLocks::LockKeeper::LockLease#hold_for`).
82
+ # @option lock_keeper [RedisQueuedLocks::LockKeeper]
83
+ # The lock keeper of the client.
68
84
  # @option retry_count [Integer,NilClass]
69
85
  # How many times we should try to acquire the whole series. Nil means "infinite retries".
70
86
  # @option retry_delay [Integer]
@@ -118,6 +134,8 @@ module RedisQueuedLocks::Acquirer::LockSeries
118
134
  # @option instr_sample_this [Boolean]
119
135
  # See `AcquireLock.acquire_lock`.
120
136
  # @yield A block of code that should be executed under all obtained locks.
137
+ # @yieldparam lease [RedisQueuedLocks::LockKeeper::LockLease]
138
+ # The lease of an auto extended series (a block with arguments): see `Client#lock_series`.
121
139
  # @yieldreturn [Any]
122
140
  # @return [Hash<Symbol,Any>,yield]
123
141
  # - Format: { ok: true/false, result: Any };
@@ -126,7 +144,7 @@ module RedisQueuedLocks::Acquirer::LockSeries
126
144
  #
127
145
  # @api private
128
146
  # @since 1.23.0
129
- # @version 1.23.0
147
+ # @version 1.24.0
130
148
  # rubocop:disable Metrics/MethodLength
131
149
  def lock_series(
132
150
  redis,
@@ -142,6 +160,10 @@ module RedisQueuedLocks::Acquirer::LockSeries
142
160
  lock_index_grace_period:,
143
161
  timeout:,
144
162
  timed:,
163
+ auto_extend:,
164
+ auto_extend_ttl:,
165
+ max_hold_time_during_auto_extend:,
166
+ lock_keeper:,
145
167
  retry_count:,
146
168
  retry_delay:,
147
169
  retry_jitter:,
@@ -246,6 +268,35 @@ module RedisQueuedLocks::Acquirer::LockSeries
246
268
  )
247
269
  end
248
270
 
271
+ # Step 0.1: prevent :auto_extend_ttl and :max_hold_time_during_auto_extend incompatibilities
272
+ # (the same ranges as their config keys); the hold limit shorter than the lock ttl can not
273
+ # be reached: the lock is obtained for a longer time;
274
+ if auto_extend_ttl != nil && (!auto_extend_ttl.is_a?(::Integer) || auto_extend_ttl <= 0)
275
+ raise(
276
+ RedisQueuedLocks::ArgumentError,
277
+ "`:auto_extend_ttl` argument should be nil or a positive Integer, " \
278
+ "got #{auto_extend_ttl.inspect}."
279
+ )
280
+ end
281
+ if max_hold_time_during_auto_extend != nil &&
282
+ (!max_hold_time_during_auto_extend.is_a?(::Integer) ||
283
+ max_hold_time_during_auto_extend <= 0)
284
+ raise(
285
+ RedisQueuedLocks::ArgumentError,
286
+ "`:max_hold_time_during_auto_extend` argument should be nil or a positive Integer, " \
287
+ "got #{max_hold_time_during_auto_extend.inspect}."
288
+ )
289
+ end
290
+ if auto_extend && block_given? &&
291
+ max_hold_time_during_auto_extend && max_hold_time_during_auto_extend < ttl
292
+ raise(
293
+ RedisQueuedLocks::ArgumentError,
294
+ "`:max_hold_time_during_auto_extend` argument of an auto extended lock should not " \
295
+ "be less than `:ttl`, got #{max_hold_time_during_auto_extend.inspect} " \
296
+ "(ttl: #{ttl.inspect})."
297
+ )
298
+ end
299
+
249
300
  # Step 0.1: prevent :priority incompatibilities (the same range as its config key)
250
301
  # - a Symbol is a priority name of `config['lock_priorities']`: it is resolved to its
251
302
  # Integer priority (an unknown name stays a Symbol and fails the check);
@@ -350,12 +401,14 @@ module RedisQueuedLocks::Acquirer::LockSeries
350
401
  acq_process = {
351
402
  should_try: true,
352
403
  tries: 0,
404
+ reentrant_retries: 0,
353
405
  acquired: false,
354
406
  result: nil,
355
407
  failed_lock_name: nil,
356
408
  ts: nil, # NOTE: see `try_to_lock_series`
357
409
  lock_processes: nil, # NOTE: see `try_to_lock_series`
358
410
  held_rw_modes: nil, # NOTE: see `try_to_lock_series`
411
+ try_start_time: nil,
359
412
  acq_time: nil, # NOTE: in milliseconds
360
413
  acq_end_time: nil,
361
414
  rel_ts: nil,
@@ -368,12 +421,19 @@ module RedisQueuedLocks::Acquirer::LockSeries
368
421
  reported_ready_locks = Array.new(lock_names.size, false)
369
422
  # @type var yield_result: untyped
370
423
  yield_result = nil
424
+ # @type var lock_lease: RedisQueuedLocks::LockKeeper::Lease?
425
+ lock_lease = nil
426
+ # @type var lease_handle: RedisQueuedLocks::LockKeeper::LockLease?
427
+ lease_handle = nil
371
428
 
372
429
  LogVisitor.start_lock_series_obtaining(
373
430
  logger, log_sampled, lock_keys,
374
431
  queue_ttl, acquirer_id, host_id, access_strategy, rw_mode, priority
375
432
  )
376
433
 
434
+ # Step 1.1: (auto extension) the lock keeper should be ready before the locks are obtained
435
+ lock_keeper.start if auto_extend && block_given?
436
+
377
437
  # Step 2: try to obtain the series with timeout
378
438
  # NOTE: the acquirement start time is defined out of the timeout block: the failed
379
439
  # acquirement reports the acquirement time too (Step 3.b);
@@ -404,6 +464,8 @@ module RedisQueuedLocks::Acquirer::LockSeries
404
464
  )
405
465
  end
406
466
 
467
+ acq_process[:try_start_time] = clock_gettime
468
+
407
469
  attempt = try_to_lock_series(
408
470
  redis,
409
471
  logger,
@@ -470,6 +532,14 @@ module RedisQueuedLocks::Acquirer::LockSeries
470
532
  end
471
533
  end
472
534
 
535
+ # Step 2.1.b: a reentrant lock of the series is changed during the attempt: the
536
+ # same as in `AcquireLock.acquire_lock` (the next attempt is made at once);
537
+ if attempt[:result] == :reentrant_lock_is_changed_during_extension &&
538
+ acq_process[:reentrant_retries] < MAX_REENTRANT_EXTENSION_RETRIES
539
+ acq_process[:reentrant_retries] += 1
540
+ next
541
+ end
542
+
473
543
  unless attempt[:ok]
474
544
  # Step 2.2: failed to acquire. anylize each case and act in accordance
475
545
  case attempt[:result]
@@ -536,13 +606,57 @@ module RedisQueuedLocks::Acquirer::LockSeries
536
606
  host_id, acq_process[:ts], acq_process[:acq_time], reentrant_lock_keys, instrument
537
607
  )
538
608
 
609
+ # NOTE: the budget of a `timed` block (see `Resource::REDIS_TIMESHIFT_ERROR`):
610
+ # - the lock ttl starts inside the attempt (write: `EXEC` of the transaction,
611
+ # read: `TIME` of the lock state read), this moment is unknown on the client:
612
+ # the time is counted from the start of the successful attempt (it is
613
+ # earlier, the budget can only be shorter than the real lifetime of the lock);
614
+ # - the Redis time error is a margin: it decreases the budget;
539
615
  ttl_shift = (
540
- (clock_gettime - acq_process[:acq_end_time]) / 1_000.0 -
616
+ (clock_gettime - acq_process[:try_start_time]) / 1_000.0 +
541
617
  RedisQueuedLocks::Resource::REDIS_TIMESHIFT_ERROR
542
618
  ).ceil(2)
543
619
 
620
+ # NOTE: (auto extension) one lease for all locks of the series (reentrant locks too: the
621
+ # block of code needs them, an extension of a lock with a lease of the outer logic is
622
+ # harmless); inside the `ensure` scope of the release: the lease of an interrupted
623
+ # method is dropped by the keeper (the released locks are not found);
624
+ if auto_extend && block_given?
625
+ series_lease = lock_keeper.keep(
626
+ lock_keys,
627
+ lock_readers_keys,
628
+ read_lock_keys,
629
+ acq_process[:held_rw_modes],
630
+ lock_names,
631
+ acquirer_id,
632
+ host_id,
633
+ acq_process[:try_start_time],
634
+ # NOTE: the locks live `ttl` from the attempt, except the reentrant locks that are not
635
+ # extended (`:conflict_work_through`): their remaining ttl is unknown (the outer
636
+ # logic can have spent it), so the locks of such a series are extended at once
637
+ # (`0`; an extension never shortens a lock);
638
+ acq_process[:lock_processes].include?(:conflict_work_through) ? 0 : ttl,
639
+ auto_extend_ttl || ttl,
640
+ max_hold_time_during_auto_extend,
641
+ lock_index_enabled,
642
+ lock_index_grace_period,
643
+ logger,
644
+ log_sampled,
645
+ instrumenter,
646
+ instr_sampled,
647
+ instrument
648
+ )
649
+ lock_lease = series_lease
650
+ # NOTE: the block of code gets the lease of the series when it takes an argument;
651
+ if block&.arity != 0
652
+ lease_handle =
653
+ RedisQueuedLocks::LockKeeper::LockLease.new(lock_keeper, series_lease, redis)
654
+ end
655
+ end
656
+
544
657
  yield_result = yield_lock_series(
545
- lock_keys, acquirer_id, host_id, timed, ttl_shift, ttl, meta, &block
658
+ lock_keys, acquirer_id, host_id, timed, ttl_shift, ttl,
659
+ max_hold_time_during_auto_extend, lock_keeper, lock_lease, lease_handle, meta, &block
546
660
  )
547
661
  end
548
662
  ensure
@@ -554,6 +668,10 @@ module RedisQueuedLocks::Acquirer::LockSeries
554
668
  log_sampled
555
669
  )
556
670
  elsif block_given?
671
+ # NOTE: (auto extension) the lock keeper can not find the released locks and report them
672
+ # as the lost ones;
673
+ lock_keeper.forget(lock_lease) if lock_lease
674
+
557
675
  # Step 3.a.X: release the locks of the series after the block of code (on any failure too)
558
676
  spent_time = ((clock_gettime - acq_process[:acq_end_time]) / 1_000.0).ceil
559
677
  decreased_ttl = ttl - spent_time - RedisQueuedLocks::Resource::REDIS_TIMESHIFT_ERROR
@@ -693,27 +811,54 @@ module RedisQueuedLocks::Acquirer::LockSeries
693
811
  # @param timed [Boolean]
694
812
  # @param ttl_shift [Numeric] In milliseconds.
695
813
  # @param ttl [Integer] In milliseconds.
814
+ # @param max_hold_time_during_auto_extend [Integer,NilClass] In milliseconds.
815
+ # @param lock_keeper [RedisQueuedLocks::LockKeeper]
816
+ # @param lock_lease [RedisQueuedLocks::LockKeeper::Lease,NilClass]
817
+ # @param lease_handle [RedisQueuedLocks::LockKeeper::LockLease,NilClass]
818
+ # The argument of the block of code.
696
819
  # @param meta [NilClass,Hash<String|Symbol,Any>]
697
820
  # @yield Custom logic that should be invoked under the obtained locks.
821
+ # @yieldparam lease [RedisQueuedLocks::LockKeeper::LockLease]
822
+ # The lease of an auto extended block of code (only for a block with arguments).
698
823
  # @yieldreturn [Any]
699
824
  # @return [Any,NilClass] nil is returned when no block parametr is provided.
700
825
  #
701
826
  # @api private
702
827
  # @since 1.23.0
703
- def yield_lock_series(lock_keys, acquirer_id, host_id, timed, ttl_shift, ttl, meta, &block)
828
+ # @version 1.24.0
829
+ def yield_lock_series(
830
+ lock_keys,
831
+ acquirer_id,
832
+ host_id,
833
+ timed,
834
+ ttl_shift,
835
+ ttl,
836
+ max_hold_time_during_auto_extend,
837
+ lock_keeper,
838
+ lock_lease,
839
+ lease_handle,
840
+ meta,
841
+ &block
842
+ )
704
843
  return unless block_given?
705
- return yield unless timed
706
-
707
- # NOTE: (steep) see `YieldExpire#yield_expire`: `::Integer - ::Integer|::Float`
708
- # steep:ignore:start
709
- # @type var timeout: Float
710
- timeout = ((ttl - ttl_shift) / 1_000.0).yield_self do |time|
711
- # NOTE: time in <seconds> cuz Ruby's Timeout requires <seconds>
712
- (time < 0) ? 0.0 : time
844
+
845
+ unless timed
846
+ return lease_handle ? yield(lease_handle) : yield
713
847
  end
714
- # steep:ignore:end
715
848
 
716
- yield_with_timeout(timeout, lock_keys.join(', '), ttl, acquirer_id, host_id, meta, &block)
849
+ yield_with_timeout(
850
+ timed_block_budget(lock_lease ? max_hold_time_during_auto_extend : ttl, ttl_shift),
851
+ lock_keys.join(', '),
852
+ ttl,
853
+ max_hold_time_during_auto_extend,
854
+ lock_keeper,
855
+ lock_lease,
856
+ lease_handle,
857
+ acquirer_id,
858
+ host_id,
859
+ meta,
860
+ &block
861
+ )
717
862
  end
718
863
 
719
864
  # Releases the series: an interruption of the release itself (`Timeout.timeout` of the outer