@upstash/ratelimit 1.0.1-canary → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -352
- package/dist/index.d.mts +24 -3
- package/dist/index.d.ts +24 -3
- package/dist/index.js +284 -177
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +284 -177
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/analytics.ts","../src/cache.ts","../src/duration.ts","../src/ratelimit.ts","../src/multi.ts","../src/single.ts"],"sourcesContent":["import { Analytics as CoreAnalytics } from \"@upstash/core-analytics\";\nimport type { Redis } from \"./types\";\n\nexport type Geo = {\n country?: string;\n city?: string;\n region?: string;\n ip?: string;\n};\nexport type Event = Geo & {\n identifier: string;\n time: number;\n success: boolean;\n};\n\nexport type AnalyticsConfig = {\n redis: Redis;\n prefix?: string;\n};\n\n/**\n * The Analytics package is experimental and can change at any time.\n */\nexport class Analytics {\n private readonly analytics: CoreAnalytics;\n private readonly table = \"events\";\n\n constructor(config: AnalyticsConfig) {\n this.analytics = new CoreAnalytics({\n // @ts-expect-error we need to fix the types in core-analytics, it should only require the methods it needs, not the whole sdk\n redis: config.redis,\n window: \"1h\",\n prefix: config.prefix ?? \"@upstash/ratelimit\",\n retention: \"90d\",\n });\n }\n\n /**\n * Try to extract the geo information from the request\n *\n * This handles Vercel's `req.geo` and and Cloudflare's `request.cf` properties\n * @param req\n * @returns\n */\n public extractGeo(req: { geo?: Geo; cf?: Geo }): Geo {\n if (typeof req.geo !== \"undefined\") {\n return req.geo;\n }\n if (typeof req.cf !== \"undefined\") {\n return req.cf;\n }\n\n return {};\n }\n\n public async record(event: Event): Promise<void> {\n await this.analytics.ingest(this.table, event);\n }\n\n async series<TFilter extends keyof Omit<Event, \"time\">>(\n filter: TFilter,\n cutoff: number,\n ): Promise<({ time: number } & Record<string, number>)[]> {\n const records = await this.analytics.query(this.table, {\n filter: [filter],\n range: [cutoff, Date.now()],\n });\n return records;\n }\n public async getUsage(cutoff = 0): Promise<Record<string, { success: number; blocked: number }>> {\n const records = await this.analytics.aggregateBy(this.table, \"identifier\", {\n range: [cutoff, Date.now()],\n });\n const usage = {} as Record<string, { success: number; blocked: number }>;\n for (const bucket of records) {\n for (const [k, v] of Object.entries(bucket)) {\n if (k === \"time\") {\n continue;\n }\n\n if (!usage[k]) {\n usage[k] = { success: 0, blocked: 0 };\n }\n // @ts-ignore\n usage[k].success += v.true ?? 0;\n // @ts-ignore\n usage[k].blocked += v.false ?? 0;\n }\n }\n return usage;\n }\n}\n","import { EphemeralCache } from \"./types\";\n\nexport class Cache implements EphemeralCache {\n /**\n * Stores identifier -> reset (in milliseconds)\n */\n private readonly cache: Map<string, number>;\n\n constructor(cache: Map<string, number>) {\n this.cache = cache;\n }\n\n public isBlocked(identifier: string): { blocked: boolean; reset: number } {\n if (!this.cache.has(identifier)) {\n return { blocked: false, reset: 0 };\n }\n const reset = this.cache.get(identifier)!;\n if (reset < Date.now()) {\n this.cache.delete(identifier);\n return { blocked: false, reset: 0 };\n }\n\n return { blocked: true, reset: reset };\n }\n\n public blockUntil(identifier: string, reset: number): void {\n this.cache.set(identifier, reset);\n }\n\n public set(key: string, value: number): void {\n this.cache.set(key, value);\n }\n public get(key: string): number | null {\n return this.cache.get(key) || null;\n }\n\n public incr(key: string): number {\n let value = this.cache.get(key) ?? 0;\n value += 1;\n this.cache.set(key, value);\n return value;\n }\n}\n","type Unit = \"ms\" | \"s\" | \"m\" | \"h\" | \"d\";\nexport type Duration = `${number} ${Unit}` | `${number}${Unit}`;\n\n/**\n * Convert a human readable duration to milliseconds\n */\nexport function ms(d: Duration): number {\n const match = d.match(/^(\\d+)\\s?(ms|s|m|h|d)$/);\n if (!match) {\n throw new Error(`Unable to parse window size: ${d}`);\n }\n const time = parseInt(match[1]);\n const unit = match[2] as Unit;\n\n switch (unit) {\n case \"ms\":\n return time;\n case \"s\":\n return time * 1000;\n case \"m\":\n return time * 1000 * 60;\n case \"h\":\n return time * 1000 * 60 * 60;\n case \"d\":\n return time * 1000 * 60 * 60 * 24;\n\n default:\n throw new Error(`Unable to parse window size: ${d}`);\n }\n}\n","import { Analytics, Geo } from \"./analytics\";\nimport { Cache } from \"./cache\";\nimport type { Algorithm, Context, RatelimitResponse } from \"./types\";\n\nexport class TimeoutError extends Error {\n constructor() {\n super(\"Timeout\");\n this.name = \"TimeoutError\";\n }\n}\nexport type RatelimitConfig<TContext> = {\n /**\n * The ratelimiter function to use.\n *\n * Choose one of the predefined ones or implement your own.\n * Available algorithms are exposed via static methods:\n * - Ratelimiter.fixedWindow\n * - Ratelimiter.slidingWindow\n * - Ratelimiter.tokenBucket\n */\n\n limiter: Algorithm<TContext>;\n\n ctx: TContext;\n /**\n * All keys in redis are prefixed with this.\n *\n * @default `@upstash/ratelimit`\n */\n prefix?: string;\n\n /**\n * If enabled, the ratelimiter will keep a global cache of identifiers, that have\n * exhausted their ratelimit. In serverless environments this is only possible if\n * you create the ratelimiter instance outside of your handler function. While the\n * function is still hot, the ratelimiter can block requests without having to\n * request data from redis, thus saving time and money.\n *\n * Whenever an identifier has exceeded its limit, the ratelimiter will add it to an\n * internal list together with its reset timestamp. If the same identifier makes a\n * new request before it is reset, we can immediately reject it.\n *\n * Set to `false` to disable.\n *\n * If left undefined, a map is created automatically, but it can only work\n * if the map or the ratelimit instance is created outside your serverless function handler.\n */\n ephemeralCache?: Map<string, number> | false;\n\n /**\n * If set, the ratelimiter will allow requests to pass after this many milliseconds.\n *\n * Use this if you want to allow requests in case of network problems\n *\n * @default 5000\n */\n timeout?: number;\n\n /**\n * If enabled, the ratelimiter will store analytics data in redis, which you can check out at\n * https://console.upstash.com/ratelimit\n *\n * @default false\n */\n analytics?: boolean;\n};\n\n/**\n * Ratelimiter using serverless redis from https://upstash.com/\n *\n * @example\n * ```ts\n * const { limit } = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(\n * 10, // Allow 10 requests per window of 30 minutes\n * \"30 m\", // interval of 30 minutes\n * ),\n * })\n *\n * ```\n */\nexport abstract class Ratelimit<TContext extends Context> {\n protected readonly limiter: Algorithm<TContext>;\n\n protected readonly ctx: TContext;\n\n protected readonly prefix: string;\n\n protected readonly timeout: number;\n protected readonly analytics?: Analytics;\n constructor(config: RatelimitConfig<TContext>) {\n this.ctx = config.ctx;\n this.limiter = config.limiter;\n this.timeout = config.timeout ?? 5000;\n this.prefix = config.prefix ?? \"@upstash/ratelimit\";\n this.analytics = config.analytics\n ? new Analytics({\n redis: Array.isArray(this.ctx.redis) ? this.ctx.redis[0] : this.ctx.redis,\n prefix: this.prefix,\n })\n : undefined;\n\n if (config.ephemeralCache instanceof Map) {\n this.ctx.cache = new Cache(config.ephemeralCache);\n } else if (typeof config.ephemeralCache === \"undefined\") {\n this.ctx.cache = new Cache(new Map());\n }\n }\n\n /**\n * Determine if a request should pass or be rejected based on the identifier and previously chosen ratelimit.\n *\n * Use this if you want to reject all requests that you can not handle right now.\n *\n * @example\n * ```ts\n * const ratelimit = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(10, \"10 s\")\n * })\n *\n * const { success } = await ratelimit.limit(id)\n * if (!success){\n * return \"Nope\"\n * }\n * return \"Yes\"\n * ```\n */\n public limit = async (identifier: string, req?: { geo?: Geo }): Promise<RatelimitResponse> => {\n const key = [this.prefix, identifier].join(\":\");\n let timeoutId: any = null;\n try {\n const arr: Promise<RatelimitResponse>[] = [this.limiter(this.ctx, key)];\n if (this.timeout > 0) {\n arr.push(\n new Promise((resolve) => {\n timeoutId = setTimeout(() => {\n resolve({\n success: true,\n limit: 0,\n remaining: 0,\n reset: 0,\n pending: Promise.resolve(),\n });\n }, this.timeout);\n }),\n );\n }\n\n const res = await Promise.race(arr);\n if (this.analytics) {\n try {\n const geo = req ? this.analytics.extractGeo(req) : undefined;\n const analyticsP = this.analytics\n .record({\n identifier,\n time: Date.now(),\n success: res.success,\n ...geo,\n })\n .catch((err) => {\n console.warn(\"Failed to record analytics\", err);\n });\n res.pending = Promise.all([res.pending, analyticsP]);\n } catch (err) {\n console.warn(\"Failed to record analytics\", err);\n }\n }\n return res;\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n };\n\n /**\n * Block until the request may pass or timeout is reached.\n *\n * This method returns a promise that resolves as soon as the request may be processed\n * or after the timeout has been reached.\n *\n * Use this if you want to delay the request until it is ready to get processed.\n *\n * @example\n * ```ts\n * const ratelimit = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(10, \"10 s\")\n * })\n *\n * const { success } = await ratelimit.blockUntilReady(id, 60_000)\n * if (!success){\n * return \"Nope\"\n * }\n * return \"Yes\"\n * ```\n */\n public blockUntilReady = async (\n /**\n * An identifier per user or api.\n * Choose a userID, or api token, or ip address.\n *\n * If you want to limit your api across all users, you can set a constant string.\n */\n identifier: string,\n /**\n * Maximum duration to wait in milliseconds.\n * After this time the request will be denied.\n */\n timeout: number,\n ): Promise<RatelimitResponse> => {\n if (timeout <= 0) {\n throw new Error(\"timeout must be positive\");\n }\n let res: RatelimitResponse;\n\n const deadline = Date.now() + timeout;\n while (true) {\n res = await this.limit(identifier);\n if (res.success) {\n break;\n }\n if (res.reset === 0) {\n throw new Error(\"This should not happen\");\n }\n\n const wait = Math.min(res.reset, deadline) - Date.now();\n await new Promise((r) => setTimeout(r, wait));\n\n if (Date.now() > deadline) {\n break;\n }\n }\n return res!;\n };\n}\n","import { Cache } from \"./cache\";\nimport type { Duration } from \"./duration\";\nimport { ms } from \"./duration\";\nimport { Ratelimit } from \"./ratelimit\";\nimport type { Algorithm, MultiRegionContext } from \"./types\";\nimport type { Redis } from \"./types\";\n\nfunction randomId(): string {\n let result = \"\";\n const characters = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n const charactersLength = characters.length;\n for (let i = 0; i < 16; i++) {\n result += characters.charAt(Math.floor(Math.random() * charactersLength));\n }\n return result;\n}\n\nexport type MultiRegionRatelimitConfig = {\n /**\n * Instances of `@upstash/redis`\n * @see https://github.com/upstash/upstash-redis#quick-start\n */\n redis: Redis[];\n /**\n * The ratelimiter function to use.\n *\n * Choose one of the predefined ones or implement your own.\n * Available algorithms are exposed via static methods:\n * - MultiRegionRatelimit.fixedWindow\n */\n limiter: Algorithm<MultiRegionContext>;\n /**\n * All keys in redis are prefixed with this.\n *\n * @default `@upstash/ratelimit`\n */\n prefix?: string;\n\n /**\n * If enabled, the ratelimiter will keep a global cache of identifiers, that have\n * exhausted their ratelimit. In serverless environments this is only possible if\n * you create the ratelimiter instance outside of your handler function. While the\n * function is still hot, the ratelimiter can block requests without having to\n * request data from redis, thus saving time and money.\n *\n * Whenever an identifier has exceeded its limit, the ratelimiter will add it to an\n * internal list together with its reset timestamp. If the same identifier makes a\n * new request before it is reset, we can immediately reject it.\n *\n * Set to `false` to disable.\n *\n * If left undefined, a map is created automatically, but it can only work\n * if the map or the ratelimit instance is created outside your serverless function handler.\n */\n ephemeralCache?: Map<string, number> | false;\n\n /**\n * If set, the ratelimiter will allow requests to pass after this many milliseconds.\n *\n * Use this if you want to allow requests in case of network problems\n */\n timeout?: number;\n\n /**\n * If enabled, the ratelimiter will store analytics data in redis, which you can check out at\n * https://console.upstash.com/ratelimit\n *\n * @default true\n */\n analytics?: boolean;\n};\n\n/**\n * Ratelimiter using serverless redis from https://upstash.com/\n *\n * @example\n * ```ts\n * const { limit } = new MultiRegionRatelimit({\n * redis: Redis.fromEnv(),\n * limiter: MultiRegionRatelimit.fixedWindow(\n * 10, // Allow 10 requests per window of 30 minutes\n * \"30 m\", // interval of 30 minutes\n * )\n * })\n *\n * ```\n */\nexport class MultiRegionRatelimit extends Ratelimit<MultiRegionContext> {\n /**\n * Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithn of your choice.\n */\n constructor(config: MultiRegionRatelimitConfig) {\n super({\n prefix: config.prefix,\n limiter: config.limiter,\n timeout: config.timeout,\n analytics: config.analytics,\n ctx: {\n redis: config.redis,\n cache: config.ephemeralCache ? new Cache(config.ephemeralCache) : undefined,\n },\n });\n }\n\n /**\n * Each request inside a fixed time increases a counter.\n * Once the counter reaches the maximum allowed number, all further requests are\n * rejected.\n *\n * **Pro:**\n *\n * - Newer requests are not starved by old ones.\n * - Low storage cost.\n *\n * **Con:**\n *\n * A burst of requests near the boundary of a window can result in a very\n * high request rate because two windows will be filled with requests quickly.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - A fixed timeframe\n */\n static fixedWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<MultiRegionContext> {\n const windowDuration = ms(window);\n const script = `\n local key = KEYS[1]\n local id = ARGV[1]\n local window = ARGV[2]\n \n redis.call(\"SADD\", key, id)\n local members = redis.call(\"SMEMBERS\", key)\n if #members == 1 then\n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", key, window)\n end\n \n return members\n`;\n\n return async function (ctx: MultiRegionContext, identifier: string) {\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: tokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n\n const requestId = randomId();\n const bucket = Math.floor(Date.now() / windowDuration);\n const key = [identifier, bucket].join(\":\");\n\n const dbs: { redis: Redis; request: Promise<string[]> }[] = ctx.redis.map((redis) => ({\n redis,\n request: redis.eval(script, [key], [requestId, windowDuration]) as Promise<string[]>,\n }));\n\n const firstResponse = await Promise.any(dbs.map((s) => s.request));\n\n const usedTokens = firstResponse.length;\n\n const remaining = tokens - usedTokens - 1;\n\n /**\n * If the length between two databases does not match, we sync the two databases\n */\n async function sync() {\n const individualIDs = await Promise.all(dbs.map((s) => s.request));\n const allIDs = Array.from(new Set(individualIDs.flatMap((_) => _)).values());\n\n for (const db of dbs) {\n const ids = await db.request;\n /**\n * If the bucket in this db is already full, it doesn't matter which ids it contains.\n * So we do not have to sync.\n */\n if (ids.length >= tokens) {\n continue;\n }\n const diff = allIDs.filter((id) => !ids.includes(id));\n /**\n * Don't waste a request if there is nothing to send\n */\n if (diff.length === 0) {\n continue;\n }\n\n await db.redis.sadd(key, ...allIDs);\n }\n }\n\n /**\n * Do not await sync. This should not run in the critical path.\n */\n\n const success = remaining > 0;\n const reset = (bucket + 1) * windowDuration;\n\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n return {\n success,\n limit: tokens,\n remaining,\n reset,\n pending: sync(),\n };\n };\n }\n\n /**\n * Combined approach of `slidingLogs` and `fixedWindow` with lower storage\n * costs than `slidingLogs` and improved boundary behavior by calculating a\n * weighted score between two windows.\n *\n * **Pro:**\n *\n * Good performance allows this to scale to very high loads.\n *\n * **Con:**\n *\n * Nothing major.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - The duration in which the user can max X requests.\n */\n static slidingWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<MultiRegionContext> {\n const windowSize = ms(window);\n const script = `\n local currentKey = KEYS[1] -- identifier including prefixes\n local previousKey = KEYS[2] -- key of the previous bucket\n local tokens = tonumber(ARGV[1]) -- tokens per window\n local now = ARGV[2] -- current timestamp in milliseconds\n local window = ARGV[3] -- interval in milliseconds\n local requestId = ARGV[4] -- uuid for this request\n\n\n local currentMembers = redis.call(\"SMEMBERS\", currentKey)\n local requestsInCurrentWindow = #currentMembers\n local previousMembers = redis.call(\"SMEMBERS\", previousKey)\n local requestsInPreviousWindow = #previousMembers\n\n local percentageInCurrent = ( now % window) / window\n if requestsInPreviousWindow * ( 1 - percentageInCurrent ) + requestsInCurrentWindow >= tokens then\n return {currentMembers, previousMembers, false}\n end\n\n redis.call(\"SADD\", currentKey, requestId)\n table.insert(currentMembers, requestId)\n if requestsInCurrentWindow == 0 then \n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", currentKey, window * 2 + 1000) -- Enough time to overlap with a new window + 1 second\n end\n return {currentMembers, previousMembers, true}\n `;\n const windowDuration = ms(window);\n\n return async function (ctx: MultiRegionContext, identifier: string) {\n // if (ctx.cache) {\n // const { blocked, reset } = ctx.cache.isBlocked(identifier);\n // if (blocked) {\n // return {\n // success: false,\n // limit: tokens,\n // remaining: 0,\n // reset: reset,\n // pending: Promise.resolve(),\n // };\n // }\n // }\n\n const requestId = randomId();\n const now = Date.now();\n\n const currentWindow = Math.floor(now / windowSize);\n const currentKey = [identifier, currentWindow].join(\":\");\n const previousWindow = currentWindow - 1;\n const previousKey = [identifier, previousWindow].join(\":\");\n\n const dbs = ctx.redis.map((redis) => ({\n redis,\n request: redis.eval(\n script,\n [currentKey, previousKey],\n [tokens, now, windowDuration, requestId],\n // lua seems to return `1` for true and `null` for false\n ) as Promise<[string[], string[], 1 | null]>,\n }));\n\n const percentageInCurrent = (now % windowDuration) / windowDuration;\n const [current, previous, success] = await Promise.any(dbs.map((s) => s.request));\n\n const previousPartialUsed = previous.length * (1 - percentageInCurrent);\n const usedTokens = previousPartialUsed + current.length;\n\n const remaining = tokens - usedTokens;\n\n /**\n * If a database differs from the consensus, we sync it\n */\n async function sync() {\n const res = await Promise.all(dbs.map((s) => s.request));\n const allCurrentIds = res.flatMap(([current]) => current);\n for (const db of dbs) {\n const [ids] = await db.request;\n /**\n * If the bucket in this db is already full, it doesn't matter which ids it contains.\n * So we do not have to sync.\n */\n if (ids.length >= tokens) {\n continue;\n }\n const diff = allCurrentIds.filter((id) => !ids.includes(id));\n /**\n * Don't waste a request if there is nothing to send\n */\n if (diff.length === 0) {\n continue;\n }\n\n await db.redis.sadd(currentKey, ...diff);\n }\n }\n\n // const success = remaining >= 0;\n const reset = (currentWindow + 1) * windowDuration;\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n return {\n success: Boolean(success),\n limit: tokens,\n remaining,\n reset,\n pending: sync(),\n };\n };\n }\n}\n","import type { Duration } from \"./duration\";\nimport { ms } from \"./duration\";\nimport type { Algorithm, RegionContext } from \"./types\";\nimport type { Redis } from \"./types\";\n\nimport { Ratelimit } from \"./ratelimit\";\nexport type RegionRatelimitConfig = {\n /**\n * Instance of `@upstash/redis`\n * @see https://github.com/upstash/upstash-redis#quick-start\n */\n redis: Redis;\n /**\n * The ratelimiter function to use.\n *\n * Choose one of the predefined ones or implement your own.\n * Available algorithms are exposed via static methods:\n * - Ratelimiter.fixedWindow\n * - Ratelimiter.slidingWindow\n * - Ratelimiter.tokenBucket\n */\n limiter: Algorithm<RegionContext>;\n /**\n * All keys in redis are prefixed with this.\n *\n * @default `@upstash/ratelimit`\n */\n prefix?: string;\n\n /**\n * If enabled, the ratelimiter will keep a global cache of identifiers, that have\n * exhausted their ratelimit. In serverless environments this is only possible if\n * you create the ratelimiter instance outside of your handler function. While the\n * function is still hot, the ratelimiter can block requests without having to\n * request data from redis, thus saving time and money.\n *\n * Whenever an identifier has exceeded its limit, the ratelimiter will add it to an\n * internal list together with its reset timestamp. If the same identifier makes a\n * new request before it is reset, we can immediately reject it.\n *\n * Set to `false` to disable.\n *\n * If left undefined, a map is created automatically, but it can only work\n * if the map or the ratelimit instance is created outside your serverless function handler.\n */\n ephemeralCache?: Map<string, number> | false;\n\n /**\n * If set, the ratelimiter will allow requests to pass after this many milliseconds.\n *\n * Use this if you want to allow requests in case of network problems\n */\n timeout?: number;\n\n /**\n * If enabled, the ratelimiter will store analytics data in redis, which you can check out at\n * https://console.upstash.com/ratelimit\n *\n * @default true\n */\n analytics?: boolean;\n};\n\n/**\n * Ratelimiter using serverless redis from https://upstash.com/\n *\n * @example\n * ```ts\n * const { limit } = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(\n * \"30 m\", // interval of 30 minutes\n * 10, // Allow 10 requests per window of 30 minutes\n * )\n * })\n *\n * ```\n */\nexport class RegionRatelimit extends Ratelimit<RegionContext> {\n /**\n * Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithm of your choice.\n */\n\n constructor(config: RegionRatelimitConfig) {\n super({\n prefix: config.prefix,\n limiter: config.limiter,\n timeout: config.timeout,\n analytics: config.analytics,\n ctx: {\n redis: config.redis,\n },\n ephemeralCache: config.ephemeralCache,\n });\n }\n\n /**\n * Each request inside a fixed time increases a counter.\n * Once the counter reaches the maximum allowed number, all further requests are\n * rejected.\n *\n * **Pro:**\n *\n * - Newer requests are not starved by old ones.\n * - Low storage cost.\n *\n * **Con:**\n *\n * A burst of requests near the boundary of a window can result in a very\n * high request rate because two windows will be filled with requests quickly.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - A fixed timeframe\n */\n static fixedWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<RegionContext> {\n const windowDuration = ms(window);\n\n const script = `\n local key = KEYS[1]\n local window = ARGV[1]\n \n local r = redis.call(\"INCR\", key)\n if r == 1 then \n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", key, window)\n end\n \n return r\n `;\n\n return async function (ctx: RegionContext, identifier: string) {\n const bucket = Math.floor(Date.now() / windowDuration);\n const key = [identifier, bucket].join(\":\");\n\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: tokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n const usedTokensAfterUpdate = (await ctx.redis.eval(\n script,\n [key],\n [windowDuration],\n )) as number;\n\n const success = usedTokensAfterUpdate <= tokens;\n const reset = (bucket + 1) * windowDuration;\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n\n return {\n success,\n limit: tokens,\n remaining: Math.max(0, tokens - usedTokensAfterUpdate),\n reset,\n pending: Promise.resolve(),\n };\n };\n }\n\n /**\n * Combined approach of `slidingLogs` and `fixedWindow` with lower storage\n * costs than `slidingLogs` and improved boundary behavior by calculating a\n * weighted score between two windows.\n *\n * **Pro:**\n *\n * Good performance allows this to scale to very high loads.\n *\n * **Con:**\n *\n * Nothing major.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - The duration in which the user can max X requests.\n */\n static slidingWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<RegionContext> {\n const script = `\n local currentKey = KEYS[1] -- identifier including prefixes\n local previousKey = KEYS[2] -- key of the previous bucket\n local tokens = tonumber(ARGV[1]) -- tokens per window\n local now = ARGV[2] -- current timestamp in milliseconds\n local window = ARGV[3] -- interval in milliseconds\n\n local requestsInCurrentWindow = redis.call(\"GET\", currentKey)\n if requestsInCurrentWindow == false then\n requestsInCurrentWindow = 0\n end\n\n local requestsInPreviousWindow = redis.call(\"GET\", previousKey)\n if requestsInPreviousWindow == false then\n requestsInPreviousWindow = 0\n end\n local percentageInCurrent = ( now % window ) / window\n -- weighted requests to consider from the previous window\n requestsInPreviousWindow = math.floor(( 1 - percentageInCurrent ) * requestsInPreviousWindow)\n if requestsInPreviousWindow + requestsInCurrentWindow >= tokens then\n return -1\n end\n\n local newValue = redis.call(\"INCR\", currentKey)\n if newValue == 1 then \n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", currentKey, window * 2 + 1000) -- Enough time to overlap with a new window + 1 second\n end\n return tokens - ( newValue + requestsInPreviousWindow )\n `;\n const windowSize = ms(window);\n return async function (ctx: RegionContext, identifier: string) {\n const now = Date.now();\n\n const currentWindow = Math.floor(now / windowSize);\n const currentKey = [identifier, currentWindow].join(\":\");\n const previousWindow = currentWindow - 1;\n const previousKey = [identifier, previousWindow].join(\":\");\n\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: tokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n\n const remaining = (await ctx.redis.eval(\n script,\n [currentKey, previousKey],\n [tokens, now, windowSize],\n )) as number;\n\n const success = remaining >= 0;\n const reset = (currentWindow + 1) * windowSize;\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n return {\n success,\n limit: tokens,\n remaining: Math.max(0, remaining),\n reset,\n pending: Promise.resolve(),\n };\n };\n }\n\n /**\n * You have a bucket filled with `{maxTokens}` tokens that refills constantly\n * at `{refillRate}` per `{interval}`.\n * Every request will remove one token from the bucket and if there is no\n * token to take, the request is rejected.\n *\n * **Pro:**\n *\n * - Bursts of requests are smoothed out and you can process them at a constant\n * rate.\n * - Allows to set a higher initial burst limit by setting `maxTokens` higher\n * than `refillRate`\n */\n static tokenBucket(\n /**\n * How many tokens are refilled per `interval`\n *\n * An interval of `10s` and refillRate of 5 will cause a new token to be added every 2 seconds.\n */\n refillRate: number,\n /**\n * The interval for the `refillRate`\n */\n interval: Duration,\n /**\n * Maximum number of tokens.\n * A newly created bucket starts with this many tokens.\n * Useful to allow higher burst limits.\n */\n maxTokens: number,\n ): Algorithm<RegionContext> {\n const script = `\n local key = KEYS[1] -- identifier including prefixes\n local maxTokens = tonumber(ARGV[1]) -- maximum number of tokens\n local interval = tonumber(ARGV[2]) -- size of the window in milliseconds\n local refillRate = tonumber(ARGV[3]) -- how many tokens are refilled after each interval\n local now = tonumber(ARGV[4]) -- current timestamp in milliseconds\n \n local bucket = redis.call(\"HMGET\", key, \"refilledAt\", \"tokens\")\n \n local refilledAt\n local tokens\n\n if bucket[1] == false then\n refilledAt = now\n tokens = maxTokens\n else\n refilledAt = tonumber(bucket[1])\n tokens = tonumber(bucket[2])\n end\n \n if now >= refilledAt + interval then\n local numRefills = math.floor((now - refilledAt) / interval)\n tokens = math.min(maxTokens, tokens + numRefills * refillRate)\n\n refilledAt = refilledAt + numRefills * interval\n end\n\n if tokens == 0 then\n return {-1, refilledAt + interval}\n end\n\n local remaining = tokens - 1\n local expireAt = math.ceil(((maxTokens - remaining) / refillRate)) * interval\n \n redis.call(\"HSET\", key, \"refilledAt\", refilledAt, \"tokens\", remaining)\n redis.call(\"PEXPIRE\", key, expireAt)\n return {remaining, refilledAt + interval}\n `;\n\n const intervalDuration = ms(interval);\n return async function (ctx: RegionContext, identifier: string) {\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: maxTokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n\n const now = Date.now();\n\n const [remaining, reset] = (await ctx.redis.eval(\n script,\n [identifier],\n [maxTokens, intervalDuration, refillRate, now],\n )) as [number, number];\n\n const success = remaining >= 0;\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n\n return {\n success,\n limit: maxTokens,\n remaining,\n reset,\n pending: Promise.resolve(),\n };\n };\n }\n\n /**\n * cachedFixedWindow first uses the local cache to decide if a request may pass and then updates\n * it asynchronously.\n * This is experimental and not yet recommended for production use.\n *\n * @experimental\n *\n * Each request inside a fixed time increases a counter.\n * Once the counter reaches the maximum allowed number, all further requests are\n * rejected.\n *\n * **Pro:**\n *\n * - Newer requests are not starved by old ones.\n * - Low storage cost.\n *\n * **Con:**\n *\n * A burst of requests near the boundary of a window can result in a very\n * high request rate because two windows will be filled with requests quickly.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - A fixed timeframe\n */\n static cachedFixedWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<RegionContext> {\n const windowDuration = ms(window);\n\n const script = `\n local key = KEYS[1]\n local window = ARGV[1]\n \n local r = redis.call(\"INCR\", key)\n if r == 1 then \n -- The first time this key is set, the value will be 1.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", key, window)\n end\n \n return r\n `;\n\n return async function (ctx: RegionContext, identifier: string) {\n if (!ctx.cache) {\n throw new Error(\"This algorithm requires a cache\");\n }\n const bucket = Math.floor(Date.now() / windowDuration);\n const key = [identifier, bucket].join(\":\");\n const reset = (bucket + 1) * windowDuration;\n\n const hit = typeof ctx.cache.get(key) === \"number\";\n if (hit) {\n const cachedTokensAfterUpdate = ctx.cache.incr(key);\n const success = cachedTokensAfterUpdate < tokens;\n\n const pending = success\n ? ctx.redis.eval(script, [key], [windowDuration]).then((t) => {\n ctx.cache!.set(key, t as number);\n })\n : Promise.resolve();\n\n return {\n success,\n limit: tokens,\n remaining: tokens - cachedTokensAfterUpdate,\n reset: reset,\n pending,\n };\n }\n\n const usedTokensAfterUpdate = (await ctx.redis.eval(\n script,\n [key],\n [windowDuration],\n )) as number;\n ctx.cache.set(key, usedTokensAfterUpdate);\n const remaining = tokens - usedTokensAfterUpdate;\n\n return {\n success: remaining >= 0,\n limit: tokens,\n remaining,\n reset: reset,\n pending: Promise.resolve(),\n };\n };\n }\n}\n"],"mappings":";AAAA,SAAS,aAAa,qBAAqB;AAuBpC,IAAM,YAAN,MAAgB;AAAA,EACJ;AAAA,EACA,QAAQ;AAAA,EAEzB,YAAY,QAAyB;AACnC,SAAK,YAAY,IAAI,cAAc;AAAA;AAAA,MAEjC,OAAO,OAAO;AAAA,MACd,QAAQ;AAAA,MACR,QAAQ,OAAO,UAAU;AAAA,MACzB,WAAW;AAAA,IACb,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASO,WAAW,KAAmC;AACnD,QAAI,OAAO,IAAI,QAAQ,aAAa;AAClC,aAAO,IAAI;AAAA,IACb;AACA,QAAI,OAAO,IAAI,OAAO,aAAa;AACjC,aAAO,IAAI;AAAA,IACb;AAEA,WAAO,CAAC;AAAA,EACV;AAAA,EAEA,MAAa,OAAO,OAA6B;A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A,OAAO;AAAA,UACP,WAAW,SAAS;AAAA,UACpB;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAEA,YAAM,wBAAyB,MAAM,IAAI,MAAM;AAAA,QAC7C;AAAA,QACA,CAAC,GAAG;AAAA,QACJ,CAAC,cAAc;AAAA,MACjB;AACA,UAAI,MAAM,IAAI,KAAK,qBAAqB;AACxC,YAAM,YAAY,SAAS;AAE3B,aAAO;AAAA,QACL,SAAS,aAAa;AAAA,QACtB,OAAO;AAAA,QACP;AAAA,QACA;AAAA,QACA,SAAS,QAAQ,QAAQ;AAAA,MAC3B;AAAA,IACF;AAAA,EACF;AACF;","names":["reset","current","reset"]}
|
|
1
|
+
{"version":3,"sources":["../src/analytics.ts","../src/cache.ts","../src/duration.ts","../src/lua-scripts/multi.ts","../src/ratelimit.ts","../src/multi.ts","../src/lua-scripts/single.ts","../src/single.ts"],"sourcesContent":["import { Analytics as CoreAnalytics } from \"@upstash/core-analytics\";\nimport type { Redis } from \"./types\";\n\nexport type Geo = {\n country?: string;\n city?: string;\n region?: string;\n ip?: string;\n};\nexport type Event = Geo & {\n identifier: string;\n time: number;\n success: boolean;\n};\n\nexport type AnalyticsConfig = {\n redis: Redis;\n prefix?: string;\n};\n\n/**\n * The Analytics package is experimental and can change at any time.\n */\nexport class Analytics {\n private readonly analytics: CoreAnalytics;\n private readonly table = \"events\";\n\n constructor(config: AnalyticsConfig) {\n this.analytics = new CoreAnalytics({\n // @ts-expect-error we need to fix the types in core-analytics, it should only require the methods it needs, not the whole sdk\n redis: config.redis,\n window: \"1h\",\n prefix: config.prefix ?? \"@upstash/ratelimit\",\n retention: \"90d\",\n });\n }\n\n /**\n * Try to extract the geo information from the request\n *\n * This handles Vercel's `req.geo` and and Cloudflare's `request.cf` properties\n * @param req\n * @returns\n */\n public extractGeo(req: { geo?: Geo; cf?: Geo }): Geo {\n if (typeof req.geo !== \"undefined\") {\n return req.geo;\n }\n if (typeof req.cf !== \"undefined\") {\n return req.cf;\n }\n\n return {};\n }\n\n public async record(event: Event): Promise<void> {\n await this.analytics.ingest(this.table, event);\n }\n\n async series<TFilter extends keyof Omit<Event, \"time\">>(\n filter: TFilter,\n cutoff: number,\n ): Promise<({ time: number } & Record<string, number>)[]> {\n const records = await this.analytics.query(this.table, {\n filter: [filter],\n range: [cutoff, Date.now()],\n });\n return records;\n }\n public async getUsage(cutoff = 0): Promise<Record<string, { success: number; blocked: number }>> {\n const records = await this.analytics.aggregateBy(this.table, \"identifier\", {\n range: [cutoff, Date.now()],\n });\n const usage = {} as Record<string, { success: number; blocked: number }>;\n for (const bucket of records) {\n for (const [k, v] of Object.entries(bucket)) {\n if (k === \"time\") {\n continue;\n }\n\n if (!usage[k]) {\n usage[k] = { success: 0, blocked: 0 };\n }\n // @ts-ignore\n usage[k].success += v.true ?? 0;\n // @ts-ignore\n usage[k].blocked += v.false ?? 0;\n }\n }\n return usage;\n }\n}\n","import type { EphemeralCache } from \"./types\";\n\nexport class Cache implements EphemeralCache {\n /**\n * Stores identifier -> reset (in milliseconds)\n */\n private readonly cache: Map<string, number>;\n\n constructor(cache: Map<string, number>) {\n this.cache = cache;\n }\n\n public isBlocked(identifier: string): { blocked: boolean; reset: number } {\n if (!this.cache.has(identifier)) {\n return { blocked: false, reset: 0 };\n }\n const reset = this.cache.get(identifier)!;\n if (reset < Date.now()) {\n this.cache.delete(identifier);\n return { blocked: false, reset: 0 };\n }\n\n return { blocked: true, reset: reset };\n }\n\n public blockUntil(identifier: string, reset: number): void {\n this.cache.set(identifier, reset);\n }\n\n public set(key: string, value: number): void {\n this.cache.set(key, value);\n }\n public get(key: string): number | null {\n return this.cache.get(key) || null;\n }\n\n public incr(key: string): number {\n let value = this.cache.get(key) ?? 0;\n value += 1;\n this.cache.set(key, value);\n return value;\n }\n}\n","type Unit = \"ms\" | \"s\" | \"m\" | \"h\" | \"d\";\nexport type Duration = `${number} ${Unit}` | `${number}${Unit}`;\n\n/**\n * Convert a human readable duration to milliseconds\n */\nexport function ms(d: Duration): number {\n const match = d.match(/^(\\d+)\\s?(ms|s|m|h|d)$/);\n if (!match) {\n throw new Error(`Unable to parse window size: ${d}`);\n }\n const time = Number.parseInt(match[1]);\n const unit = match[2] as Unit;\n\n switch (unit) {\n case \"ms\":\n return time;\n case \"s\":\n return time * 1000;\n case \"m\":\n return time * 1000 * 60;\n case \"h\":\n return time * 1000 * 60 * 60;\n case \"d\":\n return time * 1000 * 60 * 60 * 24;\n\n default:\n throw new Error(`Unable to parse window size: ${d}`);\n }\n}\n","export const fixedWindowScript = `\n\tlocal key = KEYS[1]\n\tlocal id = ARGV[1]\n\tlocal window = ARGV[2]\n\tlocal incrementBy = tonumber(ARGV[3])\n\n\tredis.call(\"HSET\", key, id, incrementBy)\n\tlocal fields = redis.call(\"HGETALL\", key)\n\tif #fields == 1 and tonumber(fields[1])==incrementBy then\n\t-- The first time this key is set, and the value will be equal to incrementBy.\n\t-- So we only need the expire command once\n\t redis.call(\"PEXPIRE\", key, window)\n\tend\n\n\treturn fields\n`;\n\nexport const slidingWindowScript = `\n\tlocal currentKey = KEYS[1] -- identifier including prefixes\n\tlocal previousKey = KEYS[2] -- key of the previous bucket\n\tlocal tokens = tonumber(ARGV[1]) -- tokens per window\n\tlocal now = ARGV[2] -- current timestamp in milliseconds\n\tlocal window = ARGV[3] -- interval in milliseconds\n\tlocal requestId = ARGV[4] -- uuid for this request\n\tlocal incrementBy = tonumber(ARGV[5]) -- custom rate, default is 1\n\n\tlocal currentFields = redis.call(\"HGETALL\", currentKey)\n\tlocal requestsInCurrentWindow = 0\n\tfor i = 2, #currentFields, 2 do\n\trequestsInCurrentWindow = requestsInCurrentWindow + tonumber(currentFields[i])\n\tend\n\n\tlocal previousFields = redis.call(\"HGETALL\", previousKey)\n\tlocal requestsInPreviousWindow = 0\n\tfor i = 2, #previousFields, 2 do\n\trequestsInPreviousWindow = requestsInPreviousWindow + tonumber(previousFields[i])\n\tend\n\n\tlocal percentageInCurrent = ( now % window) / window\n\tif requestsInPreviousWindow * (1 - percentageInCurrent ) + requestsInCurrentWindow >= tokens then\n\t return {currentFields, previousFields, false}\n\tend\n\n\tredis.call(\"HSET\", currentKey, requestId, incrementBy)\n\n\tif requestsInCurrentWindow == 0 then \n\t -- The first time this key is set, the value will be equal to incrementBy.\n\t -- So we only need the expire command once\n\t redis.call(\"PEXPIRE\", currentKey, window * 2 + 1000) -- Enough time to overlap with a new window + 1 second\n\tend\n\treturn {currentFields, previousFields, true}\n`;\n","import { Analytics, type Geo } from \"./analytics\";\nimport { Cache } from \"./cache\";\nimport type { Algorithm, Context, RatelimitResponse } from \"./types\";\n\nexport class TimeoutError extends Error {\n constructor() {\n super(\"Timeout\");\n this.name = \"TimeoutError\";\n }\n}\nexport type RatelimitConfig<TContext> = {\n /**\n * The ratelimiter function to use.\n *\n * Choose one of the predefined ones or implement your own.\n * Available algorithms are exposed via static methods:\n * - Ratelimiter.fixedWindow\n * - Ratelimiter.slidingWindow\n * - Ratelimiter.tokenBucket\n */\n\n limiter: Algorithm<TContext>;\n\n ctx: TContext;\n /**\n * All keys in redis are prefixed with this.\n *\n * @default `@upstash/ratelimit`\n */\n prefix?: string;\n\n /**\n * If enabled, the ratelimiter will keep a global cache of identifiers, that have\n * exhausted their ratelimit. In serverless environments this is only possible if\n * you create the ratelimiter instance outside of your handler function. While the\n * function is still hot, the ratelimiter can block requests without having to\n * request data from redis, thus saving time and money.\n *\n * Whenever an identifier has exceeded its limit, the ratelimiter will add it to an\n * internal list together with its reset timestamp. If the same identifier makes a\n * new request before it is reset, we can immediately reject it.\n *\n * Set to `false` to disable.\n *\n * If left undefined, a map is created automatically, but it can only work\n * if the map or the ratelimit instance is created outside your serverless function handler.\n */\n ephemeralCache?: Map<string, number> | false;\n\n /**\n * If set, the ratelimiter will allow requests to pass after this many milliseconds.\n *\n * Use this if you want to allow requests in case of network problems\n *\n * @default 5000\n */\n timeout?: number;\n\n /**\n * If enabled, the ratelimiter will store analytics data in redis, which you can check out at\n * https://console.upstash.com/ratelimit\n *\n * @default false\n */\n analytics?: boolean;\n};\n\n/**\n * Ratelimiter using serverless redis from https://upstash.com/\n *\n * @example\n * ```ts\n * const { limit } = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(\n * 10, // Allow 10 requests per window of 30 minutes\n * \"30 m\", // interval of 30 minutes\n * ),\n * })\n *\n * ```\n */\nexport abstract class Ratelimit<TContext extends Context> {\n protected readonly limiter: Algorithm<TContext>;\n\n protected readonly ctx: TContext;\n\n protected readonly prefix: string;\n\n protected readonly timeout: number;\n\n protected readonly analytics?: Analytics;\n\n constructor(config: RatelimitConfig<TContext>) {\n this.ctx = config.ctx;\n this.limiter = config.limiter;\n this.timeout = config.timeout ?? 5000;\n this.prefix = config.prefix ?? \"@upstash/ratelimit\";\n this.analytics = config.analytics\n ? new Analytics({\n redis: Array.isArray(this.ctx.redis) ? this.ctx.redis[0] : this.ctx.redis,\n prefix: this.prefix,\n })\n : undefined;\n\n if (config.ephemeralCache instanceof Map) {\n this.ctx.cache = new Cache(config.ephemeralCache);\n } else if (typeof config.ephemeralCache === \"undefined\") {\n this.ctx.cache = new Cache(new Map());\n }\n }\n\n /**\n * Determine if a request should pass or be rejected based on the identifier and previously chosen ratelimit.\n *\n * Use this if you want to reject all requests that you can not handle right now.\n *\n * @example\n * ```ts\n * const ratelimit = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(10, \"10 s\")\n * })\n *\n * const { success } = await ratelimit.limit(id)\n * if (!success){\n * return \"Nope\"\n * }\n * return \"Yes\"\n * ```\n *\n * @param req.rate - The rate at which tokens will be added or consumed from the token bucket. A higher rate allows for more requests to be processed. Defaults to 1 token per interval if not specified.\n *\n * Usage with `req.rate`\n * @example\n * ```ts\n * const ratelimit = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(100, \"10 s\")\n * })\n *\n * const { success } = await ratelimit.limit(id, {rate: 10})\n * if (!success){\n * return \"Nope\"\n * }\n * return \"Yes\"\n * ```\n */\n public limit = async (\n identifier: string,\n req?: { geo?: Geo; rate?: number },\n ): Promise<RatelimitResponse> => {\n const key = [this.prefix, identifier].join(\":\");\n let timeoutId: any = null;\n try {\n const arr: Promise<RatelimitResponse>[] = [this.limiter(this.ctx, key, req?.rate)];\n if (this.timeout > 0) {\n arr.push(\n new Promise((resolve) => {\n timeoutId = setTimeout(() => {\n resolve({\n success: true,\n limit: 0,\n remaining: 0,\n reset: 0,\n pending: Promise.resolve(),\n });\n }, this.timeout);\n }),\n );\n }\n\n const res = await Promise.race(arr);\n if (this.analytics) {\n try {\n const geo = req ? this.analytics.extractGeo(req) : undefined;\n const analyticsP = this.analytics\n .record({\n identifier,\n time: Date.now(),\n success: res.success,\n ...geo,\n })\n .catch((err) => {\n console.warn(\"Failed to record analytics\", err);\n });\n res.pending = Promise.all([res.pending, analyticsP]);\n } catch (err) {\n console.warn(\"Failed to record analytics\", err);\n }\n }\n return res;\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n };\n\n /**\n * Block until the request may pass or timeout is reached.\n *\n * This method returns a promise that resolves as soon as the request may be processed\n * or after the timeout has been reached.\n *\n * Use this if you want to delay the request until it is ready to get processed.\n *\n * @example\n * ```ts\n * const ratelimit = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(10, \"10 s\")\n * })\n *\n * const { success } = await ratelimit.blockUntilReady(id, 60_000)\n * if (!success){\n * return \"Nope\"\n * }\n * return \"Yes\"\n * ```\n */\n public blockUntilReady = async (\n /**\n * An identifier per user or api.\n * Choose a userID, or api token, or ip address.\n *\n * If you want to limit your api across all users, you can set a constant string.\n */\n identifier: string,\n /**\n * Maximum duration to wait in milliseconds.\n * After this time the request will be denied.\n */\n timeout: number,\n ): Promise<RatelimitResponse> => {\n if (timeout <= 0) {\n throw new Error(\"timeout must be positive\");\n }\n let res: RatelimitResponse;\n\n const deadline = Date.now() + timeout;\n while (true) {\n res = await this.limit(identifier);\n if (res.success) {\n break;\n }\n if (res.reset === 0) {\n throw new Error(\"This should not happen\");\n }\n\n const wait = Math.min(res.reset, deadline) - Date.now();\n await new Promise((r) => setTimeout(r, wait));\n\n if (Date.now() > deadline) {\n break;\n }\n }\n return res!;\n };\n}\n","import { Cache } from \"./cache\";\nimport type { Duration } from \"./duration\";\nimport { ms } from \"./duration\";\nimport { fixedWindowScript, slidingWindowScript } from \"./lua-scripts/multi\";\nimport { Ratelimit } from \"./ratelimit\";\nimport type { Algorithm, MultiRegionContext } from \"./types\";\n\nimport type { Redis } from \"./types\";\n\nfunction randomId(): string {\n let result = \"\";\n const characters = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n const charactersLength = characters.length;\n for (let i = 0; i < 16; i++) {\n result += characters.charAt(Math.floor(Math.random() * charactersLength));\n }\n return result;\n}\n\nexport type MultiRegionRatelimitConfig = {\n /**\n * Instances of `@upstash/redis`\n * @see https://github.com/upstash/upstash-redis#quick-start\n */\n redis: Redis[];\n /**\n * The ratelimiter function to use.\n *\n * Choose one of the predefined ones or implement your own.\n * Available algorithms are exposed via static methods:\n * - MultiRegionRatelimit.fixedWindow\n */\n limiter: Algorithm<MultiRegionContext>;\n /**\n * All keys in redis are prefixed with this.\n *\n * @default `@upstash/ratelimit`\n */\n prefix?: string;\n\n /**\n * If enabled, the ratelimiter will keep a global cache of identifiers, that have\n * exhausted their ratelimit. In serverless environments this is only possible if\n * you create the ratelimiter instance outside of your handler function. While the\n * function is still hot, the ratelimiter can block requests without having to\n * request data from redis, thus saving time and money.\n *\n * Whenever an identifier has exceeded its limit, the ratelimiter will add it to an\n * internal list together with its reset timestamp. If the same identifier makes a\n * new request before it is reset, we can immediately reject it.\n *\n * Set to `false` to disable.\n *\n * If left undefined, a map is created automatically, but it can only work\n * if the map or the ratelimit instance is created outside your serverless function handler.\n */\n ephemeralCache?: Map<string, number> | false;\n\n /**\n * If set, the ratelimiter will allow requests to pass after this many milliseconds.\n *\n * Use this if you want to allow requests in case of network problems\n */\n timeout?: number;\n\n /**\n * If enabled, the ratelimiter will store analytics data in redis, which you can check out at\n * https://console.upstash.com/ratelimit\n *\n * @default false\n */\n analytics?: boolean;\n};\n\n/**\n * Ratelimiter using serverless redis from https://upstash.com/\n *\n * @example\n * ```ts\n * const { limit } = new MultiRegionRatelimit({\n * redis: Redis.fromEnv(),\n * limiter: MultiRegionRatelimit.fixedWindow(\n * 10, // Allow 10 requests per window of 30 minutes\n * \"30 m\", // interval of 30 minutes\n * )\n * })\n *\n * ```\n */\nexport class MultiRegionRatelimit extends Ratelimit<MultiRegionContext> {\n /**\n * Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithn of your choice.\n */\n constructor(config: MultiRegionRatelimitConfig) {\n super({\n prefix: config.prefix,\n limiter: config.limiter,\n timeout: config.timeout,\n analytics: config.analytics,\n ctx: {\n redis: config.redis,\n cache: config.ephemeralCache ? new Cache(config.ephemeralCache) : undefined,\n },\n });\n }\n\n /**\n * Each request inside a fixed time increases a counter.\n * Once the counter reaches the maximum allowed number, all further requests are\n * rejected.\n *\n * **Pro:**\n *\n * - Newer requests are not starved by old ones.\n * - Low storage cost.\n *\n * **Con:**\n *\n * A burst of requests near the boundary of a window can result in a very\n * high request rate because two windows will be filled with requests quickly.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - A fixed timeframe\n */\n static fixedWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<MultiRegionContext> {\n const windowDuration = ms(window);\n\n return async (ctx: MultiRegionContext, identifier: string, rate?: number) => {\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: tokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n\n const requestId = randomId();\n const bucket = Math.floor(Date.now() / windowDuration);\n const key = [identifier, bucket].join(\":\");\n const incrementBy = rate ? Math.max(1, rate) : 1;\n\n const dbs: { redis: Redis; request: Promise<string[]> }[] = ctx.redis.map((redis) => ({\n redis,\n request: redis.eval(\n fixedWindowScript,\n [key],\n [requestId, windowDuration, incrementBy],\n ) as Promise<string[]>,\n }));\n\n // The firstResponse is an array of string at every EVEN indexes and rate at which the tokens are used at every ODD indexes\n const firstResponse = await Promise.any(dbs.map((s) => s.request));\n\n const usedTokens = firstResponse.reduce((accTokens: number, usedToken, index) => {\n let parsedToken = 0;\n if (index % 2) {\n parsedToken = Number.parseInt(usedToken);\n }\n\n return accTokens + parsedToken;\n }, 0);\n\n const remaining = tokens - usedTokens;\n\n /**\n * If the length between two databases does not match, we sync the two databases\n */\n async function sync() {\n const individualIDs = await Promise.all(dbs.map((s) => s.request));\n\n const allIDs = Array.from(\n new Set(\n individualIDs\n .flatMap((_) => _)\n .reduce((acc: string[], curr, index) => {\n if (index % 2 === 0) {\n acc.push(curr);\n }\n return acc;\n }, []),\n ).values(),\n );\n\n for (const db of dbs) {\n const usedDbTokens = (await db.request).reduce((accTokens: number, usedToken, index) => {\n let parsedToken = 0;\n if (index % 2) {\n parsedToken = Number.parseInt(usedToken);\n }\n\n return accTokens + parsedToken;\n }, 0);\n\n const dbIds = (await db.request).reduce((ids: string[], currentId, index) => {\n if (index % 2 === 0) {\n ids.push(currentId);\n }\n return ids;\n }, []);\n /**\n * If the bucket in this db is already full, it doesn't matter which ids it contains.\n * So we do not have to sync.\n */\n if (usedDbTokens >= tokens) {\n continue;\n }\n const diff = allIDs.filter((id) => !dbIds.includes(id));\n /**\n * Don't waste a request if there is nothing to send\n */\n if (diff.length === 0) {\n continue;\n }\n\n for (const requestId of diff) {\n await db.redis.hset(key, { [requestId]: incrementBy });\n }\n }\n }\n\n /**\n * Do not await sync. This should not run in the critical path.\n */\n\n const success = remaining > 0;\n const reset = (bucket + 1) * windowDuration;\n\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n return {\n success,\n limit: tokens,\n remaining,\n reset,\n pending: sync(),\n };\n };\n }\n\n /**\n * Combined approach of `slidingLogs` and `fixedWindow` with lower storage\n * costs than `slidingLogs` and improved boundary behavior by calculating a\n * weighted score between two windows.\n *\n * **Pro:**\n *\n * Good performance allows this to scale to very high loads.\n *\n * **Con:**\n *\n * Nothing major.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - The duration in which the user can max X requests.\n */\n static slidingWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<MultiRegionContext> {\n const windowSize = ms(window);\n\n const windowDuration = ms(window);\n\n return async (ctx: MultiRegionContext, identifier: string, rate?: number) => {\n // if (ctx.cache) {\n // const { blocked, reset } = ctx.cache.isBlocked(identifier);\n // if (blocked) {\n // return {\n // success: false,\n // limit: tokens,\n // remaining: 0,\n // reset: reset,\n // pending: Promise.resolve(),\n // };\n // }\n // }\n\n const requestId = randomId();\n const now = Date.now();\n\n const currentWindow = Math.floor(now / windowSize);\n const currentKey = [identifier, currentWindow].join(\":\");\n const previousWindow = currentWindow - 1;\n const previousKey = [identifier, previousWindow].join(\":\");\n const incrementBy = rate ? Math.max(1, rate) : 1;\n\n const dbs = ctx.redis.map((redis) => ({\n redis,\n request: redis.eval(\n slidingWindowScript,\n [currentKey, previousKey],\n [tokens, now, windowDuration, requestId, incrementBy],\n // lua seems to return `1` for true and `null` for false\n ) as Promise<[string[], string[], 1 | null]>,\n }));\n\n const percentageInCurrent = (now % windowDuration) / windowDuration;\n const [current, previous, success] = await Promise.any(dbs.map((s) => s.request));\n\n const previousUsedTokens = previous.reduce((accTokens: number, usedToken, index) => {\n let parsedToken = 0;\n if (index % 2) {\n parsedToken = Number.parseInt(usedToken);\n }\n\n return accTokens + parsedToken;\n }, 0);\n\n const currentUsedTokens = current.reduce((accTokens: number, usedToken, index) => {\n let parsedToken = 0;\n if (index % 2) {\n parsedToken = Number.parseInt(usedToken);\n }\n\n return accTokens + parsedToken;\n }, 0);\n\n const previousPartialUsed = previousUsedTokens * (1 - percentageInCurrent);\n\n const usedTokens = previousPartialUsed + currentUsedTokens;\n\n const remaining = tokens - usedTokens;\n\n /**\n * If a database differs from the consensus, we sync it\n */\n async function sync() {\n const res = await Promise.all(dbs.map((s) => s.request));\n const allCurrentIds = res\n .flatMap(([current]) => current)\n .reduce((accCurrentIds: string[], curr, index) => {\n if (index % 2 === 0) {\n accCurrentIds.push(curr);\n }\n return accCurrentIds;\n }, []);\n\n for (const db of dbs) {\n const [_current, previous, _success] = await db.request;\n const dbIds = previous.reduce((ids: string[], currentId, index) => {\n if (index % 2 === 0) {\n ids.push(currentId);\n }\n return ids;\n }, []);\n\n const usedDbTokens = previous.reduce((accTokens: number, usedToken, index) => {\n let parsedToken = 0;\n if (index % 2) {\n parsedToken = Number.parseInt(usedToken);\n }\n\n return accTokens + parsedToken;\n }, 0);\n /**\n * If the bucket in this db is already full, it doesn't matter which ids it contains.\n * So we do not have to sync.\n */\n if (usedDbTokens >= tokens) {\n continue;\n }\n const diff = allCurrentIds.filter((id) => !dbIds.includes(id));\n /**\n * Don't waste a request if there is nothing to send\n */\n if (diff.length === 0) {\n continue;\n }\n\n for (const requestId of diff) {\n await db.redis.hset(currentKey, { [requestId]: incrementBy });\n }\n }\n }\n\n // const success = remaining >= 0;\n const reset = (currentWindow + 1) * windowDuration;\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n return {\n success: Boolean(success),\n limit: tokens,\n remaining: Math.max(0, remaining),\n reset,\n pending: sync(),\n };\n };\n }\n}\n","export const fixedWindowScript = `\n local key = KEYS[1]\n local window = ARGV[1]\n local incrementBy = ARGV[2] -- increment rate per request at a given value, default is 1\n\n local r = redis.call(\"INCRBY\", key, incrementBy)\n if r == incrementBy then\n -- The first time this key is set, the value will be equal to incrementBy.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", key, window)\n end\n\n return r\n`;\n\nexport const slidingWindowScript = `\n local currentKey = KEYS[1] -- identifier including prefixes\n local previousKey = KEYS[2] -- key of the previous bucket\n local tokens = tonumber(ARGV[1]) -- tokens per window\n local now = ARGV[2] -- current timestamp in milliseconds\n local window = ARGV[3] -- interval in milliseconds\n local incrementBy = ARGV[4] -- increment rate per request at a given value, default is 1\n\n local requestsInCurrentWindow = redis.call(\"GET\", currentKey)\n if requestsInCurrentWindow == false then\n requestsInCurrentWindow = 0\n end\n\n local requestsInPreviousWindow = redis.call(\"GET\", previousKey)\n if requestsInPreviousWindow == false then\n requestsInPreviousWindow = 0\n end\n local percentageInCurrent = ( now % window ) / window\n -- weighted requests to consider from the previous window\n requestsInPreviousWindow = math.floor(( 1 - percentageInCurrent ) * requestsInPreviousWindow)\n if requestsInPreviousWindow + requestsInCurrentWindow >= tokens then\n return -1\n end\n\n local newValue = redis.call(\"INCRBY\", currentKey, incrementBy)\n if newValue == incrementBy then\n -- The first time this key is set, the value will be equal to incrementBy.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", currentKey, window * 2 + 1000) -- Enough time to overlap with a new window + 1 second\n end\n return tokens - ( newValue + requestsInPreviousWindow )\n`;\n\nexport const tokenBucketScript = `\n local key = KEYS[1] -- identifier including prefixes\n local maxTokens = tonumber(ARGV[1]) -- maximum number of tokens\n local interval = tonumber(ARGV[2]) -- size of the window in milliseconds\n local refillRate = tonumber(ARGV[3]) -- how many tokens are refilled after each interval\n local now = tonumber(ARGV[4]) -- current timestamp in milliseconds\n local incrementBy = tonumber(ARGV[5]) -- how many tokens to consume, default is 1\n \n local bucket = redis.call(\"HMGET\", key, \"refilledAt\", \"tokens\")\n \n local refilledAt\n local tokens\n\n if bucket[1] == false then\n refilledAt = now\n tokens = maxTokens\n else\n refilledAt = tonumber(bucket[1])\n tokens = tonumber(bucket[2])\n end\n \n if now >= refilledAt + interval then\n local numRefills = math.floor((now - refilledAt) / interval)\n tokens = math.min(maxTokens, tokens + numRefills * refillRate)\n\n refilledAt = refilledAt + numRefills * interval\n end\n\n if tokens == 0 then\n return {-1, refilledAt + interval}\n end\n\n local remaining = tokens - incrementBy\n local expireAt = math.ceil(((maxTokens - remaining) / refillRate)) * interval\n \n redis.call(\"HSET\", key, \"refilledAt\", refilledAt, \"tokens\", remaining)\n redis.call(\"PEXPIRE\", key, expireAt)\n return {remaining, refilledAt + interval}\n`;\n\nexport const cachedFixedWindowScript = `\n local key = KEYS[1]\n local window = ARGV[1]\n local incrementBy = ARGV[2] -- increment rate per request at a given value, default is 1\n\n local r = redis.call(\"INCRBY\", key, incrementBy)\n if r == incrementBy then\n -- The first time this key is set, the value will be equal to incrementBy.\n -- So we only need the expire command once\n redis.call(\"PEXPIRE\", key, window)\n end\n \n return r\n`;\n","import type { Duration } from \"./duration\";\nimport { ms } from \"./duration\";\nimport {\n cachedFixedWindowScript,\n fixedWindowScript,\n slidingWindowScript,\n tokenBucketScript,\n} from \"./lua-scripts/single\";\nimport { Ratelimit } from \"./ratelimit\";\nimport type { Algorithm, RegionContext } from \"./types\";\nimport type { Redis } from \"./types\";\n\nexport type RegionRatelimitConfig = {\n /**\n * Instance of `@upstash/redis`\n * @see https://github.com/upstash/upstash-redis#quick-start\n */\n redis: Redis;\n /**\n * The ratelimiter function to use.\n *\n * Choose one of the predefined ones or implement your own.\n * Available algorithms are exposed via static methods:\n * - Ratelimiter.fixedWindow\n * - Ratelimiter.slidingWindow\n * - Ratelimiter.tokenBucket\n */\n limiter: Algorithm<RegionContext>;\n /**\n * All keys in redis are prefixed with this.\n *\n * @default `@upstash/ratelimit`\n */\n prefix?: string;\n\n /**\n * If enabled, the ratelimiter will keep a global cache of identifiers, that have\n * exhausted their ratelimit. In serverless environments this is only possible if\n * you create the ratelimiter instance outside of your handler function. While the\n * function is still hot, the ratelimiter can block requests without having to\n * request data from redis, thus saving time and money.\n *\n * Whenever an identifier has exceeded its limit, the ratelimiter will add it to an\n * internal list together with its reset timestamp. If the same identifier makes a\n * new request before it is reset, we can immediately reject it.\n *\n * Set to `false` to disable.\n *\n * If left undefined, a map is created automatically, but it can only work\n * if the map or the ratelimit instance is created outside your serverless function handler.\n */\n ephemeralCache?: Map<string, number> | false;\n\n /**\n * If set, the ratelimiter will allow requests to pass after this many milliseconds.\n *\n * Use this if you want to allow requests in case of network problems\n */\n timeout?: number;\n\n /**\n * If enabled, the ratelimiter will store analytics data in redis, which you can check out at\n * https://console.upstash.com/ratelimit\n *\n * @default false\n */\n analytics?: boolean;\n};\n\n/**\n * Ratelimiter using serverless redis from https://upstash.com/\n *\n * @example\n * ```ts\n * const { limit } = new Ratelimit({\n * redis: Redis.fromEnv(),\n * limiter: Ratelimit.slidingWindow(\n * \"30 m\", // interval of 30 minutes\n * 10, // Allow 10 requests per window of 30 minutes\n * )\n * })\n *\n * ```\n */\nexport class RegionRatelimit extends Ratelimit<RegionContext> {\n /**\n * Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithm of your choice.\n */\n\n constructor(config: RegionRatelimitConfig) {\n super({\n prefix: config.prefix,\n limiter: config.limiter,\n timeout: config.timeout,\n analytics: config.analytics,\n ctx: {\n redis: config.redis,\n },\n ephemeralCache: config.ephemeralCache,\n });\n }\n\n /**\n * Each request inside a fixed time increases a counter.\n * Once the counter reaches the maximum allowed number, all further requests are\n * rejected.\n *\n * **Pro:**\n *\n * - Newer requests are not starved by old ones.\n * - Low storage cost.\n *\n * **Con:**\n *\n * A burst of requests near the boundary of a window can result in a very\n * high request rate because two windows will be filled with requests quickly.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - A fixed timeframe\n */\n static fixedWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<RegionContext> {\n const windowDuration = ms(window);\n return async (ctx: RegionContext, identifier: string, rate?: number) => {\n const bucket = Math.floor(Date.now() / windowDuration);\n const key = [identifier, bucket].join(\":\");\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: tokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n\n const incrementBy = rate ? Math.max(1, rate) : 1;\n\n const usedTokensAfterUpdate = (await ctx.redis.eval(\n fixedWindowScript,\n [key],\n [windowDuration, incrementBy],\n )) as number;\n\n const success = usedTokensAfterUpdate <= tokens;\n\n const remainingTokens = Math.max(0, tokens - usedTokensAfterUpdate);\n\n const reset = (bucket + 1) * windowDuration;\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n\n return {\n success,\n limit: tokens,\n remaining: remainingTokens,\n reset,\n pending: Promise.resolve(),\n };\n };\n }\n\n /**\n * Combined approach of `slidingLogs` and `fixedWindow` with lower storage\n * costs than `slidingLogs` and improved boundary behavior by calculating a\n * weighted score between two windows.\n *\n * **Pro:**\n *\n * Good performance allows this to scale to very high loads.\n *\n * **Con:**\n *\n * Nothing major.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - The duration in which the user can max X requests.\n */\n static slidingWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<RegionContext> {\n const windowSize = ms(window);\n return async (ctx: RegionContext, identifier: string, rate?: number) => {\n const now = Date.now();\n\n const currentWindow = Math.floor(now / windowSize);\n const currentKey = [identifier, currentWindow].join(\":\");\n const previousWindow = currentWindow - 1;\n const previousKey = [identifier, previousWindow].join(\":\");\n\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: tokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n\n const incrementBy = rate ? Math.max(1, rate) : 1;\n\n const remainingTokens = (await ctx.redis.eval(\n slidingWindowScript,\n [currentKey, previousKey],\n [tokens, now, windowSize, incrementBy],\n )) as number;\n\n const success = remainingTokens >= 0;\n\n const reset = (currentWindow + 1) * windowSize;\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n return {\n success,\n limit: tokens,\n remaining: Math.max(0, remainingTokens),\n reset,\n pending: Promise.resolve(),\n };\n };\n }\n\n /**\n * You have a bucket filled with `{maxTokens}` tokens that refills constantly\n * at `{refillRate}` per `{interval}`.\n * Every request will remove one token from the bucket and if there is no\n * token to take, the request is rejected.\n *\n * **Pro:**\n *\n * - Bursts of requests are smoothed out and you can process them at a constant\n * rate.\n * - Allows to set a higher initial burst limit by setting `maxTokens` higher\n * than `refillRate`\n */\n static tokenBucket(\n /**\n * How many tokens are refilled per `interval`\n *\n * An interval of `10s` and refillRate of 5 will cause a new token to be added every 2 seconds.\n */\n refillRate: number,\n /**\n * The interval for the `refillRate`\n */\n interval: Duration,\n /**\n * Maximum number of tokens.\n * A newly created bucket starts with this many tokens.\n * Useful to allow higher burst limits.\n */\n maxTokens: number,\n ): Algorithm<RegionContext> {\n const intervalDuration = ms(interval);\n return async (ctx: RegionContext, identifier: string, rate?: number) => {\n if (ctx.cache) {\n const { blocked, reset } = ctx.cache.isBlocked(identifier);\n if (blocked) {\n return {\n success: false,\n limit: maxTokens,\n remaining: 0,\n reset: reset,\n pending: Promise.resolve(),\n };\n }\n }\n\n const now = Date.now();\n\n const incrementBy = rate ? Math.max(1, rate) : 1;\n\n const [remaining, reset] = (await ctx.redis.eval(\n tokenBucketScript,\n [identifier],\n [maxTokens, intervalDuration, refillRate, now, incrementBy],\n )) as [number, number];\n\n const success = remaining >= 0;\n if (ctx.cache && !success) {\n ctx.cache.blockUntil(identifier, reset);\n }\n\n return {\n success,\n limit: maxTokens,\n remaining,\n reset,\n pending: Promise.resolve(),\n };\n };\n }\n\n /**\n * cachedFixedWindow first uses the local cache to decide if a request may pass and then updates\n * it asynchronously.\n * This is experimental and not yet recommended for production use.\n *\n * @experimental\n *\n * Each request inside a fixed time increases a counter.\n * Once the counter reaches the maximum allowed number, all further requests are\n * rejected.\n *\n * **Pro:**\n *\n * - Newer requests are not starved by old ones.\n * - Low storage cost.\n *\n * **Con:**\n *\n * A burst of requests near the boundary of a window can result in a very\n * high request rate because two windows will be filled with requests quickly.\n *\n * @param tokens - How many requests a user can make in each time window.\n * @param window - A fixed timeframe\n */\n static cachedFixedWindow(\n /**\n * How many requests are allowed per window.\n */\n tokens: number,\n /**\n * The duration in which `tokens` requests are allowed.\n */\n window: Duration,\n ): Algorithm<RegionContext> {\n const windowDuration = ms(window);\n\n return async (ctx: RegionContext, identifier: string, rate?: number) => {\n if (!ctx.cache) {\n throw new Error(\"This algorithm requires a cache\");\n }\n const bucket = Math.floor(Date.now() / windowDuration);\n const key = [identifier, bucket].join(\":\");\n const reset = (bucket + 1) * windowDuration;\n const incrementBy = rate ? Math.max(1, rate) : 1;\n\n const hit = typeof ctx.cache.get(key) === \"number\";\n if (hit) {\n const cachedTokensAfterUpdate = ctx.cache.incr(key);\n const success = cachedTokensAfterUpdate < tokens;\n\n const pending = success\n ? ctx.redis\n .eval(cachedFixedWindowScript, [key], [windowDuration, incrementBy])\n .then((t) => {\n ctx.cache!.set(key, t as number);\n })\n : Promise.resolve();\n\n return {\n success,\n limit: tokens,\n remaining: tokens - cachedTokensAfterUpdate,\n reset: reset,\n pending,\n };\n }\n\n const usedTokensAfterUpdate = (await ctx.redis.eval(\n cachedFixedWindowScript,\n [key],\n [windowDuration, incrementBy],\n )) as number;\n ctx.cache.set(key, usedTokensAfterUpdate);\n const remaining = tokens - usedTokensAfterUpdate;\n\n return {\n success: remaining >= 0,\n limit: tokens,\n remaining,\n reset: reset,\n pending: Promise.resolve(),\n };\n };\n }\n}\n"],"mappings":";AAAA,SAAS,aAAa,qBAAqB;AAuBpC,IAAM,YAAN,MAAgB;AAAA,EACJ;AAAA,EACA,QAAQ;AAAA,EAEzB,YAAY,QAAyB;AACnC,SAAK,YAAY,IAAI,cAAc;AAAA;AAAA,MAEjC,OAAO,OAAO;AAAA,MACd,QAAQ;AAAA,MACR,QAAQ,OAAO,UAAU;AAAA,MACzB,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,IAAI,MACD,KAAK,yBAAyB,CAAC,GAAG,GAAG,CAAC,gBAAgB,WAAW,CAAC,EAClE,KAAK,CAAC,MAAM;AACX,cAAI,MAAO,IAAI,KAAK,CAAW;AAAA,QACjC,CAAC,IACH,QAAQ,QAAQ;AAEpB,eAAO;AAAA,UACL;AAAA,UACA,OAAO;AAAA,UACP,WAAW,SAAS;AAAA,UACpB;AAAA,UACA;AAAA,QACF;AAAA,MACF;AAEA,YAAM,wBAAyB,MAAM,IAAI,MAAM;AAAA,QAC7C;AAAA,QACA,CAAC,GAAG;AAAA,QACJ,CAAC,gBAAgB,WAAW;AAAA,MAC9B;AACA,UAAI,MAAM,IAAI,KAAK,qBAAqB;AACxC,YAAM,YAAY,SAAS;AAE3B,aAAO;AAAA,QACL,SAAS,aAAa;AAAA,QACtB,OAAO;AAAA,QACP;AAAA,QACA;AAAA,QACA,SAAS,QAAQ,QAAQ;AAAA,MAC3B;AAAA,IACF;AAAA,EACF;AACF;","names":["reset","requestId","current","previous","fixedWindowScript","slidingWindowScript","reset","fixedWindowScript","slidingWindowScript"]}
|
package/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{ "name": "@upstash/ratelimit", "version": "v1.0.
|
|
1
|
+
{ "name": "@upstash/ratelimit", "version": "v1.0.3", "main": "./dist/index.js", "types": "./dist/index.d.ts", "files": [ "dist" ], "scripts": { "build": "tsup", "test": "bun test src --coverage", "fmt": "bunx @biomejs/biome check --apply ./src" }, "devDependencies": { "@upstash/redis": "^1.28.3", "bun-types": "latest", "rome": "^11.0.0", "turbo": "^1.10.15", "tsup": "^7.2.0", "typescript": "^5.0.0" }, "dependencies": { "@upstash/core-analytics": "^0.0.7" }, "license": "MIT" }
|