@upstash/ratelimit 0.4.5-canary.0 → 1.0.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 (94) hide show
  1. package/README.md +2 -2
  2. package/dist/index.d.mts +556 -0
  3. package/dist/index.d.ts +556 -0
  4. package/dist/index.js +832 -0
  5. package/dist/index.js.map +1 -0
  6. package/dist/index.mjs +803 -0
  7. package/dist/index.mjs.map +1 -0
  8. package/package.json +1 -22
  9. package/.github/actions/redis/action.yaml +0 -58
  10. package/.github/img/dashboard.png +0 -0
  11. package/.github/workflows/release.yml +0 -46
  12. package/.github/workflows/stale.yaml +0 -31
  13. package/.github/workflows/tests.yaml +0 -79
  14. package/biome.json +0 -37
  15. package/bun.lockb +0 -0
  16. package/cmd/set-version.js +0 -14
  17. package/examples/cloudflare-workers/package.json +0 -18
  18. package/examples/cloudflare-workers/src/index.ts +0 -35
  19. package/examples/cloudflare-workers/tsconfig.json +0 -105
  20. package/examples/cloudflare-workers/wrangler.toml +0 -3
  21. package/examples/nextjs/LICENSE +0 -21
  22. package/examples/nextjs/README.md +0 -17
  23. package/examples/nextjs/components/Breadcrumb.tsx +0 -67
  24. package/examples/nextjs/components/Header.tsx +0 -18
  25. package/examples/nextjs/components/ReadBlogPost.tsx +0 -9
  26. package/examples/nextjs/components/StarButton.tsx +0 -27
  27. package/examples/nextjs/middleware.ts +0 -35
  28. package/examples/nextjs/next-env.d.ts +0 -5
  29. package/examples/nextjs/package.json +0 -27
  30. package/examples/nextjs/pages/_app.tsx +0 -47
  31. package/examples/nextjs/pages/api/blocked.ts +0 -6
  32. package/examples/nextjs/pages/api/hello.ts +0 -5
  33. package/examples/nextjs/pages/index.tsx +0 -62
  34. package/examples/nextjs/postcss.config.js +0 -6
  35. package/examples/nextjs/public/favicon.ico +0 -0
  36. package/examples/nextjs/public/github.svg +0 -11
  37. package/examples/nextjs/public/upstash.svg +0 -27
  38. package/examples/nextjs/styles/globals.css +0 -76
  39. package/examples/nextjs/tailwind.config.js +0 -19
  40. package/examples/nextjs/tsconfig.json +0 -21
  41. package/examples/nextjs13/README.md +0 -38
  42. package/examples/nextjs13/app/favicon.ico +0 -0
  43. package/examples/nextjs13/app/globals.css +0 -107
  44. package/examples/nextjs13/app/layout.tsx +0 -18
  45. package/examples/nextjs13/app/page.module.css +0 -271
  46. package/examples/nextjs13/app/route.tsx +0 -14
  47. package/examples/nextjs13/next.config.js +0 -8
  48. package/examples/nextjs13/package.json +0 -22
  49. package/examples/nextjs13/public/next.svg +0 -1
  50. package/examples/nextjs13/public/thirteen.svg +0 -1
  51. package/examples/nextjs13/public/vercel.svg +0 -1
  52. package/examples/nextjs13/tsconfig.json +0 -28
  53. package/examples/remix/.env.example +0 -2
  54. package/examples/remix/.eslintrc.js +0 -4
  55. package/examples/remix/README.md +0 -59
  56. package/examples/remix/app/root.tsx +0 -25
  57. package/examples/remix/app/routes/index.tsx +0 -47
  58. package/examples/remix/package.json +0 -32
  59. package/examples/remix/public/favicon.ico +0 -0
  60. package/examples/remix/remix.config.js +0 -12
  61. package/examples/remix/remix.env.d.ts +0 -2
  62. package/examples/remix/server.js +0 -4
  63. package/examples/remix/tsconfig.json +0 -22
  64. package/examples/with-vercel-kv/README.md +0 -51
  65. package/examples/with-vercel-kv/app/favicon.ico +0 -0
  66. package/examples/with-vercel-kv/app/globals.css +0 -27
  67. package/examples/with-vercel-kv/app/layout.tsx +0 -21
  68. package/examples/with-vercel-kv/app/page.tsx +0 -71
  69. package/examples/with-vercel-kv/next.config.js +0 -8
  70. package/examples/with-vercel-kv/package.json +0 -25
  71. package/examples/with-vercel-kv/postcss.config.js +0 -6
  72. package/examples/with-vercel-kv/public/next.svg +0 -1
  73. package/examples/with-vercel-kv/public/vercel.svg +0 -1
  74. package/examples/with-vercel-kv/tailwind.config.js +0 -17
  75. package/examples/with-vercel-kv/tsconfig.json +0 -28
  76. package/src/analytics.test.ts +0 -23
  77. package/src/analytics.ts +0 -92
  78. package/src/blockUntilReady.test.ts +0 -56
  79. package/src/cache.test.ts +0 -41
  80. package/src/cache.ts +0 -43
  81. package/src/duration.test.ts +0 -23
  82. package/src/duration.ts +0 -30
  83. package/src/index.ts +0 -17
  84. package/src/multi.ts +0 -365
  85. package/src/ratelimit.test.ts +0 -155
  86. package/src/ratelimit.ts +0 -238
  87. package/src/single.ts +0 -487
  88. package/src/test_utils.ts +0 -65
  89. package/src/tools/seed.ts +0 -37
  90. package/src/types.ts +0 -78
  91. package/src/version.ts +0 -1
  92. package/tsconfig.json +0 -103
  93. package/tsup.config.js +0 -11
  94. package/turbo.json +0 -16
package/dist/index.mjs ADDED
@@ -0,0 +1,803 @@
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, false}
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, true}
412
+ `;
413
+ const windowDuration = ms(window);
414
+ return async function(ctx, identifier) {
415
+ const requestId = randomId();
416
+ const now = Date.now();
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 dbs = ctx.redis.map((redis) => ({
422
+ redis,
423
+ request: redis.eval(
424
+ script,
425
+ [currentKey, previousKey],
426
+ [tokens, now, windowDuration, requestId]
427
+ // lua seems to return `1` for true and `null` for false
428
+ )
429
+ }));
430
+ const percentageInCurrent = now % windowDuration / windowDuration;
431
+ const [current, previous, success] = await Promise.any(dbs.map((s) => s.request));
432
+ const previousPartialUsed = previous.length * (1 - percentageInCurrent);
433
+ const usedTokens = previousPartialUsed + current.length;
434
+ const remaining = tokens - usedTokens;
435
+ async function sync() {
436
+ const res = await Promise.all(dbs.map((s) => s.request));
437
+ const allCurrentIds = res.flatMap(([current2]) => current2);
438
+ for (const db of dbs) {
439
+ const [ids] = await db.request;
440
+ if (ids.length >= tokens) {
441
+ continue;
442
+ }
443
+ const diff = allCurrentIds.filter((id) => !ids.includes(id));
444
+ if (diff.length === 0) {
445
+ continue;
446
+ }
447
+ await db.redis.sadd(currentKey, ...diff);
448
+ }
449
+ }
450
+ const reset = (currentWindow + 1) * windowDuration;
451
+ if (ctx.cache && !success) {
452
+ ctx.cache.blockUntil(identifier, reset);
453
+ }
454
+ return {
455
+ success: Boolean(success),
456
+ limit: tokens,
457
+ remaining,
458
+ reset,
459
+ pending: sync()
460
+ };
461
+ };
462
+ }
463
+ };
464
+
465
+ // src/single.ts
466
+ var RegionRatelimit = class extends Ratelimit {
467
+ /**
468
+ * Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithm of your choice.
469
+ */
470
+ constructor(config) {
471
+ super({
472
+ prefix: config.prefix,
473
+ limiter: config.limiter,
474
+ timeout: config.timeout,
475
+ analytics: config.analytics,
476
+ ctx: {
477
+ redis: config.redis
478
+ },
479
+ ephemeralCache: config.ephemeralCache
480
+ });
481
+ }
482
+ /**
483
+ * Each request inside a fixed time increases a counter.
484
+ * Once the counter reaches the maximum allowed number, all further requests are
485
+ * rejected.
486
+ *
487
+ * **Pro:**
488
+ *
489
+ * - Newer requests are not starved by old ones.
490
+ * - Low storage cost.
491
+ *
492
+ * **Con:**
493
+ *
494
+ * A burst of requests near the boundary of a window can result in a very
495
+ * high request rate because two windows will be filled with requests quickly.
496
+ *
497
+ * @param tokens - How many requests a user can make in each time window.
498
+ * @param window - A fixed timeframe
499
+ */
500
+ static fixedWindow(tokens, window) {
501
+ const windowDuration = ms(window);
502
+ const script = `
503
+ local key = KEYS[1]
504
+ local window = ARGV[1]
505
+
506
+ local r = redis.call("INCR", key)
507
+ if r == 1 then
508
+ -- The first time this key is set, the value will be 1.
509
+ -- So we only need the expire command once
510
+ redis.call("PEXPIRE", key, window)
511
+ end
512
+
513
+ return r
514
+ `;
515
+ return async function(ctx, identifier) {
516
+ const bucket = Math.floor(Date.now() / windowDuration);
517
+ const key = [identifier, bucket].join(":");
518
+ if (ctx.cache) {
519
+ const { blocked, reset: reset2 } = ctx.cache.isBlocked(identifier);
520
+ if (blocked) {
521
+ return {
522
+ success: false,
523
+ limit: tokens,
524
+ remaining: 0,
525
+ reset: reset2,
526
+ pending: Promise.resolve()
527
+ };
528
+ }
529
+ }
530
+ const usedTokensAfterUpdate = await ctx.redis.eval(
531
+ script,
532
+ [key],
533
+ [windowDuration]
534
+ );
535
+ const success = usedTokensAfterUpdate <= tokens;
536
+ const reset = (bucket + 1) * windowDuration;
537
+ if (ctx.cache && !success) {
538
+ ctx.cache.blockUntil(identifier, reset);
539
+ }
540
+ return {
541
+ success,
542
+ limit: tokens,
543
+ remaining: Math.max(0, tokens - usedTokensAfterUpdate),
544
+ reset,
545
+ pending: Promise.resolve()
546
+ };
547
+ };
548
+ }
549
+ /**
550
+ * Combined approach of `slidingLogs` and `fixedWindow` with lower storage
551
+ * costs than `slidingLogs` and improved boundary behavior by calculating a
552
+ * weighted score between two windows.
553
+ *
554
+ * **Pro:**
555
+ *
556
+ * Good performance allows this to scale to very high loads.
557
+ *
558
+ * **Con:**
559
+ *
560
+ * Nothing major.
561
+ *
562
+ * @param tokens - How many requests a user can make in each time window.
563
+ * @param window - The duration in which the user can max X requests.
564
+ */
565
+ static slidingWindow(tokens, window) {
566
+ const script = `
567
+ local currentKey = KEYS[1] -- identifier including prefixes
568
+ local previousKey = KEYS[2] -- key of the previous bucket
569
+ local tokens = tonumber(ARGV[1]) -- tokens per window
570
+ local now = ARGV[2] -- current timestamp in milliseconds
571
+ local window = ARGV[3] -- interval in milliseconds
572
+
573
+ local requestsInCurrentWindow = redis.call("GET", currentKey)
574
+ if requestsInCurrentWindow == false then
575
+ requestsInCurrentWindow = 0
576
+ end
577
+
578
+ local requestsInPreviousWindow = redis.call("GET", previousKey)
579
+ if requestsInPreviousWindow == false then
580
+ requestsInPreviousWindow = 0
581
+ end
582
+ local percentageInCurrent = ( now % window ) / window
583
+ -- weighted requests to consider from the previous window
584
+ requestsInPreviousWindow = math.floor(( 1 - percentageInCurrent ) * requestsInPreviousWindow)
585
+ if requestsInPreviousWindow + requestsInCurrentWindow >= tokens then
586
+ return -1
587
+ end
588
+
589
+ local newValue = redis.call("INCR", currentKey)
590
+ if newValue == 1 then
591
+ -- The first time this key is set, the value will be 1.
592
+ -- So we only need the expire command once
593
+ redis.call("PEXPIRE", currentKey, window * 2 + 1000) -- Enough time to overlap with a new window + 1 second
594
+ end
595
+ return tokens - ( newValue + requestsInPreviousWindow )
596
+ `;
597
+ const windowSize = ms(window);
598
+ return async function(ctx, identifier) {
599
+ const now = Date.now();
600
+ const currentWindow = Math.floor(now / windowSize);
601
+ const currentKey = [identifier, currentWindow].join(":");
602
+ const previousWindow = currentWindow - 1;
603
+ const previousKey = [identifier, previousWindow].join(":");
604
+ if (ctx.cache) {
605
+ const { blocked, reset: reset2 } = ctx.cache.isBlocked(identifier);
606
+ if (blocked) {
607
+ return {
608
+ success: false,
609
+ limit: tokens,
610
+ remaining: 0,
611
+ reset: reset2,
612
+ pending: Promise.resolve()
613
+ };
614
+ }
615
+ }
616
+ const remaining = await ctx.redis.eval(
617
+ script,
618
+ [currentKey, previousKey],
619
+ [tokens, now, windowSize]
620
+ );
621
+ const success = remaining >= 0;
622
+ const reset = (currentWindow + 1) * windowSize;
623
+ if (ctx.cache && !success) {
624
+ ctx.cache.blockUntil(identifier, reset);
625
+ }
626
+ return {
627
+ success,
628
+ limit: tokens,
629
+ remaining: Math.max(0, remaining),
630
+ reset,
631
+ pending: Promise.resolve()
632
+ };
633
+ };
634
+ }
635
+ /**
636
+ * You have a bucket filled with `{maxTokens}` tokens that refills constantly
637
+ * at `{refillRate}` per `{interval}`.
638
+ * Every request will remove one token from the bucket and if there is no
639
+ * token to take, the request is rejected.
640
+ *
641
+ * **Pro:**
642
+ *
643
+ * - Bursts of requests are smoothed out and you can process them at a constant
644
+ * rate.
645
+ * - Allows to set a higher initial burst limit by setting `maxTokens` higher
646
+ * than `refillRate`
647
+ */
648
+ static tokenBucket(refillRate, interval, maxTokens) {
649
+ const script = `
650
+ local key = KEYS[1] -- identifier including prefixes
651
+ local maxTokens = tonumber(ARGV[1]) -- maximum number of tokens
652
+ local interval = tonumber(ARGV[2]) -- size of the window in milliseconds
653
+ local refillRate = tonumber(ARGV[3]) -- how many tokens are refilled after each interval
654
+ local now = tonumber(ARGV[4]) -- current timestamp in milliseconds
655
+
656
+ local bucket = redis.call("HMGET", key, "refilledAt", "tokens")
657
+
658
+ local refilledAt
659
+ local tokens
660
+
661
+ if bucket[1] == false then
662
+ refilledAt = now
663
+ tokens = maxTokens
664
+ else
665
+ refilledAt = tonumber(bucket[1])
666
+ tokens = tonumber(bucket[2])
667
+ end
668
+
669
+ if now >= refilledAt + interval then
670
+ local numRefills = math.floor((now - refilledAt) / interval)
671
+ tokens = math.min(maxTokens, tokens + numRefills * refillRate)
672
+
673
+ refilledAt = refilledAt + numRefills * interval
674
+ end
675
+
676
+ if tokens == 0 then
677
+ return {-1, refilledAt + interval}
678
+ end
679
+
680
+ local remaining = tokens - 1
681
+ local expireAt = math.ceil(((maxTokens - remaining) / refillRate)) * interval
682
+
683
+ redis.call("HSET", key, "refilledAt", refilledAt, "tokens", remaining)
684
+ redis.call("PEXPIRE", key, expireAt)
685
+ return {remaining, refilledAt + interval}
686
+ `;
687
+ const intervalDuration = ms(interval);
688
+ return async function(ctx, identifier) {
689
+ if (ctx.cache) {
690
+ const { blocked, reset: reset2 } = ctx.cache.isBlocked(identifier);
691
+ if (blocked) {
692
+ return {
693
+ success: false,
694
+ limit: maxTokens,
695
+ remaining: 0,
696
+ reset: reset2,
697
+ pending: Promise.resolve()
698
+ };
699
+ }
700
+ }
701
+ const now = Date.now();
702
+ const [remaining, reset] = await ctx.redis.eval(
703
+ script,
704
+ [identifier],
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 request inside a fixed time increases a counter.
728
+ * Once the counter reaches the maximum 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(
782
+ script,
783
+ [key],
784
+ [windowDuration]
785
+ );
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