diff --git a/backend/src/admin/accounts/service/types.rs b/backend/src/admin/accounts/service/contracts.rs similarity index 100% rename from backend/src/admin/accounts/service/types.rs rename to backend/src/admin/accounts/service/contracts.rs diff --git a/backend/src/admin/accounts/service/exporting.rs b/backend/src/admin/accounts/service/exporting.rs index 05e3cdc44..7b54c8266 100644 --- a/backend/src/admin/accounts/service/exporting.rs +++ b/backend/src/admin/accounts/service/exporting.rs @@ -1,7 +1,7 @@ use secrecy::ExposeSecret; use super::{ - types::{ExportedAccount, ExportedAccounts}, + contracts::{ExportedAccount, ExportedAccounts}, AdminAccountError, AdminAccountService, }; use crate::{ diff --git a/backend/src/admin/accounts/service/importing.rs b/backend/src/admin/accounts/service/importing.rs index b7205783d..78ba7d47e 100644 --- a/backend/src/admin/accounts/service/importing.rs +++ b/backend/src/admin/accounts/service/importing.rs @@ -2,7 +2,7 @@ use chrono::Utc; use secrecy::SecretString; use super::{ - types::{ + contracts::{ import_quota_plan_type, import_status_from_usage_error, import_usage_plan_type, import_usage_string, AdminAccountError, ImportSupplementalAccountInfo, ImportSupplementalNeeds, ImportedAccountState, ImportedAccounts, ResolvedImportTokens, diff --git a/backend/src/admin/accounts/service/lifecycle.rs b/backend/src/admin/accounts/service/lifecycle.rs index 75703b19d..e0485b6cb 100644 --- a/backend/src/admin/accounts/service/lifecycle.rs +++ b/backend/src/admin/accounts/service/lifecycle.rs @@ -17,7 +17,7 @@ use crate::{ }; use super::{ - types::{ + contracts::{ parse_account_status, stored_to_admin_metadata, AdminAccountError, AdminAccountHealthCheck, AdminAccountMetadata, AdminAccountRefreshOutcome, AdminAccountRefreshResult, AdminAccountUpdate, BatchDeleteAccounts, ManualCreateTokens, UpdatedAccountStatus, diff --git a/backend/src/admin/accounts/service/mod.rs b/backend/src/admin/accounts/service/mod.rs index d67336213..8cf3541b9 100644 --- a/backend/src/admin/accounts/service/mod.rs +++ b/backend/src/admin/accounts/service/mod.rs @@ -1,5 +1,6 @@ //! 管理端账号业务服务。 +mod contracts; mod cookies; mod exporting; mod importing; @@ -7,7 +8,6 @@ mod lifecycle; pub(crate) mod oauth; mod quota; mod testing; -mod types; use std::sync::Arc as StdArc; @@ -20,11 +20,11 @@ use crate::{ store::SqliteAccountStore, token_refresh::{RuntimeRefreshPolicy, TokenRefresher}, }, - upstream::models::ModelService, + upstream::models::service::ModelService, upstream::transport::CodexBackendClient, }; -pub use types::{ +pub use contracts::{ AdminAccountError, AdminAccountHealthCheck, AdminAccountMetadata, AdminAccountRefreshOutcome, AdminAccountRefreshResult, AdminAccountUpdate, BatchDeleteAccounts, ExportedAccounts, ImportedAccounts, OAuthAuthorizeResult, OAuthExchangeInput, UpdatedAccountStatus, diff --git a/backend/src/admin/accounts/service/oauth.rs b/backend/src/admin/accounts/service/oauth.rs index d691b20ab..b176ee3c5 100644 --- a/backend/src/admin/accounts/service/oauth.rs +++ b/backend/src/admin/accounts/service/oauth.rs @@ -9,7 +9,7 @@ use sha2::{Digest, Sha256}; use tokio::sync::Mutex; use super::{ - types::{AdminAccountError, OAuthAuthorizeResult, OAuthExchangeInput}, + contracts::{AdminAccountError, OAuthAuthorizeResult, OAuthExchangeInput}, AdminAccountService, }; @@ -144,7 +144,7 @@ impl AdminAccountService { pub async fn oauth_exchange( &self, input: OAuthExchangeInput, - ) -> Result { + ) -> Result { let tokens = self.oauth.exchange(input).await?; self.import(serde_json::json!({ "sourceFormat": "cpr", diff --git a/backend/src/admin/accounts/service/quota.rs b/backend/src/admin/accounts/service/quota.rs index 1a9b88a3b..7f058a90c 100644 --- a/backend/src/admin/accounts/service/quota.rs +++ b/backend/src/admin/accounts/service/quota.rs @@ -1,6 +1,6 @@ use secrecy::ExposeSecret; -use super::{types::AdminAccountError, AdminAccountService}; +use super::{contracts::AdminAccountError, AdminAccountService}; impl AdminAccountService { pub async fn account_quota( diff --git a/backend/src/admin/accounts/service/testing.rs b/backend/src/admin/accounts/service/testing.rs index 9c7fac4ab..b49b592e5 100644 --- a/backend/src/admin/accounts/service/testing.rs +++ b/backend/src/admin/accounts/service/testing.rs @@ -8,8 +8,7 @@ use tokio::sync::mpsc; use crate::upstream::{ accounts::{model::Account, store::StoredAccount}, - models::CodexModelInfo, - models::ModelRefreshPlanAccount, + models::{info::CodexModelInfo, service::ModelRefreshPlanAccount}, protocol::{ responses::CodexResponsesRequest, sse::{encode_sse_event, parse_sse_events, SseEvent}, @@ -17,7 +16,7 @@ use crate::upstream::{ transport::CodexRequestContext, }; -use super::{types::AdminAccountError, AdminAccountService}; +use super::{contracts::AdminAccountError, AdminAccountService}; pub(super) type AccountTestStream = Pin> + Send>>; diff --git a/backend/src/admin/settings/routes.rs b/backend/src/admin/settings/routes.rs index 8da1fdae4..855672ee9 100644 --- a/backend/src/admin/settings/routes.rs +++ b/backend/src/admin/settings/routes.rs @@ -9,10 +9,11 @@ use crate::{ admin::auth::session::AdminAuth, admin::response::{AdminEnvelope, AdminError, AdminResponse}, config::{ + schema::AppConfig, settings::{AdminSettingsPatch, RuntimeSettingsError, SettingsServiceError}, - types::AppConfig, }, runtime::state::AppState, + upstream::models::config::ModelConfig, }; const ALLOWED_SETTINGS_KEYS: [&str; 7] = [ @@ -76,12 +77,9 @@ pub(crate) async fn update_settings( .update(patch) .await .map_err(settings_service_error)?; - state - .services - .models - .update_config(crate::upstream::models::ModelConfig { - model_aliases: config.model_aliases.clone(), - }); + state.services.models.update_config(ModelConfig { + model_aliases: config.model_aliases.clone(), + }); Ok(AdminResponse::new( StatusCode::OK, diff --git a/backend/src/admin/system/updater.rs b/backend/src/admin/system/updater/mod.rs similarity index 100% rename from backend/src/admin/system/updater.rs rename to backend/src/admin/system/updater/mod.rs diff --git a/backend/src/config/loader.rs b/backend/src/config/loader.rs index 79c849f93..154729411 100644 --- a/backend/src/config/loader.rs +++ b/backend/src/config/loader.rs @@ -1,6 +1,6 @@ use std::{env, path::Path}; -use super::types::AppConfig; +use super::schema::AppConfig; const CONFIG_FILE_ENV: &str = "CPR_CONFIG_FILE"; diff --git a/backend/src/config/mod.rs b/backend/src/config/mod.rs index 0d7330769..013acb1c6 100644 --- a/backend/src/config/mod.rs +++ b/backend/src/config/mod.rs @@ -1,10 +1,10 @@ -//! 配置加载与配置类型。 +//! 配置加载与配置 schema。 #![deny(missing_docs)] /// 配置加载器。 pub mod loader; +/// 配置文件 schema 与默认值。 +pub mod schema; /// 管理端可变设置与运行时写回服务。 pub mod settings; -/// 配置类型定义。 -pub mod types; diff --git a/backend/src/config/types.rs b/backend/src/config/schema.rs similarity index 100% rename from backend/src/config/types.rs rename to backend/src/config/schema.rs diff --git a/backend/src/config/settings.rs b/backend/src/config/settings.rs index abc0d24df..8d95af17d 100644 --- a/backend/src/config/settings.rs +++ b/backend/src/config/settings.rs @@ -11,7 +11,7 @@ use sqlx::{sqlite::SqliteRow, Row, SqlitePool}; use subtle::ConstantTimeEq; use thiserror::Error; -use crate::config::types::AppConfig; +use crate::config::schema::AppConfig; use crate::infra::identity::generate_admin_api_key; use crate::upstream::accounts::{ pool::{AccountPoolOptions, RotationStrategy, RuntimeAccountPoolService}, diff --git a/backend/src/proxy/dispatch/chat.rs b/backend/src/proxy/dispatch/chat.rs index 2648d209d..9ab73cf0f 100644 --- a/backend/src/proxy/dispatch/chat.rs +++ b/backend/src/proxy/dispatch/chat.rs @@ -42,7 +42,7 @@ use crate::{ token_refresh::RuntimeTokenRefreshService, }, upstream::{ - models::ModelCatalog, + models::{catalog::ModelCatalog, service::ModelService}, protocol::responses::{apply_response_model_options, CodexResponsesRequest}, token_client::OpenAiTokenClient, transport::{ @@ -56,7 +56,7 @@ use crate::{ #[derive(Clone)] pub struct ChatDispatchService { account_pool: Arc, - models: Arc, + models: Arc, codex: Arc, usage_records: Arc, token_refresh: Arc>, @@ -67,7 +67,7 @@ pub struct ChatDispatchService { impl ChatDispatchService { pub(crate) fn new( account_pool: Arc, - models: Arc, + models: Arc, codex: Arc, usage_records: Arc, token_refresh: Arc>, diff --git a/backend/src/proxy/dispatch/responses/affinity.rs b/backend/src/proxy/dispatch/responses/affinity.rs new file mode 100644 index 000000000..5750c77ac --- /dev/null +++ b/backend/src/proxy/dispatch/responses/affinity.rs @@ -0,0 +1,100 @@ +use std::sync::Arc; + +use chrono::Utc; +use tokio::sync::Mutex; + +use crate::{ + proxy::dispatch::{ + reasoning_replay::ReasoningReplayCache, + session_affinity::{ + compute_variant_hash, hash_instructions, RuntimeSessionAffinityService, + }, + }, + upstream::protocol::{ + events::TokenUsage, + responses::{completed_response_metadata, CodexResponsesRequest}, + }, +}; + +pub(super) async fn record_response_affinity( + session_affinity: &Arc, + reasoning_replay: &Arc>, + request: &CodexResponsesRequest, + account_id: &str, + body: &str, + turn_state: Option, + usage: Option, +) { + let Some(conversation_id) = request + .prompt_cache_key + .as_deref() + .map(str::trim) + .filter(|value| !value.is_empty()) + else { + return; + }; + let metadata = match completed_response_metadata(body) { + Ok(Some(metadata)) => metadata, + Ok(None) => return, + Err(error) => { + tracing::warn!( + error = %error, + "failed to parse completed response metadata for session affinity" + ); + return; + } + }; + + let variant_hash = compute_variant_hash(request); + let entry = crate::proxy::dispatch::session_affinity::SessionAffinityEntry { + account_id: account_id.to_string(), + conversation_id: conversation_id.to_string(), + turn_state: turn_state + .filter(|value| !value.trim().is_empty()) + .or_else(|| request.turn_state.clone()), + instructions_hash: Some(hash_instructions(Some(&request.instructions))), + input_tokens: usage.map(|usage| usage.input_tokens), + function_call_ids: metadata.function_call_ids, + variant_hash: Some(variant_hash.clone()), + created_at: Utc::now(), + }; + if let Err(error) = session_affinity + .record(metadata.response_id.clone(), entry) + .await + { + tracing::warn!( + error = %error, + response_id = %metadata.response_id, + account_id = %account_id, + "failed to record session affinity" + ); + } + + reasoning_replay.lock().await.record( + metadata.response_id, + account_id, + conversation_id, + &variant_hash, + &metadata.replay_items, + Utc::now(), + ); +} + +pub(super) async fn evict_reasoning_replay( + reasoning_replay: &Arc>, + request: &CodexResponsesRequest, + account_id: &str, +) { + let variant_hash = compute_variant_hash(request); + let conversation_id = request + .prompt_cache_key + .as_deref() + .unwrap_or("") + .to_string(); + reasoning_replay.lock().await.evict_by_identity( + account_id, + &conversation_id, + &variant_hash, + Utc::now(), + ); +} diff --git a/backend/src/proxy/dispatch/responses/errors.rs b/backend/src/proxy/dispatch/responses/errors.rs new file mode 100644 index 000000000..b8389a305 --- /dev/null +++ b/backend/src/proxy/dispatch/responses/errors.rs @@ -0,0 +1,234 @@ +use serde_json::{json, Value}; +use thiserror::Error; + +use crate::{ + proxy::dispatch::errors::{upstream_error_body, upstream_error_http_status}, + upstream::{ + protocol::{responses::ResponsesSseFailure, sse::SseError}, + transport::CodexClientError, + }, +}; + +use super::sse_failure::{sse_failure_error_body, stream_failure_http_status}; + +/// Responses 调度错误。 +#[derive(Debug, Error)] +pub enum ResponseDispatchError { + #[error("failed to list runtime accounts")] + AccountStore, + #[error("no active account is available")] + NoActiveAccount, + #[error("all accounts exhausted by quota")] + QuotaExhausted { + count: usize, + upstream_error: String, + }, + #[error("all accounts exhausted by rate limit")] + RateLimited { + count: usize, + upstream_error: String, + }, + #[error("all accounts exhausted by expired auth")] + Expired { + count: usize, + upstream_error: String, + }, + #[error("all accounts exhausted by disabled auth")] + Disabled { + count: usize, + upstream_error: String, + }, + #[error("all accounts exhausted by banned auth")] + Banned { + count: usize, + upstream_error: String, + status_code: u16, + }, + #[error("all accounts exhausted by Cloudflare challenge")] + CloudflareChallenge { + count: usize, + upstream_error: String, + }, + #[error("all accounts exhausted by Cloudflare path-block")] + CloudflarePathBlocked { + count: usize, + upstream_error: String, + }, + #[error("all accounts exhausted by unsupported model")] + ModelUnsupported { + count: usize, + upstream_error: String, + }, + #[error("upstream request failed: {0}")] + Upstream(#[from] CodexClientError), + #[error("invalid upstream SSE response: {0}")] + InvalidSse(#[from] SseError), + #[error("upstream response did not include response.completed")] + MissingCompleted, + #[error("upstream response did not include visible output")] + EmptyUpstreamResponse, + #[error("upstream response failed: {0:?}")] + Failed(ResponsesSseFailure), +} + +impl ResponseDispatchError { + pub fn http_status_code(&self) -> u16 { + match self { + Self::NoActiveAccount | Self::AccountStore => 503, + Self::QuotaExhausted { .. } => 429, + Self::RateLimited { .. } => 429, + Self::Expired { .. } | Self::Disabled { .. } => 401, + Self::Banned { status_code, .. } => *status_code, + Self::CloudflareChallenge { .. } + | Self::CloudflarePathBlocked { .. } + | Self::InvalidSse(_) + | Self::MissingCompleted + | Self::EmptyUpstreamResponse => 502, + Self::Failed(failure) => stream_failure_http_status(failure), + Self::ModelUnsupported { .. } => 400, + Self::Upstream(error) => upstream_error_http_status(error), + } + } +} + +/// Responses live SSE body stream error. +#[derive(Debug, Error)] +pub enum ResponseDispatchStreamError { + #[error("upstream stream failed: {0}")] + Upstream(#[from] CodexClientError), +} + +pub(super) fn dispatch_error_metadata( + error: impl std::fmt::Display, + stream: bool, + compact: bool, + transport: Option<&str>, +) -> Value { + let mut metadata = serde_json::json!({ + "stream": stream, + "failed": true, + "errorKind": "dispatch", + "error": error.to_string(), + }); + let Some(object) = metadata.as_object_mut() else { + return metadata; + }; + if compact { + object.insert("compact".to_string(), Value::Bool(true)); + } + if let Some(transport) = transport { + object.insert( + "transport".to_string(), + Value::String(transport.to_string()), + ); + } + metadata +} + +pub(super) fn enrich_response_dispatch_error_metadata( + metadata: &mut Value, + error: &ResponseDispatchError, +) { + let Some(object) = metadata.as_object_mut() else { + return; + }; + let (failure_class, exhausted_count, upstream_error, upstream_status) = match error { + ResponseDispatchError::AccountStore => ("account_store", None, None, None), + ResponseDispatchError::NoActiveAccount => ("no_available_accounts", None, None, None), + ResponseDispatchError::QuotaExhausted { + count, + upstream_error, + } => ( + "quota_exhausted", + Some(*count), + Some(upstream_error.clone()), + None, + ), + ResponseDispatchError::RateLimited { + count, + upstream_error, + } => ( + "rate_limited", + Some(*count), + Some(upstream_error.clone()), + None, + ), + ResponseDispatchError::Expired { + count, + upstream_error, + } => ("expired", Some(*count), Some(upstream_error.clone()), None), + ResponseDispatchError::Disabled { + count, + upstream_error, + } => ("disabled", Some(*count), Some(upstream_error.clone()), None), + ResponseDispatchError::Banned { + count, + upstream_error, + .. + } => ("banned", Some(*count), Some(upstream_error.clone()), None), + ResponseDispatchError::CloudflareChallenge { + count, + upstream_error, + } => ( + "cloudflare_challenge", + Some(*count), + Some(upstream_error.clone()), + None, + ), + ResponseDispatchError::CloudflarePathBlocked { + count, + upstream_error, + } => ( + "cloudflare_path_blocked", + Some(*count), + Some(upstream_error.clone()), + None, + ), + ResponseDispatchError::ModelUnsupported { + count, + upstream_error, + } => ( + "model_unsupported", + Some(*count), + Some(upstream_error.clone()), + None, + ), + ResponseDispatchError::Upstream(error) => { + let upstream_status = match error { + CodexClientError::Upstream { status, .. } => Some(status.as_u16()), + _ => None, + }; + ( + "upstream", + None, + Some(upstream_error_body(error)), + upstream_status, + ) + } + ResponseDispatchError::InvalidSse(_) => ("invalid_sse", None, None, None), + ResponseDispatchError::MissingCompleted => ("missing_completed", None, None, None), + ResponseDispatchError::EmptyUpstreamResponse => { + ("empty_upstream_response", None, None, None) + } + ResponseDispatchError::Failed(failure) => ( + "response_failed", + None, + Some(sse_failure_error_body(failure)), + None, + ), + }; + + object.insert( + "failureClass".to_string(), + Value::String(failure_class.to_string()), + ); + if let Some(count) = exhausted_count { + object.insert("exhaustedCount".to_string(), json!(count)); + } + if let Some(error) = upstream_error { + object.insert("upstreamError".to_string(), Value::String(error)); + } + if let Some(status) = upstream_status { + object.insert("upstreamStatus".to_string(), json!(status)); + } +} diff --git a/backend/src/proxy/dispatch/responses/event_recording.rs b/backend/src/proxy/dispatch/responses/event_recording.rs new file mode 100644 index 000000000..811c3dac3 --- /dev/null +++ b/backend/src/proxy/dispatch/responses/event_recording.rs @@ -0,0 +1,371 @@ +use std::time::Instant; + +use serde_json::{json, Value}; + +use crate::{ + admin::monitoring::{ + usage_record_model::{ResponseUsageRecord, UsageRecord, UsageRecordLevel}, + usage_record_service::AdminUsageRecordService, + }, + infra::time::elapsed_millis_i64, + proxy::dispatch::{ + errors::{backend_transport_name, upstream_error_http_status}, + 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, + }, + }, + upstream::{ + protocol::responses::{CodexResponsesRequest, ResponsesSseFailure}, + transport::{CodexBackendTransport, CodexClientError, WebSocketPoolDecision}, + }, +}; + +use super::{ + errors::{ + dispatch_error_metadata, enrich_response_dispatch_error_metadata, ResponseDispatchError, + }, + sse_failure::{status_code_for_stream_failure, stream_failure_metadata}, + stream_lifecycle::{latest_response_id, LiveResponseStreamContext}, +}; + +pub(super) struct ResponseUpstreamErrorEventRecord<'a> { + pub(super) usage_records: &'a AdminUsageRecordService, + pub(super) request_id: &'a str, + pub(super) account_id: &'a str, + pub(super) account_email: Option<&'a str>, + pub(super) route: &'a str, + pub(super) model: &'a str, + pub(super) started_at: Instant, + pub(super) stream: bool, + pub(super) transport: CodexBackendTransport, + pub(super) error: &'a CodexClientError, +} + +pub(super) struct ResponseStreamFailureEventRecord<'a> { + pub(super) usage_records: &'a AdminUsageRecordService, + pub(super) request_id: &'a str, + pub(super) account_id: &'a str, + pub(super) route: &'a str, + pub(super) model: &'a str, + pub(super) requested_model: &'a str, + pub(super) started_at: Instant, + pub(super) transport: CodexBackendTransport, + pub(super) request: &'a CodexResponsesRequest, + pub(super) failure: &'a ResponsesSseFailure, + pub(super) rate_limit_headers: &'a [(String, String)], + pub(super) prefetched: &'a [u8], +} + +pub(super) struct ResponseDispatchErrorEventRecord<'a> { + pub(super) usage_records: &'a AdminUsageRecordService, + pub(super) request_id: &'a str, + pub(super) account_id: Option<&'a str>, + pub(super) route: &'a str, + pub(super) model: &'a str, + pub(super) started_at: Instant, + pub(super) stream: bool, + pub(super) compact: bool, + pub(super) transport: Option<&'a str>, + pub(super) error: &'a ResponseDispatchError, +} + +pub(super) struct ResponseDispatchErrorDetails<'a> { + pub(super) account_id: Option<&'a str>, + pub(super) stream: bool, + pub(super) compact: bool, + pub(super) transport: Option<&'a str>, +} + +pub(super) async fn record_response_dispatch_error_event( + record: ResponseDispatchErrorEventRecord<'_>, +) { + let mut metadata = dispatch_error_metadata( + record.error, + record.stream, + record.compact, + record.transport, + ); + enrich_response_dispatch_error_metadata(&mut metadata, record.error); + record_dispatch_error_event(DispatchErrorUsageRecord { + usage_records: record.usage_records, + request_id: record.request_id, + account_id: record.account_id, + route: record.route, + model: record.model, + started_at: record.started_at, + status_code: i64::from(record.error.http_status_code()), + message: "v1 responses dispatch failed", + metadata, + }) + .await; +} + +pub(super) async fn record_response_upstream_error_event( + record: ResponseUpstreamErrorEventRecord<'_>, +) { + let mut metadata = dispatch_error_metadata( + record.error, + record.stream, + false, + 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", + ); + 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(i64::from(upstream_error_http_status(record.error))); + event.latency_ms = Some(elapsed_millis_i64(record.started_at)); + if let Some(object) = metadata.as_object_mut() { + if let Some(account_email) = record + .account_email + .map(str::trim) + .filter(|value| !value.is_empty()) + { + object.insert( + "accountEmail".to_string(), + Value::String(account_email.to_string()), + ); + } + } + event.metadata = metadata; + if let Err(error) = record.usage_records.record(event).await { + tracing::warn!(account_id = %record.account_id, error = %error, "failed to record upstream error event"); + } +} + +pub(super) async fn record_prefetched_response_stream_failure_event( + record: ResponseStreamFailureEventRecord<'_>, +) { + let mut metadata = stream_failure_metadata(record.failure, None); + if let Some(object) = metadata.as_object_mut() { + if record.transport == CodexBackendTransport::WebSocket { + object.insert( + "transport".to_string(), + Value::String("websocket".to_string()), + ); + } + object.insert("requestBody".to_string(), json!(record.request)); + object.insert( + "responseBody".to_string(), + Value::String(String::from_utf8_lossy(record.prefetched).to_string()), + ); + } + 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.as_deref(), + started_at: record.started_at, + status_code: status_code_for_stream_failure(record.failure), + level: UsageRecordLevel::Error, + message: "v1 responses stream failed", + metadata, + rate_limit_headers: record.rate_limit_headers, + }) + .await; +} + +fn ensure_stream_metadata_flag(metadata: &mut Value) { + let Some(object) = metadata.as_object_mut() else { + *metadata = serde_json::json!({ "stream": true }); + return; + }; + object + .entry("stream".to_string()) + .or_insert(Value::Bool(true)); +} + +fn enrich_live_response_stream_metadata( + context: &LiveResponseStreamContext, + rate_limit_headers: &[(String, String)], + metadata: &mut Value, + body: &str, +) { + let Some(object) = metadata.as_object_mut() else { + return; + }; + object + .entry("transport".to_string()) + .or_insert_with(|| Value::String(backend_transport_name(context.transport).to_string())); + if !rate_limit_headers.is_empty() { + object + .entry("rateLimitHeaders".to_string()) + .or_insert_with(|| serde_json::json!(rate_limit_headers)); + } + if let Some(decision) = context.websocket_pool_decision { + object + .entry("websocketPool".to_string()) + .or_insert_with(|| decision.metadata_value()); + } + object + .entry("requestBody".to_string()) + .or_insert_with(|| serde_json::json!(context.request)); + object + .entry("responseBody".to_string()) + .or_insert_with(|| Value::String(body.to_string())); +} + +pub(super) async fn record_live_response_stream_event( + context: &LiveResponseStreamContext, + status_code: i64, + level: UsageRecordLevel, + message: &str, + mut metadata: Value, + rate_limit_headers: &[(String, String)], + body: &str, +) { + ensure_stream_metadata_flag(&mut metadata); + enrich_event_route_metadata(&mut metadata, &context.route); + enrich_live_response_stream_metadata(context, rate_limit_headers, &mut metadata, 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), + &context.display_model, + context.client_ip.as_deref(), + context.request.client_user_agent.as_deref(), + reasoning_effort_from_request(&context.request), + context.request.service_tier.as_deref(), + ); + 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"); + } +} + +fn log_live_response_stream_finalized( + context: &LiveResponseStreamContext, + status_code: i64, + level: UsageRecordLevel, + message: &str, + metadata: &Value, + body: &str, +) { + let response_id = metadata_string_field(metadata, "responseId") + .map(ToString::to_string) + .or_else(|| latest_response_id(body)); + let first_token_ms = metadata.get("firstTokenMs").and_then(Value::as_i64); + let websocket_pool_kind = context + .websocket_pool_decision + .map(WebSocketPoolDecision::kind); + let websocket_pool_reason = context + .websocket_pool_decision + .and_then(WebSocketPoolDecision::reason); + let completed = metadata.get("completed").and_then(Value::as_bool); + let failed = metadata.get("failed").and_then(Value::as_bool); + let upstream_code = metadata_string_field(metadata, "upstreamCode"); + let failure_class = metadata_string_field(metadata, "failureClass"); + let failure_source = metadata_string_field(metadata, "failureSource"); + let failure_detail = metadata_string_field(metadata, "failureDetail"); + + macro_rules! emit_stream_finalized_log { + ($level:expr) => { + tracing::event!( + $level, + account_id = %context.account_id, + request_id = %context.request_id, + route = %context.route, + model = %context.display_model, + status_code, + usage_level = ?level, + event_message = %message, + transport = %backend_transport_name(context.transport), + websocket_pool_kind = ?websocket_pool_kind, + websocket_pool_reason = ?websocket_pool_reason, + response_id = response_id.as_deref().unwrap_or(""), + first_token_ms = ?first_token_ms, + latency_ms = elapsed_millis_i64(context.started_at), + completed = ?completed, + failed = ?failed, + upstream_code = ?upstream_code, + failure_class = ?failure_class, + failure_source = ?failure_source, + failure_detail = ?failure_detail, + "live response stream finalized" + ); + }; + } + + match level { + UsageRecordLevel::Debug => { + emit_stream_finalized_log!(tracing::Level::DEBUG); + } + UsageRecordLevel::Info => { + emit_stream_finalized_log!(tracing::Level::INFO); + } + UsageRecordLevel::Warn => { + emit_stream_finalized_log!(tracing::Level::WARN); + } + UsageRecordLevel::Error => { + emit_stream_finalized_log!(tracing::Level::ERROR); + } + } +} + +fn metadata_string_field<'a>(metadata: &'a Value, field: &str) -> Option<&'a str> { + metadata.get(field).and_then(Value::as_str) +} + +pub(super) async fn live_response_rate_limit_headers( + context: &LiveResponseStreamContext, +) -> Vec<(String, String)> { + let mut headers = context.rate_limit_headers.clone(); + if let Some(updates) = &context.rate_limit_header_updates { + headers.extend(updates.lock().await.iter().cloned()); + } + headers +} + +pub(super) async fn live_response_turn_state( + context: &LiveResponseStreamContext, +) -> Option { + if let Some(update) = &context.turn_state_update { + return update.lock().await.clone(); + } + context.turn_state.clone() +} + +pub(super) fn insert_first_token_ms(metadata: &mut Value, first_token_ms: Option) { + let Some(first_token_ms) = first_token_ms else { + return; + }; + if let Some(object) = metadata.as_object_mut() { + object.insert( + "firstTokenMs".to_string(), + Value::Number(first_token_ms.into()), + ); + } +} + +pub(super) fn insert_websocket_pool_decision( + metadata: &mut Value, + decision: Option, +) { + let Some(decision) = decision else { + return; + }; + if let Some(object) = metadata.as_object_mut() { + object.insert("websocketPool".to_string(), decision.metadata_value()); + } +} diff --git a/backend/src/proxy/dispatch/responses/live_stream.rs b/backend/src/proxy/dispatch/responses/live_stream.rs index fa0c4c78e..deb3d9e16 100644 --- a/backend/src/proxy/dispatch/responses/live_stream.rs +++ b/backend/src/proxy/dispatch/responses/live_stream.rs @@ -10,8 +10,12 @@ use tokio::sync::{mpsc, oneshot}; use crate::{ proxy::dispatch::responses::{ - finalize_live_response_stream, latest_response_id, premature_close_failed_event, - LiveResponseStreamContext, ResponseDispatchStream, ResponseDispatchStreamError, + errors::ResponseDispatchStreamError, + service::ResponseDispatchStream, + stream_lifecycle::{ + finalize_live_response_stream, latest_response_id, premature_close_failed_event, + LiveResponseStreamContext, + }, }, upstream::{ protocol::{ diff --git a/backend/src/proxy/dispatch/responses/mod.rs b/backend/src/proxy/dispatch/responses/mod.rs new file mode 100644 index 000000000..907a8989e --- /dev/null +++ b/backend/src/proxy/dispatch/responses/mod.rs @@ -0,0 +1,10 @@ +//! Responses 调度领域。 + +mod affinity; +pub(crate) mod errors; +mod event_recording; +mod live_stream; +mod prefetch; +pub(crate) mod service; +mod sse_failure; +mod stream_lifecycle; diff --git a/backend/src/proxy/dispatch/responses/prefetch.rs b/backend/src/proxy/dispatch/responses/prefetch.rs new file mode 100644 index 000000000..d102c3b24 --- /dev/null +++ b/backend/src/proxy/dispatch/responses/prefetch.rs @@ -0,0 +1,36 @@ +use axum::body::Bytes; +use futures::StreamExt; + +use crate::upstream::{ + protocol::sse::{sse_frame_end, SseError}, + transport::CodexBackendSseStream, +}; + +use super::errors::ResponseDispatchError; + +const MAX_STREAM_PREFETCH_BYTES: usize = 64 * 1024; + +pub(super) async fn prefetch_first_sse_chunk( + mut body: CodexBackendSseStream, +) -> Result<(Bytes, CodexBackendSseStream), ResponseDispatchError> { + let mut prefetched = Vec::new(); + while sse_frame_end(&prefetched).is_none() { + let Some(next) = body.next().await else { + if prefetched.is_empty() { + return Err(ResponseDispatchError::EmptyUpstreamResponse); + } + return Err(ResponseDispatchError::MissingCompleted); + }; + let chunk = next.map_err(ResponseDispatchError::Upstream)?; + prefetched.extend_from_slice(&chunk); + if prefetched.len() > MAX_STREAM_PREFETCH_BYTES { + return Err(ResponseDispatchError::InvalidSse( + SseError::BufferExceeded { + max_bytes: MAX_STREAM_PREFETCH_BYTES, + }, + )); + } + } + + Ok((Bytes::from(prefetched), body)) +} diff --git a/backend/src/proxy/dispatch/responses.rs b/backend/src/proxy/dispatch/responses/service.rs similarity index 73% rename from backend/src/proxy/dispatch/responses.rs rename to backend/src/proxy/dispatch/responses/service.rs index 62a75a061..c1a3b4586 100644 --- a/backend/src/proxy/dispatch/responses.rs +++ b/backend/src/proxy/dispatch/responses/service.rs @@ -11,18 +11,15 @@ use std::{pin::Pin, sync::Arc, time::Instant}; use axum::body::Bytes; use chrono::{DateTime, Duration, Utc}; -use futures::{stream::Stream, StreamExt}; +use futures::stream::Stream; use serde_json::{json, Value}; -use thiserror::Error; use tokio::sync::Mutex; -use tracing; use crate::{ admin::monitoring::{ - usage_record_model::{ResponseUsageRecord, UsageRecord, UsageRecordLevel}, + usage_record_model::{ResponseUsageRecord, UsageRecordLevel}, usage_record_service::AdminUsageRecordService, }, - infra::time::elapsed_millis_i64, proxy::dispatch::{ auth_recovery::trigger_refresh_after_auth_failure, cloudflare::{ @@ -50,10 +47,8 @@ use crate::{ QUOTA_VERIFY_LIMIT_REACHED_MESSAGE, }, usage_events::{ - enrich_event_route_metadata, enrich_usage_record_identity, - event_kind as response_event_kind, reasoning_effort_from_compact_request, - reasoning_effort_from_request, record_dispatch_error_event, record_response_event, - DispatchErrorUsageRecord, + reasoning_effort_from_compact_request, reasoning_effort_from_request, + record_response_event, }, }, upstream::accounts::{ @@ -62,40 +57,44 @@ use crate::{ token_refresh::RuntimeTokenRefreshService, }, upstream::{ - models::ModelCatalog, + models::{catalog::ModelCatalog, service::ModelService}, protocol::{ - events::{extract_sse_usage, extract_usage, TokenUsage}, + events::{extract_usage, TokenUsage}, responses::{ - apply_response_model_options, completed_response_metadata, response_from_codex_sse, - CodexCompactRequest, CodexResponsesRequest, CollectedResponse, ResponsesSseFailure, + apply_response_model_options, response_from_codex_sse, CodexCompactRequest, + CodexResponsesRequest, CollectedResponse, }, - sse::{parse_sse_events, sse_frame_end, SseError}, }, token_client::OpenAiTokenClient, transport::{ backend_transport_for_response_request, is_banned_upstream_error, CodexBackendClient, - CodexBackendResponse, CodexBackendSseStream, CodexBackendTransport, CodexClientError, - CodexRateLimitHeaderUpdates, CodexTurnStateUpdate, WebSocketPoolDecision, + CodexBackendResponse, }, }, }; -use super::implicit_resume::{ +use crate::proxy::dispatch::implicit_resume::{ continuation_input_start, implicit_resume_allowed, ImplicitResumeSnapshot, }; -use crate::proxy::openai::responses::response_failed_sse_event_with_id; - -mod live_stream; -use live_stream::spawn_live_response_stream; -mod sse_failure; -use sse_failure::{ - auth_sse_failure_account_status, client_error_invalid_reasoning_replay, first_sse_failure, - is_auth_sse_failure, is_history_recovery_sse_failure, is_model_unsupported_sse_failure, - is_quota_exhausted_sse_failure, sse_failure_error_body, sse_failure_invalid_reasoning_replay, - status_code_for_stream_failure, stream_failure_http_status, stream_failure_metadata, - stream_failure_source, synthetic_stream_disconnected_detail, STREAM_DISCONNECTED_CODE, - STREAM_DISCONNECTED_MESSAGE, +use super::{ + affinity::{evict_reasoning_replay, record_response_affinity}, + errors::{ResponseDispatchError, ResponseDispatchStreamError}, + event_recording::{ + insert_websocket_pool_decision, record_prefetched_response_stream_failure_event, + record_response_dispatch_error_event, record_response_upstream_error_event, + ResponseDispatchErrorDetails, ResponseDispatchErrorEventRecord, + ResponseStreamFailureEventRecord, ResponseUpstreamErrorEventRecord, + }, + live_stream::spawn_live_response_stream, + prefetch::prefetch_first_sse_chunk, + sse_failure::{ + auth_sse_failure_account_status, client_error_invalid_reasoning_replay, first_sse_failure, + is_auth_sse_failure, is_history_recovery_sse_failure, is_model_unsupported_sse_failure, + is_quota_exhausted_sse_failure, sse_failure_error_body, + sse_failure_invalid_reasoning_replay, stream_failure_http_status, + }, + stream_lifecycle::LiveResponseStreamContext, }; #[derive(Clone, Copy)] @@ -114,7 +113,7 @@ enum ExhaustedAccountClass { #[derive(Clone)] pub struct ResponseDispatchService { account_pool: Arc, - models: Arc, + models: Arc, codex: Arc, session_affinity: Arc, reasoning_replay: Arc>, @@ -126,7 +125,7 @@ pub struct ResponseDispatchService { pub(crate) struct ResponseDispatchServiceParts { pub account_pool: Arc, - pub models: Arc, + pub models: Arc, pub codex: Arc, pub session_affinity: Arc, pub usage_records: Arc, @@ -1951,886 +1950,3 @@ fn strip_request_history(request: &mut CodexResponsesRequest) { request.previous_response_id = None; request.turn_state = None; } - -const MAX_STREAM_PREFETCH_BYTES: usize = 64 * 1024; - -async fn prefetch_first_sse_chunk( - mut body: CodexBackendSseStream, -) -> Result<(Bytes, CodexBackendSseStream), ResponseDispatchError> { - let mut prefetched = Vec::new(); - while sse_frame_end(&prefetched).is_none() { - let Some(next) = body.next().await else { - if prefetched.is_empty() { - return Err(ResponseDispatchError::EmptyUpstreamResponse); - } - return Err(ResponseDispatchError::MissingCompleted); - }; - let chunk = next.map_err(ResponseDispatchError::Upstream)?; - prefetched.extend_from_slice(&chunk); - if prefetched.len() > MAX_STREAM_PREFETCH_BYTES { - return Err(ResponseDispatchError::InvalidSse( - SseError::BufferExceeded { - max_bytes: MAX_STREAM_PREFETCH_BYTES, - }, - )); - } - } - - Ok((Bytes::from(prefetched), body)) -} - -struct LiveResponseStreamContext { - account_pool: Arc, - session_affinity: Arc, - reasoning_replay: Arc>, - usage_records: Arc, - cloudflare: CloudflareRecovery, - account_id: String, - account_plan_type: Option, - request_id: String, - route: String, - model: String, - display_model: String, - requested_model: String, - client_ip: Option, - request: CodexResponsesRequest, - tuple_schema: Option, - transport: CodexBackendTransport, - rate_limit_headers: Vec<(String, String)>, - rate_limit_header_updates: Option, - turn_state_update: Option, - websocket_pool_decision: Option, - turn_state: Option, - started_at: Instant, -} - -fn latest_response_id(body: &str) -> Option { - parse_sse_events(body).ok().and_then(|events| { - events.iter().rev().find_map(|event| { - serde_json::from_str::(&event.data) - .ok() - .and_then(|data| { - data.pointer("/response/id") - .and_then(Value::as_str) - .filter(|id| !id.trim().is_empty()) - .map(ToString::to_string) - }) - }) - }) -} - -fn premature_close_failed_event(response_id: Option<&str>, detail: Option<&str>) -> String { - let message = match detail.filter(|value| !value.trim().is_empty()) { - Some(detail) => format!("{STREAM_DISCONNECTED_MESSAGE}: {detail}"), - None => STREAM_DISCONNECTED_MESSAGE.to_string(), - }; - response_failed_sse_event_with_id( - response_id, - "server_error", - STREAM_DISCONNECTED_CODE, - &message, - ) -} - -async fn finalize_live_response_stream( - context: LiveResponseStreamContext, - body: String, - first_token_ms: Option, -) { - let rate_limit_headers = live_response_rate_limit_headers(&context).await; - context - .account_pool - .sync_passive_rate_limit_headers_for_account( - &context.account_id, - context.account_plan_type.as_deref(), - &rate_limit_headers, - ) - .await; - let turn_state = live_response_turn_state(&context).await; - let usage = match extract_sse_usage(&body) { - Ok(Some(usage)) => { - context - .account_pool - .record_token_usage(&context.account_id, &context.model, &usage) - .await; - Some(usage) - } - Ok(None) => None, - Err(error) => { - tracing::warn!(account_id = %context.account_id, error = %error, "failed to extract streaming token usage"); - None - } - }; - - match response_from_codex_sse(&body, context.tuple_schema.as_ref()) { - Ok(CollectedResponse::Completed(completed)) => { - context - .cloudflare - .reset_account_recovery(&context.account_id) - .await; - let response_id = completed.get("id").and_then(Value::as_str); - record_response_affinity( - &context.session_affinity, - &context.reasoning_replay, - &context.request, - &context.account_id, - &body, - turn_state, - usage, - ) - .await; - record_live_response_stream_event( - &context, - 200, - UsageRecordLevel::Info, - "v1 responses stream completed", - serde_json::json!({ - "stream": true, - "completed": true, - "responseId": response_id, - "firstTokenMs": first_token_ms, - "usage": usage, - }), - &rate_limit_headers, - &body, - ) - .await; - } - Ok(CollectedResponse::Failed(failure)) => { - if sse_failure_invalid_reasoning_replay(&failure) { - evict_reasoning_replay( - &context.reasoning_replay, - &context.request, - &context.account_id, - ) - .await; - } - let response_id = latest_response_id(&body); - let latency_ms = elapsed_millis_i64(context.started_at); - let failure_source = stream_failure_source(&failure); - let failure_detail = synthetic_stream_disconnected_detail(&failure); - let websocket_pool_kind = context - .websocket_pool_decision - .map(|decision| decision.kind()); - let websocket_pool_reason = context - .websocket_pool_decision - .and_then(|decision| decision.reason()); - tracing::warn!( - account_id = %context.account_id, - request_id = %context.request_id, - response_id = response_id.as_deref().unwrap_or(""), - transport = %backend_transport_name(context.transport), - websocket_pool_kind = ?websocket_pool_kind, - websocket_pool_reason = ?websocket_pool_reason, - first_token_ms = ?first_token_ms, - latency_ms, - event = %failure.event, - code = ?failure.upstream_code.as_deref(), - failure_source = %failure_source, - failure_detail = ?failure_detail.as_deref(), - "live upstream stream ended with response.failed" - ); - let mut metadata = stream_failure_metadata(&failure, usage); - insert_first_token_ms(&mut metadata, first_token_ms); - record_live_response_stream_event( - &context, - status_code_for_stream_failure(&failure), - UsageRecordLevel::Error, - "v1 responses stream failed", - metadata, - &rate_limit_headers, - &body, - ) - .await; - } - Ok(CollectedResponse::MissingCompleted | CollectedResponse::Empty) => { - tracing::warn!( - account_id = %context.account_id, - "live upstream stream ended without response.completed" - ); - let mut metadata = serde_json::json!({ - "stream": true, - "failed": true, - "upstreamCode": "missing_completed", - "usage": usage, - }); - insert_first_token_ms(&mut metadata, first_token_ms); - record_live_response_stream_event( - &context, - 502, - UsageRecordLevel::Error, - "v1 responses stream ended without response.completed", - metadata, - &rate_limit_headers, - &body, - ) - .await; - } - Err(error) => { - tracing::warn!(account_id = %context.account_id, error = %error, "failed to parse completed live stream"); - let mut metadata = serde_json::json!({ - "stream": true, - "sseParseError": error.to_string(), - "usage": usage, - }); - insert_first_token_ms(&mut metadata, first_token_ms); - record_live_response_stream_event( - &context, - 502, - UsageRecordLevel::Warn, - "v1 responses stream SSE response invalid", - metadata, - &rate_limit_headers, - &body, - ) - .await; - } - } - - context.account_pool.release(&context.account_id).await; -} - -// ==================================================================== -// Event recording helpers -// ==================================================================== - -struct ResponseUpstreamErrorEventRecord<'a> { - usage_records: &'a AdminUsageRecordService, - request_id: &'a str, - account_id: &'a str, - account_email: Option<&'a str>, - route: &'a str, - model: &'a str, - started_at: Instant, - stream: bool, - transport: CodexBackendTransport, - error: &'a CodexClientError, -} - -struct ResponseStreamFailureEventRecord<'a> { - usage_records: &'a AdminUsageRecordService, - request_id: &'a str, - account_id: &'a str, - route: &'a str, - model: &'a str, - requested_model: &'a str, - started_at: Instant, - transport: CodexBackendTransport, - request: &'a CodexResponsesRequest, - failure: &'a ResponsesSseFailure, - rate_limit_headers: &'a [(String, String)], - prefetched: &'a [u8], -} - -struct ResponseDispatchErrorEventRecord<'a> { - usage_records: &'a AdminUsageRecordService, - request_id: &'a str, - account_id: Option<&'a str>, - route: &'a str, - model: &'a str, - started_at: Instant, - stream: bool, - compact: bool, - transport: Option<&'a str>, - error: &'a ResponseDispatchError, -} - -struct ResponseDispatchErrorDetails<'a> { - account_id: Option<&'a str>, - stream: bool, - compact: bool, - transport: Option<&'a str>, -} - -async fn record_response_dispatch_error_event(record: ResponseDispatchErrorEventRecord<'_>) { - let mut metadata = dispatch_error_metadata( - record.error, - record.stream, - record.compact, - record.transport, - ); - enrich_response_dispatch_error_metadata(&mut metadata, record.error); - record_dispatch_error_event(DispatchErrorUsageRecord { - usage_records: record.usage_records, - request_id: record.request_id, - account_id: record.account_id, - route: record.route, - model: record.model, - started_at: record.started_at, - status_code: i64::from(record.error.http_status_code()), - message: "v1 responses dispatch failed", - metadata, - }) - .await; -} - -async fn record_response_upstream_error_event(record: ResponseUpstreamErrorEventRecord<'_>) { - let mut metadata = dispatch_error_metadata( - record.error, - record.stream, - false, - 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", - ); - 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(i64::from(upstream_error_http_status(record.error))); - event.latency_ms = Some(elapsed_millis_i64(record.started_at)); - if let Some(object) = metadata.as_object_mut() { - if let Some(account_email) = record - .account_email - .map(str::trim) - .filter(|value| !value.is_empty()) - { - object.insert( - "accountEmail".to_string(), - Value::String(account_email.to_string()), - ); - } - } - event.metadata = metadata; - if let Err(error) = record.usage_records.record(event).await { - tracing::warn!(account_id = %record.account_id, error = %error, "failed to record upstream error event"); - } -} - -async fn record_prefetched_response_stream_failure_event( - record: ResponseStreamFailureEventRecord<'_>, -) { - let mut metadata = stream_failure_metadata(record.failure, None); - if let Some(object) = metadata.as_object_mut() { - if record.transport == CodexBackendTransport::WebSocket { - object.insert( - "transport".to_string(), - Value::String("websocket".to_string()), - ); - } - object.insert("requestBody".to_string(), json!(record.request)); - object.insert( - "responseBody".to_string(), - Value::String(String::from_utf8_lossy(record.prefetched).to_string()), - ); - } - 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.as_deref(), - started_at: record.started_at, - status_code: status_code_for_stream_failure(record.failure), - level: UsageRecordLevel::Error, - message: "v1 responses stream failed", - metadata, - rate_limit_headers: record.rate_limit_headers, - }) - .await; -} - -fn ensure_stream_metadata_flag(metadata: &mut Value) { - let Some(object) = metadata.as_object_mut() else { - *metadata = serde_json::json!({ "stream": true }); - return; - }; - object - .entry("stream".to_string()) - .or_insert(Value::Bool(true)); -} - -fn enrich_live_response_stream_metadata( - context: &LiveResponseStreamContext, - rate_limit_headers: &[(String, String)], - metadata: &mut Value, - body: &str, -) { - let Some(object) = metadata.as_object_mut() else { - return; - }; - object - .entry("transport".to_string()) - .or_insert_with(|| Value::String(backend_transport_name(context.transport).to_string())); - if !rate_limit_headers.is_empty() { - object - .entry("rateLimitHeaders".to_string()) - .or_insert_with(|| serde_json::json!(rate_limit_headers)); - } - if let Some(decision) = context.websocket_pool_decision { - object - .entry("websocketPool".to_string()) - .or_insert_with(|| decision.metadata_value()); - } - object - .entry("requestBody".to_string()) - .or_insert_with(|| serde_json::json!(context.request)); - object - .entry("responseBody".to_string()) - .or_insert_with(|| Value::String(body.to_string())); -} - -async fn record_live_response_stream_event( - context: &LiveResponseStreamContext, - status_code: i64, - level: UsageRecordLevel, - message: &str, - mut metadata: Value, - rate_limit_headers: &[(String, String)], - body: &str, -) { - ensure_stream_metadata_flag(&mut metadata); - enrich_event_route_metadata(&mut metadata, &context.route); - enrich_live_response_stream_metadata(context, rate_limit_headers, &mut metadata, 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), - &context.display_model, - context.client_ip.as_deref(), - context.request.client_user_agent.as_deref(), - reasoning_effort_from_request(&context.request), - context.request.service_tier.as_deref(), - ); - 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"); - } -} - -fn log_live_response_stream_finalized( - context: &LiveResponseStreamContext, - status_code: i64, - level: UsageRecordLevel, - message: &str, - metadata: &Value, - body: &str, -) { - let response_id = metadata_string_field(metadata, "responseId") - .map(ToString::to_string) - .or_else(|| latest_response_id(body)); - let first_token_ms = metadata.get("firstTokenMs").and_then(Value::as_i64); - let websocket_pool_kind = context - .websocket_pool_decision - .map(WebSocketPoolDecision::kind); - let websocket_pool_reason = context - .websocket_pool_decision - .and_then(WebSocketPoolDecision::reason); - let completed = metadata.get("completed").and_then(Value::as_bool); - let failed = metadata.get("failed").and_then(Value::as_bool); - let upstream_code = metadata_string_field(metadata, "upstreamCode"); - let failure_class = metadata_string_field(metadata, "failureClass"); - let failure_source = metadata_string_field(metadata, "failureSource"); - let failure_detail = metadata_string_field(metadata, "failureDetail"); - - macro_rules! emit_stream_finalized_log { - ($level:expr) => { - tracing::event!( - $level, - account_id = %context.account_id, - request_id = %context.request_id, - route = %context.route, - model = %context.display_model, - status_code, - usage_level = ?level, - event_message = %message, - transport = %backend_transport_name(context.transport), - websocket_pool_kind = ?websocket_pool_kind, - websocket_pool_reason = ?websocket_pool_reason, - response_id = response_id.as_deref().unwrap_or(""), - first_token_ms = ?first_token_ms, - latency_ms = elapsed_millis_i64(context.started_at), - completed = ?completed, - failed = ?failed, - upstream_code = ?upstream_code, - failure_class = ?failure_class, - failure_source = ?failure_source, - failure_detail = ?failure_detail, - "live response stream finalized" - ); - }; - } - - match level { - UsageRecordLevel::Debug => { - emit_stream_finalized_log!(tracing::Level::DEBUG); - } - UsageRecordLevel::Info => { - emit_stream_finalized_log!(tracing::Level::INFO); - } - UsageRecordLevel::Warn => { - emit_stream_finalized_log!(tracing::Level::WARN); - } - UsageRecordLevel::Error => { - emit_stream_finalized_log!(tracing::Level::ERROR); - } - } -} - -fn metadata_string_field<'a>(metadata: &'a Value, field: &str) -> Option<&'a str> { - metadata.get(field).and_then(Value::as_str) -} - -async fn live_response_rate_limit_headers( - context: &LiveResponseStreamContext, -) -> Vec<(String, String)> { - let mut headers = context.rate_limit_headers.clone(); - if let Some(updates) = &context.rate_limit_header_updates { - headers.extend(updates.lock().await.iter().cloned()); - } - headers -} - -async fn live_response_turn_state(context: &LiveResponseStreamContext) -> Option { - if let Some(update) = &context.turn_state_update { - return update.lock().await.clone(); - } - context.turn_state.clone() -} - -fn insert_first_token_ms(metadata: &mut Value, first_token_ms: Option) { - let Some(first_token_ms) = first_token_ms else { - return; - }; - if let Some(object) = metadata.as_object_mut() { - object.insert( - "firstTokenMs".to_string(), - Value::Number(first_token_ms.into()), - ); - } -} - -fn insert_websocket_pool_decision(metadata: &mut Value, decision: Option) { - let Some(decision) = decision else { - return; - }; - if let Some(object) = metadata.as_object_mut() { - object.insert("websocketPool".to_string(), decision.metadata_value()); - } -} - -// ==================================================================== -// Affinity + replay recording -// ==================================================================== - -async fn record_response_affinity( - session_affinity: &Arc, - reasoning_replay: &Arc>, - request: &CodexResponsesRequest, - account_id: &str, - body: &str, - turn_state: Option, - usage: Option, -) { - let Some(conversation_id) = request - .prompt_cache_key - .as_deref() - .map(str::trim) - .filter(|value| !value.is_empty()) - else { - return; - }; - let metadata = match completed_response_metadata(body) { - Ok(Some(metadata)) => metadata, - Ok(None) => return, - Err(error) => { - tracing::warn!( - error = %error, - "failed to parse completed response metadata for session affinity" - ); - return; - } - }; - - let variant_hash = compute_variant_hash(request); - let entry = crate::proxy::dispatch::session_affinity::SessionAffinityEntry { - account_id: account_id.to_string(), - conversation_id: conversation_id.to_string(), - turn_state: turn_state - .filter(|value| !value.trim().is_empty()) - .or_else(|| request.turn_state.clone()), - instructions_hash: Some(hash_instructions(Some(&request.instructions))), - input_tokens: usage.map(|usage| usage.input_tokens), - function_call_ids: metadata.function_call_ids, - variant_hash: Some(variant_hash.clone()), - created_at: Utc::now(), - }; - if let Err(error) = session_affinity - .record(metadata.response_id.clone(), entry) - .await - { - tracing::warn!( - error = %error, - response_id = %metadata.response_id, - account_id = %account_id, - "failed to record session affinity" - ); - } - - reasoning_replay.lock().await.record( - metadata.response_id, - account_id, - conversation_id, - &variant_hash, - &metadata.replay_items, - Utc::now(), - ); -} - -async fn evict_reasoning_replay( - reasoning_replay: &Arc>, - request: &CodexResponsesRequest, - account_id: &str, -) { - let variant_hash = compute_variant_hash(request); - let conversation_id = request - .prompt_cache_key - .as_deref() - .unwrap_or("") - .to_string(); - reasoning_replay.lock().await.evict_by_identity( - account_id, - &conversation_id, - &variant_hash, - Utc::now(), - ); -} - -// ==================================================================== -// ResponseDispatchError and ResponseDispatchStreamError -// ==================================================================== - -/// Responses 调度错误。 -#[derive(Debug, Error)] -pub enum ResponseDispatchError { - #[error("failed to list runtime accounts")] - AccountStore, - #[error("no active account is available")] - NoActiveAccount, - #[error("all accounts exhausted by quota")] - QuotaExhausted { - count: usize, - upstream_error: String, - }, - #[error("all accounts exhausted by rate limit")] - RateLimited { - count: usize, - upstream_error: String, - }, - #[error("all accounts exhausted by expired auth")] - Expired { - count: usize, - upstream_error: String, - }, - #[error("all accounts exhausted by disabled auth")] - Disabled { - count: usize, - upstream_error: String, - }, - #[error("all accounts exhausted by banned auth")] - Banned { - count: usize, - upstream_error: String, - status_code: u16, - }, - #[error("all accounts exhausted by Cloudflare challenge")] - CloudflareChallenge { - count: usize, - upstream_error: String, - }, - #[error("all accounts exhausted by Cloudflare path-block")] - CloudflarePathBlocked { - count: usize, - upstream_error: String, - }, - #[error("all accounts exhausted by unsupported model")] - ModelUnsupported { - count: usize, - upstream_error: String, - }, - #[error("upstream request failed: {0}")] - Upstream(#[from] CodexClientError), - #[error("invalid upstream SSE response: {0}")] - InvalidSse(#[from] SseError), - #[error("upstream response did not include response.completed")] - MissingCompleted, - #[error("upstream response did not include visible output")] - EmptyUpstreamResponse, - #[error("upstream response failed: {0:?}")] - Failed(ResponsesSseFailure), -} - -impl ResponseDispatchError { - pub fn http_status_code(&self) -> u16 { - match self { - Self::NoActiveAccount | Self::AccountStore => 503, - Self::QuotaExhausted { .. } => 429, - Self::RateLimited { .. } => 429, - Self::Expired { .. } | Self::Disabled { .. } => 401, - Self::Banned { status_code, .. } => *status_code, - Self::CloudflareChallenge { .. } - | Self::CloudflarePathBlocked { .. } - | Self::InvalidSse(_) - | Self::MissingCompleted - | Self::EmptyUpstreamResponse => 502, - Self::Failed(failure) => stream_failure_http_status(failure), - Self::ModelUnsupported { .. } => 400, - Self::Upstream(error) => upstream_error_http_status(error), - } - } -} - -/// Responses live SSE body stream error. -#[derive(Debug, Error)] -pub enum ResponseDispatchStreamError { - #[error("upstream stream failed: {0}")] - Upstream(#[from] CodexClientError), -} - -fn dispatch_error_metadata( - error: impl std::fmt::Display, - stream: bool, - compact: bool, - transport: Option<&str>, -) -> Value { - let mut metadata = serde_json::json!({ - "stream": stream, - "failed": true, - "errorKind": "dispatch", - "error": error.to_string(), - }); - let Some(object) = metadata.as_object_mut() else { - return metadata; - }; - if compact { - object.insert("compact".to_string(), Value::Bool(true)); - } - if let Some(transport) = transport { - object.insert( - "transport".to_string(), - Value::String(transport.to_string()), - ); - } - metadata -} - -fn enrich_response_dispatch_error_metadata(metadata: &mut Value, error: &ResponseDispatchError) { - let Some(object) = metadata.as_object_mut() else { - return; - }; - let (failure_class, exhausted_count, upstream_error, upstream_status) = match error { - ResponseDispatchError::AccountStore => ("account_store", None, None, None), - ResponseDispatchError::NoActiveAccount => ("no_available_accounts", None, None, None), - ResponseDispatchError::QuotaExhausted { - count, - upstream_error, - } => ( - "quota_exhausted", - Some(*count), - Some(upstream_error.clone()), - None, - ), - ResponseDispatchError::RateLimited { - count, - upstream_error, - } => ( - "rate_limited", - Some(*count), - Some(upstream_error.clone()), - None, - ), - ResponseDispatchError::Expired { - count, - upstream_error, - } => ("expired", Some(*count), Some(upstream_error.clone()), None), - ResponseDispatchError::Disabled { - count, - upstream_error, - } => ("disabled", Some(*count), Some(upstream_error.clone()), None), - ResponseDispatchError::Banned { - count, - upstream_error, - .. - } => ("banned", Some(*count), Some(upstream_error.clone()), None), - ResponseDispatchError::CloudflareChallenge { - count, - upstream_error, - } => ( - "cloudflare_challenge", - Some(*count), - Some(upstream_error.clone()), - None, - ), - ResponseDispatchError::CloudflarePathBlocked { - count, - upstream_error, - } => ( - "cloudflare_path_blocked", - Some(*count), - Some(upstream_error.clone()), - None, - ), - ResponseDispatchError::ModelUnsupported { - count, - upstream_error, - } => ( - "model_unsupported", - Some(*count), - Some(upstream_error.clone()), - None, - ), - ResponseDispatchError::Upstream(error) => { - let upstream_status = match error { - CodexClientError::Upstream { status, .. } => Some(status.as_u16()), - _ => None, - }; - ( - "upstream", - None, - Some(upstream_error_body(error)), - upstream_status, - ) - } - ResponseDispatchError::InvalidSse(_) => ("invalid_sse", None, None, None), - ResponseDispatchError::MissingCompleted => ("missing_completed", None, None, None), - ResponseDispatchError::EmptyUpstreamResponse => { - ("empty_upstream_response", None, None, None) - } - ResponseDispatchError::Failed(failure) => ( - "response_failed", - None, - Some(sse_failure_error_body(failure)), - None, - ), - }; - - object.insert( - "failureClass".to_string(), - Value::String(failure_class.to_string()), - ); - if let Some(count) = exhausted_count { - object.insert("exhaustedCount".to_string(), json!(count)); - } - if let Some(error) = upstream_error { - object.insert("upstreamError".to_string(), Value::String(error)); - } - if let Some(status) = upstream_status { - object.insert("upstreamStatus".to_string(), json!(status)); - } -} diff --git a/backend/src/proxy/dispatch/responses/stream_lifecycle.rs b/backend/src/proxy/dispatch/responses/stream_lifecycle.rs new file mode 100644 index 000000000..d70a244ef --- /dev/null +++ b/backend/src/proxy/dispatch/responses/stream_lifecycle.rs @@ -0,0 +1,258 @@ +use std::{sync::Arc, time::Instant}; + +use serde_json::Value; +use tokio::sync::Mutex; + +use crate::{ + admin::monitoring::{ + usage_record_model::UsageRecordLevel, usage_record_service::AdminUsageRecordService, + }, + infra::time::elapsed_millis_i64, + proxy::{ + dispatch::{ + errors::backend_transport_name, reasoning_replay::ReasoningReplayCache, + session_affinity::RuntimeSessionAffinityService, + }, + openai::responses::response_failed_sse_event_with_id, + }, + upstream::{ + accounts::pool::RuntimeAccountPoolService, + protocol::{ + events::extract_sse_usage, + responses::{response_from_codex_sse, CodexResponsesRequest, CollectedResponse}, + sse::parse_sse_events, + }, + transport::{ + CodexBackendTransport, CodexRateLimitHeaderUpdates, CodexTurnStateUpdate, + WebSocketPoolDecision, + }, + }, +}; + +use super::{ + affinity::{evict_reasoning_replay, record_response_affinity}, + event_recording::{ + insert_first_token_ms, live_response_rate_limit_headers, live_response_turn_state, + record_live_response_stream_event, + }, + sse_failure::{ + sse_failure_invalid_reasoning_replay, status_code_for_stream_failure, + stream_failure_metadata, stream_failure_source, synthetic_stream_disconnected_detail, + STREAM_DISCONNECTED_CODE, STREAM_DISCONNECTED_MESSAGE, + }, +}; +use crate::proxy::dispatch::cloudflare::CloudflareRecovery; + +pub(super) struct LiveResponseStreamContext { + pub(super) account_pool: Arc, + pub(super) session_affinity: Arc, + pub(super) reasoning_replay: Arc>, + pub(super) usage_records: Arc, + pub(super) cloudflare: CloudflareRecovery, + pub(super) account_id: String, + pub(super) account_plan_type: Option, + pub(super) request_id: String, + pub(super) route: String, + pub(super) model: String, + pub(super) display_model: String, + pub(super) requested_model: String, + pub(super) client_ip: Option, + pub(super) request: CodexResponsesRequest, + pub(super) tuple_schema: Option, + pub(super) transport: CodexBackendTransport, + pub(super) rate_limit_headers: Vec<(String, String)>, + pub(super) rate_limit_header_updates: Option, + pub(super) turn_state_update: Option, + pub(super) websocket_pool_decision: Option, + pub(super) turn_state: Option, + pub(super) started_at: Instant, +} + +pub(super) fn latest_response_id(body: &str) -> Option { + parse_sse_events(body).ok().and_then(|events| { + events.iter().rev().find_map(|event| { + serde_json::from_str::(&event.data) + .ok() + .and_then(|data| { + data.pointer("/response/id") + .and_then(Value::as_str) + .filter(|id| !id.trim().is_empty()) + .map(ToString::to_string) + }) + }) + }) +} + +pub(super) fn premature_close_failed_event( + response_id: Option<&str>, + detail: Option<&str>, +) -> String { + let message = match detail.filter(|value| !value.trim().is_empty()) { + Some(detail) => format!("{STREAM_DISCONNECTED_MESSAGE}: {detail}"), + None => STREAM_DISCONNECTED_MESSAGE.to_string(), + }; + response_failed_sse_event_with_id( + response_id, + "server_error", + STREAM_DISCONNECTED_CODE, + &message, + ) +} + +pub(super) async fn finalize_live_response_stream( + context: LiveResponseStreamContext, + body: String, + first_token_ms: Option, +) { + let rate_limit_headers = live_response_rate_limit_headers(&context).await; + context + .account_pool + .sync_passive_rate_limit_headers_for_account( + &context.account_id, + context.account_plan_type.as_deref(), + &rate_limit_headers, + ) + .await; + let turn_state = live_response_turn_state(&context).await; + let usage = match extract_sse_usage(&body) { + Ok(Some(usage)) => { + context + .account_pool + .record_token_usage(&context.account_id, &context.model, &usage) + .await; + Some(usage) + } + Ok(None) => None, + Err(error) => { + tracing::warn!(account_id = %context.account_id, error = %error, "failed to extract streaming token usage"); + None + } + }; + + match response_from_codex_sse(&body, context.tuple_schema.as_ref()) { + Ok(CollectedResponse::Completed(completed)) => { + context + .cloudflare + .reset_account_recovery(&context.account_id) + .await; + let response_id = completed.get("id").and_then(Value::as_str); + record_response_affinity( + &context.session_affinity, + &context.reasoning_replay, + &context.request, + &context.account_id, + &body, + turn_state, + usage, + ) + .await; + record_live_response_stream_event( + &context, + 200, + UsageRecordLevel::Info, + "v1 responses stream completed", + serde_json::json!({ + "stream": true, + "completed": true, + "responseId": response_id, + "firstTokenMs": first_token_ms, + "usage": usage, + }), + &rate_limit_headers, + &body, + ) + .await; + } + Ok(CollectedResponse::Failed(failure)) => { + if sse_failure_invalid_reasoning_replay(&failure) { + evict_reasoning_replay( + &context.reasoning_replay, + &context.request, + &context.account_id, + ) + .await; + } + let response_id = latest_response_id(&body); + let latency_ms = elapsed_millis_i64(context.started_at); + let failure_source = stream_failure_source(&failure); + let failure_detail = synthetic_stream_disconnected_detail(&failure); + let websocket_pool_kind = context + .websocket_pool_decision + .map(|decision| decision.kind()); + let websocket_pool_reason = context + .websocket_pool_decision + .and_then(|decision| decision.reason()); + tracing::warn!( + account_id = %context.account_id, + request_id = %context.request_id, + response_id = response_id.as_deref().unwrap_or(""), + transport = %backend_transport_name(context.transport), + websocket_pool_kind = ?websocket_pool_kind, + websocket_pool_reason = ?websocket_pool_reason, + first_token_ms = ?first_token_ms, + latency_ms, + event = %failure.event, + code = ?failure.upstream_code.as_deref(), + failure_source = %failure_source, + failure_detail = ?failure_detail.as_deref(), + "live upstream stream ended with response.failed" + ); + let mut metadata = stream_failure_metadata(&failure, usage); + insert_first_token_ms(&mut metadata, first_token_ms); + record_live_response_stream_event( + &context, + status_code_for_stream_failure(&failure), + UsageRecordLevel::Error, + "v1 responses stream failed", + metadata, + &rate_limit_headers, + &body, + ) + .await; + } + Ok(CollectedResponse::MissingCompleted | CollectedResponse::Empty) => { + tracing::warn!( + account_id = %context.account_id, + "live upstream stream ended without response.completed" + ); + let mut metadata = serde_json::json!({ + "stream": true, + "failed": true, + "upstreamCode": "missing_completed", + "usage": usage, + }); + insert_first_token_ms(&mut metadata, first_token_ms); + record_live_response_stream_event( + &context, + 502, + UsageRecordLevel::Error, + "v1 responses stream ended without response.completed", + metadata, + &rate_limit_headers, + &body, + ) + .await; + } + Err(error) => { + tracing::warn!(account_id = %context.account_id, error = %error, "failed to parse completed live stream"); + let mut metadata = serde_json::json!({ + "stream": true, + "sseParseError": error.to_string(), + "usage": usage, + }); + insert_first_token_ms(&mut metadata, first_token_ms); + record_live_response_stream_event( + &context, + 502, + UsageRecordLevel::Warn, + "v1 responses stream SSE response invalid", + metadata, + &rate_limit_headers, + &body, + ) + .await; + } + } + + context.account_pool.release(&context.account_id).await; +} diff --git a/backend/src/proxy/openai/chat.rs b/backend/src/proxy/openai/chat.rs index 2c4f4ef62..f05ed05b9 100644 --- a/backend/src/proxy/openai/chat.rs +++ b/backend/src/proxy/openai/chat.rs @@ -21,11 +21,11 @@ use crate::{ http::middleware::request_id::RequestId, proxy::{ auth::authorize_client_api_key, - dispatch::responses::{ResponseDispatchError, ResponseDispatchStream}, + dispatch::responses::{errors::ResponseDispatchError, service::ResponseDispatchStream}, }, runtime::state::AppState, upstream::{ - models::ModelCatalog, + models::catalog::ModelCatalog, protocol::{ responses::{apply_response_model_options, CodexResponsesRequest}, schema::{prepare_schema, reconvert_tuple_values}, diff --git a/backend/src/proxy/openai/errors.rs b/backend/src/proxy/openai/errors.rs index e6026bd65..d956834a6 100644 --- a/backend/src/proxy/openai/errors.rs +++ b/backend/src/proxy/openai/errors.rs @@ -8,7 +8,7 @@ use axum::{ use serde_json::{json, Value}; use crate::proxy::{ - dispatch::{chat::ChatDispatchError, responses::ResponseDispatchError}, + dispatch::{chat::ChatDispatchError, responses::errors::ResponseDispatchError}, openai::responses::response_failed_sse_event as encode_response_failed_sse_event, }; diff --git a/backend/src/proxy/openai/models.rs b/backend/src/proxy/openai/models.rs index ffbcb1c52..99696dbc9 100644 --- a/backend/src/proxy/openai/models.rs +++ b/backend/src/proxy/openai/models.rs @@ -8,7 +8,10 @@ use axum::{ }; use serde_json::{json, Value}; -use crate::{proxy::auth::authorize_client_api_key, runtime::state::AppState}; +use crate::{ + proxy::auth::authorize_client_api_key, runtime::state::AppState, + upstream::models::catalog::ModelCatalog, +}; use super::errors::{missing_client_api_key_response, model_not_found_response}; @@ -83,7 +86,7 @@ pub async fn model_info( (StatusCode::OK, Json(json!(info))) } -pub async fn model_catalog_for_state(state: &AppState) -> crate::upstream::models::ModelCatalog { +pub async fn model_catalog_for_state(state: &AppState) -> ModelCatalog { state.services.models.catalog().await } diff --git a/backend/src/proxy/openai/responses.rs b/backend/src/proxy/openai/responses.rs index d81b8ded2..5ddda300f 100644 --- a/backend/src/proxy/openai/responses.rs +++ b/backend/src/proxy/openai/responses.rs @@ -15,7 +15,7 @@ use crate::{ http::middleware::request_id::RequestId, proxy::{ auth::authorize_client_api_key, - dispatch::responses::{ResponseDispatchError, ResponseDispatchStream}, + dispatch::responses::{errors::ResponseDispatchError, service::ResponseDispatchStream}, }, runtime::state::AppState, upstream::protocol::{ diff --git a/backend/src/runtime/bootstrap.rs b/backend/src/runtime/bootstrap.rs index 5cac696b4..0fe56736f 100644 --- a/backend/src/runtime/bootstrap.rs +++ b/backend/src/runtime/bootstrap.rs @@ -3,8 +3,8 @@ use std::error::Error; use axum::Router; use chrono::Utc; +use crate::config::schema::AppConfig; use crate::config::settings::RuntimeSettingsService; -use crate::config::types::AppConfig; use crate::http::middleware::request_id::TrustedProxyConfig; use crate::infra::database::connect_sqlite; use crate::infra::logging::{init_tracing, LogGuard, RotationConfig}; diff --git a/backend/src/runtime/services.rs b/backend/src/runtime/services.rs index 8a2d7cbec..33c94f947 100644 --- a/backend/src/runtime/services.rs +++ b/backend/src/runtime/services.rs @@ -21,12 +21,12 @@ use crate::{ }, }, config::{ + schema::AppConfig, settings::{account_pool_options_from_config, RuntimeSettingsService}, - types::AppConfig, }, proxy::dispatch::{ chat::ChatDispatchService, - responses::{ResponseDispatchService, ResponseDispatchServiceParts}, + responses::service::{ResponseDispatchService, ResponseDispatchServiceParts}, session_affinity::{RuntimeSessionAffinityService, SqliteSessionAffinityStore}, }, upstream::accounts::{ @@ -40,7 +40,11 @@ use crate::{ }, upstream::{ fingerprint::{Fingerprint, FingerprintRepository}, - models::{ModelService, ModelServiceError, ModelSnapshotStore}, + models::{ + config::ModelConfig, + service::{ModelService, ModelServiceError}, + snapshot_store::{ModelSnapshotStore, SqliteModelSnapshotStore}, + }, token_client::{default_openai_token_client, OpenAiTokenClient, TokenClientConfig}, transport::{ build_reqwest_client, tls::CustomCaError, CodexBackendClient, CodexModelCatalogClient, @@ -219,10 +223,10 @@ impl Services { ); let upstream_client: StdArc = codex.clone(); let snapshot_store: StdArc = StdArc::new( - crate::upstream::models::SqliteModelSnapshotStore::new(stores.accounts.pool().clone()), + SqliteModelSnapshotStore::new(stores.accounts.pool().clone()), ); let models = StdArc::new(ModelService::new( - crate::upstream::models::ModelConfig { + ModelConfig { model_aliases: config.model_aliases.clone(), }, Some(snapshot_store), diff --git a/backend/src/runtime/state.rs b/backend/src/runtime/state.rs index 9cf4daca8..4389d2ea0 100644 --- a/backend/src/runtime/state.rs +++ b/backend/src/runtime/state.rs @@ -1,6 +1,6 @@ //! 运行时共享状态。 -use crate::config::types::AppConfig; +use crate::config::schema::AppConfig; use crate::runtime::services::Services; /// HTTP handler 共享的运行时状态。 @@ -13,9 +13,9 @@ pub struct AppState { /// 运行时配置镜像(从 AppConfig 衍生)。 #[derive(Debug, Clone)] pub struct RuntimeConfig { - pub admin: crate::config::types::AdminConfig, - pub auth: crate::config::types::AuthConfig, - pub quota: crate::config::types::QuotaConfig, + pub admin: crate::config::schema::AdminConfig, + pub auth: crate::config::schema::AuthConfig, + pub quota: crate::config::schema::QuotaConfig, } impl From for RuntimeConfig { diff --git a/backend/src/runtime/tasks/model_refresh.rs b/backend/src/runtime/tasks/model_refresh.rs index 4cc8d5055..758707071 100644 --- a/backend/src/runtime/tasks/model_refresh.rs +++ b/backend/src/runtime/tasks/model_refresh.rs @@ -7,7 +7,7 @@ use tokio::time::{interval, sleep}; use tracing::{info, warn}; use crate::upstream::accounts::pool::RuntimeAccountPoolService; -use crate::upstream::models::{ +use crate::upstream::models::service::{ ModelRefreshPlanAccount, ModelRefreshResult, ModelService, ModelServiceError, }; diff --git a/backend/src/upstream/accounts/store.rs b/backend/src/upstream/accounts/store/mod.rs similarity index 56% rename from backend/src/upstream/accounts/store.rs rename to backend/src/upstream/accounts/store/mod.rs index 409516f9f..526546daf 100644 --- a/backend/src/upstream/accounts/store.rs +++ b/backend/src/upstream/accounts/store/mod.rs @@ -3,552 +3,28 @@ use async_trait::async_trait; use chrono::{DateTime, Utc}; use secrecy::{ExposeSecret, SecretString}; -use serde_json::Value; -use sqlx::{sqlite::SqliteRow, QueryBuilder, Row, Sqlite, SqlitePool}; +use sqlx::{QueryBuilder, Row, Sqlite, SqlitePool}; use thiserror::Error; use crate::infra::{ - format::nonnegative_i64_to_u64, json::{decode_cursor, page_offset, NumberedPage, Page}, time::parse_optional_rfc3339_utc as parse_optional_rfc3339, }; use crate::upstream::accounts::model::{ Account, AccountModelUsageDelta, AccountStatus, AccountUsageDelta, }; -use crate::upstream::accounts::quota::{ - quota_snapshot_limit_window_seconds, quota_snapshot_reset_at, -}; use crate::upstream::accounts::window::should_reset_usage_window; -// ============================================================================ -// SQL 常量 -// ============================================================================ +mod queries; +mod rows; -const LIST_POOL_ACCOUNTS_SQL: &str = r" -select - a.id, - a.email, - a.chatgpt_account_id as account_id, - a.chatgpt_user_id as user_id, - a.label, - a.plan_type, - a.access_token, - a.refresh_token, - a.access_token_expires_at, - a.next_refresh_at, - a.status, - a.quota_limit_reached, - a.quota_verify_required, - a.quota_cooldown_until, - a.quota_json, - a.cloudflare_cooldown_until, - a.added_at, - coalesce(au.request_count, 0) as usage_request_count, - coalesce(au.empty_response_count, 0) as usage_empty_response_count, - coalesce(au.image_input_tokens, 0) as usage_image_input_tokens, - coalesce(au.image_output_tokens, 0) as usage_image_output_tokens, - coalesce(au.image_request_count, 0) as usage_image_request_count, - coalesce(au.image_request_failed_count, 0) as usage_image_request_failed_count, - coalesce(au.window_request_count, 0) as usage_window_request_count, - coalesce(au.window_input_tokens, 0) as usage_window_input_tokens, - coalesce(au.window_output_tokens, 0) as usage_window_output_tokens, - coalesce(au.window_cached_tokens, 0) as usage_window_cached_tokens, - coalesce(au.window_image_input_tokens, 0) as usage_window_image_input_tokens, - coalesce(au.window_image_output_tokens, 0) as usage_window_image_output_tokens, - coalesce(au.window_image_request_count, 0) as usage_window_image_request_count, - coalesce(au.window_image_request_failed_count, 0) as usage_window_image_request_failed_count, - au.window_started_at as usage_window_started_at, - au.window_reset_at as usage_window_reset_at, - au.limit_window_seconds as usage_limit_window_seconds, - au.last_used_at as usage_last_used_at -from accounts a -left join account_usage au on au.account_id = a.id -order by a.rowid asc"; - -const GET_POOL_ACCOUNT_SQL: &str = r" -select - a.id, - a.email, - a.chatgpt_account_id as account_id, - a.chatgpt_user_id as user_id, - a.label, - a.plan_type, - a.access_token, - a.refresh_token, - a.access_token_expires_at, - a.next_refresh_at, - a.status, - a.quota_limit_reached, - a.quota_verify_required, - a.quota_cooldown_until, - a.quota_json, - a.cloudflare_cooldown_until, - a.added_at, - coalesce(au.request_count, 0) as usage_request_count, - coalesce(au.empty_response_count, 0) as usage_empty_response_count, - coalesce(au.image_input_tokens, 0) as usage_image_input_tokens, - coalesce(au.image_output_tokens, 0) as usage_image_output_tokens, - coalesce(au.image_request_count, 0) as usage_image_request_count, - coalesce(au.image_request_failed_count, 0) as usage_image_request_failed_count, - coalesce(au.window_request_count, 0) as usage_window_request_count, - coalesce(au.window_input_tokens, 0) as usage_window_input_tokens, - coalesce(au.window_output_tokens, 0) as usage_window_output_tokens, - coalesce(au.window_cached_tokens, 0) as usage_window_cached_tokens, - coalesce(au.window_image_input_tokens, 0) as usage_window_image_input_tokens, - coalesce(au.window_image_output_tokens, 0) as usage_window_image_output_tokens, - coalesce(au.window_image_request_count, 0) as usage_window_image_request_count, - coalesce(au.window_image_request_failed_count, 0) as usage_window_image_request_failed_count, - au.window_started_at as usage_window_started_at, - au.window_reset_at as usage_window_reset_at, - au.limit_window_seconds as usage_limit_window_seconds, - au.last_used_at as usage_last_used_at -from accounts a -left join account_usage au on au.account_id = a.id -where a.id = ?"; - -const INSERT_ACCOUNT_SQL: &str = r" -insert into accounts ( - id, - email, - chatgpt_account_id, - chatgpt_user_id, - label, - plan_type, - access_token, - refresh_token, - access_token_expires_at, - status, - added_at, - updated_at -) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; - -const SELECT_STORED_ACCOUNT_BY_ID_SQL: &str = r" -select - id, - email, - chatgpt_account_id as account_id, - chatgpt_user_id as user_id, - label, - plan_type, - access_token, - refresh_token, - access_token_expires_at, - next_refresh_at, - status, - added_at, - updated_at -from accounts -where id = ?"; - -const SELECT_STORED_ACCOUNT_BY_CHATGPT_IDENTITY_SQL: &str = r" -select - id, - email, - chatgpt_account_id as account_id, - chatgpt_user_id as user_id, - label, - plan_type, - access_token, - refresh_token, - access_token_expires_at, - next_refresh_at, - status, - added_at, - updated_at -from accounts -where chatgpt_account_id = ? - and ((chatgpt_user_id is null and ? is null) or chatgpt_user_id = ?) -order by added_at asc -limit 1"; - -const SELECT_ACCOUNT_METADATA_BY_ID_SQL: &str = r" -select - id, - email, - chatgpt_account_id as account_id, - chatgpt_user_id as user_id, - label, - plan_type, - access_token_expires_at, - status, - added_at, - updated_at -from accounts -where id = ?"; - -const UPDATE_ACCOUNT_METADATA_SQL: &str = r" -update accounts -set - email = case when ? then ? else email end, - chatgpt_account_id = case when ? then ? else chatgpt_account_id end, - chatgpt_user_id = case when ? then ? else chatgpt_user_id end, - label = case when ? then ? else label end, - plan_type = case when ? then ? else plan_type end, - status = case when ? then ? else status end, - updated_at = ? -where id = ?"; - -const LIST_STORED_ACCOUNTS_AFTER_CURSOR_SQL: &str = r" -select - id, - email, - chatgpt_account_id as account_id, - chatgpt_user_id as user_id, - label, - plan_type, - access_token, - refresh_token, - access_token_expires_at, - next_refresh_at, - status, - added_at, - updated_at -from accounts -where added_at < ? - or (added_at = ? and id < ?) -order by added_at desc, id desc -limit ?"; - -const LIST_STORED_ACCOUNTS_SQL: &str = r" -select - id, - email, - chatgpt_account_id as account_id, - chatgpt_user_id as user_id, - label, - plan_type, - access_token, - refresh_token, - access_token_expires_at, - next_refresh_at, - status, - added_at, - updated_at -from accounts -order by added_at desc, id desc -limit ?"; - -const LIST_ACCOUNT_METADATA_AFTER_CURSOR_SQL: &str = r" -select - id, - email, - chatgpt_account_id as account_id, - chatgpt_user_id as user_id, - label, - plan_type, - access_token_expires_at, - status, - added_at, - updated_at -from accounts -where added_at < ? - or (added_at = ? and id < ?) -order by added_at desc, id desc -limit ?"; - -const LIST_ACCOUNT_METADATA_SQL: &str = r" -select - id, - email, - chatgpt_account_id as account_id, - chatgpt_user_id as user_id, - label, - plan_type, - access_token_expires_at, - status, - added_at, - updated_at -from accounts -order by added_at desc, id desc -limit ?"; - -const LIST_ACCOUNT_METADATA_SELECT_SQL: &str = r" -select - id, - email, - chatgpt_account_id as account_id, - chatgpt_user_id as user_id, - label, - plan_type, - access_token_expires_at, - status, - added_at, - updated_at -from accounts"; - -const RECORD_USAGE_SQL: &str = r" -insert into account_usage ( - account_id, - request_count, - empty_response_count, - input_tokens, - output_tokens, - cached_tokens, - reasoning_tokens, - total_tokens, - image_input_tokens, - image_output_tokens, - image_request_count, - image_request_failed_count, - window_request_count, - window_input_tokens, - window_output_tokens, - window_cached_tokens, - window_image_input_tokens, - window_image_output_tokens, - window_image_request_count, - window_image_request_failed_count, - window_started_at, - last_used_at -) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) -on conflict(account_id) do update set - request_count = request_count + excluded.request_count, - empty_response_count = empty_response_count + excluded.empty_response_count, - input_tokens = input_tokens + excluded.input_tokens, - output_tokens = output_tokens + excluded.output_tokens, - cached_tokens = cached_tokens + excluded.cached_tokens, - reasoning_tokens = reasoning_tokens + excluded.reasoning_tokens, - total_tokens = total_tokens + excluded.total_tokens, - image_input_tokens = image_input_tokens + excluded.image_input_tokens, - image_output_tokens = image_output_tokens + excluded.image_output_tokens, - image_request_count = image_request_count + excluded.image_request_count, - image_request_failed_count = image_request_failed_count + excluded.image_request_failed_count, - window_request_count = window_request_count + excluded.window_request_count, - window_input_tokens = window_input_tokens + excluded.window_input_tokens, - window_output_tokens = window_output_tokens + excluded.window_output_tokens, - window_cached_tokens = window_cached_tokens + excluded.window_cached_tokens, - window_image_input_tokens = window_image_input_tokens + excluded.window_image_input_tokens, - window_image_output_tokens = window_image_output_tokens + excluded.window_image_output_tokens, - window_image_request_count = window_image_request_count + excluded.window_image_request_count, - window_image_request_failed_count = window_image_request_failed_count + excluded.window_image_request_failed_count, - window_started_at = coalesce(account_usage.window_started_at, excluded.window_started_at), - last_used_at = excluded.last_used_at"; - -const RECORD_MODEL_USAGE_SQL: &str = r" -insert into account_model_usage ( - account_id, - model, - request_count, - error_count, - input_tokens, - output_tokens, - cached_tokens, - last_used_at -) values (?, ?, ?, ?, ?, ?, ?, ?) -on conflict(account_id, model) 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, - last_used_at = excluded.last_used_at"; - -const LIST_MODEL_USAGE_SQL: &str = r" -select - account_id, - model, - request_count, - error_count, - input_tokens, - output_tokens, - cached_tokens, - last_used_at -from account_model_usage -order by account_id asc, request_count desc, last_used_at desc, model asc"; - -const LIST_QUOTA_SNAPSHOTS_SQL: &str = r" -select - id, - email, - quota_json, - quota_fetched_at -from accounts -where quota_json is not null - and trim(quota_json) <> '' -order by coalesce(quota_fetched_at, '') desc, id desc"; - -const UPDATE_QUOTA_JSON_SQL: &str = r" -update accounts -set - quota_json = ?, - quota_fetched_at = ?, - plan_type = coalesce(?, plan_type), - updated_at = ? -where id = ?"; - -const APPLY_QUOTA_SNAPSHOT_SQL: &str = r" -update accounts -set - quota_json = ?, - quota_fetched_at = ?, - plan_type = coalesce(?, plan_type), - status = case - when status in ('disabled', 'banned', 'expired', 'refreshing') then status - when ? = 1 then 'quota_exhausted' - when status = 'quota_exhausted' then 'active' - else status - end, - quota_limit_reached = ?, - quota_verify_required = 0, - quota_cooldown_until = ?, - updated_at = ? -where id = ?"; - -const SELECT_RATE_LIMIT_WINDOW_SQL: &str = r" -select - window_reset_at, - limit_window_seconds -from account_usage -where account_id = ?"; - -const SYNC_RATE_LIMIT_WINDOW_RESET_SQL: &str = r" -insert into account_usage ( - account_id, - window_request_count, - window_input_tokens, - window_output_tokens, - window_cached_tokens, - window_image_input_tokens, - window_image_output_tokens, - window_image_request_count, - window_image_request_failed_count, - window_started_at, - window_reset_at, - limit_window_seconds -) values (?, 0, 0, 0, 0, 0, 0, 0, 0, ?, ?, ?) -on conflict(account_id) do update set - window_request_count = 0, - window_input_tokens = 0, - window_output_tokens = 0, - window_cached_tokens = 0, - window_image_input_tokens = 0, - window_image_output_tokens = 0, - window_image_request_count = 0, - window_image_request_failed_count = 0, - window_started_at = excluded.window_started_at, - window_reset_at = excluded.window_reset_at, - limit_window_seconds = coalesce(excluded.limit_window_seconds, account_usage.limit_window_seconds)"; - -const SYNC_RATE_LIMIT_WINDOW_SQL: &str = r" -insert into account_usage ( - account_id, - window_reset_at, - limit_window_seconds -) values (?, ?, ?) -on conflict(account_id) do update set - window_reset_at = excluded.window_reset_at, - limit_window_seconds = coalesce(excluded.limit_window_seconds, account_usage.limit_window_seconds)"; - -const MARK_QUOTA_LIMITED_UNTIL_SQL: &str = r" -update accounts -set - quota_limit_reached = 1, - quota_verify_required = 0, - quota_cooldown_until = ?, - updated_at = ? -where id = ?"; - -const SET_CLOUDFLARE_COOLDOWN_UNTIL_SQL: &str = r" -update accounts -set - cloudflare_cooldown_until = ?, - updated_at = ? -where id = ?"; - -const UPDATE_ACCOUNT_CLAIMS_WITH_REFRESH_SQL: &str = r" -update accounts -set - email = ?, - chatgpt_account_id = ?, - chatgpt_user_id = ?, - plan_type = ?, - access_token = ?, - refresh_token = ?, - access_token_expires_at = ?, - next_refresh_at = ?, - status = case - when status in ('disabled', 'banned') then status - else ? - end, - updated_at = ? -where id = ?"; - -const UPDATE_ACCOUNT_CLAIMS_PRESERVING_REFRESH_SQL: &str = r" -update accounts -set - email = ?, - chatgpt_account_id = ?, - chatgpt_user_id = ?, - plan_type = ?, - access_token = ?, - access_token_expires_at = ?, - next_refresh_at = ?, - status = case - when status in ('disabled', 'banned') then status - else ? - end, - updated_at = ? -where id = ?"; - -const SET_NEXT_REFRESH_AT_SQL: &str = r" -update accounts -set - next_refresh_at = ?, - updated_at = ? -where id = ?"; - -const UPDATE_IMPORTED_ACCOUNT_WITH_REFRESH_SQL: &str = r" -update accounts -set - email = ?, - chatgpt_account_id = ?, - chatgpt_user_id = ?, - label = ?, - plan_type = ?, - access_token = ?, - refresh_token = ?, - access_token_expires_at = ?, - status = ?, - quota_json = coalesce(?, quota_json), - quota_fetched_at = case when ? is null then quota_fetched_at else ? end, - quota_limit_reached = 0, - quota_cooldown_until = null, - quota_verify_required = ?, - updated_at = ? -where id = ?"; - -const UPDATE_IMPORTED_ACCOUNT_PRESERVING_REFRESH_SQL: &str = r" -update accounts -set - email = ?, - chatgpt_account_id = ?, - chatgpt_user_id = ?, - label = ?, - plan_type = ?, - access_token = ?, - access_token_expires_at = ?, - status = ?, - quota_json = coalesce(?, quota_json), - quota_fetched_at = case when ? is null then quota_fetched_at else ? end, - quota_limit_reached = 0, - quota_cooldown_until = null, - quota_verify_required = ?, - updated_at = ? -where id = ?"; - -const APPLY_IMPORTED_QUOTA_STATE_SQL: &str = r" -update accounts -set - quota_json = coalesce(?, quota_json), - quota_fetched_at = case when ? is null then quota_fetched_at else ? end, - plan_type = coalesce(?, plan_type), - quota_limit_reached = 0, - quota_cooldown_until = null, - quota_verify_required = ?, - updated_at = ? -where id = ?"; - -const DELETE_ACCOUNT_SQL: &str = "delete from accounts where id = ?"; +use queries::*; +use rows::{ + count_account_metadata, get_pool_account, list_pool_accounts, map_account_store_error, + metadata_from_row, model_usage_from_row, optional_positive_i64_to_u64, optional_update_value, + push_account_metadata_search, quota_plan_type, quota_snapshot_from_row, sqlite_usage_delta, + status_to_db, stored_account_from_row, to_page, u64_to_i64_saturating, +}; // ============================================================================ // 错误类型 @@ -1615,336 +1091,3 @@ impl AccountStore for SqliteAccountStore { .map_err(|error| map_account_store_error(&error)) } } - -// ============================================================================ -// 私有辅助函数 -// ============================================================================ - -async fn list_pool_accounts(store: &SqliteAccountStore) -> SqliteAccountStoreResult> { - let rows = sqlx::query(LIST_POOL_ACCOUNTS_SQL) - .fetch_all(&store.pool) - .await?; - let mut accounts = Vec::with_capacity(rows.len()); - - for row in rows { - accounts.push(pool_account_from_row(&row)?); - } - - Ok(accounts) -} - -async fn get_pool_account( - store: &SqliteAccountStore, - account_id: &str, -) -> SqliteAccountStoreResult> { - let row = sqlx::query(GET_POOL_ACCOUNT_SQL) - .bind(account_id) - .fetch_optional(&store.pool) - .await?; - row.map(|row| pool_account_from_row(&row)).transpose() -} - -fn pool_account_from_row(row: &SqliteRow) -> SqliteAccountStoreResult { - let quota_json = row - .get::, _>("quota_json") - .and_then(|quota_json| serde_json::from_str::("a_json).ok()); - let quota_window_reset_at = quota_json.as_ref().and_then(quota_snapshot_reset_at); - let quota_limit_window_seconds = quota_json - .as_ref() - .and_then(quota_snapshot_limit_window_seconds); - - Ok(Account { - id: row.get("id"), - email: row.get("email"), - account_id: row.get("account_id"), - user_id: row.get("user_id"), - label: row.get("label"), - plan_type: row.get("plan_type"), - access_token: row.get("access_token"), - refresh_token: row.get("refresh_token"), - access_token_expires_at: parse_optional_rfc3339( - row.get::, _>("access_token_expires_at") - .as_deref(), - )?, - next_refresh_at: parse_optional_rfc3339( - row.get::, _>("next_refresh_at").as_deref(), - )?, - status: status_from_db(&row.get::("status"))?, - quota_limit_reached: row.get::("quota_limit_reached") != 0, - quota_verify_required: row.get::("quota_verify_required") != 0, - quota_cooldown_until: parse_optional_rfc3339( - row.get::, _>("quota_cooldown_until") - .as_deref(), - )?, - cloudflare_cooldown_until: parse_optional_rfc3339( - row.get::, _>("cloudflare_cooldown_until") - .as_deref(), - )?, - request_count: nonnegative_i64_to_u64(row.get::("usage_request_count")), - empty_response_count: nonnegative_i64_to_u64( - row.get::("usage_empty_response_count"), - ), - image_input_tokens: nonnegative_i64_to_u64(row.get::("usage_image_input_tokens")), - image_output_tokens: nonnegative_i64_to_u64(row.get::("usage_image_output_tokens")), - image_request_count: nonnegative_i64_to_u64(row.get::("usage_image_request_count")), - image_request_failed_count: nonnegative_i64_to_u64( - row.get::("usage_image_request_failed_count"), - ), - window_request_count: nonnegative_i64_to_u64( - row.get::("usage_window_request_count"), - ), - window_input_tokens: nonnegative_i64_to_u64(row.get::("usage_window_input_tokens")), - window_output_tokens: nonnegative_i64_to_u64( - row.get::("usage_window_output_tokens"), - ), - window_cached_tokens: nonnegative_i64_to_u64( - row.get::("usage_window_cached_tokens"), - ), - window_image_input_tokens: nonnegative_i64_to_u64( - row.get::("usage_window_image_input_tokens"), - ), - window_image_output_tokens: nonnegative_i64_to_u64( - row.get::("usage_window_image_output_tokens"), - ), - window_image_request_count: nonnegative_i64_to_u64( - row.get::("usage_window_image_request_count"), - ), - window_image_request_failed_count: nonnegative_i64_to_u64( - row.get::("usage_window_image_request_failed_count"), - ), - window_started_at: parse_optional_rfc3339( - row.get::, _>("usage_window_started_at") - .as_deref(), - )?, - window_reset_at: parse_optional_rfc3339( - row.get::, _>("usage_window_reset_at") - .as_deref(), - )? - .or(quota_window_reset_at), - limit_window_seconds: optional_positive_i64_to_u64( - row.get::, _>("usage_limit_window_seconds"), - ) - .or(quota_limit_window_seconds), - added_at: row.get("added_at"), - last_used_at: row.get("usage_last_used_at"), - }) -} - -fn stored_account_from_row(row: &SqliteRow) -> SqliteAccountStoreResult { - Ok(StoredAccount { - id: row.get("id"), - email: row.get("email"), - account_id: row.get("account_id"), - user_id: row.get("user_id"), - label: row.get("label"), - plan_type: row.get("plan_type"), - access_token: SecretString::new(row.get::("access_token").into()), - refresh_token: row - .get::, _>("refresh_token") - .map(|token| SecretString::new(token.into())), - access_token_expires_at: parse_optional_rfc3339( - row.get::, _>("access_token_expires_at") - .as_deref(), - )?, - next_refresh_at: parse_optional_rfc3339( - row.get::, _>("next_refresh_at").as_deref(), - )?, - status: status_from_db(&row.get::("status"))?, - added_at: row.get("added_at"), - updated_at: row.get("updated_at"), - }) -} - -fn metadata_from_row(row: &SqliteRow) -> SqliteAccountStoreResult { - Ok(StoredAccountMetadata { - id: row.get("id"), - email: row.get("email"), - account_id: row.get("account_id"), - user_id: row.get("user_id"), - label: row.get("label"), - plan_type: row.get("plan_type"), - access_token_expires_at: parse_optional_rfc3339( - row.get::, _>("access_token_expires_at") - .as_deref(), - )?, - status: status_from_db(&row.get::("status"))?, - added_at: row.get("added_at"), - updated_at: row.get("updated_at"), - }) -} - -fn map_account_store_error(error: &impl ToString) -> AccountStoreError { - AccountStoreError::OperationFailed { - message: error.to_string(), - } -} - -fn sqlite_usage_delta(usage: AccountUsageDelta) -> UsageDelta { - let request_count = u64_to_i64_saturating(usage.requests); - let input_tokens = u64_to_i64_saturating(usage.input_tokens); - let output_tokens = u64_to_i64_saturating(usage.output_tokens); - let cached_tokens = u64_to_i64_saturating(usage.cached_tokens); - let image_input_tokens = u64_to_i64_saturating(usage.image_input_tokens); - let image_output_tokens = u64_to_i64_saturating(usage.image_output_tokens); - let image_request_count = u64_to_i64_saturating(usage.image_requests); - let image_request_failed_count = u64_to_i64_saturating(usage.image_request_failures); - UsageDelta { - request_count, - empty_response_count: u64_to_i64_saturating(usage.empty_responses), - input_tokens, - output_tokens, - cached_tokens, - reasoning_tokens: u64_to_i64_saturating(usage.reasoning_tokens), - total_tokens: u64_to_i64_saturating(usage.total_tokens), - image_input_tokens, - image_output_tokens, - image_request_count, - image_request_failed_count, - window_request_count: request_count, - window_input_tokens: input_tokens, - window_output_tokens: output_tokens, - window_cached_tokens: cached_tokens, - window_image_input_tokens: image_input_tokens, - window_image_output_tokens: image_output_tokens, - window_image_request_count: image_request_count, - window_image_request_failed_count: image_request_failed_count, - } -} - -fn quota_plan_type(quota_json: &str) -> Option { - serde_json::from_str::(quota_json) - .ok()? - .get("plan_type")? - .as_str() - .map(str::trim) - .filter(|value| { - !value.is_empty() && !matches!(value.to_ascii_lowercase().as_str(), "unknown" | "null") - }) - .map(ToString::to_string) -} - -fn model_usage_from_row( - row: &sqlx::sqlite::SqliteRow, -) -> SqliteAccountStoreResult { - Ok(AccountModelUsageRecord { - account_id: row.get("account_id"), - model: row.get("model"), - request_count: row.get("request_count"), - error_count: row.get("error_count"), - input_tokens: row.get("input_tokens"), - output_tokens: row.get("output_tokens"), - cached_tokens: row.get("cached_tokens"), - last_used_at: parse_optional_rfc3339( - row.get::, _>("last_used_at").as_deref(), - )?, - }) -} - -fn quota_snapshot_from_row( - row: &sqlx::sqlite::SqliteRow, -) -> SqliteAccountStoreResult { - Ok(AccountQuotaSnapshot { - account_id: row.get("id"), - email: row.get("email"), - quota_json: row.get("quota_json"), - quota_fetched_at: parse_optional_rfc3339( - row.get::, _>("quota_fetched_at").as_deref(), - )?, - }) -} - -fn status_to_db(status: AccountStatus) -> &'static str { - match status { - AccountStatus::Active => "active", - AccountStatus::Expired => "expired", - AccountStatus::QuotaExhausted => "quota_exhausted", - AccountStatus::Refreshing => "refreshing", - AccountStatus::Disabled => "disabled", - AccountStatus::Banned => "banned", - } -} - -fn optional_update_value(value: &Option>) -> Option<&str> { - value.as_ref().and_then(|value| value.as_deref()) -} - -fn status_from_db(value: &str) -> SqliteAccountStoreResult { - match value { - "active" => Ok(AccountStatus::Active), - "expired" => Ok(AccountStatus::Expired), - "quota_exhausted" => Ok(AccountStatus::QuotaExhausted), - "refreshing" => Ok(AccountStatus::Refreshing), - "disabled" => Ok(AccountStatus::Disabled), - "banned" => Ok(AccountStatus::Banned), - other => Err(SqliteAccountStoreError::InvalidStatus(other.to_string())), - } -} - -fn u64_to_i64_saturating(value: u64) -> i64 { - value.min(i64::MAX as u64) as i64 -} - -fn optional_positive_i64_to_u64(value: Option) -> Option { - value - .and_then(|value| u64::try_from(value).ok()) - .filter(|value| *value > 0) -} - -async fn count_account_metadata( - pool: &SqlitePool, - search: Option<&str>, -) -> SqliteAccountStoreResult { - let mut builder = QueryBuilder::::new("select count(*) from accounts"); - push_account_metadata_search(&mut builder, search); - let (total,): (i64,) = builder.build_query_as().fetch_one(pool).await?; - Ok(nonnegative_i64_to_u64(total)) -} - -fn push_account_metadata_search(builder: &mut QueryBuilder, search: Option<&str>) { - let Some(search) = search else { - return; - }; - - let pattern = format!("%{search}%"); - builder.push(" where id like "); - builder.push_bind(pattern.clone()); - builder.push(" or email like "); - builder.push_bind(pattern.clone()); - builder.push(" or label like "); - builder.push_bind(pattern.clone()); - builder.push(" or chatgpt_account_id like "); - builder.push_bind(pattern.clone()); - builder.push(" or chatgpt_user_id like "); - builder.push_bind(pattern); -} - -fn to_page( - rows: &[SqliteRow], - limit: u32, - mapper: impl Fn(&SqliteRow) -> SqliteAccountStoreResult, - cursor_fields: (&str, &str), -) -> Page { - let has_more = rows.len() > limit as usize; - let mut items: Vec = Vec::with_capacity(limit as usize); - let mut last_row: Option<&SqliteRow> = None; - for (i, row) in rows.iter().enumerate() { - if i >= limit as usize { - break; - } - if let Ok(item) = mapper(row) { - items.push(item); - last_row = Some(row); - } - } - let next_cursor = if has_more { - last_row.map(|row| { - use sqlx::Row; - let ts: String = row.get(cursor_fields.0); - let id: String = row.get(cursor_fields.1); - crate::infra::json::encode_cursor(&ts, &id) - }) - } else { - None - }; - Page { items, next_cursor } -} diff --git a/backend/src/upstream/accounts/store/queries.rs b/backend/src/upstream/accounts/store/queries.rs new file mode 100644 index 000000000..2c9359ef6 --- /dev/null +++ b/backend/src/upstream/accounts/store/queries.rs @@ -0,0 +1,531 @@ +//! SQLite 账号仓储 SQL。 + +// ============================================================================ +// SQL 常量 +// ============================================================================ + +pub(super) const LIST_POOL_ACCOUNTS_SQL: &str = r" +select + a.id, + a.email, + a.chatgpt_account_id as account_id, + a.chatgpt_user_id as user_id, + a.label, + a.plan_type, + a.access_token, + a.refresh_token, + a.access_token_expires_at, + a.next_refresh_at, + a.status, + a.quota_limit_reached, + a.quota_verify_required, + a.quota_cooldown_until, + a.quota_json, + a.cloudflare_cooldown_until, + a.added_at, + coalesce(au.request_count, 0) as usage_request_count, + coalesce(au.empty_response_count, 0) as usage_empty_response_count, + coalesce(au.image_input_tokens, 0) as usage_image_input_tokens, + coalesce(au.image_output_tokens, 0) as usage_image_output_tokens, + coalesce(au.image_request_count, 0) as usage_image_request_count, + coalesce(au.image_request_failed_count, 0) as usage_image_request_failed_count, + coalesce(au.window_request_count, 0) as usage_window_request_count, + coalesce(au.window_input_tokens, 0) as usage_window_input_tokens, + coalesce(au.window_output_tokens, 0) as usage_window_output_tokens, + coalesce(au.window_cached_tokens, 0) as usage_window_cached_tokens, + coalesce(au.window_image_input_tokens, 0) as usage_window_image_input_tokens, + coalesce(au.window_image_output_tokens, 0) as usage_window_image_output_tokens, + coalesce(au.window_image_request_count, 0) as usage_window_image_request_count, + coalesce(au.window_image_request_failed_count, 0) as usage_window_image_request_failed_count, + au.window_started_at as usage_window_started_at, + au.window_reset_at as usage_window_reset_at, + au.limit_window_seconds as usage_limit_window_seconds, + au.last_used_at as usage_last_used_at +from accounts a +left join account_usage au on au.account_id = a.id +order by a.rowid asc"; + +pub(super) const GET_POOL_ACCOUNT_SQL: &str = r" +select + a.id, + a.email, + a.chatgpt_account_id as account_id, + a.chatgpt_user_id as user_id, + a.label, + a.plan_type, + a.access_token, + a.refresh_token, + a.access_token_expires_at, + a.next_refresh_at, + a.status, + a.quota_limit_reached, + a.quota_verify_required, + a.quota_cooldown_until, + a.quota_json, + a.cloudflare_cooldown_until, + a.added_at, + coalesce(au.request_count, 0) as usage_request_count, + coalesce(au.empty_response_count, 0) as usage_empty_response_count, + coalesce(au.image_input_tokens, 0) as usage_image_input_tokens, + coalesce(au.image_output_tokens, 0) as usage_image_output_tokens, + coalesce(au.image_request_count, 0) as usage_image_request_count, + coalesce(au.image_request_failed_count, 0) as usage_image_request_failed_count, + coalesce(au.window_request_count, 0) as usage_window_request_count, + coalesce(au.window_input_tokens, 0) as usage_window_input_tokens, + coalesce(au.window_output_tokens, 0) as usage_window_output_tokens, + coalesce(au.window_cached_tokens, 0) as usage_window_cached_tokens, + coalesce(au.window_image_input_tokens, 0) as usage_window_image_input_tokens, + coalesce(au.window_image_output_tokens, 0) as usage_window_image_output_tokens, + coalesce(au.window_image_request_count, 0) as usage_window_image_request_count, + coalesce(au.window_image_request_failed_count, 0) as usage_window_image_request_failed_count, + au.window_started_at as usage_window_started_at, + au.window_reset_at as usage_window_reset_at, + au.limit_window_seconds as usage_limit_window_seconds, + au.last_used_at as usage_last_used_at +from accounts a +left join account_usage au on au.account_id = a.id +where a.id = ?"; + +pub(super) const INSERT_ACCOUNT_SQL: &str = r" +insert into accounts ( + id, + email, + chatgpt_account_id, + chatgpt_user_id, + label, + plan_type, + access_token, + refresh_token, + access_token_expires_at, + status, + added_at, + updated_at +) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; + +pub(super) const SELECT_STORED_ACCOUNT_BY_ID_SQL: &str = r" +select + id, + email, + chatgpt_account_id as account_id, + chatgpt_user_id as user_id, + label, + plan_type, + access_token, + refresh_token, + access_token_expires_at, + next_refresh_at, + status, + added_at, + updated_at +from accounts +where id = ?"; + +pub(super) const SELECT_STORED_ACCOUNT_BY_CHATGPT_IDENTITY_SQL: &str = r" +select + id, + email, + chatgpt_account_id as account_id, + chatgpt_user_id as user_id, + label, + plan_type, + access_token, + refresh_token, + access_token_expires_at, + next_refresh_at, + status, + added_at, + updated_at +from accounts +where chatgpt_account_id = ? + and ((chatgpt_user_id is null and ? is null) or chatgpt_user_id = ?) +order by added_at asc +limit 1"; + +pub(super) const SELECT_ACCOUNT_METADATA_BY_ID_SQL: &str = r" +select + id, + email, + chatgpt_account_id as account_id, + chatgpt_user_id as user_id, + label, + plan_type, + access_token_expires_at, + status, + added_at, + updated_at +from accounts +where id = ?"; + +pub(super) const UPDATE_ACCOUNT_METADATA_SQL: &str = r" +update accounts +set + email = case when ? then ? else email end, + chatgpt_account_id = case when ? then ? else chatgpt_account_id end, + chatgpt_user_id = case when ? then ? else chatgpt_user_id end, + label = case when ? then ? else label end, + plan_type = case when ? then ? else plan_type end, + status = case when ? then ? else status end, + updated_at = ? +where id = ?"; + +pub(super) const LIST_STORED_ACCOUNTS_AFTER_CURSOR_SQL: &str = r" +select + id, + email, + chatgpt_account_id as account_id, + chatgpt_user_id as user_id, + label, + plan_type, + access_token, + refresh_token, + access_token_expires_at, + next_refresh_at, + status, + added_at, + updated_at +from accounts +where added_at < ? + or (added_at = ? and id < ?) +order by added_at desc, id desc +limit ?"; + +pub(super) const LIST_STORED_ACCOUNTS_SQL: &str = r" +select + id, + email, + chatgpt_account_id as account_id, + chatgpt_user_id as user_id, + label, + plan_type, + access_token, + refresh_token, + access_token_expires_at, + next_refresh_at, + status, + added_at, + updated_at +from accounts +order by added_at desc, id desc +limit ?"; + +pub(super) const LIST_ACCOUNT_METADATA_AFTER_CURSOR_SQL: &str = r" +select + id, + email, + chatgpt_account_id as account_id, + chatgpt_user_id as user_id, + label, + plan_type, + access_token_expires_at, + status, + added_at, + updated_at +from accounts +where added_at < ? + or (added_at = ? and id < ?) +order by added_at desc, id desc +limit ?"; + +pub(super) const LIST_ACCOUNT_METADATA_SQL: &str = r" +select + id, + email, + chatgpt_account_id as account_id, + chatgpt_user_id as user_id, + label, + plan_type, + access_token_expires_at, + status, + added_at, + updated_at +from accounts +order by added_at desc, id desc +limit ?"; + +pub(super) const LIST_ACCOUNT_METADATA_SELECT_SQL: &str = r" +select + id, + email, + chatgpt_account_id as account_id, + chatgpt_user_id as user_id, + label, + plan_type, + access_token_expires_at, + status, + added_at, + updated_at +from accounts"; + +pub(super) const RECORD_USAGE_SQL: &str = r" +insert into account_usage ( + account_id, + request_count, + empty_response_count, + input_tokens, + output_tokens, + cached_tokens, + reasoning_tokens, + total_tokens, + image_input_tokens, + image_output_tokens, + image_request_count, + image_request_failed_count, + window_request_count, + window_input_tokens, + window_output_tokens, + window_cached_tokens, + window_image_input_tokens, + window_image_output_tokens, + window_image_request_count, + window_image_request_failed_count, + window_started_at, + last_used_at +) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) +on conflict(account_id) do update set + request_count = request_count + excluded.request_count, + empty_response_count = empty_response_count + excluded.empty_response_count, + input_tokens = input_tokens + excluded.input_tokens, + output_tokens = output_tokens + excluded.output_tokens, + cached_tokens = cached_tokens + excluded.cached_tokens, + reasoning_tokens = reasoning_tokens + excluded.reasoning_tokens, + total_tokens = total_tokens + excluded.total_tokens, + image_input_tokens = image_input_tokens + excluded.image_input_tokens, + image_output_tokens = image_output_tokens + excluded.image_output_tokens, + image_request_count = image_request_count + excluded.image_request_count, + image_request_failed_count = image_request_failed_count + excluded.image_request_failed_count, + window_request_count = window_request_count + excluded.window_request_count, + window_input_tokens = window_input_tokens + excluded.window_input_tokens, + window_output_tokens = window_output_tokens + excluded.window_output_tokens, + window_cached_tokens = window_cached_tokens + excluded.window_cached_tokens, + window_image_input_tokens = window_image_input_tokens + excluded.window_image_input_tokens, + window_image_output_tokens = window_image_output_tokens + excluded.window_image_output_tokens, + window_image_request_count = window_image_request_count + excluded.window_image_request_count, + window_image_request_failed_count = window_image_request_failed_count + excluded.window_image_request_failed_count, + window_started_at = coalesce(account_usage.window_started_at, excluded.window_started_at), + last_used_at = excluded.last_used_at"; + +pub(super) const RECORD_MODEL_USAGE_SQL: &str = r" +insert into account_model_usage ( + account_id, + model, + request_count, + error_count, + input_tokens, + output_tokens, + cached_tokens, + last_used_at +) values (?, ?, ?, ?, ?, ?, ?, ?) +on conflict(account_id, model) 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, + last_used_at = excluded.last_used_at"; + +pub(super) const LIST_MODEL_USAGE_SQL: &str = r" +select + account_id, + model, + request_count, + error_count, + input_tokens, + output_tokens, + cached_tokens, + last_used_at +from account_model_usage +order by account_id asc, request_count desc, last_used_at desc, model asc"; + +pub(super) const LIST_QUOTA_SNAPSHOTS_SQL: &str = r" +select + id, + email, + quota_json, + quota_fetched_at +from accounts +where quota_json is not null + and trim(quota_json) <> '' +order by coalesce(quota_fetched_at, '') desc, id desc"; + +pub(super) const UPDATE_QUOTA_JSON_SQL: &str = r" +update accounts +set + quota_json = ?, + quota_fetched_at = ?, + plan_type = coalesce(?, plan_type), + updated_at = ? +where id = ?"; + +pub(super) const APPLY_QUOTA_SNAPSHOT_SQL: &str = r" +update accounts +set + quota_json = ?, + quota_fetched_at = ?, + plan_type = coalesce(?, plan_type), + status = case + when status in ('disabled', 'banned', 'expired', 'refreshing') then status + when ? = 1 then 'quota_exhausted' + when status = 'quota_exhausted' then 'active' + else status + end, + quota_limit_reached = ?, + quota_verify_required = 0, + quota_cooldown_until = ?, + updated_at = ? +where id = ?"; + +pub(super) const SELECT_RATE_LIMIT_WINDOW_SQL: &str = r" +select + window_reset_at, + limit_window_seconds +from account_usage +where account_id = ?"; + +pub(super) const SYNC_RATE_LIMIT_WINDOW_RESET_SQL: &str = r" +insert into account_usage ( + account_id, + window_request_count, + window_input_tokens, + window_output_tokens, + window_cached_tokens, + window_image_input_tokens, + window_image_output_tokens, + window_image_request_count, + window_image_request_failed_count, + window_started_at, + window_reset_at, + limit_window_seconds +) values (?, 0, 0, 0, 0, 0, 0, 0, 0, ?, ?, ?) +on conflict(account_id) do update set + window_request_count = 0, + window_input_tokens = 0, + window_output_tokens = 0, + window_cached_tokens = 0, + window_image_input_tokens = 0, + window_image_output_tokens = 0, + window_image_request_count = 0, + window_image_request_failed_count = 0, + window_started_at = excluded.window_started_at, + window_reset_at = excluded.window_reset_at, + limit_window_seconds = coalesce(excluded.limit_window_seconds, account_usage.limit_window_seconds)"; + +pub(super) const SYNC_RATE_LIMIT_WINDOW_SQL: &str = r" +insert into account_usage ( + account_id, + window_reset_at, + limit_window_seconds +) values (?, ?, ?) +on conflict(account_id) do update set + window_reset_at = excluded.window_reset_at, + limit_window_seconds = coalesce(excluded.limit_window_seconds, account_usage.limit_window_seconds)"; + +pub(super) const MARK_QUOTA_LIMITED_UNTIL_SQL: &str = r" +update accounts +set + quota_limit_reached = 1, + quota_verify_required = 0, + quota_cooldown_until = ?, + updated_at = ? +where id = ?"; + +pub(super) const SET_CLOUDFLARE_COOLDOWN_UNTIL_SQL: &str = r" +update accounts +set + cloudflare_cooldown_until = ?, + updated_at = ? +where id = ?"; + +pub(super) const UPDATE_ACCOUNT_CLAIMS_WITH_REFRESH_SQL: &str = r" +update accounts +set + email = ?, + chatgpt_account_id = ?, + chatgpt_user_id = ?, + plan_type = ?, + access_token = ?, + refresh_token = ?, + access_token_expires_at = ?, + next_refresh_at = ?, + status = case + when status in ('disabled', 'banned') then status + else ? + end, + updated_at = ? +where id = ?"; + +pub(super) const UPDATE_ACCOUNT_CLAIMS_PRESERVING_REFRESH_SQL: &str = r" +update accounts +set + email = ?, + chatgpt_account_id = ?, + chatgpt_user_id = ?, + plan_type = ?, + access_token = ?, + access_token_expires_at = ?, + next_refresh_at = ?, + status = case + when status in ('disabled', 'banned') then status + else ? + end, + updated_at = ? +where id = ?"; + +pub(super) const SET_NEXT_REFRESH_AT_SQL: &str = r" +update accounts +set + next_refresh_at = ?, + updated_at = ? +where id = ?"; + +pub(super) const UPDATE_IMPORTED_ACCOUNT_WITH_REFRESH_SQL: &str = r" +update accounts +set + email = ?, + chatgpt_account_id = ?, + chatgpt_user_id = ?, + label = ?, + plan_type = ?, + access_token = ?, + refresh_token = ?, + access_token_expires_at = ?, + status = ?, + quota_json = coalesce(?, quota_json), + quota_fetched_at = case when ? is null then quota_fetched_at else ? end, + quota_limit_reached = 0, + quota_cooldown_until = null, + quota_verify_required = ?, + updated_at = ? +where id = ?"; + +pub(super) const UPDATE_IMPORTED_ACCOUNT_PRESERVING_REFRESH_SQL: &str = r" +update accounts +set + email = ?, + chatgpt_account_id = ?, + chatgpt_user_id = ?, + label = ?, + plan_type = ?, + access_token = ?, + access_token_expires_at = ?, + status = ?, + quota_json = coalesce(?, quota_json), + quota_fetched_at = case when ? is null then quota_fetched_at else ? end, + quota_limit_reached = 0, + quota_cooldown_until = null, + quota_verify_required = ?, + updated_at = ? +where id = ?"; + +pub(super) const APPLY_IMPORTED_QUOTA_STATE_SQL: &str = r" +update accounts +set + quota_json = coalesce(?, quota_json), + quota_fetched_at = case when ? is null then quota_fetched_at else ? end, + plan_type = coalesce(?, plan_type), + quota_limit_reached = 0, + quota_cooldown_until = null, + quota_verify_required = ?, + updated_at = ? +where id = ?"; + +pub(super) const DELETE_ACCOUNT_SQL: &str = "delete from accounts where id = ?"; diff --git a/backend/src/upstream/accounts/store/rows.rs b/backend/src/upstream/accounts/store/rows.rs new file mode 100644 index 000000000..bc344f1cc --- /dev/null +++ b/backend/src/upstream/accounts/store/rows.rs @@ -0,0 +1,359 @@ +//! SQLite 账号仓储 row 映射与查询辅助。 + +use secrecy::SecretString; +use serde_json::Value; +use sqlx::{sqlite::SqliteRow, QueryBuilder, Row, Sqlite, SqlitePool}; + +use crate::{ + infra::{ + format::nonnegative_i64_to_u64, json::Page, + time::parse_optional_rfc3339_utc as parse_optional_rfc3339, + }, + upstream::accounts::{ + model::{Account, AccountStatus, AccountUsageDelta}, + quota::{quota_snapshot_limit_window_seconds, quota_snapshot_reset_at}, + }, +}; + +use super::{ + queries::{GET_POOL_ACCOUNT_SQL, LIST_POOL_ACCOUNTS_SQL}, + AccountModelUsageRecord, AccountQuotaSnapshot, AccountStoreError, SqliteAccountStore, + SqliteAccountStoreError, SqliteAccountStoreResult, StoredAccount, StoredAccountMetadata, + UsageDelta, +}; + +pub(super) async fn list_pool_accounts( + store: &SqliteAccountStore, +) -> SqliteAccountStoreResult> { + let rows = sqlx::query(LIST_POOL_ACCOUNTS_SQL) + .fetch_all(&store.pool) + .await?; + let mut accounts = Vec::with_capacity(rows.len()); + + for row in rows { + accounts.push(pool_account_from_row(&row)?); + } + + Ok(accounts) +} + +pub(super) async fn get_pool_account( + store: &SqliteAccountStore, + account_id: &str, +) -> SqliteAccountStoreResult> { + let row = sqlx::query(GET_POOL_ACCOUNT_SQL) + .bind(account_id) + .fetch_optional(&store.pool) + .await?; + row.map(|row| pool_account_from_row(&row)).transpose() +} + +pub(super) fn pool_account_from_row(row: &SqliteRow) -> SqliteAccountStoreResult { + let quota_json = row + .get::, _>("quota_json") + .and_then(|quota_json| serde_json::from_str::("a_json).ok()); + let quota_window_reset_at = quota_json.as_ref().and_then(quota_snapshot_reset_at); + let quota_limit_window_seconds = quota_json + .as_ref() + .and_then(quota_snapshot_limit_window_seconds); + + Ok(Account { + id: row.get("id"), + email: row.get("email"), + account_id: row.get("account_id"), + user_id: row.get("user_id"), + label: row.get("label"), + plan_type: row.get("plan_type"), + access_token: row.get("access_token"), + refresh_token: row.get("refresh_token"), + access_token_expires_at: parse_optional_rfc3339( + row.get::, _>("access_token_expires_at") + .as_deref(), + )?, + next_refresh_at: parse_optional_rfc3339( + row.get::, _>("next_refresh_at").as_deref(), + )?, + status: status_from_db(&row.get::("status"))?, + quota_limit_reached: row.get::("quota_limit_reached") != 0, + quota_verify_required: row.get::("quota_verify_required") != 0, + quota_cooldown_until: parse_optional_rfc3339( + row.get::, _>("quota_cooldown_until") + .as_deref(), + )?, + cloudflare_cooldown_until: parse_optional_rfc3339( + row.get::, _>("cloudflare_cooldown_until") + .as_deref(), + )?, + request_count: nonnegative_i64_to_u64(row.get::("usage_request_count")), + empty_response_count: nonnegative_i64_to_u64( + row.get::("usage_empty_response_count"), + ), + image_input_tokens: nonnegative_i64_to_u64(row.get::("usage_image_input_tokens")), + image_output_tokens: nonnegative_i64_to_u64(row.get::("usage_image_output_tokens")), + image_request_count: nonnegative_i64_to_u64(row.get::("usage_image_request_count")), + image_request_failed_count: nonnegative_i64_to_u64( + row.get::("usage_image_request_failed_count"), + ), + window_request_count: nonnegative_i64_to_u64( + row.get::("usage_window_request_count"), + ), + window_input_tokens: nonnegative_i64_to_u64(row.get::("usage_window_input_tokens")), + window_output_tokens: nonnegative_i64_to_u64( + row.get::("usage_window_output_tokens"), + ), + window_cached_tokens: nonnegative_i64_to_u64( + row.get::("usage_window_cached_tokens"), + ), + window_image_input_tokens: nonnegative_i64_to_u64( + row.get::("usage_window_image_input_tokens"), + ), + window_image_output_tokens: nonnegative_i64_to_u64( + row.get::("usage_window_image_output_tokens"), + ), + window_image_request_count: nonnegative_i64_to_u64( + row.get::("usage_window_image_request_count"), + ), + window_image_request_failed_count: nonnegative_i64_to_u64( + row.get::("usage_window_image_request_failed_count"), + ), + window_started_at: parse_optional_rfc3339( + row.get::, _>("usage_window_started_at") + .as_deref(), + )?, + window_reset_at: parse_optional_rfc3339( + row.get::, _>("usage_window_reset_at") + .as_deref(), + )? + .or(quota_window_reset_at), + limit_window_seconds: optional_positive_i64_to_u64( + row.get::, _>("usage_limit_window_seconds"), + ) + .or(quota_limit_window_seconds), + added_at: row.get("added_at"), + last_used_at: row.get("usage_last_used_at"), + }) +} + +pub(super) fn stored_account_from_row(row: &SqliteRow) -> SqliteAccountStoreResult { + Ok(StoredAccount { + id: row.get("id"), + email: row.get("email"), + account_id: row.get("account_id"), + user_id: row.get("user_id"), + label: row.get("label"), + plan_type: row.get("plan_type"), + access_token: SecretString::new(row.get::("access_token").into()), + refresh_token: row + .get::, _>("refresh_token") + .map(|token| SecretString::new(token.into())), + access_token_expires_at: parse_optional_rfc3339( + row.get::, _>("access_token_expires_at") + .as_deref(), + )?, + next_refresh_at: parse_optional_rfc3339( + row.get::, _>("next_refresh_at").as_deref(), + )?, + status: status_from_db(&row.get::("status"))?, + added_at: row.get("added_at"), + updated_at: row.get("updated_at"), + }) +} + +pub(super) fn metadata_from_row( + row: &SqliteRow, +) -> SqliteAccountStoreResult { + Ok(StoredAccountMetadata { + id: row.get("id"), + email: row.get("email"), + account_id: row.get("account_id"), + user_id: row.get("user_id"), + label: row.get("label"), + plan_type: row.get("plan_type"), + access_token_expires_at: parse_optional_rfc3339( + row.get::, _>("access_token_expires_at") + .as_deref(), + )?, + status: status_from_db(&row.get::("status"))?, + added_at: row.get("added_at"), + updated_at: row.get("updated_at"), + }) +} + +pub(super) fn map_account_store_error(error: &impl ToString) -> AccountStoreError { + AccountStoreError::OperationFailed { + message: error.to_string(), + } +} + +pub(super) fn sqlite_usage_delta(usage: AccountUsageDelta) -> UsageDelta { + let request_count = u64_to_i64_saturating(usage.requests); + let input_tokens = u64_to_i64_saturating(usage.input_tokens); + let output_tokens = u64_to_i64_saturating(usage.output_tokens); + let cached_tokens = u64_to_i64_saturating(usage.cached_tokens); + let image_input_tokens = u64_to_i64_saturating(usage.image_input_tokens); + let image_output_tokens = u64_to_i64_saturating(usage.image_output_tokens); + let image_request_count = u64_to_i64_saturating(usage.image_requests); + let image_request_failed_count = u64_to_i64_saturating(usage.image_request_failures); + UsageDelta { + request_count, + empty_response_count: u64_to_i64_saturating(usage.empty_responses), + input_tokens, + output_tokens, + cached_tokens, + reasoning_tokens: u64_to_i64_saturating(usage.reasoning_tokens), + total_tokens: u64_to_i64_saturating(usage.total_tokens), + image_input_tokens, + image_output_tokens, + image_request_count, + image_request_failed_count, + window_request_count: request_count, + window_input_tokens: input_tokens, + window_output_tokens: output_tokens, + window_cached_tokens: cached_tokens, + window_image_input_tokens: image_input_tokens, + window_image_output_tokens: image_output_tokens, + window_image_request_count: image_request_count, + window_image_request_failed_count: image_request_failed_count, + } +} + +pub(super) fn quota_plan_type(quota_json: &str) -> Option { + serde_json::from_str::(quota_json) + .ok()? + .get("plan_type")? + .as_str() + .map(str::trim) + .filter(|value| { + !value.is_empty() && !matches!(value.to_ascii_lowercase().as_str(), "unknown" | "null") + }) + .map(ToString::to_string) +} + +pub(super) fn model_usage_from_row( + row: &sqlx::sqlite::SqliteRow, +) -> SqliteAccountStoreResult { + Ok(AccountModelUsageRecord { + account_id: row.get("account_id"), + model: row.get("model"), + request_count: row.get("request_count"), + error_count: row.get("error_count"), + input_tokens: row.get("input_tokens"), + output_tokens: row.get("output_tokens"), + cached_tokens: row.get("cached_tokens"), + last_used_at: parse_optional_rfc3339( + row.get::, _>("last_used_at").as_deref(), + )?, + }) +} + +pub(super) fn quota_snapshot_from_row( + row: &sqlx::sqlite::SqliteRow, +) -> SqliteAccountStoreResult { + Ok(AccountQuotaSnapshot { + account_id: row.get("id"), + email: row.get("email"), + quota_json: row.get("quota_json"), + quota_fetched_at: parse_optional_rfc3339( + row.get::, _>("quota_fetched_at").as_deref(), + )?, + }) +} + +pub(super) fn status_to_db(status: AccountStatus) -> &'static str { + match status { + AccountStatus::Active => "active", + AccountStatus::Expired => "expired", + AccountStatus::QuotaExhausted => "quota_exhausted", + AccountStatus::Refreshing => "refreshing", + AccountStatus::Disabled => "disabled", + AccountStatus::Banned => "banned", + } +} + +pub(super) fn optional_update_value(value: &Option>) -> Option<&str> { + value.as_ref().and_then(|value| value.as_deref()) +} + +pub(super) fn status_from_db(value: &str) -> SqliteAccountStoreResult { + match value { + "active" => Ok(AccountStatus::Active), + "expired" => Ok(AccountStatus::Expired), + "quota_exhausted" => Ok(AccountStatus::QuotaExhausted), + "refreshing" => Ok(AccountStatus::Refreshing), + "disabled" => Ok(AccountStatus::Disabled), + "banned" => Ok(AccountStatus::Banned), + other => Err(SqliteAccountStoreError::InvalidStatus(other.to_string())), + } +} + +pub(super) fn u64_to_i64_saturating(value: u64) -> i64 { + value.min(i64::MAX as u64) as i64 +} + +pub(super) fn optional_positive_i64_to_u64(value: Option) -> Option { + value + .and_then(|value| u64::try_from(value).ok()) + .filter(|value| *value > 0) +} + +pub(super) async fn count_account_metadata( + pool: &SqlitePool, + search: Option<&str>, +) -> SqliteAccountStoreResult { + let mut builder = QueryBuilder::::new("select count(*) from accounts"); + push_account_metadata_search(&mut builder, search); + let (total,): (i64,) = builder.build_query_as().fetch_one(pool).await?; + Ok(nonnegative_i64_to_u64(total)) +} + +pub(super) fn push_account_metadata_search( + builder: &mut QueryBuilder, + search: Option<&str>, +) { + let Some(search) = search else { + return; + }; + + let pattern = format!("%{search}%"); + builder.push(" where id like "); + builder.push_bind(pattern.clone()); + builder.push(" or email like "); + builder.push_bind(pattern.clone()); + builder.push(" or label like "); + builder.push_bind(pattern.clone()); + builder.push(" or chatgpt_account_id like "); + builder.push_bind(pattern.clone()); + builder.push(" or chatgpt_user_id like "); + builder.push_bind(pattern); +} + +pub(super) fn to_page( + rows: &[SqliteRow], + limit: u32, + mapper: impl Fn(&SqliteRow) -> SqliteAccountStoreResult, + cursor_fields: (&str, &str), +) -> Page { + let has_more = rows.len() > limit as usize; + let mut items: Vec = Vec::with_capacity(limit as usize); + let mut last_row: Option<&SqliteRow> = None; + for (i, row) in rows.iter().enumerate() { + if i >= limit as usize { + break; + } + if let Ok(item) = mapper(row) { + items.push(item); + last_row = Some(row); + } + } + let next_cursor = if has_more { + last_row.map(|row| { + use sqlx::Row; + let ts: String = row.get(cursor_fields.0); + let id: String = row.get(cursor_fields.1); + crate::infra::json::encode_cursor(&ts, &id) + }) + } else { + None + }; + Page { items, next_cursor } +} diff --git a/backend/src/upstream/fingerprint.rs b/backend/src/upstream/fingerprint.rs index 1db21edaf..614bb502a 100644 --- a/backend/src/upstream/fingerprint.rs +++ b/backend/src/upstream/fingerprint.rs @@ -53,7 +53,7 @@ pub struct Fingerprint { impl Fingerprint { /// 从配置构造指纹。 - pub fn from_config(config: &crate::config::types::FingerprintConfig) -> Self { + pub fn from_config(config: &crate::config::schema::FingerprintConfig) -> Self { Self { originator: config.originator.clone(), app_version: config.app_version.clone(), diff --git a/backend/src/upstream/models/backend_entry.rs b/backend/src/upstream/models/backend_entry.rs new file mode 100644 index 000000000..6f6f24536 --- /dev/null +++ b/backend/src/upstream/models/backend_entry.rs @@ -0,0 +1,73 @@ +//! 上游模型目录原始条目。 + +use serde::{Deserialize, Serialize}; + +/// 上游声明的 reasoning effort 条目。 +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] +pub struct BackendReasoningEffort { + /// reasoning_effort 字段。 + #[serde(default, rename = "reasoning_effort", alias = "reasoningEffort")] + pub reasoning_effort: Option, + /// 上游可能返回的 effort 字段别名。 + #[serde(default)] + pub effort: Option, + /// 展示描述。 + #[serde(default)] + pub description: Option, +} + +/// 上游截断策略定义。 +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] +pub struct BackendTruncationPolicy { + /// 上下文截断限制。 + pub limit: Option, +} + +/// 上游 `/codex/models` 返回的原始模型条目。 +#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] +pub struct BackendModelEntry { + /// slug。 + pub slug: Option, + /// id。 + pub id: Option, + /// name。 + pub name: Option, + /// display_name。 + pub display_name: Option, + /// title。 + pub title: Option, + /// description。 + pub description: Option, + /// 是否默认模型。 + pub is_default: Option, + /// 默认 reasoning effort。 + pub default_reasoning_effort: Option, + /// 默认 reasoning level。 + pub default_reasoning_level: Option, + /// 支持的 reasoning effort 列表。 + #[serde(default)] + pub supported_reasoning_efforts: Vec, + /// 支持的 reasoning level 列表。 + #[serde(default)] + pub supported_reasoning_levels: Vec, + /// 输入模态。 + pub input_modalities: Option>, + /// 输出模态。 + pub output_modalities: Option>, + /// 是否支持 personality。 + pub supports_personality: Option, + /// 升级提示。 + pub upgrade: Option, + /// contextWindow 别名。 + #[serde(alias = "contextWindow")] + pub context_window: Option, + /// maxContextWindow 别名。 + #[serde(alias = "maxContextWindow")] + pub max_context_window: Option, + /// maxOutputTokens 别名。 + #[serde(alias = "maxOutputTokens")] + pub max_output_tokens: Option, + /// truncationPolicy 别名。 + #[serde(alias = "truncationPolicy")] + pub truncation_policy: Option, +} diff --git a/backend/src/upstream/models/catalog.rs b/backend/src/upstream/models/catalog.rs new file mode 100644 index 000000000..dc5f18368 --- /dev/null +++ b/backend/src/upstream/models/catalog.rs @@ -0,0 +1,406 @@ +//! 模型目录聚合与模型名解析。 + +use std::collections::{BTreeMap, BTreeSet}; + +use super::{ + backend_entry::{BackendModelEntry, BackendReasoningEffort}, + config::ModelConfig, + info::{CodexModelInfo, ReasoningEffortInfo}, + snapshot::ModelPlanSnapshot, +}; + +/// 解析模型名后得到的标准化结果。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ParsedModelName { + /// 最终模型 ID。 + pub model_id: String, + /// 推理强度后缀。 + pub reasoning_effort: Option, + /// 服务层级后缀。 + pub service_tier: Option, +} + +const SERVICE_TIER_SUFFIXES: [&str; 2] = ["fast", "flex"]; +const REASONING_EFFORT_SUFFIXES: [&str; 6] = ["none", "minimal", "low", "medium", "high", "xhigh"]; +const BUILTIN_CODEX_MODELS: [(&str, &str, bool); 8] = [ + ("gpt-5.5", "GPT-5.5", true), + ("gpt-5.4", "GPT-5.4", false), + ("gpt-5.4-mini", "GPT-5.4 Mini", false), + ("gpt-5.3-codex", "GPT-5.3 Codex", false), + ("gpt-5.3-codex-spark", "GPT-5.3 Codex Spark", false), + ("codex-auto-review", "Codex Auto Review", false), + ("gpt-5.2", "GPT-5.2", false), + ("gpt-image-1", "GPT Image 1", false), +]; + +/// 模型目录聚合。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ModelCatalog { + models: Vec, + model_aliases: BTreeMap, + model_plan_index: BTreeMap>, + fetched_plan_types: BTreeSet, +} + +impl ModelPlanSnapshot { + /// 将上游模型条目标准化为可持久化快照。 + pub fn from_backend_entries( + plan_type: impl Into, + entries: Vec, + ) -> Self { + Self { + plan_type: plan_type.into(), + models: entries.into_iter().map(normalize_backend_model).collect(), + } + } +} + +impl ModelCatalog { + /// 从静态配置构造模型目录。 + pub fn from_config(config: &ModelConfig) -> Self { + let model_aliases = normalize_aliases(&config.model_aliases); + Self { + models: builtin_codex_models(), + model_aliases, + model_plan_index: BTreeMap::new(), + fetched_plan_types: BTreeSet::new(), + } + } + + /// 从静态配置和后端快照构造模型目录。 + pub fn from_config_and_snapshots( + config: &ModelConfig, + snapshots: &[ModelPlanSnapshot], + ) -> Self { + if snapshots.is_empty() { + return Self::from_config(config); + } + + let model_aliases = normalize_aliases(&config.model_aliases); + let mut models_by_id = BTreeMap::new(); + let mut model_order = Vec::new(); + let mut model_plan_index: BTreeMap> = BTreeMap::new(); + let mut fetched_plan_types = BTreeSet::new(); + + for snapshot in snapshots { + fetched_plan_types.insert(snapshot.plan_type.clone()); + for model in &snapshot.models { + if !models_by_id.contains_key(&model.id) { + model_order.push(model.id.clone()); + } + models_by_id.insert(model.id.clone(), model.clone()); + let plans = model_plan_index.entry(model.id.clone()).or_default(); + if !plans.contains(&snapshot.plan_type) { + plans.push(snapshot.plan_type.clone()); + } + } + } + + let models = model_order + .into_iter() + .filter_map(|id| models_by_id.remove(&id)) + .collect::>(); + if models.is_empty() { + return Self { + models: builtin_codex_models(), + model_aliases, + model_plan_index, + fetched_plan_types, + }; + } + + Self { + models, + model_aliases, + model_plan_index, + fetched_plan_types, + } + } + + /// 返回对外可见的模型列表副本。 + pub fn models(&self) -> Vec { + self.models.clone() + } + + /// 返回 OpenAI `/v1/models` 对外暴露的模型 ID。 + pub fn public_model_ids(&self) -> Vec { + let mut seen = BTreeSet::new(); + let mut ids = Vec::new(); + for model in &self.models { + if seen.insert(model.id.clone()) { + ids.push(model.id.clone()); + } + } + for alias in self.model_aliases.keys() { + if seen.insert(alias.clone()) { + ids.push(alias.clone()); + } + } + ids + } + + /// 返回模型数量。 + pub fn len(&self) -> usize { + self.models.len() + } + + /// 模型目录是否为空。 + pub fn is_empty(&self) -> bool { + self.models.is_empty() + } + + /// 返回指定订阅计划可用的模型列表。 + pub fn models_for_plan(&self, plan_type: &str) -> Vec { + self.models + .iter() + .filter(|model| { + self.model_plan_index + .get(&model.id) + .is_some_and(|plans| plans.iter().any(|plan| plan == plan_type)) + }) + .cloned() + .collect() + } + + /// 按模型 ID 查询模型信息。 + pub fn model_info(&self, model_id: &str) -> Option { + self.models + .iter() + .find(|model| model.id == model_id) + .cloned() + } + + /// 按对外模型名查询模型信息,支持别名和已知后缀。 + pub fn model_info_for_name(&self, input: &str) -> Option { + let parsed = self.parse_model_name(input); + self.model_info(&parsed.model_id) + } + + /// 返回 model -> plans allowlist。 + pub fn model_plan_allowlist(&self) -> BTreeMap> { + self.model_plan_index.clone() + } + + /// 返回已成功拉取过模型列表的订阅计划。 + pub fn fetched_plan_types(&self) -> BTreeSet { + self.fetched_plan_types.clone() + } + + /// 判断输入模型名是否在目录中可识别。 + pub fn is_recognized_model_name(&self, input: &str) -> bool { + let trimmed = input.trim(); + if trimmed.is_empty() { + return false; + } + if self.model_aliases.contains_key(trimmed) || self.model_info(trimmed).is_some() { + return true; + } + + let stripped = strip_known_model_suffixes(trimmed); + if stripped.model_name == trimmed + || (stripped.reasoning_effort.is_none() && stripped.service_tier.is_none()) + { + return false; + } + self.model_aliases.contains_key(&stripped.model_name) + || self.model_info(&stripped.model_name).is_some() + } + + /// 解析外部传入的模型名,提取别名、推理强度和服务层级后缀。 + pub fn parse_model_name(&self, input: &str) -> ParsedModelName { + let trimmed = input.trim(); + if self.model_aliases.contains_key(trimmed) || self.model_info(trimmed).is_some() { + return ParsedModelName { + model_id: self.resolve_model_id(trimmed), + reasoning_effort: None, + service_tier: None, + }; + } + + let stripped = strip_known_model_suffixes(trimmed); + ParsedModelName { + model_id: self.resolve_model_id(&stripped.model_name), + reasoning_effort: stripped.reasoning_effort, + service_tier: stripped.service_tier, + } + } + + /// 将标准化模型名重新拼成展示名。 + pub fn build_display_model_name(parsed: &ParsedModelName) -> String { + let mut name = parsed.model_id.clone(); + if let Some(reasoning_effort) = &parsed.reasoning_effort { + name.push('-'); + name.push_str(reasoning_effort); + } + if let Some(service_tier) = &parsed.service_tier { + name.push('-'); + name.push_str(service_tier); + } + name + } + + fn resolve_model_id(&self, input: &str) -> String { + self.resolve_alias_chain(input) + } + + fn resolve_alias_chain(&self, input: &str) -> String { + let original = input.trim(); + let mut current = original.to_string(); + let mut seen = BTreeSet::new(); + for _ in 0..20 { + let Some(target) = self.model_aliases.get(¤t).map(|value| value.trim()) else { + return current; + }; + if !seen.insert(current.clone()) || seen.contains(target) { + return original.to_string(); + } + current = target.to_string(); + } + original.to_string() + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +struct StrippedModelName { + model_name: String, + reasoning_effort: Option, + service_tier: Option, +} + +fn strip_known_model_suffixes(input: &str) -> StrippedModelName { + let mut remaining = input.trim().to_string(); + let service_tier = take_suffix(&mut remaining, &SERVICE_TIER_SUFFIXES); + let reasoning_effort = take_suffix(&mut remaining, &REASONING_EFFORT_SUFFIXES); + StrippedModelName { + model_name: remaining, + reasoning_effort, + service_tier, + } +} + +fn take_suffix(remaining: &mut String, suffixes: &[&str]) -> Option { + let suffix = suffixes + .iter() + .find(|suffix| remaining.ends_with(&format!("-{suffix}")))?; + let truncate_to = remaining.len() - suffix.len() - 1; + remaining.truncate(truncate_to); + Some((*suffix).to_string()) +} + +fn normalize_aliases(input: &BTreeMap) -> BTreeMap { + input + .iter() + .filter_map(|(alias, target)| { + let alias = alias.trim(); + let target = target.trim(); + (!alias.is_empty() && !target.is_empty()) + .then(|| (alias.to_string(), target.to_string())) + }) + .collect() +} + +fn builtin_codex_models() -> Vec { + BUILTIN_CODEX_MODELS + .into_iter() + .map(|(id, display_name, is_default)| CodexModelInfo { + id: id.to_string(), + display_name: display_name.to_string(), + description: String::new(), + is_default, + supported_reasoning_efforts: default_reasoning_efforts(), + default_reasoning_effort: "medium".to_string(), + input_modalities: vec!["text".to_string()], + output_modalities: vec!["text".to_string()], + supports_personality: false, + upgrade: None, + source: "builtin".to_string(), + context_window: None, + max_context_window: None, + max_output_tokens: None, + truncation_policy_limit: None, + }) + .collect() +} + +fn default_reasoning_efforts() -> Vec { + ["minimal", "low", "medium", "high"] + .into_iter() + .map(|reasoning_effort| ReasoningEffortInfo { + reasoning_effort: reasoning_effort.to_string(), + description: String::new(), + }) + .collect() +} + +fn normalize_backend_model(raw: BackendModelEntry) -> CodexModelInfo { + let id = first_non_empty([raw.slug.as_deref(), raw.id.as_deref(), raw.name.as_deref()]) + .unwrap_or("unknown") + .to_string(); + let display_name = first_non_empty([ + raw.display_name.as_deref(), + raw.title.as_deref(), + raw.name.as_deref(), + ]) + .unwrap_or(&id) + .to_string(); + let reasoning_entries = if raw.supported_reasoning_efforts.is_empty() { + raw.supported_reasoning_levels + } else { + raw.supported_reasoning_efforts + }; + let mut supported_reasoning_efforts = reasoning_entries + .into_iter() + .filter_map(normalize_backend_reasoning_effort) + .collect::>(); + if supported_reasoning_efforts.is_empty() { + supported_reasoning_efforts.push(ReasoningEffortInfo { + reasoning_effort: "medium".to_string(), + description: "Default".to_string(), + }); + } + let default_reasoning_effort = first_non_empty([ + raw.default_reasoning_effort.as_deref(), + raw.default_reasoning_level.as_deref(), + ]) + .unwrap_or("medium") + .to_string(); + + CodexModelInfo { + id, + display_name, + description: raw.description.unwrap_or_default(), + is_default: raw.is_default.unwrap_or(false), + supported_reasoning_efforts, + default_reasoning_effort, + input_modalities: raw + .input_modalities + .unwrap_or_else(|| vec!["text".to_string()]), + output_modalities: raw + .output_modalities + .unwrap_or_else(|| vec!["text".to_string()]), + supports_personality: raw.supports_personality.unwrap_or(false), + upgrade: raw.upgrade, + source: "backend".to_string(), + context_window: raw.context_window, + max_context_window: raw.max_context_window, + max_output_tokens: raw.max_output_tokens, + truncation_policy_limit: raw.truncation_policy.and_then(|policy| policy.limit), + } +} + +fn normalize_backend_reasoning_effort(raw: BackendReasoningEffort) -> Option { + let reasoning_effort = + first_non_empty([raw.reasoning_effort.as_deref(), raw.effort.as_deref()])?.to_string(); + Some(ReasoningEffortInfo { + description: raw.description.unwrap_or_default(), + reasoning_effort, + }) +} + +fn first_non_empty<'a>(values: impl IntoIterator>) -> Option<&'a str> { + values + .into_iter() + .flatten() + .map(str::trim) + .find(|value| !value.is_empty()) +} diff --git a/backend/src/upstream/models/config.rs b/backend/src/upstream/models/config.rs new file mode 100644 index 000000000..40e79a39b --- /dev/null +++ b/backend/src/upstream/models/config.rs @@ -0,0 +1,12 @@ +//! 模型目录配置。 + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +/// 模型目录别名配置。 +#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] +pub struct ModelConfig { + /// 模型别名映射。 + pub model_aliases: BTreeMap, +} diff --git a/backend/src/upstream/models/info.rs b/backend/src/upstream/models/info.rs new file mode 100644 index 000000000..927a4eedb --- /dev/null +++ b/backend/src/upstream/models/info.rs @@ -0,0 +1,53 @@ +//! 标准化模型展示信息。 + +use serde::{Deserialize, Serialize}; + +/// 单个 reasoning effort 的标准化展示信息。 +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct ReasoningEffortInfo { + /// 推理强度名。 + pub reasoning_effort: String, + /// 展示描述。 + pub description: String, +} + +/// 对外暴露的单个模型目录条目。 +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct CodexModelInfo { + /// 模型唯一 ID。 + pub id: String, + /// 展示名。 + pub display_name: String, + /// 描述文本。 + pub description: String, + /// 是否默认模型。 + pub is_default: bool, + /// 支持的推理强度列表。 + pub supported_reasoning_efforts: Vec, + /// 默认推理强度。 + pub default_reasoning_effort: String, + /// 输入模态。 + pub input_modalities: Vec, + /// 输出模态。 + pub output_modalities: Vec, + /// 是否支持 personality。 + pub supports_personality: bool, + /// 升级提示。 + pub upgrade: Option, + /// 来源标记。 + pub source: String, + /// 当前上下文窗口。 + #[serde(skip_serializing_if = "Option::is_none")] + pub context_window: Option, + /// 最大上下文窗口。 + #[serde(skip_serializing_if = "Option::is_none")] + pub max_context_window: Option, + /// 最大输出 token 数。 + #[serde(skip_serializing_if = "Option::is_none")] + pub max_output_tokens: Option, + /// 截断策略限制。 + #[serde(skip_serializing_if = "Option::is_none")] + pub truncation_policy_limit: Option, +} diff --git a/backend/src/upstream/models/mod.rs b/backend/src/upstream/models/mod.rs index 8ee0ed8b0..8657e7a49 100644 --- a/backend/src/upstream/models/mod.rs +++ b/backend/src/upstream/models/mod.rs @@ -1,894 +1,9 @@ -//! 模型目录领域:数据类型、快照存储端口与服务。 - -use std::{ - collections::BTreeMap, - sync::{Arc, RwLock}, -}; - -use async_trait::async_trait; -use serde::{Deserialize, Serialize}; -use sqlx::Row; -use thiserror::Error; - -use crate::upstream::accounts::model::Account; - -// --------------------------------------------------------------------------- -// 数据类型 -// --------------------------------------------------------------------------- - -/// 模型目录别名配置。 -#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] -pub struct ModelConfig { - /// 模型别名映射。 - pub model_aliases: BTreeMap, -} - -/// 单个 reasoning effort 的标准化展示信息。 -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -#[serde(rename_all = "camelCase")] -pub struct ReasoningEffortInfo { - /// 推理强度名。 - pub reasoning_effort: String, - /// 展示描述。 - pub description: String, -} - -/// 对外暴露的单个模型目录条目。 -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -#[serde(rename_all = "camelCase")] -pub struct CodexModelInfo { - /// 模型唯一 ID。 - pub id: String, - /// 展示名。 - pub display_name: String, - /// 描述文本。 - pub description: String, - /// 是否默认模型。 - pub is_default: bool, - /// 支持的推理强度列表。 - pub supported_reasoning_efforts: Vec, - /// 默认推理强度。 - pub default_reasoning_effort: String, - /// 输入模态。 - pub input_modalities: Vec, - /// 输出模态。 - pub output_modalities: Vec, - /// 是否支持 personality。 - pub supports_personality: bool, - /// 升级提示。 - pub upgrade: Option, - /// 来源标记。 - pub source: String, - /// 当前上下文窗口。 - #[serde(skip_serializing_if = "Option::is_none")] - pub context_window: Option, - /// 最大上下文窗口。 - #[serde(skip_serializing_if = "Option::is_none")] - pub max_context_window: Option, - /// 最大输出 token 数。 - #[serde(skip_serializing_if = "Option::is_none")] - pub max_output_tokens: Option, - /// 截断策略限制。 - #[serde(skip_serializing_if = "Option::is_none")] - pub truncation_policy_limit: Option, -} - -/// 解析模型名后得到的标准化结果。 -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ParsedModelName { - /// 最终模型 ID。 - pub model_id: String, - /// 推理强度后缀。 - pub reasoning_effort: Option, - /// 服务层级后缀。 - pub service_tier: Option, -} - -/// 按计划类型持久化的模型快照。 -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] -#[serde(rename_all = "camelCase")] -pub struct ModelPlanSnapshot { - /// 订阅计划类型。 - pub plan_type: String, - /// 该计划可见的模型列表。 - pub models: Vec, -} - -/// 上游声明的 reasoning effort 条目。 -#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] -pub struct BackendReasoningEffort { - /// reasoning_effort 字段。 - #[serde(default, rename = "reasoning_effort", alias = "reasoningEffort")] - pub reasoning_effort: Option, - /// 上游可能返回的 effort 字段别名。 - #[serde(default)] - pub effort: Option, - /// 展示描述。 - #[serde(default)] - pub description: Option, -} - -/// 上游截断策略定义。 -#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] -pub struct BackendTruncationPolicy { - /// 上下文截断限制。 - pub limit: Option, -} - -/// 上游 `/codex/models` 返回的原始模型条目。 -#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)] -pub struct BackendModelEntry { - /// slug。 - pub slug: Option, - /// id。 - pub id: Option, - /// name。 - pub name: Option, - /// display_name。 - pub display_name: Option, - /// title。 - pub title: Option, - /// description。 - pub description: Option, - /// 是否默认模型。 - pub is_default: Option, - /// 默认 reasoning effort。 - pub default_reasoning_effort: Option, - /// 默认 reasoning level。 - pub default_reasoning_level: Option, - /// 支持的 reasoning effort 列表。 - #[serde(default)] - pub supported_reasoning_efforts: Vec, - /// 支持的 reasoning level 列表。 - #[serde(default)] - pub supported_reasoning_levels: Vec, - /// 输入模态。 - pub input_modalities: Option>, - /// 输出模态。 - pub output_modalities: Option>, - /// 是否支持 personality。 - pub supports_personality: Option, - /// 升级提示。 - pub upgrade: Option, - /// contextWindow 别名。 - #[serde(alias = "contextWindow")] - pub context_window: Option, - /// maxContextWindow 别名。 - #[serde(alias = "maxContextWindow")] - pub max_context_window: Option, - /// maxOutputTokens 别名。 - #[serde(alias = "maxOutputTokens")] - pub max_output_tokens: Option, - /// truncationPolicy 别名。 - #[serde(alias = "truncationPolicy")] - pub truncation_policy: Option, -} - -// --------------------------------------------------------------------------- -// 模型快照存储端口 -// --------------------------------------------------------------------------- - -/// 模型快照存储错误。 -#[derive(Debug, Error)] -pub enum ModelSnapshotStoreError { - /// 底层存储失败。 - #[error("model snapshot store operation failed: {message}")] - OperationFailed { - /// 错误说明。 - message: String, - }, -} - -/// 模型快照存储结果类型。 -pub type ModelSnapshotStoreResult = Result; - -/// 模型快照存储端口。 -#[async_trait] -pub trait ModelSnapshotStore: Send + Sync + 'static { - /// 用单个计划快照替换同名快照。 - async fn replace_plan_snapshot( - &self, - snapshot: &ModelPlanSnapshot, - ) -> ModelSnapshotStoreResult<()>; - - /// 列出所有计划快照。 - async fn list_plan_snapshots(&self) -> ModelSnapshotStoreResult>; -} - -/// SQLite 模型快照存储。 -#[derive(Clone)] -pub struct SqliteModelSnapshotStore { - pool: sqlx::SqlitePool, -} - -impl SqliteModelSnapshotStore { - /// 使用给定连接池构造存储。 - pub fn new(pool: sqlx::SqlitePool) -> Self { - Self { pool } - } -} - -#[async_trait] -impl ModelSnapshotStore for SqliteModelSnapshotStore { - async fn replace_plan_snapshot( - &self, - snapshot: &ModelPlanSnapshot, - ) -> ModelSnapshotStoreResult<()> { - let now = chrono::Utc::now().to_rfc3339(); - let models_json = serde_json::to_string(&snapshot.models).map_err(|e| { - ModelSnapshotStoreError::OperationFailed { - message: e.to_string(), - } - })?; - sqlx::query( - "insert or replace into model_plan_snapshots (plan_type, models_json, fetched_at) values (?, ?, ?)", - ) - .bind(&snapshot.plan_type) - .bind(&models_json) - .bind(&now) - .execute(&self.pool) - .await - .map_err(|e| ModelSnapshotStoreError::OperationFailed { - message: e.to_string(), - })?; - Ok(()) - } - - async fn list_plan_snapshots(&self) -> ModelSnapshotStoreResult> { - let rows = sqlx::query("select plan_type, models_json from model_plan_snapshots") - .fetch_all(&self.pool) - .await - .map_err(|e| ModelSnapshotStoreError::OperationFailed { - message: e.to_string(), - })?; - let mut snapshots = Vec::new(); - for row in rows { - let plan_type: String = row.get("plan_type"); - let models_json: String = row.get("models_json"); - let models: Vec = serde_json::from_str(&models_json).map_err(|e| { - ModelSnapshotStoreError::OperationFailed { - message: e.to_string(), - } - })?; - snapshots.push(ModelPlanSnapshot { plan_type, models }); - } - Ok(snapshots) - } -} - -// --------------------------------------------------------------------------- -// 模型目录聚合 -// --------------------------------------------------------------------------- - -use std::collections::BTreeSet; - -const SERVICE_TIER_SUFFIXES: [&str; 2] = ["fast", "flex"]; -const REASONING_EFFORT_SUFFIXES: [&str; 6] = ["none", "minimal", "low", "medium", "high", "xhigh"]; -const BUILTIN_CODEX_MODELS: [(&str, &str, bool); 8] = [ - ("gpt-5.5", "GPT-5.5", true), - ("gpt-5.4", "GPT-5.4", false), - ("gpt-5.4-mini", "GPT-5.4 Mini", false), - ("gpt-5.3-codex", "GPT-5.3 Codex", false), - ("gpt-5.3-codex-spark", "GPT-5.3 Codex Spark", false), - ("codex-auto-review", "Codex Auto Review", false), - ("gpt-5.2", "GPT-5.2", false), - ("gpt-image-1", "GPT Image 1", false), -]; - -/// 模型目录聚合。 -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ModelCatalog { - models: Vec, - model_aliases: BTreeMap, - model_plan_index: BTreeMap>, - fetched_plan_types: BTreeSet, -} - -impl ModelPlanSnapshot { - /// 将上游模型条目标准化为可持久化快照。 - pub fn from_backend_entries( - plan_type: impl Into, - entries: Vec, - ) -> Self { - Self { - plan_type: plan_type.into(), - models: entries.into_iter().map(normalize_backend_model).collect(), - } - } -} - -impl ModelCatalog { - /// 从静态配置构造模型目录。 - pub fn from_config(config: &ModelConfig) -> Self { - let model_aliases = normalize_aliases(&config.model_aliases); - Self { - models: builtin_codex_models(), - model_aliases, - model_plan_index: BTreeMap::new(), - fetched_plan_types: BTreeSet::new(), - } - } - - /// 从静态配置和后端快照构造模型目录。 - pub fn from_config_and_snapshots( - config: &ModelConfig, - snapshots: &[ModelPlanSnapshot], - ) -> Self { - if snapshots.is_empty() { - return Self::from_config(config); - } - - let model_aliases = normalize_aliases(&config.model_aliases); - let mut models_by_id = BTreeMap::new(); - let mut model_order = Vec::new(); - let mut model_plan_index: BTreeMap> = BTreeMap::new(); - let mut fetched_plan_types = BTreeSet::new(); - - for snapshot in snapshots { - fetched_plan_types.insert(snapshot.plan_type.clone()); - for model in &snapshot.models { - if !models_by_id.contains_key(&model.id) { - model_order.push(model.id.clone()); - } - models_by_id.insert(model.id.clone(), model.clone()); - let plans = model_plan_index.entry(model.id.clone()).or_default(); - if !plans.contains(&snapshot.plan_type) { - plans.push(snapshot.plan_type.clone()); - } - } - } - - let models = model_order - .into_iter() - .filter_map(|id| models_by_id.remove(&id)) - .collect::>(); - if models.is_empty() { - return Self { - models: builtin_codex_models(), - model_aliases, - model_plan_index, - fetched_plan_types, - }; - } - - Self { - models, - model_aliases, - model_plan_index, - fetched_plan_types, - } - } - - /// 返回对外可见的模型列表副本。 - pub fn models(&self) -> Vec { - self.models.clone() - } - - /// 返回 OpenAI `/v1/models` 对外暴露的模型 ID。 - pub fn public_model_ids(&self) -> Vec { - let mut seen = BTreeSet::new(); - let mut ids = Vec::new(); - for model in &self.models { - if seen.insert(model.id.clone()) { - ids.push(model.id.clone()); - } - } - for alias in self.model_aliases.keys() { - if seen.insert(alias.clone()) { - ids.push(alias.clone()); - } - } - ids - } - - /// 返回模型数量。 - pub fn len(&self) -> usize { - self.models.len() - } - - /// 模型目录是否为空。 - pub fn is_empty(&self) -> bool { - self.models.is_empty() - } - - /// 返回指定订阅计划可用的模型列表。 - pub fn models_for_plan(&self, plan_type: &str) -> Vec { - self.models - .iter() - .filter(|model| { - self.model_plan_index - .get(&model.id) - .is_some_and(|plans| plans.iter().any(|plan| plan == plan_type)) - }) - .cloned() - .collect() - } - - /// 按模型 ID 查询模型信息。 - pub fn model_info(&self, model_id: &str) -> Option { - self.models - .iter() - .find(|model| model.id == model_id) - .cloned() - } - - /// 按对外模型名查询模型信息,支持别名和已知后缀。 - pub fn model_info_for_name(&self, input: &str) -> Option { - let parsed = self.parse_model_name(input); - self.model_info(&parsed.model_id) - } - - /// 返回 model -> plans allowlist。 - pub fn model_plan_allowlist(&self) -> BTreeMap> { - self.model_plan_index.clone() - } - - /// 返回已成功拉取过模型列表的订阅计划。 - pub fn fetched_plan_types(&self) -> BTreeSet { - self.fetched_plan_types.clone() - } - - /// 判断输入模型名是否在目录中可识别。 - pub fn is_recognized_model_name(&self, input: &str) -> bool { - let trimmed = input.trim(); - if trimmed.is_empty() { - return false; - } - if self.model_aliases.contains_key(trimmed) || self.model_info(trimmed).is_some() { - return true; - } - - let stripped = strip_known_model_suffixes(trimmed); - if stripped.model_name == trimmed - || (stripped.reasoning_effort.is_none() && stripped.service_tier.is_none()) - { - return false; - } - self.model_aliases.contains_key(&stripped.model_name) - || self.model_info(&stripped.model_name).is_some() - } - - /// 解析外部传入的模型名,提取别名、推理强度和服务层级后缀。 - pub fn parse_model_name(&self, input: &str) -> ParsedModelName { - let trimmed = input.trim(); - if self.model_aliases.contains_key(trimmed) || self.model_info(trimmed).is_some() { - return ParsedModelName { - model_id: self.resolve_model_id(trimmed), - reasoning_effort: None, - service_tier: None, - }; - } - - let stripped = strip_known_model_suffixes(trimmed); - ParsedModelName { - model_id: self.resolve_model_id(&stripped.model_name), - reasoning_effort: stripped.reasoning_effort, - service_tier: stripped.service_tier, - } - } - - /// 将标准化模型名重新拼成展示名。 - pub fn build_display_model_name(parsed: &ParsedModelName) -> String { - let mut name = parsed.model_id.clone(); - if let Some(reasoning_effort) = &parsed.reasoning_effort { - name.push('-'); - name.push_str(reasoning_effort); - } - if let Some(service_tier) = &parsed.service_tier { - name.push('-'); - name.push_str(service_tier); - } - name - } - - fn resolve_model_id(&self, input: &str) -> String { - self.resolve_alias_chain(input) - } - - fn resolve_alias_chain(&self, input: &str) -> String { - let original = input.trim(); - let mut current = original.to_string(); - let mut seen = BTreeSet::new(); - for _ in 0..20 { - let Some(target) = self.model_aliases.get(¤t).map(|value| value.trim()) else { - return current; - }; - if !seen.insert(current.clone()) || seen.contains(target) { - return original.to_string(); - } - current = target.to_string(); - } - original.to_string() - } -} - -#[derive(Debug, Clone, PartialEq, Eq)] -struct StrippedModelName { - model_name: String, - reasoning_effort: Option, - service_tier: Option, -} - -fn strip_known_model_suffixes(input: &str) -> StrippedModelName { - let mut remaining = input.trim().to_string(); - let service_tier = take_suffix(&mut remaining, &SERVICE_TIER_SUFFIXES); - let reasoning_effort = take_suffix(&mut remaining, &REASONING_EFFORT_SUFFIXES); - StrippedModelName { - model_name: remaining, - reasoning_effort, - service_tier, - } -} - -fn take_suffix(remaining: &mut String, suffixes: &[&str]) -> Option { - let suffix = suffixes - .iter() - .find(|suffix| remaining.ends_with(&format!("-{suffix}")))?; - let truncate_to = remaining.len() - suffix.len() - 1; - remaining.truncate(truncate_to); - Some((*suffix).to_string()) -} - -fn normalize_aliases(input: &BTreeMap) -> BTreeMap { - input - .iter() - .filter_map(|(alias, target)| { - let alias = alias.trim(); - let target = target.trim(); - (!alias.is_empty() && !target.is_empty()) - .then(|| (alias.to_string(), target.to_string())) - }) - .collect() -} - -fn builtin_codex_models() -> Vec { - BUILTIN_CODEX_MODELS - .into_iter() - .map(|(id, display_name, is_default)| CodexModelInfo { - id: id.to_string(), - display_name: display_name.to_string(), - description: String::new(), - is_default, - supported_reasoning_efforts: default_reasoning_efforts(), - default_reasoning_effort: "medium".to_string(), - input_modalities: vec!["text".to_string()], - output_modalities: vec!["text".to_string()], - supports_personality: false, - upgrade: None, - source: "builtin".to_string(), - context_window: None, - max_context_window: None, - max_output_tokens: None, - truncation_policy_limit: None, - }) - .collect() -} - -fn default_reasoning_efforts() -> Vec { - ["minimal", "low", "medium", "high"] - .into_iter() - .map(|reasoning_effort| ReasoningEffortInfo { - reasoning_effort: reasoning_effort.to_string(), - description: String::new(), - }) - .collect() -} - -fn normalize_backend_model(raw: BackendModelEntry) -> CodexModelInfo { - let id = first_non_empty([raw.slug.as_deref(), raw.id.as_deref(), raw.name.as_deref()]) - .unwrap_or("unknown") - .to_string(); - let display_name = first_non_empty([ - raw.display_name.as_deref(), - raw.title.as_deref(), - raw.name.as_deref(), - ]) - .unwrap_or(&id) - .to_string(); - let reasoning_entries = if raw.supported_reasoning_efforts.is_empty() { - raw.supported_reasoning_levels - } else { - raw.supported_reasoning_efforts - }; - let mut supported_reasoning_efforts = reasoning_entries - .into_iter() - .filter_map(normalize_backend_reasoning_effort) - .collect::>(); - if supported_reasoning_efforts.is_empty() { - supported_reasoning_efforts.push(ReasoningEffortInfo { - reasoning_effort: "medium".to_string(), - description: "Default".to_string(), - }); - } - let default_reasoning_effort = first_non_empty([ - raw.default_reasoning_effort.as_deref(), - raw.default_reasoning_level.as_deref(), - ]) - .unwrap_or("medium") - .to_string(); - - CodexModelInfo { - id, - display_name, - description: raw.description.unwrap_or_default(), - is_default: raw.is_default.unwrap_or(false), - supported_reasoning_efforts, - default_reasoning_effort, - input_modalities: raw - .input_modalities - .unwrap_or_else(|| vec!["text".to_string()]), - output_modalities: raw - .output_modalities - .unwrap_or_else(|| vec!["text".to_string()]), - supports_personality: raw.supports_personality.unwrap_or(false), - upgrade: raw.upgrade, - source: "backend".to_string(), - context_window: raw.context_window, - max_context_window: raw.max_context_window, - max_output_tokens: raw.max_output_tokens, - truncation_policy_limit: raw.truncation_policy.and_then(|policy| policy.limit), - } -} - -fn normalize_backend_reasoning_effort(raw: BackendReasoningEffort) -> Option { - let reasoning_effort = - first_non_empty([raw.reasoning_effort.as_deref(), raw.effort.as_deref()])?.to_string(); - Some(ReasoningEffortInfo { - description: raw.description.unwrap_or_default(), - reasoning_effort, - }) -} - -fn first_non_empty<'a>(values: impl IntoIterator>) -> Option<&'a str> { - values - .into_iter() - .flatten() - .map(str::trim) - .find(|value| !value.is_empty()) -} - -// --------------------------------------------------------------------------- -// 模型目录服务 -// --------------------------------------------------------------------------- - -use crate::upstream::transport::{CodexModelCatalogClient, CodexModelCatalogRequest}; - -/// 模型刷新摘要。 -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct ModelRefreshResult { - /// 成功刷新并写入的计划数。 - pub refreshed_plans: usize, - /// 本次成功写入的模型数。 - pub model_count: usize, - /// 刷新失败的计划数。 - pub failed_plans: usize, -} - -/// 模型服务错误。 -#[derive(Debug, Error, PartialEq, Eq)] -pub enum ModelServiceError { - /// 没有注入快照存储。 - #[error("model snapshot store is unavailable")] - SnapshotStoreUnavailable, - /// 没有注入上游模型客户端。 - #[error("model catalog client is unavailable")] - UpstreamClientUnavailable, - /// 没有可用账号。 - #[error("no active accounts available for model refresh")] - NoAccounts, - /// 快照写入失败。 - #[error("failed to store model snapshot")] - StoreSnapshot, - /// 刷新后重新读取快照失败。 - #[error("failed to load model snapshots")] - LoadSnapshots, - /// 所有计划都刷新失败。 - #[error("all model refresh plans failed")] - AllPlansFailed(ModelRefreshResult), -} - -/// 模型到可用计划的映射。 -pub type ModelPlanAllowlist = BTreeMap>; - -/// 模型调度约束快照。 -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct ModelPlanRouting { - /// 模型到允许订阅计划的映射。 - pub allowlist: ModelPlanAllowlist, - /// 已成功拉取过模型列表的订阅计划。 - pub fetched_plan_types: BTreeSet, -} - -/// 模型刷新用的计划账号。 -#[derive(Debug, Clone)] -pub struct ModelRefreshPlanAccount { - /// 订阅计划类型。 - pub plan_type: String, - /// 用于刷新该计划模型列表的账号。 - pub account: Account, -} - -/// 模型目录服务。 -#[derive(Clone)] -pub struct ModelService { - config: Arc>, - snapshots: Arc>>, - catalog: Arc>, - snapshot_store: Option>, - upstream_client: Option>, -} - -impl ModelService { - /// 构造模型服务。 - pub fn new( - config: ModelConfig, - snapshot_store: Option>, - upstream_client: Option>, - ) -> Self { - let catalog = ModelCatalog::from_config(&config); - Self { - config: Arc::new(RwLock::new(config)), - snapshots: Arc::new(RwLock::new(Vec::new())), - catalog: Arc::new(RwLock::new(catalog)), - snapshot_store, - upstream_client, - } - } - - /// 更新模型服务配置。 - pub fn update_config(&self, config: ModelConfig) { - *self - .config - .write() - .unwrap_or_else(std::sync::PoisonError::into_inner) = config; - self.rebuild_catalog_from_memory(); - } - - /// 从快照存储加载运行时内存模型目录。 - pub async fn reload_from_store(&self) -> Result<(), ModelServiceError> { - let Some(snapshot_store) = self.snapshot_store.as_ref() else { - self.replace_snapshots(Vec::new()); - return Ok(()); - }; - let snapshots = snapshot_store - .list_plan_snapshots() - .await - .map_err(map_load_snapshots_error)?; - self.replace_snapshots(snapshots); - Ok(()) - } - - /// 构造当前对外暴露的模型目录。 - pub async fn catalog(&self) -> ModelCatalog { - self.cached_catalog() - } - - /// 使用运行时 installation id 刷新活跃账号对应的后端模型目录。 - pub async fn refresh_backend_models_with_installation_id( - &self, - plan_accounts: &[ModelRefreshPlanAccount], - request_id: &str, - installation_id: Option<&str>, - ) -> Result { - let snapshot_store = self - .snapshot_store - .as_ref() - .ok_or(ModelServiceError::SnapshotStoreUnavailable)?; - let upstream_client = self - .upstream_client - .as_ref() - .ok_or(ModelServiceError::UpstreamClientUnavailable)?; - - if plan_accounts.is_empty() { - return Err(ModelServiceError::NoAccounts); - } - - let mut result = ModelRefreshResult { - refreshed_plans: 0, - model_count: 0, - failed_plans: 0, - }; - - for plan_account in plan_accounts { - let request = CodexModelCatalogRequest { - access_token: &plan_account.account.access_token, - account_id: plan_account.account.account_id.as_deref(), - request_id, - installation_id, - plan_type: &plan_account.plan_type, - }; - - let entries = match upstream_client.fetch_models(&request).await { - Ok(entries) if !entries.is_empty() => entries, - Ok(_) => { - result.failed_plans += 1; - continue; - } - Err(error) => { - tracing::warn!(error = %error, plan_type = %plan_account.plan_type, "刷新后端模型失败"); - result.failed_plans += 1; - continue; - } - }; - - let snapshot = - ModelPlanSnapshot::from_backend_entries(plan_account.plan_type.clone(), entries); - result.model_count += snapshot.models.len(); - snapshot_store - .replace_plan_snapshot(&snapshot) - .await - .map_err(map_store_snapshot_error)?; - result.refreshed_plans += 1; - } - - if result.refreshed_plans == 0 { - return Err(ModelServiceError::AllPlansFailed(result)); - } - - self.reload_from_store().await?; - - Ok(result) - } - - /// 读取当前缓存的 model -> plans allowlist。 - pub async fn model_plan_allowlist(&self) -> Result { - Ok(self.model_plan_routing().await?.allowlist) - } - - /// 读取当前缓存的模型调度约束。 - pub async fn model_plan_routing(&self) -> Result { - let catalog = self.cached_catalog(); - Ok(ModelPlanRouting { - allowlist: catalog.model_plan_allowlist(), - fetched_plan_types: catalog.fetched_plan_types(), - }) - } - - fn cached_catalog(&self) -> ModelCatalog { - self.catalog - .read() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .clone() - } - - fn replace_snapshots(&self, snapshots: Vec) { - *self - .snapshots - .write() - .unwrap_or_else(std::sync::PoisonError::into_inner) = snapshots; - self.rebuild_catalog_from_memory(); - } - - fn rebuild_catalog_from_memory(&self) { - let config = self.config_snapshot(); - let snapshots = self - .snapshots - .read() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .clone(); - let catalog = if snapshots.is_empty() { - ModelCatalog::from_config(&config) - } else { - ModelCatalog::from_config_and_snapshots(&config, &snapshots) - }; - *self - .catalog - .write() - .unwrap_or_else(std::sync::PoisonError::into_inner) = catalog; - } - - fn config_snapshot(&self) -> ModelConfig { - self.config - .read() - .unwrap_or_else(std::sync::PoisonError::into_inner) - .clone() - } -} - -fn map_store_snapshot_error(_: ModelSnapshotStoreError) -> ModelServiceError { - ModelServiceError::StoreSnapshot -} - -fn map_load_snapshots_error(_: ModelSnapshotStoreError) -> ModelServiceError { - ModelServiceError::LoadSnapshots -} +//! 模型目录领域。 + +pub mod backend_entry; +pub mod catalog; +pub mod config; +pub mod info; +pub mod service; +pub mod snapshot; +pub mod snapshot_store; diff --git a/backend/src/upstream/models/service.rs b/backend/src/upstream/models/service.rs new file mode 100644 index 000000000..e98c50b98 --- /dev/null +++ b/backend/src/upstream/models/service.rs @@ -0,0 +1,260 @@ +//! 模型目录刷新服务。 + +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::{Arc, RwLock}, +}; + +use thiserror::Error; + +use crate::upstream::{ + accounts::model::Account, + transport::{CodexModelCatalogClient, CodexModelCatalogRequest}, +}; + +use super::{ + catalog::ModelCatalog, + config::ModelConfig, + snapshot::ModelPlanSnapshot, + snapshot_store::{ModelSnapshotStore, ModelSnapshotStoreError}, +}; + +/// 模型刷新摘要。 +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ModelRefreshResult { + /// 成功刷新并写入的计划数。 + pub refreshed_plans: usize, + /// 本次成功写入的模型数。 + pub model_count: usize, + /// 刷新失败的计划数。 + pub failed_plans: usize, +} + +/// 模型服务错误。 +#[derive(Debug, Error, PartialEq, Eq)] +pub enum ModelServiceError { + /// 没有注入快照存储。 + #[error("model snapshot store is unavailable")] + SnapshotStoreUnavailable, + /// 没有注入上游模型客户端。 + #[error("model catalog client is unavailable")] + UpstreamClientUnavailable, + /// 没有可用账号。 + #[error("no active accounts available for model refresh")] + NoAccounts, + /// 快照写入失败。 + #[error("failed to store model snapshot")] + StoreSnapshot, + /// 刷新后重新读取快照失败。 + #[error("failed to load model snapshots")] + LoadSnapshots, + /// 所有计划都刷新失败。 + #[error("all model refresh plans failed")] + AllPlansFailed(ModelRefreshResult), +} + +/// 模型到可用计划的映射。 +pub type ModelPlanAllowlist = BTreeMap>; + +/// 模型调度约束快照。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ModelPlanRouting { + /// 模型到允许订阅计划的映射。 + pub allowlist: ModelPlanAllowlist, + /// 已成功拉取过模型列表的订阅计划。 + pub fetched_plan_types: BTreeSet, +} + +/// 模型刷新用的计划账号。 +#[derive(Debug, Clone)] +pub struct ModelRefreshPlanAccount { + /// 订阅计划类型。 + pub plan_type: String, + /// 用于刷新该计划模型列表的账号。 + pub account: Account, +} + +/// 模型目录服务。 +#[derive(Clone)] +pub struct ModelService { + config: Arc>, + snapshots: Arc>>, + catalog: Arc>, + snapshot_store: Option>, + upstream_client: Option>, +} + +impl ModelService { + /// 构造模型服务。 + pub fn new( + config: ModelConfig, + snapshot_store: Option>, + upstream_client: Option>, + ) -> Self { + let catalog = ModelCatalog::from_config(&config); + Self { + config: Arc::new(RwLock::new(config)), + snapshots: Arc::new(RwLock::new(Vec::new())), + catalog: Arc::new(RwLock::new(catalog)), + snapshot_store, + upstream_client, + } + } + + /// 更新模型服务配置。 + pub fn update_config(&self, config: ModelConfig) { + *self + .config + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) = config; + self.rebuild_catalog_from_memory(); + } + + /// 从快照存储加载运行时内存模型目录。 + pub async fn reload_from_store(&self) -> Result<(), ModelServiceError> { + let Some(snapshot_store) = self.snapshot_store.as_ref() else { + self.replace_snapshots(Vec::new()); + return Ok(()); + }; + let snapshots = snapshot_store + .list_plan_snapshots() + .await + .map_err(map_load_snapshots_error)?; + self.replace_snapshots(snapshots); + Ok(()) + } + + /// 构造当前对外暴露的模型目录。 + pub async fn catalog(&self) -> ModelCatalog { + self.cached_catalog() + } + + /// 使用运行时 installation id 刷新活跃账号对应的后端模型目录。 + pub async fn refresh_backend_models_with_installation_id( + &self, + plan_accounts: &[ModelRefreshPlanAccount], + request_id: &str, + installation_id: Option<&str>, + ) -> Result { + let snapshot_store = self + .snapshot_store + .as_ref() + .ok_or(ModelServiceError::SnapshotStoreUnavailable)?; + let upstream_client = self + .upstream_client + .as_ref() + .ok_or(ModelServiceError::UpstreamClientUnavailable)?; + + if plan_accounts.is_empty() { + return Err(ModelServiceError::NoAccounts); + } + + let mut result = ModelRefreshResult { + refreshed_plans: 0, + model_count: 0, + failed_plans: 0, + }; + + for plan_account in plan_accounts { + let request = CodexModelCatalogRequest { + access_token: &plan_account.account.access_token, + account_id: plan_account.account.account_id.as_deref(), + request_id, + installation_id, + plan_type: &plan_account.plan_type, + }; + + let entries = match upstream_client.fetch_models(&request).await { + Ok(entries) if !entries.is_empty() => entries, + Ok(_) => { + result.failed_plans += 1; + continue; + } + Err(error) => { + tracing::warn!(error = %error, plan_type = %plan_account.plan_type, "刷新后端模型失败"); + result.failed_plans += 1; + continue; + } + }; + + let snapshot = + ModelPlanSnapshot::from_backend_entries(plan_account.plan_type.clone(), entries); + result.model_count += snapshot.models.len(); + snapshot_store + .replace_plan_snapshot(&snapshot) + .await + .map_err(map_store_snapshot_error)?; + result.refreshed_plans += 1; + } + + if result.refreshed_plans == 0 { + return Err(ModelServiceError::AllPlansFailed(result)); + } + + self.reload_from_store().await?; + + Ok(result) + } + + /// 读取当前缓存的 model -> plans allowlist。 + pub async fn model_plan_allowlist(&self) -> Result { + Ok(self.model_plan_routing().await?.allowlist) + } + + /// 读取当前缓存的模型调度约束。 + pub async fn model_plan_routing(&self) -> Result { + let catalog = self.cached_catalog(); + Ok(ModelPlanRouting { + allowlist: catalog.model_plan_allowlist(), + fetched_plan_types: catalog.fetched_plan_types(), + }) + } + + fn cached_catalog(&self) -> ModelCatalog { + self.catalog + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + } + + fn replace_snapshots(&self, snapshots: Vec) { + *self + .snapshots + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) = snapshots; + self.rebuild_catalog_from_memory(); + } + + fn rebuild_catalog_from_memory(&self) { + let config = self.config_snapshot(); + let snapshots = self + .snapshots + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone(); + let catalog = if snapshots.is_empty() { + ModelCatalog::from_config(&config) + } else { + ModelCatalog::from_config_and_snapshots(&config, &snapshots) + }; + *self + .catalog + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) = catalog; + } + + fn config_snapshot(&self) -> ModelConfig { + self.config + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .clone() + } +} + +fn map_store_snapshot_error(_: ModelSnapshotStoreError) -> ModelServiceError { + ModelServiceError::StoreSnapshot +} + +fn map_load_snapshots_error(_: ModelSnapshotStoreError) -> ModelServiceError { + ModelServiceError::LoadSnapshots +} diff --git a/backend/src/upstream/models/snapshot.rs b/backend/src/upstream/models/snapshot.rs new file mode 100644 index 000000000..3f9ef7f6f --- /dev/null +++ b/backend/src/upstream/models/snapshot.rs @@ -0,0 +1,15 @@ +//! 模型计划快照。 + +use serde::{Deserialize, Serialize}; + +use super::info::CodexModelInfo; + +/// 按计划类型持久化的模型快照。 +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct ModelPlanSnapshot { + /// 订阅计划类型。 + pub plan_type: String, + /// 该计划可见的模型列表。 + pub models: Vec, +} diff --git a/backend/src/upstream/models/snapshot_store.rs b/backend/src/upstream/models/snapshot_store.rs new file mode 100644 index 000000000..40882381e --- /dev/null +++ b/backend/src/upstream/models/snapshot_store.rs @@ -0,0 +1,95 @@ +//! 模型计划快照存储。 + +use async_trait::async_trait; +use sqlx::Row; +use thiserror::Error; + +use super::{info::CodexModelInfo, snapshot::ModelPlanSnapshot}; + +/// 模型快照存储错误。 +#[derive(Debug, Error)] +pub enum ModelSnapshotStoreError { + /// 底层存储失败。 + #[error("model snapshot store operation failed: {message}")] + OperationFailed { + /// 错误说明。 + message: String, + }, +} + +/// 模型快照存储结果类型。 +pub type ModelSnapshotStoreResult = Result; + +/// 模型快照存储端口。 +#[async_trait] +pub trait ModelSnapshotStore: Send + Sync + 'static { + /// 用单个计划快照替换同名快照。 + async fn replace_plan_snapshot( + &self, + snapshot: &ModelPlanSnapshot, + ) -> ModelSnapshotStoreResult<()>; + + /// 列出所有计划快照。 + async fn list_plan_snapshots(&self) -> ModelSnapshotStoreResult>; +} + +/// SQLite 模型快照存储。 +#[derive(Clone)] +pub struct SqliteModelSnapshotStore { + pool: sqlx::SqlitePool, +} + +impl SqliteModelSnapshotStore { + /// 使用给定连接池构造存储。 + pub fn new(pool: sqlx::SqlitePool) -> Self { + Self { pool } + } +} + +#[async_trait] +impl ModelSnapshotStore for SqliteModelSnapshotStore { + async fn replace_plan_snapshot( + &self, + snapshot: &ModelPlanSnapshot, + ) -> ModelSnapshotStoreResult<()> { + let now = chrono::Utc::now().to_rfc3339(); + let models_json = serde_json::to_string(&snapshot.models).map_err(|e| { + ModelSnapshotStoreError::OperationFailed { + message: e.to_string(), + } + })?; + sqlx::query( + "insert or replace into model_plan_snapshots (plan_type, models_json, fetched_at) values (?, ?, ?)", + ) + .bind(&snapshot.plan_type) + .bind(&models_json) + .bind(&now) + .execute(&self.pool) + .await + .map_err(|e| ModelSnapshotStoreError::OperationFailed { + message: e.to_string(), + })?; + Ok(()) + } + + async fn list_plan_snapshots(&self) -> ModelSnapshotStoreResult> { + let rows = sqlx::query("select plan_type, models_json from model_plan_snapshots") + .fetch_all(&self.pool) + .await + .map_err(|e| ModelSnapshotStoreError::OperationFailed { + message: e.to_string(), + })?; + let mut snapshots = Vec::new(); + for row in rows { + let plan_type: String = row.get("plan_type"); + let models_json: String = row.get("models_json"); + let models: Vec = serde_json::from_str(&models_json).map_err(|e| { + ModelSnapshotStoreError::OperationFailed { + message: e.to_string(), + } + })?; + snapshots.push(ModelPlanSnapshot { plan_type, models }); + } + Ok(snapshots) + } +} diff --git a/backend/src/upstream/protocol/responses.rs b/backend/src/upstream/protocol/responses.rs index 3f638dcf2..1f3eef698 100644 --- a/backend/src/upstream/protocol/responses.rs +++ b/backend/src/upstream/protocol/responses.rs @@ -6,7 +6,7 @@ use serde_json::{json, Map, Value}; use crate::{ infra::time::elapsed_millis_i64, upstream::{ - models::ParsedModelName, + models::catalog::ParsedModelName, protocol::{ schema::reconvert_tuple_values, sse::{parse_sse_events, SseError, SseEvent}, diff --git a/backend/src/upstream/transport/client.rs b/backend/src/upstream/transport/client.rs index b76c3bf4f..81b0c7631 100644 --- a/backend/src/upstream/transport/client.rs +++ b/backend/src/upstream/transport/client.rs @@ -23,7 +23,7 @@ use tokio_tungstenite::tungstenite::handshake::client::generate_key; use uuid::Uuid; use crate::upstream::fingerprint::Fingerprint; -use crate::upstream::models::BackendModelEntry; +use crate::upstream::models::backend_entry::BackendModelEntry; use crate::upstream::protocol::events::extract_sse_usage; use crate::upstream::protocol::responses::{ http_sse_fallback_allowed, transport_for_request, CodexCompactRequest, CodexResponsesRequest, diff --git a/backend/tests/admin/monitoring/usage_record_routes.rs b/backend/tests/admin/monitoring/usage_record_routes.rs index 2a15b4c44..f49bcc2a9 100644 --- a/backend/tests/admin/monitoring/usage_record_routes.rs +++ b/backend/tests/admin/monitoring/usage_record_routes.rs @@ -10,7 +10,7 @@ use codex_proxy_rs::{ usage_record_model::{UsageRecord, UsageRecordLevel}, usage_record_store::SqliteUsageRecordStore, }, - config::types::AppConfig, + config::schema::AppConfig, infra::database::connect_sqlite, proxy::dispatch::session_affinity::SqliteSessionAffinityStore, runtime::services::{BackgroundTaskStores, Services}, diff --git a/backend/tests/admin/settings/routes.rs b/backend/tests/admin/settings/routes.rs index 0a6bbf254..c8a8253f2 100644 --- a/backend/tests/admin/settings/routes.rs +++ b/backend/tests/admin/settings/routes.rs @@ -12,7 +12,7 @@ use codex_proxy_rs::{ admin::auth::service::SqliteAdminSessionStore, admin::keys::service::SqliteClientKeyStore, admin::monitoring::usage_record_store::SqliteUsageRecordStore, - config::{settings::RuntimeSettingsService, types::AppConfig}, + config::{schema::AppConfig, settings::RuntimeSettingsService}, infra::database::connect_sqlite, proxy::dispatch::session_affinity::SqliteSessionAffinityStore, runtime::services::{BackgroundTaskStores, Services}, diff --git a/backend/tests/config/mod.rs b/backend/tests/config/mod.rs index 6ea8a3b6c..3000fa683 100644 --- a/backend/tests/config/mod.rs +++ b/backend/tests/config/mod.rs @@ -1,6 +1,6 @@ +use codex_proxy_rs::config::schema::LoggingConfig; +use codex_proxy_rs::config::schema::{AdminConfig, AdminConfigError, AppConfig}; use codex_proxy_rs::config::settings::account_pool_options_from_config; -use codex_proxy_rs::config::types::LoggingConfig; -use codex_proxy_rs::config::types::{AdminConfig, AdminConfigError, AppConfig}; use serde::de::DeserializeOwned; use std::fs; diff --git a/backend/tests/http/web_assets/mod.rs b/backend/tests/http/web_assets/mod.rs index 8d8844868..a8e43dfed 100644 --- a/backend/tests/http/web_assets/mod.rs +++ b/backend/tests/http/web_assets/mod.rs @@ -5,7 +5,7 @@ use axum::{ http::{header, Request, StatusCode}, Router, }; -use codex_proxy_rs::{config::types::AppConfig, infra::database::connect_sqlite}; +use codex_proxy_rs::{config::schema::AppConfig, infra::database::connect_sqlite}; use serde_json::Value; use sqlx::SqlitePool; use tower::ServiceExt; diff --git a/backend/tests/proxy/dispatch/chat_upstream/mod.rs b/backend/tests/proxy/dispatch/chat_upstream/mod.rs index 60a9c8cea..97cc7a9a4 100644 --- a/backend/tests/proxy/dispatch/chat_upstream/mod.rs +++ b/backend/tests/proxy/dispatch/chat_upstream/mod.rs @@ -20,7 +20,7 @@ use codex_proxy_rs::{ SqliteUsageRecordStore, UsageRecordFilter, DEFAULT_USAGE_RECORD_CAPACITY, }, }, - config::types::AppConfig, + config::schema::AppConfig, http::router, infra::database::connect_sqlite, proxy::dispatch::session_affinity::{ diff --git a/backend/tests/proxy/openai/models_routes.rs b/backend/tests/proxy/openai/models_routes.rs index 0bd0c3e9b..7ff54d8fa 100644 --- a/backend/tests/proxy/openai/models_routes.rs +++ b/backend/tests/proxy/openai/models_routes.rs @@ -149,7 +149,7 @@ async fn test_app_with_aliases( async fn build_test_app( pool: sqlx::SqlitePool, - config: codex_proxy_rs::config::types::AppConfig, + config: codex_proxy_rs::config::schema::AppConfig, plaintext: Option, dir: tempfile::TempDir, ) -> (Router, Option, tempfile::TempDir) { diff --git a/backend/tests/runtime/tasks/mod.rs b/backend/tests/runtime/tasks/mod.rs index 228af33c6..7a4eb88ca 100644 --- a/backend/tests/runtime/tasks/mod.rs +++ b/backend/tests/runtime/tasks/mod.rs @@ -11,8 +11,8 @@ use codex_proxy_rs::upstream::accounts::model::{Account, AccountStatus}; use codex_proxy_rs::upstream::accounts::model::{AccountModelUsageDelta, AccountUsageDelta}; use codex_proxy_rs::upstream::accounts::store::{AccountStore, AccountStoreResult}; use codex_proxy_rs::upstream::fingerprint::FingerprintRepository; -use codex_proxy_rs::upstream::models::ModelConfig; -use codex_proxy_rs::upstream::models::ModelService; +use codex_proxy_rs::upstream::models::config::ModelConfig; +use codex_proxy_rs::upstream::models::service::ModelService; use wiremock::{ matchers::{method, path}, Mock, MockServer, ResponseTemplate, diff --git a/backend/tests/runtime/tasks/model_refresh.rs b/backend/tests/runtime/tasks/model_refresh.rs index e800e24ed..dd8c6eac8 100644 --- a/backend/tests/runtime/tasks/model_refresh.rs +++ b/backend/tests/runtime/tasks/model_refresh.rs @@ -4,7 +4,11 @@ use std::collections::BTreeMap; use codex_proxy_rs::upstream::{ accounts::pool::{AccountAcquireRequest, AccountPoolOptions, RuntimeAccountPoolService}, - models::{BackendModelEntry, ModelPlanSnapshot, ModelSnapshotStore, ModelSnapshotStoreResult}, + models::{ + backend_entry::BackendModelEntry, + snapshot::ModelPlanSnapshot, + snapshot_store::{ModelSnapshotStore, ModelSnapshotStoreResult}, + }, transport::{CodexModelCatalogClient, CodexModelCatalogClientError, CodexModelCatalogRequest}, }; diff --git a/backend/tests/support/config.rs b/backend/tests/support/config.rs index 851050d9b..132f14b98 100644 --- a/backend/tests/support/config.rs +++ b/backend/tests/support/config.rs @@ -1,6 +1,6 @@ use std::collections::BTreeMap; -use codex_proxy_rs::config::types::{ +use codex_proxy_rs::config::schema::{ AdminConfig, ApiConfig, AppConfig, AuthConfig, DatabaseConfig, FingerprintConfig, LoggingConfig, QuotaConfig, ServerConfig, TlsConfig, WebSocketPoolConfig, }; diff --git a/backend/tests/support/fingerprint.rs b/backend/tests/support/fingerprint.rs index f311c8bb0..3dc19f25e 100644 --- a/backend/tests/support/fingerprint.rs +++ b/backend/tests/support/fingerprint.rs @@ -1,4 +1,4 @@ -use codex_proxy_rs::{config::types::FingerprintConfig, upstream::fingerprint::Fingerprint}; +use codex_proxy_rs::{config::schema::FingerprintConfig, upstream::fingerprint::Fingerprint}; pub(crate) fn test_fingerprint() -> Fingerprint { Fingerprint::from_config(&FingerprintConfig::default()) diff --git a/backend/tests/upstream/fingerprint_integration/mod.rs b/backend/tests/upstream/fingerprint_integration/mod.rs index ebb0a9a41..c3c1ad4ad 100644 --- a/backend/tests/upstream/fingerprint_integration/mod.rs +++ b/backend/tests/upstream/fingerprint_integration/mod.rs @@ -1,7 +1,8 @@ use codex_proxy_rs::infra::database::connect_sqlite; -use codex_proxy_rs::upstream::models::ModelSnapshotStore as _; -use codex_proxy_rs::upstream::models::SqliteModelSnapshotStore; -use codex_proxy_rs::upstream::models::{BackendModelEntry, ModelPlanSnapshot}; +use codex_proxy_rs::upstream::models::backend_entry::BackendModelEntry; +use codex_proxy_rs::upstream::models::snapshot::ModelPlanSnapshot; +use codex_proxy_rs::upstream::models::snapshot_store::ModelSnapshotStore as _; +use codex_proxy_rs::upstream::models::snapshot_store::SqliteModelSnapshotStore; #[tokio::test] async fn runtime_state_should_expose_backend_model_snapshot_through_model_service() { diff --git a/backend/tests/upstream/models/catalog.rs b/backend/tests/upstream/models/catalog.rs index 6a301db1c..97e68d4fe 100644 --- a/backend/tests/upstream/models/catalog.rs +++ b/backend/tests/upstream/models/catalog.rs @@ -9,13 +9,17 @@ use std::{ use async_trait::async_trait; use codex_proxy_rs::upstream::accounts::model::{Account, AccountStatus}; -use codex_proxy_rs::upstream::models::{ - BackendModelEntry, BackendReasoningEffort, BackendTruncationPolicy, ModelConfig, - ModelPlanSnapshot, ModelRefreshPlanAccount, ParsedModelName, +use codex_proxy_rs::upstream::models::backend_entry::{ + BackendModelEntry, BackendReasoningEffort, BackendTruncationPolicy, }; -use codex_proxy_rs::upstream::models::{ - ModelCatalog, ModelRefreshResult, ModelService, ModelServiceError, ModelSnapshotStore, - ModelSnapshotStoreResult, +use codex_proxy_rs::upstream::models::catalog::{ModelCatalog, ParsedModelName}; +use codex_proxy_rs::upstream::models::config::ModelConfig; +use codex_proxy_rs::upstream::models::service::{ + ModelRefreshPlanAccount, ModelRefreshResult, ModelService, ModelServiceError, +}; +use codex_proxy_rs::upstream::models::snapshot::ModelPlanSnapshot; +use codex_proxy_rs::upstream::models::snapshot_store::{ + ModelSnapshotStore, ModelSnapshotStoreResult, }; use codex_proxy_rs::upstream::transport::{ CodexModelCatalogClient, CodexModelCatalogClientError, CodexModelCatalogRequest, diff --git a/backend/tests/upstream/models/store.rs b/backend/tests/upstream/models/store.rs index db21e9008..eb4251ea5 100644 --- a/backend/tests/upstream/models/store.rs +++ b/backend/tests/upstream/models/store.rs @@ -4,7 +4,11 @@ use codex_proxy_rs::upstream::{ model::AccountStatus, store::{AccountStore, SqliteAccountStore}, }, - models::{BackendModelEntry, ModelPlanSnapshot, ModelSnapshotStore, SqliteModelSnapshotStore}, + models::{ + backend_entry::BackendModelEntry, + snapshot::ModelPlanSnapshot, + snapshot_store::{ModelSnapshotStore, SqliteModelSnapshotStore}, + }, }; #[tokio::test] diff --git a/backend/tests/upstream/protocol/mod.rs b/backend/tests/upstream/protocol/mod.rs index dd0db209f..6bb271c9b 100644 --- a/backend/tests/upstream/protocol/mod.rs +++ b/backend/tests/upstream/protocol/mod.rs @@ -2,7 +2,7 @@ use codex_proxy_rs::proxy::openai::responses::{ response_failed_sse_event, translate_response_to_codex, translate_response_to_compact, OpenAiResponsesRequest, }; -use codex_proxy_rs::upstream::models::ParsedModelName; +use codex_proxy_rs::upstream::models::catalog::ParsedModelName; use codex_proxy_rs::upstream::protocol::events::{ extract_sse_usage, extract_usage, parse_rate_limit_headers, parse_rate_limits_event, rate_limit_quota, retry_after_seconds_from_body, RateLimitWindow, TokenUsage,