-
Notifications
You must be signed in to change notification settings - Fork 547
/
Copy pathrateLimiter.ts
54 lines (49 loc) · 1.68 KB
/
rateLimiter.ts
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
/*!
* Copyright (c) Microsoft Corporation and contributors. All rights reserved.
* Licensed under the MIT License.
*/
/**
* A rate limiter to make sure that a client can only request help for one task within a time window.
*
* @deprecated This class has no replacement.
*
* @privateremarks
* This class is not used anywhere in the repo. driver-utils already has a similar class that is used by the odsp and
* routerlicious drivers.
* @internal
*/
export class RateLimiter {
private readonly requestMap = new Map<string, number>();
/**
* Creates a rate limiter that keep track of the request it has made
*
* @param windowMSec - time in millisecond, use to filter out messages
* for a clientId if the last request falls within this time window
*/
constructor(private readonly windowMSec: number) {}
/**
* Filter out the messages that had already been requested within the time window
*
* @param clientId - the clientId who want to send the message
* @param messages - the message we want to send
* @returns the message we approved to send that hasn't been sent recently
*/
public filter(clientId: string, messages: string[]): string[] {
const approvedList: string[] = [];
const currentTime = Date.now();
for (const message of messages) {
const key = `${clientId}/${message}`;
if (!this.requestMap.has(key)) {
this.requestMap.set(key, currentTime);
approvedList.push(message);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
} else if (this.requestMap.get(key)! + this.windowMSec > currentTime) {
continue;
} else {
this.requestMap.set(key, currentTime);
approvedList.push(message);
}
}
return approvedList;
}
}