-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathRequestManager.test.js
More file actions
277 lines (216 loc) · 8.92 KB
/
RequestManager.test.js
File metadata and controls
277 lines (216 loc) · 8.92 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
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
// Copyright (c) 2026 Music Blocks Contributors
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the The GNU Affero General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
const RequestManager = require("../RequestManager");
describe("RequestManager", () => {
let requestManager;
beforeEach(() => {
requestManager = new RequestManager({
minDelay: 100,
maxRetries: 2,
baseRetryDelay: 50,
maxConcurrent: 2
});
});
describe("failure handling and cleanup", () => {
it("should reject the promise if request never responds", async () => {
jest.useFakeTimers();
const neverResolvingRequest = jest.fn(() => {
// intentionally never calls callback
});
const promise = requestManager.throttledRequest(
{ action: "hang-test" },
neverResolvingRequest
);
// Fast-forward time beyond expected timeout (30s or configured)
jest.advanceTimersByTime(60000);
await Promise.resolve();
await expect(promise).rejects.toBeDefined();
jest.useRealTimers();
});
it("should clean up pendingRequests after timeout failure", async () => {
jest.useFakeTimers();
const neverResolvingRequest = jest.fn(() => {});
const promise = requestManager.throttledRequest(
{ action: "cleanup-test" },
neverResolvingRequest
);
// Request should be pending initially
expect(requestManager.pendingRequests.size).toBe(1);
jest.advanceTimersByTime(60000);
await Promise.resolve();
await promise.catch(() => {});
expect(requestManager.pendingRequests.size).toBe(0);
jest.useRealTimers();
});
it("should allow new requests after a failed request", async () => {
jest.useFakeTimers();
const neverResolvingRequest = jest.fn(() => {});
const successRequest = jest.fn(cb => cb({ success: true }));
const failed = requestManager.throttledRequest(
{ action: "fail-first" },
neverResolvingRequest
);
jest.advanceTimersByTime(60000);
await Promise.resolve();
await failed.catch(() => {});
const result = await requestManager.throttledRequest(
{ action: "next" },
successRequest
);
expect(result.success).toBe(true);
jest.useRealTimers();
});
});
afterEach(() => {
requestManager.clearPending();
});
describe("constructor", () => {
it("should initialize with default options", () => {
const rm = new RequestManager();
expect(rm.minDelay).toBe(500);
expect(rm.maxRetries).toBe(3);
expect(rm.baseRetryDelay).toBe(1000);
expect(rm.maxConcurrent).toBe(3);
});
it("should initialize with custom options", () => {
expect(requestManager.minDelay).toBe(100);
expect(requestManager.maxRetries).toBe(2);
expect(requestManager.baseRetryDelay).toBe(50);
expect(requestManager.maxConcurrent).toBe(2);
});
it("should initialize empty pending requests", () => {
expect(requestManager.pendingRequests.size).toBe(0);
});
it("should initialize stats to zero", () => {
const stats = requestManager.getStats();
expect(stats.totalRequests).toBe(0);
expect(stats.cachedResponses).toBe(0);
expect(stats.retries).toBe(0);
expect(stats.failures).toBe(0);
});
});
describe("generateRequestKey", () => {
it("should generate unique keys for different actions", () => {
const key1 = requestManager.generateRequestKey({ action: "getProject", id: 1 });
const key2 = requestManager.generateRequestKey({ action: "searchProject", id: 1 });
expect(key1).not.toBe(key2);
});
it("should generate same key for same data", () => {
const key1 = requestManager.generateRequestKey({ action: "getProject", id: 1 });
const key2 = requestManager.generateRequestKey({ action: "getProject", id: 1 });
expect(key1).toBe(key2);
});
it("should exclude api-key from key generation", () => {
const key1 = requestManager.generateRequestKey({
"action": "getProject",
"api-key": "abc"
});
const key2 = requestManager.generateRequestKey({
"action": "getProject",
"api-key": "xyz"
});
expect(key1).toBe(key2);
});
});
describe("throttledRequest", () => {
it("should execute request and return result", async () => {
const mockResult = { success: true, data: "test" };
const mockRequestFn = jest.fn(callback => {
callback(mockResult);
});
const result = await requestManager.throttledRequest({ action: "test" }, mockRequestFn);
expect(result).toEqual(mockResult);
expect(mockRequestFn).toHaveBeenCalled();
});
it("should deduplicate concurrent requests with same key", async () => {
let callCount = 0;
const mockResult = { success: true, data: "test" };
const mockRequestFn = jest.fn(callback => {
callCount++;
setTimeout(() => callback(mockResult), 50);
});
// Make two identical requests concurrently
const promise1 = requestManager.throttledRequest(
{ action: "test", id: 1 },
mockRequestFn
);
const promise2 = requestManager.throttledRequest(
{ action: "test", id: 1 },
mockRequestFn
);
const [result1, result2] = await Promise.all([promise1, promise2]);
expect(result1).toEqual(mockResult);
expect(result2).toEqual(mockResult);
// Should only make one actual request due to deduplication
expect(callCount).toBe(1);
});
it("should increment cached responses for deduplicated requests", async () => {
const mockResult = { success: true };
const mockRequestFn = callback => {
setTimeout(() => callback(mockResult), 50);
};
await Promise.all([
requestManager.throttledRequest({ action: "test" }, mockRequestFn),
requestManager.throttledRequest({ action: "test" }, mockRequestFn)
]);
const stats = requestManager.getStats();
expect(stats.cachedResponses).toBe(1);
});
});
describe("retry logic", () => {
it("should retry on connection failure", async () => {
let attempts = 0;
const mockRequestFn = jest.fn(callback => {
attempts++;
if (attempts < 2) {
callback({ success: false, error: "ERROR_CONNECTION_FAILURE" });
} else {
callback({ success: true, data: "recovered" });
}
});
const result = await requestManager.throttledRequest({ action: "test" }, mockRequestFn);
expect(result.success).toBe(true);
expect(attempts).toBeGreaterThan(1);
});
it("should fail after max retries exceeded", async () => {
const mockRequestFn = jest.fn(callback => {
callback({ success: false, error: "ERROR_CONNECTION_FAILURE" });
});
const result = await requestManager.throttledRequest({ action: "test" }, mockRequestFn);
// After all retries, should return the failure result
expect(result.success).toBe(false);
});
});
describe("hasPendingRequests", () => {
it("should return false when no pending requests", () => {
expect(requestManager.hasPendingRequests()).toBe(false);
});
});
describe("resetStats", () => {
it("should reset all statistics to zero", async () => {
// Make some requests first
await requestManager.throttledRequest({ action: "test" }, callback =>
callback({ success: true })
);
requestManager.resetStats();
const stats = requestManager.getStats();
expect(stats.totalRequests).toBe(0);
expect(stats.cachedResponses).toBe(0);
expect(stats.retries).toBe(0);
expect(stats.failures).toBe(0);
});
});
describe("clearPending", () => {
it("should clear all pending requests", () => {
requestManager.pendingRequests.set("test", Promise.resolve());
requestManager.requestQueue.push({});
requestManager.clearPending();
expect(requestManager.pendingRequests.size).toBe(0);
expect(requestManager.requestQueue.length).toBe(0);
});
});
});