-
-
Notifications
You must be signed in to change notification settings - Fork 185
Expand file tree
/
Copy pathtypes.d.ts
More file actions
637 lines (543 loc) · 19.5 KB
/
types.d.ts
File metadata and controls
637 lines (543 loc) · 19.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
export interface IRateLimiterRes {
msBeforeNext?: number;
remainingPoints?: number;
consumedPoints?: number;
isFirstInDuration?: boolean;
}
export class RateLimiterRes {
constructor(
remainingPoints?: number,
msBeforeNext?: number,
consumedPoints?: number,
isFirstInDuration?: boolean
);
readonly msBeforeNext: number;
readonly remainingPoints: number;
readonly consumedPoints: number;
readonly isFirstInDuration: boolean;
toString(): string;
toJSON(): {
remainingPoints: number;
msBeforeNext: number;
consumedPoints: number;
isFirstInDuration: boolean;
};
}
export class RateLimiterCompatibleAbstract {
readonly keyPrefix: string;
blockDuration: number;
execEvenly: boolean;
consume(
key: string | number,
pointsToConsume?: number,
options?: { [key: string]: any }
): Promise<RateLimiterRes>;
penalty(
key: string | number,
points?: number,
options?: { [key: string]: any }
): Promise<RateLimiterRes>;
reward(
key: string | number,
points?: number,
options?: { [key: string]: any }
): Promise<RateLimiterRes>;
get(
key: string | number,
options?: { [key: string]: any }
): Promise<RateLimiterRes | null>;
set(
key: string | number,
points: number,
secDuration: number,
options?: { [key: string]: any }
): Promise<RateLimiterRes>;
block(
key: string | number,
secDuration: number,
options?: { [key: string]: any }
): Promise<RateLimiterRes>;
delete(
key: string | number,
options?: { [key: string]: any }
): Promise<boolean>;
}
export type RateLimiterLike = RateLimiterAbstract | RateLimiterCompatibleAbstract;
export class RateLimiterAbstract {
constructor(opts: IRateLimiterOptions);
/**
* Maximum number of points can be consumed over duration. Limiter compares this number with
* number of consumed points by key to decide if an operation should be rejected or resolved.
*/
points: number;
/**
* Number of seconds before consumed points are reset.
* Keys never expire, if duration is 0.
*/
duration: number;
/**
* duration in milliseconds
*/
get msDuration(): number;
/**
* If positive number and consumed more than points in current duration, block for blockDuration
* seconds.
*/
blockDuration: number;
/**
* blockDuration in milliseconds
*/
get msBlockDuration(): number;
/**
* Delay action to be executed evenly over duration First action in duration is executed without
* delay. All next allowed actions in current duration are delayed by formula
* msBeforeDurationEnd / (remainingPoints + 2) with minimum delay of duration * 1000 / points.
* It allows to cut off load peaks similar way to Leaky Bucket.
*
* Note: it isn't recommended to use it for long duration and few points, as it may delay action
* for too long with default execEvenlyMinDelayMs.
*/
execEvenly: boolean;
/**
* Sets minimum delay in milliseconds, when action is delayed with execEvenly
*/
execEvenlyMinDelayMs: number;
/**
* If you need to create several limiters for different purpose.
* Set to empty string '', if keys should be stored without prefix.
*/
keyPrefix: string;
/**
* Returns internal key prefixed with keyPrefix option as it is saved in store.
*/
getKey(key: string | number): string;
/**
* Returns internal key without the keyPrefix.
*/
parseKey(rlKey: string): string;
/**
* @param key is usually IP address or some unique client id
* @param pointsToConsume number of points consumed. default: 1
* @param options is object with additional settings:
* - customDuration expire in seconds for this operation only overwrites limiter's duration. It doesn't work, if key already created.
* @returns Returns Promise, which:
* - `resolved` with `RateLimiterRes` when point(s) is consumed, so action can be done
* - `rejected` only for store and database limiters if insuranceLimiter isn't setup: when some error happened, where reject reason `rejRes` is Error object
* - `rejected` only for RateLimiterCluster if insuranceLimiter isn't setup: when timeoutMs exceeded, where reject reason `rejRes` is Error object
* - `rejected` when there is no points to be consumed, where reject reason `rejRes` is `RateLimiterRes` object
* - `rejected` when key is blocked (if block strategy is set up), where reject reason `rejRes` is `RateLimiterRes` object
*/
consume(
key: string | number,
pointsToConsume?: number,
options?: { [key: string]: any }
): Promise<RateLimiterRes>;
/**
* Fine key by points number of points for one duration.
*
* Note: Depending on time penalty may go to next durations
*
* @returns Returns Promise, which:
* - `resolved` with RateLimiterRes
* - `rejected` only for database limiters if insuranceLimiter isn't setup: when some error happened, where reject reason `rejRes` is Error object
* - `rejected` only for RateLimiterCluster if insuranceLimiter isn't setup: when timeoutMs exceeded, where reject reason `rejRes` is Error object
*/
penalty(
key: string | number,
points?: number,
options?: { [key: string]: any }
): Promise<RateLimiterRes>;
/**
* Reward key by points number of points for one duration.
* Note: Depending on time reward may go to next durations
* @returns Promise, which:
* - `resolved` with RateLimiterRes
* - `rejected` only for database limiters if insuranceLimiter isn't setup: when some error happened, where reject reason `rejRes` is Error object
* - `rejected` only for RateLimiterCluster if insuranceLimiter isn't setup: when timeoutMs exceeded, where reject reason `rejRes` is Error object
*/
reward(
key: string | number,
points?: number,
options?: { [key: string]: any }
): Promise<RateLimiterRes>;
/**
* Get RateLimiterRes in current duration. It always returns RateLimiterRes.isFirstInDuration=false.
* @param key is usually IP address or some unique client id
* @param options
* @returns Promise, which:
* - `resolved` with RateLimiterRes if key is set
* - `resolved` with null if key is NOT set or expired
* - `rejected` only for database limiters if insuranceLimiter isn't setup: when some error happened, where reject reason `rejRes` is Error object
* - `rejected` only for RateLimiterCluster if insuranceLimiter isn't setup: when timeoutMs exceeded, where reject reason `rejRes` is Error object
*/
get(
key: string | number,
options?: { [key: string]: any }
): Promise<RateLimiterRes | null>;
/**
* Set points to key for secDuration seconds.
* Store it forever, if secDuration is 0.
* @param key
* @param points
* @param secDuration
* @param options
* @returns Promise, which:
* - `resolved` with RateLimiterRes
* - `rejected` only for database limiters if insuranceLimiter isn't setup: when some error happened, where reject reason `rejRes` is Error object
* - `rejected` only for RateLimiterCluster if insuranceLimiter isn't setup: when timeoutMs exceeded, where reject reason `rejRes` is Error object
*/
set(
key: string | number,
points: number,
secDuration: number,
options?: { [key: string]: any }
): Promise<RateLimiterRes>;
/**
* Block key by setting consumed points to points + 1 for secDuration seconds.
*
* It force updates expire, if there is already key.
*
* Blocked key never expires, if secDuration is 0.
* @returns Promise, which:
* - `resolved` with RateLimiterRes
* - `rejected` only for database limiters if insuranceLimiter isn't setup: when some error happened, where reject reason `rejRes` is Error object
* - `rejected` only for RateLimiterCluster if insuranceLimiter isn't setup: when timeoutMs exceeded, where reject reason `rejRes` is Error object
*/
block(
key: string | number,
secDuration: number,
options?: { [key: string]: any }
): Promise<RateLimiterRes>;
/**
* Delete all data related to key.
*
* For example, previously blocked key is not blocked after delete as there is no data anymore.
* @returns Promise, which:
* - `resolved` with boolean, true if data is removed by key, false if there is no such key.
* - `rejected` only for database limiters if insuranceLimiter isn't setup: when some error happened, where reject reason `rejRes` is Error object
* - `rejected` only for RateLimiterCluster if insuranceLimiter isn't setup: when timeoutMs exceeded, where reject reason `rejRes` is Error object
*/
delete(
key: string | number,
options?: { [key: string]: any }
): Promise<boolean>;
}
export class RateLimiterInsuredAbstract extends RateLimiterAbstract {
constructor(opts: IRateLimiterOptions);
}
export class RateLimiterStoreAbstract extends RateLimiterInsuredAbstract {
constructor(opts: IRateLimiterStoreOptions);
/**
* Cleanup keys blocked in current process memory
*/
deleteInMemoryBlockedAll(): void;
}
interface IRateLimiterOptions {
keyPrefix?: string;
points: number;
duration: number;
execEvenly?: boolean;
execEvenlyMinDelayMs?: number;
blockDuration?: number;
insuranceLimiter?: RateLimiterLike;
}
interface IRateLimiterClusterOptions extends IRateLimiterOptions {
timeoutMs?: number;
}
interface IRateLimiterStoreOptions extends IRateLimiterOptions {
storeClient: any;
storeType?: string;
inMemoryBlockOnConsumed?: number;
inMemoryBlockDuration?: number;
insuranceLimiter?: RateLimiterLike;
dbName?: string;
tableName?: string;
tableCreated?: boolean;
}
interface IRateLimiterStoreNoAutoExpiryOptions extends IRateLimiterStoreOptions {
clearExpiredByTimeout?: boolean;
}
interface IRateLimiterStoreNoAutoExpiryOptionsAndSchema extends IRateLimiterStoreNoAutoExpiryOptions {
schema: any;
}
interface IRateLimiterMongoOptions extends IRateLimiterStoreOptions {
indexKeyPrefix?: {
[key: string]: any;
};
disableIndexesCreation?: boolean;
}
interface IRateLimiterPostgresOptions extends IRateLimiterStoreNoAutoExpiryOptions {
schemaName?: string;
}
interface IRateLimiterRedisOptions extends IRateLimiterStoreOptions {
rejectIfRedisNotReady?: boolean;
useRedisPackage?: boolean;
useRedis3AndLowerPackage?: boolean;
customIncrTtlLuaScript?: string;
}
interface IRateLimiterValkeyOptions extends IRateLimiterStoreOptions {
customIncrTtlLuaScript?: string;
}
interface ICallbackReady {
(error?: Error): void;
}
interface IRLWrapperBlackAndWhiteOptions {
limiter: RateLimiterLike;
blackList?: string[] | number[];
whiteList?: string[] | number[];
isBlackListed?(key: any): boolean;
isWhiteListed?(key: any): boolean;
runActionAnyway?: boolean;
}
export class RateLimiterMemory extends RateLimiterAbstract {
constructor(opts: IRateLimiterOptions);
}
export class RateLimiterCluster extends RateLimiterAbstract {
constructor(opts: IRateLimiterClusterOptions);
}
export class RateLimiterClusterMaster {
constructor();
}
export class RateLimiterClusterMasterPM2 {
constructor(pm2: any);
}
export class RateLimiterRedis extends RateLimiterStoreAbstract {
constructor(opts: IRateLimiterRedisOptions);
}
export class RateLimiterRedisNonAtomic extends RateLimiterStoreAbstract {
constructor(opts: IRateLimiterRedisOptions);
}
export class RateLimiterValkey extends RateLimiterStoreAbstract {
constructor(opts: IRateLimiterValkeyOptions);
}
export interface IRateLimiterMongoFunctionOptions {
attrs: { [key: string]: any };
}
export class RateLimiterMongo extends RateLimiterStoreAbstract {
constructor(opts: IRateLimiterMongoOptions);
indexKeyPrefix(): Object;
indexKeyPrefix(obj?: Object): void;
createIndexes(): Promise<void>;
consume(
key: string | number,
pointsToConsume?: number,
options?: IRateLimiterMongoFunctionOptions
): Promise<RateLimiterRes>;
penalty(
key: string | number,
points?: number,
options?: IRateLimiterMongoFunctionOptions
): Promise<RateLimiterRes>;
reward(
key: string | number,
points?: number,
options?: IRateLimiterMongoFunctionOptions
): Promise<RateLimiterRes>;
block(
key: string | number,
secDuration: number,
options?: IRateLimiterMongoFunctionOptions
): Promise<RateLimiterRes>;
get(
key: string | number,
options?: IRateLimiterMongoFunctionOptions
): Promise<RateLimiterRes | null>;
set(
key: string | number,
points: number,
secDuration: number,
options?: IRateLimiterMongoFunctionOptions
): Promise<RateLimiterRes>;
delete(
key: string | number,
options?: IRateLimiterMongoFunctionOptions
): Promise<boolean>;
}
export class RateLimiterMySQL extends RateLimiterStoreAbstract {
constructor(opts: IRateLimiterStoreNoAutoExpiryOptions, cb?: ICallbackReady);
}
export class RateLimiterPostgres extends RateLimiterStoreAbstract {
constructor(opts: IRateLimiterPostgresOptions, cb?: ICallbackReady);
}
export class RateLimiterSQLite extends RateLimiterStoreAbstract {
constructor(opts: IRateLimiterStoreNoAutoExpiryOptions, cb?: ICallbackReady);
}
export class RateLimiterPrisma extends RateLimiterStoreAbstract {
constructor(opts: IRateLimiterStoreNoAutoExpiryOptions, cb?: ICallbackReady);
}
export class RateLimiterDrizzle extends RateLimiterStoreAbstract {
constructor(opts: IRateLimiterStoreNoAutoExpiryOptionsAndSchema, cb?: ICallbackReady);
}
export class RateLimiterDrizzleNonAtomic extends RateLimiterStoreAbstract {
constructor(opts: IRateLimiterStoreNoAutoExpiryOptionsAndSchema, cb?: ICallbackReady);
}
export class RateLimiterMemcache extends RateLimiterStoreAbstract { }
export class RateLimiterUnion {
constructor(...limiters: RateLimiterLike[]);
consume(key: string | number, points?: number): Promise<Record<string, RateLimiterRes>>;
}
export class RLWrapperBlackAndWhite extends RateLimiterCompatibleAbstract {
constructor(opts: IRLWrapperBlackAndWhiteOptions);
limiter: RateLimiterLike;
blackList: string[] | number[];
whiteList: string[] | number[];
isBlackListed: (key: any) => boolean;
isWhiteListed: (key: any) => boolean;
runActionAnyway: boolean;
}
interface IRLWrapperTimeoutsOptions extends Omit<IRateLimiterOptions, 'points' | 'duration'> {
limiter: RateLimiterLike;
timeoutMs?: number;
}
export class RLWrapperTimeouts extends RateLimiterInsuredAbstract {
constructor(opts: IRLWrapperTimeoutsOptions);
}
interface IRateLimiterQueueOpts {
maxQueueSize?: number;
}
export class RateLimiterQueue {
constructor(
limiterFlexible: RateLimiterLike | BurstyRateLimiter,
opts?: IRateLimiterQueueOpts
);
getTokensRemaining(key?: string | number): Promise<number>;
removeTokens(tokens: number, key?: string | number): Promise<number>;
}
export class BurstyRateLimiter {
constructor(
rateLimiter: RateLimiterLike,
burstLimiter: RateLimiterLike
);
consume(
key: string | number,
pointsToConsume?: number,
options?: IRateLimiterMongoFunctionOptions
): Promise<RateLimiterRes>;
}
interface IRateLimiterDynamoOptions extends IRateLimiterStoreOptions {
dynamoTableOpts?: {
readCapacityUnits: number;
writeCapacityUnits: number;
};
ttlSet?: boolean;
}
export class RateLimiterDynamo extends RateLimiterStoreAbstract {
constructor(opts: IRateLimiterDynamoOptions, cb?: ICallbackReady);
}
/**
* Options for RateLimiterValkeyGlide
*/
interface IRateLimiterValkeyGlideOptions extends IRateLimiterStoreOptions {
/**
* Valkey Glide client instance (GlideClient or GlideClusterClient)
*/
storeClient: any; // GlideClient | GlideClusterClient;
/**
* Whether to reject requests if Valkey is not ready
* @default false
*/
rejectIfValkeyNotReady?: boolean;
/**
* Custom Lua script for rate limiting logic.
* Must accept parameters:
* - KEYS[1]: The key being rate limited
* - ARGV[1]: Points to consume (as string, use tonumber() to convert)
* - ARGV[2]: Duration in seconds (as string, use tonumber() to convert)
*
* Must return an array with exactly two elements:
* - [0]: Consumed points (number)
* - [1]: TTL in milliseconds (number)
*/
customFunction?: string;
/**
* Custom name for the function library, defaults to 'ratelimiter'.
* The name is used to identify the library of the Lua function.
* A custom name should be used only if you want to use different
* libraries for different rate limiters.
* @default 'ratelimiter'
*/
customFunctionLibName?: string;
}
/**
* Rate limiter that uses Valkey Glide client for storage
*/
export class RateLimiterValkeyGlide extends RateLimiterStoreAbstract {
/**
* Creates a new instance of RateLimiterValkeyGlide
*
* @param opts Configuration options
*
* @example
* ```typescript
* // Basic usage
* const rateLimiter = new RateLimiterValkeyGlide({
* storeClient: glideClient,
* points: 5,
* duration: 1
* });
*
* // With custom Lua function
* const customScript = `local key = KEYS[1]
* local pointsToConsume = tonumber(ARGV[1]) or 0
* local secDuration = tonumber(ARGV[2]) or 0
*
* -- Custom implementation
* -- ...
*
* -- Must return exactly two values: [consumed_points, ttl_in_ms]
* return {consumed, ttl}`;
*
* const rateLimiter = new RateLimiterValkeyGlide({
* storeClient: glideClient,
* points: 5,
* customFunction: customScript
* });
*
* // With insurance limiter
* const rateLimiter = new RateLimiterValkeyGlide({
* storeClient: primaryGlideClient,
* points: 5,
* duration: 2,
* insuranceLimiter: new RateLimiterMemory({
* points: 5,
* duration: 2
* })
* });
* ```
*/
constructor(opts: IRateLimiterValkeyGlideOptions);
/**
* Close the rate limiter and release resources
* Note: The method won't close the Valkey client, as it may be shared with other instances.
*
* @returns Promise that resolves when the rate limiter is closed
*/
close(): Promise<void>;
}
/**
* Etcd Rate Limiter class.
*
* The option "storeClient" needs to be set to an instance of class "EtcdClient".
*/
export class RateLimiterEtcd extends RateLimiterEtcdNonAtomic {
constructor(opts: IRateLimiterStoreOptions);
}
/**
* Non-Atomic Etcd Rate Limiter class.
*
* The option "storeClient" needs to be set to an instance of class "EtcdClient".
*/
export class RateLimiterEtcdNonAtomic extends RateLimiterStoreAbstract {
constructor(opts: IRateLimiterStoreOptions);
}
export class RateLimiterQueueError extends Error {
constructor(message?: string, extra?: string);
readonly name: string;
readonly message: string;
readonly extra: string;
}
export class RateLimiterEtcdTransactionFailedError extends Error {
constructor(message?: string);
readonly name: string;
readonly message: string;
}