@upstash/ratelimit 0.4.4 → 1.0.0-canary
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 +11 -4
- package/dist/index.d.mts +556 -0
- package/dist/index.js +64 -64
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +64 -64
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -43
package/README.md
CHANGED
|
@@ -6,8 +6,8 @@
|
|
|
6
6
|
It is the only connectionless (HTTP based) rate limiting library and designed
|
|
7
7
|
for:
|
|
8
8
|
|
|
9
|
-
- Serverless functions (AWS Lambda, Vercel
|
|
10
|
-
- Cloudflare Workers
|
|
9
|
+
- Serverless functions (AWS Lambda, Vercel ....)
|
|
10
|
+
- Cloudflare Workers & Pages
|
|
11
11
|
- Vercel Edge
|
|
12
12
|
- Fastly Compute@Edge
|
|
13
13
|
- Next.js, Jamstack ...
|
|
@@ -80,7 +80,7 @@ documentation on how to create a redis instance.
|
|
|
80
80
|
|
|
81
81
|
```ts
|
|
82
82
|
import { Ratelimit } from "@upstash/ratelimit"; // for deno: see above
|
|
83
|
-
import { Redis } from "@upstash/redis";
|
|
83
|
+
import { Redis } from "@upstash/redis"; // see below for cloudflare and fastly adapters
|
|
84
84
|
|
|
85
85
|
// Create a new ratelimiter, that allows 10 requests per 10 seconds
|
|
86
86
|
const ratelimit = new Ratelimit({
|
|
@@ -91,7 +91,7 @@ const ratelimit = new Ratelimit({
|
|
|
91
91
|
* Optional prefix for the keys used in redis. This is useful if you want to share a redis
|
|
92
92
|
* instance with other applications and want to avoid key collisions. The default prefix is
|
|
93
93
|
* "@upstash/ratelimit"
|
|
94
|
-
*/
|
|
94
|
+
*/
|
|
95
95
|
prefix: "@upstash/ratelimit",
|
|
96
96
|
});
|
|
97
97
|
|
|
@@ -107,6 +107,13 @@ doExpensiveCalculation();
|
|
|
107
107
|
return "Here you go!";
|
|
108
108
|
```
|
|
109
109
|
|
|
110
|
+
For Cloudflare Workers and Fastly Compute@Edge, you can use the following imports:
|
|
111
|
+
|
|
112
|
+
```ts
|
|
113
|
+
import { Redis } from "@upstash/redis/cloudflare"; // for cloudflare workers and pages
|
|
114
|
+
import { Redis } from "@upstash/redis/fastly"; // for fastly compute@edge
|
|
115
|
+
```
|
|
116
|
+
|
|
110
117
|
[Here's a complete nextjs example](https://github.com/upstash/ratelimit/tree/main/examples/nextjs)
|
|
111
118
|
|
|
112
119
|
The `limit` method returns some more metadata that might be useful to you:
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,556 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* EphemeralCache is used to block certain identifiers right away in case they have already exceeded the ratelimit.
|
|
3
|
+
*/
|
|
4
|
+
interface EphemeralCache {
|
|
5
|
+
isBlocked: (identifier: string) => {
|
|
6
|
+
blocked: boolean;
|
|
7
|
+
reset: number;
|
|
8
|
+
};
|
|
9
|
+
blockUntil: (identifier: string, reset: number) => void;
|
|
10
|
+
set: (key: string, value: number) => void;
|
|
11
|
+
get: (key: string) => number | null;
|
|
12
|
+
incr: (key: string) => number;
|
|
13
|
+
}
|
|
14
|
+
type RegionContext = {
|
|
15
|
+
redis: Redis;
|
|
16
|
+
cache?: EphemeralCache;
|
|
17
|
+
};
|
|
18
|
+
type MultiRegionContext = {
|
|
19
|
+
redis: Redis[];
|
|
20
|
+
cache?: EphemeralCache;
|
|
21
|
+
};
|
|
22
|
+
type Context = RegionContext | MultiRegionContext;
|
|
23
|
+
type RatelimitResponse = {
|
|
24
|
+
/**
|
|
25
|
+
* Whether the request may pass(true) or exceeded the limit(false)
|
|
26
|
+
*/
|
|
27
|
+
success: boolean;
|
|
28
|
+
/**
|
|
29
|
+
* Maximum number of requests allowed within a window.
|
|
30
|
+
*/
|
|
31
|
+
limit: number;
|
|
32
|
+
/**
|
|
33
|
+
* How many requests the user has left within the current window.
|
|
34
|
+
*/
|
|
35
|
+
remaining: number;
|
|
36
|
+
/**
|
|
37
|
+
* Unix timestamp in milliseconds when the limits are reset.
|
|
38
|
+
*/
|
|
39
|
+
reset: number;
|
|
40
|
+
/**
|
|
41
|
+
* For the MultiRegion setup we do some synchronizing in the background, after returning the current limit.
|
|
42
|
+
* In most case you can simply ignore this.
|
|
43
|
+
*
|
|
44
|
+
* On Vercel Edge or Cloudflare workers, you need to explicitly handle the pending Promise like this:
|
|
45
|
+
*
|
|
46
|
+
* **Vercel Edge:**
|
|
47
|
+
* https://nextjs.org/docs/api-reference/next/server#nextfetchevent
|
|
48
|
+
*
|
|
49
|
+
* ```ts
|
|
50
|
+
* const { pending } = await ratelimit.limit("id")
|
|
51
|
+
* event.waitUntil(pending)
|
|
52
|
+
* ```
|
|
53
|
+
*
|
|
54
|
+
* **Cloudflare Worker:**
|
|
55
|
+
* https://developers.cloudflare.com/workers/runtime-apis/fetch-event/#syntax-module-worker
|
|
56
|
+
*
|
|
57
|
+
* ```ts
|
|
58
|
+
* const { pending } = await ratelimit.limit("id")
|
|
59
|
+
* context.waitUntil(pending)
|
|
60
|
+
* ```
|
|
61
|
+
*/
|
|
62
|
+
pending: Promise<unknown>;
|
|
63
|
+
};
|
|
64
|
+
type Algorithm<TContext> = (ctx: TContext, identifier: string, opts?: {
|
|
65
|
+
cache?: EphemeralCache;
|
|
66
|
+
}) => Promise<RatelimitResponse>;
|
|
67
|
+
/**
|
|
68
|
+
* This is all we need from the redis sdk.
|
|
69
|
+
*/
|
|
70
|
+
interface Redis {
|
|
71
|
+
sadd: <TData>(key: string, ...members: TData[]) => Promise<number>;
|
|
72
|
+
eval: <TArgs extends unknown[], TData = unknown>(...args: [script: string, keys: string[], args: TArgs]) => Promise<TData>;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
type Geo = {
|
|
76
|
+
country?: string;
|
|
77
|
+
city?: string;
|
|
78
|
+
region?: string;
|
|
79
|
+
ip?: string;
|
|
80
|
+
};
|
|
81
|
+
type Event = Geo & {
|
|
82
|
+
identifier: string;
|
|
83
|
+
time: number;
|
|
84
|
+
success: boolean;
|
|
85
|
+
};
|
|
86
|
+
type AnalyticsConfig = {
|
|
87
|
+
redis: Redis;
|
|
88
|
+
prefix?: string;
|
|
89
|
+
};
|
|
90
|
+
/**
|
|
91
|
+
* The Analytics package is experimental and can change at any time.
|
|
92
|
+
*/
|
|
93
|
+
declare class Analytics {
|
|
94
|
+
private readonly analytics;
|
|
95
|
+
private readonly table;
|
|
96
|
+
constructor(config: AnalyticsConfig);
|
|
97
|
+
/**
|
|
98
|
+
* Try to extract the geo information from the request
|
|
99
|
+
*
|
|
100
|
+
* This handles Vercel's `req.geo` and and Cloudflare's `request.cf` properties
|
|
101
|
+
* @param req
|
|
102
|
+
* @returns
|
|
103
|
+
*/
|
|
104
|
+
extractGeo(req: {
|
|
105
|
+
geo?: Geo;
|
|
106
|
+
cf?: Geo;
|
|
107
|
+
}): Geo;
|
|
108
|
+
record(event: Event): Promise<void>;
|
|
109
|
+
series<TFilter extends keyof Omit<Event, "time">>(filter: TFilter, cutoff: number): Promise<({
|
|
110
|
+
time: number;
|
|
111
|
+
} & Record<string, number>)[]>;
|
|
112
|
+
getUsage(cutoff?: number): Promise<Record<string, {
|
|
113
|
+
success: number;
|
|
114
|
+
blocked: number;
|
|
115
|
+
}>>;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
type Unit = "ms" | "s" | "m" | "h" | "d";
|
|
119
|
+
type Duration = `${number} ${Unit}` | `${number}${Unit}`;
|
|
120
|
+
|
|
121
|
+
type RatelimitConfig<TContext> = {
|
|
122
|
+
/**
|
|
123
|
+
* The ratelimiter function to use.
|
|
124
|
+
*
|
|
125
|
+
* Choose one of the predefined ones or implement your own.
|
|
126
|
+
* Available algorithms are exposed via static methods:
|
|
127
|
+
* - Ratelimiter.fixedWindow
|
|
128
|
+
* - Ratelimiter.slidingWindow
|
|
129
|
+
* - Ratelimiter.tokenBucket
|
|
130
|
+
*/
|
|
131
|
+
limiter: Algorithm<TContext>;
|
|
132
|
+
ctx: TContext;
|
|
133
|
+
/**
|
|
134
|
+
* All keys in redis are prefixed with this.
|
|
135
|
+
*
|
|
136
|
+
* @default `@upstash/ratelimit`
|
|
137
|
+
*/
|
|
138
|
+
prefix?: string;
|
|
139
|
+
/**
|
|
140
|
+
* If enabled, the ratelimiter will keep a global cache of identifiers, that have
|
|
141
|
+
* exhausted their ratelimit. In serverless environments this is only possible if
|
|
142
|
+
* you create the ratelimiter instance outside of your handler function. While the
|
|
143
|
+
* function is still hot, the ratelimiter can block requests without having to
|
|
144
|
+
* request data from redis, thus saving time and money.
|
|
145
|
+
*
|
|
146
|
+
* Whenever an identifier has exceeded its limit, the ratelimiter will add it to an
|
|
147
|
+
* internal list together with its reset timestamp. If the same identifier makes a
|
|
148
|
+
* new request before it is reset, we can immediately reject it.
|
|
149
|
+
*
|
|
150
|
+
* Set to `false` to disable.
|
|
151
|
+
*
|
|
152
|
+
* If left undefined, a map is created automatically, but it can only work
|
|
153
|
+
* if the map or the ratelimit instance is created outside your serverless function handler.
|
|
154
|
+
*/
|
|
155
|
+
ephemeralCache?: Map<string, number> | false;
|
|
156
|
+
/**
|
|
157
|
+
* If set, the ratelimiter will allow requests to pass after this many milliseconds.
|
|
158
|
+
*
|
|
159
|
+
* Use this if you want to allow requests in case of network problems
|
|
160
|
+
*
|
|
161
|
+
* @default 5000
|
|
162
|
+
*/
|
|
163
|
+
timeout?: number;
|
|
164
|
+
/**
|
|
165
|
+
* If enabled, the ratelimiter will store analytics data in redis, which you can check out at
|
|
166
|
+
* https://console.upstash.com/ratelimit
|
|
167
|
+
*
|
|
168
|
+
* @default false
|
|
169
|
+
*/
|
|
170
|
+
analytics?: boolean;
|
|
171
|
+
};
|
|
172
|
+
/**
|
|
173
|
+
* Ratelimiter using serverless redis from https://upstash.com/
|
|
174
|
+
*
|
|
175
|
+
* @example
|
|
176
|
+
* ```ts
|
|
177
|
+
* const { limit } = new Ratelimit({
|
|
178
|
+
* redis: Redis.fromEnv(),
|
|
179
|
+
* limiter: Ratelimit.slidingWindow(
|
|
180
|
+
* 10, // Allow 10 requests per window of 30 minutes
|
|
181
|
+
* "30 m", // interval of 30 minutes
|
|
182
|
+
* ),
|
|
183
|
+
* })
|
|
184
|
+
*
|
|
185
|
+
* ```
|
|
186
|
+
*/
|
|
187
|
+
declare abstract class Ratelimit<TContext extends Context> {
|
|
188
|
+
protected readonly limiter: Algorithm<TContext>;
|
|
189
|
+
protected readonly ctx: TContext;
|
|
190
|
+
protected readonly prefix: string;
|
|
191
|
+
protected readonly timeout: number;
|
|
192
|
+
protected readonly analytics?: Analytics;
|
|
193
|
+
constructor(config: RatelimitConfig<TContext>);
|
|
194
|
+
/**
|
|
195
|
+
* Determine if a request should pass or be rejected based on the identifier and previously chosen ratelimit.
|
|
196
|
+
*
|
|
197
|
+
* Use this if you want to reject all requests that you can not handle right now.
|
|
198
|
+
*
|
|
199
|
+
* @example
|
|
200
|
+
* ```ts
|
|
201
|
+
* const ratelimit = new Ratelimit({
|
|
202
|
+
* redis: Redis.fromEnv(),
|
|
203
|
+
* limiter: Ratelimit.slidingWindow(10, "10 s")
|
|
204
|
+
* })
|
|
205
|
+
*
|
|
206
|
+
* const { success } = await ratelimit.limit(id)
|
|
207
|
+
* if (!success){
|
|
208
|
+
* return "Nope"
|
|
209
|
+
* }
|
|
210
|
+
* return "Yes"
|
|
211
|
+
* ```
|
|
212
|
+
*/
|
|
213
|
+
limit: (identifier: string, req?: {
|
|
214
|
+
geo?: Geo;
|
|
215
|
+
}) => Promise<RatelimitResponse>;
|
|
216
|
+
/**
|
|
217
|
+
* Block until the request may pass or timeout is reached.
|
|
218
|
+
*
|
|
219
|
+
* This method returns a promise that resolves as soon as the request may be processed
|
|
220
|
+
* or after the timeout has been reached.
|
|
221
|
+
*
|
|
222
|
+
* Use this if you want to delay the request until it is ready to get processed.
|
|
223
|
+
*
|
|
224
|
+
* @example
|
|
225
|
+
* ```ts
|
|
226
|
+
* const ratelimit = new Ratelimit({
|
|
227
|
+
* redis: Redis.fromEnv(),
|
|
228
|
+
* limiter: Ratelimit.slidingWindow(10, "10 s")
|
|
229
|
+
* })
|
|
230
|
+
*
|
|
231
|
+
* const { success } = await ratelimit.blockUntilReady(id, 60_000)
|
|
232
|
+
* if (!success){
|
|
233
|
+
* return "Nope"
|
|
234
|
+
* }
|
|
235
|
+
* return "Yes"
|
|
236
|
+
* ```
|
|
237
|
+
*/
|
|
238
|
+
blockUntilReady: (identifier: string, timeout: number) => Promise<RatelimitResponse>;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
type MultiRegionRatelimitConfig = {
|
|
242
|
+
/**
|
|
243
|
+
* Instances of `@upstash/redis`
|
|
244
|
+
* @see https://github.com/upstash/upstash-redis#quick-start
|
|
245
|
+
*/
|
|
246
|
+
redis: Redis[];
|
|
247
|
+
/**
|
|
248
|
+
* The ratelimiter function to use.
|
|
249
|
+
*
|
|
250
|
+
* Choose one of the predefined ones or implement your own.
|
|
251
|
+
* Available algorithms are exposed via static methods:
|
|
252
|
+
* - MultiRegionRatelimit.fixedWindow
|
|
253
|
+
*/
|
|
254
|
+
limiter: Algorithm<MultiRegionContext>;
|
|
255
|
+
/**
|
|
256
|
+
* All keys in redis are prefixed with this.
|
|
257
|
+
*
|
|
258
|
+
* @default `@upstash/ratelimit`
|
|
259
|
+
*/
|
|
260
|
+
prefix?: string;
|
|
261
|
+
/**
|
|
262
|
+
* If enabled, the ratelimiter will keep a global cache of identifiers, that have
|
|
263
|
+
* exhausted their ratelimit. In serverless environments this is only possible if
|
|
264
|
+
* you create the ratelimiter instance outside of your handler function. While the
|
|
265
|
+
* function is still hot, the ratelimiter can block requests without having to
|
|
266
|
+
* request data from redis, thus saving time and money.
|
|
267
|
+
*
|
|
268
|
+
* Whenever an identifier has exceeded its limit, the ratelimiter will add it to an
|
|
269
|
+
* internal list together with its reset timestamp. If the same identifier makes a
|
|
270
|
+
* new request before it is reset, we can immediately reject it.
|
|
271
|
+
*
|
|
272
|
+
* Set to `false` to disable.
|
|
273
|
+
*
|
|
274
|
+
* If left undefined, a map is created automatically, but it can only work
|
|
275
|
+
* if the map or the ratelimit instance is created outside your serverless function handler.
|
|
276
|
+
*/
|
|
277
|
+
ephemeralCache?: Map<string, number> | false;
|
|
278
|
+
/**
|
|
279
|
+
* If set, the ratelimiter will allow requests to pass after this many milliseconds.
|
|
280
|
+
*
|
|
281
|
+
* Use this if you want to allow requests in case of network problems
|
|
282
|
+
*/
|
|
283
|
+
timeout?: number;
|
|
284
|
+
/**
|
|
285
|
+
* If enabled, the ratelimiter will store analytics data in redis, which you can check out at
|
|
286
|
+
* https://console.upstash.com/ratelimit
|
|
287
|
+
*
|
|
288
|
+
* @default true
|
|
289
|
+
*/
|
|
290
|
+
analytics?: boolean;
|
|
291
|
+
};
|
|
292
|
+
/**
|
|
293
|
+
* Ratelimiter using serverless redis from https://upstash.com/
|
|
294
|
+
*
|
|
295
|
+
* @example
|
|
296
|
+
* ```ts
|
|
297
|
+
* const { limit } = new MultiRegionRatelimit({
|
|
298
|
+
* redis: Redis.fromEnv(),
|
|
299
|
+
* limiter: MultiRegionRatelimit.fixedWindow(
|
|
300
|
+
* 10, // Allow 10 requests per window of 30 minutes
|
|
301
|
+
* "30 m", // interval of 30 minutes
|
|
302
|
+
* )
|
|
303
|
+
* })
|
|
304
|
+
*
|
|
305
|
+
* ```
|
|
306
|
+
*/
|
|
307
|
+
declare class MultiRegionRatelimit extends Ratelimit<MultiRegionContext> {
|
|
308
|
+
/**
|
|
309
|
+
* Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithn of your choice.
|
|
310
|
+
*/
|
|
311
|
+
constructor(config: MultiRegionRatelimitConfig);
|
|
312
|
+
/**
|
|
313
|
+
* Each request inside a fixed time increases a counter.
|
|
314
|
+
* Once the counter reaches the maximum allowed number, all further requests are
|
|
315
|
+
* rejected.
|
|
316
|
+
*
|
|
317
|
+
* **Pro:**
|
|
318
|
+
*
|
|
319
|
+
* - Newer requests are not starved by old ones.
|
|
320
|
+
* - Low storage cost.
|
|
321
|
+
*
|
|
322
|
+
* **Con:**
|
|
323
|
+
*
|
|
324
|
+
* A burst of requests near the boundary of a window can result in a very
|
|
325
|
+
* high request rate because two windows will be filled with requests quickly.
|
|
326
|
+
*
|
|
327
|
+
* @param tokens - How many requests a user can make in each time window.
|
|
328
|
+
* @param window - A fixed timeframe
|
|
329
|
+
*/
|
|
330
|
+
static fixedWindow(
|
|
331
|
+
/**
|
|
332
|
+
* How many requests are allowed per window.
|
|
333
|
+
*/
|
|
334
|
+
tokens: number,
|
|
335
|
+
/**
|
|
336
|
+
* The duration in which `tokens` requests are allowed.
|
|
337
|
+
*/
|
|
338
|
+
window: Duration): Algorithm<MultiRegionContext>;
|
|
339
|
+
/**
|
|
340
|
+
* Combined approach of `slidingLogs` and `fixedWindow` with lower storage
|
|
341
|
+
* costs than `slidingLogs` and improved boundary behavior by calculating a
|
|
342
|
+
* weighted score between two windows.
|
|
343
|
+
*
|
|
344
|
+
* **Pro:**
|
|
345
|
+
*
|
|
346
|
+
* Good performance allows this to scale to very high loads.
|
|
347
|
+
*
|
|
348
|
+
* **Con:**
|
|
349
|
+
*
|
|
350
|
+
* Nothing major.
|
|
351
|
+
*
|
|
352
|
+
* @param tokens - How many requests a user can make in each time window.
|
|
353
|
+
* @param window - The duration in which the user can max X requests.
|
|
354
|
+
*/
|
|
355
|
+
static slidingWindow(
|
|
356
|
+
/**
|
|
357
|
+
* How many requests are allowed per window.
|
|
358
|
+
*/
|
|
359
|
+
tokens: number,
|
|
360
|
+
/**
|
|
361
|
+
* The duration in which `tokens` requests are allowed.
|
|
362
|
+
*/
|
|
363
|
+
window: Duration): Algorithm<MultiRegionContext>;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
type RegionRatelimitConfig = {
|
|
367
|
+
/**
|
|
368
|
+
* Instance of `@upstash/redis`
|
|
369
|
+
* @see https://github.com/upstash/upstash-redis#quick-start
|
|
370
|
+
*/
|
|
371
|
+
redis: Redis;
|
|
372
|
+
/**
|
|
373
|
+
* The ratelimiter function to use.
|
|
374
|
+
*
|
|
375
|
+
* Choose one of the predefined ones or implement your own.
|
|
376
|
+
* Available algorithms are exposed via static methods:
|
|
377
|
+
* - Ratelimiter.fixedWindow
|
|
378
|
+
* - Ratelimiter.slidingWindow
|
|
379
|
+
* - Ratelimiter.tokenBucket
|
|
380
|
+
*/
|
|
381
|
+
limiter: Algorithm<RegionContext>;
|
|
382
|
+
/**
|
|
383
|
+
* All keys in redis are prefixed with this.
|
|
384
|
+
*
|
|
385
|
+
* @default `@upstash/ratelimit`
|
|
386
|
+
*/
|
|
387
|
+
prefix?: string;
|
|
388
|
+
/**
|
|
389
|
+
* If enabled, the ratelimiter will keep a global cache of identifiers, that have
|
|
390
|
+
* exhausted their ratelimit. In serverless environments this is only possible if
|
|
391
|
+
* you create the ratelimiter instance outside of your handler function. While the
|
|
392
|
+
* function is still hot, the ratelimiter can block requests without having to
|
|
393
|
+
* request data from redis, thus saving time and money.
|
|
394
|
+
*
|
|
395
|
+
* Whenever an identifier has exceeded its limit, the ratelimiter will add it to an
|
|
396
|
+
* internal list together with its reset timestamp. If the same identifier makes a
|
|
397
|
+
* new request before it is reset, we can immediately reject it.
|
|
398
|
+
*
|
|
399
|
+
* Set to `false` to disable.
|
|
400
|
+
*
|
|
401
|
+
* If left undefined, a map is created automatically, but it can only work
|
|
402
|
+
* if the map or the ratelimit instance is created outside your serverless function handler.
|
|
403
|
+
*/
|
|
404
|
+
ephemeralCache?: Map<string, number> | false;
|
|
405
|
+
/**
|
|
406
|
+
* If set, the ratelimiter will allow requests to pass after this many milliseconds.
|
|
407
|
+
*
|
|
408
|
+
* Use this if you want to allow requests in case of network problems
|
|
409
|
+
*/
|
|
410
|
+
timeout?: number;
|
|
411
|
+
/**
|
|
412
|
+
* If enabled, the ratelimiter will store analytics data in redis, which you can check out at
|
|
413
|
+
* https://console.upstash.com/ratelimit
|
|
414
|
+
*
|
|
415
|
+
* @default true
|
|
416
|
+
*/
|
|
417
|
+
analytics?: boolean;
|
|
418
|
+
};
|
|
419
|
+
/**
|
|
420
|
+
* Ratelimiter using serverless redis from https://upstash.com/
|
|
421
|
+
*
|
|
422
|
+
* @example
|
|
423
|
+
* ```ts
|
|
424
|
+
* const { limit } = new Ratelimit({
|
|
425
|
+
* redis: Redis.fromEnv(),
|
|
426
|
+
* limiter: Ratelimit.slidingWindow(
|
|
427
|
+
* "30 m", // interval of 30 minutes
|
|
428
|
+
* 10, // Allow 10 requests per window of 30 minutes
|
|
429
|
+
* )
|
|
430
|
+
* })
|
|
431
|
+
*
|
|
432
|
+
* ```
|
|
433
|
+
*/
|
|
434
|
+
declare class RegionRatelimit extends Ratelimit<RegionContext> {
|
|
435
|
+
/**
|
|
436
|
+
* Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithm of your choice.
|
|
437
|
+
*/
|
|
438
|
+
constructor(config: RegionRatelimitConfig);
|
|
439
|
+
/**
|
|
440
|
+
* Each request inside a fixed time increases a counter.
|
|
441
|
+
* Once the counter reaches the maximum allowed number, all further requests are
|
|
442
|
+
* rejected.
|
|
443
|
+
*
|
|
444
|
+
* **Pro:**
|
|
445
|
+
*
|
|
446
|
+
* - Newer requests are not starved by old ones.
|
|
447
|
+
* - Low storage cost.
|
|
448
|
+
*
|
|
449
|
+
* **Con:**
|
|
450
|
+
*
|
|
451
|
+
* A burst of requests near the boundary of a window can result in a very
|
|
452
|
+
* high request rate because two windows will be filled with requests quickly.
|
|
453
|
+
*
|
|
454
|
+
* @param tokens - How many requests a user can make in each time window.
|
|
455
|
+
* @param window - A fixed timeframe
|
|
456
|
+
*/
|
|
457
|
+
static fixedWindow(
|
|
458
|
+
/**
|
|
459
|
+
* How many requests are allowed per window.
|
|
460
|
+
*/
|
|
461
|
+
tokens: number,
|
|
462
|
+
/**
|
|
463
|
+
* The duration in which `tokens` requests are allowed.
|
|
464
|
+
*/
|
|
465
|
+
window: Duration): Algorithm<RegionContext>;
|
|
466
|
+
/**
|
|
467
|
+
* Combined approach of `slidingLogs` and `fixedWindow` with lower storage
|
|
468
|
+
* costs than `slidingLogs` and improved boundary behavior by calculating a
|
|
469
|
+
* weighted score between two windows.
|
|
470
|
+
*
|
|
471
|
+
* **Pro:**
|
|
472
|
+
*
|
|
473
|
+
* Good performance allows this to scale to very high loads.
|
|
474
|
+
*
|
|
475
|
+
* **Con:**
|
|
476
|
+
*
|
|
477
|
+
* Nothing major.
|
|
478
|
+
*
|
|
479
|
+
* @param tokens - How many requests a user can make in each time window.
|
|
480
|
+
* @param window - The duration in which the user can max X requests.
|
|
481
|
+
*/
|
|
482
|
+
static slidingWindow(
|
|
483
|
+
/**
|
|
484
|
+
* How many requests are allowed per window.
|
|
485
|
+
*/
|
|
486
|
+
tokens: number,
|
|
487
|
+
/**
|
|
488
|
+
* The duration in which `tokens` requests are allowed.
|
|
489
|
+
*/
|
|
490
|
+
window: Duration): Algorithm<RegionContext>;
|
|
491
|
+
/**
|
|
492
|
+
* You have a bucket filled with `{maxTokens}` tokens that refills constantly
|
|
493
|
+
* at `{refillRate}` per `{interval}`.
|
|
494
|
+
* Every request will remove one token from the bucket and if there is no
|
|
495
|
+
* token to take, the request is rejected.
|
|
496
|
+
*
|
|
497
|
+
* **Pro:**
|
|
498
|
+
*
|
|
499
|
+
* - Bursts of requests are smoothed out and you can process them at a constant
|
|
500
|
+
* rate.
|
|
501
|
+
* - Allows to set a higher initial burst limit by setting `maxTokens` higher
|
|
502
|
+
* than `refillRate`
|
|
503
|
+
*/
|
|
504
|
+
static tokenBucket(
|
|
505
|
+
/**
|
|
506
|
+
* How many tokens are refilled per `interval`
|
|
507
|
+
*
|
|
508
|
+
* An interval of `10s` and refillRate of 5 will cause a new token to be added every 2 seconds.
|
|
509
|
+
*/
|
|
510
|
+
refillRate: number,
|
|
511
|
+
/**
|
|
512
|
+
* The interval for the `refillRate`
|
|
513
|
+
*/
|
|
514
|
+
interval: Duration,
|
|
515
|
+
/**
|
|
516
|
+
* Maximum number of tokens.
|
|
517
|
+
* A newly created bucket starts with this many tokens.
|
|
518
|
+
* Useful to allow higher burst limits.
|
|
519
|
+
*/
|
|
520
|
+
maxTokens: number): Algorithm<RegionContext>;
|
|
521
|
+
/**
|
|
522
|
+
* cachedFixedWindow first uses the local cache to decide if a request may pass and then updates
|
|
523
|
+
* it asynchronously.
|
|
524
|
+
* This is experimental and not yet recommended for production use.
|
|
525
|
+
*
|
|
526
|
+
* @experimental
|
|
527
|
+
*
|
|
528
|
+
* Each request inside a fixed time increases a counter.
|
|
529
|
+
* Once the counter reaches the maximum allowed number, all further requests are
|
|
530
|
+
* rejected.
|
|
531
|
+
*
|
|
532
|
+
* **Pro:**
|
|
533
|
+
*
|
|
534
|
+
* - Newer requests are not starved by old ones.
|
|
535
|
+
* - Low storage cost.
|
|
536
|
+
*
|
|
537
|
+
* **Con:**
|
|
538
|
+
*
|
|
539
|
+
* A burst of requests near the boundary of a window can result in a very
|
|
540
|
+
* high request rate because two windows will be filled with requests quickly.
|
|
541
|
+
*
|
|
542
|
+
* @param tokens - How many requests a user can make in each time window.
|
|
543
|
+
* @param window - A fixed timeframe
|
|
544
|
+
*/
|
|
545
|
+
static cachedFixedWindow(
|
|
546
|
+
/**
|
|
547
|
+
* How many requests are allowed per window.
|
|
548
|
+
*/
|
|
549
|
+
tokens: number,
|
|
550
|
+
/**
|
|
551
|
+
* The duration in which `tokens` requests are allowed.
|
|
552
|
+
*/
|
|
553
|
+
window: Duration): Algorithm<RegionContext>;
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
export { Algorithm, Analytics, AnalyticsConfig, MultiRegionRatelimit, MultiRegionRatelimitConfig, RegionRatelimit as Ratelimit, RegionRatelimitConfig as RatelimitConfig };
|