mirror of
https://github.com/fawney19/Aether.git
synced 2026-09-02 01:10:23 +08:00
fix(pool): 修复 Codex 配额倒计时不准确 (#297)
* fix(pool): 修复 Codex 配额倒计时不准确 - 后端号池 keys payload 增加 upstream_metadata 透传 - 前端补充 PoolKeyDetail.upstream_metadata 与 Codex reset_after_seconds 类型 - 号池页倒计时优先使用 reset_at/reset_seconds/updated_at 结构化数据计算 - 仅在缺少结构化字段时回退 account_quota 文案解析 * fix(pool): 将已重置的 Codex 配额恢复为 100% - reset_after_seconds/reset_seconds 会按 updated_at 扣减经过时间(不再当作静态值) - 若窗口已重置(剩余秒数 <= 0),该窗口 used_percent 按 0 处理
This commit is contained in:
@@ -243,29 +243,50 @@ fn admin_pool_build_codex_account_quota(
|
|||||||
reset_seconds_key: &str,
|
reset_seconds_key: &str,
|
||||||
reset_after_seconds_key: &str,
|
reset_after_seconds_key: &str,
|
||||||
reset_at_key: &str,
|
reset_at_key: &str,
|
||||||
|
now_unix_secs: u64,
|
||||||
|
updated_at_unix_secs: Option<u64>,
|
||||||
) -> Option<f64> {
|
) -> Option<f64> {
|
||||||
admin_pool_json_to_f64(data.get(reset_seconds_key))
|
if let Some(reset_at) = admin_pool_json_to_u64(data.get(reset_at_key)) {
|
||||||
.or_else(|| admin_pool_json_to_f64(data.get(reset_after_seconds_key)))
|
return Some(reset_at.saturating_sub(now_unix_secs) as f64);
|
||||||
.or_else(|| {
|
}
|
||||||
let reset_at = admin_pool_json_to_u64(data.get(reset_at_key))?;
|
|
||||||
let now_unix_secs = chrono::Utc::now().timestamp().max(0) as u64;
|
let remaining = admin_pool_json_to_f64(data.get(reset_seconds_key))
|
||||||
Some(reset_at.saturating_sub(now_unix_secs) as f64)
|
.or_else(|| admin_pool_json_to_f64(data.get(reset_after_seconds_key)))?;
|
||||||
})
|
let elapsed = updated_at_unix_secs
|
||||||
|
.map(|updated_at| now_unix_secs.saturating_sub(updated_at) as f64)
|
||||||
|
.unwrap_or(0.0);
|
||||||
|
Some((remaining - elapsed).max(0.0))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn codex_effective_used_percent(used_percent: f64, reset_seconds: Option<f64>) -> f64 {
|
||||||
|
let normalized = used_percent.clamp(0.0, 100.0);
|
||||||
|
if normalized <= 1e-6 {
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
if reset_seconds.is_some_and(|value| value <= 0.0) {
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
normalized
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut parts = Vec::new();
|
let mut parts = Vec::new();
|
||||||
|
let now_unix_secs = chrono::Utc::now().timestamp().max(0) as u64;
|
||||||
|
let updated_at_unix_secs = admin_pool_json_to_u64(data.get("updated_at"));
|
||||||
|
|
||||||
let primary_used = admin_pool_json_to_f64(data.get("primary_used_percent"));
|
let primary_used_raw = admin_pool_json_to_f64(data.get("primary_used_percent"));
|
||||||
if let Some(primary_used) = primary_used {
|
if let Some(primary_used_raw) = primary_used_raw {
|
||||||
|
let primary_reset_seconds = codex_reset_seconds(
|
||||||
|
data,
|
||||||
|
"primary_reset_seconds",
|
||||||
|
"primary_reset_after_seconds",
|
||||||
|
"primary_reset_at",
|
||||||
|
now_unix_secs,
|
||||||
|
updated_at_unix_secs,
|
||||||
|
);
|
||||||
|
let primary_used = codex_effective_used_percent(primary_used_raw, primary_reset_seconds);
|
||||||
let mut part = format!("周剩余 {}", admin_pool_format_percent(100.0 - primary_used));
|
let mut part = format!("周剩余 {}", admin_pool_format_percent(100.0 - primary_used));
|
||||||
if admin_pool_has_quota_consumption(Some(primary_used)) {
|
if admin_pool_has_quota_consumption(Some(primary_used)) {
|
||||||
if let Some(reset_text) = codex_reset_seconds(
|
if let Some(reset_text) = primary_reset_seconds.and_then(admin_pool_format_reset_after)
|
||||||
data,
|
|
||||||
"primary_reset_seconds",
|
|
||||||
"primary_reset_after_seconds",
|
|
||||||
"primary_reset_at",
|
|
||||||
)
|
|
||||||
.and_then(admin_pool_format_reset_after)
|
|
||||||
{
|
{
|
||||||
part.push_str(&format!(" ({reset_text})"));
|
part.push_str(&format!(" ({reset_text})"));
|
||||||
}
|
}
|
||||||
@@ -273,20 +294,25 @@ fn admin_pool_build_codex_account_quota(
|
|||||||
parts.push(part);
|
parts.push(part);
|
||||||
}
|
}
|
||||||
|
|
||||||
let secondary_used = admin_pool_json_to_f64(data.get("secondary_used_percent"));
|
let secondary_used_raw = admin_pool_json_to_f64(data.get("secondary_used_percent"));
|
||||||
if let Some(secondary_used) = secondary_used {
|
if let Some(secondary_used_raw) = secondary_used_raw {
|
||||||
|
let secondary_reset_seconds = codex_reset_seconds(
|
||||||
|
data,
|
||||||
|
"secondary_reset_seconds",
|
||||||
|
"secondary_reset_after_seconds",
|
||||||
|
"secondary_reset_at",
|
||||||
|
now_unix_secs,
|
||||||
|
updated_at_unix_secs,
|
||||||
|
);
|
||||||
|
let secondary_used =
|
||||||
|
codex_effective_used_percent(secondary_used_raw, secondary_reset_seconds);
|
||||||
let mut part = format!(
|
let mut part = format!(
|
||||||
"5H剩余 {}",
|
"5H剩余 {}",
|
||||||
admin_pool_format_percent(100.0 - secondary_used)
|
admin_pool_format_percent(100.0 - secondary_used)
|
||||||
);
|
);
|
||||||
if admin_pool_has_quota_consumption(Some(secondary_used)) {
|
if admin_pool_has_quota_consumption(Some(secondary_used)) {
|
||||||
if let Some(reset_text) = codex_reset_seconds(
|
if let Some(reset_text) =
|
||||||
data,
|
secondary_reset_seconds.and_then(admin_pool_format_reset_after)
|
||||||
"secondary_reset_seconds",
|
|
||||||
"secondary_reset_after_seconds",
|
|
||||||
"secondary_reset_at",
|
|
||||||
)
|
|
||||||
.and_then(admin_pool_format_reset_after)
|
|
||||||
{
|
{
|
||||||
part.push_str(&format!(" ({reset_text})"));
|
part.push_str(&format!(" ({reset_text})"));
|
||||||
}
|
}
|
||||||
@@ -754,6 +780,10 @@ pub(super) fn build_admin_pool_key_payload(
|
|||||||
"model_exclude_patterns".to_string(),
|
"model_exclude_patterns".to_string(),
|
||||||
json!(admin_pool_string_list(key.model_exclude_patterns.as_ref())),
|
json!(admin_pool_string_list(key.model_exclude_patterns.as_ref())),
|
||||||
);
|
);
|
||||||
|
payload.insert(
|
||||||
|
"upstream_metadata".to_string(),
|
||||||
|
json!(key.upstream_metadata.clone()),
|
||||||
|
);
|
||||||
payload.insert("proxy".to_string(), json!(key.proxy.clone()));
|
payload.insert("proxy".to_string(), json!(key.proxy.clone()));
|
||||||
payload.insert("fingerprint".to_string(), json!(key.fingerprint.clone()));
|
payload.insert("fingerprint".to_string(), json!(key.fingerprint.clone()));
|
||||||
payload.insert(
|
payload.insert(
|
||||||
|
|||||||
@@ -1067,7 +1067,7 @@ async fn gateway_formats_codex_quota_countdown_from_reset_after_seconds() {
|
|||||||
key.upstream_metadata = Some(json!({
|
key.upstream_metadata = Some(json!({
|
||||||
"codex": {
|
"codex": {
|
||||||
"plan_type": "plus",
|
"plan_type": "plus",
|
||||||
"updated_at": 1_775_553_285u64,
|
"updated_at": 4_102_444_800u64,
|
||||||
"primary_used_percent": 10.0,
|
"primary_used_percent": 10.0,
|
||||||
"primary_reset_after_seconds": 266_400,
|
"primary_reset_after_seconds": 266_400,
|
||||||
"secondary_used_percent": 33.0,
|
"secondary_used_percent": 33.0,
|
||||||
@@ -1109,6 +1109,75 @@ async fn gateway_formats_codex_quota_countdown_from_reset_after_seconds() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn gateway_codex_quota_resets_to_full_after_countdown_elapsed() {
|
||||||
|
let mut provider = sample_provider("provider-codex", "codex", 10).with_transport_fields(
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
true,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
Some(json!({
|
||||||
|
"pool_advanced": {
|
||||||
|
"enabled": true
|
||||||
|
}
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
provider.provider_type = "codex".to_string();
|
||||||
|
|
||||||
|
let mut key = sample_key(
|
||||||
|
"key-codex-expired",
|
||||||
|
"provider-codex",
|
||||||
|
"openai:cli",
|
||||||
|
"oauth-placeholder",
|
||||||
|
);
|
||||||
|
key.name = "codex expired quota key".to_string();
|
||||||
|
key.auth_type = "oauth".to_string();
|
||||||
|
key.upstream_metadata = Some(json!({
|
||||||
|
"codex": {
|
||||||
|
"plan_type": "plus",
|
||||||
|
"updated_at": 1u64,
|
||||||
|
"primary_used_percent": 42.0,
|
||||||
|
"primary_reset_after_seconds": 60,
|
||||||
|
"secondary_used_percent": 77.0,
|
||||||
|
"secondary_reset_after_seconds": 120
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
|
||||||
|
let provider_catalog_repository = Arc::new(InMemoryProviderCatalogReadRepository::seed(
|
||||||
|
vec![provider],
|
||||||
|
Vec::new(),
|
||||||
|
vec![key],
|
||||||
|
));
|
||||||
|
let state = AppState::new()
|
||||||
|
.expect("gateway should build")
|
||||||
|
.with_data_state_for_tests(GatewayDataState::with_provider_catalog_reader_for_tests(
|
||||||
|
provider_catalog_repository,
|
||||||
|
));
|
||||||
|
|
||||||
|
let response = local_admin_pool_response(
|
||||||
|
&state,
|
||||||
|
http::Method::GET,
|
||||||
|
"/api/admin/pool/provider-codex/keys?page=1&page_size=50&status=all",
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
assert_eq!(response.status(), StatusCode::OK);
|
||||||
|
let payload: serde_json::Value = serde_json::from_slice(
|
||||||
|
&to_bytes(response.into_body(), usize::MAX)
|
||||||
|
.await
|
||||||
|
.expect("body should read"),
|
||||||
|
)
|
||||||
|
.expect("json body should parse");
|
||||||
|
let keys = payload["keys"].as_array().expect("keys should be array");
|
||||||
|
assert_eq!(keys.len(), 1);
|
||||||
|
assert_eq!(keys[0]["account_quota"], "周剩余 100.0% | 5H剩余 100.0%");
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn gateway_pool_prefers_upstream_plan_type_over_auth_config() {
|
async fn gateway_pool_prefers_upstream_plan_type_over_auth_config() {
|
||||||
let mut provider = sample_provider("provider-codex", "codex", 10).with_transport_fields(
|
let mut provider = sample_provider("provider-codex", "codex", 10).with_transport_fields(
|
||||||
|
|||||||
@@ -1,6 +1,11 @@
|
|||||||
import client from '../client'
|
import client from '../client'
|
||||||
import { dedupedRequest } from '@/utils/cache'
|
import { dedupedRequest } from '@/utils/cache'
|
||||||
import type { AllowedModels, OAuthOrganizationInfo, ProxyConfig } from './types/provider'
|
import type {
|
||||||
|
AllowedModels,
|
||||||
|
OAuthOrganizationInfo,
|
||||||
|
ProxyConfig,
|
||||||
|
UpstreamMetadata,
|
||||||
|
} from './types/provider'
|
||||||
import type { ProviderKeyStatusSnapshot } from './types/statusSnapshot'
|
import type { ProviderKeyStatusSnapshot } from './types/statusSnapshot'
|
||||||
|
|
||||||
const POOL_BATCH_ACTION_TIMEOUT_MS = 5 * 60 * 1000
|
const POOL_BATCH_ACTION_TIMEOUT_MS = 5 * 60 * 1000
|
||||||
@@ -114,6 +119,7 @@ export interface PoolKeyDetail {
|
|||||||
account_status_recoverable?: boolean // 兼容字段;优先使用 status_snapshot.account
|
account_status_recoverable?: boolean // 兼容字段;优先使用 status_snapshot.account
|
||||||
account_status_source?: string | null // 兼容字段;优先使用 status_snapshot.account
|
account_status_source?: string | null // 兼容字段;优先使用 status_snapshot.account
|
||||||
status_snapshot?: ProviderKeyStatusSnapshot | null
|
status_snapshot?: ProviderKeyStatusSnapshot | null
|
||||||
|
upstream_metadata?: UpstreamMetadata | null
|
||||||
quota_updated_at?: number | null
|
quota_updated_at?: number | null
|
||||||
health_score?: number
|
health_score?: number
|
||||||
circuit_breaker_open?: boolean
|
circuit_breaker_open?: boolean
|
||||||
|
|||||||
@@ -307,10 +307,12 @@ export interface CodexUpstreamMetadata {
|
|||||||
plan_type?: string // 套餐类型
|
plan_type?: string // 套餐类型
|
||||||
primary_used_percent?: number // 周限额窗口使用百分比
|
primary_used_percent?: number // 周限额窗口使用百分比
|
||||||
primary_reset_seconds?: number // 周限额重置剩余秒数
|
primary_reset_seconds?: number // 周限额重置剩余秒数
|
||||||
|
primary_reset_after_seconds?: number // 周限额重置剩余秒数(兼容字段)
|
||||||
primary_reset_at?: number // 周限额重置时间(Unix 时间戳)
|
primary_reset_at?: number // 周限额重置时间(Unix 时间戳)
|
||||||
primary_window_minutes?: number // 周限额窗口大小(分钟)
|
primary_window_minutes?: number // 周限额窗口大小(分钟)
|
||||||
secondary_used_percent?: number // 5H限额窗口使用百分比
|
secondary_used_percent?: number // 5H限额窗口使用百分比
|
||||||
secondary_reset_seconds?: number // 5H限额重置剩余秒数
|
secondary_reset_seconds?: number // 5H限额重置剩余秒数
|
||||||
|
secondary_reset_after_seconds?: number // 5H限额重置剩余秒数(兼容字段)
|
||||||
secondary_reset_at?: number // 5H限额重置时间(Unix 时间戳)
|
secondary_reset_at?: number // 5H限额重置时间(Unix 时间戳)
|
||||||
secondary_window_minutes?: number // 5H限额窗口大小(分钟)
|
secondary_window_minutes?: number // 5H限额窗口大小(分钟)
|
||||||
has_credits?: boolean // 是否有积分
|
has_credits?: boolean // 是否有积分
|
||||||
|
|||||||
@@ -1631,12 +1631,14 @@ interface QuotaProgressItem {
|
|||||||
remainingPercent: number
|
remainingPercent: number
|
||||||
detail?: string
|
detail?: string
|
||||||
resetAtSeconds?: number | null
|
resetAtSeconds?: number | null
|
||||||
|
resetSeconds?: number | null
|
||||||
|
updatedAtSeconds?: number | null
|
||||||
}
|
}
|
||||||
|
|
||||||
const quotaProgressMap = computed<Record<string, QuotaProgressItem[]>>(() => {
|
const quotaProgressMap = computed<Record<string, QuotaProgressItem[]>>(() => {
|
||||||
const map: Record<string, QuotaProgressItem[]> = {}
|
const map: Record<string, QuotaProgressItem[]> = {}
|
||||||
for (const key of keyPage.value.keys) {
|
for (const key of keyPage.value.keys) {
|
||||||
map[key.key_id] = parseQuotaProgressItems(key.account_quota)
|
map[key.key_id] = parseQuotaProgressItems(key)
|
||||||
}
|
}
|
||||||
return map
|
return map
|
||||||
})
|
})
|
||||||
@@ -2602,8 +2604,15 @@ function getQuotaProgressLabel(label: string): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function getQuotaProgressCountdown(item: QuotaProgressItem) {
|
function getQuotaProgressCountdown(item: QuotaProgressItem) {
|
||||||
if ((item.label !== '5H' && item.label !== '周') || item.resetAtSeconds == null) return null
|
if (item.label !== '5H' && item.label !== '周') return null
|
||||||
return getCodexResetCountdown(item.resetAtSeconds, null, null, countdownTick.value, item.remainingPercent)
|
if (item.resetAtSeconds == null && item.resetSeconds == null) return null
|
||||||
|
return getCodexResetCountdown(
|
||||||
|
item.resetAtSeconds,
|
||||||
|
item.resetSeconds,
|
||||||
|
item.updatedAtSeconds,
|
||||||
|
countdownTick.value,
|
||||||
|
item.remainingPercent
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
function getQuotaProgressCountdownText(item: QuotaProgressItem): string {
|
function getQuotaProgressCountdownText(item: QuotaProgressItem): string {
|
||||||
@@ -2644,6 +2653,42 @@ function clampPercent(value: number): number {
|
|||||||
return value
|
return value
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function normalizeUnixSeconds(raw: number | null | undefined): number | null {
|
||||||
|
const value = Number(raw ?? 0)
|
||||||
|
if (!Number.isFinite(value) || value <= 0) return null
|
||||||
|
if (value > 1_000_000_000_000) return Math.floor(value / 1000)
|
||||||
|
return Math.floor(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeRemainingSeconds(raw: number | null | undefined): number | null {
|
||||||
|
const value = Number(raw ?? NaN)
|
||||||
|
if (!Number.isFinite(value) || value < 0) return null
|
||||||
|
return Math.floor(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveCodexQuotaCountdown(
|
||||||
|
key: PoolKeyDetail,
|
||||||
|
label: string
|
||||||
|
): Pick<QuotaProgressItem, 'resetAtSeconds' | 'resetSeconds' | 'updatedAtSeconds'> | null {
|
||||||
|
if (label !== '5H' && label !== '周') return null
|
||||||
|
const codex = key.upstream_metadata?.codex
|
||||||
|
if (!codex) return null
|
||||||
|
|
||||||
|
const isWeeklyWindow = label === '周'
|
||||||
|
const resetAtSeconds = normalizeUnixSeconds(
|
||||||
|
isWeeklyWindow ? codex.primary_reset_at : codex.secondary_reset_at
|
||||||
|
)
|
||||||
|
const resetSeconds = normalizeRemainingSeconds(
|
||||||
|
isWeeklyWindow
|
||||||
|
? (codex.primary_reset_seconds ?? codex.primary_reset_after_seconds ?? null)
|
||||||
|
: (codex.secondary_reset_seconds ?? codex.secondary_reset_after_seconds ?? null)
|
||||||
|
)
|
||||||
|
const updatedAtSeconds = normalizeUnixSeconds(codex.updated_at)
|
||||||
|
|
||||||
|
if (resetAtSeconds == null && resetSeconds == null) return null
|
||||||
|
return { resetAtSeconds, resetSeconds, updatedAtSeconds }
|
||||||
|
}
|
||||||
|
|
||||||
function parseQuotaResetRemainingSeconds(detail: string | undefined): number | null {
|
function parseQuotaResetRemainingSeconds(detail: string | undefined): number | null {
|
||||||
if (!detail) return null
|
if (!detail) return null
|
||||||
const text = detail.replace(/\s+/g, '')
|
const text = detail.replace(/\s+/g, '')
|
||||||
@@ -2667,7 +2712,8 @@ function parseQuotaResetRemainingSeconds(detail: string | undefined): number | n
|
|||||||
return total
|
return total
|
||||||
}
|
}
|
||||||
|
|
||||||
function parseQuotaProgressItems(quotaText: string | null | undefined): QuotaProgressItem[] {
|
function parseQuotaProgressItems(key: PoolKeyDetail): QuotaProgressItem[] {
|
||||||
|
const quotaText = key.account_quota
|
||||||
if (!quotaText) return []
|
if (!quotaText) return []
|
||||||
|
|
||||||
const segments = quotaText
|
const segments = quotaText
|
||||||
@@ -2684,16 +2730,27 @@ function parseQuotaProgressItems(quotaText: string | null | undefined): QuotaPro
|
|||||||
const remainingPercent = clampPercent(Number(rawPercent))
|
const remainingPercent = clampPercent(Number(rawPercent))
|
||||||
const label = normalizeQuotaLabel(rawLabel)
|
const label = normalizeQuotaLabel(rawLabel)
|
||||||
const detail = rawTail.trim().replace(/^[()]+|[()]+$/g, '').trim()
|
const detail = rawTail.trim().replace(/^[()]+|[()]+$/g, '').trim()
|
||||||
const resetRemainingSeconds = parseQuotaResetRemainingSeconds(detail || undefined)
|
const codexCountdown = resolveCodexQuotaCountdown(key, label)
|
||||||
const resetAtSeconds = resetRemainingSeconds == null
|
let resetAtSeconds = codexCountdown?.resetAtSeconds ?? null
|
||||||
? null
|
let resetSeconds = codexCountdown?.resetSeconds ?? null
|
||||||
: Math.floor(Date.now() / 1000) + resetRemainingSeconds
|
let updatedAtSeconds = codexCountdown?.updatedAtSeconds ?? null
|
||||||
|
|
||||||
|
if (resetAtSeconds == null && resetSeconds == null) {
|
||||||
|
const resetRemainingSeconds = parseQuotaResetRemainingSeconds(detail || undefined)
|
||||||
|
resetAtSeconds = resetRemainingSeconds == null
|
||||||
|
? null
|
||||||
|
: Math.floor(Date.now() / 1000) + resetRemainingSeconds
|
||||||
|
resetSeconds = null
|
||||||
|
updatedAtSeconds = null
|
||||||
|
}
|
||||||
|
|
||||||
items.push({
|
items.push({
|
||||||
label,
|
label,
|
||||||
remainingPercent,
|
remainingPercent,
|
||||||
detail: detail || undefined,
|
detail: detail || undefined,
|
||||||
resetAtSeconds,
|
resetAtSeconds,
|
||||||
|
resetSeconds,
|
||||||
|
updatedAtSeconds,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user