mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-27 08:01:04 +00:00
refactor: split http services and codex domains
Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AccountLifecycleEvent {
|
||||
Added,
|
||||
Refreshed,
|
||||
Expired,
|
||||
QuotaExhausted,
|
||||
Banned,
|
||||
Disabled,
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
pub mod lifecycle;
|
||||
pub mod model;
|
||||
pub mod pool;
|
||||
pub mod repository;
|
||||
pub mod service;
|
||||
@@ -0,0 +1,53 @@
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum AccountStatus {
|
||||
Active,
|
||||
Expired,
|
||||
QuotaExhausted,
|
||||
Refreshing,
|
||||
Disabled,
|
||||
Banned,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct Account {
|
||||
pub id: String,
|
||||
pub email: Option<String>,
|
||||
pub account_id: Option<String>,
|
||||
pub user_id: Option<String>,
|
||||
pub label: Option<String>,
|
||||
pub plan_type: Option<String>,
|
||||
pub access_token: String,
|
||||
pub refresh_token: Option<String>,
|
||||
pub access_token_expires_at: Option<DateTime<Utc>>,
|
||||
pub status: AccountStatus,
|
||||
pub quota_limit_reached: bool,
|
||||
pub quota_cooldown_until: Option<DateTime<Utc>>,
|
||||
pub cloudflare_cooldown_until: Option<DateTime<Utc>>,
|
||||
pub added_at: String,
|
||||
pub last_used_at: Option<String>,
|
||||
}
|
||||
|
||||
impl Account {
|
||||
pub fn test(id: &str, status: AccountStatus) -> Self {
|
||||
Self {
|
||||
id: id.to_string(),
|
||||
email: None,
|
||||
account_id: None,
|
||||
user_id: None,
|
||||
label: None,
|
||||
plan_type: None,
|
||||
access_token: format!("token-{id}"),
|
||||
refresh_token: Some(format!("refresh-{id}")),
|
||||
access_token_expires_at: Some(Utc::now() + Duration::hours(1)),
|
||||
status,
|
||||
quota_limit_reached: false,
|
||||
quota_cooldown_until: None,
|
||||
cloudflare_cooldown_until: None,
|
||||
added_at: Utc::now().to_rfc3339(),
|
||||
last_used_at: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
use std::collections::{BTreeMap, VecDeque};
|
||||
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
|
||||
use crate::codex::accounts::model::{Account, AccountStatus};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RotationStrategy {
|
||||
LeastUsed,
|
||||
RoundRobin,
|
||||
Sticky,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AccountPoolOptions {
|
||||
pub max_concurrent_per_account: usize,
|
||||
pub stale_slot_ttl: Duration,
|
||||
pub rotation_strategy: RotationStrategy,
|
||||
pub skip_quota_limited: bool,
|
||||
pub tier_priority: Vec<String>,
|
||||
pub model_plan_allowlist: BTreeMap<String, Vec<String>>,
|
||||
}
|
||||
|
||||
impl Default for AccountPoolOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
max_concurrent_per_account: 3,
|
||||
stale_slot_ttl: Duration::minutes(5),
|
||||
rotation_strategy: RotationStrategy::LeastUsed,
|
||||
skip_quota_limited: true,
|
||||
tier_priority: Vec::new(),
|
||||
model_plan_allowlist: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AccountAcquireRequest {
|
||||
pub model: String,
|
||||
pub exclude_account_ids: Vec<String>,
|
||||
pub preferred_account_id: Option<String>,
|
||||
pub now: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl AccountAcquireRequest {
|
||||
pub fn new(model: impl Into<String>, now: DateTime<Utc>) -> Self {
|
||||
Self {
|
||||
model: model.into(),
|
||||
exclude_account_ids: Vec::new(),
|
||||
preferred_account_id: None,
|
||||
now,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_exclude_account_ids(
|
||||
mut self,
|
||||
account_ids: impl IntoIterator<Item = impl Into<String>>,
|
||||
) -> Self {
|
||||
self.exclude_account_ids = account_ids.into_iter().map(Into::into).collect();
|
||||
self
|
||||
}
|
||||
|
||||
pub fn with_preferred_account_id(mut self, account_id: impl Into<String>) -> Self {
|
||||
self.preferred_account_id = Some(account_id.into());
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AcquiredAccount {
|
||||
pub account: Account,
|
||||
pub previous_slot_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct AccountCapacitySummary {
|
||||
pub max_concurrent_per_account: usize,
|
||||
pub total_slots: usize,
|
||||
pub used_slots: usize,
|
||||
pub available_slots: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct AccountPool {
|
||||
accounts: BTreeMap<String, Account>,
|
||||
slots: BTreeMap<String, VecDeque<DateTime<Utc>>>,
|
||||
options: AccountPoolOptions,
|
||||
round_robin_cursor: usize,
|
||||
}
|
||||
|
||||
impl Default for AccountPool {
|
||||
fn default() -> Self {
|
||||
Self::with_options(AccountPoolOptions::default())
|
||||
}
|
||||
}
|
||||
|
||||
impl AccountPool {
|
||||
pub fn with_options(options: AccountPoolOptions) -> Self {
|
||||
Self {
|
||||
accounts: BTreeMap::new(),
|
||||
slots: BTreeMap::new(),
|
||||
options,
|
||||
round_robin_cursor: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn insert(&mut self, account: Account) {
|
||||
self.accounts.insert(account.id.clone(), account);
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, account_id: &str) -> bool {
|
||||
let removed = self.accounts.remove(account_id).is_some();
|
||||
self.slots.remove(account_id);
|
||||
removed
|
||||
}
|
||||
|
||||
pub fn clear(&mut self) {
|
||||
self.accounts.clear();
|
||||
self.slots.clear();
|
||||
self.round_robin_cursor = 0;
|
||||
}
|
||||
|
||||
pub fn set_model_plan_allowlist(&mut self, allowlist: BTreeMap<String, Vec<String>>) {
|
||||
self.options.model_plan_allowlist = allowlist;
|
||||
}
|
||||
|
||||
pub fn set_label(&mut self, account_id: &str, label: Option<String>) -> bool {
|
||||
let Some(account) = self.accounts.get_mut(account_id) else {
|
||||
return false;
|
||||
};
|
||||
account.label = label;
|
||||
true
|
||||
}
|
||||
|
||||
pub fn set_status(&mut self, account_id: &str, status: AccountStatus) -> bool {
|
||||
let Some(account) = self.accounts.get_mut(account_id) else {
|
||||
return false;
|
||||
};
|
||||
account.status = status;
|
||||
if status != AccountStatus::Active {
|
||||
self.slots.remove(account_id);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
pub fn reset_usage(&mut self, account_id: &str) -> bool {
|
||||
let Some(account) = self.accounts.get_mut(account_id) else {
|
||||
return false;
|
||||
};
|
||||
account.last_used_at = None;
|
||||
true
|
||||
}
|
||||
|
||||
pub fn mark_quota_limited_until(
|
||||
&mut self,
|
||||
account_id: &str,
|
||||
cooldown_until: DateTime<Utc>,
|
||||
) -> bool {
|
||||
let Some(account) = self.accounts.get_mut(account_id) else {
|
||||
return false;
|
||||
};
|
||||
account.quota_limit_reached = true;
|
||||
account.quota_cooldown_until = Some(cooldown_until);
|
||||
self.slots.remove(account_id);
|
||||
true
|
||||
}
|
||||
|
||||
pub fn set_cloudflare_cooldown_until(
|
||||
&mut self,
|
||||
account_id: &str,
|
||||
cooldown_until: DateTime<Utc>,
|
||||
) -> bool {
|
||||
let Some(account) = self.accounts.get_mut(account_id) else {
|
||||
return false;
|
||||
};
|
||||
account.cloudflare_cooldown_until = Some(cooldown_until);
|
||||
self.slots.remove(account_id);
|
||||
true
|
||||
}
|
||||
|
||||
pub fn acquire(&mut self, model: &str) -> Option<Account> {
|
||||
self.acquire_with(AccountAcquireRequest::new(model, Utc::now()))
|
||||
.map(|acquired| acquired.account)
|
||||
}
|
||||
|
||||
pub fn acquire_with(&mut self, request: AccountAcquireRequest) -> Option<AcquiredAccount> {
|
||||
self.cleanup_stale_slots(request.now);
|
||||
let candidates = self.candidates(&request);
|
||||
let selected = if let Some(preferred_account_id) = &request.preferred_account_id {
|
||||
candidates
|
||||
.iter()
|
||||
.find(|account| account.id == *preferred_account_id)
|
||||
.cloned()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
.or_else(|| match self.options.rotation_strategy {
|
||||
RotationStrategy::LeastUsed => self.select_least_used(&candidates),
|
||||
RotationStrategy::RoundRobin => self.select_round_robin(&candidates),
|
||||
RotationStrategy::Sticky => self.select_sticky(&candidates),
|
||||
})?;
|
||||
let previous_slot_at = self.previous_slot_at(&selected.id);
|
||||
self.push_slot(&selected.id, request.now);
|
||||
Some(AcquiredAccount {
|
||||
account: selected,
|
||||
previous_slot_at,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn release(&mut self, account_id: &str) {
|
||||
let Some(slots) = self.slots.get_mut(account_id) else {
|
||||
return;
|
||||
};
|
||||
slots.pop_front();
|
||||
if slots.is_empty() {
|
||||
self.slots.remove(account_id);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn capacity_summary(&mut self, now: DateTime<Utc>) -> AccountCapacitySummary {
|
||||
self.cleanup_stale_slots(now);
|
||||
let active_accounts = self
|
||||
.accounts
|
||||
.values()
|
||||
.filter(|account| {
|
||||
account.status == AccountStatus::Active && self.is_quota_available(account, now)
|
||||
})
|
||||
.count();
|
||||
let total_slots = active_accounts * self.options.max_concurrent_per_account;
|
||||
let used_slots = self
|
||||
.slots
|
||||
.iter()
|
||||
.filter(|(account_id, _)| {
|
||||
self.accounts
|
||||
.get(*account_id)
|
||||
.is_some_and(|account| account.status == AccountStatus::Active)
|
||||
})
|
||||
.map(|(_, slots)| slots.len().min(self.options.max_concurrent_per_account))
|
||||
.sum();
|
||||
|
||||
AccountCapacitySummary {
|
||||
max_concurrent_per_account: self.options.max_concurrent_per_account,
|
||||
total_slots,
|
||||
used_slots,
|
||||
available_slots: total_slots.saturating_sub(used_slots),
|
||||
}
|
||||
}
|
||||
|
||||
fn select_least_used(&mut self, candidates: &[Account]) -> Option<Account> {
|
||||
let best_last_used = candidates
|
||||
.iter()
|
||||
.map(|account| account.last_used_at.as_deref())
|
||||
.min()?;
|
||||
let tied = candidates
|
||||
.iter()
|
||||
.filter(|account| account.last_used_at.as_deref() == best_last_used)
|
||||
.collect::<Vec<_>>();
|
||||
let index = self.round_robin_cursor % tied.len();
|
||||
self.round_robin_cursor = (self.round_robin_cursor + 1) % tied.len();
|
||||
Some((*tied[index]).clone())
|
||||
}
|
||||
|
||||
fn select_sticky(&self, candidates: &[Account]) -> Option<Account> {
|
||||
candidates
|
||||
.iter()
|
||||
.max_by_key(|account| account.last_used_at.clone())
|
||||
.cloned()
|
||||
}
|
||||
|
||||
fn select_round_robin(&mut self, candidates: &[Account]) -> Option<Account> {
|
||||
if candidates.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let index = self.round_robin_cursor % candidates.len();
|
||||
self.round_robin_cursor = (index + 1) % candidates.len();
|
||||
Some(candidates[index].clone())
|
||||
}
|
||||
|
||||
fn candidates(&self, request: &AccountAcquireRequest) -> Vec<Account> {
|
||||
let mut candidates = self
|
||||
.accounts
|
||||
.values()
|
||||
.filter(|account| self.is_base_available(account, request))
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
if let Some(best_tier) = self.best_available_tier(&candidates) {
|
||||
candidates.retain(|account| account.plan_type.as_deref() == Some(best_tier.as_str()));
|
||||
}
|
||||
candidates
|
||||
}
|
||||
|
||||
fn is_base_available(&self, account: &Account, request: &AccountAcquireRequest) -> bool {
|
||||
account.status == AccountStatus::Active
|
||||
&& self.slot_count(&account.id) < self.options.max_concurrent_per_account
|
||||
&& self.is_quota_available(account, request.now)
|
||||
&& self.is_model_allowed(account, &request.model)
|
||||
&& !request
|
||||
.exclude_account_ids
|
||||
.iter()
|
||||
.any(|account_id| account_id == &account.id)
|
||||
&& account
|
||||
.cloudflare_cooldown_until
|
||||
.is_none_or(|cooldown_until| request.now >= cooldown_until)
|
||||
}
|
||||
|
||||
fn is_quota_available(&self, account: &Account, now: DateTime<Utc>) -> bool {
|
||||
if !self.options.skip_quota_limited || !account.quota_limit_reached {
|
||||
return true;
|
||||
}
|
||||
account
|
||||
.quota_cooldown_until
|
||||
.is_some_and(|cooldown_until| now >= cooldown_until)
|
||||
}
|
||||
|
||||
fn slot_count(&self, account_id: &str) -> usize {
|
||||
self.slots.get(account_id).map_or(0, VecDeque::len)
|
||||
}
|
||||
|
||||
fn previous_slot_at(&self, account_id: &str) -> Option<DateTime<Utc>> {
|
||||
self.slots
|
||||
.get(account_id)
|
||||
.and_then(|slots| slots.back().cloned())
|
||||
}
|
||||
|
||||
fn push_slot(&mut self, account_id: &str, now: DateTime<Utc>) {
|
||||
self.slots
|
||||
.entry(account_id.to_string())
|
||||
.or_default()
|
||||
.push_back(now);
|
||||
}
|
||||
|
||||
fn cleanup_stale_slots(&mut self, now: DateTime<Utc>) {
|
||||
let ttl = self.options.stale_slot_ttl;
|
||||
self.slots.retain(|_, slots| {
|
||||
// slot 只代表本进程内的在途请求,超过 TTL 后必须释放,避免异常中断永久占满账号。
|
||||
slots.retain(|slot_at| now.signed_duration_since(*slot_at) <= ttl);
|
||||
!slots.is_empty()
|
||||
});
|
||||
}
|
||||
|
||||
fn is_model_allowed(&self, account: &Account, model: &str) -> bool {
|
||||
let Some(allowed_plans) = self.options.model_plan_allowlist.get(model) else {
|
||||
return true;
|
||||
};
|
||||
allowed_plans
|
||||
.iter()
|
||||
.any(|plan| account.plan_type.as_deref() == Some(plan.as_str()))
|
||||
}
|
||||
|
||||
fn best_available_tier(&self, candidates: &[Account]) -> Option<String> {
|
||||
self.options.tier_priority.iter().find_map(|tier| {
|
||||
candidates
|
||||
.iter()
|
||||
.find(|account| account.plan_type.as_deref() == Some(tier.as_str()))
|
||||
.and_then(|account| account.plan_type.clone())
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,716 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use secrecy::{ExposeSecret, SecretString};
|
||||
use sqlx::{Row, SqlitePool};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::{
|
||||
codex::accounts::model::{Account, AccountStatus},
|
||||
utils::crypto::{CryptoError, SecretBox},
|
||||
utils::pagination::{decode_cursor, encode_cursor, Page},
|
||||
};
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum AccountRepositoryError {
|
||||
#[error("database error: {0}")]
|
||||
Database(#[from] sqlx::Error),
|
||||
#[error("account secret encryption error: {0}")]
|
||||
Crypto(#[from] CryptoError),
|
||||
#[error("invalid account status: {0}")]
|
||||
InvalidStatus(String),
|
||||
#[error("invalid account timestamp: {0}")]
|
||||
InvalidTimestamp(#[from] chrono::ParseError),
|
||||
#[error("invalid pagination cursor")]
|
||||
InvalidCursor,
|
||||
}
|
||||
|
||||
pub type AccountRepositoryResult<T> = Result<T, AccountRepositoryError>;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct NewAccount {
|
||||
pub id: String,
|
||||
pub email: Option<String>,
|
||||
pub account_id: Option<String>,
|
||||
pub user_id: Option<String>,
|
||||
pub label: Option<String>,
|
||||
pub plan_type: Option<String>,
|
||||
pub access_token: SecretString,
|
||||
pub refresh_token: Option<SecretString>,
|
||||
pub access_token_expires_at: Option<DateTime<Utc>>,
|
||||
pub status: AccountStatus,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct TokenUpdate {
|
||||
pub access_token: SecretString,
|
||||
pub refresh_token: Option<SecretString>,
|
||||
pub access_token_expires_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct AccountClaimsUpdate {
|
||||
pub email: Option<String>,
|
||||
pub account_id: Option<String>,
|
||||
pub user_id: Option<String>,
|
||||
pub plan_type: Option<String>,
|
||||
pub access_token: SecretString,
|
||||
pub refresh_token: Option<SecretString>,
|
||||
pub access_token_expires_at: Option<DateTime<Utc>>,
|
||||
pub status: AccountStatus,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StoredAccount {
|
||||
pub id: String,
|
||||
pub email: Option<String>,
|
||||
pub account_id: Option<String>,
|
||||
pub user_id: Option<String>,
|
||||
pub label: Option<String>,
|
||||
pub plan_type: Option<String>,
|
||||
pub access_token: SecretString,
|
||||
pub refresh_token: Option<SecretString>,
|
||||
pub access_token_expires_at: Option<DateTime<Utc>>,
|
||||
pub status: AccountStatus,
|
||||
pub added_at: DateTime<Utc>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StoredAccountMetadata {
|
||||
pub id: String,
|
||||
pub email: Option<String>,
|
||||
pub account_id: Option<String>,
|
||||
pub user_id: Option<String>,
|
||||
pub label: Option<String>,
|
||||
pub plan_type: Option<String>,
|
||||
pub access_token_expires_at: Option<DateTime<Utc>>,
|
||||
pub status: AccountStatus,
|
||||
pub added_at: DateTime<Utc>,
|
||||
pub updated_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct UsageDelta {
|
||||
pub input_tokens: i64,
|
||||
pub output_tokens: i64,
|
||||
pub cached_tokens: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AccountUsageRecord {
|
||||
pub account_id: String,
|
||||
pub request_count: i64,
|
||||
pub input_tokens: i64,
|
||||
pub output_tokens: i64,
|
||||
pub cached_tokens: i64,
|
||||
pub last_used_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AccountUsageListRecord {
|
||||
pub account_id: String,
|
||||
pub email: Option<String>,
|
||||
pub label: Option<String>,
|
||||
pub plan_type: Option<String>,
|
||||
pub request_count: i64,
|
||||
pub input_tokens: i64,
|
||||
pub output_tokens: i64,
|
||||
pub cached_tokens: i64,
|
||||
pub last_used_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct AccountUsageSummary {
|
||||
pub account_count: i64,
|
||||
pub request_count: i64,
|
||||
pub input_tokens: i64,
|
||||
pub output_tokens: i64,
|
||||
pub cached_tokens: i64,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AccountRepository {
|
||||
pool: SqlitePool,
|
||||
secret_box: SecretBox,
|
||||
}
|
||||
|
||||
impl AccountRepository {
|
||||
pub fn new(pool: SqlitePool, secret_box: SecretBox) -> Self {
|
||||
Self { pool, secret_box }
|
||||
}
|
||||
|
||||
pub async fn insert(&self, account: NewAccount) -> AccountRepositoryResult<()> {
|
||||
let now = Utc::now().to_rfc3339();
|
||||
let access_token_cipher = self.secret_box.encrypt(&account.access_token)?;
|
||||
let refresh_token_cipher = account
|
||||
.refresh_token
|
||||
.as_ref()
|
||||
.map(|token| self.secret_box.encrypt(token))
|
||||
.transpose()?;
|
||||
sqlx::query(
|
||||
"insert into accounts (id, email, account_id, user_id, label, plan_type, access_token_cipher, refresh_token_cipher, access_token_expires_at, status, added_at, updated_at) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
)
|
||||
.bind(account.id)
|
||||
.bind(account.email)
|
||||
.bind(account.account_id)
|
||||
.bind(account.user_id)
|
||||
.bind(account.label)
|
||||
.bind(account.plan_type)
|
||||
.bind(access_token_cipher)
|
||||
.bind(refresh_token_cipher)
|
||||
.bind(account.access_token_expires_at.map(|value| value.to_rfc3339()))
|
||||
.bind(status_to_db(account.status))
|
||||
.bind(&now)
|
||||
.bind(now)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get(&self, id: &str) -> AccountRepositoryResult<Option<StoredAccount>> {
|
||||
let row = sqlx::query(
|
||||
"select id, email, account_id, user_id, label, plan_type, access_token_cipher, refresh_token_cipher, access_token_expires_at, status, added_at, updated_at from accounts where id = ?",
|
||||
)
|
||||
.bind(id)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
row.map(|row| self.account_from_row(&row)).transpose()
|
||||
}
|
||||
|
||||
pub async fn exists(&self, id: &str) -> AccountRepositoryResult<bool> {
|
||||
let row = sqlx::query("select 1 from accounts where id = ?")
|
||||
.bind(id)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
Ok(row.is_some())
|
||||
}
|
||||
|
||||
pub async fn find_by_chatgpt_identity(
|
||||
&self,
|
||||
account_id: &str,
|
||||
user_id: Option<&str>,
|
||||
) -> AccountRepositoryResult<Option<StoredAccount>> {
|
||||
let row = sqlx::query(
|
||||
"select id, email, account_id, user_id, label, plan_type, access_token_cipher, refresh_token_cipher, access_token_expires_at, status, added_at, updated_at from accounts where account_id = ? and ((user_id is null and ? is null) or user_id = ?) order by added_at asc limit 1",
|
||||
)
|
||||
.bind(account_id)
|
||||
.bind(user_id)
|
||||
.bind(user_id)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
row.map(|row| self.account_from_row(&row)).transpose()
|
||||
}
|
||||
|
||||
pub async fn list(
|
||||
&self,
|
||||
cursor: Option<String>,
|
||||
limit: u32,
|
||||
) -> AccountRepositoryResult<Page<StoredAccount>> {
|
||||
let fetch_limit = i64::from(limit) + 1;
|
||||
let rows = if let Some(cursor) = cursor {
|
||||
let (created_at, id) =
|
||||
decode_cursor(&cursor).ok_or(AccountRepositoryError::InvalidCursor)?;
|
||||
sqlx::query(
|
||||
"select id, email, account_id, user_id, label, plan_type, access_token_cipher, refresh_token_cipher, access_token_expires_at, status, added_at, updated_at from accounts where added_at < ? or (added_at = ? and id < ?) order by added_at desc, id desc limit ?",
|
||||
)
|
||||
.bind(&created_at)
|
||||
.bind(created_at)
|
||||
.bind(id)
|
||||
.bind(fetch_limit)
|
||||
.fetch_all(&self.pool)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query(
|
||||
"select id, email, account_id, user_id, label, plan_type, access_token_cipher, refresh_token_cipher, access_token_expires_at, status, added_at, updated_at from accounts order by added_at desc, id desc limit ?",
|
||||
)
|
||||
.bind(fetch_limit)
|
||||
.fetch_all(&self.pool)
|
||||
.await?
|
||||
};
|
||||
|
||||
let has_next = rows.len() > limit as usize;
|
||||
let take_count = rows.len().min(limit as usize);
|
||||
let mut items = Vec::with_capacity(take_count);
|
||||
for row in rows.into_iter().take(take_count) {
|
||||
items.push(self.account_from_row(&row)?);
|
||||
}
|
||||
let next_cursor = if has_next {
|
||||
items
|
||||
.last()
|
||||
.map(|account| encode_cursor(&account.added_at.to_rfc3339(), &account.id))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(Page { items, next_cursor })
|
||||
}
|
||||
|
||||
pub async fn list_all(&self) -> AccountRepositoryResult<Vec<StoredAccount>> {
|
||||
let rows = sqlx::query(
|
||||
"select id, email, account_id, user_id, label, plan_type, access_token_cipher, refresh_token_cipher, access_token_expires_at, status, added_at, updated_at from accounts order by added_at desc, id desc",
|
||||
)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
let mut accounts = Vec::with_capacity(rows.len());
|
||||
for row in rows {
|
||||
accounts.push(self.account_from_row(&row)?);
|
||||
}
|
||||
Ok(accounts)
|
||||
}
|
||||
|
||||
pub async fn list_metadata(
|
||||
&self,
|
||||
cursor: Option<String>,
|
||||
limit: u32,
|
||||
) -> AccountRepositoryResult<Page<StoredAccountMetadata>> {
|
||||
let fetch_limit = i64::from(limit) + 1;
|
||||
let rows = if let Some(cursor) = cursor {
|
||||
let (created_at, id) =
|
||||
decode_cursor(&cursor).ok_or(AccountRepositoryError::InvalidCursor)?;
|
||||
sqlx::query(
|
||||
"select id, email, account_id, user_id, label, plan_type, access_token_expires_at, status, added_at, updated_at from accounts where added_at < ? or (added_at = ? and id < ?) order by added_at desc, id desc limit ?",
|
||||
)
|
||||
.bind(&created_at)
|
||||
.bind(created_at)
|
||||
.bind(id)
|
||||
.bind(fetch_limit)
|
||||
.fetch_all(&self.pool)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query(
|
||||
"select id, email, account_id, user_id, label, plan_type, access_token_expires_at, status, added_at, updated_at from accounts order by added_at desc, id desc limit ?",
|
||||
)
|
||||
.bind(fetch_limit)
|
||||
.fetch_all(&self.pool)
|
||||
.await?
|
||||
};
|
||||
|
||||
let has_next = rows.len() > limit as usize;
|
||||
let take_count = rows.len().min(limit as usize);
|
||||
let mut items = Vec::with_capacity(take_count);
|
||||
for row in rows.into_iter().take(take_count) {
|
||||
items.push(metadata_from_row(&row)?);
|
||||
}
|
||||
let next_cursor = if has_next {
|
||||
items
|
||||
.last()
|
||||
.map(|account| encode_cursor(&account.added_at.to_rfc3339(), &account.id))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(Page { items, next_cursor })
|
||||
}
|
||||
|
||||
pub async fn list_all_metadata(&self) -> AccountRepositoryResult<Vec<StoredAccountMetadata>> {
|
||||
let rows = sqlx::query(
|
||||
"select id, email, account_id, user_id, label, plan_type, access_token_expires_at, status, added_at, updated_at from accounts order by added_at desc, id desc",
|
||||
)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
let mut accounts = Vec::with_capacity(rows.len());
|
||||
for row in rows {
|
||||
accounts.push(metadata_from_row(&row)?);
|
||||
}
|
||||
Ok(accounts)
|
||||
}
|
||||
|
||||
pub async fn list_pool_accounts(&self) -> AccountRepositoryResult<Vec<Account>> {
|
||||
let rows = sqlx::query(
|
||||
"select accounts.id, email, accounts.account_id, user_id, label, plan_type, access_token_cipher, refresh_token_cipher, access_token_expires_at, status, added_at, updated_at, account_usage.last_used_at as usage_last_used_at from accounts left join account_usage on account_usage.account_id = accounts.id order by added_at desc, accounts.id desc",
|
||||
)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
let mut accounts = Vec::with_capacity(rows.len());
|
||||
for row in rows {
|
||||
let stored = self.account_from_row(&row)?;
|
||||
let access_token = stored.access_token.expose_secret().to_string();
|
||||
let refresh_token = stored
|
||||
.refresh_token
|
||||
.as_ref()
|
||||
.map(|token| token.expose_secret().to_string());
|
||||
accounts.push(Account {
|
||||
id: stored.id,
|
||||
email: stored.email,
|
||||
account_id: stored.account_id,
|
||||
user_id: stored.user_id,
|
||||
label: stored.label,
|
||||
plan_type: stored.plan_type,
|
||||
access_token,
|
||||
refresh_token,
|
||||
access_token_expires_at: stored.access_token_expires_at,
|
||||
status: stored.status,
|
||||
quota_limit_reached: false,
|
||||
quota_cooldown_until: None,
|
||||
cloudflare_cooldown_until: None,
|
||||
added_at: stored.added_at.to_rfc3339(),
|
||||
last_used_at: row.get("usage_last_used_at"),
|
||||
});
|
||||
}
|
||||
Ok(accounts)
|
||||
}
|
||||
|
||||
pub async fn set_status(
|
||||
&self,
|
||||
id: &str,
|
||||
status: AccountStatus,
|
||||
) -> AccountRepositoryResult<bool> {
|
||||
let result = sqlx::query("update accounts set status = ?, updated_at = ? where id = ?")
|
||||
.bind(status_to_db(status))
|
||||
.bind(Utc::now().to_rfc3339())
|
||||
.bind(id)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(result.rows_affected() > 0)
|
||||
}
|
||||
|
||||
pub async fn set_label(
|
||||
&self,
|
||||
id: &str,
|
||||
label: Option<String>,
|
||||
) -> AccountRepositoryResult<bool> {
|
||||
let result = sqlx::query("update accounts set label = ?, updated_at = ? where id = ?")
|
||||
.bind(label)
|
||||
.bind(Utc::now().to_rfc3339())
|
||||
.bind(id)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(result.rows_affected() > 0)
|
||||
}
|
||||
|
||||
pub async fn delete(&self, id: &str) -> AccountRepositoryResult<bool> {
|
||||
let result = sqlx::query("delete from accounts where id = ?")
|
||||
.bind(id)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(result.rows_affected() > 0)
|
||||
}
|
||||
|
||||
pub async fn delete_all(&self) -> AccountRepositoryResult<u64> {
|
||||
let result = sqlx::query("delete from accounts")
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(result.rows_affected())
|
||||
}
|
||||
|
||||
pub async fn update_tokens(
|
||||
&self,
|
||||
id: &str,
|
||||
update: TokenUpdate,
|
||||
) -> AccountRepositoryResult<bool> {
|
||||
let now = Utc::now().to_rfc3339();
|
||||
let access_token_cipher = self.secret_box.encrypt(&update.access_token)?;
|
||||
let expires_at = update
|
||||
.access_token_expires_at
|
||||
.map(|value| value.to_rfc3339());
|
||||
let result = if let Some(refresh_token) = update.refresh_token {
|
||||
let refresh_token_cipher = self.secret_box.encrypt(&refresh_token)?;
|
||||
sqlx::query(
|
||||
"update accounts set access_token_cipher = ?, refresh_token_cipher = ?, access_token_expires_at = ?, status = case when status in ('disabled', 'banned') then status else 'active' end, updated_at = ? where id = ?",
|
||||
)
|
||||
.bind(access_token_cipher)
|
||||
.bind(refresh_token_cipher)
|
||||
.bind(expires_at)
|
||||
.bind(now)
|
||||
.bind(id)
|
||||
.execute(&self.pool)
|
||||
.await?
|
||||
} else {
|
||||
// 刷新接口可能不返回新的 refresh_token;此时必须保留旧 RT,避免账号失去后续刷新能力。
|
||||
sqlx::query(
|
||||
"update accounts set access_token_cipher = ?, access_token_expires_at = ?, status = case when status in ('disabled', 'banned') then status else 'active' end, updated_at = ? where id = ?",
|
||||
)
|
||||
.bind(access_token_cipher)
|
||||
.bind(expires_at)
|
||||
.bind(now)
|
||||
.bind(id)
|
||||
.execute(&self.pool)
|
||||
.await?
|
||||
};
|
||||
Ok(result.rows_affected() > 0)
|
||||
}
|
||||
|
||||
pub async fn update_from_claims(
|
||||
&self,
|
||||
id: &str,
|
||||
update: AccountClaimsUpdate,
|
||||
) -> AccountRepositoryResult<bool> {
|
||||
let now = Utc::now().to_rfc3339();
|
||||
let access_token_cipher = self.secret_box.encrypt(&update.access_token)?;
|
||||
let expires_at = update
|
||||
.access_token_expires_at
|
||||
.map(|value| value.to_rfc3339());
|
||||
let result = if let Some(refresh_token) = update.refresh_token {
|
||||
let refresh_token_cipher = self.secret_box.encrypt(&refresh_token)?;
|
||||
sqlx::query(
|
||||
"update accounts set email = ?, account_id = ?, user_id = ?, plan_type = ?, access_token_cipher = ?, refresh_token_cipher = ?, access_token_expires_at = ?, status = ?, updated_at = ? where id = ?",
|
||||
)
|
||||
.bind(update.email)
|
||||
.bind(update.account_id)
|
||||
.bind(update.user_id)
|
||||
.bind(update.plan_type)
|
||||
.bind(access_token_cipher)
|
||||
.bind(refresh_token_cipher)
|
||||
.bind(expires_at)
|
||||
.bind(status_to_db(update.status))
|
||||
.bind(now)
|
||||
.bind(id)
|
||||
.execute(&self.pool)
|
||||
.await?
|
||||
} else {
|
||||
// OpenAI 刷新/导入未给新 RT 时保留原值,避免把可继续刷新的账号写坏。
|
||||
sqlx::query(
|
||||
"update accounts set email = ?, account_id = ?, user_id = ?, plan_type = ?, access_token_cipher = ?, access_token_expires_at = ?, status = ?, updated_at = ? where id = ?",
|
||||
)
|
||||
.bind(update.email)
|
||||
.bind(update.account_id)
|
||||
.bind(update.user_id)
|
||||
.bind(update.plan_type)
|
||||
.bind(access_token_cipher)
|
||||
.bind(expires_at)
|
||||
.bind(status_to_db(update.status))
|
||||
.bind(now)
|
||||
.bind(id)
|
||||
.execute(&self.pool)
|
||||
.await?
|
||||
};
|
||||
Ok(result.rows_affected() > 0)
|
||||
}
|
||||
|
||||
pub async fn record_usage(
|
||||
&self,
|
||||
account_id: &str,
|
||||
usage: UsageDelta,
|
||||
) -> AccountRepositoryResult<()> {
|
||||
let now = Utc::now().to_rfc3339();
|
||||
sqlx::query(
|
||||
"insert into account_usage (account_id, request_count, input_tokens, output_tokens, cached_tokens, last_used_at) values (?, 1, ?, ?, ?, ?) on conflict(account_id) do update set request_count = request_count + 1, input_tokens = input_tokens + excluded.input_tokens, output_tokens = output_tokens + excluded.output_tokens, cached_tokens = cached_tokens + excluded.cached_tokens, last_used_at = excluded.last_used_at",
|
||||
)
|
||||
.bind(account_id)
|
||||
.bind(usage.input_tokens)
|
||||
.bind(usage.output_tokens)
|
||||
.bind(usage.cached_tokens)
|
||||
.bind(now)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get_usage(
|
||||
&self,
|
||||
account_id: &str,
|
||||
) -> AccountRepositoryResult<Option<AccountUsageRecord>> {
|
||||
let row = sqlx::query(
|
||||
"select account_id, request_count, input_tokens, output_tokens, cached_tokens, last_used_at from account_usage where account_id = ?",
|
||||
)
|
||||
.bind(account_id)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
row.map(|row| usage_from_row(&row)).transpose()
|
||||
}
|
||||
|
||||
pub async fn update_quota_json(
|
||||
&self,
|
||||
account_id: &str,
|
||||
quota_json: &str,
|
||||
) -> AccountRepositoryResult<bool> {
|
||||
let now = Utc::now().to_rfc3339();
|
||||
let result = sqlx::query(
|
||||
"update accounts set quota_json = ?, quota_fetched_at = ?, updated_at = ? where id = ?",
|
||||
)
|
||||
.bind(quota_json)
|
||||
.bind(&now)
|
||||
.bind(now)
|
||||
.bind(account_id)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(result.rows_affected() > 0)
|
||||
}
|
||||
|
||||
fn account_from_row(
|
||||
&self,
|
||||
row: &sqlx::sqlite::SqliteRow,
|
||||
) -> AccountRepositoryResult<StoredAccount> {
|
||||
let access_token_cipher = row.get::<String, _>("access_token_cipher");
|
||||
let access_token = self.secret_box.decrypt(&access_token_cipher)?;
|
||||
let refresh_token = match row.get::<Option<String>, _>("refresh_token_cipher") {
|
||||
Some(cipher) => Some(self.secret_box.decrypt(&cipher)?),
|
||||
None => None,
|
||||
};
|
||||
Ok(StoredAccount {
|
||||
id: row.get("id"),
|
||||
email: row.get("email"),
|
||||
account_id: row.get("account_id"),
|
||||
user_id: row.get("user_id"),
|
||||
label: row.get("label"),
|
||||
plan_type: row.get("plan_type"),
|
||||
access_token,
|
||||
refresh_token,
|
||||
access_token_expires_at: parse_optional_rfc3339(
|
||||
row.get::<Option<String>, _>("access_token_expires_at"),
|
||||
)?,
|
||||
status: status_from_db(&row.get::<String, _>("status"))?,
|
||||
added_at: parse_rfc3339(&row.get::<String, _>("added_at"))?,
|
||||
updated_at: parse_rfc3339(&row.get::<String, _>("updated_at"))?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn status_to_db(status: AccountStatus) -> &'static str {
|
||||
match status {
|
||||
AccountStatus::Active => "active",
|
||||
AccountStatus::Expired => "expired",
|
||||
AccountStatus::QuotaExhausted => "quota_exhausted",
|
||||
AccountStatus::Refreshing => "refreshing",
|
||||
AccountStatus::Disabled => "disabled",
|
||||
AccountStatus::Banned => "banned",
|
||||
}
|
||||
}
|
||||
|
||||
fn status_from_db(value: &str) -> AccountRepositoryResult<AccountStatus> {
|
||||
match value {
|
||||
"active" => Ok(AccountStatus::Active),
|
||||
"expired" => Ok(AccountStatus::Expired),
|
||||
"quota_exhausted" => Ok(AccountStatus::QuotaExhausted),
|
||||
"refreshing" => Ok(AccountStatus::Refreshing),
|
||||
"disabled" => Ok(AccountStatus::Disabled),
|
||||
"banned" => Ok(AccountStatus::Banned),
|
||||
other => Err(AccountRepositoryError::InvalidStatus(other.to_string())),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_optional_rfc3339(value: Option<String>) -> AccountRepositoryResult<Option<DateTime<Utc>>> {
|
||||
value.as_deref().map(parse_rfc3339).transpose()
|
||||
}
|
||||
|
||||
fn parse_rfc3339(value: &str) -> AccountRepositoryResult<DateTime<Utc>> {
|
||||
Ok(DateTime::parse_from_rfc3339(value)?.with_timezone(&Utc))
|
||||
}
|
||||
|
||||
fn usage_from_row(row: &sqlx::sqlite::SqliteRow) -> AccountRepositoryResult<AccountUsageRecord> {
|
||||
Ok(AccountUsageRecord {
|
||||
account_id: row.get("account_id"),
|
||||
request_count: row.get("request_count"),
|
||||
input_tokens: row.get("input_tokens"),
|
||||
output_tokens: row.get("output_tokens"),
|
||||
cached_tokens: row.get("cached_tokens"),
|
||||
last_used_at: parse_optional_rfc3339(row.get::<Option<String>, _>("last_used_at"))?,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AccountUsageRepository {
|
||||
pool: SqlitePool,
|
||||
}
|
||||
|
||||
impl AccountUsageRepository {
|
||||
pub fn new(pool: SqlitePool) -> Self {
|
||||
Self { pool }
|
||||
}
|
||||
|
||||
pub async fn list(
|
||||
&self,
|
||||
cursor: Option<String>,
|
||||
limit: u32,
|
||||
) -> AccountRepositoryResult<Page<AccountUsageListRecord>> {
|
||||
let fetch_limit = i64::from(limit) + 1;
|
||||
let rows = if let Some(cursor) = cursor {
|
||||
let (last_used_at, account_id) =
|
||||
decode_cursor(&cursor).ok_or(AccountRepositoryError::InvalidCursor)?;
|
||||
sqlx::query(
|
||||
"select account_usage.account_id, accounts.email, accounts.label, accounts.plan_type, account_usage.request_count, account_usage.input_tokens, account_usage.output_tokens, account_usage.cached_tokens, account_usage.last_used_at from account_usage left join accounts on accounts.id = account_usage.account_id where coalesce(account_usage.last_used_at, '') < ? or (coalesce(account_usage.last_used_at, '') = ? and account_usage.account_id < ?) order by coalesce(account_usage.last_used_at, '') desc, account_usage.account_id desc limit ?",
|
||||
)
|
||||
.bind(&last_used_at)
|
||||
.bind(last_used_at)
|
||||
.bind(account_id)
|
||||
.bind(fetch_limit)
|
||||
.fetch_all(&self.pool)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query(
|
||||
"select account_usage.account_id, accounts.email, accounts.label, accounts.plan_type, account_usage.request_count, account_usage.input_tokens, account_usage.output_tokens, account_usage.cached_tokens, account_usage.last_used_at from account_usage left join accounts on accounts.id = account_usage.account_id order by coalesce(account_usage.last_used_at, '') desc, account_usage.account_id desc limit ?",
|
||||
)
|
||||
.bind(fetch_limit)
|
||||
.fetch_all(&self.pool)
|
||||
.await?
|
||||
};
|
||||
|
||||
let has_next = rows.len() > limit as usize;
|
||||
let take_count = rows.len().min(limit as usize);
|
||||
let mut items = Vec::with_capacity(take_count);
|
||||
for row in rows.into_iter().take(take_count) {
|
||||
items.push(usage_list_from_row(&row)?);
|
||||
}
|
||||
let next_cursor = if has_next {
|
||||
items.last().map(|usage| {
|
||||
encode_cursor(
|
||||
&usage
|
||||
.last_used_at
|
||||
.map(|value| value.to_rfc3339())
|
||||
.unwrap_or_default(),
|
||||
&usage.account_id,
|
||||
)
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Ok(Page { items, next_cursor })
|
||||
}
|
||||
|
||||
pub async fn summary(&self) -> AccountRepositoryResult<AccountUsageSummary> {
|
||||
let row = sqlx::query(
|
||||
"select count(*) as account_count, coalesce(sum(request_count), 0) as request_count, coalesce(sum(input_tokens), 0) as input_tokens, coalesce(sum(output_tokens), 0) as output_tokens, coalesce(sum(cached_tokens), 0) as cached_tokens from account_usage",
|
||||
)
|
||||
.fetch_one(&self.pool)
|
||||
.await?;
|
||||
Ok(AccountUsageSummary {
|
||||
account_count: row.get("account_count"),
|
||||
request_count: row.get("request_count"),
|
||||
input_tokens: row.get("input_tokens"),
|
||||
output_tokens: row.get("output_tokens"),
|
||||
cached_tokens: row.get("cached_tokens"),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn reset_account(&self, account_id: &str) -> AccountRepositoryResult<()> {
|
||||
sqlx::query(
|
||||
"insert into account_usage (account_id, request_count, input_tokens, output_tokens, cached_tokens, last_used_at) values (?, 0, 0, 0, 0, null) on conflict(account_id) do update set request_count = 0, input_tokens = 0, output_tokens = 0, cached_tokens = 0, last_used_at = null",
|
||||
)
|
||||
.bind(account_id)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn usage_list_from_row(
|
||||
row: &sqlx::sqlite::SqliteRow,
|
||||
) -> AccountRepositoryResult<AccountUsageListRecord> {
|
||||
Ok(AccountUsageListRecord {
|
||||
account_id: row.get("account_id"),
|
||||
email: row.get("email"),
|
||||
label: row.get("label"),
|
||||
plan_type: row.get("plan_type"),
|
||||
request_count: row.get("request_count"),
|
||||
input_tokens: row.get("input_tokens"),
|
||||
output_tokens: row.get("output_tokens"),
|
||||
cached_tokens: row.get("cached_tokens"),
|
||||
last_used_at: parse_optional_rfc3339(row.get::<Option<String>, _>("last_used_at"))?,
|
||||
})
|
||||
}
|
||||
|
||||
fn metadata_from_row(
|
||||
row: &sqlx::sqlite::SqliteRow,
|
||||
) -> AccountRepositoryResult<StoredAccountMetadata> {
|
||||
Ok(StoredAccountMetadata {
|
||||
id: row.get("id"),
|
||||
email: row.get("email"),
|
||||
account_id: row.get("account_id"),
|
||||
user_id: row.get("user_id"),
|
||||
label: row.get("label"),
|
||||
plan_type: row.get("plan_type"),
|
||||
access_token_expires_at: parse_optional_rfc3339(
|
||||
row.get::<Option<String>, _>("access_token_expires_at"),
|
||||
)?,
|
||||
status: status_from_db(&row.get::<String, _>("status"))?,
|
||||
added_at: parse_rfc3339(&row.get::<String, _>("added_at"))?,
|
||||
updated_at: parse_rfc3339(&row.get::<String, _>("updated_at"))?,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
use reqwest::Url;
|
||||
|
||||
use super::{AccountService, AccountServiceError};
|
||||
|
||||
impl AccountService {
|
||||
pub async fn get_cookies(
|
||||
&self,
|
||||
account_id: &str,
|
||||
) -> Result<Option<String>, AccountServiceError> {
|
||||
self.ensure_account_exists(account_id).await?;
|
||||
self.cookie_repository()?
|
||||
.cookie_header(account_id, "chatgpt.com")
|
||||
.await
|
||||
.map_err(|_| AccountServiceError::LoadCookies)
|
||||
}
|
||||
|
||||
pub async fn set_cookies(
|
||||
&self,
|
||||
account_id: &str,
|
||||
cookie_header: &str,
|
||||
) -> Result<Option<String>, AccountServiceError> {
|
||||
self.ensure_account_exists(account_id).await?;
|
||||
let cookie_repo = self.cookie_repository()?;
|
||||
match cookie_repo
|
||||
.set_cookie_header(account_id, cookie_header)
|
||||
.await
|
||||
{
|
||||
Ok(0) => Err(AccountServiceError::NoValidCookies),
|
||||
Ok(_) => cookie_repo
|
||||
.cookie_header(account_id, "chatgpt.com")
|
||||
.await
|
||||
.map_err(|_| AccountServiceError::LoadCookies),
|
||||
Err(_) => Err(AccountServiceError::StoreCookies),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn delete_cookies(&self, account_id: &str) -> Result<(), AccountServiceError> {
|
||||
self.ensure_account_exists(account_id).await?;
|
||||
self.cookie_repository()?
|
||||
.delete_account_cookies(account_id)
|
||||
.await
|
||||
.map(|_| ())
|
||||
.map_err(|_| AccountServiceError::DeleteCookies)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn request_domain(base_url: &str) -> Option<String> {
|
||||
Url::parse(base_url)
|
||||
.ok()
|
||||
.and_then(|url| url.host_str().map(ToString::to_string))
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
use std::time::Duration as StdDuration;
|
||||
|
||||
use chrono::Utc;
|
||||
use futures::{stream, StreamExt};
|
||||
use reqwest::StatusCode;
|
||||
use secrecy::ExposeSecret;
|
||||
use serde_json::Value;
|
||||
use tokio::time::sleep;
|
||||
|
||||
use crate::{
|
||||
codex::accounts::{
|
||||
model::AccountStatus,
|
||||
repository::{AccountRepository, StoredAccount},
|
||||
},
|
||||
codex::fingerprint::model::Fingerprint,
|
||||
codex::transport::client::{
|
||||
build_reqwest_client, CodexBackendClient, CodexClientError, CodexRequestContext,
|
||||
},
|
||||
};
|
||||
|
||||
use super::{
|
||||
cookies::request_domain, quota::quota_from_usage, AccountProbeOutcome, AccountProbeResult,
|
||||
AccountService, HealthCheckError,
|
||||
};
|
||||
|
||||
impl AccountService {
|
||||
pub async fn health_check_accounts(
|
||||
&self,
|
||||
ids: Option<Vec<String>>,
|
||||
concurrency: usize,
|
||||
stagger_ms: u64,
|
||||
request_id: &str,
|
||||
) -> Result<Vec<AccountProbeResult>, HealthCheckError> {
|
||||
let repo = self
|
||||
.repository
|
||||
.as_ref()
|
||||
.ok_or(HealthCheckError::RepositoryUnavailable)?;
|
||||
let accounts = repo
|
||||
.list_all()
|
||||
.await
|
||||
.map(|accounts| filter_health_check_accounts(accounts, ids.as_deref()))
|
||||
.map_err(|_| HealthCheckError::List)?;
|
||||
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);
|
||||
sleep(StdDuration::from_millis(
|
||||
stagger_ms.saturating_mul(multiplier as u64),
|
||||
))
|
||||
.await;
|
||||
}
|
||||
service
|
||||
.probe_account_with_codex_backend(&repo, account, &request_id)
|
||||
.await
|
||||
}
|
||||
})
|
||||
.buffer_unordered(concurrency)
|
||||
.collect::<Vec<_>>()
|
||||
.await;
|
||||
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");
|
||||
}
|
||||
|
||||
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()),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn fetch_account_usage(
|
||||
service: &AccountService,
|
||||
account: &StoredAccount,
|
||||
request_id: &str,
|
||||
) -> Result<Value, CodexClientError> {
|
||||
let cookie_header = account_cookie_header(service, &account.id).await;
|
||||
let client = CodexBackendClient::new(
|
||||
build_reqwest_client(service.config.tls.force_http11)?,
|
||||
service.config.api.base_url.clone(),
|
||||
Fingerprint::default_codex_desktop(),
|
||||
);
|
||||
client
|
||||
.fetch_usage(CodexRequestContext {
|
||||
access_token: account.access_token.expose_secret(),
|
||||
account_id: account.account_id.as_deref(),
|
||||
request_id,
|
||||
turn_state: None,
|
||||
turn_metadata: None,
|
||||
beta_features: None,
|
||||
include_timing_metrics: None,
|
||||
version: None,
|
||||
codex_window_id: None,
|
||||
parent_thread_id: None,
|
||||
cookie_header: cookie_header.as_deref(),
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn account_cookie_header(service: &AccountService, account_id: &str) -> Option<String> {
|
||||
let domain = request_domain(&service.config.api.base_url)?;
|
||||
service
|
||||
.cookie_repository
|
||||
.as_ref()?
|
||||
.cookie_header(account_id, &domain)
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
|
||||
pub(super) async fn apply_codex_account_error(
|
||||
service: &AccountService,
|
||||
repo: &AccountRepository,
|
||||
account: &StoredAccount,
|
||||
error: &CodexClientError,
|
||||
) -> Option<AccountStatus> {
|
||||
match classify_codex_account_error(error) {
|
||||
Some(CodexAccountErrorAction::SetStatus(status)) => {
|
||||
let _ = repo.set_status(&account.id, status).await;
|
||||
service
|
||||
.account_pool
|
||||
.lock()
|
||||
.await
|
||||
.set_status(&account.id, status);
|
||||
Some(status)
|
||||
}
|
||||
Some(CodexAccountErrorAction::RateLimited {
|
||||
retry_after_seconds,
|
||||
}) => {
|
||||
let cooldown_until = Utc::now() + chrono::Duration::seconds(retry_after_seconds as i64);
|
||||
service
|
||||
.account_pool
|
||||
.lock()
|
||||
.await
|
||||
.mark_quota_limited_until(&account.id, cooldown_until);
|
||||
None
|
||||
}
|
||||
Some(CodexAccountErrorAction::CloudflareChallenge { cooldown_seconds }) => {
|
||||
let cooldown_until = Utc::now() + chrono::Duration::seconds(cooldown_seconds as i64);
|
||||
service
|
||||
.account_pool
|
||||
.lock()
|
||||
.await
|
||||
.set_cloudflare_cooldown_until(&account.id, cooldown_until);
|
||||
None
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn skipped_probe_result(account: &StoredAccount, error: &str) -> AccountProbeResult {
|
||||
AccountProbeResult {
|
||||
id: account.id.clone(),
|
||||
email: account.email.clone(),
|
||||
previous_status: account.status,
|
||||
outcome: AccountProbeOutcome::Skipped,
|
||||
status: Some(account.status),
|
||||
error: Some(error.to_string()),
|
||||
duration_ms: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn filter_health_check_accounts(
|
||||
accounts: Vec<StoredAccount>,
|
||||
ids: Option<&[String]>,
|
||||
) -> Vec<StoredAccount> {
|
||||
let Some(ids) = ids else {
|
||||
return accounts;
|
||||
};
|
||||
accounts
|
||||
.into_iter()
|
||||
.filter(|account| ids.iter().any(|id| id == &account.id))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum CodexAccountErrorAction {
|
||||
SetStatus(AccountStatus),
|
||||
RateLimited { retry_after_seconds: u64 },
|
||||
CloudflareChallenge { cooldown_seconds: u64 },
|
||||
}
|
||||
|
||||
pub(super) fn classify_codex_account_error(
|
||||
error: &CodexClientError,
|
||||
) -> Option<CodexAccountErrorAction> {
|
||||
const DEFAULT_RATE_LIMIT_BACKOFF_SECONDS: u64 = 60;
|
||||
const MAX_RATE_LIMIT_BACKOFF_SECONDS: u64 = 3_600;
|
||||
const CLOUDFLARE_CHALLENGE_COOLDOWN_SECONDS: u64 = 120;
|
||||
|
||||
let CodexClientError::Upstream {
|
||||
status,
|
||||
body,
|
||||
retry_after_seconds,
|
||||
} = error
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let lower = body.to_ascii_lowercase();
|
||||
if *status == StatusCode::UNAUTHORIZED
|
||||
|| lower.contains("invalid_grant")
|
||||
|| lower.contains("invalid_token")
|
||||
|| lower.contains("access_denied")
|
||||
|| lower.contains("refresh_token_expired")
|
||||
|| lower.contains("token_revoked")
|
||||
{
|
||||
return Some(CodexAccountErrorAction::SetStatus(AccountStatus::Expired));
|
||||
}
|
||||
if *status == StatusCode::PAYMENT_REQUIRED || lower.contains("quota") {
|
||||
return Some(CodexAccountErrorAction::SetStatus(
|
||||
AccountStatus::QuotaExhausted,
|
||||
));
|
||||
}
|
||||
if *status == StatusCode::TOO_MANY_REQUESTS {
|
||||
return Some(CodexAccountErrorAction::RateLimited {
|
||||
retry_after_seconds: retry_after_seconds
|
||||
.unwrap_or(DEFAULT_RATE_LIMIT_BACKOFF_SECONDS)
|
||||
.min(MAX_RATE_LIMIT_BACKOFF_SECONDS),
|
||||
});
|
||||
}
|
||||
if *status == StatusCode::FORBIDDEN {
|
||||
if is_cloudflare_challenge(body) {
|
||||
return Some(CodexAccountErrorAction::CloudflareChallenge {
|
||||
cooldown_seconds: CLOUDFLARE_CHALLENGE_COOLDOWN_SECONDS,
|
||||
});
|
||||
}
|
||||
return Some(CodexAccountErrorAction::SetStatus(AccountStatus::Banned));
|
||||
}
|
||||
if lower.contains("account has been deactivated")
|
||||
|| lower.contains("deactivated")
|
||||
|| lower.contains("banned")
|
||||
|| lower.contains("suspended")
|
||||
{
|
||||
return Some(CodexAccountErrorAction::SetStatus(AccountStatus::Banned));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub(super) fn public_codex_error(error: &CodexClientError) -> String {
|
||||
match error {
|
||||
CodexClientError::Upstream { status, .. } => {
|
||||
format!("upstream returned status {}", status.as_u16())
|
||||
}
|
||||
CodexClientError::Http(_) => "upstream transport failed".to_string(),
|
||||
CodexClientError::InvalidHeaderName(_) | CodexClientError::InvalidHeaderValue(_) => {
|
||||
"invalid upstream request headers".to_string()
|
||||
}
|
||||
CodexClientError::UnsupportedTransport(_)
|
||||
| CodexClientError::WebSocket(_)
|
||||
| CodexClientError::InvalidSse(_)
|
||||
| CodexClientError::ModelsUnavailable => "Codex backend request failed".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_cloudflare_challenge(body: &str) -> bool {
|
||||
let lower = body.to_ascii_lowercase();
|
||||
lower.contains("cf-mitigated")
|
||||
|| lower.contains("cf-chl-bypass")
|
||||
|| lower.contains("_cf_chl")
|
||||
|| lower.contains("cf_chl")
|
||||
|| lower.contains("attention required")
|
||||
|| lower.contains("just a moment")
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
|
||||
use chrono::{DateTime, Utc};
|
||||
use secrecy::SecretString;
|
||||
use serde_json::{Map, Value};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{
|
||||
codex::accounts::{
|
||||
model::{Account, AccountStatus},
|
||||
repository::{AccountClaimsUpdate, AccountRepository, NewAccount, StoredAccount},
|
||||
},
|
||||
codex::oauth::RefreshFailure,
|
||||
};
|
||||
|
||||
use super::{
|
||||
runtime_pool::pool_account_from_stored, AccountImportCounts, AccountImportEntry,
|
||||
AccountService, StoreImportAccountError, ValidatedAccountImportError,
|
||||
};
|
||||
|
||||
enum StoredImportAccount {
|
||||
Imported,
|
||||
Skipped,
|
||||
}
|
||||
|
||||
impl AccountService {
|
||||
pub async fn import_validated(
|
||||
&self,
|
||||
token: Option<String>,
|
||||
refresh_token: Option<String>,
|
||||
) -> Result<StoredAccount, ValidatedAccountImportError> {
|
||||
let repo = self
|
||||
.repository
|
||||
.as_ref()
|
||||
.ok_or(ValidatedAccountImportError::RepositoryUnavailable)?;
|
||||
let (access_token, refresh_token_update, new_account_refresh_token) = match (
|
||||
empty_to_none(token.map(normalize_bearer_token)),
|
||||
empty_to_none(refresh_token),
|
||||
) {
|
||||
(Some(token), refresh_token) => (token, refresh_token.clone(), refresh_token),
|
||||
(None, Some(refresh_token)) => {
|
||||
let Some(refresher) = self.token_refresher.as_ref() else {
|
||||
return Err(ValidatedAccountImportError::TokenRefresherUnavailable);
|
||||
};
|
||||
let tokens = match refresher.refresh(&refresh_token).await {
|
||||
Ok(tokens) => tokens,
|
||||
Err(RefreshFailure::Transport) => {
|
||||
return Err(ValidatedAccountImportError::RefreshTransport);
|
||||
}
|
||||
Err(_) => return Err(ValidatedAccountImportError::RefreshRejected),
|
||||
};
|
||||
let access_token = normalize_bearer_token(tokens.access_token);
|
||||
let rotated_refresh_token = empty_to_none(tokens.refresh_token);
|
||||
let new_account_refresh_token =
|
||||
rotated_refresh_token.clone().or(Some(refresh_token));
|
||||
(
|
||||
access_token,
|
||||
rotated_refresh_token,
|
||||
new_account_refresh_token,
|
||||
)
|
||||
}
|
||||
(None, None) => return Err(ValidatedAccountImportError::TokenRequired),
|
||||
};
|
||||
|
||||
let claims = manual_account_claims(&access_token, Utc::now())
|
||||
.map_err(ValidatedAccountImportError::InvalidToken)?;
|
||||
let existing = repo
|
||||
.find_by_chatgpt_identity(&claims.account_id, claims.user_id.as_deref())
|
||||
.await
|
||||
.map_err(|_| ValidatedAccountImportError::Inspect)?;
|
||||
|
||||
let account_id = if let Some(existing) = existing {
|
||||
let updated = repo
|
||||
.update_from_claims(
|
||||
&existing.id,
|
||||
AccountClaimsUpdate {
|
||||
email: claims.email.clone(),
|
||||
account_id: Some(claims.account_id.clone()),
|
||||
user_id: claims.user_id.clone(),
|
||||
plan_type: claims.plan_type.clone(),
|
||||
access_token: SecretString::new(access_token.into()),
|
||||
refresh_token: refresh_token_update
|
||||
.map(|token| SecretString::new(token.into())),
|
||||
access_token_expires_at: Some(claims.expires_at),
|
||||
status: AccountStatus::Active,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(|_| ValidatedAccountImportError::Update)?;
|
||||
if !updated {
|
||||
return Err(ValidatedAccountImportError::NotFound);
|
||||
}
|
||||
existing.id
|
||||
} else {
|
||||
let id = normalized_account_id(None);
|
||||
let account = NewAccount {
|
||||
id: id.clone(),
|
||||
email: claims.email.clone(),
|
||||
account_id: Some(claims.account_id.clone()),
|
||||
user_id: claims.user_id.clone(),
|
||||
label: None,
|
||||
plan_type: claims.plan_type.clone(),
|
||||
access_token: SecretString::new(access_token.into()),
|
||||
refresh_token: new_account_refresh_token
|
||||
.map(|token| SecretString::new(token.into())),
|
||||
access_token_expires_at: Some(claims.expires_at),
|
||||
status: AccountStatus::Active,
|
||||
};
|
||||
repo.insert(account)
|
||||
.await
|
||||
.map_err(|_| ValidatedAccountImportError::Insert)?;
|
||||
id
|
||||
};
|
||||
|
||||
let stored = repo
|
||||
.get(&account_id)
|
||||
.await
|
||||
.map_err(|_| ValidatedAccountImportError::Load)?
|
||||
.ok_or(ValidatedAccountImportError::NotFound)?;
|
||||
self.account_pool
|
||||
.lock()
|
||||
.await
|
||||
.insert(pool_account_from_stored(stored.clone()));
|
||||
Ok(stored)
|
||||
}
|
||||
|
||||
pub async fn import_entries(
|
||||
&self,
|
||||
entries: Vec<AccountImportEntry>,
|
||||
) -> Result<AccountImportCounts, StoreImportAccountError> {
|
||||
let repo = self
|
||||
.repository
|
||||
.as_ref()
|
||||
.ok_or(StoreImportAccountError::RepositoryUnavailable)?;
|
||||
let mut imported = 0u32;
|
||||
let mut skipped = 0u32;
|
||||
for entry in entries {
|
||||
match self.store_import_entry(repo, entry).await? {
|
||||
StoredImportAccount::Imported => imported += 1,
|
||||
StoredImportAccount::Skipped => skipped += 1,
|
||||
}
|
||||
}
|
||||
Ok(AccountImportCounts { imported, skipped })
|
||||
}
|
||||
|
||||
async fn store_import_entry(
|
||||
&self,
|
||||
repo: &AccountRepository,
|
||||
entry: AccountImportEntry,
|
||||
) -> Result<StoredImportAccount, StoreImportAccountError> {
|
||||
let access_token = entry.token.as_deref().unwrap_or_default().trim();
|
||||
if access_token.is_empty() {
|
||||
return Ok(StoredImportAccount::Skipped);
|
||||
}
|
||||
if entry
|
||||
.label
|
||||
.as_ref()
|
||||
.is_some_and(|label| label.chars().count() > 64)
|
||||
{
|
||||
return Err(StoreImportAccountError::Invalid(
|
||||
"Account label must be 64 characters or fewer".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let id = normalized_account_id(entry.id);
|
||||
match repo.exists(&id).await {
|
||||
Ok(true) => return Ok(StoredImportAccount::Skipped),
|
||||
Ok(false) => {}
|
||||
Err(_) => return Err(StoreImportAccountError::Inspect),
|
||||
}
|
||||
|
||||
let status = parse_import_status(entry.status.as_deref())
|
||||
.map_err(StoreImportAccountError::Invalid)?;
|
||||
let email = empty_to_none(entry.email);
|
||||
let account_id = empty_to_none(entry.account_id);
|
||||
let user_id = empty_to_none(entry.user_id);
|
||||
let label = empty_to_none(entry.label);
|
||||
let plan_type = empty_to_none(entry.plan_type);
|
||||
let refresh_token = empty_to_none(entry.refresh_token);
|
||||
let access_token = access_token.to_string();
|
||||
let now = Utc::now().to_rfc3339();
|
||||
let pool_account = Account {
|
||||
id: id.clone(),
|
||||
email: email.clone(),
|
||||
account_id: account_id.clone(),
|
||||
user_id: user_id.clone(),
|
||||
label: label.clone(),
|
||||
plan_type: plan_type.clone(),
|
||||
access_token: access_token.clone(),
|
||||
refresh_token: refresh_token.clone(),
|
||||
access_token_expires_at: None,
|
||||
status,
|
||||
quota_limit_reached: false,
|
||||
quota_cooldown_until: None,
|
||||
cloudflare_cooldown_until: None,
|
||||
added_at: now,
|
||||
last_used_at: None,
|
||||
};
|
||||
let account = NewAccount {
|
||||
id,
|
||||
email,
|
||||
account_id,
|
||||
user_id,
|
||||
label,
|
||||
plan_type,
|
||||
access_token: SecretString::new(access_token.into()),
|
||||
refresh_token: refresh_token.map(|token| SecretString::new(token.into())),
|
||||
access_token_expires_at: None,
|
||||
status,
|
||||
};
|
||||
repo.insert(account)
|
||||
.await
|
||||
.map_err(|_| StoreImportAccountError::Insert)?;
|
||||
self.account_pool.lock().await.insert(pool_account);
|
||||
|
||||
Ok(StoredImportAccount::Imported)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(super) struct ManualAccountClaims {
|
||||
pub account_id: String,
|
||||
pub user_id: Option<String>,
|
||||
pub email: Option<String>,
|
||||
pub plan_type: Option<String>,
|
||||
pub expires_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
pub(super) fn manual_account_claims(
|
||||
token: &str,
|
||||
now: DateTime<Utc>,
|
||||
) -> Result<ManualAccountClaims, &'static str> {
|
||||
let payload = decode_jwt_payload(token).ok_or("Invalid JWT format")?;
|
||||
let exp = payload
|
||||
.get("exp")
|
||||
.and_then(Value::as_i64)
|
||||
.ok_or("Token is expired")?;
|
||||
if now.timestamp() >= exp {
|
||||
return Err("Token is expired");
|
||||
}
|
||||
let expires_at = DateTime::<Utc>::from_timestamp(exp, 0).ok_or("Invalid JWT exp claim")?;
|
||||
let auth = payload
|
||||
.get("https://api.openai.com/auth")
|
||||
.and_then(Value::as_object)
|
||||
.ok_or("Token missing chatgpt_account_id claim")?;
|
||||
let account_id =
|
||||
string_claim(auth, "chatgpt_account_id").ok_or("Token missing chatgpt_account_id claim")?;
|
||||
let profile = payload
|
||||
.get("https://api.openai.com/profile")
|
||||
.and_then(Value::as_object);
|
||||
let user_id = string_claim(auth, "chatgpt_user_id")
|
||||
.or_else(|| profile.and_then(|profile| string_claim(profile, "chatgpt_user_id")));
|
||||
let plan_type = string_claim(auth, "chatgpt_plan_type")
|
||||
.or_else(|| profile.and_then(|profile| string_claim(profile, "chatgpt_plan_type")));
|
||||
let email = profile.and_then(|profile| string_claim(profile, "email"));
|
||||
|
||||
Ok(ManualAccountClaims {
|
||||
account_id,
|
||||
user_id,
|
||||
email,
|
||||
plan_type,
|
||||
expires_at,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn normalize_bearer_token(value: String) -> String {
|
||||
value
|
||||
.trim()
|
||||
.strip_prefix("Bearer ")
|
||||
.or_else(|| value.trim().strip_prefix("bearer "))
|
||||
.unwrap_or(value.trim())
|
||||
.trim()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
pub(super) fn empty_to_none(value: Option<String>) -> Option<String> {
|
||||
value
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
}
|
||||
|
||||
pub(super) fn normalized_account_id(id: Option<String>) -> String {
|
||||
id.and_then(|id| empty_to_none(Some(id)))
|
||||
.unwrap_or_else(|| format!("acct_{}", Uuid::new_v4().simple()))
|
||||
}
|
||||
|
||||
pub(super) fn parse_import_status(status: Option<&str>) -> Result<AccountStatus, String> {
|
||||
let normalized = status.unwrap_or("active").trim().to_ascii_lowercase();
|
||||
match normalized.as_str() {
|
||||
"active" => Ok(AccountStatus::Active),
|
||||
"expired" => Ok(AccountStatus::Expired),
|
||||
"quota_exhausted" => Ok(AccountStatus::QuotaExhausted),
|
||||
"refreshing" => Ok(AccountStatus::Refreshing),
|
||||
"disabled" => Ok(AccountStatus::Disabled),
|
||||
"banned" => Ok(AccountStatus::Banned),
|
||||
other => Err(format!("Unsupported account status: {other}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_jwt_payload(token: &str) -> Option<Map<String, Value>> {
|
||||
let mut parts = token.split('.');
|
||||
let _header = parts.next()?;
|
||||
let payload = parts.next()?;
|
||||
if payload.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let bytes = URL_SAFE_NO_PAD.decode(payload).ok()?;
|
||||
serde_json::from_slice::<Value>(&bytes)
|
||||
.ok()?
|
||||
.as_object()
|
||||
.cloned()
|
||||
}
|
||||
|
||||
fn string_claim(map: &Map<String, Value>, key: &str) -> Option<String> {
|
||||
map.get(key)
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(ToString::to_string)
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
pub mod cookies;
|
||||
pub mod health;
|
||||
pub mod import;
|
||||
pub mod mutation;
|
||||
pub mod quota;
|
||||
pub mod refresh;
|
||||
pub mod runtime_pool;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::Value;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::{
|
||||
codex::accounts::{
|
||||
model::AccountStatus,
|
||||
pool::AccountPool,
|
||||
repository::{
|
||||
AccountRepository, AccountUsageRepository, StoredAccount, StoredAccountMetadata,
|
||||
},
|
||||
},
|
||||
codex::cookies::repository::CookieRepository,
|
||||
codex::oauth::TokenRefresher,
|
||||
config::AppConfig,
|
||||
utils::pagination::Page,
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AccountService {
|
||||
config: AppConfig,
|
||||
repository: Option<AccountRepository>,
|
||||
usage_repository: Option<AccountUsageRepository>,
|
||||
cookie_repository: Option<CookieRepository>,
|
||||
token_refresher: Option<Arc<dyn TokenRefresher>>,
|
||||
account_pool: Arc<Mutex<AccountPool>>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum AccountServiceError {
|
||||
RepositoryUnavailable,
|
||||
UsageRepositoryUnavailable,
|
||||
CookieRepositoryUnavailable,
|
||||
AccountNotFound,
|
||||
List,
|
||||
Export,
|
||||
Inspect,
|
||||
ResetUsage,
|
||||
UpdateLabel,
|
||||
UpdateStatus,
|
||||
SyncStatus,
|
||||
Delete,
|
||||
LoadCookies,
|
||||
StoreCookies,
|
||||
DeleteCookies,
|
||||
NoValidCookies,
|
||||
EmptyIds,
|
||||
InvalidStatus(String),
|
||||
LabelTooLong,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct BatchDeleteAccounts {
|
||||
pub deleted: u32,
|
||||
pub not_found: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct BatchUpdateAccountStatus {
|
||||
pub updated: u32,
|
||||
pub not_found: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct UpdateAccountStatus {
|
||||
pub id: String,
|
||||
pub status: AccountStatus,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct AccountImportCounts {
|
||||
pub imported: u32,
|
||||
pub skipped: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AccountImportEntry {
|
||||
pub id: Option<String>,
|
||||
pub email: Option<String>,
|
||||
pub account_id: Option<String>,
|
||||
pub user_id: Option<String>,
|
||||
pub label: Option<String>,
|
||||
pub plan_type: Option<String>,
|
||||
pub token: Option<String>,
|
||||
pub refresh_token: Option<String>,
|
||||
pub status: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum AccountProbeOutcome {
|
||||
Alive,
|
||||
Dead,
|
||||
Skipped,
|
||||
}
|
||||
|
||||
impl AccountProbeOutcome {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Alive => "alive",
|
||||
Self::Dead => "dead",
|
||||
Self::Skipped => "skipped",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct AccountProbeResult {
|
||||
pub id: String,
|
||||
pub email: Option<String>,
|
||||
pub previous_status: AccountStatus,
|
||||
pub outcome: AccountProbeOutcome,
|
||||
pub status: Option<AccountStatus>,
|
||||
pub error: Option<String>,
|
||||
pub duration_ms: Option<u128>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct AccountQuotaResult {
|
||||
pub quota: Value,
|
||||
pub raw: Value,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum AccountQuotaError {
|
||||
RepositoryUnavailable,
|
||||
Load,
|
||||
NotFound,
|
||||
Inactive(AccountStatus),
|
||||
StoreQuota,
|
||||
Fetch(String),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum HealthCheckError {
|
||||
RepositoryUnavailable,
|
||||
List,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum RefreshAccountError {
|
||||
RepositoryUnavailable,
|
||||
Load,
|
||||
NotFound,
|
||||
TokenRefresherUnavailable,
|
||||
StoreRefreshed,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum StoreImportAccountError {
|
||||
RepositoryUnavailable,
|
||||
Inspect,
|
||||
Invalid(String),
|
||||
Insert,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ValidatedAccountImportError {
|
||||
RepositoryUnavailable,
|
||||
TokenRequired,
|
||||
TokenRefresherUnavailable,
|
||||
RefreshTransport,
|
||||
RefreshRejected,
|
||||
InvalidToken(&'static str),
|
||||
Inspect,
|
||||
NotFound,
|
||||
Update,
|
||||
Insert,
|
||||
Load,
|
||||
}
|
||||
|
||||
impl AccountService {
|
||||
pub fn new(
|
||||
config: AppConfig,
|
||||
repository: Option<AccountRepository>,
|
||||
usage_repository: Option<AccountUsageRepository>,
|
||||
cookie_repository: Option<CookieRepository>,
|
||||
token_refresher: Option<Arc<dyn TokenRefresher>>,
|
||||
account_pool: Arc<Mutex<AccountPool>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
config,
|
||||
repository,
|
||||
usage_repository,
|
||||
cookie_repository,
|
||||
token_refresher,
|
||||
account_pool,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn has_repository(&self) -> bool {
|
||||
self.repository.is_some()
|
||||
}
|
||||
|
||||
pub async fn list(
|
||||
&self,
|
||||
cursor: Option<String>,
|
||||
limit: u32,
|
||||
) -> Result<Page<StoredAccountMetadata>, AccountServiceError> {
|
||||
self.repository()?
|
||||
.list_metadata(cursor, limit)
|
||||
.await
|
||||
.map_err(|_| AccountServiceError::List)
|
||||
}
|
||||
|
||||
pub async fn export(
|
||||
&self,
|
||||
ids: Vec<String>,
|
||||
) -> Result<Vec<StoredAccount>, AccountServiceError> {
|
||||
let repo = self.repository()?;
|
||||
if ids.is_empty() {
|
||||
return repo
|
||||
.list_all()
|
||||
.await
|
||||
.map_err(|_| AccountServiceError::Export);
|
||||
}
|
||||
|
||||
let mut accounts = Vec::with_capacity(ids.len());
|
||||
for id in ids {
|
||||
match repo.get(&id).await {
|
||||
Ok(Some(account)) => accounts.push(account),
|
||||
Ok(None) => {}
|
||||
Err(_) => return Err(AccountServiceError::Export),
|
||||
}
|
||||
}
|
||||
Ok(accounts)
|
||||
}
|
||||
|
||||
fn repository(&self) -> Result<&AccountRepository, AccountServiceError> {
|
||||
self.repository
|
||||
.as_ref()
|
||||
.ok_or(AccountServiceError::RepositoryUnavailable)
|
||||
}
|
||||
|
||||
fn usage_repository(&self) -> Result<&AccountUsageRepository, AccountServiceError> {
|
||||
self.usage_repository
|
||||
.as_ref()
|
||||
.ok_or(AccountServiceError::UsageRepositoryUnavailable)
|
||||
}
|
||||
|
||||
fn cookie_repository(&self) -> Result<&CookieRepository, AccountServiceError> {
|
||||
self.cookie_repository
|
||||
.as_ref()
|
||||
.ok_or(AccountServiceError::CookieRepositoryUnavailable)
|
||||
}
|
||||
|
||||
async fn ensure_account_exists(&self, account_id: &str) -> Result<(), AccountServiceError> {
|
||||
match self.repository()?.exists(account_id).await {
|
||||
Ok(true) => Ok(()),
|
||||
Ok(false) => Err(AccountServiceError::AccountNotFound),
|
||||
Err(_) => Err(AccountServiceError::Inspect),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
use crate::codex::accounts::{model::AccountStatus, repository::AccountRepository};
|
||||
|
||||
use super::{
|
||||
runtime_pool::pool_account_from_stored, AccountService, AccountServiceError,
|
||||
BatchDeleteAccounts, BatchUpdateAccountStatus, UpdateAccountStatus,
|
||||
};
|
||||
|
||||
impl AccountService {
|
||||
pub async fn reset_usage(&self, account_id: &str) -> Result<bool, AccountServiceError> {
|
||||
match self.repository()?.exists(account_id).await {
|
||||
Ok(true) => {}
|
||||
Ok(false) => return Ok(false),
|
||||
Err(_) => return Err(AccountServiceError::Inspect),
|
||||
}
|
||||
self.usage_repository()?
|
||||
.reset_account(account_id)
|
||||
.await
|
||||
.map_err(|_| AccountServiceError::ResetUsage)?;
|
||||
self.account_pool.lock().await.reset_usage(account_id);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub async fn update_label(
|
||||
&self,
|
||||
account_id: &str,
|
||||
label: Option<String>,
|
||||
) -> Result<bool, AccountServiceError> {
|
||||
if label
|
||||
.as_ref()
|
||||
.is_some_and(|label| label.chars().count() > 64)
|
||||
{
|
||||
return Err(AccountServiceError::LabelTooLong);
|
||||
}
|
||||
match self
|
||||
.repository()?
|
||||
.set_label(account_id, label.clone())
|
||||
.await
|
||||
{
|
||||
Ok(true) => {
|
||||
self.account_pool.lock().await.set_label(account_id, label);
|
||||
Ok(true)
|
||||
}
|
||||
Ok(false) => Ok(false),
|
||||
Err(_) => Err(AccountServiceError::UpdateLabel),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn update_status(
|
||||
&self,
|
||||
account_id: &str,
|
||||
status: &str,
|
||||
) -> Result<Option<UpdateAccountStatus>, AccountServiceError> {
|
||||
let status = parse_admin_account_status(status)?;
|
||||
let repo = self.repository()?;
|
||||
match repo.set_status(account_id, status).await {
|
||||
Ok(true) => {
|
||||
self.sync_runtime_account_status(repo, account_id, status)
|
||||
.await?;
|
||||
Ok(Some(UpdateAccountStatus {
|
||||
id: account_id.to_string(),
|
||||
status,
|
||||
}))
|
||||
}
|
||||
Ok(false) => Ok(None),
|
||||
Err(_) => Err(AccountServiceError::UpdateStatus),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn delete(&self, account_id: &str) -> Result<bool, AccountServiceError> {
|
||||
match self.repository()?.delete(account_id).await {
|
||||
Ok(true) => {
|
||||
self.account_pool.lock().await.remove(account_id);
|
||||
Ok(true)
|
||||
}
|
||||
Ok(false) => Ok(false),
|
||||
Err(_) => Err(AccountServiceError::Delete),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn batch_delete(
|
||||
&self,
|
||||
ids: Vec<String>,
|
||||
) -> Result<BatchDeleteAccounts, AccountServiceError> {
|
||||
if ids.is_empty() {
|
||||
return Err(AccountServiceError::EmptyIds);
|
||||
}
|
||||
let repo = self.repository()?;
|
||||
let mut deleted = 0u32;
|
||||
let mut not_found = Vec::new();
|
||||
for account_id in ids {
|
||||
match repo.delete(&account_id).await {
|
||||
Ok(true) => {
|
||||
self.account_pool.lock().await.remove(&account_id);
|
||||
deleted += 1;
|
||||
}
|
||||
Ok(false) => not_found.push(account_id),
|
||||
Err(_) => return Err(AccountServiceError::Delete),
|
||||
}
|
||||
}
|
||||
Ok(BatchDeleteAccounts { deleted, not_found })
|
||||
}
|
||||
|
||||
pub async fn batch_update_status(
|
||||
&self,
|
||||
ids: Vec<String>,
|
||||
status: &str,
|
||||
) -> Result<BatchUpdateAccountStatus, AccountServiceError> {
|
||||
if ids.is_empty() {
|
||||
return Err(AccountServiceError::EmptyIds);
|
||||
}
|
||||
let status = parse_admin_account_status(status)?;
|
||||
let repo = self.repository()?;
|
||||
let mut updated = 0u32;
|
||||
let mut not_found = Vec::new();
|
||||
for account_id in ids {
|
||||
match repo.set_status(&account_id, status).await {
|
||||
Ok(true) => {
|
||||
self.sync_runtime_account_status(repo, &account_id, status)
|
||||
.await?;
|
||||
updated += 1;
|
||||
}
|
||||
Ok(false) => not_found.push(account_id),
|
||||
Err(_) => return Err(AccountServiceError::UpdateStatus),
|
||||
}
|
||||
}
|
||||
Ok(BatchUpdateAccountStatus { updated, not_found })
|
||||
}
|
||||
|
||||
async fn sync_runtime_account_status(
|
||||
&self,
|
||||
repo: &AccountRepository,
|
||||
account_id: &str,
|
||||
status: AccountStatus,
|
||||
) -> Result<(), AccountServiceError> {
|
||||
if status == AccountStatus::Active {
|
||||
match repo.get(account_id).await {
|
||||
Ok(Some(account)) => {
|
||||
self.account_pool
|
||||
.lock()
|
||||
.await
|
||||
.insert(pool_account_from_stored(account));
|
||||
}
|
||||
Ok(None) => {
|
||||
self.account_pool.lock().await.remove(account_id);
|
||||
}
|
||||
Err(_) => return Err(AccountServiceError::SyncStatus),
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
self.account_pool.lock().await.remove(account_id);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn parse_admin_account_status(
|
||||
status: &str,
|
||||
) -> Result<AccountStatus, AccountServiceError> {
|
||||
match status.trim().to_ascii_lowercase().as_str() {
|
||||
"active" => Ok(AccountStatus::Active),
|
||||
"expired" => Ok(AccountStatus::Expired),
|
||||
"quota_exhausted" | "quota-exhausted" => Ok(AccountStatus::QuotaExhausted),
|
||||
"refreshing" => Ok(AccountStatus::Refreshing),
|
||||
"disabled" => Ok(AccountStatus::Disabled),
|
||||
"banned" => Ok(AccountStatus::Banned),
|
||||
other => Err(AccountServiceError::InvalidStatus(format!(
|
||||
"Unsupported account status: {other}"
|
||||
))),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
use crate::codex::accounts::model::AccountStatus;
|
||||
|
||||
use super::{
|
||||
health::{apply_codex_account_error, fetch_account_usage, public_codex_error},
|
||||
AccountQuotaError, AccountQuotaResult, AccountService,
|
||||
};
|
||||
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
impl AccountService {
|
||||
pub async fn account_quota(
|
||||
&self,
|
||||
account_id: &str,
|
||||
request_id: &str,
|
||||
) -> Result<AccountQuotaResult, AccountQuotaError> {
|
||||
let repo = self
|
||||
.repository
|
||||
.as_ref()
|
||||
.ok_or(AccountQuotaError::RepositoryUnavailable)?;
|
||||
let account = match repo.get(account_id).await {
|
||||
Ok(Some(account)) => account,
|
||||
Ok(None) => return Err(AccountQuotaError::NotFound),
|
||||
Err(_) => return Err(AccountQuotaError::Load),
|
||||
};
|
||||
if account.status != AccountStatus::Active {
|
||||
return Err(AccountQuotaError::Inactive(account.status));
|
||||
}
|
||||
|
||||
match fetch_account_usage(self, &account, request_id).await {
|
||||
Ok(raw) => {
|
||||
let quota = quota_from_usage(&raw);
|
||||
if repo
|
||||
.update_quota_json(&account.id, "a.to_string())
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return Err(AccountQuotaError::StoreQuota);
|
||||
}
|
||||
Ok(AccountQuotaResult { quota, raw })
|
||||
}
|
||||
Err(error) => {
|
||||
apply_codex_account_error(self, repo, &account, &error).await;
|
||||
Err(AccountQuotaError::Fetch(public_codex_error(&error)))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn quota_from_usage(usage: &Value) -> Value {
|
||||
let additional = usage
|
||||
.get("additional_rate_limits")
|
||||
.and_then(Value::as_array)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let mut rate_limits_by_limit_id = Map::new();
|
||||
for item in &additional {
|
||||
let Some(limit_id) = item
|
||||
.get("metered_feature")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let quota = quota_from_rate_limit(item.get("rate_limit"));
|
||||
if quota.is_null() {
|
||||
continue;
|
||||
}
|
||||
rate_limits_by_limit_id.insert(
|
||||
limit_id.to_string(),
|
||||
json!({
|
||||
"limit_id": limit_id,
|
||||
"limit_name": item.get("limit_name").cloned().unwrap_or(Value::Null),
|
||||
"allowed": quota.get("allowed").cloned().unwrap_or(Value::Null),
|
||||
"limit_reached": quota.get("limit_reached").cloned().unwrap_or(Value::Null),
|
||||
"used_percent": quota.get("used_percent").cloned().unwrap_or(Value::Null),
|
||||
"remaining_percent": quota.get("remaining_percent").cloned().unwrap_or(Value::Null),
|
||||
"reset_at": quota.get("reset_at").cloned().unwrap_or(Value::Null),
|
||||
"limit_window_seconds": quota.get("limit_window_seconds").cloned().unwrap_or(Value::Null),
|
||||
"secondary_rate_limit": secondary_quota_from_rate_limit(item.get("rate_limit")),
|
||||
}),
|
||||
);
|
||||
}
|
||||
let additional_review = additional.iter().find(|item| {
|
||||
is_review_limit_id(item.get("metered_feature").and_then(Value::as_str))
|
||||
|| is_review_limit_id(item.get("limit_name").and_then(Value::as_str))
|
||||
});
|
||||
let code_review_rate_limit = match quota_from_rate_limit(usage.get("code_review_rate_limit")) {
|
||||
Value::Null => {
|
||||
quota_from_rate_limit(additional_review.and_then(|item| item.get("rate_limit")))
|
||||
}
|
||||
quota => quota,
|
||||
};
|
||||
|
||||
json!({
|
||||
"plan_type": usage.get("plan_type").cloned().unwrap_or(Value::Null),
|
||||
"rate_limit": quota_from_rate_limit(usage.get("rate_limit")),
|
||||
"secondary_rate_limit": secondary_quota_from_rate_limit(usage.get("rate_limit")),
|
||||
"code_review_rate_limit": code_review_rate_limit,
|
||||
"rate_limits_by_limit_id": if rate_limits_by_limit_id.is_empty() {
|
||||
Value::Null
|
||||
} else {
|
||||
Value::Object(rate_limits_by_limit_id)
|
||||
},
|
||||
"credits": normalize_quota_credits(usage.get("credits")),
|
||||
})
|
||||
}
|
||||
|
||||
fn quota_from_rate_limit(rate_limit: Option<&Value>) -> Value {
|
||||
let Some(rate_limit) = rate_limit.filter(|value| !value.is_null()) else {
|
||||
return Value::Null;
|
||||
};
|
||||
let primary = rate_limit.get("primary_window");
|
||||
let used_percent = primary
|
||||
.and_then(|window| window.get("used_percent"))
|
||||
.cloned()
|
||||
.unwrap_or(Value::Null);
|
||||
json!({
|
||||
"allowed": rate_limit.get("allowed").cloned().unwrap_or(Value::Null),
|
||||
"limit_reached": rate_limit.get("limit_reached").cloned().unwrap_or(Value::Null),
|
||||
"used_percent": used_percent,
|
||||
"remaining_percent": remaining_percent(primary.and_then(|window| window.get("used_percent"))),
|
||||
"reset_at": primary.and_then(|window| window.get("reset_at")).cloned().unwrap_or(Value::Null),
|
||||
"limit_window_seconds": primary.and_then(|window| window.get("limit_window_seconds")).cloned().unwrap_or(Value::Null),
|
||||
})
|
||||
}
|
||||
|
||||
fn secondary_quota_from_rate_limit(rate_limit: Option<&Value>) -> Value {
|
||||
let Some(secondary) = rate_limit
|
||||
.and_then(|rate_limit| rate_limit.get("secondary_window"))
|
||||
.filter(|value| !value.is_null())
|
||||
else {
|
||||
return Value::Null;
|
||||
};
|
||||
let used_percent = secondary
|
||||
.get("used_percent")
|
||||
.cloned()
|
||||
.unwrap_or(Value::Null);
|
||||
let limit_reached = secondary
|
||||
.get("used_percent")
|
||||
.and_then(Value::as_f64)
|
||||
.map(|used| used >= 100.0)
|
||||
.map(Value::Bool)
|
||||
.or_else(|| {
|
||||
rate_limit
|
||||
.and_then(|rate_limit| rate_limit.get("limit_reached"))
|
||||
.cloned()
|
||||
})
|
||||
.unwrap_or(Value::Null);
|
||||
json!({
|
||||
"limit_reached": limit_reached,
|
||||
"used_percent": used_percent,
|
||||
"remaining_percent": remaining_percent(secondary.get("used_percent")),
|
||||
"reset_at": secondary.get("reset_at").cloned().unwrap_or(Value::Null),
|
||||
"limit_window_seconds": secondary.get("limit_window_seconds").cloned().unwrap_or(Value::Null),
|
||||
})
|
||||
}
|
||||
|
||||
fn normalize_quota_credits(raw: Option<&Value>) -> Value {
|
||||
let Some(raw) = raw.filter(|value| !value.is_null()) else {
|
||||
return Value::Null;
|
||||
};
|
||||
let Some(balance) = raw
|
||||
.get("balance")
|
||||
.and_then(Value::as_str)
|
||||
.and_then(|value| value.parse::<f64>().ok())
|
||||
.filter(|value| value.is_finite())
|
||||
else {
|
||||
return Value::Null;
|
||||
};
|
||||
json!({
|
||||
"has_credits": raw.get("has_credits").and_then(Value::as_bool).unwrap_or(false),
|
||||
"unlimited": raw.get("unlimited").and_then(Value::as_bool).unwrap_or(false),
|
||||
"overage_limit_reached": raw.get("overage_limit_reached").and_then(Value::as_bool).unwrap_or(false),
|
||||
"balance": balance,
|
||||
})
|
||||
}
|
||||
|
||||
fn remaining_percent(used_percent: Option<&Value>) -> Value {
|
||||
let Some(used_percent) = used_percent.and_then(Value::as_f64) else {
|
||||
return Value::Null;
|
||||
};
|
||||
json!((100.0 - used_percent.clamp(0.0, 100.0)).round() as i64)
|
||||
}
|
||||
|
||||
fn is_review_limit_id(value: Option<&str>) -> bool {
|
||||
let normalized = value
|
||||
.unwrap_or_default()
|
||||
.trim()
|
||||
.to_ascii_lowercase()
|
||||
.replace(['-', ' '], "_");
|
||||
normalized == "review"
|
||||
|| normalized == "code_review"
|
||||
|| normalized == "codex_review"
|
||||
|| normalized == "codex_code_review"
|
||||
|| normalized.contains("code_review")
|
||||
|| normalized.contains("codex_review")
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
use secrecy::{ExposeSecret, SecretString};
|
||||
|
||||
use crate::{
|
||||
codex::accounts::{
|
||||
model::{Account, AccountStatus},
|
||||
repository::{AccountRepository, StoredAccount, TokenUpdate},
|
||||
},
|
||||
codex::oauth::RefreshFailure,
|
||||
};
|
||||
|
||||
use super::{
|
||||
health::skipped_probe_result, runtime_pool::pool_account_from_stored, AccountProbeOutcome,
|
||||
AccountProbeResult, AccountService, RefreshAccountError,
|
||||
};
|
||||
|
||||
impl AccountService {
|
||||
pub async fn refresh_account(
|
||||
&self,
|
||||
account_id: &str,
|
||||
) -> Result<AccountProbeResult, RefreshAccountError> {
|
||||
let repo = self
|
||||
.repository
|
||||
.as_ref()
|
||||
.ok_or(RefreshAccountError::RepositoryUnavailable)?;
|
||||
let account = match repo.get(account_id).await {
|
||||
Ok(Some(account)) => account,
|
||||
Ok(None) => return Err(RefreshAccountError::NotFound),
|
||||
Err(_) => return Err(RefreshAccountError::Load),
|
||||
};
|
||||
if account.status == AccountStatus::Disabled {
|
||||
return Ok(skipped_probe_result(&account, "manually disabled"));
|
||||
}
|
||||
let Some(refresh_token) = account.refresh_token.as_ref() else {
|
||||
return Ok(skipped_probe_result(&account, "no refresh token"));
|
||||
};
|
||||
let Some(refresher) = self.token_refresher.as_ref() else {
|
||||
return Err(RefreshAccountError::TokenRefresherUnavailable);
|
||||
};
|
||||
|
||||
let started_at = std::time::Instant::now();
|
||||
let previous_status = account.status;
|
||||
match refresher.refresh(refresh_token.expose_secret()).await {
|
||||
Ok(tokens) => {
|
||||
let updated = self
|
||||
.persist_refreshed_account(
|
||||
repo,
|
||||
&account.id,
|
||||
tokens.access_token,
|
||||
tokens.refresh_token,
|
||||
)
|
||||
.await
|
||||
.map_err(|()| RefreshAccountError::StoreRefreshed)?;
|
||||
Ok(AccountProbeResult {
|
||||
id: updated.id,
|
||||
email: updated.email,
|
||||
previous_status,
|
||||
outcome: AccountProbeOutcome::Alive,
|
||||
status: Some(updated.status),
|
||||
error: None,
|
||||
duration_ms: Some(started_at.elapsed().as_millis()),
|
||||
})
|
||||
}
|
||||
Err(failure) => {
|
||||
let status = self
|
||||
.apply_refresh_failure_status(repo, &account, failure)
|
||||
.await;
|
||||
Ok(AccountProbeResult {
|
||||
id: account.id,
|
||||
email: account.email,
|
||||
previous_status,
|
||||
outcome: AccountProbeOutcome::Dead,
|
||||
status,
|
||||
error: Some(public_refresh_failure(failure).to_string()),
|
||||
duration_ms: Some(started_at.elapsed().as_millis()),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn persist_refreshed_account(
|
||||
&self,
|
||||
repo: &AccountRepository,
|
||||
account_id: &str,
|
||||
access_token: String,
|
||||
refresh_token: Option<String>,
|
||||
) -> Result<Account, ()> {
|
||||
repo.update_tokens(
|
||||
account_id,
|
||||
TokenUpdate {
|
||||
access_token: SecretString::new(access_token.into()),
|
||||
refresh_token: refresh_token.map(|token| SecretString::new(token.into())),
|
||||
access_token_expires_at: None,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(|_| ())?;
|
||||
let account = repo.get(account_id).await.map_err(|_| ())?.ok_or(())?;
|
||||
let account = pool_account_from_stored(account);
|
||||
self.account_pool.lock().await.insert(account.clone());
|
||||
Ok(account)
|
||||
}
|
||||
|
||||
async fn apply_refresh_failure_status(
|
||||
&self,
|
||||
repo: &AccountRepository,
|
||||
account: &StoredAccount,
|
||||
failure: RefreshFailure,
|
||||
) -> Option<AccountStatus> {
|
||||
let status = status_for_refresh_failure(failure)?;
|
||||
let _ = repo.set_status(&account.id, status).await;
|
||||
self.account_pool
|
||||
.lock()
|
||||
.await
|
||||
.set_status(&account.id, status);
|
||||
Some(status)
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
fn public_refresh_failure(failure: RefreshFailure) -> &'static str {
|
||||
match failure {
|
||||
RefreshFailure::InvalidGrant => "invalidGrant",
|
||||
RefreshFailure::QuotaExhausted => "quotaExhausted",
|
||||
RefreshFailure::Banned => "banned",
|
||||
RefreshFailure::Disabled => "disabled",
|
||||
RefreshFailure::Transport => "transport",
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
use secrecy::ExposeSecret;
|
||||
|
||||
use crate::codex::accounts::{
|
||||
model::Account,
|
||||
repository::{AccountRepositoryResult, StoredAccount},
|
||||
};
|
||||
|
||||
use super::AccountService;
|
||||
|
||||
impl AccountService {
|
||||
pub async fn reload_runtime_accounts_from_repository(&self) -> AccountRepositoryResult<usize> {
|
||||
let Some(repository) = self.repository.as_ref() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let accounts = repository.list_pool_accounts().await?;
|
||||
let restored = accounts.len();
|
||||
let mut pool = self.account_pool.lock().await;
|
||||
for account in accounts {
|
||||
pool.insert(account);
|
||||
}
|
||||
Ok(restored)
|
||||
}
|
||||
|
||||
pub async fn insert_runtime_account(&self, account: Account) {
|
||||
self.account_pool.lock().await.insert(account);
|
||||
}
|
||||
|
||||
pub async fn acquire_runtime_account(&self, model: &str) -> Option<Account> {
|
||||
self.account_pool.lock().await.acquire(model)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn pool_account_from_stored(account: StoredAccount) -> Account {
|
||||
Account {
|
||||
id: account.id,
|
||||
email: account.email,
|
||||
account_id: account.account_id,
|
||||
user_id: account.user_id,
|
||||
label: account.label,
|
||||
plan_type: account.plan_type,
|
||||
access_token: account.access_token.expose_secret().to_string(),
|
||||
refresh_token: account
|
||||
.refresh_token
|
||||
.as_ref()
|
||||
.map(|token| token.expose_secret().to_string()),
|
||||
access_token_expires_at: account.access_token_expires_at,
|
||||
status: account.status,
|
||||
quota_limit_reached: false,
|
||||
quota_cooldown_until: None,
|
||||
cloudflare_cooldown_until: None,
|
||||
added_at: account.added_at.to_rfc3339(),
|
||||
last_used_at: None,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct StoredCookie {
|
||||
domain: String,
|
||||
name: String,
|
||||
value: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct CookieJar {
|
||||
by_account: HashMap<String, Vec<StoredCookie>>,
|
||||
}
|
||||
|
||||
impl CookieJar {
|
||||
pub fn capture_set_cookie(&mut self, account_id: &str, raw: &str) {
|
||||
let mut parts = raw.split(';').map(str::trim);
|
||||
let Some(name_value) = parts.next() else {
|
||||
return;
|
||||
};
|
||||
let Some((name, value)) = name_value.split_once('=') else {
|
||||
return;
|
||||
};
|
||||
let mut domain = "chatgpt.com".to_string();
|
||||
for part in parts {
|
||||
if let Some(value) = part.strip_prefix("Domain=") {
|
||||
domain = value.trim_start_matches('.').to_string();
|
||||
}
|
||||
}
|
||||
|
||||
let account = self.by_account.entry(account_id.to_string()).or_default();
|
||||
account.retain(|cookie| !(cookie.domain == domain && cookie.name == name));
|
||||
account.push(StoredCookie {
|
||||
domain,
|
||||
name: name.to_string(),
|
||||
value: value.to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
pub fn cookie_header(&self, account_id: &str, domain: &str) -> Option<String> {
|
||||
// Cloudflare Cookie 必须按账号隔离,不能在不同 Codex 账号之间复用。
|
||||
let cookies = self.by_account.get(account_id)?;
|
||||
let pairs = cookies
|
||||
.iter()
|
||||
.filter(|cookie| domain_matches(domain, &cookie.domain))
|
||||
.map(|cookie| format!("{}={}", cookie.name, cookie.value))
|
||||
.collect::<Vec<_>>();
|
||||
if pairs.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(pairs.join("; "))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn domain_matches(request_domain: &str, cookie_domain: &str) -> bool {
|
||||
request_domain == cookie_domain
|
||||
|| request_domain
|
||||
.strip_suffix(cookie_domain)
|
||||
.is_some_and(|prefix| prefix.ends_with('.'))
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
pub mod jar;
|
||||
pub mod repository;
|
||||
@@ -0,0 +1,163 @@
|
||||
use chrono::Utc;
|
||||
use secrecy::{ExposeSecret, SecretString};
|
||||
use sqlx::{Row, SqlitePool};
|
||||
use thiserror::Error;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::utils::crypto::{CryptoError, SecretBox};
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum CookieError {
|
||||
#[error("database error: {0}")]
|
||||
Database(#[from] sqlx::Error),
|
||||
#[error("cookie encryption error: {0}")]
|
||||
Crypto(#[from] CryptoError),
|
||||
}
|
||||
|
||||
pub type CookieResult<T> = Result<T, CookieError>;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CookieRepository {
|
||||
pool: SqlitePool,
|
||||
secret_box: SecretBox,
|
||||
}
|
||||
|
||||
impl CookieRepository {
|
||||
pub fn new(pool: SqlitePool, secret_box: SecretBox) -> Self {
|
||||
Self { pool, secret_box }
|
||||
}
|
||||
|
||||
pub async fn capture_set_cookie(&self, account_id: &str, raw: &str) -> CookieResult<()> {
|
||||
let Some(parsed) = parse_set_cookie(raw) else {
|
||||
return Ok(());
|
||||
};
|
||||
self.upsert_cookie(account_id, parsed).await
|
||||
}
|
||||
|
||||
pub async fn set_cookie_header(&self, account_id: &str, raw: &str) -> CookieResult<usize> {
|
||||
let parsed = parse_cookie_header(raw);
|
||||
let count = parsed.len();
|
||||
for cookie in parsed {
|
||||
self.upsert_cookie(account_id, cookie).await?;
|
||||
}
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
async fn upsert_cookie(&self, account_id: &str, parsed: ParsedCookie) -> CookieResult<()> {
|
||||
let now = Utc::now().to_rfc3339();
|
||||
let value_cipher = self
|
||||
.secret_box
|
||||
.encrypt(&SecretString::new(parsed.value.into()))?;
|
||||
sqlx::query(
|
||||
"insert into account_cookies (id, account_id, domain, name, value_cipher, path, expires_at, updated_at) values (?, ?, ?, ?, ?, ?, ?, ?) on conflict(account_id, domain, name, path) do update set value_cipher = excluded.value_cipher, expires_at = excluded.expires_at, updated_at = excluded.updated_at",
|
||||
)
|
||||
.bind(Uuid::new_v4().to_string())
|
||||
.bind(account_id)
|
||||
.bind(parsed.domain)
|
||||
.bind(parsed.name)
|
||||
.bind(value_cipher)
|
||||
.bind(parsed.path)
|
||||
.bind(parsed.expires_at)
|
||||
.bind(now)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn cookie_header(
|
||||
&self,
|
||||
account_id: &str,
|
||||
request_domain: &str,
|
||||
) -> CookieResult<Option<String>> {
|
||||
let rows = sqlx::query(
|
||||
"select domain, name, value_cipher from account_cookies where account_id = ? order by name asc",
|
||||
)
|
||||
.bind(account_id)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
let mut pairs = Vec::new();
|
||||
for row in rows {
|
||||
let domain = row.get::<String, _>("domain");
|
||||
if !domain_matches(request_domain, &domain) {
|
||||
continue;
|
||||
}
|
||||
let name = row.get::<String, _>("name");
|
||||
let value_cipher = row.get::<String, _>("value_cipher");
|
||||
let value = self.secret_box.decrypt(&value_cipher)?;
|
||||
pairs.push(format!("{name}={}", value.expose_secret()));
|
||||
}
|
||||
if pairs.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(pairs.join("; ")))
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn delete_account_cookies(&self, account_id: &str) -> CookieResult<u64> {
|
||||
let result = sqlx::query("delete from account_cookies where account_id = ?")
|
||||
.bind(account_id)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(result.rows_affected())
|
||||
}
|
||||
}
|
||||
|
||||
struct ParsedCookie {
|
||||
domain: String,
|
||||
name: String,
|
||||
value: String,
|
||||
path: String,
|
||||
expires_at: Option<String>,
|
||||
}
|
||||
|
||||
fn parse_set_cookie(raw: &str) -> Option<ParsedCookie> {
|
||||
let mut parts = raw.split(';').map(str::trim);
|
||||
let (name, value) = parts.next()?.split_once('=')?;
|
||||
let mut domain = "chatgpt.com".to_string();
|
||||
let mut path = "/".to_string();
|
||||
let mut expires_at = None;
|
||||
for part in parts {
|
||||
if let Some(value) = part.strip_prefix("Domain=") {
|
||||
domain = value.trim_start_matches('.').to_string();
|
||||
} else if let Some(value) = part.strip_prefix("Path=") {
|
||||
path = value.to_string();
|
||||
} else if let Some(value) = part.strip_prefix("Expires=") {
|
||||
expires_at = Some(value.to_string());
|
||||
}
|
||||
}
|
||||
Some(ParsedCookie {
|
||||
domain,
|
||||
name: name.to_string(),
|
||||
value: value.to_string(),
|
||||
path,
|
||||
expires_at,
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_cookie_header(raw: &str) -> Vec<ParsedCookie> {
|
||||
raw.split(';')
|
||||
.map(str::trim)
|
||||
.filter_map(|part| {
|
||||
let (name, value) = part.split_once('=')?;
|
||||
let name = name.trim();
|
||||
let value = value.trim();
|
||||
if name.is_empty() || value.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(ParsedCookie {
|
||||
domain: "chatgpt.com".to_string(),
|
||||
name: name.to_string(),
|
||||
value: value.to_string(),
|
||||
path: "/".to_string(),
|
||||
expires_at: None,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn domain_matches(request_domain: &str, cookie_domain: &str) -> bool {
|
||||
request_domain == cookie_domain
|
||||
|| request_domain
|
||||
.strip_suffix(cookie_domain)
|
||||
.is_some_and(|prefix| prefix.ends_with('.'))
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub mod model;
|
||||
pub mod repository;
|
||||
pub mod updater;
|
||||
@@ -0,0 +1,39 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct Fingerprint {
|
||||
pub originator: String,
|
||||
pub app_version: String,
|
||||
pub build_number: String,
|
||||
pub platform: String,
|
||||
pub arch: String,
|
||||
pub chromium_version: String,
|
||||
pub user_agent_template: String,
|
||||
}
|
||||
|
||||
impl Fingerprint {
|
||||
pub fn default_codex_desktop() -> Self {
|
||||
Self {
|
||||
originator: "Codex Desktop".to_string(),
|
||||
app_version: "26.519.81530".to_string(),
|
||||
build_number: "3178".to_string(),
|
||||
platform: "darwin".to_string(),
|
||||
arch: "arm64".to_string(),
|
||||
chromium_version: "146".to_string(),
|
||||
user_agent_template:
|
||||
"Codex/{app_version} ({platform}; {arch}) Chromium/{chromium_version}".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn default_for_tests() -> Self {
|
||||
Self::default_codex_desktop()
|
||||
}
|
||||
|
||||
pub fn user_agent(&self) -> String {
|
||||
self.user_agent_template
|
||||
.replace("{app_version}", &self.app_version)
|
||||
.replace("{platform}", &self.platform)
|
||||
.replace("{arch}", &self.arch)
|
||||
.replace("{chromium_version}", &self.chromium_version)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
use chrono::Utc;
|
||||
use sqlx::{Row, SqlitePool};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::codex::fingerprint::{
|
||||
model::Fingerprint,
|
||||
updater::{FingerprintUpdate, CODEX_DESKTOP_UPDATE_SOURCE},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct StoredFingerprint {
|
||||
pub app_version: String,
|
||||
pub build_number: String,
|
||||
pub source: String,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct FingerprintRepository {
|
||||
pool: SqlitePool,
|
||||
}
|
||||
|
||||
impl FingerprintRepository {
|
||||
pub fn new(pool: SqlitePool) -> Self {
|
||||
Self { pool }
|
||||
}
|
||||
|
||||
pub async fn insert_update(&self, update: &FingerprintUpdate) -> Result<(), sqlx::Error> {
|
||||
let mut fp = Fingerprint::default_codex_desktop();
|
||||
fp.app_version.clone_from(&update.app_version);
|
||||
fp.build_number.clone_from(&update.build_number);
|
||||
sqlx::query(
|
||||
"insert into fingerprints (id, app_version, build_number, platform, arch, chromium_version, user_agent_template, source, created_at) values (?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
||||
)
|
||||
.bind(Uuid::new_v4().to_string())
|
||||
.bind(fp.app_version)
|
||||
.bind(fp.build_number)
|
||||
.bind(fp.platform)
|
||||
.bind(fp.arch)
|
||||
.bind(fp.chromium_version)
|
||||
.bind(fp.user_agent_template)
|
||||
.bind(CODEX_DESKTOP_UPDATE_SOURCE)
|
||||
.bind(Utc::now().to_rfc3339())
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn latest(&self) -> Result<Option<StoredFingerprint>, sqlx::Error> {
|
||||
let row = sqlx::query(
|
||||
"select app_version, build_number, source from fingerprints order by created_at desc, id desc limit 1",
|
||||
)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
Ok(row.map(|row| StoredFingerprint {
|
||||
app_version: row.get("app_version"),
|
||||
build_number: row.get("build_number"),
|
||||
source: row.get("source"),
|
||||
}))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
use serde::Deserialize;
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::codex::fingerprint::repository::FingerprintRepository;
|
||||
|
||||
pub const CODEX_DESKTOP_UPDATE_SOURCE: &str = "codex_desktop_update_source";
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct FingerprintUpdate {
|
||||
pub app_version: String,
|
||||
pub build_number: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum FingerprintError {
|
||||
#[error("invalid update manifest: {0}")]
|
||||
InvalidManifest(#[from] serde_json::Error),
|
||||
#[error("failed to fetch update manifest: {0}")]
|
||||
Http(#[from] reqwest::Error),
|
||||
#[error("failed to persist fingerprint update: {0}")]
|
||||
Database(#[from] sqlx::Error),
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Manifest {
|
||||
version: String,
|
||||
build_number: String,
|
||||
}
|
||||
|
||||
pub fn parse_update_manifest(input: &str) -> Result<FingerprintUpdate, FingerprintError> {
|
||||
// 自动更新只同步桌面端指纹字段,不把远端配置当作运行时业务配置执行。
|
||||
let manifest: Manifest = serde_json::from_str(input)?;
|
||||
Ok(FingerprintUpdate {
|
||||
app_version: manifest.version,
|
||||
build_number: manifest.build_number,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct FingerprintUpdater {
|
||||
client: reqwest::Client,
|
||||
repository: FingerprintRepository,
|
||||
update_url: String,
|
||||
}
|
||||
|
||||
impl FingerprintUpdater {
|
||||
pub fn new(
|
||||
client: reqwest::Client,
|
||||
repository: FingerprintRepository,
|
||||
update_url: impl Into<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
client,
|
||||
repository,
|
||||
update_url: update_url.into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn poll_once(&self) -> Result<FingerprintUpdate, FingerprintError> {
|
||||
let manifest = self
|
||||
.client
|
||||
.get(&self.update_url)
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?
|
||||
.text()
|
||||
.await?;
|
||||
let update = parse_update_manifest(&manifest)?;
|
||||
self.repository.insert_update(&update).await?;
|
||||
Ok(update)
|
||||
}
|
||||
}
|
||||
+8
-6
@@ -1,6 +1,8 @@
|
||||
pub mod client;
|
||||
pub mod headers;
|
||||
pub mod sse;
|
||||
pub mod types;
|
||||
pub mod usage;
|
||||
pub mod websocket;
|
||||
pub mod accounts;
|
||||
pub mod cookies;
|
||||
pub mod fingerprint;
|
||||
pub mod models;
|
||||
pub mod oauth;
|
||||
pub mod protocol;
|
||||
pub mod transport;
|
||||
pub mod upstream;
|
||||
|
||||
@@ -0,0 +1,427 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::config::ModelConfig;
|
||||
|
||||
const SERVICE_TIER_SUFFIXES: [&str; 2] = ["fast", "flex"];
|
||||
const REASONING_EFFORT_SUFFIXES: [&str; 6] = ["none", "minimal", "low", "medium", "high", "xhigh"];
|
||||
const STATIC_REASONING_EFFORTS: [&str; 4] = ["low", "medium", "high", "xhigh"];
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ReasoningEffortInfo {
|
||||
pub reasoning_effort: String,
|
||||
pub description: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CodexModelInfo {
|
||||
pub id: String,
|
||||
pub display_name: String,
|
||||
pub description: String,
|
||||
pub is_default: bool,
|
||||
pub supported_reasoning_efforts: Vec<ReasoningEffortInfo>,
|
||||
pub default_reasoning_effort: String,
|
||||
pub input_modalities: Vec<String>,
|
||||
pub output_modalities: Vec<String>,
|
||||
pub supports_personality: bool,
|
||||
pub upgrade: Option<String>,
|
||||
pub source: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub context_window: Option<u64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub max_context_window: Option<u64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub max_output_tokens: Option<u64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub truncation_policy_limit: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ParsedModelName {
|
||||
pub model_id: String,
|
||||
pub reasoning_effort: Option<String>,
|
||||
pub service_tier: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ModelStoreDebug {
|
||||
pub total_models: usize,
|
||||
pub static_models: usize,
|
||||
pub alias_count: usize,
|
||||
pub models: Vec<ModelDebugEntry>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ModelDebugEntry {
|
||||
pub id: String,
|
||||
pub source: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ModelCatalog {
|
||||
models: Vec<CodexModelInfo>,
|
||||
aliases: BTreeMap<String, String>,
|
||||
default_model: String,
|
||||
model_plan_index: BTreeMap<String, Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct BackendReasoningEffort {
|
||||
#[serde(default, rename = "reasoning_effort", alias = "reasoningEffort")]
|
||||
pub reasoning_effort: Option<String>,
|
||||
#[serde(default)]
|
||||
pub effort: Option<String>,
|
||||
#[serde(default)]
|
||||
pub description: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct BackendTruncationPolicy {
|
||||
pub limit: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct BackendModelEntry {
|
||||
pub slug: Option<String>,
|
||||
pub id: Option<String>,
|
||||
pub name: Option<String>,
|
||||
pub display_name: Option<String>,
|
||||
pub description: Option<String>,
|
||||
pub is_default: Option<bool>,
|
||||
pub default_reasoning_effort: Option<String>,
|
||||
pub default_reasoning_level: Option<String>,
|
||||
#[serde(default)]
|
||||
pub supported_reasoning_efforts: Vec<BackendReasoningEffort>,
|
||||
#[serde(default)]
|
||||
pub supported_reasoning_levels: Vec<BackendReasoningEffort>,
|
||||
pub input_modalities: Option<Vec<String>>,
|
||||
pub output_modalities: Option<Vec<String>>,
|
||||
pub supports_personality: Option<bool>,
|
||||
pub upgrade: Option<String>,
|
||||
#[serde(alias = "contextWindow")]
|
||||
pub context_window: Option<u64>,
|
||||
#[serde(alias = "maxContextWindow")]
|
||||
pub max_context_window: Option<u64>,
|
||||
#[serde(alias = "maxOutputTokens")]
|
||||
pub max_output_tokens: Option<u64>,
|
||||
#[serde(alias = "truncationPolicy")]
|
||||
pub truncation_policy: Option<BackendTruncationPolicy>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ModelPlanSnapshot {
|
||||
pub plan_type: String,
|
||||
pub models: Vec<CodexModelInfo>,
|
||||
}
|
||||
|
||||
impl ModelPlanSnapshot {
|
||||
pub fn from_backend_entries(
|
||||
plan_type: impl Into<String>,
|
||||
entries: Vec<BackendModelEntry>,
|
||||
) -> Self {
|
||||
Self {
|
||||
plan_type: plan_type.into(),
|
||||
models: entries.into_iter().map(normalize_backend_model).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ModelCatalog {
|
||||
pub fn from_config(config: &ModelConfig) -> Self {
|
||||
let default_model = config.default_model.trim().to_string();
|
||||
let aliases = normalize_aliases(&config.aliases);
|
||||
Self {
|
||||
models: vec![default_model_info(config)],
|
||||
aliases,
|
||||
default_model,
|
||||
model_plan_index: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_config_and_snapshots(
|
||||
config: &ModelConfig,
|
||||
snapshots: &[ModelPlanSnapshot],
|
||||
) -> Self {
|
||||
if snapshots.is_empty() {
|
||||
return Self::from_config(config);
|
||||
}
|
||||
|
||||
let aliases = normalize_aliases(&config.aliases);
|
||||
let default_model = config.default_model.trim().to_string();
|
||||
let mut models_by_id = BTreeMap::new();
|
||||
let mut model_plan_index: BTreeMap<String, Vec<String>> = BTreeMap::new();
|
||||
|
||||
for snapshot in snapshots {
|
||||
for model in &snapshot.models {
|
||||
// 后端模型是按账号 plan 返回的;catalog 需要去重展示,调度层仍要保留 model -> plans。
|
||||
models_by_id.insert(model.id.clone(), model.clone());
|
||||
let plans = model_plan_index.entry(model.id.clone()).or_default();
|
||||
if !plans.contains(&snapshot.plan_type) {
|
||||
plans.push(snapshot.plan_type.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let models = models_by_id.into_values().collect::<Vec<_>>();
|
||||
if models.is_empty() {
|
||||
return Self::from_config(config);
|
||||
}
|
||||
|
||||
Self {
|
||||
models,
|
||||
aliases,
|
||||
default_model,
|
||||
model_plan_index,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn models(&self) -> Vec<CodexModelInfo> {
|
||||
self.models.clone()
|
||||
}
|
||||
|
||||
pub fn model_info(&self, model_id: &str) -> Option<CodexModelInfo> {
|
||||
self.models
|
||||
.iter()
|
||||
.find(|model| model.id == model_id)
|
||||
.cloned()
|
||||
}
|
||||
|
||||
pub fn debug(&self) -> ModelStoreDebug {
|
||||
ModelStoreDebug {
|
||||
total_models: self.models.len(),
|
||||
static_models: self.models.len(),
|
||||
alias_count: self.aliases.len(),
|
||||
models: self
|
||||
.models
|
||||
.iter()
|
||||
.map(|model| ModelDebugEntry {
|
||||
id: model.id.clone(),
|
||||
source: model.source.clone(),
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn model_plan_allowlist(&self) -> BTreeMap<String, Vec<String>> {
|
||||
self.model_plan_index.clone()
|
||||
}
|
||||
|
||||
pub fn is_recognized_model_name(&self, input: &str) -> bool {
|
||||
let trimmed = input.trim();
|
||||
if trimmed.is_empty() {
|
||||
return false;
|
||||
}
|
||||
if self.aliases.contains_key(trimmed) || self.model_info(trimmed).is_some() {
|
||||
return true;
|
||||
}
|
||||
|
||||
let stripped = strip_known_model_suffixes(trimmed);
|
||||
if stripped.model_name == trimmed
|
||||
|| (stripped.reasoning_effort.is_none() && stripped.service_tier.is_none())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
self.aliases.contains_key(&stripped.model_name)
|
||||
|| self.model_info(&stripped.model_name).is_some()
|
||||
}
|
||||
|
||||
pub fn parse_model_name(&self, input: &str) -> ParsedModelName {
|
||||
let trimmed = input.trim();
|
||||
if self.aliases.contains_key(trimmed) || self.model_info(trimmed).is_some() {
|
||||
return ParsedModelName {
|
||||
model_id: self.resolve_model_id(trimmed),
|
||||
reasoning_effort: None,
|
||||
service_tier: None,
|
||||
};
|
||||
}
|
||||
|
||||
let stripped = strip_known_model_suffixes(trimmed);
|
||||
ParsedModelName {
|
||||
model_id: self.resolve_model_id(&stripped.model_name),
|
||||
reasoning_effort: stripped.reasoning_effort,
|
||||
service_tier: stripped.service_tier,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_display_model_name(parsed: &ParsedModelName) -> String {
|
||||
let mut name = parsed.model_id.clone();
|
||||
if let Some(reasoning_effort) = &parsed.reasoning_effort {
|
||||
name.push('-');
|
||||
name.push_str(reasoning_effort);
|
||||
}
|
||||
if let Some(service_tier) = &parsed.service_tier {
|
||||
name.push('-');
|
||||
name.push_str(service_tier);
|
||||
}
|
||||
name
|
||||
}
|
||||
|
||||
fn resolve_model_id(&self, input: &str) -> String {
|
||||
let resolved = self.resolve_alias_chain(input);
|
||||
if self.model_info(&resolved).is_some() {
|
||||
return resolved;
|
||||
}
|
||||
self.default_model.clone()
|
||||
}
|
||||
|
||||
fn resolve_alias_chain(&self, input: &str) -> String {
|
||||
let original = input.trim();
|
||||
let mut current = original.to_string();
|
||||
let mut seen = BTreeSet::new();
|
||||
for _ in 0..20 {
|
||||
let Some(target) = self.aliases.get(¤t).map(|value| value.trim()) else {
|
||||
return current;
|
||||
};
|
||||
if !seen.insert(current.clone()) || seen.contains(target) {
|
||||
return original.to_string();
|
||||
}
|
||||
current = target.to_string();
|
||||
}
|
||||
original.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct StrippedModelName {
|
||||
model_name: String,
|
||||
reasoning_effort: Option<String>,
|
||||
service_tier: Option<String>,
|
||||
}
|
||||
|
||||
fn strip_known_model_suffixes(input: &str) -> StrippedModelName {
|
||||
let mut remaining = input.trim().to_string();
|
||||
let service_tier = take_suffix(&mut remaining, &SERVICE_TIER_SUFFIXES);
|
||||
let reasoning_effort = take_suffix(&mut remaining, &REASONING_EFFORT_SUFFIXES);
|
||||
StrippedModelName {
|
||||
model_name: remaining,
|
||||
reasoning_effort,
|
||||
service_tier,
|
||||
}
|
||||
}
|
||||
|
||||
fn take_suffix(remaining: &mut String, suffixes: &[&str]) -> Option<String> {
|
||||
let suffix = suffixes
|
||||
.iter()
|
||||
.find(|suffix| remaining.ends_with(&format!("-{suffix}")))?;
|
||||
let truncate_to = remaining.len() - suffix.len() - 1;
|
||||
remaining.truncate(truncate_to);
|
||||
Some((*suffix).to_string())
|
||||
}
|
||||
|
||||
fn normalize_aliases(input: &BTreeMap<String, String>) -> BTreeMap<String, String> {
|
||||
input
|
||||
.iter()
|
||||
.filter_map(|(alias, target)| {
|
||||
let alias = alias.trim();
|
||||
let target = target.trim();
|
||||
(!alias.is_empty() && !target.is_empty())
|
||||
.then(|| (alias.to_string(), target.to_string()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn default_model_info(config: &ModelConfig) -> CodexModelInfo {
|
||||
let id = config.default_model.trim().to_string();
|
||||
let default_reasoning_effort = config
|
||||
.default_reasoning_effort
|
||||
.clone()
|
||||
.unwrap_or_else(|| "medium".to_string());
|
||||
CodexModelInfo {
|
||||
id: id.clone(),
|
||||
display_name: id,
|
||||
description: "Codex default model".to_string(),
|
||||
is_default: true,
|
||||
supported_reasoning_efforts: STATIC_REASONING_EFFORTS
|
||||
.into_iter()
|
||||
.map(|effort| ReasoningEffortInfo {
|
||||
reasoning_effort: effort.to_string(),
|
||||
description: effort.to_string(),
|
||||
})
|
||||
.collect(),
|
||||
default_reasoning_effort,
|
||||
input_modalities: vec!["text".to_string(), "image".to_string()],
|
||||
output_modalities: vec!["text".to_string()],
|
||||
supports_personality: false,
|
||||
upgrade: None,
|
||||
source: "static".to_string(),
|
||||
context_window: None,
|
||||
max_context_window: None,
|
||||
max_output_tokens: None,
|
||||
truncation_policy_limit: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_backend_model(raw: BackendModelEntry) -> CodexModelInfo {
|
||||
let id = first_non_empty([raw.slug.as_deref(), raw.id.as_deref(), raw.name.as_deref()])
|
||||
.unwrap_or("unknown")
|
||||
.to_string();
|
||||
let display_name = first_non_empty([raw.display_name.as_deref(), raw.name.as_deref()])
|
||||
.unwrap_or(&id)
|
||||
.to_string();
|
||||
let reasoning_entries = if raw.supported_reasoning_efforts.is_empty() {
|
||||
raw.supported_reasoning_levels
|
||||
} else {
|
||||
raw.supported_reasoning_efforts
|
||||
};
|
||||
let mut supported_reasoning_efforts = reasoning_entries
|
||||
.into_iter()
|
||||
.filter_map(normalize_backend_reasoning_effort)
|
||||
.collect::<Vec<_>>();
|
||||
if supported_reasoning_efforts.is_empty() {
|
||||
supported_reasoning_efforts.push(ReasoningEffortInfo {
|
||||
reasoning_effort: "medium".to_string(),
|
||||
description: "Default".to_string(),
|
||||
});
|
||||
}
|
||||
let default_reasoning_effort = first_non_empty([
|
||||
raw.default_reasoning_effort.as_deref(),
|
||||
raw.default_reasoning_level.as_deref(),
|
||||
])
|
||||
.unwrap_or("medium")
|
||||
.to_string();
|
||||
|
||||
CodexModelInfo {
|
||||
id,
|
||||
display_name,
|
||||
description: raw.description.unwrap_or_default(),
|
||||
is_default: raw.is_default.unwrap_or(false),
|
||||
supported_reasoning_efforts,
|
||||
default_reasoning_effort,
|
||||
input_modalities: raw
|
||||
.input_modalities
|
||||
.unwrap_or_else(|| vec!["text".to_string()]),
|
||||
output_modalities: raw
|
||||
.output_modalities
|
||||
.unwrap_or_else(|| vec!["text".to_string()]),
|
||||
supports_personality: raw.supports_personality.unwrap_or(false),
|
||||
upgrade: raw.upgrade,
|
||||
source: "backend".to_string(),
|
||||
context_window: raw.context_window,
|
||||
max_context_window: raw.max_context_window,
|
||||
max_output_tokens: raw.max_output_tokens,
|
||||
truncation_policy_limit: raw.truncation_policy.and_then(|policy| policy.limit),
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_backend_reasoning_effort(raw: BackendReasoningEffort) -> Option<ReasoningEffortInfo> {
|
||||
let reasoning_effort =
|
||||
first_non_empty([raw.reasoning_effort.as_deref(), raw.effort.as_deref()])?.to_string();
|
||||
Some(ReasoningEffortInfo {
|
||||
description: raw.description.unwrap_or_default(),
|
||||
reasoning_effort,
|
||||
})
|
||||
}
|
||||
|
||||
fn first_non_empty<'a>(values: impl IntoIterator<Item = Option<&'a str>>) -> Option<&'a str> {
|
||||
values
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.map(str::trim)
|
||||
.find(|value| !value.is_empty())
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub mod catalog;
|
||||
pub mod repository;
|
||||
pub mod service;
|
||||
@@ -0,0 +1,62 @@
|
||||
use chrono::Utc;
|
||||
use sqlx::{Row, SqlitePool};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::codex::models::catalog::{CodexModelInfo, ModelPlanSnapshot};
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ModelSnapshotRepositoryError {
|
||||
#[error("model snapshot database error: {0}")]
|
||||
Database(#[from] sqlx::Error),
|
||||
#[error("model snapshot json error: {0}")]
|
||||
Json(#[from] serde_json::Error),
|
||||
}
|
||||
|
||||
pub type ModelSnapshotRepositoryResult<T> = Result<T, ModelSnapshotRepositoryError>;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ModelSnapshotRepository {
|
||||
pool: SqlitePool,
|
||||
}
|
||||
|
||||
impl ModelSnapshotRepository {
|
||||
pub fn new(pool: SqlitePool) -> Self {
|
||||
Self { pool }
|
||||
}
|
||||
|
||||
pub async fn replace_plan_snapshot(
|
||||
&self,
|
||||
snapshot: &ModelPlanSnapshot,
|
||||
) -> ModelSnapshotRepositoryResult<()> {
|
||||
let models_json = serde_json::to_string(&snapshot.models)?;
|
||||
let fetched_at = Utc::now().to_rfc3339();
|
||||
sqlx::query(
|
||||
"insert into model_plan_snapshots (plan_type, models_json, fetched_at) values (?, ?, ?) \
|
||||
on conflict(plan_type) do update set models_json = excluded.models_json, fetched_at = excluded.fetched_at",
|
||||
)
|
||||
.bind(&snapshot.plan_type)
|
||||
.bind(models_json)
|
||||
.bind(fetched_at)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn list_plan_snapshots(
|
||||
&self,
|
||||
) -> ModelSnapshotRepositoryResult<Vec<ModelPlanSnapshot>> {
|
||||
let rows = sqlx::query(
|
||||
"select plan_type, models_json from model_plan_snapshots order by plan_type asc",
|
||||
)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
rows.into_iter()
|
||||
.map(|row| {
|
||||
let plan_type: String = row.get("plan_type");
|
||||
let models_json: String = row.get("models_json");
|
||||
let models = serde_json::from_str::<Vec<CodexModelInfo>>(&models_json)?;
|
||||
Ok(ModelPlanSnapshot { plan_type, models })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::{
|
||||
codex::accounts::{
|
||||
model::{Account, AccountStatus},
|
||||
pool::AccountPool,
|
||||
repository::AccountRepository,
|
||||
},
|
||||
codex::fingerprint::model::Fingerprint,
|
||||
codex::models::{
|
||||
catalog::{ModelCatalog, ModelPlanSnapshot},
|
||||
repository::ModelSnapshotRepository,
|
||||
},
|
||||
codex::transport::client::{build_reqwest_client, CodexBackendClient, CodexRequestContext},
|
||||
config::AppConfig,
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ModelService {
|
||||
config: AppConfig,
|
||||
snapshot_repository: Option<ModelSnapshotRepository>,
|
||||
account_repository: Option<AccountRepository>,
|
||||
account_pool: Arc<Mutex<AccountPool>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct ModelRefreshResult {
|
||||
pub refreshed_plans: usize,
|
||||
pub model_count: usize,
|
||||
pub failed_plans: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ModelServiceError {
|
||||
AccountRepositoryUnavailable,
|
||||
ModelRepositoryUnavailable,
|
||||
ListAccounts,
|
||||
NoAccounts,
|
||||
BuildClient,
|
||||
StoreSnapshot,
|
||||
AllPlansFailed(ModelRefreshResult),
|
||||
LoadSnapshots,
|
||||
}
|
||||
|
||||
impl ModelService {
|
||||
pub fn new(
|
||||
config: AppConfig,
|
||||
snapshot_repository: Option<ModelSnapshotRepository>,
|
||||
account_repository: Option<AccountRepository>,
|
||||
account_pool: Arc<Mutex<AccountPool>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
config,
|
||||
snapshot_repository,
|
||||
account_repository,
|
||||
account_pool,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn catalog(&self) -> ModelCatalog {
|
||||
let Some(repo) = self.snapshot_repository.as_ref() else {
|
||||
return ModelCatalog::from_config(&self.config.model);
|
||||
};
|
||||
match repo.list_plan_snapshots().await {
|
||||
Ok(snapshots) if !snapshots.is_empty() => {
|
||||
ModelCatalog::from_config_and_snapshots(&self.config.model, &snapshots)
|
||||
}
|
||||
Ok(_) => ModelCatalog::from_config(&self.config.model),
|
||||
Err(error) => {
|
||||
// Cached model snapshots extend the catalog; fallback keeps proxy routes available.
|
||||
tracing::warn!(?error, "failed to load cached model snapshots");
|
||||
ModelCatalog::from_config(&self.config.model)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn refresh_backend_models(
|
||||
&self,
|
||||
request_id: &str,
|
||||
) -> Result<ModelRefreshResult, ModelServiceError> {
|
||||
let account_repo = self
|
||||
.account_repository
|
||||
.as_ref()
|
||||
.ok_or(ModelServiceError::AccountRepositoryUnavailable)?;
|
||||
let model_repo = self
|
||||
.snapshot_repository
|
||||
.as_ref()
|
||||
.ok_or(ModelServiceError::ModelRepositoryUnavailable)?;
|
||||
|
||||
let accounts = account_repo
|
||||
.list_pool_accounts()
|
||||
.await
|
||||
.map_err(|_| ModelServiceError::ListAccounts)?;
|
||||
let plan_accounts = distinct_active_plan_accounts(accounts);
|
||||
if plan_accounts.is_empty() {
|
||||
return Err(ModelServiceError::NoAccounts);
|
||||
}
|
||||
|
||||
let client = build_reqwest_client(self.config.tls.force_http11)
|
||||
.map(|client| {
|
||||
CodexBackendClient::new(
|
||||
client,
|
||||
self.config.api.base_url.clone(),
|
||||
Fingerprint::default_codex_desktop(),
|
||||
)
|
||||
})
|
||||
.map_err(|_| ModelServiceError::BuildClient)?;
|
||||
|
||||
let mut result = ModelRefreshResult {
|
||||
refreshed_plans: 0,
|
||||
model_count: 0,
|
||||
failed_plans: 0,
|
||||
};
|
||||
for (plan_type, account) in plan_accounts {
|
||||
let context = CodexRequestContext {
|
||||
access_token: &account.access_token,
|
||||
account_id: account.account_id.as_deref(),
|
||||
request_id,
|
||||
turn_state: None,
|
||||
turn_metadata: None,
|
||||
beta_features: None,
|
||||
include_timing_metrics: None,
|
||||
version: None,
|
||||
codex_window_id: None,
|
||||
parent_thread_id: None,
|
||||
cookie_header: None,
|
||||
};
|
||||
let entries = match client.fetch_models(context).await {
|
||||
Ok(entries) if !entries.is_empty() => entries,
|
||||
Ok(_) => {
|
||||
result.failed_plans += 1;
|
||||
continue;
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(?error, plan_type, "failed to refresh backend models");
|
||||
result.failed_plans += 1;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let snapshot = ModelPlanSnapshot::from_backend_entries(plan_type, entries);
|
||||
result.model_count += snapshot.models.len();
|
||||
model_repo
|
||||
.replace_plan_snapshot(&snapshot)
|
||||
.await
|
||||
.map_err(|_| ModelServiceError::StoreSnapshot)?;
|
||||
result.refreshed_plans += 1;
|
||||
}
|
||||
|
||||
if result.refreshed_plans == 0 {
|
||||
return Err(ModelServiceError::AllPlansFailed(result));
|
||||
}
|
||||
|
||||
let snapshots = model_repo
|
||||
.list_plan_snapshots()
|
||||
.await
|
||||
.map_err(|_| ModelServiceError::LoadSnapshots)?;
|
||||
let allowlist = ModelCatalog::from_config_and_snapshots(&self.config.model, &snapshots)
|
||||
.model_plan_allowlist();
|
||||
self.account_pool
|
||||
.lock()
|
||||
.await
|
||||
.set_model_plan_allowlist(allowlist);
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
fn distinct_active_plan_accounts(accounts: Vec<Account>) -> Vec<(String, Account)> {
|
||||
let mut by_plan = std::collections::BTreeMap::new();
|
||||
for account in accounts {
|
||||
if account.status != AccountStatus::Active {
|
||||
continue;
|
||||
}
|
||||
let plan_type = account
|
||||
.plan_type
|
||||
.as_deref()
|
||||
.unwrap_or("unknown")
|
||||
.to_string();
|
||||
by_plan.entry(plan_type).or_insert(account);
|
||||
}
|
||||
by_plan.into_iter().collect()
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
use std::{
|
||||
env, fs, io,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
use secrecy::{ExposeSecret, SecretString};
|
||||
use serde::Deserialize;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum CliAuthImportError {
|
||||
#[error("CODEX_HOME is not set and HOME is unavailable")]
|
||||
MissingHome,
|
||||
#[error("failed to read CLI auth file {path}: {source}")]
|
||||
Read { path: PathBuf, source: io::Error },
|
||||
#[error("failed to parse CLI auth.json: {0}")]
|
||||
Parse(#[from] serde_json::Error),
|
||||
#[error("CLI auth.json does not contain access_token")]
|
||||
MissingAccessToken,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CliAuth {
|
||||
access_token: SecretString,
|
||||
refresh_token: Option<SecretString>,
|
||||
id_token: Option<SecretString>,
|
||||
expires_at: Option<i64>,
|
||||
}
|
||||
|
||||
impl CliAuth {
|
||||
pub fn access_token(&self) -> &str {
|
||||
self.access_token.expose_secret()
|
||||
}
|
||||
|
||||
pub fn refresh_token(&self) -> Option<&str> {
|
||||
self.refresh_token
|
||||
.as_ref()
|
||||
.map(|token| token.expose_secret())
|
||||
}
|
||||
|
||||
pub fn id_token(&self) -> Option<&str> {
|
||||
self.id_token.as_ref().map(|token| token.expose_secret())
|
||||
}
|
||||
|
||||
pub fn expires_at(&self) -> Option<i64> {
|
||||
self.expires_at
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct CliAuthJson {
|
||||
access_token: Option<String>,
|
||||
refresh_token: Option<String>,
|
||||
id_token: Option<String>,
|
||||
expires_at: Option<i64>,
|
||||
}
|
||||
|
||||
pub fn default_codex_home() -> Result<PathBuf, CliAuthImportError> {
|
||||
if let Some(codex_home) = env::var_os("CODEX_HOME") {
|
||||
return Ok(PathBuf::from(codex_home));
|
||||
}
|
||||
let home = env::var_os("HOME").ok_or(CliAuthImportError::MissingHome)?;
|
||||
Ok(PathBuf::from(home).join(".codex"))
|
||||
}
|
||||
|
||||
pub fn read_cli_auth_from_home(codex_home: &Path) -> Result<CliAuth, CliAuthImportError> {
|
||||
let auth_path = codex_home.join("auth.json");
|
||||
let raw = fs::read_to_string(&auth_path).map_err(|source| CliAuthImportError::Read {
|
||||
path: auth_path,
|
||||
source,
|
||||
})?;
|
||||
parse_cli_auth_json(&raw)
|
||||
}
|
||||
|
||||
pub fn parse_cli_auth_json(raw: &str) -> Result<CliAuth, CliAuthImportError> {
|
||||
let parsed = serde_json::from_str::<CliAuthJson>(raw)?;
|
||||
let access_token =
|
||||
non_empty_secret(parsed.access_token).ok_or(CliAuthImportError::MissingAccessToken)?;
|
||||
|
||||
Ok(CliAuth {
|
||||
access_token,
|
||||
refresh_token: non_empty_secret(parsed.refresh_token),
|
||||
id_token: non_empty_secret(parsed.id_token),
|
||||
expires_at: parsed.expires_at,
|
||||
})
|
||||
}
|
||||
|
||||
fn non_empty_secret(value: Option<String>) -> Option<SecretString> {
|
||||
value
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(|value| SecretString::new(value.into()))
|
||||
}
|
||||
@@ -0,0 +1,415 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
use rand::Rng;
|
||||
use reqwest::{Client, StatusCode};
|
||||
use serde::Deserialize;
|
||||
use sha2::{Digest, Sha256};
|
||||
use thiserror::Error;
|
||||
|
||||
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/callback";
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct OAuthConfig {
|
||||
pub client_id: String,
|
||||
pub auth_endpoint: String,
|
||||
pub device_code_endpoint: String,
|
||||
pub token_endpoint: String,
|
||||
}
|
||||
|
||||
impl OAuthConfig {
|
||||
pub fn codex_default() -> Self {
|
||||
Self {
|
||||
client_id: CODEX_OAUTH_CLIENT_ID.to_string(),
|
||||
auth_endpoint: OPENAI_OAUTH_AUTHORIZE_ENDPOINT.to_string(),
|
||||
device_code_endpoint: OPENAI_OAUTH_DEVICE_CODE_ENDPOINT.to_string(),
|
||||
token_endpoint: OPENAI_OAUTH_TOKEN_ENDPOINT.to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
pub struct DeviceCode {
|
||||
pub device_code: String,
|
||||
pub user_code: String,
|
||||
pub verification_uri: String,
|
||||
pub verification_uri_complete: String,
|
||||
pub expires_in: u64,
|
||||
pub interval: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Error)]
|
||||
pub enum OAuthError {
|
||||
#[error("authorization pending")]
|
||||
AuthorizationPending,
|
||||
#[error("slow down")]
|
||||
SlowDown,
|
||||
#[error("OAuth request rejected: {0}")]
|
||||
Rejected(String),
|
||||
#[error("OAuth transport failed")]
|
||||
Transport,
|
||||
}
|
||||
|
||||
impl OAuthError {
|
||||
pub fn pending_code(&self) -> Option<&'static str> {
|
||||
match self {
|
||||
Self::AuthorizationPending => Some("authorization_pending"),
|
||||
Self::SlowDown => Some("slow_down"),
|
||||
Self::Rejected(_) | Self::Transport => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait OAuthClient: Send + Sync + 'static {
|
||||
async fn exchange_code(
|
||||
&self,
|
||||
code: &str,
|
||||
code_verifier: &str,
|
||||
redirect_uri: &str,
|
||||
) -> Result<TokenPair, OAuthError>;
|
||||
|
||||
async fn request_device_code(&self) -> Result<DeviceCode, OAuthError>;
|
||||
|
||||
async fn poll_device_token(&self, device_code: &str) -> Result<TokenPair, OAuthError>;
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PkceLogin {
|
||||
pub auth_url: String,
|
||||
pub state: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PkceSession {
|
||||
pub code_verifier: String,
|
||||
pub redirect_uri: String,
|
||||
pub return_host: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct PendingPkceSession {
|
||||
session: PkceSession,
|
||||
created_at: DateTime<Utc>,
|
||||
exchanging: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct PkceSessionStore {
|
||||
pending: BTreeMap<String, PendingPkceSession>,
|
||||
completed: BTreeMap<String, DateTime<Utc>>,
|
||||
ttl: Duration,
|
||||
}
|
||||
|
||||
impl Default for PkceSessionStore {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
pending: BTreeMap::new(),
|
||||
completed: BTreeMap::new(),
|
||||
ttl: Duration::minutes(5),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PkceSessionStore {
|
||||
pub fn start_login(&mut self, return_host: &str, config: &OAuthConfig) -> PkceLogin {
|
||||
self.cleanup(Utc::now());
|
||||
let (code_verifier, code_challenge) = generate_pkce_pair();
|
||||
let state = random_state();
|
||||
let redirect_uri = format!("http://localhost:{OAUTH_CALLBACK_PORT}{OAUTH_CALLBACK_PATH}");
|
||||
let auth_url = build_auth_url(config, &redirect_uri, &state, &code_challenge);
|
||||
self.pending.insert(
|
||||
state.clone(),
|
||||
PendingPkceSession {
|
||||
session: PkceSession {
|
||||
code_verifier,
|
||||
redirect_uri,
|
||||
return_host: return_host.to_string(),
|
||||
},
|
||||
created_at: Utc::now(),
|
||||
exchanging: false,
|
||||
},
|
||||
);
|
||||
PkceLogin { auth_url, state }
|
||||
}
|
||||
|
||||
pub fn try_acquire(&mut self, state: &str) -> Option<PkceSession> {
|
||||
self.cleanup(Utc::now());
|
||||
let pending = self.pending.get_mut(state)?;
|
||||
if pending.exchanging {
|
||||
return None;
|
||||
}
|
||||
pending.exchanging = true;
|
||||
Some(pending.session.clone())
|
||||
}
|
||||
|
||||
pub fn release(&mut self, state: &str) {
|
||||
if let Some(pending) = self.pending.get_mut(state) {
|
||||
pending.exchanging = false;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn complete(&mut self, state: &str) {
|
||||
self.pending.remove(state);
|
||||
self.completed.insert(state.to_string(), Utc::now());
|
||||
}
|
||||
|
||||
pub fn is_completed_or_exchanging(&mut self, state: &str) -> bool {
|
||||
self.cleanup(Utc::now());
|
||||
self.completed.contains_key(state)
|
||||
|| self
|
||||
.pending
|
||||
.get(state)
|
||||
.is_some_and(|pending| pending.exchanging)
|
||||
}
|
||||
|
||||
fn cleanup(&mut self, now: DateTime<Utc>) {
|
||||
self.pending
|
||||
.retain(|_, pending| now - pending.created_at <= self.ttl);
|
||||
self.completed
|
||||
.retain(|_, completed_at| now - *completed_at <= self.ttl);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct OpenAiOAuthRefresher {
|
||||
client: Client,
|
||||
config: OAuthConfig,
|
||||
}
|
||||
|
||||
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)]
|
||||
struct RefreshTokenResponse {
|
||||
access_token: String,
|
||||
refresh_token: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct OAuthErrorResponse {
|
||||
error: Option<String>,
|
||||
error_description: Option<String>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl OAuthClient for OpenAiOAuthRefresher {
|
||||
async fn exchange_code(
|
||||
&self,
|
||||
code: &str,
|
||||
code_verifier: &str,
|
||||
redirect_uri: &str,
|
||||
) -> Result<TokenPair, OAuthError> {
|
||||
let response = self
|
||||
.client
|
||||
.post(&self.config.token_endpoint)
|
||||
.form(&[
|
||||
("grant_type", "authorization_code"),
|
||||
("client_id", self.config.client_id.as_str()),
|
||||
("code", code),
|
||||
("redirect_uri", redirect_uri),
|
||||
("code_verifier", code_verifier),
|
||||
])
|
||||
.send()
|
||||
.await
|
||||
.map_err(|_| OAuthError::Transport)?;
|
||||
let status = response.status();
|
||||
let body = response.text().await.map_err(|_| OAuthError::Transport)?;
|
||||
if !status.is_success() {
|
||||
return Err(OAuthError::Rejected(format!(
|
||||
"Token exchange failed ({status}): {body}"
|
||||
)));
|
||||
}
|
||||
parse_token_pair(&body).map_err(|_| OAuthError::Transport)
|
||||
}
|
||||
|
||||
async fn request_device_code(&self) -> Result<DeviceCode, OAuthError> {
|
||||
let response = self
|
||||
.client
|
||||
.post(&self.config.device_code_endpoint)
|
||||
.form(&[
|
||||
("client_id", self.config.client_id.as_str()),
|
||||
("scope", "openid profile email offline_access"),
|
||||
])
|
||||
.send()
|
||||
.await
|
||||
.map_err(|_| OAuthError::Transport)?;
|
||||
let status = response.status();
|
||||
let body = response.text().await.map_err(|_| OAuthError::Transport)?;
|
||||
if !status.is_success() {
|
||||
return Err(OAuthError::Rejected(format!(
|
||||
"Device code request failed ({status}): {body}"
|
||||
)));
|
||||
}
|
||||
serde_json::from_str::<DeviceCode>(&body).map_err(|_| OAuthError::Transport)
|
||||
}
|
||||
|
||||
async fn poll_device_token(&self, device_code: &str) -> Result<TokenPair, OAuthError> {
|
||||
let response = self
|
||||
.client
|
||||
.post(&self.config.token_endpoint)
|
||||
.form(&[
|
||||
("grant_type", "urn:ietf:params:oauth:grant-type:device_code"),
|
||||
("device_code", device_code),
|
||||
("client_id", self.config.client_id.as_str()),
|
||||
])
|
||||
.send()
|
||||
.await
|
||||
.map_err(|_| OAuthError::Transport)?;
|
||||
let status = response.status();
|
||||
let body = response.text().await.map_err(|_| OAuthError::Transport)?;
|
||||
if !status.is_success() {
|
||||
return Err(classify_device_poll_failure(status, &body));
|
||||
}
|
||||
parse_token_pair(&body).map_err(|_| OAuthError::Transport)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TokenRefresher for OpenAiOAuthRefresher {
|
||||
async fn refresh(&self, refresh_token: &str) -> Result<TokenPair, RefreshFailure> {
|
||||
let response = self
|
||||
.client
|
||||
.post(&self.config.token_endpoint)
|
||||
.form(&[
|
||||
("grant_type", "refresh_token"),
|
||||
("client_id", self.config.client_id.as_str()),
|
||||
("refresh_token", refresh_token),
|
||||
])
|
||||
.send()
|
||||
.await
|
||||
.map_err(|_| RefreshFailure::Transport)?;
|
||||
let status = response.status();
|
||||
let body = response
|
||||
.text()
|
||||
.await
|
||||
.map_err(|_| RefreshFailure::Transport)?;
|
||||
if !status.is_success() {
|
||||
return Err(classify_refresh_failure(status, &body));
|
||||
}
|
||||
parse_token_pair(&body).map_err(|_| RefreshFailure::Transport)
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_token_pair(body: &str) -> Result<TokenPair, ()> {
|
||||
let tokens = serde_json::from_str::<RefreshTokenResponse>(body).map_err(|_| ())?;
|
||||
if tokens.access_token.trim().is_empty() {
|
||||
return Err(());
|
||||
}
|
||||
Ok(TokenPair {
|
||||
access_token: tokens.access_token,
|
||||
refresh_token: tokens.refresh_token,
|
||||
})
|
||||
}
|
||||
|
||||
fn classify_device_poll_failure(status: StatusCode, body: &str) -> OAuthError {
|
||||
let parsed = serde_json::from_str::<OAuthErrorResponse>(body).ok();
|
||||
match parsed.as_ref().and_then(|data| data.error.as_deref()) {
|
||||
Some("authorization_pending") => OAuthError::AuthorizationPending,
|
||||
Some("slow_down") => OAuthError::SlowDown,
|
||||
Some(code) => OAuthError::Rejected(
|
||||
parsed
|
||||
.as_ref()
|
||||
.and_then(|data| data.error_description.clone())
|
||||
.unwrap_or_else(|| code.to_string()),
|
||||
),
|
||||
None => OAuthError::Rejected(format!("Device token poll failed ({status}): {body}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn generate_pkce_pair() -> (String, String) {
|
||||
let mut bytes = [0u8; 32];
|
||||
rand::rng().fill_bytes(&mut bytes);
|
||||
let code_verifier = URL_SAFE_NO_PAD.encode(bytes);
|
||||
let digest = Sha256::digest(code_verifier.as_bytes());
|
||||
let code_challenge = URL_SAFE_NO_PAD.encode(digest);
|
||||
(code_verifier, code_challenge)
|
||||
}
|
||||
|
||||
fn random_state() -> String {
|
||||
let mut bytes = [0u8; 16];
|
||||
rand::rng().fill_bytes(&mut bytes);
|
||||
bytes.iter().map(|byte| format!("{byte:02x}")).collect()
|
||||
}
|
||||
|
||||
fn build_auth_url(
|
||||
config: &OAuthConfig,
|
||||
redirect_uri: &str,
|
||||
state: &str,
|
||||
code_challenge: &str,
|
||||
) -> String {
|
||||
let params = [
|
||||
("response_type", "code"),
|
||||
("client_id", config.client_id.as_str()),
|
||||
("redirect_uri", redirect_uri),
|
||||
("scope", "openid profile email offline_access"),
|
||||
("code_challenge", code_challenge),
|
||||
("code_challenge_method", "S256"),
|
||||
("id_token_add_organizations", "true"),
|
||||
("codex_cli_simplified_flow", "true"),
|
||||
("state", state),
|
||||
("originator", "codex_cli_rs"),
|
||||
];
|
||||
let query = params
|
||||
.iter()
|
||||
.map(|(key, value)| format!("{}={}", percent_encode(key), percent_encode(value)))
|
||||
.collect::<Vec<_>>()
|
||||
.join("&");
|
||||
format!("{}?{query}", config.auth_endpoint)
|
||||
}
|
||||
|
||||
fn percent_encode(value: &str) -> String {
|
||||
let mut encoded = String::new();
|
||||
for byte in value.bytes() {
|
||||
match byte {
|
||||
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
|
||||
encoded.push(char::from(byte));
|
||||
}
|
||||
_ => encoded.push_str(&format!("%{byte:02X}")),
|
||||
}
|
||||
}
|
||||
encoded
|
||||
}
|
||||
|
||||
fn classify_refresh_failure(status: StatusCode, body: &str) -> RefreshFailure {
|
||||
let lower = body.to_ascii_lowercase();
|
||||
if lower.contains("quota") {
|
||||
return RefreshFailure::QuotaExhausted;
|
||||
}
|
||||
if lower.contains("account has been deactivated")
|
||||
|| lower.contains("refresh_token_reused")
|
||||
|| lower.contains("banned")
|
||||
{
|
||||
return RefreshFailure::Banned;
|
||||
}
|
||||
if status == StatusCode::BAD_REQUEST
|
||||
|| status == StatusCode::UNAUTHORIZED
|
||||
|| lower.contains("invalid_grant")
|
||||
|| lower.contains("invalid_token")
|
||||
|| lower.contains("access_denied")
|
||||
|| lower.contains("refresh_token_expired")
|
||||
|| lower.contains("token_revoked")
|
||||
{
|
||||
return RefreshFailure::InvalidGrant;
|
||||
}
|
||||
RefreshFailure::Transport
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
pub mod cli_import;
|
||||
pub mod client;
|
||||
pub mod refresh;
|
||||
pub mod token;
|
||||
|
||||
pub use cli_import::*;
|
||||
pub use client::*;
|
||||
pub use refresh::*;
|
||||
pub use token::*;
|
||||
@@ -0,0 +1,142 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
use thiserror::Error;
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
use crate::codex::accounts::model::{Account, AccountStatus};
|
||||
|
||||
use super::token::TokenPair;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct RefreshPolicy {
|
||||
pub refresh_margin_seconds: u64,
|
||||
pub refresh_concurrency: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum RefreshTrigger {
|
||||
BeforeExpiry,
|
||||
Unauthorized,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
|
||||
pub enum RefreshFailure {
|
||||
#[error("refresh token is invalid or expired")]
|
||||
InvalidGrant,
|
||||
#[error("account quota is exhausted")]
|
||||
QuotaExhausted,
|
||||
#[error("account is banned")]
|
||||
Banned,
|
||||
#[error("account is disabled")]
|
||||
Disabled,
|
||||
#[error("refresh transport failed")]
|
||||
Transport,
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum RefreshError {
|
||||
#[error("refresh task semaphore closed")]
|
||||
ConcurrencyClosed,
|
||||
#[error("refresh transport failed")]
|
||||
Transport,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait TokenRefresher: Send + Sync + 'static {
|
||||
async fn refresh(&self, refresh_token: &str) -> Result<TokenPair, RefreshFailure>;
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct RefreshScheduler<C> {
|
||||
policy: RefreshPolicy,
|
||||
client: Arc<C>,
|
||||
semaphore: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
impl<C> RefreshScheduler<C>
|
||||
where
|
||||
C: TokenRefresher,
|
||||
{
|
||||
pub fn new(policy: RefreshPolicy, client: C) -> Self {
|
||||
let concurrency = policy.refresh_concurrency.max(1) as usize;
|
||||
Self {
|
||||
policy,
|
||||
client: Arc::new(client),
|
||||
semaphore: Arc::new(Semaphore::new(concurrency)),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn refresh_account_at(
|
||||
&self,
|
||||
account: &Account,
|
||||
trigger: RefreshTrigger,
|
||||
now: DateTime<Utc>,
|
||||
) -> Result<Account, RefreshError> {
|
||||
if !self.should_refresh(account, trigger, now) {
|
||||
return Ok(account.clone());
|
||||
}
|
||||
let Some(refresh_token) = account.refresh_token.as_deref() else {
|
||||
let mut expired = account.clone();
|
||||
expired.status = AccountStatus::Expired;
|
||||
return Ok(expired);
|
||||
};
|
||||
|
||||
let _permit = self
|
||||
.semaphore
|
||||
.acquire()
|
||||
.await
|
||||
.map_err(|_| RefreshError::ConcurrencyClosed)?;
|
||||
// 刷新响应未返回 refresh_token 时必须保留旧值,避免把账号永久刷新能力清空。
|
||||
match self.client.refresh(refresh_token).await {
|
||||
Ok(token_pair) => Ok(apply_token_pair(account, token_pair)),
|
||||
Err(RefreshFailure::Transport) => Err(RefreshError::Transport),
|
||||
Err(error) => Ok(apply_refresh_failure(account, error)),
|
||||
}
|
||||
}
|
||||
|
||||
fn should_refresh(
|
||||
&self,
|
||||
account: &Account,
|
||||
trigger: RefreshTrigger,
|
||||
now: DateTime<Utc>,
|
||||
) -> bool {
|
||||
if account.status != AccountStatus::Active {
|
||||
return false;
|
||||
}
|
||||
match trigger {
|
||||
RefreshTrigger::Unauthorized => true,
|
||||
RefreshTrigger::BeforeExpiry => account
|
||||
.access_token_expires_at
|
||||
.is_some_and(|expires_at| expires_at <= now + self.refresh_margin()),
|
||||
}
|
||||
}
|
||||
|
||||
fn refresh_margin(&self) -> Duration {
|
||||
let seconds = self.policy.refresh_margin_seconds.min(86_400 * 7) as i64;
|
||||
Duration::seconds(seconds)
|
||||
}
|
||||
}
|
||||
|
||||
fn apply_token_pair(account: &Account, token_pair: TokenPair) -> Account {
|
||||
let mut refreshed = account.clone();
|
||||
refreshed.access_token = token_pair.access_token;
|
||||
if let Some(refresh_token) = token_pair.refresh_token {
|
||||
refreshed.refresh_token = Some(refresh_token);
|
||||
}
|
||||
refreshed.status = AccountStatus::Active;
|
||||
refreshed
|
||||
}
|
||||
|
||||
fn apply_refresh_failure(account: &Account, failure: RefreshFailure) -> Account {
|
||||
let mut updated = account.clone();
|
||||
updated.status = match failure {
|
||||
RefreshFailure::InvalidGrant => AccountStatus::Expired,
|
||||
RefreshFailure::QuotaExhausted => AccountStatus::QuotaExhausted,
|
||||
RefreshFailure::Banned => AccountStatus::Banned,
|
||||
RefreshFailure::Disabled => AccountStatus::Disabled,
|
||||
RefreshFailure::Transport => AccountStatus::Active,
|
||||
};
|
||||
updated
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TokenPair {
|
||||
pub access_token: String,
|
||||
pub refresh_token: Option<String>,
|
||||
}
|
||||
@@ -0,0 +1,531 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use chrono::Utc;
|
||||
use serde_json::{json, Value};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::codex::transport::sse::{parse_sse_events, SseError};
|
||||
|
||||
pub fn openai_error(message: &str, code: &str) -> Value {
|
||||
json!({
|
||||
"error": {
|
||||
"message": message,
|
||||
"type": "server_error",
|
||||
"param": null,
|
||||
"code": code
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
pub fn chat_completion_from_codex_sse(
|
||||
body: &str,
|
||||
model: &str,
|
||||
include_reasoning: bool,
|
||||
) -> Result<Option<Value>, SseError> {
|
||||
let events = parse_sse_events(body)?;
|
||||
let mut content = String::new();
|
||||
let mut reasoning = String::new();
|
||||
let mut function_call_items = BTreeMap::new();
|
||||
let mut finished_call_ids = BTreeSet::new();
|
||||
let mut tool_calls = Vec::new();
|
||||
let mut completed_response = None;
|
||||
for event in events {
|
||||
let Ok(value) = serde_json::from_str::<Value>(&event.data) else {
|
||||
continue;
|
||||
};
|
||||
match event.event.as_deref() {
|
||||
Some("response.output_text.delta") => {
|
||||
if let Some(delta) = value.get("delta").and_then(Value::as_str) {
|
||||
content.push_str(delta);
|
||||
}
|
||||
}
|
||||
Some("response.reasoning_summary_text.delta") if include_reasoning => {
|
||||
if let Some(delta) = value.get("delta").and_then(Value::as_str) {
|
||||
reasoning.push_str(delta);
|
||||
}
|
||||
}
|
||||
Some("response.output_item.added") => {
|
||||
if let Some((item_id, call_id, name)) = function_call_item(value.get("item")) {
|
||||
function_call_items.insert(item_id, FunctionCallInfo { call_id, name });
|
||||
}
|
||||
}
|
||||
Some("response.function_call_arguments.done") => {
|
||||
if let Some(tool_call) =
|
||||
tool_call_from_done_event(&value, &function_call_items, &mut finished_call_ids)
|
||||
{
|
||||
tool_calls.push(tool_call);
|
||||
}
|
||||
}
|
||||
Some("response.output_item.done") => {
|
||||
if let Some(tool_call) = tool_call_from_output_item(
|
||||
value.get("item"),
|
||||
&function_call_items,
|
||||
&mut finished_call_ids,
|
||||
) {
|
||||
tool_calls.push(tool_call);
|
||||
}
|
||||
}
|
||||
Some("response.completed") => {
|
||||
completed_response = value.get("response").cloned();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let Some(response) = completed_response else {
|
||||
return Ok(None);
|
||||
};
|
||||
if content.is_empty() {
|
||||
content = output_text_from_response(&response);
|
||||
}
|
||||
let mut message = json!({
|
||||
"role": "assistant",
|
||||
"content": if content.is_empty() && !tool_calls.is_empty() {
|
||||
Value::Null
|
||||
} else {
|
||||
Value::String(content)
|
||||
},
|
||||
});
|
||||
if include_reasoning && !reasoning.is_empty() {
|
||||
message["reasoning_content"] = Value::String(reasoning);
|
||||
}
|
||||
let has_tool_calls = !tool_calls.is_empty();
|
||||
if has_tool_calls {
|
||||
message["tool_calls"] = Value::Array(tool_calls);
|
||||
}
|
||||
|
||||
Ok(Some(json!({
|
||||
"id": format!("chatcmpl-{}", Uuid::new_v4().simple()),
|
||||
"object": "chat.completion",
|
||||
"created": Utc::now().timestamp(),
|
||||
"model": model,
|
||||
"choices": [{
|
||||
"index": 0,
|
||||
"message": message,
|
||||
"finish_reason": if has_tool_calls { "tool_calls" } else { "stop" },
|
||||
}],
|
||||
"usage": openai_usage(response.get("usage")),
|
||||
})))
|
||||
}
|
||||
|
||||
pub fn chat_completion_stream_from_codex_sse(
|
||||
body: &str,
|
||||
model: &str,
|
||||
include_reasoning: bool,
|
||||
) -> Result<Option<String>, SseError> {
|
||||
let events = parse_sse_events(body)?;
|
||||
let chunk_id = format!("chatcmpl-{}", Uuid::new_v4().simple());
|
||||
let created = Utc::now().timestamp();
|
||||
let mut output = String::new();
|
||||
let mut completed_response = None;
|
||||
let mut has_tool_calls = false;
|
||||
let mut function_call_items = BTreeMap::new();
|
||||
let mut tool_call_indices = BTreeMap::new();
|
||||
let mut call_ids_with_deltas = BTreeSet::new();
|
||||
let mut next_tool_call_index = 0usize;
|
||||
|
||||
push_sse_data(
|
||||
&mut output,
|
||||
json!({
|
||||
"id": chunk_id,
|
||||
"object": "chat.completion.chunk",
|
||||
"created": created,
|
||||
"model": model,
|
||||
"choices": [{
|
||||
"index": 0,
|
||||
"delta": {"role": "assistant"},
|
||||
"finish_reason": null,
|
||||
}],
|
||||
}),
|
||||
);
|
||||
|
||||
for event in events {
|
||||
let Ok(value) = serde_json::from_str::<Value>(&event.data) else {
|
||||
continue;
|
||||
};
|
||||
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,
|
||||
}],
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
Some("response.reasoning_summary_text.delta") if include_reasoning => {
|
||||
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": {"reasoning_content": delta},
|
||||
"finish_reason": null,
|
||||
}],
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
Some("response.output_item.added") => {
|
||||
if let Some((item_id, call_id, name)) = function_call_item(value.get("item")) {
|
||||
has_tool_calls = true;
|
||||
let index = next_tool_call_index;
|
||||
next_tool_call_index = next_tool_call_index.saturating_add(1);
|
||||
function_call_items.insert(
|
||||
item_id,
|
||||
FunctionCallInfo {
|
||||
call_id: call_id.clone(),
|
||||
name: name.clone(),
|
||||
},
|
||||
);
|
||||
tool_call_indices.insert(call_id.clone(), index);
|
||||
push_sse_data(
|
||||
&mut output,
|
||||
json!({
|
||||
"id": chunk_id,
|
||||
"object": "chat.completion.chunk",
|
||||
"created": created,
|
||||
"model": model,
|
||||
"choices": [{
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"tool_calls": [{
|
||||
"index": index,
|
||||
"id": call_id,
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": name,
|
||||
"arguments": "",
|
||||
},
|
||||
}],
|
||||
},
|
||||
"finish_reason": null,
|
||||
}],
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
Some("response.function_call_arguments.delta") => {
|
||||
if let Some((call_id, index, delta)) =
|
||||
stream_tool_call_delta(&value, &function_call_items, &tool_call_indices)
|
||||
{
|
||||
has_tool_calls = true;
|
||||
call_ids_with_deltas.insert(call_id);
|
||||
push_sse_data(
|
||||
&mut output,
|
||||
json!({
|
||||
"id": chunk_id,
|
||||
"object": "chat.completion.chunk",
|
||||
"created": created,
|
||||
"model": model,
|
||||
"choices": [{
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"tool_calls": [{
|
||||
"index": index,
|
||||
"function": {
|
||||
"arguments": delta,
|
||||
},
|
||||
}],
|
||||
},
|
||||
"finish_reason": null,
|
||||
}],
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
Some("response.function_call_arguments.done") => {
|
||||
if let Some((call_id, index, arguments)) = stream_tool_call_done(
|
||||
&value,
|
||||
&function_call_items,
|
||||
&tool_call_indices,
|
||||
&call_ids_with_deltas,
|
||||
) {
|
||||
has_tool_calls = true;
|
||||
push_sse_data(
|
||||
&mut output,
|
||||
json!({
|
||||
"id": chunk_id,
|
||||
"object": "chat.completion.chunk",
|
||||
"created": created,
|
||||
"model": model,
|
||||
"choices": [{
|
||||
"index": 0,
|
||||
"delta": {
|
||||
"tool_calls": [{
|
||||
"index": index,
|
||||
"function": {
|
||||
"arguments": arguments,
|
||||
},
|
||||
}],
|
||||
},
|
||||
"finish_reason": null,
|
||||
}],
|
||||
}),
|
||||
);
|
||||
call_ids_with_deltas.insert(call_id);
|
||||
}
|
||||
}
|
||||
Some("response.output_item.done") if is_function_call_item(value.get("item")) => {
|
||||
has_tool_calls = true;
|
||||
}
|
||||
Some("response.completed") => {
|
||||
completed_response = value.get("response").cloned();
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
let Some(response) = completed_response else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
push_sse_data(
|
||||
&mut output,
|
||||
json!({
|
||||
"id": chunk_id,
|
||||
"object": "chat.completion.chunk",
|
||||
"created": created,
|
||||
"model": model,
|
||||
"choices": [{
|
||||
"index": 0,
|
||||
"delta": {},
|
||||
"finish_reason": if has_tool_calls { "tool_calls" } else { "stop" },
|
||||
}],
|
||||
"usage": openai_usage(response.get("usage")),
|
||||
}),
|
||||
);
|
||||
output.push_str("data: [DONE]\n\n");
|
||||
|
||||
Ok(Some(output))
|
||||
}
|
||||
|
||||
fn output_text_from_response(response: &Value) -> String {
|
||||
response
|
||||
.get("output_text")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToString::to_string)
|
||||
.unwrap_or_else(|| {
|
||||
response
|
||||
.get("output")
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(output_text_from_item)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n\n")
|
||||
})
|
||||
.unwrap_or_default()
|
||||
})
|
||||
}
|
||||
|
||||
fn output_text_from_item(item: &Value) -> Option<String> {
|
||||
let content = item.get("content")?.as_array()?;
|
||||
let text = content
|
||||
.iter()
|
||||
.filter_map(|part| {
|
||||
let part_type = part.get("type")?.as_str()?;
|
||||
if part_type != "output_text" && part_type != "text" {
|
||||
return None;
|
||||
}
|
||||
part.get("text")?.as_str()
|
||||
})
|
||||
.collect::<String>();
|
||||
(!text.is_empty()).then_some(text)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct FunctionCallInfo {
|
||||
call_id: String,
|
||||
name: String,
|
||||
}
|
||||
|
||||
fn function_call_item(item: Option<&Value>) -> Option<(String, String, String)> {
|
||||
let item = item?;
|
||||
if item.get("type").and_then(Value::as_str) != Some("function_call") {
|
||||
return None;
|
||||
}
|
||||
let item_id = item.get("id").and_then(Value::as_str)?;
|
||||
let call_id = item.get("call_id").and_then(Value::as_str)?;
|
||||
let name = item.get("name").and_then(Value::as_str)?;
|
||||
Some((item_id.to_string(), call_id.to_string(), name.to_string()))
|
||||
}
|
||||
|
||||
fn tool_call_from_done_event(
|
||||
event: &Value,
|
||||
function_call_items: &BTreeMap<String, FunctionCallInfo>,
|
||||
finished_call_ids: &mut BTreeSet<String>,
|
||||
) -> Option<Value> {
|
||||
let event_id = event
|
||||
.get("call_id")
|
||||
.or_else(|| event.get("item_id"))
|
||||
.and_then(Value::as_str)?;
|
||||
let info = function_call_items.get(event_id);
|
||||
let call_id = info
|
||||
.map(|info| info.call_id.as_str())
|
||||
.unwrap_or(event_id)
|
||||
.to_string();
|
||||
if !finished_call_ids.insert(call_id.clone()) {
|
||||
return None;
|
||||
}
|
||||
let name = event
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|name| !name.is_empty())
|
||||
.or_else(|| info.map(|info| info.name.as_str()))
|
||||
.unwrap_or("unknown");
|
||||
let arguments = event
|
||||
.get("arguments")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
Some(openai_tool_call(call_id, name, arguments))
|
||||
}
|
||||
|
||||
fn tool_call_from_output_item(
|
||||
item: Option<&Value>,
|
||||
function_call_items: &BTreeMap<String, FunctionCallInfo>,
|
||||
finished_call_ids: &mut BTreeSet<String>,
|
||||
) -> Option<Value> {
|
||||
let item = item?;
|
||||
if item.get("type").and_then(Value::as_str) != Some("function_call") {
|
||||
return None;
|
||||
}
|
||||
let item_id = item.get("id").and_then(Value::as_str);
|
||||
let info = item_id.and_then(|item_id| function_call_items.get(item_id));
|
||||
let call_id = item
|
||||
.get("call_id")
|
||||
.and_then(Value::as_str)
|
||||
.or_else(|| info.map(|info| info.call_id.as_str()))
|
||||
.or(item_id)?;
|
||||
if !finished_call_ids.insert(call_id.to_string()) {
|
||||
return None;
|
||||
}
|
||||
let name = item
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|name| !name.is_empty())
|
||||
.or_else(|| info.map(|info| info.name.as_str()))
|
||||
.unwrap_or("unknown");
|
||||
let arguments = item
|
||||
.get("arguments")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
Some(openai_tool_call(call_id.to_string(), name, arguments))
|
||||
}
|
||||
|
||||
fn openai_tool_call(call_id: String, name: &str, arguments: &str) -> Value {
|
||||
json!({
|
||||
"id": call_id,
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": name,
|
||||
"arguments": arguments,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn stream_tool_call_delta(
|
||||
event: &Value,
|
||||
function_call_items: &BTreeMap<String, FunctionCallInfo>,
|
||||
tool_call_indices: &BTreeMap<String, usize>,
|
||||
) -> Option<(String, usize, String)> {
|
||||
let event_id = event
|
||||
.get("call_id")
|
||||
.or_else(|| event.get("item_id"))
|
||||
.and_then(Value::as_str)?;
|
||||
let info = function_call_items.get(event_id);
|
||||
let call_id = info
|
||||
.map(|info| info.call_id.as_str())
|
||||
.unwrap_or(event_id)
|
||||
.to_string();
|
||||
let index = *tool_call_indices.get(&call_id).unwrap_or(&0);
|
||||
let delta = event.get("delta").and_then(Value::as_str)?.to_string();
|
||||
Some((call_id, index, delta))
|
||||
}
|
||||
|
||||
fn stream_tool_call_done(
|
||||
event: &Value,
|
||||
function_call_items: &BTreeMap<String, FunctionCallInfo>,
|
||||
tool_call_indices: &BTreeMap<String, usize>,
|
||||
call_ids_with_deltas: &BTreeSet<String>,
|
||||
) -> Option<(String, usize, String)> {
|
||||
let event_id = event
|
||||
.get("call_id")
|
||||
.or_else(|| event.get("item_id"))
|
||||
.and_then(Value::as_str)?;
|
||||
let info = function_call_items.get(event_id);
|
||||
let call_id = info
|
||||
.map(|info| info.call_id.as_str())
|
||||
.unwrap_or(event_id)
|
||||
.to_string();
|
||||
if call_ids_with_deltas.contains(&call_id) {
|
||||
return None;
|
||||
}
|
||||
let index = *tool_call_indices.get(&call_id).unwrap_or(&0);
|
||||
let arguments = event
|
||||
.get("arguments")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.to_string();
|
||||
Some((call_id, index, arguments))
|
||||
}
|
||||
|
||||
fn push_sse_data(output: &mut String, value: Value) {
|
||||
output.push_str("data: ");
|
||||
output.push_str(&value.to_string());
|
||||
output.push_str("\n\n");
|
||||
}
|
||||
|
||||
fn is_function_call_item(item: Option<&Value>) -> bool {
|
||||
item.and_then(|item| item.get("type"))
|
||||
.and_then(Value::as_str)
|
||||
== Some("function_call")
|
||||
}
|
||||
|
||||
fn openai_usage(usage: Option<&Value>) -> Value {
|
||||
let prompt_tokens = usage
|
||||
.and_then(|usage| usage.get("input_tokens"))
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or_default();
|
||||
let completion_tokens = usage
|
||||
.and_then(|usage| usage.get("output_tokens"))
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or_default();
|
||||
let cached_tokens = usage
|
||||
.and_then(|usage| usage.get("input_tokens_details"))
|
||||
.and_then(|details| details.get("cached_tokens"))
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or_default();
|
||||
let reasoning_tokens = usage
|
||||
.and_then(|usage| usage.get("output_tokens_details"))
|
||||
.and_then(|details| details.get("reasoning_tokens"))
|
||||
.and_then(Value::as_u64);
|
||||
let mut openai_usage = json!({
|
||||
"prompt_tokens": prompt_tokens,
|
||||
"completion_tokens": completion_tokens,
|
||||
"total_tokens": prompt_tokens.saturating_add(completion_tokens),
|
||||
"prompt_tokens_details": {
|
||||
"cached_tokens": cached_tokens,
|
||||
},
|
||||
});
|
||||
if let Some(reasoning_tokens) = reasoning_tokens {
|
||||
openai_usage["completion_tokens_details"] = json!({
|
||||
"reasoning_tokens": reasoning_tokens,
|
||||
});
|
||||
}
|
||||
openai_usage
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
use axum::{
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
use serde::Serialize;
|
||||
use thiserror::Error;
|
||||
|
||||
pub type AppResult<T> = Result<T, AppError>;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum AppError {
|
||||
#[error("configuration error: {0}")]
|
||||
Config(String),
|
||||
#[error("database error: {0}")]
|
||||
Database(#[from] sqlx::Error),
|
||||
#[error("upstream error: {0}")]
|
||||
Upstream(String),
|
||||
#[error("unauthorized")]
|
||||
Unauthorized,
|
||||
#[error("forbidden")]
|
||||
Forbidden,
|
||||
#[error("bad request: {0}")]
|
||||
BadRequest(String),
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct ErrorBody<'a> {
|
||||
error: ErrorMessage<'a>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct ErrorMessage<'a> {
|
||||
message: &'a str,
|
||||
#[serde(rename = "type")]
|
||||
kind: &'a str,
|
||||
code: &'a str,
|
||||
}
|
||||
|
||||
impl IntoResponse for AppError {
|
||||
fn into_response(self) -> Response {
|
||||
let (status, code, kind) = match &self {
|
||||
Self::BadRequest(_) | Self::Config(_) => (
|
||||
StatusCode::BAD_REQUEST,
|
||||
"bad_request",
|
||||
"invalid_request_error",
|
||||
),
|
||||
Self::Unauthorized => (
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"unauthorized",
|
||||
"invalid_request_error",
|
||||
),
|
||||
Self::Forbidden => (StatusCode::FORBIDDEN, "forbidden", "invalid_request_error"),
|
||||
Self::Database(_) | Self::Upstream(_) => {
|
||||
(StatusCode::BAD_GATEWAY, "upstream_error", "server_error")
|
||||
}
|
||||
};
|
||||
|
||||
let message = self.to_string();
|
||||
let body = ErrorBody {
|
||||
error: ErrorMessage {
|
||||
message: &message,
|
||||
kind,
|
||||
code,
|
||||
},
|
||||
};
|
||||
|
||||
(status, Json(body)).into_response()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
pub mod codex_to_openai;
|
||||
pub mod error;
|
||||
pub mod openai_to_codex;
|
||||
pub mod schema;
|
||||
@@ -0,0 +1,268 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use crate::{
|
||||
codex::protocol::error::{AppError, AppResult},
|
||||
codex::transport::types::CodexResponsesRequest,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ChatCompletionRequest {
|
||||
pub model: String,
|
||||
#[serde(default)]
|
||||
pub stream: bool,
|
||||
pub messages: Vec<ChatMessage>,
|
||||
#[serde(default)]
|
||||
pub reasoning_effort: Option<String>,
|
||||
#[serde(default)]
|
||||
pub service_tier: Option<String>,
|
||||
#[serde(default)]
|
||||
pub tools: Option<Vec<Value>>,
|
||||
#[serde(default)]
|
||||
pub tool_choice: Option<Value>,
|
||||
#[serde(default)]
|
||||
pub parallel_tool_calls: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub functions: Option<Vec<Value>>,
|
||||
#[serde(default)]
|
||||
pub response_format: Option<Value>,
|
||||
#[serde(default)]
|
||||
pub user: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ChatMessage {
|
||||
pub role: String,
|
||||
#[serde(default)]
|
||||
pub content: Option<Value>,
|
||||
#[serde(default)]
|
||||
pub name: Option<String>,
|
||||
#[serde(default)]
|
||||
pub tool_calls: Option<Vec<Value>>,
|
||||
#[serde(default)]
|
||||
pub tool_call_id: Option<String>,
|
||||
#[serde(default)]
|
||||
pub function_call: Option<Value>,
|
||||
}
|
||||
|
||||
pub fn translate_chat_to_codex(req: ChatCompletionRequest) -> AppResult<CodexResponsesRequest> {
|
||||
if req.messages.is_empty() {
|
||||
return Err(AppError::BadRequest(
|
||||
"messages must not be empty".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let instructions = chat_instructions(&req.messages);
|
||||
let mut input = chat_input(req.messages);
|
||||
if input.is_empty() {
|
||||
input.push(json!({"role": "user", "content": ""}));
|
||||
}
|
||||
|
||||
let mut request = CodexResponsesRequest::new_http_sse(req.model, instructions, input);
|
||||
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);
|
||||
request.service_tier = req.service_tier;
|
||||
if let Some(effort) = req.reasoning_effort {
|
||||
request.reasoning = Some(json!({"effort": effort, "summary": "auto"}));
|
||||
}
|
||||
Ok(request)
|
||||
}
|
||||
|
||||
fn chat_instructions(messages: &[ChatMessage]) -> String {
|
||||
let instructions = messages
|
||||
.iter()
|
||||
.filter(|message| message.role == "system" || message.role == "developer")
|
||||
.map(|message| extract_text(&message.content))
|
||||
.filter(|text| !text.is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n\n");
|
||||
if instructions.is_empty() {
|
||||
"You are a helpful assistant.".to_string()
|
||||
} else {
|
||||
instructions
|
||||
}
|
||||
}
|
||||
|
||||
fn chat_input(messages: Vec<ChatMessage>) -> Vec<Value> {
|
||||
let mut input = Vec::new();
|
||||
for message in messages {
|
||||
match message.role.as_str() {
|
||||
"system" | "developer" => {}
|
||||
"assistant" => push_assistant_message(&mut input, message),
|
||||
"tool" => input.push(json!({
|
||||
"type": "function_call_output",
|
||||
"call_id": message.tool_call_id.unwrap_or_else(|| "unknown".to_string()),
|
||||
"output": extract_text(&message.content),
|
||||
})),
|
||||
"function" => input.push(json!({
|
||||
"type": "function_call_output",
|
||||
"call_id": format!("fc_{}", message.name.unwrap_or_else(|| "unknown".to_string())),
|
||||
"output": extract_text(&message.content),
|
||||
})),
|
||||
_ => input.push(json!({
|
||||
"role": "user",
|
||||
"content": extract_content(&message.content),
|
||||
})),
|
||||
}
|
||||
}
|
||||
input
|
||||
}
|
||||
|
||||
fn push_assistant_message(input: &mut Vec<Value>, message: ChatMessage) {
|
||||
let text = extract_text(&message.content);
|
||||
let has_tool_calls = message
|
||||
.tool_calls
|
||||
.as_ref()
|
||||
.is_some_and(|calls| !calls.is_empty());
|
||||
if !text.is_empty() || (!has_tool_calls && message.function_call.is_none()) {
|
||||
input.push(json!({"role": "assistant", "content": text}));
|
||||
}
|
||||
|
||||
if let Some(tool_calls) = message.tool_calls {
|
||||
for tool_call in tool_calls {
|
||||
let call_id = tool_call
|
||||
.get("id")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("unknown");
|
||||
let function = tool_call.get("function").unwrap_or(&Value::Null);
|
||||
let name = function
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("unknown");
|
||||
let arguments = function
|
||||
.get("arguments")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("");
|
||||
input.push(json!({
|
||||
"type": "function_call",
|
||||
"call_id": call_id,
|
||||
"name": name,
|
||||
"arguments": arguments,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(function_call) = message.function_call {
|
||||
let name = function_call
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("unknown");
|
||||
let arguments = function_call
|
||||
.get("arguments")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("");
|
||||
input.push(json!({
|
||||
"type": "function_call",
|
||||
"call_id": format!("fc_{name}"),
|
||||
"name": name,
|
||||
"arguments": arguments,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
fn extract_text(content: &Option<Value>) -> String {
|
||||
let Some(content) = content else {
|
||||
return String::new();
|
||||
};
|
||||
if let Some(text) = content.as_str() {
|
||||
return text.to_string();
|
||||
}
|
||||
let Some(parts) = content.as_array() else {
|
||||
return String::new();
|
||||
};
|
||||
parts
|
||||
.iter()
|
||||
.filter_map(|part| {
|
||||
(part.get("type").and_then(Value::as_str) == Some("text"))
|
||||
.then(|| part.get("text").and_then(Value::as_str))
|
||||
.flatten()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
fn extract_content(content: &Option<Value>) -> Value {
|
||||
let Some(content) = content else {
|
||||
return Value::String(String::new());
|
||||
};
|
||||
if content.as_str().is_some() {
|
||||
return content.clone();
|
||||
}
|
||||
let Some(parts) = content.as_array() else {
|
||||
return Value::String(String::new());
|
||||
};
|
||||
let has_image = parts
|
||||
.iter()
|
||||
.any(|part| part.get("type").and_then(Value::as_str) == Some("image_url"));
|
||||
if !has_image {
|
||||
return Value::String(extract_text(&Some(content.clone())));
|
||||
}
|
||||
let codex_parts = parts
|
||||
.iter()
|
||||
.filter_map(codex_content_part)
|
||||
.collect::<Vec<_>>();
|
||||
if codex_parts.is_empty() {
|
||||
Value::String(String::new())
|
||||
} else {
|
||||
Value::Array(codex_parts)
|
||||
}
|
||||
}
|
||||
|
||||
fn codex_content_part(part: &Value) -> Option<Value> {
|
||||
match part.get("type").and_then(Value::as_str)? {
|
||||
"text" => part
|
||||
.get("text")
|
||||
.and_then(Value::as_str)
|
||||
.map(|text| json!({"type": "input_text", "text": text})),
|
||||
"image_url" => image_url(part).map(|url| json!({"type": "input_image", "image_url": url})),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn image_url(part: &Value) -> Option<&str> {
|
||||
let image = part.get("image_url")?;
|
||||
image
|
||||
.as_str()
|
||||
.or_else(|| image.get("url").and_then(Value::as_str))
|
||||
}
|
||||
|
||||
fn codex_tools(tools: Option<Vec<Value>>, functions: Option<Vec<Value>>) -> Option<Vec<Value>> {
|
||||
if let Some(tools) = tools.filter(|tools| !tools.is_empty()) {
|
||||
return Some(tools);
|
||||
}
|
||||
functions
|
||||
.filter(|functions| !functions.is_empty())
|
||||
.map(|functions| {
|
||||
functions
|
||||
.into_iter()
|
||||
.map(|function| json!({"type": "function", "function": function}))
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
|
||||
fn response_format_text(response_format: Option<Value>) -> Option<Value> {
|
||||
let format = response_format?;
|
||||
let kind = format.get("type").and_then(Value::as_str)?;
|
||||
match kind {
|
||||
"json_object" => Some(json!({"format": {"type": "json_object"}})),
|
||||
"json_schema" => {
|
||||
let schema = format.get("json_schema")?;
|
||||
let name = schema
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("response");
|
||||
let mut codex_format = json!({
|
||||
"type": "json_schema",
|
||||
"name": name,
|
||||
"schema": schema.get("schema").cloned().unwrap_or_else(|| json!({})),
|
||||
});
|
||||
if let Some(strict) = schema.get("strict").and_then(Value::as_bool) {
|
||||
codex_format["strict"] = Value::Bool(strict);
|
||||
}
|
||||
Some(json!({"format": codex_format}))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ResponseFormat {
|
||||
Text,
|
||||
JsonObject,
|
||||
JsonSchema,
|
||||
}
|
||||
@@ -8,7 +8,9 @@ use serde_json::Value;
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::{
|
||||
codex::{
|
||||
codex::fingerprint::model::Fingerprint,
|
||||
codex::models::catalog::BackendModelEntry,
|
||||
codex::transport::{
|
||||
headers::build_codex_headers,
|
||||
sse::SseError,
|
||||
types::CodexResponsesRequest,
|
||||
@@ -18,8 +20,6 @@ use crate::{
|
||||
CodexTransport, CodexWebSocketError, WebSocketSupportError,
|
||||
},
|
||||
},
|
||||
fingerprint::model::Fingerprint,
|
||||
models::catalog::BackendModelEntry,
|
||||
};
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
@@ -1,6 +1,6 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::fingerprint::model::Fingerprint;
|
||||
use crate::codex::fingerprint::model::Fingerprint;
|
||||
|
||||
pub fn build_codex_headers(
|
||||
fp: &Fingerprint,
|
||||
@@ -0,0 +1,6 @@
|
||||
pub mod client;
|
||||
pub mod headers;
|
||||
pub mod sse;
|
||||
pub mod types;
|
||||
pub mod usage;
|
||||
pub mod websocket;
|
||||
@@ -1,7 +1,7 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::codex::sse::{parse_sse_events, SseError};
|
||||
use crate::codex::transport::sse::{parse_sse_events, SseError};
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -12,7 +12,7 @@ use futures::{SinkExt, StreamExt};
|
||||
use reqwest::{header::HeaderMap, StatusCode};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use crate::codex::{sse::encode_sse_event, types::CodexResponsesRequest};
|
||||
use crate::codex::transport::{sse::encode_sse_event, types::CodexResponsesRequest};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CodexTransport {
|
||||
@@ -0,0 +1,29 @@
|
||||
use axum::{http::StatusCode, Json};
|
||||
use reqwest::Url;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::codex::protocol::codex_to_openai::openai_error;
|
||||
|
||||
pub(crate) fn no_available_accounts_response() -> (StatusCode, Json<Value>) {
|
||||
(
|
||||
StatusCode::SERVICE_UNAVAILABLE,
|
||||
Json(openai_error(
|
||||
"No available Codex accounts",
|
||||
"no_available_accounts",
|
||||
)),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn normalize_service_tier_for_upstream(service_tier: String) -> String {
|
||||
if service_tier == "fast" {
|
||||
"priority".to_string()
|
||||
} else {
|
||||
service_tier
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn request_domain(base_url: &str) -> Option<String> {
|
||||
Url::parse(base_url)
|
||||
.ok()
|
||||
.and_then(|url| url.host_str().map(ToString::to_string))
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
use axum::http::StatusCode;
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use crate::codex::transport::client::CodexClientError;
|
||||
|
||||
const DEFAULT_RATE_LIMIT_BACKOFF_SECONDS: u64 = 60;
|
||||
const MAX_RATE_LIMIT_BACKOFF_SECONDS: u64 = 86_400 * 7;
|
||||
const CLOUDFLARE_CHALLENGE_COOLDOWN_SECONDS: u64 = 10;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) enum UpstreamAccountRetry {
|
||||
RateLimited { retry_after_seconds: u64 },
|
||||
QuotaExhausted,
|
||||
CloudflareChallenge { cooldown_seconds: u64 },
|
||||
Banned,
|
||||
}
|
||||
|
||||
impl UpstreamAccountRetry {
|
||||
pub(crate) fn status(self) -> StatusCode {
|
||||
match self {
|
||||
Self::RateLimited { .. } => StatusCode::TOO_MANY_REQUESTS,
|
||||
Self::QuotaExhausted => StatusCode::PAYMENT_REQUIRED,
|
||||
Self::CloudflareChallenge { .. } => StatusCode::FORBIDDEN,
|
||||
Self::Banned => StatusCode::FORBIDDEN,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn metadata(self, stream: bool) -> Value {
|
||||
match self {
|
||||
Self::RateLimited {
|
||||
retry_after_seconds,
|
||||
} => json!({
|
||||
"stream": stream,
|
||||
"retry": true,
|
||||
"reason": "rateLimited",
|
||||
"retryAfterSeconds": retry_after_seconds,
|
||||
}),
|
||||
Self::QuotaExhausted => json!({
|
||||
"stream": stream,
|
||||
"retry": true,
|
||||
"reason": "quotaExhausted",
|
||||
}),
|
||||
Self::CloudflareChallenge { cooldown_seconds } => json!({
|
||||
"stream": stream,
|
||||
"retry": true,
|
||||
"reason": "cloudflareChallenge",
|
||||
"cooldownSeconds": cooldown_seconds,
|
||||
}),
|
||||
Self::Banned => json!({
|
||||
"stream": stream,
|
||||
"retry": true,
|
||||
"reason": "banned",
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn classify_upstream_account_retry(
|
||||
error: &CodexClientError,
|
||||
) -> Option<UpstreamAccountRetry> {
|
||||
match error {
|
||||
CodexClientError::Upstream {
|
||||
status,
|
||||
retry_after_seconds,
|
||||
..
|
||||
} if *status == StatusCode::TOO_MANY_REQUESTS => Some(UpstreamAccountRetry::RateLimited {
|
||||
retry_after_seconds: retry_after_seconds
|
||||
.unwrap_or(DEFAULT_RATE_LIMIT_BACKOFF_SECONDS)
|
||||
.min(MAX_RATE_LIMIT_BACKOFF_SECONDS),
|
||||
}),
|
||||
CodexClientError::Upstream { status, .. } if *status == StatusCode::PAYMENT_REQUIRED => {
|
||||
Some(UpstreamAccountRetry::QuotaExhausted)
|
||||
}
|
||||
CodexClientError::Upstream { status, body, .. } if *status == StatusCode::FORBIDDEN => {
|
||||
if is_cloudflare_challenge(body) {
|
||||
Some(UpstreamAccountRetry::CloudflareChallenge {
|
||||
cooldown_seconds: CLOUDFLARE_CHALLENGE_COOLDOWN_SECONDS,
|
||||
})
|
||||
} else {
|
||||
Some(UpstreamAccountRetry::Banned)
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn websocket_history_retry_metadata(retry: UpstreamAccountRetry, stream: bool) -> Value {
|
||||
match retry {
|
||||
UpstreamAccountRetry::RateLimited {
|
||||
retry_after_seconds,
|
||||
} => json!({
|
||||
"stream": stream,
|
||||
"transport": "websocket",
|
||||
"retry": false,
|
||||
"reason": "rateLimited",
|
||||
"retryAfterSeconds": retry_after_seconds,
|
||||
"accountAffinity": "previousResponseId",
|
||||
}),
|
||||
UpstreamAccountRetry::QuotaExhausted => json!({
|
||||
"stream": stream,
|
||||
"transport": "websocket",
|
||||
"retry": false,
|
||||
"reason": "quotaExhausted",
|
||||
"accountAffinity": "previousResponseId",
|
||||
}),
|
||||
UpstreamAccountRetry::CloudflareChallenge { cooldown_seconds } => json!({
|
||||
"stream": stream,
|
||||
"transport": "websocket",
|
||||
"retry": false,
|
||||
"reason": "cloudflareChallenge",
|
||||
"cooldownSeconds": cooldown_seconds,
|
||||
"accountAffinity": "previousResponseId",
|
||||
}),
|
||||
UpstreamAccountRetry::Banned => json!({
|
||||
"stream": stream,
|
||||
"transport": "websocket",
|
||||
"retry": false,
|
||||
"reason": "banned",
|
||||
"accountAffinity": "previousResponseId",
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_cloudflare_challenge(body: &str) -> bool {
|
||||
let lower = body.to_ascii_lowercase();
|
||||
lower.contains("cf-mitigated")
|
||||
|| lower.contains("cf-chl-bypass")
|
||||
|| lower.contains("_cf_chl")
|
||||
|| lower.contains("cf_chl")
|
||||
|| lower.contains("attention required")
|
||||
|| lower.contains("just a moment")
|
||||
}
|
||||
@@ -0,0 +1,859 @@
|
||||
pub mod dispatch;
|
||||
pub mod fallback;
|
||||
pub mod refresh;
|
||||
pub mod stream;
|
||||
pub mod usage;
|
||||
|
||||
use std::{sync::Arc, time::Instant};
|
||||
|
||||
use axum::{
|
||||
body::Body,
|
||||
http::{
|
||||
header::{CACHE_CONTROL, CONTENT_TYPE},
|
||||
StatusCode,
|
||||
},
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
use chrono::{Duration, Utc};
|
||||
use futures::{stream as futures_stream, StreamExt};
|
||||
use serde_json::{json, Value};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::{
|
||||
codex::accounts::{
|
||||
model::{Account, AccountStatus},
|
||||
pool::{AccountAcquireRequest, AccountPool},
|
||||
repository::AccountRepository,
|
||||
},
|
||||
codex::cookies::repository::CookieRepository,
|
||||
codex::fingerprint::model::Fingerprint,
|
||||
codex::oauth::TokenRefresher,
|
||||
codex::protocol::codex_to_openai::openai_error,
|
||||
codex::transport::{
|
||||
client::{
|
||||
build_reqwest_client, CodexBackendClient, CodexBackendStream, CodexClientError,
|
||||
CodexRequestContext,
|
||||
},
|
||||
types::CodexResponsesRequest,
|
||||
usage::{extract_sse_usage, TokenUsage},
|
||||
websocket::{transport_for_request, CodexTransport},
|
||||
},
|
||||
config::AppConfig,
|
||||
logs::event::{EventLevel, EventLog},
|
||||
logs::repository::EventLogRepository,
|
||||
};
|
||||
|
||||
use crate::http::v1::errors::codex_client_error_response;
|
||||
|
||||
pub(crate) use self::{
|
||||
dispatch::{no_available_accounts_response, normalize_service_tier_for_upstream},
|
||||
fallback::{
|
||||
classify_upstream_account_retry, websocket_history_retry_metadata, UpstreamAccountRetry,
|
||||
},
|
||||
stream::{completed_response_json, CollectedResponse},
|
||||
};
|
||||
|
||||
use self::{
|
||||
dispatch::request_domain,
|
||||
refresh::refresh_account_after_unauthorized,
|
||||
stream::{ensure_stream_metadata, responses_sse_failure},
|
||||
usage::{record_request_attempt, record_usage_with_deps},
|
||||
};
|
||||
|
||||
#[derive(Clone)]
|
||||
struct CodexUpstreamDependencies {
|
||||
config: AppConfig,
|
||||
account_pool: Arc<Mutex<AccountPool>>,
|
||||
account_repository: Option<AccountRepository>,
|
||||
cookie_repository: Option<CookieRepository>,
|
||||
event_logs: Option<EventLogRepository>,
|
||||
token_refresher: Option<Arc<dyn TokenRefresher>>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct CodexUpstreamService {
|
||||
deps: CodexUpstreamDependencies,
|
||||
}
|
||||
|
||||
impl CodexUpstreamService {
|
||||
pub(crate) fn new(
|
||||
config: AppConfig,
|
||||
account_pool: Arc<Mutex<AccountPool>>,
|
||||
account_repository: Option<AccountRepository>,
|
||||
cookie_repository: Option<CookieRepository>,
|
||||
event_logs: Option<EventLogRepository>,
|
||||
token_refresher: Option<Arc<dyn TokenRefresher>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
deps: CodexUpstreamDependencies {
|
||||
config,
|
||||
account_pool,
|
||||
account_repository,
|
||||
cookie_repository,
|
||||
event_logs,
|
||||
token_refresher,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn acquire_account(&self, model: &str) -> Option<Account> {
|
||||
self.deps
|
||||
.account_pool
|
||||
.lock()
|
||||
.await
|
||||
.acquire_with(AccountAcquireRequest::new(model, Utc::now()))
|
||||
.map(|acquired| acquired.account)
|
||||
}
|
||||
|
||||
pub(crate) async fn release_account(&self, account_id: &str) {
|
||||
self.deps.account_pool.lock().await.release(account_id);
|
||||
}
|
||||
|
||||
pub(crate) async fn send_codex_request_with_refresh_retry(
|
||||
&self,
|
||||
request: &CodexResponsesRequest,
|
||||
account: &Account,
|
||||
request_id: &str,
|
||||
) -> Result<crate::codex::transport::client::CodexBackendResponse, CodexClientError> {
|
||||
send_codex_request_with_refresh_retry_deps(&self.deps, request, account, request_id).await
|
||||
}
|
||||
|
||||
pub(crate) async fn apply_retry_and_acquire_fallback(
|
||||
&self,
|
||||
account: &Account,
|
||||
retry: UpstreamAccountRetry,
|
||||
model: &str,
|
||||
excluded_account_ids: &mut Vec<String>,
|
||||
) -> Option<Account> {
|
||||
apply_upstream_retry_and_acquire_fallback_with_deps(
|
||||
&self.deps,
|
||||
account,
|
||||
retry,
|
||||
model,
|
||||
excluded_account_ids,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn apply_account_retry(&self, account: &Account, retry: UpstreamAccountRetry) {
|
||||
apply_upstream_account_retry_with_deps(&self.deps, account, retry).await;
|
||||
}
|
||||
|
||||
pub(crate) async fn responses_stream(
|
||||
&self,
|
||||
request: CodexResponsesRequest,
|
||||
mut account: Account,
|
||||
mut log_context: CodexRequestLogContext,
|
||||
) -> Response {
|
||||
let deps = self.deps.clone();
|
||||
if transport_for_request(&request) == CodexTransport::WebSocketRequired {
|
||||
return responses_websocket_stream(deps, request, account, log_context).await;
|
||||
}
|
||||
|
||||
let mut excluded_account_ids = Vec::new();
|
||||
let stream_response = loop {
|
||||
let stream_response = send_codex_stream_request_with_refresh_retry(
|
||||
&deps,
|
||||
&request,
|
||||
&account,
|
||||
log_context.request_id.as_str(),
|
||||
)
|
||||
.await;
|
||||
match stream_response {
|
||||
Ok(response) => break response,
|
||||
Err(error) => {
|
||||
deps.account_pool.lock().await.release(&account.id);
|
||||
if let Some(retry) = classify_upstream_account_retry(&error) {
|
||||
let fallback = apply_upstream_retry_and_acquire_fallback_with_deps(
|
||||
&deps,
|
||||
&account,
|
||||
retry,
|
||||
&request.model,
|
||||
&mut excluded_account_ids,
|
||||
)
|
||||
.await;
|
||||
log_codex_upstream_response_with_deps(
|
||||
&deps,
|
||||
&log_context,
|
||||
retry.status(),
|
||||
EventLevel::Warn,
|
||||
"v1 responses stream upstream retrying with fallback account",
|
||||
retry.metadata(true),
|
||||
)
|
||||
.await;
|
||||
if let Some(fallback) = fallback {
|
||||
account = fallback;
|
||||
log_context = log_context.with_account(&account.id);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let error_response = codex_client_error_response(error);
|
||||
log_codex_upstream_response_with_deps(
|
||||
&deps,
|
||||
&log_context,
|
||||
error_response.0,
|
||||
EventLevel::Error,
|
||||
"v1 responses stream upstream request failed",
|
||||
json!({"stream": true}),
|
||||
)
|
||||
.await;
|
||||
return error_response.into_response();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if persist_upstream_cookies_with_deps(
|
||||
&deps,
|
||||
&account.id,
|
||||
&stream_response.set_cookie_headers,
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
deps.account_pool.lock().await.release(&account.id);
|
||||
log_codex_upstream_response_with_deps(
|
||||
&deps,
|
||||
&log_context,
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
EventLevel::Error,
|
||||
"v1 responses stream cookie persistence failed",
|
||||
json!({"stream": true, "cookieStoreError": true}),
|
||||
)
|
||||
.await;
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(openai_error(
|
||||
"Failed to persist upstream cookies",
|
||||
"cookie_store_error",
|
||||
)),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
|
||||
let upstream = Box::pin(stream_response.response.bytes_stream());
|
||||
let audit = StreamAudit::new(deps, log_context, account.id);
|
||||
let body_stream =
|
||||
futures_stream::unfold(Some((upstream, Vec::new(), audit)), |state| async move {
|
||||
let (mut upstream, mut collected, mut audit) = state?;
|
||||
match upstream.next().await {
|
||||
Some(Ok(chunk)) => {
|
||||
collected.extend_from_slice(&chunk);
|
||||
Some((Ok(chunk), Some((upstream, collected, audit))))
|
||||
}
|
||||
Some(Err(error)) => {
|
||||
audit.log_transport_error(&error).await;
|
||||
Some((Err(error), None))
|
||||
}
|
||||
None => {
|
||||
audit.complete(&collected).await;
|
||||
None
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header(CONTENT_TYPE, "text/event-stream")
|
||||
.header(CACHE_CONTROL, "no-cache")
|
||||
.body(Body::from_stream(body_stream))
|
||||
.unwrap_or_else(|_| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(openai_error(
|
||||
"Failed to build stream response",
|
||||
"stream_response_error",
|
||||
)),
|
||||
)
|
||||
.into_response()
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn persist_cookies(
|
||||
&self,
|
||||
account_id: &str,
|
||||
set_cookie_headers: &[String],
|
||||
) -> Result<(), ()> {
|
||||
persist_upstream_cookies_with_deps(&self.deps, account_id, set_cookie_headers).await
|
||||
}
|
||||
|
||||
pub(crate) async fn record_usage(&self, account_id: &str, usage: TokenUsage) -> Result<(), ()> {
|
||||
record_usage_with_deps(&self.deps, account_id, usage).await
|
||||
}
|
||||
|
||||
pub(crate) async fn log_response(
|
||||
&self,
|
||||
context: &CodexRequestLogContext,
|
||||
status: StatusCode,
|
||||
level: EventLevel,
|
||||
message: &str,
|
||||
metadata: Value,
|
||||
) {
|
||||
log_codex_upstream_response_with_deps(
|
||||
&self.deps, context, status, level, message, metadata,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_codex_request_with_refresh_retry_deps(
|
||||
deps: &CodexUpstreamDependencies,
|
||||
request: &CodexResponsesRequest,
|
||||
account: &Account,
|
||||
request_id: &str,
|
||||
) -> Result<crate::codex::transport::client::CodexBackendResponse, CodexClientError> {
|
||||
match send_codex_request(deps, request, account, request_id).await {
|
||||
Err(CodexClientError::Upstream {
|
||||
status,
|
||||
body,
|
||||
retry_after_seconds,
|
||||
}) if status == StatusCode::UNAUTHORIZED => {
|
||||
let Some(refreshed) =
|
||||
refresh_account_after_unauthorized(deps, request, account, request_id).await
|
||||
else {
|
||||
return Err(CodexClientError::Upstream {
|
||||
status,
|
||||
body,
|
||||
retry_after_seconds,
|
||||
});
|
||||
};
|
||||
send_codex_request(deps, request, &refreshed, request_id).await
|
||||
}
|
||||
result => result,
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_codex_request(
|
||||
deps: &CodexUpstreamDependencies,
|
||||
request: &CodexResponsesRequest,
|
||||
account: &Account,
|
||||
request_id: &str,
|
||||
) -> Result<crate::codex::transport::client::CodexBackendResponse, CodexClientError> {
|
||||
let request_domain = request_domain(&deps.config.api.base_url);
|
||||
let cookie_header = match (deps.cookie_repository.as_ref(), request_domain.as_deref()) {
|
||||
(Some(repo), Some(domain)) => repo.cookie_header(&account.id, domain).await.ok().flatten(),
|
||||
_ => None,
|
||||
};
|
||||
let client = CodexBackendClient::new(
|
||||
build_reqwest_client(deps.config.tls.force_http11)?,
|
||||
deps.config.api.base_url.clone(),
|
||||
Fingerprint::default_codex_desktop(),
|
||||
);
|
||||
client
|
||||
.create_response(
|
||||
request,
|
||||
CodexRequestContext {
|
||||
access_token: &account.access_token,
|
||||
account_id: account.account_id.as_deref(),
|
||||
request_id,
|
||||
turn_state: request.turn_state.as_deref(),
|
||||
turn_metadata: request.turn_metadata.as_deref(),
|
||||
beta_features: request.beta_features.as_deref(),
|
||||
include_timing_metrics: request.include_timing_metrics.as_deref(),
|
||||
version: request.version.as_deref(),
|
||||
codex_window_id: request.codex_window_id.as_deref(),
|
||||
parent_thread_id: request.parent_thread_id.as_deref(),
|
||||
cookie_header: cookie_header.as_deref(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn send_codex_stream_request_with_refresh_retry(
|
||||
deps: &CodexUpstreamDependencies,
|
||||
request: &CodexResponsesRequest,
|
||||
account: &Account,
|
||||
request_id: &str,
|
||||
) -> Result<CodexBackendStream, CodexClientError> {
|
||||
match send_codex_stream_request(deps, request, account, request_id).await {
|
||||
Err(CodexClientError::Upstream {
|
||||
status,
|
||||
body,
|
||||
retry_after_seconds,
|
||||
}) if status == StatusCode::UNAUTHORIZED => {
|
||||
let Some(refreshed) =
|
||||
refresh_account_after_unauthorized(deps, request, account, request_id).await
|
||||
else {
|
||||
return Err(CodexClientError::Upstream {
|
||||
status,
|
||||
body,
|
||||
retry_after_seconds,
|
||||
});
|
||||
};
|
||||
send_codex_stream_request(deps, request, &refreshed, request_id).await
|
||||
}
|
||||
result => result,
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_codex_stream_request(
|
||||
deps: &CodexUpstreamDependencies,
|
||||
request: &CodexResponsesRequest,
|
||||
account: &Account,
|
||||
request_id: &str,
|
||||
) -> Result<CodexBackendStream, CodexClientError> {
|
||||
let request_domain = request_domain(&deps.config.api.base_url);
|
||||
let cookie_header = match (deps.cookie_repository.as_ref(), request_domain.as_deref()) {
|
||||
(Some(repo), Some(domain)) => repo.cookie_header(&account.id, domain).await.ok().flatten(),
|
||||
_ => None,
|
||||
};
|
||||
let client = CodexBackendClient::new(
|
||||
build_reqwest_client(deps.config.tls.force_http11)?,
|
||||
deps.config.api.base_url.clone(),
|
||||
Fingerprint::default_codex_desktop(),
|
||||
);
|
||||
client
|
||||
.stream_response(
|
||||
request,
|
||||
CodexRequestContext {
|
||||
access_token: &account.access_token,
|
||||
account_id: account.account_id.as_deref(),
|
||||
request_id,
|
||||
turn_state: request.turn_state.as_deref(),
|
||||
turn_metadata: request.turn_metadata.as_deref(),
|
||||
beta_features: request.beta_features.as_deref(),
|
||||
include_timing_metrics: request.include_timing_metrics.as_deref(),
|
||||
version: request.version.as_deref(),
|
||||
codex_window_id: request.codex_window_id.as_deref(),
|
||||
parent_thread_id: request.parent_thread_id.as_deref(),
|
||||
cookie_header: cookie_header.as_deref(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn apply_upstream_retry_and_acquire_fallback_with_deps(
|
||||
deps: &CodexUpstreamDependencies,
|
||||
account: &Account,
|
||||
retry: UpstreamAccountRetry,
|
||||
model: &str,
|
||||
excluded_account_ids: &mut Vec<String>,
|
||||
) -> Option<Account> {
|
||||
apply_upstream_account_retry_with_deps(deps, account, retry).await;
|
||||
excluded_account_ids.push(account.id.clone());
|
||||
deps.account_pool
|
||||
.lock()
|
||||
.await
|
||||
.acquire_with(
|
||||
AccountAcquireRequest::new(model, Utc::now())
|
||||
.with_exclude_account_ids(excluded_account_ids.iter().cloned()),
|
||||
)
|
||||
.map(|fallback| fallback.account)
|
||||
}
|
||||
|
||||
async fn apply_upstream_account_retry_with_deps(
|
||||
deps: &CodexUpstreamDependencies,
|
||||
account: &Account,
|
||||
retry: UpstreamAccountRetry,
|
||||
) {
|
||||
match retry {
|
||||
UpstreamAccountRetry::RateLimited {
|
||||
retry_after_seconds,
|
||||
} => {
|
||||
let cooldown_until = Utc::now() + Duration::seconds(retry_after_seconds as i64);
|
||||
deps.account_pool
|
||||
.lock()
|
||||
.await
|
||||
.mark_quota_limited_until(&account.id, cooldown_until);
|
||||
if record_request_attempt(deps, &account.id).await.is_err() {
|
||||
tracing::warn!(
|
||||
account_id = %account.id,
|
||||
"failed to record rate-limited account attempt"
|
||||
);
|
||||
}
|
||||
}
|
||||
UpstreamAccountRetry::QuotaExhausted => {
|
||||
set_account_status(deps, account, AccountStatus::QuotaExhausted).await;
|
||||
}
|
||||
UpstreamAccountRetry::CloudflareChallenge { cooldown_seconds } => {
|
||||
let cooldown_until = Utc::now() + Duration::seconds(cooldown_seconds as i64);
|
||||
deps.account_pool
|
||||
.lock()
|
||||
.await
|
||||
.set_cloudflare_cooldown_until(&account.id, cooldown_until);
|
||||
}
|
||||
UpstreamAccountRetry::Banned => {
|
||||
set_account_status(deps, account, AccountStatus::Banned).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn set_account_status(
|
||||
deps: &CodexUpstreamDependencies,
|
||||
account: &Account,
|
||||
status: AccountStatus,
|
||||
) {
|
||||
if let Some(repo) = deps.account_repository.as_ref() {
|
||||
if repo.set_status(&account.id, status).await.is_err() {
|
||||
tracing::warn!(
|
||||
account_id = %account.id,
|
||||
"failed to persist upstream account status"
|
||||
);
|
||||
}
|
||||
}
|
||||
deps.account_pool
|
||||
.lock()
|
||||
.await
|
||||
.set_status(&account.id, status);
|
||||
}
|
||||
|
||||
async fn responses_websocket_stream(
|
||||
deps: CodexUpstreamDependencies,
|
||||
request: CodexResponsesRequest,
|
||||
mut account: Account,
|
||||
mut log_context: CodexRequestLogContext,
|
||||
) -> Response {
|
||||
let mut excluded_account_ids = Vec::new();
|
||||
let response = loop {
|
||||
let response = send_codex_request_with_refresh_retry_deps(
|
||||
&deps,
|
||||
&request,
|
||||
&account,
|
||||
log_context.request_id.as_str(),
|
||||
)
|
||||
.await;
|
||||
deps.account_pool.lock().await.release(&account.id);
|
||||
|
||||
match response {
|
||||
Ok(response) => break response,
|
||||
Err(error) => {
|
||||
if let Some(retry) = classify_upstream_account_retry(&error) {
|
||||
if request.previous_response_id.is_some() {
|
||||
// previous_response_id 的历史由上游账号持有,换账号会静默丢失会话上下文。
|
||||
apply_upstream_account_retry_with_deps(&deps, &account, retry).await;
|
||||
log_codex_upstream_response_with_deps(
|
||||
&deps,
|
||||
&log_context,
|
||||
retry.status(),
|
||||
EventLevel::Warn,
|
||||
"v1 responses websocket history request kept on original account",
|
||||
websocket_history_retry_metadata(retry, true),
|
||||
)
|
||||
.await;
|
||||
} else {
|
||||
let fallback = apply_upstream_retry_and_acquire_fallback_with_deps(
|
||||
&deps,
|
||||
&account,
|
||||
retry,
|
||||
&request.model,
|
||||
&mut excluded_account_ids,
|
||||
)
|
||||
.await;
|
||||
log_codex_upstream_response_with_deps(
|
||||
&deps,
|
||||
&log_context,
|
||||
retry.status(),
|
||||
EventLevel::Warn,
|
||||
"v1 responses websocket upstream retrying with fallback account",
|
||||
retry.metadata(true),
|
||||
)
|
||||
.await;
|
||||
if let Some(fallback) = fallback {
|
||||
account = fallback;
|
||||
log_context = log_context.with_account(&account.id);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
let error_response = codex_client_error_response(error);
|
||||
log_codex_upstream_response_with_deps(
|
||||
&deps,
|
||||
&log_context,
|
||||
error_response.0,
|
||||
EventLevel::Error,
|
||||
"v1 responses websocket stream upstream request failed",
|
||||
json!({"stream": true, "transport": "websocket"}),
|
||||
)
|
||||
.await;
|
||||
return error_response.into_response();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if persist_upstream_cookies_with_deps(&deps, &account.id, &response.set_cookie_headers)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
log_codex_upstream_response_with_deps(
|
||||
&deps,
|
||||
&log_context,
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
EventLevel::Error,
|
||||
"v1 responses websocket stream cookie persistence failed",
|
||||
json!({"stream": true, "transport": "websocket", "cookieStoreError": true}),
|
||||
)
|
||||
.await;
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(openai_error(
|
||||
"Failed to persist upstream cookies",
|
||||
"cookie_store_error",
|
||||
)),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
|
||||
let rate_limit_headers = response.rate_limit_headers.clone();
|
||||
let mut level = EventLevel::Info;
|
||||
let mut message = "v1 responses websocket stream completed";
|
||||
let mut metadata = json!({
|
||||
"stream": true,
|
||||
"transport": "websocket",
|
||||
"usage": response.usage,
|
||||
"rateLimitHeaders": rate_limit_headers.clone(),
|
||||
});
|
||||
if let Some(usage) = response.usage {
|
||||
if record_usage_with_deps(&deps, &account.id, usage)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
level = EventLevel::Warn;
|
||||
message = "v1 responses websocket stream completed with usage store error";
|
||||
metadata = json!({
|
||||
"stream": true,
|
||||
"transport": "websocket",
|
||||
"usage": usage,
|
||||
"rateLimitHeaders": rate_limit_headers.clone(),
|
||||
"usageStoreError": true,
|
||||
});
|
||||
}
|
||||
}
|
||||
log_codex_upstream_response_with_deps(
|
||||
&deps,
|
||||
&log_context,
|
||||
StatusCode::OK,
|
||||
level,
|
||||
message,
|
||||
metadata,
|
||||
)
|
||||
.await;
|
||||
|
||||
Response::builder()
|
||||
.status(StatusCode::OK)
|
||||
.header(CONTENT_TYPE, "text/event-stream")
|
||||
.header(CACHE_CONTROL, "no-cache")
|
||||
.body(Body::from(response.body))
|
||||
.unwrap_or_else(|_| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
Json(openai_error(
|
||||
"Failed to build stream response",
|
||||
"stream_response_error",
|
||||
)),
|
||||
)
|
||||
.into_response()
|
||||
})
|
||||
}
|
||||
|
||||
async fn persist_upstream_cookies_with_deps(
|
||||
deps: &CodexUpstreamDependencies,
|
||||
account_id: &str,
|
||||
set_cookie_headers: &[String],
|
||||
) -> Result<(), ()> {
|
||||
let Some(cookie_repo) = deps.cookie_repository.as_ref() else {
|
||||
return Ok(());
|
||||
};
|
||||
for cookie in set_cookie_headers {
|
||||
cookie_repo
|
||||
.capture_set_cookie(account_id, cookie)
|
||||
.await
|
||||
.map_err(|_| ())?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct CodexRequestLogContext {
|
||||
request_id: String,
|
||||
account_id: String,
|
||||
model: String,
|
||||
stream: bool,
|
||||
started_at: Instant,
|
||||
}
|
||||
|
||||
impl CodexRequestLogContext {
|
||||
pub(crate) fn new(
|
||||
request_id: &str,
|
||||
account_id: &str,
|
||||
model: &str,
|
||||
stream: bool,
|
||||
started_at: Instant,
|
||||
) -> Self {
|
||||
Self {
|
||||
request_id: request_id.to_string(),
|
||||
account_id: account_id.to_string(),
|
||||
model: model.to_string(),
|
||||
stream,
|
||||
started_at,
|
||||
}
|
||||
}
|
||||
|
||||
fn latency_ms(&self) -> i64 {
|
||||
self.started_at.elapsed().as_millis().min(i64::MAX as u128) as i64
|
||||
}
|
||||
|
||||
pub(crate) fn with_account(&self, account_id: &str) -> Self {
|
||||
Self {
|
||||
request_id: self.request_id.clone(),
|
||||
account_id: account_id.to_string(),
|
||||
model: self.model.clone(),
|
||||
stream: self.stream,
|
||||
started_at: self.started_at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct StreamAudit {
|
||||
deps: CodexUpstreamDependencies,
|
||||
context: CodexRequestLogContext,
|
||||
account_slot: AccountSlotGuard,
|
||||
}
|
||||
|
||||
impl StreamAudit {
|
||||
fn new(
|
||||
deps: CodexUpstreamDependencies,
|
||||
context: CodexRequestLogContext,
|
||||
account_id: String,
|
||||
) -> Self {
|
||||
let account_slot = AccountSlotGuard::new(deps.account_pool.clone(), account_id);
|
||||
Self {
|
||||
deps,
|
||||
context,
|
||||
account_slot,
|
||||
}
|
||||
}
|
||||
|
||||
async fn complete(&mut self, body: &[u8]) {
|
||||
let body = String::from_utf8_lossy(body);
|
||||
let mut status = StatusCode::OK;
|
||||
let mut level = EventLevel::Info;
|
||||
let mut message = "v1 responses stream completed";
|
||||
let mut metadata = match extract_sse_usage(&body) {
|
||||
Ok(usage) => {
|
||||
if let Some(usage) = usage {
|
||||
if record_usage_with_deps(&self.deps, &self.context.account_id, usage)
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
level = EventLevel::Warn;
|
||||
message = "v1 responses stream completed with usage store error";
|
||||
json!({"stream": true, "usage": usage, "usageStoreError": true})
|
||||
} else {
|
||||
json!({"stream": true, "usage": usage})
|
||||
}
|
||||
} else {
|
||||
json!({"stream": true, "usage": null})
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
level = EventLevel::Warn;
|
||||
message = "v1 responses stream completed with invalid SSE usage";
|
||||
json!({"stream": true, "sseParseError": error.to_string()})
|
||||
}
|
||||
};
|
||||
match responses_sse_failure(&body) {
|
||||
Ok(Some(failure)) => {
|
||||
// SSE 响应头已发出,HTTP 状态不能回滚;用终止事件透传给客户端,并在审计里标记上游失败。
|
||||
status = StatusCode::BAD_GATEWAY;
|
||||
level = EventLevel::Error;
|
||||
message = "v1 responses stream upstream SSE failed";
|
||||
failure.extend_metadata(&mut metadata);
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(error) => {
|
||||
level = EventLevel::Warn;
|
||||
message = "v1 responses stream completed with invalid SSE failure metadata";
|
||||
metadata = json!({"stream": true, "sseParseError": error.to_string()});
|
||||
}
|
||||
}
|
||||
ensure_stream_metadata(&mut metadata, true);
|
||||
log_codex_upstream_response_with_deps(
|
||||
&self.deps,
|
||||
&self.context,
|
||||
status,
|
||||
level,
|
||||
message,
|
||||
metadata,
|
||||
)
|
||||
.await;
|
||||
self.account_slot.release().await;
|
||||
}
|
||||
|
||||
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 failed",
|
||||
json!({"stream": true, "transportError": error.to_string()}),
|
||||
)
|
||||
.await;
|
||||
self.account_slot.release().await;
|
||||
}
|
||||
}
|
||||
|
||||
struct AccountSlotGuard {
|
||||
pool: Arc<Mutex<AccountPool>>,
|
||||
account_id: String,
|
||||
released: bool,
|
||||
}
|
||||
|
||||
impl AccountSlotGuard {
|
||||
fn new(pool: Arc<Mutex<AccountPool>>, account_id: String) -> Self {
|
||||
Self {
|
||||
pool,
|
||||
account_id,
|
||||
released: false,
|
||||
}
|
||||
}
|
||||
|
||||
async fn release(&mut self) {
|
||||
if self.released {
|
||||
return;
|
||||
}
|
||||
self.pool.lock().await.release(&self.account_id);
|
||||
self.released = true;
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for AccountSlotGuard {
|
||||
fn drop(&mut self) {
|
||||
if self.released {
|
||||
return;
|
||||
}
|
||||
let pool = self.pool.clone();
|
||||
let account_id = self.account_id.clone();
|
||||
let Ok(handle) = tokio::runtime::Handle::try_current() else {
|
||||
return;
|
||||
};
|
||||
handle.spawn(async move {
|
||||
pool.lock().await.release(&account_id);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async fn log_codex_upstream_response_with_deps(
|
||||
deps: &CodexUpstreamDependencies,
|
||||
context: &CodexRequestLogContext,
|
||||
status: StatusCode,
|
||||
level: EventLevel,
|
||||
message: &str,
|
||||
mut metadata: Value,
|
||||
) {
|
||||
let Some(repo) = deps.event_logs.as_ref() else {
|
||||
return;
|
||||
};
|
||||
ensure_stream_metadata(&mut metadata, context.stream);
|
||||
let mut event = EventLog::new("v1.response", level, message);
|
||||
event.request_id = Some(context.request_id.clone());
|
||||
event.account_id = Some(context.account_id.clone());
|
||||
event.route = Some("/v1/responses".to_string());
|
||||
event.model = Some(context.model.clone());
|
||||
event.status_code = Some(i64::from(status.as_u16()));
|
||||
event.latency_ms = Some(context.latency_ms());
|
||||
event.metadata = metadata;
|
||||
if let Err(error) = repo.insert(event).await {
|
||||
tracing::warn!(?error, "failed to insert v1 response event log");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
use axum::http::StatusCode;
|
||||
use secrecy::SecretString;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::{
|
||||
codex::accounts::{
|
||||
model::{Account, AccountStatus},
|
||||
repository::TokenUpdate,
|
||||
},
|
||||
codex::oauth::{RefreshFailure, TokenPair},
|
||||
codex::transport::types::CodexResponsesRequest,
|
||||
logs::event::{EventLevel, EventLog},
|
||||
};
|
||||
|
||||
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());
|
||||
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);
|
||||
}
|
||||
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 Some(repo) = deps.event_logs.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let mut event = EventLog::new(
|
||||
"account.refresh",
|
||||
EventLevel::Warn,
|
||||
"account refresh failed after upstream 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) = repo.insert(event).await {
|
||||
tracing::warn!(?error, "failed to insert account refresh event log");
|
||||
}
|
||||
}
|
||||
|
||||
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",
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use crate::codex::transport::sse::parse_sse_events;
|
||||
|
||||
pub(crate) enum CollectedResponse {
|
||||
Completed(Value),
|
||||
Failed(ResponsesSseFailure),
|
||||
MissingCompleted,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct ResponsesSseFailure {
|
||||
event: String,
|
||||
message: String,
|
||||
upstream_code: Option<String>,
|
||||
}
|
||||
|
||||
impl ResponsesSseFailure {
|
||||
fn from_event(event: &str, value: &Value) -> Self {
|
||||
Self {
|
||||
event: event.to_string(),
|
||||
message: failure_message(value).unwrap_or_else(|| "Codex upstream SSE failed".into()),
|
||||
upstream_code: failure_code(value),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn openai_error_message(&self) -> String {
|
||||
format!("Codex upstream SSE failed: {}", self.message)
|
||||
}
|
||||
|
||||
pub(crate) fn metadata(&self, stream: bool) -> Value {
|
||||
let mut metadata = json!({"stream": stream});
|
||||
self.extend_metadata(&mut metadata);
|
||||
metadata
|
||||
}
|
||||
|
||||
pub(super) fn extend_metadata(&self, metadata: &mut Value) {
|
||||
let Some(object) = metadata.as_object_mut() else {
|
||||
*metadata = self.metadata(true);
|
||||
return;
|
||||
};
|
||||
object.insert("failureEvent".to_string(), json!(self.event));
|
||||
object.insert("failureMessage".to_string(), json!(self.message));
|
||||
if let Some(code) = &self.upstream_code {
|
||||
object.insert("upstreamCode".to_string(), json!(code));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn completed_response_json(
|
||||
body: &str,
|
||||
) -> Result<CollectedResponse, crate::codex::transport::sse::SseError> {
|
||||
let events = parse_sse_events(body)?;
|
||||
let mut output_text = String::new();
|
||||
let mut output_items = Vec::new();
|
||||
let mut completed_response = None;
|
||||
let mut failed_response = None;
|
||||
for event in events {
|
||||
let Ok(value) = serde_json::from_str::<Value>(&event.data) else {
|
||||
continue;
|
||||
};
|
||||
match event.event.as_deref() {
|
||||
Some("response.output_text.delta") => {
|
||||
if let Some(delta) = value.get("delta").and_then(Value::as_str) {
|
||||
output_text.push_str(delta);
|
||||
}
|
||||
}
|
||||
Some("response.output_item.done") => {
|
||||
if let Some(item) = value.get("item") {
|
||||
output_items.push(item.clone());
|
||||
}
|
||||
}
|
||||
Some("response.completed") => {
|
||||
if let Some(response) = value.get("response") {
|
||||
completed_response = Some(response.clone());
|
||||
}
|
||||
}
|
||||
Some(event_name @ ("error" | "response.failed")) if failed_response.is_none() => {
|
||||
failed_response = Some(ResponsesSseFailure::from_event(event_name, &value));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some(failure) = failed_response {
|
||||
return Ok(CollectedResponse::Failed(failure));
|
||||
}
|
||||
let Some(mut response) = completed_response else {
|
||||
return Ok(CollectedResponse::MissingCompleted);
|
||||
};
|
||||
ensure_completed_response_output(&mut response, &output_items, &output_text);
|
||||
sync_output_text_from_output(&mut response);
|
||||
Ok(CollectedResponse::Completed(response))
|
||||
}
|
||||
|
||||
pub(super) fn responses_sse_failure(
|
||||
body: &str,
|
||||
) -> Result<Option<ResponsesSseFailure>, crate::codex::transport::sse::SseError> {
|
||||
for event in parse_sse_events(body)? {
|
||||
let Some(event_name @ ("error" | "response.failed")) = event.event.as_deref() else {
|
||||
continue;
|
||||
};
|
||||
let Ok(value) = serde_json::from_str::<Value>(&event.data) else {
|
||||
continue;
|
||||
};
|
||||
return Ok(Some(ResponsesSseFailure::from_event(event_name, &value)));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub(super) fn ensure_stream_metadata(metadata: &mut Value, stream_value: bool) {
|
||||
let Some(object) = metadata.as_object_mut() else {
|
||||
*metadata = json!({"stream": stream_value});
|
||||
return;
|
||||
};
|
||||
object
|
||||
.entry("stream".to_string())
|
||||
.or_insert_with(|| json!(stream_value));
|
||||
}
|
||||
|
||||
fn failure_message(value: &Value) -> Option<String> {
|
||||
value
|
||||
.pointer("/response/error/message")
|
||||
.or_else(|| value.pointer("/error/message"))
|
||||
.or_else(|| value.get("message"))
|
||||
.and_then(Value::as_str)
|
||||
.filter(|message| !message.trim().is_empty())
|
||||
.map(ToString::to_string)
|
||||
}
|
||||
|
||||
fn failure_code(value: &Value) -> Option<String> {
|
||||
value
|
||||
.pointer("/response/error/code")
|
||||
.or_else(|| value.pointer("/error/code"))
|
||||
.or_else(|| value.get("code"))
|
||||
.and_then(Value::as_str)
|
||||
.filter(|code| !code.trim().is_empty())
|
||||
.map(ToString::to_string)
|
||||
}
|
||||
|
||||
fn ensure_completed_response_output(
|
||||
response: &mut Value,
|
||||
output_items: &[Value],
|
||||
output_text: &str,
|
||||
) {
|
||||
let output_is_empty = response
|
||||
.get("output")
|
||||
.and_then(Value::as_array)
|
||||
.is_none_or(Vec::is_empty);
|
||||
if !output_is_empty {
|
||||
return;
|
||||
}
|
||||
|
||||
if !output_items.is_empty() {
|
||||
response["output"] = Value::Array(output_items.to_vec());
|
||||
return;
|
||||
}
|
||||
if output_text.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
response["output"] = json!([{
|
||||
"type": "message",
|
||||
"status": "completed",
|
||||
"role": "assistant",
|
||||
"content": [{
|
||||
"type": "output_text",
|
||||
"text": output_text,
|
||||
"annotations": []
|
||||
}]
|
||||
}]);
|
||||
}
|
||||
|
||||
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 {
|
||||
return;
|
||||
}
|
||||
let Some(items) = response.get("output").and_then(Value::as_array) else {
|
||||
return;
|
||||
};
|
||||
let texts = items
|
||||
.iter()
|
||||
.filter_map(output_text_from_item)
|
||||
.collect::<Vec<_>>();
|
||||
if texts.is_empty() {
|
||||
return;
|
||||
}
|
||||
response["output_text"] = Value::String(texts.join("\n\n"));
|
||||
}
|
||||
|
||||
fn output_text_from_item(item: &Value) -> Option<String> {
|
||||
let content = item.get("content")?.as_array()?;
|
||||
let text = content
|
||||
.iter()
|
||||
.filter_map(|part| {
|
||||
let part_type = part.get("type")?.as_str()?;
|
||||
if part_type != "output_text" && part_type != "text" {
|
||||
return None;
|
||||
}
|
||||
part.get("text")?.as_str()
|
||||
})
|
||||
.collect::<String>();
|
||||
(!text.is_empty()).then_some(text)
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
use crate::{codex::accounts::repository::UsageDelta, codex::transport::usage::TokenUsage};
|
||||
|
||||
use super::CodexUpstreamDependencies;
|
||||
|
||||
pub(super) async fn record_usage_with_deps(
|
||||
deps: &CodexUpstreamDependencies,
|
||||
account_id: &str,
|
||||
usage: TokenUsage,
|
||||
) -> Result<(), ()> {
|
||||
let Some(repo) = deps.account_repository.as_ref() else {
|
||||
return Ok(());
|
||||
};
|
||||
repo.record_usage(
|
||||
account_id,
|
||||
UsageDelta {
|
||||
input_tokens: u64_to_i64_saturating(usage.input_tokens),
|
||||
output_tokens: u64_to_i64_saturating(usage.output_tokens),
|
||||
cached_tokens: u64_to_i64_saturating(usage.cached_tokens),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(|_| ())
|
||||
}
|
||||
|
||||
pub(super) async fn record_request_attempt(
|
||||
deps: &CodexUpstreamDependencies,
|
||||
account_id: &str,
|
||||
) -> Result<(), ()> {
|
||||
let Some(repo) = deps.account_repository.as_ref() else {
|
||||
return Ok(());
|
||||
};
|
||||
repo.record_usage(
|
||||
account_id,
|
||||
UsageDelta {
|
||||
input_tokens: 0,
|
||||
output_tokens: 0,
|
||||
cached_tokens: 0,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.map_err(|_| ())
|
||||
}
|
||||
|
||||
fn u64_to_i64_saturating(value: u64) -> i64 {
|
||||
value.min(i64::MAX as u64) as i64
|
||||
}
|
||||
Reference in New Issue
Block a user