Files
OmniRoute/open-sse/config/constants.ts
Paijo 3238df3204 perf: lazy provider init, P2C quota cache, structuredClone elimination, getSettings→getCachedSettings (batch 2) (#7893)
* perf: startup parallelization, stream TextEncoder lift, auth middleware bottlenecks

Startup (~100-300ms faster cold start):
- Parallelize 4 early imports via Promise.all() in registerNodejs()
- Parallelize 10 independent background services via Promise.allSettled()
- Each service has independent try/catch — no failure domino effect

Streaming pipeline (8 fewer TextEncoder GC allocations per SSE event):
- Lift new TextEncoder() from per-chunk inside buildClaudeStreamingResponse
  to function scope alongside existing decoder singleton

Auth middleware bottlenecks (from PerfBottleneckAnalysis):
- Backoff decay loop: replace updateProviderConnection (full CRUD:
  SELECT+encrypt+cache-invalidate+backup) with resetConnectionBackoff
  (targeted UPDATE of backoff/error columns only)
- Dual .filter() for quota: replace two passes calling
  isQuotaExhaustedForRequest per connection with a single for loop
  partitioning into withQuota/exhaustedQuota
- Debug-log filter recomputation: capture connectionFilterStatus Map
  during the filter pass; debug loop reads 6 string comparisons instead
  of 6 function calls per connection

Supporting:
- Add resetConnectionBackoff to src/lib/db/providers.ts (patterned after
  clearConnectionErrorIfUnchanged, no CAS check)
- Re-export resetConnectionBackoff from src/lib/localDb.ts
- Update integration-wiring.test.ts regex for parallelized dynamic import

* perf: P2C quota cache, lazy provider init, structuredClone elimination, getSettings→getCachedSettings

- **auth.ts: P2C quota re-evaluation cache** — quotaResults Map threaded
  through selectPoolSubset → compareP2CConnections → getP2CConnectionScore.
  Populated during filter + partition passes, eliminating redundant
  evaluateQuotaLimitPolicy / isQuotaExhaustedForRequest calls when the
  P2C comparator re-evaluates previously-scored connections.
- **constants.ts: lazy PROVIDERS via Proxy** — replaces eager
  generateLegacyProviders() + loadProviderCredentials() at module load
  with Proxy delegating to deferred init on first property access.
- **providerModels.ts: lazy PROVIDER_MODELS + PROVIDER_ID_TO_ALIAS** —
  same Proxy pattern for both exports; generateModels()/generateAliasMap()
  deferred until first read.
- **stream.ts: structuredClone → minimal object spread** — replaces
  O(n) deep clone of SSE response chunks with targeted reconstruction
  of only mutated fields (usage, delta.content, finish_reason).
- **progressTracker.ts: TextDecoder lift** — module-level decoder
  instead of per-chunk new TextDecoder().
- **Route files: getSettings() → getCachedSettings()** — 13 API route
  files converted from uncached per-request DB reads to TTL-cached
  wrapper (5s default), eliminating redundant queries on every request.
- **settings.ts: re-export getCachedSettings** from readCache for
  non-localDb consumers.
- **Remove settingsCache.ts** — dead file, no imports reference it.

TS compile: 0 errors. Auth tests: 225/225 pass. Services: 269/269 pass.

* perf: Phase 1 tangible wins — egressCache eviction, mmap_size PRAGMA, composite indexes, proxyFallback lazy import

- egressCache: lazy TTL eviction on getCachedEgressIp access (bounds memory
  leak to distinct proxy URLs, typically <100)
- mmap_size: apply stored PRAGMA from key_value table (256MiB default) after
  applyStoredDatabaseOptimizationSettings — setting was stored but never applied
- schemaColumns: add idx_uh_provider_model_timestamp (covers getModelLatencyStats)
  and idx_pc_provider_auth_type (covers 6+ provider_connections queries)
- proxyFallback: convert static import to dynamic import() inside error handler
  (defers 210ms module load from startup to first proxy-retry scenario)

* perf: add dedup expression index, unref() sweep timers

- Add COALESCE expression index idx_uh_dedup on usage_history
  matching the exact dedup query pattern. Eliminates FULL TABLE
  SCAN on every saveRequestUsage insert.
- Add composite idx_uh_provider_model_timestamp on usage_history.
- Add composite idx_pc_provider_auth_type on provider_connections.
- Add .unref() to setInterval in batchProcessor.ts (polling loop).
- Add .unref() to setInterval in runtimeHeartbeat.ts (heartbeat).

* perf: bump SQLite cache_size default from 16MB to 64MB

New installs now start with 64MB page cache (was 16MB). Existing
users' stored settings are unchanged. Reduces disk reads for the
typical ~250MB database by keeping ~25% of pages in memory.

Also resolved pre-existing merge conflict in webhooks.ts.

* docs: add Redis production config guide and proxy port clash investigation report

- docs/redis-production-config.md: comprehensive Redis tuning guide
  covering client options, server config, Docker settings, scaling,
  and monitoring for all three Redis workloads (rate limiting,
  auth cache, quota store)
- docs/proxy-port-clash-report.md: investigation confirming proxy
  subsystem has no port binding issues; real EADDRINUSE history
  traced to process supervisor crash-loop restart race (#4425) and
  live-dashboard port clash (#6324), both already fixed

* fix: address PR #7893 review — add Proxy traps, extract migrations to reduce providers.ts size

- Add set trap to PROVIDER_ID_TO_ALIAS Proxy (providerModels.ts)
- Add deleteProperty traps to all three lazy Proxies (PROVIDERS,
  PROVIDER_MODELS, PROVIDER_ID_TO_ALIAS)
- Extract autoMigrateLegacyEncryptedConnections and getGheCopilotHosts
  from providers.ts (1129→1036 lines, -93) into providers/migrations.ts
- Both functions re-exported via providers.ts for backward compat

File-size ratchet resolved: src/lib/db/providers.ts now 1036 lines.

* fix: resolve merge conflict markers in 3 route/test files

- model-combo-mappings/route.ts: kept upstream version (Zod pagination
  via validateBody + isValidationFailure), restored missing return
  statement for GET handler
- playground/presets/route.ts: kept stashed version details (satisfies
  type-narrowing + inlined Response) — functionally identical
- error-sanitization.test.ts: matches upstream exactly (no diff)

Test verification: same 7 pre-existing failures confirmed on upstream
baseline (c1bdd91e7). Zero regressions from conflict resolution.

Closes remaining uncommitted work from PR #7046 rebase.

* test(db): add resetConnectionBackoff coverage + fix file-size ratchet regression

- Add tests/unit/reset-connection-backoff.test.ts: covers the new
  resetConnectionBackoff lightweight-UPDATE helper (clears backoff/error
  columns and re-activates a connection, unconditional-write behavior on
  terminal statuses, no-op for empty/unknown ids). Zero prior coverage
  per pre-merge review of PR #7893 (Hard Rule #8).
- open-sse/services/batchProcessor.ts: fold the new unref() call into the
  existing setInterval(...).unref() chain instead of a separate statement,
  keeping the file at the frozen 915-line ratchet (Timeout.unref() already
  returns `this`, so no type cast is needed).
- src/lib/localDb.ts: drop one blank separator line so the new
  resetConnectionBackoff re-export stays within the frozen 808-line ratchet.

Pre-merge fix for PR #7893 (perf/startup-stream-auth-optimizations) per
/green-prs plan-file _tasks/pipeline/prs/1-analyzed/7893-*.plan.md.

Co-authored-by: Diego Rodrigues de Sa e Souza <diegosouzapw@users.noreply.github.com>

---------

Co-authored-by: oyi77 <oyi77@users.noreply.github.com>
Co-authored-by: Diego Rodrigues de Sa e Souza <diegosouza.pw@gmail.com>
Co-authored-by: Diego Rodrigues de Sa e Souza <diegosouzapw@users.noreply.github.com>
2026-07-21 11:50:14 -03:00

318 lines
14 KiB
TypeScript

import { getUpstreamTimeoutConfig } from "@/shared/utils/runtimeTimeouts";
import type { LegacyProvider } from "./providerRegistry.ts";
import { loadProviderCredentials } from "./credentialLoader.ts";
import { generateLegacyProviders } from "./providerRegistry.ts";
const upstreamTimeouts = getUpstreamTimeoutConfig(process.env, (message) => {
console.warn(`[open-sse] ${message}`);
});
// Timeout for receiving the initial upstream response (ms).
// After headers arrive, active SSE streams are governed by STREAM_IDLE_TIMEOUT_MS
// and Undici's bodyTimeout instead of this one-shot startup timer.
export const FETCH_TIMEOUT_MS = upstreamTimeouts.fetchTimeoutMs;
// Idle timeout for SSE streams (ms). Before a stream is accepted, the same
// budget is used to wait for the first useful event so HTTP 200 zombie streams
// can fail fast and trigger fallback. After startup, it closes streams that go
// idle for this duration. Override with STREAM_IDLE_TIMEOUT_MS env var.
export const STREAM_IDLE_TIMEOUT_MS = upstreamTimeouts.streamIdleTimeoutMs;
// Timeout for the first non-ping SSE event. Inherits REQUEST_TIMEOUT_MS when
// set, unless STREAM_READINESS_TIMEOUT_MS is specified directly. This must stay
// conservative for large prompts and slow first-byte reasoning providers.
export const STREAM_READINESS_TIMEOUT_MS = upstreamTimeouts.streamReadinessTimeoutMs;
// Upper bound for adaptive stream readiness extensions (large histories,
// tool-heavy requests, high-reasoning Codex targets). Override with
// STREAM_READINESS_MAX_TIMEOUT_MS when an operator needs longer first-event
// windows for slow-thinking agent workloads.
export const STREAM_READINESS_MAX_TIMEOUT_MS = upstreamTimeouts.streamReadinessMaxTimeoutMs;
// Error code used when an upstream Antigravity request stalls before response
// headers are returned. Keep it shared so executor, core normalization and
// account fallback detection cannot drift.
export const ANTIGRAVITY_PRE_RESPONSE_TIMEOUT_CODE = "ANTIGRAVITY_PRE_RESPONSE_TIMEOUT";
// Heartbeat interval for synthetic SSE keepalive emission toward the downstream
// client (Capy, Claude Code, OpenAI SDK, etc). Keeps strict proxies from
// dropping the connection during long upstream thinking phases. Set to 0 to
// disable. Override with SSE_HEARTBEAT_INTERVAL_MS env var.
export const SSE_HEARTBEAT_INTERVAL_MS = upstreamTimeouts.sseHeartbeatIntervalMs;
// Timeout for reading the full response body after headers arrive (ms).
// Prevents indefinite hangs when the upstream sends headers but stalls on the body.
// Defaults to FETCH_TIMEOUT_MS. Override with FETCH_BODY_TIMEOUT_MS env var.
export const FETCH_BODY_TIMEOUT_MS = upstreamTimeouts.fetchBodyTimeoutMs;
// Provider configurations
// OAuth credentials read from env vars with hardcoded fallbacks for backward compatibility.
// Use provider-credentials.json or env vars to override in production.
// Lazy PROVIDERS: deferred until first property access to speed up startup.
// The Proxy defers `generateLegacyProviders()` + `loadProviderCredentials()`
// from module-evaluation time to the first read of any provider property.
let _providers: Record<string, LegacyProvider> | null = null;
function initProviders(): Record<string, LegacyProvider> {
if (!_providers) {
const p = generateLegacyProviders();
loadProviderCredentials(p);
_providers = p;
}
return _providers;
}
export const PROVIDERS: Record<string, LegacyProvider> = new Proxy(
{} as Record<string, LegacyProvider>,
{
get(_, prop) {
if (typeof prop === 'symbol') return undefined;
return Reflect.get(initProviders(), prop, _providers);
},
has(_, prop) {
if (typeof prop === 'symbol') return false;
return Reflect.has(initProviders(), prop);
},
ownKeys() {
return Reflect.ownKeys(initProviders());
},
getOwnPropertyDescriptor(_, prop) {
if (typeof prop === 'symbol') return undefined;
return Object.getOwnPropertyDescriptor(initProviders(), prop);
},
set(_, prop, value) {
if (typeof prop === 'symbol') return false;
(initProviders() as Record<string, LegacyProvider>)[prop] = value;
return true;
},
deleteProperty(_, prop) {
if (typeof prop === 'symbol') return false;
return Reflect.deleteProperty(initProviders(), prop);
},
}
);
// Claude system prompt
export const CLAUDE_SYSTEM_PROMPT = "You are Claude Code, Anthropic's official CLI for Claude.";
// Antigravity default system prompt (required for API to work)
export const ANTIGRAVITY_DEFAULT_SYSTEM =
"You are Antigravity, a powerful agentic AI coding assistant designed by the Google Deepmind team working on Advanced Agentic Coding.\n" +
"You are pair programming with a USER to solve their coding task. The task may require creating a new codebase, modifying or debugging an existing codebase, or simply answering a question.\n" +
"**Absolute paths only**\n" +
"**Proactiveness**";
// OAuth endpoints
export const OAUTH_ENDPOINTS = {
google: {
token: "https://oauth2.googleapis.com/token",
auth: "https://accounts.google.com/o/oauth2/auth",
},
openai: {
token: "https://auth.openai.com/oauth/token",
auth: "https://auth.openai.com/oauth/authorize",
},
anthropic: {
token: "https://api.anthropic.com/v1/oauth/token",
auth: "https://api.anthropic.com/v1/oauth/authorize",
},
qoder: {
token: process.env.QODER_OAUTH_TOKEN_URL || "",
auth: process.env.QODER_OAUTH_AUTHORIZE_URL || "",
},
github: {
token: "https://github.com/login/oauth/access_token",
auth: "https://github.com/login/oauth/authorize",
deviceCode: "https://github.com/login/device/code",
},
};
// Cache TTLs (seconds)
export const CACHE_TTL = {
userInfo: 300, // 5 minutes
modelAlias: 3600, // 1 hour
};
// Default max tokens
export const DEFAULT_MAX_TOKENS = 64000;
// Minimum max tokens for tool calling (to prevent truncated arguments)
export const DEFAULT_MIN_TOKENS = 32000;
export const PROVIDER_MAX_TOKENS: Record<string, number> = {
groq: 16384, // Groq strict per-model enforcement
openai: 16384, // GPT-4/4o standard
anthropic: 65536, // Claude models
gemini: 65536, // Gemini Studio
sensenova: 65536, // SenseNova Token Plan rejects MaxTokens outside [1, 65536]
};
export const DEFAULT_PROVIDER_MAX_TOKENS = 32000;
// HTTP status codes
export const HTTP_STATUS = {
BAD_REQUEST: 400,
UNAUTHORIZED: 401,
PAYMENT_REQUIRED: 402,
FORBIDDEN: 403,
NOT_FOUND: 404,
NOT_ACCEPTABLE: 406,
REQUEST_TIMEOUT: 408,
RATE_LIMITED: 429,
SERVER_ERROR: 500,
BAD_GATEWAY: 502,
SERVICE_UNAVAILABLE: 503,
GATEWAY_TIMEOUT: 504,
};
export {
BACKOFF_CONFIG,
COOLDOWN_MS,
DEFAULT_ERROR_MESSAGES,
ERROR_RULES,
ERROR_TYPES,
TRANSIENT_COOLDOWN_MS,
calculateBackoffCooldown,
findMatchingErrorRule,
getDefaultErrorMessage,
getErrorInfo,
matchErrorRuleByStatus,
matchErrorRuleByText,
} from "./errorConfig.ts";
// Configurable backoff steps for rate limits (Phase 1 — enhanced rate limiting)
// Used for per-model lockouts with increasing severity
export const BACKOFF_STEPS_MS = [60_000, 120_000, 300_000, 600_000, 1_200_000];
// 1min → 2min → 5min → 10min → 20min
// Structured error classification for rate limiting decisions
export const RateLimitReason = {
QUOTA_EXHAUSTED: "quota_exhausted", // Daily/monthly quota depleted
RATE_LIMIT_EXCEEDED: "rate_limit_exceeded", // RPM/RPD limits hit
MODEL_CAPACITY: "model_capacity", // Model overloaded (529, 503)
SERVER_ERROR: "server_error", // 5xx errors
AUTH_ERROR: "auth_error", // 401, 403
UNKNOWN: "unknown",
};
// ─── Provider Resilience Profiles ───────────────────────────────────────────
// Separate behavior for OAuth (low-limit, session-based) vs API Key (high-limit, metered)
// Circuit-breaker thresholds and reset windows are overridable via
// OMNIROUTE_CIRCUIT_BREAKER_* env vars so operators can dampen or harden
// behavior without recompiling.
function envInt(name: string, fallback: number): number {
const raw = process.env[name];
if (raw === undefined || raw === null || raw === "") return fallback;
const parsed = Number(raw);
return Number.isFinite(parsed) && parsed >= 0 ? parsed : fallback;
}
export const PROVIDER_PROFILES = {
oauth: {
transientCooldown: 5000, // 5s (session tokens — short recovery)
rateLimitCooldown: 60000, // 60s default when no retry-after header
maxBackoffLevel: 8, // Higher ceiling (sessions may stay bad longer)
circuitBreakerThreshold: envInt("OMNIROUTE_CIRCUIT_BREAKER_OAUTH_THRESHOLD", 8),
circuitBreakerReset: envInt("OMNIROUTE_CIRCUIT_BREAKER_OAUTH_RESET_MS", 60000),
// Provider-level circuit breaker (entire provider cooldown after repeated failures)
providerFailureThreshold: 10, // Scaled for 500+ connections (was 3)
providerFailureWindowMs: 900000, // 15min window (was 10min)
providerCooldownMs: 300000, // 5min cooldown when threshold reached
// Adaptive circuit breaker v2 settings
degradationThreshold: 5, // Enter DEGRADED at this many failures
maxBackoffMultiplier: 8, // Max 8x resetTimeout escalation
backoffEscalationCount: 2, // Escalate after 2 open cycles
},
apikey: {
transientCooldown: 3000, // 3s (API providers recover faster)
rateLimitCooldown: 0, // 0 = respect retry-after header from provider
maxBackoffLevel: 5, // Lower ceiling (API quotas reset at known intervals)
circuitBreakerThreshold: envInt("OMNIROUTE_CIRCUIT_BREAKER_API_KEY_THRESHOLD", 12),
circuitBreakerReset: envInt("OMNIROUTE_CIRCUIT_BREAKER_API_KEY_RESET_MS", 30000),
// Provider-level circuit breaker (entire provider cooldown after repeated failures)
providerFailureThreshold: 15, // Scaled for 500+ connections (was 5)
providerFailureWindowMs: 1800000, // 30min window (was 20min)
providerCooldownMs: 600000, // 10min cooldown when threshold reached
degradationThreshold: 7,
maxBackoffMultiplier: 4,
backoffEscalationCount: 3,
},
// Local providers (localhost inference backends like Ollama, LM Studio, oMLX).
// Not yet wired into getProviderProfile() — will be used when local provider_nodes
// are integrated into the resilience layer. Kept here to avoid a second constants change.
local: {
transientCooldown: 2000, // 2s (local — very fast recovery)
rateLimitCooldown: 5000, // 5s (local — no real rate limits)
maxBackoffLevel: 3, // Low ceiling (local either works or doesn't)
circuitBreakerThreshold: envInt("OMNIROUTE_CIRCUIT_BREAKER_LOCAL_THRESHOLD", 2),
circuitBreakerReset: envInt("OMNIROUTE_CIRCUIT_BREAKER_LOCAL_RESET_MS", 15000),
// Provider-level circuit breaker (entire provider cooldown after repeated failures)
providerFailureThreshold: 2, // 2 failures trigger provider cooldown
providerFailureWindowMs: 300000, // 5min window for counting failures
providerCooldownMs: 60000, // 1min cooldown when threshold reached
},
};
// Default rate limit values for API Key providers (auto-enabled safety net)
// These are intentionally HIGH — they won't restrict normal usage.
// Real limits are learned from provider response headers.
export const DEFAULT_API_LIMITS = {
requestsPerMinute: 60, // 60 RPM (reduced from 100 — saves Bottleneck queue memory)
minTimeBetweenRequests: 350, // 350ms minimum gap (increased from 200)
concurrentRequests: 6, // Max 6 parallel per provider (reduced from 10)
};
// Skip patterns - requests containing these texts will bypass provider
export const SKIP_PATTERNS = ["Please write a 5-10 word title for the following conversation:"];
// Default maximum number of tools allowed in a request (OpenAI default)
export const MAX_TOOLS_LIMIT = 128;
// ── Credential Health Check ────────────────────────────────────────
/**
* Interval (ms) for the background credential health check scheduler.
* Default: 300000 (5 minutes). Minimum: 10000 (10 seconds).
*/
export const CREDENTIAL_HEALTH_CHECK_INTERVAL = (() => {
const raw = process.env.CREDENTIAL_HEALTH_CHECK_INTERVAL;
if (raw) {
const parsed = Number(raw);
if (Number.isFinite(parsed) && parsed >= 10_000) return parsed;
}
return 300_000;
})();
/**
* TTL (ms) for cached credential health status.
* After this time, the cache entry expires and the next request will
* re-check. Default: 300000 (5 minutes).
*/
export const CREDENTIAL_HEALTH_CACHE_TTL = (() => {
const raw = process.env.CREDENTIAL_HEALTH_CACHE_TTL;
if (raw) {
const parsed = Number(raw);
if (Number.isFinite(parsed) && parsed >= 10_000) return parsed;
}
return 300_000;
})();
/**
* Stream-recovery tuning (opt-in, see ResilienceSettings.streamRecovery).
*
* Ported from free-claude-code's always-on recovery (`core/anthropic/stream_recovery.py`).
* In OmniRoute the holdback is disabled by default because buffering the opening
* window adds up to HOLDBACK_MS of time-to-first-token latency on every stream;
* operators opt in via STREAM_RECOVERY_ENABLED / the resilience settings.
*
* - HOLDBACK_MS: how long the opening SSE window is held so an early truncation
* can be retried transparently before any byte reaches the client.
* - BUFFER_MAX_BYTES: hard cap on the held window — commit (flush + passthrough)
* as soon as this many bytes accumulate, regardless of the timer.
* - EARLY_RETRY_MAX: max transparent re-opens of the upstream stream while the
* holdback is still uncommitted (free-claude-code uses 5 total attempts = 4 retries).
*/
export const STREAM_RECOVERY = {
HOLDBACK_MS: 750,
BUFFER_MAX_BYTES: 65536,
EARLY_RETRY_MAX: 4,
} as const;