tuxevil-rotator 3.7.1 → 3.7.2

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/src/rotator.ts CHANGED
@@ -178,8 +178,13 @@ function projectModelKey(projectId: string, modelKey: string): string {
178
178
  }
179
179
 
180
180
  const REQUEST_QUEUE_TIMEOUT_MS = 300_000;
181
+ // Node clamps delays above the signed 32-bit millisecond limit to 1ms. Long
182
+ // provider cooldowns (for example Codex weekly resets) must be rechecked in
183
+ // safe-sized timer slices instead of creating a hot timer loop.
184
+ const MAX_NODE_TIMEOUT_MS = 2_147_483_647;
181
185
 
182
186
  interface AccountRequestWaiter {
187
+ queueKey: string;
183
188
  model?: string;
184
189
  signal?: AbortSignal;
185
190
  timer: ReturnType<typeof setTimeout>;
@@ -334,6 +339,8 @@ export class AccountRotator {
334
339
  account: string;
335
340
  }> = [];
336
341
  private routingDiagnostics: Record<string, RoutingModelDiagnostics> = {};
342
+ private routingWarningLastLoggedAt = new Map<string, number>();
343
+ private static readonly ROUTING_WARNING_DEDUP_MS = 60_000;
337
344
  private autoWarmupEnabled = false;
338
345
  // Debounced state writer: batches multiple saveState() calls within a 1s window
339
346
  // to a single disk write. Hot paths (markError, recordRequest, etc.) call
@@ -1492,11 +1499,12 @@ export class AccountRotator {
1492
1499
  return { reason: "disabled", detail: "account disabled" };
1493
1500
  if (account.flagged)
1494
1501
  return { reason: "flagged", detail: "account quarantined or flagged" };
1495
- if (!this.isProviderEligibleForKey(account, modelKey))
1496
- return {
1497
- reason: "provider-ineligible",
1498
- detail: "account lacks a credential for this provider pool",
1499
- };
1502
+ const providerRejection = this.getProviderEligibilityRejection(
1503
+ account,
1504
+ modelKey,
1505
+ now,
1506
+ );
1507
+ if (providerRejection) return providerRejection;
1500
1508
  const defaultCooldown = account.cooldownsByModel["__default__"] ?? 0;
1501
1509
  if (defaultCooldown > now)
1502
1510
  return { reason: "cooldown", detail: "default cooldown active" };
@@ -1861,26 +1869,39 @@ export class AccountRotator {
1861
1869
  signal?: AbortSignal,
1862
1870
  ): Promise<AccountRuntime | null> {
1863
1871
  if (signal?.aborted) return null;
1872
+ const queueKey = this.getRequestQueueKey(model);
1864
1873
  if (
1865
- this.requestWaiters.length > 0 ||
1874
+ this.hasQueuedRequest(queueKey) ||
1866
1875
  this.isConcurrencySaturated(model)
1867
1876
  ) {
1868
- return this.enqueueAccountRequest(model, signal);
1877
+ return this.enqueueAccountRequest(model, signal, queueKey);
1869
1878
  }
1870
1879
 
1871
1880
  const account = await this.tryGetActiveAccount(model);
1872
1881
  if (account || !this.isConcurrencySaturated(model)) return account;
1873
- return this.enqueueAccountRequest(model, signal);
1882
+ return this.enqueueAccountRequest(model, signal, queueKey);
1883
+ }
1884
+
1885
+ /** Keep fairness within a provider pool without making unrelated providers wait. */
1886
+ private getRequestQueueKey(model?: string): string {
1887
+ if (!model) return DEFAULT_PROVIDER;
1888
+ return getProviderIdForPoolKey(this.resolveRequestPoolKey(model));
1889
+ }
1890
+
1891
+ private hasQueuedRequest(queueKey: string): boolean {
1892
+ return this.requestWaiters.some((waiter) => waiter.queueKey === queueKey);
1874
1893
  }
1875
1894
 
1876
1895
  private enqueueAccountRequest(
1877
1896
  model?: string,
1878
1897
  signal?: AbortSignal,
1898
+ queueKey = this.getRequestQueueKey(model),
1879
1899
  ): Promise<AccountRuntime | null> {
1880
1900
  if (signal?.aborted) return Promise.resolve(null);
1881
1901
 
1882
1902
  return new Promise<AccountRuntime | null>((resolve, reject) => {
1883
1903
  const waiter = {} as AccountRequestWaiter;
1904
+ waiter.queueKey = queueKey;
1884
1905
  waiter.model = model;
1885
1906
  waiter.signal = signal;
1886
1907
  waiter.resolve = resolve;
@@ -1945,6 +1966,10 @@ export class AccountRotator {
1945
1966
  }
1946
1967
  this.clearRequestWaiterWake();
1947
1968
  this.requestWaiterWakeAt = wakeAt;
1969
+ const delayMs = Math.min(
1970
+ MAX_NODE_TIMEOUT_MS,
1971
+ Math.max(1, wakeAt - Date.now()),
1972
+ );
1948
1973
  this.requestWaiterWakeTimer = setTimeout(() => {
1949
1974
  this.requestWaiterWakeTimer = null;
1950
1975
  if (this.requestWaiters.length === 0) {
@@ -1957,7 +1982,7 @@ export class AccountRotator {
1957
1982
  }
1958
1983
  this.requestWaiterWakeAt = 0;
1959
1984
  this.requestWaiterDrain();
1960
- }, Math.max(1, wakeAt - Date.now()));
1985
+ }, delayMs);
1961
1986
  }
1962
1987
 
1963
1988
  private requestWaiterDrain(): void {
@@ -1975,11 +2000,18 @@ export class AccountRotator {
1975
2000
  do {
1976
2001
  this.requestWaiterDrainRequested = false;
1977
2002
  progressed = false;
1978
- for (const waiter of [...this.requestWaiters]) {
2003
+ const queueKeys = [
2004
+ ...new Set(this.requestWaiters.map((waiter) => waiter.queueKey)),
2005
+ ];
2006
+ for (const queueKey of queueKeys) {
2007
+ const waiter = this.requestWaiters.find(
2008
+ (candidate) => candidate.queueKey === queueKey,
2009
+ );
2010
+ if (!waiter) continue;
1979
2011
  if (waiter.signal?.aborted) {
1980
2012
  this.settleAccountRequestWaiter(waiter, null);
1981
2013
  progressed = true;
1982
- break;
2014
+ continue;
1983
2015
  }
1984
2016
 
1985
2017
  let account: AccountRuntime | null;
@@ -1988,7 +2020,7 @@ export class AccountRotator {
1988
2020
  } catch (error) {
1989
2021
  this.rejectAccountRequestWaiter(waiter, error);
1990
2022
  progressed = true;
1991
- break;
2023
+ continue;
1992
2024
  }
1993
2025
 
1994
2026
  if (!this.requestWaiters.includes(waiter)) {
@@ -2001,16 +2033,16 @@ export class AccountRotator {
2001
2033
  );
2002
2034
  }
2003
2035
  progressed = true;
2004
- break;
2036
+ continue;
2005
2037
  }
2006
2038
  if (account) {
2007
2039
  this.settleAccountRequestWaiter(waiter, account);
2008
2040
  progressed = true;
2009
- break;
2041
+ continue;
2010
2042
  }
2011
2043
  if (this.requestWaiterDrainRequested) {
2012
2044
  progressed = true;
2013
- break;
2045
+ continue;
2014
2046
  }
2015
2047
  const wakeAt = this.getNextRequestAvailabilityAt(waiter.model);
2016
2048
  if (wakeAt !== null) this.scheduleRequestWaiterWake(wakeAt);
@@ -2018,7 +2050,6 @@ export class AccountRotator {
2018
2050
  this.settleAccountRequestWaiter(waiter, null);
2019
2051
  progressed = true;
2020
2052
  }
2021
- break;
2022
2053
  }
2023
2054
  } while (progressed || this.requestWaiterDrainRequested);
2024
2055
  } finally {
@@ -2130,12 +2161,32 @@ export class AccountRotator {
2130
2161
  }
2131
2162
  }
2132
2163
 
2133
- if (current && modelKey && !this.isProviderEligibleForKey(current, modelKey)) {
2134
- this.log(
2135
- `${current.config.label || current.config.email}: provider mismatch for model, rotating`,
2136
- "warn",
2164
+ if (current && modelKey) {
2165
+ const providerRejection = this.getProviderEligibilityRejection(
2166
+ current,
2167
+ modelKey,
2168
+ now,
2137
2169
  );
2138
- return this.rotateModelForRequest(modelKey, now, idx);
2170
+ if (providerRejection) {
2171
+ // A cooldown is expected after a provider 429 and can be hit by many
2172
+ // concurrent callers. Keep that path quiet; diagnostics already show
2173
+ // the cooldown and the generic no-route warning is deduplicated below.
2174
+ if (providerRejection.reason === "provider-ineligible") {
2175
+ const warningKey = `${modelKey}:provider-ineligible`;
2176
+ const lastLoggedAt = this.routingWarningLastLoggedAt.get(warningKey);
2177
+ if (
2178
+ lastLoggedAt === undefined ||
2179
+ now - lastLoggedAt >= AccountRotator.ROUTING_WARNING_DEDUP_MS
2180
+ ) {
2181
+ this.routingWarningLastLoggedAt.set(warningKey, now);
2182
+ this.log(
2183
+ `${current.config.label || current.config.email}: provider unavailable for model (${providerRejection.detail}), rotating`,
2184
+ "warn",
2185
+ );
2186
+ }
2187
+ }
2188
+ return this.rotateModelForRequest(modelKey, now, idx);
2189
+ }
2139
2190
  }
2140
2191
  if (
2141
2192
  current &&
@@ -2351,10 +2402,17 @@ export class AccountRotator {
2351
2402
  } else {
2352
2403
  const diagnostics = this.buildRoutingDiagnostics(modelKey, now);
2353
2404
  this.routingDiagnostics[modelKey] = diagnostics;
2354
- this.log(
2355
- `[${modelKey}] All accounts disabled or unavailable: ${diagnostics.reason}`,
2356
- "warn",
2357
- );
2405
+ const lastLoggedAt = this.routingWarningLastLoggedAt.get(modelKey);
2406
+ if (
2407
+ lastLoggedAt === undefined ||
2408
+ now - lastLoggedAt >= AccountRotator.ROUTING_WARNING_DEDUP_MS
2409
+ ) {
2410
+ this.routingWarningLastLoggedAt.set(modelKey, now);
2411
+ this.log(
2412
+ `[${modelKey}] All accounts disabled or unavailable: ${diagnostics.reason}`,
2413
+ "warn",
2414
+ );
2415
+ }
2358
2416
  }
2359
2417
  return null;
2360
2418
  }
@@ -3005,7 +3063,7 @@ export class AccountRotator {
3005
3063
  const modelKey = model
3006
3064
  ? this.resolveAccountPoolKey(account, model)
3007
3065
  : "__default__";
3008
- if (model && (modelKey.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`) || isCodexRequestModel(model))) {
3066
+ if (model && (this.isCodexPoolKey(modelKey) || isCodexRequestModel(model))) {
3009
3067
  this.setProviderCooldown(account, "openai-codex", cooldownMs);
3010
3068
  }
3011
3069
  account.cooldownsByModel[modelKey] = now + cooldownMs;
@@ -3019,6 +3077,7 @@ export class AccountRotator {
3019
3077
  candidate.modelKey === modelKey &&
3020
3078
  (candidate.providerId === DEFAULT_PROVIDER ||
3021
3079
  candidate.providerId === "ollama" ||
3080
+ candidate.providerId === "openai-codex" ||
3022
3081
  candidate.providerId === undefined),
3023
3082
  );
3024
3083
  if (quota) {
@@ -3047,11 +3106,11 @@ export class AccountRotator {
3047
3106
  providerResourceExhausted = false,
3048
3107
  ): void {
3049
3108
  const now = Date.now();
3050
- if (model && isCodexRequestModel(model)) {
3109
+ const poolKey = model ? this.resolveAccountPoolKey(account, model) : null;
3110
+ if (model && (isCodexRequestModel(model) || (poolKey && this.isCodexPoolKey(poolKey)))) {
3051
3111
  this.setProviderCooldown(account, "openai-codex", cooldownMs);
3052
3112
  return;
3053
3113
  }
3054
- const poolKey = model ? this.resolveAccountPoolKey(account, model) : null;
3055
3114
  const isAccountScopedProvider =
3056
3115
  providerResourceExhausted ||
3057
3116
  (poolKey &&
@@ -3482,7 +3541,8 @@ export class AccountRotator {
3482
3541
  }
3483
3542
 
3484
3543
  private isCodexPoolKey(modelKey: string): boolean {
3485
- return modelKey.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`);
3544
+ return modelKey === CODEX_QUOTA_MODEL_KEY ||
3545
+ modelKey.startsWith(`${CODEX_QUOTA_MODEL_KEY}:`);
3486
3546
  }
3487
3547
 
3488
3548
  private async ensureValidTokenForModel(
@@ -3622,18 +3682,54 @@ export class AccountRotator {
3622
3682
  account: AccountRuntime,
3623
3683
  modelKey: string,
3624
3684
  ): boolean {
3685
+ return this.getProviderEligibilityRejection(account, modelKey) === null;
3686
+ }
3687
+
3688
+ private getProviderEligibilityRejection(
3689
+ account: AccountRuntime,
3690
+ modelKey: string,
3691
+ now = Date.now(),
3692
+ ): { reason: RoutingRejectionReason; detail: string } | null {
3625
3693
  const accountId = getAccountIdentity(account);
3626
3694
  if (
3627
3695
  !isStaticAntigravityModel(modelKey) &&
3628
3696
  dynamicCatalog.hasOwnershipForModel(modelKey) &&
3629
3697
  !dynamicCatalog.hasModelForAccount(accountId, modelKey)
3630
3698
  ) {
3631
- return false;
3699
+ return {
3700
+ reason: "provider-ineligible",
3701
+ detail: "account does not own this provider model",
3702
+ };
3632
3703
  }
3633
3704
  const providerId = getProviderIdForPoolKey(modelKey);
3634
- return hasCredential(account.config, providerId) &&
3635
- !account.invalidProviders?.[providerId] &&
3636
- (account.providerCooldowns?.[providerId] ?? 0) <= Date.now();
3705
+ if (!hasCredential(account.config, providerId)) {
3706
+ return {
3707
+ reason: "provider-ineligible",
3708
+ detail: `account has no ${providerId} credential for this provider pool`,
3709
+ };
3710
+ }
3711
+ if (account.invalidProviders?.[providerId]) {
3712
+ return {
3713
+ reason: "provider-ineligible",
3714
+ detail: `${providerId} credential is invalid; re-authentication required`,
3715
+ };
3716
+ }
3717
+ if (
3718
+ providerId === "openai-codex" &&
3719
+ !getProviderAdapter(providerId).hasValidCredentials(account)
3720
+ ) {
3721
+ return {
3722
+ reason: "provider-ineligible",
3723
+ detail: "Codex credential is missing or empty",
3724
+ };
3725
+ }
3726
+ if ((account.providerCooldowns?.[providerId] ?? 0) > now) {
3727
+ return {
3728
+ reason: "cooldown",
3729
+ detail: "provider cooldown active",
3730
+ };
3731
+ }
3732
+ return null;
3637
3733
  }
3638
3734
 
3639
3735
  /** Public pool-key resolution for quota routing display/logging. */
@@ -4621,7 +4717,7 @@ export class AccountRotator {
4621
4717
  const providerResourceExhausted =
4622
4718
  classifyRateLimitReason(errorText, response.status) === "quota-exhausted";
4623
4719
  const cooldownMs = providerResourceExhausted
4624
- ? target.providerId === DEFAULT_PROVIDER
4720
+ ? target.providerId === DEFAULT_PROVIDER || target.providerId === "openai-codex"
4625
4721
  ? parseRetryAfterMs(
4626
4722
  errorText,
4627
4723
  response.headers,
@@ -0,0 +1,85 @@
1
+ import type { ServerResponse } from "node:http";
2
+
3
+ export const STREAM_IDLE_TIMEOUT_MS = 2 * 60 * 1000;
4
+ export const STREAM_BACKPRESSURE_TIMEOUT_MS = 30 * 1000;
5
+
6
+ export class StreamIdleTimeoutError extends Error {
7
+ constructor(timeoutMs: number) {
8
+ super(`upstream stream idle timeout after ${Math.round(timeoutMs / 1000)}s`);
9
+ this.name = "StreamIdleTimeoutError";
10
+ }
11
+ }
12
+
13
+ /** Resettable guard used to release upstream streams that stop producing data. */
14
+ export function createStreamIdleGuard(
15
+ onTimeout: (error: StreamIdleTimeoutError) => void,
16
+ timeoutMs = STREAM_IDLE_TIMEOUT_MS,
17
+ ): { reset: () => void; clear: () => void } {
18
+ const effectiveTimeoutMs = Number.isFinite(timeoutMs)
19
+ ? Math.max(1, timeoutMs)
20
+ : STREAM_IDLE_TIMEOUT_MS;
21
+ let timer: ReturnType<typeof setTimeout> | null = null;
22
+
23
+ const reset = (): void => {
24
+ if (timer) clearTimeout(timer);
25
+ timer = setTimeout(() => {
26
+ timer = null;
27
+ onTimeout(new StreamIdleTimeoutError(effectiveTimeoutMs));
28
+ }, effectiveTimeoutMs);
29
+ };
30
+
31
+ const clear = (): void => {
32
+ if (timer) clearTimeout(timer);
33
+ timer = null;
34
+ };
35
+
36
+ reset();
37
+ return { reset, clear };
38
+ }
39
+
40
+ /**
41
+ * Respect the HTTP response's high-water mark so a client that stopped
42
+ * reading cannot make the proxy buffer an unbounded streamed response.
43
+ */
44
+ export function waitForResponseDrain(
45
+ res: ServerResponse,
46
+ timeoutMs = STREAM_BACKPRESSURE_TIMEOUT_MS,
47
+ ): Promise<void> {
48
+ if (res.destroyed || res.writableEnded || !res.writableNeedDrain) {
49
+ return Promise.resolve();
50
+ }
51
+
52
+ return new Promise<void>((resolve, reject) => {
53
+ let timer: ReturnType<typeof setTimeout> | null = null;
54
+ let settled = false;
55
+
56
+ const cleanup = (): void => {
57
+ if (timer) clearTimeout(timer);
58
+ res.off("drain", onDrain);
59
+ res.off("close", onClose);
60
+ res.off("error", onError);
61
+ };
62
+ const finish = (error?: Error): void => {
63
+ if (settled) return;
64
+ settled = true;
65
+ cleanup();
66
+ if (error) reject(error);
67
+ else resolve();
68
+ };
69
+ const onDrain = (): void => finish();
70
+ const onClose = (): void =>
71
+ finish(new Error("client response closed while draining backpressure"));
72
+ const onError = (error: Error): void => finish(error);
73
+
74
+ res.once("drain", onDrain);
75
+ res.once("close", onClose);
76
+ res.once("error", onError);
77
+ timer = setTimeout(() => {
78
+ finish(
79
+ new Error(
80
+ `client backpressure timeout after ${Math.round(timeoutMs / 1000)}s`,
81
+ ),
82
+ );
83
+ }, Math.max(1, timeoutMs));
84
+ });
85
+ }