@upstash/ratelimit 0.1.0-alpha.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/LICENSE +21 -0
- package/README.md +239 -0
- package/esm/duration.js +21 -0
- package/esm/mod.js +2 -0
- package/esm/package.json +3 -0
- package/esm/ratelimiter.js +384 -0
- package/esm/types.js +1 -0
- package/package.json +51 -0
- package/script/duration.js +25 -0
- package/script/mod.js +18 -0
- package/script/package.json +3 -0
- package/script/ratelimiter.js +388 -0
- package/script/types.js +2 -0
- package/types/duration.d.ts +7 -0
- package/types/mod.d.ts +2 -0
- package/types/ratelimiter.d.ts +177 -0
- package/types/types.d.ts +25 -0
package/package.json
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
{
|
|
2
|
+
"module": "./esm/mod.js",
|
|
3
|
+
"main": "./script/mod.js",
|
|
4
|
+
"types": "./types/mod.d.ts",
|
|
5
|
+
"name": "@upstash/ratelimit",
|
|
6
|
+
"version": "v0.1.0-alpha.0",
|
|
7
|
+
"description": "A serverless ratelimiter built on top of Upstash REST API.",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/upstash/ratelimiter.git"
|
|
11
|
+
},
|
|
12
|
+
"keywords": [
|
|
13
|
+
"rate",
|
|
14
|
+
"limit",
|
|
15
|
+
"redis",
|
|
16
|
+
"serverless",
|
|
17
|
+
"edge",
|
|
18
|
+
"upstash"
|
|
19
|
+
],
|
|
20
|
+
"author": "Andreas Thomas <andreas.thomas@chronark.com>",
|
|
21
|
+
"license": "MIT",
|
|
22
|
+
"bugs": {
|
|
23
|
+
"url": "https://github.com/upstash/ratelimiter/issues"
|
|
24
|
+
},
|
|
25
|
+
"homepage": "https://github.com/upstash/ratelimiter#readme",
|
|
26
|
+
"devDependencies": {
|
|
27
|
+
"@size-limit/preset-small-lib": "latest",
|
|
28
|
+
"@upstash/redis": "1.3.3-alpha.1",
|
|
29
|
+
"size-limit": "latest"
|
|
30
|
+
},
|
|
31
|
+
"peerDependencies": {
|
|
32
|
+
"@upstash/redis": "1.3.3-alpha.1"
|
|
33
|
+
},
|
|
34
|
+
"size-limit": [
|
|
35
|
+
{
|
|
36
|
+
"path": "esm/mod.js",
|
|
37
|
+
"limit": "2 KB"
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
"path": "script/mod.js",
|
|
41
|
+
"limit": "52 KB"
|
|
42
|
+
}
|
|
43
|
+
],
|
|
44
|
+
"exports": {
|
|
45
|
+
".": {
|
|
46
|
+
"import": "./esm/mod.js",
|
|
47
|
+
"require": "./script/mod.js",
|
|
48
|
+
"types": "./types/mod.d.ts"
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ms = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Convert a human readable duration to milliseconds
|
|
6
|
+
*/
|
|
7
|
+
function ms(d) {
|
|
8
|
+
const [timeString, duration] = d.split(" ");
|
|
9
|
+
const time = parseFloat(timeString);
|
|
10
|
+
switch (duration) {
|
|
11
|
+
case "ms":
|
|
12
|
+
return time;
|
|
13
|
+
case "s":
|
|
14
|
+
return time * 1000;
|
|
15
|
+
case "m":
|
|
16
|
+
return time * 1000 * 60;
|
|
17
|
+
case "h":
|
|
18
|
+
return time * 1000 * 60 * 60;
|
|
19
|
+
case "d":
|
|
20
|
+
return time * 1000 * 60 * 60 * 24;
|
|
21
|
+
default:
|
|
22
|
+
throw new Error(`Unable to parse window size: ${d}`);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
exports.ms = ms;
|
package/script/mod.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./ratelimiter.js"), exports);
|
|
18
|
+
__exportStar(require("./types.js"), exports);
|
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Ratelimit = void 0;
|
|
4
|
+
const duration_js_1 = require("./duration.js");
|
|
5
|
+
/**
|
|
6
|
+
* Ratelimiter using serverless redis from https://upstash.com/
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* ```ts
|
|
10
|
+
* const { limit } = new Ratelimit({
|
|
11
|
+
* redis: Redis.fromEnv(),
|
|
12
|
+
* limiter: Ratelimit.slidingWindow(
|
|
13
|
+
* "30 m", // interval of 30 minutes
|
|
14
|
+
* 10, // Allow 10 requests per window of 30 minutes
|
|
15
|
+
* )
|
|
16
|
+
* })
|
|
17
|
+
*
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
class Ratelimit {
|
|
21
|
+
/**
|
|
22
|
+
* Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithn of your choice.
|
|
23
|
+
*/
|
|
24
|
+
constructor(config) {
|
|
25
|
+
Object.defineProperty(this, "redis", {
|
|
26
|
+
enumerable: true,
|
|
27
|
+
configurable: true,
|
|
28
|
+
writable: true,
|
|
29
|
+
value: void 0
|
|
30
|
+
});
|
|
31
|
+
Object.defineProperty(this, "limiter", {
|
|
32
|
+
enumerable: true,
|
|
33
|
+
configurable: true,
|
|
34
|
+
writable: true,
|
|
35
|
+
value: void 0
|
|
36
|
+
});
|
|
37
|
+
Object.defineProperty(this, "prefix", {
|
|
38
|
+
enumerable: true,
|
|
39
|
+
configurable: true,
|
|
40
|
+
writable: true,
|
|
41
|
+
value: void 0
|
|
42
|
+
});
|
|
43
|
+
/**
|
|
44
|
+
* Determine if a request should pass or be rejected based on the identifier and previously chosen ratelimit.
|
|
45
|
+
*
|
|
46
|
+
* Use this if you want to reject all requests that you can not handle right now.
|
|
47
|
+
*
|
|
48
|
+
* @example
|
|
49
|
+
* ```ts
|
|
50
|
+
* const ratelimit = new Ratelimit({
|
|
51
|
+
* redis: Redis.fromEnv(),
|
|
52
|
+
* limiter: Ratelimit.slidingWindow(10, "10 s")
|
|
53
|
+
* })
|
|
54
|
+
*
|
|
55
|
+
* const { success } = await ratelimit.limit(id)
|
|
56
|
+
* if (!success){
|
|
57
|
+
* return "Nope"
|
|
58
|
+
* }
|
|
59
|
+
* return "Yes"
|
|
60
|
+
* ```
|
|
61
|
+
*/
|
|
62
|
+
Object.defineProperty(this, "limit", {
|
|
63
|
+
enumerable: true,
|
|
64
|
+
configurable: true,
|
|
65
|
+
writable: true,
|
|
66
|
+
value: async (identifier) => {
|
|
67
|
+
const key = [this.prefix, identifier].join(":");
|
|
68
|
+
return await this.limiter({ redis: this.redis }, key);
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
/**
|
|
72
|
+
* Block until the request may pass or timeout is reached.
|
|
73
|
+
*
|
|
74
|
+
* This method returns a promsie that resolves as soon as the request may be processed
|
|
75
|
+
* or after the timeoue has been reached.
|
|
76
|
+
*
|
|
77
|
+
* Use this if you want to delay the request until it is ready to get processed.
|
|
78
|
+
*
|
|
79
|
+
* @example
|
|
80
|
+
* ```ts
|
|
81
|
+
* const ratelimit = new Ratelimit({
|
|
82
|
+
* redis: Redis.fromEnv(),
|
|
83
|
+
* limiter: Ratelimit.slidingWindow(10, "10 s")
|
|
84
|
+
* })
|
|
85
|
+
*
|
|
86
|
+
* const { success } = await ratelimit.blockUntilReady(id, 60_000)
|
|
87
|
+
* if (!success){
|
|
88
|
+
* return "Nope"
|
|
89
|
+
* }
|
|
90
|
+
* return "Yes"
|
|
91
|
+
* ```
|
|
92
|
+
*/
|
|
93
|
+
Object.defineProperty(this, "blockUntilReady", {
|
|
94
|
+
enumerable: true,
|
|
95
|
+
configurable: true,
|
|
96
|
+
writable: true,
|
|
97
|
+
value: async (
|
|
98
|
+
/**
|
|
99
|
+
* An identifier per user or api.
|
|
100
|
+
* Choose a userID, or api token, or ip address.
|
|
101
|
+
*
|
|
102
|
+
* If you want to globally limit your api, you can set a constant string.
|
|
103
|
+
*/
|
|
104
|
+
identifier,
|
|
105
|
+
/**
|
|
106
|
+
* Maximum duration to wait in milliseconds.
|
|
107
|
+
* After this time the request will be denied.
|
|
108
|
+
*/
|
|
109
|
+
timeout) => {
|
|
110
|
+
if (timeout <= 0) {
|
|
111
|
+
throw new Error("timeout must be positive");
|
|
112
|
+
}
|
|
113
|
+
let res;
|
|
114
|
+
const deadline = Date.now() + timeout;
|
|
115
|
+
while (true) {
|
|
116
|
+
res = await this.limit(identifier);
|
|
117
|
+
if (res.success) {
|
|
118
|
+
break;
|
|
119
|
+
}
|
|
120
|
+
if (res.reset === 0) {
|
|
121
|
+
throw new Error("This should not happen");
|
|
122
|
+
}
|
|
123
|
+
const wait = Math.min(res.reset, deadline) - Date.now();
|
|
124
|
+
await new Promise((r) => setTimeout(r, wait));
|
|
125
|
+
if (Date.now() > deadline) {
|
|
126
|
+
break;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return res;
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
this.redis = config.redis;
|
|
133
|
+
this.limiter = config.limiter;
|
|
134
|
+
this.prefix = config.prefix ?? "@upstash/ratelimit";
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Each requests inside a fixed time increases a counter.
|
|
138
|
+
* Once the counter reaches a maxmimum allowed number, all further requests are
|
|
139
|
+
* rejected.
|
|
140
|
+
*
|
|
141
|
+
* **Pro:**
|
|
142
|
+
*
|
|
143
|
+
* - Newer requests are not starved by old ones.
|
|
144
|
+
* - Low storage cost.
|
|
145
|
+
*
|
|
146
|
+
* **Con:**
|
|
147
|
+
*
|
|
148
|
+
* A burst of requests near the boundary of a window can result in a very
|
|
149
|
+
* high request rate because two windows will be filled with requests quickly.
|
|
150
|
+
*
|
|
151
|
+
* @param tokens - How many requests a user can make in each time window.
|
|
152
|
+
* @param window - A fixed timeframe
|
|
153
|
+
*/
|
|
154
|
+
static fixedWindow(
|
|
155
|
+
/**
|
|
156
|
+
* How many requests are allowed per window.
|
|
157
|
+
*/
|
|
158
|
+
tokens,
|
|
159
|
+
/**
|
|
160
|
+
* The duration in which `tokens` requests are allowed.
|
|
161
|
+
*/
|
|
162
|
+
window) {
|
|
163
|
+
const windowDuration = (0, duration_js_1.ms)(window);
|
|
164
|
+
const script = `
|
|
165
|
+
local key = KEYS[1]
|
|
166
|
+
local window = ARGV[1]
|
|
167
|
+
|
|
168
|
+
local r = redis.call("INCR", key)
|
|
169
|
+
if r == 1 then
|
|
170
|
+
-- The first time this key is set, the value will be 1.
|
|
171
|
+
-- So we only need the expire command once
|
|
172
|
+
redis.call("PEXPIRE", key, window)
|
|
173
|
+
end
|
|
174
|
+
|
|
175
|
+
return r
|
|
176
|
+
`;
|
|
177
|
+
return async function (ctx, identifier) {
|
|
178
|
+
const bucket = Math.floor(Date.now() / windowDuration);
|
|
179
|
+
const key = [identifier, bucket].join(":");
|
|
180
|
+
const usedTokensAfterUpdate = (await ctx.redis.eval(script, [key], [windowDuration]));
|
|
181
|
+
return {
|
|
182
|
+
success: usedTokensAfterUpdate <= tokens,
|
|
183
|
+
limit: tokens,
|
|
184
|
+
remaining: tokens - usedTokensAfterUpdate,
|
|
185
|
+
reset: (bucket + 1) * windowDuration,
|
|
186
|
+
};
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
// /**
|
|
190
|
+
// * For each request all past requests in the last `{window}` are summed up and
|
|
191
|
+
// * if they exceed `{tokens}`, the request will be rejected.
|
|
192
|
+
// *
|
|
193
|
+
// * **Pro:**
|
|
194
|
+
// *
|
|
195
|
+
// * Does not have the problem of `fixedWindow` at the window boundaries.
|
|
196
|
+
// *
|
|
197
|
+
// * **Con:**
|
|
198
|
+
// *
|
|
199
|
+
// * More expensive to store and compute, which makes this unsuitable for apis
|
|
200
|
+
// * with very high traffic.
|
|
201
|
+
// *
|
|
202
|
+
// * @param window - The duration in which the user can max X requests.
|
|
203
|
+
// * @param tokens - How many requests a user can make in each time window.
|
|
204
|
+
// */
|
|
205
|
+
// static slidingLogs(window: Duration, tokens: number): Ratelimiter {
|
|
206
|
+
// const script = `
|
|
207
|
+
// local key = KEYS[1] -- identifier including prefixes
|
|
208
|
+
// local windowStart = ARGV[1] -- timestamp of window start
|
|
209
|
+
// local windowEnd = ARGV[2] -- timestamp of window end
|
|
210
|
+
// local tokens = ARGV[3] -- tokens per window
|
|
211
|
+
// local now = ARGV[4] -- current timestamp
|
|
212
|
+
// local count = redis.call("ZCOUNT", key, windowStart, windowEnd)
|
|
213
|
+
// if count < tonumber(tokens) then
|
|
214
|
+
// -- Log the current request
|
|
215
|
+
// redis.call("ZADD", key, now, now)
|
|
216
|
+
// -- Remove all previous requests that are outside the window
|
|
217
|
+
// redis.call("ZREMRANGEBYSCORE", key, "-inf", windowStart - 1)
|
|
218
|
+
// end
|
|
219
|
+
// return count
|
|
220
|
+
// `;
|
|
221
|
+
// return async function (ctx: Context, identifier: string) {
|
|
222
|
+
// const windowEnd = Date.now();
|
|
223
|
+
// const windowStart = windowEnd - ms(window);
|
|
224
|
+
// const count = (await ctx.redis.eval(
|
|
225
|
+
// script,
|
|
226
|
+
// [identifier],
|
|
227
|
+
// [windowStart, windowEnd, tokens, Date.now()]
|
|
228
|
+
// )) as number;
|
|
229
|
+
// return {
|
|
230
|
+
// success: count < tokens,
|
|
231
|
+
// limit: tokens,
|
|
232
|
+
// remaining: Math.max(0, tokens - count - 1),
|
|
233
|
+
// reset: windowEnd,
|
|
234
|
+
// };
|
|
235
|
+
// };
|
|
236
|
+
// }
|
|
237
|
+
/**
|
|
238
|
+
* Combined approach of `slidingLogs` and `fixedWindow` with lower storage
|
|
239
|
+
* costs than `slidingLogs` and improved boundary behavior by calcualting a
|
|
240
|
+
* weighted score between two windows.
|
|
241
|
+
*
|
|
242
|
+
* **Pro:**
|
|
243
|
+
*
|
|
244
|
+
* Good performance allows this to scale to very high loads.
|
|
245
|
+
*
|
|
246
|
+
* **Con:**
|
|
247
|
+
*
|
|
248
|
+
* Nothing major.
|
|
249
|
+
*
|
|
250
|
+
* @param tokens - How many requests a user can make in each time window.
|
|
251
|
+
* @param window - The duration in which the user can max X requests.
|
|
252
|
+
*/
|
|
253
|
+
static slidingWindow(
|
|
254
|
+
/**
|
|
255
|
+
* How many requests are allowed per window.
|
|
256
|
+
*/
|
|
257
|
+
tokens,
|
|
258
|
+
/**
|
|
259
|
+
* The duration in which `tokens` requests are allowed.
|
|
260
|
+
*/
|
|
261
|
+
window) {
|
|
262
|
+
const script = `
|
|
263
|
+
local currentKey = KEYS[1] -- identifier including prefixes
|
|
264
|
+
local previousKey = KEYS[2] -- key of the previous bucket
|
|
265
|
+
local tokens = tonumber(ARGV[1]) -- tokens per window
|
|
266
|
+
local now = ARGV[2] -- current timestamp in milliseconds
|
|
267
|
+
local window = ARGV[3] -- interval in milliseconds
|
|
268
|
+
|
|
269
|
+
local requestsInCurrentWindow = redis.call("GET", currentKey)
|
|
270
|
+
if requestsInCurrentWindow == false then
|
|
271
|
+
requestsInCurrentWindow = 0
|
|
272
|
+
end
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
local requestsInPreviousWindow = redis.call("GET", previousKey)
|
|
276
|
+
if requestsInPreviousWindow == false then
|
|
277
|
+
requestsInPreviousWindow = 0
|
|
278
|
+
end
|
|
279
|
+
local percentageInCurrent = ( now % window) / window
|
|
280
|
+
if requestsInPreviousWindow * ( 1 - percentageInCurrent ) + requestsInCurrentWindow >= tokens then
|
|
281
|
+
return 0
|
|
282
|
+
end
|
|
283
|
+
|
|
284
|
+
local newValue = redis.call("INCR", currentKey)
|
|
285
|
+
if newValue == 1 then
|
|
286
|
+
-- The first time this key is set, the value will be 1.
|
|
287
|
+
-- So we only need the expire command once
|
|
288
|
+
redis.call("PEXPIRE", currentKey, window * 2 + 1000) -- Enough time to overlap with a new window + 1 second
|
|
289
|
+
end
|
|
290
|
+
return tokens - newValue
|
|
291
|
+
`;
|
|
292
|
+
const windowSize = (0, duration_js_1.ms)(window);
|
|
293
|
+
return async function (ctx, identifier) {
|
|
294
|
+
const now = Date.now();
|
|
295
|
+
const currentWindow = Math.floor(now / windowSize);
|
|
296
|
+
const currentKey = [identifier, currentWindow].join(":");
|
|
297
|
+
const previousWindow = currentWindow - windowSize;
|
|
298
|
+
const previousKey = [identifier, previousWindow].join(":");
|
|
299
|
+
const remaining = (await ctx.redis.eval(script, [currentKey, previousKey], [tokens, now, windowSize]));
|
|
300
|
+
return {
|
|
301
|
+
success: remaining > 0,
|
|
302
|
+
limit: tokens,
|
|
303
|
+
remaining,
|
|
304
|
+
reset: (currentWindow + 1) * windowSize,
|
|
305
|
+
};
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* You have a bucket filled with `{maxTokens}` tokens that refills constantly
|
|
310
|
+
* at `{refillRate}` per `{interval}`.
|
|
311
|
+
* Every request will remove one token from the bucket and if there is no
|
|
312
|
+
* token to take, the request is rejected.
|
|
313
|
+
*
|
|
314
|
+
* **Pro:**
|
|
315
|
+
*
|
|
316
|
+
* - Bursts of requests are smoothed out and you can process them at a constant
|
|
317
|
+
* rate.
|
|
318
|
+
* - Allows to set a higher initial burst limit by setting `maxTokens` higher
|
|
319
|
+
* than `refillRate`
|
|
320
|
+
*
|
|
321
|
+
* **Usage of Upstash Redis requests:**
|
|
322
|
+
*/
|
|
323
|
+
static tokenBucket(
|
|
324
|
+
/**
|
|
325
|
+
* How many tokens are refilled per `interval`
|
|
326
|
+
*
|
|
327
|
+
* An interval of `10s` and refillRate of 5 will cause a new token to be added every 2 seconds.
|
|
328
|
+
*/
|
|
329
|
+
refillRate,
|
|
330
|
+
/**
|
|
331
|
+
* The interval for the `refillRate`
|
|
332
|
+
*/
|
|
333
|
+
interval,
|
|
334
|
+
/**
|
|
335
|
+
* Maximum number of tokens.
|
|
336
|
+
* A newly created bucket starts with this many tokens.
|
|
337
|
+
* Useful to allow higher burst limits.
|
|
338
|
+
*/
|
|
339
|
+
maxTokens) {
|
|
340
|
+
const script = `
|
|
341
|
+
local key = KEYS[1] -- identifier including prefixes
|
|
342
|
+
local maxTokens = tonumber(ARGV[1]) -- maximum number of tokens
|
|
343
|
+
local interval = tonumber(ARGV[2]) -- size of the window in milliseconds
|
|
344
|
+
local refillRate = tonumber(ARGV[3]) -- how many tokens are refilled after each interval
|
|
345
|
+
local now = tonumber(ARGV[4]) -- current timestamp in milliseconds
|
|
346
|
+
local remaining = 0
|
|
347
|
+
|
|
348
|
+
local bucket = redis.call("HMGET", key, "updatedAt", "tokens")
|
|
349
|
+
|
|
350
|
+
if bucket[1] == false then
|
|
351
|
+
-- The bucket does not exist yet, so we create it and add a ttl.
|
|
352
|
+
remaining = maxTokens - 1
|
|
353
|
+
|
|
354
|
+
redis.call("HMSET", key, "updatedAt", now, "tokens", remaining)
|
|
355
|
+
redis.call("PEXPIRE", key, interval)
|
|
356
|
+
|
|
357
|
+
return {remaining, now + interval}
|
|
358
|
+
end
|
|
359
|
+
|
|
360
|
+
-- The bucket does exist
|
|
361
|
+
|
|
362
|
+
local updatedAt = tonumber(bucket[1])
|
|
363
|
+
local tokens = tonumber(bucket[2])
|
|
364
|
+
|
|
365
|
+
if now >= updatedAt + interval then
|
|
366
|
+
remaining = math.min(maxTokens, tokens + refillRate) - 1
|
|
367
|
+
|
|
368
|
+
redis.call("HMSET", key, "updatedAt", now, "tokens", remaining)
|
|
369
|
+
return {remaining, now + interval}
|
|
370
|
+
end
|
|
371
|
+
|
|
372
|
+
if tokens > 0 then
|
|
373
|
+
remaining = tokens - 1
|
|
374
|
+
redis.call("HMSET", key, "updatedAt", now, "tokens", remaining)
|
|
375
|
+
end
|
|
376
|
+
|
|
377
|
+
return {remaining, updatedAt + interval}
|
|
378
|
+
`;
|
|
379
|
+
const intervalDuration = (0, duration_js_1.ms)(interval);
|
|
380
|
+
return async function (ctx, identifier) {
|
|
381
|
+
const now = Date.now();
|
|
382
|
+
const key = [identifier, Math.floor(now / intervalDuration)].join(":");
|
|
383
|
+
const [remaining, reset] = (await ctx.redis.eval(script, [key], [maxTokens, intervalDuration, refillRate, now]));
|
|
384
|
+
return { success: remaining > 0, limit: maxTokens, remaining, reset };
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
exports.Ratelimit = Ratelimit;
|
package/script/types.js
ADDED
package/types/mod.d.ts
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import type { Duration } from "./duration.js";
|
|
2
|
+
import type { Ratelimiter, RatelimitResponse, Redis } from "./types.js";
|
|
3
|
+
export declare type RatelimitConfig = {
|
|
4
|
+
/**
|
|
5
|
+
* Instance of `@upstash/redis`
|
|
6
|
+
* @see https://github.com/upstash/upstash-redis#quick-start
|
|
7
|
+
*/
|
|
8
|
+
redis: Redis;
|
|
9
|
+
/**
|
|
10
|
+
* The ratelimiter function to use.
|
|
11
|
+
*
|
|
12
|
+
* Choose one of the predefined ones or implement your own.
|
|
13
|
+
* Available algorithms are exposed via static methods:
|
|
14
|
+
* - Ratelimiter.fixedWindow
|
|
15
|
+
* - Ratelimiter.slidingLogs
|
|
16
|
+
* - Ratelimiter.slidingWindow
|
|
17
|
+
* - Ratelimiter.tokenBucket
|
|
18
|
+
*/
|
|
19
|
+
limiter: Ratelimiter;
|
|
20
|
+
/**
|
|
21
|
+
* All keys in redis are prefixed with this.
|
|
22
|
+
*
|
|
23
|
+
* @default `@upstash/ratelimit`
|
|
24
|
+
*/
|
|
25
|
+
prefix?: string;
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Ratelimiter using serverless redis from https://upstash.com/
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* ```ts
|
|
32
|
+
* const { limit } = new Ratelimit({
|
|
33
|
+
* redis: Redis.fromEnv(),
|
|
34
|
+
* limiter: Ratelimit.slidingWindow(
|
|
35
|
+
* "30 m", // interval of 30 minutes
|
|
36
|
+
* 10, // Allow 10 requests per window of 30 minutes
|
|
37
|
+
* )
|
|
38
|
+
* })
|
|
39
|
+
*
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
export declare class Ratelimit {
|
|
43
|
+
private readonly redis;
|
|
44
|
+
private readonly limiter;
|
|
45
|
+
private readonly prefix;
|
|
46
|
+
/**
|
|
47
|
+
* Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithn of your choice.
|
|
48
|
+
*/
|
|
49
|
+
constructor(config: RatelimitConfig);
|
|
50
|
+
/**
|
|
51
|
+
* Determine if a request should pass or be rejected based on the identifier and previously chosen ratelimit.
|
|
52
|
+
*
|
|
53
|
+
* Use this if you want to reject all requests that you can not handle right now.
|
|
54
|
+
*
|
|
55
|
+
* @example
|
|
56
|
+
* ```ts
|
|
57
|
+
* const ratelimit = new Ratelimit({
|
|
58
|
+
* redis: Redis.fromEnv(),
|
|
59
|
+
* limiter: Ratelimit.slidingWindow(10, "10 s")
|
|
60
|
+
* })
|
|
61
|
+
*
|
|
62
|
+
* const { success } = await ratelimit.limit(id)
|
|
63
|
+
* if (!success){
|
|
64
|
+
* return "Nope"
|
|
65
|
+
* }
|
|
66
|
+
* return "Yes"
|
|
67
|
+
* ```
|
|
68
|
+
*/
|
|
69
|
+
limit: (identifier: string) => Promise<RatelimitResponse>;
|
|
70
|
+
/**
|
|
71
|
+
* Block until the request may pass or timeout is reached.
|
|
72
|
+
*
|
|
73
|
+
* This method returns a promsie that resolves as soon as the request may be processed
|
|
74
|
+
* or after the timeoue has been reached.
|
|
75
|
+
*
|
|
76
|
+
* Use this if you want to delay the request until it is ready to get processed.
|
|
77
|
+
*
|
|
78
|
+
* @example
|
|
79
|
+
* ```ts
|
|
80
|
+
* const ratelimit = new Ratelimit({
|
|
81
|
+
* redis: Redis.fromEnv(),
|
|
82
|
+
* limiter: Ratelimit.slidingWindow(10, "10 s")
|
|
83
|
+
* })
|
|
84
|
+
*
|
|
85
|
+
* const { success } = await ratelimit.blockUntilReady(id, 60_000)
|
|
86
|
+
* if (!success){
|
|
87
|
+
* return "Nope"
|
|
88
|
+
* }
|
|
89
|
+
* return "Yes"
|
|
90
|
+
* ```
|
|
91
|
+
*/
|
|
92
|
+
blockUntilReady: (identifier: string, timeout: number) => Promise<RatelimitResponse>;
|
|
93
|
+
/**
|
|
94
|
+
* Each requests inside a fixed time increases a counter.
|
|
95
|
+
* Once the counter reaches a maxmimum allowed number, all further requests are
|
|
96
|
+
* rejected.
|
|
97
|
+
*
|
|
98
|
+
* **Pro:**
|
|
99
|
+
*
|
|
100
|
+
* - Newer requests are not starved by old ones.
|
|
101
|
+
* - Low storage cost.
|
|
102
|
+
*
|
|
103
|
+
* **Con:**
|
|
104
|
+
*
|
|
105
|
+
* A burst of requests near the boundary of a window can result in a very
|
|
106
|
+
* high request rate because two windows will be filled with requests quickly.
|
|
107
|
+
*
|
|
108
|
+
* @param tokens - How many requests a user can make in each time window.
|
|
109
|
+
* @param window - A fixed timeframe
|
|
110
|
+
*/
|
|
111
|
+
static fixedWindow(
|
|
112
|
+
/**
|
|
113
|
+
* How many requests are allowed per window.
|
|
114
|
+
*/
|
|
115
|
+
tokens: number,
|
|
116
|
+
/**
|
|
117
|
+
* The duration in which `tokens` requests are allowed.
|
|
118
|
+
*/
|
|
119
|
+
window: Duration): Ratelimiter;
|
|
120
|
+
/**
|
|
121
|
+
* Combined approach of `slidingLogs` and `fixedWindow` with lower storage
|
|
122
|
+
* costs than `slidingLogs` and improved boundary behavior by calcualting a
|
|
123
|
+
* weighted score between two windows.
|
|
124
|
+
*
|
|
125
|
+
* **Pro:**
|
|
126
|
+
*
|
|
127
|
+
* Good performance allows this to scale to very high loads.
|
|
128
|
+
*
|
|
129
|
+
* **Con:**
|
|
130
|
+
*
|
|
131
|
+
* Nothing major.
|
|
132
|
+
*
|
|
133
|
+
* @param tokens - How many requests a user can make in each time window.
|
|
134
|
+
* @param window - The duration in which the user can max X requests.
|
|
135
|
+
*/
|
|
136
|
+
static slidingWindow(
|
|
137
|
+
/**
|
|
138
|
+
* How many requests are allowed per window.
|
|
139
|
+
*/
|
|
140
|
+
tokens: number,
|
|
141
|
+
/**
|
|
142
|
+
* The duration in which `tokens` requests are allowed.
|
|
143
|
+
*/
|
|
144
|
+
window: Duration): Ratelimiter;
|
|
145
|
+
/**
|
|
146
|
+
* You have a bucket filled with `{maxTokens}` tokens that refills constantly
|
|
147
|
+
* at `{refillRate}` per `{interval}`.
|
|
148
|
+
* Every request will remove one token from the bucket and if there is no
|
|
149
|
+
* token to take, the request is rejected.
|
|
150
|
+
*
|
|
151
|
+
* **Pro:**
|
|
152
|
+
*
|
|
153
|
+
* - Bursts of requests are smoothed out and you can process them at a constant
|
|
154
|
+
* rate.
|
|
155
|
+
* - Allows to set a higher initial burst limit by setting `maxTokens` higher
|
|
156
|
+
* than `refillRate`
|
|
157
|
+
*
|
|
158
|
+
* **Usage of Upstash Redis requests:**
|
|
159
|
+
*/
|
|
160
|
+
static tokenBucket(
|
|
161
|
+
/**
|
|
162
|
+
* How many tokens are refilled per `interval`
|
|
163
|
+
*
|
|
164
|
+
* An interval of `10s` and refillRate of 5 will cause a new token to be added every 2 seconds.
|
|
165
|
+
*/
|
|
166
|
+
refillRate: number,
|
|
167
|
+
/**
|
|
168
|
+
* The interval for the `refillRate`
|
|
169
|
+
*/
|
|
170
|
+
interval: Duration,
|
|
171
|
+
/**
|
|
172
|
+
* Maximum number of tokens.
|
|
173
|
+
* A newly created bucket starts with this many tokens.
|
|
174
|
+
* Useful to allow higher burst limits.
|
|
175
|
+
*/
|
|
176
|
+
maxTokens: number): Ratelimiter;
|
|
177
|
+
}
|