@upstash/ratelimit 0.4.4 → 0.4.5-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.
Files changed (93) hide show
  1. package/.github/actions/redis/action.yaml +58 -0
  2. package/.github/img/dashboard.png +0 -0
  3. package/.github/workflows/release.yml +46 -0
  4. package/.github/workflows/stale.yaml +31 -0
  5. package/.github/workflows/tests.yaml +79 -0
  6. package/README.md +9 -2
  7. package/biome.json +37 -0
  8. package/bun.lockb +0 -0
  9. package/cmd/set-version.js +14 -0
  10. package/examples/cloudflare-workers/package.json +18 -0
  11. package/examples/cloudflare-workers/src/index.ts +35 -0
  12. package/examples/cloudflare-workers/tsconfig.json +105 -0
  13. package/examples/cloudflare-workers/wrangler.toml +3 -0
  14. package/examples/nextjs/LICENSE +21 -0
  15. package/examples/nextjs/README.md +17 -0
  16. package/examples/nextjs/components/Breadcrumb.tsx +67 -0
  17. package/examples/nextjs/components/Header.tsx +18 -0
  18. package/examples/nextjs/components/ReadBlogPost.tsx +9 -0
  19. package/examples/nextjs/components/StarButton.tsx +27 -0
  20. package/examples/nextjs/middleware.ts +35 -0
  21. package/examples/nextjs/next-env.d.ts +5 -0
  22. package/examples/nextjs/package.json +27 -0
  23. package/examples/nextjs/pages/_app.tsx +47 -0
  24. package/examples/nextjs/pages/api/blocked.ts +6 -0
  25. package/examples/nextjs/pages/api/hello.ts +5 -0
  26. package/examples/nextjs/pages/index.tsx +62 -0
  27. package/examples/nextjs/postcss.config.js +6 -0
  28. package/examples/nextjs/public/favicon.ico +0 -0
  29. package/examples/nextjs/public/github.svg +11 -0
  30. package/examples/nextjs/public/upstash.svg +27 -0
  31. package/examples/nextjs/styles/globals.css +76 -0
  32. package/examples/nextjs/tailwind.config.js +19 -0
  33. package/examples/nextjs/tsconfig.json +21 -0
  34. package/examples/nextjs13/README.md +38 -0
  35. package/examples/nextjs13/app/favicon.ico +0 -0
  36. package/examples/nextjs13/app/globals.css +107 -0
  37. package/examples/nextjs13/app/layout.tsx +18 -0
  38. package/examples/nextjs13/app/page.module.css +271 -0
  39. package/examples/nextjs13/app/route.tsx +14 -0
  40. package/examples/nextjs13/next.config.js +8 -0
  41. package/examples/nextjs13/package.json +22 -0
  42. package/examples/nextjs13/public/next.svg +1 -0
  43. package/examples/nextjs13/public/thirteen.svg +1 -0
  44. package/examples/nextjs13/public/vercel.svg +1 -0
  45. package/examples/nextjs13/tsconfig.json +28 -0
  46. package/examples/remix/.env.example +2 -0
  47. package/examples/remix/.eslintrc.js +4 -0
  48. package/examples/remix/README.md +59 -0
  49. package/examples/remix/app/root.tsx +25 -0
  50. package/examples/remix/app/routes/index.tsx +47 -0
  51. package/examples/remix/package.json +32 -0
  52. package/examples/remix/public/favicon.ico +0 -0
  53. package/examples/remix/remix.config.js +12 -0
  54. package/examples/remix/remix.env.d.ts +2 -0
  55. package/examples/remix/server.js +4 -0
  56. package/examples/remix/tsconfig.json +22 -0
  57. package/examples/with-vercel-kv/README.md +51 -0
  58. package/examples/with-vercel-kv/app/favicon.ico +0 -0
  59. package/examples/with-vercel-kv/app/globals.css +27 -0
  60. package/examples/with-vercel-kv/app/layout.tsx +21 -0
  61. package/examples/with-vercel-kv/app/page.tsx +71 -0
  62. package/examples/with-vercel-kv/next.config.js +8 -0
  63. package/examples/with-vercel-kv/package.json +25 -0
  64. package/examples/with-vercel-kv/postcss.config.js +6 -0
  65. package/examples/with-vercel-kv/public/next.svg +1 -0
  66. package/examples/with-vercel-kv/public/vercel.svg +1 -0
  67. package/examples/with-vercel-kv/tailwind.config.js +17 -0
  68. package/examples/with-vercel-kv/tsconfig.json +28 -0
  69. package/package.json +12 -33
  70. package/src/analytics.test.ts +23 -0
  71. package/src/analytics.ts +92 -0
  72. package/src/blockUntilReady.test.ts +56 -0
  73. package/src/cache.test.ts +41 -0
  74. package/src/cache.ts +43 -0
  75. package/src/duration.test.ts +23 -0
  76. package/src/duration.ts +30 -0
  77. package/src/index.ts +17 -0
  78. package/src/multi.ts +365 -0
  79. package/src/ratelimit.test.ts +155 -0
  80. package/src/ratelimit.ts +238 -0
  81. package/src/single.ts +487 -0
  82. package/src/test_utils.ts +65 -0
  83. package/src/tools/seed.ts +37 -0
  84. package/src/types.ts +78 -0
  85. package/src/version.ts +1 -0
  86. package/tsconfig.json +103 -0
  87. package/tsup.config.js +11 -0
  88. package/turbo.json +16 -0
  89. package/dist/index.d.ts +0 -556
  90. package/dist/index.js +0 -832
  91. package/dist/index.js.map +0 -1
  92. package/dist/index.mjs +0 -803
  93. package/dist/index.mjs.map +0 -1
package/dist/index.mjs DELETED
@@ -1,803 +0,0 @@
1
- // src/analytics.ts
2
- import { Analytics as CoreAnalytics } from "@upstash/core-analytics";
3
- var Analytics = class {
4
- analytics;
5
- table = "events";
6
- constructor(config) {
7
- this.analytics = new CoreAnalytics({
8
- // @ts-expect-error we need to fix the types in core-analytics, it should only require the methods it needs, not the whole sdk
9
- redis: config.redis,
10
- window: "1h",
11
- prefix: config.prefix ?? "@upstash/ratelimit",
12
- retention: "90d"
13
- });
14
- }
15
- /**
16
- * Try to extract the geo information from the request
17
- *
18
- * This handles Vercel's `req.geo` and and Cloudflare's `request.cf` properties
19
- * @param req
20
- * @returns
21
- */
22
- extractGeo(req) {
23
- if (typeof req.geo !== "undefined") {
24
- return req.geo;
25
- }
26
- if (typeof req.cf !== "undefined") {
27
- return req.cf;
28
- }
29
- return {};
30
- }
31
- async record(event) {
32
- await this.analytics.ingest(this.table, event);
33
- }
34
- async series(filter, cutoff) {
35
- const records = await this.analytics.query(this.table, {
36
- filter: [filter],
37
- range: [cutoff, Date.now()]
38
- });
39
- return records;
40
- }
41
- async getUsage(cutoff = 0) {
42
- const records = await this.analytics.aggregateBy(this.table, "identifier", {
43
- range: [cutoff, Date.now()]
44
- });
45
- const usage = {};
46
- for (const bucket of records) {
47
- for (const [k, v] of Object.entries(bucket)) {
48
- if (k === "time") {
49
- continue;
50
- }
51
- if (!usage[k]) {
52
- usage[k] = { success: 0, blocked: 0 };
53
- }
54
- usage[k].success += v["true"] ?? 0;
55
- usage[k].blocked += v["false"] ?? 0;
56
- }
57
- }
58
- return usage;
59
- }
60
- };
61
-
62
- // src/cache.ts
63
- var Cache = class {
64
- /**
65
- * Stores identifier -> reset (in milliseconds)
66
- */
67
- cache;
68
- constructor(cache) {
69
- this.cache = cache;
70
- }
71
- isBlocked(identifier) {
72
- if (!this.cache.has(identifier)) {
73
- return { blocked: false, reset: 0 };
74
- }
75
- const reset = this.cache.get(identifier);
76
- if (reset < Date.now()) {
77
- this.cache.delete(identifier);
78
- return { blocked: false, reset: 0 };
79
- }
80
- return { blocked: true, reset };
81
- }
82
- blockUntil(identifier, reset) {
83
- this.cache.set(identifier, reset);
84
- }
85
- set(key, value) {
86
- this.cache.set(key, value);
87
- }
88
- get(key) {
89
- return this.cache.get(key) || null;
90
- }
91
- incr(key) {
92
- let value = this.cache.get(key) ?? 0;
93
- value += 1;
94
- this.cache.set(key, value);
95
- return value;
96
- }
97
- };
98
-
99
- // src/duration.ts
100
- function ms(d) {
101
- const match = d.match(/^(\d+)\s?(ms|s|m|h|d)$/);
102
- if (!match) {
103
- throw new Error(`Unable to parse window size: ${d}`);
104
- }
105
- const time = parseInt(match[1]);
106
- const unit = match[2];
107
- switch (unit) {
108
- case "ms":
109
- return time;
110
- case "s":
111
- return time * 1e3;
112
- case "m":
113
- return time * 1e3 * 60;
114
- case "h":
115
- return time * 1e3 * 60 * 60;
116
- case "d":
117
- return time * 1e3 * 60 * 60 * 24;
118
- default:
119
- throw new Error(`Unable to parse window size: ${d}`);
120
- }
121
- }
122
-
123
- // src/ratelimit.ts
124
- var Ratelimit = class {
125
- limiter;
126
- ctx;
127
- prefix;
128
- timeout;
129
- analytics;
130
- constructor(config) {
131
- this.ctx = config.ctx;
132
- this.limiter = config.limiter;
133
- this.timeout = config.timeout ?? 5e3;
134
- this.prefix = config.prefix ?? "@upstash/ratelimit";
135
- this.analytics = config.analytics ? new Analytics({
136
- redis: Array.isArray(this.ctx.redis) ? this.ctx.redis[0] : this.ctx.redis,
137
- prefix: this.prefix
138
- }) : void 0;
139
- if (config.ephemeralCache instanceof Map) {
140
- this.ctx.cache = new Cache(config.ephemeralCache);
141
- } else if (typeof config.ephemeralCache === "undefined") {
142
- this.ctx.cache = new Cache(/* @__PURE__ */ new Map());
143
- }
144
- }
145
- /**
146
- * Determine if a request should pass or be rejected based on the identifier and previously chosen ratelimit.
147
- *
148
- * Use this if you want to reject all requests that you can not handle right now.
149
- *
150
- * @example
151
- * ```ts
152
- * const ratelimit = new Ratelimit({
153
- * redis: Redis.fromEnv(),
154
- * limiter: Ratelimit.slidingWindow(10, "10 s")
155
- * })
156
- *
157
- * const { success } = await ratelimit.limit(id)
158
- * if (!success){
159
- * return "Nope"
160
- * }
161
- * return "Yes"
162
- * ```
163
- */
164
- limit = async (identifier, req) => {
165
- const key = [this.prefix, identifier].join(":");
166
- let timeoutId = null;
167
- try {
168
- const arr = [this.limiter(this.ctx, key)];
169
- if (this.timeout > 0) {
170
- arr.push(
171
- new Promise((resolve) => {
172
- timeoutId = setTimeout(() => {
173
- resolve({
174
- success: true,
175
- limit: 0,
176
- remaining: 0,
177
- reset: 0,
178
- pending: Promise.resolve()
179
- });
180
- }, this.timeout);
181
- })
182
- );
183
- }
184
- const res = await Promise.race(arr);
185
- if (this.analytics) {
186
- try {
187
- const geo = req ? this.analytics.extractGeo(req) : void 0;
188
- const analyticsP = this.analytics.record({
189
- identifier,
190
- time: Date.now(),
191
- success: res.success,
192
- ...geo
193
- }).catch((err) => {
194
- console.warn("Failed to record analytics", err);
195
- });
196
- res.pending = Promise.all([res.pending, analyticsP]);
197
- } catch (err) {
198
- console.warn("Failed to record analytics", err);
199
- }
200
- }
201
- return res;
202
- } finally {
203
- if (timeoutId) {
204
- clearTimeout(timeoutId);
205
- }
206
- }
207
- };
208
- /**
209
- * Block until the request may pass or timeout is reached.
210
- *
211
- * This method returns a promise that resolves as soon as the request may be processed
212
- * or after the timeout has been reached.
213
- *
214
- * Use this if you want to delay the request until it is ready to get processed.
215
- *
216
- * @example
217
- * ```ts
218
- * const ratelimit = new Ratelimit({
219
- * redis: Redis.fromEnv(),
220
- * limiter: Ratelimit.slidingWindow(10, "10 s")
221
- * })
222
- *
223
- * const { success } = await ratelimit.blockUntilReady(id, 60_000)
224
- * if (!success){
225
- * return "Nope"
226
- * }
227
- * return "Yes"
228
- * ```
229
- */
230
- blockUntilReady = async (identifier, timeout) => {
231
- if (timeout <= 0) {
232
- throw new Error("timeout must be positive");
233
- }
234
- let res;
235
- const deadline = Date.now() + timeout;
236
- while (true) {
237
- res = await this.limit(identifier);
238
- if (res.success) {
239
- break;
240
- }
241
- if (res.reset === 0) {
242
- throw new Error("This should not happen");
243
- }
244
- const wait = Math.min(res.reset, deadline) - Date.now();
245
- await new Promise((r) => setTimeout(r, wait));
246
- if (Date.now() > deadline) {
247
- break;
248
- }
249
- }
250
- return res;
251
- };
252
- };
253
-
254
- // src/multi.ts
255
- function randomId() {
256
- let result = "";
257
- const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
258
- const charactersLength = characters.length;
259
- for (let i = 0; i < 16; i++) {
260
- result += characters.charAt(Math.floor(Math.random() * charactersLength));
261
- }
262
- return result;
263
- }
264
- var MultiRegionRatelimit = class extends Ratelimit {
265
- /**
266
- * Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithn of your choice.
267
- */
268
- constructor(config) {
269
- super({
270
- prefix: config.prefix,
271
- limiter: config.limiter,
272
- timeout: config.timeout,
273
- analytics: config.analytics,
274
- ctx: {
275
- redis: config.redis,
276
- cache: config.ephemeralCache ? new Cache(config.ephemeralCache) : void 0
277
- }
278
- });
279
- }
280
- /**
281
- * Each request inside a fixed time increases a counter.
282
- * Once the counter reaches the maximum allowed number, all further requests are
283
- * rejected.
284
- *
285
- * **Pro:**
286
- *
287
- * - Newer requests are not starved by old ones.
288
- * - Low storage cost.
289
- *
290
- * **Con:**
291
- *
292
- * A burst of requests near the boundary of a window can result in a very
293
- * high request rate because two windows will be filled with requests quickly.
294
- *
295
- * @param tokens - How many requests a user can make in each time window.
296
- * @param window - A fixed timeframe
297
- */
298
- static fixedWindow(tokens, window) {
299
- const windowDuration = ms(window);
300
- const script = `
301
- local key = KEYS[1]
302
- local id = ARGV[1]
303
- local window = ARGV[2]
304
-
305
- redis.call("SADD", key, id)
306
- local members = redis.call("SMEMBERS", key)
307
- if #members == 1 then
308
- -- The first time this key is set, the value will be 1.
309
- -- So we only need the expire command once
310
- redis.call("PEXPIRE", key, window)
311
- end
312
-
313
- return members
314
- `;
315
- return async function(ctx, identifier) {
316
- if (ctx.cache) {
317
- const { blocked, reset: reset2 } = ctx.cache.isBlocked(identifier);
318
- if (blocked) {
319
- return {
320
- success: false,
321
- limit: tokens,
322
- remaining: 0,
323
- reset: reset2,
324
- pending: Promise.resolve()
325
- };
326
- }
327
- }
328
- const requestID = randomId();
329
- const bucket = Math.floor(Date.now() / windowDuration);
330
- const key = [identifier, bucket].join(":");
331
- const dbs = ctx.redis.map((redis) => ({
332
- redis,
333
- request: redis.eval(script, [key], [requestID, windowDuration])
334
- }));
335
- const firstResponse = await Promise.any(dbs.map((s) => s.request));
336
- const usedTokens = firstResponse.length;
337
- const remaining = tokens - usedTokens - 1;
338
- async function sync() {
339
- const individualIDs = await Promise.all(dbs.map((s) => s.request));
340
- const allIDs = Array.from(new Set(individualIDs.flatMap((_) => _)).values());
341
- for (const db of dbs) {
342
- const ids = await db.request;
343
- if (ids.length >= tokens) {
344
- continue;
345
- }
346
- const diff = allIDs.filter((id) => !ids.includes(id));
347
- if (diff.length === 0) {
348
- continue;
349
- }
350
- await db.redis.sadd(key, ...allIDs);
351
- }
352
- }
353
- const success = remaining > 0;
354
- const reset = (bucket + 1) * windowDuration;
355
- if (ctx.cache && !success) {
356
- ctx.cache.blockUntil(identifier, reset);
357
- }
358
- return {
359
- success,
360
- limit: tokens,
361
- remaining,
362
- reset,
363
- pending: sync()
364
- };
365
- };
366
- }
367
- /**
368
- * Combined approach of `slidingLogs` and `fixedWindow` with lower storage
369
- * costs than `slidingLogs` and improved boundary behavior by calculating a
370
- * weighted score between two windows.
371
- *
372
- * **Pro:**
373
- *
374
- * Good performance allows this to scale to very high loads.
375
- *
376
- * **Con:**
377
- *
378
- * Nothing major.
379
- *
380
- * @param tokens - How many requests a user can make in each time window.
381
- * @param window - The duration in which the user can max X requests.
382
- */
383
- static slidingWindow(tokens, window) {
384
- const windowSize = ms(window);
385
- const script = `
386
- local currentKey = KEYS[1] -- identifier including prefixes
387
- local previousKey = KEYS[2] -- key of the previous bucket
388
- local tokens = tonumber(ARGV[1]) -- tokens per window
389
- local now = ARGV[2] -- current timestamp in milliseconds
390
- local window = ARGV[3] -- interval in milliseconds
391
- local requestID = ARGV[4] -- uuid for this request
392
-
393
-
394
- local currentMembers = redis.call("SMEMBERS", currentKey)
395
- local requestsInCurrentWindow = #currentMembers
396
- local previousMembers = redis.call("SMEMBERS", previousKey)
397
- local requestsInPreviousWindow = #previousMembers
398
-
399
- local percentageInCurrent = ( now % window) / window
400
- if requestsInPreviousWindow * ( 1 - percentageInCurrent ) + requestsInCurrentWindow >= tokens then
401
- return {currentMembers, previousMembers}
402
- end
403
-
404
- redis.call("SADD", currentKey, requestID)
405
- table.insert(currentMembers, requestID)
406
- if requestsInCurrentWindow == 0 then
407
- -- The first time this key is set, the value will be 1.
408
- -- So we only need the expire command once
409
- redis.call("PEXPIRE", currentKey, window * 2 + 1000) -- Enough time to overlap with a new window + 1 second
410
- end
411
- return {currentMembers, previousMembers}
412
- `;
413
- const windowDuration = ms(window);
414
- return async function(ctx, identifier) {
415
- if (ctx.cache) {
416
- const { blocked, reset: reset2 } = ctx.cache.isBlocked(identifier);
417
- if (blocked) {
418
- return {
419
- success: false,
420
- limit: tokens,
421
- remaining: 0,
422
- reset: reset2,
423
- pending: Promise.resolve()
424
- };
425
- }
426
- }
427
- const requestID = randomId();
428
- const now = Date.now();
429
- const currentWindow = Math.floor(now / windowSize);
430
- const currentKey = [identifier, currentWindow].join(":");
431
- const previousWindow = currentWindow - 1;
432
- const previousKey = [identifier, previousWindow].join(":");
433
- const dbs = ctx.redis.map((redis) => ({
434
- redis,
435
- request: redis.eval(script, [currentKey, previousKey], [tokens, now, windowDuration, requestID])
436
- }));
437
- const percentageInCurrent = now % windowDuration / windowDuration;
438
- const [current, previous] = await Promise.any(dbs.map((s) => s.request));
439
- const usedTokens = previous.length * (1 - percentageInCurrent) + current.length;
440
- const remaining = tokens - usedTokens;
441
- async function sync() {
442
- const [individualIDs] = await Promise.all(dbs.map((s) => s.request));
443
- const allIDs = Array.from(new Set(individualIDs.flatMap((_) => _)).values());
444
- for (const db of dbs) {
445
- const [ids] = await db.request;
446
- if (ids.length >= tokens) {
447
- continue;
448
- }
449
- const diff = allIDs.filter((id) => !ids.includes(id));
450
- if (diff.length === 0) {
451
- continue;
452
- }
453
- await db.redis.sadd(currentKey, ...allIDs);
454
- }
455
- }
456
- const success = remaining > 0;
457
- const reset = (currentWindow + 1) * windowDuration;
458
- if (ctx.cache && !success) {
459
- ctx.cache.blockUntil(identifier, reset);
460
- }
461
- return {
462
- success,
463
- limit: tokens,
464
- remaining,
465
- reset,
466
- pending: sync()
467
- };
468
- };
469
- }
470
- };
471
-
472
- // src/single.ts
473
- var RegionRatelimit = class extends Ratelimit {
474
- /**
475
- * Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithm of your choice.
476
- */
477
- constructor(config) {
478
- super({
479
- prefix: config.prefix,
480
- limiter: config.limiter,
481
- timeout: config.timeout,
482
- analytics: config.analytics,
483
- ctx: {
484
- redis: config.redis
485
- },
486
- ephemeralCache: config.ephemeralCache
487
- });
488
- }
489
- /**
490
- * Each request inside a fixed time increases a counter.
491
- * Once the counter reaches the maximum allowed number, all further requests are
492
- * rejected.
493
- *
494
- * **Pro:**
495
- *
496
- * - Newer requests are not starved by old ones.
497
- * - Low storage cost.
498
- *
499
- * **Con:**
500
- *
501
- * A burst of requests near the boundary of a window can result in a very
502
- * high request rate because two windows will be filled with requests quickly.
503
- *
504
- * @param tokens - How many requests a user can make in each time window.
505
- * @param window - A fixed timeframe
506
- */
507
- static fixedWindow(tokens, window) {
508
- const windowDuration = ms(window);
509
- const script = `
510
- local key = KEYS[1]
511
- local window = ARGV[1]
512
-
513
- local r = redis.call("INCR", key)
514
- if r == 1 then
515
- -- The first time this key is set, the value will be 1.
516
- -- So we only need the expire command once
517
- redis.call("PEXPIRE", key, window)
518
- end
519
-
520
- return r
521
- `;
522
- return async function(ctx, identifier) {
523
- const bucket = Math.floor(Date.now() / windowDuration);
524
- const key = [identifier, bucket].join(":");
525
- if (ctx.cache) {
526
- const { blocked, reset: reset2 } = ctx.cache.isBlocked(identifier);
527
- if (blocked) {
528
- return {
529
- success: false,
530
- limit: tokens,
531
- remaining: 0,
532
- reset: reset2,
533
- pending: Promise.resolve()
534
- };
535
- }
536
- }
537
- const usedTokensAfterUpdate = await ctx.redis.eval(script, [key], [windowDuration]);
538
- const success = usedTokensAfterUpdate <= tokens;
539
- const reset = (bucket + 1) * windowDuration;
540
- if (ctx.cache && !success) {
541
- ctx.cache.blockUntil(identifier, reset);
542
- }
543
- return {
544
- success,
545
- limit: tokens,
546
- remaining: Math.max(0, tokens - usedTokensAfterUpdate),
547
- reset,
548
- pending: Promise.resolve()
549
- };
550
- };
551
- }
552
- /**
553
- * Combined approach of `slidingLogs` and `fixedWindow` with lower storage
554
- * costs than `slidingLogs` and improved boundary behavior by calculating a
555
- * weighted score between two windows.
556
- *
557
- * **Pro:**
558
- *
559
- * Good performance allows this to scale to very high loads.
560
- *
561
- * **Con:**
562
- *
563
- * Nothing major.
564
- *
565
- * @param tokens - How many requests a user can make in each time window.
566
- * @param window - The duration in which the user can max X requests.
567
- */
568
- static slidingWindow(tokens, window) {
569
- const script = `
570
- local currentKey = KEYS[1] -- identifier including prefixes
571
- local previousKey = KEYS[2] -- key of the previous bucket
572
- local tokens = tonumber(ARGV[1]) -- tokens per window
573
- local now = ARGV[2] -- current timestamp in milliseconds
574
- local window = ARGV[3] -- interval in milliseconds
575
-
576
- local requestsInCurrentWindow = redis.call("GET", currentKey)
577
- if requestsInCurrentWindow == false then
578
- requestsInCurrentWindow = 0
579
- end
580
-
581
- local requestsInPreviousWindow = redis.call("GET", previousKey)
582
- if requestsInPreviousWindow == false then
583
- requestsInPreviousWindow = 0
584
- end
585
- local percentageInCurrent = ( now % window ) / window
586
- -- weighted requests to consider from the previous window
587
- requestsInPreviousWindow = math.floor(( 1 - percentageInCurrent ) * requestsInPreviousWindow)
588
- if requestsInPreviousWindow + requestsInCurrentWindow >= tokens then
589
- return -1
590
- end
591
-
592
- local newValue = redis.call("INCR", currentKey)
593
- if newValue == 1 then
594
- -- The first time this key is set, the value will be 1.
595
- -- So we only need the expire command once
596
- redis.call("PEXPIRE", currentKey, window * 2 + 1000) -- Enough time to overlap with a new window + 1 second
597
- end
598
- return tokens - ( newValue + requestsInPreviousWindow )
599
- `;
600
- const windowSize = ms(window);
601
- return async function(ctx, identifier) {
602
- const now = Date.now();
603
- const currentWindow = Math.floor(now / windowSize);
604
- const currentKey = [identifier, currentWindow].join(":");
605
- const previousWindow = currentWindow - 1;
606
- const previousKey = [identifier, previousWindow].join(":");
607
- if (ctx.cache) {
608
- const { blocked, reset: reset2 } = ctx.cache.isBlocked(identifier);
609
- if (blocked) {
610
- return {
611
- success: false,
612
- limit: tokens,
613
- remaining: 0,
614
- reset: reset2,
615
- pending: Promise.resolve()
616
- };
617
- }
618
- }
619
- const remaining = await ctx.redis.eval(script, [currentKey, previousKey], [tokens, now, windowSize]);
620
- const success = remaining >= 0;
621
- const reset = (currentWindow + 1) * windowSize;
622
- if (ctx.cache && !success) {
623
- ctx.cache.blockUntil(identifier, reset);
624
- }
625
- return {
626
- success,
627
- limit: tokens,
628
- remaining: Math.max(0, remaining),
629
- reset,
630
- pending: Promise.resolve()
631
- };
632
- };
633
- }
634
- /**
635
- * You have a bucket filled with `{maxTokens}` tokens that refills constantly
636
- * at `{refillRate}` per `{interval}`.
637
- * Every request will remove one token from the bucket and if there is no
638
- * token to take, the request is rejected.
639
- *
640
- * **Pro:**
641
- *
642
- * - Bursts of requests are smoothed out and you can process them at a constant
643
- * rate.
644
- * - Allows to set a higher initial burst limit by setting `maxTokens` higher
645
- * than `refillRate`
646
- */
647
- static tokenBucket(refillRate, interval, maxTokens) {
648
- const script = `
649
- local key = KEYS[1] -- identifier including prefixes
650
- local maxTokens = tonumber(ARGV[1]) -- maximum number of tokens
651
- local interval = tonumber(ARGV[2]) -- size of the window in milliseconds
652
- local refillRate = tonumber(ARGV[3]) -- how many tokens are refilled after each interval
653
- local now = tonumber(ARGV[4]) -- current timestamp in milliseconds
654
- local remaining = 0
655
-
656
- local bucket = redis.call("HMGET", key, "updatedAt", "tokens")
657
-
658
- if bucket[1] == false then
659
- -- The bucket does not exist yet, so we create it and add a ttl.
660
- remaining = maxTokens - 1
661
-
662
- redis.call("HMSET", key, "updatedAt", now, "tokens", remaining)
663
- redis.call("PEXPIRE", key, interval)
664
-
665
- return {remaining, now + interval}
666
- end
667
-
668
- -- The bucket does exist
669
-
670
- local updatedAt = tonumber(bucket[1])
671
- local tokens = tonumber(bucket[2])
672
-
673
- if now >= updatedAt + interval then
674
- if tokens <= 0 then
675
- -- No more tokens were left before the refill.
676
- remaining = math.min(maxTokens, refillRate) - 1
677
- else
678
- remaining = math.min(maxTokens, tokens + refillRate) - 1
679
- end
680
- redis.call("HMSET", key, "updatedAt", now, "tokens", remaining)
681
- return {remaining, now + interval}
682
- end
683
-
684
- remaining = tokens - 1
685
- redis.call("HSET", key, "tokens", remaining)
686
- return {remaining, updatedAt + interval}
687
-
688
-
689
- `;
690
- const intervalDuration = ms(interval);
691
- return async function(ctx, identifier) {
692
- if (ctx.cache) {
693
- const { blocked, reset: reset2 } = ctx.cache.isBlocked(identifier);
694
- if (blocked) {
695
- return {
696
- success: false,
697
- limit: maxTokens,
698
- remaining: 0,
699
- reset: reset2,
700
- pending: Promise.resolve()
701
- };
702
- }
703
- }
704
- const now = Date.now();
705
- const key = [identifier, Math.floor(now / intervalDuration)].join(":");
706
- const [remaining, reset] = await ctx.redis.eval(
707
- script,
708
- [key],
709
- [maxTokens, intervalDuration, refillRate, now]
710
- );
711
- const success = remaining > 0;
712
- if (ctx.cache && !success) {
713
- ctx.cache.blockUntil(identifier, reset);
714
- }
715
- return {
716
- success,
717
- limit: maxTokens,
718
- remaining,
719
- reset,
720
- pending: Promise.resolve()
721
- };
722
- };
723
- }
724
- /**
725
- * cachedFixedWindow first uses the local cache to decide if a request may pass and then updates
726
- * it asynchronously.
727
- * This is experimental and not yet recommended for production use.
728
- *
729
- * @experimental
730
- *
731
- * Each request inside a fixed time increases a counter.
732
- * Once the counter reaches the maximum allowed number, all further requests are
733
- * rejected.
734
- *
735
- * **Pro:**
736
- *
737
- * - Newer requests are not starved by old ones.
738
- * - Low storage cost.
739
- *
740
- * **Con:**
741
- *
742
- * A burst of requests near the boundary of a window can result in a very
743
- * high request rate because two windows will be filled with requests quickly.
744
- *
745
- * @param tokens - How many requests a user can make in each time window.
746
- * @param window - A fixed timeframe
747
- */
748
- static cachedFixedWindow(tokens, window) {
749
- const windowDuration = ms(window);
750
- const script = `
751
- local key = KEYS[1]
752
- local window = ARGV[1]
753
-
754
- local r = redis.call("INCR", key)
755
- if r == 1 then
756
- -- The first time this key is set, the value will be 1.
757
- -- So we only need the expire command once
758
- redis.call("PEXPIRE", key, window)
759
- end
760
-
761
- return r
762
- `;
763
- return async function(ctx, identifier) {
764
- if (!ctx.cache) {
765
- throw new Error("This algorithm requires a cache");
766
- }
767
- const bucket = Math.floor(Date.now() / windowDuration);
768
- const key = [identifier, bucket].join(":");
769
- const reset = (bucket + 1) * windowDuration;
770
- const hit = typeof ctx.cache.get(key) === "number";
771
- if (hit) {
772
- const cachedTokensAfterUpdate = ctx.cache.incr(key);
773
- const success = cachedTokensAfterUpdate < tokens;
774
- const pending = success ? ctx.redis.eval(script, [key], [windowDuration]).then((t) => {
775
- ctx.cache.set(key, t);
776
- }) : Promise.resolve();
777
- return {
778
- success,
779
- limit: tokens,
780
- remaining: tokens - cachedTokensAfterUpdate,
781
- reset,
782
- pending
783
- };
784
- }
785
- const usedTokensAfterUpdate = await ctx.redis.eval(script, [key], [windowDuration]);
786
- ctx.cache.set(key, usedTokensAfterUpdate);
787
- const remaining = tokens - usedTokensAfterUpdate;
788
- return {
789
- success: remaining >= 0,
790
- limit: tokens,
791
- remaining,
792
- reset,
793
- pending: Promise.resolve()
794
- };
795
- };
796
- }
797
- };
798
- export {
799
- Analytics,
800
- MultiRegionRatelimit,
801
- RegionRatelimit as Ratelimit
802
- };
803
- //# sourceMappingURL=index.mjs.map