Repository navigation
Expand file tree
/
Copy pathrequestExecutor.js
More file actions
505 lines (438 loc) · 22.2 KB
/
Copy pathrequestExecutor.js
File metadata and controls
505 lines (438 loc) · 22.2 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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
import Bottleneck from 'bottleneck/es5.js';
import RequestMonitor from './requestMonitor.js';
import { config } from '../config.js';
import axios from 'axios';
import { setupCache } from 'axios-cache-interceptor';
import Redis from 'ioredis';
import logger from './logger.js';
import { v4 as uuidv4 } from 'uuid';
import { sanitizeBase64 } from './util.js';
const connectionString = config.get('storageConnectionString');
if (!connectionString) {
logger.info('No STORAGE_CONNECTION_STRING found in environment. Redis features (caching, pubsub, clustered limiters) disabled.')
} else {
logger.info('Using Redis connection specified in STORAGE_CONNECTION_STRING.');
}
let client;
if (connectionString) {
try {
// Configure Redis with exponential backoff retry strategy
const retryStrategy = (times) => {
// Exponential backoff: 100ms, 200ms, 400ms, 800ms, 1600ms, 3200ms, 6400ms, 12800ms, 25600ms, 30000ms (max)
const delay = Math.min(100 * Math.pow(2, times), 30000);
// Stop retrying after 10 attempts (about 5 minutes total)
if (times > 10) {
logger.error(`Redis connection failed after ${times} attempts. Stopping retries.`);
return null;
}
logger.warn(`Redis connection retry attempt ${times}, waiting ${delay}ms before next attempt`);
return delay;
};
client = new Redis(connectionString, {
retryStrategy,
maxRetriesPerRequest: null, // Allow unlimited retries for connection issues
enableReadyCheck: true,
lazyConnect: false,
connectTimeout: 10000, // 10 second connection timeout
});
// Handle Redis connection errors to prevent crashes
client.on('error', (error) => {
logger.error(`Redis client connection error: ${error}`);
});
client.on('connect', () => {
logger.info('Redis client connected successfully');
});
client.on('ready', () => {
logger.info('Redis client ready');
});
client.on('close', () => {
logger.warn('Redis client connection closed');
});
client.on('reconnecting', (delay) => {
logger.info(`Redis client reconnecting in ${delay}ms`);
});
} catch (error) {
logger.error(`Redis connection error: ${error}`);
}
}
const cortexId = config.get('cortexId');
const connection = client && new Bottleneck.IORedisConnection({ client: client });
let modelEndpoints = {};
const createLimiter = (endpoint, name, index) => {
const rps = endpoint.requestsPerSecond ?? 100;
let limiterOptions = {
minTime: 1000 / rps,
maxConcurrent: rps,
reservoir: rps, // Number of tokens available initially
reservoirRefreshAmount: rps, // Number of tokens added per interval
reservoirRefreshInterval: 1000, // Interval in milliseconds
};
// If Redis connection exists, add id and connection to enable clustering
if (connection) {
limiterOptions.id = `${cortexId}-${name}-${index}-limiter`; // Unique id for each limiter
limiterOptions.connection = connection; // Shared Redis connection
}
endpoint.limiter = new Bottleneck(limiterOptions);
endpoint.limiter.on('error', (err) => {
logger.error(`Limiter error for ${cortexId}-${name}-${index}: ${err}`);
endpoint.limiter.disconnect();
createLimiter(endpoint, name, index);
logger.info(`New limiter created for ${cortexId}-${name}-${index}`)
});
endpoint.limiter.on('failed', (error, info) => {
if (error.name === 'CanceledError') {
logger.debug(`Limiter request cancelled for ${cortexId}-${name}-${index}: Id: ${info.options.id || 'none'}`);
endpoint.monitor.incrementErrorCount();
} else {
const errorMsg = error?.message || error;
const status = error?.status || 'unknown';
logger.error(`Limiter request failed for ${cortexId}-${name}-${index}: Id: ${info.options.id || 'none'}: [${status}] ${errorMsg}`);
// Log response data if available (helpful for debugging 400 errors)
if (error?.responseData) {
const responseDataStr = typeof error.responseData === 'string'
? error.responseData.substring(0, 1000)
: JSON.stringify(error.responseData, null, 2).substring(0, 1000);
logger.error(`Response data: ${responseDataStr}`);
}
}
});
endpoint.limiter.on('debug', (message) => {
if (!message.includes('heartbeat.lua')) {
logger.debug(`Limiter ${cortexId}-${name}-${index}: ${message}`);
}
});
}
const buildModelEndpoints = (config) => {
modelEndpoints = JSON.parse(JSON.stringify(config.get('models')));
logger.info(`Building ${connection ? 'Redis clustered' : 'local'} model rate limiters for ${cortexId}...`);
for (const [name, model] of Object.entries(modelEndpoints)) {
model.endpoints.forEach((endpoint, index) => {
createLimiter(endpoint, name, index)
endpoint.monitor = new RequestMonitor();
});
}
}
let currentIndex = 0; // for round-robin selection
const selectEndpoint = (model) => {
if (!model || !Array.isArray(model.endpoints) || model.endpoints.length === 0) {
return null;
} else {
logger.debug(`Selecting endpoint for model ${model.name}...`);
if (model.endpoints.length === 1) {
logger.debug(`Only one endpoint for model ${model.name}. No selection required.`);
return model.endpoints[0];
}
let healthyEndpoints = model.endpoints.filter(endpoint => endpoint.monitor.healthy);
if (healthyEndpoints.length === 0) {
const selectedEndpoint = model.endpoints[currentIndex % model.endpoints.length];
currentIndex++;
logger.warn(`No healthy endpoints for model ${model.name}. Using round-robin selection. Selected: ${selectedEndpoint.name || 'default'}`);
return selectedEndpoint;
}
healthyEndpoints.forEach(endpoint =>{
logger.debug(`Healthy endpoint: ${endpoint.name || 'default'}, duration: ${endpoint.monitor.getAverageCallDuration()}ms`);
})
let selectedEndpoint;
const durations = healthyEndpoints.map(endpoint => endpoint.monitor.getAverageCallDuration());
if (shouldUseRoundRobin(durations)) {
selectedEndpoint = healthyEndpoints[currentIndex % healthyEndpoints.length];
currentIndex++;
logger.debug(`All endpoints are performing similarly. Using round-robin selection. Selected: ${selectedEndpoint.name || 'default'}`);
} else {
selectedEndpoint = fastestEndpoint(healthyEndpoints);
logger.debug(`Selected fastest endpoint: ${selectedEndpoint.name || 'default'}`);
}
return selectedEndpoint;
}
}
const calculateStandardDeviation = (durations) => {
const mean = durations.reduce((total, value) => total + value, 0) / durations.length;
const variance = durations.reduce((total, value) => total + Math.pow(value - mean, 2), 0) / durations.length;
return Math.sqrt(variance);
}
const shouldUseRoundRobin = (durations) => {
const standardDeviation = calculateStandardDeviation(durations);
const threshold = 10;
return standardDeviation <= threshold;
}
const fastestEndpoint = (endpoints) => {
return endpoints.reduce((fastest, current) => {
if (current.monitor.getAverageCallDuration() < fastest.monitor.getAverageCallDuration()) {
return current;
} else {
return fastest;
}
});
}
let cortexAxios = axios;
if (config.get('enableCache')) {
// Setup cache
cortexAxios = setupCache(axios, {
// enable cache for all requests by default
methods: ['get', 'post', 'put', 'delete', 'patch'],
interpretHeader: false,
ttl: 1000 * 60 * 60 * 24 * 7, // 7 days
});
}
//log statistics about active endpoints
setInterval(() => {
// Iterate over each model
for (const [name, model] of Object.entries(modelEndpoints)) {
// Iterate over each endpoint in the current model
let endpointIndex = 0;
model.endpoints.forEach((endpoint) => {
const monitor = endpoint.monitor;
if (!monitor) {
// Skip if monitor does not exist
return;
}
const callRate = monitor.getPeakCallRate();
if (callRate > 0) {
const error429Rate = monitor.getError429Rate();
const errorRate = monitor.getErrorRate();
const avgCallDuration = monitor.getAverageCallDuration();
logger.debug('------------------------');
logger.debug(`Monitor of ${name} endpoint ${endpoint.name || endpointIndex} Call rate: ${callRate} calls/sec, duration: ${avgCallDuration}ms, 429 errors: ${error429Rate * 100}%, errors: ${errorRate * 100}%`);
logger.debug('------------------------');
}
endpointIndex++;
});
}
}, 30000); // Log rates every 30 seconds
const requestWithMonitor = async (endpoint, url, data, axiosConfigObj) => {
//logger.warn(`Requesting ${url} with data: ${JSON.stringify(data)}`);
const callId = endpoint?.monitor?.startCall();
let response;
try {
if (axiosConfigObj?.method == 'GET'){
logger.debug(`Getting ${url} with data: ${JSON.stringify(sanitizeBase64(data))}`);
response = await cortexAxios.get(url, axiosConfigObj);
} else {
logger.debug(`Posting ${url} with data: ${JSON.stringify(sanitizeBase64(data))}`);
response = await cortexAxios.post(url, data, axiosConfigObj);
}
} catch (error) {
// throw new error with duration as part of the error data
const { code, name } = error;
const finalStatus = error?.response?.status ?? error?.status;
const statusText = error?.response?.statusText ?? error?.statusText;
let responseData = error?.response?.data;
// For streaming requests with errors, the response data is a stream that needs to be consumed
if (responseData && typeof responseData.on === 'function') {
try {
const chunks = [];
for await (const chunk of responseData) {
chunks.push(chunk);
}
const streamContent = Buffer.concat(chunks).toString('utf-8');
try {
responseData = JSON.parse(streamContent);
} catch {
responseData = { rawContent: streamContent.substring(0, 2000) };
}
} catch (streamError) {
logger.debug(`Could not read error stream: ${streamError.message}`);
responseData = null;
}
}
// Extract error message from various possible locations in the response
const errorMessage = responseData?.message
?? responseData?.error?.message
?? responseData?.error?.status
?? responseData?.rawContent?.substring(0, 500)
?? error?.message
?? String(error);
// Log full response data for debugging 4xx errors (especially 400)
if (finalStatus >= 400 && finalStatus < 500 && responseData) {
const responseDataStr = typeof responseData === 'string'
? responseData.substring(0, 2000)
: JSON.stringify(responseData, null, 2).substring(0, 2000);
logger.error(`HTTP ${finalStatus} error response data: ${responseDataStr}`);
}
throw { code, message: errorMessage, status: finalStatus, statusText, name, responseData, duration: endpoint?.monitor?.incrementErrorCount(callId, finalStatus) };
}
let duration;
if (response.status >= 200 && response.status < 300) {
duration = endpoint?.monitor?.endCall(callId);
} else {
duration = endpoint?.monitor?.incrementErrorCount(callId, response.status);
}
return { response, duration };
}
const MAX_RETRY = 6; // retries for error handling
const MAX_DUPLICATE_REQUESTS = 3; // duplicate requests to manage latency spikes
const DUPLICATE_REQUEST_AFTER = 10; // 10 seconds
const getDuplicateRequestDelay = (index, duplicateRequestAfter) => {
const duplicateRequestTime = duplicateRequestAfter * Math.pow(2, index) - duplicateRequestAfter;
const jitter = duplicateRequestTime * 0.2 * Math.random();
const duplicateRequestTimeout = Math.max(0, duplicateRequestTime + jitter);
return duplicateRequestTimeout;
}
const makeRequest = async (cortexRequest) => {
let promises = [];
// retry certain errors up to MAX_RETRY times
for (let i = 0; i < MAX_RETRY; i++) {
const { url, data, params, headers, cache, selectedEndpoint, requestId, pathway, model, stream, method} = cortexRequest;
const enableDuplicateRequests = pathway?.enableDuplicateRequests !== undefined ? pathway.enableDuplicateRequests : config.get('enableDuplicateRequests');
const maxDuplicateRequests = enableDuplicateRequests ? MAX_DUPLICATE_REQUESTS : 1;
const duplicateRequestAfter = (pathway?.duplicateRequestAfter || DUPLICATE_REQUEST_AFTER) * 1000;
const axiosConfigObj = { params, headers, cache, method };
const streamRequested = (stream || params?.stream || data?.stream);
// if we're using streaming, duplicate requests are
// not supported, so we just push one promise into the array
if (streamRequested && model.supportsStreaming) {
axiosConfigObj.responseType = 'stream';
promises.push(selectedEndpoint.limiter.schedule({expiration: pathway.timeout * 1000 + 1000, id: `${requestId}_${uuidv4()}`},() => requestWithMonitor(selectedEndpoint, url, data, axiosConfigObj)));
} else {
if (streamRequested) {
logger.info(`>>> [${requestId}] ${model.name || 'This model'} does not support streaming - sending non-streaming request`);
axiosConfigObj.params.stream = false;
data.stream = false;
}
// if we're not streaming, we push at least one promise
// into the array, but if we're supporting duplicate
// requests we push one for each potential duplicate,
// heading to a new endpoint (if available) and
// staggered by a jittered amount of time
const controllers = Array.from({ length: maxDuplicateRequests }, () => new AbortController());
promises = controllers.map((controller, index) =>
new Promise((resolve, reject) => {
setTimeout(async () => {
try {
if (index > 0) {
cortexRequest.selectNewEndpoint();
}
const { url, data, params, headers, cache, selectedEndpoint, requestId, pathway, model } = cortexRequest;
const endpointName = selectedEndpoint.name || model;
if (!selectedEndpoint.limiter) {
throw new Error(`No limiter for endpoint ${endpointName}!`);
}
const axiosConfigObj = { params, headers, cache, method };
let response = null;
let duration = null;
if (!controller.signal?.aborted) {
axiosConfigObj.signal = controller.signal;
axiosConfigObj.headers['X-Cortex-Request-Index'] = index;
if (index > 0) {
const logMessage = `>>> [${requestId}] taking too long - sending duplicate request ${index} to ${endpointName} API`;
const header = '>'.repeat(logMessage.length);
logger.info(`\n${header}\n${logMessage}`);
}
({ response, duration } = await selectedEndpoint.limiter.schedule({expiration: pathway.timeout * 1000 + 1000, id: `${requestId}_${uuidv4()}`}, () => requestWithMonitor(selectedEndpoint, url, data, axiosConfigObj)));
if (!controller.signal?.aborted) {
logger.verbose(`<<< [${requestId}] received response for request ${index}`);
}
}
resolve({ response, duration });
} catch (error) {
if (error.name === 'AbortError' || error.name === 'CanceledError') {
//logger.info(`XXX [${requestId}] request ${index} was cancelled`);
reject(error);
} else {
logger.error(`!!! [${requestId}] request ${index} failed with error: ${error?.response?.data?.message || error?.response?.data?.error?.message || error?.message || error}`);
reject(error);
}
} finally {
controllers.forEach(controller => controller.abort());
}
}, getDuplicateRequestDelay(index, duplicateRequestAfter));
})
);
}
// no requests have been made yet, but the promises array
// is full, so now we execute them in parallel
try {
const { response, duration } = await Promise.race(promises);
// if response status is 2xx
if (response?.status >= 200 && response?.status < 300) {
return { response, duration };
} else {
const error = new Error(`Request failed with status ${response?.status}`);
error.response = response;
error.duration = duration;
throw error;
}
} catch (error) {
// Handle both cases: error with response object and direct error object
const status = error?.response?.status || error?.status || 502; // default to 502 if no status
const duration = error?.duration;
const response = error?.response || {error: error};
// Calculate backoff time - use Retry-After for 429s if available
let backoffTime = 1000 * Math.pow(2, i);
if (status === 429 && (response?.headers?.['retry-after'] || error?.headers?.['retry-after'])) {
backoffTime = parseInt(response?.headers?.['retry-after'] || error?.headers?.['retry-after']) * 1000;
logger.warn(`>>> [${requestId}] Rate limited (429). Retry-After: ${response?.headers?.['retry-after'] || error?.headers?.['retry-after']}s`);
}
const jitter = backoffTime * 0.2 * Math.random();
// if there is only one endpoint, only retry select error codes
if (cortexRequest.model.endpoints.length === 1) {
if (status !== 429 &&
status !== 408 &&
status !== 500 &&
status !== 502 &&
status !== 503 &&
status !== 504) {
return { response, duration };
}
// set up for a retry by reinitializing the request
cortexRequest.initRequest();
} else {
// if there are multiple endpoints, retry everything by default
// as it could be a temporary issue with one endpoint
// certain errors (e.g. 400) are problems with the request itself
// and should not be retried
if (status == 400 || status == 413) {
return { response, duration };
}
// set up for a retry by selecting a new endpoint, which will also reinitialize the request
cortexRequest.selectNewEndpoint();
}
if (i < MAX_RETRY - 1) {
logger.info(`>>> [${requestId}] retrying request due to ${status} response. Retry count: ${i + 1}. Retrying in ${backoffTime + jitter}ms`);
await new Promise(r => setTimeout(r, backoffTime + jitter));
} else {
return { response, duration };
}
}
}
};
const executeRequest = async (cortexRequest) => {
try {
const result = await makeRequest(cortexRequest);
// Validate that we have a result and it contains response
if (!result || !result.response) {
throw new Error('No response received from request');
}
const { response, duration } = result;
const requestId = cortexRequest.requestId;
// Validate response object
if (!response || typeof response !== 'object') {
throw new Error('Invalid response object received');
}
const { data, cached } = response;
if (cached) {
logger.info(`<<< [${requestId}] served with cached response.`);
}
// Check for error object in the response
if (response.error) {
throw new Error(response.error.message || JSON.stringify(response.error));
}
// Check for HTTP error status
if (response.status >= 400) {
const errorMessage = response.data?.error?.message || response.statusText;
const errorDetails = response.data ? `\nResponse data: ${JSON.stringify(response.data)}` : '';
throw new Error(`HTTP error: ${response.status} ${errorMessage}${errorDetails}`);
}
return { data, duration };
} catch (error) {
// Add context to the error
const requestId = cortexRequest?.requestId || 'unknown';
const model = cortexRequest?.model?.name || 'unknown';
const errorMessage = error.message || 'Unknown error occurred';
logger.error(`Error in executeRequest for ${model} (requestId: ${requestId}): ${errorMessage}`);
throw error;
}
}
export {
axios, executeRequest, buildModelEndpoints, selectEndpoint, modelEndpoints, createLimiter
};