0
v-firecrawl/apps/api/src/services/rate-limiter.ts

86 lines
2.2 KiB
TypeScript
Raw Normal View History

2024-04-15 17:01:47 -04:00
import { RateLimiterRedis } from "rate-limiter-flexible";
import * as redis from "redis";
2024-04-20 14:02:22 -07:00
import { RateLimiterMode } from "../../src/types";
2024-04-15 17:01:47 -04:00
const MAX_REQUESTS_PER_MINUTE_PREVIEW = 5;
const MAX_CRAWLS_PER_MINUTE_STARTER = 2;
2024-04-17 05:13:27 +00:00
const MAX_CRAWLS_PER_MINUTE_STANDARD = 4;
2024-04-15 17:01:47 -04:00
const MAX_CRAWLS_PER_MINUTE_SCALE = 20;
2024-04-19 12:23:13 -07:00
const MAX_REQUESTS_PER_MINUTE_ACCOUNT = 20;
2024-04-15 17:01:47 -04:00
2024-04-20 14:02:22 -07:00
const MAX_REQUESTS_PER_MINUTE_CRAWL_STATUS = 120;
2024-04-15 17:01:47 -04:00
export const redisClient = redis.createClient({
url: process.env.REDIS_URL,
legacyMode: true,
});
export const previewRateLimiter = new RateLimiterRedis({
storeClient: redisClient,
keyPrefix: "middleware",
points: MAX_REQUESTS_PER_MINUTE_PREVIEW,
duration: 60, // Duration in seconds
});
export const serverRateLimiter = new RateLimiterRedis({
storeClient: redisClient,
keyPrefix: "middleware",
points: MAX_REQUESTS_PER_MINUTE_ACCOUNT,
duration: 60, // Duration in seconds
});
2024-04-20 14:02:22 -07:00
export const crawlStatusRateLimiter = new RateLimiterRedis({
storeClient: redisClient,
keyPrefix: "middleware",
points: MAX_REQUESTS_PER_MINUTE_CRAWL_STATUS,
duration: 60, // Duration in seconds
});
2024-04-15 17:01:47 -04:00
export function crawlRateLimit(plan: string){
if(plan === "standard"){
return new RateLimiterRedis({
storeClient: redisClient,
keyPrefix: "middleware",
2024-04-17 05:13:27 +00:00
points: MAX_CRAWLS_PER_MINUTE_STANDARD,
2024-04-15 17:01:47 -04:00
duration: 60, // Duration in seconds
});
}else if(plan === "scale"){
return new RateLimiterRedis({
storeClient: redisClient,
keyPrefix: "middleware",
points: MAX_CRAWLS_PER_MINUTE_SCALE,
duration: 60, // Duration in seconds
});
}
return new RateLimiterRedis({
storeClient: redisClient,
keyPrefix: "middleware",
points: MAX_CRAWLS_PER_MINUTE_STARTER,
duration: 60, // Duration in seconds
});
}
2024-04-20 14:02:22 -07:00
2024-05-08 12:18:53 -07:00
export function getRateLimiter(mode: RateLimiterMode, token: string){
// Special test suite case. TODO: Change this later.
if(token.includes("5089cefa58")){
return crawlStatusRateLimiter;
}
2024-04-20 14:10:29 -07:00
switch(mode) {
case RateLimiterMode.Preview:
return previewRateLimiter;
case RateLimiterMode.CrawlStatus:
return crawlStatusRateLimiter;
default:
return serverRateLimiter;
2024-04-15 17:01:47 -04:00
}
}