github.com/unionj-cloud/go-doudou@v1.3.8-0.20221011095552-0088008e5b31/framework/ratelimit/redisrate/lua.go (about)

     1  package redisrate
     2  
     3  import "github.com/go-redis/redis/v8"
     4  
     5  // Copyright (c) 2017 Pavel Pravosud
     6  // https://github.com/rwz/redis-gcra/blob/master/vendor/perform_gcra_ratelimit.lua
     7  var allowN = redis.NewScript(`
     8  -- this script has side-effects, so it requires replicate commands mode
     9  redis.replicate_commands()
    10  local rate_limit_key = KEYS[1]
    11  local burst = ARGV[1]
    12  local rate = ARGV[2]
    13  local period = ARGV[3]
    14  local cost = tonumber(ARGV[4])
    15  local emission_interval = period / rate
    16  local increment = emission_interval * cost
    17  local burst_offset = emission_interval * burst
    18  -- redis returns time as an array containing two integers: seconds of the epoch
    19  -- time (10 digits) and microseconds (6 digits). for convenience we need to
    20  -- convert them to a floating point number. the resulting number is 16 digits,
    21  -- bordering on the limits of a 64-bit double-precision floating point number.
    22  -- adjust the epoch to be relative to Jan 1, 2017 00:00:00 GMT to avoid floating
    23  -- point problems. this approach is good until "now" is 2,483,228,799 (Wed, 09
    24  -- Sep 2048 01:46:39 GMT), when the adjusted value is 16 digits.
    25  local jan_1_2017 = 1483228800
    26  local now = redis.call("TIME")
    27  now = (now[1] - jan_1_2017) + (now[2] / 1000000)
    28  local tat = redis.call("GET", rate_limit_key)
    29  if not tat then
    30    tat = now
    31  else
    32    tat = tonumber(tat)
    33  end
    34  tat = math.max(tat, now)
    35  local new_tat = tat + increment
    36  local allow_at = new_tat - burst_offset
    37  local diff = now - allow_at
    38  local remaining = diff / emission_interval
    39  if remaining < 0 then
    40    local reset_after = tat - now
    41    local retry_after = diff * -1
    42    return {
    43      0, -- allowed
    44      0, -- remaining
    45      tostring(retry_after),
    46      tostring(reset_after),
    47    }
    48  end
    49  local reset_after = new_tat - now
    50  if reset_after > 0 then
    51    redis.call("SET", rate_limit_key, new_tat, "EX", math.ceil(reset_after))
    52  end
    53  local retry_after = -1
    54  return {cost, remaining, tostring(retry_after), tostring(reset_after)}
    55  `)