import type { Duration } from "./duration"; import { ms } from "./duration"; import { safeEval } from "./hash"; import { RESET_SCRIPT, SCRIPTS } from "./lua-scripts/hash"; import { tokenBucketIdentifierNotFound } from "./lua-scripts/single"; import { DEFAULT_PREFIX, DYNAMIC_LIMIT_KEY_SUFFIX } from "./constants"; import { Ratelimit } from "./ratelimit"; import { addTelemetry } from "./telemetry"; import type { Algorithm, RegionContext } from "./types"; import type { Redis as RedisCore } from "./types"; // Fix for https://github.com/upstash/ratelimit-js/issues/125 type Redis = Pick export type RegionRatelimitConfig = { /** * Instance of `@upstash/redis` * @see https://github.com/upstash/upstash-redis#quick-start */ redis: Redis; /** * The ratelimiter function to use. * * Choose one of the predefined ones or implement your own. * Available algorithms are exposed via static methods: * - Ratelimiter.fixedWindow * - Ratelimiter.slidingWindow * - Ratelimiter.tokenBucket */ limiter: Algorithm; /** * All keys in redis are prefixed with this. * * @default `@upstash/ratelimit` */ prefix?: string; /** * If enabled, the ratelimiter will keep a global cache of identifiers, that have * exhausted their ratelimit. In serverless environments this is only possible if * you create the ratelimiter instance outside of your handler function. While the * function is still hot, the ratelimiter can block requests without having to * request data from redis, thus saving time and money. * * Whenever an identifier has exceeded its limit, the ratelimiter will add it to an * internal list together with its reset timestamp. If the same identifier makes a * new request before it is reset, we can immediately reject it. * * Set to `false` to disable. * * If left undefined, a map is created automatically, but it can only work * if the map or the ratelimit instance is created outside your serverless function handler. */ ephemeralCache?: Map | false; /** * If set, the ratelimiter will allow requests to pass after this many milliseconds. * * Use this if you want to allow requests in case of network problems */ timeout?: number; /** * If enabled, the ratelimiter will store analytics data in redis, which you can check out at * https://console.upstash.com/ratelimit * * @default false */ analytics?: boolean; /** * @deprecated Has no affect since v2.0.3. Instead, hash values of scripts are * hardcoded in the sdk and it attempts to run the script using EVALSHA (with the hash). * If it fails, runs script load. * * Previously, if enabled, lua scripts were sent to Redis with SCRIPT LOAD durint the first request. * In the subsequent requests, hash of the script would be used to invoke the scripts * * @default true */ cacheScripts?: boolean; /** * @default false */ enableProtection?: boolean /** * @default 6 */ denyListThreshold?: number /** * If enabled, the ratelimiter will check for dynamic limits in Redis * before applying the regular limit. This allows you to change the rate * limit at runtime using setDynamicLimit(). * * When enabled, adds +1 Redis command (GET) to every limit check. * * @default false */ dynamicLimits?: boolean; /** * Enable telemetry to help us improve the SDK. * * The sdk name and version are sent to Upstash as a header on the requests * made by the redis client you provide. * * Can also be disabled with the `UPSTASH_DISABLE_TELEMETRY` env variable. * * @default true */ enableTelemetry?: boolean; }; /** * Ratelimiter using serverless redis from https://upstash.com/ * * @example * ```ts * const { limit } = new Ratelimit({ * redis: Redis.fromEnv(), * limiter: Ratelimit.slidingWindow( * "30 m", // interval of 30 minutes * 10, // Allow 10 requests per window of 30 minutes * ) * }) * * ``` * * @see node_modules/@upstash/ratelimit/docs/gettingstarted.mdx */ export class RegionRatelimit extends Ratelimit { /** * Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithm of your choice. * * @see node_modules/@upstash/ratelimit/docs/gettingstarted.mdx */ constructor(config: RegionRatelimitConfig) { super({ prefix: config.prefix, limiter: config.limiter, timeout: config.timeout, analytics: config.analytics, ctx: { redis: config.redis as RedisCore, prefix: config.prefix ?? DEFAULT_PREFIX, }, ephemeralCache: config.ephemeralCache, enableProtection: config.enableProtection, denyListThreshold: config.denyListThreshold, dynamicLimits: config.dynamicLimits }); addTelemetry(config.redis, config.enableTelemetry); } /** * Each request inside a fixed time increases a counter. * Once the counter reaches the maximum allowed number, all further requests are * rejected. * * **Pro:** * * - Newer requests are not starved by old ones. * - Low storage cost. * * **Con:** * * A burst of requests near the boundary of a window can result in a very * high request rate because two windows will be filled with requests quickly. * * @param tokens - How many requests a user can make in each time window. * @param window - A fixed timeframe * @see node_modules/@upstash/ratelimit/docs/algorithms.mdx */ static fixedWindow( /** * How many requests are allowed per window. */ tokens: number, /** * The duration in which `tokens` requests are allowed. */ window: Duration, ): Algorithm { const windowDuration = ms(window); return () => ({ async limit(ctx: RegionContext, identifier: string, rate?: number) { const bucket = Math.floor(Date.now() / windowDuration); const key = [identifier, bucket].join(":"); const incrementBy = rate ?? 1; // Only check cache block if not refunding (negative rate) if (ctx.cache && incrementBy > 0) { const { blocked, reset } = ctx.cache.isBlocked(identifier); if (blocked) { return { success: false, limit: tokens, remaining: 0, reset: reset, pending: Promise.resolve(), reason: "cacheBlock" }; } } // Only declare the dynamic limit key when used; every declared key is locked. const dynamicLimitKeys = ctx.dynamicLimits ? [`${ctx.prefix}${DYNAMIC_LIMIT_KEY_SUFFIX}`] : []; const [usedTokensAfterUpdate, effectiveLimit] = await safeEval( ctx, SCRIPTS.singleRegion.fixedWindow.limit, [key, ...dynamicLimitKeys], [tokens, windowDuration, incrementBy], ) as [number, number]; const success = usedTokensAfterUpdate <= effectiveLimit; const remainingTokens = Math.max(0, effectiveLimit - usedTokensAfterUpdate); const reset = (bucket + 1) * windowDuration; if (ctx.cache) { if (!success) { ctx.cache.blockUntil(identifier, reset); } else if (incrementBy < 0) { // Successful refund: unblock from cache ctx.cache.pop(identifier); } } return { success, limit: effectiveLimit, remaining: remainingTokens, reset, pending: Promise.resolve(), }; }, async getRemaining(ctx: RegionContext, identifier: string) { const bucket = Math.floor(Date.now() / windowDuration); const key = [identifier, bucket].join(":"); // Only declare the dynamic limit key when used; every declared key is locked. const dynamicLimitKeys = ctx.dynamicLimits ? [`${ctx.prefix}${DYNAMIC_LIMIT_KEY_SUFFIX}`] : []; const [remaining, effectiveLimit] = await safeEval( ctx, SCRIPTS.singleRegion.fixedWindow.getRemaining, [key, ...dynamicLimitKeys], [tokens], ) as [number, number]; return { remaining: Math.max(0, remaining), reset: (bucket + 1) * windowDuration, limit: effectiveLimit }; }, async resetTokens(ctx: RegionContext, identifier: string) { const pattern = [identifier, "*"].join(":"); if (ctx.cache) { ctx.cache.pop(identifier) } await safeEval( ctx, RESET_SCRIPT, [pattern], [null], ) as number; }, }); } /** * Combined approach of `slidingLogs` and `fixedWindow` with lower storage * costs than `slidingLogs` and improved boundary behavior by calculating a * weighted score between two windows. * * **Pro:** * * Good performance allows this to scale to very high loads. * * **Con:** * * Nothing major. * * @param tokens - How many requests a user can make in each time window. * @param window - The duration in which the user can max X requests. * @see node_modules/@upstash/ratelimit/docs/algorithms.mdx */ static slidingWindow( /** * How many requests are allowed per window. */ tokens: number, /** * The duration in which `tokens` requests are allowed. */ window: Duration, ): Algorithm { const windowSize = ms(window); return () => ({ async limit(ctx: RegionContext, identifier: string, rate?: number) { const now = Date.now(); const currentWindow = Math.floor(now / windowSize); const currentKey = [identifier, currentWindow].join(":"); const previousWindow = currentWindow - 1; const previousKey = [identifier, previousWindow].join(":"); const incrementBy = rate ?? 1; // Only check cache block if not refunding (negative rate) if (ctx.cache && incrementBy > 0) { const { blocked, reset } = ctx.cache.isBlocked(identifier); if (blocked) { return { success: false, limit: tokens, remaining: 0, reset: reset, pending: Promise.resolve(), reason: "cacheBlock" }; } } // Only declare the dynamic limit key when used; every declared key is locked. const dynamicLimitKeys = ctx.dynamicLimits ? [`${ctx.prefix}${DYNAMIC_LIMIT_KEY_SUFFIX}`] : []; const [remainingTokens, effectiveLimit] = await safeEval( ctx, SCRIPTS.singleRegion.slidingWindow.limit, [currentKey, previousKey, ...dynamicLimitKeys], [tokens, now, windowSize, incrementBy], ) as [number, number]; const success = remainingTokens >= 0; const reset = (currentWindow + 1) * windowSize; if (ctx.cache) { if (!success) { ctx.cache.blockUntil(identifier, reset); } else if (incrementBy < 0) { // Successful refund: unblock from cache ctx.cache.pop(identifier); } } return { success, limit: effectiveLimit, remaining: Math.max(0, remainingTokens), reset, pending: Promise.resolve(), }; }, async getRemaining(ctx: RegionContext, identifier: string) { const now = Date.now(); const currentWindow = Math.floor(now / windowSize); const currentKey = [identifier, currentWindow].join(":"); const previousWindow = currentWindow - 1; const previousKey = [identifier, previousWindow].join(":"); // Only declare the dynamic limit key when used; every declared key is locked. const dynamicLimitKeys = ctx.dynamicLimits ? [`${ctx.prefix}${DYNAMIC_LIMIT_KEY_SUFFIX}`] : []; const [remaining, effectiveLimit] = await safeEval( ctx, SCRIPTS.singleRegion.slidingWindow.getRemaining, [currentKey, previousKey, ...dynamicLimitKeys], [tokens, now, windowSize], ) as [number, number]; return { remaining: Math.max(0, remaining), reset: (currentWindow + 1) * windowSize, limit: effectiveLimit } }, async resetTokens(ctx: RegionContext, identifier: string) { const pattern = [identifier, "*"].join(":"); if (ctx.cache) { ctx.cache.pop(identifier) } await safeEval( ctx, RESET_SCRIPT, [pattern], [null], ) as number; }, }); } /** * You have a bucket filled with `{maxTokens}` tokens that refills constantly * at `{refillRate}` per `{interval}`. * Every request will remove one token from the bucket and if there is no * token to take, the request is rejected. * * **Pro:** * * - Bursts of requests are smoothed out and you can process them at a constant * rate. * - Allows to set a higher initial burst limit by setting `maxTokens` higher * than `refillRate` * * @see node_modules/@upstash/ratelimit/docs/algorithms.mdx */ static tokenBucket( /** * How many tokens are refilled per `interval` * * An interval of `10s` and refillRate of 5 will cause a new token to be added every 2 seconds. */ refillRate: number, /** * The interval for the `refillRate` */ interval: Duration, /** * Maximum number of tokens. * A newly created bucket starts with this many tokens. * Useful to allow higher burst limits. */ maxTokens: number, ): Algorithm { const intervalDuration = ms(interval); return () => ({ async limit(ctx: RegionContext, identifier: string, rate?: number) { const now = Date.now(); const incrementBy = rate ?? 1; // Only check cache block if not refunding (negative rate) if (ctx.cache && incrementBy > 0) { const { blocked, reset } = ctx.cache.isBlocked(identifier); if (blocked) { return { success: false, limit: maxTokens, remaining: 0, reset: reset, pending: Promise.resolve(), reason: "cacheBlock" }; } } // Only declare the dynamic limit key when used; every declared key is locked. const dynamicLimitKeys = ctx.dynamicLimits ? [`${ctx.prefix}${DYNAMIC_LIMIT_KEY_SUFFIX}`] : []; const [remaining, reset, effectiveLimit] = await safeEval( ctx, SCRIPTS.singleRegion.tokenBucket.limit, [identifier, ...dynamicLimitKeys], [maxTokens, intervalDuration, refillRate, now, incrementBy], ) as [number, number, number]; const success = remaining >= 0; if (ctx.cache) { if (!success) { ctx.cache.blockUntil(identifier, reset); } else if (incrementBy < 0) { // Successful refund: unblock from cache ctx.cache.pop(identifier); } } return { success, limit: effectiveLimit, remaining: Math.max(0, remaining), reset, pending: Promise.resolve(), }; }, async getRemaining(ctx: RegionContext, identifier: string) { // Only declare the dynamic limit key when used; every declared key is locked. const dynamicLimitKeys = ctx.dynamicLimits ? [`${ctx.prefix}${DYNAMIC_LIMIT_KEY_SUFFIX}`] : []; const [remainingTokens, refilledAt, effectiveLimit] = await safeEval( ctx, SCRIPTS.singleRegion.tokenBucket.getRemaining, [identifier, ...dynamicLimitKeys], [maxTokens], ) as [number, number, number]; const freshRefillAt = Date.now() + intervalDuration const identifierRefillsAt = refilledAt + intervalDuration return { remaining: Math.max(0, remainingTokens), reset: refilledAt === tokenBucketIdentifierNotFound ? freshRefillAt : identifierRefillsAt, limit: effectiveLimit }; }, async resetTokens(ctx: RegionContext, identifier: string) { const pattern = identifier; if (ctx.cache) { ctx.cache.pop(identifier) } await safeEval( ctx, RESET_SCRIPT, [pattern], [null], ) as number; }, }); } /** * cachedFixedWindow first uses the local cache to decide if a request may pass and then updates * it asynchronously. * This is experimental and not yet recommended for production use. * * @experimental * * Each request inside a fixed time increases a counter. * Once the counter reaches the maximum allowed number, all further requests are * rejected. * * **Pro:** * * - Newer requests are not starved by old ones. * - Low storage cost. * * **Con:** * * A burst of requests near the boundary of a window can result in a very * high request rate because two windows will be filled with requests quickly. * * @param tokens - How many requests a user can make in each time window. * @param window - A fixed timeframe * @see node_modules/@upstash/ratelimit/docs/algorithms.mdx */ static cachedFixedWindow( /** * How many requests are allowed per window. */ tokens: number, /** * The duration in which `tokens` requests are allowed. */ window: Duration, ): Algorithm { const windowDuration = ms(window); return () => ({ async limit(ctx: RegionContext, identifier: string, rate?: number) { if (!ctx.cache) { throw new Error("This algorithm requires a cache"); } if (ctx.dynamicLimits) { console.warn( "Warning: Dynamic limits are not yet supported for cachedFixedWindow algorithm. " + "The dynamicLimits option will be ignored." ); } const bucket = Math.floor(Date.now() / windowDuration); const key = [identifier, bucket].join(":"); const reset = (bucket + 1) * windowDuration; const incrementBy = rate ?? 1; const hit = typeof ctx.cache.get(key) === "number"; if (hit) { const cachedTokensAfterUpdate = ctx.cache.incr(key, incrementBy); // used == tokens still succeeds, matching the cache-miss path below const success = cachedTokensAfterUpdate <= tokens; const pending = success ? safeEval( ctx, SCRIPTS.singleRegion.cachedFixedWindow.limit, [key], [windowDuration, incrementBy] ) : Promise.resolve(); return { success, limit: tokens, remaining: tokens - cachedTokensAfterUpdate, reset: reset, pending, }; } const usedTokensAfterUpdate = await safeEval( ctx, SCRIPTS.singleRegion.cachedFixedWindow.limit, [key], [windowDuration, incrementBy] ) as number; ctx.cache.set(key, usedTokensAfterUpdate); const remaining = tokens - usedTokensAfterUpdate; return { success: remaining >= 0, limit: tokens, remaining, reset: reset, pending: Promise.resolve(), }; }, async getRemaining(ctx: RegionContext, identifier: string) { if (!ctx.cache) { throw new Error("This algorithm requires a cache"); } const bucket = Math.floor(Date.now() / windowDuration); const key = [identifier, bucket].join(":"); const hit = typeof ctx.cache.get(key) === "number"; if (hit) { const cachedUsedTokens = ctx.cache.get(key) ?? 0; return { remaining: Math.max(0, tokens - cachedUsedTokens), reset: (bucket + 1) * windowDuration, limit: tokens }; } const usedTokens = await safeEval( ctx, SCRIPTS.singleRegion.cachedFixedWindow.getRemaining, [key], [null], ) as number; return { remaining: Math.max(0, tokens - usedTokens), reset: (bucket + 1) * windowDuration, limit: tokens }; }, async resetTokens(ctx: RegionContext, identifier: string) { // Empty the cache if (!ctx.cache) { throw new Error("This algorithm requires a cache"); } const bucket = Math.floor(Date.now() / windowDuration); const key = [identifier, bucket].join(":"); ctx.cache.pop(key) const pattern = [identifier, "*"].join(":"); await safeEval( ctx, RESET_SCRIPT, [pattern], [null], ) as number; }, }); } }