-
Notifications
You must be signed in to change notification settings - Fork 0
/
token-bucket.js
77 lines (58 loc) · 1.69 KB
/
token-bucket.js
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
export default class TokenBucket {
constructor(capacity, refillAmount, refillTimeInSeconds) {
this.capacity = capacity;
this.refillAmount =
refillAmount; /* Amount of tokens refilled in the bucket */
this.refillTimeInSeconds =
refillTimeInSeconds; /* In what time period, the bucket is refilled*/
this.db = {};
}
createBucket(key) {
if (!this.db[key]) {
this.db[key] = {
tokens: this.capacity,
timestamp: Date.now(),
};
}
return this.db[key];
}
refillBucket(key) {
if (!this.db[key]) return null;
const { tokens, timestamp } = this.db[key];
const currentTime = Date.now();
const elapsedTime = Math.floor(
(currentTime - timestamp) / (this.refillTimeInSeconds * 1000)
);
const newTokens = elapsedTime * this.refillAmount;
this.db[key] = {
tokens: Math.min(this.capacity, tokens + newTokens),
timestamp: Date.now(),
};
return this.db[key];
}
handleRequest(key) {
let bucket = this.createBucket(key);
const { timestamp } = bucket;
const currentTime = Date.now();
const elapsedTimeInSeconds = Math.floor((currentTime - timestamp) / 1000);
if (elapsedTimeInSeconds > this.refillTimeInSeconds) {
bucket = this.refillBucket(key);
} else {
if (bucket.tokens <= 0) {
console.log(
`Request REJECTED for ${key} -- tokens: ${
bucket.tokens
} --${new Date().toLocaleString()}`
);
return false;
}
}
console.log(
`Request ACCEPTED for ${key} -- tokens: ${
bucket.tokens
} --${new Date().toLocaleString()}`
);
bucket.tokens -= 1;
return true;
}
}