tuxevil-rotator 3.7.0 → 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.
@@ -48,7 +48,7 @@ export async function fetchOpenCodeZenQuota(
48
48
 
49
49
  const freshQuota: ModelQuota = {
50
50
  modelKey: OPENCODE_ZEN_PROVIDER_ID,
51
- displayName: "OpenCode Zen Free Pool",
51
+ displayName: "OpenCode",
52
52
  providerId: OPENCODE_ZEN_PROVIDER_ID,
53
53
  percentRemaining: 100,
54
54
  resetTime: null,
@@ -27,6 +27,8 @@ export {
27
27
  type AccountLike as ProviderCredentialLike,
28
28
  PROVIDER_ORDER,
29
29
  PROVIDER_ORDER_RANK,
30
+ OLLAMA_QUOTA_POOL_KEY,
31
+ isOllamaQuotaPoolKey,
30
32
  getProviderIdForPoolKey,
31
33
  getQuotaItemProviderId,
32
34
  sortQuotaPools,
package/src/proxy.ts CHANGED
@@ -183,6 +183,7 @@ import {
183
183
  import { authenticateVirtualKey, sendAuthErrorResponse } from "./key-auth.js";
184
184
  import { logSpend } from "./spend-logger.js";
185
185
  import { hashKey } from "./virtual-keys.js";
186
+ import { STREAM_BACKPRESSURE_TIMEOUT_MS } from "./stream-guards.js";
186
187
 
187
188
  const proxyLogger = logger.child("proxy");
188
189
  const GENERIC_UPSTREAM_ERROR = "Upstream request failed";
@@ -334,7 +335,7 @@ export async function classifyUpstreamResponse(
334
335
  const rateLimitReason = classifyRateLimitReason(errorText, response.status);
335
336
  const providerResourceExhausted = rateLimitReason === "quota-exhausted";
336
337
  const cooldownMs = providerResourceExhausted
337
- ? providerId === DEFAULT_PROVIDER
338
+ ? providerId === DEFAULT_PROVIDER || providerId === "openai-codex"
338
339
  ? parseRetryAfterMs(
339
340
  errorText,
340
341
  response.headers,
@@ -761,7 +762,7 @@ function isFetchTransportError(err: unknown): boolean {
761
762
  return true;
762
763
  }
763
764
  if (err && typeof err === "object" && "code" in err) {
764
- return ["ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET"].includes(
765
+ return ["ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_SOCKET"].includes(
765
766
  String(err.code),
766
767
  );
767
768
  }
@@ -815,9 +816,12 @@ async function streamResponseBody(
815
816
  } | null>((resolve, reject) => {
816
817
  let settled = false;
817
818
  let idleTimer: ReturnType<typeof setTimeout> | null = null;
819
+ let backpressureTimer: ReturnType<typeof setTimeout> | null = null;
820
+ let waitingForDrain = false;
818
821
 
819
822
  const cleanup = (): void => {
820
823
  if (idleTimer) clearTimeout(idleTimer);
824
+ if (backpressureTimer) clearTimeout(backpressureTimer);
821
825
  nodeStream.off("data", onData);
822
826
  nodeStream.off("end", onEnd);
823
827
  nodeStream.off("error", onError);
@@ -825,6 +829,8 @@ async function streamResponseBody(
825
829
  req.off("close", onClientClose);
826
830
  res.off("close", onResponseClose);
827
831
  res.off("error", onResponseError);
832
+ res.off("drain", onDrain);
833
+ waitingForDrain = false;
828
834
  };
829
835
 
830
836
  const finish = (reason?: string): void => {
@@ -861,6 +867,31 @@ async function streamResponseBody(
861
867
  );
862
868
  };
863
869
 
870
+ const onDrain = (): void => {
871
+ if (!waitingForDrain) return;
872
+ waitingForDrain = false;
873
+ if (backpressureTimer) clearTimeout(backpressureTimer);
874
+ backpressureTimer = null;
875
+ if (!settled && !nodeStream.destroyed) nodeStream.resume();
876
+ };
877
+
878
+ const pauseForBackpressure = (): void => {
879
+ if (waitingForDrain || settled) return;
880
+ waitingForDrain = true;
881
+ nodeStream.pause();
882
+ backpressureTimer = setTimeout(() => {
883
+ backpressureTimer = null;
884
+ if (!waitingForDrain || settled) return;
885
+ const error = new Error(
886
+ `client backpressure timeout after ${Math.round(STREAM_BACKPRESSURE_TIMEOUT_MS / 1000)}s`,
887
+ );
888
+ emitStreamError(error);
889
+ finish(error.message);
890
+ if (!nodeStream.destroyed) nodeStream.destroy();
891
+ }, STREAM_BACKPRESSURE_TIMEOUT_MS);
892
+ res.once("drain", onDrain);
893
+ };
894
+
864
895
  const resetIdleTimer = (): void => {
865
896
  if (idleTimer) clearTimeout(idleTimer);
866
897
  idleTimer = setTimeout(() => {
@@ -882,7 +913,7 @@ async function streamResponseBody(
882
913
  if (!res.destroyed && !res.writableEnded) {
883
914
  if (!res.headersSent) res.writeHead(responseStatus, responseHeaders);
884
915
  hasForwardedBytes = true;
885
- res.write(chunk);
916
+ if (!res.write(chunk)) pauseForBackpressure();
886
917
  }
887
918
  // Extract usage from any newly-completed SSE events
888
919
  if (!firstUsage) {
@@ -1191,6 +1222,7 @@ export async function withRotation<T>(
1191
1222
  const maxAttempts = maxRetries + 1;
1192
1223
 
1193
1224
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
1225
+ const admissionStartedMs = Date.now();
1194
1226
  const account = await rotator.getActiveAccount(model, signal);
1195
1227
  if (!account) {
1196
1228
  if (signal?.aborted) {
@@ -1206,6 +1238,7 @@ export async function withRotation<T>(
1206
1238
  body.displayModel || model,
1207
1239
  body.model,
1208
1240
  );
1241
+ const queueWaitMs = Date.now() - admissionStartedMs;
1209
1242
  const requestId = `${modelKey}-${Date.now().toString(36)}-${attempt + 1}`;
1210
1243
  const requestStartMs = Date.now();
1211
1244
  let accountReleased = false;
@@ -1228,7 +1261,7 @@ export async function withRotation<T>(
1228
1261
  };
1229
1262
 
1230
1263
  log(
1231
- `[${requestId}] START account=${label} model=${model} attempt=${attempt + 1}`,
1264
+ `[${requestId}] START account=${label} model=${model} attempt=${attempt + 1} queueMs=${queueWaitMs}`,
1232
1265
  rotator,
1233
1266
  );
1234
1267
 
@@ -1634,6 +1667,7 @@ async function handleProxyRequest(
1634
1667
  const maxRetries = getStreamRecoveryMaxRetries(rotator);
1635
1668
  const maxAttempts = maxRetries + 1;
1636
1669
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
1670
+ const admissionStartedMs = Date.now();
1637
1671
  const account = await rotator.getActiveAccount(
1638
1672
  body.model,
1639
1673
  clientController.signal,
@@ -1647,6 +1681,7 @@ async function handleProxyRequest(
1647
1681
  const label = account.config.label || account.config.email;
1648
1682
  const modelKey = rotator.resolveQuotaModelKeyForDisplay(body.model) ?? body.model; // quota routing
1649
1683
  const displayModelKey = observedModelKey(rotator, body.model); // metrics/logs
1684
+ const queueWaitMs = Date.now() - admissionStartedMs;
1650
1685
  const requestId = `${modelKey}-${Date.now().toString(36)}-${attempt + 1}`;
1651
1686
  let accountReleased = false;
1652
1687
  const releaseCurrentAccount = (): void => {
@@ -1663,7 +1698,7 @@ async function handleProxyRequest(
1663
1698
  return nextAccount;
1664
1699
  };
1665
1700
  proxyLog(
1666
- `[${requestId}] START account=${label} model=${body.model} attempt=${attempt + 1}`,
1701
+ `[${requestId}] START account=${label} model=${body.model} attempt=${attempt + 1} queueMs=${queueWaitMs}`,
1667
1702
  );
1668
1703
  const requestStartMs = Date.now();
1669
1704
  const logRequestEnd = (status: string | number, extra = ""): void => {
@@ -24,6 +24,8 @@ export function classifyRateLimitReason(errorText: string, status?: number): Rat
24
24
  lower.includes("quotaresettimestamp") ||
25
25
  lower.includes("resource_exhausted") ||
26
26
  lower.includes("resource exhausted") ||
27
+ lower.includes("usage_limit_reached") ||
28
+ lower.includes("usage limit reached") ||
27
29
  lower.includes("daily limit") ||
28
30
  lower.includes("quota exceeded")
29
31
  ) {
@@ -88,6 +90,33 @@ export function parseRetryAfterMs(
88
90
  if (Number.isFinite(seconds) && seconds > 0) return Math.ceil(seconds * 1000 + 1000);
89
91
  }
90
92
 
93
+ const codexResetSecondsMatch = errorText.match(
94
+ /["']?resets_in_seconds["']?\s*:\s*["']?(\d+(?:\.\d+)?)/i,
95
+ );
96
+ if (codexResetSecondsMatch?.[1]) {
97
+ const seconds = Number(codexResetSecondsMatch[1]);
98
+ if (Number.isFinite(seconds) && seconds > 0) {
99
+ return Math.ceil(seconds * 1000 + 1000);
100
+ }
101
+ }
102
+
103
+ const codexResetAtMatch = errorText.match(
104
+ /["']?resets_at["']?\s*:\s*(?:["']([^"']+)["']|(\d{10,13}))/i,
105
+ );
106
+ if (codexResetAtMatch) {
107
+ const rawResetAt = codexResetAtMatch[1] ?? codexResetAtMatch[2];
108
+ const numericResetAt = Number(rawResetAt);
109
+ const resetAt = Number.isFinite(numericResetAt)
110
+ ? numericResetAt < 1_000_000_000_000
111
+ ? numericResetAt * 1000
112
+ : numericResetAt
113
+ : Date.parse(rawResetAt ?? "");
114
+ if (Number.isFinite(resetAt)) {
115
+ const delta = resetAt - Date.now();
116
+ if (delta > 0) return Math.ceil(delta + 1000);
117
+ }
118
+ }
119
+
91
120
  const quotaDelayMatch = errorText.match(/quotaResetDelay[:\s"]+(\d+(?:\.\d+)?)(ms|s)/i);
92
121
  if (quotaDelayMatch) {
93
122
  const value = parseFloat(quotaDelayMatch[1]);