mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-27 00:00:49 +00:00
feat: extend account scheduling primitives
Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
@@ -13,7 +13,7 @@ Update this file before each feature commit.
|
||||
| Logging and pagination | Completed | `eb0341e` + `fc16c48` + `b0c10f2` | `cargo test event_logs_are_cursor_paginated`; `cargo test admin_logs_are_cursor_paginated_and_include_request_id`; `cargo test rotating_writer_splits_files_when_size_limit_is_reached`; full `fmt/test/clippy` before commit | Adds cursor pagination, `Page<T>` camelCase serialization, admin `/admin/logs` query API, event log repository, runtime tracing initialization, HTTP trace layer, and date/size-based file rotation. |
|
||||
| TLS headers and fingerprint | Completed | `1bdd08c` | `cargo test codex_headers_include_desktop_identity_and_turn_state`; `cargo tree \| rg 'reqwest\|rustls'`; full `fmt/test/clippy` before commit | Adds Codex Desktop fingerprint model, exact identity/request headers, and pinned reqwest/rustls client builder. |
|
||||
| Cookie persistence | Completed | `4710926` + `5d3cc6e` | `cargo test cookie_jar_captures_and_replays_account_scoped_cookies`; `cargo test cookie_repository_encrypts_and_replays_account_scoped_cookies`; full `fmt/test/clippy` before commit | Adds account-scoped in-memory Cookie jar and encrypted SQLite Cookie repository; Cookies are replayed only for the same account/domain. |
|
||||
| Account pool and refresh | Partial | `0f97c5c` + `2f25db8` | `cargo test account_pool_skips_expired_disabled_banned_and_quota_exhausted_accounts`; `cargo test --test account_refresh_test`; full `fmt/test/clippy` before commit | Implemented base account status filtering and refresh scheduler semantics. Still missing original scheduling parity: max concurrent slots, stale slot cleanup, rotation strategies, tier priority, quota-cache filtering, Cloudflare cooldown, request staggering, session affinity, pool integration with the SQLite repository, and admin account CRUD. |
|
||||
| Account pool and refresh | Partial | `0f97c5c` + `2f25db8` + `pending` | `cargo test account_pool_skips_expired_disabled_banned_and_quota_exhausted_accounts`; `cargo test --test account_pool_scheduling_test`; `cargo test --test account_refresh_test`; full `fmt/test/clippy` before commit | Implements base account status filtering, refresh scheduler semantics, max concurrent slots, stale slot cleanup, least-used/round-robin/sticky strategies, tier priority, quota-cache filtering, Cloudflare cooldown skip, request staggering metadata, preferred account selection, exclude IDs, and capacity summary. Still missing settings-backed scheduling config, SQLite repository integration for pool snapshots/release usage, upstream retry/fallback wiring, and admin account CRUD. |
|
||||
| Account repository | Completed | `14fe706` | `cargo test --test account_repository_test`; `cargo fmt --check`; `cargo clippy --all-targets --all-features --locked -- -D warnings`; `cargo test` | Adds encrypted SQLite account token storage, decrypting reads, cursor pagination, status/label updates, release-time usage counter persistence, and refresh-token-preserving token updates. |
|
||||
| Translation | Completed | `eff182e` | `cargo test chat_completion_translates_to_codex_response_request`; full `fmt/test/clippy` before commit | Adds OpenAI Chat request types, Codex Responses request type, translation, and OpenAI-compatible error body helper. |
|
||||
| HTTP routes | Partial | `ab0ad8f` + `3830b21` | `cargo test v1_requires_client_api_key_not_admin_cookie`; `cargo test models_route_returns_openai_compatible_codex_model_list`; full `fmt/test/clippy` before commit | Adds Axum router, health route, `/v1/models`, `/v1` unauthorized OpenAI error body, global request-id response header, and binary listener. Still missing admin auth middleware extraction, account/auth/API-key management routes, settings routes, diagnostics, usage stats, model catalog/detail/refresh routes, and additional Responses routes. |
|
||||
|
||||
@@ -2958,6 +2958,7 @@ git commit -m "docs: document codex-proxy-rs scope"
|
||||
- [x] Add a tested SQLite account repository foundation. It encrypts access/refresh tokens, decrypts account reads, cursor-pages accounts, updates status/labels without rewriting token ciphertext, persists usage counters, and preserves the existing refresh token when token refresh responses omit a new one.
|
||||
- [x] Add a real HTTP auth boundary. `src/http/auth.rs` parses client API keys and admin session cookies as separate credential types, `/v1/*` uses only `Bearer cpr_...`, and admin session parsing ignores client API keys.
|
||||
- [x] Add a tested Codex WebSocket boundary. `src/codex/websocket.rs` classifies HTTP SSE versus WebSocket-only requests, adds `previous_response_id`/`use_websocket` request fields, and returns typed errors instead of silently downgrading WebSocket-required traffic.
|
||||
- [x] Extend account scheduling primitives against the original TypeScript lifecycle. `AccountPool` now covers max concurrent slots, stale slot cleanup, least-used/round-robin/sticky strategies, tier priority, model-plan filtering, cached quota skip, exclude IDs, preferred account selection for session affinity, Cloudflare cooldown skip, request-staggering metadata, and capacity summary.
|
||||
|
||||
## 2026-06-11 Original Project Gap Audit
|
||||
|
||||
@@ -2974,7 +2975,7 @@ The Rust project has no legacy compatibility requirement, but the in-scope behav
|
||||
- [ ] **Diagnostics:** expand health/admin diagnostics to include authenticated state, pool summary, capacity summary, transport/fingerprint status, paths, runtime metadata, and test-connection checks. Keep production-local gating for sensitive debug endpoints.
|
||||
- [ ] **Logs and usage stats:** add `/admin/logs/state`, clear/detail, error-log equivalents if retained, and `/admin/usage-stats/summary` plus paginated or bounded history queries. Keep log file rotation and SQLite event pagination.
|
||||
- [ ] **Model catalog:** replace the hard-coded `/v1/models` list with a model store that supports static defaults, configured aliases, `-low/-medium/-high/-xhigh/-fast/-flex` suffix parsing, backend model fetching per plan, cache persistence, `/v1/models/catalog`, `/v1/models/{id}`, `/v1/models/{id}/info`, `/admin/refresh-models`, and `/debug/models`.
|
||||
- [ ] **Account scheduling parity:** extend account acquisition beyond `active + least last_used`: max concurrent slots per account, stale slot cleanup, least-used/round-robin/sticky strategies, quota-cache skip, tier priority, model-plan filtering, exclude IDs, preferred account from session affinity, Cloudflare cooldown, request staggering, and release-time usage accounting.
|
||||
- [ ] **Account scheduling parity:** extend account acquisition beyond `active + least last_used`. Completed in the in-memory pool: max concurrent slots per account, stale slot cleanup, least-used/round-robin/sticky strategies, quota-cache skip, tier priority, model-plan filtering, exclude IDs, preferred account from session affinity, Cloudflare cooldown skip, request-staggering metadata, and capacity summary. Remaining: settings-backed scheduling config, pool snapshots from SQLite, release-time usage accounting through the repository, and upstream retry/fallback wiring.
|
||||
- [ ] **Upstream Codex lifecycle:** implement account acquire -> Codex request -> SSE/collect -> rate-limit capture -> usage release -> retry/fallback. Include Cookie replay/capture, Codex Desktop headers, `x-codex-turn-state`, `x-client-request-id`, upstream error classification, 401-triggered refresh, 429 quota cache, 402 quota exhausted, 403 ban/Cloudflare distinction, path-block Cookie clearing, and OpenAI-compatible error mapping.
|
||||
- [ ] **Session affinity and previous response:** persist an in-memory response-id to account mapping with TTL, prompt-cache/conversation identity, turn-state replay, and preferred account selection. `src/codex/websocket.rs` must either implement the WebSocket path with verified TLS/header behavior or the API must reject WebSocket-only cases explicitly with documented limitations until fingerprint parity is proven.
|
||||
- [ ] **Fingerprint auto-update parity:** poll the real Codex Desktop appcast/update source, parse app version/build number, persist update state, select the latest stored fingerprint for runtime headers, and optionally extract Chromium version from a local Codex.app path when configured.
|
||||
|
||||
@@ -23,6 +23,8 @@ pub struct Account {
|
||||
pub refresh_token: Option<String>,
|
||||
pub access_token_expires_at: Option<DateTime<Utc>>,
|
||||
pub status: AccountStatus,
|
||||
pub quota_limit_reached: bool,
|
||||
pub cloudflare_cooldown_until: Option<DateTime<Utc>>,
|
||||
pub added_at: String,
|
||||
pub last_used_at: Option<String>,
|
||||
}
|
||||
@@ -40,6 +42,8 @@ impl Account {
|
||||
refresh_token: Some(format!("refresh-{id}")),
|
||||
access_token_expires_at: Some(Utc::now() + Duration::hours(1)),
|
||||
status,
|
||||
quota_limit_reached: false,
|
||||
cloudflare_cooldown_until: None,
|
||||
added_at: Utc::now().to_rfc3339(),
|
||||
last_used_at: None,
|
||||
}
|
||||
|
||||
+264
-6
@@ -1,22 +1,280 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, VecDeque};
|
||||
|
||||
use chrono::{DateTime, Duration, Utc};
|
||||
|
||||
use crate::accounts::model::{Account, AccountStatus};
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
#[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 acquire(&self, _model: &str) -> Option<Account> {
|
||||
self.accounts
|
||||
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)
|
||||
.min_by_key(|account| account.last_used_at.clone())
|
||||
.filter(|account| {
|
||||
account.status == AccountStatus::Active
|
||||
&& (!self.options.skip_quota_limited || !account.quota_limit_reached)
|
||||
})
|
||||
.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.options.skip_quota_limited || !account.quota_limit_reached)
|
||||
&& 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 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,221 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use chrono::{Duration, TimeZone, Utc};
|
||||
use codex_proxy_rs::accounts::{
|
||||
model::{Account, AccountStatus},
|
||||
pool::{AccountAcquireRequest, AccountPool, AccountPoolOptions, RotationStrategy},
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn account_pool_should_respect_max_concurrent_slots_per_account() {
|
||||
let mut pool = AccountPool::with_options(AccountPoolOptions {
|
||||
max_concurrent_per_account: 1,
|
||||
..AccountPoolOptions::default()
|
||||
});
|
||||
pool.insert(Account::test("acct_a", AccountStatus::Active));
|
||||
pool.insert(Account::test("acct_b", AccountStatus::Active));
|
||||
|
||||
let first = pool.acquire("gpt-5.4").unwrap();
|
||||
let second = pool.acquire("gpt-5.4").unwrap();
|
||||
let third = pool.acquire("gpt-5.4");
|
||||
|
||||
assert_ne!(first.id, second.id);
|
||||
assert!(third.is_none());
|
||||
|
||||
pool.release(&first.id);
|
||||
assert_eq!(pool.acquire("gpt-5.4").unwrap().id, first.id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_pool_should_rotate_round_robin_across_candidates() {
|
||||
let mut pool = AccountPool::with_options(AccountPoolOptions {
|
||||
max_concurrent_per_account: 1,
|
||||
rotation_strategy: RotationStrategy::RoundRobin,
|
||||
..AccountPoolOptions::default()
|
||||
});
|
||||
pool.insert(Account::test("acct_a", AccountStatus::Active));
|
||||
pool.insert(Account::test("acct_b", AccountStatus::Active));
|
||||
pool.insert(Account::test("acct_c", AccountStatus::Active));
|
||||
|
||||
assert_eq!(pool.acquire("gpt-5.4").unwrap().id, "acct_a");
|
||||
assert_eq!(pool.acquire("gpt-5.4").unwrap().id, "acct_c");
|
||||
assert_eq!(pool.acquire("gpt-5.4").unwrap().id, "acct_b");
|
||||
assert!(pool.acquire("gpt-5.4").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_pool_should_skip_accounts_with_cached_quota_limit() {
|
||||
let mut limited = Account::test("limited", AccountStatus::Active);
|
||||
limited.quota_limit_reached = true;
|
||||
let mut pool = AccountPool::default();
|
||||
pool.insert(limited);
|
||||
pool.insert(Account::test("usable", AccountStatus::Active));
|
||||
|
||||
assert_eq!(pool.acquire("gpt-5.4").unwrap().id, "usable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_pool_should_prefer_configured_tier_priority() {
|
||||
let mut pool = AccountPool::with_options(AccountPoolOptions {
|
||||
tier_priority: vec!["team".to_string(), "plus".to_string()],
|
||||
..AccountPoolOptions::default()
|
||||
});
|
||||
let mut free = Account::test("free", AccountStatus::Active);
|
||||
free.plan_type = Some("free".to_string());
|
||||
let mut team = Account::test("team", AccountStatus::Active);
|
||||
team.plan_type = Some("team".to_string());
|
||||
pool.insert(free);
|
||||
pool.insert(team);
|
||||
|
||||
assert_eq!(pool.acquire("gpt-5.4").unwrap().id, "team");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_pool_should_filter_by_model_plan_allowlist() {
|
||||
let mut model_plans = BTreeMap::new();
|
||||
model_plans.insert("gpt-5.4".to_string(), vec!["plus".to_string()]);
|
||||
let mut pool = AccountPool::with_options(AccountPoolOptions {
|
||||
model_plan_allowlist: model_plans,
|
||||
..AccountPoolOptions::default()
|
||||
});
|
||||
let mut free = Account::test("free", AccountStatus::Active);
|
||||
free.plan_type = Some("free".to_string());
|
||||
let mut plus = Account::test("plus", AccountStatus::Active);
|
||||
plus.plan_type = Some("plus".to_string());
|
||||
pool.insert(free);
|
||||
pool.insert(plus);
|
||||
|
||||
assert_eq!(pool.acquire("gpt-5.4").unwrap().id, "plus");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_pool_should_exclude_requested_account_ids() {
|
||||
let mut pool = AccountPool::default();
|
||||
pool.insert(Account::test("acct_a", AccountStatus::Active));
|
||||
pool.insert(Account::test("acct_b", AccountStatus::Active));
|
||||
|
||||
let acquired = pool
|
||||
.acquire_with(
|
||||
AccountAcquireRequest::new("gpt-5.4", fixed_time())
|
||||
.with_exclude_account_ids(["acct_a"]),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(acquired.account.id, "acct_b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_pool_should_prefer_session_affinity_account_when_available() {
|
||||
let mut pool = AccountPool::default();
|
||||
pool.insert(Account::test("acct_a", AccountStatus::Active));
|
||||
pool.insert(Account::test("acct_b", AccountStatus::Active));
|
||||
|
||||
let acquired = pool
|
||||
.acquire_with(
|
||||
AccountAcquireRequest::new("gpt-5.4", fixed_time()).with_preferred_account_id("acct_b"),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(acquired.account.id, "acct_b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_pool_should_skip_accounts_in_cloudflare_cooldown() {
|
||||
let now = fixed_time();
|
||||
let mut cooling = Account::test("cooling", AccountStatus::Active);
|
||||
cooling.cloudflare_cooldown_until = Some(now + Duration::seconds(30));
|
||||
let mut pool = AccountPool::default();
|
||||
pool.insert(cooling);
|
||||
pool.insert(Account::test("usable", AccountStatus::Active));
|
||||
|
||||
let acquired = pool
|
||||
.acquire_with(AccountAcquireRequest::new("gpt-5.4", now))
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(acquired.account.id, "usable");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_pool_should_cleanup_stale_slots_before_acquire() {
|
||||
let now = fixed_time();
|
||||
let mut pool = AccountPool::with_options(AccountPoolOptions {
|
||||
max_concurrent_per_account: 1,
|
||||
stale_slot_ttl: Duration::minutes(5),
|
||||
..AccountPoolOptions::default()
|
||||
});
|
||||
pool.insert(Account::test("acct_a", AccountStatus::Active));
|
||||
|
||||
assert!(pool
|
||||
.acquire_with(AccountAcquireRequest::new("gpt-5.4", now))
|
||||
.is_some());
|
||||
let acquired = pool
|
||||
.acquire_with(AccountAcquireRequest::new(
|
||||
"gpt-5.4",
|
||||
now + Duration::minutes(5) + Duration::seconds(1),
|
||||
))
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(acquired.account.id, "acct_a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_pool_should_return_previous_slot_time_for_request_staggering() {
|
||||
let now = fixed_time();
|
||||
let mut pool = AccountPool::with_options(AccountPoolOptions {
|
||||
max_concurrent_per_account: 2,
|
||||
..AccountPoolOptions::default()
|
||||
});
|
||||
pool.insert(Account::test("acct_a", AccountStatus::Active));
|
||||
|
||||
let first = pool
|
||||
.acquire_with(AccountAcquireRequest::new("gpt-5.4", now))
|
||||
.unwrap();
|
||||
let second = pool
|
||||
.acquire_with(AccountAcquireRequest::new(
|
||||
"gpt-5.4",
|
||||
now + Duration::milliseconds(250),
|
||||
))
|
||||
.unwrap();
|
||||
|
||||
assert!(first.previous_slot_at.is_none());
|
||||
assert_eq!(second.previous_slot_at, Some(now));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_pool_should_report_capacity_summary() {
|
||||
let now = fixed_time();
|
||||
let mut pool = AccountPool::with_options(AccountPoolOptions {
|
||||
max_concurrent_per_account: 2,
|
||||
..AccountPoolOptions::default()
|
||||
});
|
||||
pool.insert(Account::test("acct_a", AccountStatus::Active));
|
||||
pool.insert(Account::test("acct_b", AccountStatus::Disabled));
|
||||
|
||||
pool.acquire_with(AccountAcquireRequest::new("gpt-5.4", now));
|
||||
let summary = pool.capacity_summary(now);
|
||||
|
||||
assert_eq!(summary.total_slots, 2);
|
||||
assert_eq!(summary.used_slots, 1);
|
||||
assert_eq!(summary.available_slots, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn account_pool_should_rotate_tied_least_used_accounts() {
|
||||
let mut pool = AccountPool::with_options(AccountPoolOptions {
|
||||
max_concurrent_per_account: 1,
|
||||
rotation_strategy: RotationStrategy::LeastUsed,
|
||||
..AccountPoolOptions::default()
|
||||
});
|
||||
pool.insert(Account::test("acct_a", AccountStatus::Active));
|
||||
pool.insert(Account::test("acct_b", AccountStatus::Active));
|
||||
|
||||
let first = pool.acquire("gpt-5.4").unwrap();
|
||||
pool.release(&first.id);
|
||||
let second = pool.acquire("gpt-5.4").unwrap();
|
||||
|
||||
assert_ne!(first.id, second.id);
|
||||
}
|
||||
|
||||
fn fixed_time() -> chrono::DateTime<Utc> {
|
||||
Utc.with_ymd_and_hms(2026, 6, 11, 8, 0, 0).unwrap()
|
||||
}
|
||||
Reference in New Issue
Block a user