@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.
- package/.github/actions/redis/action.yaml +58 -0
- package/.github/img/dashboard.png +0 -0
- package/.github/workflows/release.yml +46 -0
- package/.github/workflows/stale.yaml +31 -0
- package/.github/workflows/tests.yaml +79 -0
- package/README.md +10 -3
- package/biome.json +37 -0
- package/bun.lockb +0 -0
- package/cmd/set-version.js +14 -0
- package/examples/cloudflare-workers/package.json +18 -0
- package/examples/cloudflare-workers/src/index.ts +35 -0
- package/examples/cloudflare-workers/tsconfig.json +105 -0
- package/examples/cloudflare-workers/wrangler.toml +3 -0
- package/examples/nextjs/LICENSE +21 -0
- package/examples/nextjs/README.md +17 -0
- package/examples/nextjs/components/Breadcrumb.tsx +67 -0
- package/examples/nextjs/components/Header.tsx +18 -0
- package/examples/nextjs/components/ReadBlogPost.tsx +9 -0
- package/examples/nextjs/components/StarButton.tsx +27 -0
- package/examples/nextjs/middleware.ts +35 -0
- package/examples/nextjs/next-env.d.ts +5 -0
- package/examples/nextjs/package.json +27 -0
- package/examples/nextjs/pages/_app.tsx +47 -0
- package/examples/nextjs/pages/api/blocked.ts +6 -0
- package/examples/nextjs/pages/api/hello.ts +5 -0
- package/examples/nextjs/pages/index.tsx +62 -0
- package/examples/nextjs/postcss.config.js +6 -0
- package/examples/nextjs/public/favicon.ico +0 -0
- package/examples/nextjs/public/github.svg +11 -0
- package/examples/nextjs/public/upstash.svg +27 -0
- package/examples/nextjs/styles/globals.css +76 -0
- package/examples/nextjs/tailwind.config.js +19 -0
- package/examples/nextjs/tsconfig.json +21 -0
- package/examples/nextjs13/README.md +38 -0
- package/examples/nextjs13/app/favicon.ico +0 -0
- package/examples/nextjs13/app/globals.css +107 -0
- package/examples/nextjs13/app/layout.tsx +18 -0
- package/examples/nextjs13/app/page.module.css +271 -0
- package/examples/nextjs13/app/route.tsx +14 -0
- package/examples/nextjs13/next.config.js +8 -0
- package/examples/nextjs13/package.json +22 -0
- package/examples/nextjs13/public/next.svg +1 -0
- package/examples/nextjs13/public/thirteen.svg +1 -0
- package/examples/nextjs13/public/vercel.svg +1 -0
- package/examples/nextjs13/tsconfig.json +28 -0
- package/examples/remix/.env.example +2 -0
- package/examples/remix/.eslintrc.js +4 -0
- package/examples/remix/README.md +59 -0
- package/examples/remix/app/root.tsx +25 -0
- package/examples/remix/app/routes/index.tsx +47 -0
- package/examples/remix/package.json +32 -0
- package/examples/remix/public/favicon.ico +0 -0
- package/examples/remix/remix.config.js +12 -0
- package/examples/remix/remix.env.d.ts +2 -0
- package/examples/remix/server.js +4 -0
- package/examples/remix/tsconfig.json +22 -0
- package/examples/with-vercel-kv/README.md +51 -0
- package/examples/with-vercel-kv/app/favicon.ico +0 -0
- package/examples/with-vercel-kv/app/globals.css +27 -0
- package/examples/with-vercel-kv/app/layout.tsx +21 -0
- package/examples/with-vercel-kv/app/page.tsx +71 -0
- package/examples/with-vercel-kv/next.config.js +8 -0
- package/examples/with-vercel-kv/package.json +25 -0
- package/examples/with-vercel-kv/postcss.config.js +6 -0
- package/examples/with-vercel-kv/public/next.svg +1 -0
- package/examples/with-vercel-kv/public/vercel.svg +1 -0
- package/examples/with-vercel-kv/tailwind.config.js +17 -0
- package/examples/with-vercel-kv/tsconfig.json +28 -0
- package/package.json +12 -33
- package/src/analytics.test.ts +23 -0
- package/src/analytics.ts +92 -0
- package/src/blockUntilReady.test.ts +56 -0
- package/src/cache.test.ts +41 -0
- package/src/cache.ts +43 -0
- package/src/duration.test.ts +23 -0
- package/src/duration.ts +30 -0
- package/src/index.ts +17 -0
- package/src/multi.ts +365 -0
- package/src/ratelimit.test.ts +155 -0
- package/src/ratelimit.ts +238 -0
- package/src/single.ts +487 -0
- package/src/test_utils.ts +65 -0
- package/src/tools/seed.ts +37 -0
- package/src/types.ts +78 -0
- package/src/version.ts +1 -0
- package/tsconfig.json +103 -0
- package/tsup.config.js +11 -0
- package/turbo.json +16 -0
- package/dist/index.d.ts +0 -558
- package/dist/index.js +0 -828
- package/dist/index.js.map +0 -1
- package/dist/index.mjs +0 -799
- package/dist/index.mjs.map +0 -1
package/src/single.ts
ADDED
|
@@ -0,0 +1,487 @@
|
|
|
1
|
+
import type { Duration } from "./duration";
|
|
2
|
+
import { ms } from "./duration";
|
|
3
|
+
import type { Algorithm, RegionContext } from "./types";
|
|
4
|
+
import type { Redis } from "./types";
|
|
5
|
+
|
|
6
|
+
import { Ratelimit } from "./ratelimit";
|
|
7
|
+
export type RegionRatelimitConfig = {
|
|
8
|
+
/**
|
|
9
|
+
* Instance of `@upstash/redis`
|
|
10
|
+
* @see https://github.com/upstash/upstash-redis#quick-start
|
|
11
|
+
*/
|
|
12
|
+
redis: Redis;
|
|
13
|
+
/**
|
|
14
|
+
* The ratelimiter function to use.
|
|
15
|
+
*
|
|
16
|
+
* Choose one of the predefined ones or implement your own.
|
|
17
|
+
* Available algorithms are exposed via static methods:
|
|
18
|
+
* - Ratelimiter.fixedWindow
|
|
19
|
+
* - Ratelimiter.slidingWindow
|
|
20
|
+
* - Ratelimiter.tokenBucket
|
|
21
|
+
*/
|
|
22
|
+
limiter: Algorithm<RegionContext>;
|
|
23
|
+
/**
|
|
24
|
+
* All keys in redis are prefixed with this.
|
|
25
|
+
*
|
|
26
|
+
* @default `@upstash/ratelimit`
|
|
27
|
+
*/
|
|
28
|
+
prefix?: string;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* If enabled, the ratelimiter will keep a global cache of identifiers, that have
|
|
32
|
+
* exhausted their ratelimit. In serverless environments this is only possible if
|
|
33
|
+
* you create the ratelimiter instance outside of your handler function. While the
|
|
34
|
+
* function is still hot, the ratelimiter can block requests without having to
|
|
35
|
+
* request data from redis, thus saving time and money.
|
|
36
|
+
*
|
|
37
|
+
* Whenever an identifier has exceeded its limit, the ratelimiter will add it to an
|
|
38
|
+
* internal list together with its reset timestamp. If the same identifier makes a
|
|
39
|
+
* new request before it is reset, we can immediately reject it.
|
|
40
|
+
*
|
|
41
|
+
* Set to `false` to disable.
|
|
42
|
+
*
|
|
43
|
+
* If left undefined, a map is created automatically, but it can only work
|
|
44
|
+
* if the map or the ratelimit instance is created outside your serverless function handler.
|
|
45
|
+
*/
|
|
46
|
+
ephemeralCache?: Map<string, number> | false;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* If set, the ratelimiter will allow requests to pass after this many milliseconds.
|
|
50
|
+
*
|
|
51
|
+
* Use this if you want to allow requests in case of network problems
|
|
52
|
+
*/
|
|
53
|
+
timeout?: number;
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* If enabled, the ratelimiter will store analytics data in redis, which you can check out at
|
|
57
|
+
* https://console.upstash.com/ratelimit
|
|
58
|
+
*
|
|
59
|
+
* @default true
|
|
60
|
+
*/
|
|
61
|
+
analytics?: boolean;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Ratelimiter using serverless redis from https://upstash.com/
|
|
66
|
+
*
|
|
67
|
+
* @example
|
|
68
|
+
* ```ts
|
|
69
|
+
* const { limit } = new Ratelimit({
|
|
70
|
+
* redis: Redis.fromEnv(),
|
|
71
|
+
* limiter: Ratelimit.slidingWindow(
|
|
72
|
+
* "30 m", // interval of 30 minutes
|
|
73
|
+
* 10, // Allow 10 requests per window of 30 minutes
|
|
74
|
+
* )
|
|
75
|
+
* })
|
|
76
|
+
*
|
|
77
|
+
* ```
|
|
78
|
+
*/
|
|
79
|
+
export class RegionRatelimit extends Ratelimit<RegionContext> {
|
|
80
|
+
/**
|
|
81
|
+
* Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithm of your choice.
|
|
82
|
+
*/
|
|
83
|
+
|
|
84
|
+
constructor(config: RegionRatelimitConfig) {
|
|
85
|
+
super({
|
|
86
|
+
prefix: config.prefix,
|
|
87
|
+
limiter: config.limiter,
|
|
88
|
+
timeout: config.timeout,
|
|
89
|
+
analytics: config.analytics,
|
|
90
|
+
ctx: {
|
|
91
|
+
redis: config.redis,
|
|
92
|
+
},
|
|
93
|
+
ephemeralCache: config.ephemeralCache,
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Each request inside a fixed time increases a counter.
|
|
99
|
+
* Once the counter reaches the maximum allowed number, all further requests are
|
|
100
|
+
* rejected.
|
|
101
|
+
*
|
|
102
|
+
* **Pro:**
|
|
103
|
+
*
|
|
104
|
+
* - Newer requests are not starved by old ones.
|
|
105
|
+
* - Low storage cost.
|
|
106
|
+
*
|
|
107
|
+
* **Con:**
|
|
108
|
+
*
|
|
109
|
+
* A burst of requests near the boundary of a window can result in a very
|
|
110
|
+
* high request rate because two windows will be filled with requests quickly.
|
|
111
|
+
*
|
|
112
|
+
* @param tokens - How many requests a user can make in each time window.
|
|
113
|
+
* @param window - A fixed timeframe
|
|
114
|
+
*/
|
|
115
|
+
static fixedWindow(
|
|
116
|
+
/**
|
|
117
|
+
* How many requests are allowed per window.
|
|
118
|
+
*/
|
|
119
|
+
tokens: number,
|
|
120
|
+
/**
|
|
121
|
+
* The duration in which `tokens` requests are allowed.
|
|
122
|
+
*/
|
|
123
|
+
window: Duration,
|
|
124
|
+
): Algorithm<RegionContext> {
|
|
125
|
+
const windowDuration = ms(window);
|
|
126
|
+
|
|
127
|
+
const script = `
|
|
128
|
+
local key = KEYS[1]
|
|
129
|
+
local window = ARGV[1]
|
|
130
|
+
|
|
131
|
+
local r = redis.call("INCR", key)
|
|
132
|
+
if r == 1 then
|
|
133
|
+
-- The first time this key is set, the value will be 1.
|
|
134
|
+
-- So we only need the expire command once
|
|
135
|
+
redis.call("PEXPIRE", key, window)
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
return r
|
|
139
|
+
`;
|
|
140
|
+
|
|
141
|
+
return async function (ctx: RegionContext, identifier: string) {
|
|
142
|
+
const bucket = Math.floor(Date.now() / windowDuration);
|
|
143
|
+
const key = [identifier, bucket].join(":");
|
|
144
|
+
|
|
145
|
+
if (ctx.cache) {
|
|
146
|
+
const { blocked, reset } = ctx.cache.isBlocked(identifier);
|
|
147
|
+
if (blocked) {
|
|
148
|
+
return {
|
|
149
|
+
success: false,
|
|
150
|
+
limit: tokens,
|
|
151
|
+
remaining: 0,
|
|
152
|
+
reset: reset,
|
|
153
|
+
pending: Promise.resolve(),
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
const usedTokensAfterUpdate = (await ctx.redis.eval(
|
|
158
|
+
script,
|
|
159
|
+
[key],
|
|
160
|
+
[windowDuration],
|
|
161
|
+
)) as number;
|
|
162
|
+
|
|
163
|
+
const success = usedTokensAfterUpdate <= tokens;
|
|
164
|
+
const reset = (bucket + 1) * windowDuration;
|
|
165
|
+
if (ctx.cache && !success) {
|
|
166
|
+
ctx.cache.blockUntil(identifier, reset);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
return {
|
|
170
|
+
success,
|
|
171
|
+
limit: tokens,
|
|
172
|
+
remaining: Math.max(0, tokens - usedTokensAfterUpdate),
|
|
173
|
+
reset,
|
|
174
|
+
pending: Promise.resolve(),
|
|
175
|
+
};
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Combined approach of `slidingLogs` and `fixedWindow` with lower storage
|
|
181
|
+
* costs than `slidingLogs` and improved boundary behavior by calculating a
|
|
182
|
+
* weighted score between two windows.
|
|
183
|
+
*
|
|
184
|
+
* **Pro:**
|
|
185
|
+
*
|
|
186
|
+
* Good performance allows this to scale to very high loads.
|
|
187
|
+
*
|
|
188
|
+
* **Con:**
|
|
189
|
+
*
|
|
190
|
+
* Nothing major.
|
|
191
|
+
*
|
|
192
|
+
* @param tokens - How many requests a user can make in each time window.
|
|
193
|
+
* @param window - The duration in which the user can max X requests.
|
|
194
|
+
*/
|
|
195
|
+
static slidingWindow(
|
|
196
|
+
/**
|
|
197
|
+
* How many requests are allowed per window.
|
|
198
|
+
*/
|
|
199
|
+
tokens: number,
|
|
200
|
+
/**
|
|
201
|
+
* The duration in which `tokens` requests are allowed.
|
|
202
|
+
*/
|
|
203
|
+
window: Duration,
|
|
204
|
+
): Algorithm<RegionContext> {
|
|
205
|
+
const script = `
|
|
206
|
+
local currentKey = KEYS[1] -- identifier including prefixes
|
|
207
|
+
local previousKey = KEYS[2] -- key of the previous bucket
|
|
208
|
+
local tokens = tonumber(ARGV[1]) -- tokens per window
|
|
209
|
+
local now = ARGV[2] -- current timestamp in milliseconds
|
|
210
|
+
local window = ARGV[3] -- interval in milliseconds
|
|
211
|
+
|
|
212
|
+
local requestsInCurrentWindow = redis.call("GET", currentKey)
|
|
213
|
+
if requestsInCurrentWindow == false then
|
|
214
|
+
requestsInCurrentWindow = 0
|
|
215
|
+
end
|
|
216
|
+
|
|
217
|
+
local requestsInPreviousWindow = redis.call("GET", previousKey)
|
|
218
|
+
if requestsInPreviousWindow == false then
|
|
219
|
+
requestsInPreviousWindow = 0
|
|
220
|
+
end
|
|
221
|
+
local percentageInCurrent = ( now % window ) / window
|
|
222
|
+
-- weighted requests to consider from the previous window
|
|
223
|
+
requestsInPreviousWindow = math.floor(( 1 - percentageInCurrent ) * requestsInPreviousWindow)
|
|
224
|
+
if requestsInPreviousWindow + requestsInCurrentWindow >= tokens then
|
|
225
|
+
return -1
|
|
226
|
+
end
|
|
227
|
+
|
|
228
|
+
local newValue = redis.call("INCR", currentKey)
|
|
229
|
+
if newValue == 1 then
|
|
230
|
+
-- The first time this key is set, the value will be 1.
|
|
231
|
+
-- So we only need the expire command once
|
|
232
|
+
redis.call("PEXPIRE", currentKey, window * 2 + 1000) -- Enough time to overlap with a new window + 1 second
|
|
233
|
+
end
|
|
234
|
+
return tokens - ( newValue + requestsInPreviousWindow )
|
|
235
|
+
`;
|
|
236
|
+
const windowSize = ms(window);
|
|
237
|
+
return async function (ctx: RegionContext, identifier: string) {
|
|
238
|
+
const now = Date.now();
|
|
239
|
+
|
|
240
|
+
const currentWindow = Math.floor(now / windowSize);
|
|
241
|
+
const currentKey = [identifier, currentWindow].join(":");
|
|
242
|
+
const previousWindow = currentWindow - 1;
|
|
243
|
+
const previousKey = [identifier, previousWindow].join(":");
|
|
244
|
+
|
|
245
|
+
if (ctx.cache) {
|
|
246
|
+
const { blocked, reset } = ctx.cache.isBlocked(identifier);
|
|
247
|
+
if (blocked) {
|
|
248
|
+
return {
|
|
249
|
+
success: false,
|
|
250
|
+
limit: tokens,
|
|
251
|
+
remaining: 0,
|
|
252
|
+
reset: reset,
|
|
253
|
+
pending: Promise.resolve(),
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
const remaining = (await ctx.redis.eval(
|
|
259
|
+
script,
|
|
260
|
+
[currentKey, previousKey],
|
|
261
|
+
[tokens, now, windowSize],
|
|
262
|
+
)) as number;
|
|
263
|
+
|
|
264
|
+
const success = remaining >= 0;
|
|
265
|
+
const reset = (currentWindow + 1) * windowSize;
|
|
266
|
+
if (ctx.cache && !success) {
|
|
267
|
+
ctx.cache.blockUntil(identifier, reset);
|
|
268
|
+
}
|
|
269
|
+
return {
|
|
270
|
+
success,
|
|
271
|
+
limit: tokens,
|
|
272
|
+
remaining: Math.max(0, remaining),
|
|
273
|
+
reset,
|
|
274
|
+
pending: Promise.resolve(),
|
|
275
|
+
};
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* You have a bucket filled with `{maxTokens}` tokens that refills constantly
|
|
281
|
+
* at `{refillRate}` per `{interval}`.
|
|
282
|
+
* Every request will remove one token from the bucket and if there is no
|
|
283
|
+
* token to take, the request is rejected.
|
|
284
|
+
*
|
|
285
|
+
* **Pro:**
|
|
286
|
+
*
|
|
287
|
+
* - Bursts of requests are smoothed out and you can process them at a constant
|
|
288
|
+
* rate.
|
|
289
|
+
* - Allows to set a higher initial burst limit by setting `maxTokens` higher
|
|
290
|
+
* than `refillRate`
|
|
291
|
+
*/
|
|
292
|
+
static tokenBucket(
|
|
293
|
+
/**
|
|
294
|
+
* How many tokens are refilled per `interval`
|
|
295
|
+
*
|
|
296
|
+
* An interval of `10s` and refillRate of 5 will cause a new token to be added every 2 seconds.
|
|
297
|
+
*/
|
|
298
|
+
refillRate: number,
|
|
299
|
+
/**
|
|
300
|
+
* The interval for the `refillRate`
|
|
301
|
+
*/
|
|
302
|
+
interval: Duration,
|
|
303
|
+
/**
|
|
304
|
+
* Maximum number of tokens.
|
|
305
|
+
* A newly created bucket starts with this many tokens.
|
|
306
|
+
* Useful to allow higher burst limits.
|
|
307
|
+
*/
|
|
308
|
+
maxTokens: number,
|
|
309
|
+
): Algorithm<RegionContext> {
|
|
310
|
+
const script = `
|
|
311
|
+
local key = KEYS[1] -- identifier including prefixes
|
|
312
|
+
local maxTokens = tonumber(ARGV[1]) -- maximum number of tokens
|
|
313
|
+
local interval = tonumber(ARGV[2]) -- size of the window in milliseconds
|
|
314
|
+
local refillRate = tonumber(ARGV[3]) -- how many tokens are refilled after each interval
|
|
315
|
+
local now = tonumber(ARGV[4]) -- current timestamp in milliseconds
|
|
316
|
+
local remaining = 0
|
|
317
|
+
|
|
318
|
+
local bucket = redis.call("HMGET", key, "updatedAt", "tokens")
|
|
319
|
+
|
|
320
|
+
if bucket[1] == false then
|
|
321
|
+
-- The bucket does not exist yet, so we create it and add a ttl.
|
|
322
|
+
remaining = maxTokens - 1
|
|
323
|
+
|
|
324
|
+
redis.call("HMSET", key, "updatedAt", now, "tokens", remaining)
|
|
325
|
+
redis.call("PEXPIRE", key, interval)
|
|
326
|
+
|
|
327
|
+
return {remaining, now + interval}
|
|
328
|
+
end
|
|
329
|
+
|
|
330
|
+
-- The bucket does exist
|
|
331
|
+
|
|
332
|
+
local updatedAt = tonumber(bucket[1])
|
|
333
|
+
local tokens = tonumber(bucket[2])
|
|
334
|
+
|
|
335
|
+
if now >= updatedAt + interval then
|
|
336
|
+
if tokens <= 0 then
|
|
337
|
+
-- No more tokens were left before the refill.
|
|
338
|
+
remaining = math.min(maxTokens, refillRate) - 1
|
|
339
|
+
else
|
|
340
|
+
remaining = math.min(maxTokens, tokens + refillRate) - 1
|
|
341
|
+
end
|
|
342
|
+
redis.call("HMSET", key, "updatedAt", now, "tokens", remaining)
|
|
343
|
+
return {remaining, now + interval}
|
|
344
|
+
end
|
|
345
|
+
|
|
346
|
+
remaining = tokens - 1
|
|
347
|
+
redis.call("HSET", key, "tokens", remaining)
|
|
348
|
+
return {remaining, updatedAt + interval}
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
`;
|
|
352
|
+
|
|
353
|
+
const intervalDuration = ms(interval);
|
|
354
|
+
return async function (ctx: RegionContext, identifier: string) {
|
|
355
|
+
if (ctx.cache) {
|
|
356
|
+
const { blocked, reset } = ctx.cache.isBlocked(identifier);
|
|
357
|
+
if (blocked) {
|
|
358
|
+
return {
|
|
359
|
+
success: false,
|
|
360
|
+
limit: maxTokens,
|
|
361
|
+
remaining: 0,
|
|
362
|
+
reset: reset,
|
|
363
|
+
pending: Promise.resolve(),
|
|
364
|
+
};
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
const now = Date.now();
|
|
369
|
+
const key = [identifier, Math.floor(now / intervalDuration)].join(":");
|
|
370
|
+
|
|
371
|
+
const [remaining, reset] = (await ctx.redis.eval(
|
|
372
|
+
script,
|
|
373
|
+
[key],
|
|
374
|
+
[maxTokens, intervalDuration, refillRate, now],
|
|
375
|
+
)) as [number, number];
|
|
376
|
+
|
|
377
|
+
const success = remaining > 0;
|
|
378
|
+
if (ctx.cache && !success) {
|
|
379
|
+
ctx.cache.blockUntil(identifier, reset);
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
return {
|
|
383
|
+
success,
|
|
384
|
+
limit: maxTokens,
|
|
385
|
+
remaining,
|
|
386
|
+
reset,
|
|
387
|
+
pending: Promise.resolve(),
|
|
388
|
+
};
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* cachedFixedWindow first uses the local cache to decide if a request may pass and then updates
|
|
394
|
+
* it asynchronously.
|
|
395
|
+
* This is experimental and not yet recommended for production use.
|
|
396
|
+
*
|
|
397
|
+
* @experimental
|
|
398
|
+
*
|
|
399
|
+
* Each request inside a fixed time increases a counter.
|
|
400
|
+
* Once the counter reaches the maximum allowed number, all further requests are
|
|
401
|
+
* rejected.
|
|
402
|
+
*
|
|
403
|
+
* **Pro:**
|
|
404
|
+
*
|
|
405
|
+
* - Newer requests are not starved by old ones.
|
|
406
|
+
* - Low storage cost.
|
|
407
|
+
*
|
|
408
|
+
* **Con:**
|
|
409
|
+
*
|
|
410
|
+
* A burst of requests near the boundary of a window can result in a very
|
|
411
|
+
* high request rate because two windows will be filled with requests quickly.
|
|
412
|
+
*
|
|
413
|
+
* @param tokens - How many requests a user can make in each time window.
|
|
414
|
+
* @param window - A fixed timeframe
|
|
415
|
+
*/
|
|
416
|
+
static cachedFixedWindow(
|
|
417
|
+
/**
|
|
418
|
+
* How many requests are allowed per window.
|
|
419
|
+
*/
|
|
420
|
+
tokens: number,
|
|
421
|
+
/**
|
|
422
|
+
* The duration in which `tokens` requests are allowed.
|
|
423
|
+
*/
|
|
424
|
+
window: Duration,
|
|
425
|
+
): Algorithm<RegionContext> {
|
|
426
|
+
const windowDuration = ms(window);
|
|
427
|
+
|
|
428
|
+
const script = `
|
|
429
|
+
local key = KEYS[1]
|
|
430
|
+
local window = ARGV[1]
|
|
431
|
+
|
|
432
|
+
local r = redis.call("INCR", key)
|
|
433
|
+
if r == 1 then
|
|
434
|
+
-- The first time this key is set, the value will be 1.
|
|
435
|
+
-- So we only need the expire command once
|
|
436
|
+
redis.call("PEXPIRE", key, window)
|
|
437
|
+
end
|
|
438
|
+
|
|
439
|
+
return r
|
|
440
|
+
`;
|
|
441
|
+
|
|
442
|
+
return async function (ctx: RegionContext, identifier: string) {
|
|
443
|
+
if (!ctx.cache) {
|
|
444
|
+
throw new Error("This algorithm requires a cache");
|
|
445
|
+
}
|
|
446
|
+
const bucket = Math.floor(Date.now() / windowDuration);
|
|
447
|
+
const key = [identifier, bucket].join(":");
|
|
448
|
+
const reset = (bucket + 1) * windowDuration;
|
|
449
|
+
|
|
450
|
+
const hit = typeof ctx.cache.get(key) === "number";
|
|
451
|
+
if (hit) {
|
|
452
|
+
const cachedTokensAfterUpdate = ctx.cache.incr(key);
|
|
453
|
+
const success = cachedTokensAfterUpdate < tokens;
|
|
454
|
+
|
|
455
|
+
const pending = success
|
|
456
|
+
? ctx.redis.eval(script, [key], [windowDuration]).then((t) => {
|
|
457
|
+
ctx.cache!.set(key, t as number);
|
|
458
|
+
})
|
|
459
|
+
: Promise.resolve();
|
|
460
|
+
|
|
461
|
+
return {
|
|
462
|
+
success,
|
|
463
|
+
limit: tokens,
|
|
464
|
+
remaining: tokens - cachedTokensAfterUpdate,
|
|
465
|
+
reset: reset,
|
|
466
|
+
pending,
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
const usedTokensAfterUpdate = (await ctx.redis.eval(
|
|
471
|
+
script,
|
|
472
|
+
[key],
|
|
473
|
+
[windowDuration],
|
|
474
|
+
)) as number;
|
|
475
|
+
ctx.cache.set(key, usedTokensAfterUpdate);
|
|
476
|
+
const remaining = tokens - usedTokensAfterUpdate;
|
|
477
|
+
|
|
478
|
+
return {
|
|
479
|
+
success: remaining >= 0,
|
|
480
|
+
limit: tokens,
|
|
481
|
+
remaining,
|
|
482
|
+
reset: reset,
|
|
483
|
+
pending: Promise.resolve(),
|
|
484
|
+
};
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import { Ratelimit } from "./ratelimit";
|
|
3
|
+
import { Context } from "./types";
|
|
4
|
+
|
|
5
|
+
type Metrics = {
|
|
6
|
+
requests: number;
|
|
7
|
+
success: number;
|
|
8
|
+
rejected: number;
|
|
9
|
+
};
|
|
10
|
+
export class TestHarness<TContext extends Context> {
|
|
11
|
+
/**
|
|
12
|
+
* Used as prefix for redis keys
|
|
13
|
+
*/
|
|
14
|
+
public readonly id: string;
|
|
15
|
+
|
|
16
|
+
private readonly ratelimit: Ratelimit<TContext>;
|
|
17
|
+
public metrics: Metrics;
|
|
18
|
+
|
|
19
|
+
public latencies: Record<string, { start: number; end: number }> = {};
|
|
20
|
+
|
|
21
|
+
constructor(ratelimit: Ratelimit<TContext>) {
|
|
22
|
+
this.ratelimit = ratelimit;
|
|
23
|
+
this.id = crypto.randomUUID();
|
|
24
|
+
this.metrics = {
|
|
25
|
+
requests: 0,
|
|
26
|
+
success: 0,
|
|
27
|
+
rejected: 0,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* @param rps - req per second
|
|
33
|
+
* @param duration - duration in seconds
|
|
34
|
+
*/
|
|
35
|
+
public async attack(rps: number, duration: number): Promise<void> {
|
|
36
|
+
const promises: Promise<{ success: boolean; pending: Promise<unknown> }>[] = [];
|
|
37
|
+
|
|
38
|
+
for (let i = 0; i < duration; i++) {
|
|
39
|
+
for (let r = 0; r < rps; r++) {
|
|
40
|
+
this.metrics.requests++;
|
|
41
|
+
const id = crypto.randomUUID();
|
|
42
|
+
this.latencies[id] = { start: Date.now(), end: -1 };
|
|
43
|
+
promises.push(
|
|
44
|
+
this.ratelimit.limit(this.id).then((res) => {
|
|
45
|
+
this.latencies[id].end = Date.now();
|
|
46
|
+
return res;
|
|
47
|
+
}),
|
|
48
|
+
);
|
|
49
|
+
await new Promise((r) => setTimeout(r, 1000 / rps));
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
await Promise.all(
|
|
54
|
+
promises.map(async (p) => {
|
|
55
|
+
const { success, pending } = await p;
|
|
56
|
+
await pending;
|
|
57
|
+
if (success) {
|
|
58
|
+
this.metrics.success++;
|
|
59
|
+
} else {
|
|
60
|
+
this.metrics.rejected++;
|
|
61
|
+
}
|
|
62
|
+
}),
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { Redis } from "@upstash/redis";
|
|
2
|
+
import { Analytics } from "../analytics";
|
|
3
|
+
|
|
4
|
+
const redis = Redis.fromEnv();
|
|
5
|
+
|
|
6
|
+
const identifier = new Set<string>();
|
|
7
|
+
|
|
8
|
+
function getId(): string {
|
|
9
|
+
if (identifier.size === 0 || Math.random() > 0.95) {
|
|
10
|
+
const newIp = new Array(4)
|
|
11
|
+
.fill(0)
|
|
12
|
+
.map((_) => Math.floor(Math.random() * 256))
|
|
13
|
+
.join(".");
|
|
14
|
+
identifier.add(newIp);
|
|
15
|
+
}
|
|
16
|
+
return [...identifier][Math.floor(Math.random() * identifier.size)];
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const a = new Analytics({ redis });
|
|
20
|
+
|
|
21
|
+
async function main() {
|
|
22
|
+
const now = Date.now();
|
|
23
|
+
for (let i = 0; i < 1000; i++) {
|
|
24
|
+
console.log(i);
|
|
25
|
+
await Promise.all(
|
|
26
|
+
new Array(100).fill(0).map((_) =>
|
|
27
|
+
a.record({
|
|
28
|
+
time: now - Math.round(Math.random() * 7 * 24 * 60 * 60 * 1000),
|
|
29
|
+
identifier: getId(),
|
|
30
|
+
success: Math.random() > 0.2,
|
|
31
|
+
}),
|
|
32
|
+
),
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
main();
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* EphemeralCache is used to block certain identifiers right away in case they have already exceeded the ratelimit.
|
|
3
|
+
*/
|
|
4
|
+
export interface EphemeralCache {
|
|
5
|
+
isBlocked: (identifier: string) => { blocked: boolean; reset: number };
|
|
6
|
+
blockUntil: (identifier: string, reset: number) => void;
|
|
7
|
+
|
|
8
|
+
set: (key: string, value: number) => void;
|
|
9
|
+
get: (key: string) => number | null;
|
|
10
|
+
|
|
11
|
+
incr: (key: string) => number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export type RegionContext = { redis: Redis; cache?: EphemeralCache };
|
|
15
|
+
export type MultiRegionContext = { redis: Redis[]; cache?: EphemeralCache };
|
|
16
|
+
|
|
17
|
+
export type Context = RegionContext | MultiRegionContext;
|
|
18
|
+
export type RatelimitResponse = {
|
|
19
|
+
/**
|
|
20
|
+
* Whether the request may pass(true) or exceeded the limit(false)
|
|
21
|
+
*/
|
|
22
|
+
success: boolean;
|
|
23
|
+
/**
|
|
24
|
+
* Maximum number of requests allowed within a window.
|
|
25
|
+
*/
|
|
26
|
+
limit: number;
|
|
27
|
+
/**
|
|
28
|
+
* How many requests the user has left within the current window.
|
|
29
|
+
*/
|
|
30
|
+
remaining: number;
|
|
31
|
+
/**
|
|
32
|
+
* Unix timestamp in milliseconds when the limits are reset.
|
|
33
|
+
*/
|
|
34
|
+
reset: number;
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* For the MultiRegion setup we do some synchronizing in the background, after returning the current limit.
|
|
38
|
+
* In most case you can simply ignore this.
|
|
39
|
+
*
|
|
40
|
+
* On Vercel Edge or Cloudflare workers, you need to explicitly handle the pending Promise like this:
|
|
41
|
+
*
|
|
42
|
+
* **Vercel Edge:**
|
|
43
|
+
* https://nextjs.org/docs/api-reference/next/server#nextfetchevent
|
|
44
|
+
*
|
|
45
|
+
* ```ts
|
|
46
|
+
* const { pending } = await ratelimit.limit("id")
|
|
47
|
+
* event.waitUntil(pending)
|
|
48
|
+
* ```
|
|
49
|
+
*
|
|
50
|
+
* **Cloudflare Worker:**
|
|
51
|
+
* https://developers.cloudflare.com/workers/runtime-apis/fetch-event/#syntax-module-worker
|
|
52
|
+
*
|
|
53
|
+
* ```ts
|
|
54
|
+
* const { pending } = await ratelimit.limit("id")
|
|
55
|
+
* context.waitUntil(pending)
|
|
56
|
+
* ```
|
|
57
|
+
*/
|
|
58
|
+
pending: Promise<unknown>;
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
export type Algorithm<TContext> = (
|
|
62
|
+
ctx: TContext,
|
|
63
|
+
identifier: string,
|
|
64
|
+
opts?: {
|
|
65
|
+
cache?: EphemeralCache;
|
|
66
|
+
},
|
|
67
|
+
) => Promise<RatelimitResponse>;
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* This is all we need from the redis sdk.
|
|
71
|
+
*/
|
|
72
|
+
export interface Redis {
|
|
73
|
+
sadd: <TData>(key: string, ...members: TData[]) => Promise<number>;
|
|
74
|
+
|
|
75
|
+
eval: <TArgs extends unknown[], TData = unknown>(
|
|
76
|
+
...args: [script: string, keys: string[], args: TArgs]
|
|
77
|
+
) => Promise<TData>;
|
|
78
|
+
}
|
package/src/version.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const VERSION = "0.4.5-canary.0";
|