@upstash/ratelimit 2.2.0 → 2.2.1
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 +2 -0
- package/dist/index.d.mts +30 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.js +23 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +23 -1
- package/dist/index.mjs.map +1 -1
- package/docs/algorithms.mdx +169 -0
- package/docs/costs.mdx +112 -0
- package/docs/features.mdx +262 -0
- package/docs/gettingstarted.mdx +220 -0
- package/docs/methods.mdx +206 -0
- package/docs/overview.mdx +159 -0
- package/docs/traffic-protection.mdx +110 -0
- package/package.json +1 -1
- package/src/analytics.ts +110 -0
- package/src/cache.ts +55 -0
- package/src/constants.ts +14 -0
- package/src/deny-list/deny-list.ts +124 -0
- package/src/deny-list/index.ts +1 -0
- package/src/deny-list/ip-deny-list.ts +131 -0
- package/src/deny-list/scripts.ts +26 -0
- package/src/deny-list/time.ts +20 -0
- package/src/duration.ts +37 -0
- package/src/hash.ts +29 -0
- package/src/index.ts +18 -0
- package/src/lua-scripts/hash.ts +95 -0
- package/src/lua-scripts/multi.ts +86 -0
- package/src/lua-scripts/reset.ts +23 -0
- package/src/lua-scripts/single.ts +237 -0
- package/src/multi.ts +610 -0
- package/src/ratelimit.ts +506 -0
- package/src/single.ts +676 -0
- package/src/telemetry.ts +43 -0
- package/src/types.ts +132 -0
- package/src/version.ts +1 -0
package/src/single.ts
ADDED
|
@@ -0,0 +1,676 @@
|
|
|
1
|
+
import type { Duration } from "./duration";
|
|
2
|
+
import { ms } from "./duration";
|
|
3
|
+
import { safeEval } from "./hash";
|
|
4
|
+
import { RESET_SCRIPT, SCRIPTS } from "./lua-scripts/hash";
|
|
5
|
+
import { tokenBucketIdentifierNotFound } from "./lua-scripts/single";
|
|
6
|
+
import { DEFAULT_PREFIX, DYNAMIC_LIMIT_KEY_SUFFIX } from "./constants";
|
|
7
|
+
|
|
8
|
+
import { Ratelimit } from "./ratelimit";
|
|
9
|
+
import { addTelemetry } from "./telemetry";
|
|
10
|
+
import type { Algorithm, RegionContext } from "./types";
|
|
11
|
+
import type { Redis as RedisCore } from "./types";
|
|
12
|
+
|
|
13
|
+
// Fix for https://github.com/upstash/ratelimit-js/issues/125
|
|
14
|
+
type Redis = Pick<RedisCore, "evalsha" | "get" | "set">
|
|
15
|
+
|
|
16
|
+
export type RegionRatelimitConfig = {
|
|
17
|
+
/**
|
|
18
|
+
* Instance of `@upstash/redis`
|
|
19
|
+
* @see https://github.com/upstash/upstash-redis#quick-start
|
|
20
|
+
*/
|
|
21
|
+
redis: Redis;
|
|
22
|
+
/**
|
|
23
|
+
* The ratelimiter function to use.
|
|
24
|
+
*
|
|
25
|
+
* Choose one of the predefined ones or implement your own.
|
|
26
|
+
* Available algorithms are exposed via static methods:
|
|
27
|
+
* - Ratelimiter.fixedWindow
|
|
28
|
+
* - Ratelimiter.slidingWindow
|
|
29
|
+
* - Ratelimiter.tokenBucket
|
|
30
|
+
*/
|
|
31
|
+
limiter: Algorithm<RegionContext>;
|
|
32
|
+
/**
|
|
33
|
+
* All keys in redis are prefixed with this.
|
|
34
|
+
*
|
|
35
|
+
* @default `@upstash/ratelimit`
|
|
36
|
+
*/
|
|
37
|
+
prefix?: string;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* If enabled, the ratelimiter will keep a global cache of identifiers, that have
|
|
41
|
+
* exhausted their ratelimit. In serverless environments this is only possible if
|
|
42
|
+
* you create the ratelimiter instance outside of your handler function. While the
|
|
43
|
+
* function is still hot, the ratelimiter can block requests without having to
|
|
44
|
+
* request data from redis, thus saving time and money.
|
|
45
|
+
*
|
|
46
|
+
* Whenever an identifier has exceeded its limit, the ratelimiter will add it to an
|
|
47
|
+
* internal list together with its reset timestamp. If the same identifier makes a
|
|
48
|
+
* new request before it is reset, we can immediately reject it.
|
|
49
|
+
*
|
|
50
|
+
* Set to `false` to disable.
|
|
51
|
+
*
|
|
52
|
+
* If left undefined, a map is created automatically, but it can only work
|
|
53
|
+
* if the map or the ratelimit instance is created outside your serverless function handler.
|
|
54
|
+
*/
|
|
55
|
+
ephemeralCache?: Map<string, number> | false;
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* If set, the ratelimiter will allow requests to pass after this many milliseconds.
|
|
59
|
+
*
|
|
60
|
+
* Use this if you want to allow requests in case of network problems
|
|
61
|
+
*/
|
|
62
|
+
timeout?: number;
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* If enabled, the ratelimiter will store analytics data in redis, which you can check out at
|
|
66
|
+
* https://console.upstash.com/ratelimit
|
|
67
|
+
*
|
|
68
|
+
* @default false
|
|
69
|
+
*/
|
|
70
|
+
analytics?: boolean;
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* @deprecated Has no affect since v2.0.3. Instead, hash values of scripts are
|
|
74
|
+
* hardcoded in the sdk and it attempts to run the script using EVALSHA (with the hash).
|
|
75
|
+
* If it fails, runs script load.
|
|
76
|
+
*
|
|
77
|
+
* Previously, if enabled, lua scripts were sent to Redis with SCRIPT LOAD durint the first request.
|
|
78
|
+
* In the subsequent requests, hash of the script would be used to invoke the scripts
|
|
79
|
+
*
|
|
80
|
+
* @default true
|
|
81
|
+
*/
|
|
82
|
+
cacheScripts?: boolean;
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* @default false
|
|
86
|
+
*/
|
|
87
|
+
enableProtection?: boolean
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* @default 6
|
|
91
|
+
*/
|
|
92
|
+
denyListThreshold?: number
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* If enabled, the ratelimiter will check for dynamic limits in Redis
|
|
96
|
+
* before applying the regular limit. This allows you to change the rate
|
|
97
|
+
* limit at runtime using setDynamicLimit().
|
|
98
|
+
*
|
|
99
|
+
* When enabled, adds +1 Redis command (GET) to every limit check.
|
|
100
|
+
*
|
|
101
|
+
* @default false
|
|
102
|
+
*/
|
|
103
|
+
dynamicLimits?: boolean;
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Enable telemetry to help us improve the SDK.
|
|
107
|
+
*
|
|
108
|
+
* The sdk name and version are sent to Upstash as a header on the requests
|
|
109
|
+
* made by the redis client you provide.
|
|
110
|
+
*
|
|
111
|
+
* Can also be disabled with the `UPSTASH_DISABLE_TELEMETRY` env variable.
|
|
112
|
+
*
|
|
113
|
+
* @default true
|
|
114
|
+
*/
|
|
115
|
+
enableTelemetry?: boolean;
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Ratelimiter using serverless redis from https://upstash.com/
|
|
120
|
+
*
|
|
121
|
+
* @example
|
|
122
|
+
* ```ts
|
|
123
|
+
* const { limit } = new Ratelimit({
|
|
124
|
+
* redis: Redis.fromEnv(),
|
|
125
|
+
* limiter: Ratelimit.slidingWindow(
|
|
126
|
+
* "30 m", // interval of 30 minutes
|
|
127
|
+
* 10, // Allow 10 requests per window of 30 minutes
|
|
128
|
+
* )
|
|
129
|
+
* })
|
|
130
|
+
*
|
|
131
|
+
* ```
|
|
132
|
+
*
|
|
133
|
+
* @see node_modules/@upstash/ratelimit/docs/gettingstarted.mdx
|
|
134
|
+
*/
|
|
135
|
+
export class RegionRatelimit extends Ratelimit<RegionContext> {
|
|
136
|
+
/**
|
|
137
|
+
* Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithm of your choice.
|
|
138
|
+
*
|
|
139
|
+
* @see node_modules/@upstash/ratelimit/docs/gettingstarted.mdx
|
|
140
|
+
*/
|
|
141
|
+
|
|
142
|
+
constructor(config: RegionRatelimitConfig) {
|
|
143
|
+
super({
|
|
144
|
+
prefix: config.prefix,
|
|
145
|
+
limiter: config.limiter,
|
|
146
|
+
timeout: config.timeout,
|
|
147
|
+
analytics: config.analytics,
|
|
148
|
+
ctx: {
|
|
149
|
+
redis: config.redis as RedisCore,
|
|
150
|
+
prefix: config.prefix ?? DEFAULT_PREFIX,
|
|
151
|
+
},
|
|
152
|
+
ephemeralCache: config.ephemeralCache,
|
|
153
|
+
enableProtection: config.enableProtection,
|
|
154
|
+
denyListThreshold: config.denyListThreshold,
|
|
155
|
+
dynamicLimits: config.dynamicLimits
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
addTelemetry(config.redis, config.enableTelemetry);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Each request inside a fixed time increases a counter.
|
|
163
|
+
* Once the counter reaches the maximum allowed number, all further requests are
|
|
164
|
+
* rejected.
|
|
165
|
+
*
|
|
166
|
+
* **Pro:**
|
|
167
|
+
*
|
|
168
|
+
* - Newer requests are not starved by old ones.
|
|
169
|
+
* - Low storage cost.
|
|
170
|
+
*
|
|
171
|
+
* **Con:**
|
|
172
|
+
*
|
|
173
|
+
* A burst of requests near the boundary of a window can result in a very
|
|
174
|
+
* high request rate because two windows will be filled with requests quickly.
|
|
175
|
+
*
|
|
176
|
+
* @param tokens - How many requests a user can make in each time window.
|
|
177
|
+
* @param window - A fixed timeframe
|
|
178
|
+
* @see node_modules/@upstash/ratelimit/docs/algorithms.mdx
|
|
179
|
+
*/
|
|
180
|
+
static fixedWindow(
|
|
181
|
+
/**
|
|
182
|
+
* How many requests are allowed per window.
|
|
183
|
+
*/
|
|
184
|
+
tokens: number,
|
|
185
|
+
/**
|
|
186
|
+
* The duration in which `tokens` requests are allowed.
|
|
187
|
+
*/
|
|
188
|
+
window: Duration,
|
|
189
|
+
): Algorithm<RegionContext> {
|
|
190
|
+
const windowDuration = ms(window);
|
|
191
|
+
return () => ({
|
|
192
|
+
async limit(ctx: RegionContext, identifier: string, rate?: number) {
|
|
193
|
+
const bucket = Math.floor(Date.now() / windowDuration);
|
|
194
|
+
const key = [identifier, bucket].join(":");
|
|
195
|
+
const incrementBy = rate ?? 1;
|
|
196
|
+
|
|
197
|
+
// Only check cache block if not refunding (negative rate)
|
|
198
|
+
if (ctx.cache && incrementBy > 0) {
|
|
199
|
+
const { blocked, reset } = ctx.cache.isBlocked(identifier);
|
|
200
|
+
if (blocked) {
|
|
201
|
+
return {
|
|
202
|
+
success: false,
|
|
203
|
+
limit: tokens,
|
|
204
|
+
remaining: 0,
|
|
205
|
+
reset: reset,
|
|
206
|
+
pending: Promise.resolve(),
|
|
207
|
+
reason: "cacheBlock"
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Only declare the dynamic limit key when used; every declared key is locked.
|
|
213
|
+
const dynamicLimitKeys = ctx.dynamicLimits
|
|
214
|
+
? [`${ctx.prefix}${DYNAMIC_LIMIT_KEY_SUFFIX}`]
|
|
215
|
+
: [];
|
|
216
|
+
|
|
217
|
+
const [usedTokensAfterUpdate, effectiveLimit] = await safeEval(
|
|
218
|
+
ctx,
|
|
219
|
+
SCRIPTS.singleRegion.fixedWindow.limit,
|
|
220
|
+
[key, ...dynamicLimitKeys],
|
|
221
|
+
[tokens, windowDuration, incrementBy],
|
|
222
|
+
) as [number, number];
|
|
223
|
+
|
|
224
|
+
const success = usedTokensAfterUpdate <= effectiveLimit;
|
|
225
|
+
const remainingTokens = Math.max(0, effectiveLimit - usedTokensAfterUpdate);
|
|
226
|
+
const reset = (bucket + 1) * windowDuration;
|
|
227
|
+
if (ctx.cache) {
|
|
228
|
+
if (!success) {
|
|
229
|
+
ctx.cache.blockUntil(identifier, reset);
|
|
230
|
+
} else if (incrementBy < 0) {
|
|
231
|
+
// Successful refund: unblock from cache
|
|
232
|
+
ctx.cache.pop(identifier);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
return {
|
|
237
|
+
success,
|
|
238
|
+
limit: effectiveLimit,
|
|
239
|
+
remaining: remainingTokens,
|
|
240
|
+
reset,
|
|
241
|
+
pending: Promise.resolve(),
|
|
242
|
+
};
|
|
243
|
+
},
|
|
244
|
+
async getRemaining(ctx: RegionContext, identifier: string) {
|
|
245
|
+
const bucket = Math.floor(Date.now() / windowDuration);
|
|
246
|
+
const key = [identifier, bucket].join(":");
|
|
247
|
+
|
|
248
|
+
// Only declare the dynamic limit key when used; every declared key is locked.
|
|
249
|
+
const dynamicLimitKeys = ctx.dynamicLimits
|
|
250
|
+
? [`${ctx.prefix}${DYNAMIC_LIMIT_KEY_SUFFIX}`]
|
|
251
|
+
: [];
|
|
252
|
+
|
|
253
|
+
const [remaining, effectiveLimit] = await safeEval(
|
|
254
|
+
ctx,
|
|
255
|
+
SCRIPTS.singleRegion.fixedWindow.getRemaining,
|
|
256
|
+
[key, ...dynamicLimitKeys],
|
|
257
|
+
[tokens],
|
|
258
|
+
) as [number, number];
|
|
259
|
+
|
|
260
|
+
return {
|
|
261
|
+
remaining: Math.max(0, remaining),
|
|
262
|
+
reset: (bucket + 1) * windowDuration,
|
|
263
|
+
limit: effectiveLimit
|
|
264
|
+
};
|
|
265
|
+
},
|
|
266
|
+
async resetTokens(ctx: RegionContext, identifier: string) {
|
|
267
|
+
const pattern = [identifier, "*"].join(":");
|
|
268
|
+
if (ctx.cache) {
|
|
269
|
+
ctx.cache.pop(identifier)
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
await safeEval(
|
|
273
|
+
ctx,
|
|
274
|
+
RESET_SCRIPT,
|
|
275
|
+
[pattern],
|
|
276
|
+
[null],
|
|
277
|
+
) as number;
|
|
278
|
+
},
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Combined approach of `slidingLogs` and `fixedWindow` with lower storage
|
|
284
|
+
* costs than `slidingLogs` and improved boundary behavior by calculating a
|
|
285
|
+
* weighted score between two windows.
|
|
286
|
+
*
|
|
287
|
+
* **Pro:**
|
|
288
|
+
*
|
|
289
|
+
* Good performance allows this to scale to very high loads.
|
|
290
|
+
*
|
|
291
|
+
* **Con:**
|
|
292
|
+
*
|
|
293
|
+
* Nothing major.
|
|
294
|
+
*
|
|
295
|
+
* @param tokens - How many requests a user can make in each time window.
|
|
296
|
+
* @param window - The duration in which the user can max X requests.
|
|
297
|
+
* @see node_modules/@upstash/ratelimit/docs/algorithms.mdx
|
|
298
|
+
*/
|
|
299
|
+
static slidingWindow(
|
|
300
|
+
/**
|
|
301
|
+
* How many requests are allowed per window.
|
|
302
|
+
*/
|
|
303
|
+
tokens: number,
|
|
304
|
+
/**
|
|
305
|
+
* The duration in which `tokens` requests are allowed.
|
|
306
|
+
*/
|
|
307
|
+
window: Duration,
|
|
308
|
+
): Algorithm<RegionContext> {
|
|
309
|
+
const windowSize = ms(window);
|
|
310
|
+
return () => ({
|
|
311
|
+
async limit(ctx: RegionContext, identifier: string, rate?: number) {
|
|
312
|
+
const now = Date.now();
|
|
313
|
+
const currentWindow = Math.floor(now / windowSize);
|
|
314
|
+
const currentKey = [identifier, currentWindow].join(":");
|
|
315
|
+
const previousWindow = currentWindow - 1;
|
|
316
|
+
const previousKey = [identifier, previousWindow].join(":");
|
|
317
|
+
const incrementBy = rate ?? 1;
|
|
318
|
+
|
|
319
|
+
// Only check cache block if not refunding (negative rate)
|
|
320
|
+
if (ctx.cache && incrementBy > 0) {
|
|
321
|
+
const { blocked, reset } = ctx.cache.isBlocked(identifier);
|
|
322
|
+
if (blocked) {
|
|
323
|
+
return {
|
|
324
|
+
success: false,
|
|
325
|
+
limit: tokens,
|
|
326
|
+
remaining: 0,
|
|
327
|
+
reset: reset,
|
|
328
|
+
pending: Promise.resolve(),
|
|
329
|
+
reason: "cacheBlock"
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// Only declare the dynamic limit key when used; every declared key is locked.
|
|
335
|
+
const dynamicLimitKeys = ctx.dynamicLimits
|
|
336
|
+
? [`${ctx.prefix}${DYNAMIC_LIMIT_KEY_SUFFIX}`]
|
|
337
|
+
: [];
|
|
338
|
+
|
|
339
|
+
const [remainingTokens, effectiveLimit] = await safeEval(
|
|
340
|
+
ctx,
|
|
341
|
+
SCRIPTS.singleRegion.slidingWindow.limit,
|
|
342
|
+
[currentKey, previousKey, ...dynamicLimitKeys],
|
|
343
|
+
[tokens, now, windowSize, incrementBy],
|
|
344
|
+
) as [number, number];
|
|
345
|
+
|
|
346
|
+
const success = remainingTokens >= 0;
|
|
347
|
+
const reset = (currentWindow + 1) * windowSize;
|
|
348
|
+
|
|
349
|
+
if (ctx.cache) {
|
|
350
|
+
if (!success) {
|
|
351
|
+
ctx.cache.blockUntil(identifier, reset);
|
|
352
|
+
} else if (incrementBy < 0) {
|
|
353
|
+
// Successful refund: unblock from cache
|
|
354
|
+
ctx.cache.pop(identifier);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
return {
|
|
359
|
+
success,
|
|
360
|
+
limit: effectiveLimit,
|
|
361
|
+
remaining: Math.max(0, remainingTokens),
|
|
362
|
+
reset,
|
|
363
|
+
pending: Promise.resolve(),
|
|
364
|
+
};
|
|
365
|
+
},
|
|
366
|
+
async getRemaining(ctx: RegionContext, identifier: string) {
|
|
367
|
+
const now = Date.now();
|
|
368
|
+
const currentWindow = Math.floor(now / windowSize);
|
|
369
|
+
const currentKey = [identifier, currentWindow].join(":");
|
|
370
|
+
const previousWindow = currentWindow - 1;
|
|
371
|
+
const previousKey = [identifier, previousWindow].join(":");
|
|
372
|
+
|
|
373
|
+
// Only declare the dynamic limit key when used; every declared key is locked.
|
|
374
|
+
const dynamicLimitKeys = ctx.dynamicLimits
|
|
375
|
+
? [`${ctx.prefix}${DYNAMIC_LIMIT_KEY_SUFFIX}`]
|
|
376
|
+
: [];
|
|
377
|
+
|
|
378
|
+
const [remaining, effectiveLimit] = await safeEval(
|
|
379
|
+
ctx,
|
|
380
|
+
SCRIPTS.singleRegion.slidingWindow.getRemaining,
|
|
381
|
+
[currentKey, previousKey, ...dynamicLimitKeys],
|
|
382
|
+
[tokens, now, windowSize],
|
|
383
|
+
) as [number, number];
|
|
384
|
+
|
|
385
|
+
return {
|
|
386
|
+
remaining: Math.max(0, remaining),
|
|
387
|
+
reset: (currentWindow + 1) * windowSize,
|
|
388
|
+
limit: effectiveLimit
|
|
389
|
+
}
|
|
390
|
+
},
|
|
391
|
+
async resetTokens(ctx: RegionContext, identifier: string) {
|
|
392
|
+
const pattern = [identifier, "*"].join(":");
|
|
393
|
+
if (ctx.cache) {
|
|
394
|
+
ctx.cache.pop(identifier)
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
await safeEval(
|
|
398
|
+
ctx,
|
|
399
|
+
RESET_SCRIPT,
|
|
400
|
+
[pattern],
|
|
401
|
+
[null],
|
|
402
|
+
) as number;
|
|
403
|
+
},
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* You have a bucket filled with `{maxTokens}` tokens that refills constantly
|
|
409
|
+
* at `{refillRate}` per `{interval}`.
|
|
410
|
+
* Every request will remove one token from the bucket and if there is no
|
|
411
|
+
* token to take, the request is rejected.
|
|
412
|
+
*
|
|
413
|
+
* **Pro:**
|
|
414
|
+
*
|
|
415
|
+
* - Bursts of requests are smoothed out and you can process them at a constant
|
|
416
|
+
* rate.
|
|
417
|
+
* - Allows to set a higher initial burst limit by setting `maxTokens` higher
|
|
418
|
+
* than `refillRate`
|
|
419
|
+
*
|
|
420
|
+
* @see node_modules/@upstash/ratelimit/docs/algorithms.mdx
|
|
421
|
+
*/
|
|
422
|
+
static tokenBucket(
|
|
423
|
+
/**
|
|
424
|
+
* How many tokens are refilled per `interval`
|
|
425
|
+
*
|
|
426
|
+
* An interval of `10s` and refillRate of 5 will cause a new token to be added every 2 seconds.
|
|
427
|
+
*/
|
|
428
|
+
refillRate: number,
|
|
429
|
+
/**
|
|
430
|
+
* The interval for the `refillRate`
|
|
431
|
+
*/
|
|
432
|
+
interval: Duration,
|
|
433
|
+
/**
|
|
434
|
+
* Maximum number of tokens.
|
|
435
|
+
* A newly created bucket starts with this many tokens.
|
|
436
|
+
* Useful to allow higher burst limits.
|
|
437
|
+
*/
|
|
438
|
+
maxTokens: number,
|
|
439
|
+
): Algorithm<RegionContext> {
|
|
440
|
+
const intervalDuration = ms(interval);
|
|
441
|
+
return () => ({
|
|
442
|
+
async limit(ctx: RegionContext, identifier: string, rate?: number) {
|
|
443
|
+
const now = Date.now();
|
|
444
|
+
const incrementBy = rate ?? 1;
|
|
445
|
+
|
|
446
|
+
// Only check cache block if not refunding (negative rate)
|
|
447
|
+
if (ctx.cache && incrementBy > 0) {
|
|
448
|
+
const { blocked, reset } = ctx.cache.isBlocked(identifier);
|
|
449
|
+
if (blocked) {
|
|
450
|
+
return {
|
|
451
|
+
success: false,
|
|
452
|
+
limit: maxTokens,
|
|
453
|
+
remaining: 0,
|
|
454
|
+
reset: reset,
|
|
455
|
+
pending: Promise.resolve(),
|
|
456
|
+
reason: "cacheBlock"
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
// Only declare the dynamic limit key when used; every declared key is locked.
|
|
462
|
+
const dynamicLimitKeys = ctx.dynamicLimits
|
|
463
|
+
? [`${ctx.prefix}${DYNAMIC_LIMIT_KEY_SUFFIX}`]
|
|
464
|
+
: [];
|
|
465
|
+
|
|
466
|
+
const [remaining, reset, effectiveLimit] = await safeEval(
|
|
467
|
+
ctx,
|
|
468
|
+
SCRIPTS.singleRegion.tokenBucket.limit,
|
|
469
|
+
[identifier, ...dynamicLimitKeys],
|
|
470
|
+
[maxTokens, intervalDuration, refillRate, now, incrementBy],
|
|
471
|
+
) as [number, number, number];
|
|
472
|
+
|
|
473
|
+
const success = remaining >= 0;
|
|
474
|
+
|
|
475
|
+
if (ctx.cache) {
|
|
476
|
+
if (!success) {
|
|
477
|
+
ctx.cache.blockUntil(identifier, reset);
|
|
478
|
+
} else if (incrementBy < 0) {
|
|
479
|
+
// Successful refund: unblock from cache
|
|
480
|
+
ctx.cache.pop(identifier);
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
return {
|
|
485
|
+
success,
|
|
486
|
+
limit: effectiveLimit,
|
|
487
|
+
remaining: Math.max(0, remaining),
|
|
488
|
+
reset,
|
|
489
|
+
pending: Promise.resolve(),
|
|
490
|
+
};
|
|
491
|
+
},
|
|
492
|
+
async getRemaining(ctx: RegionContext, identifier: string) {
|
|
493
|
+
// Only declare the dynamic limit key when used; every declared key is locked.
|
|
494
|
+
const dynamicLimitKeys = ctx.dynamicLimits
|
|
495
|
+
? [`${ctx.prefix}${DYNAMIC_LIMIT_KEY_SUFFIX}`]
|
|
496
|
+
: [];
|
|
497
|
+
|
|
498
|
+
const [remainingTokens, refilledAt, effectiveLimit] = await safeEval(
|
|
499
|
+
ctx,
|
|
500
|
+
SCRIPTS.singleRegion.tokenBucket.getRemaining,
|
|
501
|
+
[identifier, ...dynamicLimitKeys],
|
|
502
|
+
[maxTokens],
|
|
503
|
+
) as [number, number, number];
|
|
504
|
+
|
|
505
|
+
const freshRefillAt = Date.now() + intervalDuration
|
|
506
|
+
const identifierRefillsAt = refilledAt + intervalDuration
|
|
507
|
+
|
|
508
|
+
return {
|
|
509
|
+
remaining: Math.max(0, remainingTokens),
|
|
510
|
+
reset: refilledAt === tokenBucketIdentifierNotFound ? freshRefillAt : identifierRefillsAt,
|
|
511
|
+
limit: effectiveLimit
|
|
512
|
+
};
|
|
513
|
+
},
|
|
514
|
+
async resetTokens(ctx: RegionContext, identifier: string) {
|
|
515
|
+
const pattern = identifier;
|
|
516
|
+
if (ctx.cache) {
|
|
517
|
+
ctx.cache.pop(identifier)
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
await safeEval(
|
|
521
|
+
ctx,
|
|
522
|
+
RESET_SCRIPT,
|
|
523
|
+
[pattern],
|
|
524
|
+
[null],
|
|
525
|
+
) as number;
|
|
526
|
+
},
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
/**
|
|
530
|
+
* cachedFixedWindow first uses the local cache to decide if a request may pass and then updates
|
|
531
|
+
* it asynchronously.
|
|
532
|
+
* This is experimental and not yet recommended for production use.
|
|
533
|
+
*
|
|
534
|
+
* @experimental
|
|
535
|
+
*
|
|
536
|
+
* Each request inside a fixed time increases a counter.
|
|
537
|
+
* Once the counter reaches the maximum allowed number, all further requests are
|
|
538
|
+
* rejected.
|
|
539
|
+
*
|
|
540
|
+
* **Pro:**
|
|
541
|
+
*
|
|
542
|
+
* - Newer requests are not starved by old ones.
|
|
543
|
+
* - Low storage cost.
|
|
544
|
+
*
|
|
545
|
+
* **Con:**
|
|
546
|
+
*
|
|
547
|
+
* A burst of requests near the boundary of a window can result in a very
|
|
548
|
+
* high request rate because two windows will be filled with requests quickly.
|
|
549
|
+
*
|
|
550
|
+
* @param tokens - How many requests a user can make in each time window.
|
|
551
|
+
* @param window - A fixed timeframe
|
|
552
|
+
* @see node_modules/@upstash/ratelimit/docs/algorithms.mdx
|
|
553
|
+
*/
|
|
554
|
+
static cachedFixedWindow(
|
|
555
|
+
/**
|
|
556
|
+
* How many requests are allowed per window.
|
|
557
|
+
*/
|
|
558
|
+
tokens: number,
|
|
559
|
+
/**
|
|
560
|
+
* The duration in which `tokens` requests are allowed.
|
|
561
|
+
*/
|
|
562
|
+
window: Duration,
|
|
563
|
+
): Algorithm<RegionContext> {
|
|
564
|
+
const windowDuration = ms(window);
|
|
565
|
+
|
|
566
|
+
return () => ({
|
|
567
|
+
async limit(ctx: RegionContext, identifier: string, rate?: number) {
|
|
568
|
+
if (!ctx.cache) {
|
|
569
|
+
throw new Error("This algorithm requires a cache");
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
if (ctx.dynamicLimits) {
|
|
573
|
+
console.warn(
|
|
574
|
+
"Warning: Dynamic limits are not yet supported for cachedFixedWindow algorithm. " +
|
|
575
|
+
"The dynamicLimits option will be ignored."
|
|
576
|
+
);
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
const bucket = Math.floor(Date.now() / windowDuration);
|
|
580
|
+
const key = [identifier, bucket].join(":");
|
|
581
|
+
const reset = (bucket + 1) * windowDuration;
|
|
582
|
+
const incrementBy = rate ?? 1;
|
|
583
|
+
|
|
584
|
+
const hit = typeof ctx.cache.get(key) === "number";
|
|
585
|
+
if (hit) {
|
|
586
|
+
const cachedTokensAfterUpdate = ctx.cache.incr(key, incrementBy);
|
|
587
|
+
// used == tokens still succeeds, matching the cache-miss path below
|
|
588
|
+
const success = cachedTokensAfterUpdate <= tokens;
|
|
589
|
+
|
|
590
|
+
const pending = success
|
|
591
|
+
? safeEval(
|
|
592
|
+
ctx,
|
|
593
|
+
SCRIPTS.singleRegion.cachedFixedWindow.limit,
|
|
594
|
+
[key],
|
|
595
|
+
[windowDuration, incrementBy]
|
|
596
|
+
)
|
|
597
|
+
: Promise.resolve();
|
|
598
|
+
|
|
599
|
+
return {
|
|
600
|
+
success,
|
|
601
|
+
limit: tokens,
|
|
602
|
+
remaining: tokens - cachedTokensAfterUpdate,
|
|
603
|
+
reset: reset,
|
|
604
|
+
pending,
|
|
605
|
+
};
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
const usedTokensAfterUpdate = await safeEval(
|
|
609
|
+
ctx,
|
|
610
|
+
SCRIPTS.singleRegion.cachedFixedWindow.limit,
|
|
611
|
+
[key],
|
|
612
|
+
[windowDuration, incrementBy]
|
|
613
|
+
) as number;
|
|
614
|
+
ctx.cache.set(key, usedTokensAfterUpdate);
|
|
615
|
+
const remaining = tokens - usedTokensAfterUpdate;
|
|
616
|
+
|
|
617
|
+
return {
|
|
618
|
+
success: remaining >= 0,
|
|
619
|
+
limit: tokens,
|
|
620
|
+
remaining,
|
|
621
|
+
reset: reset,
|
|
622
|
+
pending: Promise.resolve(),
|
|
623
|
+
};
|
|
624
|
+
},
|
|
625
|
+
async getRemaining(ctx: RegionContext, identifier: string) {
|
|
626
|
+
if (!ctx.cache) {
|
|
627
|
+
throw new Error("This algorithm requires a cache");
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
const bucket = Math.floor(Date.now() / windowDuration);
|
|
631
|
+
const key = [identifier, bucket].join(":");
|
|
632
|
+
|
|
633
|
+
const hit = typeof ctx.cache.get(key) === "number";
|
|
634
|
+
if (hit) {
|
|
635
|
+
const cachedUsedTokens = ctx.cache.get(key) ?? 0;
|
|
636
|
+
return {
|
|
637
|
+
remaining: Math.max(0, tokens - cachedUsedTokens),
|
|
638
|
+
reset: (bucket + 1) * windowDuration,
|
|
639
|
+
limit: tokens
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
const usedTokens = await safeEval(
|
|
644
|
+
ctx,
|
|
645
|
+
SCRIPTS.singleRegion.cachedFixedWindow.getRemaining,
|
|
646
|
+
[key],
|
|
647
|
+
[null],
|
|
648
|
+
) as number;
|
|
649
|
+
return {
|
|
650
|
+
remaining: Math.max(0, tokens - usedTokens),
|
|
651
|
+
reset: (bucket + 1) * windowDuration,
|
|
652
|
+
limit: tokens
|
|
653
|
+
};
|
|
654
|
+
},
|
|
655
|
+
async resetTokens(ctx: RegionContext, identifier: string) {
|
|
656
|
+
// Empty the cache
|
|
657
|
+
if (!ctx.cache) {
|
|
658
|
+
throw new Error("This algorithm requires a cache");
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
const bucket = Math.floor(Date.now() / windowDuration);
|
|
662
|
+
const key = [identifier, bucket].join(":");
|
|
663
|
+
ctx.cache.pop(key)
|
|
664
|
+
|
|
665
|
+
const pattern = [identifier, "*"].join(":");
|
|
666
|
+
|
|
667
|
+
await safeEval(
|
|
668
|
+
ctx,
|
|
669
|
+
RESET_SCRIPT,
|
|
670
|
+
[pattern],
|
|
671
|
+
[null],
|
|
672
|
+
) as number;
|
|
673
|
+
},
|
|
674
|
+
});
|
|
675
|
+
}
|
|
676
|
+
}
|
package/src/telemetry.ts
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { VERSION } from "./version";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Minimal shape of the redis client we need for telemetry. `addTelemetry` is
|
|
5
|
+
* `protected` in `@upstash/redis`, so it is not part of the public types.
|
|
6
|
+
*/
|
|
7
|
+
type TelemetryCapableRedis = {
|
|
8
|
+
addTelemetry?: (telemetry: { sdk?: string; platform?: string; runtime?: string }) => void;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* The redis client appends to the telemetry header on every addTelemetry call,
|
|
13
|
+
* so tag each client only once no matter how many Ratelimit instances are
|
|
14
|
+
* created with it.
|
|
15
|
+
*/
|
|
16
|
+
const taggedClients = new WeakSet<object>();
|
|
17
|
+
|
|
18
|
+
const getSafeEnv = (): Record<string, string | undefined> =>
|
|
19
|
+
typeof process === "object" && process && typeof process.env === "object" ? process.env : {};
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Reports the sdk name and version to Upstash through the redis client's
|
|
23
|
+
* telemetry headers. The redis client itself already reports the platform and
|
|
24
|
+
* the runtime, so we only append our own sdk tag, resulting in a header like
|
|
25
|
+
* `@upstash/redis@1.35.0,@upstash/ratelimit@2.0.8`.
|
|
26
|
+
*
|
|
27
|
+
* Opt out with `enableTelemetry: false` in the Ratelimit config, with the same
|
|
28
|
+
* option on the redis client, or with the `UPSTASH_DISABLE_TELEMETRY` env var.
|
|
29
|
+
*/
|
|
30
|
+
export const addTelemetry = (redis: unknown, enableTelemetry = true): void => {
|
|
31
|
+
if (!enableTelemetry || getSafeEnv().UPSTASH_DISABLE_TELEMETRY) return;
|
|
32
|
+
if (!redis || typeof redis !== "object") return;
|
|
33
|
+
if (taggedClients.has(redis)) return;
|
|
34
|
+
taggedClients.add(redis);
|
|
35
|
+
|
|
36
|
+
try {
|
|
37
|
+
const client = redis as TelemetryCapableRedis;
|
|
38
|
+
// addTelemetry is intentionally hidden from the public types of @upstash/redis
|
|
39
|
+
client.addTelemetry?.({ sdk: `@upstash/ratelimit@${VERSION}` });
|
|
40
|
+
} catch {
|
|
41
|
+
// telemetry must never break the client
|
|
42
|
+
}
|
|
43
|
+
};
|