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