local consumers = redis.call("zrangebyscore", KEYS[1], 0, ARGV[1], "LIMIT", 0, ARGV[2])
redis.replicate_commands()
local limit = tonumber(ARGV[2])
for _,consumer in ipairs(consumers) do
local jobs = redis.call("spop", consumer, limit)
local count = table.getn(jobs)
if count > 0 then
redis.call("rpush", KEYS[2], unpack(jobs))
end
if count < limit then
redis.call("zrem", KEYS[1], consumer)
end
limit = limit - count
if limit <= 0 then
break
end
end
local processed = tonumber(ARGV[2]) - limit
if processed > 0 then
redis.call("del", KEYS[3])
redis.call("lpush", KEYS[3], 1)
end
return processed