mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-11-30 00:00:48 +00:00
Preserve main quota, Guardian, and WebSocket fixes alongside the new provider and module organization. Co-authored-by: Codex <noreply@openai.com>
1707 lines
59 KiB
Rust
1707 lines
59 KiB
Rust
//! Codex Provider 测试用内存 ports;不依赖 SQL、Redis 或 secret 加密
|
|
|
|
use std::collections::{BTreeMap, BTreeSet};
|
|
use std::num::NonZeroU32;
|
|
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
|
use std::sync::{Arc, Mutex};
|
|
use std::time::{Duration, SystemTime};
|
|
|
|
use async_trait::async_trait;
|
|
use futures::future::BoxFuture;
|
|
use gateway_core::account::{
|
|
AccountConcurrencyLimit, AccountErrorReason, AccountRuntimeSignals, AccountStateChange,
|
|
AccountWeight, CredentialCasOutcome, CredentialCasUpdate, CredentialCasUpdateParts,
|
|
CredentialRevision, CredentialState, LoadedCredential, NewProviderAccount, OpaqueProviderData,
|
|
ProviderAccount, ProviderAccountId, ProviderAccountStore, ProviderAccountUpdate,
|
|
ProviderRefreshQuery, QuotaAccessChange, QuotaObservation, QuotaObservationTouch, QuotaState,
|
|
QuotaWriteOutcome,
|
|
};
|
|
use gateway_core::error::{StoreError, StoreErrorKind};
|
|
use gateway_core::policy::ClientApiKeyId;
|
|
use gateway_core::provider_ports::{
|
|
ProviderAccountAdmission, ProviderCatalogCacheKey, ProviderCatalogCachePort, ProviderCooldown,
|
|
ProviderCooldownPort, ProviderCooldownScope, ProviderLeaseAcquisition, ProviderLeasePort,
|
|
ProviderLeaseRequest, ProviderRefreshPolicy, ProviderRuntimePolicyPort,
|
|
ProviderSchedulingLeaseRequest, ProviderSchedulingState, ProviderScopedCooldown,
|
|
ProviderSessionAffinityKey, ProviderSessionAffinityPort, ProviderSessionBinding,
|
|
ProviderSessionExclusionPort, ProviderSessionExclusions, ProviderStoreError,
|
|
};
|
|
use gateway_core::routing::ProviderKind;
|
|
use provider_openai::credential::{
|
|
CodexAccountProfile, CodexCredentialAdmin, CodexCredentialRepository, CodexOAuthSecret,
|
|
ImportCodexOAuthCredential,
|
|
};
|
|
use secrecy::SecretString;
|
|
use tokio::sync::oneshot;
|
|
|
|
#[derive(Clone)]
|
|
struct StoredAccount {
|
|
account: ProviderAccount,
|
|
credential: gateway_core::account::PlaintextCredential,
|
|
quota: Option<QuotaObservation>,
|
|
state_observed_at: Option<SystemTime>,
|
|
}
|
|
|
|
type CredentialLoadHook = dyn for<'a> Fn(
|
|
&'a MemoryAccountStore,
|
|
&'a ProviderAccountId,
|
|
usize,
|
|
) -> BoxFuture<'a, Result<(), StoreError>>
|
|
+ Send
|
|
+ Sync;
|
|
|
|
#[derive(Default)]
|
|
pub(crate) struct MemoryAccountStore {
|
|
pub(crate) peer_discovered: AtomicBool,
|
|
accounts: Mutex<BTreeMap<ProviderAccountId, StoredAccount>>,
|
|
warmup_states: Mutex<BTreeMap<ProviderAccountId, gateway_core::account::QuotaWarmupState>>,
|
|
catalogs: Mutex<
|
|
BTreeMap<
|
|
ProviderAccountId,
|
|
(
|
|
gateway_core::account::AccountCatalogObservation,
|
|
bytes::Bytes,
|
|
),
|
|
>,
|
|
>,
|
|
account_reads: AtomicUsize,
|
|
provider_list_reads: AtomicUsize,
|
|
quota_reads: AtomicUsize,
|
|
next_quota_read: Mutex<Option<(oneshot::Sender<()>, oneshot::Receiver<()>)>>,
|
|
largest_quota_read: AtomicUsize,
|
|
fail_provider_listing: AtomicBool,
|
|
pending_account_reads: bool,
|
|
credential_load_hook: Mutex<Option<Arc<CredentialLoadHook>>>,
|
|
credential_loads: AtomicUsize,
|
|
}
|
|
|
|
impl gateway_core::account::UpstreamInfoSource for MemoryAccountStore {
|
|
fn is_peer(&self, _: &ProviderAccount) -> bool {
|
|
self.peer_discovered.load(Ordering::SeqCst)
|
|
}
|
|
|
|
fn signal(
|
|
&self,
|
|
_: &ProviderAccount,
|
|
_: Option<&str>,
|
|
_: SystemTime,
|
|
) -> Option<gateway_core::account::UpstreamSchedulingSignal> {
|
|
None
|
|
}
|
|
}
|
|
|
|
impl MemoryAccountStore {
|
|
pub(crate) fn with_pending_account_reads() -> Self {
|
|
Self {
|
|
pending_account_reads: true,
|
|
..Self::default()
|
|
}
|
|
}
|
|
|
|
pub(crate) fn repository(self: &Arc<Self>) -> CodexCredentialRepository {
|
|
CodexCredentialRepository::new(self.clone())
|
|
}
|
|
|
|
pub(crate) async fn seed_oauth_credential(&self, input: ImportCodexOAuthCredential) {
|
|
let account = CodexCredentialAdmin
|
|
.prepare_import(input)
|
|
.expect("prepare test OAuth credential");
|
|
self.create_account(account)
|
|
.await
|
|
.expect("seed test OAuth credential");
|
|
}
|
|
|
|
pub(crate) fn set_oauth_transport(
|
|
&self,
|
|
id: &str,
|
|
transport: provider_openai::credential::ResponsesTransport,
|
|
) {
|
|
use provider_openai::credential::CodexCredentialCodec;
|
|
let mut accounts = self.accounts.lock().unwrap();
|
|
let stored = accounts
|
|
.get_mut(&ProviderAccountId::new(id).unwrap())
|
|
.unwrap();
|
|
let mut data = CodexCredentialCodec::decode_complete(&stored.credential).unwrap();
|
|
data.oauth_mut().unwrap().transport = transport;
|
|
stored.credential = CodexCredentialCodec::encode_complete(data).unwrap();
|
|
}
|
|
|
|
pub(crate) async fn seed_api_key(
|
|
&self,
|
|
id: &str,
|
|
base_url: String,
|
|
transport: provider_openai::credential::ResponsesTransport,
|
|
) {
|
|
self.seed_api_key_for_protocol(
|
|
id,
|
|
base_url,
|
|
transport,
|
|
provider_openai::credential::ApiKeyProtocol::Responses,
|
|
)
|
|
.await;
|
|
}
|
|
|
|
pub(crate) async fn seed_api_key_for_protocol(
|
|
&self,
|
|
id: &str,
|
|
base_url: String,
|
|
transport: provider_openai::credential::ResponsesTransport,
|
|
protocol: provider_openai::credential::ApiKeyProtocol,
|
|
) {
|
|
let credential = provider_openai::credential::CodexCredentialCodec::encode_complete(
|
|
provider_openai::credential::CodexCredentialData::ApiKey(
|
|
provider_openai::credential::ApiKeyCredentialData {
|
|
schema_version: 1,
|
|
installation_id: uuid::Uuid::new_v4().to_string(),
|
|
base_url,
|
|
protocol,
|
|
api_key: "sk-api-test-only".to_owned(),
|
|
transport,
|
|
},
|
|
),
|
|
)
|
|
.expect("API Key schema");
|
|
let account = ProviderAccount::new(
|
|
ProviderAccountId::new(id).expect("id"),
|
|
ProviderKind::new("openai").expect("kind"),
|
|
id.to_owned(),
|
|
None,
|
|
"api_key".to_owned(),
|
|
CredentialRevision::new(1).expect("revision"),
|
|
None,
|
|
)
|
|
.with_account_facts(
|
|
true,
|
|
CredentialState::Ready,
|
|
QuotaState::unknown(),
|
|
None,
|
|
None,
|
|
);
|
|
self.create_account(NewProviderAccount {
|
|
account,
|
|
credential,
|
|
model_access: None,
|
|
})
|
|
.await
|
|
.expect("seed API account");
|
|
}
|
|
|
|
pub(crate) fn account(&self, id: &str) -> Option<ProviderAccount> {
|
|
let id = ProviderAccountId::new(id).ok()?;
|
|
self.accounts
|
|
.lock()
|
|
.expect("account store lock")
|
|
.get(&id)
|
|
.map(|stored| stored.account.clone())
|
|
}
|
|
|
|
pub(crate) fn set_quota_settings(
|
|
&self,
|
|
id: &str,
|
|
limits: gateway_core::account::AccountQuotaSettings,
|
|
) {
|
|
let mut accounts = self.accounts.lock().unwrap();
|
|
let stored = accounts
|
|
.get_mut(&ProviderAccountId::new(id).unwrap())
|
|
.unwrap();
|
|
stored.account = stored.account.clone().with_quota_settings(limits, false);
|
|
}
|
|
|
|
pub(crate) fn enable_quota_credits(&self, id: &str) {
|
|
let mut accounts = self.accounts.lock().unwrap();
|
|
let stored = accounts
|
|
.get_mut(&ProviderAccountId::new(id).unwrap())
|
|
.unwrap();
|
|
stored.account = stored.account.clone().with_auto_use_quota_credits(true);
|
|
}
|
|
|
|
pub(crate) fn set_model_access(
|
|
&self,
|
|
id: &str,
|
|
access: gateway_core::account::AccountModelAccess,
|
|
) {
|
|
let mut accounts = self.accounts.lock().unwrap();
|
|
let stored = accounts
|
|
.get_mut(&ProviderAccountId::new(id).unwrap())
|
|
.unwrap();
|
|
stored.account = stored.account.clone().with_model_access(access);
|
|
}
|
|
|
|
pub(crate) fn set_scheduling(
|
|
&self,
|
|
id: &str,
|
|
concurrency_limit: Option<AccountConcurrencyLimit>,
|
|
weight: AccountWeight,
|
|
) {
|
|
let id = ProviderAccountId::new(id).expect("valid account ID");
|
|
let mut accounts = self.accounts.lock().expect("account store lock");
|
|
let stored = accounts.get_mut(&id).expect("seeded account");
|
|
stored.account = stored
|
|
.account
|
|
.clone()
|
|
.with_scheduling(concurrency_limit, weight);
|
|
}
|
|
|
|
pub(crate) fn set_egress(
|
|
&self,
|
|
id: &str,
|
|
proxy: Option<gateway_core::account::OutboundProxy>,
|
|
location: Option<gateway_core::account::RequestLocation>,
|
|
) {
|
|
let id = ProviderAccountId::new(id).expect("account ID");
|
|
let mut accounts = self.accounts.lock().expect("account store lock");
|
|
let stored = accounts.get_mut(&id).expect("seeded account");
|
|
stored.account = stored
|
|
.account
|
|
.clone()
|
|
.with_outbound_proxy(proxy)
|
|
.with_request_location(location);
|
|
}
|
|
|
|
pub(crate) fn largest_quota_read(&self) -> usize {
|
|
self.largest_quota_read.load(Ordering::SeqCst)
|
|
}
|
|
|
|
pub(crate) fn hold_next_quota_read(&self) -> (oneshot::Receiver<()>, oneshot::Sender<()>) {
|
|
let (read, ready) = oneshot::channel();
|
|
let (release, held) = oneshot::channel();
|
|
*self.next_quota_read.lock().unwrap() = Some((read, held));
|
|
(ready, release)
|
|
}
|
|
|
|
pub(crate) fn quota_reads(&self) -> usize {
|
|
self.quota_reads.load(Ordering::SeqCst)
|
|
}
|
|
|
|
pub(crate) fn account_reads(&self) -> usize {
|
|
self.account_reads.load(Ordering::SeqCst)
|
|
}
|
|
|
|
pub(crate) fn provider_list_reads(&self) -> usize {
|
|
self.provider_list_reads.load(Ordering::SeqCst)
|
|
}
|
|
|
|
pub(crate) fn has_quota(&self, id: &str) -> bool {
|
|
let Some(id) = ProviderAccountId::new(id).ok() else {
|
|
return false;
|
|
};
|
|
self.accounts
|
|
.lock()
|
|
.expect("account store lock")
|
|
.get(&id)
|
|
.is_some_and(|stored| stored.quota.is_some())
|
|
}
|
|
|
|
pub(crate) fn quota_json(&self, id: &str) -> Option<serde_json::Value> {
|
|
let id = ProviderAccountId::new(id).ok()?;
|
|
self.accounts
|
|
.lock()
|
|
.expect("account store lock")
|
|
.get(&id)
|
|
.and_then(|stored| stored.quota.as_ref())
|
|
.map(|observation| {
|
|
serde_json::Value::Object(observation.quota.expose_to_provider().clone())
|
|
})
|
|
}
|
|
|
|
pub(crate) fn fail_provider_listing(&self) {
|
|
self.fail_provider_listing.store(true, Ordering::SeqCst);
|
|
}
|
|
|
|
pub(crate) fn on_credential_load(&self, hook: Arc<CredentialLoadHook>) {
|
|
*self
|
|
.credential_load_hook
|
|
.lock()
|
|
.expect("credential hook lock") = Some(hook);
|
|
}
|
|
|
|
pub(crate) fn credential_loads(&self) -> usize {
|
|
self.credential_loads.load(Ordering::SeqCst)
|
|
}
|
|
}
|
|
|
|
#[async_trait]
|
|
impl ProviderAccountStore for MemoryAccountStore {
|
|
async fn load_quota_warmup_state(
|
|
&self,
|
|
account: &ProviderAccount,
|
|
) -> Result<Option<gateway_core::account::QuotaWarmupState>, StoreError> {
|
|
let accounts = self.accounts.lock().unwrap();
|
|
if accounts
|
|
.get(account.id())
|
|
.is_none_or(|stored| stored.account.revision() != account.revision())
|
|
{
|
|
return Ok(None);
|
|
}
|
|
Ok(Some(
|
|
self.warmup_states
|
|
.lock()
|
|
.unwrap()
|
|
.get(account.id())
|
|
.cloned()
|
|
.unwrap_or_default(),
|
|
))
|
|
}
|
|
|
|
async fn compare_and_swap_quota_warmup_state(
|
|
&self,
|
|
update: gateway_core::account::QuotaWarmupStateUpdate<'_>,
|
|
) -> Result<bool, StoreError> {
|
|
let accounts = self.accounts.lock().unwrap();
|
|
let Some(stored) = accounts.get(update.account.id()) else {
|
|
return Ok(false);
|
|
};
|
|
if stored.account.revision() != update.account.revision()
|
|
|| !stored.account.enabled()
|
|
|| stored.account.quota_settings() != update.account.quota_settings()
|
|
|| stored.account.credential_state() != update.account.credential_state()
|
|
|| stored.account.quota().access() != update.account.quota().access()
|
|
|| stored.account.quota_paused() != update.account.quota_paused()
|
|
|| stored.quota.as_ref().map(|quota| quota.observed_at)
|
|
!= update.expected_quota_observed_at
|
|
{
|
|
return Ok(false);
|
|
}
|
|
let mut states = self.warmup_states.lock().unwrap();
|
|
let state = states.entry(update.account.id().clone()).or_default();
|
|
if state.version != update.expected_version {
|
|
return Ok(false);
|
|
}
|
|
state.version += 1;
|
|
state.data = update.data;
|
|
Ok(true)
|
|
}
|
|
|
|
async fn load_account_catalogs(
|
|
&self,
|
|
provider: &ProviderKind,
|
|
) -> Result<Vec<gateway_core::account::StoredAccountCatalog>, StoreError> {
|
|
let accounts = self.accounts.lock().unwrap();
|
|
let mut groups = BTreeMap::<bytes::Bytes, Vec<_>>::new();
|
|
for (id, (observation, document)) in self.catalogs.lock().unwrap().iter() {
|
|
if accounts.get(id).is_some_and(|row| {
|
|
row.account.provider() == provider
|
|
&& row.account.enabled()
|
|
&& matches!(
|
|
row.account.credential_state(),
|
|
CredentialState::Ready | CredentialState::Unknown
|
|
)
|
|
&& row
|
|
.account
|
|
.access_token_expires_at()
|
|
.is_none_or(|ts| ts > SystemTime::now())
|
|
&& row.account.revision() == observation.revision
|
|
&& row.account.plan_type() == observation.plan.as_deref()
|
|
}) {
|
|
groups
|
|
.entry(document.clone())
|
|
.or_default()
|
|
.push(observation.clone());
|
|
}
|
|
}
|
|
Ok(groups
|
|
.into_iter()
|
|
.map(
|
|
|(document, accounts)| gateway_core::account::StoredAccountCatalog {
|
|
accounts,
|
|
document,
|
|
},
|
|
)
|
|
.collect())
|
|
}
|
|
async fn save_account_catalog(
|
|
&self,
|
|
observation: &gateway_core::account::AccountCatalogObservation,
|
|
document: &[u8],
|
|
) -> Result<bool, StoreError> {
|
|
let rows = self.accounts.lock().unwrap();
|
|
if !rows.get(&observation.account_id).is_some_and(|a| {
|
|
a.account.revision() == observation.revision
|
|
&& a.account.plan_type() == observation.plan.as_deref()
|
|
}) {
|
|
return Ok(false);
|
|
}
|
|
self.catalogs.lock().unwrap().insert(
|
|
observation.account_id.clone(),
|
|
(observation.clone(), bytes::Bytes::copy_from_slice(document)),
|
|
);
|
|
Ok(true)
|
|
}
|
|
|
|
async fn create_account(&self, input: NewProviderAccount) -> Result<(), StoreError> {
|
|
let mut accounts = self.accounts.lock().expect("account store lock");
|
|
if accounts.contains_key(input.account.id()) {
|
|
return Err(store_error(StoreErrorKind::Conflict));
|
|
}
|
|
accounts.insert(
|
|
input.account.id().clone(),
|
|
StoredAccount {
|
|
account: input.account,
|
|
credential: input.credential,
|
|
quota: None,
|
|
state_observed_at: None,
|
|
},
|
|
);
|
|
Ok(())
|
|
}
|
|
|
|
async fn get_account(
|
|
&self,
|
|
account: &ProviderAccountId,
|
|
) -> Result<Option<ProviderAccount>, StoreError> {
|
|
self.account_reads.fetch_add(1, Ordering::SeqCst);
|
|
if self.pending_account_reads {
|
|
futures::future::pending::<()>().await;
|
|
}
|
|
Ok(self
|
|
.accounts
|
|
.lock()
|
|
.expect("account store lock")
|
|
.get(account)
|
|
.map(|stored| stored.account.clone()))
|
|
}
|
|
|
|
async fn list_accounts(&self) -> Result<Vec<ProviderAccount>, StoreError> {
|
|
Ok(self
|
|
.accounts
|
|
.lock()
|
|
.expect("account store lock")
|
|
.values()
|
|
.map(|stored| stored.account.clone())
|
|
.collect())
|
|
}
|
|
|
|
async fn list_for_provider(
|
|
&self,
|
|
provider: &ProviderKind,
|
|
include_disabled: bool,
|
|
) -> Result<Vec<ProviderAccount>, StoreError> {
|
|
self.provider_list_reads.fetch_add(1, Ordering::SeqCst);
|
|
if self.fail_provider_listing.load(Ordering::SeqCst) {
|
|
return Err(StoreError::caused_by(
|
|
StoreErrorKind::Unavailable,
|
|
std::io::Error::new(
|
|
std::io::ErrorKind::ConnectionRefused,
|
|
"PRIVATE_DATABASE_CAUSE",
|
|
),
|
|
));
|
|
}
|
|
Ok(self
|
|
.accounts
|
|
.lock()
|
|
.expect("account store lock")
|
|
.values()
|
|
.filter(|stored| {
|
|
stored.account.provider() == provider
|
|
&& (include_disabled || stored.account.enabled())
|
|
})
|
|
.map(|stored| stored.account.clone())
|
|
.collect())
|
|
}
|
|
|
|
async fn list_for_provider_accounts(
|
|
&self,
|
|
provider: &ProviderKind,
|
|
account_ids: &[ProviderAccountId],
|
|
) -> Result<Vec<ProviderAccount>, StoreError> {
|
|
if account_ids.is_empty() {
|
|
return Ok(Vec::new());
|
|
}
|
|
self.provider_list_reads.fetch_add(1, Ordering::SeqCst);
|
|
if self.fail_provider_listing.load(Ordering::SeqCst) {
|
|
return Err(StoreError::caused_by(
|
|
StoreErrorKind::Unavailable,
|
|
std::io::Error::new(
|
|
std::io::ErrorKind::ConnectionRefused,
|
|
"PRIVATE_DATABASE_CAUSE",
|
|
),
|
|
));
|
|
}
|
|
// 与 Postgres 实现的调度列表语义一致:停用账号不进入常规候选
|
|
let accounts = self.accounts.lock().unwrap();
|
|
Ok(account_ids
|
|
.iter()
|
|
.collect::<std::collections::BTreeSet<_>>()
|
|
.into_iter()
|
|
.filter_map(|id| accounts.get(id))
|
|
.filter(|stored| stored.account.provider() == provider && stored.account.enabled())
|
|
.map(|stored| stored.account.clone())
|
|
.collect())
|
|
}
|
|
|
|
async fn list_refresh_candidates(
|
|
&self,
|
|
query: ProviderRefreshQuery,
|
|
) -> Result<Vec<LoadedCredential>, StoreError> {
|
|
let mut candidates = self
|
|
.accounts
|
|
.lock()
|
|
.expect("account store lock")
|
|
.values()
|
|
.filter(|stored| query.contains(&stored.account))
|
|
.map(|stored| LoadedCredential {
|
|
account: stored.account.clone(),
|
|
credential: stored.credential.clone(),
|
|
})
|
|
.collect::<Vec<_>>();
|
|
candidates.sort_by_key(|loaded| {
|
|
(
|
|
loaded.account.access_token_expires_at(),
|
|
loaded.account.id().clone(),
|
|
)
|
|
});
|
|
candidates.truncate(query.limit().get() as usize);
|
|
Ok(candidates)
|
|
}
|
|
|
|
async fn load_credential(
|
|
&self,
|
|
account: &ProviderAccountId,
|
|
expected_revision: CredentialRevision,
|
|
) -> Result<LoadedCredential, StoreError> {
|
|
let count = self.credential_loads.fetch_add(1, Ordering::SeqCst) + 1;
|
|
let hook = self
|
|
.credential_load_hook
|
|
.lock()
|
|
.expect("credential hook lock")
|
|
.clone();
|
|
// 在列表快照与凭据读取之间确定性提交并发变更,不依赖线程调度或延时
|
|
if let Some(hook) = hook {
|
|
hook(self, account, count).await?;
|
|
}
|
|
let loaded = self.load_current_credential(account).await?;
|
|
if loaded.account.revision() != expected_revision {
|
|
return Err(store_error(StoreErrorKind::Conflict));
|
|
}
|
|
Ok(loaded)
|
|
}
|
|
|
|
async fn load_current_credential(
|
|
&self,
|
|
account: &ProviderAccountId,
|
|
) -> Result<LoadedCredential, StoreError> {
|
|
let accounts = self.accounts.lock().expect("account store lock");
|
|
let stored = accounts
|
|
.get(account)
|
|
.ok_or_else(|| store_error(StoreErrorKind::InvalidData))?;
|
|
Ok(LoadedCredential {
|
|
account: stored.account.clone(),
|
|
credential: stored.credential.clone(),
|
|
})
|
|
}
|
|
|
|
async fn compare_and_swap_credential(
|
|
&self,
|
|
update: CredentialCasUpdate,
|
|
) -> Result<CredentialCasOutcome, StoreError> {
|
|
let CredentialCasUpdateParts {
|
|
account_id,
|
|
expected_revision,
|
|
profile,
|
|
preserve_profile,
|
|
preserve_access_token_expiry,
|
|
credential,
|
|
has_refresh_token,
|
|
access_token_expires_at,
|
|
next_refresh_at,
|
|
account_state,
|
|
} = update.into_parts();
|
|
let mut accounts = self.accounts.lock().expect("account store lock");
|
|
let stored = accounts
|
|
.get_mut(&account_id)
|
|
.ok_or_else(|| store_error(StoreErrorKind::InvalidData))?;
|
|
if stored.account.revision() != expected_revision {
|
|
return Ok(CredentialCasOutcome::Conflict);
|
|
}
|
|
let access_token_expires_at = if preserve_access_token_expiry {
|
|
stored.account.access_token_expires_at()
|
|
} else {
|
|
access_token_expires_at
|
|
};
|
|
let next = expected_revision
|
|
.next()
|
|
.map_err(|_| store_error(StoreErrorKind::Conflict))?;
|
|
let credential_state = account_state
|
|
.as_ref()
|
|
.map_or(stored.account.credential_state(), |state| {
|
|
state.credential_state
|
|
});
|
|
let last_error_reason = account_state.as_ref().map_or_else(
|
|
|| stored.account.last_error_reason(),
|
|
|state| state.error_reason,
|
|
);
|
|
let last_error_message = account_state.as_ref().map_or_else(
|
|
|| stored.account.last_error_message().map(str::to_owned),
|
|
|state| state.message.clone(),
|
|
);
|
|
let state_observed_at = account_state.as_ref().map(|state| state.observed_at);
|
|
stored.account = rebuild_account(
|
|
&stored.account,
|
|
AccountRebuild {
|
|
revision: next,
|
|
enabled: stored.account.enabled(),
|
|
credential_state,
|
|
quota: stored.account.quota(),
|
|
last_error_reason,
|
|
last_error_message,
|
|
access_token_expires_at,
|
|
has_refresh_token,
|
|
next_refresh_at,
|
|
profile: (!preserve_profile).then_some((
|
|
profile.name,
|
|
profile.email,
|
|
profile.plan_type,
|
|
)),
|
|
},
|
|
);
|
|
stored.credential = credential;
|
|
stored.quota = None;
|
|
if let Some(observed_at) = state_observed_at {
|
|
stored.state_observed_at = Some(observed_at);
|
|
}
|
|
Ok(CredentialCasOutcome::Updated(next))
|
|
}
|
|
|
|
async fn get_quotas(
|
|
&self,
|
|
accounts: &[ProviderAccountId],
|
|
) -> Result<Vec<QuotaObservation>, StoreError> {
|
|
self.quota_reads.fetch_add(1, Ordering::SeqCst);
|
|
self.largest_quota_read
|
|
.fetch_max(accounts.len(), Ordering::SeqCst);
|
|
let result = {
|
|
let stored = self.accounts.lock().expect("account store lock");
|
|
accounts
|
|
.iter()
|
|
.filter_map(|account| stored.get(account)?.quota.clone())
|
|
.collect()
|
|
};
|
|
let held = self.next_quota_read.lock().unwrap().take();
|
|
if let Some((read, held)) = held {
|
|
read.send(()).unwrap();
|
|
held.await.expect("release quota read");
|
|
}
|
|
Ok(result)
|
|
}
|
|
|
|
async fn get_quota_versions(
|
|
&self,
|
|
ids: &[ProviderAccountId],
|
|
) -> Result<Vec<gateway_core::account::QuotaObservationVersion>, StoreError> {
|
|
let accounts = self.accounts.lock().unwrap();
|
|
Ok(ids
|
|
.iter()
|
|
.filter_map(|id| {
|
|
let stored = accounts.get(id)?;
|
|
let quota = stored.quota.as_ref()?;
|
|
Some(gateway_core::account::QuotaObservationVersion {
|
|
account_id: id.clone(),
|
|
credential_revision: stored.account.revision(),
|
|
observed_at: quota.observed_at,
|
|
})
|
|
})
|
|
.collect())
|
|
}
|
|
|
|
async fn compare_and_swap_quota(
|
|
&self,
|
|
mut observation: QuotaObservation,
|
|
) -> Result<QuotaWriteOutcome, StoreError> {
|
|
let mut accounts = self.accounts.lock().expect("account store lock");
|
|
let stored = accounts
|
|
.get_mut(&observation.account_id)
|
|
.ok_or_else(|| store_error(StoreErrorKind::InvalidData))?;
|
|
if stored.account.revision() != observation.expected_revision
|
|
|| observation
|
|
.expected_connection
|
|
.as_ref()
|
|
.is_some_and(|connection| {
|
|
!stored.account.enabled()
|
|
|| gateway_core::account::UpstreamConnection::for_account(&stored.account)
|
|
!= *connection
|
|
})
|
|
{
|
|
return Ok(QuotaWriteOutcome::Conflict);
|
|
}
|
|
let current_version = stored.quota.as_ref().map(|quota| quota.observed_at);
|
|
if observation.quota_pause.as_ref().is_some_and(|decision| {
|
|
&decision.limits != stored.account.quota_settings()
|
|
|| current_version == Some(observation.observed_at)
|
|
|| decision
|
|
.merge_base
|
|
.is_some_and(|base| base.observed_at != current_version)
|
|
}) {
|
|
return Ok(QuotaWriteOutcome::Conflict);
|
|
}
|
|
if stored
|
|
.quota
|
|
.as_ref()
|
|
.is_some_and(|quota| quota.observed_at > observation.observed_at)
|
|
{
|
|
return Ok(QuotaWriteOutcome::Conflict);
|
|
}
|
|
// 与 PostgreSQL 一致,展示快照与访问事实分别按各自观察时间隔离
|
|
let current = stored.account.quota();
|
|
let quota = if observation
|
|
.state
|
|
.observed_at()
|
|
.is_some_and(|observed| current.observed_at().is_none_or(|time| time <= observed))
|
|
{
|
|
observation.state
|
|
} else {
|
|
current
|
|
};
|
|
observation.state = quota;
|
|
let mut replacement = AccountRebuild::preserving(&stored.account).with_quota(quota);
|
|
if let Some(plan_type) = &observation.plan_type {
|
|
replacement.profile = Some((
|
|
stored.account.name().to_owned(),
|
|
stored.account.email().map(str::to_owned),
|
|
Some(plan_type.clone()),
|
|
));
|
|
}
|
|
let paused = observation.quota_pause.as_ref().is_some_and(|v| v.paused);
|
|
stored.quota = Some(observation);
|
|
stored.account = rebuild_account(&stored.account, replacement)
|
|
.with_quota_settings(stored.account.quota_settings().clone(), paused);
|
|
Ok(QuotaWriteOutcome::Updated)
|
|
}
|
|
|
|
async fn touch_quota_observation(
|
|
&self,
|
|
touch: QuotaObservationTouch,
|
|
) -> Result<QuotaWriteOutcome, StoreError> {
|
|
let mut accounts = self.accounts.lock().expect("account store lock");
|
|
let stored = accounts
|
|
.get_mut(&touch.account_id)
|
|
.ok_or_else(|| store_error(StoreErrorKind::InvalidData))?;
|
|
if stored.account.revision() != touch.expected_revision {
|
|
return Ok(QuotaWriteOutcome::Conflict);
|
|
}
|
|
let Some(quota) = &mut stored.quota else {
|
|
return Ok(QuotaWriteOutcome::Conflict);
|
|
};
|
|
if quota.observed_at > touch.observed_at {
|
|
return Ok(QuotaWriteOutcome::Conflict);
|
|
}
|
|
quota.observed_at = touch.observed_at;
|
|
Ok(QuotaWriteOutcome::Updated)
|
|
}
|
|
|
|
async fn apply_quota_access(
|
|
&self,
|
|
change: QuotaAccessChange,
|
|
) -> Result<QuotaWriteOutcome, StoreError> {
|
|
let mut accounts = self.accounts.lock().expect("account store lock");
|
|
let stored = accounts
|
|
.get_mut(&change.account_id)
|
|
.ok_or_else(|| store_error(StoreErrorKind::InvalidData))?;
|
|
if stored.account.revision() != change.expected_revision {
|
|
return Ok(QuotaWriteOutcome::Conflict);
|
|
}
|
|
stored.account = rebuild_account(
|
|
&stored.account,
|
|
AccountRebuild::preserving(&stored.account).with_quota(change.state),
|
|
);
|
|
if let Some(observation) = &mut stored.quota {
|
|
observation.state = change.state;
|
|
}
|
|
Ok(QuotaWriteOutcome::Updated)
|
|
}
|
|
|
|
async fn expire_access_token(
|
|
&self,
|
|
account: &ProviderAccount,
|
|
observed_at: SystemTime,
|
|
) -> Result<bool, StoreError> {
|
|
let mut accounts = self.accounts.lock().expect("account store lock");
|
|
let Some(stored) = accounts.get_mut(account.id()) else {
|
|
return Ok(false);
|
|
};
|
|
if stored.account.revision() != account.revision()
|
|
|| stored
|
|
.state_observed_at
|
|
.is_some_and(|current| current > observed_at)
|
|
{
|
|
return Ok(false);
|
|
}
|
|
let mut facts = AccountRebuild::preserving(&stored.account);
|
|
facts.access_token_expires_at = Some(
|
|
facts
|
|
.access_token_expires_at
|
|
.map_or(observed_at, |at| at.min(observed_at)),
|
|
);
|
|
stored.account = rebuild_account(&stored.account, facts);
|
|
Ok(true)
|
|
}
|
|
|
|
async fn apply_state_change(&self, change: AccountStateChange) -> Result<(), StoreError> {
|
|
let mut accounts = self.accounts.lock().expect("account store lock");
|
|
let stored = accounts
|
|
.get_mut(&change.account_id)
|
|
.ok_or_else(|| store_error(StoreErrorKind::InvalidData))?;
|
|
if stored.account.revision() != change.expected_revision {
|
|
return Err(store_error(StoreErrorKind::Conflict));
|
|
}
|
|
if stored
|
|
.state_observed_at
|
|
.is_some_and(|current| current > change.observed_at)
|
|
{
|
|
return Err(store_error(StoreErrorKind::Conflict));
|
|
}
|
|
stored.account = rebuild_account(
|
|
&stored.account,
|
|
AccountRebuild {
|
|
revision: stored.account.revision(),
|
|
enabled: stored.account.enabled(),
|
|
credential_state: change.credential_state,
|
|
quota: stored.account.quota(),
|
|
last_error_reason: change.error_reason,
|
|
last_error_message: change.message,
|
|
access_token_expires_at: stored.account.access_token_expires_at(),
|
|
has_refresh_token: stored.account.has_refresh_token(),
|
|
next_refresh_at: stored.account.next_refresh_at(),
|
|
profile: None,
|
|
},
|
|
);
|
|
stored.state_observed_at = Some(change.observed_at);
|
|
Ok(())
|
|
}
|
|
|
|
async fn update_account(&self, update: ProviderAccountUpdate) -> Result<(), StoreError> {
|
|
let mut accounts = self.accounts.lock().expect("account store lock");
|
|
let stored = accounts
|
|
.get_mut(&update.account_id)
|
|
.ok_or_else(|| store_error(StoreErrorKind::InvalidData))?;
|
|
stored.account = rebuild_account(
|
|
&stored.account,
|
|
AccountRebuild {
|
|
revision: stored.account.revision(),
|
|
enabled: stored.account.enabled(),
|
|
credential_state: stored.account.credential_state(),
|
|
quota: stored.account.quota(),
|
|
last_error_reason: stored.account.last_error_reason(),
|
|
last_error_message: stored.account.last_error_message().map(str::to_owned),
|
|
access_token_expires_at: stored.account.access_token_expires_at(),
|
|
has_refresh_token: stored.account.has_refresh_token(),
|
|
next_refresh_at: stored.account.next_refresh_at(),
|
|
profile: Some((update.name, update.email, update.plan_type)),
|
|
},
|
|
);
|
|
Ok(())
|
|
}
|
|
|
|
async fn set_enabled(
|
|
&self,
|
|
account: &ProviderAccountId,
|
|
enabled: bool,
|
|
) -> Result<(), StoreError> {
|
|
let mut accounts = self.accounts.lock().expect("account store lock");
|
|
let stored = accounts
|
|
.get_mut(account)
|
|
.ok_or_else(|| store_error(StoreErrorKind::InvalidData))?;
|
|
stored.account = rebuild_account(
|
|
&stored.account,
|
|
AccountRebuild {
|
|
revision: stored.account.revision(),
|
|
enabled,
|
|
credential_state: stored.account.credential_state(),
|
|
quota: stored.account.quota(),
|
|
last_error_reason: stored.account.last_error_reason(),
|
|
last_error_message: stored.account.last_error_message().map(str::to_owned),
|
|
access_token_expires_at: stored.account.access_token_expires_at(),
|
|
has_refresh_token: stored.account.has_refresh_token(),
|
|
next_refresh_at: stored.account.next_refresh_at(),
|
|
profile: None,
|
|
},
|
|
);
|
|
Ok(())
|
|
}
|
|
|
|
async fn delete_account(&self, account: &ProviderAccountId) -> Result<(), StoreError> {
|
|
self.accounts
|
|
.lock()
|
|
.expect("account store lock")
|
|
.remove(account)
|
|
.ok_or_else(|| store_error(StoreErrorKind::InvalidData))?;
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
const fn store_error(kind: StoreErrorKind) -> StoreError {
|
|
StoreError::new(kind)
|
|
}
|
|
|
|
struct AccountRebuild {
|
|
revision: CredentialRevision,
|
|
enabled: bool,
|
|
credential_state: CredentialState,
|
|
quota: QuotaState,
|
|
last_error_reason: Option<AccountErrorReason>,
|
|
last_error_message: Option<String>,
|
|
access_token_expires_at: Option<SystemTime>,
|
|
has_refresh_token: bool,
|
|
next_refresh_at: Option<SystemTime>,
|
|
profile: Option<(String, Option<String>, Option<String>)>,
|
|
}
|
|
|
|
impl AccountRebuild {
|
|
fn preserving(account: &ProviderAccount) -> Self {
|
|
Self {
|
|
revision: account.revision(),
|
|
enabled: account.enabled(),
|
|
credential_state: account.credential_state(),
|
|
quota: account.quota(),
|
|
last_error_reason: account.last_error_reason(),
|
|
last_error_message: account.last_error_message().map(str::to_owned),
|
|
access_token_expires_at: account.access_token_expires_at(),
|
|
has_refresh_token: account.has_refresh_token(),
|
|
next_refresh_at: account.next_refresh_at(),
|
|
profile: None,
|
|
}
|
|
}
|
|
|
|
fn with_quota(mut self, quota: QuotaState) -> Self {
|
|
self.quota = quota;
|
|
self
|
|
}
|
|
}
|
|
|
|
fn rebuild_account(current: &ProviderAccount, rebuild: AccountRebuild) -> ProviderAccount {
|
|
let (name, email, plan_type) = rebuild.profile.unwrap_or_else(|| {
|
|
(
|
|
current.name().to_owned(),
|
|
current.email().map(str::to_owned),
|
|
current.plan_type().map(str::to_owned),
|
|
)
|
|
});
|
|
ProviderAccount::new(
|
|
current.id().clone(),
|
|
current.provider().clone(),
|
|
name,
|
|
current.upstream_user_id().map(str::to_owned),
|
|
current.authentication_kind().to_owned(),
|
|
rebuild.revision,
|
|
rebuild.access_token_expires_at,
|
|
)
|
|
.with_profile(
|
|
email,
|
|
current.upstream_account_id().map(str::to_owned),
|
|
plan_type,
|
|
)
|
|
.with_account_facts(
|
|
rebuild.enabled,
|
|
rebuild.credential_state,
|
|
rebuild.quota,
|
|
rebuild.last_error_reason,
|
|
rebuild.last_error_message,
|
|
)
|
|
.with_scheduling(current.concurrency_limit(), current.weight())
|
|
.with_quota_settings(current.quota_settings().clone(), current.quota_paused())
|
|
.with_auto_use_quota_credits(current.auto_use_quota_credits())
|
|
.with_refresh_schedule(rebuild.has_refresh_token, rebuild.next_refresh_at)
|
|
.with_outbound_proxy(current.outbound_proxy().cloned())
|
|
.with_request_location(current.request_location().cloned())
|
|
}
|
|
|
|
#[derive(Default)]
|
|
pub(crate) struct TestLeaseCoordinator {
|
|
pub(crate) requests: Mutex<Vec<ProviderSchedulingLeaseRequest>>,
|
|
pub(crate) busy: Mutex<bool>,
|
|
pub(crate) busy_accounts: Mutex<BTreeSet<ProviderAccountId>>,
|
|
pub(crate) signals: Mutex<BTreeMap<ProviderAccountId, AccountRuntimeSignals>>,
|
|
pub(crate) reserved_signals: Mutex<BTreeMap<ProviderAccountId, AccountRuntimeSignals>>,
|
|
round_robin_cursor: Mutex<u64>,
|
|
}
|
|
|
|
impl ProviderLeasePort for TestLeaseCoordinator {
|
|
fn load_state<'a>(
|
|
&'a self,
|
|
_client_api_key_id: &'a ClientApiKeyId,
|
|
_provider_kind: &'a ProviderKind,
|
|
accounts: &'a [ProviderAccountId],
|
|
pool: gateway_core::provider_ports::ProviderConcurrencyPool,
|
|
) -> BoxFuture<'a, Result<ProviderSchedulingState, ProviderStoreError>> {
|
|
Box::pin(async move {
|
|
let overrides = match pool {
|
|
gateway_core::provider_ports::ProviderConcurrencyPool::Shared => &self.signals,
|
|
gateway_core::provider_ports::ProviderConcurrencyPool::Reserved => {
|
|
&self.reserved_signals
|
|
}
|
|
}
|
|
.lock()
|
|
.expect("scheduling signals lock");
|
|
let signals = accounts
|
|
.iter()
|
|
.map(|account| {
|
|
(
|
|
account.clone(),
|
|
overrides
|
|
.get(account)
|
|
.cloned()
|
|
.unwrap_or(AccountRuntimeSignals {
|
|
in_flight: 0,
|
|
last_started_at: None,
|
|
quota_reset_at: None,
|
|
quota_reset_windows: None,
|
|
quota_remaining_rank: None,
|
|
cooldown: None,
|
|
failure_rate_basis_points: None,
|
|
first_output_latency_ms: None,
|
|
}),
|
|
)
|
|
})
|
|
.collect();
|
|
let mut cursor = self
|
|
.round_robin_cursor
|
|
.lock()
|
|
.expect("round robin cursor lock");
|
|
let current = *cursor;
|
|
*cursor = cursor.wrapping_add(1);
|
|
Ok(ProviderSchedulingState::new(signals, current))
|
|
})
|
|
}
|
|
|
|
fn try_acquire(
|
|
&self,
|
|
request: ProviderLeaseRequest,
|
|
) -> BoxFuture<'_, Result<ProviderLeaseAcquisition, ProviderStoreError>> {
|
|
Box::pin(async move {
|
|
let ProviderLeaseRequest::Scheduling(request) = request else {
|
|
panic!("expected scheduling lease request");
|
|
};
|
|
let account_busy = self
|
|
.busy_accounts
|
|
.lock()
|
|
.expect("busy account lock")
|
|
.contains(request.account_id());
|
|
self.requests
|
|
.lock()
|
|
.expect("lease requests lock")
|
|
.push(request);
|
|
if *self.busy.lock().expect("lease busy lock") || account_busy {
|
|
Ok(ProviderLeaseAcquisition::Busy {
|
|
retry_after: Some(Duration::from_millis(25)),
|
|
})
|
|
} else {
|
|
Ok(ProviderLeaseAcquisition::Acquired(Box::new(())))
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
#[derive(Default)]
|
|
pub(crate) struct MemorySessionAffinity {
|
|
cursors: Mutex<BTreeMap<(ClientApiKeyId, ProviderKind), u64>>,
|
|
operation_delay: Duration,
|
|
initial_claim_barrier: Option<Arc<tokio::sync::Barrier>>,
|
|
aliases: Mutex<BTreeMap<(String, String), gateway_core::provider_ports::ProviderSessionAlias>>,
|
|
bindings:
|
|
Mutex<BTreeMap<(String, String), gateway_core::provider_ports::ProviderSessionBinding>>,
|
|
lookups: Mutex<Vec<String>>,
|
|
renewal_ttls: Mutex<Vec<Duration>>,
|
|
alias_ttls: Mutex<Vec<Duration>>,
|
|
}
|
|
|
|
impl MemorySessionAffinity {
|
|
pub(crate) fn with_operation_delay(operation_delay: Duration) -> Self {
|
|
Self {
|
|
operation_delay,
|
|
..Self::default()
|
|
}
|
|
}
|
|
|
|
async fn delay_operation(&self) {
|
|
if !self.operation_delay.is_zero() {
|
|
tokio::time::sleep(self.operation_delay).await;
|
|
}
|
|
}
|
|
|
|
pub(crate) fn with_initial_claim_barrier(participants: usize) -> Self {
|
|
Self {
|
|
initial_claim_barrier: Some(Arc::new(tokio::sync::Barrier::new(participants))),
|
|
..Self::default()
|
|
}
|
|
}
|
|
|
|
pub(crate) fn alias_ttls(&self) -> Vec<Duration> {
|
|
self.alias_ttls.lock().unwrap().clone()
|
|
}
|
|
|
|
pub(crate) fn renewal_ttls(&self) -> Vec<Duration> {
|
|
self.renewal_ttls.lock().expect("affinity TTL lock").clone()
|
|
}
|
|
|
|
pub(crate) fn lookup_keys(&self) -> Vec<String> {
|
|
self.lookups.lock().expect("session affinity lock").clone()
|
|
}
|
|
|
|
pub(crate) fn binding_count(&self) -> usize {
|
|
self.bindings.lock().expect("session affinity lock").len()
|
|
}
|
|
|
|
pub(crate) fn seed_binding(
|
|
&self,
|
|
provider_kind: &ProviderKind,
|
|
key: &str,
|
|
account_id: ProviderAccountId,
|
|
) {
|
|
self.bindings.lock().expect("session affinity lock").insert(
|
|
(provider_kind.as_str().to_owned(), key.to_owned()),
|
|
gateway_core::provider_ports::ProviderSessionBinding::new(
|
|
account_id,
|
|
uuid::Uuid::new_v4().simple().to_string(),
|
|
)
|
|
.expect("binding"),
|
|
);
|
|
}
|
|
pub(crate) async fn bind(
|
|
&self,
|
|
provider: &ProviderKind,
|
|
key: &ProviderSessionAffinityKey,
|
|
account: &ProviderAccountId,
|
|
_ttl: Duration,
|
|
) -> Result<(), ProviderStoreError> {
|
|
self.seed_binding(provider, key.expose_to_store(), account.clone());
|
|
Ok(())
|
|
}
|
|
|
|
pub(crate) async fn load(
|
|
&self,
|
|
provider: &ProviderKind,
|
|
key: &ProviderSessionAffinityKey,
|
|
) -> Result<Option<ProviderAccountId>, ProviderStoreError> {
|
|
ProviderSessionAffinityPort::load(self, provider, key)
|
|
.await
|
|
.map(|binding| binding.map(|binding| binding.account_id().clone()))
|
|
}
|
|
}
|
|
|
|
impl ProviderSessionAffinityPort for MemorySessionAffinity {
|
|
fn load<'a>(
|
|
&'a self,
|
|
provider: &'a ProviderKind,
|
|
key: &'a ProviderSessionAffinityKey,
|
|
) -> BoxFuture<
|
|
'a,
|
|
Result<Option<gateway_core::provider_ports::ProviderSessionBinding>, ProviderStoreError>,
|
|
> {
|
|
Box::pin(async move {
|
|
self.delay_operation().await;
|
|
self.lookups
|
|
.lock()
|
|
.expect("lookups")
|
|
.push(key.expose_to_store().to_owned());
|
|
Ok(self
|
|
.bindings
|
|
.lock()
|
|
.expect("bindings")
|
|
.get(&(
|
|
provider.as_str().to_owned(),
|
|
key.expose_to_store().to_owned(),
|
|
))
|
|
.cloned())
|
|
})
|
|
}
|
|
|
|
fn round_robin_cursor<'a>(
|
|
&'a self,
|
|
provider: &'a ProviderKind,
|
|
client: &'a ClientApiKeyId,
|
|
) -> BoxFuture<'a, Result<u64, ProviderStoreError>> {
|
|
Box::pin(async move {
|
|
Ok(self
|
|
.cursors
|
|
.lock()
|
|
.unwrap()
|
|
.get(&(client.clone(), provider.clone()))
|
|
.copied()
|
|
.unwrap_or_default())
|
|
})
|
|
}
|
|
|
|
fn admit_account<'a>(
|
|
&'a self,
|
|
provider: &'a ProviderKind,
|
|
admission: ProviderAccountAdmission<'a>,
|
|
) -> BoxFuture<'a, Result<bool, ProviderStoreError>> {
|
|
Box::pin(async move {
|
|
self.delay_operation().await;
|
|
if admission
|
|
.session()
|
|
.is_some_and(|claim| claim.expected.is_none())
|
|
&& let Some(barrier) = &self.initial_claim_barrier
|
|
{
|
|
barrier.wait().await;
|
|
}
|
|
let mut cursors = self.cursors.lock().unwrap();
|
|
let step = if let ProviderAccountAdmission::RoundRobin {
|
|
client_key, cursor, ..
|
|
} = admission
|
|
{
|
|
let current = cursors
|
|
.entry((client_key.clone(), provider.clone()))
|
|
.or_default();
|
|
if *current != cursor {
|
|
return Ok(false);
|
|
}
|
|
Some(current)
|
|
} else {
|
|
None
|
|
};
|
|
if let Some(claim) = admission.session() {
|
|
let key = (
|
|
provider.as_str().to_owned(),
|
|
claim.key.expose_to_store().to_owned(),
|
|
);
|
|
let mut bindings = self.bindings.lock().unwrap();
|
|
if bindings.get(&key) != claim.expected {
|
|
return Ok(false);
|
|
}
|
|
let binding = match claim.expected.filter(|b| b.account_id() == claim.account) {
|
|
Some(binding) => binding.clone(),
|
|
None => ProviderSessionBinding::new(
|
|
claim.account.clone(),
|
|
uuid::Uuid::new_v4().simple().to_string(),
|
|
)?,
|
|
};
|
|
bindings.insert(key, binding);
|
|
self.renewal_ttls.lock().unwrap().push(claim.ttl);
|
|
}
|
|
if let Some(cursor) = step {
|
|
*cursor = cursor.wrapping_add(1);
|
|
}
|
|
Ok(true)
|
|
})
|
|
}
|
|
|
|
fn load_alias<'a>(
|
|
&'a self,
|
|
provider: &'a ProviderKind,
|
|
alias: &'a ProviderSessionAffinityKey,
|
|
) -> BoxFuture<
|
|
'a,
|
|
Result<Option<gateway_core::provider_ports::ProviderSessionAlias>, ProviderStoreError>,
|
|
> {
|
|
Box::pin(async move {
|
|
self.delay_operation().await;
|
|
Ok(self
|
|
.aliases
|
|
.lock()
|
|
.unwrap()
|
|
.get(&(
|
|
provider.as_str().to_owned(),
|
|
alias.expose_to_store().to_owned(),
|
|
))
|
|
.cloned())
|
|
})
|
|
}
|
|
fn bind_alias<'a>(
|
|
&'a self,
|
|
provider: &'a ProviderKind,
|
|
alias: &'a ProviderSessionAffinityKey,
|
|
session: &'a gateway_core::provider_ports::ProviderSessionAlias,
|
|
ttl: Duration,
|
|
) -> BoxFuture<'a, Result<bool, ProviderStoreError>> {
|
|
Box::pin(async move {
|
|
self.delay_operation().await;
|
|
let mut aliases = self.aliases.lock().unwrap();
|
|
let current = aliases
|
|
.entry((
|
|
provider.as_str().to_owned(),
|
|
alias.expose_to_store().to_owned(),
|
|
))
|
|
.or_insert_with(|| session.clone());
|
|
let applied = current == session;
|
|
if applied {
|
|
self.alias_ttls.lock().unwrap().push(ttl);
|
|
}
|
|
Ok(applied)
|
|
})
|
|
}
|
|
}
|
|
|
|
#[derive(Default)]
|
|
pub(crate) struct MemorySessionExclusions {
|
|
states: Mutex<BTreeMap<(String, String), ProviderSessionExclusions>>,
|
|
revision: AtomicUsize,
|
|
}
|
|
|
|
impl ProviderSessionExclusionPort for MemorySessionExclusions {
|
|
fn load<'a>(
|
|
&'a self,
|
|
provider_kind: &'a ProviderKind,
|
|
key: &'a ProviderSessionAffinityKey,
|
|
) -> BoxFuture<'a, Result<Option<ProviderSessionExclusions>, ProviderStoreError>> {
|
|
Box::pin(async move {
|
|
Ok(self
|
|
.states
|
|
.lock()
|
|
.expect("session exclusion lock")
|
|
.get(&(
|
|
provider_kind.as_str().to_owned(),
|
|
key.expose_to_store().to_owned(),
|
|
))
|
|
.cloned())
|
|
})
|
|
}
|
|
|
|
fn record_failure<'a>(
|
|
&'a self,
|
|
provider_kind: &'a ProviderKind,
|
|
key: &'a ProviderSessionAffinityKey,
|
|
account_id: &'a ProviderAccountId,
|
|
_ttl: Duration,
|
|
) -> BoxFuture<'a, Result<ProviderSessionExclusions, ProviderStoreError>> {
|
|
Box::pin(async move {
|
|
let key = (
|
|
provider_kind.as_str().to_owned(),
|
|
key.expose_to_store().to_owned(),
|
|
);
|
|
let mut states = self.states.lock().expect("session exclusion lock");
|
|
let mut excluded_accounts = states
|
|
.get(&key)
|
|
.map(|state| state.excluded_accounts().clone())
|
|
.unwrap_or_default();
|
|
excluded_accounts.insert(account_id.clone());
|
|
let state = ProviderSessionExclusions::new(
|
|
excluded_accounts,
|
|
self.revision.fetch_add(1, Ordering::SeqCst).to_string(),
|
|
);
|
|
states.insert(key, state.clone());
|
|
Ok(state)
|
|
})
|
|
}
|
|
|
|
fn clear<'a>(
|
|
&'a self,
|
|
provider_kind: &'a ProviderKind,
|
|
key: &'a ProviderSessionAffinityKey,
|
|
expected_revision: &'a str,
|
|
) -> BoxFuture<'a, Result<bool, ProviderStoreError>> {
|
|
Box::pin(async move {
|
|
let key = (
|
|
provider_kind.as_str().to_owned(),
|
|
key.expose_to_store().to_owned(),
|
|
);
|
|
let mut states = self.states.lock().expect("session exclusion lock");
|
|
if states
|
|
.get(&key)
|
|
.is_some_and(|state| state.revision() == expected_revision)
|
|
{
|
|
states.remove(&key);
|
|
Ok(true)
|
|
} else {
|
|
Ok(false)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
#[derive(Default)]
|
|
pub(crate) struct MemoryCatalogCache {
|
|
values: Mutex<BTreeMap<String, OpaqueProviderData>>,
|
|
}
|
|
|
|
impl ProviderCatalogCachePort for MemoryCatalogCache {
|
|
fn replace<'a>(
|
|
&'a self,
|
|
key: &'a ProviderCatalogCacheKey,
|
|
catalog: &'a OpaqueProviderData,
|
|
_ttl: Duration,
|
|
) -> BoxFuture<'a, Result<(), ProviderStoreError>> {
|
|
Box::pin(async move {
|
|
self.values
|
|
.lock()
|
|
.expect("catalog cache")
|
|
.insert(key.scope().as_str().to_owned(), catalog.clone());
|
|
Ok(())
|
|
})
|
|
}
|
|
|
|
fn read<'a>(
|
|
&'a self,
|
|
key: &'a ProviderCatalogCacheKey,
|
|
) -> BoxFuture<'a, Result<Option<OpaqueProviderData>, ProviderStoreError>> {
|
|
Box::pin(async move {
|
|
Ok(self
|
|
.values
|
|
.lock()
|
|
.expect("catalog cache")
|
|
.get(key.scope().as_str())
|
|
.cloned())
|
|
})
|
|
}
|
|
}
|
|
|
|
pub(crate) fn catalog_cache() -> Arc<dyn ProviderCatalogCachePort> {
|
|
Arc::new(MemoryCatalogCache::default())
|
|
}
|
|
|
|
pub(crate) fn profile(account_id: &str) -> CodexAccountProfile {
|
|
let now = chrono::Utc::now();
|
|
CodexAccountProfile {
|
|
oauth_subject: format!("subject-{account_id}"),
|
|
poid: Some(format!("poid-{account_id}")),
|
|
chatgpt_account_id: account_id.to_owned(),
|
|
chatgpt_user_id: format!("user-{account_id}"),
|
|
email: Some(format!("{account_id}@example.com")),
|
|
plan_type: Some("pro".to_owned()),
|
|
access_token_expires_at: Some(now + chrono::Duration::hours(1)),
|
|
}
|
|
}
|
|
|
|
pub(crate) struct RequestProfileRuntimePolicy(
|
|
pub(crate) std::sync::Mutex<gateway_core::account::OpaqueProviderData>,
|
|
);
|
|
|
|
impl gateway_core::provider_ports::ProviderRuntimePolicyPort for RequestProfileRuntimePolicy {
|
|
fn load_request_profile<'a>(
|
|
&'a self,
|
|
provider: &'a ProviderKind,
|
|
) -> futures::future::BoxFuture<
|
|
'a,
|
|
Result<
|
|
Option<gateway_core::account::OpaqueProviderData>,
|
|
gateway_core::provider_ports::ProviderStoreError,
|
|
>,
|
|
> {
|
|
assert_eq!(provider.as_str(), "openai");
|
|
let profile = self.0.lock().unwrap().clone();
|
|
Box::pin(async move { Ok(Some(profile)) })
|
|
}
|
|
|
|
fn load_refresh_policy(
|
|
&self,
|
|
) -> futures::future::BoxFuture<
|
|
'_,
|
|
Result<
|
|
gateway_core::provider_ports::ProviderRefreshPolicy,
|
|
gateway_core::provider_ports::ProviderStoreError,
|
|
>,
|
|
> {
|
|
Box::pin(async { crate::support::runtime_policy().load_refresh_policy().await })
|
|
}
|
|
}
|
|
|
|
pub(crate) struct StaticRuntimePolicy;
|
|
|
|
impl ProviderRuntimePolicyPort for StaticRuntimePolicy {
|
|
fn load_refresh_policy(
|
|
&self,
|
|
) -> BoxFuture<'_, Result<ProviderRefreshPolicy, ProviderStoreError>> {
|
|
Box::pin(async {
|
|
ProviderRefreshPolicy::try_new(
|
|
Duration::from_secs(60 * 60),
|
|
NonZeroU32::new(2).expect("positive concurrency"),
|
|
)
|
|
})
|
|
}
|
|
}
|
|
|
|
pub(crate) fn runtime_policy() -> Arc<dyn ProviderRuntimePolicyPort> {
|
|
Arc::new(StaticRuntimePolicy)
|
|
}
|
|
|
|
pub(crate) fn fedramp_secret(access_token: &str) -> CodexOAuthSecret {
|
|
use base64::Engine as _;
|
|
let mut credential = secret(access_token);
|
|
let claims = base64::engine::general_purpose::URL_SAFE_NO_PAD
|
|
.encode(br#"{"https://api.openai.com/auth":{"chatgpt_account_is_fedramp":true}}"#);
|
|
credential.id_token = Some(format!("header.{claims}.signature").into());
|
|
credential
|
|
}
|
|
|
|
pub(crate) fn secret(access_token: &str) -> CodexOAuthSecret {
|
|
CodexOAuthSecret {
|
|
access_token: SecretString::from(access_token.to_owned()),
|
|
refresh_token: Some(SecretString::from(format!("rt-{access_token}"))),
|
|
id_token: None,
|
|
}
|
|
}
|
|
|
|
pub(crate) fn account_policy() -> gateway_core::account::AccountSelectionPolicy {
|
|
gateway_core::account::AccountSelectionPolicy::new(
|
|
gateway_core::account::RotationStrategy::Smart,
|
|
NonZeroU32::new(2).expect("nonzero concurrency"),
|
|
)
|
|
.with_account_affinity(gateway_core::account::AccountAffinity::Strict)
|
|
}
|
|
|
|
type CooldownReadHook =
|
|
dyn Fn(ProviderAccountId) -> BoxFuture<'static, Result<(), ProviderStoreError>> + Send + Sync;
|
|
|
|
/// 内存账号与模型冷却端口,保留版本和到期时间供选号行为测试
|
|
#[derive(Clone, Default)]
|
|
pub(crate) struct MemoryCooldownPort {
|
|
pub(crate) cooldowns: Arc<Mutex<BTreeMap<ProviderAccountId, ProviderCooldown>>>,
|
|
pub(crate) scoped:
|
|
Arc<Mutex<BTreeMap<(ProviderAccountId, ProviderCooldownScope), ProviderScopedCooldown>>>,
|
|
before_read: Option<Arc<CooldownReadHook>>,
|
|
before_scoped_read: Option<Arc<CooldownReadHook>>,
|
|
}
|
|
|
|
impl MemoryCooldownPort {
|
|
#[must_use]
|
|
pub(crate) fn new() -> Self {
|
|
Self::default()
|
|
}
|
|
|
|
pub(crate) fn with_read_hook(mut self, hook: Arc<CooldownReadHook>) -> Self {
|
|
self.before_read = Some(hook);
|
|
self
|
|
}
|
|
|
|
pub(crate) fn with_scoped_read_hook(mut self, hook: Arc<CooldownReadHook>) -> Self {
|
|
self.before_scoped_read = Some(hook);
|
|
self
|
|
}
|
|
}
|
|
|
|
impl ProviderCooldownPort for MemoryCooldownPort {
|
|
fn read_many<'a>(
|
|
&'a self,
|
|
account_ids: &'a [ProviderAccountId],
|
|
) -> BoxFuture<'a, Vec<Result<Option<ProviderCooldown>, ProviderStoreError>>> {
|
|
Box::pin(async move {
|
|
let mut results = Vec::with_capacity(account_ids.len());
|
|
for batch in account_ids.chunks(128) {
|
|
results
|
|
.extend(futures::future::join_all(batch.iter().map(|id| self.read(id))).await);
|
|
}
|
|
results
|
|
})
|
|
}
|
|
|
|
fn read_scoped_many<'a>(
|
|
&'a self,
|
|
account_ids: &'a [ProviderAccountId],
|
|
scope: &'a ProviderCooldownScope,
|
|
) -> BoxFuture<'a, Vec<Result<Option<ProviderScopedCooldown>, ProviderStoreError>>> {
|
|
Box::pin(async move {
|
|
let mut results = Vec::with_capacity(account_ids.len());
|
|
for batch in account_ids.chunks(128) {
|
|
results.extend(
|
|
futures::future::join_all(batch.iter().map(|id| self.read_scoped(id, scope)))
|
|
.await,
|
|
);
|
|
}
|
|
results
|
|
})
|
|
}
|
|
|
|
fn put_if_later(
|
|
&self,
|
|
cooldown: ProviderCooldown,
|
|
) -> BoxFuture<'_, Result<bool, ProviderStoreError>> {
|
|
Box::pin(async move {
|
|
let mut cooldowns = self.cooldowns.lock().expect("cooldown lock");
|
|
let should_write = cooldowns.get(cooldown.account_id()).is_none_or(|current| {
|
|
current.credential_revision() < cooldown.credential_revision()
|
|
|| (current.credential_revision() == cooldown.credential_revision()
|
|
&& current.until() < cooldown.until())
|
|
});
|
|
if should_write {
|
|
cooldowns.insert(cooldown.account_id().clone(), cooldown);
|
|
}
|
|
Ok(should_write)
|
|
})
|
|
}
|
|
|
|
fn read<'a>(
|
|
&'a self,
|
|
account_id: &'a ProviderAccountId,
|
|
) -> BoxFuture<'a, Result<Option<ProviderCooldown>, ProviderStoreError>> {
|
|
Box::pin(async move {
|
|
if let Some(hook) = &self.before_read {
|
|
hook(account_id.clone()).await?;
|
|
}
|
|
Ok(self
|
|
.cooldowns
|
|
.lock()
|
|
.expect("cooldown lock")
|
|
.get(account_id)
|
|
.cloned())
|
|
})
|
|
}
|
|
|
|
fn clear<'a>(
|
|
&'a self,
|
|
_account_id: &'a ProviderAccountId,
|
|
_through_revision: CredentialRevision,
|
|
) -> BoxFuture<'a, Result<bool, ProviderStoreError>> {
|
|
Box::pin(async { Ok(false) })
|
|
}
|
|
|
|
fn put_scoped_if_later(
|
|
&self,
|
|
cooldown: ProviderScopedCooldown,
|
|
) -> BoxFuture<'_, Result<bool, ProviderStoreError>> {
|
|
Box::pin(async move {
|
|
let mut scoped = self.scoped.lock().unwrap();
|
|
let key = (cooldown.account_id().clone(), cooldown.scope().clone());
|
|
let should_write = scoped.get(&key).is_none_or(|current| {
|
|
current.credential_revision() < cooldown.credential_revision()
|
|
|| (current.credential_revision() == cooldown.credential_revision()
|
|
&& current.until() < cooldown.until())
|
|
});
|
|
if should_write {
|
|
scoped.insert(key, cooldown);
|
|
}
|
|
Ok(should_write)
|
|
})
|
|
}
|
|
|
|
fn read_scoped<'a>(
|
|
&'a self,
|
|
account_id: &'a ProviderAccountId,
|
|
scope: &'a ProviderCooldownScope,
|
|
) -> BoxFuture<'a, Result<Option<ProviderScopedCooldown>, ProviderStoreError>> {
|
|
Box::pin(async move {
|
|
if let Some(hook) = &self.before_scoped_read {
|
|
hook(account_id.clone()).await?;
|
|
}
|
|
Ok(self
|
|
.scoped
|
|
.lock()
|
|
.unwrap()
|
|
.get(&(account_id.clone(), scope.clone()))
|
|
.cloned())
|
|
})
|
|
}
|
|
|
|
fn clear_scoped<'a>(
|
|
&'a self,
|
|
_account_id: &'a ProviderAccountId,
|
|
_scope: &'a ProviderCooldownScope,
|
|
_through_revision: CredentialRevision,
|
|
) -> BoxFuture<'a, Result<bool, ProviderStoreError>> {
|
|
Box::pin(async { Ok(false) })
|
|
}
|
|
|
|
fn clear_all<'a>(
|
|
&'a self,
|
|
_account_id: &'a ProviderAccountId,
|
|
) -> BoxFuture<'a, Result<bool, ProviderStoreError>> {
|
|
Box::pin(async { Ok(false) })
|
|
}
|
|
|
|
fn clear_after_success<'a>(
|
|
&'a self,
|
|
account_id: &'a ProviderAccountId,
|
|
_through_revision: gateway_core::account::CredentialRevision,
|
|
) -> BoxFuture<'a, Result<(), ProviderStoreError>> {
|
|
Box::pin(async move {
|
|
let mut cooldowns = self.cooldowns.lock().expect("cooldown lock");
|
|
if cooldowns.get(account_id).is_some_and(|value| {
|
|
value.kind().is_error_protection()
|
|
|| value.credential_revision() > _through_revision
|
|
}) {
|
|
return Ok(());
|
|
}
|
|
cooldowns.remove(account_id);
|
|
Ok(())
|
|
})
|
|
}
|
|
}
|