|
| 1 | +-- Simple token initialization and management for Python BRPOP |
| 2 | +-- KEYS[1]: tokens_key (LIST of available tokens) |
| 3 | +-- KEYS[2]: holders_key (SET of current holder instance IDs) |
| 4 | +-- KEYS[3]: holder_key (individual holder TTL key for this instance) |
| 5 | +-- ARGV[1]: instance_id |
| 6 | +-- ARGV[2]: capacity (max concurrent holders) |
| 7 | +-- ARGV[3]: ttl_seconds |
| 8 | +-- ARGV[4]: token (the token received from BRPOP) |
| 9 | +-- |
| 10 | +-- Returns: {exit_code, status, current_count} |
| 11 | +-- exit_code: 0 if registered successfully |
| 12 | + |
| 13 | +local tokens_key = KEYS[1] |
| 14 | +local holders_key = KEYS[2] |
| 15 | +local holder_key = KEYS[3] |
| 16 | + |
| 17 | +local instance_id = ARGV[1] |
| 18 | +local capacity = tonumber(ARGV[2]) |
| 19 | +local ttl_seconds = tonumber(ARGV[3]) |
| 20 | +local token = ARGV[4] |
| 21 | + |
| 22 | +-- Step 1: Initialize token pool if needed (first time setup) |
| 23 | +local tokens_exist = redis.call('EXISTS', tokens_key) |
| 24 | +if tokens_exist == 0 then |
| 25 | + -- Initialize with capacity number of tokens |
| 26 | + for i = 1, capacity do |
| 27 | + redis.call('LPUSH', tokens_key, 'token_' .. i) |
| 28 | + end |
| 29 | + -- Set expiry on tokens list to prevent infinite growth |
| 30 | + redis.call('EXPIRE', tokens_key, ttl_seconds * 10) |
| 31 | +end |
| 32 | + |
| 33 | +-- Step 2: Register as holder (token was already popped by Python BRPOP) |
| 34 | +redis.call('SADD', holders_key, instance_id) |
| 35 | +redis.call('SETEX', holder_key, ttl_seconds, token) |
| 36 | + |
| 37 | +-- Step 3: Set expiry on holders set to prevent infinite growth |
| 38 | +redis.call('EXPIRE', holders_key, ttl_seconds * 10) |
| 39 | + |
| 40 | +local current_count = redis.call('SCARD', holders_key) |
| 41 | + |
| 42 | +return {0, 'registered', current_count} |
0 commit comments