Sha256: 1cce6360b3a16a1df0b051e2eb36d2eb5fc11a5e258917008eb9d57d15d240cc

Contents?: true

Size: 1.57 KB

Versions: 27

Compression:

Stored size: 1.57 KB

Contents

module EasyML
  module Support
    module Lockable
      KEYS_HASH = "easy_ml:lock_keys"

      def self.unlock!(key)
        suo_client = lock_client(key)

        suo_client.locks.map(&:last).each do |lock_key|
          suo_client.unlock(lock_key)
        end
      end

      def self.locked?(key)
        suo_client = lock_client(key)
        suo_client.locked?
      end

      def self.locks(key)
        suo_client = lock_client(key)
        suo_client.locks
      end

      def self.lock_client(key, wait_timeout: 0.1, stale_timeout: 60 * 10, resources: 1)
        Suo::Client::Redis.new(prefixed_key(key), {
          acquisition_timeout: wait_timeout,
          stale_lock_expiry: stale_timeout,
          resources: resources,
          client: client,
        })
      end

      def self.prefixed_key(key)
        "easy_ml:#{key}"
      end

      # Execute a block with a Redis lock
      def self.with_lock(key, wait_timeout: 0.1, stale_timeout: 60 * 10, resources: 1)
        lock_key = nil
        suo_client = lock_client(key, wait_timeout: wait_timeout, stale_timeout: stale_timeout, resources: resources)
        begin
          lock_key = suo_client.lock
          if lock_key
            yield suo_client
          end
        ensure
          suo_client.unlock(lock_key) if lock_key
        end
      end

      # Redis client
      def self.client
        @client ||= Redis.new(host: redis_host)
      end

      # Determine Redis host
      def self.redis_host
        ENV["REDIS_HOST"] || (defined?(Resque) ? Resque.redis.client.host : "localhost")
      end
    end
  end
end

Version data entries

27 entries across 27 versions & 1 rubygems

Version Path
easy_ml-0.2.0.pre.rc27 lib/easy_ml/support/lockable.rb
easy_ml-0.2.0.pre.rc26 lib/easy_ml/support/lockable.rb
easy_ml-0.2.0.pre.rc25 lib/easy_ml/support/lockable.rb
easy_ml-0.2.0.pre.rc24 lib/easy_ml/support/lockable.rb
easy_ml-0.2.0.pre.rc23 lib/easy_ml/support/lockable.rb
easy_ml-0.2.0.pre.rc22 lib/easy_ml/support/lockable.rb
easy_ml-0.2.0.pre.rc21 lib/easy_ml/support/lockable.rb
easy_ml-0.2.0.pre.rc20 lib/easy_ml/support/lockable.rb
easy_ml-0.2.0.pre.rc19 lib/easy_ml/support/lockable.rb
easy_ml-0.2.0.pre.rc18 lib/easy_ml/support/lockable.rb
easy_ml-0.2.0.pre.rc17 lib/easy_ml/support/lockable.rb
easy_ml-0.2.0.pre.rc16 lib/easy_ml/support/lockable.rb
easy_ml-0.2.0.pre.rc15 lib/easy_ml/support/lockable.rb
easy_ml-0.2.0.pre.rc14 lib/easy_ml/support/lockable.rb
easy_ml-0.2.0.pre.rc13 lib/easy_ml/support/lockable.rb
easy_ml-0.2.0.pre.rc12 lib/easy_ml/support/lockable.rb
easy_ml-0.2.0.pre.rc11 lib/easy_ml/support/lockable.rb
easy_ml-0.2.0.pre.rc10 lib/easy_ml/support/lockable.rb
easy_ml-0.2.0.pre.rc9 lib/easy_ml/support/lockable.rb
easy_ml-0.2.0.pre.rc8 lib/easy_ml/support/lockable.rb