mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-27 08:01:04 +00:00
@@ -1,22 +1,31 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
/// Cloudflare Path Block Tracker
|
||||
///
|
||||
/// 追踪每个账户连续遇到的 Cloudflare path-block 404 错误。
|
||||
/// 当一个账户连续遇到 3 次 path-block 时,自动将其标记为 Banned。
|
||||
/// 当一个账户连续遇到 3 次 path-block 时,自动将其标记为 Disabled。
|
||||
///
|
||||
/// Path-block 的特征:
|
||||
/// - HTTP 404 状态码
|
||||
/// - 空响应体或 Cloudflare 页面
|
||||
/// - 通常发生在 /backend-api/responses 路径
|
||||
const PATH_BLOCK_THRESHOLD: u32 = 3;
|
||||
const PATH_BLOCK_STALE_AFTER: Duration = Duration::hours(1);
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct PathBlockState {
|
||||
count: u32,
|
||||
last_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CfPathBlockTracker {
|
||||
/// 每个账户的连续 path-block 计数
|
||||
counts: Arc<RwLock<HashMap<String, u32>>>,
|
||||
counts: Arc<RwLock<HashMap<String, PathBlockState>>>,
|
||||
}
|
||||
|
||||
impl Default for CfPathBlockTracker {
|
||||
@@ -37,9 +46,20 @@ impl CfPathBlockTracker {
|
||||
/// 返回当前连续计数,调用者应该在达到阈值时采取行动
|
||||
pub async fn record_path_block(&self, account_id: &str) -> u32 {
|
||||
let mut counts = self.counts.write().await;
|
||||
let count = counts.entry(account_id.to_string()).or_insert(0);
|
||||
*count += 1;
|
||||
*count
|
||||
let now = Utc::now();
|
||||
let count = counts
|
||||
.get(account_id)
|
||||
.filter(|state| now.signed_duration_since(state.last_at) <= PATH_BLOCK_STALE_AFTER)
|
||||
.map(|state| state.count + 1)
|
||||
.unwrap_or(1);
|
||||
counts.insert(
|
||||
account_id.to_string(),
|
||||
PathBlockState {
|
||||
count,
|
||||
last_at: now,
|
||||
},
|
||||
);
|
||||
count
|
||||
}
|
||||
|
||||
/// 重置账户的 path-block 计数(成功请求后调用)
|
||||
@@ -51,7 +71,13 @@ impl CfPathBlockTracker {
|
||||
/// 获取账户当前的 path-block 计数
|
||||
pub async fn get_count(&self, account_id: &str) -> u32 {
|
||||
let counts = self.counts.read().await;
|
||||
counts.get(account_id).copied().unwrap_or(0)
|
||||
counts
|
||||
.get(account_id)
|
||||
.filter(|state| {
|
||||
Utc::now().signed_duration_since(state.last_at) <= PATH_BLOCK_STALE_AFTER
|
||||
})
|
||||
.map(|state| state.count)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// 检查是否应该禁用账户
|
||||
|
||||
@@ -12,15 +12,14 @@ use crate::{
|
||||
model::AccountStatus,
|
||||
repository::{AccountRepository, StoredAccount},
|
||||
},
|
||||
codex::gateway::fingerprint::model::Fingerprint,
|
||||
codex::gateway::transport::http_client::{
|
||||
build_reqwest_client, CodexBackendClient, CodexClientError, CodexRequestContext,
|
||||
},
|
||||
};
|
||||
|
||||
use super::{
|
||||
cookies::request_domain, quota::quota_from_usage, AccountProbeOutcome, AccountProbeResult,
|
||||
AccountService, HealthCheckError,
|
||||
cookies::request_domain, AccountProbeOutcome, AccountProbeResult, AccountService,
|
||||
HealthCheckError,
|
||||
};
|
||||
|
||||
impl AccountService {
|
||||
@@ -29,7 +28,6 @@ impl AccountService {
|
||||
ids: Option<Vec<String>>,
|
||||
concurrency: usize,
|
||||
stagger_ms: u64,
|
||||
request_id: &str,
|
||||
) -> Result<Vec<AccountProbeResult>, HealthCheckError> {
|
||||
let repo = self
|
||||
.repository
|
||||
@@ -43,8 +41,6 @@ impl AccountService {
|
||||
let results = stream::iter(accounts.into_iter().enumerate())
|
||||
.map(|(index, account)| {
|
||||
let service = self.clone();
|
||||
let repo = repo.clone();
|
||||
let request_id = request_id.to_string();
|
||||
async move {
|
||||
if stagger_ms > 0 && index > 0 {
|
||||
let multiplier = index.min(concurrency);
|
||||
@@ -53,9 +49,7 @@ impl AccountService {
|
||||
))
|
||||
.await;
|
||||
}
|
||||
service
|
||||
.probe_account_with_codex_backend(&repo, account, &request_id)
|
||||
.await
|
||||
service.probe_account_with_oauth_refresh(account).await
|
||||
}
|
||||
})
|
||||
.buffer_unordered(concurrency)
|
||||
@@ -64,53 +58,23 @@ impl AccountService {
|
||||
Ok(results)
|
||||
}
|
||||
|
||||
async fn probe_account_with_codex_backend(
|
||||
&self,
|
||||
repo: &AccountRepository,
|
||||
account: StoredAccount,
|
||||
request_id: &str,
|
||||
) -> AccountProbeResult {
|
||||
if account.status == AccountStatus::Disabled {
|
||||
return skipped_probe_result(&account, "manually disabled");
|
||||
}
|
||||
|
||||
async fn probe_account_with_oauth_refresh(&self, account: StoredAccount) -> AccountProbeResult {
|
||||
let started_at = std::time::Instant::now();
|
||||
let previous_status = account.status;
|
||||
match fetch_account_usage(self, &account, request_id).await {
|
||||
Ok(raw) => {
|
||||
let quota = quota_from_usage(&raw);
|
||||
let _ = repo
|
||||
.update_quota_json(&account.id, "a.to_string())
|
||||
.await;
|
||||
if account.status != AccountStatus::Active {
|
||||
let _ = repo.set_status(&account.id, AccountStatus::Active).await;
|
||||
self.account_pool
|
||||
.lock()
|
||||
.await
|
||||
.set_status(&account.id, AccountStatus::Active);
|
||||
}
|
||||
AccountProbeResult {
|
||||
id: account.id,
|
||||
email: account.email,
|
||||
previous_status,
|
||||
outcome: AccountProbeOutcome::Alive,
|
||||
status: Some(AccountStatus::Active),
|
||||
error: None,
|
||||
duration_ms: Some(started_at.elapsed().as_millis()),
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
let status = apply_codex_account_error(self, repo, &account, &error).await;
|
||||
AccountProbeResult {
|
||||
id: account.id,
|
||||
email: account.email,
|
||||
previous_status,
|
||||
outcome: AccountProbeOutcome::Dead,
|
||||
status,
|
||||
error: Some(public_codex_error(&error)),
|
||||
duration_ms: Some(started_at.elapsed().as_millis()),
|
||||
}
|
||||
match self.refresh_account(&account.id).await {
|
||||
Ok(mut result) => {
|
||||
result.previous_status = previous_status;
|
||||
result
|
||||
}
|
||||
Err(error) => AccountProbeResult {
|
||||
id: account.id,
|
||||
email: account.email,
|
||||
previous_status,
|
||||
outcome: AccountProbeOutcome::Dead,
|
||||
status: None,
|
||||
error: Some(error.to_string()),
|
||||
duration_ms: Some(started_at.elapsed().as_millis()),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -124,7 +88,7 @@ pub(super) async fn fetch_account_usage(
|
||||
let client = CodexBackendClient::new(
|
||||
build_reqwest_client(service.config.tls.force_http11)?,
|
||||
service.config.api.base_url.clone(),
|
||||
Fingerprint::default_codex_desktop(),
|
||||
service.fingerprint.clone(),
|
||||
);
|
||||
client
|
||||
.fetch_usage(CodexRequestContext {
|
||||
|
||||
@@ -20,7 +20,10 @@ use crate::{
|
||||
AccountRepository, AccountUsageRepository, StoredAccount, StoredAccountMetadata,
|
||||
},
|
||||
},
|
||||
codex::gateway::{oauth::TokenRefresher, transport::websocket::CodexWebSocketPool},
|
||||
codex::gateway::{
|
||||
fingerprint::model::Fingerprint, oauth::TokenRefresher,
|
||||
transport::websocket::CodexWebSocketPool,
|
||||
},
|
||||
config::AppConfig,
|
||||
utils::pagination::Page,
|
||||
};
|
||||
@@ -34,6 +37,17 @@ pub struct AccountService {
|
||||
token_refresher: Option<Arc<dyn TokenRefresher>>,
|
||||
account_pool: Arc<Mutex<AccountPool>>,
|
||||
websocket_pool: Arc<CodexWebSocketPool>,
|
||||
fingerprint: Fingerprint,
|
||||
}
|
||||
|
||||
pub struct AccountServiceDependencies {
|
||||
pub repository: Option<AccountRepository>,
|
||||
pub usage_repository: Option<AccountUsageRepository>,
|
||||
pub cookie_repository: Option<CookieRepository>,
|
||||
pub token_refresher: Option<Arc<dyn TokenRefresher>>,
|
||||
pub account_pool: Arc<Mutex<AccountPool>>,
|
||||
pub websocket_pool: Arc<CodexWebSocketPool>,
|
||||
pub fingerprint: Fingerprint,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -241,15 +255,16 @@ pub enum ValidatedAccountImportError {
|
||||
}
|
||||
|
||||
impl AccountService {
|
||||
pub fn new(
|
||||
config: Arc<AppConfig>,
|
||||
repository: Option<AccountRepository>,
|
||||
usage_repository: Option<AccountUsageRepository>,
|
||||
cookie_repository: Option<CookieRepository>,
|
||||
token_refresher: Option<Arc<dyn TokenRefresher>>,
|
||||
account_pool: Arc<Mutex<AccountPool>>,
|
||||
websocket_pool: Arc<CodexWebSocketPool>,
|
||||
) -> Self {
|
||||
pub fn new(config: Arc<AppConfig>, dependencies: AccountServiceDependencies) -> Self {
|
||||
let AccountServiceDependencies {
|
||||
repository,
|
||||
usage_repository,
|
||||
cookie_repository,
|
||||
token_refresher,
|
||||
account_pool,
|
||||
websocket_pool,
|
||||
fingerprint,
|
||||
} = dependencies;
|
||||
Self {
|
||||
config,
|
||||
repository,
|
||||
@@ -258,6 +273,7 @@ impl AccountService {
|
||||
token_refresher,
|
||||
account_pool,
|
||||
websocket_pool,
|
||||
fingerprint,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -19,10 +19,33 @@ use super::{
|
||||
|
||||
const REFRESH_LEASE_TTL_SECONDS: i64 = 5 * 60;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
enum RefreshFailurePolicy {
|
||||
PersistStatus,
|
||||
ReportOnly,
|
||||
}
|
||||
|
||||
impl AccountService {
|
||||
pub async fn refresh_account(
|
||||
&self,
|
||||
account_id: &str,
|
||||
) -> Result<AccountProbeResult, RefreshAccountError> {
|
||||
self.refresh_account_with_failure_policy(account_id, RefreshFailurePolicy::PersistStatus)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn probe_account_refresh(
|
||||
&self,
|
||||
account_id: &str,
|
||||
) -> Result<AccountProbeResult, RefreshAccountError> {
|
||||
self.refresh_account_with_failure_policy(account_id, RefreshFailurePolicy::ReportOnly)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn refresh_account_with_failure_policy(
|
||||
&self,
|
||||
account_id: &str,
|
||||
failure_policy: RefreshFailurePolicy,
|
||||
) -> Result<AccountProbeResult, RefreshAccountError> {
|
||||
let repo = self
|
||||
.repository
|
||||
@@ -56,7 +79,7 @@ impl AccountService {
|
||||
}
|
||||
|
||||
let result = self
|
||||
.refresh_account_with_lease(repo, account_id, refresher)
|
||||
.refresh_account_with_lease(repo, account_id, refresher, failure_policy)
|
||||
.await;
|
||||
if let Err(error) = repo.release_refresh_lease(account_id, &lease_owner).await {
|
||||
tracing::warn!(
|
||||
@@ -73,6 +96,7 @@ impl AccountService {
|
||||
repo: &AccountRepository,
|
||||
account_id: &str,
|
||||
refresher: Arc<dyn TokenRefresher>,
|
||||
failure_policy: RefreshFailurePolicy,
|
||||
) -> Result<AccountProbeResult, RefreshAccountError> {
|
||||
let account = match repo.get(account_id).await {
|
||||
Ok(Some(account)) => account,
|
||||
@@ -110,9 +134,13 @@ impl AccountService {
|
||||
})
|
||||
}
|
||||
Err(failure) => {
|
||||
let status = self
|
||||
.apply_refresh_failure_status(repo, &account, failure)
|
||||
.await;
|
||||
let status = match failure_policy {
|
||||
RefreshFailurePolicy::PersistStatus => {
|
||||
self.apply_refresh_failure_status(repo, &account, failure)
|
||||
.await
|
||||
}
|
||||
RefreshFailurePolicy::ReportOnly => None,
|
||||
};
|
||||
Ok(AccountProbeResult {
|
||||
id: account.id,
|
||||
email: account.email,
|
||||
|
||||
@@ -23,7 +23,7 @@ impl Fingerprint {
|
||||
platform: "darwin".to_string(),
|
||||
arch: "arm64".to_string(),
|
||||
chromium_version: "146".to_string(),
|
||||
user_agent_template: "Codex Desktop/{app_version} ({platform}; {arch})".to_string(),
|
||||
user_agent_template: "Codex Desktop/{version} ({platform}; {arch})".to_string(),
|
||||
default_headers: Self::default_headers(),
|
||||
header_order: Self::default_header_order(),
|
||||
}
|
||||
@@ -56,14 +56,7 @@ impl Fingerprint {
|
||||
"x-openai-internal-codex-residency".to_string(),
|
||||
"x-client-request-id".to_string(),
|
||||
"x-codex-installation-id".to_string(),
|
||||
"session_id".to_string(),
|
||||
"x-codex-window-id".to_string(),
|
||||
"x-codex-turn-state".to_string(),
|
||||
"x-codex-turn-metadata".to_string(),
|
||||
"x-codex-beta-features".to_string(),
|
||||
"x-responsesapi-include-timing-metrics".to_string(),
|
||||
"x-codex-parent-thread-id".to_string(),
|
||||
"version".to_string(),
|
||||
"openai-beta".to_string(),
|
||||
"user-agent".to_string(),
|
||||
"sec-ch-ua".to_string(),
|
||||
@@ -82,7 +75,7 @@ impl Fingerprint {
|
||||
|
||||
pub fn user_agent(&self) -> String {
|
||||
self.user_agent_template
|
||||
.replace("{app_version}", &self.app_version)
|
||||
.replace("{version}", &self.app_version)
|
||||
.replace("{platform}", &self.platform)
|
||||
.replace("{arch}", &self.arch)
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ const AUTO_UPDATED_FINGERPRINT_ID: &str = "auto_updated";
|
||||
const AUTO_UPDATE_SOURCE: &str = "auto_update";
|
||||
const AUTO_UPDATE_PLATFORM: &str = "darwin";
|
||||
const AUTO_UPDATE_ARCH: &str = "arm64";
|
||||
const AUTO_UPDATE_USER_AGENT_TEMPLATE: &str = "Codex Desktop/{app_version} ({platform}; {arch})";
|
||||
const AUTO_UPDATE_USER_AGENT_TEMPLATE: &str = "Codex Desktop/{version} ({platform}; {arch})";
|
||||
const DEFAULT_AUTO_UPDATE_CHROMIUM_VERSION: &str = "146";
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
//! 用于路由/亲和性提示,使上游可以将客户端固定到同一后端实例以保持提示缓存温暖。
|
||||
//!
|
||||
//! 查找顺序:
|
||||
//! 1. `~/.codex/installation_id`(兼容真实 Codex Desktop)
|
||||
//! 1. `~/.codex/installation_id`(真实 Codex Desktop 位置)
|
||||
//! 2. `<database_dir>/installation_id`(之前持久化的)
|
||||
//! 3. 生成新 UUID 并持久化到 `<database_dir>/installation_id`
|
||||
|
||||
|
||||
@@ -9,17 +9,16 @@ use serde::Deserialize;
|
||||
use sha2::{Digest, Sha256};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::config::AuthConfig;
|
||||
|
||||
use super::{
|
||||
refresh::{RefreshFailure, TokenRefresher},
|
||||
token::TokenPair,
|
||||
};
|
||||
|
||||
const CODEX_OAUTH_CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann";
|
||||
const OPENAI_OAUTH_AUTHORIZE_ENDPOINT: &str = "https://auth.openai.com/oauth/authorize";
|
||||
const OPENAI_OAUTH_DEVICE_CODE_ENDPOINT: &str = "https://auth.openai.com/oauth/device/code";
|
||||
const OPENAI_OAUTH_TOKEN_ENDPOINT: &str = "https://auth.openai.com/oauth/token";
|
||||
const OAUTH_CALLBACK_PORT: u16 = 1455;
|
||||
const OAUTH_CALLBACK_PATH: &str = "/auth/openai/callback";
|
||||
const OAUTH_CALLBACK_PATH: &str = "/auth/callback";
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct OAuthConfig {
|
||||
@@ -30,12 +29,12 @@ pub struct OAuthConfig {
|
||||
}
|
||||
|
||||
impl OAuthConfig {
|
||||
pub fn codex_default() -> Self {
|
||||
pub fn from_auth_config(config: &AuthConfig) -> Self {
|
||||
Self {
|
||||
client_id: CODEX_OAUTH_CLIENT_ID.to_string(),
|
||||
auth_endpoint: OPENAI_OAUTH_AUTHORIZE_ENDPOINT.to_string(),
|
||||
client_id: config.oauth_client_id.clone(),
|
||||
auth_endpoint: config.oauth_auth_endpoint.clone(),
|
||||
device_code_endpoint: OPENAI_OAUTH_DEVICE_CODE_ENDPOINT.to_string(),
|
||||
token_endpoint: OPENAI_OAUTH_TOKEN_ENDPOINT.to_string(),
|
||||
token_endpoint: config.oauth_token_endpoint.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -193,10 +192,6 @@ impl OpenAiOAuthRefresher {
|
||||
pub fn new(client: Client, config: OAuthConfig) -> Self {
|
||||
Self { client, config }
|
||||
}
|
||||
|
||||
pub fn codex_default(client: Client) -> Self {
|
||||
Self::new(client, OAuthConfig::codex_default())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
|
||||
@@ -4,7 +4,10 @@ use chrono::Utc;
|
||||
use serde_json::{json, Value};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::codex::gateway::transport::sse::{parse_sse_events, SseError};
|
||||
use crate::codex::gateway::{
|
||||
protocol::tuple_schema::reconvert_tuple_values,
|
||||
transport::sse::{parse_sse_events, SseError},
|
||||
};
|
||||
|
||||
pub fn openai_error(message: &str, code: &str) -> Value {
|
||||
json!({
|
||||
@@ -21,6 +24,7 @@ pub fn chat_completion_from_codex_sse(
|
||||
body: &str,
|
||||
model: &str,
|
||||
include_reasoning: bool,
|
||||
tuple_schema: Option<&Value>,
|
||||
) -> Result<Option<Value>, SseError> {
|
||||
let events = parse_sse_events(body)?;
|
||||
let mut content = String::new();
|
||||
@@ -77,6 +81,9 @@ pub fn chat_completion_from_codex_sse(
|
||||
if content.is_empty() {
|
||||
content = output_text_from_response(&response);
|
||||
}
|
||||
if let Some(tuple_schema) = tuple_schema {
|
||||
content = reconvert_tuple_text(&content, tuple_schema).unwrap_or(content);
|
||||
}
|
||||
let mut message = json!({
|
||||
"role": "assistant",
|
||||
"content": if content.is_empty() && !tool_calls.is_empty() {
|
||||
@@ -111,6 +118,7 @@ pub fn chat_completion_stream_from_codex_sse(
|
||||
body: &str,
|
||||
model: &str,
|
||||
include_reasoning: bool,
|
||||
tuple_schema: Option<&Value>,
|
||||
) -> Result<Option<String>, SseError> {
|
||||
let events = parse_sse_events(body)?;
|
||||
let chunk_id = format!("chatcmpl-{}", Uuid::new_v4().simple());
|
||||
@@ -122,6 +130,7 @@ pub fn chat_completion_stream_from_codex_sse(
|
||||
let mut tool_call_indices = BTreeMap::new();
|
||||
let mut call_ids_with_deltas = BTreeSet::new();
|
||||
let mut next_tool_call_index = 0usize;
|
||||
let mut tuple_text_buffer = tuple_schema.map(|_| String::new());
|
||||
|
||||
push_sse_data(
|
||||
&mut output,
|
||||
@@ -145,20 +154,11 @@ pub fn chat_completion_stream_from_codex_sse(
|
||||
match event.event.as_deref() {
|
||||
Some("response.output_text.delta") => {
|
||||
if let Some(delta) = value.get("delta").and_then(Value::as_str) {
|
||||
push_sse_data(
|
||||
&mut output,
|
||||
json!({
|
||||
"id": chunk_id,
|
||||
"object": "chat.completion.chunk",
|
||||
"created": created,
|
||||
"model": model,
|
||||
"choices": [{
|
||||
"index": 0,
|
||||
"delta": {"content": delta},
|
||||
"finish_reason": null,
|
||||
}],
|
||||
}),
|
||||
);
|
||||
if let Some(buffer) = tuple_text_buffer.as_mut() {
|
||||
buffer.push_str(delta);
|
||||
} else {
|
||||
push_chat_content_delta(&mut output, &chunk_id, created, model, delta);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some("response.reasoning_summary_text.delta") if include_reasoning => {
|
||||
@@ -293,6 +293,14 @@ pub fn chat_completion_stream_from_codex_sse(
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
if let (Some(tuple_schema), Some(buffer)) = (tuple_schema, tuple_text_buffer.as_ref()) {
|
||||
if !buffer.is_empty() {
|
||||
let content =
|
||||
reconvert_tuple_text(buffer, tuple_schema).unwrap_or_else(|| buffer.clone());
|
||||
push_chat_content_delta(&mut output, &chunk_id, created, model, &content);
|
||||
}
|
||||
}
|
||||
|
||||
push_sse_data(
|
||||
&mut output,
|
||||
json!({
|
||||
@@ -313,6 +321,34 @@ pub fn chat_completion_stream_from_codex_sse(
|
||||
Ok(Some(output))
|
||||
}
|
||||
|
||||
fn push_chat_content_delta(
|
||||
output: &mut String,
|
||||
chunk_id: &str,
|
||||
created: i64,
|
||||
model: &str,
|
||||
content: &str,
|
||||
) {
|
||||
push_sse_data(
|
||||
output,
|
||||
json!({
|
||||
"id": chunk_id,
|
||||
"object": "chat.completion.chunk",
|
||||
"created": created,
|
||||
"model": model,
|
||||
"choices": [{
|
||||
"index": 0,
|
||||
"delta": {"content": content},
|
||||
"finish_reason": null,
|
||||
}],
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
fn reconvert_tuple_text(text: &str, tuple_schema: &Value) -> Option<String> {
|
||||
let parsed = serde_json::from_str::<Value>(text).ok()?;
|
||||
Some(reconvert_tuple_values(parsed, tuple_schema).to_string())
|
||||
}
|
||||
|
||||
fn output_text_from_response(response: &Value) -> String {
|
||||
response
|
||||
.get("output_text")
|
||||
|
||||
@@ -2,3 +2,4 @@ pub mod codex_to_openai;
|
||||
pub mod error;
|
||||
pub mod openai_to_codex;
|
||||
pub mod schema;
|
||||
pub(crate) mod tuple_schema;
|
||||
|
||||
@@ -3,6 +3,7 @@ use serde_json::{json, Value};
|
||||
|
||||
use crate::{
|
||||
codex::gateway::protocol::error::{AppError, AppResult},
|
||||
codex::gateway::protocol::tuple_schema::prepare_schema,
|
||||
codex::gateway::transport::types::CodexResponsesRequest,
|
||||
};
|
||||
|
||||
@@ -52,6 +53,12 @@ pub fn translate_chat_to_codex(req: ChatCompletionRequest) -> AppResult<CodexRes
|
||||
));
|
||||
}
|
||||
|
||||
let client_conversation_id = req
|
||||
.user
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(ToString::to_string);
|
||||
let instructions = chat_instructions(&req.messages);
|
||||
let mut input = chat_input(req.messages);
|
||||
if input.is_empty() {
|
||||
@@ -63,8 +70,12 @@ pub fn translate_chat_to_codex(req: ChatCompletionRequest) -> AppResult<CodexRes
|
||||
request.tools = codex_tools(req.tools, req.functions);
|
||||
request.tool_choice = req.tool_choice;
|
||||
request.parallel_tool_calls = req.parallel_tool_calls;
|
||||
request.text = response_format_text(req.response_format);
|
||||
let response_format = response_format_text(req.response_format);
|
||||
request.text = response_format.text;
|
||||
request.tuple_schema = response_format.tuple_schema;
|
||||
request.service_tier = req.service_tier;
|
||||
request.prompt_cache_key = client_conversation_id.clone();
|
||||
request.client_conversation_id = client_conversation_id;
|
||||
if let Some(effort) = req.reasoning_effort {
|
||||
request.reasoning = Some(json!({"effort": effort, "summary": "auto"}));
|
||||
}
|
||||
@@ -243,27 +254,58 @@ fn codex_tools(tools: Option<Vec<Value>>, functions: Option<Vec<Value>>) -> Opti
|
||||
})
|
||||
}
|
||||
|
||||
fn response_format_text(response_format: Option<Value>) -> Option<Value> {
|
||||
let format = response_format?;
|
||||
let kind = format.get("type").and_then(Value::as_str)?;
|
||||
struct PreparedResponseFormat {
|
||||
text: Option<Value>,
|
||||
tuple_schema: Option<Value>,
|
||||
}
|
||||
|
||||
fn response_format_text(response_format: Option<Value>) -> PreparedResponseFormat {
|
||||
let Some(format) = response_format else {
|
||||
return PreparedResponseFormat {
|
||||
text: None,
|
||||
tuple_schema: None,
|
||||
};
|
||||
};
|
||||
let Some(kind) = format.get("type").and_then(Value::as_str) else {
|
||||
return PreparedResponseFormat {
|
||||
text: None,
|
||||
tuple_schema: None,
|
||||
};
|
||||
};
|
||||
match kind {
|
||||
"json_object" => Some(json!({"format": {"type": "json_object"}})),
|
||||
"json_object" => PreparedResponseFormat {
|
||||
text: Some(json!({"format": {"type": "json_object"}})),
|
||||
tuple_schema: None,
|
||||
},
|
||||
"json_schema" => {
|
||||
let schema = format.get("json_schema")?;
|
||||
let Some(schema) = format.get("json_schema") else {
|
||||
return PreparedResponseFormat {
|
||||
text: None,
|
||||
tuple_schema: None,
|
||||
};
|
||||
};
|
||||
let name = schema
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("response");
|
||||
let prepared_schema =
|
||||
prepare_schema(schema.get("schema").cloned().unwrap_or_else(|| json!({})));
|
||||
let mut codex_format = json!({
|
||||
"type": "json_schema",
|
||||
"name": name,
|
||||
"schema": schema.get("schema").cloned().unwrap_or_else(|| json!({})),
|
||||
"schema": prepared_schema.schema,
|
||||
});
|
||||
if let Some(strict) = schema.get("strict").and_then(Value::as_bool) {
|
||||
codex_format["strict"] = Value::Bool(strict);
|
||||
}
|
||||
Some(json!({"format": codex_format}))
|
||||
PreparedResponseFormat {
|
||||
text: Some(json!({"format": codex_format})),
|
||||
tuple_schema: prepared_schema.original_schema,
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
_ => PreparedResponseFormat {
|
||||
text: None,
|
||||
tuple_schema: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
pub(crate) struct PreparedSchema {
|
||||
pub(crate) schema: Value,
|
||||
pub(crate) original_schema: Option<Value>,
|
||||
}
|
||||
|
||||
pub(crate) fn prepare_schema(schema: Value) -> PreparedSchema {
|
||||
let original_schema = has_tuple_schemas(&schema).then(|| schema.clone());
|
||||
let mut schema = schema;
|
||||
if original_schema.is_some() {
|
||||
convert_tuple_schemas(&mut schema);
|
||||
}
|
||||
inject_additional_properties(&mut schema);
|
||||
PreparedSchema {
|
||||
schema,
|
||||
original_schema,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn reconvert_tuple_values(data: Value, schema: &Value) -> Value {
|
||||
reconvert_tuple_values_with_root(data, schema, schema)
|
||||
}
|
||||
|
||||
fn reconvert_tuple_values_with_root(data: Value, schema: &Value, root_schema: &Value) -> Value {
|
||||
let Value::Object(schema_object) = schema else {
|
||||
return data;
|
||||
};
|
||||
|
||||
if let Some(reference) = schema_object.get("$ref").and_then(Value::as_str) {
|
||||
let Some(resolved) = resolve_ref(reference, root_schema) else {
|
||||
return data;
|
||||
};
|
||||
return reconvert_tuple_values_with_root(data, resolved, root_schema);
|
||||
}
|
||||
|
||||
if let Some(Value::Array(prefix_items)) = schema_object.get("prefixItems") {
|
||||
let mut data_object = match data {
|
||||
Value::Object(data_object) => data_object,
|
||||
other => return other,
|
||||
};
|
||||
let values = prefix_items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, item_schema)| {
|
||||
let value = data_object
|
||||
.remove(&index.to_string())
|
||||
.unwrap_or(Value::Null);
|
||||
reconvert_tuple_values_with_root(value, item_schema, root_schema)
|
||||
})
|
||||
.collect();
|
||||
return Value::Array(values);
|
||||
}
|
||||
|
||||
if let Some(Value::Object(properties)) = schema_object.get("properties") {
|
||||
let mut data_object = match data {
|
||||
Value::Object(data_object) => data_object,
|
||||
other => return other,
|
||||
};
|
||||
for (key, property_schema) in properties {
|
||||
if let Some(value) = data_object.remove(key) {
|
||||
data_object.insert(
|
||||
key.clone(),
|
||||
reconvert_tuple_values_with_root(value, property_schema, root_schema),
|
||||
);
|
||||
}
|
||||
}
|
||||
return Value::Object(data_object);
|
||||
}
|
||||
|
||||
if let Some(items_schema) = schema_object.get("items") {
|
||||
let values = match data {
|
||||
Value::Array(values) => values,
|
||||
other => return other,
|
||||
};
|
||||
return Value::Array(
|
||||
values
|
||||
.into_iter()
|
||||
.map(|value| reconvert_tuple_values_with_root(value, items_schema, root_schema))
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
|
||||
for key in ["oneOf", "anyOf", "allOf"] {
|
||||
let Some(Value::Array(branches)) = schema_object.get(key) else {
|
||||
continue;
|
||||
};
|
||||
let Some(branch) = branches.iter().find(|branch| has_tuple_schemas(branch)) else {
|
||||
continue;
|
||||
};
|
||||
return reconvert_tuple_values_with_root(data, branch, root_schema);
|
||||
}
|
||||
|
||||
data
|
||||
}
|
||||
|
||||
fn resolve_ref<'a>(reference: &str, root_schema: &'a Value) -> Option<&'a Value> {
|
||||
let path = reference
|
||||
.strip_prefix("#/$defs/")
|
||||
.map(|path| ("$defs", path))
|
||||
.or_else(|| {
|
||||
reference
|
||||
.strip_prefix("#/definitions/")
|
||||
.map(|path| ("definitions", path))
|
||||
})?;
|
||||
root_schema.get(path.0)?.get(path.1)
|
||||
}
|
||||
|
||||
fn has_tuple_schemas(value: &Value) -> bool {
|
||||
let Value::Object(object) = value else {
|
||||
return false;
|
||||
};
|
||||
if object
|
||||
.get("prefixItems")
|
||||
.is_some_and(serde_json::Value::is_array)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
object_values_have_tuple_schema(object, "properties")
|
||||
|| object.get("items").is_some_and(has_tuple_schemas)
|
||||
|| schema_array_has_tuple_schema(object, "oneOf")
|
||||
|| schema_array_has_tuple_schema(object, "anyOf")
|
||||
|| schema_array_has_tuple_schema(object, "allOf")
|
||||
|| object_values_have_tuple_schema(object, "$defs")
|
||||
|| object_values_have_tuple_schema(object, "definitions")
|
||||
|| object.get("if").is_some_and(has_tuple_schemas)
|
||||
|| object.get("then").is_some_and(has_tuple_schemas)
|
||||
|| object.get("else").is_some_and(has_tuple_schemas)
|
||||
|| object.get("not").is_some_and(has_tuple_schemas)
|
||||
}
|
||||
|
||||
fn object_values_have_tuple_schema(object: &Map<String, Value>, key: &str) -> bool {
|
||||
let Some(Value::Object(values)) = object.get(key) else {
|
||||
return false;
|
||||
};
|
||||
values.values().any(has_tuple_schemas)
|
||||
}
|
||||
|
||||
fn schema_array_has_tuple_schema(object: &Map<String, Value>, key: &str) -> bool {
|
||||
let Some(Value::Array(values)) = object.get(key) else {
|
||||
return false;
|
||||
};
|
||||
values.iter().any(has_tuple_schemas)
|
||||
}
|
||||
|
||||
fn convert_tuple_schemas(value: &mut Value) {
|
||||
let Value::Object(object) = value else {
|
||||
return;
|
||||
};
|
||||
|
||||
if let Some(Value::Array(prefix_items)) = object.remove("prefixItems") {
|
||||
let mut properties = Map::new();
|
||||
let mut required = Vec::new();
|
||||
for (index, mut item) in prefix_items.into_iter().enumerate() {
|
||||
convert_tuple_schemas(&mut item);
|
||||
let key = index.to_string();
|
||||
properties.insert(key.clone(), item);
|
||||
required.push(Value::String(key));
|
||||
}
|
||||
object.insert("type".to_string(), Value::String("object".to_string()));
|
||||
object.insert("properties".to_string(), Value::Object(properties));
|
||||
object.insert("required".to_string(), Value::Array(required));
|
||||
object.insert("additionalProperties".to_string(), Value::Bool(false));
|
||||
object.remove("items");
|
||||
return;
|
||||
}
|
||||
|
||||
convert_object_values(object, "properties");
|
||||
convert_object_value(object, "items");
|
||||
convert_schema_array(object, "oneOf");
|
||||
convert_schema_array(object, "anyOf");
|
||||
convert_schema_array(object, "allOf");
|
||||
convert_object_values(object, "$defs");
|
||||
convert_object_values(object, "definitions");
|
||||
convert_object_value(object, "if");
|
||||
convert_object_value(object, "then");
|
||||
convert_object_value(object, "else");
|
||||
convert_object_value(object, "not");
|
||||
}
|
||||
|
||||
fn convert_object_value(object: &mut Map<String, Value>, key: &str) {
|
||||
if let Some(value) = object.get_mut(key) {
|
||||
convert_tuple_schemas(value);
|
||||
}
|
||||
}
|
||||
|
||||
fn convert_object_values(object: &mut Map<String, Value>, key: &str) {
|
||||
let Some(Value::Object(values)) = object.get_mut(key) else {
|
||||
return;
|
||||
};
|
||||
for value in values.values_mut() {
|
||||
convert_tuple_schemas(value);
|
||||
}
|
||||
}
|
||||
|
||||
fn convert_schema_array(object: &mut Map<String, Value>, key: &str) {
|
||||
let Some(Value::Array(values)) = object.get_mut(key) else {
|
||||
return;
|
||||
};
|
||||
for value in values {
|
||||
convert_tuple_schemas(value);
|
||||
}
|
||||
}
|
||||
|
||||
fn inject_additional_properties(value: &mut Value) {
|
||||
let Value::Object(object) = value else {
|
||||
return;
|
||||
};
|
||||
if object.get("type").and_then(Value::as_str) == Some("object")
|
||||
&& !object.contains_key("additionalProperties")
|
||||
{
|
||||
object.insert("additionalProperties".to_string(), Value::Bool(false));
|
||||
}
|
||||
|
||||
inject_object_values(object, "properties");
|
||||
inject_object_value(object, "items");
|
||||
inject_schema_array(object, "oneOf");
|
||||
inject_schema_array(object, "anyOf");
|
||||
inject_schema_array(object, "allOf");
|
||||
inject_object_values(object, "$defs");
|
||||
inject_object_values(object, "definitions");
|
||||
inject_object_value(object, "if");
|
||||
inject_object_value(object, "then");
|
||||
inject_object_value(object, "else");
|
||||
inject_object_value(object, "not");
|
||||
}
|
||||
|
||||
fn inject_object_value(object: &mut Map<String, Value>, key: &str) {
|
||||
if let Some(value) = object.get_mut(key) {
|
||||
inject_additional_properties(value);
|
||||
}
|
||||
}
|
||||
|
||||
fn inject_object_values(object: &mut Map<String, Value>, key: &str) {
|
||||
let Some(Value::Object(values)) = object.get_mut(key) else {
|
||||
return;
|
||||
};
|
||||
for value in values.values_mut() {
|
||||
inject_additional_properties(value);
|
||||
}
|
||||
}
|
||||
|
||||
fn inject_schema_array(object: &mut Map<String, Value>, key: &str) {
|
||||
let Some(Value::Array(values)) = object.get_mut(key) else {
|
||||
return;
|
||||
};
|
||||
for value in values {
|
||||
inject_additional_properties(value);
|
||||
}
|
||||
}
|
||||
@@ -2,12 +2,10 @@ use indexmap::IndexMap;
|
||||
|
||||
use crate::codex::gateway::fingerprint::model::Fingerprint;
|
||||
|
||||
pub fn build_codex_headers(
|
||||
pub fn build_codex_base_headers(
|
||||
fp: &Fingerprint,
|
||||
access_token: &str,
|
||||
account_id: Option<&str>,
|
||||
turn_state: Option<&str>,
|
||||
request_id: &str,
|
||||
) -> IndexMap<String, String> {
|
||||
let mut headers = IndexMap::new();
|
||||
|
||||
@@ -19,16 +17,6 @@ pub fn build_codex_headers(
|
||||
headers.insert("chatgpt-account-id".to_string(), id.to_string());
|
||||
}
|
||||
headers.insert("originator".to_string(), fp.originator.clone());
|
||||
headers.insert(
|
||||
"x-openai-internal-codex-residency".to_string(),
|
||||
"us".to_string(),
|
||||
);
|
||||
headers.insert("x-client-request-id".to_string(), request_id.to_string());
|
||||
|
||||
if let Some(state) = turn_state {
|
||||
headers.insert("x-codex-turn-state".to_string(), state.to_string());
|
||||
}
|
||||
|
||||
headers.insert("user-agent".to_string(), fp.user_agent());
|
||||
headers.insert("sec-ch-ua".to_string(), fp.sec_ch_ua());
|
||||
|
||||
@@ -39,6 +27,27 @@ pub fn build_codex_headers(
|
||||
}
|
||||
}
|
||||
|
||||
headers
|
||||
}
|
||||
|
||||
pub fn build_codex_headers(
|
||||
fp: &Fingerprint,
|
||||
access_token: &str,
|
||||
account_id: Option<&str>,
|
||||
turn_state: Option<&str>,
|
||||
request_id: &str,
|
||||
) -> IndexMap<String, String> {
|
||||
let mut headers = build_codex_base_headers(fp, access_token, account_id);
|
||||
headers.insert(
|
||||
"x-openai-internal-codex-residency".to_string(),
|
||||
"us".to_string(),
|
||||
);
|
||||
headers.insert("x-client-request-id".to_string(), request_id.to_string());
|
||||
|
||||
if let Some(state) = turn_state {
|
||||
headers.insert("x-codex-turn-state".to_string(), state.to_string());
|
||||
}
|
||||
|
||||
headers.insert("accept".to_string(), "text/event-stream".to_string());
|
||||
|
||||
headers
|
||||
@@ -72,3 +81,12 @@ pub fn build_ordered_codex_headers(
|
||||
let headers = build_codex_headers(fp, access_token, account_id, turn_state, request_id);
|
||||
order_headers(headers, &fp.header_order)
|
||||
}
|
||||
|
||||
pub fn build_ordered_codex_base_headers(
|
||||
fp: &Fingerprint,
|
||||
access_token: &str,
|
||||
account_id: Option<&str>,
|
||||
) -> IndexMap<String, String> {
|
||||
let headers = build_codex_base_headers(fp, access_token, account_id);
|
||||
order_headers(headers, &fp.header_order)
|
||||
}
|
||||
|
||||
@@ -1,21 +1,28 @@
|
||||
use std::sync::Arc;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
sync::{Arc, Mutex, OnceLock},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use futures::StreamExt;
|
||||
use indexmap::IndexMap;
|
||||
use reqwest::{
|
||||
header::{
|
||||
HeaderMap, HeaderName, HeaderValue, ACCEPT, CONTENT_TYPE, COOKIE, RETRY_AFTER, SET_COOKIE,
|
||||
HeaderMap, HeaderName, HeaderValue, ACCEPT, ACCEPT_ENCODING, CONTENT_TYPE, COOKIE,
|
||||
RETRY_AFTER, SET_COOKIE,
|
||||
},
|
||||
Client, Response as ReqwestResponse, StatusCode,
|
||||
};
|
||||
use serde_json::{Map, Value};
|
||||
use thiserror::Error;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{
|
||||
codex::gateway::fingerprint::model::Fingerprint,
|
||||
codex::gateway::transport::{
|
||||
headers::build_ordered_codex_headers,
|
||||
headers::build_ordered_codex_base_headers,
|
||||
sse::SseError,
|
||||
types::CodexResponsesRequest,
|
||||
types::{CodexCompactRequest, CodexResponsesRequest},
|
||||
usage_events::{extract_sse_usage, TokenUsage},
|
||||
websocket::{
|
||||
append_rate_limit_updates, create_response_via_websocket,
|
||||
@@ -80,6 +87,13 @@ pub struct CodexBackendResponse {
|
||||
pub rate_limit_headers: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CodexCompactResponse {
|
||||
pub body: Value,
|
||||
pub set_cookie_headers: Vec<String>,
|
||||
pub rate_limit_headers: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CodexConnectivityProbe {
|
||||
pub endpoint: String,
|
||||
@@ -101,6 +115,8 @@ pub struct CodexBackendWebSocketStream {
|
||||
pub rate_limit_updates: SharedRateLimitUpdates,
|
||||
}
|
||||
|
||||
const MAX_UPSTREAM_ERROR_BODY_BYTES: usize = 1024 * 1024;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CodexBackendClient {
|
||||
client: Client,
|
||||
@@ -147,11 +163,12 @@ impl CodexBackendClient {
|
||||
) -> CodexClientResult<CodexBackendResponse> {
|
||||
let transport = transport_for_request(request);
|
||||
let upstream_request = response_upstream_request(request, context);
|
||||
let headers = self.request_headers_for_response(&upstream_request, context)?;
|
||||
if matches!(
|
||||
transport,
|
||||
CodexTransport::WebSocketPreferred | CodexTransport::WebSocketRequired
|
||||
) {
|
||||
let headers =
|
||||
self.request_headers_for_websocket_response(&upstream_request, context)?;
|
||||
match self
|
||||
.create_response_via_configured_websocket(&upstream_request, headers.clone())
|
||||
.await
|
||||
@@ -179,6 +196,7 @@ impl CodexBackendClient {
|
||||
}
|
||||
}
|
||||
|
||||
let headers = self.request_headers_for_http_response(&upstream_request, context)?;
|
||||
let response = self
|
||||
.send_response_request(&upstream_request, headers)
|
||||
.await?;
|
||||
@@ -187,7 +205,49 @@ impl CodexBackendClient {
|
||||
let set_cookie_headers = set_cookie_headers(&response);
|
||||
let rate_limit_headers = rate_limit_headers(response.headers());
|
||||
let retry_after_seconds = retry_after_seconds(response.headers(), None);
|
||||
if !status.is_success() {
|
||||
let body = read_capped_error_body(response).await?;
|
||||
return Err(CodexClientError::Upstream {
|
||||
status,
|
||||
retry_after_seconds: retry_after_seconds
|
||||
.or_else(|| retry_after_seconds_from_body(&body)),
|
||||
body,
|
||||
});
|
||||
}
|
||||
let body = response.text().await?;
|
||||
let usage = extract_sse_usage(&body)?;
|
||||
|
||||
Ok(CodexBackendResponse {
|
||||
body,
|
||||
usage,
|
||||
turn_state,
|
||||
set_cookie_headers,
|
||||
rate_limit_headers,
|
||||
})
|
||||
}
|
||||
|
||||
#[tracing::instrument(
|
||||
skip(self, request, context),
|
||||
fields(
|
||||
request_id = %context.request_id,
|
||||
account_id = %context.account_id.unwrap_or("unknown"),
|
||||
model = %request.model,
|
||||
transport = "http_json",
|
||||
)
|
||||
)]
|
||||
pub async fn create_compact_response(
|
||||
&self,
|
||||
request: &CodexCompactRequest,
|
||||
context: CodexRequestContext<'_>,
|
||||
) -> CodexClientResult<CodexCompactResponse> {
|
||||
let headers = self.compact_request_headers(context)?;
|
||||
let response = self.send_compact_request(request, headers).await?;
|
||||
let status = response.status();
|
||||
let set_cookie_headers = set_cookie_headers(&response);
|
||||
let rate_limit_headers = rate_limit_headers(response.headers());
|
||||
let retry_after_seconds = retry_after_seconds(response.headers(), None);
|
||||
let body = response.text().await?;
|
||||
|
||||
if !status.is_success() {
|
||||
return Err(CodexClientError::Upstream {
|
||||
status,
|
||||
@@ -196,12 +256,19 @@ impl CodexBackendClient {
|
||||
body,
|
||||
});
|
||||
}
|
||||
let usage = extract_sse_usage(&body)?;
|
||||
|
||||
Ok(CodexBackendResponse {
|
||||
body,
|
||||
usage,
|
||||
turn_state,
|
||||
let parsed =
|
||||
serde_json::from_str::<Value>(&body).map_err(|_| CodexClientError::Upstream {
|
||||
status: StatusCode::BAD_GATEWAY,
|
||||
retry_after_seconds: None,
|
||||
body: format!(
|
||||
"Compact response is not valid JSON: {}",
|
||||
truncate_for_error(&body)
|
||||
),
|
||||
})?;
|
||||
|
||||
Ok(CodexCompactResponse {
|
||||
body: parsed,
|
||||
set_cookie_headers,
|
||||
rate_limit_headers,
|
||||
})
|
||||
@@ -222,7 +289,7 @@ impl CodexBackendClient {
|
||||
context: CodexRequestContext<'_>,
|
||||
) -> CodexClientResult<CodexBackendStream> {
|
||||
let upstream_request = response_upstream_request(request, context);
|
||||
let headers = self.request_headers_for_response(&upstream_request, context)?;
|
||||
let headers = self.request_headers_for_http_response(&upstream_request, context)?;
|
||||
let response = self
|
||||
.send_response_request(&upstream_request, headers)
|
||||
.await?;
|
||||
@@ -232,7 +299,7 @@ impl CodexBackendClient {
|
||||
let rate_limit_headers = rate_limit_headers(response.headers());
|
||||
if !status.is_success() {
|
||||
let retry_after_seconds = retry_after_seconds(response.headers(), None);
|
||||
let body = response.text().await?;
|
||||
let body = read_capped_error_body(response).await?;
|
||||
return Err(CodexClientError::Upstream {
|
||||
status,
|
||||
retry_after_seconds: retry_after_seconds
|
||||
@@ -264,7 +331,7 @@ impl CodexBackendClient {
|
||||
context: CodexRequestContext<'_>,
|
||||
) -> CodexClientResult<CodexBackendWebSocketStream> {
|
||||
let upstream_request = response_upstream_request(request, context);
|
||||
let headers = self.request_headers_for_response(&upstream_request, context)?;
|
||||
let headers = self.request_headers_for_websocket_response(&upstream_request, context)?;
|
||||
let response = self
|
||||
.create_stream_via_configured_websocket(&upstream_request, headers)
|
||||
.await
|
||||
@@ -350,8 +417,7 @@ impl CodexBackendClient {
|
||||
];
|
||||
|
||||
for endpoint in endpoints {
|
||||
let mut headers = self.request_headers(context)?;
|
||||
headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
|
||||
let headers = self.auxiliary_request_headers(context)?;
|
||||
let response = self.client.get(endpoint).headers(headers).send().await?;
|
||||
if !response.status().is_success() {
|
||||
continue;
|
||||
@@ -374,8 +440,7 @@ impl CodexBackendClient {
|
||||
"{}/codex/models?client_version={}",
|
||||
self.base_url, self.fingerprint.app_version
|
||||
);
|
||||
let mut headers = self.request_headers(context)?;
|
||||
headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
|
||||
let headers = self.auxiliary_request_headers(context)?;
|
||||
let response = self.client.get(&endpoint).headers(headers).send().await?;
|
||||
|
||||
Ok(CodexConnectivityProbe {
|
||||
@@ -387,17 +452,17 @@ impl CodexBackendClient {
|
||||
pub async fn fetch_usage(&self, context: CodexRequestContext<'_>) -> CodexClientResult<Value> {
|
||||
let mut last_invalid_body = None;
|
||||
for endpoint in self.usage_endpoints() {
|
||||
let mut headers = self.request_headers(context)?;
|
||||
headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
|
||||
let headers = self.auxiliary_request_headers(context)?;
|
||||
let response = self.client.get(endpoint).headers(headers).send().await?;
|
||||
let status = response.status();
|
||||
let retry_after_seconds = retry_after_seconds(response.headers(), None);
|
||||
let body = response.text().await?;
|
||||
if status == StatusCode::NOT_FOUND {
|
||||
let body = read_capped_error_body(response).await?;
|
||||
last_invalid_body = Some(body);
|
||||
continue;
|
||||
}
|
||||
if !status.is_success() {
|
||||
let body = read_capped_error_body(response).await?;
|
||||
return Err(CodexClientError::Upstream {
|
||||
status,
|
||||
retry_after_seconds: retry_after_seconds
|
||||
@@ -405,6 +470,7 @@ impl CodexBackendClient {
|
||||
body,
|
||||
});
|
||||
}
|
||||
let body = response.text().await?;
|
||||
match serde_json::from_str::<Value>(&body) {
|
||||
Ok(parsed) if parsed.get("rate_limit").is_some() => return Ok(parsed),
|
||||
_ => last_invalid_body = Some(body),
|
||||
@@ -435,6 +501,21 @@ impl CodexBackendClient {
|
||||
.await?)
|
||||
}
|
||||
|
||||
async fn send_compact_request(
|
||||
&self,
|
||||
request: &CodexCompactRequest,
|
||||
headers: HeaderMap,
|
||||
) -> CodexClientResult<ReqwestResponse> {
|
||||
let url = format!("{}/codex/responses/compact", self.base_url);
|
||||
Ok(self
|
||||
.client
|
||||
.post(url)
|
||||
.headers(headers)
|
||||
.json(request)
|
||||
.send()
|
||||
.await?)
|
||||
}
|
||||
|
||||
fn usage_endpoints(&self) -> Vec<String> {
|
||||
if self.base_url.contains("/backend-api") {
|
||||
vec![
|
||||
@@ -451,35 +532,37 @@ impl CodexBackendClient {
|
||||
|
||||
fn request_headers(&self, context: CodexRequestContext<'_>) -> CodexClientResult<HeaderMap> {
|
||||
let request_id = context.session_id.unwrap_or(context.request_id);
|
||||
let ordered_headers = build_ordered_codex_headers(
|
||||
let ordered_headers = build_ordered_codex_base_headers(
|
||||
&self.fingerprint,
|
||||
context.access_token,
|
||||
context.account_id,
|
||||
context.turn_state,
|
||||
request_id,
|
||||
);
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
|
||||
for (name, value) in &ordered_headers {
|
||||
if name == "content-type" || name == "openai-beta" || name == "cookie" {
|
||||
continue;
|
||||
}
|
||||
headers.insert(
|
||||
HeaderName::from_bytes(name.as_bytes())?,
|
||||
HeaderValue::from_str(value)?,
|
||||
);
|
||||
}
|
||||
|
||||
if let Some(cookie_header) = context.cookie_header {
|
||||
headers.insert(COOKIE, HeaderValue::from_str(cookie_header)?);
|
||||
}
|
||||
insert_ordered_headers(&mut headers, &ordered_headers)?;
|
||||
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
|
||||
insert_optional_header(&mut headers, "cookie", context.cookie_header)?;
|
||||
headers.insert(ACCEPT, HeaderValue::from_static("text/event-stream"));
|
||||
headers.insert(
|
||||
HeaderName::from_static("openai-beta"),
|
||||
HeaderValue::from_static("responses_websockets=2026-02-06"),
|
||||
);
|
||||
headers.insert(
|
||||
HeaderName::from_static("x-openai-internal-codex-residency"),
|
||||
HeaderValue::from_static("us"),
|
||||
);
|
||||
headers.insert(
|
||||
HeaderName::from_static("x-client-request-id"),
|
||||
HeaderValue::from_str(request_id)?,
|
||||
);
|
||||
insert_optional_header(
|
||||
&mut headers,
|
||||
"x-codex-installation-id",
|
||||
context.installation_id,
|
||||
)?;
|
||||
insert_optional_header(&mut headers, "session_id", context.session_id)?;
|
||||
insert_optional_header(&mut headers, "x-codex-window-id", context.codex_window_id)?;
|
||||
insert_optional_header(&mut headers, "x-codex-turn-state", context.turn_state)?;
|
||||
insert_optional_header(&mut headers, "x-codex-turn-metadata", context.turn_metadata)?;
|
||||
insert_optional_header(&mut headers, "x-codex-beta-features", context.beta_features)?;
|
||||
insert_optional_header(
|
||||
@@ -488,23 +571,74 @@ impl CodexBackendClient {
|
||||
context.include_timing_metrics,
|
||||
)?;
|
||||
insert_optional_header(&mut headers, "version", context.version)?;
|
||||
insert_optional_header(&mut headers, "x-codex-window-id", context.codex_window_id)?;
|
||||
insert_optional_header(
|
||||
&mut headers,
|
||||
"x-codex-parent-thread-id",
|
||||
context.parent_thread_id,
|
||||
)?;
|
||||
|
||||
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
|
||||
headers.insert(
|
||||
HeaderName::from_static("openai-beta"),
|
||||
HeaderValue::from_static("responses_websockets=2026-02-06"),
|
||||
Ok(headers)
|
||||
}
|
||||
|
||||
fn auxiliary_request_headers(
|
||||
&self,
|
||||
context: CodexRequestContext<'_>,
|
||||
) -> CodexClientResult<HeaderMap> {
|
||||
let ordered_headers = build_ordered_codex_base_headers(
|
||||
&self.fingerprint,
|
||||
context.access_token,
|
||||
context.account_id,
|
||||
);
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
|
||||
insert_ordered_headers(&mut headers, &ordered_headers)?;
|
||||
|
||||
if let Some(cookie_header) = context.cookie_header {
|
||||
headers.insert(COOKIE, HeaderValue::from_str(cookie_header)?);
|
||||
}
|
||||
headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
|
||||
headers.insert(ACCEPT_ENCODING, HeaderValue::from_static("gzip, deflate"));
|
||||
|
||||
Ok(headers)
|
||||
}
|
||||
|
||||
fn request_headers_for_response(
|
||||
fn compact_request_headers(
|
||||
&self,
|
||||
context: CodexRequestContext<'_>,
|
||||
) -> CodexClientResult<HeaderMap> {
|
||||
let ordered_headers = build_ordered_codex_base_headers(
|
||||
&self.fingerprint,
|
||||
context.access_token,
|
||||
context.account_id,
|
||||
);
|
||||
|
||||
let mut headers = HeaderMap::new();
|
||||
insert_ordered_headers(&mut headers, &ordered_headers)?;
|
||||
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
|
||||
insert_optional_header(&mut headers, "cookie", context.cookie_header)?;
|
||||
headers.insert(
|
||||
HeaderName::from_static("openai-beta"),
|
||||
HeaderValue::from_static("responses_websockets=2026-02-06"),
|
||||
);
|
||||
headers.insert(
|
||||
HeaderName::from_static("x-openai-internal-codex-residency"),
|
||||
HeaderValue::from_static("us"),
|
||||
);
|
||||
headers.insert(
|
||||
HeaderName::from_static("x-client-request-id"),
|
||||
HeaderValue::from_str(&Uuid::new_v4().to_string())?,
|
||||
);
|
||||
insert_optional_header(
|
||||
&mut headers,
|
||||
"x-codex-installation-id",
|
||||
context.installation_id,
|
||||
)?;
|
||||
|
||||
Ok(headers)
|
||||
}
|
||||
|
||||
fn request_headers_for_http_response(
|
||||
&self,
|
||||
request: &CodexResponsesRequest,
|
||||
context: CodexRequestContext<'_>,
|
||||
@@ -518,6 +652,17 @@ impl CodexBackendClient {
|
||||
}
|
||||
Ok(headers)
|
||||
}
|
||||
|
||||
fn request_headers_for_websocket_response(
|
||||
&self,
|
||||
request: &CodexResponsesRequest,
|
||||
context: CodexRequestContext<'_>,
|
||||
) -> CodexClientResult<HeaderMap> {
|
||||
let mut headers = self.request_headers_for_http_response(request, context)?;
|
||||
headers.remove(CONTENT_TYPE);
|
||||
headers.remove(ACCEPT);
|
||||
Ok(headers)
|
||||
}
|
||||
}
|
||||
|
||||
fn response_upstream_request(
|
||||
@@ -532,6 +677,25 @@ fn response_upstream_request(
|
||||
upstream
|
||||
}
|
||||
|
||||
async fn read_capped_error_body(response: ReqwestResponse) -> Result<String, reqwest::Error> {
|
||||
let mut stream = response.bytes_stream();
|
||||
let mut body = Vec::new();
|
||||
while let Some(chunk) = stream.next().await {
|
||||
let chunk = chunk?;
|
||||
let remaining = MAX_UPSTREAM_ERROR_BODY_BYTES.saturating_sub(body.len());
|
||||
if remaining == 0 {
|
||||
break;
|
||||
}
|
||||
if chunk.len() <= remaining {
|
||||
body.extend_from_slice(&chunk);
|
||||
} else {
|
||||
body.extend_from_slice(&chunk[..remaining]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(String::from_utf8_lossy(&body).into_owned())
|
||||
}
|
||||
|
||||
async fn collect_websocket_stream_response(
|
||||
response: CodexWebSocketStreamResponse,
|
||||
) -> Result<crate::codex::gateway::transport::websocket::CodexWebSocketResponse, CodexWebSocketError>
|
||||
@@ -660,11 +824,34 @@ fn insert_optional_header(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn insert_ordered_headers(
|
||||
headers: &mut HeaderMap,
|
||||
ordered_headers: &IndexMap<String, String>,
|
||||
) -> CodexClientResult<()> {
|
||||
for (name, value) in ordered_headers {
|
||||
headers.insert(
|
||||
HeaderName::from_bytes(name.as_bytes())?,
|
||||
HeaderValue::from_str(value)?,
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn build_reqwest_client(force_http11: bool) -> Result<Client, reqwest::Error> {
|
||||
// Codex Desktop 指纹依赖 reqwest/rustls 组合,升级前必须重新验证 TLS 行为。
|
||||
static CLIENTS: OnceLock<Mutex<HashMap<bool, Client>>> = OnceLock::new();
|
||||
let cache = CLIENTS.get_or_init(|| Mutex::new(HashMap::new()));
|
||||
let mut clients = cache
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
if let Some(client) = clients.get(&force_http11) {
|
||||
return Ok(client.clone());
|
||||
}
|
||||
|
||||
let builder = Client::builder()
|
||||
.use_rustls_tls()
|
||||
.no_proxy()
|
||||
.pool_max_idle_per_host(4)
|
||||
.tcp_keepalive(Duration::from_secs(30))
|
||||
.gzip(true)
|
||||
.brotli(true)
|
||||
.zstd(true)
|
||||
@@ -674,7 +861,9 @@ pub fn build_reqwest_client(force_http11: bool) -> Result<Client, reqwest::Error
|
||||
} else {
|
||||
builder
|
||||
};
|
||||
builder.build()
|
||||
let client = builder.build()?;
|
||||
clients.insert(force_http11, client.clone());
|
||||
Ok(client)
|
||||
}
|
||||
|
||||
fn turn_state(response: &ReqwestResponse) -> Option<String> {
|
||||
@@ -755,7 +944,9 @@ fn truncate_for_error(body: &str) -> String {
|
||||
|
||||
fn websocket_error_allows_http_sse_fallback(error: &CodexWebSocketError) -> bool {
|
||||
match error {
|
||||
CodexWebSocketError::Transport(_) | CodexWebSocketError::EmptyResponse => true,
|
||||
CodexWebSocketError::Transport(_)
|
||||
| CodexWebSocketError::OpenTimeout { .. }
|
||||
| CodexWebSocketError::EmptyResponse => true,
|
||||
CodexWebSocketError::Upstream { status, .. } => matches!(
|
||||
*status,
|
||||
StatusCode::NOT_FOUND
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use thiserror::Error;
|
||||
|
||||
pub const MAX_SSE_EVENT_BUFFER_BYTES: usize = 64 * 1024 * 1024;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SseEvent {
|
||||
pub event: Option<String>,
|
||||
@@ -12,6 +14,8 @@ pub struct SseEvent {
|
||||
pub enum SseError {
|
||||
#[error("invalid SSE retry value: {0}")]
|
||||
InvalidRetry(String),
|
||||
#[error("SSE buffer exceeded {max_bytes} bytes — aborting stream")]
|
||||
BufferExceeded { max_bytes: usize },
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
@@ -40,6 +44,13 @@ impl EventBuilder {
|
||||
return None;
|
||||
}
|
||||
self.has_data = false;
|
||||
if self.data == "[DONE]" {
|
||||
self.event = None;
|
||||
self.id = None;
|
||||
self.retry = None;
|
||||
self.data.clear();
|
||||
return None;
|
||||
}
|
||||
Some(SseEvent {
|
||||
event: self.event.take(),
|
||||
data: std::mem::take(&mut self.data),
|
||||
@@ -52,20 +63,28 @@ impl EventBuilder {
|
||||
pub fn parse_sse_events(input: &str) -> Result<Vec<SseEvent>, SseError> {
|
||||
let mut events = Vec::new();
|
||||
let mut builder = EventBuilder::default();
|
||||
let mut saw_sse_syntax = false;
|
||||
let mut event_buffer_bytes = 0usize;
|
||||
|
||||
for raw_line in input.lines() {
|
||||
let line = raw_line.strip_suffix('\r').unwrap_or(raw_line);
|
||||
if line.is_empty() {
|
||||
event_buffer_bytes = 0;
|
||||
if let Some(event) = builder.finish() {
|
||||
events.push(event);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
track_event_buffer_bytes(&mut event_buffer_bytes, raw_line)?;
|
||||
if line.starts_with(':') {
|
||||
saw_sse_syntax = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
let (field, value) = split_sse_field(line);
|
||||
if matches!(field, "event" | "data" | "id" | "retry") {
|
||||
saw_sse_syntax = true;
|
||||
}
|
||||
match field {
|
||||
"event" => builder.event = Some(value.to_string()),
|
||||
"data" => builder.push_data(value),
|
||||
@@ -77,6 +96,7 @@ pub fn parse_sse_events(input: &str) -> Result<Vec<SseEvent>, SseError> {
|
||||
.map_err(|_| SseError::InvalidRetry(value.to_string()))?,
|
||||
);
|
||||
}
|
||||
_ if builder.has_data && !is_sse_metadata_line(line) => builder.push_data(line),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -84,9 +104,68 @@ pub fn parse_sse_events(input: &str) -> Result<Vec<SseEvent>, SseError> {
|
||||
if let Some(event) = builder.finish() {
|
||||
events.push(event);
|
||||
}
|
||||
if events.is_empty() && !saw_sse_syntax && !input.trim().is_empty() {
|
||||
events.push(non_sse_response_event(input.trim()));
|
||||
}
|
||||
Ok(events)
|
||||
}
|
||||
|
||||
fn track_event_buffer_bytes(current_bytes: &mut usize, line: &str) -> Result<(), SseError> {
|
||||
let line_separator_bytes = usize::from(*current_bytes != 0);
|
||||
*current_bytes = current_bytes
|
||||
.saturating_add(line_separator_bytes)
|
||||
.saturating_add(line.len());
|
||||
if *current_bytes > MAX_SSE_EVENT_BUFFER_BYTES {
|
||||
return Err(SseError::BufferExceeded {
|
||||
max_bytes: MAX_SSE_EVENT_BUFFER_BYTES,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_sse_metadata_line(line: &str) -> bool {
|
||||
line.starts_with("event:")
|
||||
|| line.starts_with("data:")
|
||||
|| line.starts_with("id:")
|
||||
|| line.starts_with("retry:")
|
||||
|| line.starts_with(':')
|
||||
}
|
||||
|
||||
fn non_sse_response_event(raw: &str) -> SseEvent {
|
||||
let message = non_sse_error_message(raw);
|
||||
let data = serde_json::json!({
|
||||
"error": {
|
||||
"type": "error",
|
||||
"code": "non_sse_response",
|
||||
"message": message,
|
||||
}
|
||||
})
|
||||
.to_string();
|
||||
SseEvent {
|
||||
event: Some("error".to_string()),
|
||||
data,
|
||||
id: None,
|
||||
retry: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn non_sse_error_message(raw: &str) -> String {
|
||||
let Ok(value) = serde_json::from_str::<serde_json::Value>(raw) else {
|
||||
return raw.to_string();
|
||||
};
|
||||
value
|
||||
.get("detail")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.or_else(|| {
|
||||
value
|
||||
.pointer("/error/message")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
})
|
||||
.filter(|message| !message.trim().is_empty())
|
||||
.unwrap_or(raw)
|
||||
.to_string()
|
||||
}
|
||||
|
||||
pub fn encode_sse_event(event: &str, data: &str) -> String {
|
||||
let mut frame = String::new();
|
||||
if !event.is_empty() {
|
||||
|
||||
@@ -18,12 +18,20 @@ pub struct CodexResponsesRequest {
|
||||
pub parallel_tool_calls: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub text: Option<Value>,
|
||||
#[serde(skip)]
|
||||
pub tuple_schema: Option<Value>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub service_tier: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub previous_response_id: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub prompt_cache_key: Option<String>,
|
||||
#[serde(skip)]
|
||||
pub explicit_prompt_cache_key: bool,
|
||||
#[serde(skip)]
|
||||
pub client_conversation_id: Option<String>,
|
||||
#[serde(skip)]
|
||||
pub variant_identity: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub include: Option<Vec<String>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
@@ -65,9 +73,13 @@ impl CodexResponsesRequest {
|
||||
tool_choice: None,
|
||||
parallel_tool_calls: None,
|
||||
text: None,
|
||||
tuple_schema: None,
|
||||
service_tier: None,
|
||||
previous_response_id: None,
|
||||
prompt_cache_key: None,
|
||||
explicit_prompt_cache_key: false,
|
||||
client_conversation_id: None,
|
||||
variant_identity: None,
|
||||
include: None,
|
||||
client_metadata: None,
|
||||
use_websocket: false,
|
||||
@@ -82,3 +94,18 @@ impl CodexResponsesRequest {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct CodexCompactRequest {
|
||||
pub model: String,
|
||||
pub input: Vec<Value>,
|
||||
pub instructions: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub tools: Option<Vec<Value>>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub parallel_tool_calls: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub reasoning: Option<Value>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub text: Option<Value>,
|
||||
}
|
||||
|
||||
@@ -11,6 +11,12 @@ pub(super) struct ClassifiedWebSocketError {
|
||||
pub(super) connection_fatal: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum WebSocketErrorClassificationProfile {
|
||||
OneShot,
|
||||
Pooled,
|
||||
}
|
||||
|
||||
pub(super) fn websocket_request_body(request: &CodexResponsesRequest) -> Value {
|
||||
let mut body = json!({
|
||||
"type": "response.create",
|
||||
@@ -82,7 +88,10 @@ pub(super) fn is_terminal_websocket_event(event: &str) -> bool {
|
||||
event == "response.completed" || event == "response.failed" || event == "error"
|
||||
}
|
||||
|
||||
pub(super) fn classify_ws_error_frame(raw: &str) -> Option<ClassifiedWebSocketError> {
|
||||
pub(super) fn classify_ws_error_frame(
|
||||
raw: &str,
|
||||
profile: WebSocketErrorClassificationProfile,
|
||||
) -> Option<ClassifiedWebSocketError> {
|
||||
let value = serde_json::from_str::<Value>(raw).ok()?;
|
||||
let event_type = value.get("type").and_then(Value::as_str)?;
|
||||
if event_type != "error" && event_type != "response.failed" {
|
||||
@@ -95,10 +104,11 @@ pub(super) fn classify_ws_error_frame(raw: &str) -> Option<ClassifiedWebSocketEr
|
||||
.or_else(|| value.pointer("/error/type"))
|
||||
.and_then(Value::as_str)?
|
||||
.to_ascii_lowercase();
|
||||
let status = rotatable_error_status(&code)?;
|
||||
let status = rotatable_error_status(&code, profile)?;
|
||||
Some(ClassifiedWebSocketError {
|
||||
status,
|
||||
connection_fatal: code == "websocket_connection_limit_reached",
|
||||
connection_fatal: profile == WebSocketErrorClassificationProfile::Pooled
|
||||
&& code == "websocket_connection_limit_reached",
|
||||
})
|
||||
}
|
||||
|
||||
@@ -169,7 +179,10 @@ pub(super) fn retry_after_seconds_from_body(body: &str) -> Option<u64> {
|
||||
(resets_at > now).then_some(resets_at - now)
|
||||
}
|
||||
|
||||
fn rotatable_error_status(code: &str) -> Option<StatusCode> {
|
||||
fn rotatable_error_status(
|
||||
code: &str,
|
||||
profile: WebSocketErrorClassificationProfile,
|
||||
) -> Option<StatusCode> {
|
||||
match code {
|
||||
"usage_limit_reached" | "rate_limit_exceeded" | "rate_limit_reached" => {
|
||||
Some(StatusCode::TOO_MANY_REQUESTS)
|
||||
@@ -180,7 +193,11 @@ fn rotatable_error_status(code: &str) -> Option<StatusCode> {
|
||||
}
|
||||
"forbidden" | "account_banned" | "banned" => Some(StatusCode::FORBIDDEN),
|
||||
"previous_response_not_found" => Some(StatusCode::BAD_REQUEST),
|
||||
"websocket_connection_limit_reached" => Some(StatusCode::SERVICE_UNAVAILABLE),
|
||||
"websocket_connection_limit_reached"
|
||||
if profile == WebSocketErrorClassificationProfile::Pooled =>
|
||||
{
|
||||
Some(StatusCode::SERVICE_UNAVAILABLE)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
use std::{pin::Pin, sync::Arc, time::Instant};
|
||||
use std::{
|
||||
pin::Pin,
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use thiserror::Error;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio_tungstenite::{
|
||||
connect_async,
|
||||
tungstenite::{
|
||||
client::IntoClientRequest, http::Request as WsRequest, Error as WsError, Message,
|
||||
},
|
||||
use tokio::{sync::Mutex, time::timeout};
|
||||
use tokio_tungstenite::tungstenite::{
|
||||
client::IntoClientRequest, http::Request as WsRequest, Error as WsError, Message,
|
||||
};
|
||||
|
||||
use futures::{channel::mpsc, SinkExt, Stream, StreamExt};
|
||||
@@ -18,12 +19,14 @@ use crate::codex::gateway::transport::{
|
||||
};
|
||||
|
||||
mod codec;
|
||||
mod opening;
|
||||
mod pool;
|
||||
|
||||
use codec::{
|
||||
classify_ws_error_frame, codex_websocket_transport_error, is_internal_websocket_event,
|
||||
is_terminal_websocket_event, retry_after_seconds_from_body, websocket_event_type,
|
||||
websocket_message_text, websocket_request_body, websocket_sse_chunk,
|
||||
WebSocketErrorClassificationProfile,
|
||||
};
|
||||
use pool::{
|
||||
CodexWebSocketConnectionMetadata, CodexWsStream, PooledWebSocketConnection,
|
||||
@@ -31,6 +34,8 @@ use pool::{
|
||||
};
|
||||
pub use pool::{CodexWebSocketPool, CodexWebSocketPoolConfig, CodexWebSocketPoolKey};
|
||||
|
||||
const WEBSOCKET_OPEN_TIMEOUT: Duration = Duration::from_secs(20);
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CodexTransport {
|
||||
HttpSse,
|
||||
@@ -52,6 +57,8 @@ pub enum CodexWebSocketError {
|
||||
InvalidRequest(#[from] tokio_tungstenite::tungstenite::http::Error),
|
||||
#[error("websocket transport error: {0}")]
|
||||
Transport(#[source] WsError),
|
||||
#[error("websocket handshake timed out after {timeout:?}")]
|
||||
OpenTimeout { timeout: Duration },
|
||||
#[error("websocket handshake returned status {status}: {body}")]
|
||||
Upstream {
|
||||
status: StatusCode,
|
||||
@@ -99,6 +106,14 @@ struct WebSocketPoolReturn {
|
||||
}
|
||||
|
||||
impl ActiveWebSocket {
|
||||
fn error_classification_profile(&self) -> WebSocketErrorClassificationProfile {
|
||||
if self.pool_return.is_some() {
|
||||
WebSocketErrorClassificationProfile::Pooled
|
||||
} else {
|
||||
WebSocketErrorClassificationProfile::OneShot
|
||||
}
|
||||
}
|
||||
|
||||
async fn finish(self) {
|
||||
let Self {
|
||||
websocket,
|
||||
@@ -288,7 +303,8 @@ async fn create_response_via_websocket_stream_inner(
|
||||
capture_internal_rate_limit_event(&raw, &rate_limit_updates).await;
|
||||
continue;
|
||||
}
|
||||
if let Some(classified) = classify_ws_error_frame(&raw) {
|
||||
let classification_profile = active.error_classification_profile();
|
||||
if let Some(classified) = classify_ws_error_frame(&raw, classification_profile) {
|
||||
if classified.connection_fatal {
|
||||
active.discard().await;
|
||||
} else {
|
||||
@@ -405,11 +421,25 @@ async fn acquire_websocket(
|
||||
async fn connect_websocket(
|
||||
base_url: &str,
|
||||
headers: HeaderMap,
|
||||
) -> Result<(CodexWsStream, CodexWebSocketConnectionMetadata), CodexWebSocketError> {
|
||||
connect_websocket_with_timeout(base_url, headers, WEBSOCKET_OPEN_TIMEOUT).await
|
||||
}
|
||||
|
||||
async fn connect_websocket_with_timeout(
|
||||
base_url: &str,
|
||||
headers: HeaderMap,
|
||||
open_timeout: Duration,
|
||||
) -> Result<(CodexWsStream, CodexWebSocketConnectionMetadata), CodexWebSocketError> {
|
||||
let ws_request = build_ws_request(base_url, headers)?;
|
||||
let (websocket, handshake_response) = connect_async(ws_request)
|
||||
.await
|
||||
.map_err(codex_websocket_transport_error)?;
|
||||
let (websocket, handshake_response) = timeout(
|
||||
open_timeout,
|
||||
opening::connect_with_original_opening_handshake(ws_request),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| CodexWebSocketError::OpenTimeout {
|
||||
timeout: open_timeout,
|
||||
})?
|
||||
.map_err(codex_websocket_transport_error)?;
|
||||
Ok((
|
||||
websocket,
|
||||
CodexWebSocketConnectionMetadata::from_headers(handshake_response.headers()),
|
||||
@@ -504,3 +534,34 @@ pub async fn append_rate_limit_updates(
|
||||
headers.extend(rate_limits_to_header_pairs(update));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use reqwest::header::HeaderMap;
|
||||
use tokio::{net::TcpListener, time::Duration};
|
||||
|
||||
use super::{connect_websocket_with_timeout, CodexWebSocketError};
|
||||
|
||||
#[tokio::test]
|
||||
async fn connect_websocket_with_timeout_should_fail_when_handshake_stalls() {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move {
|
||||
let (_stream, _) = listener.accept().await.unwrap();
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
});
|
||||
|
||||
let result = connect_websocket_with_timeout(
|
||||
&format!("http://{addr}"),
|
||||
HeaderMap::new(),
|
||||
Duration::from_millis(10),
|
||||
)
|
||||
.await;
|
||||
|
||||
let Err(CodexWebSocketError::OpenTimeout { timeout }) = result else {
|
||||
panic!("expected websocket open timeout");
|
||||
};
|
||||
assert_eq!(timeout, Duration::from_millis(10));
|
||||
server.abort();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
|
||||
use rustls::{ClientConfig, RootCertStore};
|
||||
use rustls_pki_types::ServerName;
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::TcpStream,
|
||||
};
|
||||
use tokio_rustls::TlsConnector;
|
||||
use tokio_tungstenite::{
|
||||
tungstenite::{
|
||||
error::{CapacityError, Error as WsError, ProtocolError, TlsError, UrlError},
|
||||
handshake::{
|
||||
client::{generate_key, Response as WsResponse},
|
||||
derive_accept_key,
|
||||
},
|
||||
http::{Request as WsRequest, StatusCode, Uri},
|
||||
protocol::Role,
|
||||
},
|
||||
MaybeTlsStream, WebSocketStream,
|
||||
};
|
||||
|
||||
use super::pool::CodexWsStream;
|
||||
|
||||
const MAX_OPENING_RESPONSE_BYTES: usize = 64 * 1024;
|
||||
const ORIGINAL_WS_PERMESSAGE_DEFLATE_EXTENSION: &str = "permessage-deflate; client_max_window_bits";
|
||||
|
||||
const ORIGINAL_WS_HEADER_ORDER: &[&str] = &[
|
||||
"authorization",
|
||||
"chatgpt-account-id",
|
||||
"originator",
|
||||
"user-agent",
|
||||
"sec-ch-ua",
|
||||
"sec-ch-ua-mobile",
|
||||
"sec-ch-ua-platform",
|
||||
"accept-encoding",
|
||||
"accept-language",
|
||||
"sec-fetch-site",
|
||||
"sec-fetch-mode",
|
||||
"sec-fetch-dest",
|
||||
"cookie",
|
||||
"openai-beta",
|
||||
"x-openai-internal-codex-residency",
|
||||
"x-client-request-id",
|
||||
"x-codex-installation-id",
|
||||
"session_id",
|
||||
"x-codex-window-id",
|
||||
"x-codex-turn-state",
|
||||
"x-codex-turn-metadata",
|
||||
"x-codex-beta-features",
|
||||
"x-responsesapi-include-timing-metrics",
|
||||
"version",
|
||||
"x-codex-parent-thread-id",
|
||||
"x-openai-subagent",
|
||||
];
|
||||
|
||||
pub(super) async fn connect_with_original_opening_handshake(
|
||||
mut request: WsRequest<()>,
|
||||
) -> Result<(CodexWsStream, WsResponse), WsError> {
|
||||
ensure_websocket_key(&mut request)?;
|
||||
let uri = request.uri().clone();
|
||||
let mut stream = connect_stream(&uri).await?;
|
||||
let request_bytes = opening_request_bytes(&request)?;
|
||||
|
||||
stream
|
||||
.write_all(&request_bytes)
|
||||
.await
|
||||
.map_err(WsError::Io)?;
|
||||
stream.flush().await.map_err(WsError::Io)?;
|
||||
|
||||
let (response, buffered) = read_opening_response(&mut stream).await?;
|
||||
if response.status() != StatusCode::SWITCHING_PROTOCOLS {
|
||||
return Err(WsError::Http(Box::new(response)));
|
||||
}
|
||||
verify_accept_key(&request, &response)?;
|
||||
|
||||
let websocket =
|
||||
WebSocketStream::from_partially_read(stream, buffered, Role::Client, None).await;
|
||||
Ok((websocket, response))
|
||||
}
|
||||
|
||||
fn ensure_websocket_key(request: &mut WsRequest<()>) -> Result<(), WsError> {
|
||||
if request.headers().contains_key("Sec-WebSocket-Key") {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
request
|
||||
.headers_mut()
|
||||
.insert("Sec-WebSocket-Key", HeaderValue::from_str(&generate_key())?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn connect_stream(uri: &Uri) -> Result<MaybeTlsStream<TcpStream>, WsError> {
|
||||
let host = uri.host().ok_or(UrlError::NoHostName)?;
|
||||
if host.is_empty() {
|
||||
return Err(UrlError::EmptyHostName.into());
|
||||
}
|
||||
let port = uri
|
||||
.port_u16()
|
||||
.or_else(|| match uri.scheme_str() {
|
||||
Some("wss") => Some(443),
|
||||
Some("ws") => Some(80),
|
||||
_ => None,
|
||||
})
|
||||
.ok_or(UrlError::UnsupportedUrlScheme)?;
|
||||
|
||||
let socket = TcpStream::connect((host, port))
|
||||
.await
|
||||
.map_err(WsError::Io)?;
|
||||
|
||||
match uri.scheme_str() {
|
||||
Some("ws") => Ok(MaybeTlsStream::Plain(socket)),
|
||||
Some("wss") => {
|
||||
let server_name = ServerName::try_from(host.to_string())
|
||||
.map_err(|_| WsError::Tls(TlsError::InvalidDnsName))?;
|
||||
let connector = TlsConnector::from(Arc::new(rustls_client_config()?));
|
||||
let stream = connector
|
||||
.connect(server_name, socket)
|
||||
.await
|
||||
.map_err(WsError::Io)?;
|
||||
Ok(MaybeTlsStream::Rustls(stream))
|
||||
}
|
||||
_ => Err(UrlError::UnsupportedUrlScheme.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn rustls_client_config() -> Result<ClientConfig, WsError> {
|
||||
let mut root_store = RootCertStore::empty();
|
||||
let rustls_native_certs::CertificateResult { certs, errors, .. } =
|
||||
rustls_native_certs::load_native_certs();
|
||||
if !errors.is_empty() {
|
||||
return Err(WsError::Io(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
format!("failed to load native root certificates: {errors:?}"),
|
||||
)));
|
||||
}
|
||||
|
||||
let (added, _) = root_store.add_parsable_certificates(certs);
|
||||
if added == 0 {
|
||||
return Err(WsError::Io(std::io::Error::new(
|
||||
std::io::ErrorKind::NotFound,
|
||||
"no native root certificates found",
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(ClientConfig::builder()
|
||||
.with_root_certificates(root_store)
|
||||
.with_no_client_auth())
|
||||
}
|
||||
|
||||
fn opening_request_bytes(request: &WsRequest<()>) -> Result<Vec<u8>, WsError> {
|
||||
let path = request
|
||||
.uri()
|
||||
.path_and_query()
|
||||
.ok_or(UrlError::NoPathOrQuery)?
|
||||
.as_str();
|
||||
let host = host_header(request.uri())?;
|
||||
let key = request
|
||||
.headers()
|
||||
.get("Sec-WebSocket-Key")
|
||||
.ok_or_else(|| ProtocolError::MissingSecWebSocketKey)?
|
||||
.as_bytes();
|
||||
|
||||
let mut bytes = Vec::new();
|
||||
bytes.extend_from_slice(format!("GET {path} HTTP/1.1\r\n").as_bytes());
|
||||
write_header(&mut bytes, "Host", host.as_bytes());
|
||||
write_header(&mut bytes, "Connection", b"Upgrade");
|
||||
write_header(&mut bytes, "Upgrade", b"websocket");
|
||||
write_header(&mut bytes, "Sec-WebSocket-Version", b"13");
|
||||
write_header(
|
||||
&mut bytes,
|
||||
"Sec-WebSocket-Extensions",
|
||||
ORIGINAL_WS_PERMESSAGE_DEFLATE_EXTENSION.as_bytes(),
|
||||
);
|
||||
write_header(&mut bytes, "Sec-WebSocket-Key", key);
|
||||
write_original_business_headers(&mut bytes, request.headers());
|
||||
bytes.extend_from_slice(b"\r\n");
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
fn host_header(uri: &Uri) -> Result<String, WsError> {
|
||||
let host = uri.host().ok_or(UrlError::NoHostName)?;
|
||||
if host.is_empty() {
|
||||
return Err(UrlError::EmptyHostName.into());
|
||||
}
|
||||
let Some(port) = uri.port_u16() else {
|
||||
return Ok(host.to_string());
|
||||
};
|
||||
let is_default = matches!(
|
||||
(uri.scheme_str(), port),
|
||||
(Some("ws"), 80) | (Some("wss"), 443)
|
||||
);
|
||||
if is_default {
|
||||
Ok(host.to_string())
|
||||
} else {
|
||||
Ok(format!("{host}:{port}"))
|
||||
}
|
||||
}
|
||||
|
||||
fn write_original_business_headers(bytes: &mut Vec<u8>, headers: &HeaderMap) {
|
||||
let mut emitted = Vec::new();
|
||||
for name in ORIGINAL_WS_HEADER_ORDER {
|
||||
if write_named_header(bytes, headers, name) {
|
||||
emitted.push(*name);
|
||||
}
|
||||
}
|
||||
|
||||
for (name, value) in headers {
|
||||
let lower = name.as_str();
|
||||
if emitted.iter().any(|seen| seen.eq_ignore_ascii_case(lower))
|
||||
|| is_opening_header(lower)
|
||||
|| lower == "content-type"
|
||||
|| lower == "accept"
|
||||
{
|
||||
continue;
|
||||
}
|
||||
write_header(bytes, original_header_name(lower), value.as_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
fn write_named_header(bytes: &mut Vec<u8>, headers: &HeaderMap, name: &str) -> bool {
|
||||
let Some(value) = headers.get(name) else {
|
||||
return false;
|
||||
};
|
||||
write_header(bytes, original_header_name(name), value.as_bytes());
|
||||
true
|
||||
}
|
||||
|
||||
fn write_header(bytes: &mut Vec<u8>, name: &str, value: &[u8]) {
|
||||
bytes.extend_from_slice(name.as_bytes());
|
||||
bytes.extend_from_slice(b": ");
|
||||
bytes.extend_from_slice(value);
|
||||
bytes.extend_from_slice(b"\r\n");
|
||||
}
|
||||
|
||||
fn is_opening_header(name: &str) -> bool {
|
||||
matches!(
|
||||
name,
|
||||
"host"
|
||||
| "connection"
|
||||
| "upgrade"
|
||||
| "sec-websocket-version"
|
||||
| "sec-websocket-extensions"
|
||||
| "sec-websocket-key"
|
||||
)
|
||||
}
|
||||
|
||||
fn original_header_name(name: &str) -> &str {
|
||||
match name {
|
||||
"authorization" => "Authorization",
|
||||
"chatgpt-account-id" => "ChatGPT-Account-Id",
|
||||
"user-agent" => "User-Agent",
|
||||
"accept-encoding" => "Accept-Encoding",
|
||||
"accept-language" => "Accept-Language",
|
||||
"openai-beta" => "OpenAI-Beta",
|
||||
"cookie" => "Cookie",
|
||||
"content-type" => "Content-Type",
|
||||
"accept" => "Accept",
|
||||
_ => name,
|
||||
}
|
||||
}
|
||||
|
||||
async fn read_opening_response(
|
||||
stream: &mut MaybeTlsStream<TcpStream>,
|
||||
) -> Result<(WsResponse, Vec<u8>), WsError> {
|
||||
let mut bytes = Vec::new();
|
||||
let mut chunk = [0_u8; 1024];
|
||||
let header_end = loop {
|
||||
let read = stream.read(&mut chunk).await.map_err(WsError::Io)?;
|
||||
if read == 0 {
|
||||
return Err(ProtocolError::HandshakeIncomplete.into());
|
||||
}
|
||||
bytes.extend_from_slice(&chunk[..read]);
|
||||
if bytes.len() > MAX_OPENING_RESPONSE_BYTES {
|
||||
return Err(CapacityError::MessageTooLong {
|
||||
size: bytes.len(),
|
||||
max_size: MAX_OPENING_RESPONSE_BYTES,
|
||||
}
|
||||
.into());
|
||||
}
|
||||
if let Some(index) = find_header_end(&bytes) {
|
||||
break index;
|
||||
}
|
||||
};
|
||||
|
||||
let body_start = header_end + 4;
|
||||
let mut body = bytes[body_start..].to_vec();
|
||||
let mut response = parse_response_head(&bytes[..header_end])?;
|
||||
if response.status() != StatusCode::SWITCHING_PROTOCOLS {
|
||||
read_response_body(stream, response.headers(), &mut body).await?;
|
||||
*response.body_mut() = Some(body);
|
||||
return Ok((response, Vec::new()));
|
||||
}
|
||||
|
||||
Ok((response, body))
|
||||
}
|
||||
|
||||
fn find_header_end(bytes: &[u8]) -> Option<usize> {
|
||||
bytes.windows(4).position(|window| window == b"\r\n\r\n")
|
||||
}
|
||||
|
||||
fn parse_response_head(head: &[u8]) -> Result<WsResponse, WsError> {
|
||||
let head = std::str::from_utf8(head)?;
|
||||
let mut lines = head.split("\r\n");
|
||||
let status_line = lines
|
||||
.next()
|
||||
.ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidData, "empty response"))?;
|
||||
let status = status_line
|
||||
.split_whitespace()
|
||||
.nth(1)
|
||||
.ok_or_else(|| {
|
||||
std::io::Error::new(std::io::ErrorKind::InvalidData, "missing response status")
|
||||
})?
|
||||
.parse::<u16>()
|
||||
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidData, error))?;
|
||||
|
||||
let mut response = WsResponse::new(None);
|
||||
*response.status_mut() = StatusCode::from_u16(status)?;
|
||||
for line in lines {
|
||||
let Some((name, value)) = line.split_once(':') else {
|
||||
continue;
|
||||
};
|
||||
response.headers_mut().append(
|
||||
HeaderName::from_bytes(name.trim().as_bytes())?,
|
||||
HeaderValue::from_bytes(value.trim_start().as_bytes())?,
|
||||
);
|
||||
}
|
||||
Ok(response)
|
||||
}
|
||||
|
||||
async fn read_response_body(
|
||||
stream: &mut MaybeTlsStream<TcpStream>,
|
||||
headers: &HeaderMap,
|
||||
body: &mut Vec<u8>,
|
||||
) -> Result<(), WsError> {
|
||||
let Some(content_length) = headers
|
||||
.get("content-length")
|
||||
.and_then(|value| value.to_str().ok())
|
||||
.and_then(|value| value.parse::<usize>().ok())
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
while body.len() < content_length {
|
||||
let remaining = content_length - body.len();
|
||||
let mut chunk = vec![0_u8; remaining.min(1024)];
|
||||
let read = stream.read(&mut chunk).await.map_err(WsError::Io)?;
|
||||
if read == 0 {
|
||||
break;
|
||||
}
|
||||
body.extend_from_slice(&chunk[..read]);
|
||||
}
|
||||
body.truncate(content_length);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn verify_accept_key(request: &WsRequest<()>, response: &WsResponse) -> Result<(), WsError> {
|
||||
let key = request
|
||||
.headers()
|
||||
.get("Sec-WebSocket-Key")
|
||||
.ok_or(ProtocolError::MissingSecWebSocketKey)?;
|
||||
let expected = derive_accept_key(key.as_bytes());
|
||||
let actual = response
|
||||
.headers()
|
||||
.get("Sec-WebSocket-Accept")
|
||||
.ok_or(ProtocolError::SecWebSocketAcceptKeyMismatch)?;
|
||||
|
||||
if actual == expected.as_str() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ProtocolError::SecWebSocketAcceptKeyMismatch.into())
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ pub struct ModelService {
|
||||
snapshot_repository: Option<ModelSnapshotRepository>,
|
||||
account_repository: Option<AccountRepository>,
|
||||
account_pool: Arc<Mutex<AccountPool>>,
|
||||
fingerprint: Fingerprint,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
@@ -52,12 +53,14 @@ impl ModelService {
|
||||
snapshot_repository: Option<ModelSnapshotRepository>,
|
||||
account_repository: Option<AccountRepository>,
|
||||
account_pool: Arc<Mutex<AccountPool>>,
|
||||
fingerprint: Fingerprint,
|
||||
) -> Self {
|
||||
Self {
|
||||
config,
|
||||
snapshot_repository,
|
||||
account_repository,
|
||||
account_pool,
|
||||
fingerprint,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,7 +108,7 @@ impl ModelService {
|
||||
CodexBackendClient::new(
|
||||
client,
|
||||
self.config.api.base_url.clone(),
|
||||
Fingerprint::default_codex_desktop(),
|
||||
self.fingerprint.clone(),
|
||||
)
|
||||
})
|
||||
.map_err(|_| ModelServiceError::BuildClient)?;
|
||||
|
||||
@@ -109,13 +109,14 @@ impl ChatService {
|
||||
);
|
||||
|
||||
let mut excluded_account_ids = Vec::new();
|
||||
let mut model_unsupported_retry_used = false;
|
||||
let response = loop {
|
||||
self.upstream
|
||||
.stagger_request(acquired.previous_slot_at)
|
||||
.await;
|
||||
let response = self
|
||||
.upstream
|
||||
.send_codex_request_with_refresh_retry(
|
||||
.send_codex_request_with_upstream_retries(
|
||||
&codex_request,
|
||||
&acquired.account,
|
||||
request_id,
|
||||
@@ -126,7 +127,12 @@ impl ChatService {
|
||||
match response {
|
||||
Ok(response) => break response,
|
||||
Err(error) => {
|
||||
if let Some(retry) = classify_upstream_account_retry(&error) {
|
||||
if let Some(retry) =
|
||||
classify_upstream_account_retry(&error, model_unsupported_retry_used)
|
||||
{
|
||||
if retry.is_model_unsupported() {
|
||||
model_unsupported_retry_used = true;
|
||||
}
|
||||
let fallback = self
|
||||
.upstream
|
||||
.apply_retry_and_acquire_fallback(
|
||||
@@ -203,6 +209,7 @@ impl ChatService {
|
||||
&response.body,
|
||||
&display_model,
|
||||
include_reasoning,
|
||||
codex_request.tuple_schema.as_ref(),
|
||||
) {
|
||||
Ok(Some(body)) => Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
@@ -237,8 +244,12 @@ impl ChatService {
|
||||
.into_response(),
|
||||
}
|
||||
} else {
|
||||
match chat_completion_from_codex_sse(&response.body, &display_model, include_reasoning)
|
||||
{
|
||||
match chat_completion_from_codex_sse(
|
||||
&response.body,
|
||||
&display_model,
|
||||
include_reasoning,
|
||||
codex_request.tuple_schema.as_ref(),
|
||||
) {
|
||||
Ok(Some(body)) => (StatusCode::OK, Json(body)).into_response(),
|
||||
Ok(None) => (
|
||||
StatusCode::BAD_GATEWAY,
|
||||
|
||||
@@ -16,6 +16,7 @@ use crate::{
|
||||
#[derive(Clone)]
|
||||
pub struct DiagnosticsService {
|
||||
config: Arc<AppConfig>,
|
||||
fingerprint: Fingerprint,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
@@ -33,17 +34,25 @@ pub struct UpstreamProbeResult {
|
||||
}
|
||||
|
||||
impl DiagnosticsService {
|
||||
pub fn new(config: Arc<AppConfig>) -> Self {
|
||||
Self { config }
|
||||
pub fn new(config: Arc<AppConfig>, fingerprint: Fingerprint) -> Self {
|
||||
Self {
|
||||
config,
|
||||
fingerprint,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn fingerprint(&self) -> &Fingerprint {
|
||||
&self.fingerprint
|
||||
}
|
||||
|
||||
pub async fn probe_upstream(&self, request_id: &str) -> UpstreamProbeResult {
|
||||
let started_at = Instant::now();
|
||||
let fingerprint = Fingerprint::default_codex_desktop();
|
||||
let client = match build_reqwest_client(self.config.tls.force_http11) {
|
||||
Ok(client) => {
|
||||
CodexBackendClient::new(client, self.config.api.base_url.clone(), fingerprint)
|
||||
}
|
||||
Ok(client) => CodexBackendClient::new(
|
||||
client,
|
||||
self.config.api.base_url.clone(),
|
||||
self.fingerprint.clone(),
|
||||
),
|
||||
Err(error) => {
|
||||
return self.unreachable_probe(
|
||||
None,
|
||||
|
||||
@@ -1,146 +0,0 @@
|
||||
use axum::http::StatusCode;
|
||||
use secrecy::SecretString;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::{
|
||||
codex::accounts::{
|
||||
model::{Account, AccountStatus},
|
||||
repository::TokenUpdate,
|
||||
},
|
||||
codex::events::event::{EventLevel, EventLog},
|
||||
codex::gateway::oauth::{RefreshFailure, TokenPair},
|
||||
codex::gateway::transport::types::CodexResponsesRequest,
|
||||
};
|
||||
|
||||
use super::CodexUpstreamDependencies;
|
||||
|
||||
pub(super) async fn refresh_account_after_unauthorized(
|
||||
deps: &CodexUpstreamDependencies,
|
||||
request: &CodexResponsesRequest,
|
||||
account: &Account,
|
||||
request_id: &str,
|
||||
) -> Option<Account> {
|
||||
if !deps.config.auth.refresh_enabled {
|
||||
return None;
|
||||
}
|
||||
let refresh_token = account.refresh_token.as_deref()?;
|
||||
let refresher = deps.token_refresher.as_ref()?;
|
||||
match refresher.refresh(refresh_token).await {
|
||||
Ok(tokens) => persist_refreshed_account(deps, account, tokens).await,
|
||||
Err(failure) => {
|
||||
mark_refresh_failure(deps, account, failure, request_id, &request.model).await;
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn persist_refreshed_account(
|
||||
deps: &CodexUpstreamDependencies,
|
||||
account: &Account,
|
||||
tokens: TokenPair,
|
||||
) -> Option<Account> {
|
||||
let repo = deps.account_repository.as_ref()?;
|
||||
let access_token = tokens.access_token;
|
||||
let refresh_token = tokens.refresh_token;
|
||||
repo.update_tokens(
|
||||
&account.id,
|
||||
TokenUpdate {
|
||||
access_token: SecretString::new(access_token.clone().into()),
|
||||
refresh_token: refresh_token
|
||||
.clone()
|
||||
.map(|token| SecretString::new(token.into())),
|
||||
access_token_expires_at: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.ok()?;
|
||||
|
||||
let mut refreshed = account.clone();
|
||||
refreshed.access_token = access_token;
|
||||
if let Some(refresh_token) = refresh_token {
|
||||
refreshed.refresh_token = Some(refresh_token);
|
||||
}
|
||||
refreshed.status = AccountStatus::Active;
|
||||
deps.account_pool.lock().await.insert(refreshed.clone());
|
||||
deps.websocket_pool.evict_account(&account.id).await;
|
||||
Some(refreshed)
|
||||
}
|
||||
|
||||
async fn mark_refresh_failure(
|
||||
deps: &CodexUpstreamDependencies,
|
||||
account: &Account,
|
||||
failure: RefreshFailure,
|
||||
request_id: &str,
|
||||
model: &str,
|
||||
) {
|
||||
let status = status_for_refresh_failure(failure);
|
||||
if let Some(status) = status {
|
||||
if let Some(repo) = deps.account_repository.as_ref() {
|
||||
let _ = repo.set_status(&account.id, status).await;
|
||||
}
|
||||
let mut updated = account.clone();
|
||||
updated.status = status;
|
||||
deps.account_pool.lock().await.insert(updated);
|
||||
deps.websocket_pool.evict_account(&account.id).await;
|
||||
}
|
||||
log_account_refresh_failure(deps, account, failure, status, request_id, model).await;
|
||||
}
|
||||
|
||||
fn status_for_refresh_failure(failure: RefreshFailure) -> Option<AccountStatus> {
|
||||
match failure {
|
||||
RefreshFailure::InvalidGrant => Some(AccountStatus::Expired),
|
||||
RefreshFailure::QuotaExhausted => Some(AccountStatus::QuotaExhausted),
|
||||
RefreshFailure::Banned => Some(AccountStatus::Banned),
|
||||
RefreshFailure::Disabled => Some(AccountStatus::Disabled),
|
||||
RefreshFailure::Transport => None,
|
||||
}
|
||||
}
|
||||
|
||||
async fn log_account_refresh_failure(
|
||||
deps: &CodexUpstreamDependencies,
|
||||
account: &Account,
|
||||
failure: RefreshFailure,
|
||||
status: Option<AccountStatus>,
|
||||
request_id: &str,
|
||||
model: &str,
|
||||
) {
|
||||
let mut event = EventLog::new(
|
||||
"account.refresh",
|
||||
EventLevel::Warn,
|
||||
"上游 401 后账户刷新失败",
|
||||
);
|
||||
event.request_id = Some(request_id.to_string());
|
||||
event.account_id = Some(account.id.clone());
|
||||
event.route = Some("/v1/responses".to_string());
|
||||
event.model = Some(model.to_string());
|
||||
event.status_code = Some(i64::from(StatusCode::UNAUTHORIZED.as_u16()));
|
||||
event.metadata = json!({
|
||||
"trigger": "upstream_401",
|
||||
"failure": refresh_failure_value(failure),
|
||||
"accountStatus": status.map(account_status_value),
|
||||
});
|
||||
if let Err(error) = deps.logs.record(event).await {
|
||||
tracing::warn!(error = %error, "写入账户刷新事件日志失败");
|
||||
}
|
||||
}
|
||||
|
||||
fn refresh_failure_value(failure: RefreshFailure) -> &'static str {
|
||||
match failure {
|
||||
RefreshFailure::InvalidGrant => "invalidGrant",
|
||||
RefreshFailure::QuotaExhausted => "quotaExhausted",
|
||||
RefreshFailure::Banned => "banned",
|
||||
RefreshFailure::Disabled => "disabled",
|
||||
RefreshFailure::Transport => "transport",
|
||||
}
|
||||
}
|
||||
|
||||
fn account_status_value(status: AccountStatus) -> &'static str {
|
||||
match status {
|
||||
AccountStatus::Active => "active",
|
||||
AccountStatus::Expired => "expired",
|
||||
AccountStatus::QuotaExhausted => "quotaExhausted",
|
||||
AccountStatus::Refreshing => "refreshing",
|
||||
AccountStatus::Disabled => "disabled",
|
||||
AccountStatus::Banned => "banned",
|
||||
}
|
||||
}
|
||||
@@ -3,12 +3,15 @@ use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::Serialize;
|
||||
use sha2::{Digest, Sha256};
|
||||
use sqlx::{Row, SqlitePool};
|
||||
use thiserror::Error;
|
||||
use tokio::sync::RwLock;
|
||||
use tokio::time::interval;
|
||||
|
||||
use crate::codex::gateway::conversation_identity::derive_stable_conversation_key;
|
||||
use crate::codex::gateway::transport::types::CodexResponsesRequest;
|
||||
|
||||
/// 会话亲和性条目 - 记录响应ID到账户的映射
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AffinityEntry {
|
||||
@@ -117,10 +120,64 @@ from session_affinities
|
||||
where expires_at > ?
|
||||
order by created_at asc, response_id asc";
|
||||
|
||||
pub(super) fn compute_variant_hash(value: &impl Serialize) -> Option<String> {
|
||||
serde_json::to_string(value)
|
||||
.ok()
|
||||
.filter(|serialized| !serialized.is_empty())
|
||||
pub(super) fn compute_variant_hash(request: &CodexResponsesRequest) -> String {
|
||||
compute_variant_hash_with_identity(request, request.variant_identity.as_deref())
|
||||
}
|
||||
|
||||
fn compute_variant_hash_with_identity(
|
||||
request: &CodexResponsesRequest,
|
||||
identity: Option<&str>,
|
||||
) -> String {
|
||||
let tools_json = request
|
||||
.tools
|
||||
.as_ref()
|
||||
.map_or_else(|| "[]".to_string(), |tools| tools_json(tools));
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(request.instructions.as_bytes());
|
||||
hasher.update(b"\0");
|
||||
hasher.update(tools_json.as_bytes());
|
||||
if let Some(identity) = identity
|
||||
.map(str::trim)
|
||||
.filter(|identity| !identity.is_empty())
|
||||
{
|
||||
hasher.update(b"\0");
|
||||
hasher.update(identity.as_bytes());
|
||||
}
|
||||
hex::encode(hasher.finalize()).chars().take(12).collect()
|
||||
}
|
||||
|
||||
fn tools_json(tools: &[serde_json::Value]) -> String {
|
||||
serde_json::to_string(tools).unwrap_or_else(|_| "[]".to_string())
|
||||
}
|
||||
|
||||
pub(super) fn prepare_variant_identity(request: &mut CodexResponsesRequest) {
|
||||
request.variant_identity = build_variant_identity(request);
|
||||
}
|
||||
|
||||
fn build_variant_identity(request: &CodexResponsesRequest) -> Option<String> {
|
||||
let mut parts = Vec::with_capacity(2);
|
||||
if let Some(window_id) = non_empty_string(request.codex_window_id.as_deref()) {
|
||||
parts.push(format!("window:{window_id}"));
|
||||
}
|
||||
if request.explicit_prompt_cache_key
|
||||
|| non_empty_string(request.client_conversation_id.as_deref()).is_some()
|
||||
{
|
||||
if let Some(anchor) = derive_stable_conversation_key(request) {
|
||||
parts.push(format!("anchor:{anchor}"));
|
||||
}
|
||||
}
|
||||
|
||||
(!parts.is_empty()).then(|| parts.join("\0"))
|
||||
}
|
||||
|
||||
fn non_empty_string(value: Option<&str>) -> Option<&str> {
|
||||
value.map(str::trim).filter(|value| !value.is_empty())
|
||||
}
|
||||
|
||||
pub(super) fn hash_instructions(instructions: Option<&str>) -> String {
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(instructions.unwrap_or_default().as_bytes());
|
||||
hex::encode(hasher.finalize())
|
||||
}
|
||||
|
||||
impl SessionAffinityRepository {
|
||||
@@ -229,13 +286,7 @@ impl SessionAffinityMap {
|
||||
function_call_ids: Option<Vec<String>>,
|
||||
variant_hash: Option<String>,
|
||||
) -> AffinityEntry {
|
||||
let instructions_hash = instructions.map(|s| {
|
||||
use sha2::{Digest, Sha256};
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(s.as_bytes());
|
||||
let result = hasher.finalize();
|
||||
hex::encode(result)
|
||||
});
|
||||
let instructions_hash = instructions.map(|value| hash_instructions(Some(value)));
|
||||
|
||||
let entry = AffinityEntry {
|
||||
account_id,
|
||||
@@ -572,16 +623,76 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_variant_hash_should_follow_serialized_request_body() {
|
||||
fn compute_variant_hash_should_follow_original_shape_contract() {
|
||||
let mut request = CodexResponsesRequest::new_http_sse(
|
||||
"gpt-5.5",
|
||||
"You are Codex.",
|
||||
vec![json!({"role": "user", "content": "hello"})],
|
||||
);
|
||||
let first = compute_variant_hash(&request).unwrap();
|
||||
request.tools = Some(vec![json!({"type": "function", "name": "shell"})]);
|
||||
let first = compute_variant_hash(&request);
|
||||
request.input = vec![
|
||||
json!({"role": "user", "content": "hello"}),
|
||||
json!({"role": "assistant", "content": "cached"}),
|
||||
json!({"role": "user", "content": "continue"}),
|
||||
];
|
||||
request.previous_response_id = Some("resp_dynamic".to_string());
|
||||
request.prompt_cache_key = Some("conversation_dynamic".to_string());
|
||||
request.include = Some(vec!["reasoning.encrypted_content".to_string()]);
|
||||
let same_shape = compute_variant_hash(&request);
|
||||
|
||||
request.instructions = "You are Codex with different instructions.".to_string();
|
||||
let second = compute_variant_hash(&request).unwrap();
|
||||
let different_instructions = compute_variant_hash(&request);
|
||||
|
||||
assert_eq!(first, same_shape);
|
||||
assert_ne!(first, different_instructions);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_variant_hash_should_include_optional_identity() {
|
||||
let request = CodexResponsesRequest::new_http_sse(
|
||||
"gpt-5.5",
|
||||
"You are Codex.",
|
||||
vec![json!({"role": "user", "content": "hello"})],
|
||||
);
|
||||
let first = compute_variant_hash_with_identity(&request, Some("window:main"));
|
||||
let second = compute_variant_hash_with_identity(&request, Some("window:review"));
|
||||
|
||||
assert_ne!(first, second);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_variant_hash_should_include_prepared_codex_window_identity() {
|
||||
let mut first = CodexResponsesRequest::new_http_sse(
|
||||
"gpt-5.5",
|
||||
"You are Codex.",
|
||||
vec![json!({"role": "user", "content": "hello"})],
|
||||
);
|
||||
first.codex_window_id = Some("main-window".to_string());
|
||||
prepare_variant_identity(&mut first);
|
||||
|
||||
let mut second = first.clone();
|
||||
second.codex_window_id = Some("review-window".to_string());
|
||||
prepare_variant_identity(&mut second);
|
||||
|
||||
assert_ne!(compute_variant_hash(&first), compute_variant_hash(&second));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_variant_hash_should_include_explicit_prompt_cache_anchor() {
|
||||
let mut first = CodexResponsesRequest::new_http_sse(
|
||||
"gpt-5.5",
|
||||
"You are Codex.",
|
||||
vec![json!({"role": "user", "content": "alpha"})],
|
||||
);
|
||||
first.prompt_cache_key = Some("shared-session".to_string());
|
||||
first.explicit_prompt_cache_key = true;
|
||||
prepare_variant_identity(&mut first);
|
||||
|
||||
let mut second = first.clone();
|
||||
second.input = vec![json!({"role": "user", "content": "beta"})];
|
||||
prepare_variant_identity(&mut second);
|
||||
|
||||
assert_ne!(compute_variant_hash(&first), compute_variant_hash(&second));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,24 +18,46 @@ const CLOUDFLARE_CHALLENGE_COOLDOWN_SECONDS: u64 = 10;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) enum UpstreamAccountRetry {
|
||||
ModelUnsupported { status: StatusCode },
|
||||
RateLimited { retry_after_seconds: u64 },
|
||||
QuotaExhausted,
|
||||
CloudflareChallenge { cooldown_seconds: u64 },
|
||||
CloudflarePathBlock,
|
||||
TokenInvalid { account_status: AccountStatus },
|
||||
Banned,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum UpstreamRequestRecovery {
|
||||
StripPreviousResponse { reason: HistoryRecoveryReason },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum HistoryRecoveryReason {
|
||||
PreviousResponseNotFound,
|
||||
UnansweredFunctionCall,
|
||||
}
|
||||
|
||||
impl UpstreamAccountRetry {
|
||||
pub(crate) fn status(self) -> StatusCode {
|
||||
match self {
|
||||
Self::ModelUnsupported { status } => status,
|
||||
Self::RateLimited { .. } => StatusCode::TOO_MANY_REQUESTS,
|
||||
Self::QuotaExhausted => StatusCode::PAYMENT_REQUIRED,
|
||||
Self::CloudflareChallenge { .. } => StatusCode::FORBIDDEN,
|
||||
Self::CloudflarePathBlock => StatusCode::BAD_GATEWAY,
|
||||
Self::TokenInvalid { .. } => StatusCode::UNAUTHORIZED,
|
||||
Self::Banned => StatusCode::FORBIDDEN,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn metadata(self, stream: bool) -> Value {
|
||||
match self {
|
||||
Self::ModelUnsupported { .. } => json!({
|
||||
"stream": stream,
|
||||
"retry": true,
|
||||
"reason": "modelUnsupported",
|
||||
}),
|
||||
Self::RateLimited {
|
||||
retry_after_seconds,
|
||||
} => json!({
|
||||
@@ -55,6 +77,17 @@ impl UpstreamAccountRetry {
|
||||
"reason": "cloudflareChallenge",
|
||||
"cooldownSeconds": cooldown_seconds,
|
||||
}),
|
||||
Self::CloudflarePathBlock => json!({
|
||||
"stream": stream,
|
||||
"retry": true,
|
||||
"reason": "cloudflarePathBlock",
|
||||
}),
|
||||
Self::TokenInvalid { account_status } => json!({
|
||||
"stream": stream,
|
||||
"retry": true,
|
||||
"reason": "tokenInvalid",
|
||||
"accountStatus": account_status_metadata(account_status),
|
||||
}),
|
||||
Self::Banned => json!({
|
||||
"stream": stream,
|
||||
"retry": true,
|
||||
@@ -62,12 +95,68 @@ impl UpstreamAccountRetry {
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_model_unsupported(self) -> bool {
|
||||
matches!(self, Self::ModelUnsupported { .. })
|
||||
}
|
||||
|
||||
pub(crate) fn preserve_history_account_affinity(self) -> bool {
|
||||
!self.is_model_unsupported()
|
||||
}
|
||||
}
|
||||
|
||||
impl UpstreamRequestRecovery {
|
||||
pub(crate) fn metadata(self, stream: bool, stale_response_id: Option<&str>) -> Value {
|
||||
match self {
|
||||
Self::StripPreviousResponse { reason } => json!({
|
||||
"stream": stream,
|
||||
"retry": true,
|
||||
"reason": reason.as_metadata_value(),
|
||||
"previousResponseId": stale_response_id,
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryRecoveryReason {
|
||||
fn as_metadata_value(self) -> &'static str {
|
||||
match self {
|
||||
Self::PreviousResponseNotFound => "previousResponseNotFound",
|
||||
Self::UnansweredFunctionCall => "unansweredFunctionCall",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn classify_upstream_request_recovery(
|
||||
error: &CodexClientError,
|
||||
recovery_already_used: bool,
|
||||
) -> Option<UpstreamRequestRecovery> {
|
||||
if recovery_already_used {
|
||||
return None;
|
||||
}
|
||||
if is_previous_response_not_found_error(error) {
|
||||
return Some(UpstreamRequestRecovery::StripPreviousResponse {
|
||||
reason: HistoryRecoveryReason::PreviousResponseNotFound,
|
||||
});
|
||||
}
|
||||
if is_unanswered_function_call_error(error) {
|
||||
return Some(UpstreamRequestRecovery::StripPreviousResponse {
|
||||
reason: HistoryRecoveryReason::UnansweredFunctionCall,
|
||||
});
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub(crate) fn classify_upstream_account_retry(
|
||||
error: &CodexClientError,
|
||||
model_unsupported_retry_used: bool,
|
||||
) -> Option<UpstreamAccountRetry> {
|
||||
match error {
|
||||
CodexClientError::Upstream { status, .. }
|
||||
if is_model_not_supported_error(error) && !model_unsupported_retry_used =>
|
||||
{
|
||||
Some(UpstreamAccountRetry::ModelUnsupported { status: *status })
|
||||
}
|
||||
CodexClientError::Upstream {
|
||||
status,
|
||||
retry_after_seconds,
|
||||
@@ -89,12 +178,101 @@ pub(crate) fn classify_upstream_account_retry(
|
||||
Some(UpstreamAccountRetry::Banned)
|
||||
}
|
||||
}
|
||||
CodexClientError::Upstream { status, body, .. }
|
||||
if *status == StatusCode::NOT_FOUND && body.trim().is_empty() =>
|
||||
{
|
||||
Some(UpstreamAccountRetry::CloudflarePathBlock)
|
||||
}
|
||||
CodexClientError::Upstream { status, body, .. } if *status == StatusCode::UNAUTHORIZED => {
|
||||
Some(UpstreamAccountRetry::TokenInvalid {
|
||||
account_status: account_status_for_unauthorized(body),
|
||||
})
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_model_not_supported_error(error: &CodexClientError) -> bool {
|
||||
let CodexClientError::Upstream { status, body, .. } = error else {
|
||||
return false;
|
||||
};
|
||||
if !status.is_client_error() || *status == StatusCode::TOO_MANY_REQUESTS {
|
||||
return false;
|
||||
}
|
||||
let haystack = format!(
|
||||
"{} {} {}",
|
||||
error_code(body).unwrap_or_default(),
|
||||
error_message(body).unwrap_or_default(),
|
||||
body
|
||||
)
|
||||
.to_ascii_lowercase();
|
||||
haystack.contains("model")
|
||||
&& (haystack.contains("not supported")
|
||||
|| haystack.contains("not_supported")
|
||||
|| haystack.contains("not available")
|
||||
|| haystack.contains("not_available"))
|
||||
}
|
||||
|
||||
fn account_status_for_unauthorized(body: &str) -> AccountStatus {
|
||||
if body.to_ascii_lowercase().contains("deactivated") {
|
||||
AccountStatus::Banned
|
||||
} else {
|
||||
AccountStatus::Expired
|
||||
}
|
||||
}
|
||||
|
||||
fn is_previous_response_not_found_error(error: &CodexClientError) -> bool {
|
||||
let CodexClientError::Upstream { body, .. } = error else {
|
||||
return false;
|
||||
};
|
||||
if error_code(body).as_deref() == Some("previous_response_not_found") {
|
||||
return true;
|
||||
}
|
||||
let lower = body.to_ascii_lowercase();
|
||||
lower.contains("previous_response_not_found")
|
||||
|| (lower.contains("previous response with id") && lower.contains("not found"))
|
||||
}
|
||||
|
||||
fn is_unanswered_function_call_error(error: &CodexClientError) -> bool {
|
||||
let CodexClientError::Upstream { status, body, .. } = error else {
|
||||
return false;
|
||||
};
|
||||
if *status != StatusCode::BAD_REQUEST {
|
||||
return false;
|
||||
}
|
||||
body.to_ascii_lowercase()
|
||||
.contains("no tool output found for function call")
|
||||
}
|
||||
|
||||
fn error_code(body: &str) -> Option<String> {
|
||||
let value = serde_json::from_str::<Value>(body).ok()?;
|
||||
value
|
||||
.pointer("/response/error/code")
|
||||
.or_else(|| value.pointer("/response/error/type"))
|
||||
.or_else(|| value.pointer("/error/code"))
|
||||
.or_else(|| value.pointer("/error/type"))
|
||||
.and_then(Value::as_str)
|
||||
.map(|code| code.to_ascii_lowercase())
|
||||
}
|
||||
|
||||
fn error_message(body: &str) -> Option<String> {
|
||||
let value = serde_json::from_str::<Value>(body).ok()?;
|
||||
value
|
||||
.pointer("/response/error/message")
|
||||
.or_else(|| value.pointer("/error/message"))
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned)
|
||||
}
|
||||
|
||||
pub(crate) fn websocket_history_retry_metadata(retry: UpstreamAccountRetry, stream: bool) -> Value {
|
||||
match retry {
|
||||
UpstreamAccountRetry::ModelUnsupported { .. } => json!({
|
||||
"stream": stream,
|
||||
"transport": "websocket",
|
||||
"retry": false,
|
||||
"reason": "modelUnsupported",
|
||||
"accountAffinity": "previousResponseId",
|
||||
}),
|
||||
UpstreamAccountRetry::RateLimited {
|
||||
retry_after_seconds,
|
||||
} => json!({
|
||||
@@ -120,6 +298,21 @@ pub(crate) fn websocket_history_retry_metadata(retry: UpstreamAccountRetry, stre
|
||||
"cooldownSeconds": cooldown_seconds,
|
||||
"accountAffinity": "previousResponseId",
|
||||
}),
|
||||
UpstreamAccountRetry::CloudflarePathBlock => json!({
|
||||
"stream": stream,
|
||||
"transport": "websocket",
|
||||
"retry": false,
|
||||
"reason": "cloudflarePathBlock",
|
||||
"accountAffinity": "previousResponseId",
|
||||
}),
|
||||
UpstreamAccountRetry::TokenInvalid { account_status } => json!({
|
||||
"stream": stream,
|
||||
"transport": "websocket",
|
||||
"retry": false,
|
||||
"reason": "tokenInvalid",
|
||||
"accountStatus": account_status_metadata(account_status),
|
||||
"accountAffinity": "previousResponseId",
|
||||
}),
|
||||
UpstreamAccountRetry::Banned => json!({
|
||||
"stream": stream,
|
||||
"transport": "websocket",
|
||||
@@ -160,7 +353,14 @@ pub(super) async fn apply_upstream_account_retry_with_deps(
|
||||
account: &Account,
|
||||
retry: UpstreamAccountRetry,
|
||||
) {
|
||||
match retry {
|
||||
let evict_websocket_pool = match retry {
|
||||
UpstreamAccountRetry::ModelUnsupported { .. } => {
|
||||
tracing::warn!(
|
||||
account_id = %account.id,
|
||||
"上游账号不支持当前 model,将尝试备用账号"
|
||||
);
|
||||
false
|
||||
}
|
||||
UpstreamAccountRetry::RateLimited {
|
||||
retry_after_seconds,
|
||||
} => {
|
||||
@@ -189,9 +389,11 @@ pub(super) async fn apply_upstream_account_retry_with_deps(
|
||||
"记录被 rate limit 的账户请求尝试失败"
|
||||
);
|
||||
}
|
||||
true
|
||||
}
|
||||
UpstreamAccountRetry::QuotaExhausted => {
|
||||
set_account_status(deps, account, AccountStatus::QuotaExhausted).await;
|
||||
true
|
||||
}
|
||||
UpstreamAccountRetry::CloudflareChallenge { cooldown_seconds } => {
|
||||
let cooldown_until = Utc::now() + Duration::seconds(cooldown_seconds as i64);
|
||||
@@ -221,12 +423,55 @@ pub(super) async fn apply_upstream_account_retry_with_deps(
|
||||
.lock()
|
||||
.await
|
||||
.set_cloudflare_cooldown_until(&account.id, cooldown_until);
|
||||
true
|
||||
}
|
||||
UpstreamAccountRetry::CloudflarePathBlock => {
|
||||
if let Some(cookie_repo) = deps.cookie_repository.as_ref() {
|
||||
if let Err(error) = cookie_repo.delete_account_cookies(&account.id).await {
|
||||
tracing::warn!(
|
||||
error = %error,
|
||||
account_id = %account.id,
|
||||
"清理 Cloudflare path-block 账户 cookies 失败"
|
||||
);
|
||||
}
|
||||
}
|
||||
let block_count = deps
|
||||
.cf_path_block_tracker
|
||||
.record_path_block(&account.id)
|
||||
.await;
|
||||
if deps.cf_path_block_tracker.should_disable(&account.id).await {
|
||||
set_account_status(deps, account, AccountStatus::Disabled).await;
|
||||
}
|
||||
tracing::warn!(
|
||||
account_id = %account.id,
|
||||
block_count,
|
||||
"上游返回 Cloudflare path-block 404,已清理 cookies"
|
||||
);
|
||||
true
|
||||
}
|
||||
UpstreamAccountRetry::TokenInvalid { account_status } => {
|
||||
set_account_status(deps, account, account_status).await;
|
||||
true
|
||||
}
|
||||
UpstreamAccountRetry::Banned => {
|
||||
set_account_status(deps, account, AccountStatus::Banned).await;
|
||||
true
|
||||
}
|
||||
};
|
||||
if evict_websocket_pool {
|
||||
deps.websocket_pool.evict_account(&account.id).await;
|
||||
}
|
||||
}
|
||||
|
||||
fn account_status_metadata(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",
|
||||
}
|
||||
deps.websocket_pool.evict_account(&account.id).await;
|
||||
}
|
||||
|
||||
async fn set_account_status(
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::codex::gateway::transport::types::CodexResponsesRequest;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct ImplicitResumeSnapshot {
|
||||
input: Vec<Value>,
|
||||
previous_response_id: Option<String>,
|
||||
turn_state: Option<String>,
|
||||
use_websocket: bool,
|
||||
force_http_sse: bool,
|
||||
}
|
||||
|
||||
impl ImplicitResumeSnapshot {
|
||||
pub(super) fn capture(request: &CodexResponsesRequest) -> Self {
|
||||
Self {
|
||||
input: request.input.clone(),
|
||||
previous_response_id: request.previous_response_id.clone(),
|
||||
turn_state: request.turn_state.clone(),
|
||||
use_websocket: request.use_websocket,
|
||||
force_http_sse: request.force_http_sse,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn restore(self, request: &mut CodexResponsesRequest) {
|
||||
request.input = self.input;
|
||||
request.previous_response_id = self.previous_response_id;
|
||||
request.turn_state = self.turn_state;
|
||||
request.use_websocket = self.use_websocket;
|
||||
request.force_http_sse = self.force_http_sse;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn continuation_input_start(input: &[Value]) -> usize {
|
||||
let mut last_model_output_index = None;
|
||||
for (index, item) in input.iter().enumerate() {
|
||||
if item.get("role").is_some() {
|
||||
if item.get("role").and_then(Value::as_str) == Some("assistant") {
|
||||
last_model_output_index = Some(index);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if item.get("type").and_then(Value::as_str) == Some("function_call") {
|
||||
last_model_output_index = Some(index);
|
||||
}
|
||||
}
|
||||
last_model_output_index.map_or(0, |index| index.saturating_add(1))
|
||||
}
|
||||
|
||||
pub(super) fn implicit_resume_allowed(
|
||||
continuation_input: &[Value],
|
||||
full_input: &[Value],
|
||||
stored_function_call_ids: &[String],
|
||||
) -> bool {
|
||||
let required_call_ids = function_call_output_ids(continuation_input);
|
||||
if required_call_ids.is_empty() {
|
||||
return stored_function_call_ids.is_empty();
|
||||
}
|
||||
|
||||
let inline_call_ids = inline_function_call_ids(full_input);
|
||||
if required_call_ids
|
||||
.iter()
|
||||
.all(|call_id| inline_call_ids.contains(call_id))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
let stored_call_ids = stored_function_call_ids.iter().collect::<HashSet<_>>();
|
||||
let required_call_ids = required_call_ids.iter().collect::<HashSet<_>>();
|
||||
required_call_ids
|
||||
.iter()
|
||||
.all(|call_id| stored_call_ids.contains(*call_id))
|
||||
&& stored_call_ids
|
||||
.iter()
|
||||
.all(|call_id| required_call_ids.contains(*call_id))
|
||||
}
|
||||
|
||||
fn function_call_output_ids(input: &[Value]) -> Vec<String> {
|
||||
input
|
||||
.iter()
|
||||
.filter(|item| item.get("role").is_none())
|
||||
.filter(|item| item.get("type").and_then(Value::as_str) == Some("function_call_output"))
|
||||
.filter_map(|item| item.get("call_id").and_then(Value::as_str))
|
||||
.filter(|call_id| !call_id.trim().is_empty())
|
||||
.map(ToString::to_string)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn inline_function_call_ids(input: &[Value]) -> HashSet<String> {
|
||||
input
|
||||
.iter()
|
||||
.filter(|item| item.get("role").is_none())
|
||||
.filter(|item| item.get("type").and_then(Value::as_str) == Some("function_call"))
|
||||
.filter_map(|item| item.get("call_id").and_then(Value::as_str))
|
||||
.filter(|call_id| !call_id.trim().is_empty())
|
||||
.map(ToString::to_string)
|
||||
.collect()
|
||||
}
|
||||
+612
-104
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,288 @@
|
||||
use std::{collections::HashMap, time::Duration};
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde_json::{json, Map, Value};
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
const REASONING_REPLAY_TTL: Duration = Duration::from_secs(55 * 60);
|
||||
const MAX_ENTRIES: usize = 512;
|
||||
const MAX_ENTRY_BYTES: usize = 256 * 1024;
|
||||
const MAX_TOTAL_BYTES: usize = 4 * 1024 * 1024;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct ReasoningReplayEntry {
|
||||
account_id: String,
|
||||
conversation_id: String,
|
||||
variant_hash: String,
|
||||
items: Vec<Value>,
|
||||
byte_size: usize,
|
||||
created_at: DateTime<Utc>,
|
||||
sequence: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct ReasoningReplayState {
|
||||
entries: HashMap<String, ReasoningReplayEntry>,
|
||||
total_bytes: usize,
|
||||
next_sequence: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct ReasoningReplayCache {
|
||||
state: RwLock<ReasoningReplayState>,
|
||||
}
|
||||
|
||||
impl ReasoningReplayCache {
|
||||
pub(super) async fn record(
|
||||
&self,
|
||||
response_id: &str,
|
||||
account_id: &str,
|
||||
conversation_id: &str,
|
||||
variant_hash: &str,
|
||||
items: &[Value],
|
||||
) -> usize {
|
||||
let sanitized = sanitize_reasoning_replay_items(items);
|
||||
let mut state = self.state.write().await;
|
||||
cleanup_expired(&mut state, Utc::now());
|
||||
delete_entry(&mut state, response_id);
|
||||
|
||||
if sanitized.is_empty() {
|
||||
return 0;
|
||||
}
|
||||
let byte_size = estimate_items_bytes(&sanitized);
|
||||
if byte_size > MAX_ENTRY_BYTES {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let sequence = state.next_sequence;
|
||||
state.next_sequence = state.next_sequence.saturating_add(1);
|
||||
state.total_bytes = state.total_bytes.saturating_add(byte_size);
|
||||
state.entries.insert(
|
||||
response_id.to_string(),
|
||||
ReasoningReplayEntry {
|
||||
account_id: account_id.to_string(),
|
||||
conversation_id: conversation_id.to_string(),
|
||||
variant_hash: variant_hash.to_string(),
|
||||
items: sanitized,
|
||||
byte_size,
|
||||
created_at: Utc::now(),
|
||||
sequence,
|
||||
},
|
||||
);
|
||||
evict_overflow(&mut state);
|
||||
state
|
||||
.entries
|
||||
.get(response_id)
|
||||
.map_or(0, |entry| entry.items.len())
|
||||
}
|
||||
|
||||
pub(super) async fn lookup(
|
||||
&self,
|
||||
response_id: &str,
|
||||
account_id: &str,
|
||||
conversation_id: &str,
|
||||
variant_hash: &str,
|
||||
) -> Vec<Value> {
|
||||
let mut state = self.state.write().await;
|
||||
cleanup_expired(&mut state, Utc::now());
|
||||
let Some(entry) = state.entries.get(response_id) else {
|
||||
return Vec::new();
|
||||
};
|
||||
if entry.account_id != account_id
|
||||
|| entry.conversation_id != conversation_id
|
||||
|| entry.variant_hash != variant_hash
|
||||
{
|
||||
return Vec::new();
|
||||
}
|
||||
entry.items.clone()
|
||||
}
|
||||
|
||||
pub(super) async fn evict_by_identity(
|
||||
&self,
|
||||
account_id: &str,
|
||||
conversation_id: &str,
|
||||
variant_hash: &str,
|
||||
) -> usize {
|
||||
let mut state = self.state.write().await;
|
||||
cleanup_expired(&mut state, Utc::now());
|
||||
let response_ids = state
|
||||
.entries
|
||||
.iter()
|
||||
.filter(|(_, entry)| {
|
||||
entry.account_id == account_id
|
||||
&& entry.conversation_id == conversation_id
|
||||
&& entry.variant_hash == variant_hash
|
||||
})
|
||||
.map(|(response_id, _)| response_id.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let evicted = response_ids.len();
|
||||
for response_id in response_ids {
|
||||
delete_entry(&mut state, &response_id);
|
||||
}
|
||||
evicted
|
||||
}
|
||||
}
|
||||
|
||||
fn sanitize_reasoning_replay_items(items: &[Value]) -> Vec<Value> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let mut sanitized = Vec::new();
|
||||
for item in items {
|
||||
let Some(replay_item) =
|
||||
sanitize_reasoning_item(item).or_else(|| sanitize_function_call(item))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Some(key) = replay_item_key(&replay_item) else {
|
||||
continue;
|
||||
};
|
||||
if !seen.insert(key) {
|
||||
continue;
|
||||
}
|
||||
sanitized.push(replay_item);
|
||||
}
|
||||
sanitized
|
||||
}
|
||||
|
||||
fn sanitize_reasoning_item(value: &Value) -> Option<Value> {
|
||||
let object = value.as_object()?;
|
||||
if object.get("type").and_then(Value::as_str) != Some("reasoning") {
|
||||
return None;
|
||||
}
|
||||
let id = non_empty_str(object.get("id")?)?;
|
||||
let summary = sanitize_summary(object.get("summary")?)?;
|
||||
let encrypted_content = non_empty_str(object.get("encrypted_content")?)?;
|
||||
|
||||
let mut sanitized = Map::new();
|
||||
sanitized.insert("type".to_string(), json!("reasoning"));
|
||||
sanitized.insert("id".to_string(), json!(id));
|
||||
if let Some(status) = object
|
||||
.get("status")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|status| matches!(*status, "in_progress" | "completed" | "incomplete"))
|
||||
{
|
||||
sanitized.insert("status".to_string(), json!(status));
|
||||
}
|
||||
sanitized.insert("summary".to_string(), Value::Array(summary));
|
||||
sanitized.insert("encrypted_content".to_string(), json!(encrypted_content));
|
||||
if let Some(content) = object.get("content").and_then(sanitize_content) {
|
||||
sanitized.insert("content".to_string(), Value::Array(content));
|
||||
}
|
||||
Some(Value::Object(sanitized))
|
||||
}
|
||||
|
||||
fn sanitize_function_call(value: &Value) -> Option<Value> {
|
||||
let object = value.as_object()?;
|
||||
if object.get("type").and_then(Value::as_str) != Some("function_call") {
|
||||
return None;
|
||||
}
|
||||
let call_id = non_empty_str(object.get("call_id")?)?;
|
||||
let name = non_empty_str(object.get("name")?)?;
|
||||
let arguments = object.get("arguments")?.as_str()?;
|
||||
|
||||
let mut sanitized = Map::new();
|
||||
sanitized.insert("type".to_string(), json!("function_call"));
|
||||
if let Some(id) = object.get("id").and_then(non_empty_str) {
|
||||
sanitized.insert("id".to_string(), json!(id));
|
||||
}
|
||||
sanitized.insert("call_id".to_string(), json!(call_id));
|
||||
sanitized.insert("name".to_string(), json!(name));
|
||||
sanitized.insert("arguments".to_string(), json!(arguments));
|
||||
Some(Value::Object(sanitized))
|
||||
}
|
||||
|
||||
fn sanitize_summary(value: &Value) -> Option<Vec<Value>> {
|
||||
Some(
|
||||
value
|
||||
.as_array()?
|
||||
.iter()
|
||||
.filter_map(|part| {
|
||||
let object = part.as_object()?;
|
||||
if object.get("type").and_then(Value::as_str) != Some("summary_text") {
|
||||
return None;
|
||||
}
|
||||
let text = object.get("text")?.as_str()?;
|
||||
Some(json!({"type": "summary_text", "text": text}))
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
fn sanitize_content(value: &Value) -> Option<Vec<Value>> {
|
||||
let content = value
|
||||
.as_array()?
|
||||
.iter()
|
||||
.filter_map(|part| {
|
||||
let object = part.as_object()?;
|
||||
if object.get("type").and_then(Value::as_str) != Some("reasoning_text") {
|
||||
return None;
|
||||
}
|
||||
let text = object.get("text")?.as_str()?;
|
||||
Some(json!({"type": "reasoning_text", "text": text}))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
(!content.is_empty()).then_some(content)
|
||||
}
|
||||
|
||||
fn replay_item_key(item: &Value) -> Option<String> {
|
||||
match item.get("type").and_then(Value::as_str)? {
|
||||
"reasoning" => item
|
||||
.get("id")
|
||||
.and_then(Value::as_str)
|
||||
.map(|id| format!("reasoning:{id}")),
|
||||
"function_call" => item
|
||||
.get("call_id")
|
||||
.and_then(Value::as_str)
|
||||
.map(|call_id| format!("function_call:{call_id}")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn non_empty_str(value: &Value) -> Option<&str> {
|
||||
value.as_str().filter(|value| !value.trim().is_empty())
|
||||
}
|
||||
|
||||
fn estimate_items_bytes(items: &[Value]) -> usize {
|
||||
serde_json::to_vec(items).map_or(usize::MAX, |bytes| bytes.len())
|
||||
}
|
||||
|
||||
fn cleanup_expired(state: &mut ReasoningReplayState, now: DateTime<Utc>) {
|
||||
let response_ids = state
|
||||
.entries
|
||||
.iter()
|
||||
.filter(|(_, entry)| entry_expired(entry.created_at, now))
|
||||
.map(|(response_id, _)| response_id.clone())
|
||||
.collect::<Vec<_>>();
|
||||
for response_id in response_ids {
|
||||
delete_entry(state, &response_id);
|
||||
}
|
||||
}
|
||||
|
||||
fn entry_expired(created_at: DateTime<Utc>, now: DateTime<Utc>) -> bool {
|
||||
now.signed_duration_since(created_at)
|
||||
.to_std()
|
||||
.is_ok_and(|age| age > REASONING_REPLAY_TTL)
|
||||
}
|
||||
|
||||
fn evict_overflow(state: &mut ReasoningReplayState) {
|
||||
while state.entries.len() > MAX_ENTRIES || state.total_bytes > MAX_TOTAL_BYTES {
|
||||
let Some(response_id) = oldest_response_id(state) else {
|
||||
return;
|
||||
};
|
||||
delete_entry(state, &response_id);
|
||||
}
|
||||
}
|
||||
|
||||
fn oldest_response_id(state: &ReasoningReplayState) -> Option<String> {
|
||||
state
|
||||
.entries
|
||||
.iter()
|
||||
.min_by_key(|(_, entry)| (entry.created_at, entry.sequence))
|
||||
.map(|(response_id, _)| response_id.clone())
|
||||
}
|
||||
|
||||
fn delete_entry(state: &mut ReasoningReplayState, response_id: &str) {
|
||||
let Some(entry) = state.entries.remove(response_id) else {
|
||||
return;
|
||||
};
|
||||
state.total_bytes = state.total_bytes.saturating_sub(entry.byte_size);
|
||||
}
|
||||
@@ -1,8 +1,16 @@
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use serde_json::{json, Value};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::codex::gateway::transport::sse::parse_sse_events;
|
||||
use crate::codex::gateway::{
|
||||
protocol::tuple_schema::reconvert_tuple_values,
|
||||
transport::{
|
||||
http_client::CodexClientError,
|
||||
sse::{encode_sse_event, parse_sse_events},
|
||||
},
|
||||
};
|
||||
|
||||
pub(crate) enum CollectedResponse {
|
||||
Completed(Value),
|
||||
@@ -15,6 +23,7 @@ pub(crate) enum CollectedResponse {
|
||||
pub(crate) struct CompletedResponseMetadata {
|
||||
pub response_id: String,
|
||||
pub function_call_ids: Vec<String>,
|
||||
pub replay_items: Vec<Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -22,6 +31,7 @@ pub(crate) struct ResponsesSseFailure {
|
||||
event: String,
|
||||
message: String,
|
||||
upstream_code: Option<String>,
|
||||
invalid_reasoning_replay: bool,
|
||||
}
|
||||
|
||||
impl ResponsesSseFailure {
|
||||
@@ -30,11 +40,28 @@ impl ResponsesSseFailure {
|
||||
event: event.to_string(),
|
||||
message: failure_message(value).unwrap_or_else(|| "Codex upstream SSE failed".into()),
|
||||
upstream_code: failure_code(value),
|
||||
invalid_reasoning_replay: contains_invalid_encrypted_content_signal(value),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn openai_error_message(&self) -> String {
|
||||
format!("Codex upstream SSE failed: {}", self.message)
|
||||
pub(crate) fn invalid_reasoning_replay(&self) -> bool {
|
||||
self.invalid_reasoning_replay
|
||||
}
|
||||
|
||||
pub(crate) fn upstream_error(&self) -> CodexClientError {
|
||||
let code = self.upstream_code.as_deref().unwrap_or("error");
|
||||
CodexClientError::Upstream {
|
||||
status: status_for_failure_code(code),
|
||||
retry_after_seconds: None,
|
||||
body: json!({
|
||||
"error": {
|
||||
"type": code,
|
||||
"code": code,
|
||||
"message": self.message,
|
||||
}
|
||||
})
|
||||
.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn metadata(&self, stream: bool) -> Value {
|
||||
@@ -56,8 +83,34 @@ impl ResponsesSseFailure {
|
||||
}
|
||||
}
|
||||
|
||||
fn status_for_failure_code(code: &str) -> StatusCode {
|
||||
let lower = code.to_ascii_lowercase();
|
||||
if lower.contains("model")
|
||||
&& (lower.contains("not_supported") || lower.contains("not_available"))
|
||||
{
|
||||
return StatusCode::BAD_REQUEST;
|
||||
}
|
||||
if lower.contains("invalid_request") || lower.contains("not_found") {
|
||||
return StatusCode::BAD_REQUEST;
|
||||
}
|
||||
if lower.contains("rate_limit") || lower.contains("usage_limit") {
|
||||
return StatusCode::TOO_MANY_REQUESTS;
|
||||
}
|
||||
if lower.contains("unauthorized") || lower.contains("invalid_api_key") {
|
||||
return StatusCode::UNAUTHORIZED;
|
||||
}
|
||||
if lower.contains("forbidden") || lower.contains("banned") {
|
||||
return StatusCode::FORBIDDEN;
|
||||
}
|
||||
if lower.contains("payment") || lower.contains("quota") {
|
||||
return StatusCode::PAYMENT_REQUIRED;
|
||||
}
|
||||
StatusCode::BAD_GATEWAY
|
||||
}
|
||||
|
||||
pub(crate) fn completed_response_json(
|
||||
body: &str,
|
||||
tuple_schema: Option<&Value>,
|
||||
) -> Result<CollectedResponse, crate::codex::gateway::transport::sse::SseError> {
|
||||
let events = parse_sse_events(body)?;
|
||||
let mut output_text = String::new();
|
||||
@@ -103,6 +156,7 @@ pub(crate) fn completed_response_json(
|
||||
}
|
||||
|
||||
ensure_completed_response_output(&mut response, &output_items, &output_text);
|
||||
reconvert_completed_response_tuple_values(&mut response, tuple_schema);
|
||||
sync_output_text_from_output(&mut response);
|
||||
Ok(CollectedResponse::Completed(response))
|
||||
}
|
||||
@@ -128,6 +182,116 @@ fn is_empty_response(response: &Value, output_text: &str, output_items: &[Value]
|
||||
output_tokens == 0
|
||||
}
|
||||
|
||||
pub(super) struct TupleStreamReconverter {
|
||||
tuple_schema: Option<Value>,
|
||||
pending: String,
|
||||
tuple_text_buffer: String,
|
||||
}
|
||||
|
||||
impl TupleStreamReconverter {
|
||||
pub(super) fn new(tuple_schema: Option<Value>) -> Self {
|
||||
Self {
|
||||
tuple_schema,
|
||||
pending: String::new(),
|
||||
tuple_text_buffer: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn transform_chunk(&mut self, chunk: &str) -> String {
|
||||
if self.tuple_schema.is_none() {
|
||||
return chunk.to_string();
|
||||
}
|
||||
self.pending.push_str(chunk);
|
||||
let mut output = String::new();
|
||||
while let Some(delimiter_index) = self.pending.find("\n\n") {
|
||||
let block = self.pending[..delimiter_index].to_string();
|
||||
self.pending.drain(..delimiter_index + 2);
|
||||
output.push_str(&self.transform_block(&block));
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
pub(super) fn finish(&mut self) -> String {
|
||||
if self.tuple_schema.is_none() || self.pending.trim().is_empty() {
|
||||
self.pending.clear();
|
||||
return String::new();
|
||||
}
|
||||
let block = std::mem::take(&mut self.pending);
|
||||
self.transform_block(&block)
|
||||
}
|
||||
|
||||
fn transform_block(&mut self, block: &str) -> String {
|
||||
if block.trim().is_empty() {
|
||||
return "\n\n".to_string();
|
||||
}
|
||||
let frame = format!("{block}\n\n");
|
||||
let Ok(mut events) = parse_sse_events(&frame) else {
|
||||
return frame;
|
||||
};
|
||||
if events.len() != 1 {
|
||||
return frame;
|
||||
}
|
||||
let event = events.remove(0);
|
||||
let Some(event_name) = event.event.as_deref() else {
|
||||
return frame;
|
||||
};
|
||||
match event_name {
|
||||
"response.output_text.delta" => self.transform_output_text_delta(&event.data, &frame),
|
||||
"response.completed" => {
|
||||
self.transform_response_completed(&event.data, event_name, &frame)
|
||||
}
|
||||
_ => frame,
|
||||
}
|
||||
}
|
||||
|
||||
fn transform_output_text_delta(&mut self, data: &str, original_frame: &str) -> String {
|
||||
let Ok(value) = serde_json::from_str::<Value>(data) else {
|
||||
return original_frame.to_string();
|
||||
};
|
||||
let Some(delta) = value.get("delta").and_then(Value::as_str) else {
|
||||
return original_frame.to_string();
|
||||
};
|
||||
self.tuple_text_buffer.push_str(delta);
|
||||
String::new()
|
||||
}
|
||||
|
||||
fn transform_response_completed(
|
||||
&mut self,
|
||||
data: &str,
|
||||
event_name: &str,
|
||||
original_frame: &str,
|
||||
) -> String {
|
||||
let Some(tuple_schema) = self.tuple_schema.as_ref() else {
|
||||
return original_frame.to_string();
|
||||
};
|
||||
let Ok(mut value) = serde_json::from_str::<Value>(data) else {
|
||||
return original_frame.to_string();
|
||||
};
|
||||
|
||||
let mut output = String::new();
|
||||
if !self.tuple_text_buffer.is_empty() {
|
||||
let reconverted_text = reconvert_tuple_text(&self.tuple_text_buffer, tuple_schema)
|
||||
.unwrap_or_else(|| self.tuple_text_buffer.clone());
|
||||
self.tuple_text_buffer.clear();
|
||||
output.push_str(&encode_sse_event(
|
||||
"response.output_text.delta",
|
||||
&json!({
|
||||
"type": "response.output_text.delta",
|
||||
"delta": reconverted_text,
|
||||
})
|
||||
.to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
if let Some(response) = value.get_mut("response") {
|
||||
reconvert_completed_response_tuple_values(response, Some(tuple_schema));
|
||||
sync_output_text_from_output(response);
|
||||
}
|
||||
output.push_str(&encode_sse_event(event_name, &value.to_string()));
|
||||
output
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn responses_sse_failure(
|
||||
body: &str,
|
||||
) -> Result<Option<ResponsesSseFailure>, crate::codex::gateway::transport::sse::SseError> {
|
||||
@@ -149,6 +313,7 @@ pub(super) fn completed_response_metadata(
|
||||
let events = parse_sse_events(body)?;
|
||||
let mut response_id = None;
|
||||
let mut function_call_ids = BTreeSet::new();
|
||||
let mut replay_items = Vec::new();
|
||||
|
||||
for event in events {
|
||||
let Ok(value) = serde_json::from_str::<Value>(&event.data) else {
|
||||
@@ -156,6 +321,9 @@ pub(super) fn completed_response_metadata(
|
||||
};
|
||||
match event.event.as_deref() {
|
||||
Some("response.output_item.done") => {
|
||||
if let Some(item) = value.get("item") {
|
||||
collect_response_replay_items(item, &mut replay_items);
|
||||
}
|
||||
if let Some(call_id) = value.pointer("/item/call_id").and_then(Value::as_str) {
|
||||
function_call_ids.insert(call_id.to_string());
|
||||
}
|
||||
@@ -166,6 +334,11 @@ pub(super) fn completed_response_metadata(
|
||||
.and_then(Value::as_str)
|
||||
.map(ToString::to_string);
|
||||
collect_response_function_call_ids(&value, &mut function_call_ids);
|
||||
if let Some(output) = value.pointer("/response/output").and_then(Value::as_array) {
|
||||
for item in output {
|
||||
collect_response_replay_items(item, &mut replay_items);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
@@ -174,6 +347,7 @@ pub(super) fn completed_response_metadata(
|
||||
Ok(response_id.map(|response_id| CompletedResponseMetadata {
|
||||
response_id,
|
||||
function_call_ids: function_call_ids.into_iter().collect(),
|
||||
replay_items,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -187,6 +361,47 @@ pub(super) fn ensure_stream_metadata(metadata: &mut Value, stream_value: bool) {
|
||||
.or_insert_with(|| json!(stream_value));
|
||||
}
|
||||
|
||||
pub(super) fn has_terminal_sse_event(
|
||||
body: &str,
|
||||
) -> Result<bool, crate::codex::gateway::transport::sse::SseError> {
|
||||
parse_sse_events(body).map(|events| {
|
||||
events.iter().any(|event| {
|
||||
matches!(
|
||||
event.event.as_deref(),
|
||||
Some("response.completed" | "response.failed" | "error")
|
||||
)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn premature_close_failed_event(detail: Option<&str>) -> String {
|
||||
let message = match detail.filter(|value| !value.trim().is_empty()) {
|
||||
Some(detail) => format!("Upstream stream closed before response.completed: {detail}"),
|
||||
None => "Upstream stream closed before response.completed".to_string(),
|
||||
};
|
||||
let response_id_suffix: String = Uuid::new_v4()
|
||||
.simple()
|
||||
.to_string()
|
||||
.chars()
|
||||
.take(24)
|
||||
.collect();
|
||||
let error = json!({
|
||||
"type": "server_error",
|
||||
"code": "stream_disconnected",
|
||||
"message": message,
|
||||
});
|
||||
let data = json!({
|
||||
"type": "response.failed",
|
||||
"response": {
|
||||
"id": format!("resp_proxy_{response_id_suffix}"),
|
||||
"status": "failed",
|
||||
"error": error,
|
||||
},
|
||||
"error": error,
|
||||
});
|
||||
encode_sse_event("response.failed", &data.to_string())
|
||||
}
|
||||
|
||||
fn collect_response_function_call_ids(value: &Value, function_call_ids: &mut BTreeSet<String>) {
|
||||
let Some(output) = value.pointer("/response/output").and_then(Value::as_array) else {
|
||||
return;
|
||||
@@ -198,6 +413,15 @@ fn collect_response_function_call_ids(value: &Value, function_call_ids: &mut BTr
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_response_replay_items(item: &Value, replay_items: &mut Vec<Value>) {
|
||||
if matches!(
|
||||
item.get("type").and_then(Value::as_str),
|
||||
Some("reasoning" | "function_call")
|
||||
) {
|
||||
replay_items.push(item.clone());
|
||||
}
|
||||
}
|
||||
|
||||
fn failure_message(value: &Value) -> Option<String> {
|
||||
value
|
||||
.pointer("/response/error/message")
|
||||
@@ -218,6 +442,33 @@ fn failure_code(value: &Value) -> Option<String> {
|
||||
.map(ToString::to_string)
|
||||
}
|
||||
|
||||
pub(super) fn contains_invalid_encrypted_content_signal(value: &Value) -> bool {
|
||||
visit_invalid_encrypted_content(value, 0)
|
||||
}
|
||||
|
||||
fn visit_invalid_encrypted_content(value: &Value, depth: usize) -> bool {
|
||||
if depth > 5 {
|
||||
return false;
|
||||
}
|
||||
match value {
|
||||
Value::String(value) => string_contains_invalid_encrypted_content(value),
|
||||
Value::Array(values) => values
|
||||
.iter()
|
||||
.any(|value| visit_invalid_encrypted_content(value, depth + 1)),
|
||||
Value::Object(object) => object.iter().any(|(key, value)| {
|
||||
string_contains_invalid_encrypted_content(key)
|
||||
|| visit_invalid_encrypted_content(value, depth + 1)
|
||||
}),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn string_contains_invalid_encrypted_content(value: &str) -> bool {
|
||||
let lower = value.to_ascii_lowercase();
|
||||
lower.contains("invalid_encrypted_content")
|
||||
|| (lower.contains("invalid") && lower.contains("encrypted") && lower.contains("content"))
|
||||
}
|
||||
|
||||
fn ensure_completed_response_output(
|
||||
response: &mut Value,
|
||||
output_items: &[Value],
|
||||
@@ -251,14 +502,40 @@ fn ensure_completed_response_output(
|
||||
}]);
|
||||
}
|
||||
|
||||
fn sync_output_text_from_output(response: &mut Value) {
|
||||
let output_text_is_empty = response
|
||||
.get("output_text")
|
||||
.and_then(Value::as_str)
|
||||
.is_none_or(str::is_empty);
|
||||
if !output_text_is_empty {
|
||||
fn reconvert_completed_response_tuple_values(response: &mut Value, tuple_schema: Option<&Value>) {
|
||||
let Some(tuple_schema) = tuple_schema else {
|
||||
return;
|
||||
};
|
||||
let Some(items) = response.get_mut("output").and_then(Value::as_array_mut) else {
|
||||
return;
|
||||
};
|
||||
for item in items {
|
||||
let Some(content) = item.get_mut("content").and_then(Value::as_array_mut) else {
|
||||
continue;
|
||||
};
|
||||
for part in content {
|
||||
let part_type = part.get("type").and_then(Value::as_str);
|
||||
if !matches!(part_type, Some("output_text" | "text")) {
|
||||
continue;
|
||||
}
|
||||
let Some(text) = part.get("text").and_then(Value::as_str) else {
|
||||
continue;
|
||||
};
|
||||
let Ok(parsed) = serde_json::from_str::<Value>(text) else {
|
||||
continue;
|
||||
};
|
||||
let reconverted = reconvert_tuple_values(parsed, tuple_schema);
|
||||
part["text"] = Value::String(reconverted.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn reconvert_tuple_text(text: &str, tuple_schema: &Value) -> Option<String> {
|
||||
let parsed = serde_json::from_str::<Value>(text).ok()?;
|
||||
Some(reconvert_tuple_values(parsed, tuple_schema).to_string())
|
||||
}
|
||||
|
||||
fn sync_output_text_from_output(response: &mut Value) {
|
||||
let Some(items) = response.get("output").and_then(Value::as_array) else {
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -11,12 +11,13 @@ use crate::{
|
||||
events::event::EventLevel,
|
||||
gateway::transport::{
|
||||
usage_events::extract_sse_usage,
|
||||
websocket::{append_rate_limit_updates, CodexWebSocketError, SharedRateLimitUpdates},
|
||||
websocket::{append_rate_limit_updates, SharedRateLimitUpdates},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
use super::{
|
||||
evict_reasoning_replay_with_deps,
|
||||
limits::apply_rate_limit_headers_with_deps,
|
||||
log_codex_upstream_response_with_deps, record_response_affinity_with_deps,
|
||||
record_usage_with_deps,
|
||||
@@ -29,6 +30,7 @@ pub(super) struct StreamAudit {
|
||||
context: CodexRequestLogContext,
|
||||
account_slot: AccountSlotGuard,
|
||||
account_plan_type: Option<String>,
|
||||
request: CodexResponsesRequest,
|
||||
rate_limit_headers: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
@@ -38,6 +40,7 @@ impl StreamAudit {
|
||||
context: CodexRequestLogContext,
|
||||
account_id: String,
|
||||
account_plan_type: Option<String>,
|
||||
request: CodexResponsesRequest,
|
||||
rate_limit_headers: Vec<(String, String)>,
|
||||
) -> Self {
|
||||
let account_slot = AccountSlotGuard::new(deps.account_pool.clone(), account_id);
|
||||
@@ -46,6 +49,7 @@ impl StreamAudit {
|
||||
context,
|
||||
account_slot,
|
||||
account_plan_type,
|
||||
request,
|
||||
rate_limit_headers,
|
||||
}
|
||||
}
|
||||
@@ -91,6 +95,14 @@ impl StreamAudit {
|
||||
status = StatusCode::BAD_GATEWAY;
|
||||
level = EventLevel::Error;
|
||||
message = "v1 responses stream 上游 SSE 失败";
|
||||
if failure.invalid_reasoning_replay() {
|
||||
evict_reasoning_replay_with_deps(
|
||||
&self.deps,
|
||||
&self.request,
|
||||
&self.context.account_id,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
failure.extend_metadata(&mut metadata);
|
||||
}
|
||||
Ok(None) => {}
|
||||
@@ -112,19 +124,6 @@ impl StreamAudit {
|
||||
.await;
|
||||
self.account_slot.release().await;
|
||||
}
|
||||
|
||||
pub(super) async fn log_transport_error(&mut self, error: &reqwest::Error) {
|
||||
log_codex_upstream_response_with_deps(
|
||||
&self.deps,
|
||||
&self.context,
|
||||
StatusCode::BAD_GATEWAY,
|
||||
EventLevel::Error,
|
||||
"v1 responses stream transport 失败",
|
||||
json!({"stream": true, "transportError": error.to_string()}),
|
||||
)
|
||||
.await;
|
||||
self.account_slot.release().await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct WebSocketStreamAudit {
|
||||
@@ -242,6 +241,14 @@ impl WebSocketStreamAudit {
|
||||
status = StatusCode::BAD_GATEWAY;
|
||||
level = EventLevel::Error;
|
||||
message = "v1 responses WebSocket stream 上游 SSE 失败";
|
||||
if failure.invalid_reasoning_replay() {
|
||||
evict_reasoning_replay_with_deps(
|
||||
&self.deps,
|
||||
&self.request,
|
||||
&self.context.account_id,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
failure.extend_metadata(&mut metadata);
|
||||
}
|
||||
Ok(None) => {}
|
||||
@@ -268,24 +275,6 @@ impl WebSocketStreamAudit {
|
||||
.await;
|
||||
self.account_slot.release().await;
|
||||
}
|
||||
|
||||
pub(super) async fn log_transport_error(&mut self, error: &CodexWebSocketError) {
|
||||
log_codex_upstream_response_with_deps(
|
||||
&self.deps,
|
||||
&self.context,
|
||||
StatusCode::BAD_GATEWAY,
|
||||
EventLevel::Error,
|
||||
"v1 responses WebSocket stream transport 失败",
|
||||
json!({
|
||||
"stream": true,
|
||||
"transport": "websocket",
|
||||
"rateLimitHeaders": self.rate_limit_headers.clone(),
|
||||
"transportError": error.to_string(),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
self.account_slot.release().await;
|
||||
}
|
||||
}
|
||||
|
||||
struct AccountSlotGuard {
|
||||
|
||||
@@ -129,7 +129,7 @@ pub(crate) async fn diagnostics_data(state: &AppState) -> DiagnosticsData {
|
||||
let config = state.services.settings.current().await;
|
||||
let auth_status = state.services.admin_auth.status().await.ok();
|
||||
let capacity = state.services.accounts.runtime_capacity_summary().await;
|
||||
let fingerprint = Fingerprint::default_codex_desktop();
|
||||
let fingerprint = state.services.diagnostics.fingerprint().clone();
|
||||
|
||||
DiagnosticsData {
|
||||
status: "ok",
|
||||
@@ -166,7 +166,7 @@ pub async fn debug_fingerprint(
|
||||
}
|
||||
|
||||
// 从实际服务中获取指纹
|
||||
let fingerprint = state.services.responses.upstream_fingerprint();
|
||||
let fingerprint = state.services.diagnostics.fingerprint();
|
||||
|
||||
(
|
||||
StatusCode::OK,
|
||||
@@ -230,7 +230,7 @@ fn transport_diagnostics(config: &AppConfig, fingerprint: Fingerprint) -> Transp
|
||||
fn fingerprint_diagnostics(fingerprint: Fingerprint) -> FingerprintDiagnostics {
|
||||
let user_agent = fingerprint.user_agent();
|
||||
FingerprintDiagnostics {
|
||||
source: "staticDefault",
|
||||
source: "runtime",
|
||||
originator: fingerprint.originator,
|
||||
app_version: fingerprint.app_version,
|
||||
build_number: fingerprint.build_number,
|
||||
|
||||
@@ -15,6 +15,17 @@ pub(crate) fn codex_client_error_response(error: CodexClientError) -> (StatusCod
|
||||
"websocket_required",
|
||||
)),
|
||||
),
|
||||
CodexClientError::Upstream { status, body, .. }
|
||||
if status == StatusCode::NOT_FOUND && body.trim().is_empty() =>
|
||||
{
|
||||
(
|
||||
StatusCode::BAD_GATEWAY,
|
||||
Json(openai_error(
|
||||
"Upstream blocked the request (Cloudflare path-block)",
|
||||
"upstream_error",
|
||||
)),
|
||||
)
|
||||
}
|
||||
CodexClientError::Upstream { status, body, .. } => (
|
||||
status,
|
||||
Json(openai_error(
|
||||
|
||||
@@ -3,7 +3,7 @@ use std::time::Instant;
|
||||
use axum::{
|
||||
body::Bytes,
|
||||
extract::State,
|
||||
http::HeaderMap,
|
||||
http::{HeaderMap, HeaderName, HeaderValue},
|
||||
response::{IntoResponse, Response},
|
||||
Extension,
|
||||
};
|
||||
@@ -12,11 +12,50 @@ use crate::{platform::http::request_id::RequestId, runtime::state::AppState};
|
||||
|
||||
use super::{auth::authorize_client_api_key, errors::missing_client_api_key_response};
|
||||
|
||||
const OPENAI_SUBAGENT_HEADER: HeaderName = HeaderName::from_static("x-openai-subagent");
|
||||
|
||||
pub async fn responses(
|
||||
State(state): State<AppState>,
|
||||
Extension(request_id): Extension<RequestId>,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
handle_responses(state, request_id, headers, body).await
|
||||
}
|
||||
|
||||
pub async fn review_responses(
|
||||
State(state): State<AppState>,
|
||||
Extension(request_id): Extension<RequestId>,
|
||||
mut headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
headers.insert(OPENAI_SUBAGENT_HEADER, HeaderValue::from_static("review"));
|
||||
handle_responses(state, request_id, headers, body).await
|
||||
}
|
||||
|
||||
pub async fn compact_responses(
|
||||
State(state): State<AppState>,
|
||||
Extension(request_id): Extension<RequestId>,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
let started_at = Instant::now();
|
||||
if !authorize_client_api_key(&state, &headers).await {
|
||||
return missing_client_api_key_response().into_response();
|
||||
}
|
||||
|
||||
state
|
||||
.services
|
||||
.responses
|
||||
.handle_compact(request_id.as_str(), body, started_at)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn handle_responses(
|
||||
state: AppState,
|
||||
request_id: RequestId,
|
||||
headers: HeaderMap,
|
||||
body: Bytes,
|
||||
) -> Response {
|
||||
let started_at = Instant::now();
|
||||
if !authorize_client_api_key(&state, &headers).await {
|
||||
|
||||
@@ -8,12 +8,14 @@ use crate::runtime::state::AppState;
|
||||
use super::{
|
||||
chat::chat_completions,
|
||||
models::{debug_models, model_catalog, model_detail, model_info, models},
|
||||
responses::responses,
|
||||
responses::{compact_responses, responses, review_responses},
|
||||
};
|
||||
|
||||
pub fn router() -> Router<AppState> {
|
||||
Router::new()
|
||||
.route("/v1/responses", post(responses))
|
||||
.route("/v1/responses/review", post(review_responses))
|
||||
.route("/v1/responses/compact", post(compact_responses))
|
||||
.route("/v1/chat/completions", post(chat_completions))
|
||||
.route("/v1/models", get(models))
|
||||
.route("/v1/models/catalog", get(model_catalog))
|
||||
|
||||
+669
-80
@@ -6,20 +6,21 @@ use axum::{
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use crate::{
|
||||
codex::events::event::EventLevel,
|
||||
codex::gateway::fingerprint::model::Fingerprint,
|
||||
codex::gateway::protocol::codex_to_openai::openai_error,
|
||||
codex::gateway::transport::types::CodexResponsesRequest,
|
||||
codex::gateway::protocol::tuple_schema::prepare_schema,
|
||||
codex::gateway::transport::types::{CodexCompactRequest, CodexResponsesRequest},
|
||||
codex::models::service::ModelService,
|
||||
codex::serving::dispatch::{
|
||||
affinity::SessionAffinityRepositoryResult, classify_upstream_account_retry,
|
||||
completed_response_json, no_available_accounts_response,
|
||||
normalize_service_tier_for_upstream, websocket_history_retry_metadata,
|
||||
CodexRequestLogContext, CodexUpstreamService, CollectedResponse,
|
||||
classify_upstream_request_recovery, completed_response_json,
|
||||
no_available_accounts_response, normalize_service_tier_for_upstream,
|
||||
websocket_history_retry_metadata, CodexRequestLogContext, CodexUpstreamService,
|
||||
CollectedResponse, ImplicitResumeSnapshot, UpstreamRequestRecovery,
|
||||
},
|
||||
codex::serving::http::errors::codex_client_error_response,
|
||||
config::ModelConfig,
|
||||
@@ -68,8 +69,10 @@ impl ResponsesService {
|
||||
started_at: Instant,
|
||||
) -> Response {
|
||||
let default_model = self.model_config.default_model.clone();
|
||||
let body = serde_json::from_slice::<ResponsesBody>(&body)
|
||||
.unwrap_or_else(|_| default_body(default_model.clone()));
|
||||
let body = match parse_responses_body(&body, default_model.clone()) {
|
||||
Some(body) => body,
|
||||
None => return invalid_responses_body_response(),
|
||||
};
|
||||
let client_stream = body.stream.unwrap_or(true);
|
||||
let requested_model = body.model.clone().unwrap_or(default_model);
|
||||
let catalog = self.models.catalog().await;
|
||||
@@ -91,6 +94,11 @@ impl ResponsesService {
|
||||
codex_request.tool_choice = body.tool_choice;
|
||||
codex_request.parallel_tool_calls = body.parallel_tool_calls;
|
||||
codex_request.text = body.text;
|
||||
codex_request.tuple_schema = body.tuple_schema;
|
||||
codex_request.explicit_prompt_cache_key = body
|
||||
.prompt_cache_key
|
||||
.as_deref()
|
||||
.is_some_and(|value| !value.trim().is_empty());
|
||||
codex_request.prompt_cache_key = body.prompt_cache_key;
|
||||
codex_request.include = body.include;
|
||||
let openai_subagent =
|
||||
@@ -132,12 +140,13 @@ impl ResponsesService {
|
||||
match body.use_websocket {
|
||||
Some(true) => codex_request.use_websocket = true,
|
||||
Some(false) => {
|
||||
// 显式 false 是客户端兼容开关;previous_response_id 仍会在 transport 层强制 WebSocket。
|
||||
// 显式传输控制不覆盖历史续链;previous_response_id 会在 transport 层强制 WebSocket。
|
||||
codex_request.force_http_sse = true;
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
self.upstream
|
||||
let mut implicit_resume = self
|
||||
.upstream
|
||||
.prepare_response_session(&mut codex_request)
|
||||
.await;
|
||||
let Some(mut acquired) = self
|
||||
@@ -158,21 +167,23 @@ impl ResponsesService {
|
||||
if client_stream {
|
||||
return self
|
||||
.upstream
|
||||
.responses_stream(codex_request, acquired, log_context)
|
||||
.responses_stream(codex_request, acquired, log_context, implicit_resume)
|
||||
.await;
|
||||
}
|
||||
|
||||
let mut excluded_account_ids = Vec::new();
|
||||
let mut empty_response_retries = 0;
|
||||
let mut history_recovery_used = false;
|
||||
let mut model_unsupported_retry_used = false;
|
||||
const MAX_EMPTY_RETRIES: u8 = 2;
|
||||
|
||||
let response = loop {
|
||||
let (response, collected_response) = loop {
|
||||
self.upstream
|
||||
.stagger_request(acquired.previous_slot_at)
|
||||
.await;
|
||||
let response = self
|
||||
.upstream
|
||||
.send_codex_request_with_refresh_retry(
|
||||
.send_codex_request_with_upstream_retries(
|
||||
&codex_request,
|
||||
&acquired.account,
|
||||
request_id,
|
||||
@@ -182,45 +193,49 @@ impl ResponsesService {
|
||||
|
||||
match response {
|
||||
Ok(response) => {
|
||||
// 检测空响应
|
||||
if let Ok(CollectedResponse::Empty) = completed_response_json(&response.body) {
|
||||
if self
|
||||
.upstream
|
||||
.record_empty_response(&acquired.account.id)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
self.upstream
|
||||
.log_response(
|
||||
&log_context,
|
||||
StatusCode::OK,
|
||||
EventLevel::Warn,
|
||||
"v1 responses 记录空响应计数失败",
|
||||
json!({
|
||||
"stream": false,
|
||||
"emptyResponse": true,
|
||||
"emptyResponseStoreError": true,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
empty_response_retries += 1;
|
||||
if empty_response_retries <= MAX_EMPTY_RETRIES {
|
||||
self.upstream
|
||||
.log_response(
|
||||
&log_context,
|
||||
StatusCode::OK,
|
||||
EventLevel::Warn,
|
||||
"v1 responses 空响应,准备重试",
|
||||
json!({
|
||||
"stream": false,
|
||||
"emptyResponse": true,
|
||||
"retryAttempt": empty_response_retries,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
continue;
|
||||
} else {
|
||||
let collected_response = completed_response_json(
|
||||
&response.body,
|
||||
codex_request.tuple_schema.as_ref(),
|
||||
);
|
||||
match &collected_response {
|
||||
Ok(CollectedResponse::Empty) => {
|
||||
if self
|
||||
.upstream
|
||||
.record_empty_response(&acquired.account.id)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
self.upstream
|
||||
.log_response(
|
||||
&log_context,
|
||||
StatusCode::OK,
|
||||
EventLevel::Warn,
|
||||
"v1 responses 记录空响应计数失败",
|
||||
json!({
|
||||
"stream": false,
|
||||
"emptyResponse": true,
|
||||
"emptyResponseStoreError": true,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
empty_response_retries += 1;
|
||||
if empty_response_retries <= MAX_EMPTY_RETRIES {
|
||||
self.upstream
|
||||
.log_response(
|
||||
&log_context,
|
||||
StatusCode::OK,
|
||||
EventLevel::Warn,
|
||||
"v1 responses 空响应,准备重试",
|
||||
json!({
|
||||
"stream": false,
|
||||
"emptyResponse": true,
|
||||
"retryAttempt": empty_response_retries,
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
continue;
|
||||
}
|
||||
self.upstream
|
||||
.log_response(
|
||||
&log_context,
|
||||
@@ -243,12 +258,114 @@ impl ResponsesService {
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
Ok(CollectedResponse::Failed(failure)) => {
|
||||
if failure.invalid_reasoning_replay() {
|
||||
self.upstream
|
||||
.evict_reasoning_replay(&codex_request, &acquired.account.id)
|
||||
.await;
|
||||
}
|
||||
let error = failure.upstream_error();
|
||||
if let Some(recovery) =
|
||||
classify_upstream_request_recovery(&error, history_recovery_used)
|
||||
{
|
||||
self.apply_request_recovery(
|
||||
&mut codex_request,
|
||||
&mut history_recovery_used,
|
||||
&mut implicit_resume,
|
||||
&log_context,
|
||||
recovery,
|
||||
)
|
||||
.await;
|
||||
continue;
|
||||
}
|
||||
if let Some(retry) = classify_upstream_account_retry(
|
||||
&error,
|
||||
model_unsupported_retry_used,
|
||||
) {
|
||||
if retry.is_model_unsupported() {
|
||||
model_unsupported_retry_used = true;
|
||||
}
|
||||
if codex_request.previous_response_id.is_some()
|
||||
&& retry.preserve_history_account_affinity()
|
||||
{
|
||||
self.upstream
|
||||
.apply_account_retry(&acquired.account, retry)
|
||||
.await;
|
||||
self.upstream
|
||||
.log_response(
|
||||
&log_context,
|
||||
retry.status(),
|
||||
EventLevel::Warn,
|
||||
"v1 responses SSE history 失败保持原账户",
|
||||
websocket_history_retry_metadata(retry, false),
|
||||
)
|
||||
.await;
|
||||
} else {
|
||||
let fallback = self
|
||||
.upstream
|
||||
.apply_retry_and_acquire_fallback(
|
||||
&acquired.account,
|
||||
retry,
|
||||
&codex_request.model,
|
||||
&mut excluded_account_ids,
|
||||
)
|
||||
.await;
|
||||
self.upstream
|
||||
.log_response(
|
||||
&log_context,
|
||||
retry.status(),
|
||||
EventLevel::Warn,
|
||||
"v1 responses 上游 SSE 失败将使用备用账户重试",
|
||||
retry.metadata(false),
|
||||
)
|
||||
.await;
|
||||
if let Some(fallback) = fallback {
|
||||
log_context =
|
||||
log_context.with_account(&fallback.account.id);
|
||||
acquired = fallback;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
let error_response = codex_client_error_response(error);
|
||||
self.upstream
|
||||
.log_response(
|
||||
&log_context,
|
||||
error_response.0,
|
||||
EventLevel::Error,
|
||||
"v1 responses 上游 SSE 失败",
|
||||
failure.metadata(false),
|
||||
)
|
||||
.await;
|
||||
return error_response.into_response();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
break response;
|
||||
break (response, collected_response);
|
||||
}
|
||||
Err(error) => {
|
||||
if let Some(retry) = classify_upstream_account_retry(&error) {
|
||||
if codex_request.previous_response_id.is_some() {
|
||||
if let Some(recovery) =
|
||||
classify_upstream_request_recovery(&error, history_recovery_used)
|
||||
{
|
||||
self.apply_request_recovery(
|
||||
&mut codex_request,
|
||||
&mut history_recovery_used,
|
||||
&mut implicit_resume,
|
||||
&log_context,
|
||||
recovery,
|
||||
)
|
||||
.await;
|
||||
continue;
|
||||
}
|
||||
if let Some(retry) =
|
||||
classify_upstream_account_retry(&error, model_unsupported_retry_used)
|
||||
{
|
||||
if retry.is_model_unsupported() {
|
||||
model_unsupported_retry_used = true;
|
||||
}
|
||||
if codex_request.previous_response_id.is_some()
|
||||
&& retry.preserve_history_account_affinity()
|
||||
{
|
||||
// previous_response_id history is account-affine upstream.
|
||||
self.upstream
|
||||
.apply_account_retry(&acquired.account, retry)
|
||||
@@ -353,7 +470,7 @@ impl ResponsesService {
|
||||
}
|
||||
}
|
||||
|
||||
match completed_response_json(&response.body) {
|
||||
match collected_response {
|
||||
Ok(CollectedResponse::Completed(body)) => {
|
||||
self.upstream
|
||||
.record_response_affinity(
|
||||
@@ -415,23 +532,22 @@ impl ResponsesService {
|
||||
.into_response()
|
||||
}
|
||||
Ok(CollectedResponse::Failed(failure)) => {
|
||||
if failure.invalid_reasoning_replay() {
|
||||
self.upstream
|
||||
.evict_reasoning_replay(&codex_request, &acquired.account.id)
|
||||
.await;
|
||||
}
|
||||
let error_response = codex_client_error_response(failure.upstream_error());
|
||||
self.upstream
|
||||
.log_response(
|
||||
&log_context,
|
||||
StatusCode::BAD_GATEWAY,
|
||||
error_response.0,
|
||||
EventLevel::Error,
|
||||
"v1 responses 上游 SSE 失败",
|
||||
failure.metadata(false),
|
||||
)
|
||||
.await;
|
||||
(
|
||||
StatusCode::BAD_GATEWAY,
|
||||
Json(openai_error(
|
||||
&failure.openai_error_message(),
|
||||
"upstream_error",
|
||||
)),
|
||||
)
|
||||
.into_response()
|
||||
error_response.into_response()
|
||||
}
|
||||
Ok(CollectedResponse::MissingCompleted) => {
|
||||
self.upstream
|
||||
@@ -473,9 +589,183 @@ impl ResponsesService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn handle_compact(
|
||||
&self,
|
||||
request_id: &str,
|
||||
body: Bytes,
|
||||
started_at: Instant,
|
||||
) -> Response {
|
||||
let default_model = self.model_config.default_model.clone();
|
||||
let body = match parse_compact_body(&body, default_model) {
|
||||
Some(body) => body,
|
||||
None => return invalid_responses_body_response(),
|
||||
};
|
||||
let catalog = self.models.catalog().await;
|
||||
if !catalog.is_recognized_model_name(&body.model) {
|
||||
return (
|
||||
StatusCode::NOT_FOUND,
|
||||
Json(openai_error("Model not found", "model_not_found")),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
let parsed_model = catalog.parse_model_name(&body.model);
|
||||
let compact_request = CodexCompactRequest {
|
||||
model: parsed_model.model_id,
|
||||
input: body.input,
|
||||
instructions: body.instructions,
|
||||
tools: body.tools,
|
||||
parallel_tool_calls: body.parallel_tool_calls,
|
||||
reasoning: body.reasoning,
|
||||
text: body.text,
|
||||
};
|
||||
|
||||
let Some(mut acquired) = self.upstream.acquire_account(&compact_request.model).await else {
|
||||
return no_available_accounts_response().into_response();
|
||||
};
|
||||
let mut log_context = CodexRequestLogContext::new(
|
||||
request_id,
|
||||
&acquired.account.id,
|
||||
&compact_request.model,
|
||||
false,
|
||||
started_at,
|
||||
);
|
||||
let mut excluded_account_ids = Vec::new();
|
||||
let mut model_unsupported_retry_used = false;
|
||||
let mut attempts = 0_u8;
|
||||
const MAX_COMPACT_RETRIES: u8 = 8;
|
||||
|
||||
loop {
|
||||
attempts += 1;
|
||||
self.upstream
|
||||
.stagger_request(acquired.previous_slot_at)
|
||||
.await;
|
||||
let response = self
|
||||
.upstream
|
||||
.send_compact_request_with_upstream_retries(
|
||||
&compact_request,
|
||||
&acquired.account,
|
||||
request_id,
|
||||
)
|
||||
.await;
|
||||
self.upstream.release_account(&acquired.account.id).await;
|
||||
|
||||
match response {
|
||||
Ok(response) => {
|
||||
if self
|
||||
.upstream
|
||||
.persist_cookies(&acquired.account.id, &response.set_cookie_headers)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
self.upstream
|
||||
.log_response(
|
||||
&log_context,
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
EventLevel::Error,
|
||||
"v1 responses compact 持久化 cookie 失败",
|
||||
json!({"stream": false, "compact": true, "cookieStoreError": true}),
|
||||
)
|
||||
.await;
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(openai_error(
|
||||
"Failed to persist upstream cookies",
|
||||
"cookie_store_error",
|
||||
)),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
self.upstream
|
||||
.log_response(
|
||||
&log_context,
|
||||
StatusCode::OK,
|
||||
EventLevel::Info,
|
||||
"v1 responses compact 已完成",
|
||||
json!({"stream": false, "compact": true}),
|
||||
)
|
||||
.await;
|
||||
return (StatusCode::OK, Json(response.body)).into_response();
|
||||
}
|
||||
Err(error) => {
|
||||
if attempts < MAX_COMPACT_RETRIES {
|
||||
if let Some(retry) =
|
||||
classify_upstream_account_retry(&error, model_unsupported_retry_used)
|
||||
{
|
||||
if retry.is_model_unsupported() {
|
||||
model_unsupported_retry_used = true;
|
||||
}
|
||||
let fallback = self
|
||||
.upstream
|
||||
.apply_retry_and_acquire_fallback(
|
||||
&acquired.account,
|
||||
retry,
|
||||
&compact_request.model,
|
||||
&mut excluded_account_ids,
|
||||
)
|
||||
.await;
|
||||
self.upstream
|
||||
.log_response(
|
||||
&log_context,
|
||||
retry.status(),
|
||||
EventLevel::Warn,
|
||||
"v1 responses compact 上游请求将使用备用账户重试",
|
||||
retry.metadata(false),
|
||||
)
|
||||
.await;
|
||||
if let Some(fallback) = fallback {
|
||||
log_context = log_context.with_account(&fallback.account.id);
|
||||
acquired = fallback;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
let error_response = codex_client_error_response(error);
|
||||
self.upstream
|
||||
.log_response(
|
||||
&log_context,
|
||||
error_response.0,
|
||||
EventLevel::Error,
|
||||
"v1 responses compact 上游请求失败",
|
||||
json!({"stream": false, "compact": true}),
|
||||
)
|
||||
.await;
|
||||
return error_response.into_response();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn apply_request_recovery(
|
||||
&self,
|
||||
request: &mut CodexResponsesRequest,
|
||||
history_recovery_used: &mut bool,
|
||||
implicit_resume: &mut Option<ImplicitResumeSnapshot>,
|
||||
log_context: &CodexRequestLogContext,
|
||||
recovery: UpstreamRequestRecovery,
|
||||
) {
|
||||
*history_recovery_used = true;
|
||||
let stale_response_id = request.previous_response_id.clone();
|
||||
if let Some(response_id) = stale_response_id.as_deref() {
|
||||
self.upstream.forget_response_affinity(response_id).await;
|
||||
}
|
||||
if let Some(snapshot) = implicit_resume.take() {
|
||||
snapshot.restore(request);
|
||||
}
|
||||
request.previous_response_id = None;
|
||||
request.turn_state = None;
|
||||
self.upstream
|
||||
.log_response(
|
||||
log_context,
|
||||
StatusCode::BAD_REQUEST,
|
||||
EventLevel::Warn,
|
||||
"v1 responses 上游历史失效,去除 previous_response_id 后重试",
|
||||
recovery.metadata(false, stale_response_id.as_deref()),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ResponsesBody {
|
||||
model: Option<String>,
|
||||
input: Option<Vec<Value>>,
|
||||
@@ -486,26 +776,92 @@ struct ResponsesBody {
|
||||
tool_choice: Option<Value>,
|
||||
parallel_tool_calls: Option<bool>,
|
||||
text: Option<Value>,
|
||||
tuple_schema: Option<Value>,
|
||||
prompt_cache_key: Option<String>,
|
||||
include: Option<Vec<String>>,
|
||||
client_metadata: Option<Value>,
|
||||
previous_response_id: Option<String>,
|
||||
stream: Option<bool>,
|
||||
#[serde(rename = "turnState")]
|
||||
turn_state: Option<String>,
|
||||
#[serde(rename = "turnMetadata")]
|
||||
turn_metadata: Option<String>,
|
||||
#[serde(rename = "betaFeatures")]
|
||||
beta_features: Option<String>,
|
||||
#[serde(rename = "includeTimingMetrics")]
|
||||
include_timing_metrics: Option<String>,
|
||||
#[serde(rename = "codexWindowId")]
|
||||
codex_window_id: Option<String>,
|
||||
#[serde(rename = "parentThreadId")]
|
||||
parent_thread_id: Option<String>,
|
||||
use_websocket: Option<bool>,
|
||||
}
|
||||
|
||||
struct CompactBody {
|
||||
model: String,
|
||||
input: Vec<Value>,
|
||||
instructions: String,
|
||||
reasoning: Option<Value>,
|
||||
tools: Option<Vec<Value>>,
|
||||
parallel_tool_calls: Option<bool>,
|
||||
text: Option<Value>,
|
||||
}
|
||||
|
||||
fn parse_responses_body(body: &[u8], default_model: String) -> Option<ResponsesBody> {
|
||||
let Value::Object(mut body) = serde_json::from_slice::<Value>(body).ok()? else {
|
||||
return None;
|
||||
};
|
||||
|
||||
let mut parsed = default_body(default_model);
|
||||
parsed.model = take_string(&mut body, "model").or(parsed.model);
|
||||
parsed.input = take_array(&mut body, "input").map(sanitize_codex_input_items);
|
||||
parsed.instructions = take_string(&mut body, "instructions").or(parsed.instructions);
|
||||
parsed.reasoning = take_object_value(&mut body, "reasoning");
|
||||
parsed.tools = take_non_empty_array(&mut body, "tools");
|
||||
parsed.service_tier = take_string(&mut body, "service_tier");
|
||||
parsed.tool_choice = body.remove("tool_choice");
|
||||
parsed.parallel_tool_calls = take_bool(&mut body, "parallel_tool_calls");
|
||||
let prepared_text = take_prepared_text_format(&mut body);
|
||||
parsed.text = prepared_text.as_ref().map(|text| text.text.clone());
|
||||
parsed.tuple_schema = prepared_text.and_then(|text| text.tuple_schema);
|
||||
parsed.prompt_cache_key = take_string(&mut body, "prompt_cache_key");
|
||||
parsed.include = take_string_array(&mut body, "include");
|
||||
parsed.client_metadata = sanitize_client_metadata(body.remove("client_metadata"));
|
||||
parsed.previous_response_id = take_string(&mut body, "previous_response_id");
|
||||
parsed.stream = take_bool(&mut body, "stream");
|
||||
parsed.turn_state = take_non_empty_string(&mut body, "turnState");
|
||||
parsed.turn_metadata = take_non_empty_string(&mut body, "turnMetadata");
|
||||
parsed.beta_features = take_non_empty_string(&mut body, "betaFeatures");
|
||||
parsed.include_timing_metrics = take_non_empty_string(&mut body, "includeTimingMetrics");
|
||||
parsed.codex_window_id = take_non_empty_string(&mut body, "codexWindowId");
|
||||
parsed.parent_thread_id = take_non_empty_string(&mut body, "parentThreadId");
|
||||
parsed.use_websocket = take_bool(&mut body, "use_websocket");
|
||||
Some(parsed)
|
||||
}
|
||||
|
||||
fn parse_compact_body(body: &[u8], default_model: String) -> Option<CompactBody> {
|
||||
let Value::Object(mut body) = serde_json::from_slice::<Value>(body).ok()? else {
|
||||
return None;
|
||||
};
|
||||
|
||||
Some(CompactBody {
|
||||
model: take_string(&mut body, "model").unwrap_or(default_model),
|
||||
input: take_array(&mut body, "input")
|
||||
.map(sanitize_codex_input_items)
|
||||
.unwrap_or_default(),
|
||||
instructions: take_string(&mut body, "instructions").unwrap_or_default(),
|
||||
reasoning: sanitize_compact_reasoning(take_object_value(&mut body, "reasoning")),
|
||||
tools: take_non_empty_array(&mut body, "tools"),
|
||||
parallel_tool_calls: take_bool(&mut body, "parallel_tool_calls"),
|
||||
text: take_text_format(&mut body),
|
||||
})
|
||||
}
|
||||
|
||||
fn invalid_responses_body_response() -> Response {
|
||||
(
|
||||
StatusCode::BAD_REQUEST,
|
||||
Json(openai_error(
|
||||
"Request body must be a JSON object",
|
||||
"invalid_request",
|
||||
)),
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
|
||||
fn default_body(default_model: String) -> ResponsesBody {
|
||||
ResponsesBody {
|
||||
model: Some(default_model),
|
||||
@@ -517,6 +873,7 @@ fn default_body(default_model: String) -> ResponsesBody {
|
||||
tool_choice: None,
|
||||
parallel_tool_calls: None,
|
||||
text: None,
|
||||
tuple_schema: None,
|
||||
prompt_cache_key: None,
|
||||
include: None,
|
||||
client_metadata: None,
|
||||
@@ -532,6 +889,236 @@ fn default_body(default_model: String) -> ResponsesBody {
|
||||
}
|
||||
}
|
||||
|
||||
fn take_string(body: &mut Map<String, Value>, key: &str) -> Option<String> {
|
||||
body.remove(key).and_then(|value| match value {
|
||||
Value::String(value) => Some(value),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn take_non_empty_string(body: &mut Map<String, Value>, key: &str) -> Option<String> {
|
||||
take_string(body, key).and_then(|value| {
|
||||
let trimmed = value.trim();
|
||||
(!trimmed.is_empty()).then(|| trimmed.to_string())
|
||||
})
|
||||
}
|
||||
|
||||
fn take_bool(body: &mut Map<String, Value>, key: &str) -> Option<bool> {
|
||||
body.remove(key).and_then(|value| value.as_bool())
|
||||
}
|
||||
|
||||
fn take_array(body: &mut Map<String, Value>, key: &str) -> Option<Vec<Value>> {
|
||||
body.remove(key).and_then(|value| match value {
|
||||
Value::Array(values) => Some(values),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn take_non_empty_array(body: &mut Map<String, Value>, key: &str) -> Option<Vec<Value>> {
|
||||
take_array(body, key).filter(|values| !values.is_empty())
|
||||
}
|
||||
|
||||
fn take_object_value(body: &mut Map<String, Value>, key: &str) -> Option<Value> {
|
||||
body.remove(key).and_then(|value| match value {
|
||||
Value::Object(_) => Some(value),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn take_string_array(body: &mut Map<String, Value>, key: &str) -> Option<Vec<String>> {
|
||||
let values = take_array(body, key)?;
|
||||
values
|
||||
.into_iter()
|
||||
.map(|value| match value {
|
||||
Value::String(value) => Some(value),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
struct PreparedTextFormat {
|
||||
text: Value,
|
||||
tuple_schema: Option<Value>,
|
||||
}
|
||||
|
||||
fn take_prepared_text_format(body: &mut Map<String, Value>) -> Option<PreparedTextFormat> {
|
||||
take_text_format_inner(body, true)
|
||||
}
|
||||
|
||||
fn take_text_format(body: &mut Map<String, Value>) -> Option<Value> {
|
||||
take_text_format_inner(body, false).map(|prepared| prepared.text)
|
||||
}
|
||||
|
||||
fn take_text_format_inner(
|
||||
body: &mut Map<String, Value>,
|
||||
prepare_tuple_schema: bool,
|
||||
) -> Option<PreparedTextFormat> {
|
||||
let Value::Object(text) = body.remove("text")? else {
|
||||
return None;
|
||||
};
|
||||
let Value::Object(format) = text.get("format")? else {
|
||||
return None;
|
||||
};
|
||||
let format_type = format.get("type")?.as_str()?;
|
||||
let mut sanitized_format = Map::new();
|
||||
sanitized_format.insert("type".to_string(), Value::String(format_type.to_string()));
|
||||
let mut tuple_schema = None;
|
||||
if let Some(name) = format.get("name").and_then(Value::as_str) {
|
||||
sanitized_format.insert("name".to_string(), Value::String(name.to_string()));
|
||||
}
|
||||
if let Some(Value::Object(schema)) = format.get("schema") {
|
||||
let schema = Value::Object(schema.clone());
|
||||
let schema = if prepare_tuple_schema {
|
||||
let prepared = prepare_schema(schema);
|
||||
tuple_schema = prepared.original_schema;
|
||||
prepared.schema
|
||||
} else {
|
||||
schema
|
||||
};
|
||||
sanitized_format.insert("schema".to_string(), schema);
|
||||
}
|
||||
if let Some(strict) = format.get("strict").and_then(Value::as_bool) {
|
||||
sanitized_format.insert("strict".to_string(), Value::Bool(strict));
|
||||
}
|
||||
|
||||
let mut sanitized_text = Map::new();
|
||||
sanitized_text.insert("format".to_string(), Value::Object(sanitized_format));
|
||||
Some(PreparedTextFormat {
|
||||
text: Value::Object(sanitized_text),
|
||||
tuple_schema,
|
||||
})
|
||||
}
|
||||
|
||||
fn sanitize_client_metadata(client_metadata: Option<Value>) -> Option<Value> {
|
||||
let Value::Object(input) = client_metadata? else {
|
||||
return None;
|
||||
};
|
||||
let metadata: Map<String, Value> = input
|
||||
.into_iter()
|
||||
.filter_map(|(key, value)| {
|
||||
value
|
||||
.as_str()
|
||||
.map(|value| (key, Value::String(value.to_string())))
|
||||
})
|
||||
.collect();
|
||||
(!metadata.is_empty()).then_some(Value::Object(metadata))
|
||||
}
|
||||
|
||||
fn sanitize_compact_reasoning(reasoning: Option<Value>) -> Option<Value> {
|
||||
let Value::Object(input) = reasoning? else {
|
||||
return None;
|
||||
};
|
||||
let mut output = Map::new();
|
||||
if let Some(effort) = input.get("effort").and_then(Value::as_str) {
|
||||
output.insert("effort".to_string(), Value::String(effort.to_string()));
|
||||
}
|
||||
if let Some(summary) = input.get("summary").and_then(Value::as_str) {
|
||||
output.insert("summary".to_string(), Value::String(summary.to_string()));
|
||||
}
|
||||
(!output.is_empty()).then_some(Value::Object(output))
|
||||
}
|
||||
|
||||
fn sanitize_codex_input_items(input: Vec<Value>) -> Vec<Value> {
|
||||
input
|
||||
.into_iter()
|
||||
.filter_map(|item| {
|
||||
let Value::Object(object) = item else {
|
||||
return Some(item);
|
||||
};
|
||||
match object.get("type").and_then(Value::as_str) {
|
||||
Some("reasoning") => sanitize_reasoning_item(&object),
|
||||
Some("compaction") => sanitize_compaction_item(&object),
|
||||
_ => Some(Value::Object(object)),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn sanitize_reasoning_item(item: &Map<String, Value>) -> Option<Value> {
|
||||
let id = non_empty_string(item.get("id"))?;
|
||||
let summary = sanitize_summary(item.get("summary"))?;
|
||||
let mut sanitized = Map::new();
|
||||
sanitized.insert("type".to_string(), Value::String("reasoning".to_string()));
|
||||
sanitized.insert("id".to_string(), Value::String(id.to_string()));
|
||||
sanitized.insert("summary".to_string(), Value::Array(summary));
|
||||
if let Some(status) = item
|
||||
.get("status")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|status| matches!(*status, "in_progress" | "completed" | "incomplete"))
|
||||
{
|
||||
sanitized.insert("status".to_string(), Value::String(status.to_string()));
|
||||
}
|
||||
if let Some(encrypted_content) = non_empty_string(item.get("encrypted_content")) {
|
||||
sanitized.insert(
|
||||
"encrypted_content".to_string(),
|
||||
Value::String(encrypted_content.to_string()),
|
||||
);
|
||||
}
|
||||
if let Some(content) = sanitize_reasoning_content(item.get("content")) {
|
||||
sanitized.insert("content".to_string(), Value::Array(content));
|
||||
}
|
||||
Some(Value::Object(sanitized))
|
||||
}
|
||||
|
||||
fn sanitize_summary(value: Option<&Value>) -> Option<Vec<Value>> {
|
||||
let Value::Array(parts) = value? else {
|
||||
return None;
|
||||
};
|
||||
let summary: Vec<Value> = parts
|
||||
.iter()
|
||||
.filter_map(|part| {
|
||||
let Value::Object(part) = part else {
|
||||
return None;
|
||||
};
|
||||
if part.get("type").and_then(Value::as_str) != Some("summary_text") {
|
||||
return None;
|
||||
}
|
||||
let text = part.get("text").and_then(Value::as_str)?;
|
||||
Some(json!({"type": "summary_text", "text": text}))
|
||||
})
|
||||
.collect();
|
||||
Some(summary)
|
||||
}
|
||||
|
||||
fn sanitize_reasoning_content(value: Option<&Value>) -> Option<Vec<Value>> {
|
||||
let Value::Array(parts) = value? else {
|
||||
return None;
|
||||
};
|
||||
let content: Vec<Value> = parts
|
||||
.iter()
|
||||
.filter_map(|part| {
|
||||
let Value::Object(part) = part else {
|
||||
return None;
|
||||
};
|
||||
if part.get("type").and_then(Value::as_str) != Some("reasoning_text") {
|
||||
return None;
|
||||
}
|
||||
let text = part.get("text").and_then(Value::as_str)?;
|
||||
Some(json!({"type": "reasoning_text", "text": text}))
|
||||
})
|
||||
.collect();
|
||||
(!content.is_empty()).then_some(content)
|
||||
}
|
||||
|
||||
fn sanitize_compaction_item(item: &Map<String, Value>) -> Option<Value> {
|
||||
let encrypted_content = non_empty_string(item.get("encrypted_content"))?;
|
||||
let mut sanitized = Map::new();
|
||||
sanitized.insert("type".to_string(), Value::String("compaction".to_string()));
|
||||
sanitized.insert(
|
||||
"encrypted_content".to_string(),
|
||||
Value::String(encrypted_content.to_string()),
|
||||
);
|
||||
if let Some(id) = non_empty_string(item.get("id")) {
|
||||
sanitized.insert("id".to_string(), Value::String(id.to_string()));
|
||||
}
|
||||
Some(Value::Object(sanitized))
|
||||
}
|
||||
|
||||
fn non_empty_string(value: Option<&Value>) -> Option<&str> {
|
||||
let value = value?.as_str()?;
|
||||
(!value.trim().is_empty()).then_some(value)
|
||||
}
|
||||
|
||||
fn responses_reasoning(
|
||||
client_reasoning: Option<Value>,
|
||||
suffix_effort: Option<&str>,
|
||||
@@ -562,14 +1149,14 @@ fn ensure_reasoning_include(request: &mut CodexResponsesRequest) {
|
||||
if request.reasoning.is_none() {
|
||||
return;
|
||||
}
|
||||
let include = request.include.get_or_insert_with(Vec::new);
|
||||
if include
|
||||
.iter()
|
||||
.any(|item| item == "reasoning.encrypted_content")
|
||||
if request
|
||||
.include
|
||||
.as_ref()
|
||||
.is_some_and(|include| !include.is_empty())
|
||||
{
|
||||
return;
|
||||
}
|
||||
include.push("reasoning.encrypted_content".to_string());
|
||||
request.include = Some(vec!["reasoning.encrypted_content".to_string()]);
|
||||
}
|
||||
|
||||
fn header_string(headers: &HeaderMap, name: &str) -> Option<String> {
|
||||
@@ -584,10 +1171,12 @@ fn client_metadata_with_openai_subagent(
|
||||
client_metadata: Option<Value>,
|
||||
openai_subagent: Option<String>,
|
||||
) -> Option<Value> {
|
||||
let mut metadata = match client_metadata {
|
||||
Some(Value::Object(metadata)) => metadata,
|
||||
_ => Map::new(),
|
||||
};
|
||||
let mut metadata = sanitize_client_metadata(client_metadata)
|
||||
.and_then(|value| match value {
|
||||
Value::Object(metadata) => Some(metadata),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or_default();
|
||||
metadata.remove(OPENAI_SUBAGENT_HEADER);
|
||||
if let Some(openai_subagent) = openai_subagent {
|
||||
metadata.insert(
|
||||
|
||||
@@ -8,7 +8,10 @@ use tokio::{
|
||||
use tracing::{debug, error, info, warn};
|
||||
|
||||
use crate::{
|
||||
codex::accounts::{model::AccountStatus, service::AccountService},
|
||||
codex::accounts::{
|
||||
model::AccountStatus,
|
||||
service::{AccountProbeOutcome, AccountService},
|
||||
},
|
||||
config::AppConfig,
|
||||
runtime::tasks::types::{SchedulerError, SchedulerHandle},
|
||||
};
|
||||
@@ -44,6 +47,7 @@ const BAN_ERRORS: &[&str] = &["account has been deactivated", "refresh_token_reu
|
||||
// 表示刷新令牌无效但不一定是封禁的错误
|
||||
const EXPIRED_ERRORS: &[&str] = &[
|
||||
"invalid_grant",
|
||||
"invalidgrant",
|
||||
"invalid_token",
|
||||
"access_denied",
|
||||
"refresh_token_expired",
|
||||
@@ -294,8 +298,8 @@ impl RefreshScheduler {
|
||||
let mut permanent_hits = 0;
|
||||
|
||||
for attempt in 1..=MAX_ATTEMPTS {
|
||||
match self.account_service.refresh_account(account_id).await {
|
||||
Ok(_result) => {
|
||||
let error = match self.account_service.probe_account_refresh(account_id).await {
|
||||
Ok(result) if matches!(result.outcome, AccountProbeOutcome::Alive) => {
|
||||
info!(account_id = %account_id, "token 刷新成功");
|
||||
// 获取新令牌并重新调度下次刷新
|
||||
if let Ok(accounts) = self
|
||||
@@ -315,69 +319,90 @@ impl RefreshScheduler {
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
Err(e) => {
|
||||
let error_msg = format!("{}", e).to_lowercase();
|
||||
Ok(result) if matches!(result.outcome, AccountProbeOutcome::Skipped) => {
|
||||
info!(
|
||||
account_id = %account_id,
|
||||
reason = result.error.as_deref().unwrap_or("skipped"),
|
||||
"token 刷新已跳过"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
Ok(result) => result
|
||||
.error
|
||||
.unwrap_or_else(|| "token refresh failed".to_string()),
|
||||
Err(error) => error.to_string(),
|
||||
};
|
||||
|
||||
// 检查是否是永久错误
|
||||
let is_ban = BAN_ERRORS.iter().any(|&err| error_msg.contains(err));
|
||||
let is_expired = EXPIRED_ERRORS.iter().any(|&err| error_msg.contains(err));
|
||||
let is_permanent = is_ban || is_expired;
|
||||
let error_msg = error.to_lowercase();
|
||||
|
||||
if is_permanent {
|
||||
permanent_hits += 1;
|
||||
if permanent_hits >= PERMANENT_THRESHOLD {
|
||||
error!(
|
||||
account_id = %account_id,
|
||||
hits = permanent_hits,
|
||||
"检测到永久刷新失败"
|
||||
);
|
||||
// refresh_account 已经标记了状态,这里不需要再次标记
|
||||
return Err(SchedulerError::AccountNotFound(format!(
|
||||
"Permanent failure: {}",
|
||||
e
|
||||
)));
|
||||
}
|
||||
warn!(
|
||||
account_id = %account_id,
|
||||
hits = permanent_hits,
|
||||
threshold = PERMANENT_THRESHOLD,
|
||||
"检测到永久错误,继续重试确认"
|
||||
);
|
||||
}
|
||||
// 检查是否是永久错误
|
||||
let is_ban = BAN_ERRORS.iter().any(|&err| error_msg.contains(err));
|
||||
let is_expired = EXPIRED_ERRORS.iter().any(|&err| error_msg.contains(err));
|
||||
let is_permanent = is_ban || is_expired;
|
||||
|
||||
if attempt < MAX_ATTEMPTS {
|
||||
// 指数退避:5s, 15s, 45s, 135s, 300s(有上限)
|
||||
let backoff = BASE_DELAY_MS.saturating_mul(3_u64.pow(attempt - 1));
|
||||
let backoff = backoff.min(300_000);
|
||||
let delay = Duration::from_millis(backoff);
|
||||
|
||||
warn!(
|
||||
account_id = %account_id,
|
||||
attempt,
|
||||
max_attempts = MAX_ATTEMPTS,
|
||||
delay_secs = delay.as_secs(),
|
||||
error = %e,
|
||||
"token 刷新尝试失败,准备重试"
|
||||
);
|
||||
tokio::time::sleep(delay).await;
|
||||
} else {
|
||||
if is_permanent {
|
||||
permanent_hits += 1;
|
||||
if permanent_hits >= PERMANENT_THRESHOLD {
|
||||
error!(
|
||||
account_id = %account_id,
|
||||
hits = permanent_hits,
|
||||
"检测到永久刷新失败"
|
||||
);
|
||||
let status = if is_ban { "banned" } else { "expired" };
|
||||
if let Err(status_error) =
|
||||
self.account_service.update_status(account_id, status).await
|
||||
{
|
||||
error!(
|
||||
account_id = %account_id,
|
||||
attempts = MAX_ATTEMPTS,
|
||||
error = %e,
|
||||
"token 刷新重试次数已耗尽"
|
||||
status,
|
||||
error = ?status_error,
|
||||
"写入永久刷新失败状态失败"
|
||||
);
|
||||
self.schedule_recovery(
|
||||
account_id.to_string(),
|
||||
Duration::from_millis(RECOVERY_DELAY_MS),
|
||||
)
|
||||
.await;
|
||||
return Err(SchedulerError::AccountNotFound(format!(
|
||||
"Max attempts reached: {}",
|
||||
e
|
||||
)));
|
||||
}
|
||||
return Err(SchedulerError::AccountNotFound(format!(
|
||||
"Permanent failure: {}",
|
||||
error
|
||||
)));
|
||||
}
|
||||
warn!(
|
||||
account_id = %account_id,
|
||||
hits = permanent_hits,
|
||||
threshold = PERMANENT_THRESHOLD,
|
||||
"检测到永久错误,继续重试确认"
|
||||
);
|
||||
}
|
||||
|
||||
if attempt < MAX_ATTEMPTS {
|
||||
// 指数退避:5s, 15s, 45s, 135s, 300s(有上限)
|
||||
let backoff = BASE_DELAY_MS.saturating_mul(3_u64.pow(attempt - 1));
|
||||
let backoff = backoff.min(300_000);
|
||||
let delay = Duration::from_millis(backoff);
|
||||
|
||||
warn!(
|
||||
account_id = %account_id,
|
||||
attempt,
|
||||
max_attempts = MAX_ATTEMPTS,
|
||||
delay_secs = delay.as_secs(),
|
||||
error = %error,
|
||||
"token 刷新尝试失败,准备重试"
|
||||
);
|
||||
tokio::time::sleep(delay).await;
|
||||
} else {
|
||||
error!(
|
||||
account_id = %account_id,
|
||||
attempts = MAX_ATTEMPTS,
|
||||
error = %error,
|
||||
"token 刷新重试次数已耗尽"
|
||||
);
|
||||
self.schedule_recovery(
|
||||
account_id.to_string(),
|
||||
Duration::from_millis(RECOVERY_DELAY_MS),
|
||||
)
|
||||
.await;
|
||||
return Err(SchedulerError::AccountNotFound(format!(
|
||||
"Max attempts reached: {}",
|
||||
error
|
||||
)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -463,6 +488,34 @@ fn jitter_delay_with_factor(delay: Duration, factor: f64) -> Duration {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use async_trait::async_trait;
|
||||
use secrecy::SecretString;
|
||||
use std::sync::{
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
Arc,
|
||||
};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::{
|
||||
codex::{
|
||||
accounts::{
|
||||
pool::AccountPool,
|
||||
repository::{AccountRepository, AccountUsageRepository, NewAccount},
|
||||
service::{AccountService, AccountServiceDependencies},
|
||||
},
|
||||
gateway::{
|
||||
fingerprint::model::Fingerprint,
|
||||
oauth::{RefreshFailure, TokenPair, TokenRefresher},
|
||||
transport::websocket::CodexWebSocketPool,
|
||||
},
|
||||
},
|
||||
config::{
|
||||
AdminConfig, ApiConfig, AuthConfig, DatabaseConfig, LoggingConfig, ModelConfig,
|
||||
QuotaConfig, QuotaWarningThresholds, SecurityConfig, ServerConfig, TlsConfig,
|
||||
UsageStatsConfig,
|
||||
},
|
||||
platform::{crypto::SecretBox, storage::db::connect_sqlite},
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn refresh_concurrency_limit_should_never_be_zero() {
|
||||
@@ -480,4 +533,146 @@ mod tests {
|
||||
Duration::from_secs(120)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn do_refresh_inner_should_mark_expired_only_after_second_permanent_failure() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let db = dir.path().join("refresh-scheduler.sqlite");
|
||||
let url = format!("sqlite://{}", db.display());
|
||||
let pool = connect_sqlite(&url).await.unwrap();
|
||||
let repo = AccountRepository::new(pool.clone(), SecretBox::new([41u8; 32]));
|
||||
repo.insert(NewAccount {
|
||||
id: "acct_scheduler".to_string(),
|
||||
email: None,
|
||||
account_id: None,
|
||||
user_id: None,
|
||||
label: None,
|
||||
plan_type: None,
|
||||
access_token: SecretString::new("access-old".to_string().into()),
|
||||
refresh_token: Some(SecretString::new("refresh-old".to_string().into())),
|
||||
access_token_expires_at: None,
|
||||
status: AccountStatus::Active,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let observed_statuses = Arc::new(Mutex::new(Vec::new()));
|
||||
let refresher = AlwaysInvalidGrantRefresher {
|
||||
repo: repo.clone(),
|
||||
account_id: "acct_scheduler".to_string(),
|
||||
calls: Arc::new(AtomicUsize::new(0)),
|
||||
observed_statuses: observed_statuses.clone(),
|
||||
};
|
||||
let config = test_config(url);
|
||||
let account_service = Arc::new(AccountService::new(
|
||||
Arc::new(config.clone()),
|
||||
AccountServiceDependencies {
|
||||
repository: Some(repo.clone()),
|
||||
usage_repository: Some(AccountUsageRepository::new(pool)),
|
||||
cookie_repository: None,
|
||||
token_refresher: Some(Arc::new(refresher.clone())),
|
||||
account_pool: Arc::new(Mutex::new(AccountPool::default())),
|
||||
websocket_pool: Arc::new(CodexWebSocketPool::with_default_max_age()),
|
||||
fingerprint: Fingerprint::default_for_tests(),
|
||||
},
|
||||
));
|
||||
let scheduler = RefreshScheduler::new(account_service, config);
|
||||
|
||||
let result = scheduler.do_refresh_inner("acct_scheduler").await;
|
||||
|
||||
assert!(result.is_err());
|
||||
assert_eq!(refresher.calls.load(Ordering::SeqCst), 2);
|
||||
assert_eq!(
|
||||
observed_statuses.lock().await.as_slice(),
|
||||
[AccountStatus::Active, AccountStatus::Active]
|
||||
);
|
||||
let stored = repo.get("acct_scheduler").await.unwrap().unwrap();
|
||||
assert_eq!(stored.status, AccountStatus::Expired);
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct AlwaysInvalidGrantRefresher {
|
||||
repo: AccountRepository,
|
||||
account_id: String,
|
||||
calls: Arc<AtomicUsize>,
|
||||
observed_statuses: Arc<Mutex<Vec<AccountStatus>>>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TokenRefresher for AlwaysInvalidGrantRefresher {
|
||||
async fn refresh(&self, _refresh_token: &str) -> Result<TokenPair, RefreshFailure> {
|
||||
self.calls.fetch_add(1, Ordering::SeqCst);
|
||||
let status = self
|
||||
.repo
|
||||
.get(&self.account_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.status;
|
||||
self.observed_statuses.lock().await.push(status);
|
||||
Err(RefreshFailure::InvalidGrant)
|
||||
}
|
||||
}
|
||||
|
||||
fn test_config(database_url: String) -> AppConfig {
|
||||
AppConfig {
|
||||
server: ServerConfig {
|
||||
host: "127.0.0.1".to_string(),
|
||||
port: 0,
|
||||
},
|
||||
api: ApiConfig {
|
||||
base_url: "https://chatgpt.com/backend-api".to_string(),
|
||||
},
|
||||
model: ModelConfig {
|
||||
default_model: "gpt-5.5".to_string(),
|
||||
default_reasoning_effort: None,
|
||||
service_tier: None,
|
||||
aliases: Default::default(),
|
||||
},
|
||||
auth: AuthConfig {
|
||||
refresh_margin_seconds: 300,
|
||||
refresh_enabled: true,
|
||||
refresh_concurrency: 2,
|
||||
max_concurrent_per_account: 3,
|
||||
request_interval_ms: 50,
|
||||
rotation_strategy: "least_used".to_string(),
|
||||
tier_priority: Vec::new(),
|
||||
oauth_client_id: "app_EMoamEEZ73f0CkXaXp7hrann".to_string(),
|
||||
oauth_auth_endpoint: "https://auth.openai.com/oauth/authorize".to_string(),
|
||||
oauth_token_endpoint: "https://auth.openai.com/oauth/token".to_string(),
|
||||
},
|
||||
quota: QuotaConfig {
|
||||
refresh_interval_minutes: 5,
|
||||
warning_thresholds: QuotaWarningThresholds {
|
||||
primary: vec![80, 90],
|
||||
secondary: vec![80, 90],
|
||||
},
|
||||
skip_exhausted: true,
|
||||
},
|
||||
usage_stats: UsageStatsConfig {
|
||||
history_retention_days: None,
|
||||
},
|
||||
database: DatabaseConfig { url: database_url },
|
||||
security: SecurityConfig {
|
||||
master_key_file: "data/master.key".to_string(),
|
||||
api_key_pepper_file: "data/api-key-pepper.key".to_string(),
|
||||
},
|
||||
tls: TlsConfig {
|
||||
force_http11: false,
|
||||
},
|
||||
ws_pool: Default::default(),
|
||||
admin: AdminConfig {
|
||||
session_ttl_minutes: 1440,
|
||||
default_username: "admin".to_string(),
|
||||
default_password: "admin".to_string(),
|
||||
session_cleanup_interval_secs: 3600,
|
||||
},
|
||||
logging: LoggingConfig {
|
||||
directory: "logs".to_string(),
|
||||
retention_days: 14,
|
||||
enabled: false,
|
||||
capacity: 2_000,
|
||||
capture_body: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user