-
-
Save tpasipanodya/e7cbe9d3cd8903022dad3e2d197ed612 to your computer and use it in GitHub Desktop.
The Lua Script to Reserve a Job
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
redis.replicate_commands() | |
local queue = ARGV[1] | |
-- randomly select a tenant | |
local runnable_tenants = queue .. '_runnable_tenants' | |
local tenant_id = redis.call('SRANDMEMBER', runnable_tenants) | |
-- get their next pending job | |
local pending_jobs = queue .. '_pending_jobs:' .. tenant_id | |
local job_id = redis.call('RPOP', pending_jobs) | |
-- update all other structures to be in the running state | |
local running_jobs = queue .. '_running_jobs:' .. tenant_id | |
redis.call('SADD', running_jobs, job_id) | |
-- If reserving this job brings a tenant above the limit, they become un-runnable | |
local runing_jobs_count = redis.call('SCARD', running_jobs) | |
local limit = tonumber(redis.call('HGET', 'tenant_limits', queue)) | |
if (runing_jobs_count >= limit) then | |
local runnable_tenants = queue .. '_runnable_tenants' | |
redis.call('SREM', runnable_tenants, tenant_id) | |
end | |
return {job_id, tenant_id} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment