Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

1.4 KB
Raw Blame
/**
 * connectionProvider.ts — Resolve the provider name for a quota-governed
 * connection.
 *
 * A `QuotaPool` (and the pool-usage route) only carries a `connectionId`, not
 * the provider name. To resolve the connection's plan via the catalog
 * (`resolvePlan(connectionId, provider)`) we must look the provider up from the
 * `provider_connections` row. `getProviderConnectionById` is async, so this
 * MUST be awaited — a previous private copy in the plans route omitted the
 * await and silently degraded every catalog lookup to "unknown".
 *
 * Fail-safe: returns "unknown" if the DB is unavailable or the connection is
 * missing, so callers degrade to an empty/manual plan rather than throwing.
 *
 * Part of: Group B — Quota Sharing Engine (plan 22).
 */

export async function resolveConnectionProvider(connectionId: string): Promise<string> {
  try {
    // Lazy import — avoids circular deps and keeps the module loadable without a full DB.
    const { getCachedProviderConnectionById } = await import("@/lib/db/readCache");
    if (typeof getCachedProviderConnectionById === "function") {
      const conn = await getCachedProviderConnectionById(connectionId);
      if (conn && typeof (conn as { provider?: string }).provider === "string") {
        return (conn as { provider: string }).provider;
      }
    }
  } catch {
    // DB not available or export not present — fall through to the safe default.
  }
  return "unknown";
}