@upstash/ratelimit 2.2.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.
package/src/multi.ts ADDED
@@ -0,0 +1,610 @@
1
+ import { Cache } from "./cache";
2
+ import { DEFAULT_PREFIX } from "./constants";
3
+ import type { Duration } from "./duration";
4
+ import { ms } from "./duration";
5
+ import { safeEval } from "./hash";
6
+ import { RESET_SCRIPT, SCRIPTS } from "./lua-scripts/hash";
7
+
8
+ import { Ratelimit } from "./ratelimit";
9
+ import { addTelemetry } from "./telemetry";
10
+ import type { Algorithm, MultiRegionContext } from "./types";
11
+
12
+ import type { Redis } from "./types";
13
+
14
+ function randomId(): string {
15
+ let result = "";
16
+ const characters =
17
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
18
+ const charactersLength = characters.length;
19
+ for (let i = 0; i < 16; i++) {
20
+ result += characters.charAt(Math.floor(Math.random() * charactersLength));
21
+ }
22
+ return result;
23
+ }
24
+
25
+ export type MultiRegionRatelimitConfig = {
26
+ /**
27
+ * Instances of `@upstash/redis`
28
+ * @see https://github.com/upstash/upstash-redis#quick-start
29
+ */
30
+ redis: Redis[];
31
+ /**
32
+ * The ratelimiter function to use.
33
+ *
34
+ * Choose one of the predefined ones or implement your own.
35
+ * Available algorithms are exposed via static methods:
36
+ * - MultiRegionRatelimit.fixedWindow
37
+ */
38
+ limiter: Algorithm<MultiRegionContext>;
39
+ /**
40
+ * All keys in redis are prefixed with this.
41
+ *
42
+ * @default `@upstash/ratelimit`
43
+ */
44
+ prefix?: string;
45
+
46
+ /**
47
+ * If enabled, the ratelimiter will keep a global cache of identifiers, that have
48
+ * exhausted their ratelimit. In serverless environments this is only possible if
49
+ * you create the ratelimiter instance outside of your handler function. While the
50
+ * function is still hot, the ratelimiter can block requests without having to
51
+ * request data from redis, thus saving time and money.
52
+ *
53
+ * Whenever an identifier has exceeded its limit, the ratelimiter will add it to an
54
+ * internal list together with its reset timestamp. If the same identifier makes a
55
+ * new request before it is reset, we can immediately reject it.
56
+ *
57
+ * Set to `false` to disable.
58
+ *
59
+ * If left undefined, a map is created automatically, but it can only work
60
+ * if the map or the ratelimit instance is created outside your serverless function handler.
61
+ */
62
+ ephemeralCache?: Map<string, number> | false;
63
+
64
+ /**
65
+ * If set, the ratelimiter will allow requests to pass after this many milliseconds.
66
+ *
67
+ * Use this if you want to allow requests in case of network problems
68
+ */
69
+ timeout?: number;
70
+
71
+ /**
72
+ * If enabled, the ratelimiter will store analytics data in redis, which you can check out at
73
+ * https://console.upstash.com/ratelimit
74
+ *
75
+ * @default false
76
+ */
77
+ analytics?: boolean;
78
+
79
+ /**
80
+ * If enabled, lua scripts will be sent to Redis with SCRIPT LOAD durint the first request.
81
+ * In the subsequent requests, hash of the script will be used to invoke it
82
+ *
83
+ * @default true
84
+ */
85
+ cacheScripts?: boolean;
86
+
87
+ /**
88
+ * If enabled, the ratelimiter will check for dynamic limits in Redis
89
+ * before applying the regular limit. This allows you to change the rate
90
+ * limit at runtime using setDynamicLimit().
91
+ *
92
+ * Note: Dynamic limits are not yet supported for multi-region rate limiters.
93
+ * This option will be ignored for MultiRegionRatelimit.
94
+ *
95
+ * @default false
96
+ */
97
+ dynamicLimits?: boolean;
98
+
99
+ /**
100
+ * Enable telemetry to help us improve the SDK.
101
+ *
102
+ * The sdk name and version are sent to Upstash as a header on the requests
103
+ * made by the redis clients you provide.
104
+ *
105
+ * Can also be disabled with the `UPSTASH_DISABLE_TELEMETRY` env variable.
106
+ *
107
+ * @default true
108
+ */
109
+ enableTelemetry?: boolean;
110
+ };
111
+
112
+ /**
113
+ * Ratelimiter using serverless redis from https://upstash.com/
114
+ *
115
+ * @example
116
+ * ```ts
117
+ * const { limit } = new MultiRegionRatelimit({
118
+ * redis: Redis.fromEnv(),
119
+ * limiter: MultiRegionRatelimit.fixedWindow(
120
+ * 10, // Allow 10 requests per window of 30 minutes
121
+ * "30 m", // interval of 30 minutes
122
+ * )
123
+ * })
124
+ *
125
+ * ```
126
+ *
127
+ * @see node_modules/@upstash/ratelimit/docs/features.mdx
128
+ */
129
+ export class MultiRegionRatelimit extends Ratelimit<MultiRegionContext> {
130
+ /**
131
+ * Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithn of your choice.
132
+ *
133
+ * @see node_modules/@upstash/ratelimit/docs/features.mdx
134
+ */
135
+ constructor(config: MultiRegionRatelimitConfig) {
136
+ super({
137
+ prefix: config.prefix,
138
+ limiter: config.limiter,
139
+ timeout: config.timeout,
140
+ analytics: config.analytics,
141
+ dynamicLimits: config.dynamicLimits,
142
+ ctx: {
143
+ regionContexts: config.redis.map((redis) => ({
144
+ redis: redis,
145
+ prefix: config.prefix ?? DEFAULT_PREFIX,
146
+ })),
147
+ cache: config.ephemeralCache
148
+ ? new Cache(config.ephemeralCache)
149
+ : undefined,
150
+ },
151
+ });
152
+
153
+ for (const redis of config.redis) {
154
+ addTelemetry(redis, config.enableTelemetry);
155
+ }
156
+
157
+ if (config.dynamicLimits) {
158
+ console.warn(
159
+ "Warning: Dynamic limits are not yet supported for multi-region rate limiters. " +
160
+ "The dynamicLimits option will be ignored."
161
+ );
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Each request inside a fixed time increases a counter.
167
+ * Once the counter reaches the maximum allowed number, all further requests are
168
+ * rejected.
169
+ *
170
+ * **Pro:**
171
+ *
172
+ * - Newer requests are not starved by old ones.
173
+ * - Low storage cost.
174
+ *
175
+ * **Con:**
176
+ *
177
+ * A burst of requests near the boundary of a window can result in a very
178
+ * high request rate because two windows will be filled with requests quickly.
179
+ *
180
+ * @param tokens - How many requests a user can make in each time window.
181
+ * @param window - A fixed timeframe
182
+ * @see node_modules/@upstash/ratelimit/docs/algorithms.mdx
183
+ */
184
+ static fixedWindow(
185
+ /**
186
+ * How many requests are allowed per window.
187
+ */
188
+ tokens: number,
189
+ /**
190
+ * The duration in which `tokens` requests are allowed.
191
+ */
192
+ window: Duration
193
+ ): Algorithm<MultiRegionContext> {
194
+ const windowDuration = ms(window);
195
+
196
+ return () => ({
197
+ async limit(ctx: MultiRegionContext, identifier: string, rate?: number) {
198
+ const requestId = randomId();
199
+ const bucket = Math.floor(Date.now() / windowDuration);
200
+ const key = [identifier, bucket].join(":");
201
+ const incrementBy = rate ?? 1;
202
+
203
+ // Only check cache block if not refunding (negative rate)
204
+ if (ctx.cache && incrementBy > 0) {
205
+ const { blocked, reset } = ctx.cache.isBlocked(identifier);
206
+ if (blocked) {
207
+ return {
208
+ success: false,
209
+ limit: tokens,
210
+ remaining: 0,
211
+ reset: reset,
212
+ pending: Promise.resolve(),
213
+ reason: "cacheBlock",
214
+ };
215
+ }
216
+ }
217
+
218
+ const dbs: { redis: Redis; request: Promise<string[]> }[] =
219
+ ctx.regionContexts.map((regionContext) => ({
220
+ redis: regionContext.redis,
221
+ request: safeEval(
222
+ regionContext,
223
+ SCRIPTS.multiRegion.fixedWindow.limit,
224
+ [key],
225
+ [requestId, windowDuration, incrementBy]
226
+ ) as Promise<string[]>,
227
+ }));
228
+
229
+ // The firstResponse is an array of string at every EVEN indexes and rate at which the tokens are used at every ODD indexes
230
+ const firstResponse = await Promise.any(dbs.map((s) => s.request));
231
+
232
+ const usedTokens = firstResponse.reduce(
233
+ (accTokens: number, usedToken, index) => {
234
+ let parsedToken = 0;
235
+ if (index % 2) {
236
+ parsedToken = Number.parseInt(usedToken);
237
+ }
238
+
239
+ return accTokens + parsedToken;
240
+ },
241
+ 0
242
+ );
243
+
244
+ const remaining = tokens - usedTokens;
245
+
246
+ /**
247
+ * If the length between two databases does not match, we sync the two databases
248
+ */
249
+ async function sync() {
250
+ const individualIDs = await Promise.all(dbs.map((s) => s.request));
251
+
252
+ const allIDs = [
253
+ ...new Set(
254
+ individualIDs.flat().reduce((acc: string[], curr, index) => {
255
+ if (index % 2 === 0) {
256
+ acc.push(curr);
257
+ }
258
+ return acc;
259
+ }, [])
260
+ ).values(),
261
+ ];
262
+
263
+ for (const db of dbs) {
264
+ const usedDbTokensRequest = await db.request;
265
+ const usedDbTokens = usedDbTokensRequest.reduce(
266
+ (accTokens: number, usedToken, index) => {
267
+ let parsedToken = 0;
268
+ if (index % 2) {
269
+ parsedToken = Number.parseInt(usedToken);
270
+ }
271
+
272
+ return accTokens + parsedToken;
273
+ },
274
+ 0
275
+ );
276
+
277
+ const dbIdsRequest = await db.request;
278
+ const dbIds = dbIdsRequest.reduce(
279
+ (ids: string[], currentId, index) => {
280
+ if (index % 2 === 0) {
281
+ ids.push(currentId);
282
+ }
283
+ return ids;
284
+ },
285
+ []
286
+ );
287
+ /**
288
+ * If the bucket in this db is already full, it doesn't matter which ids it contains.
289
+ * So we do not have to sync.
290
+ */
291
+ if (usedDbTokens >= tokens) {
292
+ continue;
293
+ }
294
+ const diff = allIDs.filter((id) => !dbIds.includes(id));
295
+ /**
296
+ * Don't waste a request if there is nothing to send
297
+ */
298
+ if (diff.length === 0) {
299
+ continue;
300
+ }
301
+
302
+ for (const requestId of diff) {
303
+ await db.redis.hset(key, { [requestId]: incrementBy });
304
+ }
305
+ }
306
+ }
307
+
308
+ /**
309
+ * Do not await sync. This should not run in the critical path.
310
+ */
311
+
312
+ const success = remaining >= 0;
313
+ const reset = (bucket + 1) * windowDuration;
314
+
315
+ if (ctx.cache) {
316
+ if (!success) {
317
+ ctx.cache.blockUntil(identifier, reset);
318
+ } else if (incrementBy < 0) {
319
+ // Successful refund: unblock from cache
320
+ ctx.cache.pop(identifier);
321
+ }
322
+ }
323
+ return {
324
+ success,
325
+ limit: tokens,
326
+ remaining,
327
+ reset,
328
+ pending: sync(),
329
+ };
330
+ },
331
+ async getRemaining(ctx: MultiRegionContext, identifier: string) {
332
+ const bucket = Math.floor(Date.now() / windowDuration);
333
+ const key = [identifier, bucket].join(":");
334
+
335
+ const dbs: { redis: Redis; request: Promise<string[]> }[] =
336
+ ctx.regionContexts.map((regionContext) => ({
337
+ redis: regionContext.redis,
338
+ request: safeEval(
339
+ regionContext,
340
+ SCRIPTS.multiRegion.fixedWindow.getRemaining,
341
+ [key],
342
+ [null]
343
+ ) as Promise<string[]>,
344
+ }));
345
+
346
+ // The firstResponse is an array of string at every EVEN indexes and rate at which the tokens are used at every ODD indexes
347
+ const firstResponse = await Promise.any(dbs.map((s) => s.request));
348
+ const usedTokens = firstResponse.reduce(
349
+ (accTokens: number, usedToken, index) => {
350
+ let parsedToken = 0;
351
+ if (index % 2) {
352
+ parsedToken = Number.parseInt(usedToken);
353
+ }
354
+
355
+ return accTokens + parsedToken;
356
+ },
357
+ 0
358
+ );
359
+
360
+ return {
361
+ remaining: Math.max(0, tokens - usedTokens),
362
+ reset: (bucket + 1) * windowDuration,
363
+ limit: tokens
364
+ };
365
+ },
366
+ async resetTokens(ctx: MultiRegionContext, identifier: string) {
367
+ const pattern = [identifier, "*"].join(":");
368
+ if (ctx.cache) {
369
+ ctx.cache.pop(identifier);
370
+ }
371
+
372
+ await Promise.all(
373
+ ctx.regionContexts.map((regionContext) => {
374
+ safeEval(regionContext, RESET_SCRIPT, [pattern], [null]);
375
+ })
376
+ );
377
+ },
378
+ });
379
+ }
380
+
381
+ /**
382
+ * Combined approach of `slidingLogs` and `fixedWindow` with lower storage
383
+ * costs than `slidingLogs` and improved boundary behavior by calculating a
384
+ * weighted score between two windows.
385
+ *
386
+ * **Pro:**
387
+ *
388
+ * Good performance allows this to scale to very high loads.
389
+ *
390
+ * **Con:**
391
+ *
392
+ * Nothing major.
393
+ *
394
+ * @param tokens - How many requests a user can make in each time window.
395
+ * @param window - The duration in which the user can max X requests.
396
+ * @see node_modules/@upstash/ratelimit/docs/algorithms.mdx
397
+ */
398
+ static slidingWindow(
399
+ /**
400
+ * How many requests are allowed per window.
401
+ */
402
+ tokens: number,
403
+ /**
404
+ * The duration in which `tokens` requests are allowed.
405
+ */
406
+ window: Duration
407
+ ): Algorithm<MultiRegionContext> {
408
+ const windowSize = ms(window);
409
+
410
+ const windowDuration = ms(window);
411
+
412
+ return () => ({
413
+ async limit(ctx: MultiRegionContext, identifier: string, rate?: number) {
414
+ const requestId = randomId();
415
+ const now = Date.now();
416
+
417
+ const currentWindow = Math.floor(now / windowSize);
418
+ const currentKey = [identifier, currentWindow].join(":");
419
+ const previousWindow = currentWindow - 1;
420
+ const previousKey = [identifier, previousWindow].join(":");
421
+ const incrementBy = rate ?? 1;
422
+
423
+ // Only check cache block if not refunding (negative rate)
424
+ if (ctx.cache && incrementBy > 0) {
425
+ const { blocked, reset } = ctx.cache.isBlocked(identifier);
426
+ if (blocked) {
427
+ return {
428
+ success: false,
429
+ limit: tokens,
430
+ remaining: 0,
431
+ reset: reset,
432
+ pending: Promise.resolve(),
433
+ reason: "cacheBlock",
434
+ };
435
+ }
436
+ }
437
+
438
+ const dbs = ctx.regionContexts.map((regionContext) => ({
439
+ redis: regionContext.redis,
440
+ request: safeEval(
441
+ regionContext,
442
+ SCRIPTS.multiRegion.slidingWindow.limit,
443
+ [currentKey, previousKey],
444
+ [tokens, now, windowDuration, requestId, incrementBy]
445
+ // lua seems to return `1` for true and `null` for false
446
+ ) as Promise<[string[], string[], 1 | null]>,
447
+ }));
448
+
449
+ const percentageInCurrent = (now % windowDuration) / windowDuration;
450
+ const [current, previous, success] = await Promise.any(
451
+ dbs.map((s) => s.request)
452
+ );
453
+
454
+ // in the case of success, the new request is not included in the current array.
455
+ // add it manually
456
+ if (success) {
457
+ current.push(requestId, incrementBy.toString());
458
+ }
459
+
460
+ const previousUsedTokens = previous.reduce(
461
+ (accTokens: number, usedToken, index) => {
462
+ let parsedToken = 0;
463
+ if (index % 2) {
464
+ parsedToken = Number.parseInt(usedToken);
465
+ }
466
+
467
+ return accTokens + parsedToken;
468
+ },
469
+ 0
470
+ );
471
+
472
+ const currentUsedTokens = current.reduce(
473
+ (accTokens: number, usedToken, index) => {
474
+ let parsedToken = 0;
475
+ if (index % 2) {
476
+ parsedToken = Number.parseInt(usedToken);
477
+ }
478
+
479
+ return accTokens + parsedToken;
480
+ },
481
+ 0
482
+ );
483
+
484
+ const previousPartialUsed = Math.ceil(
485
+ previousUsedTokens * (1 - percentageInCurrent)
486
+ );
487
+
488
+ const usedTokens = previousPartialUsed + currentUsedTokens;
489
+
490
+ const remaining = tokens - usedTokens;
491
+
492
+ /**
493
+ * If a database differs from the consensus, we sync it
494
+ */
495
+ async function sync() {
496
+ const res = await Promise.all(dbs.map((s) => s.request));
497
+
498
+ const allCurrentIds = [
499
+ ...new Set(
500
+ res
501
+ .flatMap(([current]) => current)
502
+ .reduce((acc: string[], curr, index) => {
503
+ if (index % 2 === 0) {
504
+ acc.push(curr);
505
+ }
506
+ return acc;
507
+ }, [])
508
+ ).values(),
509
+ ];
510
+
511
+ for (const db of dbs) {
512
+ const [current, _previous, _success] = await db.request;
513
+ const dbIds = current.reduce((ids: string[], currentId, index) => {
514
+ if (index % 2 === 0) {
515
+ ids.push(currentId);
516
+ }
517
+ return ids;
518
+ }, []);
519
+
520
+ const usedDbTokens = current.reduce(
521
+ (accTokens: number, usedToken, index) => {
522
+ let parsedToken = 0;
523
+ if (index % 2) {
524
+ parsedToken = Number.parseInt(usedToken);
525
+ }
526
+
527
+ return accTokens + parsedToken;
528
+ },
529
+ 0
530
+ );
531
+ /**
532
+ * If the bucket in this db is already full, it doesn't matter which ids it contains.
533
+ * So we do not have to sync.
534
+ */
535
+ if (usedDbTokens >= tokens) {
536
+ continue;
537
+ }
538
+ const diff = allCurrentIds.filter((id) => !dbIds.includes(id));
539
+ /**
540
+ * Don't waste a request if there is nothing to send
541
+ */
542
+ if (diff.length === 0) {
543
+ continue;
544
+ }
545
+
546
+ for (const requestId of diff) {
547
+ await db.redis.hset(currentKey, { [requestId]: incrementBy });
548
+ }
549
+ }
550
+ }
551
+
552
+ // const success = remaining >= 0;
553
+ const reset = (currentWindow + 1) * windowDuration;
554
+ if (ctx.cache) {
555
+ if (!success) {
556
+ ctx.cache.blockUntil(identifier, reset);
557
+ } else if (incrementBy < 0) {
558
+ // Successful refund: unblock from cache
559
+ ctx.cache.pop(identifier);
560
+ }
561
+ }
562
+ return {
563
+ success: Boolean(success),
564
+ limit: tokens,
565
+ remaining: Math.max(0, remaining),
566
+ reset,
567
+ pending: sync(),
568
+ };
569
+ },
570
+ async getRemaining(ctx: MultiRegionContext, identifier: string) {
571
+ const now = Date.now();
572
+
573
+ const currentWindow = Math.floor(now / windowSize);
574
+ const currentKey = [identifier, currentWindow].join(":");
575
+ const previousWindow = currentWindow - 1;
576
+ const previousKey = [identifier, previousWindow].join(":");
577
+
578
+ const dbs = ctx.regionContexts.map((regionContext) => ({
579
+ redis: regionContext.redis,
580
+ request: safeEval(
581
+ regionContext,
582
+ SCRIPTS.multiRegion.slidingWindow.getRemaining,
583
+ [currentKey, previousKey],
584
+ [now, windowSize]
585
+ // lua seems to return `1` for true and `null` for false
586
+ ) as Promise<number>,
587
+ }));
588
+
589
+ const usedTokens = await Promise.any(dbs.map((s) => s.request));
590
+ return {
591
+ remaining: Math.max(0, tokens - usedTokens),
592
+ reset: (currentWindow + 1) * windowSize,
593
+ limit: tokens
594
+ };
595
+ },
596
+ async resetTokens(ctx: MultiRegionContext, identifier: string) {
597
+ const pattern = [identifier, "*"].join(":");
598
+ if (ctx.cache) {
599
+ ctx.cache.pop(identifier);
600
+ }
601
+
602
+ await Promise.all(
603
+ ctx.regionContexts.map((regionContext) => {
604
+ safeEval(regionContext, RESET_SCRIPT, [pattern], [null]);
605
+ })
606
+ );
607
+ },
608
+ });
609
+ }
610
+ }