feat: Add rate limiting across multiple servers via Redis (#8394)

This commit is contained in:
Daniel
2023-03-07 03:43:15 +11:00
committed by GitHub
parent 0f1979f814
commit 34833e42ee
7 changed files with 90 additions and 0 deletions

View File

@@ -11,6 +11,8 @@ import rateLimit from 'express-rate-limit';
import { RateLimitOptions } from './Options/Definitions';
import pathToRegexp from 'path-to-regexp';
import ipRangeCheck from 'ip-range-check';
import RedisStore from 'rate-limit-redis';
import { createClient } from 'redis';
export const DEFAULT_ALLOWED_HEADERS =
'X-Parse-Master-Key, X-Parse-REST-API-Key, X-Parse-Javascript-Key, X-Parse-Application-Id, X-Parse-Client-Version, X-Parse-Session-Token, X-Requested-With, X-Parse-Revocable-Session, X-Parse-Request-Id, Content-Type, Pragma, Cache-Control';
@@ -476,6 +478,35 @@ export const addRateLimit = (route, config) => {
if (!config.rateLimits) {
config.rateLimits = [];
}
const redisStore = {
connectionPromise: Promise.resolve(),
store: null,
connected: false,
};
if (route.redisrUrl) {
const client = createClient({
url: route.redisrUrl,
});
redisStore.connectionPromise = async () => {
if (redisStore.connected) {
return;
}
try {
await client.connect();
redisStore.connected = true;
} catch (e) {
const log = config?.loggerController || defaultLogger;
log.error(`Could not connect to redisURL in rate limit: ${e}`);
}
};
redisStore.connectionPromise();
redisStore.store = new RedisStore({
sendCommand: async (...args) => {
await redisStore.connectionPromise();
return client.sendCommand(args);
},
});
}
config.rateLimits.push({
path: pathToRegexp(route.requestPath),
handler: rateLimit({
@@ -512,6 +543,7 @@ export const addRateLimit = (route, config) => {
keyGenerator: request => {
return request.config.ip;
},
store: redisStore.store,
}),
});
Config.put(config);