Sha256: 0dddb3cc52a48c1a22f65e016bfc9cb3eaf904d70c6ed3d39fc4faffabce9d8a

Contents?: true

Size: 1.57 KB

Versions: 14

Compression:

Stored size: 1.57 KB

Contents

module WorkerRoulette
  class Lua
    Thread.main[:worker_roulette_lua_script_cache] = Hash.new

    def initialize(connection_pool)
      @connection_pool = connection_pool
    end

    def call(lua_script, keys_accessed = [], args = [], &callback)
      @connection_pool.with do |redis|
        evalsha(redis, lua_script, keys_accessed, args, &callback)
      end
    end

    def sha(lua_script)
      Thread.main[:worker_roulette_lua_script_cache][lua_script] ||= Digest::SHA1.hexdigest(lua_script)
    end

    def cache
      Thread.main[:worker_roulette_lua_script_cache].dup
    end

    def clear_cache!
      Thread.main[:worker_roulette_lua_script_cache] = {}
    end

    def eval(redis, lua_script, keys_accessed, args, &callback)
      results = redis.eval(lua_script, keys_accessed.length, *keys_accessed, *args)
      results.callback(&callback) if callback
      results.errback  {|err_msg| raise EM::Hiredis::RedisError.new(err_msg)}
    end

    def evalsha(redis, lua_script, keys_accessed, args, &callback)
      if redis.class == EM::Hiredis::Client
        results = redis.evalsha(sha(lua_script), keys_accessed.length, *keys_accessed, *args)
        results.callback(&callback) if callback
        results.errback {eval(redis, lua_script, keys_accessed, args, &callback)}
      else
        begin
          results = redis.evalsha(sha(lua_script), keys_accessed, args)
        rescue Redis::CommandError
          results = redis.eval(lua_script, keys_accessed, args)
        ensure
          return callback.call results if callback
        end
      end
      results
    end
  end
end

Version data entries

14 entries across 14 versions & 2 rubygems

Version Path
nexia_worker_roulette-0.2.9 lib/worker_roulette/lua.rb
nexia_worker_roulette-0.2.8 lib/worker_roulette/lua.rb
nexia_worker_roulette-0.2.7 lib/worker_roulette/lua.rb
nexia_worker_roulette-0.2.6 lib/worker_roulette/lua.rb
nexia_worker_roulette-0.2.5 lib/worker_roulette/lua.rb
nexia_worker_roulette-0.2.4 lib/worker_roulette/lua.rb
nexia_worker_roulette-0.2.3 lib/worker_roulette/lua.rb
nexia_worker_roulette-0.2.2 lib/worker_roulette/lua.rb
nexia_worker_roulette-0.2.1 lib/worker_roulette/lua.rb
nexia_worker_roulette-0.2.0 lib/worker_roulette/lua.rb
worker_roulette-0.1.13 lib/worker_roulette/lua.rb
worker_roulette-0.1.12 lib/worker_roulette/lua.rb
nexia_worker_roulette-0.1.12 lib/worker_roulette/lua.rb
nexia_worker_roulette-0.1.11 lib/worker_roulette/lua.rb