lua script and rate limit process
This commit is contained in:
parent
5fca005a3f
commit
c059f44bf1
@ -37,25 +37,35 @@ const ENDPOINT_KEY_REDIS = 'rate-limit:store:';
|
||||
const USER_KEY_REDIS = 'rate-limit:status:';
|
||||
|
||||
|
||||
module.exports = function rateLimitMiddleware (metadataBackend) {
|
||||
module.exports = function rateLimitMiddleware(metadataBackend) {
|
||||
return function rateLimit(req, res, next) {
|
||||
|
||||
|
||||
const user = 'cdb';
|
||||
// const user = res.locals.user;
|
||||
const endpointGroup = getEndpointGroup();
|
||||
|
||||
const redisParams = [
|
||||
getLuaScript(),
|
||||
3,
|
||||
2,
|
||||
getStoreKey(user, endpointGroup), // KEY[1]
|
||||
getStatusKey(user, endpointGroup) // KEY[2]
|
||||
];
|
||||
|
||||
metadataBackend.redisCmd(REDIS_DB, 'EVAL', redisParams, function(err, {isBloqued, limit, remaining, retry, reset}) {
|
||||
metadataBackend.redisCmd(REDIS_DB, 'EVAL', redisParams, function(err, data) {
|
||||
if (err) {
|
||||
return next(err);
|
||||
}
|
||||
|
||||
|
||||
if (!data || !Array.isArray(data)) {
|
||||
return next();
|
||||
}
|
||||
|
||||
const isBloqued = data[0];
|
||||
const limit = data[1];
|
||||
const remaining = data[2];
|
||||
const retry = data[3];
|
||||
const reset = data[4];
|
||||
|
||||
res.set({
|
||||
'X-Rate-Limit-Limit': limit,
|
||||
'X-Rate-Limit-Remaining': remaining,
|
||||
@ -63,13 +73,13 @@ module.exports = function rateLimitMiddleware (metadataBackend) {
|
||||
'X-Rate-Limit-Reset': reset
|
||||
});
|
||||
|
||||
if(isBloqued) {
|
||||
if (isBloqued) {
|
||||
const err = new Error('You are over the limits.');
|
||||
err.http_status = 429;
|
||||
return next(err);
|
||||
}
|
||||
|
||||
next();
|
||||
|
||||
return next();
|
||||
});
|
||||
};
|
||||
};
|
||||
@ -85,7 +95,7 @@ function getEndpointGroup(currentEndpoint = null) {
|
||||
return ENDPOINTS_GROUPS_REDIS.ENDPOINT_8;
|
||||
} else {
|
||||
// get endpoint from route path
|
||||
return ENDPOINTS_GROUPS_REDIS.ENDPOINT_8;
|
||||
return ENDPOINTS_GROUPS_REDIS.ENDPOINT_8;
|
||||
}
|
||||
}
|
||||
|
||||
@ -109,8 +119,17 @@ function getStatusKey(user, endpointGroup) {
|
||||
}
|
||||
|
||||
function getLuaScript() {
|
||||
return `
|
||||
local userValues = redis.call("HGETALL", KEYS[1])
|
||||
return redis.call("CL.THROTTLE", KEYS[2], userValues[b], userValues[c], userValues[p])
|
||||
return `
|
||||
local limmits = {}
|
||||
local limmitsArray = redis.call("HGETALL", KEYS[1])
|
||||
if table.getn(limmitsArray) == 4 then
|
||||
limmits[limmitsArray[1]] = limmitsArray[2]
|
||||
limmits[limmitsArray[3]] = limmitsArray[4]
|
||||
limmits[limmitsArray[5]] = limmitsArray[6]
|
||||
|
||||
return redis.call("CL.THROTTLE", KEYS[2], limmits['b'], limmits['c'], limmits['p'])
|
||||
else
|
||||
return nil
|
||||
end
|
||||
`;
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user