Sha256: b500b2b36b9b0533c2deee5b4abc56736ed6a9c1fb14896c9253f30891be7823

Contents?: true

Size: 1017 Bytes

Versions: 48

Compression:

Stored size: 1017 Bytes

Contents

#!/usr/bin/env ruby

require 'securerandom'

module Flapjack
  module Data

    # http://redis.io/commands/set
    class Semaphore

      SEMAPHORE_KEYSPACE = 'semaphores:'

      attr_reader :token, :expiry, :resource

      class ResourceLocked < RuntimeError
      end

      def initialize(resource, options)
        raise "redis connection must be passed in options" unless @redis = options[:redis]
        @resource = resource
        @token    = options[:token]  || SecureRandom.uuid
        @expiry   = options[:expiry] || 30

        @key = "#{SEMAPHORE_KEYSPACE}#{@resource}"

        raise Flapjack::Data::Semaphore::ResourceLocked.new unless @redis.set(@key, @token, {:nx => true, :ex => @expiry})
      end

      def release
        unlock_script = '
         if redis.call("get",KEYS[1]) == ARGV[1]
          then
            return redis.call("del",KEYS[1])
          else
            return 0
          end
        '
        @redis.eval(unlock_script, [@key], [@token])
      end

    end
  end
end

Version data entries

48 entries across 48 versions & 1 rubygems

Version Path
flapjack-1.2.0rc2 lib/flapjack/data/semaphore.rb
flapjack-1.2.0rc1 lib/flapjack/data/semaphore.rb
flapjack-0.9.5 lib/flapjack/data/semaphore.rb
flapjack-0.9.4 lib/flapjack/data/semaphore.rb
flapjack-1.1.0 lib/flapjack/data/semaphore.rb
flapjack-1.0.0 lib/flapjack/data/semaphore.rb
flapjack-1.0.0rc6 lib/flapjack/data/semaphore.rb
flapjack-1.0.0rc5 lib/flapjack/data/semaphore.rb
flapjack-0.9.3 lib/flapjack/data/semaphore.rb
flapjack-1.0.0rc3 lib/flapjack/data/semaphore.rb
flapjack-1.0.0rc2 lib/flapjack/data/semaphore.rb
flapjack-0.9.2 lib/flapjack/data/semaphore.rb
flapjack-0.9.1 lib/flapjack/data/semaphore.rb
flapjack-1.0.0rc1 lib/flapjack/data/semaphore.rb
flapjack-0.9.0 lib/flapjack/data/semaphore.rb
flapjack-0.8.12 lib/flapjack/data/semaphore.rb
flapjack-0.8.11 lib/flapjack/data/semaphore.rb
flapjack-0.8.10 lib/flapjack/data/semaphore.rb
flapjack-0.8.9 lib/flapjack/data/semaphore.rb
flapjack-0.8.8 lib/flapjack/data/semaphore.rb