-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathtoken_bucket.ts
More file actions
54 lines (49 loc) · 1.16 KB
/
token_bucket.ts
File metadata and controls
54 lines (49 loc) · 1.16 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
/**
* @internal
*/
export class TokenBucket {
private budget: number;
private capacity: number;
constructor(allowance: number) {
this.budget = allowance;
this.capacity = allowance;
}
deposit(tokens: number) {
this.budget = Math.min(this.budget + tokens, this.capacity);
}
consume(tokens: number): boolean {
if (tokens > this.budget) return false;
this.budget -= tokens;
return true;
}
}
/**
* @internal
* The amount to deposit on successful operations, as defined in the backpressure specification.
*/
export const RETRY_TOKEN_RETURN_RATE = 0.1;
/**
* @internal
* The initial size of the token bucket, as defined in the backpressure specification.
*/
export const INITIAL_TOKEN_BUCKET_SIZE = 1_000;
/**
* @internal
* The cost of a retry, as defined in the backpressure specification.
*/
export const RETRY_COST = 1;
/**
* @internal
* The maximum number of retries for overload errors
* */
export const MAX_RETRIES = 5;
/**
* @internal
* The base backoff duration in milliseconds
* */
export const BASE_BACKOFF_MS = 100;
/**
* @internal
* The maximum backoff duration in milliseconds
* */
export const MAX_BACKOFF_MS = 10_000;