Module: Gitlab::ExclusiveLeaseHelpers

Overview

This module provides helper methods which are intregrated with GitLab::ExclusiveLease

Defined Under Namespace

Classes: SleepingLock

Constant Summary collapse

FailedToObtainLockError =
Class.new(StandardError)

Instance Method Summary collapse

Instance Method Details

#in_lock(key, ttl: 1.minute, retries: 10, sleep_sec: 0.01.seconds) ⇒ Object

This helper method blocks a process/thread until the lease can be acquired, either due to the lease TTL expiring, or due to the current holder explicitly releasing their hold.

If the lease cannot be obtained, raises `FailedToObtainLockError`.

(from 1 to retries - 1)

Note: It's basically discouraged to use this method in a unicorn thread,

because this ties up all thread related resources until all `retries` are consumed.
This could potentially eat up all connection pools.

Parameters:

  • key (String)

    The lock the thread will try to acquire. Only one thread in one process across all Rails instances can hold this named lock at any one time.

  • ttl: (Float) (defaults to: 1.minute)

    The length of time the lock will be valid for. The lock will be automatically be released after this time, so any work should be completed within this time.

  • retries: (Integer) (defaults to: 10)

    The maximum number of times we will re-attempt to acquire the lock. The maximum number of attempts will be `retries + 1`: one for the initial attempt, and then one for every re-try.

  • sleep_sec: (Float|Proc) (defaults to: 0.01.seconds)

    Either a number of seconds to sleep, or a proc that computes the sleep time given the number of preceding attempts


31
32
33
34
35
36
37
38
39
40
41
# File 'lib/gitlab/exclusive_lease_helpers.rb', line 31

def in_lock(key, ttl: 1.minute, retries: 10, sleep_sec: 0.01.seconds)
  raise ArgumentError, 'Key needs to be specified' unless key

  lease = SleepingLock.new(key, timeout: ttl, delay: sleep_sec)

  lease.obtain(1 + retries)

  yield(lease.retried?)
ensure
  lease&.cancel
end