Files
firecrawl/apps/api/src/services/rate-limiter.ts
T

101 lines
2.0 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
2024-05-30 14:31:36 -07:00
const RATE_LIMITS = {
crawl: {
2024-06-06 11:23:10 -07:00
default: 3,
2024-06-05 14:38:10 -07:00
free: 2,
2024-05-30 14:31:36 -07:00
starter: 3,
standard: 5,
2024-06-06 09:29:25 -07:00
standardOld: 40,
2024-05-30 14:31:36 -07:00
scale: 20,
hobby: 3,
standardNew: 10,
growth: 50,
},
scrape: {
2024-06-06 11:23:10 -07:00
default: 20,
2024-05-30 14:31:36 -07:00
free: 5,
starter: 20,
2024-06-06 09:31:44 -07:00
standard: 50,
2024-05-30 14:31:36 -07:00
standardOld: 40,
scale: 50,
hobby: 10,
standardNew: 50,
growth: 500,
},
search: {
2024-06-06 11:23:10 -07:00
default: 20,
2024-05-30 14:31:36 -07:00
free: 5,
starter: 20,
standard: 40,
2024-06-06 09:29:25 -07:00
standardOld: 40,
2024-05-30 14:31:36 -07:00
scale: 50,
hobby: 10,
standardNew: 50,
growth: 500,
},
2024-06-06 11:23:10 -07:00
preview: {
default: 5,
},
account: {
default: 20,
},
crawlStatus: {
default: 150,
},
testSuite: {
default: 10000,
},
2024-05-30 14:31:36 -07:00
};
2024-04-20 14:02:22 -07:00
2024-04-15 17:01:47 -04:00
export const redisClient = redis.createClient({
url: process.env.REDIS_URL,
legacyMode: true,
});
2024-06-06 11:23:10 -07:00
const createRateLimiter = (keyPrefix, points) =>
new RateLimiterRedis({
storeClient: redisClient,
keyPrefix,
points,
duration: 60, // Duration in seconds
});
2024-04-15 17:01:47 -04:00
2024-06-06 11:23:10 -07:00
export const previewRateLimiter = createRateLimiter(
"preview",
RATE_LIMITS.preview
);
export const serverRateLimiter = createRateLimiter(
"server",
RATE_LIMITS.account
);
export const crawlStatusRateLimiter = createRateLimiter(
"crawl-status",
RATE_LIMITS.crawlStatus
);
export const testSuiteRateLimiter = createRateLimiter(
"test-suite",
RATE_LIMITS.testSuite
);
2024-04-15 17:01:47 -04:00
2024-06-06 11:23:10 -07:00
export function getRateLimiter(
mode: RateLimiterMode,
token: string,
plan?: string
) {
2024-06-04 11:05:50 -03:00
if (token.includes("a01ccae") || token.includes("6254cf9")) {
2024-05-30 14:31:36 -07:00
return testSuiteRateLimiter;
}
2024-04-20 14:02:22 -07:00
2024-06-06 11:23:10 -07:00
const rateLimitConfig = RATE_LIMITS[mode]; // {default : 5}
2024-05-30 14:31:36 -07:00
if (!rateLimitConfig) return serverRateLimiter;
2024-05-08 15:14:39 -07:00
2024-06-06 11:23:10 -07:00
const planKey = plan ? plan.replace("-", "") : "default"; // "default"
const points =
rateLimitConfig[planKey] || rateLimitConfig.default || rateLimitConfig; // 5
2024-04-15 17:01:47 -04:00
2024-05-30 14:31:36 -07:00
return createRateLimiter(`${mode}-${planKey}`, points);
2024-04-15 17:01:47 -04:00
}