-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
170 lines (151 loc) · 5.01 KB
/
index.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
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
import axios, { AxiosInstance, AxiosRequestConfig, InternalAxiosRequestConfig } from 'axios';
interface Job {
id: string;
createdAt: string;
status: 'queued' | 'processing' | 'completed' | 'failed';
priority?: number;
retryCount?: number;
data?: any;
execute: () => void;
}
type ConstructArgs = {
maxRequestsPerSecond: number,
burstRequests: number,
burstTime: number;
instance: AxiosInstance
}
class RequestQueue {
private instance: AxiosInstance;
private queue: Job[];
private maxRequestsPerSecond: number;
private burstRequests: number;
private burstTime: number;
private requestsMade: number;
private burstRequestsMade: number;
private sending: boolean;
private burstTimer: NodeJS.Timeout | null
private rateTimer: NodeJS.Timeout | null
private requestLogs: {time: string}[]
private start: number | null
constructor({maxRequestsPerSecond, burstRequests, burstTime, instance}: ConstructArgs) {
this.queue = [];
this.maxRequestsPerSecond = maxRequestsPerSecond;
this.burstRequests = burstRequests;
this.burstTime = burstTime;
this.requestsMade = 0;
this.burstRequestsMade = 0;
this.sending = false;
this.burstTimer = null
this.rateTimer = null
this.requestLogs = []
this.start = null
this.instance = instance ?? axios.create();
this.addRequestInterceptor();
}
private async processQueue() {
if (!this.sending) {
}
if (this.queue.length === 0) {
this.sending = false;
return;
}
const canProcessBurstRequest = this.burstRequestsMade < this.burstRequests;
const canProcessNonBurstRequest = this.requestsMade < this.maxRequestsPerSecond;
if (canProcessBurstRequest || canProcessNonBurstRequest) {
// console.log(`requestsMade: ${this.requestsMade} burstRequestsMade:${this.burstRequestsMade}`);
const { execute } = this.queue.shift() as Job;
try {
if (this.queue.length === 0) {
// await execute()
if (this.start) {
// dang, I don't actually have the promise for the request
// this won't be accurate if I can't tell when it's done
// console.log(`Queue drained after ${Date.now() - this.start}`)
}
}
execute();
this.handleRequestSent(); // Call after executing the job
} catch (error) {
// we retry if we hit an error
// Idk what axios does when we throw in the interceptor
console.log(error);
}
}
// If there are more requests and we haven't exhausted the burst limit, process the next request immediately
if (canProcessBurstRequest && this.queue.length > 0) {
this.processQueue();
} else {
setTimeout(() => {
this.processQueue();
}, this.getRequestDelay());
}
}
private getRequestDelay() {
const delayBetweenRequests = 1000 / this.maxRequestsPerSecond;
const burstWindowReset = this.burstTime * 1000;
const rateLimitReset = 1000;
if (!this.rateTimer) {
this.rateTimer = setTimeout(() => {
this.requestsMade = 0;
// I think this should suffice for having a single reset for the overall called
this.rateTimer = null
}, rateLimitReset);
}
if (!this.burstTimer) {
// does it matter that these are on static resets?
// I can use the reset time on response header, but
// I still don't know how bursts are tracked, is the window rolling? I doubt it
this.burstTimer = setTimeout(() => {
this.burstRequestsMade = 0;
this.burstTimer = null
}, burstWindowReset);
}
return delayBetweenRequests;
}
private handleRequestSent() {
const timestamp = new Date()
this.requestLogs.push({ time: timestamp.toISOString() });
if (this.burstRequestsMade < this.burstRequests) {
this.burstRequestsMade++;
} else {
this.requestsMade++;
}
}
public exportRequestLogs() {
return this.requestLogs
}
// should also ad a response interceptor to update
// the queue information based on returned rate limit data
private addRequestInterceptor() {
this.instance.interceptors.request.use(async (config: InternalAxiosRequestConfig) => {
return new Promise<InternalAxiosRequestConfig>(async (resolve) => {
const executeJob = () => {
resolve(config);
this.handleRequestSent();
};
const newJob: Job = {
id: this.generateUniqueId(),
createdAt: new Date().toISOString(),
status: 'queued',
execute: executeJob,
};
this.queue.push(newJob);
if (!this.sending) {
// console.log('starting')
this.start = Date.now()
this.sending = true;
this.processQueue();
}
});
});
}
private generateUniqueId(): string {
return (
Date.now().toString(36) + Math.random().toString(36).substr(2, 5)
).toUpperCase();
}
getInstance(): AxiosInstance {
return this.instance;
}
}
export default RequestQueue;