Merge pull request '98K 欠费模型在充值后自动恢复' (#116) from codex/provider-balance-recovery into main
This commit is contained in:
commit
868104ea19
@ -20,4 +20,11 @@ export function register() {
|
|||||||
};
|
};
|
||||||
setTimeout(recover, 5000).unref?.();
|
setTimeout(recover, 5000).unref?.();
|
||||||
setInterval(recover, 60_000).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?.();
|
||||||
}
|
}
|
||||||
|
|||||||
50
lib/ai/providers/vip98k-token-usage.ts
Normal file
50
lib/ai/providers/vip98k-token-usage.ts
Normal file
@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -2,17 +2,19 @@ import "server-only";
|
|||||||
import { ProviderTaskUncertainError } from "@/lib/video-canvas/video-task-lifecycle";
|
import { ProviderTaskUncertainError } from "@/lib/video-canvas/video-task-lifecycle";
|
||||||
import { isProviderAuthenticationFailure, isCredentialFailureBan } from "./authentication-failover";
|
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 { db } from "@/lib/db";
|
||||||
import {
|
import {
|
||||||
aiModel,
|
aiModel,
|
||||||
aiModelHealthEvent,
|
aiModelHealthEvent,
|
||||||
|
aiProvider,
|
||||||
type AiModel,
|
type AiModel,
|
||||||
} from "@/lib/db/schema";
|
} from "@/lib/db/schema";
|
||||||
import {
|
import {
|
||||||
isMediaInputFailure,
|
isMediaInputFailure,
|
||||||
isNonProviderRequestStatus,
|
isNonProviderRequestStatus,
|
||||||
} from "@/lib/ai/runtime/request-failure-classification";
|
} 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";
|
import { getRequestFailureDetails, isGatewayResponseTimeout, isProviderBalanceError, isRateLimitError } from "@/lib/request-error";
|
||||||
|
|
||||||
export type AiModelHealthEventType =
|
export type AiModelHealthEventType =
|
||||||
@ -774,30 +776,126 @@ export async function recordAiModelHealthFailure(params: {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function restoredHealthValues(): Partial<AiModel> {
|
||||||
|
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) {
|
export async function restoreAiModelHealth(modelId: string) {
|
||||||
const normalizedModelId = normalizeText(modelId);
|
const normalizedModelId = normalizeText(modelId);
|
||||||
if (!normalizedModelId) return [];
|
if (!normalizedModelId) return [];
|
||||||
|
|
||||||
return await db
|
return db.update(aiModel)
|
||||||
.update(aiModel)
|
.set(restoredHealthValues())
|
||||||
.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(),
|
|
||||||
})
|
|
||||||
.where(eq(aiModel.id, normalizedModelId))
|
.where(eq(aiModel.id, normalizedModelId))
|
||||||
.returning();
|
.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<string>`${aiModel.updatedAt}::text`,
|
||||||
|
provider: {
|
||||||
|
id: aiProvider.id,
|
||||||
|
name: aiProvider.name,
|
||||||
|
baseUrl: aiProvider.baseUrl,
|
||||||
|
apiKey: aiProvider.apiKey,
|
||||||
|
version: sql<string>`${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<string, (typeof rows)[number][]>();
|
||||||
|
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 }) {
|
export async function listAiModelHealthEvents(params?: { modelId?: string; limit?: number }) {
|
||||||
const limit = Math.max(1, Math.min(params?.limit || RECENT_EVENT_LIMIT, 200));
|
const limit = Math.max(1, Math.min(params?.limit || RECENT_EVENT_LIMIT, 200));
|
||||||
const modelId = normalizeText(params?.modelId);
|
const modelId = normalizeText(params?.modelId);
|
||||||
|
|||||||
53
tests/routes/provider-balance-recovery.test.ts
Normal file
53
tests/routes/provider-balance-recovery.test.ts
Normal file
@ -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();
|
||||||
|
});
|
||||||
Loading…
x
Reference in New Issue
Block a user