@upstash/ratelimit 0.1.0-alpha.0 → 0.1.2
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/README.md +85 -4
- package/esm/global.js +228 -0
- package/esm/mod.js +2 -2
- package/esm/ratelimit.js +129 -0
- package/esm/{ratelimiter.js → region.js} +6 -158
- package/package.json +4 -4
- package/script/global.js +232 -0
- package/script/mod.js +5 -16
- package/script/ratelimit.js +133 -0
- package/script/{ratelimiter.js → region.js} +8 -160
- package/types/global.d.ts +98 -0
- package/types/mod.d.ts +5 -2
- package/types/ratelimit.d.ts +85 -0
- package/types/{ratelimiter.d.ts → region.d.ts} +10 -54
- package/types/types.d.ts +10 -5
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"main": "./script/mod.js",
|
|
4
4
|
"types": "./types/mod.d.ts",
|
|
5
5
|
"name": "@upstash/ratelimit",
|
|
6
|
-
"version": "v0.1.
|
|
6
|
+
"version": "v0.1.2",
|
|
7
7
|
"description": "A serverless ratelimiter built on top of Upstash REST API.",
|
|
8
8
|
"repository": {
|
|
9
9
|
"type": "git",
|
|
@@ -29,16 +29,16 @@
|
|
|
29
29
|
"size-limit": "latest"
|
|
30
30
|
},
|
|
31
31
|
"peerDependencies": {
|
|
32
|
-
"@upstash/redis": "1.3.
|
|
32
|
+
"@upstash/redis": "^1.3.4"
|
|
33
33
|
},
|
|
34
34
|
"size-limit": [
|
|
35
35
|
{
|
|
36
36
|
"path": "esm/mod.js",
|
|
37
|
-
"limit": "
|
|
37
|
+
"limit": "15 KB"
|
|
38
38
|
},
|
|
39
39
|
{
|
|
40
40
|
"path": "script/mod.js",
|
|
41
|
-
"limit": "
|
|
41
|
+
"limit": "15 KB"
|
|
42
42
|
}
|
|
43
43
|
],
|
|
44
44
|
"exports": {
|
package/script/global.js
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.GlobalRatelimit = void 0;
|
|
4
|
+
const duration_js_1 = require("./duration.js");
|
|
5
|
+
const ratelimit_js_1 = require("./ratelimit.js");
|
|
6
|
+
/**
|
|
7
|
+
* Ratelimiter using serverless redis from https://upstash.com/
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```ts
|
|
11
|
+
* const { limit } = new GlobalRatelimit({
|
|
12
|
+
* redis: Redis.fromEnv(),
|
|
13
|
+
* limiter: GlobalRatelimit.fixedWindow(
|
|
14
|
+
* 10, // Allow 10 requests per window of 30 minutes
|
|
15
|
+
* "30 m", // interval of 30 minutes
|
|
16
|
+
* )
|
|
17
|
+
* })
|
|
18
|
+
*
|
|
19
|
+
* ```
|
|
20
|
+
*/
|
|
21
|
+
class GlobalRatelimit extends ratelimit_js_1.Ratelimit {
|
|
22
|
+
/**
|
|
23
|
+
* Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithn of your choice.
|
|
24
|
+
*/
|
|
25
|
+
constructor(config) {
|
|
26
|
+
super({
|
|
27
|
+
prefix: config.prefix,
|
|
28
|
+
limiter: config.limiter,
|
|
29
|
+
ctx: { redis: config.redis },
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Each requests inside a fixed time increases a counter.
|
|
34
|
+
* Once the counter reaches a maxmimum allowed number, all further requests are
|
|
35
|
+
* rejected.
|
|
36
|
+
*
|
|
37
|
+
* **Pro:**
|
|
38
|
+
*
|
|
39
|
+
* - Newer requests are not starved by old ones.
|
|
40
|
+
* - Low storage cost.
|
|
41
|
+
*
|
|
42
|
+
* **Con:**
|
|
43
|
+
*
|
|
44
|
+
* A burst of requests near the boundary of a window can result in a very
|
|
45
|
+
* high request rate because two windows will be filled with requests quickly.
|
|
46
|
+
*
|
|
47
|
+
* @param tokens - How many requests a user can make in each time window.
|
|
48
|
+
* @param window - A fixed timeframe
|
|
49
|
+
*/
|
|
50
|
+
static fixedWindow(
|
|
51
|
+
/**
|
|
52
|
+
* How many requests are allowed per window.
|
|
53
|
+
*/
|
|
54
|
+
tokens,
|
|
55
|
+
/**
|
|
56
|
+
* The duration in which `tokens` requests are allowed.
|
|
57
|
+
*/
|
|
58
|
+
window) {
|
|
59
|
+
const windowDuration = (0, duration_js_1.ms)(window);
|
|
60
|
+
const script = `
|
|
61
|
+
local key = KEYS[1]
|
|
62
|
+
local id = ARGV[1]
|
|
63
|
+
local window = ARGV[2]
|
|
64
|
+
|
|
65
|
+
redis.call("SADD", key, id)
|
|
66
|
+
local members = redis.call("SMEMBERS", key)
|
|
67
|
+
if #members == 1 then
|
|
68
|
+
-- The first time this key is set, the value will be 1.
|
|
69
|
+
-- So we only need the expire command once
|
|
70
|
+
redis.call("PEXPIRE", key, window)
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
return members
|
|
74
|
+
`;
|
|
75
|
+
return async function (ctx, identifier) {
|
|
76
|
+
const requestID = crypto.randomUUID();
|
|
77
|
+
const bucket = Math.floor(Date.now() / windowDuration);
|
|
78
|
+
const key = [identifier, bucket].join(":");
|
|
79
|
+
const dbs = ctx.redis.map((redis) => ({
|
|
80
|
+
redis,
|
|
81
|
+
request: redis.eval(script, [key], [requestID, windowDuration]),
|
|
82
|
+
}));
|
|
83
|
+
const firstResponse = await Promise.any(dbs.map((s) => s.request));
|
|
84
|
+
const usedTokens = firstResponse.length;
|
|
85
|
+
const remaining = tokens - usedTokens - 1;
|
|
86
|
+
/**
|
|
87
|
+
* If the length between two databases does not match, we sync the two databases
|
|
88
|
+
*/
|
|
89
|
+
async function sync() {
|
|
90
|
+
const individualIDs = await Promise.all(dbs.map((s) => s.request));
|
|
91
|
+
const allIDs = Array.from(new Set(individualIDs.flatMap((_) => _)).values());
|
|
92
|
+
for (const db of dbs) {
|
|
93
|
+
const ids = await db.request;
|
|
94
|
+
/**
|
|
95
|
+
* If the bucket in this db is already full, it doesn't matter which ids it contains.
|
|
96
|
+
* So we do not have to sync.
|
|
97
|
+
*/
|
|
98
|
+
if (ids.length >= tokens) {
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
const diff = allIDs.filter((id) => !ids.includes(id));
|
|
102
|
+
/**
|
|
103
|
+
* Don't waste a request if there is nothing to send
|
|
104
|
+
*/
|
|
105
|
+
if (diff.length === 0) {
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
await db.redis.sadd(key, ...allIDs);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Do not await sync. This should not run in the critical path.
|
|
113
|
+
*/
|
|
114
|
+
sync();
|
|
115
|
+
return {
|
|
116
|
+
success: remaining > 0,
|
|
117
|
+
limit: tokens,
|
|
118
|
+
remaining,
|
|
119
|
+
reset: (bucket + 1) * windowDuration,
|
|
120
|
+
};
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Combined approach of `slidingLogs` and `fixedWindow` with lower storage
|
|
125
|
+
* costs than `slidingLogs` and improved boundary behavior by calcualting a
|
|
126
|
+
* weighted score between two windows.
|
|
127
|
+
*
|
|
128
|
+
* **Pro:**
|
|
129
|
+
*
|
|
130
|
+
* Good performance allows this to scale to very high loads.
|
|
131
|
+
*
|
|
132
|
+
* **Con:**
|
|
133
|
+
*
|
|
134
|
+
* Nothing major.
|
|
135
|
+
*
|
|
136
|
+
* @param tokens - How many requests a user can make in each time window.
|
|
137
|
+
* @param window - The duration in which the user can max X requests.
|
|
138
|
+
*/
|
|
139
|
+
static slidingWindow(
|
|
140
|
+
/**
|
|
141
|
+
* How many requests are allowed per window.
|
|
142
|
+
*/
|
|
143
|
+
tokens,
|
|
144
|
+
/**
|
|
145
|
+
* The duration in which `tokens` requests are allowed.
|
|
146
|
+
*/
|
|
147
|
+
window) {
|
|
148
|
+
const windowSize = (0, duration_js_1.ms)(window);
|
|
149
|
+
const script = `
|
|
150
|
+
local currentKey = KEYS[1] -- identifier including prefixes
|
|
151
|
+
local previousKey = KEYS[2] -- key of the previous bucket
|
|
152
|
+
local tokens = tonumber(ARGV[1]) -- tokens per window
|
|
153
|
+
local now = ARGV[2] -- current timestamp in milliseconds
|
|
154
|
+
local window = ARGV[3] -- interval in milliseconds
|
|
155
|
+
local requestID = ARGV[4] -- uuid for this request
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
local currentMembers = redis.call("SMEMBERS", currentKey)
|
|
159
|
+
local requestsInCurrentWindow = #currentMembers
|
|
160
|
+
local previousMembers = redis.call("SMEMBERS", previousKey)
|
|
161
|
+
local requestsInPreviousWindow = #previousMembers
|
|
162
|
+
|
|
163
|
+
local percentageInCurrent = ( now % window) / window
|
|
164
|
+
if requestsInPreviousWindow * ( 1 - percentageInCurrent ) + requestsInCurrentWindow >= tokens then
|
|
165
|
+
return {currentMembers, previousMembers}
|
|
166
|
+
end
|
|
167
|
+
|
|
168
|
+
redis.call("SADD", currentKey, requestID)
|
|
169
|
+
table.insert(currentMembers, requestID)
|
|
170
|
+
if requestsInCurrentWindow == 0 then
|
|
171
|
+
-- The first time this key is set, the value will be 1.
|
|
172
|
+
-- So we only need the expire command once
|
|
173
|
+
redis.call("PEXPIRE", currentKey, window * 2 + 1000) -- Enough time to overlap with a new window + 1 second
|
|
174
|
+
end
|
|
175
|
+
return {currentMembers, previousMembers}
|
|
176
|
+
`;
|
|
177
|
+
const windowDuration = (0, duration_js_1.ms)(window);
|
|
178
|
+
return async function (ctx, identifier) {
|
|
179
|
+
const requestID = crypto.randomUUID();
|
|
180
|
+
const now = Date.now();
|
|
181
|
+
const currentWindow = Math.floor(now / windowSize);
|
|
182
|
+
const currentKey = [identifier, currentWindow].join(":");
|
|
183
|
+
const previousWindow = currentWindow - windowSize;
|
|
184
|
+
const previousKey = [identifier, previousWindow].join(":");
|
|
185
|
+
const dbs = ctx.redis.map((redis) => ({
|
|
186
|
+
redis,
|
|
187
|
+
request: redis.eval(script, [currentKey, previousKey], [tokens, now, windowDuration, requestID]),
|
|
188
|
+
}));
|
|
189
|
+
const percentageInCurrent = (now % windowDuration) / windowDuration;
|
|
190
|
+
const [current, previous] = await Promise.any(dbs.map((s) => s.request));
|
|
191
|
+
const usedTokens = previous.length * (1 - percentageInCurrent) +
|
|
192
|
+
current.length;
|
|
193
|
+
const remaining = tokens - usedTokens;
|
|
194
|
+
/**
|
|
195
|
+
* If a database differs from the consensus, we sync it
|
|
196
|
+
*/
|
|
197
|
+
async function sync() {
|
|
198
|
+
const [individualIDs] = await Promise.all(dbs.map((s) => s.request));
|
|
199
|
+
const allIDs = Array.from(new Set(individualIDs.flatMap((_) => _)).values());
|
|
200
|
+
for (const db of dbs) {
|
|
201
|
+
const [ids] = await db.request;
|
|
202
|
+
/**
|
|
203
|
+
* If the bucket in this db is already full, it doesn't matter which ids it contains.
|
|
204
|
+
* So we do not have to sync.
|
|
205
|
+
*/
|
|
206
|
+
if (ids.length >= tokens) {
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
const diff = allIDs.filter((id) => !ids.includes(id));
|
|
210
|
+
/**
|
|
211
|
+
* Don't waste a request if there is nothing to send
|
|
212
|
+
*/
|
|
213
|
+
if (diff.length === 0) {
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
await db.redis.sadd(currentKey, ...allIDs);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Do not await sync. This should not run in the critical path.
|
|
221
|
+
*/
|
|
222
|
+
sync();
|
|
223
|
+
return {
|
|
224
|
+
success: remaining > 0,
|
|
225
|
+
limit: tokens,
|
|
226
|
+
remaining,
|
|
227
|
+
reset: (currentWindow + 1) * windowDuration,
|
|
228
|
+
};
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
exports.GlobalRatelimit = GlobalRatelimit;
|
package/script/mod.js
CHANGED
|
@@ -1,18 +1,7 @@
|
|
|
1
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
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
|
|
18
|
-
|
|
3
|
+
exports.GlobalRatelimit = exports.Ratelimit = void 0;
|
|
4
|
+
var region_js_1 = require("./region.js");
|
|
5
|
+
Object.defineProperty(exports, "Ratelimit", { enumerable: true, get: function () { return region_js_1.RegionRatelimit; } });
|
|
6
|
+
var global_js_1 = require("./global.js");
|
|
7
|
+
Object.defineProperty(exports, "GlobalRatelimit", { enumerable: true, get: function () { return global_js_1.GlobalRatelimit; } });
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.Ratelimit = void 0;
|
|
4
|
+
/**
|
|
5
|
+
* Ratelimiter using serverless redis from https://upstash.com/
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```ts
|
|
9
|
+
* const { limit } = new Ratelimit({
|
|
10
|
+
* redis: Redis.fromEnv(),
|
|
11
|
+
* limiter: Ratelimit.slidingWindow(
|
|
12
|
+
* 10, // Allow 10 requests per window of 30 minutes
|
|
13
|
+
* "30 m", // interval of 30 minutes
|
|
14
|
+
* )
|
|
15
|
+
* })
|
|
16
|
+
*
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
class Ratelimit {
|
|
20
|
+
constructor(config) {
|
|
21
|
+
Object.defineProperty(this, "limiter", {
|
|
22
|
+
enumerable: true,
|
|
23
|
+
configurable: true,
|
|
24
|
+
writable: true,
|
|
25
|
+
value: void 0
|
|
26
|
+
});
|
|
27
|
+
Object.defineProperty(this, "ctx", {
|
|
28
|
+
enumerable: true,
|
|
29
|
+
configurable: true,
|
|
30
|
+
writable: true,
|
|
31
|
+
value: void 0
|
|
32
|
+
});
|
|
33
|
+
Object.defineProperty(this, "prefix", {
|
|
34
|
+
enumerable: true,
|
|
35
|
+
configurable: true,
|
|
36
|
+
writable: true,
|
|
37
|
+
value: void 0
|
|
38
|
+
});
|
|
39
|
+
/**
|
|
40
|
+
* Determine if a request should pass or be rejected based on the identifier and previously chosen ratelimit.
|
|
41
|
+
*
|
|
42
|
+
* Use this if you want to reject all requests that you can not handle right now.
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* ```ts
|
|
46
|
+
* const ratelimit = new Ratelimit({
|
|
47
|
+
* redis: Redis.fromEnv(),
|
|
48
|
+
* limiter: Ratelimit.slidingWindow(10, "10 s")
|
|
49
|
+
* })
|
|
50
|
+
*
|
|
51
|
+
* const { success } = await ratelimit.limit(id)
|
|
52
|
+
* if (!success){
|
|
53
|
+
* return "Nope"
|
|
54
|
+
* }
|
|
55
|
+
* return "Yes"
|
|
56
|
+
* ```
|
|
57
|
+
*/
|
|
58
|
+
Object.defineProperty(this, "limit", {
|
|
59
|
+
enumerable: true,
|
|
60
|
+
configurable: true,
|
|
61
|
+
writable: true,
|
|
62
|
+
value: async (identifier) => {
|
|
63
|
+
const key = [this.prefix, identifier].join(":");
|
|
64
|
+
return await this.limiter(this.ctx, key);
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
/**
|
|
68
|
+
* Block until the request may pass or timeout is reached.
|
|
69
|
+
*
|
|
70
|
+
* This method returns a promsie that resolves as soon as the request may be processed
|
|
71
|
+
* or after the timeoue has been reached.
|
|
72
|
+
*
|
|
73
|
+
* Use this if you want to delay the request until it is ready to get processed.
|
|
74
|
+
*
|
|
75
|
+
* @example
|
|
76
|
+
* ```ts
|
|
77
|
+
* const ratelimit = new Ratelimit({
|
|
78
|
+
* redis: Redis.fromEnv(),
|
|
79
|
+
* limiter: Ratelimit.slidingWindow(10, "10 s")
|
|
80
|
+
* })
|
|
81
|
+
*
|
|
82
|
+
* const { success } = await ratelimit.blockUntilReady(id, 60_000)
|
|
83
|
+
* if (!success){
|
|
84
|
+
* return "Nope"
|
|
85
|
+
* }
|
|
86
|
+
* return "Yes"
|
|
87
|
+
* ```
|
|
88
|
+
*/
|
|
89
|
+
Object.defineProperty(this, "blockUntilReady", {
|
|
90
|
+
enumerable: true,
|
|
91
|
+
configurable: true,
|
|
92
|
+
writable: true,
|
|
93
|
+
value: async (
|
|
94
|
+
/**
|
|
95
|
+
* An identifier per user or api.
|
|
96
|
+
* Choose a userID, or api token, or ip address.
|
|
97
|
+
*
|
|
98
|
+
* If you want to globally limit your api, you can set a constant string.
|
|
99
|
+
*/
|
|
100
|
+
identifier,
|
|
101
|
+
/**
|
|
102
|
+
* Maximum duration to wait in milliseconds.
|
|
103
|
+
* After this time the request will be denied.
|
|
104
|
+
*/
|
|
105
|
+
timeout) => {
|
|
106
|
+
if (timeout <= 0) {
|
|
107
|
+
throw new Error("timeout must be positive");
|
|
108
|
+
}
|
|
109
|
+
let res;
|
|
110
|
+
const deadline = Date.now() + timeout;
|
|
111
|
+
while (true) {
|
|
112
|
+
res = await this.limit(identifier);
|
|
113
|
+
if (res.success) {
|
|
114
|
+
break;
|
|
115
|
+
}
|
|
116
|
+
if (res.reset === 0) {
|
|
117
|
+
throw new Error("This should not happen");
|
|
118
|
+
}
|
|
119
|
+
const wait = Math.min(res.reset, deadline) - Date.now();
|
|
120
|
+
await new Promise((r) => setTimeout(r, wait));
|
|
121
|
+
if (Date.now() > deadline) {
|
|
122
|
+
break;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return res;
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
this.ctx = config.ctx;
|
|
129
|
+
this.limiter = config.limiter;
|
|
130
|
+
this.prefix = config.prefix ?? "@upstash/ratelimit";
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
exports.Ratelimit = Ratelimit;
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.
|
|
3
|
+
exports.RegionRatelimit = void 0;
|
|
4
4
|
const duration_js_1 = require("./duration.js");
|
|
5
|
+
const ratelimit_js_1 = require("./ratelimit.js");
|
|
5
6
|
/**
|
|
6
7
|
* Ratelimiter using serverless redis from https://upstash.com/
|
|
7
8
|
*
|
|
@@ -17,121 +18,16 @@ const duration_js_1 = require("./duration.js");
|
|
|
17
18
|
*
|
|
18
19
|
* ```
|
|
19
20
|
*/
|
|
20
|
-
class Ratelimit {
|
|
21
|
+
class RegionRatelimit extends ratelimit_js_1.Ratelimit {
|
|
21
22
|
/**
|
|
22
23
|
* Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithn of your choice.
|
|
23
24
|
*/
|
|
24
25
|
constructor(config) {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
value: void 0
|
|
26
|
+
super({
|
|
27
|
+
prefix: config.prefix,
|
|
28
|
+
limiter: config.limiter,
|
|
29
|
+
ctx: { redis: config.redis },
|
|
30
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
31
|
}
|
|
136
32
|
/**
|
|
137
33
|
* Each requests inside a fixed time increases a counter.
|
|
@@ -186,54 +82,6 @@ class Ratelimit {
|
|
|
186
82
|
};
|
|
187
83
|
};
|
|
188
84
|
}
|
|
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
85
|
/**
|
|
238
86
|
* Combined approach of `slidingLogs` and `fixedWindow` with lower storage
|
|
239
87
|
* costs than `slidingLogs` and improved boundary behavior by calcualting a
|
|
@@ -385,4 +233,4 @@ class Ratelimit {
|
|
|
385
233
|
};
|
|
386
234
|
}
|
|
387
235
|
}
|
|
388
|
-
exports.
|
|
236
|
+
exports.RegionRatelimit = RegionRatelimit;
|