Skip to content

Commit ee63bb7

Browse files
committed
added timestamp to processRequest for RateLimiters and overahauled TokenBucket test suite to accomodate
1 parent c12b9e6 commit ee63bb7

File tree

3 files changed

+243
-111
lines changed

3 files changed

+243
-111
lines changed

src/@types/rateLimit.d.ts

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,23 @@ interface RateLimiter {
22
/**
33
* Checks if a request is allowed under the given conditions and withdraws the specified number of tokens
44
* @param uuid Unique identifier for the user associated with the request
5+
* @param timestamp UNIX format timestamp of when request was received
56
* @param tokens Number of tokens being used in this request. Optional
6-
* @returns true if the request is allowed
7+
* @returns a RateLimiterResponse indicating with a sucess and tokens property indicating the number of tokens remaining
78
*/
8-
processRequest: (uuid: string, tokens?: number) => boolean;
9+
processRequest: (
10+
uuid: string,
11+
timestamp: number,
12+
tokens?: number | undefined
13+
) => RateLimiterResponse;
914
}
1015

11-
interface RedisToken {
16+
interface RateLimiterResponse {
17+
success: boolean;
18+
tokens?: number;
19+
}
20+
21+
interface RedisBucket {
1222
tokens: number;
1323
timestamp: number;
1424
}

src/rateLimiters/tokenBucket.ts

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -25,24 +25,23 @@ class TokenBucket implements RateLimiter {
2525
this.capacity = capacity;
2626
this.refillRate = refillRate;
2727
this.client = client;
28+
if (refillRate <= 0 || capacity <= 0)
29+
throw Error('TokenBucket refillRate and capacity must be positive');
2830
}
2931

30-
processRequest(uuid: string, tokens = 1): boolean {
32+
processRequest(
33+
uuid: string,
34+
timestamp: number,
35+
tokens: number | undefined
36+
): RateLimiterResponse {
3137
throw Error(`TokenBucket.processRequest not implemented, ${this}`);
3238
}
3339

34-
/**
35-
* @returns current size of the token bucket in redis store or CAPACITY if user is not present
36-
*/
37-
getSize(uuid: string): number {
38-
throw Error(`TokenBucket.connect not implemented, ${this}`);
39-
}
40-
4140
/**
4241
* Resets the rate limiter to the intial state by clearing the redis store.
4342
*/
4443
reset(): void {
45-
throw Error(`TokenBucket.connect not implemented, ${this}`);
44+
throw Error(`TokenBucket.reset not implemented, ${this}`);
4645
}
4746
}
4847

0 commit comments

Comments
 (0)