From 79171a12828f60fef96b275574269740d23c6856 Mon Sep 17 00:00:00 2001 From: WuYongJie <549727955@qq.com> Date: Mon, 23 Nov 2026 13:17:51 +0800 Subject: [PATCH] Recover balance-disabled models after provider recharge --- instrumentation.ts | 7 + lib/ai/providers/vip98k-token-usage.ts | 50 +++++++ lib/ai/runtime/model-health.ts | 132 +++++++++++++++--- .../routes/provider-balance-recovery.test.ts | 53 +++++++ 4 files changed, 225 insertions(+), 17 deletions(-) create mode 100644 lib/ai/providers/vip98k-token-usage.ts create mode 100644 tests/routes/provider-balance-recovery.test.ts diff --git a/instrumentation.ts b/instrumentation.ts index 4845c2423..fc0170051 100644 --- a/instrumentation.ts +++ b/instrumentation.ts @@ -20,4 +20,11 @@ export function register() { }; setTimeout(recover, 5000).unref?.(); setInterval(recover, 60_000).unref?.(); + + const recoverBalanceDisabledModels = () => { + void import("@/lib/ai/runtime/model-health") + .then(({ recoverModelsAfterProviderRecharge }) => recoverModelsAfterProviderRecharge()) + .catch(() => console.warn("[AI Model Health] Balance recovery check failed")); + }; + setInterval(recoverBalanceDisabledModels, 5 * 60_000).unref?.(); } diff --git a/lib/ai/providers/vip98k-token-usage.ts b/lib/ai/providers/vip98k-token-usage.ts new file mode 100644 index 000000000..cdde8fd37 --- /dev/null +++ b/lib/ai/providers/vip98k-token-usage.ts @@ -0,0 +1,50 @@ +import { z } from "zod"; + +const amount = z.union([z.number(), z.string().trim().regex(/^-?\d+(?:\.\d+)?$/)]) + .transform(Number) + .pipe(z.number().finite()); + +const tokenUsageSchema = z.object({ + code: z.literal(true), + data: z.object({ + object: z.literal("token_usage"), + available_balance: amount, + currency: z.string().min(1), + total_available: amount, + unlimited_quota: z.boolean(), + api_key: z.object({ status: z.literal("active") }), + model_limits_enabled: z.boolean(), + model_limits: z.record(z.boolean()).nullable(), + }), +}); + +export function parseVip98kTokenUsage(value: unknown) { + const response = tokenUsageSchema.safeParse(value); + if (!response.success) return null; + const usage = response.data.data; + if (usage.model_limits_enabled && !usage.model_limits) return null; + + return { + currency: usage.currency.toUpperCase(), + available: usage.unlimited_quota + ? usage.available_balance + : Math.min(usage.available_balance, usage.total_available), + modelLimits: usage.model_limits_enabled ? usage.model_limits : null, + }; +} + +export async function readVip98kTokenUsage(provider: { baseUrl: string; apiKey: string }) { + try { + const address = new URL("/api/usage/token/", provider.baseUrl); + if (address.protocol !== "https:" || address.username || address.password) return null; + const response = await fetch(address, { + headers: { Authorization: `Bearer ${provider.apiKey}`, Accept: "application/json" }, + cache: "no-store", + redirect: "error", + signal: AbortSignal.timeout(5000), + }); + return response.ok ? parseVip98kTokenUsage(await response.json()) : null; + } catch { + return null; + } +} diff --git a/lib/ai/runtime/model-health.ts b/lib/ai/runtime/model-health.ts index f61f29e92..47ec6e077 100644 --- a/lib/ai/runtime/model-health.ts +++ b/lib/ai/runtime/model-health.ts @@ -2,17 +2,19 @@ import "server-only"; import { ProviderTaskUncertainError } from "@/lib/video-canvas/video-task-lifecycle"; import { isProviderAuthenticationFailure, isCredentialFailureBan } from "./authentication-failover"; -import { and, desc, eq, inArray, sql } from "drizzle-orm"; +import { and, desc, eq, exists, inArray, isNotNull, or, sql } from "drizzle-orm"; import { db } from "@/lib/db"; import { aiModel, aiModelHealthEvent, + aiProvider, type AiModel, } from "@/lib/db/schema"; import { isMediaInputFailure, isNonProviderRequestStatus, } from "@/lib/ai/runtime/request-failure-classification"; +import { readVip98kTokenUsage } from "@/lib/ai/providers/vip98k-token-usage"; import { getRequestFailureDetails, isGatewayResponseTimeout, isProviderBalanceError, isRateLimitError } from "@/lib/request-error"; export type AiModelHealthEventType = @@ -774,30 +776,126 @@ export async function recordAiModelHealthFailure(params: { } } +function restoredHealthValues(): Partial { + const now = new Date(); + return { + isEnabled: true, + healthStatus: "healthy", + healthConsecutiveFailures: 0, + healthLastEventType: "success", + healthLastError: null, + healthLastFailureAt: null, + healthAutoDisabledAt: null, + healthAutoDisabledReason: null, + healthRecoverySuccessStreak: 0, + healthObservationStartedAt: null, + healthUpdatedAt: now, + updatedAt: now, + }; +} + export async function restoreAiModelHealth(modelId: string) { const normalizedModelId = normalizeText(modelId); if (!normalizedModelId) return []; - return await db - .update(aiModel) - .set({ - isEnabled: true, - healthStatus: "healthy", - healthConsecutiveFailures: 0, - healthLastEventType: "success", - healthLastError: null, - healthLastFailureAt: null, - healthAutoDisabledAt: null, - healthAutoDisabledReason: null, - healthRecoverySuccessStreak: 0, - healthObservationStartedAt: null, - healthUpdatedAt: new Date(), - updatedAt: new Date(), - }) + return db.update(aiModel) + .set(restoredHealthValues()) .where(eq(aiModel.id, normalizedModelId)) .returning(); } +function getVip98kPrice(capabilities: AiModel["capabilities"]) { + const config = capabilities as { + vip98k?: { pricing?: { currency?: unknown; effective_price?: unknown } }; + } | null; + const pricing = config?.vip98k?.pricing; + if (typeof pricing?.currency !== "string" || typeof pricing.effective_price !== "number" || + !Number.isFinite(pricing.effective_price) || pricing.effective_price <= 0) { + return null; + } + return { currency: pricing.currency.toUpperCase(), amount: pricing.effective_price }; +} + +export async function recoverModelsAfterProviderRecharge() { + const stoppedForHealth = and( + eq(aiModel.isEnabled, false), + eq(aiModel.healthStatus, "auto_disabled"), + isNotNull(aiModel.healthAutoDisabledAt), + ); + const rows = await db.select({ + id: aiModel.id, + modelId: aiModel.modelId, + capabilities: aiModel.capabilities, + reason: aiModel.healthAutoDisabledReason, + version: sql`${aiModel.updatedAt}::text`, + provider: { + id: aiProvider.id, + name: aiProvider.name, + baseUrl: aiProvider.baseUrl, + apiKey: aiProvider.apiKey, + version: sql`${aiProvider.updatedAt}::text`, + }, + }).from(aiModel) + .innerJoin(aiProvider, eq(aiModel.providerId, aiProvider.id)) + .where(and(stoppedForHealth, eq(aiProvider.isEnabled, true), eq(aiProvider.type, "vip98k"))); + + const byProvider = new Map(); + for (const row of rows) { + if (!isProviderBalanceError(row.reason)) continue; + const group = byProvider.get(row.provider.id) ?? []; + group.push(row); + byProvider.set(row.provider.id, group); + } + + for (const group of byProvider.values()) { + const { provider } = group[0]!; + const usage = await readVip98kTokenUsage(provider); + if (!usage || usage.available <= 0) continue; + const eligible = group.filter(({ modelId, capabilities }) => { + if (usage.modelLimits && usage.modelLimits[modelId] !== true) return false; + const price = getVip98kPrice(capabilities); + return !price || (price.currency === usage.currency && usage.available >= price.amount); + }); + if (!eligible.length) continue; + + const recovered = await db.transaction(async (tx) => { + const models = await tx.update(aiModel) + .set(restoredHealthValues()) + .where(and( + stoppedForHealth, + eq(aiModel.providerId, provider.id), + exists(tx.select({ id: aiProvider.id }).from(aiProvider).where(and( + eq(aiProvider.id, provider.id), + eq(aiProvider.isEnabled, true), + sql`${aiProvider.updatedAt} = ${provider.version}::timestamp`, + ))), + or(...eligible.map((model) => and( + eq(aiModel.id, model.id), + sql`${aiModel.updatedAt} = ${model.version}::timestamp`, + ))), + )) + .returning({ id: aiModel.id, runtimeId: aiModel.modelId, displayName: aiModel.displayName }); + if (models.length) await tx.insert(aiModelHealthEvent).values(models.map((model) => ({ + modelId: model.id, + providerId: provider.id, + modelRuntimeId: model.runtimeId, + modelDisplayName: model.displayName, + providerType: "vip98k", + providerName: provider.name, + eventType: "success", + severity: "info", + context: "provider_balance_recovery", + counted: false, + }))); + return models; + }); + if (recovered.length) console.info("[AI Model Health] Restored models after provider recharge", { + providerId: provider.id, + count: recovered.length, + }); + } +} + export async function listAiModelHealthEvents(params?: { modelId?: string; limit?: number }) { const limit = Math.max(1, Math.min(params?.limit || RECENT_EVENT_LIMIT, 200)); const modelId = normalizeText(params?.modelId); diff --git a/tests/routes/provider-balance-recovery.test.ts b/tests/routes/provider-balance-recovery.test.ts new file mode 100644 index 000000000..ba1f67f81 --- /dev/null +++ b/tests/routes/provider-balance-recovery.test.ts @@ -0,0 +1,53 @@ +import { expect, test } from "@playwright/test"; +import { parseVip98kTokenUsage } from "@/lib/ai/providers/vip98k-token-usage"; + +const usage = { + code: true, + data: { + object: "token_usage", + available_balance: "12.30", + currency: "CNY", + total_available: 0, + unlimited_quota: true, + api_key: { status: "active" }, + model_limits_enabled: false, + model_limits: {}, + }, +}; + +test("uses the prepaid balance for a key with unlimited key quota", () => { + expect(parseVip98kTokenUsage(usage)).toMatchObject({ available: 12.3 }); + expect(parseVip98kTokenUsage({ + ...usage, + data: { ...usage.data, available_balance: "0.00" }, + })).toMatchObject({ available: 0 }); +}); + +test("limits recovery by the remaining key quota and model permissions", () => { + expect(parseVip98kTokenUsage({ + ...usage, + data: { + ...usage.data, + unlimited_quota: false, + total_available: 0.5, + model_limits_enabled: true, + model_limits: { "nano-banana-2.1": true }, + }, + })).toMatchObject({ available: 0.5, modelLimits: { "nano-banana-2.1": true } }); + expect(parseVip98kTokenUsage({ + ...usage, + data: { ...usage.data, unlimited_quota: false }, + })).toMatchObject({ available: 0 }); +}); + +test("requires explicit billing data and an active key", () => { + for (const data of [ + { ...usage.data, available_balance: null }, + { ...usage.data, available_balance: " " }, + { ...usage.data, api_key: { status: "disabled" } }, + { ...usage.data, model_limits_enabled: true, model_limits: null }, + ]) { + expect(parseVip98kTokenUsage({ code: true, data })).toBeNull(); + } + expect(parseVip98kTokenUsage({ ...usage, code: false })).toBeNull(); +});