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