tuxevil-rotator 3.2.2 → 3.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -0
- package/README.md +1 -1
- package/package.json +1 -1
- package/src/compat.ts +12 -0
- package/src/config-defaults.ts +4 -4
- package/src/providers/credential-helpers.ts +12 -0
- package/src/providers/google-antigravity/code-assist.ts +3 -1
- package/src/providers/google-antigravity/forward.ts +4 -2
- package/src/providers/google-antigravity/index.ts +5 -0
- package/src/providers/google-antigravity/quota.ts +4 -1
- package/src/providers/registry.ts +1 -0
- package/src/proxy.ts +105 -45
- package/src/rotator.ts +718 -100
- package/src/static/dashboard.js +8 -3
- package/src/types.ts +3 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,28 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [3.3.0] - 2026-08-24
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
- **Queued multi-request Antigravity pooling (5×5 concurrent streams)**: Up to 5 concurrent Antigravity streams per account across model pools, with a 25-stream total across 5 accounts. Requests are distributed breadth-first by total account load across mixed Gemini and Claude traffic ([#24](https://github.com/tuxevil/tuxevil-rotator/pull/24) by [@javargasm](https://github.com/javargasm)).
|
|
7
|
+
- **Process-local strict FIFO request queue**: Requests exceeding total pool capacity wait in a strict FIFO queue with automatic 300-second expiration, early client disconnect cancellation (`AbortSignal`), and immediate wakeup on lease release, cooldown expiry, circuit-breaker reset, catalog discovery, or config reload ([#24](https://github.com/tuxevil/tuxevil-rotator/pull/24) by [@javargasm](https://github.com/javargasm)).
|
|
8
|
+
- **Dashboard concurrency metrics**: Account cards on the web dashboard display active vs. max concurrency (e.g. `Concurrency: 3/5`) for Google Antigravity accounts ([#24](https://github.com/tuxevil/tuxevil-rotator/pull/24) by [@javargasm](https://github.com/javargasm)).
|
|
9
|
+
|
|
10
|
+
### Changed
|
|
11
|
+
- **Config defaults**: `maxConcurrentRequestsPerAccount` and `maxConcurrentRequestsPerProjectModel` default values raised from `1` to `5` ([#24](https://github.com/tuxevil/tuxevil-rotator/pull/24) by [@javargasm](https://github.com/javargasm)).
|
|
12
|
+
|
|
13
|
+
### Fixed
|
|
14
|
+
- **Canonical project ID resolution**: Forwarding, quota polling, Code Assist passthrough, and admission gating consistently resolve trimmed nested `google-antigravity` credentials before legacy flat `projectId` fields, preventing unkeyed empty project ID collision across unrelated accounts ([#24](https://github.com/tuxevil/tuxevil-rotator/pull/24) by [@javargasm](https://github.com/javargasm)).
|
|
15
|
+
|
|
16
|
+
## [3.2.3] - 2026-08-21
|
|
17
|
+
|
|
18
|
+
### Fixed
|
|
19
|
+
- **Account-scoped 429 `RESOURCE_EXHAUSTED` resilience & account lifecycle**: When an individual account exhausts its quota (returning 429 `RESOURCE_EXHAUSTED` on Claude or Gemini), the proxy now safely releases the failed account before rotating, allowing immediate retry with the next eligible account in the pool instead of failing prematurely ([#23](https://github.com/tuxevil/tuxevil-rotator/pull/23) by [@javargasm](https://github.com/javargasm)).
|
|
20
|
+
- **Synchronous account leasing & atomic concurrency accounting**: `inFlightRequests` reservation and model assignment tracking now occur synchronously and indivisibly at lease time before asynchronous save or refresh operations. If activation fails, in-flight counters are rolled back and token buckets are refunded immediately ([#23](https://github.com/tuxevil/tuxevil-rotator/pull/23) by [@javargasm](https://github.com/javargasm)).
|
|
21
|
+
- **Snapshot-based token refresh & generation tracking**: Provider token refreshes execute against isolated account snapshot clones. Refreshed tokens are published only if the credential generation has not changed during flight, cleanly discarding stale tokens if credentials were reconfigured ([#23](https://github.com/tuxevil/tuxevil-rotator/pull/23) by [@javargasm](https://github.com/javargasm)).
|
|
22
|
+
- **Provider-scoped token publication**: Token refreshes for multi-provider accounts (e.g. Google Antigravity + OpenAI Codex) now update strictly provider-owned fields, preventing cross-provider token and credential overwrites ([#23](https://github.com/tuxevil/tuxevil-rotator/pull/23) by [@javargasm](https://github.com/javargasm)).
|
|
23
|
+
- **Identity resolution with non-secret credential fingerprinting**: Duplicate-email accounts without stable provider IDs are resolved using a 12-character SHA-256 non-secret credential fingerprint, isolating runtime state during `replaceConfig` ([#23](https://github.com/tuxevil/tuxevil-rotator/pull/23) by [@javargasm](https://github.com/javargasm)).
|
|
24
|
+
- **Exact incarnation exclusion on retry**: `rotateToNext(model, failedAccount)` binds exclusion strictly to the exact runtime object instance, preventing false 503 errors when an account is replaced by a healthy incarnation ([#23](https://github.com/tuxevil/tuxevil-rotator/pull/23) by [@javargasm](https://github.com/javargasm)).
|
|
25
|
+
|
|
3
26
|
## [3.2.2] - 2026-08-21
|
|
4
27
|
|
|
5
28
|
### Fixed
|
package/README.md
CHANGED
|
@@ -343,7 +343,7 @@ Thanks to these amazing people who have contributed to the project:
|
|
|
343
343
|
- **[@CyR1en](https://github.com/CyR1en)** (Ethan Bacurio) — Added Gemini 3.6 Flash and Gemini 3.7 Flash model families, shared quota-pool routing, pricing, dashboard support, and regression coverage. ([PR #18](https://github.com/tuxevil/tuxevil-rotator/pull/18), [PR #21](https://github.com/tuxevil/tuxevil-rotator/pull/21))
|
|
344
344
|
- **[@josenicomaia](https://github.com/josenicomaia)** (José Nicodemos Maia Neto) — Modularized the compatibility layer architecture, added multimodal tool response support, fixed streaming pass-through for tool executions, and added PostgreSQL storage and weighted pool quota forecasting. ([PR #8](https://github.com/tuxevil/tuxevil-rotator/pull/8), [PR #9](https://github.com/tuxevil/tuxevil-rotator/pull/9), [PR #11](https://github.com/tuxevil/tuxevil-rotator/pull/11), [PR #13](https://github.com/tuxevil/tuxevil-rotator/pull/13), [PR #14](https://github.com/tuxevil/tuxevil-rotator/pull/14))
|
|
345
345
|
- **[@yashyadav711](https://github.com/yashyadav711)** (Yash) — Fixed Draft-2020-12 inline JSON-Schema union type mapping for Gemini tools support. ([PR #10](https://github.com/tuxevil/tuxevil-rotator/pull/10))
|
|
346
|
-
- **[@javargasm](https://github.com/javargasm)** (Jeisson Alexander Vargas Marroquin) —
|
|
346
|
+
- **[@javargasm](https://github.com/javargasm)** (Jeisson Alexander Vargas Marroquin) — Queued multi-request Antigravity account pooling (5×5 concurrent streams), strict FIFO overflow queue, dashboard concurrency metrics, canonical project ID resolution, 429 quota resilience with account-scoped retry, synchronous leasing, snapshot-based token refresh with generation validation, provider-scoped token publication, spend-logger memory leak fix, atomic PostgreSQL CTE daily spend aggregation with idempotent retries, virtual-key cache bounding, Anthropic tool-use compatibility layer (`tool_use`/`tool_result` content block conversion), JSON schema round-trip fixes, and compat test suite expansion. ([PR #3](https://github.com/tuxevil/tuxevil-rotator/pull/3), [PR #7](https://github.com/tuxevil/tuxevil-rotator/pull/7), [PR #22](https://github.com/tuxevil/tuxevil-rotator/pull/22), [PR #23](https://github.com/tuxevil/tuxevil-rotator/pull/23), [PR #24](https://github.com/tuxevil/tuxevil-rotator/pull/24))
|
|
347
347
|
|
|
348
348
|
## Development
|
|
349
349
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tuxevil-rotator",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.3.0",
|
|
4
4
|
"description": "Multi-provider, multi-account AI proxy rotator with per-model routing, real-time quota tracking, and infringement detection (Google Antigravity, Ollama Cloud)",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
package/src/compat.ts
CHANGED
|
@@ -452,6 +452,7 @@ function writeJson(
|
|
|
452
452
|
payload: unknown,
|
|
453
453
|
headers: Record<string, string> = {},
|
|
454
454
|
): void {
|
|
455
|
+
if (res.destroyed || res.writableEnded) return;
|
|
455
456
|
res.writeHead(status, { "Content-Type": "application/json", ...headers });
|
|
456
457
|
res.end(JSON.stringify(payload));
|
|
457
458
|
}
|
|
@@ -1728,6 +1729,10 @@ async function completeResponsesViaRotator(
|
|
|
1728
1729
|
compressionStats?: CompressionStats | null;
|
|
1729
1730
|
}> {
|
|
1730
1731
|
const createdAt = Math.floor(Date.now() / 1000);
|
|
1732
|
+
const controller = new AbortController();
|
|
1733
|
+
const abort = (): void => controller.abort();
|
|
1734
|
+
req.once("aborted", abort);
|
|
1735
|
+
if (typeof res.once === "function") res.once("close", abort);
|
|
1731
1736
|
const outcome = await withRotation(
|
|
1732
1737
|
rotator,
|
|
1733
1738
|
body.model,
|
|
@@ -1767,6 +1772,7 @@ async function completeResponsesViaRotator(
|
|
|
1767
1772
|
);
|
|
1768
1773
|
return completion;
|
|
1769
1774
|
},
|
|
1775
|
+
controller.signal,
|
|
1770
1776
|
);
|
|
1771
1777
|
if (!outcome.ok) {
|
|
1772
1778
|
recordCompatFailure(rotator, body, outcome, options);
|
|
@@ -1824,6 +1830,11 @@ async function completeViaRotator(
|
|
|
1824
1830
|
const enabled = cfg?.idempotencyEnabled === true;
|
|
1825
1831
|
const windowMs = cfg?.idempotencyWindowMs ?? 2000;
|
|
1826
1832
|
const shouldDedup = enabled && streamMode === "none" && !idempotencyManager.isOptedOut(req);
|
|
1833
|
+
const controller = new AbortController();
|
|
1834
|
+
const abort = (): void => controller.abort();
|
|
1835
|
+
req.once("aborted", abort);
|
|
1836
|
+
if (typeof res.once === "function") res.once("close", abort);
|
|
1837
|
+
if (req.aborted || res.destroyed) abort();
|
|
1827
1838
|
|
|
1828
1839
|
const runWithRotation = () =>
|
|
1829
1840
|
withRotation(
|
|
@@ -1891,6 +1902,7 @@ async function completeViaRotator(
|
|
|
1891
1902
|
return completion;
|
|
1892
1903
|
}
|
|
1893
1904
|
},
|
|
1905
|
+
controller.signal,
|
|
1894
1906
|
);
|
|
1895
1907
|
|
|
1896
1908
|
let outcome: RotationOutcome<CompatCompletion>;
|
package/src/config-defaults.ts
CHANGED
|
@@ -32,8 +32,8 @@ export function applyConfigDefaults(config: Config): Config {
|
|
|
32
32
|
requestsPerRotation: config.requestsPerRotation || 5,
|
|
33
33
|
rotateOnQuotaDrop: config.rotateOnQuotaDrop ?? 20,
|
|
34
34
|
quotaPollIntervalMs: safeQuotaPollIntervalMs(config.quotaPollIntervalMs),
|
|
35
|
-
maxConcurrentRequestsPerAccount: config.maxConcurrentRequestsPerAccount ??
|
|
36
|
-
maxConcurrentRequestsPerProjectModel: config.maxConcurrentRequestsPerProjectModel ??
|
|
35
|
+
maxConcurrentRequestsPerAccount: config.maxConcurrentRequestsPerAccount ?? 5,
|
|
36
|
+
maxConcurrentRequestsPerProjectModel: config.maxConcurrentRequestsPerProjectModel ?? 5,
|
|
37
37
|
projectCircuitBreaker429Threshold: config.projectCircuitBreaker429Threshold ?? 3,
|
|
38
38
|
projectCircuitBreakerWindowMs: config.projectCircuitBreakerWindowMs ?? 10 * 60 * 1000,
|
|
39
39
|
projectCircuitBreakerCooldownMs: config.projectCircuitBreakerCooldownMs ?? 60 * 60 * 1000,
|
|
@@ -69,8 +69,8 @@ export function getDefaultConfig(): Config {
|
|
|
69
69
|
requestsPerRotation: 5,
|
|
70
70
|
rotateOnQuotaDrop: 20,
|
|
71
71
|
quotaPollIntervalMs: DEFAULT_QUOTA_POLL_INTERVAL_MS,
|
|
72
|
-
maxConcurrentRequestsPerAccount:
|
|
73
|
-
maxConcurrentRequestsPerProjectModel:
|
|
72
|
+
maxConcurrentRequestsPerAccount: 5,
|
|
73
|
+
maxConcurrentRequestsPerProjectModel: 5,
|
|
74
74
|
projectCircuitBreaker429Threshold: 3,
|
|
75
75
|
projectCircuitBreakerWindowMs: 10 * 60 * 1000,
|
|
76
76
|
projectCircuitBreakerCooldownMs: 60 * 60 * 1000,
|
|
@@ -64,6 +64,18 @@ export function getCredential(
|
|
|
64
64
|
return undefined;
|
|
65
65
|
}
|
|
66
66
|
|
|
67
|
+
/** Resolve a provider project without letting whitespace mask legacy fallback. */
|
|
68
|
+
export function getProviderProjectId(
|
|
69
|
+
account: AccountLike,
|
|
70
|
+
providerId: string,
|
|
71
|
+
): string {
|
|
72
|
+
const nested = account.credentials
|
|
73
|
+
?.find((credential) => credential.provider === providerId)
|
|
74
|
+
?.projectId?.trim();
|
|
75
|
+
if (nested) return nested;
|
|
76
|
+
return providerId === DEFAULT_PROVIDER ? account.projectId?.trim() || "" : "";
|
|
77
|
+
}
|
|
78
|
+
|
|
67
79
|
/**
|
|
68
80
|
* Resolve the egress proxy configured for one provider credential. Incoming
|
|
69
81
|
* request headers are deliberately not consulted here; proxy selection is
|
|
@@ -7,6 +7,7 @@ import {
|
|
|
7
7
|
import type { AccountRuntime } from "../../types.js";
|
|
8
8
|
import type { ForwardedResponse } from "../../proxy.js";
|
|
9
9
|
import { fetchWithRetry } from "../../fetch-with-retry.js";
|
|
10
|
+
import { DEFAULT_PROVIDER, getProviderProjectId } from "../credential-helpers.js";
|
|
10
11
|
import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
|
|
11
12
|
|
|
12
13
|
export const CODE_ASSIST_ACTIONS = [
|
|
@@ -101,7 +102,7 @@ function buildUpstreamBody(
|
|
|
101
102
|
"retrieveUserQuotaSummary",
|
|
102
103
|
]);
|
|
103
104
|
if (!projectScoped.has(action)) return { ...body };
|
|
104
|
-
const projectId = account.config
|
|
105
|
+
const projectId = getProviderProjectId(account.config, DEFAULT_PROVIDER);
|
|
105
106
|
if (!projectId) {
|
|
106
107
|
throw new Error(`Code Assist ${action} requires the active account projectId`);
|
|
107
108
|
}
|
|
@@ -151,6 +152,7 @@ export async function forwardCodeAssistRequest(
|
|
|
151
152
|
return { response, endpoint };
|
|
152
153
|
} catch (err) {
|
|
153
154
|
lastError = err;
|
|
155
|
+
if (signal?.aborted) throw err;
|
|
154
156
|
if (index < ANTIGRAVITY_ENDPOINTS.length - 1) continue;
|
|
155
157
|
}
|
|
156
158
|
}
|
|
@@ -13,6 +13,7 @@ import type { AccountRuntime } from "../../types.js";
|
|
|
13
13
|
import type { RequestBody, ForwardedResponse } from "../../proxy.js";
|
|
14
14
|
import { logger } from "../../logger.js";
|
|
15
15
|
import type { TokenUsage } from "../adapter.js";
|
|
16
|
+
import { DEFAULT_PROVIDER, getProviderProjectId } from "../credential-helpers.js";
|
|
16
17
|
import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
|
|
17
18
|
import type { RequestInitWithDispatcher } from "../../fetch-with-retry.js";
|
|
18
19
|
|
|
@@ -234,7 +235,7 @@ const BENCHMARK_TIMEOUT_MS = 30_000;
|
|
|
234
235
|
|
|
235
236
|
function benchmarkRequestBody(account: AccountRuntime): RequestBody {
|
|
236
237
|
return {
|
|
237
|
-
project: account.config
|
|
238
|
+
project: getProviderProjectId(account.config, DEFAULT_PROVIDER),
|
|
238
239
|
model: BENCHMARK_MODEL,
|
|
239
240
|
request: {
|
|
240
241
|
contents: [
|
|
@@ -297,7 +298,7 @@ export async function forwardRequest(
|
|
|
297
298
|
signal?: AbortSignal,
|
|
298
299
|
): Promise<ForwardedResponse> {
|
|
299
300
|
// Swap credentials
|
|
300
|
-
body.project = account.config
|
|
301
|
+
body.project = getProviderProjectId(account.config, DEFAULT_PROVIDER);
|
|
301
302
|
|
|
302
303
|
// Map internal display/compat names to Google upstream names (single source
|
|
303
304
|
// of truth: src/types.ts:applyModelAlias)
|
|
@@ -404,6 +405,7 @@ export async function forwardRequest(
|
|
|
404
405
|
|
|
405
406
|
return { response, endpoint };
|
|
406
407
|
} catch (err) {
|
|
408
|
+
if (signal?.aborted) throw err;
|
|
407
409
|
if (endpointIdx < ANTIGRAVITY_ENDPOINTS.length - 1) {
|
|
408
410
|
forwardLogger.log("info",
|
|
409
411
|
`Endpoint ${endpoint} failed: ${
|
|
@@ -51,6 +51,11 @@ async function ensureGoogleToken(account: AccountRuntime): Promise<void> {
|
|
|
51
51
|
`Account ${account.config.email} has no refreshToken; re-run login`,
|
|
52
52
|
);
|
|
53
53
|
}
|
|
54
|
+
if (account.config.refreshToken.startsWith("enc:")) {
|
|
55
|
+
throw new Error(
|
|
56
|
+
`Account ${account.config.email} has an encrypted refreshToken (enc:*) but it could not be decrypted. Set TUXEVIL_ROTATOR_ENCRYPTION_KEY or re-run login.`,
|
|
57
|
+
);
|
|
58
|
+
}
|
|
54
59
|
const oauth = getOAuthClientConfig();
|
|
55
60
|
const response = await fetchWithRetry(TOKEN_URL, {
|
|
56
61
|
method: "POST",
|
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
} from "../../types.js";
|
|
14
14
|
import { fetchWithRetry } from "../../fetch-with-retry.js";
|
|
15
15
|
import type { QuotaFetchContext } from "../adapter.js";
|
|
16
|
+
import { DEFAULT_PROVIDER, getProviderProjectId } from "../credential-helpers.js";
|
|
16
17
|
import { getAccountProxyDispatcher } from "../proxy-dispatcher.js";
|
|
17
18
|
import { sortQuotaPools } from "../registry.js";
|
|
18
19
|
|
|
@@ -92,7 +93,9 @@ export async function fetchProviderQuota(
|
|
|
92
93
|
Authorization: `Bearer ${account.accessToken}`,
|
|
93
94
|
"User-Agent": QUOTA_USER_AGENT,
|
|
94
95
|
},
|
|
95
|
-
body: JSON.stringify({
|
|
96
|
+
body: JSON.stringify({
|
|
97
|
+
project: getProviderProjectId(account.config, DEFAULT_PROVIDER),
|
|
98
|
+
}),
|
|
96
99
|
timeoutMs: 8000,
|
|
97
100
|
dispatcher: getAccountProxyDispatcher(account, "google-antigravity"),
|
|
98
101
|
});
|
package/src/proxy.ts
CHANGED
|
@@ -164,8 +164,21 @@ const RESOURCE_EXHAUSTED_COOLDOWN_MS = 30 * 60 * 1000; // Stop hammering provide
|
|
|
164
164
|
const STREAM_IDLE_TIMEOUT_MS = 2 * 60 * 1000; // Release account if a stream goes silent.
|
|
165
165
|
const LARGE_CONTEXT_WARN_BYTES = 1 * 1024 * 1024;
|
|
166
166
|
|
|
167
|
-
function sleep(ms: number): Promise<void> {
|
|
168
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
167
|
+
function sleep(ms: number, signal?: AbortSignal): Promise<void> {
|
|
168
|
+
if (!signal) return new Promise((resolve) => setTimeout(resolve, ms));
|
|
169
|
+
if (signal.aborted) return Promise.reject(signal.reason ?? new Error("Request aborted"));
|
|
170
|
+
|
|
171
|
+
return new Promise((resolve, reject) => {
|
|
172
|
+
const onAbort = (): void => {
|
|
173
|
+
clearTimeout(timer);
|
|
174
|
+
reject(signal.reason ?? new Error("Request aborted"));
|
|
175
|
+
};
|
|
176
|
+
const timer = setTimeout(() => {
|
|
177
|
+
signal.removeEventListener("abort", onAbort);
|
|
178
|
+
resolve();
|
|
179
|
+
}, ms);
|
|
180
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
181
|
+
});
|
|
169
182
|
}
|
|
170
183
|
|
|
171
184
|
export class PreFlushStreamError extends Error {
|
|
@@ -922,7 +935,7 @@ export async function benchmarkAccount(
|
|
|
922
935
|
const startedAt = Date.now();
|
|
923
936
|
const maxConcurrent = Math.max(
|
|
924
937
|
1,
|
|
925
|
-
rotator.getConfig().maxConcurrentRequestsPerAccount ??
|
|
938
|
+
rotator.getConfig().maxConcurrentRequestsPerAccount ?? 5,
|
|
926
939
|
);
|
|
927
940
|
if (account.inFlightRequests >= maxConcurrent) {
|
|
928
941
|
return {
|
|
@@ -1139,23 +1152,15 @@ export async function withRotation<T>(
|
|
|
1139
1152
|
};
|
|
1140
1153
|
};
|
|
1141
1154
|
|
|
1142
|
-
const rotateAndRelease = async (): Promise<AccountRuntime | null> => {
|
|
1143
|
-
const nextAccount = await rotator.rotateToNext(model);
|
|
1144
|
-
if (nextAccount) {
|
|
1145
|
-
rotator.finishRequest(
|
|
1146
|
-
nextAccount,
|
|
1147
|
-
routingModelKey(rotator, model),
|
|
1148
|
-
);
|
|
1149
|
-
}
|
|
1150
|
-
return nextAccount;
|
|
1151
|
-
};
|
|
1152
|
-
|
|
1153
1155
|
const maxRetries = getStreamRecoveryMaxRetries(rotator);
|
|
1154
1156
|
const maxAttempts = maxRetries + 1;
|
|
1155
1157
|
|
|
1156
1158
|
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
1157
|
-
const account = await rotator.getActiveAccount(model);
|
|
1159
|
+
const account = await rotator.getActiveAccount(model, signal);
|
|
1158
1160
|
if (!account) {
|
|
1161
|
+
if (signal?.aborted) {
|
|
1162
|
+
return { ok: false, status: 499, errorText: "Client closed request" };
|
|
1163
|
+
}
|
|
1159
1164
|
return sendNoAccountsAvailable("rotation returned no available account");
|
|
1160
1165
|
}
|
|
1161
1166
|
|
|
@@ -1164,6 +1169,17 @@ export async function withRotation<T>(
|
|
|
1164
1169
|
const displayModelKey = resolveDisplayModelKey(body.displayModel || model);
|
|
1165
1170
|
const requestId = `${modelKey}-${Date.now().toString(36)}-${attempt + 1}`;
|
|
1166
1171
|
const requestStartMs = Date.now();
|
|
1172
|
+
let accountReleased = false;
|
|
1173
|
+
const releaseCurrentAccount = (): void => {
|
|
1174
|
+
if (accountReleased) return;
|
|
1175
|
+
accountReleased = true;
|
|
1176
|
+
rotator.finishRequest(account, modelKey);
|
|
1177
|
+
};
|
|
1178
|
+
const rotateAndRelease = async (): Promise<AccountRuntime | null> => {
|
|
1179
|
+
releaseCurrentAccount();
|
|
1180
|
+
const nextAccount = await rotator.rotateToNext(model, account);
|
|
1181
|
+
return nextAccount;
|
|
1182
|
+
};
|
|
1167
1183
|
const logRequestEnd = (status: string | number, extra = ""): void => {
|
|
1168
1184
|
log(
|
|
1169
1185
|
`[${requestId}] END account=${label} model=${model} status=${status}${extra ? ` ${extra}` : ""} totalMs=${Date.now() - requestStartMs}`,
|
|
@@ -1196,7 +1212,7 @@ export async function withRotation<T>(
|
|
|
1196
1212
|
"info",
|
|
1197
1213
|
);
|
|
1198
1214
|
}
|
|
1199
|
-
await sleep(totalDelayMs);
|
|
1215
|
+
await sleep(totalDelayMs, signal);
|
|
1200
1216
|
}
|
|
1201
1217
|
|
|
1202
1218
|
rotator.recordUpstreamAttempt(account);
|
|
@@ -1258,10 +1274,13 @@ export async function withRotation<T>(
|
|
|
1258
1274
|
const shouldRotate = rotator.recordRequest(account, model);
|
|
1259
1275
|
logRequestEnd(response.status, `endpoint=${endpoint}`);
|
|
1260
1276
|
if (shouldRotate) {
|
|
1261
|
-
await
|
|
1277
|
+
await rotator.rotateToNext(model, account);
|
|
1262
1278
|
}
|
|
1263
1279
|
return { ok: true, result, endpoint, context };
|
|
1264
1280
|
} catch (err) {
|
|
1281
|
+
if (signal?.aborted) {
|
|
1282
|
+
return { ok: false, status: 499, errorText: "Client closed request" };
|
|
1283
|
+
}
|
|
1265
1284
|
const formattedError = formatError(err);
|
|
1266
1285
|
log(
|
|
1267
1286
|
`[${label}] Request failed: ${formattedError}`,
|
|
@@ -1317,7 +1336,7 @@ export async function withRotation<T>(
|
|
|
1317
1336
|
}
|
|
1318
1337
|
continue;
|
|
1319
1338
|
} finally {
|
|
1320
|
-
|
|
1339
|
+
releaseCurrentAccount();
|
|
1321
1340
|
}
|
|
1322
1341
|
}
|
|
1323
1342
|
|
|
@@ -1433,6 +1452,15 @@ async function handleProxyRequest(
|
|
|
1433
1452
|
return;
|
|
1434
1453
|
}
|
|
1435
1454
|
const apiKeyHash = auth.key?.tokenHash || (auth.rawKey ? hashKey(auth.rawKey) : null);
|
|
1455
|
+
const clientController = new AbortController();
|
|
1456
|
+
const abortClient = (): void => clientController.abort();
|
|
1457
|
+
const removeAbortListeners = (): void => {
|
|
1458
|
+
req.off("aborted", abortClient);
|
|
1459
|
+
res.off("close", abortClient);
|
|
1460
|
+
};
|
|
1461
|
+
req.once("aborted", abortClient);
|
|
1462
|
+
res.once("close", abortClient);
|
|
1463
|
+
res.once("finish", removeAbortListeners);
|
|
1436
1464
|
|
|
1437
1465
|
const proxyLog = (
|
|
1438
1466
|
msg: string,
|
|
@@ -1448,6 +1476,7 @@ async function handleProxyRequest(
|
|
|
1448
1476
|
}
|
|
1449
1477
|
|
|
1450
1478
|
const sendNoAccountsAvailable = (reason: string): void => {
|
|
1479
|
+
if (clientController.signal.aborted || res.destroyed) return;
|
|
1451
1480
|
proxyLog(`[${body.model}] No healthy account available: ${reason}`, "warn");
|
|
1452
1481
|
const retryAfterMs = rotator.getRetryAfterMs(body.model);
|
|
1453
1482
|
if (retryAfterMs > 0) {
|
|
@@ -1477,17 +1506,8 @@ async function handleProxyRequest(
|
|
|
1477
1506
|
}),
|
|
1478
1507
|
);
|
|
1479
1508
|
};
|
|
1480
|
-
const rotateAndRelease = async (): Promise<AccountRuntime | null> => {
|
|
1481
|
-
const nextAccount = await rotator.rotateToNext(body.model);
|
|
1482
|
-
if (nextAccount) {
|
|
1483
|
-
rotator.finishRequest(
|
|
1484
|
-
nextAccount,
|
|
1485
|
-
routingModelKey(rotator, body.model),
|
|
1486
|
-
);
|
|
1487
|
-
}
|
|
1488
|
-
return nextAccount;
|
|
1489
|
-
};
|
|
1490
1509
|
const sendFailureDecision = (decision: UpstreamFailureDecision): void => {
|
|
1510
|
+
if (clientController.signal.aborted || res.destroyed) return;
|
|
1491
1511
|
if (decision.noReplacementReason) {
|
|
1492
1512
|
sendNoAccountsAvailable(decision.noReplacementReason);
|
|
1493
1513
|
return;
|
|
@@ -1554,8 +1574,12 @@ async function handleProxyRequest(
|
|
|
1554
1574
|
const maxRetries = getStreamRecoveryMaxRetries(rotator);
|
|
1555
1575
|
const maxAttempts = maxRetries + 1;
|
|
1556
1576
|
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
1557
|
-
const account = await rotator.getActiveAccount(
|
|
1577
|
+
const account = await rotator.getActiveAccount(
|
|
1578
|
+
body.model,
|
|
1579
|
+
clientController.signal,
|
|
1580
|
+
);
|
|
1558
1581
|
if (!account) {
|
|
1582
|
+
if (clientController.signal.aborted || res.destroyed) return;
|
|
1559
1583
|
sendNoAccountsAvailable("rotation returned no available account");
|
|
1560
1584
|
return;
|
|
1561
1585
|
}
|
|
@@ -1564,6 +1588,20 @@ async function handleProxyRequest(
|
|
|
1564
1588
|
const modelKey = rotator.resolveQuotaModelKeyForDisplay(body.model) ?? body.model; // quota routing
|
|
1565
1589
|
const displayModelKey = resolveDisplayModelKey(body.model); // metrics/logs
|
|
1566
1590
|
const requestId = `${modelKey}-${Date.now().toString(36)}-${attempt + 1}`;
|
|
1591
|
+
let accountReleased = false;
|
|
1592
|
+
const releaseCurrentAccount = (): void => {
|
|
1593
|
+
if (accountReleased) return;
|
|
1594
|
+
accountReleased = true;
|
|
1595
|
+
rotator.finishRequest(
|
|
1596
|
+
account,
|
|
1597
|
+
routingModelKey(rotator, body.model),
|
|
1598
|
+
);
|
|
1599
|
+
};
|
|
1600
|
+
const rotateAndRelease = async (): Promise<AccountRuntime | null> => {
|
|
1601
|
+
releaseCurrentAccount();
|
|
1602
|
+
const nextAccount = await rotator.rotateToNext(body.model, account);
|
|
1603
|
+
return nextAccount;
|
|
1604
|
+
};
|
|
1567
1605
|
proxyLog(
|
|
1568
1606
|
`[${requestId}] START account=${label} model=${body.model} attempt=${attempt + 1}`,
|
|
1569
1607
|
);
|
|
@@ -1609,7 +1647,7 @@ async function handleProxyRequest(
|
|
|
1609
1647
|
"info",
|
|
1610
1648
|
);
|
|
1611
1649
|
}
|
|
1612
|
-
await sleep(totalDelayMs);
|
|
1650
|
+
await sleep(totalDelayMs, clientController.signal);
|
|
1613
1651
|
}
|
|
1614
1652
|
rotator.recordUpstreamAttempt(account);
|
|
1615
1653
|
const provider = providerAdapterForModel(
|
|
@@ -1622,6 +1660,7 @@ async function handleProxyRequest(
|
|
|
1622
1660
|
account,
|
|
1623
1661
|
{ ...body },
|
|
1624
1662
|
flattenHeaders(req.headers),
|
|
1663
|
+
clientController.signal,
|
|
1625
1664
|
);
|
|
1626
1665
|
const { response, endpoint } = forwarded;
|
|
1627
1666
|
const context: RotationAttemptContext = {
|
|
@@ -1746,10 +1785,11 @@ async function handleProxyRequest(
|
|
|
1746
1785
|
res.end();
|
|
1747
1786
|
|
|
1748
1787
|
if (shouldRotate) {
|
|
1749
|
-
await
|
|
1788
|
+
await rotator.rotateToNext(body.model, account);
|
|
1750
1789
|
}
|
|
1751
1790
|
return;
|
|
1752
1791
|
} catch (err) {
|
|
1792
|
+
if (clientController.signal.aborted || res.destroyed) return;
|
|
1753
1793
|
const formattedError = formatError(err);
|
|
1754
1794
|
proxyLog(
|
|
1755
1795
|
`[${label}] Request failed: ${formattedError}`,
|
|
@@ -1781,14 +1821,12 @@ async function handleProxyRequest(
|
|
|
1781
1821
|
}
|
|
1782
1822
|
continue;
|
|
1783
1823
|
} finally {
|
|
1784
|
-
|
|
1785
|
-
account,
|
|
1786
|
-
routingModelKey(rotator, body.model),
|
|
1787
|
-
);
|
|
1824
|
+
releaseCurrentAccount();
|
|
1788
1825
|
if (onComplete) onComplete();
|
|
1789
1826
|
}
|
|
1790
1827
|
}
|
|
1791
1828
|
|
|
1829
|
+
if (clientController.signal.aborted || res.destroyed) return;
|
|
1792
1830
|
if (!res.headersSent) {
|
|
1793
1831
|
res.writeHead(502, { "Content-Type": "application/json" });
|
|
1794
1832
|
}
|
|
@@ -1834,22 +1872,47 @@ async function handleCodeAssistPassthrough(
|
|
|
1834
1872
|
return;
|
|
1835
1873
|
}
|
|
1836
1874
|
|
|
1875
|
+
const clientController = new AbortController();
|
|
1876
|
+
const abortClient = (): void => clientController.abort();
|
|
1877
|
+
const removeAbortListeners = (): void => {
|
|
1878
|
+
req.off("aborted", abortClient);
|
|
1879
|
+
res.off("close", abortClient);
|
|
1880
|
+
};
|
|
1881
|
+
req.once("aborted", abortClient);
|
|
1882
|
+
res.once("close", abortClient);
|
|
1883
|
+
res.once("finish", removeAbortListeners);
|
|
1884
|
+
|
|
1837
1885
|
const maxRetries = getStreamRecoveryMaxRetries(rotator);
|
|
1838
1886
|
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
1839
1887
|
let account: AccountRuntime | null;
|
|
1840
1888
|
try {
|
|
1841
|
-
account = await rotator.getActiveAccount(
|
|
1889
|
+
account = await rotator.getActiveAccount(
|
|
1890
|
+
CODE_ASSIST_ROUTING_MODEL,
|
|
1891
|
+
clientController.signal,
|
|
1892
|
+
);
|
|
1842
1893
|
} catch {
|
|
1894
|
+
if (clientController.signal.aborted || res.destroyed) return;
|
|
1843
1895
|
res.writeHead(502, { "Content-Type": "application/json" });
|
|
1844
1896
|
res.end(JSON.stringify({ error: "Account token refresh failed" }));
|
|
1845
1897
|
return;
|
|
1846
1898
|
}
|
|
1847
1899
|
if (!account) {
|
|
1900
|
+
if (clientController.signal.aborted || res.destroyed) return;
|
|
1848
1901
|
res.writeHead(503, { "Content-Type": "application/json" });
|
|
1849
1902
|
res.end(JSON.stringify({ error: "All Google accounts exhausted or disabled" }));
|
|
1850
1903
|
return;
|
|
1851
1904
|
}
|
|
1852
1905
|
|
|
1906
|
+
let accountReleased = false;
|
|
1907
|
+
const releaseCurrentAccount = (): void => {
|
|
1908
|
+
if (accountReleased) return;
|
|
1909
|
+
accountReleased = true;
|
|
1910
|
+
rotator.finishRequest(
|
|
1911
|
+
account,
|
|
1912
|
+
resolveQuotaModelKey(CODE_ASSIST_ROUTING_MODEL) ?? undefined,
|
|
1913
|
+
);
|
|
1914
|
+
};
|
|
1915
|
+
|
|
1853
1916
|
try {
|
|
1854
1917
|
// getActiveAccount performs the normal account lifecycle check, but the
|
|
1855
1918
|
// explicit provider call is required for dual Google+Ollama accounts.
|
|
@@ -1860,35 +1923,32 @@ async function handleCodeAssistPassthrough(
|
|
|
1860
1923
|
action,
|
|
1861
1924
|
body,
|
|
1862
1925
|
flattenHeaders(req.headers),
|
|
1926
|
+
clientController.signal,
|
|
1863
1927
|
);
|
|
1864
1928
|
const responseBody = await forwarded.response.text();
|
|
1929
|
+
if (clientController.signal.aborted || res.destroyed) return;
|
|
1865
1930
|
res.writeHead(forwarded.response.status, {
|
|
1866
1931
|
"Content-Type": forwarded.response.headers.get("content-type") || "application/json",
|
|
1867
1932
|
});
|
|
1868
1933
|
res.end(responseBody);
|
|
1869
1934
|
return;
|
|
1870
1935
|
} catch (err) {
|
|
1936
|
+
if (clientController.signal.aborted || res.destroyed) return;
|
|
1871
1937
|
if (!isFetchTransportError(err) || attempt >= maxRetries) {
|
|
1872
1938
|
res.writeHead(502, { "Content-Type": "application/json" });
|
|
1873
1939
|
res.end(JSON.stringify({ error: "Code Assist upstream request failed" }));
|
|
1874
1940
|
return;
|
|
1875
1941
|
}
|
|
1876
|
-
|
|
1942
|
+
releaseCurrentAccount();
|
|
1943
|
+
const nextAccount = await rotator.rotateToNext(CODE_ASSIST_ROUTING_MODEL, account);
|
|
1877
1944
|
if (nextAccount) {
|
|
1878
|
-
rotator.finishRequest(
|
|
1879
|
-
nextAccount,
|
|
1880
|
-
resolveQuotaModelKey(CODE_ASSIST_ROUTING_MODEL) ?? undefined,
|
|
1881
|
-
);
|
|
1882
1945
|
continue;
|
|
1883
1946
|
}
|
|
1884
1947
|
res.writeHead(503, { "Content-Type": "application/json" });
|
|
1885
1948
|
res.end(JSON.stringify({ error: "No replacement Google account available" }));
|
|
1886
1949
|
return;
|
|
1887
1950
|
} finally {
|
|
1888
|
-
|
|
1889
|
-
account,
|
|
1890
|
-
resolveQuotaModelKey(CODE_ASSIST_ROUTING_MODEL) ?? undefined,
|
|
1891
|
-
);
|
|
1951
|
+
releaseCurrentAccount();
|
|
1892
1952
|
}
|
|
1893
1953
|
}
|
|
1894
1954
|
}
|