@upstash/ratelimit 2.1.0 → 2.2.1-canary.0

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.
@@ -0,0 +1,506 @@
1
+ import { Analytics } from "./analytics";
2
+ import { Cache } from "./cache";
3
+ import { DEFAULT_PREFIX, DYNAMIC_LIMIT_KEY_SUFFIX } from "./constants";
4
+ import type { Algorithm, Context, LimitOptions, LimitPayload, RatelimitResponse, Redis } from "./types";
5
+ import { checkDenyList, checkDenyListCache, defaultDeniedResponse, resolveLimitPayload } from "./deny-list/index";
6
+
7
+ export class TimeoutError extends Error {
8
+ constructor() {
9
+ super("Timeout");
10
+ this.name = "TimeoutError";
11
+ }
12
+ }
13
+ export type RatelimitConfig<TContext> = {
14
+ /**
15
+ * The ratelimiter function to use.
16
+ *
17
+ * Choose one of the predefined ones or implement your own.
18
+ * Available algorithms are exposed via static methods:
19
+ * - Ratelimiter.fixedWindow
20
+ * - Ratelimiter.slidingWindow
21
+ * - Ratelimiter.tokenBucket
22
+ */
23
+
24
+ limiter: Algorithm<TContext>;
25
+
26
+ ctx: TContext;
27
+ /**
28
+ * All keys in redis are prefixed with this.
29
+ *
30
+ * @default `@upstash/ratelimit`
31
+ */
32
+ prefix?: string;
33
+
34
+ /**
35
+ * If enabled, the ratelimiter will check for dynamic limits in Redis
36
+ * before applying the regular limit. This allows you to change the rate
37
+ * limit at runtime using setDynamicLimit().
38
+ *
39
+ * When enabled, adds +1 Redis command (GET) to every limit check.
40
+ *
41
+ * @default false
42
+ */
43
+ dynamicLimits?: boolean;
44
+
45
+ /**
46
+ * If enabled, the ratelimiter will keep a global cache of identifiers, that have
47
+ * exhausted their ratelimit. In serverless environments this is only possible if
48
+ * you create the ratelimiter instance outside of your handler function. While the
49
+ * function is still hot, the ratelimiter can block requests without having to
50
+ * request data from redis, thus saving time and money.
51
+ *
52
+ * Whenever an identifier has exceeded its limit, the ratelimiter will add it to an
53
+ * internal list together with its reset timestamp. If the same identifier makes a
54
+ * new request before it is reset, we can immediately reject it.
55
+ *
56
+ * Set to `false` to disable.
57
+ *
58
+ * If left undefined, a map is created automatically, but it can only work
59
+ * if the map or the ratelimit instance is created outside your serverless function handler.
60
+ */
61
+ ephemeralCache?: Map<string, number> | false;
62
+
63
+ /**
64
+ * If set, the ratelimiter will allow requests to pass after this many milliseconds.
65
+ *
66
+ * Use this if you want to allow requests in case of network problems
67
+ *
68
+ * @default 5000
69
+ */
70
+ timeout?: number;
71
+
72
+ /**
73
+ * If enabled, the ratelimiter will store analytics data in redis, which you can check out at
74
+ * https://console.upstash.com/ratelimit
75
+ *
76
+ * @default false
77
+ */
78
+ analytics?: boolean;
79
+
80
+ /**
81
+ * Enables deny list. If set to true, requests with identifier or ip/user-agent/countrie
82
+ * in the deny list will be rejected automatically. To edit the deny list, check out the
83
+ * ratelimit dashboard at https://console.upstash.com/ratelimit
84
+ *
85
+ * @default false
86
+ */
87
+ enableProtection?: boolean
88
+
89
+ denyListThreshold?: number
90
+ };
91
+
92
+ /**
93
+ * Ratelimiter using serverless redis from https://upstash.com/
94
+ *
95
+ * @example
96
+ * ```ts
97
+ * const { limit } = new Ratelimit({
98
+ * redis: Redis.fromEnv(),
99
+ * limiter: Ratelimit.slidingWindow(
100
+ * 10, // Allow 10 requests per window of 30 minutes
101
+ * "30 m", // interval of 30 minutes
102
+ * ),
103
+ * })
104
+ *
105
+ * ```
106
+ */
107
+ export abstract class Ratelimit<TContext extends Context> {
108
+ protected readonly limiter: Algorithm<TContext>;
109
+
110
+ protected readonly ctx: TContext;
111
+
112
+ protected readonly prefix: string;
113
+
114
+ protected readonly timeout: number;
115
+
116
+ protected readonly primaryRedis: Redis;
117
+
118
+ protected readonly analytics?: Analytics;
119
+
120
+ protected readonly enableProtection: boolean;
121
+
122
+ protected readonly denyListThreshold: number
123
+
124
+ protected readonly dynamicLimits: boolean;
125
+
126
+ constructor(config: RatelimitConfig<TContext>) {
127
+ this.ctx = config.ctx;
128
+ this.limiter = config.limiter;
129
+ this.timeout = config.timeout ?? 5000;
130
+ this.prefix = config.prefix ?? DEFAULT_PREFIX;
131
+ this.dynamicLimits = config.dynamicLimits ?? false;
132
+
133
+ this.enableProtection = config.enableProtection ?? false;
134
+ this.denyListThreshold = config.denyListThreshold ?? 6;
135
+
136
+ this.primaryRedis = ("redis" in this.ctx) ? this.ctx.redis : this.ctx.regionContexts[0].redis;
137
+
138
+ // Pass dynamicLimits and prefix to context if it's a RegionContext
139
+ if ("redis" in this.ctx) {
140
+ this.ctx.dynamicLimits = this.dynamicLimits;
141
+ this.ctx.prefix = this.prefix;
142
+ }
143
+ this.analytics = config.analytics
144
+ ? new Analytics({
145
+ redis: this.primaryRedis,
146
+ prefix: this.prefix,
147
+ })
148
+ : undefined;
149
+
150
+ if (config.ephemeralCache instanceof Map) {
151
+ this.ctx.cache = new Cache(config.ephemeralCache);
152
+ } else if (config.ephemeralCache === undefined) {
153
+ this.ctx.cache = new Cache(new Map());
154
+ }
155
+ }
156
+
157
+ /**
158
+ * Determine if a request should pass or be rejected based on the identifier and previously chosen ratelimit.
159
+ *
160
+ * Use this if you want to reject all requests that you can not handle right now.
161
+ *
162
+ * @example
163
+ * ```ts
164
+ * const ratelimit = new Ratelimit({
165
+ * redis: Redis.fromEnv(),
166
+ * limiter: Ratelimit.slidingWindow(10, "10 s")
167
+ * })
168
+ *
169
+ * const { success } = await ratelimit.limit(id)
170
+ * if (!success){
171
+ * return "Nope"
172
+ * }
173
+ * return "Yes"
174
+ * ```
175
+ *
176
+ * @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.
177
+ *
178
+ * Usage with `req.rate`
179
+ * @example
180
+ * ```ts
181
+ * const ratelimit = new Ratelimit({
182
+ * redis: Redis.fromEnv(),
183
+ * limiter: Ratelimit.slidingWindow(100, "10 s")
184
+ * })
185
+ *
186
+ * const { success } = await ratelimit.limit(id, {rate: 10})
187
+ * if (!success){
188
+ * return "Nope"
189
+ * }
190
+ * return "Yes"
191
+ * ```
192
+ *
193
+ * @see node_modules/@upstash/ratelimit/docs/methods.mdx
194
+ */
195
+ public limit = async (
196
+ identifier: string,
197
+ req?: LimitOptions,
198
+ ): Promise<RatelimitResponse> => {
199
+
200
+ let timeoutId: any = null;
201
+ try {
202
+ const response = this.getRatelimitResponse(identifier, req);
203
+ const { responseArray, newTimeoutId } = this.applyTimeout(response);
204
+ timeoutId = newTimeoutId;
205
+
206
+ const timedResponse = await Promise.race(responseArray);
207
+ const finalResponse = this.submitAnalytics(timedResponse, identifier, req);
208
+ return finalResponse;
209
+ } finally {
210
+ if (timeoutId) {
211
+ clearTimeout(timeoutId);
212
+ }
213
+ }
214
+ };
215
+
216
+ /**
217
+ * Block until the request may pass or timeout is reached.
218
+ *
219
+ * This method returns a promise that resolves as soon as the request may be processed
220
+ * or after the timeout has been reached.
221
+ *
222
+ * Use this if you want to delay the request until it is ready to get processed.
223
+ *
224
+ * @example
225
+ * ```ts
226
+ * const ratelimit = new Ratelimit({
227
+ * redis: Redis.fromEnv(),
228
+ * limiter: Ratelimit.slidingWindow(10, "10 s")
229
+ * })
230
+ *
231
+ * const { success } = await ratelimit.blockUntilReady(id, 60_000)
232
+ * if (!success){
233
+ * return "Nope"
234
+ * }
235
+ * return "Yes"
236
+ * ```
237
+ *
238
+ * @see node_modules/@upstash/ratelimit/docs/methods.mdx
239
+ */
240
+ public blockUntilReady = async (
241
+ /**
242
+ * An identifier per user or api.
243
+ * Choose a userID, or api token, or ip address.
244
+ *
245
+ * If you want to limit your api across all users, you can set a constant string.
246
+ */
247
+ identifier: string,
248
+ /**
249
+ * Maximum duration to wait in milliseconds.
250
+ * After this time the request will be denied.
251
+ */
252
+ timeout: number,
253
+ ): Promise<RatelimitResponse> => {
254
+ if (timeout <= 0) {
255
+ throw new Error("timeout must be positive");
256
+ }
257
+ let res: RatelimitResponse;
258
+
259
+ const deadline = Date.now() + timeout;
260
+ while (true) {
261
+ res = await this.limit(identifier);
262
+ if (res.success) {
263
+ break;
264
+ }
265
+ if (res.reset === 0) {
266
+ throw new Error("This should not happen");
267
+ }
268
+
269
+ // `reset` can already be in the past: the window turned over between the
270
+ // limit call and this line, or the client clock runs ahead of the server's.
271
+ // Passing the resulting negative delay to setTimeout makes Node use 1ms and
272
+ // emit a TimeoutNegativeWarning, so the wait becomes a hot poll loop until
273
+ // the deadline.
274
+ const wait = Math.min(res.reset, deadline) - Date.now();
275
+ await new Promise((r) => setTimeout(r, wait > 0 ? wait : 100));
276
+
277
+ if (Date.now() > deadline) {
278
+ break;
279
+ }
280
+ }
281
+ return res!;
282
+ };
283
+
284
+ /**
285
+ * @see node_modules/@upstash/ratelimit/docs/methods.mdx
286
+ */
287
+ public resetUsedTokens = async (identifier: string) => {
288
+ const pattern = [this.prefix, identifier].join(":");
289
+ await this.limiter().resetTokens(this.ctx, pattern);
290
+ };
291
+
292
+ /**
293
+ * Returns the remaining token count together with a reset timestamps
294
+ *
295
+ * @param identifier identifir to check
296
+ * @returns object with `remaining`, `reset`, and `limit` fields. `remaining` denotes
297
+ * the remaining tokens, `limit` is the effective limit (considering dynamic
298
+ * limits if enabled), and `reset` denotes the timestamp when the tokens reset.
299
+ *
300
+ * @see node_modules/@upstash/ratelimit/docs/methods.mdx
301
+ */
302
+ public getRemaining = async (identifier: string): Promise<{
303
+ remaining: number;
304
+ reset: number;
305
+ limit: number;
306
+ }> => {
307
+ const pattern = [this.prefix, identifier].join(":");
308
+
309
+ return await this.limiter().getRemaining(this.ctx, pattern);
310
+ };
311
+
312
+ /**
313
+ * Checks if the identifier or the values in req are in the deny list cache.
314
+ * If so, returns the default denied response.
315
+ *
316
+ * Otherwise, calls redis to check the rate limit and deny list. Returns after
317
+ * resolving the result. Resolving is overriding the rate limit result if
318
+ * the some value is in deny list.
319
+ *
320
+ * @param identifier identifier to block
321
+ * @param req options with ip, user agent, country, rate and geo info
322
+ * @returns rate limit response
323
+ */
324
+ private getRatelimitResponse = async (
325
+ identifier: string,
326
+ req?: LimitOptions
327
+ ): Promise<RatelimitResponse> => {
328
+ const key = this.getKey(identifier);
329
+ const definedMembers = this.getDefinedMembers(identifier, req);
330
+
331
+ const deniedValue = checkDenyListCache(definedMembers)
332
+
333
+ const result: LimitPayload = deniedValue ? [defaultDeniedResponse(deniedValue), { deniedValue, invalidIpDenyList: false }] : (await Promise.all([
334
+ this.limiter().limit(this.ctx, key, req?.rate),
335
+ this.enableProtection
336
+ ? checkDenyList(this.primaryRedis, this.prefix, definedMembers)
337
+ : { deniedValue: undefined, invalidIpDenyList: false }
338
+ ]));
339
+
340
+ return resolveLimitPayload(this.primaryRedis, this.prefix, result, this.denyListThreshold)
341
+ };
342
+
343
+ /**
344
+ * Creates an array with the original response promise and a timeout promise
345
+ * if this.timeout > 0.
346
+ *
347
+ * @param response Ratelimit response promise
348
+ * @returns array with the response and timeout promise. also includes the timeout id
349
+ */
350
+ private applyTimeout = (response: Promise<RatelimitResponse>) => {
351
+ let newTimeoutId: any = null;
352
+ const responseArray: Array<Promise<RatelimitResponse>> = [response];
353
+
354
+ if (this.timeout > 0) {
355
+ const timeoutResponse = new Promise<RatelimitResponse>((resolve) => {
356
+ newTimeoutId = setTimeout(() => {
357
+ resolve({
358
+ success: true,
359
+ limit: 0,
360
+ remaining: 0,
361
+ reset: 0,
362
+ pending: Promise.resolve(),
363
+ reason: "timeout"
364
+ });
365
+ }, this.timeout);
366
+ })
367
+ responseArray.push(timeoutResponse);
368
+ }
369
+
370
+ return {
371
+ responseArray,
372
+ newTimeoutId,
373
+ }
374
+ }
375
+
376
+ /**
377
+ * submits analytics if this.analytics is set
378
+ *
379
+ * @param ratelimitResponse final rate limit response
380
+ * @param identifier identifier to submit
381
+ * @param req limit options
382
+ * @returns rate limit response after updating the .pending field
383
+ */
384
+ private submitAnalytics = (
385
+ ratelimitResponse: RatelimitResponse,
386
+ identifier: string,
387
+ req?: Pick<LimitOptions, "geo">,
388
+ ) => {
389
+ if (this.analytics) {
390
+ try {
391
+ const geo = req ? this.analytics.extractGeo(req) : undefined;
392
+ const analyticsP = this.analytics
393
+ .record({
394
+ identifier: ratelimitResponse.reason === "denyList" // if in denyList, use denied value as identifier
395
+ ? ratelimitResponse.deniedValue!
396
+ : identifier,
397
+ time: Date.now(),
398
+ success: ratelimitResponse.reason === "denyList" // if in denyList, label success as "denied"
399
+ ? "denied"
400
+ : ratelimitResponse.success,
401
+ ...geo,
402
+ })
403
+ .catch((error) => {
404
+ let errorMessage = "Failed to record analytics"
405
+ if (`${error}`.includes("WRONGTYPE")) {
406
+ errorMessage = `
407
+ Failed to record analytics. See the information below:
408
+
409
+ This can occur when you uprade to Ratelimit version 1.1.2
410
+ or later from an earlier version.
411
+
412
+ This occurs simply because the way we store analytics data
413
+ has changed. To avoid getting this error, disable analytics
414
+ for *an hour*, then simply enable it back.\n
415
+ `
416
+ }
417
+ console.warn(errorMessage, error);
418
+ });
419
+ ratelimitResponse.pending = Promise.all([ratelimitResponse.pending, analyticsP]);
420
+ } catch (error) {
421
+ console.warn("Failed to record analytics", error);
422
+ };
423
+ };
424
+ return ratelimitResponse;
425
+ }
426
+
427
+ private getKey = (identifier: string): string => {
428
+ return [this.prefix, identifier].join(":");
429
+ }
430
+
431
+ /**
432
+ * returns a list of defined values from
433
+ * [identifier, req.ip, req.userAgent, req.country]
434
+ *
435
+ * @param identifier identifier
436
+ * @param req limit options
437
+ * @returns list of defined values
438
+ */
439
+ private getDefinedMembers = (
440
+ identifier: string,
441
+ req?: Pick<LimitOptions, "ip" | "userAgent" | "country">
442
+ ): string[] => {
443
+ const members = [identifier, req?.ip, req?.userAgent, req?.country];
444
+ return (members as string[]).filter(Boolean);
445
+ }
446
+
447
+ /**
448
+ * Set a dynamic rate limit globally.
449
+ *
450
+ * When dynamicLimits is enabled, this limit will override the default limit
451
+ * set in the constructor for all requests.
452
+ *
453
+ * @example
454
+ * ```ts
455
+ * const ratelimit = new Ratelimit({
456
+ * redis: Redis.fromEnv(),
457
+ * limiter: Ratelimit.slidingWindow(10, "10 s"),
458
+ * dynamicLimits: true
459
+ * });
460
+ *
461
+ * // Set global dynamic limit to 120 requests
462
+ * await ratelimit.setDynamicLimit({ limit: 120 });
463
+ *
464
+ * // Disable dynamic limit (falls back to default)
465
+ * await ratelimit.setDynamicLimit({ limit: false });
466
+ * ```
467
+ *
468
+ * @param options.limit - The new rate limit to apply globally, or false to disable
469
+ * @see node_modules/@upstash/ratelimit/docs/methods.mdx
470
+ */
471
+ public setDynamicLimit = async (options: { limit: number | false }): Promise<void> => {
472
+ if (!this.dynamicLimits) {
473
+ throw new Error(
474
+ "dynamicLimits must be enabled in the Ratelimit constructor to use setDynamicLimit()"
475
+ );
476
+ }
477
+
478
+ const globalKey = `${this.prefix}${DYNAMIC_LIMIT_KEY_SUFFIX}`;
479
+
480
+ await (options.limit === false ? this.primaryRedis.del(globalKey) : this.primaryRedis.set(globalKey, options.limit));
481
+ };
482
+
483
+ /**
484
+ * Get the current global dynamic rate limit.
485
+ *
486
+ * @example
487
+ * ```ts
488
+ * const { dynamicLimit } = await ratelimit.getDynamicLimit();
489
+ * console.log(dynamicLimit); // 120 or null if not set
490
+ * ```
491
+ *
492
+ * @returns Object containing the current global dynamic limit, or null if not set
493
+ * @see node_modules/@upstash/ratelimit/docs/methods.mdx
494
+ */
495
+ public getDynamicLimit = async (): Promise<{ dynamicLimit: number | null }> => {
496
+ if (!this.dynamicLimits) {
497
+ throw new Error(
498
+ "dynamicLimits must be enabled in the Ratelimit constructor to use getDynamicLimit()"
499
+ );
500
+ }
501
+
502
+ const globalKey = `${this.prefix}${DYNAMIC_LIMIT_KEY_SUFFIX}`;
503
+ const result = await this.primaryRedis.get(globalKey);
504
+ return { dynamicLimit: result === null ? null : Number(result) };
505
+ };
506
+ }