feat: 适配codex用量数据

This commit is contained in:
shaw
2025-09-25 17:23:26 +08:00
parent 991dd1436f
commit c15ef0b6ae
3 changed files with 431 additions and 4 deletions

View File

@@ -17,6 +17,50 @@ function createProxyAgent(proxy) {
return ProxyHelper.createProxyAgent(proxy)
}
function normalizeHeaders(headers = {}) {
if (!headers || typeof headers !== 'object') {
return {}
}
const normalized = {}
for (const [key, value] of Object.entries(headers)) {
if (!key) {
continue
}
normalized[key.toLowerCase()] = Array.isArray(value) ? value[0] : value
}
return normalized
}
function toNumberSafe(value) {
if (value === undefined || value === null || value === '') {
return null
}
const num = Number(value)
return Number.isFinite(num) ? num : null
}
function extractCodexUsageHeaders(headers) {
const normalized = normalizeHeaders(headers)
if (!normalized || Object.keys(normalized).length === 0) {
return null
}
const snapshot = {
primaryUsedPercent: toNumberSafe(normalized['x-codex-primary-used-percent']),
primaryResetAfterSeconds: toNumberSafe(normalized['x-codex-primary-reset-after-seconds']),
primaryWindowMinutes: toNumberSafe(normalized['x-codex-primary-window-minutes']),
secondaryUsedPercent: toNumberSafe(normalized['x-codex-secondary-used-percent']),
secondaryResetAfterSeconds: toNumberSafe(normalized['x-codex-secondary-reset-after-seconds']),
secondaryWindowMinutes: toNumberSafe(normalized['x-codex-secondary-window-minutes']),
primaryOverSecondaryPercent: toNumberSafe(
normalized['x-codex-primary-over-secondary-limit-percent']
)
}
const hasData = Object.values(snapshot).some((value) => value !== null)
return hasData ? snapshot : null
}
// 使用统一调度器选择 OpenAI 账户
async function getOpenAIAuthToken(apiKeyData, sessionId = null, requestedModel = null) {
try {
@@ -266,6 +310,15 @@ const handleResponses = async (req, res) => {
)
}
const codexUsageSnapshot = extractCodexUsageHeaders(upstream.headers)
if (codexUsageSnapshot) {
try {
await openaiAccountService.updateCodexUsageSnapshot(accountId, codexUsageSnapshot)
} catch (codexError) {
logger.error('⚠️ 更新 Codex 使用统计失败:', codexError)
}
}
// 处理 429 限流错误
if (upstream.status === 429) {
logger.warn(`🚫 Rate limit detected for OpenAI account ${accountId} (Codex API)`)