@upstash/ratelimit 0.4.3 → 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 +10 -3
  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 -558
  90. package/dist/index.js +0 -828
  91. package/dist/index.js.map +0 -1
  92. package/dist/index.mjs +0 -799
  93. package/dist/index.mjs.map +0 -1
package/dist/index.mjs DELETED
@@ -1,799 +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 timeoue 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 requests inside a fixed time increases a counter.
282
- * Once the counter reaches a maxmimum 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 calcualting 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 - windowSize;
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 algorithn 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 requests inside a fixed time increases a counter.
491
- * Once the counter reaches a maxmimum 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: 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 calcualting 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 = -1
579
- end
580
-
581
-
582
- local requestsInPreviousWindow = redis.call("GET", previousKey)
583
- if requestsInPreviousWindow == false then
584
- requestsInPreviousWindow = 0
585
- end
586
- local percentageInCurrent = ( now % window) / window
587
- if requestsInPreviousWindow * ( 1 - percentageInCurrent ) + requestsInCurrentWindow >= tokens then
588
- return -1
589
- end
590
-
591
- local newValue = redis.call("INCR", currentKey)
592
- if newValue == 1 then
593
- -- The first time this key is set, the value will be 1.
594
- -- So we only need the expire command once
595
- redis.call("PEXPIRE", currentKey, window * 2 + 1000) -- Enough time to overlap with a new window + 1 second
596
- end
597
- return tokens - newValue
598
- `;
599
- const windowSize = ms(window);
600
- return async function(ctx, identifier) {
601
- const now = Date.now();
602
- const currentWindow = Math.floor(now / windowSize);
603
- const currentKey = [identifier, currentWindow].join(":");
604
- const previousWindow = currentWindow - windowSize;
605
- const previousKey = [identifier, previousWindow].join(":");
606
- if (ctx.cache) {
607
- const { blocked, reset: reset2 } = ctx.cache.isBlocked(identifier);
608
- if (blocked) {
609
- return {
610
- success: false,
611
- limit: tokens,
612
- remaining: 0,
613
- reset: reset2,
614
- pending: Promise.resolve()
615
- };
616
- }
617
- }
618
- const remaining = await ctx.redis.eval(script, [currentKey, previousKey], [tokens, now, windowSize]);
619
- const success = remaining >= 0;
620
- const reset = (currentWindow + 1) * windowSize;
621
- if (ctx.cache && !success) {
622
- ctx.cache.blockUntil(identifier, reset);
623
- }
624
- return {
625
- success,
626
- limit: tokens,
627
- remaining: Math.max(0, remaining),
628
- reset,
629
- pending: Promise.resolve()
630
- };
631
- };
632
- }
633
- /**
634
- * You have a bucket filled with `{maxTokens}` tokens that refills constantly
635
- * at `{refillRate}` per `{interval}`.
636
- * Every request will remove one token from the bucket and if there is no
637
- * token to take, the request is rejected.
638
- *
639
- * **Pro:**
640
- *
641
- * - Bursts of requests are smoothed out and you can process them at a constant
642
- * rate.
643
- * - Allows to set a higher initial burst limit by setting `maxTokens` higher
644
- * than `refillRate`
645
- */
646
- static tokenBucket(refillRate, interval, maxTokens) {
647
- const script = `
648
- local key = KEYS[1] -- identifier including prefixes
649
- local maxTokens = tonumber(ARGV[1]) -- maximum number of tokens
650
- local interval = tonumber(ARGV[2]) -- size of the window in milliseconds
651
- local refillRate = tonumber(ARGV[3]) -- how many tokens are refilled after each interval
652
- local now = tonumber(ARGV[4]) -- current timestamp in milliseconds
653
- local remaining = 0
654
-
655
- local bucket = redis.call("HMGET", key, "updatedAt", "tokens")
656
-
657
- if bucket[1] == false then
658
- -- The bucket does not exist yet, so we create it and add a ttl.
659
- remaining = maxTokens - 1
660
-
661
- redis.call("HMSET", key, "updatedAt", now, "tokens", remaining)
662
- redis.call("PEXPIRE", key, interval)
663
-
664
- return {remaining, now + interval}
665
- end
666
-
667
- -- The bucket does exist
668
-
669
- local updatedAt = tonumber(bucket[1])
670
- local tokens = tonumber(bucket[2])
671
-
672
- if now >= updatedAt + interval then
673
- remaining = math.min(maxTokens, tokens + refillRate) - 1
674
-
675
- redis.call("HMSET", key, "updatedAt", now, "tokens", remaining)
676
- return {remaining, now + interval}
677
- end
678
-
679
- if tokens > 0 then
680
- remaining = tokens - 1
681
- redis.call("HMSET", key, "updatedAt", now, "tokens", remaining)
682
- end
683
-
684
- return {remaining, updatedAt + interval}
685
- `;
686
- const intervalDuration = ms(interval);
687
- return async function(ctx, identifier) {
688
- if (ctx.cache) {
689
- const { blocked, reset: reset2 } = ctx.cache.isBlocked(identifier);
690
- if (blocked) {
691
- return {
692
- success: false,
693
- limit: maxTokens,
694
- remaining: 0,
695
- reset: reset2,
696
- pending: Promise.resolve()
697
- };
698
- }
699
- }
700
- const now = Date.now();
701
- const key = [identifier, Math.floor(now / intervalDuration)].join(":");
702
- const [remaining, reset] = await ctx.redis.eval(
703
- script,
704
- [key],
705
- [maxTokens, intervalDuration, refillRate, now]
706
- );
707
- const success = remaining > 0;
708
- if (ctx.cache && !success) {
709
- ctx.cache.blockUntil(identifier, reset);
710
- }
711
- return {
712
- success,
713
- limit: maxTokens,
714
- remaining,
715
- reset,
716
- pending: Promise.resolve()
717
- };
718
- };
719
- }
720
- /**
721
- * cachedFixedWindow first uses the local cache to decide if a request may pass and then updates
722
- * it asynchronously.
723
- * This is experimental and not yet recommended for production use.
724
- *
725
- * @experimental
726
- *
727
- * Each requests inside a fixed time increases a counter.
728
- * Once the counter reaches a maxmimum allowed number, all further requests are
729
- * rejected.
730
- *
731
- * **Pro:**
732
- *
733
- * - Newer requests are not starved by old ones.
734
- * - Low storage cost.
735
- *
736
- * **Con:**
737
- *
738
- * A burst of requests near the boundary of a window can result in a very
739
- * high request rate because two windows will be filled with requests quickly.
740
- *
741
- * @param tokens - How many requests a user can make in each time window.
742
- * @param window - A fixed timeframe
743
- */
744
- static cachedFixedWindow(tokens, window) {
745
- const windowDuration = ms(window);
746
- const script = `
747
- local key = KEYS[1]
748
- local window = ARGV[1]
749
-
750
- local r = redis.call("INCR", key)
751
- if r == 1 then
752
- -- The first time this key is set, the value will be 1.
753
- -- So we only need the expire command once
754
- redis.call("PEXPIRE", key, window)
755
- end
756
-
757
- return r
758
- `;
759
- return async function(ctx, identifier) {
760
- if (!ctx.cache) {
761
- throw new Error("This algorithm requires a cache");
762
- }
763
- const bucket = Math.floor(Date.now() / windowDuration);
764
- const key = [identifier, bucket].join(":");
765
- const reset = (bucket + 1) * windowDuration;
766
- const hit = typeof ctx.cache.get(key) === "number";
767
- if (hit) {
768
- const cachedTokensAfterUpdate = ctx.cache.incr(key);
769
- const success = cachedTokensAfterUpdate < tokens;
770
- const pending = success ? ctx.redis.eval(script, [key], [windowDuration]).then((t) => {
771
- ctx.cache.set(key, t);
772
- }) : Promise.resolve();
773
- return {
774
- success,
775
- limit: tokens,
776
- remaining: tokens - cachedTokensAfterUpdate,
777
- reset,
778
- pending
779
- };
780
- }
781
- const usedTokensAfterUpdate = await ctx.redis.eval(script, [key], [windowDuration]);
782
- ctx.cache.set(key, usedTokensAfterUpdate);
783
- const remaining = tokens - usedTokensAfterUpdate;
784
- return {
785
- success: remaining >= 0,
786
- limit: tokens,
787
- remaining,
788
- reset,
789
- pending: Promise.resolve()
790
- };
791
- };
792
- }
793
- };
794
- export {
795
- Analytics,
796
- MultiRegionRatelimit,
797
- RegionRatelimit as Ratelimit
798
- };
799
- //# sourceMappingURL=index.mjs.map