<commit_before>module Sidetiq
  class Lock # :nodoc: all
    attr_reader :key, :timeout

    OWNER = "#{Socket.gethostname}:#{Process.pid}"

    def initialize(key, timeout = Sidetiq.config.lock_expire)
      @key  = key.kind_of?(Class) ? "sidetiq:#{key.name}:lock" : "sidetiq:#{key}:lock"
      @timeout   = timeout
    end

    def synchronize
      Sidekiq.redis do |redis|
        if lock(redis)

          begin
            yield redis
          ensure
            unlock(redis)
          end
        end
      end
    end

    private

    def lock(redis)
      acquired = false

      watch(redis, key) do
        if !redis.exists(key)
          acquired = !!redis.multi do |multi|
            multi.psetex(key, timeout, OWNER)
          end
        end
      end

      Sidetiq.logger.info "Sidetiq::Clock lock #{key}" if acquired

      acquired
    end

    def unlock(redis)
      watch(redis, key) do
        if redis.get(key) == OWNER
          redis.multi do |multi|
            multi.del(key)
          end

          Sidetiq.logger.info "Sidetiq::Clock unlock #{key}"
        end
      end
    end

    def watch(redis, *args)<commit_msg>Move lock debug logging into #synchronize.<commit_after>module Sidetiq
  class Lock # :nodoc: all
    attr_reader :key, :timeout

    OWNER = "#{Socket.gethostname}:#{Process.pid}"

    def initialize(key, timeout = Sidetiq.config.lock_expire)
      @key  = key.kind_of?(Class) ? "sidetiq:#{key.name}:lock" : "sidetiq:#{key}:lock"
      @timeout   = timeout
    end

    def synchronize
      Sidekiq.redis do |redis|
        if lock(redis)
          Sidetiq.logger.debug "Sidetiq::Clock lock #{key}"

          begin
            yield redis
          ensure
            unlock(redis)
            Sidetiq.logger.debug "Sidetiq::Clock unlock #{key}"
          end
        end
      end
    end

    private

    def lock(redis)
      acquired = false

      watch(redis, key) do
        if !redis.exists(key)
          acquired = !!redis.multi do |multi|
            multi.psetex(key, timeout, OWNER)
          end
        end
      end

      acquired
    end

    def unlock(redis)
      watch(redis, key) do
        if redis.get(key) == OWNER
          redis.multi do |multi|
            multi.del(key)
          end
        end
      end
    end

    def watch(redis, *args)
{'fraction_non_alphanumeric': 0.1021021021021021, 'fraction_numerical': 0.0, 'mean_word_length': 1.7338804220398594, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1832664', 'n_tokens_mistral': 769, 'n_tokens_neox': 757, 'n_words': 180}