Class: SidekiqUniqueJobs::Lock::BaseLock Abstract

Inherits:
Object
  • Object
show all
Includes:
SidekiqUniqueJobs::Logging
Defined in:
lib/sidekiq_unique_jobs/lock/base_lock.rb

Overview

This class is abstract.

Abstract base class for locks

Author:

Instance Method Summary collapse

Methods included from SidekiqUniqueJobs::Logging

#log_debug, #log_error, #log_fatal, #log_info, #log_warn, #logger, #logging_context

Constructor Details

#initialize(item, callback, redis_pool = nil) ⇒ BaseLock

Returns a new instance of BaseLock.

Parameters:

  • item (Hash)

    the Sidekiq job hash

  • callback (Proc)

    the callback to use after unlock

  • redis_pool (Sidekiq::RedisConnection, ConnectionPool) (defaults to: nil)

    the redis connection



15
16
17
18
19
20
# File 'lib/sidekiq_unique_jobs/lock/base_lock.rb', line 15

def initialize(item, callback, redis_pool = nil)
  @item       = item
  @callback   = callback
  @redis_pool = redis_pool
  add_uniqueness_when_missing # Used to ease testing
end

Instance Method Details

#deleteObject

Deletes the job from redis if it is locked.



50
51
52
# File 'lib/sidekiq_unique_jobs/lock/base_lock.rb', line 50

def delete
  locksmith.delete # Soft delete (don't forcefully remove when expiration is set)
end

#delete!Object

Forcefully deletes the job from redis.

This is good for jobs when a previous lock was not unlocked


56
57
58
# File 'lib/sidekiq_unique_jobs/lock/base_lock.rb', line 56

def delete!
  locksmith.delete! # Force delete the lock
end

#executeObject

Execute the job in the Sidekiq server processor

Raises:

  • (NotImplementedError)

    needs to be implemented in child class



38
39
40
# File 'lib/sidekiq_unique_jobs/lock/base_lock.rb', line 38

def execute
  raise NotImplementedError, "##{__method__} needs to be implemented in #{self.class}"
end

#lockString

Handles locking of sidekiq jobs.

Will call a conflict strategy if lock can't be achieved.

Returns:

  • (String)

    the sidekiq job id



25
26
27
28
29
30
31
32
33
34
# File 'lib/sidekiq_unique_jobs/lock/base_lock.rb', line 25

def lock
  @attempt = 0
  return item[JID_KEY] if locked?

  if (token = locksmith.lock(item[LOCK_TIMEOUT_KEY]))
    token
  else
    call_strategy
  end
end

#locked?true, false

Checks if the item has achieved a lock

Returns:

  • (true)

    when this jid has locked the job

  • (false)

    when this jid has not locked the job



63
64
65
# File 'lib/sidekiq_unique_jobs/lock/base_lock.rb', line 63

def locked?
  locksmith.locked?(item[JID_KEY])
end

#unlockString, false

Unlocks the job from redis

Returns:

  • (String)

    sidekiq job id when successful

  • (false)

    when unsuccessful



45
46
47
# File 'lib/sidekiq_unique_jobs/lock/base_lock.rb', line 45

def unlock
  locksmith.unlock(item[JID_KEY]) # Only signal to release the lock
end