Compare commits

..
10 Commits
Author SHA1 Message Date
ZyyandCodex ff0de4742d chore: bump version to 1.0.9
Co-authored-by: Codex <noreply@openai.com>
2026-07-08 18:06:08 +08:00
ZyyandCodex 44f45101b8 test: assert account quota local usage
Co-authored-by: Codex <noreply@openai.com>
2026-07-08 17:44:01 +08:00
ZyyandCodex a240668a47 fix: polish sidebar focus state
Co-authored-by: Codex <noreply@openai.com>
2026-07-08 16:45:52 +08:00
ZyyandCodex 30f354965c fix: align account quota usage tracking
Co-authored-by: Codex <noreply@openai.com>
2026-07-08 16:37:32 +08:00
ZyyandCodex 3b462f7ecf refactor: remove trusted proxy config
Co-authored-by: Codex <noreply@openai.com>
2026-07-08 15:22:23 +08:00
ZyyandCodex 5682d4fbe9 test: simplify ops error log snapshot helper
Co-authored-by: Codex <noreply@openai.com>
2026-07-08 14:55:05 +08:00
ZyyandCodex 146776c742 fix: separate ops errors from usage records
Co-authored-by: Codex <noreply@openai.com>
2026-07-08 14:04:49 +08:00
ZyyandCodex e8c14d4324 fix: complete update log streaming
Co-authored-by: Codex <noreply@openai.com>
2026-07-08 13:58:28 +08:00
zyycnandCodex 5483e37b00 refactor: extract upstream scheduler
Co-authored-by: Codex <noreply@openai.com>
2026-07-08 13:56:27 +08:00
ZyyandCodex daad7c746c fix: strengthen response account affinity
Co-authored-by: Codex <noreply@openai.com>
2026-07-07 18:31:50 +08:00
66 changed files with 2888 additions and 1034 deletions
+56 -19
View File
@@ -7,7 +7,7 @@ use serde::Serialize;
use serde_json::Value;
use crate::infra::{
format::{format_compact_percent, format_tokens},
format::{format_compact_percent, format_plain_number, format_tokens, nonnegative_i64_to_u64},
time::{china_datetime, china_relative_time},
};
@@ -31,13 +31,29 @@ struct AdminAccountQuotaWindowData {
label_display: String,
used_percent: Option<f64>,
used_percent_display: String,
token_usage_display: String,
#[serde(skip_serializing_if = "Option::is_none")]
local_usage: Option<AdminAccountQuotaWindowLocalUsageData>,
reset_at_display: String,
window_used_display: String,
#[serde(skip)]
reset_at: Option<DateTime<Utc>>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct AdminAccountQuotaWindowLocalUsageData {
request_count: i64,
request_count_display: String,
input_tokens: i64,
input_tokens_display: String,
output_tokens: i64,
output_tokens_display: String,
cached_tokens: i64,
cached_tokens_display: String,
total_tokens: i64,
total_tokens_display: String,
}
#[derive(Debug, Clone)]
pub(crate) struct AdminAccountQuotaUsageWindow {
pub(crate) key: String,
@@ -56,17 +72,37 @@ impl AdminAccountQuotaUsageWindow {
}
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct AdminAccountQuotaWindowTokenUsage {
total_tokens: u64,
pub(crate) struct AdminAccountQuotaWindowLocalUsage {
pub(crate) request_count: i64,
pub(crate) input_tokens: i64,
pub(crate) output_tokens: i64,
pub(crate) cached_tokens: i64,
}
impl AdminAccountQuotaWindowTokenUsage {
pub(crate) fn add_tokens(&mut self, tokens: u64) {
self.total_tokens = self.total_tokens.saturating_add(tokens);
impl AdminAccountQuotaWindowLocalUsage {
pub(crate) fn add(&mut self, other: Self) {
self.request_count = self.request_count.saturating_add(other.request_count);
self.input_tokens = self.input_tokens.saturating_add(other.input_tokens);
self.output_tokens = self.output_tokens.saturating_add(other.output_tokens);
self.cached_tokens = self.cached_tokens.saturating_add(other.cached_tokens);
}
}
fn display(self) -> String {
format_tokens(self.total_tokens)
impl From<AdminAccountQuotaWindowLocalUsage> for AdminAccountQuotaWindowLocalUsageData {
fn from(usage: AdminAccountQuotaWindowLocalUsage) -> Self {
let total_tokens = usage.input_tokens.saturating_add(usage.output_tokens);
Self {
request_count: usage.request_count,
request_count_display: format_plain_number(nonnegative_i64_to_u64(usage.request_count)),
input_tokens: usage.input_tokens,
input_tokens_display: format_tokens(nonnegative_i64_to_u64(usage.input_tokens)),
output_tokens: usage.output_tokens,
output_tokens_display: format_tokens(nonnegative_i64_to_u64(usage.output_tokens)),
cached_tokens: usage.cached_tokens,
cached_tokens_display: format_tokens(nonnegative_i64_to_u64(usage.cached_tokens)),
total_tokens,
total_tokens_display: format_tokens(nonnegative_i64_to_u64(total_tokens)),
}
}
}
@@ -93,17 +129,18 @@ impl AdminAccountQuotaData {
.collect()
}
pub(crate) fn apply_token_usage(
pub(crate) fn apply_local_usage(
&mut self,
usage_by_window: &HashMap<String, AdminAccountQuotaWindowTokenUsage>,
usage_by_window: &HashMap<String, AdminAccountQuotaWindowLocalUsage>,
) {
for window in &mut self.windows {
window.token_usage_display =
match (window.usage_window(), usage_by_window.get(&window.key)) {
(Some(_), Some(usage)) => usage.display(),
(Some(_), None) => AdminAccountQuotaWindowTokenUsage::default().display(),
(None, _) => "-".to_string(),
};
window.local_usage = window.usage_window().map(|_| {
usage_by_window
.get(&window.key)
.copied()
.unwrap_or_default()
.into()
});
}
}
}
@@ -185,7 +222,7 @@ fn push_monthly_quota_window(
label_display: "月限额".to_string(),
used_percent,
used_percent_display: used_percent.map_or_else(|| "-".to_string(), format_compact_percent),
token_usage_display: "-".to_string(),
local_usage: None,
reset_at_display: reset_at
.as_ref()
.map_or_else(|| "-".to_string(), china_datetime),
@@ -274,7 +311,7 @@ fn push_quota_window(
label_display,
used_percent,
used_percent_display: used_percent.map_or_else(|| "-".to_string(), format_compact_percent),
token_usage_display: "-".to_string(),
local_usage: None,
reset_at_display: reset_at
.as_ref()
.map_or_else(|| "-".to_string(), china_datetime),
+76 -126
View File
@@ -27,7 +27,7 @@ use crate::{
admin::{
accounts::quota_view::{
quota_data, AdminAccountQuotaData, AdminAccountQuotaUsageWindow,
AdminAccountQuotaWindowTokenUsage,
AdminAccountQuotaWindowLocalUsage,
},
accounts::service::{
AdminAccountError, AdminAccountHealthCheck, AdminAccountMetadata,
@@ -303,14 +303,6 @@ struct AccountModelUsageRecord {
last_used_at: Option<DateTime<Utc>>,
}
#[derive(Debug, Clone, Copy, Default)]
struct AccountUsageWindowStats {
request_count: i64,
input_tokens: i64,
output_tokens: i64,
cached_tokens: i64,
}
#[derive(Debug, Clone)]
struct AccountQuotaUsageWindow {
account_id: String,
@@ -691,7 +683,7 @@ pub(crate) async fn account_quota(
let raw = data.get("raw").cloned().unwrap_or(Value::Null);
let quota_json = quota.to_string();
let mut quota_data = quota_data(&quota_json, Some(Utc::now()));
apply_account_quota_window_token_usage(&state, &account_id, &mut quota_data).await;
apply_account_quota_window_local_usage(&state, &account_id, &mut quota_data).await;
let account =
account_data_for_quota_refresh(&state, &account_id, quota_data.clone()).await?;
Ok(AdminResponse::new(
@@ -922,10 +914,11 @@ async fn account_list_stats(
.await
.unwrap_or_default();
let mut quota_by_account = quota_by_account.clone();
apply_quota_window_token_usage(state, accounts, &mut quota_by_account).await;
let selected_quota_windows = selected_quota_windows_by_account(accounts, &quota_by_account);
let all_quota_windows = quota_usage_windows_by_account(accounts, &quota_by_account);
let quota_window_usage_stats =
account_usage_stats_by_quota_window(state, &selected_quota_windows).await;
quota_window_local_usage_by_account(state, &all_quota_windows).await;
apply_quota_window_local_usage(accounts, &mut quota_by_account, &quota_window_usage_stats);
let selected_quota_windows = selected_quota_windows_by_account(accounts, &quota_by_account);
let usage_records = usage_records
.into_iter()
.map(|usage| {
@@ -972,105 +965,11 @@ fn selected_quota_window(quota: &AdminAccountQuotaData) -> Option<AdminAccountQu
})
}
async fn account_usage_stats_by_quota_window(
state: &AppState,
windows_by_account: &HashMap<String, AdminAccountQuotaUsageWindow>,
) -> HashMap<String, AccountUsageWindowStats> {
if windows_by_account.is_empty() {
return HashMap::new();
}
let mut builder = QueryBuilder::<Sqlite>::new(
"select
account_id,
coalesce(sum(request_count), 0) as request_count,
coalesce(sum(input_tokens), 0) as input_tokens,
coalesce(sum(output_tokens), 0) as output_tokens,
coalesce(sum(cached_tokens), 0) as cached_tokens
from usage_time_buckets
where ",
);
for (index, (account_id, window)) in windows_by_account.iter().enumerate() {
if index > 0 {
builder.push(" or ");
}
let bucket_start = china_quarter_hour_start(window.start);
builder.push("(account_id = ");
builder.push_bind(account_id);
builder.push(" and bucket_start >= ");
builder.push_bind(bucket_start.to_rfc3339());
builder.push(" and bucket_start <= ");
builder.push_bind(window.end.to_rfc3339());
builder.push(")");
}
builder.push(" group by account_id");
let rows = builder
.build()
.fetch_all(state.services.background_tasks.accounts.pool())
.await
.unwrap_or_default();
rows.into_iter()
.map(|row| {
(
row.get::<String, _>("account_id"),
AccountUsageWindowStats {
request_count: row.get("request_count"),
input_tokens: row.get("input_tokens"),
output_tokens: row.get("output_tokens"),
cached_tokens: row.get("cached_tokens"),
},
)
})
.collect()
}
fn apply_selected_quota_window_usage(
mut usage: AdminUsageRecord,
selected_quota_windows: &HashMap<String, AdminAccountQuotaUsageWindow>,
quota_window_usage_stats: &HashMap<String, AccountUsageWindowStats>,
) -> AdminUsageRecord {
let Some(window) = selected_quota_windows.get(&usage.account_id) else {
return usage;
};
let stats = quota_window_usage_stats
.get(&usage.account_id)
.copied()
.unwrap_or_default();
usage.window_request_count = stats.request_count;
usage.window_input_tokens = stats.input_tokens;
usage.window_output_tokens = stats.output_tokens;
usage.window_cached_tokens = stats.cached_tokens;
usage.window_started_at = Some(window.start);
usage.window_reset_at = Some(window.end);
usage.limit_window_seconds = Some(window.window_seconds);
usage
}
async fn apply_account_quota_window_token_usage(
state: &AppState,
account_id: &str,
quota: &mut AdminAccountQuotaData,
) {
let windows = quota
.usage_windows()
.into_iter()
.map(|window| AccountQuotaUsageWindow {
account_id: account_id.to_string(),
window,
})
.collect::<Vec<_>>();
let usage_by_account = quota_window_token_usage_by_account(state, &windows).await;
let empty_usage = HashMap::new();
quota.apply_token_usage(usage_by_account.get(account_id).unwrap_or(&empty_usage));
}
async fn apply_quota_window_token_usage(
state: &AppState,
fn quota_usage_windows_by_account(
accounts: &[AdminAccountMetadata],
quota_by_account: &mut HashMap<String, AdminAccountQuotaData>,
) {
let windows = accounts
quota_by_account: &HashMap<String, AdminAccountQuotaData>,
) -> Vec<AccountQuotaUsageWindow> {
accounts
.iter()
.filter_map(|account| {
quota_by_account
@@ -1086,21 +985,44 @@ async fn apply_quota_window_token_usage(
window,
})
})
.collect::<Vec<_>>();
let usage_by_account = quota_window_token_usage_by_account(state, &windows).await;
.collect()
}
async fn apply_account_quota_window_local_usage(
state: &AppState,
account_id: &str,
quota: &mut AdminAccountQuotaData,
) {
let windows = quota
.usage_windows()
.into_iter()
.map(|window| AccountQuotaUsageWindow {
account_id: account_id.to_string(),
window,
})
.collect::<Vec<_>>();
let usage_by_account = quota_window_local_usage_by_account(state, &windows).await;
let empty_usage = HashMap::new();
quota.apply_local_usage(usage_by_account.get(account_id).unwrap_or(&empty_usage));
}
fn apply_quota_window_local_usage(
accounts: &[AdminAccountMetadata],
quota_by_account: &mut HashMap<String, AdminAccountQuotaData>,
usage_by_account: &HashMap<String, HashMap<String, AdminAccountQuotaWindowLocalUsage>>,
) {
for account in accounts {
if let Some(quota) = quota_by_account.get_mut(&account.id) {
let empty_usage = HashMap::new();
quota.apply_token_usage(usage_by_account.get(&account.id).unwrap_or(&empty_usage));
quota.apply_local_usage(usage_by_account.get(&account.id).unwrap_or(&empty_usage));
}
}
}
async fn quota_window_token_usage_by_account(
async fn quota_window_local_usage_by_account(
state: &AppState,
windows: &[AccountQuotaUsageWindow],
) -> HashMap<String, HashMap<String, AdminAccountQuotaWindowTokenUsage>> {
) -> HashMap<String, HashMap<String, AdminAccountQuotaWindowLocalUsage>> {
let Some(min_start) = windows.iter().map(|window| window.window.start).min() else {
return HashMap::new();
};
@@ -1123,8 +1045,10 @@ async fn quota_window_token_usage_by_account(
"select
account_id,
bucket_start,
coalesce(sum(request_count), 0) as request_count,
coalesce(sum(input_tokens), 0) as input_tokens,
coalesce(sum(output_tokens), 0) as output_tokens
coalesce(sum(output_tokens), 0) as output_tokens,
coalesce(sum(cached_tokens), 0) as cached_tokens
from usage_time_buckets
where account_id in (",
);
@@ -1134,7 +1058,7 @@ async fn quota_window_token_usage_by_account(
}
separated.push_unseparated(")");
builder.push(" and bucket_start >= ");
builder.push_bind(min_start.to_rfc3339());
builder.push_bind(china_quarter_hour_start(min_start).to_rfc3339());
builder.push(" and bucket_start <= ");
builder.push_bind(max_end.to_rfc3339());
builder.push(" group by account_id, bucket_start");
@@ -1145,35 +1069,61 @@ async fn quota_window_token_usage_by_account(
.await
.unwrap_or_default();
let mut usage_by_account =
HashMap::<String, HashMap<String, AdminAccountQuotaWindowTokenUsage>>::new();
HashMap::<String, HashMap<String, AdminAccountQuotaWindowLocalUsage>>::new();
for row in rows {
let account_id: String = row.get("account_id");
let Ok(bucket_start) = parse_rfc3339_utc(row.get::<&str, _>("bucket_start")) else {
continue;
};
let total_tokens = nonnegative_i64_to_u64(row.get::<i64, _>("input_tokens"))
.saturating_add(nonnegative_i64_to_u64(row.get::<i64, _>("output_tokens")));
let bucket_usage = AdminAccountQuotaWindowLocalUsage {
request_count: row.get("request_count"),
input_tokens: row.get("input_tokens"),
output_tokens: row.get("output_tokens"),
cached_tokens: row.get("cached_tokens"),
};
let Some(account_windows) = windows_by_account.get(account_id.as_str()) else {
continue;
};
for window in account_windows
.iter()
.filter(|window| bucket_start >= window.start && bucket_start <= window.end)
{
for window in account_windows.iter().filter(|window| {
bucket_start >= china_quarter_hour_start(window.start) && bucket_start <= window.end
}) {
usage_by_account
.entry(account_id.clone())
.or_default()
.entry(window.key.clone())
.or_default()
.add_tokens(total_tokens);
.add(bucket_usage);
}
}
usage_by_account
}
fn apply_selected_quota_window_usage(
mut usage: AdminUsageRecord,
selected_quota_windows: &HashMap<String, AdminAccountQuotaUsageWindow>,
quota_window_usage_stats: &HashMap<String, HashMap<String, AdminAccountQuotaWindowLocalUsage>>,
) -> AdminUsageRecord {
let Some(window) = selected_quota_windows.get(&usage.account_id) else {
return usage;
};
let stats = quota_window_usage_stats
.get(&usage.account_id)
.and_then(|usage_by_window| usage_by_window.get(&window.key))
.copied()
.unwrap_or_default();
usage.window_request_count = stats.request_count;
usage.window_input_tokens = stats.input_tokens;
usage.window_output_tokens = stats.output_tokens;
usage.window_cached_tokens = stats.cached_tokens;
usage.window_started_at = Some(window.start);
usage.window_reset_at = Some(window.end);
usage.limit_window_seconds = Some(window.window_seconds);
usage
}
async fn account_summary_data(
state: &AppState,
quota_by_account: &HashMap<String, AdminAccountQuotaData>,
+13 -30
View File
@@ -15,7 +15,7 @@ use crate::{
admin::{
auth::session::AdminAuth,
monitoring::{
account_usage_service::{AdminUsageSummary, AdminUsageTimeBucketRecord},
account_usage_service::AdminUsageTimeBucketRecord,
diagnostics::{
fingerprint_diagnostics, AccountCapacityDiagnostics, AccountPoolDiagnostics,
},
@@ -27,7 +27,7 @@ use crate::{
UsageRecordCostDetailsData, UsageRecordTokenDetailsData,
},
usage_record_service::AdminUsageRecordFilter,
usage_record_store::UsageRecordAccountUsage,
usage_record_store::{UsageRecordAccountUsage, UsageRecordSummary},
},
response::{AdminEnvelope, AdminError, AdminResponse},
},
@@ -292,10 +292,10 @@ pub(crate) async fn dashboard_summary(
let today_filter = today_usage_record_filter(now);
let usage_summary = state
.services
.usage
.summary()
.usage_records
.summary(AdminUsageRecordFilter::default())
.await
.unwrap_or_else(|_| empty_usage_summary());
.unwrap_or_else(|_| UsageRecordSummary::default());
let account_usage_records = state
.services
.usage_records
@@ -375,7 +375,7 @@ pub(crate) async fn dashboard_trend(
fn dashboard_cards(
accounts: &[Account],
buckets: &[AdminUsageTimeBucketRecord],
usage_summary: &AdminUsageSummary,
usage_summary: &UsageRecordSummary,
) -> DashboardCardsData {
dashboard_cards_at(accounts, buckets, usage_summary, Utc::now())
}
@@ -383,7 +383,7 @@ fn dashboard_cards(
fn dashboard_cards_at(
accounts: &[Account],
buckets: &[AdminUsageTimeBucketRecord],
usage_summary: &AdminUsageSummary,
usage_summary: &UsageRecordSummary,
now: DateTime<Utc>,
) -> DashboardCardsData {
let today_start = china_day_start(now);
@@ -391,9 +391,9 @@ fn dashboard_cards_at(
let today = usage_window(buckets, today_start, now);
let yesterday = usage_window(buckets, yesterday_start, today_start);
let today_cost = cost_window(buckets, today_start, now).unwrap_or(0.0);
let total_requests = nonnegative_i64_to_u64(usage_summary.request_count);
let total_tokens = nonnegative_i64_to_u64(usage_summary.total_tokens);
let total_cached_tokens = nonnegative_i64_to_u64(usage_summary.cached_tokens);
let total_requests = usage_summary.total_requests;
let total_tokens = usage_summary.total_tokens;
let total_cached_tokens = usage_summary.cached_tokens;
let total_hit_rate = summary_cache_hit_rate(usage_summary);
let total_accounts = accounts.len() as u64;
@@ -449,27 +449,10 @@ fn dashboard_cards_at(
}
}
fn empty_usage_summary() -> AdminUsageSummary {
AdminUsageSummary {
account_count: 0,
request_count: 0,
empty_response_count: 0,
input_tokens: 0,
output_tokens: 0,
cached_tokens: 0,
reasoning_tokens: 0,
total_tokens: 0,
image_input_tokens: 0,
image_output_tokens: 0,
image_request_count: 0,
image_request_failed_count: 0,
}
}
fn summary_cache_hit_rate(summary: &AdminUsageSummary) -> Option<f64> {
let input_tokens = nonnegative_i64_to_u64(summary.input_tokens);
fn summary_cache_hit_rate(summary: &UsageRecordSummary) -> Option<f64> {
let input_tokens = summary.input_tokens;
if input_tokens > 0 {
Some(nonnegative_i64_to_u64(summary.cached_tokens) as f64 / input_tokens as f64)
Some(summary.cached_tokens as f64 / input_tokens as f64)
} else {
None
}
+3
View File
@@ -5,6 +5,9 @@ pub mod account_usage_store;
pub(crate) mod billing;
pub mod dashboard;
pub mod diagnostics;
pub mod ops_error_model;
pub mod ops_error_service;
pub mod ops_error_store;
pub mod usage_record_model;
pub mod usage_record_routes;
pub mod usage_record_service;
@@ -0,0 +1,75 @@
//! 运维错误事件模型。
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use uuid::Uuid;
/// 结构化运维错误事件。
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct OpsErrorLog {
/// 事件 ID。
pub id: String,
/// 请求 ID。
pub request_id: Option<String>,
/// 事件类别。
pub kind: String,
/// 账号 ID。预账号调度失败时为空。
pub account_id: Option<String>,
/// HTTP 路由。
pub route: Option<String>,
/// 模型名。
pub model: Option<String>,
/// 事件状态码。
pub status_code: Option<i64>,
/// 客户端看到的状态码。
pub client_status_code: Option<i64>,
/// 上游 HTTP 状态码。
pub upstream_status_code: Option<i64>,
/// 上游传输方式,例如 http_sse 或 websocket。
pub transport: Option<String>,
/// 同一请求内的上游尝试序号。
pub attempt_index: Option<i64>,
/// 失败分类。
pub failure_class: Option<String>,
/// 上游响应 ID。
pub response_id: Option<String>,
/// 上游请求 ID。
pub upstream_request_id: Option<String>,
/// 请求耗时毫秒。
pub latency_ms: Option<i64>,
/// 展示消息。
pub message: String,
/// 结构化元数据。
pub metadata: Value,
/// 创建时间。
#[serde(serialize_with = "crate::infra::time::serialize_china_rfc3339")]
pub created_at: DateTime<Utc>,
}
impl OpsErrorLog {
/// 构造运维错误事件。
pub fn new(kind: impl Into<String>, message: impl Into<String>) -> Self {
Self {
id: format!("ops_error_{}", Uuid::new_v4().simple()),
request_id: None,
kind: kind.into(),
account_id: None,
route: None,
model: None,
status_code: None,
client_status_code: None,
upstream_status_code: None,
transport: None,
attempt_index: None,
failure_class: None,
response_id: None,
upstream_request_id: None,
latency_ms: None,
message: message.into(),
metadata: Value::Object(Map::default()),
created_at: Utc::now(),
}
}
}
@@ -0,0 +1,68 @@
//! 管理端运维错误事件服务。
use chrono::Utc;
use thiserror::Error;
use crate::admin::monitoring::{
ops_error_model::OpsErrorLog, ops_error_store::SqliteOpsErrorLogStore,
};
/// 管理端运维错误事件错误。
#[derive(Debug, Error)]
pub enum AdminOpsErrorLogError {
/// 写入失败。
#[error("failed to append ops error log")]
Append,
/// 保留期清理失败。
#[error("failed to trim expired ops error logs")]
Retention,
}
/// 管理端运维错误事件服务。
#[derive(Clone)]
pub struct AdminOpsErrorLogService {
store: SqliteOpsErrorLogStore,
capture_body: bool,
}
impl AdminOpsErrorLogService {
/// 构造管理端运维错误事件服务。
pub fn new(store: SqliteOpsErrorLogStore, capture_body: bool) -> Self {
Self {
store,
capture_body,
}
}
/// 记录运维错误事件。
pub async fn record(&self, mut event: OpsErrorLog) -> Result<(), AdminOpsErrorLogError> {
apply_capture_body_policy(&mut event, self.capture_body);
self.store
.append(&event)
.await
.map_err(|_| AdminOpsErrorLogError::Append)?;
self.store
.trim_to_retention(Utc::now())
.await
.map_err(|_| AdminOpsErrorLogError::Retention)?;
Ok(())
}
}
fn apply_capture_body_policy(event: &mut OpsErrorLog, capture_body: bool) {
if capture_body {
return;
}
let Some(metadata) = event.metadata.as_object_mut() else {
return;
};
for key in [
"body",
"rawBody",
"requestBody",
"responseBody",
"upstreamBody",
] {
metadata.remove(key);
}
}
@@ -0,0 +1,261 @@
//! 运维错误事件存储实现(SQLite)。
use chrono::{DateTime, Duration, Utc};
use serde_json::Value;
use sqlx::SqlitePool;
use thiserror::Error;
use crate::{
admin::monitoring::{
ops_error_model::OpsErrorLog,
usage_record_model::{metadata_i64, metadata_service_tier, metadata_string},
usage_record_store::USAGE_RECORD_RETENTION_DAYS,
},
infra::time::china_quarter_hour_start,
};
/// SQLite 运维错误事件错误。
#[derive(Debug, Error)]
pub enum SqliteOpsErrorLogStoreError {
/// 数据库错误。
#[error("sqlite ops error log database error: {0}")]
Database(#[from] sqlx::Error),
}
/// SQLite 运维错误事件结果。
pub type SqliteOpsErrorLogStoreResult<T> = Result<T, SqliteOpsErrorLogStoreError>;
/// SQLite 运维错误事件存储。
#[derive(Clone)]
pub struct SqliteOpsErrorLogStore {
pool: SqlitePool,
}
impl SqliteOpsErrorLogStore {
/// 构造存储。
pub fn new(pool: SqlitePool) -> Self {
Self { pool }
}
/// 写入运维错误事件。
pub async fn append(&self, event: &OpsErrorLog) -> SqliteOpsErrorLogStoreResult<()> {
append_event(&self.pool, event).await
}
/// 按保留期清理运维错误事件。
pub async fn trim_to_retention(&self, now: DateTime<Utc>) -> SqliteOpsErrorLogStoreResult<u64> {
trim_to_retention(&self.pool, now).await
}
/// 清空运维错误事件。
pub async fn clear(&self) -> SqliteOpsErrorLogStoreResult<u64> {
let result = sqlx::query("delete from ops_error_logs")
.execute(&self.pool)
.await?;
Ok(result.rows_affected())
}
/// 读取错误事件数量。
pub async fn count(&self) -> SqliteOpsErrorLogStoreResult<u64> {
let (total,): (i64,) = sqlx::query_as("select count(*) from ops_error_logs")
.fetch_one(&self.pool)
.await?;
Ok(total.max(0) as u64)
}
}
#[derive(Debug, Clone)]
struct OpsErrorSummaryFields {
client_status_code: Option<i64>,
upstream_status_code: Option<i64>,
transport: Option<String>,
attempt_index: Option<i64>,
failure_class: Option<String>,
response_id: Option<String>,
upstream_request_id: Option<String>,
}
fn ops_error_summary_fields(event: &OpsErrorLog) -> OpsErrorSummaryFields {
OpsErrorSummaryFields {
client_status_code: event.client_status_code.or_else(|| {
metadata_i64(
&event.metadata,
&["clientStatusCode", "client_status_code", "clientStatus"],
)
}),
upstream_status_code: event.upstream_status_code.or_else(|| {
metadata_i64(
&event.metadata,
&[
"upstreamStatus",
"upstreamStatusCode",
"upstream_status_code",
],
)
}),
transport: event
.transport
.clone()
.or_else(|| metadata_string(&event.metadata, &["transport"])),
attempt_index: event
.attempt_index
.or_else(|| metadata_i64(&event.metadata, &["attemptIndex", "attempt_index"])),
failure_class: event
.failure_class
.clone()
.or_else(|| metadata_string(&event.metadata, &["failureClass", "failure_class"])),
response_id: event
.response_id
.clone()
.or_else(|| metadata_string(&event.metadata, &["responseId", "response_id"])),
upstream_request_id: event.upstream_request_id.clone().or_else(|| {
metadata_string(
&event.metadata,
&[
"upstreamRequestId",
"upstream_request_id",
"openaiRequestId",
],
)
}),
}
}
async fn append_event(pool: &SqlitePool, event: &OpsErrorLog) -> SqliteOpsErrorLogStoreResult<()> {
let summary = ops_error_summary_fields(event);
sqlx::query(
"insert into ops_error_logs (id, request_id, kind, account_id, route, model, status_code, client_status_code, upstream_status_code, transport, attempt_index, failure_class, response_id, upstream_request_id, latency_ms, message, metadata_json, created_at) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
)
.bind(&event.id)
.bind(&event.request_id)
.bind(&event.kind)
.bind(&event.account_id)
.bind(&event.route)
.bind(&event.model)
.bind(event.status_code)
.bind(summary.client_status_code)
.bind(summary.upstream_status_code)
.bind(summary.transport)
.bind(summary.attempt_index)
.bind(summary.failure_class)
.bind(summary.response_id)
.bind(summary.upstream_request_id)
.bind(event.latency_ms)
.bind(&event.message)
.bind(event.metadata.to_string())
.bind(event.created_at.to_rfc3339())
.execute(pool)
.await?;
append_error_time_bucket(pool, event).await?;
Ok(())
}
async fn append_error_time_bucket(
pool: &SqlitePool,
event: &OpsErrorLog,
) -> SqliteOpsErrorLogStoreResult<()> {
let bucket_start = china_quarter_hour_start(event.created_at);
let input_tokens = metadata_usage_i64(&event.metadata, "inputTokens");
let output_tokens = metadata_usage_i64(&event.metadata, "outputTokens");
let cached_tokens = metadata_usage_i64(&event.metadata, "cachedTokens");
let first_token_latency = metadata_first_token_latency(&event.metadata).unwrap_or(0);
let first_token_latency_count = i64::from(first_token_latency > 0);
let latency = event.latency_ms.filter(|value| *value > 0).unwrap_or(0);
let latency_count = i64::from(latency > 0);
let now = Utc::now().to_rfc3339();
sqlx::query(
r"
insert into usage_time_buckets (
bucket_start,
account_id,
model,
service_tier,
request_count,
error_count,
input_tokens,
output_tokens,
cached_tokens,
first_token_latency_sum,
first_token_latency_count,
latency_sum,
latency_count,
max_latency_ms,
min_latency_ms,
updated_at
) values (?, ?, ?, ?, 1, 1, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
on conflict(bucket_start, account_id, model, service_tier) do update set
request_count = request_count + excluded.request_count,
error_count = error_count + excluded.error_count,
input_tokens = input_tokens + excluded.input_tokens,
output_tokens = output_tokens + excluded.output_tokens,
cached_tokens = cached_tokens + excluded.cached_tokens,
first_token_latency_sum = first_token_latency_sum + excluded.first_token_latency_sum,
first_token_latency_count = first_token_latency_count + excluded.first_token_latency_count,
latency_sum = latency_sum + excluded.latency_sum,
latency_count = latency_count + excluded.latency_count,
max_latency_ms = max(max_latency_ms, excluded.max_latency_ms),
min_latency_ms = case
when min_latency_ms = 0 then excluded.min_latency_ms
when excluded.min_latency_ms = 0 then min_latency_ms
else min(min_latency_ms, excluded.min_latency_ms)
end,
updated_at = excluded.updated_at",
)
.bind(bucket_start.to_rfc3339())
.bind(event.account_id.as_deref().unwrap_or_default())
.bind(event.model.as_deref().unwrap_or_default())
.bind(metadata_service_tier(&event.metadata).unwrap_or_default())
.bind(input_tokens)
.bind(output_tokens)
.bind(cached_tokens)
.bind(first_token_latency)
.bind(first_token_latency_count)
.bind(latency)
.bind(latency_count)
.bind(latency)
.bind(latency)
.bind(now)
.execute(pool)
.await?;
Ok(())
}
fn metadata_usage_i64(metadata: &Value, field: &str) -> i64 {
metadata
.get("usage")
.and_then(|usage| usage.get(field))
.or_else(|| metadata.get(field))
.and_then(Value::as_i64)
.filter(|value| *value > 0)
.unwrap_or(0)
}
fn metadata_first_token_latency(metadata: &Value) -> Option<i64> {
[
"firstTokenMs",
"first_token_ms",
"firstTokenLatencyMs",
"first_token_latency_ms",
]
.into_iter()
.find_map(|field| {
metadata
.get(field)
.or_else(|| metadata.get("usage").and_then(|usage| usage.get(field)))
.and_then(Value::as_i64)
.filter(|value| *value > 0)
})
}
async fn trim_to_retention(
pool: &SqlitePool,
now: DateTime<Utc>,
) -> SqliteOpsErrorLogStoreResult<u64> {
let cutoff = now - Duration::days(USAGE_RECORD_RETENTION_DAYS);
let result = sqlx::query("delete from ops_error_logs where created_at < ?")
.bind(cutoff.to_rfc3339())
.execute(pool)
.await?;
Ok(result.rows_affected())
}
@@ -265,7 +265,19 @@ impl AdminUsageRecordService {
/// 记录使用记录。
pub async fn record(&self, event: UsageRecord) -> Result<(), AdminUsageRecordError> {
let settings = *self.settings.read().await;
if !settings.enabled && event.level != UsageRecordLevel::Error {
if !settings.enabled {
return Ok(());
}
if !is_usage_log_event(&event) {
tracing::warn!(
usage_record_id = %event.id,
request_id = event.request_id.as_deref().unwrap_or(""),
account_id = event.account_id.as_deref().unwrap_or(""),
model = event.model.as_deref().unwrap_or(""),
level = ?event.level,
status_code = ?event.status_code,
"skipped non-usage event in usage record service"
);
return Ok(());
}
self.append_with_settings(event, settings).await
@@ -289,6 +301,21 @@ impl AdminUsageRecordService {
}
}
fn is_usage_log_event(event: &UsageRecord) -> bool {
event.level != UsageRecordLevel::Error
&& event.status_code.is_none_or(|status| status < 400)
&& event
.account_id
.as_deref()
.map(str::trim)
.is_some_and(|account_id| !account_id.is_empty())
&& event
.model
.as_deref()
.map(str::trim)
.is_some_and(|model| !model.is_empty())
}
fn apply_capture_body_policy(event: &mut UsageRecord, capture_body: bool) {
if capture_body {
return;
@@ -100,6 +100,11 @@ impl SqliteUsageRecordStore {
Self { pool }
}
/// 暴露底层连接池,供运行时组合层复用。
pub fn pool(&self) -> &SqlitePool {
&self.pool
}
/// 写入使用记录。
pub async fn append(&self, event: &UsageRecord) -> SqliteUsageRecordStoreResult<()> {
append_event(&self.pool, event).await
+40 -9
View File
@@ -110,6 +110,8 @@ struct SystemUpdateEvent {
level: UpdateLogLevel,
step: Option<String>,
message: String,
#[serde(skip_serializing_if = "is_false")]
terminal: bool,
at: String,
}
@@ -157,18 +159,23 @@ pub(crate) async fn update_event_stream(
let receiver = update_event_sender().subscribe();
let shutdown = shutdown_subscription();
let stream = futures::stream::unfold(
(receiver, shutdown),
|(mut receiver, mut shutdown)| async move {
(receiver, shutdown, false),
|(mut receiver, mut shutdown, close_after_send)| async move {
if close_after_send {
return None;
}
loop {
tokio::select! {
_ = shutdown.recv() => return None,
received = receiver.recv() => {
match received {
Ok(message) => {
let close_after_send = message.terminal;
let id = message.id.clone();
let data = serde_json::to_string(&message).unwrap_or_else(|_| "{}".to_string());
let event = Event::default().event("update").id(id).data(data);
return Some((Ok(event), (receiver, shutdown)));
return Some((Ok(event), (receiver, shutdown, close_after_send)));
}
Err(broadcast::error::RecvError::Lagged(_)) => continue,
Err(broadcast::error::RecvError::Closed) => return None,
@@ -192,7 +199,7 @@ pub(crate) async fn perform_update(
.map_err(|_| AdminError::conflict("System update already running"))?;
let config = SystemUpdateConfig::from_env();
if let Some(reason) = config.update_support_error() {
emit_update_event(
emit_terminal_update_event(
UpdateLogLevel::Error,
None,
Some("preflight"),
@@ -217,7 +224,7 @@ pub(crate) async fn perform_update(
)
.await
.map_err(|error| {
emit_update_event(UpdateLogLevel::Error, None, Some("release"), error.clone());
emit_terminal_update_event(UpdateLogLevel::Error, None, Some("release"), error.clone());
AdminError::bad_gateway(error)
})?;
let info = update_info_from_release(&config, release.clone());
@@ -226,7 +233,7 @@ pub(crate) async fn perform_update(
"远端最新版本已变更为 v{},请重新检查并确认",
info.latest_version
);
emit_update_event(
emit_terminal_update_event(
UpdateLogLevel::Warning,
None,
Some("release"),
@@ -235,7 +242,7 @@ pub(crate) async fn perform_update(
return Err(AdminError::conflict(message));
}
if !info.has_update {
emit_update_event(
emit_terminal_update_event(
UpdateLogLevel::Warning,
None,
Some("release"),
@@ -261,14 +268,14 @@ pub(crate) async fn perform_update(
);
let result = perform_release_update(&config, &release, &target_version, &operation_id).await;
if let Err(error) = &result {
emit_update_event(
emit_terminal_update_event(
UpdateLogLevel::Error,
Some(&operation_id),
Some("failed"),
error.to_string(),
);
} else {
emit_update_event(
emit_terminal_update_event(
UpdateLogLevel::Success,
Some(&operation_id),
Some("done"),
@@ -732,6 +739,25 @@ fn emit_update_event(
operation_id: Option<&str>,
step: Option<&str>,
message: impl Into<String>,
) {
emit_update_event_with_terminal(level, operation_id, step, message, false);
}
fn emit_terminal_update_event(
level: UpdateLogLevel,
operation_id: Option<&str>,
step: Option<&str>,
message: impl Into<String>,
) {
emit_update_event_with_terminal(level, operation_id, step, message, true);
}
fn emit_update_event_with_terminal(
level: UpdateLogLevel,
operation_id: Option<&str>,
step: Option<&str>,
message: impl Into<String>,
terminal: bool,
) {
let now = Utc::now();
let event = SystemUpdateEvent {
@@ -744,11 +770,16 @@ fn emit_update_event(
level,
step: step.map(ToString::to_string),
message: message.into(),
terminal,
at: now.to_rfc3339(),
};
let _ = update_event_sender().send(event);
}
fn is_false(value: &bool) -> bool {
!*value
}
fn format_bytes(bytes: u64) -> String {
const KIB: u64 = 1024;
const MIB: u64 = KIB * 1024;
-3
View File
@@ -57,9 +57,6 @@ pub struct ServerConfig {
pub host: String,
/// 监听端口。
pub port: u16,
/// 可信反向代理 IP 或 CIDR。非空时只有这些 peer 的转发 IP 头会被采信。
#[serde(default)]
pub trusted_proxies: Vec<String>,
}
/// 上游 API 地址配置。
+11 -95
View File
@@ -4,7 +4,7 @@ use std::net::{IpAddr, SocketAddr};
use std::sync::LazyLock;
use axum::{
extract::{connect_info::ConnectInfo, Request, State},
extract::{connect_info::ConnectInfo, Request},
http::{HeaderMap, HeaderValue},
middleware::Next,
response::Response,
@@ -19,7 +19,7 @@ const CF_CONNECTING_IP_HEADER: &str = "cf-connecting-ip";
const REAL_IP_HEADER: &str = "x-real-ip";
const X_FORWARDED_FOR_HEADER: &str = "x-forwarded-for";
/// 私有 / 回环 / 唯一本地地址网段,用于在自动模式下从 `X-Forwarded-For` 中跳过内网跳板 IP。
/// 私有 / 回环 / 唯一本地地址网段,用于从 `X-Forwarded-For` 中跳过内网跳板 IP。
static PRIVATE_NETWORKS: LazyLock<Vec<IpNet>> = LazyLock::new(|| {
[
"10.0.0.0/8",
@@ -38,40 +38,6 @@ fn is_private_ip(ip: IpAddr) -> bool {
PRIVATE_NETWORKS.iter().any(|network| network.contains(&ip))
}
/// 可信反向代理配置。
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TrustedProxyConfig {
networks: Vec<IpNet>,
}
impl TrustedProxyConfig {
/// 从 IP 或 CIDR 字符串构造可信代理配置。
pub fn from_entries(entries: &[String]) -> Result<Self, TrustedProxyConfigError> {
let networks = entries
.iter()
.map(|entry| parse_trusted_proxy_entry(entry))
.collect::<Result<Vec<_>, _>>()?;
Ok(Self { networks })
}
fn is_trusted(&self, ip: IpAddr) -> bool {
self.networks.iter().any(|network| network.contains(&ip))
}
/// 是否未配置任何可信代理(决定是否启用自动真实 IP 探测)。
fn is_empty(&self) -> bool {
self.networks.is_empty()
}
}
/// 可信代理配置错误。
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum TrustedProxyConfigError {
/// 配置项不是 IP 地址或 CIDR。
#[error("invalid trusted proxy entry `{entry}`; expected an IP address or CIDR network")]
InvalidEntry { entry: String },
}
/// 请求 ID。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RequestId(String);
@@ -97,7 +63,7 @@ impl RequestId {
}
}
/// 由连接来源和可信代理链解析出的客户端 IP。
/// 由连接来源和转发头解析出的客户端 IP。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClientIp(String);
@@ -118,17 +84,7 @@ fn valid_request_id(value: &str) -> bool {
/// 为请求附加请求 ID,并在响应头中回写。
pub async fn attach_request_id(mut request: Request, next: Next) -> Response {
attach_request_context(&TrustedProxyConfig::default(), &mut request);
run_with_request_id(request, next).await
}
/// 为请求附加请求上下文,并按可信代理配置解析真实客户端 IP。
pub async fn attach_request_id_with_proxy_config(
State(trusted_proxies): State<TrustedProxyConfig>,
mut request: Request,
next: Next,
) -> Response {
attach_request_context(&trusted_proxies, &mut request);
attach_request_context(&mut request);
run_with_request_id(request, next).await
}
@@ -147,17 +103,16 @@ async fn run_with_request_id(mut request: Request, next: Next) -> Response {
response
}
fn attach_request_context(trusted_proxies: &TrustedProxyConfig, request: &mut Request) {
attach_client_ip_from_connection(trusted_proxies, request);
fn attach_request_context(request: &mut Request) {
attach_client_ip_from_connection(request);
}
fn attach_client_ip_from_connection(trusted_proxies: &TrustedProxyConfig, request: &mut Request) {
fn attach_client_ip_from_connection(request: &mut Request) {
let peer_ip = request
.extensions()
.get::<ConnectInfo<SocketAddr>>()
.map(|ConnectInfo(addr)| addr.ip());
let client_ip =
peer_ip.map(|peer_ip| client_ip_from_peer(peer_ip, request.headers(), trusted_proxies));
let client_ip = peer_ip.map(|peer_ip| client_ip_from_peer(peer_ip, request.headers()));
let Some(client_ip) = client_ip else {
return;
@@ -165,28 +120,12 @@ fn attach_client_ip_from_connection(trusted_proxies: &TrustedProxyConfig, reques
request.extensions_mut().insert(ClientIp(client_ip));
}
fn client_ip_from_peer(
peer_ip: IpAddr,
headers: &HeaderMap,
trusted_proxies: &TrustedProxyConfig,
) -> String {
if trusted_proxies.is_empty() {
// 未配置可信代理:自动模式,按 CF-Connecting-IP → X-Real-IP →
// X-Forwarded-For(首个公网 IP)→ peer IP 的优先级解析真实客户端 IP。
return auto_forwarded_client_ip(headers).unwrap_or_else(|| peer_ip.to_string());
}
if trusted_proxies.is_trusted(peer_ip) {
// 已配置可信代理且直连来源可信:只采信转发头。
trusted_forwarded_client_ip(headers).unwrap_or_else(|| peer_ip.to_string())
} else {
// 已配置可信代理但直连来源不可信:忽略转发头,使用 peer IP。
peer_ip.to_string()
}
fn client_ip_from_peer(peer_ip: IpAddr, headers: &HeaderMap) -> String {
auto_forwarded_client_ip(headers).unwrap_or_else(|| peer_ip.to_string())
}
/// 自动模式下解析转发头中的真实客户端 IP。
/// 解析转发头中的真实客户端 IP。
///
/// 未配置可信代理时使用,对齐常见反代(Cloudflare / Nginx)默认行为:
/// `CF-Connecting-IP` → `X-Real-IP` → `X-Forwarded-For` 首个公网 IP。
fn auto_forwarded_client_ip(headers: &HeaderMap) -> Option<String> {
if let Some(cf_ip) = header_string(headers, CF_CONNECTING_IP_HEADER) {
@@ -212,13 +151,6 @@ fn forwarded_for_public_ip(headers: &HeaderMap) -> Option<String> {
.map(ToString::to_string)
}
fn trusted_forwarded_client_ip(headers: &HeaderMap) -> Option<String> {
header_string(headers, CF_CONNECTING_IP_HEADER)
.or_else(|| header_string(headers, REAL_IP_HEADER))
.or_else(|| forwarded_for_public_ip(headers))
.or_else(|| first_forwarded_for_value(headers))
}
fn header_string(headers: &HeaderMap, name: &str) -> Option<String> {
headers
.get(name)
@@ -237,19 +169,3 @@ fn first_forwarded_for_value(headers: &HeaderMap) -> Option<String> {
.filter(|value| !value.is_empty())
.map(ToString::to_string)
}
fn parse_trusted_proxy_entry(entry: &str) -> Result<IpNet, TrustedProxyConfigError> {
if let Ok(network) = entry.parse::<IpNet>() {
return Ok(network);
}
entry
.parse::<IpAddr>()
.map(IpNet::from)
.map_err(|_| invalid_trusted_proxy_entry(entry))
}
fn invalid_trusted_proxy_entry(entry: &str) -> TrustedProxyConfigError {
TrustedProxyConfigError::InvalidEntry {
entry: entry.to_string(),
}
}
+3 -22
View File
@@ -5,10 +5,7 @@ use std::path::Path;
use axum::{extract::State, http::StatusCode, middleware, routing::get, Router};
use crate::admin;
use crate::http::middleware::{
request_id::{attach_request_id_with_proxy_config, TrustedProxyConfig},
trace::http_trace_layer,
};
use crate::http::middleware::{request_id::attach_request_id, trace::http_trace_layer};
use crate::proxy;
use crate::runtime::state::AppState;
use crate::web;
@@ -18,34 +15,18 @@ pub const DEFAULT_ASSET_DIST_DIR: &str = "web/dist";
/// 构造整个 HTTP 服务路由。
pub fn router() -> Router<AppState> {
router_with_trusted_proxies(TrustedProxyConfig::default())
}
/// 使用指定可信代理配置构造整个 HTTP 服务路由。
pub fn router_with_trusted_proxies(trusted_proxies: TrustedProxyConfig) -> Router<AppState> {
router_with_assets_and_trusted_proxies(DEFAULT_ASSET_DIST_DIR, trusted_proxies)
router_with_assets(DEFAULT_ASSET_DIST_DIR)
}
/// 使用指定前端构建产物目录构造整个 HTTP 服务路由。
pub fn router_with_assets(dist_dir: impl AsRef<Path>) -> Router<AppState> {
router_with_assets_and_trusted_proxies(dist_dir, TrustedProxyConfig::default())
}
/// 使用指定前端构建产物目录和可信代理配置构造整个 HTTP 服务路由。
pub fn router_with_assets_and_trusted_proxies(
dist_dir: impl AsRef<Path>,
trusted_proxies: TrustedProxyConfig,
) -> Router<AppState> {
Router::new()
.route("/healthz", get(healthz))
.merge(proxy::router::router())
.merge(admin::router::router())
.fallback_service(web::assets::spa_router(dist_dir))
.layer(http_trace_layer())
.layer(middleware::from_fn_with_state(
trusted_proxies,
attach_request_id_with_proxy_config,
))
.layer(middleware::from_fn(attach_request_id))
}
async fn healthz(State(state): State<AppState>) -> StatusCode {
+6 -1
View File
@@ -4,7 +4,7 @@ use std::{fs, path::Path, str::FromStr, time::Duration};
use sqlx::{sqlite::SqliteConnectOptions, SqlitePool};
const CURRENT_SCHEMA_VERSION: i64 = 2;
const CURRENT_SCHEMA_VERSION: i64 = 3;
const MIGRATIONS: &[Migration] = &[
Migration {
version: 1,
@@ -16,6 +16,11 @@ const MIGRATIONS: &[Migration] = &[
name: "rename_rotation_strategies",
sql: include_str!("migrations/0002_rename_rotation_strategies.sql"),
},
Migration {
version: 3,
name: "ops_error_logs",
sql: include_str!("migrations/0003_ops_error_logs.sql"),
},
];
struct Migration {
@@ -0,0 +1,31 @@
create table ops_error_logs (
id text primary key,
request_id text,
kind text not null,
account_id text,
route text,
model text,
status_code integer check (status_code is null or (status_code >= 100 and status_code <= 599)),
client_status_code integer check (client_status_code is null or (client_status_code >= 100 and client_status_code <= 599)),
upstream_status_code integer check (upstream_status_code is null or (upstream_status_code >= 100 and upstream_status_code <= 599)),
transport text,
attempt_index integer check (attempt_index is null or attempt_index >= 0),
failure_class text,
response_id text,
upstream_request_id text,
latency_ms integer check (latency_ms is null or latency_ms >= 0),
message text not null,
metadata_json text not null,
created_at text not null
);
create index idx_ops_error_logs_created_id on ops_error_logs(created_at desc, id desc);
create index idx_ops_error_logs_request_id on ops_error_logs(request_id) where request_id is not null;
create index idx_ops_error_logs_account on ops_error_logs(account_id, created_at desc) where account_id is not null;
create index idx_ops_error_logs_route_created on ops_error_logs(route, created_at desc) where route is not null;
create index idx_ops_error_logs_model_created on ops_error_logs(model, created_at desc) where model is not null;
create index idx_ops_error_logs_status_created on ops_error_logs(status_code, created_at desc) where status_code is not null;
create index idx_ops_error_logs_transport_created on ops_error_logs(transport, created_at desc) where transport is not null;
create index idx_ops_error_logs_failure_class on ops_error_logs(failure_class, created_at desc) where failure_class is not null;
create index idx_ops_error_logs_response_id on ops_error_logs(response_id) where response_id is not null;
create index idx_ops_error_logs_upstream_request_id on ops_error_logs(upstream_request_id) where upstream_request_id is not null;
@@ -4,8 +4,9 @@ use serde_json::{json, Map, Value};
use crate::{
admin::monitoring::{
usage_record_model::{ResponseUsageRecord, UsageRecord, UsageRecordLevel},
usage_record_service::AdminUsageRecordService,
ops_error_model::OpsErrorLog,
ops_error_service::AdminOpsErrorLogService,
usage_record_model::{UsageRecord, UsageRecordLevel},
},
infra::time::elapsed_millis_i64,
proxy::dispatch::{
@@ -17,7 +18,7 @@ use crate::{
usage_events::{
enrich_event_route_metadata, enrich_usage_record_identity,
event_kind as response_event_kind, reasoning_effort_from_request,
record_dispatch_error_event, record_response_event, DispatchErrorUsageRecord,
record_dispatch_error_event, DispatchErrorLogRecord,
},
},
upstream::{
@@ -39,7 +40,7 @@ use super::{
};
pub(super) struct ResponseUpstreamErrorEventRecord<'a> {
pub(super) usage_records: &'a AdminUsageRecordService,
pub(super) ops_errors: &'a AdminOpsErrorLogService,
pub(super) request_id: &'a str,
pub(super) account_id: &'a str,
pub(super) account_email: Option<&'a str>,
@@ -55,7 +56,7 @@ pub(super) struct ResponseUpstreamErrorEventRecord<'a> {
}
pub(super) struct ResponseStreamFailureEventRecord<'a> {
pub(super) usage_records: &'a AdminUsageRecordService,
pub(super) ops_errors: &'a AdminOpsErrorLogService,
pub(super) request_id: &'a str,
pub(super) account_id: &'a str,
pub(super) route: &'a str,
@@ -73,7 +74,7 @@ pub(super) struct ResponseStreamFailureEventRecord<'a> {
}
pub(super) struct ResponseDispatchErrorEventRecord<'a> {
pub(super) usage_records: &'a AdminUsageRecordService,
pub(super) ops_errors: &'a AdminOpsErrorLogService,
pub(super) request_id: &'a str,
pub(super) account_id: Option<&'a str>,
pub(super) route: &'a str,
@@ -110,8 +111,8 @@ pub(super) async fn record_response_dispatch_error_event(
dispatch_error_upstream_status_code(record.error),
);
}
record_dispatch_error_event(DispatchErrorUsageRecord {
usage_records: record.usage_records,
record_dispatch_error_event(DispatchErrorLogRecord {
ops_errors: record.ops_errors,
request_id: record.request_id,
account_id: record.account_id,
route: record.route,
@@ -135,11 +136,7 @@ pub(super) async fn record_response_upstream_error_event(
Some(backend_transport_name(record.transport)),
);
enrich_event_route_metadata(&mut metadata, record.route);
let mut event = UsageRecord::new(
"v1.response",
UsageRecordLevel::Error,
"v1 responses upstream request failed",
);
let mut event = OpsErrorLog::new("v1.response", "v1 responses upstream request failed");
event.request_id = Some(record.request_id.to_string());
event.account_id = Some(record.account_id.to_string());
event.route = Some(record.route.to_string());
@@ -167,8 +164,17 @@ pub(super) async fn record_response_upstream_error_event(
);
}
}
enrich_usage_record_identity(
&mut metadata,
Some(record.request.model()),
record.model,
record.request.client_ip.as_deref(),
record.request.client_user_agent.as_deref(),
reasoning_effort_from_request(record.request),
record.request.service_tier(),
);
event.metadata = metadata;
if let Err(error) = record.usage_records.record(event).await {
if let Err(error) = record.ops_errors.record(event).await {
tracing::warn!(account_id = %record.account_id, error = %error, "failed to record upstream error event");
}
}
@@ -204,25 +210,38 @@ pub(super) async fn record_prefetched_response_stream_failure_event(
Some(record.attempt),
);
}
record_response_event(ResponseUsageRecord {
usage_records: record.usage_records,
request_id: record.request_id,
account_id: record.account_id,
route: record.route,
model: record.model,
requested_model: Some(record.requested_model),
client_ip: record.request.client_ip.as_deref(),
client_user_agent: record.request.client_user_agent.as_deref(),
reasoning_effort: reasoning_effort_from_request(record.request),
service_tier: record.request.service_tier(),
started_at: record.started_at,
status_code: event_status_code,
level: UsageRecordLevel::Error,
message: "v1 responses stream failed",
metadata,
rate_limit_headers: record.rate_limit_headers,
})
.await;
enrich_event_route_metadata(&mut metadata, record.route);
enrich_usage_record_identity(
&mut metadata,
Some(record.requested_model),
record.model,
record.request.client_ip.as_deref(),
record.request.client_user_agent.as_deref(),
reasoning_effort_from_request(record.request),
record.request.service_tier(),
);
let mut event = OpsErrorLog::new(
response_event_kind(record.route),
"v1 responses stream failed",
);
event.request_id = Some(record.request_id.to_string());
event.account_id = Some(record.account_id.to_string());
event.route = Some(record.route.to_string());
event.model = Some(record.model.to_string());
event.status_code = Some(event_status_code);
event.latency_ms = Some(elapsed_millis_i64(record.started_at));
if !record.rate_limit_headers.is_empty() {
if let Some(object) = metadata.as_object_mut() {
object.insert(
"rateLimitHeaders".to_string(),
serde_json::json!(record.rate_limit_headers),
);
}
}
event.metadata = metadata;
if let Err(error) = record.ops_errors.record(event).await {
tracing::warn!(account_id = %record.account_id, error = %error, "failed to record prefetched stream error event");
}
}
fn ensure_stream_metadata_flag(metadata: &mut Value) {
@@ -469,13 +488,6 @@ pub(super) async fn record_live_response_stream_event(
body,
);
log_live_response_stream_finalized(context, status_code, level, message, &metadata, body);
let mut event = UsageRecord::new(response_event_kind(&context.route), level, message);
event.request_id = Some(context.request_id.clone());
event.account_id = Some(context.account_id.clone());
event.route = Some(context.route.clone());
event.model = Some(context.display_model.clone());
event.status_code = Some(status_code);
event.latency_ms = Some(elapsed_millis_i64(context.started_at));
enrich_usage_record_identity(
&mut metadata,
Some(&context.requested_model),
@@ -485,12 +497,38 @@ pub(super) async fn record_live_response_stream_event(
reasoning_effort_from_request(&context.request),
context.request.service_tier(),
);
event.metadata = metadata;
if let Err(error) = context.usage_records.record(event).await {
tracing::warn!(account_id = %context.account_id, error = %error, "failed to record live response stream event");
if is_success_usage_event(level, status_code) {
let mut event = UsageRecord::new(response_event_kind(&context.route), level, message);
event.request_id = Some(context.request_id.clone());
event.account_id = Some(context.account_id.clone());
event.route = Some(context.route.clone());
event.model = Some(context.display_model.clone());
event.status_code = Some(status_code);
event.latency_ms = Some(elapsed_millis_i64(context.started_at));
event.metadata = metadata;
if let Err(error) = context.usage_records.record(event).await {
tracing::warn!(account_id = %context.account_id, error = %error, "failed to record live response stream event");
}
} else {
let mut event = OpsErrorLog::new(response_event_kind(&context.route), message);
event.request_id = Some(context.request_id.clone());
event.account_id = Some(context.account_id.clone());
event.route = Some(context.route.clone());
event.model = Some(context.display_model.clone());
event.status_code = Some(status_code);
event.latency_ms = Some(elapsed_millis_i64(context.started_at));
event.metadata = metadata;
if let Err(error) = context.ops_errors.record(event).await {
tracing::warn!(account_id = %context.account_id, error = %error, "failed to record live response stream error event");
}
}
}
fn is_success_usage_event(level: UsageRecordLevel, status_code: i64) -> bool {
level != UsageRecordLevel::Error && status_code < 400
}
fn log_live_response_stream_finalized(
context: &LiveResponseStreamContext,
status_code: i64,
+123 -26
View File
@@ -17,6 +17,7 @@ use tokio::sync::Mutex;
use crate::{
admin::monitoring::{
ops_error_service::AdminOpsErrorLogService,
usage_record_model::{ResponseUsageRecord, UsageRecordLevel},
usage_record_service::AdminUsageRecordService,
},
@@ -110,6 +111,7 @@ pub struct ResponseDispatchService {
session_affinity: Arc<RuntimeSessionAffinityService>,
reasoning_replay: Arc<Mutex<ReasoningReplayCache>>,
usage_records: Arc<AdminUsageRecordService>,
ops_errors: Arc<AdminOpsErrorLogService>,
token_refresh: Arc<RuntimeTokenRefreshService<OpenAiTokenClient>>,
installation_id: Option<String>,
cloudflare: CloudflareRecovery,
@@ -121,6 +123,7 @@ pub(crate) struct ResponseDispatchServiceParts {
pub codex: Arc<CodexBackendClient>,
pub session_affinity: Arc<RuntimeSessionAffinityService>,
pub usage_records: Arc<AdminUsageRecordService>,
pub ops_errors: Arc<AdminOpsErrorLogService>,
pub token_refresh: Arc<RuntimeTokenRefreshService<OpenAiTokenClient>>,
pub installation_id: Option<String>,
pub cloudflare: CloudflareRecovery,
@@ -130,6 +133,34 @@ pub(crate) struct ResponseDispatchServiceParts {
const DEFAULT_REASONING_REPLAY_TTL_SECS: i64 = 55 * 60;
const IMPLICIT_RESUME_MAX_AGE_SECS: i64 = DEFAULT_REASONING_REPLAY_TTL_SECS;
#[derive(Debug, Clone, Default)]
struct AccountAffinityDecision {
preferred_account_id: Option<String>,
request_history_owner: RequestHistoryOwner,
}
#[derive(Debug, Clone, Default)]
enum RequestHistoryOwner {
#[default]
Absent,
Known(String),
Unknown,
}
impl AccountAffinityDecision {
fn preferred_account_id(&self) -> Option<&str> {
self.preferred_account_id.as_deref()
}
fn should_strip_request_history_for(&self, account_id: &str) -> bool {
match &self.request_history_owner {
RequestHistoryOwner::Absent => false,
RequestHistoryOwner::Known(history_account_id) => history_account_id != account_id,
RequestHistoryOwner::Unknown => true,
}
}
}
/// Responses live SSE 响应体流。
pub type ResponseBodyStream =
Pin<Box<dyn Stream<Item = Result<Bytes, ResponseDispatchStreamError>> + Send + 'static>>;
@@ -150,6 +181,7 @@ impl ResponseDispatchService {
DEFAULT_REASONING_REPLAY_TTL_SECS,
)))),
usage_records: parts.usage_records,
ops_errors: parts.ops_errors,
token_refresh: parts.token_refresh,
installation_id: parts.installation_id,
cloudflare: parts.cloudflare,
@@ -260,7 +292,31 @@ impl ResponseDispatchService {
Some(snapshot)
}
async fn preferred_account_id_for_request(
async fn account_affinity_for_request(
&self,
request: &CodexResponsesRequest,
now: DateTime<Utc>,
) -> AccountAffinityDecision {
let has_previous_response_id = request.previous_response_id().is_some();
if let Some(account_id) = self.previous_response_account_id(request, now).await {
return AccountAffinityDecision {
preferred_account_id: Some(account_id.clone()),
request_history_owner: RequestHistoryOwner::Known(account_id),
};
}
let conversation_account_id = self.conversation_account_id(request, now).await;
AccountAffinityDecision {
preferred_account_id: conversation_account_id,
request_history_owner: if has_previous_response_id {
RequestHistoryOwner::Unknown
} else {
RequestHistoryOwner::Absent
},
}
}
async fn previous_response_account_id(
&self,
request: &CodexResponsesRequest,
now: DateTime<Utc>,
@@ -271,6 +327,21 @@ impl ResponseDispatchService {
.await
}
async fn conversation_account_id(
&self,
request: &CodexResponsesRequest,
now: DateTime<Utc>,
) -> Option<String> {
let conversation_id = request
.prompt_cache_key()
.map(str::trim)
.filter(|value| !value.is_empty())?;
let variant_hash = compute_variant_hash(request);
self.session_affinity
.lookup_latest_account_by_conversation(conversation_id, None, Some(&variant_hash), now)
.await
}
async fn recover_request_history(
&self,
request: &mut CodexResponsesRequest,
@@ -279,13 +350,22 @@ impl ResponseDispatchService {
if let Some(previous_response_id) = request.previous_response_id() {
self.session_affinity.forget(previous_response_id).await;
}
if let Some(snapshot) = implicit_resume.take() {
snapshot.restore(request);
request.set_previous_response_id(None);
request.turn_state = None;
} else {
strip_request_history(request);
restore_request_without_history(request, implicit_resume);
}
fn strip_history_if_account_changed(
request: &mut CodexResponsesRequest,
implicit_resume: &mut Option<ImplicitResumeSnapshot>,
account_affinity: &AccountAffinityDecision,
acquired_account_id: &str,
) {
if request.previous_response_id().is_none()
|| !account_affinity.should_strip_request_history_for(acquired_account_id)
{
return;
}
restore_request_without_history(request, implicit_resume);
}
async fn apply_cascading_ban_defense(
@@ -326,13 +406,7 @@ impl ResponseDispatchService {
let response_id_to_forget = explicit_previous_response_id
.or(request.previous_response_id())
.map(str::to_string);
if let Some(snapshot) = implicit_resume.take() {
snapshot.restore(request);
request.set_previous_response_id(None);
request.turn_state = None;
} else {
strip_request_history(request);
}
restore_request_without_history(request, implicit_resume);
if let Some(response_id) = response_id_to_forget {
self.session_affinity.forget(&response_id).await;
}
@@ -380,9 +454,9 @@ impl ResponseDispatchService {
let now = Utc::now();
let explicit_previous_response_id = request.previous_response_id().map(ToString::to_string);
let mut implicit_resume = self.prepare_response_session(&mut request).await;
let preferred_account_id = self.preferred_account_id_for_request(&request, now).await;
let account_affinity = self.account_affinity_for_request(&request, now).await;
let mut acquire_request = AccountAcquireRequest::new(request.model(), now);
if let Some(preferred_account_id) = preferred_account_id.as_deref() {
if let Some(preferred_account_id) = account_affinity.preferred_account_id() {
acquire_request = acquire_request.with_preferred_account_id(preferred_account_id);
}
let mut excluded_account_ids = Vec::new();
@@ -493,11 +567,17 @@ impl ResponseDispatchService {
self.apply_cascading_ban_defense(
&mut request,
&mut implicit_resume,
preferred_account_id.as_deref(),
account_affinity.preferred_account_id(),
&acquired.account.id,
explicit_previous_response_id.as_deref(),
)
.await;
Self::strip_history_if_account_changed(
&mut request,
&mut implicit_resume,
&account_affinity,
&acquired.account.id,
);
self.account_pool.wait_for_request_interval(&acquired).await;
let account = acquired.account;
let release_account_id = account.id.clone();
@@ -758,7 +838,7 @@ impl ResponseDispatchService {
}
Err(error) => {
record_response_upstream_error_event(ResponseUpstreamErrorEventRecord {
usage_records: &self.usage_records,
ops_errors: &self.ops_errors,
request_id,
account_id: &release_account_id,
account_email: account.email.as_deref(),
@@ -904,7 +984,7 @@ impl ResponseDispatchService {
error: &ResponseDispatchError,
) {
record_response_dispatch_error_event(ResponseDispatchErrorEventRecord {
usage_records: &self.usage_records,
ops_errors: &self.ops_errors,
request_id,
account_id: details.account_id,
route,
@@ -935,9 +1015,9 @@ impl ResponseDispatchService {
let now = Utc::now();
let explicit_previous_response_id = request.previous_response_id().map(ToString::to_string);
let mut implicit_resume = self.prepare_response_session(&mut request).await;
let preferred_account_id = self.preferred_account_id_for_request(&request, now).await;
let account_affinity = self.account_affinity_for_request(&request, now).await;
let mut acquire_request = AccountAcquireRequest::new(request.model(), now);
if let Some(preferred_account_id) = preferred_account_id.as_deref() {
if let Some(preferred_account_id) = account_affinity.preferred_account_id() {
acquire_request = acquire_request.with_preferred_account_id(preferred_account_id);
}
let mut excluded_account_ids = Vec::new();
@@ -1053,11 +1133,17 @@ impl ResponseDispatchService {
self.apply_cascading_ban_defense(
&mut request,
&mut implicit_resume,
preferred_account_id.as_deref(),
account_affinity.preferred_account_id(),
&acquired.account.id,
explicit_previous_response_id.as_deref(),
)
.await;
Self::strip_history_if_account_changed(
&mut request,
&mut implicit_resume,
&account_affinity,
&acquired.account.id,
);
self.account_pool.wait_for_request_interval(&acquired).await;
let account = acquired.account;
@@ -1236,7 +1322,7 @@ impl ResponseDispatchService {
if let ResponseDispatchError::Upstream(upstream_error) = &error {
record_response_upstream_error_event(
ResponseUpstreamErrorEventRecord {
usage_records: &self.usage_records,
ops_errors: &self.ops_errors,
request_id,
account_id: &release_account_id,
account_email: account.email.as_deref(),
@@ -1341,7 +1427,7 @@ impl ResponseDispatchService {
self.account_pool.release(&release_account_id).await;
record_prefetched_response_stream_failure_event(
ResponseStreamFailureEventRecord {
usage_records: &self.usage_records,
ops_errors: &self.ops_errors,
request_id,
account_id: &release_account_id,
route,
@@ -1367,6 +1453,7 @@ impl ResponseDispatchService {
session_affinity: Arc::clone(&self.session_affinity),
reasoning_replay: Arc::clone(&self.reasoning_replay),
usage_records: Arc::clone(&self.usage_records),
ops_errors: Arc::clone(&self.ops_errors),
cloudflare: self.cloudflare.clone(),
account_id: account.id,
account_plan_type: account.plan_type,
@@ -1503,7 +1590,7 @@ impl ResponseDispatchService {
Err(error) => {
self.account_pool.release(&release_account_id).await;
record_response_upstream_error_event(ResponseUpstreamErrorEventRecord {
usage_records: &self.usage_records,
ops_errors: &self.ops_errors,
request_id,
account_id: &release_account_id,
account_email: account.email.as_deref(),
@@ -1795,7 +1882,7 @@ impl ResponseDispatchService {
error: &ResponseDispatchError,
) {
record_response_dispatch_error_event(ResponseDispatchErrorEventRecord {
usage_records: &self.usage_records,
ops_errors: &self.ops_errors,
request_id,
account_id,
route: "/v1/responses/compact",
@@ -1814,3 +1901,13 @@ fn strip_request_history(request: &mut CodexResponsesRequest) {
request.set_previous_response_id(None);
request.turn_state = None;
}
fn restore_request_without_history(
request: &mut CodexResponsesRequest,
implicit_resume: &mut Option<ImplicitResumeSnapshot>,
) {
if let Some(snapshot) = implicit_resume.take() {
snapshot.restore(request);
}
strip_request_history(request);
}
@@ -5,7 +5,8 @@ use tokio::sync::Mutex;
use crate::{
admin::monitoring::{
usage_record_model::UsageRecordLevel, usage_record_service::AdminUsageRecordService,
ops_error_service::AdminOpsErrorLogService, usage_record_model::UsageRecordLevel,
usage_record_service::AdminUsageRecordService,
},
infra::time::elapsed_millis_i64,
proxy::{
@@ -49,6 +50,7 @@ pub(super) struct LiveResponseStreamContext {
pub(super) session_affinity: Arc<RuntimeSessionAffinityService>,
pub(super) reasoning_replay: Arc<Mutex<ReasoningReplayCache>>,
pub(super) usage_records: Arc<AdminUsageRecordService>,
pub(super) ops_errors: Arc<AdminOpsErrorLogService>,
pub(super) cloudflare: CloudflareRecovery,
pub(super) account_id: String,
pub(super) account_plan_type: Option<String>,
+47 -11
View File
@@ -106,6 +106,38 @@ impl SessionAffinityMap {
variant_hash: Option<&str>,
now: DateTime<Utc>,
) -> Option<String> {
self.latest_entry_by_conversation(conversation_id, max_age, variant_hash, now)
.map(|(response_id, _)| response_id.clone())
}
pub fn lookup_latest_account_by_conversation(
&self,
conversation_id: &str,
max_age: Option<Duration>,
variant_hash: Option<&str>,
now: DateTime<Utc>,
) -> Option<String> {
self.latest_entry_by_conversation(conversation_id, max_age, variant_hash, now)
.map(|(_, entry)| entry.account_id.clone())
}
pub fn forget(&mut self, response_id: &str) -> bool {
self.entries.remove(response_id).is_some()
}
fn active_entry(&self, response_id: &str, now: DateTime<Utc>) -> Option<&SessionAffinityEntry> {
self.entries
.get(response_id)
.filter(|entry| self.entry_is_active(entry, now))
}
fn latest_entry_by_conversation(
&self,
conversation_id: &str,
max_age: Option<Duration>,
variant_hash: Option<&str>,
now: DateTime<Utc>,
) -> Option<(&String, &SessionAffinityEntry)> {
self.entries
.iter()
.filter(|(_, entry)| entry.conversation_id == conversation_id)
@@ -118,17 +150,6 @@ impl SessionAffinityMap {
max_age.is_none_or(|max_age| now.signed_duration_since(entry.created_at) <= max_age)
})
.max_by_key(|(_, entry)| entry.created_at)
.map(|(response_id, _)| response_id.clone())
}
pub fn forget(&mut self, response_id: &str) -> bool {
self.entries.remove(response_id).is_some()
}
fn active_entry(&self, response_id: &str, now: DateTime<Utc>) -> Option<&SessionAffinityEntry> {
self.entries
.get(response_id)
.filter(|entry| self.entry_is_active(entry, now))
}
fn stored_record_is_active(&self, record: &StoredSessionAffinity, now: DateTime<Utc>) -> bool {
@@ -630,6 +651,21 @@ impl RuntimeSessionAffinityService {
.lookup_latest_response_by_conversation(conversation_id, max_age, variant_hash, now)
}
pub async fn lookup_latest_account_by_conversation(
&self,
conversation_id: &str,
max_age: Option<Duration>,
variant_hash: Option<&str>,
now: DateTime<Utc>,
) -> Option<String> {
self.map.read().await.lookup_latest_account_by_conversation(
conversation_id,
max_age,
variant_hash,
now,
)
}
pub async fn forget(&self, response_id: &str) -> bool {
let in_memory = self.map.write().await.forget(response_id);
match self.store.forget(response_id).await {
+4 -1
View File
@@ -103,7 +103,10 @@ pub(crate) async fn verify_acquired_quota_if_required(
.apply_quota_snapshot(&account_id, &quota)
.await;
if quota_snapshot_limit_reached(&quota) {
context.account_pool.release(&account_id).await;
context
.account_pool
.release_without_request_usage(&account_id)
.await;
context.excluded_account_ids.push(account_id.clone());
*context.verify_attempts += 1;
let max_attempts_reached = *context.verify_attempts >= MAX_QUOTA_VERIFY_ATTEMPTS;
+8 -11
View File
@@ -6,15 +6,16 @@ use serde_json::Value;
use crate::{
admin::monitoring::{
usage_record_model::{ResponseUsageRecord, UsageRecord, UsageRecordLevel},
usage_record_service::AdminUsageRecordService,
ops_error_model::OpsErrorLog,
ops_error_service::AdminOpsErrorLogService,
usage_record_model::{ResponseUsageRecord, UsageRecord},
},
infra::time::elapsed_millis_i64,
upstream::protocol::responses::{CodexCompactRequest, CodexResponsesRequest},
};
pub(super) struct DispatchErrorUsageRecord<'a> {
pub usage_records: &'a AdminUsageRecordService,
pub(super) struct DispatchErrorLogRecord<'a> {
pub ops_errors: &'a AdminOpsErrorLogService,
pub request_id: &'a str,
pub account_id: Option<&'a str>,
pub route: &'a str,
@@ -25,15 +26,11 @@ pub(super) struct DispatchErrorUsageRecord<'a> {
pub metadata: Value,
}
pub(super) async fn record_dispatch_error_event(record: DispatchErrorUsageRecord<'_>) {
pub(super) async fn record_dispatch_error_event(record: DispatchErrorLogRecord<'_>) {
let mut metadata = record.metadata;
enrich_event_route_metadata(&mut metadata, record.route);
let mut event = UsageRecord::new(
event_kind(record.route),
UsageRecordLevel::Error,
record.message,
);
let mut event = OpsErrorLog::new(event_kind(record.route), record.message);
event.request_id = Some(record.request_id.to_string());
event.account_id = record.account_id.map(ToString::to_string);
event.route = Some(record.route.to_string());
@@ -42,7 +39,7 @@ pub(super) async fn record_dispatch_error_event(record: DispatchErrorUsageRecord
event.latency_ms = Some(elapsed_millis_i64(record.started_at));
event.metadata = metadata;
if let Err(error) = record.usage_records.record(event).await {
if let Err(error) = record.ops_errors.record(event).await {
tracing::warn!(
account_id = record.account_id.unwrap_or(""),
error = %error,
+1 -3
View File
@@ -5,7 +5,6 @@ use chrono::Utc;
use crate::config::schema::AppConfig;
use crate::config::settings::RuntimeSettingsService;
use crate::http::middleware::request_id::TrustedProxyConfig;
use crate::infra::database::connect_sqlite;
use crate::infra::logging::{init_tracing, LogGuard, RotationConfig};
use crate::infra::paths::{ensure_data_dir, load_or_create_installation_id};
@@ -113,11 +112,10 @@ async fn build_application(
);
let task_coordinator = TaskCoordinator::start(&runtime_config, &services);
let trusted_proxies = TrustedProxyConfig::from_entries(&config.server.trusted_proxies)?;
let app_state = AppState { services };
Ok((
crate::http::router::router_with_trusted_proxies(trusted_proxies).with_state(app_state),
crate::http::router::router().with_state(app_state),
task_coordinator,
))
}
+9
View File
@@ -6,6 +6,8 @@ use crate::{
admin::monitoring::{
account_usage_service::AdminUsageService,
account_usage_store::SqliteUsageStore,
ops_error_service::AdminOpsErrorLogService,
ops_error_store::SqliteOpsErrorLogStore,
usage_record_service::AdminUsageRecordService,
usage_record_store::{SqliteUsageRecordStore, DEFAULT_USAGE_RECORD_CAPTURE_BODY},
},
@@ -91,6 +93,7 @@ pub struct Services {
pub refresh_policy: RuntimeRefreshPolicy,
pub admin_accounts: StdArc<AdminAccountService>,
pub usage_records: StdArc<AdminUsageRecordService>,
pub ops_errors: StdArc<AdminOpsErrorLogService>,
pub usage: StdArc<AdminUsageService>,
pub account_pool: StdArc<RuntimeAccountPoolService>,
pub token_refresh: StdArc<RuntimeTokenRefreshService<OpenAiTokenClient>>,
@@ -193,6 +196,10 @@ impl Services {
usage_record_options.enabled,
usage_record_options.capture_body,
));
let ops_errors = StdArc::new(AdminOpsErrorLogService::new(
SqliteOpsErrorLogStore::new(stores.usage_records.pool().clone()),
usage_record_options.capture_body,
));
let account_pool = StdArc::new(RuntimeAccountPoolService::new(
account_store_trait.clone(),
account_pool_options_from_config(config),
@@ -269,6 +276,7 @@ impl Services {
codex: codex.clone(),
session_affinity: session_affinity.clone(),
usage_records: usage_records.clone(),
ops_errors: ops_errors.clone(),
token_refresh: token_refresh.clone(),
installation_id: installation_id.clone(),
cloudflare: cloudflare_recovery,
@@ -284,6 +292,7 @@ impl Services {
refresh_policy,
admin_accounts,
usage_records,
ops_errors,
usage,
account_pool,
token_refresh,
+3 -1
View File
@@ -88,7 +88,9 @@ impl ModelRefreshTask {
)
.await;
for selected in &selected_accounts {
self.account_pool.release(&selected.account.id).await;
self.account_pool
.release_without_request_usage(&selected.account.id)
.await;
}
let result = result?;
+128 -264
View File
@@ -1,7 +1,6 @@
//! 账号池调度策略。
use std::{
cmp::Ordering,
collections::{BTreeMap, BTreeSet, VecDeque},
sync::Arc as StdArc,
time::Duration as StdDuration,
@@ -11,7 +10,6 @@ use chrono::{DateTime, Duration, Utc};
use indexmap::IndexMap;
use thiserror::Error;
use crate::infra::time::parse_rfc3339_utc;
use crate::upstream::accounts::quota::{quota_snapshot_limit_reached, quota_snapshot_reset_at};
use crate::upstream::accounts::store::AccountStore;
use crate::upstream::accounts::token_refresh::{jwt_expiry, JwtExpiry};
@@ -23,30 +21,12 @@ use crate::upstream::accounts::{
use crate::upstream::protocol::events::{
parse_rate_limit_headers, rate_limit_quota, TokenUsage as CodexTokenUsage,
};
use crate::upstream::scheduler::{
candidates::{self, CandidateFilter, CandidateRequest},
AccountScheduler, ScoreWeights,
};
/// 账号轮转策略。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RotationStrategy {
/// 综合并发压力、窗口用量和历史用量进行调度。
Smart,
/// 优先消耗即将重置的额度窗口。
QuotaResetPriority,
/// 按候选账号顺序循环选择。
RoundRobin,
/// 优先选择最近使用过的账号。
Sticky,
}
impl RotationStrategy {
fn as_str(self) -> &'static str {
match self {
Self::Smart => "smart",
Self::QuotaResetPriority => "quota_reset_priority",
Self::RoundRobin => "round_robin",
Self::Sticky => "sticky",
}
}
}
pub use crate::upstream::scheduler::RotationStrategy;
/// 账号池配置。
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -263,13 +243,17 @@ pub struct AccountWindowUsageDelta {
pub image_request_failed: bool,
}
/// 纯内存账号池,负责账号调度和运行时状态维护。
/// 纯内存账号池:负责账号存储、在途槽位与运行时状态维护。
///
/// 账号**选择**已剥离到 [`crate::upstream::scheduler`]:候选过滤走
/// [`candidates::filter`],策略选择走 [`AccountScheduler::select`]。账号池只提供选择
/// 所需的只读视图(候选切片 + `slot_count`),并持有调度器实例。
#[derive(Debug)]
pub struct AccountPool {
accounts: IndexMap<String, Account>,
slots: BTreeMap<String, VecDeque<AccountSlot>>,
options: AccountPoolOptions,
rotation_cursor: usize,
scheduler: AccountScheduler,
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -278,16 +262,6 @@ struct AccountSlot {
model: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct SmartAccountLoadScore {
quota_limited: bool,
slot_count: usize,
window_request_count: u64,
window_token_count: u64,
window_cached_tokens: u64,
request_count: u64,
}
/// 账号释放结果。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReleasedAccountUsage {
@@ -308,7 +282,7 @@ impl AccountPool {
accounts: IndexMap::new(),
slots: BTreeMap::new(),
options,
rotation_cursor: 0,
scheduler: AccountScheduler::new(ScoreWeights::default()),
}
}
@@ -322,10 +296,11 @@ impl AccountPool {
self.accounts.get(account_id).cloned()
}
/// 移除账号及其在途槽位。
/// 移除账号及其在途槽位与运行时反馈。
pub fn remove(&mut self, account_id: &str) -> bool {
let removed = self.accounts.shift_remove(account_id).is_some();
self.slots.remove(account_id);
self.scheduler.forget_feedback(account_id);
removed
}
@@ -333,17 +308,24 @@ impl AccountPool {
pub fn clear(&mut self) {
self.accounts.clear();
self.slots.clear();
self.rotation_cursor = 0;
self.scheduler.reset_cursor();
self.scheduler.clear_feedback();
}
/// 替换账号池运行参数。
pub fn set_options(&mut self, options: AccountPoolOptions) {
if self.options.rotation_strategy != options.rotation_strategy {
self.rotation_cursor = 0;
self.scheduler.reset_cursor();
}
self.options = options;
}
/// 回灌一次请求结果到调度器的运行时反馈(供 Smart 打分)。
pub fn report_feedback(&self, account_id: &str, success: bool, first_token_ms: Option<u64>) {
self.scheduler
.report_feedback(account_id, success, first_token_ms);
}
/// 更新账号状态。
pub fn set_status(&mut self, account_id: &str, status: AccountStatus) -> bool {
let Some(account) = self.accounts.get_mut(account_id) else {
@@ -498,7 +480,9 @@ impl AccountPool {
) -> AccountAcquireWithStatusRefresh {
self.cleanup_stale_slots(request.now);
let refreshed_accounts = self.refresh_account_statuses(request.now);
let candidates = self.candidates(request);
let candidates = self.filter_candidates(request);
// 亲和优先:required 硬锁定该账号;preferred 若在候选内则直接选中;
// 二者都不命中时,回退到调度器按当前策略选择。
let selected = if let Some(required_account_id) = &request.required_account_id {
candidates.first().cloned().map(|account| {
(
@@ -508,43 +492,24 @@ impl AccountPool {
)
})
} else if let Some(preferred_account_id) = &request.preferred_account_id {
let preferred = candidates
candidates
.iter()
.find(|account| account.id == *preferred_account_id)
.cloned();
preferred.map(|account| {
(
account,
self.previous_slot_at(preferred_account_id),
"preferred",
)
})
.cloned()
.map(|account| {
(
account,
self.previous_slot_at(preferred_account_id),
"preferred",
)
})
} else {
None
}
.or_else(|| {
Some(match self.options.rotation_strategy {
RotationStrategy::Smart => {
let account = self.select_smart(&candidates)?;
let previous = self.previous_slot_at(&account.id);
(account, previous, "smart")
}
RotationStrategy::QuotaResetPriority => {
let account = self.select_quota_reset_priority(&candidates)?;
let previous = self.previous_slot_at(&account.id);
(account, previous, "quota_reset_priority")
}
RotationStrategy::RoundRobin => {
let account = self.select_round_robin(&candidates)?;
let previous = self.previous_slot_at(&account.id);
(account, previous, "round_robin")
}
RotationStrategy::Sticky => {
let account = Self::select_sticky(&candidates)?;
let previous = self.previous_slot_at(&account.id);
(account, previous, "sticky")
}
})
let account = self.select_candidate(&candidates, request.now)?;
let previous = self.previous_slot_at(&account.id);
Some((account, previous, self.options.rotation_strategy.as_str()))
});
let Some((selected, previous_slot_at, selection_source)) = selected else {
return AccountAcquireWithStatusRefresh {
@@ -552,26 +517,20 @@ impl AccountPool {
refreshed_accounts,
};
};
let selected_slot_count = self.slot_count(&selected.id);
let selected_window_token_count = account_window_token_count(&selected);
let selected_smart_load_score = self.smart_load_score(&selected);
tracing::info!(
model = %request.model,
rotation_strategy = self.options.rotation_strategy.as_str(),
selection_source,
account_id = %selected.id,
candidate_count = candidates.len(),
slot_count = selected_slot_count,
slot_count = self.slot_count(&selected.id),
request_count = selected.request_count,
window_request_count = selected.window_request_count,
window_token_count = selected_window_token_count,
window_reset_at = ?selected.window_reset_at,
last_used_at = selected.last_used_at.as_deref().unwrap_or_default(),
quota_limit_reached = selected.quota_limit_reached,
quota_cooldown_until = ?selected.quota_cooldown_until,
previous_slot_at = ?previous_slot_at,
smart_load_score = ?selected_smart_load_score,
rotation_cursor = self.rotation_cursor,
"account selected for upstream request"
);
@@ -615,6 +574,22 @@ impl AccountPool {
/// 释放指定账号的一个在途槽位。
pub fn release(&mut self, account_id: &str) -> Option<ReleasedAccountUsage> {
self.release_slot(account_id, true)
}
/// 释放指定账号的一个在途槽位,不累计请求用量。
pub fn release_without_request_usage(
&mut self,
account_id: &str,
) -> Option<ReleasedAccountUsage> {
self.release_slot(account_id, false)
}
fn release_slot(
&mut self,
account_id: &str,
record_request_usage: bool,
) -> Option<ReleasedAccountUsage> {
self.accounts.get(account_id)?;
let mut remove_slots = false;
@@ -626,7 +601,9 @@ impl AccountPool {
if remove_slots {
self.slots.remove(account_id);
}
self.mark_request_usage(account_id, Utc::now());
if record_request_usage {
self.mark_request_usage(account_id, Utc::now());
}
Some(ReleasedAccountUsage {
model: slot.and_then(|slot| slot.model),
})
@@ -689,48 +666,48 @@ impl AccountPool {
let refreshed_accounts = self.refresh_account_statuses(now);
let mut by_plan = IndexMap::<String, Vec<Account>>::new();
for account in self.accounts.values() {
if !self.is_model_refresh_available(account, now) {
continue;
let max_concurrent = self.options.max_concurrent_per_account;
let skip_quota_limited = self.options.skip_quota_limited;
{
let slot_count = |account_id: &str| self.slots.get(account_id).map_or(0, VecDeque::len);
for account in self.accounts.values() {
if !candidates::is_model_refresh_available(
account,
max_concurrent,
skip_quota_limited,
&slot_count,
now,
) {
continue;
}
let Some(plan_type) = account.plan_type.as_ref() else {
continue;
};
by_plan
.entry(plan_type.clone())
.or_default()
.push(account.clone());
}
let Some(plan_type) = account.plan_type.as_ref() else {
continue;
};
by_plan
.entry(plan_type.clone())
.or_default()
.push(account.clone());
}
let strategy = self.options.rotation_strategy;
let mut accounts = Vec::new();
for (plan_type, group) in by_plan {
let selected = match self.options.rotation_strategy {
RotationStrategy::Smart => self.select_smart(&group),
RotationStrategy::QuotaResetPriority => self.select_quota_reset_priority(&group),
RotationStrategy::RoundRobin => self.select_round_robin(&group),
RotationStrategy::Sticky => Self::select_sticky(&group),
};
let Some(account) = selected else {
let Some(account) = self.select_candidate(&group, now) else {
continue;
};
let selected_slot_count = self.slot_count(&account.id);
let selected_window_token_count = account_window_token_count(&account);
let selected_smart_load_score = self.smart_load_score(&account);
tracing::info!(
plan_type,
rotation_strategy = self.options.rotation_strategy.as_str(),
rotation_strategy = strategy.as_str(),
account_id = %account.id,
candidate_count = group.len(),
slot_count = selected_slot_count,
slot_count = self.slot_count(&account.id),
request_count = account.request_count,
window_request_count = account.window_request_count,
window_token_count = selected_window_token_count,
window_reset_at = ?account.window_reset_at,
last_used_at = account.last_used_at.as_deref().unwrap_or_default(),
quota_limit_reached = account.quota_limit_reached,
quota_cooldown_until = ?account.quota_cooldown_until,
smart_load_score = ?selected_smart_load_score,
rotation_cursor = self.rotation_cursor,
"account selected for model refresh"
);
self.push_slot(&account.id, now, None);
@@ -743,106 +720,6 @@ impl AccountPool {
}
}
fn select_smart(&mut self, candidates: &[Account]) -> Option<Account> {
self.select_by(candidates, |pool, a, b| pool.compare_smart(a, b))
}
fn select_quota_reset_priority(&mut self, candidates: &[Account]) -> Option<Account> {
self.select_by(candidates, |_pool, a, b| compare_quota_reset_priority(a, b))
}
fn select_by(
&mut self,
candidates: &[Account],
compare: impl Fn(&Self, &Account, &Account) -> Ordering,
) -> Option<Account> {
let mut sorted = candidates.iter().collect::<Vec<_>>();
sorted.sort_by(|a, b| compare(self, a, b));
let best = *sorted.first()?;
let tied_count = sorted
.iter()
.take_while(|account| compare(self, best, account) == Ordering::Equal)
.count();
let index = self.rotation_cursor % tied_count;
self.rotation_cursor = self.rotation_cursor.wrapping_add(1);
Some((*sorted[index]).clone())
}
fn compare_smart(&self, a: &Account, b: &Account) -> Ordering {
self.smart_load_score(a)
.cmp(&self.smart_load_score(b))
.then_with(|| compare_window_reset(a.window_reset_at, b.window_reset_at))
.then_with(|| compare_last_used(a.last_used_at.as_deref(), b.last_used_at.as_deref()))
}
fn smart_load_score(&self, account: &Account) -> SmartAccountLoadScore {
SmartAccountLoadScore {
quota_limited: account.quota_limit_reached,
slot_count: self.slot_count(&account.id),
window_request_count: account.window_request_count,
window_token_count: account_window_token_count(account),
window_cached_tokens: account.window_cached_tokens,
request_count: account.request_count,
}
}
fn select_sticky(candidates: &[Account]) -> Option<Account> {
let mut selected = candidates.first()?;
for candidate in &candidates[1..] {
if compare_last_used(
candidate.last_used_at.as_deref(),
selected.last_used_at.as_deref(),
) == Ordering::Greater
{
selected = candidate;
}
}
Some((*selected).clone())
}
fn select_round_robin(&mut self, candidates: &[Account]) -> Option<Account> {
if candidates.is_empty() {
return None;
}
self.rotation_cursor %= candidates.len();
let index = self.rotation_cursor;
self.rotation_cursor = self.rotation_cursor.wrapping_add(1);
Some(candidates[index].clone())
}
fn candidates(&self, request: &AccountAcquireRequest) -> Vec<Account> {
let mut candidates = self
.accounts
.values()
.filter(|account| self.is_base_available(account, request))
.cloned()
.collect::<Vec<_>>();
if let Some(required_account_id) = &request.required_account_id {
candidates.retain(|account| account.id == *required_account_id);
return candidates;
}
if let Some(best_tier) = self.best_available_tier(&candidates) {
candidates.retain(|account| account.plan_type.as_deref() == Some(best_tier.as_str()));
}
candidates
}
fn is_base_available(&self, account: &Account, request: &AccountAcquireRequest) -> bool {
account.status == AccountStatus::Active
&& self.slot_count(&account.id) < self.options.max_concurrent_per_account
&& AccountService::quota_available_at(
account,
request.now,
self.options.skip_quota_limited,
)
&& self.is_model_allowed(account, &request.model)
&& !request
.exclude_account_ids
.iter()
.any(|account_id| account_id == &account.id)
&& AccountService::cloudflare_available_at(account, request.now)
}
fn slot_count(&self, account_id: &str) -> usize {
self.slots.get(account_id).map_or(0, VecDeque::len)
}
@@ -864,13 +741,6 @@ impl AccountPool {
});
}
fn is_model_refresh_available(&self, account: &Account, now: DateTime<Utc>) -> bool {
account.status == AccountStatus::Active
&& self.slot_count(&account.id) < self.options.max_concurrent_per_account
&& AccountService::quota_available_at(account, now, self.options.skip_quota_limited)
&& AccountService::cloudflare_available_at(account, now)
}
fn mark_request_usage(&mut self, account_id: &str, now: DateTime<Utc>) -> Option<Account> {
let account = self.accounts.get_mut(account_id)?;
account.last_used_at = Some(now.to_rfc3339());
@@ -920,24 +790,33 @@ impl AccountPool {
});
}
fn is_model_allowed(&self, account: &Account, model: &str) -> bool {
let Some(allowed_plans) = self.options.model_plan_allowlist.get(model) else {
return true;
};
let Some(plan_type) = account.plan_type.as_deref() else {
return false;
};
allowed_plans.iter().any(|plan| plan == plan_type)
|| !self.options.fetched_model_plan_types.contains(plan_type)
/// 过滤出本次请求的可用候选集合(委托 [`candidates::filter`])。
fn filter_candidates(&self, request: &AccountAcquireRequest) -> Vec<Account> {
let slot_count = |account_id: &str| self.slots.get(account_id).map_or(0, VecDeque::len);
candidates::filter(
self.accounts.values(),
&CandidateFilter {
max_concurrent_per_account: self.options.max_concurrent_per_account,
skip_quota_limited: self.options.skip_quota_limited,
tier_priority: &self.options.tier_priority,
model_plan_allowlist: &self.options.model_plan_allowlist,
fetched_model_plan_types: &self.options.fetched_model_plan_types,
slot_count: &slot_count,
},
&CandidateRequest {
model: &request.model,
exclude_account_ids: &request.exclude_account_ids,
required_account_id: request.required_account_id.as_deref(),
now: request.now,
},
)
}
fn best_available_tier(&self, candidates: &[Account]) -> Option<String> {
self.options.tier_priority.iter().find_map(|tier| {
candidates
.iter()
.find(|account| account.plan_type.as_deref() == Some(tier.as_str()))
.and_then(|account| account.plan_type.clone())
})
/// 按当前策略从候选集合中选择一个账号(委托 [`AccountScheduler::select`])。
fn select_candidate(&self, candidates: &[Account], now: DateTime<Utc>) -> Option<Account> {
let slot_count = |account_id: &str| self.slots.get(account_id).map_or(0, VecDeque::len);
self.scheduler
.select(self.options.rotation_strategy, candidates, &slot_count, now)
}
}
@@ -1039,10 +918,29 @@ impl RuntimeAccountPoolService {
/// 释放账号在途槽位。
pub async fn release(&self, account_id: &str) {
let released = self.pool.lock().await.release(account_id);
self.release_slot(account_id, true).await;
}
/// 释放账号在途槽位,不累计请求用量。
pub async fn release_without_request_usage(&self, account_id: &str) {
self.release_slot(account_id, false).await;
}
async fn release_slot(&self, account_id: &str, record_request_usage: bool) {
let released = if record_request_usage {
self.pool.lock().await.release(account_id)
} else {
self.pool
.lock()
.await
.release_without_request_usage(account_id)
};
let Some(released) = released else {
return;
};
if !record_request_usage {
return;
}
if let Err(error) = self.store.record_request(account_id).await {
tracing::warn!(
account_id,
@@ -1520,37 +1418,3 @@ fn refresh_cloudflare_cooldown(account: &mut Account, now: DateTime<Utc>) {
account.cloudflare_cooldown_until = None;
}
}
fn compare_quota_reset_priority(a: &Account, b: &Account) -> Ordering {
a.quota_limit_reached
.cmp(&b.quota_limit_reached)
.then_with(|| compare_window_reset(a.window_reset_at, b.window_reset_at))
.then_with(|| a.request_count.cmp(&b.request_count))
.then_with(|| compare_last_used(a.last_used_at.as_deref(), b.last_used_at.as_deref()))
}
fn account_window_token_count(account: &Account) -> u64 {
account
.window_input_tokens
.saturating_add(account.window_output_tokens)
.saturating_add(account.window_image_input_tokens)
.saturating_add(account.window_image_output_tokens)
}
fn compare_window_reset(a: Option<DateTime<Utc>>, b: Option<DateTime<Utc>>) -> Ordering {
match (a, b) {
(Some(a), Some(b)) => a.cmp(&b),
(Some(_) | None, None) | (None, Some(_)) => Ordering::Equal,
}
}
fn compare_last_used(a: Option<&str>, b: Option<&str>) -> Ordering {
last_used_millis(a).cmp(&last_used_millis(b))
}
fn last_used_millis(value: Option<&str>) -> i64 {
value
.and_then(|value| parse_rfc3339_utc(value).ok())
.map(|datetime| datetime.timestamp_millis())
.unwrap_or(0)
}
+1
View File
@@ -4,5 +4,6 @@ pub mod accounts;
pub mod fingerprint;
pub mod models;
pub mod protocol;
pub mod scheduler;
pub mod token_client;
pub mod transport;
@@ -0,0 +1,137 @@
//! 候选账号过滤。
//!
//! 所有调度策略共享的前置:从账号池中筛出「本次请求可用」的候选集合。这是选择流程
//! 的第一步,与具体策略无关——策略只在过滤后的候选之间做选择。
//!
//! 过滤规则(全部满足才入选):
//!
//! 1. 账号状态为 [`AccountStatus::Active`];
//! 2. 在途槽位数未达单账号并发上限;
//! 3. 配额可用([`AccountService::quota_available_at`],受 `skip_quota_limited` 控制);
//! 4. 模型在账号订阅计划的允许列表内;
//! 5. 不在本次请求的排除列表内;
//! 6. 不处于 Cloudflare 冷却期。
//!
//! 之后再按订阅层级优先级(`tier_priority`)收窄到最高可用层级;若请求指定了
//! `required_account_id`,则只保留该账号(跳过层级收窄)。
use chrono::{DateTime, Utc};
use crate::upstream::accounts::model::{Account, AccountStatus};
use crate::upstream::accounts::service::AccountService;
/// 候选过滤所需的账号池策略参数(只读视图)。
pub struct CandidateFilter<'a> {
/// 单账号最大并发请求数。
pub max_concurrent_per_account: usize,
/// 是否跳过已标记配额耗尽的账号。
pub skip_quota_limited: bool,
/// 订阅层级优先级,越靠前优先级越高。
pub tier_priority: &'a [String],
/// 模型到允许订阅计划的映射。
pub model_plan_allowlist: &'a std::collections::BTreeMap<String, Vec<String>>,
/// 已成功拉取过模型列表的订阅计划。
pub fetched_model_plan_types: &'a std::collections::BTreeSet<String>,
/// 按账号 ID 读取当前在途槽位数。
pub slot_count: &'a dyn Fn(&str) -> usize,
}
/// 本次账号获取请求的过滤条件。
pub struct CandidateRequest<'a> {
/// 本次请求使用的模型。
pub model: &'a str,
/// 本次请求需要排除的账号 ID。
pub exclude_account_ids: &'a [String],
/// 本次请求必须使用的账号 ID(存在时跳过层级收窄,只保留该账号)。
pub required_account_id: Option<&'a str>,
/// 本次调度使用的当前时间。
pub now: DateTime<Utc>,
}
/// 从账号池筛出本次请求的可用候选集合。
pub fn filter<'a>(
accounts: impl Iterator<Item = &'a Account>,
filter: &CandidateFilter<'_>,
request: &CandidateRequest<'_>,
) -> Vec<Account> {
let mut candidates = accounts
.filter(|account| is_base_available(account, filter, request))
.cloned()
.collect::<Vec<_>>();
if let Some(required_account_id) = request.required_account_id {
candidates.retain(|account| account.id == required_account_id);
return candidates;
}
if let Some(best_tier) = best_available_tier(&candidates, filter.tier_priority) {
candidates.retain(|account| account.plan_type.as_deref() == Some(best_tier.as_str()));
}
candidates
}
/// 判断账号是否满足全部基础可用条件。
fn is_base_available(
account: &Account,
filter: &CandidateFilter<'_>,
request: &CandidateRequest<'_>,
) -> bool {
account.status == AccountStatus::Active
&& (filter.slot_count)(&account.id) < filter.max_concurrent_per_account
&& AccountService::quota_available_at(account, request.now, filter.skip_quota_limited)
&& is_model_allowed(
account,
request.model,
filter.model_plan_allowlist,
filter.fetched_model_plan_types,
)
&& !request
.exclude_account_ids
.iter()
.any(|account_id| account_id == &account.id)
&& AccountService::cloudflare_available_at(account, request.now)
}
/// 判断模型是否允许该账号的订阅计划使用。
fn is_model_allowed(
account: &Account,
model: &str,
model_plan_allowlist: &std::collections::BTreeMap<String, Vec<String>>,
fetched_model_plan_types: &std::collections::BTreeSet<String>,
) -> bool {
let Some(allowed_plans) = model_plan_allowlist.get(model) else {
return true;
};
let Some(plan_type) = account.plan_type.as_deref() else {
return false;
};
allowed_plans.iter().any(|plan| plan == plan_type)
|| !fetched_model_plan_types.contains(plan_type)
}
/// 在候选集合中找出订阅层级优先级最高的可用层级。
fn best_available_tier(candidates: &[Account], tier_priority: &[String]) -> Option<String> {
for tier in tier_priority {
let matched = candidates
.iter()
.any(|account| account.plan_type.as_deref() == Some(tier.as_str()));
if matched {
return Some(tier.clone());
}
}
None
}
/// 判断账号是否可用于模型列表刷新(不涉及排除列表 / 模型允许列表 / 层级收窄)。
pub fn is_model_refresh_available(
account: &Account,
max_concurrent_per_account: usize,
skip_quota_limited: bool,
slot_count: &dyn Fn(&str) -> usize,
now: DateTime<Utc>,
) -> bool {
account.status == AccountStatus::Active
&& slot_count(&account.id) < max_concurrent_per_account
&& AccountService::quota_available_at(account, now, skip_quota_limited)
&& AccountService::cloudflare_available_at(account, now)
}
+171
View File
@@ -0,0 +1,171 @@
//! 账号运行时反馈:错误率与 TTFT 的 EWMA 统计。
//!
//! 每个账号维护两个指数加权移动平均(EWMA):错误率与首 token 延迟(TTFT,
//! 毫秒)。请求结束后经 [`FeedbackStats::report`] 回灌,直接进 [`super::score`]
//! 打分并可驱动 sticky escape。统计以 `AtomicU64`(存 `f64` 位模式)+ CAS 无锁更新,
//! 对齐 sub2api 的设计,避免选择热路径上的锁与 DB 往返。
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::RwLock;
/// EWMA 平滑系数(新样本权重)。与 sub2api 一致取 0.2。
const EWMA_ALPHA: f64 = 0.2;
/// 单账号的运行时 EWMA 统计。
///
/// `*_bits` 存 `f64` 的位模式;`NaN`(全 1 的哨兵)表示"尚无样本"。
#[derive(Debug)]
struct AccountFeedback {
/// 错误率 EWMA,范围 `[0, 1]`。
error_rate_bits: AtomicU64,
/// TTFT EWMA,单位毫秒。
ttft_ms_bits: AtomicU64,
}
/// 表示"尚无样本"的哨兵位模式。
const EMPTY_BITS: u64 = f64::NAN.to_bits();
impl Default for AccountFeedback {
fn default() -> Self {
Self {
error_rate_bits: AtomicU64::new(EMPTY_BITS),
ttft_ms_bits: AtomicU64::new(EMPTY_BITS),
}
}
}
impl AccountFeedback {
/// 读取当前错误率 EWMA;无样本时返回 `None`。
fn error_rate(&self) -> Option<f64> {
load_sample(&self.error_rate_bits)
}
/// 读取当前 TTFT EWMA(毫秒);无样本时返回 `None`。
fn ttft_ms(&self) -> Option<f64> {
load_sample(&self.ttft_ms_bits)
}
/// 回灌一次请求结果。
fn report(&self, success: bool, first_token_ms: Option<u64>) {
let error_sample = if success { 0.0 } else { 1.0 };
update_ewma(&self.error_rate_bits, error_sample);
if let Some(ms) = first_token_ms {
update_ewma(&self.ttft_ms_bits, ms as f64);
}
}
}
/// 读取 EWMA 样本;哨兵(NaN)返回 `None`。
fn load_sample(bits: &AtomicU64) -> Option<f64> {
let value = f64::from_bits(bits.load(Ordering::Relaxed));
if value.is_nan() {
None
} else {
Some(value)
}
}
/// 无锁 CAS 更新 EWMA:首个样本直接落值,其后按 alpha 混合。
fn update_ewma(bits: &AtomicU64, sample: f64) {
let mut current = bits.load(Ordering::Relaxed);
loop {
let previous = f64::from_bits(current);
let next = if previous.is_nan() {
sample
} else {
EWMA_ALPHA * sample + (1.0 - EWMA_ALPHA) * previous
};
match bits.compare_exchange_weak(
current,
next.to_bits(),
Ordering::Relaxed,
Ordering::Relaxed,
) {
Ok(_) => return,
Err(observed) => current = observed,
}
}
}
/// 账号 EWMA 反馈的读数快照,供打分使用。
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct FeedbackSample {
/// 错误率 EWMA,范围 `[0, 1]`;无样本时为 `None`。
pub error_rate: Option<f64>,
/// TTFT EWMA(毫秒);无样本时为 `None`。
pub ttft_ms: Option<f64>,
}
/// 账号运行时反馈存储:按账号 ID 聚合 EWMA 统计。
///
/// 选择热路径只读(`sample`),请求结束后写(`report`)。内部按账号分片为独立的
/// 原子对象,`RwLock` 仅保护 map 结构本身(插入新账号时短暂写锁)。
#[derive(Debug, Default)]
pub struct FeedbackStats {
accounts: RwLock<HashMap<String, AccountFeedback>>,
}
impl FeedbackStats {
/// 创建空的反馈存储。
pub fn new() -> Self {
Self::default()
}
/// 读取指定账号的 EWMA 快照;账号无记录时返回全 `None`。
pub fn sample(&self, account_id: &str) -> FeedbackSample {
let accounts = self
.accounts
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
match accounts.get(account_id) {
Some(feedback) => FeedbackSample {
error_rate: feedback.error_rate(),
ttft_ms: feedback.ttft_ms(),
},
None => FeedbackSample::default(),
}
}
/// 回灌一次请求结果:成功/失败 + 首 token 延迟(毫秒)。
pub fn report(&self, account_id: &str, success: bool, first_token_ms: Option<u64>) {
// 快路径:账号已存在时只需读锁 + 原子更新。
{
let accounts = self
.accounts
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(feedback) = accounts.get(account_id) {
feedback.report(success, first_token_ms);
return;
}
}
// 慢路径:首次见到该账号,取写锁插入后回灌。
let mut accounts = self
.accounts
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
accounts
.entry(account_id.to_string())
.or_default()
.report(success, first_token_ms);
}
/// 移除指定账号的反馈记录(账号被删除时调用)。
pub fn remove(&self, account_id: &str) {
let mut accounts = self
.accounts
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
accounts.remove(account_id);
}
/// 清空全部反馈记录(账号池清空时调用)。
pub fn clear(&self) {
let mut accounts = self
.accounts
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
accounts.clear();
}
}
+112
View File
@@ -0,0 +1,112 @@
//! 智能账号调度模块。
//!
//! 账号选择的唯一归属地。把「选择」从账号池存储中剥离,集中于此:
//!
//! - [`candidates`] —— 候选过滤(可用性 / 层级 / 模型允许列表),所有策略共享的前置。
//! - [`strategy`] —— 全部选择策略,每个策略一个文件([`strategy::smart`] /
//! [`strategy::quota_reset`] / [`strategy::round_robin`] / [`strategy::sticky`])。
//! - [`feedback`] —— 跨策略的运行时 EWMA 反馈(错误率 / TTFT),喂给 Smart 打分。
//!
//! [`AccountScheduler`] 是对外门面:持有轮转游标、打分权重与 EWMA 反馈存储,接收
//! **已过滤的候选切片**并返回选中账号。它不 lock 账号池、不刷状态、不写库——存储与
//! 状态维护仍归 `AccountPool`,二者经候选切片与 `slot_count` 闭包解耦。
pub mod candidates;
pub mod feedback;
pub mod strategy;
use std::sync::Mutex;
use chrono::{DateTime, Utc};
use crate::upstream::accounts::model::Account;
pub use candidates::{CandidateFilter, CandidateRequest};
pub use feedback::{FeedbackSample, FeedbackStats};
pub use strategy::smart::rank_candidates;
pub use strategy::{RotationStrategy, ScoreBreakdown, ScoreWeights};
/// 账号调度器:账号选择的对外门面。
///
/// 持有轮转游标(并列破并列用)、打分权重(Smart 用)与 EWMA 反馈存储。选择热路径
/// 只读反馈与权重,请求结束后经 [`AccountScheduler::report_feedback`] 回灌。游标用
/// [`Mutex`] 保护(选择需可变,但 `AccountScheduler` 以共享引用参与并发请求)。
#[derive(Debug)]
pub struct AccountScheduler {
/// 轮转游标:在并列最优账号之间做公平轮转。
cursor: Mutex<usize>,
/// Smart 策略的打分权重。
weights: ScoreWeights,
/// 账号运行时 EWMA 反馈(错误率 / TTFT)。
feedback: FeedbackStats,
}
impl Default for AccountScheduler {
fn default() -> Self {
Self::new(ScoreWeights::default())
}
}
impl AccountScheduler {
/// 使用指定打分权重创建调度器。
pub fn new(weights: ScoreWeights) -> Self {
Self {
cursor: Mutex::new(0),
weights,
feedback: FeedbackStats::new(),
}
}
/// 替换打分权重(策略切换或热更时调用)。
pub fn set_weights(&mut self, weights: ScoreWeights) {
self.weights = weights;
}
/// 重置轮转游标(策略切换时调用,保证轮转从头开始)。
pub fn reset_cursor(&self) {
*self.lock_cursor() = 0;
}
/// 从已过滤的候选集合中按指定策略选择一个账号。
///
/// `candidates` 必须是 [`candidates::filter`] 的输出;`slot_count` 按账号 ID 读取
/// 当前在途槽位数(Smart 打分与候选无关的运行时状态由调用方提供)。
pub fn select(
&self,
strategy: RotationStrategy,
candidates: &[Account],
slot_count: &dyn Fn(&str) -> usize,
now: DateTime<Utc>,
) -> Option<Account> {
let input = strategy::SelectionInput {
candidates,
slot_count,
feedback: &self.feedback,
weights: &self.weights,
now,
};
let mut cursor = self.lock_cursor();
strategy::select(strategy, &input, &mut cursor)
}
/// 回灌一次请求结果到运行时 EWMA 反馈(错误率 / TTFT),供 Smart 打分。
pub fn report_feedback(&self, account_id: &str, success: bool, first_token_ms: Option<u64>) {
self.feedback.report(account_id, success, first_token_ms);
}
/// 移除指定账号的运行时反馈(账号被删除时调用)。
pub fn forget_feedback(&self, account_id: &str) {
self.feedback.remove(account_id);
}
/// 清空全部运行时反馈(账号池清空时调用)。
pub fn clear_feedback(&self) {
self.feedback.clear();
}
fn lock_cursor(&self) -> std::sync::MutexGuard<'_, usize> {
self.cursor
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
}
@@ -0,0 +1,142 @@
//! 账号调度策略层。
//!
//! 所有账号选择策略集中于此,每个策略一个文件,互不依赖:
//!
//! - [`smart`] —— 加权线性打分 + EWMA 反馈(“智能调度”)。
//! - [`quota_reset`] —— 优先消耗即将重置的额度窗口。
//! - [`round_robin`] —— 按候选顺序循环。
//! - [`sticky`] —— 优先最近使用过的账号。
//!
//! 本模块只承担三件事:定义 [`RotationStrategy`] 枚举、把选择请求分派到对应策略、
//! 提供各策略共享的 tie-break 比较原语([`select_by`] / [`compare_window_reset`] /
//! [`compare_last_used`])。策略本身不触碰账号池存储:在途槽位数经 `slot_count`
//! 闭包按需读取,EWMA 反馈与打分权重经 [`SelectionInput`] 传入。
use std::cmp::Ordering;
use chrono::{DateTime, Utc};
use crate::infra::time::parse_rfc3339_utc;
use crate::upstream::accounts::model::Account;
use crate::upstream::scheduler::feedback::FeedbackStats;
pub mod quota_reset;
pub mod round_robin;
pub mod smart;
pub mod sticky;
pub use smart::{ScoreBreakdown, ScoreWeights};
/// 账号轮转策略。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RotationStrategy {
/// 加权线性打分调度:多因子(负载/窗口/错误率/TTFT/重置)归一化后加权求和,
/// 配合 EWMA 反馈。
Smart,
/// 优先消耗即将重置的额度窗口。
QuotaResetPriority,
/// 按候选账号顺序循环选择。
RoundRobin,
/// 优先选择最近使用过的账号。
Sticky,
}
impl RotationStrategy {
/// 返回策略的持久化/日志字符串。
pub fn as_str(self) -> &'static str {
match self {
Self::Smart => "smart",
Self::QuotaResetPriority => "quota_reset_priority",
Self::RoundRobin => "round_robin",
Self::Sticky => "sticky",
}
}
}
/// 策略选择的运行时输入。
///
/// `slot_count` 按账号 ID 读取当前在途槽位数;`feedback` / `weights` 仅 [`smart`]
/// 使用,其余策略忽略;`now` 用于窗口重置相关的打分。
pub struct SelectionInput<'a> {
/// 已过滤的候选账号集合。
pub candidates: &'a [Account],
/// 按账号 ID 读取当前在途槽位数。
pub slot_count: &'a dyn Fn(&str) -> usize,
/// 账号 EWMA 反馈存储(Smart 打分用)。
pub feedback: &'a FeedbackStats,
/// 打分权重(Smart 打分用)。
pub weights: &'a ScoreWeights,
/// 当前时刻(窗口重置因子用)。
pub now: DateTime<Utc>,
}
/// 按指定策略从候选集合中选择一个账号。
///
/// `cursor` 是账号池持有的轮转游标,用于在并列最优账号之间做公平轮转;不同策略对它
/// 的读写方式不同(详见各策略模块),本函数只负责透传可变引用。
pub fn select(
strategy: RotationStrategy,
input: &SelectionInput<'_>,
cursor: &mut usize,
) -> Option<Account> {
match strategy {
RotationStrategy::Smart => smart::select(input, cursor),
RotationStrategy::QuotaResetPriority => quota_reset::select(input, cursor),
RotationStrategy::RoundRobin => round_robin::select(input, cursor),
RotationStrategy::Sticky => sticky::select(input, cursor),
}
}
// ====================================================================
// 共享 tie-break 原语
// ====================================================================
/// 按比较函数升序排序后,在并列最优(`Ordering::Equal`)的账号之间用轮转游标破并列。
///
/// 这是 [`smart`] 与 [`quota_reset`] 共享的选择骨架:先按各自的比较规则排序,再在得分
/// 相同的账号之间轮转,保证并列账号被公平地依次选中。
pub(crate) fn select_by(
candidates: &[Account],
cursor: &mut usize,
compare: impl Fn(&Account, &Account) -> Ordering,
) -> Option<Account> {
let mut sorted = candidates.iter().collect::<Vec<_>>();
sorted.sort_by(|a, b| compare(a, b));
let best = *sorted.first()?;
let tied_count = sorted
.iter()
.take_while(|account| compare(best, account) == Ordering::Equal)
.count();
let index = *cursor % tied_count;
*cursor = cursor.wrapping_add(1);
Some((*sorted[index]).clone())
}
/// 计算账号当前窗口的总 token 数(输入 + 输出 + 图片输入 + 图片输出)。
pub(crate) fn account_window_token_count(account: &Account) -> u64 {
account
.window_input_tokens
.saturating_add(account.window_output_tokens)
.saturating_add(account.window_image_input_tokens)
.saturating_add(account.window_image_output_tokens)
}
/// 比较两个窗口重置时间:越早重置越优先;缺失重置时间视为并列(不惩罚)。
pub(crate) fn compare_window_reset(a: Option<DateTime<Utc>>, b: Option<DateTime<Utc>>) -> Ordering {
match (a, b) {
(Some(a), Some(b)) => a.cmp(&b),
(Some(_) | None, None) | (None, Some(_)) => Ordering::Equal,
}
}
/// 比较两个账号的最近使用时间:越久未用越优先(升序,最小者排前)。
pub(crate) fn compare_last_used(a: Option<&str>, b: Option<&str>) -> Ordering {
last_used_millis(a).cmp(&last_used_millis(b))
}
fn last_used_millis(value: Option<&str>) -> i64 {
value
.and_then(|value| parse_rfc3339_utc(value).ok())
.map(|datetime| datetime.timestamp_millis())
.unwrap_or(0)
}
@@ -0,0 +1,29 @@
//! QuotaResetPriority 策略:优先消耗即将重置的额度窗口。
//!
//! 排序规则(升序,越靠前越优先):
//! 1. 未封顶配额优先于已封顶(`quota_limit_reached` false < true);
//! 2. 窗口重置时间越早越优先;
//! 3. 历史请求数越少越优先;
//! 4. 最近使用时间越久越优先(LRU)。
//!
//! 并列最优的账号之间由 [`super::select_by`] 用轮转游标破并列。
use std::cmp::Ordering;
use crate::upstream::accounts::model::Account;
use super::{compare_last_used, compare_window_reset, select_by, SelectionInput};
/// QuotaResetPriority 策略选择。
pub fn select(input: &SelectionInput<'_>, cursor: &mut usize) -> Option<Account> {
select_by(input.candidates, cursor, compare_quota_reset_priority)
}
/// 配额重置优先级比较:升序,最优(最应先用)排在最前。
fn compare_quota_reset_priority(a: &Account, b: &Account) -> Ordering {
a.quota_limit_reached
.cmp(&b.quota_limit_reached)
.then_with(|| compare_window_reset(a.window_reset_at, b.window_reset_at))
.then_with(|| a.request_count.cmp(&b.request_count))
.then_with(|| compare_last_used(a.last_used_at.as_deref(), b.last_used_at.as_deref()))
}
@@ -0,0 +1,20 @@
//! RoundRobin 策略:按候选顺序循环选择。
//!
//! 最简单的策略:忽略账号负载与用量,纯粹按候选集合的顺序用轮转游标依次选中,
//! 保证请求在候选账号间均匀轮转。
use crate::upstream::accounts::model::Account;
use super::SelectionInput;
/// 按候选顺序做纯轮转选择。
pub fn select(input: &SelectionInput<'_>, cursor: &mut usize) -> Option<Account> {
let candidates = input.candidates;
if candidates.is_empty() {
return None;
}
*cursor %= candidates.len();
let index = *cursor;
*cursor = cursor.wrapping_add(1);
Some(candidates[index].clone())
}
@@ -0,0 +1,291 @@
//! Smart 策略:加权线性打分 + EWMA 反馈。
//!
//! 参考 sub2api 的调度设计:把多个归一化因子(负载、窗口 token 用量、窗口缓存、窗口
//! 请求数、错误率、TTFT、窗口重置)按可配置权重线性求和,得分越高越优先。相较字典序
//! 元组比较,加权打分是更平滑的负载均衡,不会让单一维度无条件压制其余维度,同时通过
//! EWMA 反馈感知账号健康度与延迟。
//!
//! 各归一化因子都落在 `[0, 1]` 且方向统一(越大越好),因此权重之间可直接比较。配额
//! 已封顶(`quota_limit_reached`)的账号会被施加一个强惩罚,确保只要还有未封顶的候选就
//! 不会选中它。并列最高分的账号之间由 [`super::select_by`] 用轮转游标破并列。
use crate::upstream::accounts::model::Account;
use crate::upstream::scheduler::feedback::{FeedbackSample, FeedbackStats};
use super::{account_window_token_count, SelectionInput};
/// 配额封顶账号的惩罚分。远大于各因子加权和的理论上限(各因子 ∈ [0,1],权重和通常为
/// 个位数),保证未封顶账号总是优先于封顶账号。
const QUOTA_LIMITED_PENALTY: f64 = 1_000.0;
/// 打分权重。每个字段对应一个归一化因子的权重,权重为 0 即关闭该维度。
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ScoreWeights {
/// 在途槽位压力(越空闲越优先)。
pub load: f64,
/// 当前窗口实际 token 用量(用得越少越优先)。
pub window: f64,
/// 当前窗口缓存 token 用量(缓存越少越优先,权重小,仅在实际用量相当时区分)。
pub cached: f64,
/// 当前窗口请求数(请求越少越优先)。
pub window_requests: f64,
/// 错误率 EWMA(越健康越优先)。
pub error_rate: f64,
/// 首 token 延迟 EWMA(越快越优先)。
pub ttft: f64,
/// 窗口重置临近度(越快重置越优先,use-it-or-lose-it,默认关闭)。
pub reset: f64,
}
impl Default for ScoreWeights {
fn default() -> Self {
// 默认权重对齐 sub2api 的取向:负载与健康度为主,窗口用量次之,TTFT 再次,
// 窗口重置默认关闭(避免过早榨干即将重置的账号)。cached 权重远小于 window,
// 确保实际 token 用量主导、缓存仅作细粒度区分。
Self {
load: 1.0,
window: 0.8,
cached: 0.05,
window_requests: 0.6,
error_rate: 1.0,
ttft: 0.5,
reset: 0.0,
}
}
}
/// 单个候选账号的打分明细,供日志与可观测使用。
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ScoreBreakdown {
/// 各因子加权后的总分(已含配额封顶惩罚)。
pub total: f64,
/// 负载因子(归一化后,未乘权重)。
pub load: f64,
/// 窗口实际 token 用量因子。
pub window: f64,
/// 窗口缓存 token 用量因子。
pub cached: f64,
/// 窗口请求数因子。
pub window_requests: f64,
/// 错误率因子。
pub error_rate: f64,
/// TTFT 因子。
pub ttft: f64,
/// 窗口重置因子。
pub reset: f64,
/// 是否被施加配额封顶惩罚。
pub quota_limited: bool,
}
/// Smart 策略选择:按加权得分降序排序,在并列最高分之间用轮转游标破并列。
pub fn select(input: &SelectionInput<'_>, cursor: &mut usize) -> Option<Account> {
let ranked = rank_candidates(
input.candidates,
input.weights,
input.now.timestamp(),
input.slot_count,
input.feedback,
);
let best_total = ranked.first()?.1.total;
// 并列最高分的账号数量(浮点相等用位相等判定,得分由相同输入算出,稳定)。
let tied_count = ranked
.iter()
.take_while(|(_, breakdown)| breakdown.total.to_bits() == best_total.to_bits())
.count();
let index = *cursor % tied_count;
*cursor = cursor.wrapping_add(1);
let account_index = ranked[index].0;
Some(input.candidates[account_index].clone())
}
/// 对候选集合按加权得分排序(降序),返回 `(账号索引, 打分明细)` 列表。
///
/// 只做打分与排序,最终的并列破并列交给 [`select`]。公开供测试直接断言排序结果。
pub fn rank_candidates(
candidates: &[Account],
weights: &ScoreWeights,
now_secs: i64,
slot_count: &dyn Fn(&str) -> usize,
feedback: &FeedbackStats,
) -> Vec<(usize, ScoreBreakdown)> {
let samples = candidates
.iter()
.map(|account| feedback.sample(&account.id))
.collect::<Vec<_>>();
let ctx = NormalizationContext::build(candidates, &samples, now_secs, slot_count);
let mut ranked = candidates
.iter()
.zip(&samples)
.enumerate()
.map(|(index, (account, sample))| {
(
index,
score_account(account, sample, weights, &ctx, now_secs, slot_count),
)
})
.collect::<Vec<_>>();
// 降序:得分高在前。NaN 不应出现(因子均有界),保守用 total_cmp。
ranked.sort_by(|a, b| b.1.total.total_cmp(&a.1.total));
ranked
}
/// 候选集合的归一化上下文:预先算好各维度的 min/max,供逐账号归一化。
struct NormalizationContext {
max_slot_count: f64,
max_window_tokens: f64,
max_window_cached: f64,
max_window_requests: f64,
min_ttft_ms: f64,
max_ttft_ms: f64,
min_reset_secs: f64,
max_reset_secs: f64,
}
impl NormalizationContext {
fn build(
candidates: &[Account],
samples: &[FeedbackSample],
now_secs: i64,
slot_count: &dyn Fn(&str) -> usize,
) -> Self {
let mut max_slot_count = 0.0_f64;
let mut max_window_tokens = 0.0_f64;
let mut max_window_cached = 0.0_f64;
let mut max_window_requests = 0.0_f64;
let mut min_ttft_ms = f64::INFINITY;
let mut max_ttft_ms = 0.0_f64;
let mut min_reset_secs = f64::INFINITY;
let mut max_reset_secs = 0.0_f64;
for (account, sample) in candidates.iter().zip(samples) {
max_slot_count = max_slot_count.max(slot_count(&account.id) as f64);
max_window_tokens = max_window_tokens.max(account_window_token_count(account) as f64);
max_window_cached = max_window_cached.max(account.window_cached_tokens as f64);
max_window_requests = max_window_requests.max(account.window_request_count as f64);
if let Some(ttft) = sample.ttft_ms {
if ttft > 0.0 {
min_ttft_ms = min_ttft_ms.min(ttft);
max_ttft_ms = max_ttft_ms.max(ttft);
}
}
if let Some(reset_at) = account.window_reset_at {
let secs = (reset_at.timestamp() - now_secs).max(0) as f64;
min_reset_secs = min_reset_secs.min(secs);
max_reset_secs = max_reset_secs.max(secs);
}
}
Self {
max_slot_count,
max_window_tokens,
max_window_cached,
max_window_requests,
min_ttft_ms: if min_ttft_ms.is_finite() {
min_ttft_ms
} else {
0.0
},
max_ttft_ms,
min_reset_secs: if min_reset_secs.is_finite() {
min_reset_secs
} else {
0.0
},
max_reset_secs,
}
}
}
/// 把 `value` 从 `[min, max]` 线性映射到 `[0, 1]`;区间退化时返回中性值 `1.0`
/// (表示该维度对所有候选无区分度,不应影响排序)。
fn normalize_ascending_good(value: f64, min: f64, max: f64) -> f64 {
if max <= min {
return 1.0;
}
((value - min) / (max - min)).clamp(0.0, 1.0)
}
/// 计算指定账号在候选集合中的加权得分明细。
fn score_account(
account: &Account,
sample: &FeedbackSample,
weights: &ScoreWeights,
ctx: &NormalizationContext,
now_secs: i64,
slot_count: &dyn Fn(&str) -> usize,
) -> ScoreBreakdown {
// 负载:槽位越少越好。归一化到 [0,1] 后取反(1 - x),使“越空闲得分越高”。
let load =
1.0 - normalize_ascending_good(slot_count(&account.id) as f64, 0.0, ctx.max_slot_count);
// 窗口实际 token 用量:token 越少越好。
let window = 1.0
- normalize_ascending_good(
account_window_token_count(account) as f64,
0.0,
ctx.max_window_tokens,
);
// 窗口缓存 token 用量:缓存越少越好(权重小,仅在实际用量相当时细分)。
let cached = 1.0
- normalize_ascending_good(
account.window_cached_tokens as f64,
0.0,
ctx.max_window_cached,
);
// 窗口请求数:请求越少越好。
let window_requests = 1.0
- normalize_ascending_good(
account.window_request_count as f64,
0.0,
ctx.max_window_requests,
);
// 错误率 EWMA:本身即 [0,1],越低越健康。无样本时视为 0(满分健康)。
let error_rate = 1.0 - sample.error_rate.unwrap_or(0.0).clamp(0.0, 1.0);
// TTFT:延迟越低越好。无样本的账号视为中性满分,避免冷启动被压。
let ttft = match sample.ttft_ms {
Some(ms) if ms > 0.0 => {
1.0 - normalize_ascending_good(ms, ctx.min_ttft_ms, ctx.max_ttft_ms)
}
_ => 1.0,
};
// 窗口重置:越快重置越优先(use-it-or-lose-it)。无 reset 时间视为中性满分。
let reset = match account.window_reset_at {
Some(reset_at) => {
let secs = (reset_at.timestamp() - now_secs).max(0) as f64;
1.0 - normalize_ascending_good(secs, ctx.min_reset_secs, ctx.max_reset_secs)
}
None => 1.0,
};
let mut total = weights.load * load
+ weights.window * window
+ weights.cached * cached
+ weights.window_requests * window_requests
+ weights.error_rate * error_rate
+ weights.ttft * ttft
+ weights.reset * reset;
// 配额封顶硬惩罚:确保只要还有未封顶候选就不会选中封顶账号。
if account.quota_limit_reached {
total -= QUOTA_LIMITED_PENALTY;
}
ScoreBreakdown {
total,
load,
window,
cached,
window_requests,
error_rate,
ttft,
reset,
quota_limited: account.quota_limit_reached,
}
}
@@ -0,0 +1,28 @@
//! Sticky 策略:优先选择最近使用过的账号。
//!
//! 选中 `last_used_at` 最大(最近使用)的账号,倾向于持续复用同一账号(利于上游的
//! prompt 缓存命中)。该策略不使用轮转游标——最近使用时间本身即确定性顺序。
use std::cmp::Ordering;
use crate::upstream::accounts::model::Account;
use super::{compare_last_used, SelectionInput};
/// 选中最近使用过的账号(`last_used_at` 最大者)。
///
/// `_cursor` 未使用:Sticky 由 `last_used_at` 决定顺序,不参与轮转破并列。
pub fn select(input: &SelectionInput<'_>, _cursor: &mut usize) -> Option<Account> {
let candidates = input.candidates;
let mut selected = candidates.first()?;
for candidate in &candidates[1..] {
if compare_last_used(
candidate.last_used_at.as_deref(),
selected.last_used_at.as_deref(),
) == Ordering::Greater
{
selected = candidate;
}
}
Some(selected.clone())
}
+12 -5
View File
@@ -755,7 +755,7 @@ async fn execute_fresh_pooled_response_create_request(
key,
PooledWebSocketConnection {
websocket,
metadata,
metadata: reusable_websocket_metadata(metadata),
created_at: now,
},
)
@@ -827,7 +827,7 @@ async fn execute_pooled_response_create_request(
let created_at = connection.created_at;
match collect_websocket_response(
connection.websocket,
connection.metadata,
reusable_websocket_metadata(connection.metadata),
true,
started_at,
first_token_started_at,
@@ -840,7 +840,7 @@ async fn execute_pooled_response_create_request(
key,
PooledWebSocketConnection {
websocket,
metadata,
metadata: reusable_websocket_metadata(metadata),
created_at,
},
)
@@ -861,7 +861,7 @@ async fn execute_pooled_response_create_request_stream(
connection: PooledWebSocketConnection,
) -> Result<CodexWebSocketStreamingExchange, CodexWebSocketExchangeError> {
let mut websocket = connection.websocket;
let mut metadata = connection.metadata;
let mut metadata = reusable_websocket_metadata(connection.metadata);
let created_at = connection.created_at;
let first_token_started_at = Instant::now();
if let Err(error) = websocket
@@ -1144,6 +1144,13 @@ fn websocket_connection_metadata(
}
}
fn reusable_websocket_metadata(
mut metadata: CodexWebSocketConnectionMetadata,
) -> CodexWebSocketConnectionMetadata {
metadata.rate_limit_headers.clear();
metadata
}
// ---------------------------------------------------------------------------
// Streaming
// ---------------------------------------------------------------------------
@@ -1406,7 +1413,7 @@ async fn finish_stream_websocket(
pool_return.key,
PooledWebSocketConnection {
websocket,
metadata,
metadata: reusable_websocket_metadata(metadata),
created_at: pool_return.created_at,
},
)
+12 -3
View File
@@ -271,13 +271,22 @@ async fn admin_accounts_list_should_include_usage_quota_and_model_stats() {
assert_eq!(item["quota"]["windows"].as_array().unwrap().len(), 3);
assert_eq!(item["quota"]["windows"][0]["labelDisplay"], "月限额");
assert_eq!(item["quota"]["windows"][0]["group"], "monthly");
assert_eq!(item["quota"]["windows"][0]["tokenUsageDisplay"], "1.12M");
assert_eq!(
item["quota"]["windows"][0]["localUsage"]["totalTokensDisplay"],
"1.12M"
);
assert_eq!(item["quota"]["windows"][1]["labelDisplay"], "5小时限额");
assert_eq!(item["quota"]["windows"][1]["group"], "shortTerm");
assert_eq!(item["quota"]["windows"][1]["tokenUsageDisplay"], "2.5K");
assert_eq!(
item["quota"]["windows"][1]["localUsage"]["totalTokensDisplay"],
"2.5K"
);
assert_eq!(item["quota"]["windows"][2]["labelDisplay"], "周限额");
assert_eq!(item["quota"]["windows"][2]["group"], "shortTerm");
assert_eq!(item["quota"]["windows"][2]["tokenUsageDisplay"], "124K");
assert_eq!(
item["quota"]["windows"][2]["localUsage"]["totalTokensDisplay"],
"124K"
);
assert!(item["quota"]["windows"][2]["windowUsedDisplay"]
.as_str()
.is_some_and(|value| value.contains(" / 7.0d")));
+2 -2
View File
@@ -175,7 +175,7 @@ async fn admin_account_quota_should_send_usage_cookie() {
"shortTerm"
);
assert_eq!(
body["data"]["quotaData"]["windows"][0]["tokenUsageDisplay"],
body["data"]["quotaData"]["windows"][0]["localUsage"]["totalTokensDisplay"],
"2K"
);
assert_eq!(
@@ -183,7 +183,7 @@ async fn admin_account_quota_should_send_usage_cookie() {
"周限额"
);
assert_eq!(
body["data"]["quotaData"]["windows"][1]["tokenUsageDisplay"],
body["data"]["quotaData"]["windows"][1]["localUsage"]["totalTokensDisplay"],
"2K"
);
}
+6 -39
View File
@@ -70,7 +70,7 @@ async fn dashboard_summary_should_render_dash_when_fingerprint_updated_at_is_mis
#[tokio::test]
async fn dashboard_summary_should_calculate_today_traffic_and_average_first_token_latency_from_time_buckets(
) {
let (app, store, pool, _dir) = dashboard_test_app(
let (app, store, _pool, _dir) = dashboard_test_app(
"dashboard-traffic-latency.sqlite",
crate::support::fingerprint::test_fingerprint(),
)
@@ -96,23 +96,22 @@ async fn dashboard_summary_should_calculate_today_traffic_and_average_first_toke
.append(&usage_record_with_tokens(yesterday_record_at, 30))
.await
.unwrap();
seed_usage_summary_with_cached_tokens(&pool, 120, 30, 24).await;
let body = dashboard_summary(app).await;
assert_eq!(body["data"]["cards"]["traffic"]["todayRequests"], "2");
assert_eq!(body["data"]["cards"]["traffic"]["todayRequestsValue"], 2);
assert_eq!(body["data"]["cards"]["traffic"]["totalRequests"], "42");
assert_eq!(body["data"]["cards"]["traffic"]["totalRequests"], "3");
assert_eq!(
body["data"]["cards"]["traffic"]["yesterdayRequestsValue"],
1
);
assert_eq!(body["data"]["cards"]["tokens"]["todayTokens"], "30");
assert_eq!(body["data"]["cards"]["tokens"]["todayTokensValue"], 30);
assert_eq!(body["data"]["cards"]["tokens"]["totalTokens"], "150");
assert_eq!(body["data"]["cards"]["tokens"]["totalTokens"], "60");
assert_eq!(body["data"]["cards"]["tokens"]["yesterdayTokensValue"], 30);
assert_eq!(body["data"]["cards"]["cache"]["totalHitRate"], "20.0%");
assert_eq!(body["data"]["cards"]["cache"]["totalCachedTokens"], "24");
assert_eq!(body["data"]["cards"]["cache"]["totalHitRate"], "0.0%");
assert_eq!(body["data"]["cards"]["cache"]["totalCachedTokens"], "0");
assert_eq!(
body["data"]["cards"]["cache"]["averageFirstTokenLatencyMs"],
"300 ms"
@@ -719,39 +718,6 @@ async fn seed_usage_summary(pool: &SqlitePool, input_tokens: u64, output_tokens:
.await;
}
async fn seed_usage_summary_with_cached_tokens(
pool: &SqlitePool,
input_tokens: u64,
output_tokens: u64,
cached_tokens: u64,
) {
sqlx::query(
"insert into accounts (id, email, access_token, status, added_at, updated_at) values (?, ?, ?, ?, ?, ?)",
)
.bind("acct_usage_cached")
.bind("acct-usage-cached@example.com")
.bind("cipher")
.bind("active")
.bind("2026-06-18T00:00:00Z")
.bind("2026-06-18T00:00:00Z")
.execute(pool)
.await
.unwrap();
sqlx::query(
"insert into account_usage (account_id, request_count, input_tokens, output_tokens, cached_tokens, total_tokens, last_used_at) values (?, ?, ?, ?, ?, ?, ?)",
)
.bind("acct_usage_cached")
.bind(42_i64)
.bind(input_tokens as i64)
.bind(output_tokens as i64)
.bind(cached_tokens as i64)
.bind((input_tokens + output_tokens) as i64)
.bind("2026-06-18T00:00:00Z")
.execute(pool)
.await
.unwrap();
}
async fn seed_usage_summary_with_last_used(
pool: &SqlitePool,
input_tokens: u64,
@@ -857,6 +823,7 @@ fn usage_record_with_account_tokens(
fn usage_record(created_at: chrono::DateTime<Utc>, model: &str, metadata: Value) -> UsageRecord {
let mut record = UsageRecord::new("v1.response", UsageRecordLevel::Info, "completed");
record.model = Some(model.to_string());
record.status_code = Some(200);
record.created_at = created_at;
record.metadata = metadata;
record
@@ -54,10 +54,16 @@ async fn admin_usage_records_should_cursor_page_events_and_include_request_id()
let now = Utc::now();
let mut older = UsageRecord::new("request", UsageRecordLevel::Info, "older");
older.id = "usage_older".to_string();
older.account_id = Some("acct_usage".to_string());
older.model = Some("gpt-5.5".to_string());
older.status_code = Some(200);
older.created_at = now;
store.append(&older).await.unwrap();
let mut newer = UsageRecord::new("request", UsageRecordLevel::Info, "newer");
newer.id = "usage_newer".to_string();
newer.account_id = Some("acct_usage".to_string());
newer.model = Some("gpt-5.5".to_string());
newer.status_code = Some(200);
newer.created_at = now + Duration::seconds(1);
store.append(&newer).await.unwrap();
@@ -88,8 +94,11 @@ async fn admin_usage_records_should_return_numbered_page_metadata() {
("usage_old", "older timeout", 0),
("usage_new", "newer timeout", 1),
] {
let mut event = UsageRecord::new("request", UsageRecordLevel::Error, message);
let mut event = UsageRecord::new("request", UsageRecordLevel::Info, message);
event.id = id.to_string();
event.account_id = Some("acct_usage".to_string());
event.model = Some("gpt-5.5".to_string());
event.status_code = Some(200);
event.created_at = now + Duration::seconds(offset);
store.append(&event).await.unwrap();
}
@@ -98,7 +107,7 @@ async fn admin_usage_records_should_return_numbered_page_metadata() {
.oneshot(
Request::builder()
.method("GET")
.uri("/api/admin/usage/records?page=1&pageSize=1&level=error&search=timeout")
.uri("/api/admin/usage/records?page=1&pageSize=1&search=timeout")
.header("cookie", "cpr_admin_session=session_1")
.header("x-request-id", "req_usage_records_numbered")
.body(Body::empty())
@@ -203,12 +212,13 @@ async fn admin_usage_records_should_return_table_display_fields() {
async fn admin_usage_records_should_use_record_account_email_snapshot_when_account_is_missing() {
let (app, store, _dir) =
admin_usage_records_test_app("admin-usage-records-email-snapshot.sqlite").await;
let mut event = UsageRecord::new("v1.response", UsageRecordLevel::Error, "upstream failed");
let mut event = UsageRecord::new("v1.response", UsageRecordLevel::Info, "completed");
event.id = "usage_email_snapshot".to_string();
event.account_id = Some("acct_deleted".to_string());
event.model = Some("gpt-5.5".to_string());
event.status_code = Some(200);
event.metadata = json!({
"accountEmail": "deleted@example.com",
"failed": true
"accountEmail": "deleted@example.com"
});
store.append(&event).await.unwrap();
@@ -237,7 +247,9 @@ async fn admin_usage_records_summary_should_aggregate_filtered_usage() {
admin_usage_records_test_app("admin-usage-records-summary.sqlite").await;
let mut success = UsageRecord::new("request", UsageRecordLevel::Info, "summary success");
success.id = "usage_summary_success".to_string();
success.account_id = Some("acct_summary".to_string());
success.model = Some("gpt-5.5".to_string());
success.status_code = Some(200);
success.latency_ms = Some(1200);
success.metadata = json!({
"usage": {
@@ -250,6 +262,7 @@ async fn admin_usage_records_summary_should_aggregate_filtered_usage() {
let mut failure = UsageRecord::new("request", UsageRecordLevel::Error, "summary failure");
failure.id = "usage_summary_failure".to_string();
failure.account_id = Some("acct_summary".to_string());
failure.model = Some("gpt-5.5-mini".to_string());
failure.status_code = Some(429);
failure.latency_ms = Some(600);
@@ -291,8 +304,10 @@ async fn admin_usage_record_insight_cards_should_aggregate_filtered_usage_dimens
admin_usage_records_test_app_with_pool("admin-usage-records-insights.sqlite").await;
let mut first = UsageRecord::new("request", UsageRecordLevel::Info, "insight success");
first.id = "usage_insight_success".to_string();
first.account_id = Some("acct_insight".to_string());
first.route = Some("/v1/responses".to_string());
first.model = Some("gpt-5.5".to_string());
first.status_code = Some(200);
first.latency_ms = Some(240);
first.metadata = json!({
"stream": true,
@@ -310,6 +325,7 @@ async fn admin_usage_record_insight_cards_should_aggregate_filtered_usage_dimens
let mut second = UsageRecord::new("request", UsageRecordLevel::Error, "insight failure");
second.id = "usage_insight_failure".to_string();
second.account_id = Some("acct_insight".to_string());
second.route = Some("/v1/responses/review".to_string());
second.model = Some("gpt-5.5-mini".to_string());
second.status_code = Some(500);
@@ -451,6 +467,9 @@ async fn admin_usage_record_trends_should_bucket_by_china_calendar_day() {
admin_usage_records_test_app_with_pool("admin-usage-records-china-day-trend.sqlite").await;
let mut june_29 = UsageRecord::new("request", UsageRecordLevel::Info, "china-day trend");
june_29.id = "usage_china_day_29".to_string();
june_29.account_id = Some("acct_trend".to_string());
june_29.model = Some("gpt-5.5".to_string());
june_29.status_code = Some(200);
june_29.created_at = chrono::DateTime::parse_from_rfc3339("2026-06-29T15:30:00Z")
.unwrap()
.with_timezone(&Utc);
@@ -465,6 +484,9 @@ async fn admin_usage_record_trends_should_bucket_by_china_calendar_day() {
let mut june_30 = UsageRecord::new("request", UsageRecordLevel::Info, "china-day trend");
june_30.id = "usage_china_day_30".to_string();
june_30.account_id = Some("acct_trend".to_string());
june_30.model = Some("gpt-5.5".to_string());
june_30.status_code = Some(200);
june_30.created_at = chrono::DateTime::parse_from_rfc3339("2026-06-29T16:30:00Z")
.unwrap()
.with_timezone(&Utc);
@@ -517,8 +539,10 @@ async fn admin_usage_records_insight_card_endpoints_should_return_source_specifi
admin_usage_records_test_app_with_pool("admin-usage-records-insight-cards.sqlite").await;
let mut first = UsageRecord::new("request", UsageRecordLevel::Info, "card success");
first.id = "usage_card_success".to_string();
first.account_id = Some("acct_card".to_string());
first.route = Some("/v1/responses".to_string());
first.model = Some("gpt-5.5".to_string());
first.status_code = Some(200);
first.latency_ms = Some(240);
first.metadata = json!({
"stream": true,
@@ -535,8 +559,10 @@ async fn admin_usage_records_insight_card_endpoints_should_return_source_specifi
let mut second = UsageRecord::new("request", UsageRecordLevel::Info, "card mini");
second.id = "usage_card_mini".to_string();
second.account_id = Some("acct_card".to_string());
second.route = Some("/v1/responses/compact".to_string());
second.model = Some("gpt-5.5-mini".to_string());
second.status_code = Some(200);
second.latency_ms = Some(120);
second.metadata = json!({
"stream": false,
@@ -662,11 +688,17 @@ async fn admin_usage_records_should_filter_summary_and_table_by_time_range() {
let now = Utc::now();
let mut older = UsageRecord::new("request", UsageRecordLevel::Info, "outside range");
older.id = "usage_outside_range".to_string();
older.account_id = Some("acct_range".to_string());
older.model = Some("gpt-5.5".to_string());
older.status_code = Some(200);
older.created_at = now - Duration::days(3);
store.append(&older).await.unwrap();
let mut current = UsageRecord::new("request", UsageRecordLevel::Info, "inside range");
current.id = "usage_inside_range".to_string();
current.account_id = Some("acct_range".to_string());
current.model = Some("gpt-5.5".to_string());
current.status_code = Some(200);
current.created_at = now;
store.append(&current).await.unwrap();
@@ -710,18 +742,18 @@ async fn admin_usage_records_should_filter_summary_and_table_by_time_range() {
#[tokio::test]
async fn admin_usage_records_should_filter_and_cursor_page_events() {
let (app, store, _dir) = admin_usage_records_test_app("admin-usage-records.sqlite").await;
let mut matching = UsageRecord::new("request", UsageRecordLevel::Error, "upstream timeout");
let mut matching = UsageRecord::new("request", UsageRecordLevel::Info, "upstream timeout");
matching.id = "usage_matching".to_string();
matching.account_id = Some("acct_filter".to_string());
matching.route = Some("/v1/responses".to_string());
matching.model = Some("gpt-5.5".to_string());
matching.status_code = Some(200);
store.append(&matching).await.unwrap();
store
.append(&UsageRecord::new(
"request",
UsageRecordLevel::Info,
"upstream timeout",
))
.await
.unwrap();
let mut non_matching_message = UsageRecord::new("request", UsageRecordLevel::Info, "completed");
non_matching_message.account_id = Some("acct_filter".to_string());
non_matching_message.model = Some("gpt-5.5".to_string());
non_matching_message.status_code = Some(200);
store.append(&non_matching_message).await.unwrap();
store
.append(&UsageRecord::new(
"account",
@@ -735,7 +767,7 @@ async fn admin_usage_records_should_filter_and_cursor_page_events() {
.oneshot(
Request::builder()
.method("GET")
.uri("/api/admin/usage/records?kind=request&level=error&search=timeout&limit=1")
.uri("/api/admin/usage/records?kind=request&level=info&search=timeout&limit=1")
.header("cookie", "cpr_admin_session=session_1")
.header("x-request-id", "req_usage_records_filter")
.body(Body::empty())
+64
View File
@@ -860,6 +860,70 @@ async fn update_events_should_close_on_shutdown() {
assert!(body.is_empty());
}
#[tokio::test]
async fn update_events_should_close_after_terminal_update_log() {
let _guard = SYSTEM_ENV_LOCK.lock().await;
let repository = "zyycn/codex-proxy-rs-events-terminal-route";
let github = MockServer::start().await;
let deploy = tempfile::tempdir().unwrap();
let exe_path = deploy.path().join("codex-proxy-rs");
let web_dist = deploy.path().join("web/dist");
std::fs::create_dir_all(&web_dist).unwrap();
std::fs::write(&exe_path, "old-binary").unwrap();
std::fs::write(web_dist.join("index.html"), "old-web").unwrap();
mount_latest_release_with_archive(&github, repository, "0.4.0", "new-binary", "new-web").await;
set_system_update_env(repository, &github.uri());
set_system_update_paths(deploy.path(), &exe_path, &web_dist);
let (app, _dir) = admin_system_test_app("system-events-terminal.sqlite").await;
let sse_response = app
.clone()
.oneshot(
Request::builder()
.method("GET")
.uri("/api/admin/system/update-events")
.header("cookie", "cpr_admin_session=session_1")
.header("x-request-id", "req_system_update_events_terminal")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
let update_app = app.clone();
let update_task = tokio::spawn(async move {
update_app
.oneshot(
Request::builder()
.method("POST")
.uri("/api/admin/system/update")
.header("cookie", "cpr_admin_session=session_1")
.header("x-request-id", "req_system_update_events_terminal_update")
.header(CONTENT_TYPE, "application/json")
.body(confirmed_update_body("0.4.0"))
.unwrap(),
)
.await
.unwrap()
});
let body = tokio::time::timeout(
Duration::from_secs(2),
to_bytes(sse_response.into_body(), 128 * 1024),
)
.await
.expect("update event stream should end after terminal update log")
.unwrap();
let update_response = update_task.await.unwrap();
let text = String::from_utf8(body.to_vec()).unwrap();
assert!(
update_response.status() == StatusCode::OK
&& text.contains("\"step\":\"done\"")
&& text.contains("\"terminal\":true")
&& text.contains("更新文件已替换,等待服务重启生效")
);
}
async fn get_update_detail(app: &axum::Router, refresh: bool, request_id: &str) -> Value {
let response = app
.clone()
+4 -22
View File
@@ -8,7 +8,6 @@ const DEFAULT_CONFIG_YAML: &str = r#"
server:
host: 0.0.0.0
port: 8080
trusted_proxies: []
api:
base_url: https://chatgpt.com/backend-api
database:
@@ -80,7 +79,6 @@ logging:
fn default_config_keeps_only_codex_backend() {
let cfg: AppConfig = parse_yaml_config(DEFAULT_CONFIG_YAML).unwrap();
assert_eq!(cfg.server.host, "0.0.0.0");
assert!(cfg.server.trusted_proxies.is_empty());
assert_eq!(cfg.api.base_url, "https://chatgpt.com/backend-api");
assert!(cfg.model_aliases.is_empty());
assert_eq!(cfg.auth.refresh_margin_seconds, 300);
@@ -259,7 +257,6 @@ ws_pool:
assert_eq!(cfg.server.host, "127.0.0.1");
assert_eq!(cfg.server.port, 8080);
assert!(cfg.server.trusted_proxies.is_empty());
assert_eq!(
cfg.database.url,
"sqlite://.runtime/data/codex-proxy-rs.sqlite"
@@ -280,30 +277,15 @@ ws_pool:
assert_eq!(cfg.logging.retention_days, 14);
}
#[test]
fn config_should_parse_trusted_proxy_entries() {
let cfg: AppConfig = parse_yaml_config(&DEFAULT_CONFIG_YAML.replace(
"trusted_proxies: []",
"trusted_proxies:\n - 127.0.0.1\n - 10.0.0.0/8",
))
.unwrap();
assert_eq!(
cfg.server.trusted_proxies,
vec!["127.0.0.1".to_string(), "10.0.0.0/8".to_string()]
);
}
#[test]
fn server_config_should_reject_unknown_fields() {
let err = parse_yaml_config::<AppConfig>(&DEFAULT_CONFIG_YAML.replace(
"trusted_proxies: []",
"trusted_proxies: []\n trusted_proxy: 127.0.0.1",
))
let err = parse_yaml_config::<AppConfig>(
&DEFAULT_CONFIG_YAML.replace(" port: 8080", " port: 8080\n trusted_proxies: []"),
)
.unwrap_err();
assert!(
err.to_string().contains("trusted_proxy"),
err.to_string().contains("trusted_proxies"),
"expected unknown server field to be rejected, got {err}"
);
}
+7 -95
View File
@@ -9,14 +9,12 @@ use axum::{
extract::connect_info::ConnectInfo,
http::HeaderMap,
http::{Request, StatusCode},
middleware::{from_fn, from_fn_with_state},
middleware::from_fn,
routing::get,
Extension, Router,
};
use codex_proxy_rs::http::middleware::{
request_id::{
attach_request_id, attach_request_id_with_proxy_config, ClientIp, TrustedProxyConfig,
},
request_id::{attach_request_id, ClientIp},
trace::http_trace_layer,
};
use tokio::time::{sleep, Duration};
@@ -285,7 +283,7 @@ async fn request_context_should_auto_detect_forwarded_ip_without_trusted_proxy_c
let response = app.oneshot(request).await.expect("response");
let bytes = to_bytes(response.into_body(), 1024).await.unwrap();
// 未配置可信代理时进入自动模式:CF-Connecting-IP 优先于 X-Real-IP / X-Forwarded-For。
// CF-Connecting-IP 优先于 X-Real-IP / X-Forwarded-For。
assert_eq!(
std::str::from_utf8(&bytes).unwrap(),
"203.0.113.43|cf=203.0.113.43|xff=203.0.113.42, 10.0.0.2|real=203.0.113.44"
@@ -319,45 +317,7 @@ async fn request_context_should_skip_private_forwarded_hops_in_auto_mode() {
}
#[tokio::test]
async fn request_context_should_accept_forwarded_ip_from_trusted_proxy() {
let trusted_proxies =
TrustedProxyConfig::from_entries(&["127.0.0.0/8".to_string()]).expect("trusted proxy");
let app = Router::new()
.route(
"/ip",
get(
|Extension(client_ip): Extension<ClientIp>, headers: HeaderMap| async move {
let forwarded_present = headers.contains_key("x-forwarded-for");
format!("{}|forwarded={forwarded_present}", client_ip.as_str())
},
),
)
.layer(from_fn_with_state(
trusted_proxies,
attach_request_id_with_proxy_config,
));
let mut request = Request::builder()
.uri("/ip")
.header("x-forwarded-for", "203.0.113.42, 10.0.0.2")
.body(Body::empty())
.expect("request should build");
request
.extensions_mut()
.insert(ConnectInfo(SocketAddr::from(([127, 0, 0, 1], 61234))));
let response = app.oneshot(request).await.expect("response");
let bytes = to_bytes(response.into_body(), 1024).await.unwrap();
assert_eq!(
std::str::from_utf8(&bytes).unwrap(),
"203.0.113.42|forwarded=true"
);
}
#[tokio::test]
async fn request_context_should_accept_real_ip_from_trusted_proxy_when_forwarded_for_missing() {
let trusted_proxies =
TrustedProxyConfig::from_entries(&["127.0.0.1".to_string()]).expect("trusted proxy");
async fn request_context_should_accept_real_ip_when_forwarded_for_missing() {
let app = Router::new()
.route(
"/ip",
@@ -365,10 +325,7 @@ async fn request_context_should_accept_real_ip_from_trusted_proxy_when_forwarded
client_ip.as_str().to_string()
}),
)
.layer(from_fn_with_state(
trusted_proxies,
attach_request_id_with_proxy_config,
));
.layer(from_fn(attach_request_id));
let mut request = Request::builder()
.uri("/ip")
.header("x-real-ip", "198.51.100.23")
@@ -385,9 +342,7 @@ async fn request_context_should_accept_real_ip_from_trusted_proxy_when_forwarded
}
#[tokio::test]
async fn request_context_should_prefer_real_ip_over_forwarded_for_from_trusted_proxy() {
let trusted_proxies =
TrustedProxyConfig::from_entries(&["127.0.0.1".to_string()]).expect("trusted proxy");
async fn request_context_should_prefer_real_ip_over_forwarded_for() {
let app = Router::new()
.route(
"/ip",
@@ -395,10 +350,7 @@ async fn request_context_should_prefer_real_ip_over_forwarded_for_from_trusted_p
client_ip.as_str().to_string()
}),
)
.layer(from_fn_with_state(
trusted_proxies,
attach_request_id_with_proxy_config,
));
.layer(from_fn(attach_request_id));
let mut request = Request::builder()
.uri("/ip")
.header("x-forwarded-for", "198.51.100.99, 203.0.113.42")
@@ -415,36 +367,6 @@ async fn request_context_should_prefer_real_ip_over_forwarded_for_from_trusted_p
assert_eq!(std::str::from_utf8(&bytes).unwrap(), "203.0.113.42");
}
#[tokio::test]
async fn request_context_should_ignore_forwarded_ip_from_untrusted_peer() {
let trusted_proxies =
TrustedProxyConfig::from_entries(&["10.0.0.0/8".to_string()]).expect("trusted proxy");
let app = Router::new()
.route(
"/ip",
get(|Extension(client_ip): Extension<ClientIp>| async move {
client_ip.as_str().to_string()
}),
)
.layer(from_fn_with_state(
trusted_proxies,
attach_request_id_with_proxy_config,
));
let mut request = Request::builder()
.uri("/ip")
.header("x-forwarded-for", "203.0.113.42")
.body(Body::empty())
.expect("request should build");
request
.extensions_mut()
.insert(ConnectInfo(SocketAddr::from(([127, 0, 0, 1], 61234))));
let response = app.oneshot(request).await.expect("response");
let bytes = to_bytes(response.into_body(), 1024).await.unwrap();
assert_eq!(std::str::from_utf8(&bytes).unwrap(), "127.0.0.1");
}
#[tokio::test]
async fn request_context_should_not_inject_real_ip_header() {
let app = Router::new()
@@ -474,13 +396,3 @@ async fn request_context_should_not_inject_real_ip_header() {
assert_eq!(std::str::from_utf8(&bytes).unwrap(), "missing");
}
#[test]
fn trusted_proxy_config_should_reject_invalid_entries() {
let error = TrustedProxyConfig::from_entries(&["not-an-ip".to_string()]).unwrap_err();
assert!(
error.to_string().contains("not-an-ip"),
"unexpected error: {error}"
);
}
+58 -2
View File
@@ -10,7 +10,7 @@ async fn sqlite_schema_should_create_current_tables() {
let pool = connect_sqlite(&url).await.unwrap();
let rows: Vec<(String,)> = sqlx::query_as(
"select name from sqlite_master where type = 'table' and name in ('schema_migrations', 'admin_users', 'admin_sessions', 'client_api_keys', 'runtime_settings', 'accounts', 'account_refresh_leases', 'account_usage', 'account_model_usage', 'usage_time_buckets', 'account_cookies', 'fingerprints', 'fingerprint_update_history', 'usage_records', 'model_plan_snapshots', 'session_affinities') order by name",
"select name from sqlite_master where type = 'table' and name in ('schema_migrations', 'admin_users', 'admin_sessions', 'client_api_keys', 'runtime_settings', 'accounts', 'account_refresh_leases', 'account_usage', 'account_model_usage', 'usage_time_buckets', 'account_cookies', 'fingerprints', 'fingerprint_update_history', 'usage_records', 'ops_error_logs', 'model_plan_snapshots', 'session_affinities') order by name",
)
.fetch_all(&pool)
.await
@@ -29,6 +29,7 @@ async fn sqlite_schema_should_create_current_tables() {
"fingerprint_update_history",
"fingerprints",
"model_plan_snapshots",
"ops_error_logs",
"runtime_settings",
"schema_migrations",
"session_affinities",
@@ -56,6 +57,7 @@ async fn sqlite_schema_should_record_applied_migrations() {
[
(1, "initial".to_string()),
(2, "rename_rotation_strategies".to_string()),
(3, "ops_error_logs".to_string()),
]
);
}
@@ -161,7 +163,7 @@ async fn sqlite_schema_should_persist_diagnostic_filter_indexes() {
let pool = connect_sqlite(&url).await.unwrap();
let rows: Vec<(String,)> = sqlx::query_as(
"select name from sqlite_master where type = 'index' and name in ('idx_account_cookies_expires', 'idx_usage_records_level_created', 'idx_usage_records_model_created', 'idx_usage_records_route_created', 'idx_usage_records_status_created', 'idx_usage_records_upstream_status_created', 'idx_session_affinities_active_order', 'idx_usage_time_buckets_bucket', 'idx_usage_time_buckets_model_bucket') order by name",
"select name from sqlite_master where type = 'index' and name in ('idx_account_cookies_expires', 'idx_usage_records_level_created', 'idx_usage_records_model_created', 'idx_usage_records_route_created', 'idx_usage_records_status_created', 'idx_usage_records_upstream_status_created', 'idx_ops_error_logs_created_id', 'idx_ops_error_logs_status_created', 'idx_ops_error_logs_failure_class', 'idx_session_affinities_active_order', 'idx_usage_time_buckets_bucket', 'idx_usage_time_buckets_model_bucket') order by name",
)
.fetch_all(&pool)
.await
@@ -171,6 +173,9 @@ async fn sqlite_schema_should_persist_diagnostic_filter_indexes() {
rows.into_iter().map(|row| row.0).collect::<Vec<_>>(),
[
"idx_account_cookies_expires",
"idx_ops_error_logs_created_id",
"idx_ops_error_logs_failure_class",
"idx_ops_error_logs_status_created",
"idx_session_affinities_active_order",
"idx_usage_records_level_created",
"idx_usage_records_model_created",
@@ -475,6 +480,41 @@ async fn sqlite_schema_should_persist_structured_event_diagnostic_columns() {
);
}
#[tokio::test]
async fn sqlite_schema_should_persist_ops_error_log_columns() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("ops-error-columns.sqlite");
let url = format!("sqlite://{}", db.display());
let pool = connect_sqlite(&url).await.unwrap();
let rows: Vec<(String,)> = sqlx::query_as(
"select name from pragma_table_info('ops_error_logs') where name in ('request_id', 'account_id', 'route', 'model', 'status_code', 'client_status_code', 'upstream_status_code', 'transport', 'attempt_index', 'failure_class', 'response_id', 'upstream_request_id', 'latency_ms', 'metadata_json') order by name",
)
.fetch_all(&pool)
.await
.unwrap();
assert_eq!(
rows.into_iter().map(|row| row.0).collect::<Vec<_>>(),
[
"account_id",
"attempt_index",
"client_status_code",
"failure_class",
"latency_ms",
"metadata_json",
"model",
"request_id",
"response_id",
"route",
"status_code",
"transport",
"upstream_request_id",
"upstream_status_code",
]
);
}
#[tokio::test]
async fn sqlite_schema_should_reject_invalid_account_status() {
let dir = tempfile::tempdir().unwrap();
@@ -507,6 +547,22 @@ async fn sqlite_schema_should_reject_invalid_usage_record_level() {
assert!(result.is_err());
}
#[tokio::test]
async fn sqlite_schema_should_reject_invalid_ops_error_status_code() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("ops-error-status-check.sqlite");
let url = format!("sqlite://{}", db.display());
let pool = connect_sqlite(&url).await.unwrap();
let result = sqlx::query(
"insert into ops_error_logs (id, kind, status_code, message, metadata_json, created_at) values ('ops_bad', 'request', 99, 'bad', '{}', '2026-06-14T00:00:00Z')",
)
.execute(&pool)
.await;
assert!(result.is_err());
}
#[tokio::test]
async fn sqlite_schema_should_reject_non_boolean_flags() {
let dir = tempfile::tempdir().unwrap();
@@ -274,7 +274,7 @@ async fn responses_compact_should_return_rate_limit_error_when_fallback_is_exhau
assert_eq!(body["error"]["code"], "rate_limit_exceeded");
assert!(message.contains("All accounts exhausted (1 rate-limited)"));
assert!(message.contains("compact quota reached"));
let event = latest_response_usage_record(&pool).await;
let event = latest_response_ops_error_log(&pool).await;
let metadata: Value = serde_json::from_str(&event.metadata_json).unwrap();
assert_eq!(
event.request_id.as_deref(),
@@ -339,7 +339,7 @@ async fn responses_compact_should_preserve_upstream_client_error_status() {
assert_eq!(status, StatusCode::BAD_REQUEST);
assert_eq!(body["error"]["type"], "invalid_request_error");
assert_eq!(body["error"]["code"], "codex_api_error");
let event = latest_response_usage_record(&pool).await;
let event = latest_response_ops_error_log(&pool).await;
let metadata: Value = serde_json::from_str(&event.metadata_json).unwrap();
assert_eq!(
event.request_id.as_deref(),
@@ -361,7 +361,7 @@ async fn responses_compact_should_preserve_upstream_client_error_status() {
#[tokio::test]
async fn responses_compact_should_return_responses_error_when_no_accounts_are_available() {
let server = MockServer::start().await;
let (app, api_key, _dir) = test_app_without_accounts(server.uri()).await;
let (app, api_key, _pool, _dir) = test_app_without_accounts(server.uri()).await;
let response = app
.oneshot(
@@ -22,7 +22,8 @@ use codex_proxy_rs::{
http::router,
infra::database::connect_sqlite,
proxy::dispatch::session_affinity::{
build_conversation_identity, SessionAffinityEntry, SqliteSessionAffinityStore,
build_conversation_identity, compute_variant_hash, prepare_variant_identity,
SessionAffinityEntry, SqliteSessionAffinityStore,
},
runtime::services::{BackgroundTaskStores, Services, UsageRecordOptions},
runtime::state::AppState,
@@ -31,6 +32,7 @@ use codex_proxy_rs::{
store::SqliteAccountStore, token_refresh::RefreshLeaseStore,
},
upstream::fingerprint::FingerprintRepository,
upstream::protocol::responses::CodexResponsesRequest,
};
use futures::{SinkExt, StreamExt};
use serde_json::{json, Value};
@@ -318,7 +320,16 @@ async fn test_app_with_account_and_pool(
test_app_with_account_pool_config(base_url, |_| {}).await
}
async fn test_app_without_accounts(base_url: String) -> (axum::Router, String, tempfile::TempDir) {
async fn test_app_with_account_pool_and_affinity(
base_url: String,
response_id: &str,
) -> (axum::Router, String, SqlitePool, tempfile::TempDir) {
test_app_with_account_pool_config_and_affinity(base_url, |_| {}, Some(response_id)).await
}
async fn test_app_without_accounts(
base_url: String,
) -> (axum::Router, String, SqlitePool, tempfile::TempDir) {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("openai-responses-no-accounts.sqlite");
let url = format!("sqlite://{}", db.display());
@@ -327,7 +338,7 @@ async fn test_app_without_accounts(base_url: String) -> (axum::Router, String, t
insert_model_snapshot(&pool).await;
let state = test_app_state_with_pool_and_installation_id(
&test_config(url, base_url),
pool,
pool.clone(),
TEST_INSTALLATION_ID.to_string(),
)
.await;
@@ -337,7 +348,7 @@ async fn test_app_without_accounts(base_url: String) -> (axum::Router, String, t
.restore_from_repository()
.await
.expect("empty account pool should restore");
(router::router().with_state(state), api_key, dir)
(router::router().with_state(state), api_key, pool, dir)
}
async fn test_app_with_account_pool_and_logging(
@@ -407,6 +418,14 @@ async fn test_app_with_account_pool_and_logging_capture_body(
async fn test_app_with_account_pool_config(
base_url: String,
configure: impl FnOnce(&mut AppConfig),
) -> (axum::Router, String, SqlitePool, tempfile::TempDir) {
test_app_with_account_pool_config_and_affinity(base_url, configure, None).await
}
async fn test_app_with_account_pool_config_and_affinity(
base_url: String,
configure: impl FnOnce(&mut AppConfig),
affinity_response_id: Option<&str>,
) -> (axum::Router, String, SqlitePool, tempfile::TempDir) {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("openai-record-affinity.sqlite");
@@ -414,6 +433,9 @@ async fn test_app_with_account_pool_config(
let pool = connect_sqlite(&url).await.unwrap();
let api_key = insert_client_api_key(&pool).await;
insert_account(&pool).await;
if let Some(response_id) = affinity_response_id {
insert_session_affinity(&pool, response_id, "acct_chat").await;
}
let mut config = test_config(url, base_url);
configure(&mut config);
let state = test_app_state_with_pool_and_installation_id(
@@ -428,6 +450,14 @@ async fn test_app_with_account_pool_config(
.restore_from_repository()
.await
.expect("account pool should restore");
if affinity_response_id.is_some() {
state
.services
.session_affinity
.restore_from_repository(Utc::now())
.await
.expect("session affinity should restore");
}
(router::router().with_state(state), api_key, pool, dir)
}
@@ -713,6 +743,26 @@ async fn insert_model_snapshot(pool: &SqlitePool) {
.unwrap();
}
async fn insert_session_affinity(pool: &SqlitePool, response_id: &str, account_id: &str) {
SqliteSessionAffinityStore::new(pool.clone())
.upsert(
response_id,
&SessionAffinityEntry {
account_id: account_id.to_string(),
conversation_id: format!("conv_{response_id}"),
turn_state: Some("turn-stale".to_string()),
instructions_hash: None,
input_tokens: None,
function_call_ids: Vec::new(),
variant_hash: None,
created_at: Utc::now(),
},
Duration::hours(4),
)
.await
.unwrap();
}
async fn insert_named_account(
pool: &SqlitePool,
id: &str,
@@ -1393,10 +1443,52 @@ struct ResponseUsageRecordSnapshot {
metadata_json: String,
}
#[derive(sqlx::FromRow)]
struct OpsErrorLogSnapshot {
request_id: Option<String>,
account_id: Option<String>,
route: Option<String>,
model: Option<String>,
status_code: Option<i64>,
response_id: Option<String>,
metadata_json: String,
}
impl From<OpsErrorLogSnapshot> for ResponseUsageRecordSnapshot {
fn from(snapshot: OpsErrorLogSnapshot) -> Self {
Self {
level: "error".to_string(),
request_id: snapshot.request_id,
account_id: snapshot.account_id,
route: snapshot.route,
model: snapshot.model,
status_code: snapshot.status_code,
response_id: snapshot.response_id,
metadata_json: snapshot.metadata_json,
}
}
}
async fn latest_response_usage_record(pool: &SqlitePool) -> ResponseUsageRecordSnapshot {
latest_usage_record(pool, "v1.response").await
}
async fn latest_response_ops_error_log(pool: &SqlitePool) -> ResponseUsageRecordSnapshot {
let row = sqlx::query_as::<_, OpsErrorLogSnapshot>(
"select request_id, account_id, route, model, status_code, response_id, metadata_json
from ops_error_logs
where kind = ?
order by created_at desc, id desc
limit 1",
)
.bind("v1.response")
.fetch_optional(pool)
.await
.unwrap();
row.unwrap_or_else(|| panic!("expected a v1.response ops error log"))
.into()
}
async fn latest_usage_record(pool: &SqlitePool, kind: &str) -> ResponseUsageRecordSnapshot {
let page = SqliteUsageRecordStore::new(pool.clone())
.list(
@@ -1249,7 +1249,7 @@ async fn responses_should_strip_banned_affinity_history_when_switching_to_active
}
#[tokio::test]
async fn responses_should_keep_history_when_affinity_account_is_quota_exhausted() {
async fn responses_should_strip_quota_history_when_switching_to_active_account() {
let (base_url, upstream) =
spawn_single_websocket_completed_upstream("resp_after_quota_affinity").await;
let (app, api_key, pool, _dir) =
@@ -1287,13 +1287,7 @@ async fn responses_should_keep_history_when_affinity_account_is_quota_exhausted(
captured_header(&captured.headers, "authorization"),
Some("Bearer access-primary")
);
assert_eq!(
captured_header(&captured.headers, "x-codex-turn-state"),
Some("turn_affinity_risk")
);
assert_eq!(
captured.payload["previous_response_id"],
"resp_affinity_risk"
);
assert!(captured_header(&captured.headers, "x-codex-turn-state").is_none());
assert!(captured.payload.get("previous_response_id").is_none());
assert_eq!(affinity_count.0, 1);
}
@@ -93,7 +93,7 @@ async fn responses_should_classify_sse_cyber_policy_failure_as_bad_request() {
#[tokio::test]
async fn responses_should_return_no_available_accounts_error_when_no_accounts_are_available() {
let server = MockServer::start().await;
let (app, api_key, _dir) = test_app_without_accounts(server.uri()).await;
let (app, api_key, pool, _dir) = test_app_without_accounts(server.uri()).await;
let response = app
.oneshot(
@@ -121,6 +121,35 @@ async fn responses_should_return_no_available_accounts_error_when_no_accounts_ar
assert_eq!(status, StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(body["error"]["type"], "server_error");
assert_eq!(body["error"]["code"], "no_available_accounts");
let (usage_count,): (i64,) = sqlx::query_as("select count(*) from usage_records")
.fetch_one(&pool)
.await
.unwrap();
let (ops_count, account_id, model, failure_class): (
i64,
Option<String>,
Option<String>,
Option<String>,
) = sqlx::query_as(
"select count(*), max(account_id), max(model), max(failure_class) from ops_error_logs",
)
.fetch_one(&pool)
.await
.unwrap();
let (bucket_requests, bucket_errors): (i64, i64) = sqlx::query_as(
"select coalesce(sum(request_count), 0), coalesce(sum(error_count), 0) from usage_time_buckets",
)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(usage_count, 0);
assert_eq!(ops_count, 1);
assert_eq!(account_id, None);
assert_eq!(model.as_deref(), Some("gpt-5.5"));
assert_eq!(failure_class.as_deref(), Some("no_available_accounts"));
assert_eq!((bucket_requests, bucket_errors), (1, 1));
}
#[tokio::test]
@@ -1021,7 +1050,8 @@ async fn responses_should_strip_history_after_previous_response_not_found() {
"Previous response with id resp_stale was not found",
))
.await;
let (app, api_key, _pool, _dir) = test_app_with_account_and_pool(base_url).await;
let (app, api_key, _pool, _dir) =
test_app_with_account_pool_and_affinity(base_url, "resp_stale").await;
let response = app
.oneshot(
Request::builder()
@@ -1073,7 +1103,8 @@ async fn responses_should_strip_history_after_unanswered_function_call() {
"No tool output found for function call call_1",
))
.await;
let (app, api_key, _pool, _dir) = test_app_with_account_and_pool(base_url).await;
let (app, api_key, _pool, _dir) =
test_app_with_account_pool_and_affinity(base_url, "resp_stale").await;
let response = app
.oneshot(
Request::builder()
@@ -1117,7 +1148,8 @@ async fn responses_should_strip_history_after_websocket_invalid_encrypted_reason
"Invalid encrypted content in reasoning replay",
))
.await;
let (app, api_key, _pool, _dir) = test_app_with_account_and_pool(base_url).await;
let (app, api_key, _pool, _dir) =
test_app_with_account_pool_and_affinity(base_url, "resp_stale").await;
let response = app
.oneshot(
Request::builder()
@@ -1161,7 +1193,8 @@ async fn responses_should_strip_history_after_sse_invalid_encrypted_reasoning_re
"Invalid encrypted content in reasoning replay",
))
.await;
let (app, api_key, _pool, _dir) = test_app_with_account_and_pool(base_url).await;
let (app, api_key, _pool, _dir) =
test_app_with_account_pool_and_affinity(base_url, "resp_stale").await;
let response = app
.oneshot(
Request::builder()
@@ -1205,7 +1238,8 @@ async fn responses_stream_should_strip_history_after_previous_response_not_found
"Previous response with id resp_stale was not found",
))
.await;
let (app, api_key, _pool, _dir) = test_app_with_account_and_pool(base_url).await;
let (app, api_key, _pool, _dir) =
test_app_with_account_pool_and_affinity(base_url, "resp_stale").await;
let response = app
.oneshot(
Request::builder()
@@ -1258,7 +1292,8 @@ async fn responses_stream_should_strip_history_after_websocket_invalid_encrypted
"Invalid encrypted content in reasoning replay",
))
.await;
let (app, api_key, _pool, _dir) = test_app_with_account_and_pool(base_url).await;
let (app, api_key, _pool, _dir) =
test_app_with_account_pool_and_affinity(base_url, "resp_stale").await;
let response = app
.oneshot(
Request::builder()
@@ -2122,7 +2157,7 @@ async fn responses_should_return_rate_limit_error_when_429_fallback_is_exhausted
assert_eq!(body["error"]["code"], "rate_limit_exceeded");
assert_eq!(quota_state.0, 1);
assert!(quota_state.1.is_some());
let event = latest_response_usage_record(&pool).await;
let event = latest_response_ops_error_log(&pool).await;
let metadata: Value = serde_json::from_str(&event.metadata_json).unwrap();
assert_eq!(event.level, "error");
assert_eq!(
@@ -2206,7 +2241,7 @@ async fn responses_stream_should_return_rate_limit_error_when_429_fallback_is_ex
assert_eq!(quota_state.0, 1);
assert!(quota_state.1.is_some());
assert!(!response_request_id.is_empty());
let event = latest_response_usage_record(&pool).await;
let event = latest_response_ops_error_log(&pool).await;
let metadata: Value = serde_json::from_str(&event.metadata_json).unwrap();
assert_eq!(event.level, "error");
assert_eq!(
@@ -1539,24 +1539,76 @@ async fn responses_websocket_should_route_previous_response_id_to_recorded_accou
}
#[tokio::test]
async fn responses_websocket_non_stream_previous_response_not_found_should_strip_history_and_retry_same_account(
async fn responses_websocket_should_prefer_conversation_account_without_previous_response_id() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let base_url = format!("http://{}", listener.local_addr().unwrap());
let upstream = tokio::spawn(async move {
accept_successful_websocket_response_with_authorization(
&listener,
"Bearer access-secondary",
"resp_conversation_affinity",
)
.await
});
let (app, state, api_key, _pool, _dir) = test_app_with_two_accounts_and_state(base_url).await;
let request_body = json!({
"model": "gpt-5.5",
"prompt_cache_key": "conv_conversation_affinity",
"input": [],
"stream": false,
"use_websocket": true
});
let mut affinity_body = request_body.as_object().unwrap().clone();
affinity_body.remove("use_websocket");
let mut affinity_request = CodexResponsesRequest::from_body(affinity_body);
affinity_request.explicit_prompt_cache_key = true;
prepare_variant_identity(&mut affinity_request);
let variant_hash = compute_variant_hash(&affinity_request);
state
.services
.session_affinity
.record(
"resp_conversation_latest".to_string(),
SessionAffinityEntry {
account_id: "acct_secondary".to_string(),
conversation_id: "conv_conversation_affinity".to_string(),
turn_state: None,
instructions_hash: None,
input_tokens: None,
function_call_ids: Vec::new(),
variant_hash: Some(variant_hash),
created_at: Utc::now(),
},
)
.await
.unwrap();
let response = app
.oneshot(responses_json_request(&api_key, &request_body))
.await
.unwrap();
let body = response_text(response).await;
let payload = upstream.await.unwrap();
assert!(body.contains("\"id\":\"resp_conversation_affinity\""));
assert!(payload["prompt_cache_key"]
.as_str()
.is_some_and(|value| value.starts_with("cp_")));
assert!(payload.get("previous_response_id").is_none());
}
#[tokio::test]
async fn responses_websocket_non_stream_unknown_previous_response_should_strip_history_before_upstream(
) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let base_url = format!("http://{}", listener.local_addr().unwrap());
let upstream = tokio::spawn(async move {
let first_payload = accept_websocket_response_with_authorization_and_message(
&listener,
"Bearer access-secret",
WEBSOCKET_PREVIOUS_RESPONSE_NOT_FOUND.trim().to_string(),
)
.await;
let second_payload = accept_websocket_response_with_authorization_and_message(
accept_websocket_response_with_authorization_and_message(
&listener,
"Bearer access-secret",
websocket_completed_response("resp_after_history_strip", 3, 1),
)
.await;
(first_payload, second_payload)
.await
});
let (app, api_key, _dir) = test_app_with_account(base_url).await;
@@ -1573,32 +1625,23 @@ async fn responses_websocket_non_stream_previous_response_not_found_should_strip
.await
.unwrap();
let body = response_json(response).await;
let (first_payload, second_payload) = upstream.await.unwrap();
let payload = upstream.await.unwrap();
assert_eq!(body["id"], "resp_after_history_strip");
assert_eq!(first_payload["previous_response_id"], "resp_missing");
assert!(second_payload.get("previous_response_id").is_none());
assert!(payload.get("previous_response_id").is_none());
}
#[tokio::test]
async fn responses_websocket_history_recovery_should_stay_on_fallback_account_when_preferred_is_full(
) {
async fn responses_websocket_should_strip_known_history_when_preferred_account_is_full() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let base_url = format!("http://{}", listener.local_addr().unwrap());
let upstream = tokio::spawn(async move {
let first_payload = accept_websocket_response_with_authorization_and_message(
&listener,
"Bearer access-secondary",
WEBSOCKET_PREVIOUS_RESPONSE_NOT_FOUND.trim().to_string(),
)
.await;
let second_payload = accept_websocket_response_with_authorization_and_message(
accept_websocket_response_with_authorization_and_message(
&listener,
"Bearer access-secondary",
websocket_completed_response("resp_after_fallback_history_strip", 3, 1),
)
.await;
(first_payload, second_payload)
.await
});
let (app, state, api_key, _pool, _dir) =
test_app_with_two_accounts_and_state_config(base_url, |config| {
@@ -1620,35 +1663,23 @@ async fn responses_websocket_history_recovery_should_stay_on_fallback_account_wh
.await
.unwrap();
let body = response_json(response).await;
let (first_payload, second_payload) = upstream.await.unwrap();
let payload = upstream.await.unwrap();
assert_eq!(body["id"], "resp_after_fallback_history_strip");
assert_eq!(
first_payload["previous_response_id"],
"resp_owned_by_primary"
);
assert!(second_payload.get("previous_response_id").is_none());
assert!(payload.get("previous_response_id").is_none());
}
#[tokio::test]
async fn responses_websocket_stream_history_recovery_should_stay_on_fallback_account_when_preferred_is_full(
) {
async fn responses_websocket_stream_should_strip_known_history_when_preferred_account_is_full() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let base_url = format!("http://{}", listener.local_addr().unwrap());
let upstream = tokio::spawn(async move {
let first_payload = accept_websocket_response_with_authorization_and_message(
&listener,
"Bearer access-secondary",
WEBSOCKET_PREVIOUS_RESPONSE_NOT_FOUND.trim().to_string(),
)
.await;
let second_payload = accept_websocket_response_with_authorization_and_message(
accept_websocket_response_with_authorization_and_message(
&listener,
"Bearer access-secondary",
websocket_completed_response("resp_stream_after_fallback_history_strip", 3, 1),
)
.await;
(first_payload, second_payload)
.await
});
let (app, state, api_key, _pool, _dir) =
test_app_with_two_accounts_and_state_config(base_url, |config| {
@@ -1670,35 +1701,24 @@ async fn responses_websocket_stream_history_recovery_should_stay_on_fallback_acc
.await
.unwrap();
let body = response_text(response).await;
let (first_payload, second_payload) = upstream.await.unwrap();
let payload = upstream.await.unwrap();
assert!(body.contains("resp_stream_after_fallback_history_strip"));
assert_eq!(
first_payload["previous_response_id"],
"resp_owned_by_primary"
);
assert!(second_payload.get("previous_response_id").is_none());
assert!(payload.get("previous_response_id").is_none());
}
#[tokio::test]
async fn responses_websocket_stream_previous_response_not_found_should_strip_history_and_retry_same_account(
) {
async fn responses_websocket_stream_unknown_previous_response_should_strip_history_before_upstream()
{
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let base_url = format!("http://{}", listener.local_addr().unwrap());
let upstream = tokio::spawn(async move {
let first_payload = accept_websocket_response_with_authorization_and_message(
&listener,
"Bearer access-secret",
WEBSOCKET_PREVIOUS_RESPONSE_NOT_FOUND.trim().to_string(),
)
.await;
let second_payload = accept_websocket_response_with_authorization_and_message(
accept_websocket_response_with_authorization_and_message(
&listener,
"Bearer access-secret",
websocket_completed_response("resp_stream_after_history_strip", 3, 1),
)
.await;
(first_payload, second_payload)
.await
});
let (app, api_key, _dir) = test_app_with_account(base_url).await;
@@ -1715,11 +1735,10 @@ async fn responses_websocket_stream_previous_response_not_found_should_strip_his
.await
.unwrap();
let body = response_text(response).await;
let (first_payload, second_payload) = upstream.await.unwrap();
let payload = upstream.await.unwrap();
assert!(body.contains("\"id\":\"resp_stream_after_history_strip\""));
assert_eq!(first_payload["previous_response_id"], "resp_missing");
assert!(second_payload.get("previous_response_id").is_none());
assert!(payload.get("previous_response_id").is_none());
}
#[tokio::test]
@@ -1742,7 +1761,8 @@ async fn responses_websocket_non_stream_unanswered_function_call_should_strip_hi
.await;
(first_payload, second_payload)
});
let (app, api_key, _dir) = test_app_with_account(base_url).await;
let (app, api_key, _pool, _dir) =
test_app_with_account_pool_and_affinity(base_url, "resp_with_call").await;
let response = app
.oneshot(responses_json_request(
@@ -1808,7 +1828,9 @@ async fn responses_websocket_previous_response_id_should_retry_fallback_account_
.unwrap();
assert!(body.contains("\"id\":\"resp_history_fallback\""));
assert_eq!(fallback_payload["previous_response_id"], "resp_prev");
// 亲和缓存无 `resp_prev` 记录(Unknown owner),换账号前历史即被剥离,
// 由 `input` 让备用账号重建上下文,不把上一账号作用域的 id 透传给它。
assert_eq!(fallback_payload.get("previous_response_id"), None);
assert_eq!(secondary_usage.0, 1);
}
@@ -1858,7 +1880,9 @@ async fn responses_websocket_non_stream_previous_response_id_should_retry_fallba
.unwrap();
assert_eq!(body["id"], "resp_history_fallback_non_stream");
assert_eq!(fallback_payload["previous_response_id"], "resp_prev");
// 亲和缓存无 `resp_prev` 记录(Unknown owner),换账号前历史即被剥离,
// 由 `input` 让备用账号重建上下文,不把上一账号作用域的 id 透传给它。
assert_eq!(fallback_payload.get("previous_response_id"), None);
assert_eq!(secondary_usage.0, 1);
}
@@ -2304,10 +2328,9 @@ async fn responses_stream_with_previous_response_id_should_forward_websocket_chu
captured_header(&captured.headers, "authorization"),
Some("Bearer access-secret")
);
assert_eq!(
captured.payload["previous_response_id"],
"resp_runtime_pool_previous"
);
// 亲和缓存无该 previous_response_id 的记录(Unknown),故上游 payload 里应被剥离,
// 靠已展开的 input 让选中账号自行重建续链——与 sub2api/codex2api 的默认行为一致。
assert_eq!(captured.payload["previous_response_id"], Value::Null);
}
#[tokio::test]
@@ -2335,10 +2358,8 @@ async fn responses_stream_with_previous_response_id_should_record_websocket_audi
let metadata: Value = serde_json::from_str(&event.metadata_json).unwrap();
assert!(body.contains("resp_live_websocket_stream"));
assert_eq!(
captured.payload["previous_response_id"],
"resp_runtime_pool_previous"
);
// 亲和缓存无记录(Unknown)→ 上游 payload 里 previous_response_id 被剥离。
assert_eq!(captured.payload["previous_response_id"], Value::Null);
assert_eq!(event.level, "info");
assert_eq!(metadata["stream"], true);
assert_eq!(metadata["transport"], "websocket");
@@ -678,7 +678,7 @@ async fn responses_stream_should_record_usage_record_after_late_disconnect() {
let response = response_task.await.unwrap();
close_upstream.send(()).unwrap();
let body = response_text(response).await;
let event = latest_response_usage_record(&pool).await;
let event = latest_response_ops_error_log(&pool).await;
let metadata: Value = serde_json::from_str(&event.metadata_json).unwrap();
assert!(body.contains("stream_disconnected"));
@@ -744,7 +744,7 @@ async fn responses_stream_should_record_failure_detail_after_transport_error() {
let response = response_task.await.unwrap();
close_upstream.send(()).unwrap();
let _body = response_text(response).await;
let event = latest_response_usage_record(&pool).await;
let event = latest_response_ops_error_log(&pool).await;
let metadata: Value = serde_json::from_str(&event.metadata_json).unwrap();
assert_eq!(metadata["failureSource"], "proxy");
@@ -788,7 +788,7 @@ async fn responses_stream_should_not_record_first_token_when_metadata_only_prefi
let response = response_task.await.unwrap();
close_upstream.send(()).unwrap();
let body = response_text(response).await;
let event = latest_response_usage_record(&pool).await;
let event = latest_response_ops_error_log(&pool).await;
let metadata: Value = serde_json::from_str(&event.metadata_json).unwrap();
let first_token_bucket: (i64, i64) = sqlx::query_as(
"select coalesce(sum(first_token_latency_sum), 0), coalesce(sum(first_token_latency_count), 0) from usage_time_buckets",
@@ -855,7 +855,7 @@ async fn responses_should_record_request_count_when_5xx_retries_are_exhausted()
assert_eq!(status, StatusCode::BAD_GATEWAY);
assert_eq!(authorizations.len(), 3, "requests: {authorizations:?}");
assert_eq!(failed_usage.map(|row| row.0).unwrap_or_default(), 1);
let event = latest_response_usage_record(&pool).await;
let event = latest_response_ops_error_log(&pool).await;
let metadata: Value = serde_json::from_str(&event.metadata_json).unwrap();
assert_eq!(event.account_id.as_deref(), Some("acct_chat"));
assert_eq!(metadata["accountEmail"], "user@example.com");
@@ -906,7 +906,7 @@ async fn responses_should_record_attempt_trace_after_retrying_another_account()
)
.await
.unwrap();
let event = latest_response_usage_record(&pool).await;
let event = latest_response_ops_error_log(&pool).await;
let metadata: Value = serde_json::from_str(&event.metadata_json).unwrap();
assert_eq!(response.status(), StatusCode::BAD_GATEWAY);
@@ -261,6 +261,14 @@ fn session_affinity_map_should_find_latest_response_by_conversation_and_variant(
map.lookup_latest_response_by_conversation("conv", None, Some("variant_a"), now),
Some("resp_new".to_string())
);
assert_eq!(
map.lookup_latest_account_by_conversation("conv", None, Some("variant_a"), now),
Some("acct_b".to_string())
);
assert_eq!(
map.lookup_latest_account_by_conversation("conv", None, Some("variant_b"), now),
Some("acct_c".to_string())
);
assert_eq!(
map.lookup_turn_state("resp_new", now),
Some("turn_new".to_string())
+27 -3
View File
@@ -1,6 +1,9 @@
use super::*;
use std::collections::BTreeMap;
use std::{
collections::BTreeMap,
sync::atomic::{AtomicUsize, Ordering},
};
use codex_proxy_rs::upstream::{
accounts::pool::{AccountAcquireRequest, AccountPoolOptions, RuntimeAccountPoolService},
@@ -50,6 +53,8 @@ async fn model_refresh_task_should_sync_model_plan_allowlist_to_account_pool() {
plan_account("acct-plus", "plus"),
plan_account("acct-team", "team"),
],
request_usage_records: Arc::new(AtomicUsize::new(0)),
model_request_usage_records: Arc::new(AtomicUsize::new(0)),
});
let account_pool = Arc::new(RuntimeAccountPoolService::new(
account_store.clone(),
@@ -74,6 +79,16 @@ async fn model_refresh_task_should_sync_model_plan_allowlist_to_account_pool() {
.await
.expect("team model should acquire an account");
assert_eq!(acquired.account.id, "acct-team");
assert_eq!(
account_store.request_usage_records.load(Ordering::SeqCst),
0
);
assert_eq!(
account_store
.model_request_usage_records
.load(Ordering::SeqCst),
0
);
}
fn empty_model_config() -> ModelConfig {
@@ -139,6 +154,8 @@ impl CodexModelCatalogClient for FakeModelCatalogClient {
struct PlanAccountStore {
accounts: Vec<Account>,
request_usage_records: Arc<AtomicUsize>,
model_request_usage_records: Arc<AtomicUsize>,
}
#[async_trait]
@@ -174,8 +191,11 @@ impl AccountStore for PlanAccountStore {
async fn record_usage_delta(
&self,
_account_id: &str,
_usage: AccountUsageDelta,
usage: AccountUsageDelta,
) -> AccountStoreResult<()> {
if usage.requests > 0 {
self.request_usage_records.fetch_add(1, Ordering::SeqCst);
}
Ok(())
}
@@ -183,8 +203,12 @@ impl AccountStore for PlanAccountStore {
&self,
_account_id: &str,
_model: &str,
_usage: AccountModelUsageDelta,
usage: AccountModelUsageDelta,
) -> AccountStoreResult<()> {
if usage.requests > 0 {
self.model_request_usage_records
.fetch_add(1, Ordering::SeqCst);
}
Ok(())
}
-1
View File
@@ -8,7 +8,6 @@ pub(crate) fn test_config(database_url: String) -> AppConfig {
server: ServerConfig {
host: "127.0.0.1".to_string(),
port: 0,
trusted_proxies: Vec::new(),
},
api: ApiConfig {
base_url: "https://chatgpt.com/backend-api".to_string(),
+1
View File
@@ -2,5 +2,6 @@ pub(crate) mod accounts;
pub(crate) mod fingerprint;
pub(crate) mod models;
pub(crate) mod protocol;
pub(crate) mod scheduler;
pub(crate) mod token_client;
pub(crate) mod transport;
@@ -0,0 +1,44 @@
use codex_proxy_rs::upstream::scheduler::{FeedbackSample, FeedbackStats};
#[test]
fn sample_of_unknown_account_is_empty() {
let stats = FeedbackStats::new();
assert_eq!(stats.sample("missing"), FeedbackSample::default());
}
#[test]
fn first_sample_lands_directly() {
let stats = FeedbackStats::new();
stats.report("acct", false, Some(400));
let sample = stats.sample("acct");
assert_eq!(sample.error_rate, Some(1.0));
assert_eq!(sample.ttft_ms, Some(400.0));
}
#[test]
fn subsequent_samples_blend_by_alpha() {
let stats = FeedbackStats::new();
stats.report("acct", false, Some(1000)); // error_rate=1.0, ttft=1000
stats.report("acct", true, Some(0)); // error_rate=0.8, ttft=800
let sample = stats.sample("acct");
assert!((sample.error_rate.unwrap() - 0.8).abs() < 1e-9);
assert!((sample.ttft_ms.unwrap() - 800.0).abs() < 1e-9);
}
#[test]
fn success_only_reports_decay_error_rate() {
let stats = FeedbackStats::new();
stats.report("acct", false, None); // error_rate=1.0, ttft untouched
stats.report("acct", true, None); // error_rate=0.8
let sample = stats.sample("acct");
assert!((sample.error_rate.unwrap() - 0.8).abs() < 1e-9);
assert_eq!(sample.ttft_ms, None);
}
#[test]
fn remove_clears_account() {
let stats = FeedbackStats::new();
stats.report("acct", false, Some(100));
stats.remove("acct");
assert_eq!(stats.sample("acct"), FeedbackSample::default());
}
+2
View File
@@ -0,0 +1,2 @@
pub(crate) mod feedback;
pub(crate) mod score;
+144
View File
@@ -0,0 +1,144 @@
use chrono::Utc;
use codex_proxy_rs::upstream::accounts::model::AccountStatus;
use codex_proxy_rs::upstream::scheduler::{rank_candidates, FeedbackStats, ScoreWeights};
use crate::support::accounts::test_account;
#[test]
fn ranks_idle_account_above_loaded_one() {
let mut loaded = test_account("loaded", AccountStatus::Active);
loaded.window_input_tokens = 1_000_000;
let idle = test_account("idle", AccountStatus::Active);
let candidates = vec![loaded, idle];
let feedback = FeedbackStats::new();
let slot_count = |_: &str| 0;
let ranked = rank_candidates(
&candidates,
&ScoreWeights::default(),
Utc::now().timestamp(),
&slot_count,
&feedback,
);
// idle 账号(索引 1)窗口用量为 0,应排在负载重的账号之前。
assert_eq!(ranked.first().unwrap().0, 1);
}
#[test]
fn high_error_rate_account_is_penalized() {
let healthy = test_account("healthy", AccountStatus::Active);
let flaky = test_account("flaky", AccountStatus::Active);
let candidates = vec![healthy, flaky];
let feedback = FeedbackStats::new();
// flaky 连续失败,错误率 EWMA 拉高。
for _ in 0..5 {
feedback.report("flaky", false, None);
}
let slot_count = |_: &str| 0;
let ranked = rank_candidates(
&candidates,
&ScoreWeights::default(),
Utc::now().timestamp(),
&slot_count,
&feedback,
);
// healthy(索引 0)应排在 flaky 之前。
assert_eq!(ranked.first().unwrap().0, 0);
}
#[test]
fn quota_limited_account_ranks_last_despite_being_idle() {
let mut limited = test_account("limited", AccountStatus::Active);
limited.quota_limit_reached = true;
let mut busy = test_account("busy", AccountStatus::Active);
busy.window_input_tokens = 1_000_000;
busy.window_request_count = 100;
let candidates = vec![limited, busy];
let feedback = FeedbackStats::new();
let slot_count = |_: &str| 0;
let ranked = rank_candidates(
&candidates,
&ScoreWeights::default(),
Utc::now().timestamp(),
&slot_count,
&feedback,
);
// 即使 limited 完全空闲,配额封顶惩罚也应让繁忙但未封顶的 busy(索引 1)排前。
assert_eq!(ranked.first().unwrap().0, 1);
}
#[test]
fn actual_token_load_dominates_cached() {
// cache_heavy 实际 token 更少(但缓存高),heavier_actual 实际 token 更多。
// 实际用量权重远大于缓存,cache_heavy(索引 0)应排前。
let mut cache_heavy = test_account("cache_heavy", AccountStatus::Active);
cache_heavy.window_input_tokens = 10_000;
cache_heavy.window_cached_tokens = 100_000;
let mut heavier_actual = test_account("heavier_actual", AccountStatus::Active);
heavier_actual.window_input_tokens = 20_000;
let candidates = vec![cache_heavy, heavier_actual];
let feedback = FeedbackStats::new();
let slot_count = |_: &str| 0;
let ranked = rank_candidates(
&candidates,
&ScoreWeights::default(),
Utc::now().timestamp(),
&slot_count,
&feedback,
);
assert_eq!(ranked.first().unwrap().0, 0);
}
#[test]
fn cached_breaks_ties_when_actual_load_matches() {
// 实际 token 相同,缓存少者(cache_light,索引 1)应排前。
let mut cache_heavy = test_account("cache_heavy", AccountStatus::Active);
cache_heavy.window_input_tokens = 10_000;
cache_heavy.window_cached_tokens = 100_000;
let mut cache_light = test_account("cache_light", AccountStatus::Active);
cache_light.window_input_tokens = 10_000;
cache_light.window_cached_tokens = 1_000;
let candidates = vec![cache_heavy, cache_light];
let feedback = FeedbackStats::new();
let slot_count = |_: &str| 0;
let ranked = rank_candidates(
&candidates,
&ScoreWeights::default(),
Utc::now().timestamp(),
&slot_count,
&feedback,
);
assert_eq!(ranked.first().unwrap().0, 1);
}
#[test]
fn zero_weights_produce_flat_scores() {
let candidates = vec![
test_account("a", AccountStatus::Active),
test_account("b", AccountStatus::Active),
];
let feedback = FeedbackStats::new();
let weights = ScoreWeights {
load: 0.0,
window: 0.0,
cached: 0.0,
window_requests: 0.0,
error_rate: 0.0,
ttft: 0.0,
reset: 0.0,
};
let slot_count = |_: &str| 0;
let ranked = rank_candidates(
&candidates,
&weights,
Utc::now().timestamp(),
&slot_count,
&feedback,
);
assert!(ranked.iter().all(|(_, b)| b.total == 0.0));
}
@@ -4,6 +4,29 @@ use codex_proxy_rs::upstream::{
transport::websocket::write_websocket_audit_artifact_for_dir,
};
fn rate_limit_event(used_percent: u64) -> String {
json!({
"type": "codex.rate_limits",
"rate_limits": {
"primary": {
"used_percent": used_percent,
"window_minutes": 43200,
"reset_at": 1893456000 + used_percent as i64,
}
}
})
.to_string()
}
fn primary_used_percent_values(headers: &[(String, String)]) -> Vec<&str> {
headers
.iter()
.filter_map(|(name, value)| {
(name == "x-codex-primary-used-percent").then_some(value.as_str())
})
.collect()
}
#[tokio::test]
async fn websocket_audit_artifact_should_require_explicit_directory() {
let dir = tempfile::tempdir().expect("temp dir");
@@ -663,6 +686,74 @@ async fn websocket_execute_response_create_request_should_capture_internal_metad
.any(|(name, value)| name == "x-codex-primary-reset-at" && value == "1893456300"));
}
#[tokio::test]
async fn codex_backend_client_should_not_reuse_websocket_rate_limit_headers() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
let (stream, _) = listener.accept().await.unwrap();
let mut websocket = accept_codex_test_websocket(stream).await;
let _first_message = websocket.next().await.unwrap().unwrap();
websocket
.send(Message::Text(rate_limit_event(10).into()))
.await
.unwrap();
websocket
.send(Message::Text(
completed_websocket_response("resp_rate_limit_first", 3, 1).into(),
))
.await
.unwrap();
let _second_message = websocket.next().await.unwrap().unwrap();
websocket
.send(Message::Text(rate_limit_event(20).into()))
.await
.unwrap();
websocket
.send(Message::Text(
completed_websocket_response("resp_rate_limit_second", 5, 2).into(),
))
.await
.unwrap();
websocket.close(None).await.unwrap();
});
let pool = Arc::new(CodexWebSocketPool::new(8, Duration::from_mins(1)));
let backend = CodexBackendClient::new(
reqwest::Client::builder().no_proxy().build().unwrap(),
format!("http://{addr}"),
crate::support::fingerprint::runtime_test_fingerprint(),
)
.with_websocket_pool(pool);
let request = pooled_websocket_request("conversation-rate-limit-reuse");
let first = backend
.create_response(
&request,
request_context("req_rate_limit_first", Some("chatgpt-account")),
)
.await
.expect("first pooled websocket response should succeed");
let second = backend
.create_response(
&request,
request_context("req_rate_limit_second", Some("chatgpt-account")),
)
.await
.expect("second pooled websocket response should reuse connection");
server.await.unwrap();
assert_eq!(
primary_used_percent_values(&first.rate_limit_headers),
vec!["10"]
);
assert_eq!(
primary_used_percent_values(&second.rate_limit_headers),
vec!["20"]
);
}
#[tokio::test]
async fn websocket_execute_response_create_request_should_surface_incomplete_response() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+1 -3
View File
@@ -19,9 +19,7 @@ cp deploy/config.example.yaml .runtime/config.yaml
复制后必须设置 `admin.default_password`。空值、长度不足 12 位或常见弱口令会被后端拒绝。
如果前面还有 Nginx、Caddy、Cloudflare Tunnel 等反向代理,把后端实际看到的代理 peer IP 或 CIDR 写入 `server.trusted_proxies`。经宿主机反代访问 Docker 端口时,这个 peer 通常是 Compose 网络网关,例如 `172.18.0.1/32`,不是宿主 `127.0.0.1/32`。
`server.trusted_proxies` 非空时,只有这些 peer 的 `CF-Connecting-IP` / `X-Real-IP` / `X-Forwarded-For` 会被采信;为空时进入自动解析模式,按同一组头解析真实 IP。
如果前面还有 Nginx、Caddy、Cloudflare Tunnel 等反向代理,确保反代正常传递 `CF-Connecting-IP`、`X-Real-IP` 或 `X-Forwarded-For`。后端会按这组头自动解析真实客户端 IP;没有这些头时回落到直连 peer IP。
构建并启动:
-5
View File
@@ -3,11 +3,6 @@ server:
host: '0.0.0.0'
# 容器内服务端口,需与 docker-compose.yml 的 target port 一致。
port: 8080
# 可信反向代理 IP 或 CIDR。非空时只有这些 peer 的转发 IP 头会被采信。
# Docker 端口映射经宿主反代访问时,后端看到的 peer 通常是 Compose 网络网关
# (例如 172.18.0.1),不是宿主 127.0.0.1。
# 为空时进入自动解析模式,按 CF-Connecting-IP / X-Real-IP / X-Forwarded-For 解析。
trusted_proxies: []
api:
# ChatGPT / Codex 上游 API 地址。
+19 -5
View File
@@ -19,6 +19,7 @@ export interface SystemUpdateLog {
level: SystemUpdateLogLevel
step?: string
message: string
terminal?: boolean
at: string
}
@@ -84,8 +85,12 @@ function clearUpdateLogs() {
updateStreamError.value = ''
}
function connectUpdateEvents() {
if (updateEventSource.value) return
function connectUpdateEvents(options: { force?: boolean } = {}) {
if (options.force) {
disconnectUpdateEvents()
} else if (updateEventSource.value) {
return
}
if (typeof EventSource === 'undefined') {
updateStreamError.value = '当前浏览器不支持实时更新日志'
@@ -97,6 +102,8 @@ function connectUpdateEvents() {
updateEventSource.value = source
source.onopen = () => {
if (updateEventSource.value !== source) return
updateStreaming.value = true
updateStreamError.value = ''
}
@@ -106,6 +113,9 @@ function connectUpdateEvents() {
const log = JSON.parse((event as MessageEvent<string>).data)
if (isUpdateLog(log)) {
appendUpdateLog(log)
if (log.terminal) {
disconnectUpdateEvents(source)
}
}
} catch {
updateStreamError.value = '更新日志解析失败'
@@ -113,6 +123,8 @@ function connectUpdateEvents() {
})
source.onerror = () => {
if (updateEventSource.value !== source) return
updateStreaming.value = false
updateStreamError.value = '更新日志连接中断'
if (source.readyState === EventSource.CLOSED) {
@@ -121,8 +133,10 @@ function connectUpdateEvents() {
}
}
function disconnectUpdateEvents() {
updateEventSource.value?.close()
function disconnectUpdateEvents(source: EventSource | null = updateEventSource.value) {
source?.close()
if (source && updateEventSource.value !== source) return
updateEventSource.value = null
updateStreaming.value = false
}
@@ -184,7 +198,7 @@ async function updateNow(targetVersion: string) {
if (!canUpdate.value || !currentInfo || updating.value || !confirmedTargetVersion) return null
clearUpdateLogs()
connectUpdateEvents()
connectUpdateEvents({ force: true })
updating.value = true
updateError.value = ''
updateSuccess.value = false
@@ -286,7 +286,7 @@ watch(
<button
v-if="hasVersionLabel"
type="button"
class="inline-flex h-4.5 min-w-0 items-center gap-1 rounded-(--cp-input-radius-small) border-0 px-1.5 font-mono text-[10px] leading-none font-[720] cursor-pointer transition-colors"
class="inline-flex h-4.5 min-w-0 cursor-pointer items-center gap-1 rounded-(--cp-input-radius-small) border-0 px-1.5 font-mono text-[10px] leading-none font-[720] transition-colors outline-none focus-visible:ring-2 focus-visible:ring-(--cp-info-border) focus-visible:ring-offset-2 focus-visible:ring-offset-(--cp-bg-surface)"
:class="[
hasUpdate
? 'bg-(--cp-success-bg) text-(--cp-success-text) hover:bg-(--cp-success-bg-hover)'
@@ -309,7 +309,7 @@ watch(
v-for="item in navItems"
:key="item.label"
type="button"
class="inline-flex h-11.5 items-center rounded-(--cp-icon-button-radius) text-sm leading-[1.15] border-0 cursor-pointer transition-colors duration-200"
class="inline-flex h-11.5 cursor-pointer items-center rounded-(--cp-icon-button-radius) border-0 text-sm leading-[1.15] transition-colors duration-200 outline-none focus-visible:ring-2 focus-visible:ring-(--cp-info-border) focus-visible:ring-offset-2 focus-visible:ring-offset-(--cp-bg-surface)"
:class="[
isCollapsed ? 'w-11.5 justify-center' : 'w-full gap-3 px-4',
isActive(item.path)
@@ -45,7 +45,6 @@ const {
updateNow,
restartNow,
clearRestartTimer,
connectUpdateEvents,
disconnectUpdateEvents,
} = useSystemUpdate()
@@ -54,7 +53,6 @@ const updateConfirmOpen = shallowRef(false)
const updateConfirmInfo = shallowRef<SystemUpdateInfo | null>(null)
const updateConfirmPreviousTarget = shallowRef('')
const preparingUpdate = shallowRef(false)
let updateLogPinTimer: number | undefined
const statusView = computed(() => {
if (updating.value) {
@@ -137,7 +135,6 @@ const renderedReleaseNotes = computed(() => renderMarkdown(updateInfo.value?.not
const showUpdateProgress = computed(
() => hasUpdate.value || updating.value || restarting.value || updateLogRows.value.length > 0,
)
const shouldConnectUpdateEvents = computed(() => (open.value && hasUpdate.value) || updating.value)
const updateConfirmRows = computed(() => [
{
@@ -212,20 +209,6 @@ function pinUpdateLogsToBottom() {
})
}
function startUpdateLogPinning() {
if (updateLogPinTimer !== undefined) return
pinUpdateLogsToBottom()
updateLogPinTimer = window.setInterval(pinUpdateLogsToBottom, 250)
}
function stopUpdateLogPinning() {
if (updateLogPinTimer === undefined) return
window.clearInterval(updateLogPinTimer)
updateLogPinTimer = undefined
}
async function handleCheckUpdates(force = true) {
try {
const data = await checkUpdates(force)
@@ -304,45 +287,17 @@ watch(open, (visible) => {
}
})
watch(
shouldConnectUpdateEvents,
(shouldConnect) => {
if (shouldConnect) {
connectUpdateEvents()
} else {
disconnectUpdateEvents()
}
},
{ immediate: true },
)
watch(
() => updateLogs.value.at(-1)?.id,
() => {
(logId, previousLogId) => {
if (!logId || logId === previousLogId) return
pinUpdateLogsToBottom()
},
)
watch(
() => updateLogRows.value.length,
() => {
pinUpdateLogsToBottom()
},
)
watch(
() => updating.value || restarting.value || updateStreaming.value,
(active) => {
if (active) {
startUpdateLogPinning()
return
}
stopUpdateLogPinning()
},
{ flush: 'post' },
)
onUnmounted(() => {
stopUpdateLogPinning()
clearRestartTimer()
disconnectUpdateEvents()
})
@@ -42,6 +42,29 @@ function quotaWindowBarClass(window?: any) {
}
return 'bg-(--cp-success)'
}
function quotaWindowPercentTextClass(window?: any) {
if (window?.usedPercent === null || window?.usedPercent === undefined) {
return 'text-(--cp-text-muted)'
}
if (window.usedPercent >= 95) {
return 'text-(--cp-danger-text)'
}
if (window.usedPercent >= 80) {
return 'text-(--cp-warning-text)'
}
return 'text-(--cp-success-text)'
}
function quotaWindowLocalUsageDisplay(window?: any) {
const display = window?.localUsage?.totalTokensDisplay
return typeof display === 'string' && display.trim() ? display : '-'
}
function shouldShowQuotaWindowLocalUsage(window?: any) {
const totalTokens = window?.localUsage?.totalTokens
return typeof totalTokens === 'number' && totalTokens > 0
}
</script>
<template>
@@ -80,7 +103,17 @@ function quotaWindowBarClass(window?: any) {
>
<div class="flex items-center justify-between gap-3 text-[12px] font-[720]">
<span class="text-(--cp-text-secondary)">{{ window.labelDisplay }}</span>
<span class="text-(--cp-text-primary)">{{ window.usedPercentDisplay }}</span>
<span class="flex shrink-0 items-baseline justify-end gap-1.5 font-mono tabular-nums">
<span
v-if="shouldShowQuotaWindowLocalUsage(window)"
class="text-[12px] font-[680] text-(--cp-text-muted)"
>
{{ quotaWindowLocalUsageDisplay(window) }}
</span>
<span class="text-[12px] font-[780]" :class="quotaWindowPercentTextClass(window)">
{{ window.usedPercentDisplay }}
</span>
</span>
</div>
<div class="mt-2 h-2 overflow-hidden rounded-full bg-(--cp-default-border)">
<div
@@ -105,7 +138,17 @@ function quotaWindowBarClass(window?: any) {
>
<div class="flex items-center justify-between gap-3 text-[12px] font-[720]">
<span class="text-(--cp-text-secondary)">{{ window.labelDisplay }}</span>
<span class="text-(--cp-text-primary)">{{ window.usedPercentDisplay }}</span>
<span class="flex shrink-0 items-baseline justify-end gap-1.5 font-mono tabular-nums">
<span
v-if="shouldShowQuotaWindowLocalUsage(window)"
class="text-[12px] font-[680] text-(--cp-text-muted)"
>
{{ quotaWindowLocalUsageDisplay(window) }}
</span>
<span class="text-[12px] font-[780]" :class="quotaWindowPercentTextClass(window)">
{{ window.usedPercentDisplay }}
</span>
</span>
</div>
<div class="mt-2 h-2 overflow-hidden rounded-full bg-(--cp-default-border)">
<div
@@ -130,7 +173,17 @@ function quotaWindowBarClass(window?: any) {
>
<div class="flex items-center justify-between gap-3 text-[12px] font-[720]">
<span class="text-(--cp-text-secondary)">{{ window.labelDisplay }}</span>
<span class="text-(--cp-text-primary)">{{ window.usedPercentDisplay }}</span>
<span class="flex shrink-0 items-baseline justify-end gap-1.5 font-mono tabular-nums">
<span
v-if="shouldShowQuotaWindowLocalUsage(window)"
class="text-[12px] font-[680] text-(--cp-text-muted)"
>
{{ quotaWindowLocalUsageDisplay(window) }}
</span>
<span class="text-[12px] font-[780]" :class="quotaWindowPercentTextClass(window)">
{{ window.usedPercentDisplay }}
</span>
</span>
</div>
<div class="mt-2 h-2 overflow-hidden rounded-full bg-(--cp-default-border)">
<div
@@ -50,16 +50,21 @@ function quotaWindowBarClass(window?: any) {
return 'bg-(--cp-success)'
}
function windowUsageDisplay(window?: any) {
const display = window?.tokenUsageDisplay
return typeof display === 'string' && display.trim() ? display : '-'
}
function windowPercentDisplay(window?: any) {
const display = window?.usedPercentDisplay
return typeof display === 'string' && display.trim() ? display : '-'
}
function windowLocalUsageDisplay(window?: any) {
const display = window?.localUsage?.totalTokensDisplay
return typeof display === 'string' && display.trim() ? display : '-'
}
function shouldShowWindowLocalUsage(window?: any) {
const totalTokens = window?.localUsage?.totalTokens
return typeof totalTokens === 'number' && totalTokens > 0
}
function quotaWindowPercentTextClass(window?: any) {
if (window?.usedPercent === null || window?.usedPercent === undefined) {
return 'text-(--cp-text-muted)'
@@ -99,15 +104,18 @@ function quotaWindowMatches(actual: unknown, expected: number) {
{{ window.labelDisplay }}
</span>
<span class="flex shrink-0 items-baseline justify-end gap-1.5 font-mono tabular-nums">
<span
v-if="shouldShowWindowLocalUsage(window)"
class="text-[10px] leading-none font-[680] text-(--cp-text-muted)"
>
{{ windowLocalUsageDisplay(window) }}
</span>
<span
class="text-[10px] leading-none font-[780]"
:class="quotaWindowPercentTextClass(window)"
>
{{ windowPercentDisplay(window) }}
</span>
<span class="text-[10px] leading-none font-[680] text-(--cp-text-muted)">
{{ windowUsageDisplay(window) }}
</span>
</span>
</div>
<div class="h-1 w-full overflow-hidden rounded-full bg-(--cp-default-border)">
@@ -19,8 +19,8 @@ const model = defineModel<RotationStrategy>({ required: true })
<template>
<BaseCard
:padded="false"
title="账号选择"
description="决定每次请求如何使用账号池。"
title="调度策略"
description="决定每次请求如何调度账号池。"
header-class="px-5 pt-4"
body-class="px-5 py-5"
>
+1 -1
View File
@@ -1 +1 @@
version: "1.0.8"
version: "1.0.9"