Class: Petruchio::Ring

Inherits:
Object
  • Object
show all
Defined in:
lib/petruchio.rb

Constant Summary collapse

INIT_LUA_SCRIPT =
<<~LUA
  local key = KEYS[1]
  local size = tonumber(ARGV[1])
  local value = ARGV[2]

  if redis.call('EXISTS', key) == 0 then
    for i=1,size do
      redis.call('RPUSH', key, value)
    end
  end
LUA
RESIZE_LUA_SCRIPT =
<<~LUA
  local key = KEYS[1]
  local size = redis.call("llen", key)
  local new_size = tonumber(ARGV[1])
  local value = ARGV[2]

  if size > new_size then
    redis.call('LTRIM', key, (size - new_size), (size - 1))
  elseif size < new_size then
    for i = 1, (new_size - size) do
      redis.call('RPUSH', key, value)
    end
  end

  return redis.call('LLEN', key)
LUA

Instance Method Summary collapse

Constructor Details

#initialize(redis, ring_name, size, initial_item) ⇒ Ring

Returns a new instance of Ring.



37
38
39
40
41
42
43
# File 'lib/petruchio.rb', line 37

def initialize(redis, ring_name, size, initial_item)
  @redis = redis
  @ring_name = ring_name
  @initial_item = initial_item

  @redis.eval(INIT_LUA_SCRIPT, [@ring_name], [size, @initial_item])
end

Instance Method Details

#popObject



50
51
52
# File 'lib/petruchio.rb', line 50

def pop
  @redis.lpop @ring_name
end

#push(item) ⇒ Object



54
55
56
# File 'lib/petruchio.rb', line 54

def push(item)
  @redis.rpush @ring_name, item
end

#push_pop(item) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/petruchio.rb', line 58

def push_pop(item)
  popped, *rest =
    T.let(
      @redis.multi do |transaction|
        transaction.lpop @ring_name
        transaction.rpush @ring_name, item
      end,
      [String, T.untyped]
    )

  popped
end

#readObject



71
72
73
# File 'lib/petruchio.rb', line 71

def read
  @redis.lrange(@ring_name, 0, -1)
end

#resize(new_size) ⇒ Object



45
46
47
48
# File 'lib/petruchio.rb', line 45

def resize(new_size)
  # returns the new size
  @redis.eval RESIZE_LUA_SCRIPT, [@ring_name], [new_size, @initial_item]
end