@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/types/single.d.ts DELETED
@@ -1,187 +0,0 @@
1
- import type { Duration } from "./duration.js";
2
- import type { Algorithm, RegionContext } from "./types.js";
3
- import type { Redis } from "./types.js";
4
- import { Ratelimit } from "./ratelimit.js";
5
- export type RegionRatelimitConfig = {
6
- /**
7
- * Instance of `@upstash/redis`
8
- * @see https://github.com/upstash/upstash-redis#quick-start
9
- */
10
- redis: Redis;
11
- /**
12
- * The ratelimiter function to use.
13
- *
14
- * Choose one of the predefined ones or implement your own.
15
- * Available algorithms are exposed via static methods:
16
- * - Ratelimiter.fixedWindow
17
- * - Ratelimiter.slidingLogs
18
- * - Ratelimiter.slidingWindow
19
- * - Ratelimiter.tokenBucket
20
- */
21
- limiter: Algorithm<RegionContext>;
22
- /**
23
- * All keys in redis are prefixed with this.
24
- *
25
- * @default `@upstash/ratelimit`
26
- */
27
- prefix?: string;
28
- /**
29
- * If enabled, the ratelimiter will keep a global cache of identifiers, that have
30
- * exhausted their ratelimit. In serverless environments this is only possible if
31
- * you create the ratelimiter instance outside of your handler function. While the
32
- * function is still hot, the ratelimiter can block requests without having to
33
- * request data from redis, thus saving time and money.
34
- *
35
- * Whenever an identifier has exceeded its limit, the ratelimiter will add it to an
36
- * internal list together with its reset timestamp. If the same identifier makes a
37
- * new request before it is reset, we can immediately reject it.
38
- *
39
- * Set to `false` to disable.
40
- *
41
- * If left undefined, a map is created automatically, but it can only work
42
- * if the map or the ratelimit instance is created outside your serverless function handler.
43
- */
44
- ephemeralCache?: Map<string, number> | false;
45
- /**
46
- * If set, the ratelimiter will allow requests to pass after this many milliseconds.
47
- *
48
- * Use this if you want to allow requests in case of network problems
49
- */
50
- timeout?: number;
51
- };
52
- /**
53
- * Ratelimiter using serverless redis from https://upstash.com/
54
- *
55
- * @example
56
- * ```ts
57
- * const { limit } = new Ratelimit({
58
- * redis: Redis.fromEnv(),
59
- * limiter: Ratelimit.slidingWindow(
60
- * "30 m", // interval of 30 minutes
61
- * 10, // Allow 10 requests per window of 30 minutes
62
- * )
63
- * })
64
- *
65
- * ```
66
- */
67
- export declare class RegionRatelimit extends Ratelimit<RegionContext> {
68
- /**
69
- * Create a new Ratelimit instance by providing a `@upstash/redis` instance and the algorithn of your choice.
70
- */
71
- constructor(config: RegionRatelimitConfig);
72
- /**
73
- * Each requests inside a fixed time increases a counter.
74
- * Once the counter reaches a maxmimum allowed number, all further requests are
75
- * rejected.
76
- *
77
- * **Pro:**
78
- *
79
- * - Newer requests are not starved by old ones.
80
- * - Low storage cost.
81
- *
82
- * **Con:**
83
- *
84
- * A burst of requests near the boundary of a window can result in a very
85
- * high request rate because two windows will be filled with requests quickly.
86
- *
87
- * @param tokens - How many requests a user can make in each time window.
88
- * @param window - A fixed timeframe
89
- */
90
- static fixedWindow(
91
- /**
92
- * How many requests are allowed per window.
93
- */
94
- tokens: number,
95
- /**
96
- * The duration in which `tokens` requests are allowed.
97
- */
98
- window: Duration): Algorithm<RegionContext>;
99
- /**
100
- * Combined approach of `slidingLogs` and `fixedWindow` with lower storage
101
- * costs than `slidingLogs` and improved boundary behavior by calcualting a
102
- * weighted score between two windows.
103
- *
104
- * **Pro:**
105
- *
106
- * Good performance allows this to scale to very high loads.
107
- *
108
- * **Con:**
109
- *
110
- * Nothing major.
111
- *
112
- * @param tokens - How many requests a user can make in each time window.
113
- * @param window - The duration in which the user can max X requests.
114
- */
115
- static slidingWindow(
116
- /**
117
- * How many requests are allowed per window.
118
- */
119
- tokens: number,
120
- /**
121
- * The duration in which `tokens` requests are allowed.
122
- */
123
- window: Duration): Algorithm<RegionContext>;
124
- /**
125
- * You have a bucket filled with `{maxTokens}` tokens that refills constantly
126
- * at `{refillRate}` per `{interval}`.
127
- * Every request will remove one token from the bucket and if there is no
128
- * token to take, the request is rejected.
129
- *
130
- * **Pro:**
131
- *
132
- * - Bursts of requests are smoothed out and you can process them at a constant
133
- * rate.
134
- * - Allows to set a higher initial burst limit by setting `maxTokens` higher
135
- * than `refillRate`
136
- */
137
- static tokenBucket(
138
- /**
139
- * How many tokens are refilled per `interval`
140
- *
141
- * An interval of `10s` and refillRate of 5 will cause a new token to be added every 2 seconds.
142
- */
143
- refillRate: number,
144
- /**
145
- * The interval for the `refillRate`
146
- */
147
- interval: Duration,
148
- /**
149
- * Maximum number of tokens.
150
- * A newly created bucket starts with this many tokens.
151
- * Useful to allow higher burst limits.
152
- */
153
- maxTokens: number): Algorithm<RegionContext>;
154
- /**
155
- * cachedFixedWindow first uses the local cache to decide if a request may pass and then updates
156
- * it asynchronously.
157
- * This is experimental and not yet recommended for production use.
158
- *
159
- * @experimental
160
- *
161
- * Each requests inside a fixed time increases a counter.
162
- * Once the counter reaches a maxmimum allowed number, all further requests are
163
- * rejected.
164
- *
165
- * **Pro:**
166
- *
167
- * - Newer requests are not starved by old ones.
168
- * - Low storage cost.
169
- *
170
- * **Con:**
171
- *
172
- * A burst of requests near the boundary of a window can result in a very
173
- * high request rate because two windows will be filled with requests quickly.
174
- *
175
- * @param tokens - How many requests a user can make in each time window.
176
- * @param window - A fixed timeframe
177
- */
178
- static cachedFixedWindow(
179
- /**
180
- * How many requests are allowed per window.
181
- */
182
- tokens: number,
183
- /**
184
- * The duration in which `tokens` requests are allowed.
185
- */
186
- window: Duration): Algorithm<RegionContext>;
187
- }
package/types/types.d.ts DELETED
@@ -1,70 +0,0 @@
1
- export interface Redis {
2
- eval: (script: string, keys: string[], values: unknown[]) => Promise<unknown>;
3
- sadd: (key: string, ...members: string[]) => Promise<number>;
4
- }
5
- /**
6
- * EphemeralCache is used to block certain identifiers right away in case they have already exceedd the ratelimit.
7
- */
8
- export interface EphemeralCache {
9
- isBlocked: (identifier: string) => {
10
- blocked: boolean;
11
- reset: number;
12
- };
13
- blockUntil: (identifier: string, reset: number) => void;
14
- set: (key: string, value: number) => void;
15
- get: (key: string) => number | null;
16
- incr: (key: string) => number;
17
- }
18
- export type RegionContext = {
19
- redis: Redis;
20
- cache?: EphemeralCache;
21
- };
22
- export type MultiRegionContext = {
23
- redis: Redis[];
24
- cache?: EphemeralCache;
25
- };
26
- export type Context = RegionContext | MultiRegionContext;
27
- export type RatelimitResponse = {
28
- /**
29
- * Whether the request may pass(true) or exceeded the limit(false)
30
- */
31
- success: boolean;
32
- /**
33
- * Maximum number of requests allowed within a window.
34
- */
35
- limit: number;
36
- /**
37
- * How many requests the user has left within the current window.
38
- */
39
- remaining: number;
40
- /**
41
- * Unix timestamp in milliseconds when the limits are reset.
42
- */
43
- reset: number;
44
- /**
45
- * For the MultiRegion setup we do some synchronizing in the background, after returning the current limit.
46
- * In most case you can simply ignore this.
47
- *
48
- * On Vercel Edge or Cloudflare workers, you need to explicitely handle the pending Promise like this:
49
- *
50
- * **Vercel Edge:**
51
- * https://nextjs.org/docs/api-reference/next/server#nextfetchevent
52
- *
53
- * ```ts
54
- * const { pending } = await ratelimit.limit("id")
55
- * event.waitUntil(pending)
56
- * ```
57
- *
58
- * **Cloudflare Worker:**
59
- * https://developers.cloudflare.com/workers/runtime-apis/fetch-event/#syntax-module-worker
60
- *
61
- * ```ts
62
- * const { pending } = await ratelimit.limit("id")
63
- * context.waitUntil(pending)
64
- * ```
65
- */
66
- pending: Promise<unknown>;
67
- };
68
- export type Algorithm<TContext> = (ctx: TContext, identifier: string, opts?: {
69
- cache?: EphemeralCache;
70
- }) => Promise<RatelimitResponse>;