-
Notifications
You must be signed in to change notification settings - Fork 157
Expand file tree
/
Copy pathRequestHandler.js
More file actions
4055 lines (3680 loc) · 187 KB
/
RequestHandler.js
File metadata and controls
4055 lines (3680 loc) · 187 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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* File: src/core/RequestHandler.js
* Description: Main request handler that processes API requests, manages retries, and coordinates between authentication and format conversion
*
* Author: Ellinav, iBenzene, bbbugg
*/
/**
* Request Handler Module (Refactored)
* Main request handler that coordinates between other modules
*/
const AuthSwitcher = require("../auth/AuthSwitcher");
const FormatConverter = require("./FormatConverter");
const { isUserAbortedError } = require("../utils/CustomErrors");
const { QueueClosedError, QueueTimeoutError } = require("../utils/MessageQueue");
// Timeout constants (in milliseconds)
const TIMEOUTS = {
FAKE_STREAM: 300000, // 300 seconds (5 minutes) - timeout for fake streaming (buffered response)
STREAM_CHUNK: 60000, // 60 seconds - timeout between stream chunks
};
class RequestHandler {
constructor(serverSystem, connectionRegistry, logger, browserManager, config, authSource) {
this.serverSystem = serverSystem;
this.connectionRegistry = connectionRegistry;
this.logger = logger;
this.browserManager = browserManager;
this.config = config;
this.authSource = authSource;
// Initialize sub-modules
this.authSwitcher = new AuthSwitcher(logger, config, authSource, browserManager);
this.formatConverter = new FormatConverter(logger, serverSystem);
this.maxRetries = this.config.maxRetries;
this.retryDelay = this.config.retryDelay;
this.needsSwitchingAfterRequest = false;
// Timeout settings
this.timeouts = TIMEOUTS;
}
// Delegate properties to AuthSwitcher
get currentAuthIndex() {
return this.authSwitcher.currentAuthIndex;
}
get failureCount() {
return this.authSwitcher.failureCount;
}
get usageCount() {
return this.authSwitcher.usageCount;
}
get isSystemBusy() {
return this.authSwitcher.isSystemBusy;
}
_getUsageStatsService() {
return this.serverSystem.usageStatsService || null;
}
_getAccountNameForIndex(authIndex) {
if (!Number.isInteger(authIndex) || authIndex < 0) {
return null;
}
return this.authSource?.accountNameMap?.get(authIndex) || null;
}
_getClientIp(req) {
return this.serverSystem.webRoutes.authRoutes.getClientIP(req);
}
_extractModelFromPath(pathValue) {
if (typeof pathValue !== "string") return null;
const match = pathValue.match(/\/models\/([^:/?]+)(?::|$)/);
return match?.[1] || null;
}
_categorizeRequest(pathValue, fallback = "request") {
if (typeof pathValue !== "string") return fallback;
if (pathValue.includes("countTokens") || pathValue.includes("input_tokens")) return "count_tokens";
if (pathValue.includes("generateContent") || pathValue.includes("streamGenerateContent")) return "generation";
if (pathValue.includes("/upload/")) return "upload";
return fallback;
}
_startTrackedRequest(requestId, req, meta = {}) {
const usageStatsService = this._getUsageStatsService();
if (!usageStatsService) return;
usageStatsService.startRequest(requestId, {
clientIp: this._getClientIp(req),
initialAccountName: this._getAccountNameForIndex(this.currentAuthIndex),
initialAuthIndex: this.currentAuthIndex,
method: req.method,
path: req.path,
...meta,
});
}
_updateTrackedRequest(requestId, patch = {}) {
const usageStatsService = this._getUsageStatsService();
if (!usageStatsService) return;
usageStatsService.updateRequest(requestId, patch);
}
_finalizeTrackedRequest(requestId, res, overrides = {}) {
const usageStatsService = this._getUsageStatsService();
if (!usageStatsService) return;
let outcome = overrides.outcome;
if (!outcome) {
if (res.__usageTrackingClientAborted) {
outcome = "aborted";
} else if (res.__usageTrackingOutcome) {
outcome = res.__usageTrackingOutcome;
} else {
const statusCode = Number.isFinite(res.statusCode) ? Number(res.statusCode) : null;
outcome = statusCode !== null && statusCode >= 400 ? "error" : "success";
}
}
const statusCode =
overrides.statusCode ??
res.__usageTrackingErrorStatus ??
(Number.isFinite(res.statusCode) && res.statusCode > 0 ? Number(res.statusCode) : null);
const errorMessage =
overrides.errorMessage ??
res.__usageTrackingErrorMessage ??
(outcome === "error" ? "Request failed" : null);
usageStatsService.finishRequest(requestId, {
errorMessage,
finalAccountName: overrides.finalAccountName,
finalAuthIndex: overrides.finalAuthIndex,
outcome,
statusCode,
});
}
_markTrackedResponseError(res, message, statusCode = null, outcome = "error") {
if (!res) return;
res.__usageTrackingOutcome = outcome;
res.__usageTrackingErrorMessage = message || null;
if (Number.isFinite(statusCode)) {
res.__usageTrackingErrorStatus = Number(statusCode);
}
}
_markTrackedClientAbort(res, message = "Client disconnected") {
if (!res) return;
res.__usageTrackingClientAborted = true;
res.__usageTrackingOutcome = "aborted";
res.__usageTrackingErrorMessage = message;
}
// Delegate methods to AuthSwitcher
async _switchToNextAuth() {
return this.authSwitcher.switchToNextAuth();
}
async _switchToSpecificAuth(targetIndex) {
return this.authSwitcher.switchToSpecificAuth(targetIndex);
}
async _waitForGraceReconnect(timeoutMs = 60000) {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
if (!this.connectionRegistry.isInGracePeriod() && !this.connectionRegistry.isReconnectingInProgress()) {
const connectionReady = await this._waitForConnection(10000);
return connectionReady;
}
await new Promise(resolve => setTimeout(resolve, 100));
}
return !!this.connectionRegistry.getConnectionByAuth(this.currentAuthIndex);
}
_isConnectionResetError(error) {
if (!error) return false;
// Check for QueueClosedError type
if (error instanceof QueueClosedError) return true;
// Check for error code
if (error.code === "QUEUE_CLOSED") return true;
// Fallback to message check for backward compatibility
if (error.message) {
return (
error.message.includes("Queue closed") ||
error.message.includes("Queue is closed") ||
error.message.includes("Connection lost")
);
}
return false;
}
_logGeminiNativeChunkDebug(googleChunk, mode = "stream") {
this.logger.debug(`[Proxy] Debug: Received Google chunk for Gemini native ${mode}: ${googleChunk}`);
}
_logGeminiNativeResponseDebug(googleResponse, mode = "non-stream") {
try {
this.logger.debug(
`[Proxy] Debug: Received Google response for Gemini native ${mode}: ${JSON.stringify(googleResponse)}`
);
} catch (e) {
this.logger.debug(
`[Proxy] Debug: Received Google response for Gemini native ${mode} (non-serializable): ${String(
googleResponse
)}`
);
}
}
/**
* Handle queue closed error in real streaming mode with proper SSE error response
* @param {Error} error - The error object (QueueClosedError)
* @param {Object} res - Express response object
* @param {string} format - Response format ('openai', 'response_api', 'claude', or 'gemini')
* @returns {boolean} true if error was handled, false otherwise
*/
_handleRealStreamQueueClosedError(error, res, format) {
const isClientDisconnect = error.reason === "client_disconnect" || !this._isResponseWritable(res);
if (isClientDisconnect) {
// Client disconnected or queue closed due to client disconnect - no error needed
this._markTrackedClientAbort(res, error.message || "Client disconnected");
this.logger.debug(
`[Request] ${format} stream interrupted by client disconnect (reason: ${error.reason || "connection_lost"})`
);
return true;
}
// Queue was closed for other reasons (account switch, page_closed, etc.)
// but client is still connected - send proper error SSE
this.logger.warn(
`[Request] ${format} stream interrupted: Queue closed (reason: ${error.reason || "unknown"}), sending error SSE`
);
if (!this._isResponseWritable(res)) {
return true;
}
try {
const errorMessage = `Stream interrupted: ${error.reason === "page_closed" ? "Account context closed" : error.reason || "Connection lost"}`;
this._markTrackedResponseError(res, errorMessage, 503);
if (format === "claude") {
// Claude format: event: error\ndata: {...}
res.write(
`event: error\ndata: ${JSON.stringify({
error: {
message: errorMessage,
type: "api_error",
},
type: "error",
})}\n\n`
);
} else if (format === "openai") {
// OpenAI format: data: {"error": {...}}
res.write(
`data: ${JSON.stringify({
error: {
code: 503,
message: errorMessage,
type: "api_error",
},
})}\n\n`
);
} else if (format === "response_api") {
// OpenAI Response API format: event: error\ndata: {...}
if (res.__responseApiSeq == null) res.__responseApiSeq = 0;
res.__responseApiSeq += 1;
res.write(
`event: error\ndata: ${JSON.stringify({
code: "service_unavailable",
message: `Service unavailable: ${errorMessage}`,
param: null,
sequence_number: res.__responseApiSeq,
type: "error",
})}\n\n`
);
} else if (format === "gemini") {
// Gemini format: data: {"error": {...}}
res.write(
`data: ${JSON.stringify({
error: {
code: 503,
message: errorMessage,
status: "UNAVAILABLE",
},
})}\n\n`
);
}
} catch (writeError) {
this.logger.debug(`[Request] Failed to write error to ${format} stream: ${writeError.message}`);
}
return true;
}
/**
* Classify and handle fake stream errors
* @param {Error} error - The error object
* @param {Object} res - Express response object
* @param {string} format - Response format ('openai', 'response_api', 'claude', or 'gemini')
* @throws {Error} Rethrows unexpected errors for outer handler
*/
_handleFakeStreamError(error, res, format) {
if (!this._isResponseWritable(res)) {
return; // Client disconnected, no need to send error
}
try {
let errorPayload;
let trackingStatus = 500;
let trackingMessage = String(error?.message ?? error);
if (error.code === "QUEUE_TIMEOUT" || error instanceof QueueTimeoutError) {
// True timeout error - 504
trackingStatus = 504;
trackingMessage = `Stream timeout: ${trackingMessage}`;
if (format === "openai") {
errorPayload = {
error: {
code: 504,
message: `Stream timeout: ${error.message}`,
type: "timeout_error",
},
};
if (this._isResponseWritable(res)) {
res.write(`data: ${JSON.stringify(errorPayload)}\n\n`);
}
} else if (format === "claude") {
errorPayload = {
error: {
message: `Stream timeout: ${error.message}`,
type: "timeout_error",
},
type: "error",
};
if (this._isResponseWritable(res)) {
res.write(`event: error\ndata: ${JSON.stringify(errorPayload)}\n\n`);
}
} else if (format === "response_api") {
// OpenAI Response API format
errorPayload = {
code: "timeout_error",
message: `Stream timeout: ${error.message}`,
param: null,
sequence_number: 0,
type: "error",
};
if (res.__responseApiSeq == null) res.__responseApiSeq = 0;
res.__responseApiSeq += 1;
errorPayload.sequence_number = res.__responseApiSeq;
if (this._isResponseWritable(res)) {
res.write(`event: error\ndata: ${JSON.stringify(errorPayload)}\n\n`);
}
} else {
// gemini
errorPayload = {
error: {
code: 504,
message: `Stream timeout: ${error.message}`,
status: "DEADLINE_EXCEEDED",
},
};
if (this._isResponseWritable(res)) {
res.write(`data: ${JSON.stringify(errorPayload)}\n\n`);
}
}
} else if (error.code === "QUEUE_CLOSED" || error instanceof QueueClosedError) {
// Queue closed (account switch, system reset, etc.) - 503
trackingStatus = 503;
trackingMessage = `Service unavailable: ${trackingMessage}`;
if (format === "openai") {
errorPayload = {
error: {
code: 503,
message: `Service unavailable: ${error.message}`,
type: "service_unavailable",
},
};
if (this._isResponseWritable(res)) {
res.write(`data: ${JSON.stringify(errorPayload)}\n\n`);
}
} else if (format === "claude") {
errorPayload = {
error: {
message: `Service unavailable: ${error.message}`,
type: "overloaded_error",
},
type: "error",
};
if (this._isResponseWritable(res)) {
res.write(`event: error\ndata: ${JSON.stringify(errorPayload)}\n\n`);
}
} else if (format === "response_api") {
// OpenAI Response API format
errorPayload = {
code: "service_unavailable",
message: `Service unavailable: ${error.message}`,
param: null,
sequence_number: 0,
type: "error",
};
if (res.__responseApiSeq == null) res.__responseApiSeq = 0;
res.__responseApiSeq += 1;
errorPayload.sequence_number = res.__responseApiSeq;
if (this._isResponseWritable(res)) {
res.write(`event: error\ndata: ${JSON.stringify(errorPayload)}\n\n`);
}
} else {
// gemini
errorPayload = {
error: {
code: 503,
message: `Service unavailable: ${error.message}`,
status: "UNAVAILABLE",
},
};
if (this._isResponseWritable(res)) {
res.write(`data: ${JSON.stringify(errorPayload)}\n\n`);
}
}
} else {
// Other unexpected errors - rethrow to outer handler
throw error;
}
this._markTrackedResponseError(res, trackingMessage, trackingStatus);
} catch (writeError) {
this.logger.debug(`[Request] Failed to write fake stream error to client: ${writeError.message}`);
// If write failed or unexpected error, rethrow original error
throw error;
}
}
/**
* Wait for WebSocket connection to be established for current account
* @param {number} timeoutMs - Maximum time to wait in milliseconds
* @returns {Promise<boolean>} true if connection established, false if timeout
*/
async _waitForConnection(timeoutMs = 10000) {
const startTime = Date.now();
const checkInterval = 200; // Check every 200ms
while (Date.now() - startTime < timeoutMs) {
const connection = this.connectionRegistry.getConnectionByAuth(this.currentAuthIndex);
// Check both existence and readyState (1 = OPEN)
if (connection && connection.readyState === 1) {
return true;
}
await new Promise(resolve => setTimeout(resolve, checkInterval));
}
this.logger.warn(
`[Request] Timeout waiting for WebSocket connection for account #${this.currentAuthIndex}. Closing unresponsive context...`
);
// Proactively close the unresponsive context so subsequent attempts re-initialize it
if (this.browserManager) {
try {
await this.browserManager.closeContext(this.currentAuthIndex);
} catch (e) {
this.logger.warn(
`[System] Failed to close unresponsive context for account #${this.currentAuthIndex}: ${e.message}`
);
}
}
return false;
}
/**
* Wait for system to become ready (not busy with switching/recovery)
* @param {number} timeoutMs - Maximum time to wait in milliseconds (default 120s, same as browser launch timeout)
* @returns {Promise<boolean>} true if system becomes ready, false if timeout
*/
async _waitForSystemReady(timeoutMs = 120000) {
if (!this.authSwitcher.isSystemBusy) {
return true;
}
this.logger.info(`[System] System is busy (switching/recovering), waiting up to ${timeoutMs / 1000}s...`);
const startTime = Date.now();
const checkInterval = 200; // Check every 200ms
while (Date.now() - startTime < timeoutMs) {
if (!this.authSwitcher.isSystemBusy) {
this.logger.info(`[System] System ready after ${Date.now() - startTime}ms.`);
return true;
}
await new Promise(resolve => setTimeout(resolve, checkInterval));
}
this.logger.warn(`[System] Timeout waiting for system after ${timeoutMs}ms.`);
return false;
}
async _waitForSystemAndConnectionIfBusy(res = null, options = {}) {
if (!this.authSwitcher.isSystemBusy) {
return true;
}
const {
busyMessage = "Server undergoing internal maintenance (account switching/recovery), please try again later.",
connectionMessage = "Service temporarily unavailable: Connection not established after switching.",
connectionTimeoutMs = 10000,
onConnectionTimeout,
sendError = res ? (status, message) => this._sendErrorResponse(res, status, message) : () => {},
} = options;
const ready = await this._waitForSystemReady();
if (!ready) {
sendError(503, busyMessage);
return false;
}
if (!this.connectionRegistry.getConnectionByAuth(this.currentAuthIndex)) {
const connectionReady = await this._waitForConnection(connectionTimeoutMs);
if (!connectionReady) {
if (typeof onConnectionTimeout === "function") {
try {
onConnectionTimeout();
} catch (e) {
this.logger.debug(`[System] onConnectionTimeout handler failed: ${e.message}`);
}
}
sendError(503, connectionMessage);
return false;
}
}
return true;
}
_createImmediateSwitchTracker() {
const attemptedAuthIndices = new Set();
if (Number.isInteger(this.currentAuthIndex) && this.currentAuthIndex >= 0) {
attemptedAuthIndices.add(this.currentAuthIndex);
}
return { attemptedAuthIndices };
}
async _performImmediateSwitchRetry(errorDetails, requestId, tracker) {
await this.authSwitcher.handleRequestFailureAndSwitch(
{ message: errorDetails.message, status: Number(errorDetails.status) },
null
);
const ready = await this._waitForSystemAndConnectionIfBusy(null, {
sendError: () => {},
});
if (!ready) {
throw new Error("System not ready after immediate-switch retry.");
}
const newAuthIndex = this.currentAuthIndex;
if (!Number.isInteger(newAuthIndex) || newAuthIndex < 0) {
this.logger.warn(
`[Request] Immediate switch for request #${requestId} did not produce a valid target account.`
);
return false;
}
if (tracker.attemptedAuthIndices.has(newAuthIndex)) {
this.logger.warn(
`[Request] Immediate switch for request #${requestId} returned to already-attempted account #${newAuthIndex}, stopping account-switch retries.`
);
return false;
}
tracker.attemptedAuthIndices.add(newAuthIndex);
return true;
}
_logFinalRequestFailure(errorDetails, contextLabel = "Request") {
this.logger.error(
`[Request] ${contextLabel} failed after retries. Status code: ${errorDetails?.status || 500}, message: ${errorDetails?.message || "Unknown error"}`
);
}
/**
* Handle browser recovery when connection is lost
*
* Important: isSystemBusy flag management strategy:
* - Direct recovery (recoveryAuthIndex >= 0): We manually set and reset isSystemBusy
* - Switch to next account (recoveryAuthIndex = -1): Let switchToNextAuth() manage isSystemBusy internally
* - This prevents the bug where isSystemBusy is set here, then switchToNextAuth() checks it and returns "already in progress"
*
* @returns {boolean} true if recovery successful, false otherwise
*/
async _handleBrowserRecovery(res) {
// If within grace period or lightweight reconnect is running, wait up to 60s for WebSocket reconnection
if (this.connectionRegistry.isInGracePeriod() || this.connectionRegistry.isReconnectingInProgress()) {
this.logger.info(
"[System] Waiting up to 60s for WebSocket reconnection (grace/reconnect in progress) before full recovery..."
);
const reconnected = await this._waitForGraceReconnect(60000);
if (reconnected) {
this.logger.info("[System] Connection restored, skipping recovery.");
return true;
}
this.logger.warn("[System] Reconnection wait expired, proceeding to recovery workflow.");
}
// Wait for system to become ready if it's busy (someone else is starting/switching browser)
if (this.authSwitcher.isSystemBusy) {
return await this._waitForSystemAndConnectionIfBusy(res, {
connectionMessage: "Service temporarily unavailable: Browser failed to start. Please try again.",
onConnectionTimeout: () => {
this.logger.error(
`[System] WebSocket connection not established for account #${this.currentAuthIndex} after system ready, browser startup may have failed.`
);
},
});
}
// Determine if this is first-time startup or actual crash recovery
const recoveryAuthIndex = this.currentAuthIndex;
const isFirstTimeStartup = recoveryAuthIndex < 0 && !this.browserManager.browser;
if (isFirstTimeStartup) {
this.logger.info(
"🚀 [System] Browser not yet started. Initializing browser with first available account..."
);
} else {
this.logger.error(
"❌ [System] Browser WebSocket connection disconnected! Possible process crash. Attempting recovery..."
);
}
let wasDirectRecovery = false;
let recoverySuccess = false;
try {
if (recoveryAuthIndex >= 0) {
// Direct recovery: we manage isSystemBusy ourselves
wasDirectRecovery = true;
this.authSwitcher.isSystemBusy = true;
this.logger.info(`[System] Set isSystemBusy=true for direct recovery to account #${recoveryAuthIndex}`);
await this.browserManager.launchOrSwitchContext(recoveryAuthIndex);
this.logger.info(`✅ [System] Browser successfully recovered to account #${recoveryAuthIndex}!`);
// Wait for WebSocket connection to be established
this.logger.info("[System] Waiting for WebSocket connection to be ready...");
const connectionReady = await this._waitForConnection(10000); // 10 seconds timeout
if (!connectionReady) {
throw new Error("WebSocket connection not established within timeout period");
}
this.logger.info("✅ [System] WebSocket connection is ready!");
recoverySuccess = true;
} else if (this.authSource.getRotationIndices().length > 0) {
// Don't set isSystemBusy here - let switchToNextAuth manage it
const result = await this.authSwitcher.switchToNextAuth();
if (!result.success) {
this.logger.error(`❌ [System] Failed to switch to available account: ${result.reason}`);
await this._sendErrorResponse(res, 503, `Service temporarily unavailable: ${result.reason}`);
recoverySuccess = false;
} else {
this.logger.info(`✅ [System] Successfully recovered to account #${result.newIndex}!`);
// Wait for WebSocket connection to be established
this.logger.info("[System] Waiting for WebSocket connection to be ready...");
const connectionReady = await this._waitForConnection(10000); // 10 seconds timeout
if (!connectionReady) {
throw new Error("WebSocket connection not established within timeout period");
}
this.logger.info("✅ [System] WebSocket connection is ready!");
recoverySuccess = true;
}
} else {
this.logger.error("❌ [System] No available accounts for recovery.");
await this._sendErrorResponse(res, 503, "Service temporarily unavailable: No available accounts.");
recoverySuccess = false;
}
} catch (error) {
this.logger.error(`❌ [System] Recovery failed: ${error.message}`);
if (wasDirectRecovery && this.authSource.getRotationIndices().length > 1) {
this.logger.warn("⚠️ [System] Attempting to switch to alternative account...");
// Reset isSystemBusy before calling switchToNextAuth to avoid "already in progress" rejection
this.authSwitcher.isSystemBusy = false;
wasDirectRecovery = false; // Prevent finally block from resetting again
try {
const result = await this.authSwitcher.switchToNextAuth();
if (!result.success) {
this.logger.error(`❌ [System] Failed to switch to alternative account: ${result.reason}`);
await this._sendErrorResponse(res, 503, `Service temporarily unavailable: ${result.reason}`);
recoverySuccess = false;
} else {
this.logger.info(
`✅ [System] Successfully switched to alternative account #${result.newIndex}!`
);
// Wait for WebSocket connection to be established
this.logger.info("[System] Waiting for WebSocket connection to be ready...");
const connectionReady = await this._waitForConnection(10000);
if (!connectionReady) {
throw new Error("WebSocket connection not established within timeout period");
}
this.logger.info("✅ [System] WebSocket connection is ready!");
recoverySuccess = true;
}
} catch (switchError) {
this.logger.error(`❌ [System] All accounts failed: ${switchError.message}`);
await this._sendErrorResponse(res, 503, "Service temporarily unavailable: All accounts failed.");
recoverySuccess = false;
}
} else {
await this._sendErrorResponse(
res,
503,
"Service temporarily unavailable: Browser crashed and cannot auto-recover."
);
recoverySuccess = false;
}
} finally {
// Only reset if we set it (for direct recovery attempt)
if (wasDirectRecovery) {
this.logger.info("[System] Resetting isSystemBusy=false in recovery finally block");
this.authSwitcher.isSystemBusy = false;
}
}
return recoverySuccess;
}
// Process standard Google API requests
async processRequest(req, res) {
const requestId = this._generateRequestId();
this._startTrackedRequest(requestId, req, {
apiFormat: "gemini",
requestCategory: this._categorizeRequest(req.path, "request"),
});
res.__proxyResponseStreamMode = null;
try {
// Check current account's browser connection
if (!this.connectionRegistry.getConnectionByAuth(this.currentAuthIndex)) {
this.logger.warn(`[Request] No WebSocket connection for current account #${this.currentAuthIndex}`);
const recovered = await this._handleBrowserRecovery(res);
if (!recovered) return;
}
// Wait for system to become ready if it's busy
{
const ready = await this._waitForSystemAndConnectionIfBusy(res);
if (!ready) return;
}
if (this.browserManager) {
this.browserManager.notifyUserActivity();
}
// Handle usage-based account switching
const isGenerativeRequest =
req.method === "POST" &&
(req.path.includes("generateContent") || req.path.includes("streamGenerateContent"));
if (isGenerativeRequest) {
const usageCount = this.authSwitcher.incrementUsageCount();
if (usageCount > 0) {
const rotationCountText =
this.config.switchOnUses > 0 ? `${usageCount}/${this.config.switchOnUses}` : `${usageCount}`;
this.logger.info(
`[Request] Generation request - account rotation count: ${rotationCountText} (Current account: ${this.currentAuthIndex})`
);
if (this.authSwitcher.shouldSwitchByUsage()) {
this.needsSwitchingAfterRequest = true;
}
}
}
const proxyRequest = this._buildProxyRequest(req, requestId);
proxyRequest.is_generative = isGenerativeRequest;
this._initializeProxyRequestAttempt(proxyRequest);
const wantsStream = req.path.includes(":streamGenerateContent");
res.__proxyResponseStreamMode = wantsStream ? proxyRequest.streaming_mode : null;
this._updateTrackedRequest(requestId, {
isStreaming: wantsStream,
model: this._extractModelFromPath(proxyRequest.path),
path: proxyRequest.path,
requestCategory: this._categorizeRequest(
proxyRequest.path,
isGenerativeRequest ? "generation" : "request"
),
streamMode: wantsStream ? proxyRequest.streaming_mode : null,
});
try {
// Create message queue inside try-catch to handle invalid authIndex
const messageQueue = this.connectionRegistry.createMessageQueue(
requestId,
this.currentAuthIndex,
proxyRequest.request_attempt_id
);
this._setupClientDisconnectHandler(res, requestId);
if (wantsStream) {
this.logger.info(
`[Request] Client enabled streaming (${proxyRequest.streaming_mode}), entering streaming processing mode...`
);
if (proxyRequest.streaming_mode === "fake") {
await this._handlePseudoStreamResponse(proxyRequest, messageQueue, req, res);
} else {
await this._handleRealStreamResponse(proxyRequest, messageQueue, req, res);
}
} else {
proxyRequest.streaming_mode = "fake";
await this._handleNonStreamResponse(proxyRequest, messageQueue, req, res);
}
} catch (error) {
// Handle queue timeout by notifying browser
this._handleQueueTimeout(error, requestId);
this._handleRequestError(error, res, "gemini");
} finally {
this.connectionRegistry.removeMessageQueue(requestId, "request_complete");
if (this.needsSwitchingAfterRequest) {
this.logger.info(
`[Auth] Rotation count reached switching threshold (${this.authSwitcher.usageCount}/${this.config.switchOnUses}), will automatically switch account in background...`
);
this.authSwitcher.switchToNextAuth().catch(err => {
this.logger.error(`[Auth] Background account switching task failed: ${err.message}`);
});
this.needsSwitchingAfterRequest = false;
}
if (!res.writableEnded) res.end();
}
} finally {
this._finalizeTrackedRequest(requestId, res);
}
}
// Process File Upload requests
async processUploadRequest(req, res) {
const requestId = this._generateRequestId();
this.logger.info(`[Upload] Processing upload request ${req.method} ${req.path} (ID: ${requestId})`);
this._startTrackedRequest(requestId, req, {
apiFormat: "upload",
isStreaming: false,
requestCategory: "upload",
streamMode: null,
});
try {
// Check current account's browser connection
if (!this.connectionRegistry.getConnectionByAuth(this.currentAuthIndex)) {
this.logger.warn(`[Upload] No WebSocket connection for current account #${this.currentAuthIndex}`);
const recovered = await this._handleBrowserRecovery(res);
if (!recovered) return;
}
// Wait for system to become ready if it's busy
{
const ready = await this._waitForSystemAndConnectionIfBusy(res);
if (!ready) return;
}
if (this.browserManager) {
this.browserManager.notifyUserActivity();
}
const proxyRequest = {
body_b64: req.rawBody ? req.rawBody.toString("base64") : undefined,
headers: req.headers,
is_generative: false, // Uploads are never generative
method: req.method,
path: req.path.replace(/^\/proxy/, ""),
query_params: req.query || {},
request_id: requestId,
streaming_mode: "fake", // Uploads always return a single JSON response
};
this._initializeProxyRequestAttempt(proxyRequest);
this._updateTrackedRequest(requestId, {
path: proxyRequest.path,
});
try {
// Create message queue inside try-catch to handle invalid authIndex
const messageQueue = this.connectionRegistry.createMessageQueue(
requestId,
this.currentAuthIndex,
proxyRequest.request_attempt_id
);
this._setupClientDisconnectHandler(res, requestId);
await this._handleNonStreamResponse(proxyRequest, messageQueue, req, res);
} catch (error) {
this._handleRequestError(error, res);
} finally {
this.connectionRegistry.removeMessageQueue(requestId, "request_complete");
if (!res.writableEnded) res.end();
}
} finally {
this._finalizeTrackedRequest(requestId, res);
}
}
// Process OpenAI format requests
async processOpenAIRequest(req, res) {
const requestId = this._generateRequestId();
this._startTrackedRequest(requestId, req, {
apiFormat: "openai",
isStreaming: req.body.stream === true,
requestCategory: "generation",
streamMode: req.body.stream === true ? this.serverSystem.streamingMode : null,
});
res.__proxyResponseStreamMode = null;
try {
// Check current account's browser connection
if (!this.connectionRegistry.getConnectionByAuth(this.currentAuthIndex)) {
this.logger.warn(`[Request] No WebSocket connection for current account #${this.currentAuthIndex}`);
const recovered = await this._handleBrowserRecovery(res);
if (!recovered) return;
}
// Wait for system to become ready if it's busy
{
const ready = await this._waitForSystemAndConnectionIfBusy(res);
if (!ready) return;
}
if (this.browserManager) {
this.browserManager.notifyUserActivity();
}
const isOpenAIStream = req.body.stream === true;
const systemStreamMode = this.serverSystem.streamingMode;
// Handle usage counting
const usageCount = this.authSwitcher.incrementUsageCount();
if (usageCount > 0) {
const rotationCountText =
this.config.switchOnUses > 0 ? `${usageCount}/${this.config.switchOnUses}` : `${usageCount}`;
this.logger.info(
`[Request] OpenAI generation request - account rotation count: ${rotationCountText} (Current account: ${this.currentAuthIndex})`
);
if (this.authSwitcher.shouldSwitchByUsage()) {
this.needsSwitchingAfterRequest = true;
}
}
// Translate OpenAI format to Google format (also handles model name suffix parsing)
let googleBody, model, modelStreamingMode;
try {
const result = await this.formatConverter.translateOpenAIToGoogle(req.body);
googleBody = result.googleRequest;
model = result.cleanModelName;
modelStreamingMode = result.modelStreamingMode || null;
} catch (error) {
this.logger.error(`[Adapter] OpenAI request translation failed: ${error.message}`);
return this._sendErrorResponse(res, 400, "Invalid OpenAI request format.");
}
const effectiveStreamMode = modelStreamingMode || systemStreamMode;
const useRealStream = isOpenAIStream && effectiveStreamMode === "real";
const googleEndpoint = useRealStream ? "streamGenerateContent" : "generateContent";
const proxyRequest = {
body: JSON.stringify(googleBody),
headers: { "Content-Type": "application/json" },
is_generative: true,
method: "POST",
path: `/v1beta/models/${model}:${googleEndpoint}`,
query_params: useRealStream ? { alt: "sse" } : {},
request_id: requestId,
streaming_mode: useRealStream ? "real" : "fake",
};
this._initializeProxyRequestAttempt(proxyRequest);
res.__proxyResponseStreamMode = isOpenAIStream ? (useRealStream ? "real" : "fake") : null;
this._updateTrackedRequest(requestId, {
isStreaming: isOpenAIStream,
model,
path: proxyRequest.path,
requestCategory: "generation",
...(isOpenAIStream ? { streamMode: useRealStream ? "real" : "fake" } : {}),
});
try {
// Create message queue inside try-catch to handle invalid authIndex
const messageQueue = this.connectionRegistry.createMessageQueue(
requestId,
this.currentAuthIndex,
proxyRequest.request_attempt_id
);
this._setupClientDisconnectHandler(res, requestId);
if (useRealStream) {
let currentQueue = messageQueue;
let initialMessage;
let skipFinalFailureSwitch = false;
const immediateSwitchTracker = this._createImmediateSwitchTracker();