Files
codex-proxy-rs/backend/crates/gateway-admin/tests/use_case/mod.rs
T
ZyyandCodex 832858dade feat(plugins): expose historical quota observations by window
Let plugins page through retained account observations and find a prior baseline without reading raw provider documents or refreshing upstream. Reuse provider window identities and the existing completion index, preserving resets and gaps.

Co-authored-by: Codex <noreply@openai.com>
2026-11-17 17:06:55 +08:00

1305 lines
40 KiB
Rust

//! 管理控制面各服务用例的测试入口
mod account_groups;
mod accounts;
mod auth;
mod auth_key;
mod backup;
mod client_keys;
mod credentials;
mod freeze_recovery;
mod import_tasks;
mod observability;
mod peer_link;
mod plugins;
mod proxies;
mod settings;
mod system;
mod system_preflight;
mod usage_data;
use std::{
str::FromStr,
sync::{Arc, Mutex},
};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use futures::future::BoxFuture;
use gateway_admin::{
AdminConfig, AdminServices, ClientConfig, InitialAdminPassword,
model::{
MutationContext, Revision,
account_groups::{
AccountGroupListQuery, AccountGroupMemberFact, AccountGroupMutation,
AccountGroupOptionsPage, AccountGroupPage, DeleteAccountGroup, NewAccountGroup,
SetAccountGroupEnabled, UpdateAccountGroup,
},
accounts::{
AccountListQuery, AccountPage, AccountRuntimeSnapshot, AccountUpdateResult,
AccountUsage, AccountUsageWindowQuery, AccountUsageWindowResult, AccountsUpdateResult,
BatchUpdateAccounts, DeleteAccounts, UpdateAccount,
},
auth::{AdminAuditEvent, AuthSession},
client_distribution::CodexDesktopWindowsDownloads,
client_keys::{
ClientKeyListQuery, ClientKeyPage, ClientKeyRecord, ClientKeySecret, DeleteClientKey,
NewClientKey, SetClientKeyEnabled, UpdateClientKey,
},
observability::{
DashboardDesktopRelease, DashboardObservation, DashboardQuery, DashboardWireAttribute,
DashboardWireProfile, DashboardWireTarget, DesktopReleaseStatus, DiagnosticDimension,
DiagnosticsObservation, Granularity, OpsErrorPage, OpsErrorQuery, RequestMetricPoint,
TimeRange, UsageDetail, UsageFilter, UsagePage, UsageQuery, UsageSummaryObservation,
},
provider_credentials::{
AuthorizationCommit, AuthorizationStarted, CompleteAuthorization, CredentialDetails,
CredentialImportCommit, CredentialImportResult, CredentialMutationResult,
CredentialRotationCommit, PrepareCredentialImport, PrepareCredentialRefresh,
PrepareCredentialRotation, PreparedAuthorizationCommit, PreparedCredentialImport,
PreparedCredentialRotation, ProviderExport, ProviderExportCredentialInput,
ProviderModels, ProviderQuota,
},
settings::{AdminApiKey, AdminApiKeyMutation, ReplaceRuntimeSettings, RuntimeSettings},
system::{SystemOperationAccepted, SystemUpdateDetail, SystemUpdateStatus, SystemVersion},
},
ports::{
backup::BackupStorePorts,
client_distribution::ClientDistributionResolver,
provider::{ProviderAdmin, ProviderAdminError, ProviderAdminErrorKind},
store::{
AccountGroupStore, AccountRuntimeStore, AccountStore, AdminAccountStorePorts,
AdminStoreError, AdminStoreErrorKind, AdminStorePorts, AdminStoreResult, AuthStore,
ClientKeyStore, ObservabilityStore, SettingsStore,
},
system::{
SystemOperationError, SystemOperationErrorKind, SystemOperations,
SystemUpdateEventStream,
},
},
};
use gateway_core::{
account::ProviderAccountId,
engine::{
execution::{ClientAuthenticationError, ClientKeyVerifier},
probe::{AccountProbe, AccountProbeError, AccountProbeRequest, AccountProbeResult},
},
error::{GatewayError, GatewayErrorKind},
policy::ClientApiKeyId,
routing::{ConfigRevision, ProviderKind},
runtime::SnapshotControl,
};
use std::collections::BTreeMap;
pub(super) struct AdminHarness {
default_password: String,
session_ttl_minutes: u64,
client_session_ttl_minutes: u64,
accounts: Arc<dyn AccountStore>,
proxies: Arc<dyn gateway_admin::ports::proxy::ProxyStore>,
proxy_probe: Arc<dyn gateway_admin::ports::proxy::ProxyProbe>,
account_runtime: Arc<dyn AccountRuntimeStore>,
account_groups: Arc<dyn AccountGroupStore>,
snapshot: Arc<dyn SnapshotControl>,
auth: Arc<dyn AuthStore>,
client_keys: Arc<dyn ClientKeyStore>,
observability: Arc<dyn ObservabilityStore>,
settings: Arc<dyn SettingsStore>,
backup: BackupStorePorts,
providers: Vec<Arc<dyn ProviderAdmin>>,
probe: Arc<dyn AccountProbe>,
system: Arc<dyn SystemOperations>,
plugin_store: Arc<dyn gateway_admin::ports::plugins::PluginStore>,
plugin_inspector: Arc<dyn gateway_admin::ports::plugins::PluginPackageInspector>,
client_key_verifier: Arc<dyn ClientKeyVerifier>,
upstream_info: Option<Arc<dyn gateway_admin::ports::peer::PeerUpstreamService>>,
service_middleware: gateway_admin::public_service::PlanSource,
}
impl AdminHarness {
pub(super) fn new() -> Self {
let unavailable = Arc::new(UnavailableStore);
Self {
default_password: "strong-test-password".to_owned(),
session_ttl_minutes: 60,
client_session_ttl_minutes: 1_440,
accounts: unavailable.clone(),
proxies: Arc::new(proxies::TestProxies::default()),
proxy_probe: Arc::new(proxies::TestProxies::default()),
account_runtime: unavailable.clone(),
account_groups: Arc::new(UnavailableAccountGroupStore),
snapshot: Arc::new(NoopSnapshot),
auth: Arc::new(BootstrapAuthStore::default()),
client_keys: unavailable.clone(),
observability: unavailable.clone(),
settings: unavailable,
backup: BackupStorePorts::disabled(),
providers: vec![
Arc::new(UnavailableProvider::new("openai")),
Arc::new(UnavailableProvider::new("xai")),
],
probe: Arc::new(UnavailableProbe),
system: Arc::new(UnavailableSystem),
plugin_store: Arc::new(plugins::TestPluginPorts),
plugin_inspector: Arc::new(plugins::TestPluginPorts),
client_key_verifier: Arc::new(UnavailableClientKeyVerifier),
upstream_info: None,
service_middleware: Arc::new(|| None),
}
}
pub(super) fn default_password(mut self, password: &str) -> Self {
self.default_password = password.to_owned();
self
}
pub(super) fn session_ttl_minutes(mut self, minutes: u64) -> Self {
self.session_ttl_minutes = minutes;
self
}
pub(super) fn accounts(mut self, store: Arc<dyn AccountStore>) -> Self {
self.accounts = store;
self
}
pub(super) fn upstream_info(
mut self,
peer: Arc<dyn gateway_admin::ports::peer::PeerUpstreamService>,
) -> Self {
self.upstream_info = Some(peer);
self
}
pub(super) fn account_runtime(mut self, store: Arc<dyn AccountRuntimeStore>) -> Self {
self.account_runtime = store;
self
}
pub(super) fn account_groups(mut self, store: Arc<dyn AccountGroupStore>) -> Self {
self.account_groups = store;
self
}
pub(super) fn snapshot(mut self, snapshot: Arc<dyn SnapshotControl>) -> Self {
self.snapshot = snapshot;
self
}
pub(super) fn auth(mut self, store: Arc<dyn AuthStore>) -> Self {
self.auth = store;
self
}
pub(super) fn client_keys(mut self, store: Arc<dyn ClientKeyStore>) -> Self {
self.client_keys = store;
self
}
pub(super) fn client_session_ttl_minutes(mut self, minutes: u64) -> Self {
self.client_session_ttl_minutes = minutes;
self
}
pub(super) fn client_key_verifier(mut self, verifier: Arc<dyn ClientKeyVerifier>) -> Self {
self.client_key_verifier = verifier;
self
}
pub(super) fn observability(mut self, store: Arc<dyn ObservabilityStore>) -> Self {
self.observability = store;
self
}
pub(super) fn settings(mut self, store: Arc<dyn SettingsStore>) -> Self {
self.settings = store;
self
}
pub(super) fn service_middleware(
mut self,
source: gateway_admin::public_service::PlanSource,
) -> Self {
self.service_middleware = source;
self
}
pub(super) fn backup(mut self, backup: BackupStorePorts) -> Self {
self.backup = backup;
self
}
pub(super) fn provider(mut self, provider: Arc<dyn ProviderAdmin>) -> Self {
self.providers
.retain(|registered| registered.provider_kind() != provider.provider_kind());
self.providers.push(provider);
self
}
pub(super) fn probe(mut self, probe: Arc<dyn AccountProbe>) -> Self {
self.probe = probe;
self
}
pub(super) fn proxies(
mut self,
proxies: Arc<dyn gateway_admin::ports::proxy::ProxyStore>,
) -> Self {
self.proxies = proxies;
self
}
pub(super) fn system(mut self, system: Arc<dyn SystemOperations>) -> Self {
self.system = system;
self
}
pub(super) fn plugins(
mut self,
store: Arc<dyn gateway_admin::ports::plugins::PluginStore>,
inspector: Arc<dyn gateway_admin::ports::plugins::PluginPackageInspector>,
) -> Self {
self.plugin_store = store;
self.plugin_inspector = inspector;
self
}
pub(super) async fn build(self) -> AdminServices {
self.build_bundle().await.services()
}
pub(super) async fn build_bundle(self) -> gateway_admin::AdminBundle {
gateway_admin::initialize(
AdminConfig {
session_absolute_ttl_minutes: 30 * 24 * 60,
session_ttl_minutes: self.session_ttl_minutes,
default_username: "admin".to_owned(),
default_password: InitialAdminPassword::new(self.default_password),
},
ClientConfig {
session_ttl_minutes: self.client_session_ttl_minutes,
},
AdminStorePorts::new(
AdminAccountStorePorts::new(
self.accounts,
self.account_runtime,
self.account_groups,
self.proxies,
),
self.auth,
self.client_keys,
self.observability,
self.settings,
self.backup,
self.plugin_store,
Arc::new(plugins::TestPluginPorts),
Arc::new(plugins::TestPluginPorts),
Arc::new(plugins::TestPluginPorts),
),
gateway_admin::AdminRuntimePorts {
upstream_info: self.upstream_info,
timezone: Default::default(),
service_middleware: self.service_middleware,
plugin_preparation: Arc::new(plugins::TestPluginPorts),
plugin_management: Arc::new(plugins::TestPluginPorts),
published_snapshot: gateway_core::runtime::RuntimeSnapshotHandle::default(),
plugin_inspector: self.plugin_inspector,
plugin_distribution: Arc::new(plugins::TestPluginPorts),
pricing_source: Arc::new(UnavailablePricingSource),
providers: gateway_admin::ports::provider::ProviderAdminRegistry::new(
self.providers,
)
.unwrap(),
snapshot: self.snapshot,
account_probe: self.probe,
proxy_probe: self.proxy_probe,
client_distribution: Arc::new(NoopClientDistribution),
system: self.system,
client_key_verifier: self.client_key_verifier,
},
)
.await
.expect("initialize admin test harness")
}
}
struct NoopClientDistribution;
#[async_trait]
impl ClientDistributionResolver for NoopClientDistribution {
async fn resolve_codex_desktop_windows(&self, _: bool) -> CodexDesktopWindowsDownloads {
CodexDesktopWindowsDownloads {
resolved_at: Utc::now(),
cached: false,
warning: None,
packages: Vec::new(),
}
}
}
#[derive(Default)]
struct BootstrapAuthStore {
password_hash: Mutex<Option<String>>,
}
#[async_trait]
impl AuthStore for BootstrapAuthStore {
async fn load_password_hash(&self, _: &str) -> AdminStoreResult<Option<String>> {
Ok(self.password_hash.lock().expect("password hash").clone())
}
async fn change_password(
&self,
_: &str,
expected_hash: &str,
password_hash: &str,
audit: gateway_admin::model::auth::AdminAuditEvent,
) -> AdminStoreResult<bool> {
let mut stored = self.password_hash.lock().unwrap();
let Some(credentials) = stored
.as_mut()
.filter(|value| value.as_str() == expected_hash)
else {
return Ok(false);
};
*credentials = password_hash.to_owned();
let _ = audit;
Ok(true)
}
async fn create_password_hash_if_absent(
&self,
_: &str,
password_hash: &str,
) -> AdminStoreResult<bool> {
let mut stored = self.password_hash.lock().expect("password hash");
if stored.is_some() {
return Ok(false);
}
*stored = Some(password_hash.to_owned());
Ok(true)
}
async fn load_admin_api_key(&self) -> AdminStoreResult<Option<AdminApiKey>> {
Ok(None)
}
async fn load_session(&self, _: &str) -> AdminStoreResult<Option<AuthSession>> {
Ok(None)
}
async fn store_session(&self, _: &str, _: &AuthSession) -> AdminStoreResult<()> {
Err(unavailable("admin session"))
}
async fn compare_exchange_session(
&self,
_: &str,
_: &gateway_admin::model::auth::AuthSession,
_: Option<&gateway_admin::model::auth::AuthSession>,
) -> AdminStoreResult<Option<gateway_admin::model::auth::AuthSession>> {
Ok(None)
}
async fn delete_session(&self, _: &str) -> AdminStoreResult<Option<AuthSession>> {
Err(unavailable("admin session"))
}
async fn client_key_enabled(
&self,
_: &gateway_core::policy::ClientApiKeyId,
) -> AdminStoreResult<bool> {
Ok(false)
}
async fn consume_login_attempt(
&self,
_: std::net::IpAddr,
_: u32,
_: u32,
_: std::time::Duration,
) -> AdminStoreResult<Option<std::time::Duration>> {
Ok(None)
}
async fn append_audit_event(&self, _: AdminAuditEvent) -> AdminStoreResult<()> {
Ok(())
}
}
struct UnavailableStore;
struct UnavailableClientKeyVerifier;
impl ClientKeyVerifier for UnavailableClientKeyVerifier {
fn verify_client_key(&self, _: &str) -> Result<ClientApiKeyId, ClientAuthenticationError> {
Err(ClientAuthenticationError::InvalidKey)
}
}
struct UnavailableAccountGroupStore;
#[async_trait]
impl AccountGroupStore for UnavailableAccountGroupStore {
async fn list_account_groups(
&self,
_: AccountGroupListQuery,
) -> AdminStoreResult<AccountGroupPage> {
Err(unavailable("account groups"))
}
async fn list_account_group_options(
&self,
_: AccountGroupListQuery,
) -> AdminStoreResult<AccountGroupOptionsPage> {
Err(unavailable("account group options"))
}
async fn load_account_group_members(
&self,
_: &[gateway_core::routing::AccountGroupId],
) -> AdminStoreResult<Vec<AccountGroupMemberFact>> {
Err(unavailable("account group members"))
}
async fn create_account_group(
&self,
_: NewAccountGroup,
_: &MutationContext,
) -> AdminStoreResult<AccountGroupMutation> {
Err(unavailable("account group create"))
}
async fn update_account_group(
&self,
_: UpdateAccountGroup,
_: &MutationContext,
) -> AdminStoreResult<AccountGroupMutation> {
Err(unavailable("account group update"))
}
async fn set_account_group_enabled(
&self,
_: SetAccountGroupEnabled,
_: &MutationContext,
) -> AdminStoreResult<AccountGroupMutation> {
Err(unavailable("account group state"))
}
async fn delete_account_group(
&self,
_: DeleteAccountGroup,
_: &MutationContext,
) -> AdminStoreResult<AccountGroupMutation> {
Err(unavailable("account group delete"))
}
}
#[async_trait]
impl AccountStore for UnavailableStore {
async fn load_account_record(
&self,
_: &ProviderAccountId,
) -> AdminStoreResult<Option<gateway_admin::model::accounts::AccountRecord>> {
Err(unavailable("account"))
}
async fn account_exists(&self, _: &str) -> AdminStoreResult<bool> {
Err(unavailable("account"))
}
async fn list_plugin_accounts(
&self,
_: gateway_admin::model::provider_credentials::PluginAccountListQuery,
) -> AdminStoreResult<gateway_admin::model::provider_credentials::PluginAccountPage> {
Err(unavailable("plugin accounts"))
}
async fn list_accounts(
&self,
_: AccountListQuery,
_: AccountRuntimeSnapshot,
) -> AdminStoreResult<AccountPage> {
Err(unavailable("accounts"))
}
async fn load_account(
&self,
_: &str,
_: AccountRuntimeSnapshot,
) -> AdminStoreResult<Option<gateway_admin::model::accounts::AccountPageItem>> {
Err(unavailable("account"))
}
async fn load_account_usage(
&self,
_: TimeRange,
_: &[String],
) -> AdminStoreResult<Vec<AccountUsage>> {
Err(unavailable("account usage"))
}
async fn load_account_usage_by_windows(
&self,
_: &[AccountUsageWindowQuery],
) -> AdminStoreResult<Vec<AccountUsageWindowResult>> {
Err(unavailable("account quota window usage"))
}
async fn quota_documents(
&self,
_: &gateway_core::account::ProviderAccountId,
_: &gateway_core::routing::ProviderKind,
_: chrono::DateTime<chrono::Utc>,
_: gateway_admin::model::observability::TimeRange,
_: Option<&gateway_admin::model::quota_history::QuotaHistoryCursor>,
) -> AdminStoreResult<gateway_admin::model::quota_history::QuotaDocumentPage> {
unreachable!("测试不读取历史额度文档")
}
async fn load_quota_forecast_history(
&self,
_: &AccountUsageWindowQuery,
) -> AdminStoreResult<gateway_admin::model::quota_forecast_sampling::QuotaForecastHistory> {
Err(unavailable("quota forecast history"))
}
async fn credential_details(
&self,
_: &ProviderKind,
_: &ProviderAccountId,
) -> AdminStoreResult<Option<CredentialDetails>> {
Err(unavailable("credential"))
}
async fn credential_details_by_id(
&self,
_: &ProviderAccountId,
) -> AdminStoreResult<Option<CredentialDetails>> {
Err(unavailable("credential"))
}
async fn load_credentials_for_export(
&self,
_: &ProviderKind,
_: &[ProviderAccountId],
) -> AdminStoreResult<Vec<ProviderExportCredentialInput>> {
Err(unavailable("credential export"))
}
async fn load_credential_for_plugin(
&self,
_: &ProviderAccountId,
) -> AdminStoreResult<Option<ProviderExportCredentialInput>> {
Err(unavailable("credential export"))
}
async fn commit_credential_import(
&self,
_: CredentialImportCommit,
_: &MutationContext,
) -> AdminStoreResult<CredentialImportResult> {
Err(unavailable("credential import"))
}
async fn authorization_receipt(
&self,
_: &gateway_admin::model::provider_credentials::AuthorizationReceiptKey,
) -> AdminStoreResult<
Option<gateway_admin::model::provider_credentials::CredentialMutationResult>,
> {
Err(unavailable("authorization receipt"))
}
async fn commit_authorization(
&self,
_: AuthorizationCommit,
_: &MutationContext,
) -> AdminStoreResult<gateway_admin::model::provider_credentials::AuthorizationCommitResult>
{
Err(unavailable("authorization"))
}
async fn commit_credential_rotation(
&self,
_: CredentialRotationCommit,
_: &MutationContext,
) -> AdminStoreResult<CredentialMutationResult> {
Err(unavailable("credential rotation"))
}
async fn commit_credential_refresh(
&self,
_: CredentialRotationCommit,
_: &MutationContext,
) -> AdminStoreResult<CredentialMutationResult> {
Err(unavailable("credential refresh"))
}
async fn update_account(
&self,
_: UpdateAccount,
_: &MutationContext,
) -> AdminStoreResult<AccountUpdateResult> {
Err(unavailable("account enabled"))
}
async fn recover_account(
&self,
_: &ProviderAccountId,
_: &MutationContext,
) -> AdminStoreResult<AccountUpdateResult> {
Err(unavailable("account recovery"))
}
async fn batch_update_accounts(
&self,
_: BatchUpdateAccounts,
_: gateway_admin::model::accounts::PreparedQuotaPauses,
_: &MutationContext,
) -> AdminStoreResult<AccountsUpdateResult> {
Err(unavailable("account batch update"))
}
async fn delete_accounts(
&self,
_: DeleteAccounts,
_: &MutationContext,
) -> AdminStoreResult<Revision> {
Err(unavailable("account delete"))
}
async fn record_credential_export(
&self,
_: &[ProviderAccountId],
_: &MutationContext,
) -> AdminStoreResult<()> {
Err(unavailable("credential export audit"))
}
}
#[async_trait]
impl AccountRuntimeStore for UnavailableStore {
async fn account_concurrency(
&self,
_: &str,
_: u64,
_: u32,
) -> AdminStoreResult<gateway_admin::model::accounts::AccountConcurrencyPage> {
Err(gateway_admin::ports::store::AdminStoreError::new(
gateway_admin::ports::store::AdminStoreErrorKind::Unavailable,
"account concurrency",
"not configured in this fixture",
))
}
async fn active_rate_limits(&self) -> AdminStoreResult<AccountRuntimeSnapshot> {
Ok(AccountRuntimeSnapshot::default())
}
async fn account_runtime(&self, _: &[String]) -> AdminStoreResult<AccountRuntimeSnapshot> {
Ok(AccountRuntimeSnapshot::default())
}
async fn active_freezes(
&self,
) -> AdminStoreResult<BTreeMap<String, gateway_admin::model::accounts::AccountFreeze>> {
Ok(BTreeMap::new())
}
async fn finish_freeze(
&self,
_account_id: &str,
_expected: &gateway_admin::model::accounts::AccountFreeze,
_postpone_until: Option<DateTime<Utc>>,
) -> AdminStoreResult<bool> {
Ok(false)
}
}
#[async_trait]
impl ClientKeyStore for UnavailableStore {
async fn client_key_budget_window(
&self,
_: &gateway_core::policy::ClientApiKeyId,
_: gateway_admin::model::client_keys::ClientKeyBudgetWindowPeriod,
) -> gateway_admin::ports::store::AdminStoreResult<
gateway_admin::model::client_keys::ClientKeyBudgetWindow,
> {
Err(gateway_admin::ports::store::AdminStoreError::new(
gateway_admin::ports::store::AdminStoreErrorKind::Unavailable,
"client key",
"unused budget window",
))
}
async fn set_client_key_budget_window(
&self,
_: gateway_admin::model::client_keys::SetClientKeyBudgetWindow,
_: gateway_admin::model::client_keys::ClientKeyBudgetMutationOrigin,
_: &MutationContext,
) -> gateway_admin::ports::store::AdminStoreResult<u64> {
Err(gateway_admin::ports::store::AdminStoreError::new(
gateway_admin::ports::store::AdminStoreErrorKind::Unavailable,
"client key",
"unused budget window",
))
}
async fn update_client_key_budget_limits(
&self,
_: gateway_admin::model::client_keys::UpdateClientKeyBudgetLimits,
_: gateway_admin::model::client_keys::ClientKeyBudgetMutationOrigin,
_: &MutationContext,
) -> AdminStoreResult<Option<Revision>> {
Err(unavailable("client key budget limits"))
}
async fn reset_client_key_budget(
&self,
_: gateway_admin::model::client_keys::ResetClientKeyBudget,
_: gateway_admin::model::client_keys::ClientKeyBudgetMutationOrigin,
_: &MutationContext,
) -> AdminStoreResult<()> {
Err(unavailable("client key budget reset"))
}
async fn get_client_key(
&self,
_: &ClientApiKeyId,
) -> AdminStoreResult<Option<ClientKeyRecord>> {
Err(unavailable("client key"))
}
async fn list_client_keys(&self, _: ClientKeyListQuery) -> AdminStoreResult<ClientKeyPage> {
Err(unavailable("client key list"))
}
async fn reveal_client_key(
&self,
_: &ClientApiKeyId,
) -> AdminStoreResult<Option<ClientKeySecret>> {
Err(unavailable("client key"))
}
async fn create_client_key(
&self,
_: NewClientKey,
_: &MutationContext,
) -> AdminStoreResult<(Revision, ClientKeyRecord)> {
Err(unavailable("client key create"))
}
async fn update_client_key(
&self,
_: UpdateClientKey,
_: &MutationContext,
) -> AdminStoreResult<(Revision, ClientKeyRecord)> {
Err(unavailable("client key update"))
}
async fn set_client_key_enabled(
&self,
_: SetClientKeyEnabled,
_: &MutationContext,
) -> AdminStoreResult<(Revision, ClientKeyRecord)> {
Err(unavailable("client key enabled"))
}
async fn delete_client_key(
&self,
_: DeleteClientKey,
_: &MutationContext,
) -> AdminStoreResult<Revision> {
Err(unavailable("client key delete"))
}
}
#[async_trait]
impl ObservabilityStore for UnavailableStore {
async fn diagnostic_errors(
&self,
_target: &gateway_admin::model::diagnostics::DiagnosticTarget,
_limit: u16,
) -> AdminStoreResult<Vec<gateway_admin::model::observability::OpsError>> {
Err(unavailable("diagnostic errors"))
}
fn query_timeout(&self) -> std::time::Duration {
std::time::Duration::from_secs(10)
}
async fn dashboard_summary(
&self,
_: DashboardQuery,
_: DateTime<Utc>,
) -> AdminStoreResult<DashboardObservation> {
Err(unavailable("dashboard"))
}
async fn dashboard_trend(
&self,
_: TimeRange,
_: Granularity,
) -> AdminStoreResult<Vec<RequestMetricPoint>> {
Err(unavailable("dashboard trend"))
}
async fn usage_trend(
&self,
_: TimeRange,
_: UsageFilter,
_: Granularity,
) -> AdminStoreResult<Vec<RequestMetricPoint>> {
Err(unavailable("usage trend"))
}
async fn analytics_cache_generation(&self) -> AdminStoreResult<u64> {
Err(unavailable("analytics generation"))
}
async fn usage_insights_observation(
&self,
_: TimeRange,
_: UsageFilter,
_: Granularity,
_include_concurrency: bool,
) -> AdminStoreResult<gateway_admin::model::observability::UsageInsightsObservation> {
Err(unavailable("usage insights"))
}
async fn usage_metric_observation(
&self,
range: gateway_admin::model::observability::TimeRange,
filter: gateway_admin::model::observability::UsageFilter,
granularity: gateway_admin::model::observability::Granularity,
metric: gateway_admin::model::observability::UsageInsightMetric,
) -> AdminStoreResult<gateway_admin::model::observability::UsageInsightsObservation> {
self.usage_insights_observation(
range,
filter,
granularity,
metric == gateway_admin::model::observability::UsageInsightMetric::Load,
)
.await
}
async fn list_usage_records(&self, _: UsageQuery) -> AdminStoreResult<UsagePage> {
Err(unavailable("usage records"))
}
async fn usage_record_detail(&self, _: &str) -> AdminStoreResult<UsageDetail> {
Err(unavailable("usage detail"))
}
async fn usage_summary(
&self,
_: TimeRange,
_: UsageFilter,
) -> AdminStoreResult<UsageSummaryObservation> {
Err(unavailable("usage summary"))
}
async fn usage_diagnostics(
&self,
_: TimeRange,
_: UsageFilter,
_: DiagnosticDimension,
_: u16,
) -> AdminStoreResult<DiagnosticsObservation> {
Err(unavailable("usage diagnostics"))
}
async fn list_ops_errors(&self, _: OpsErrorQuery) -> AdminStoreResult<OpsErrorPage> {
Err(unavailable("ops errors"))
}
}
#[async_trait]
impl SettingsStore for UnavailableStore {
async fn load_pricing(&self) -> AdminStoreResult<gateway_admin::model::pricing::StoredPricing> {
Ok(Default::default())
}
async fn sync_pricing(
&self,
_: gateway_admin::model::pricing::PricingSyncChanges,
_: &MutationContext,
) -> AdminStoreResult<gateway_admin::model::Revision> {
panic!("unexpected pricing sync")
}
async fn update_pricing(
&self,
_: gateway_admin::model::pricing::UpdatePricing,
_: &MutationContext,
) -> AdminStoreResult<gateway_admin::model::Revision> {
panic!("unexpected pricing update")
}
async fn load_runtime_settings(&self) -> AdminStoreResult<RuntimeSettings> {
Err(unavailable("settings"))
}
async fn admin_api_key_exists(&self) -> AdminStoreResult<bool> {
Err(unavailable("admin API key"))
}
async fn replace_runtime_settings(
&self,
_: ReplaceRuntimeSettings,
_: &MutationContext,
) -> AdminStoreResult<RuntimeSettings> {
Err(unavailable("settings"))
}
async fn replace_admin_api_key(
&self,
_: AdminApiKey,
_: &MutationContext,
) -> AdminStoreResult<AdminApiKeyMutation> {
Err(unavailable("admin API key"))
}
async fn delete_admin_api_key(
&self,
_: &MutationContext,
) -> AdminStoreResult<AdminApiKeyMutation> {
Err(unavailable("admin API key"))
}
}
struct UnavailableProvider {
peer_enabled: bool,
kind: ProviderKind,
dashboard_profile: Option<DashboardWireProfile>,
calculated_billing: Option<gateway_admin::model::observability::CalculatedBillingBreakdown>,
}
struct UnavailablePricingSource;
#[async_trait]
impl gateway_admin::ports::pricing::PricingSource for UnavailablePricingSource {
async fn fetch(
&self,
) -> Result<gateway_admin::model::pricing::PricingSyncPreview, gateway_admin::model::AdminError>
{
Err(gateway_admin::model::AdminError::internal(
"pricing source unavailable",
))
}
}
impl UnavailableProvider {
fn new(kind: &str) -> Self {
Self {
kind: ProviderKind::new(kind).expect("provider kind"),
peer_enabled: false,
dashboard_profile: None,
calculated_billing: None,
}
}
}
pub(super) fn test_provider(kind: &str) -> Arc<dyn ProviderAdmin> {
Arc::new(UnavailableProvider::new(kind))
}
#[async_trait]
impl ProviderAdmin for UnavailableProvider {
fn peer_authentication_kinds(&self) -> &[&str] {
if self.peer_enabled {
&["peer_test"]
} else {
&[]
}
}
fn peer_connection(
&self,
loaded: &gateway_core::account::LoadedCredential,
) -> Result<Option<gateway_admin::ports::peer::PeerConnection>, ProviderAdminError> {
Ok(
(self.peer_enabled && loaded.account.authentication_kind() == "peer_test").then(|| {
gateway_admin::ports::peer::PeerConnection {
base_url: format!("https://{}.invalid/v1", self.kind),
bearer_token: secrecy::SecretString::from("test-peer-only"),
}
}),
)
}
fn provider_kind(&self) -> &ProviderKind {
&self.kind
}
async fn account_unavailable(&self, _: &ProviderAccountId) {}
async fn connection_test_operation(
&self,
_: &gateway_core::routing::UpstreamModelId,
_: &str,
) -> Result<gateway_core::operation::Operation, ProviderAdminError> {
Err(unsupported_provider())
}
fn dashboard_wire_profile(&self) -> Option<DashboardWireProfile> {
self.dashboard_profile.clone()
}
fn calculated_billing(
&self,
_: &gateway_admin::model::observability::ProviderBillingInput,
) -> Result<
Option<gateway_admin::model::observability::CalculatedBillingBreakdown>,
ProviderAdminError,
> {
Ok(self.calculated_billing.clone())
}
async fn prepare_import(
&self,
_: PrepareCredentialImport,
) -> Result<PreparedCredentialImport, ProviderAdminError> {
Err(unsupported_provider())
}
async fn start_authorization(
&self,
_: gateway_admin::model::provider_credentials::PendingAuthorizationMutation,
) -> Result<AuthorizationStarted, ProviderAdminError> {
Err(unsupported_provider())
}
async fn complete_authorization(
&self,
_: CompleteAuthorization,
) -> Result<PreparedAuthorizationCommit, ProviderAdminError> {
Err(unsupported_provider())
}
async fn prepare_rotation(
&self,
_: PrepareCredentialRotation,
) -> Result<PreparedCredentialRotation, ProviderAdminError> {
Err(unsupported_provider())
}
async fn prepare_refresh(
&self,
_: PrepareCredentialRefresh,
) -> Result<PreparedCredentialRotation, ProviderAdminError> {
Err(unsupported_provider())
}
async fn quota(
&self,
_: gateway_admin::model::provider_credentials::ProviderQuotaRequest,
) -> Result<ProviderQuota, ProviderAdminError> {
Err(unsupported_provider())
}
async fn models(
&self,
_: &ProviderAccountId,
_: bool,
) -> Result<ProviderModels, ProviderAdminError> {
Err(unsupported_provider())
}
async fn export_credentials(
&self,
_: Vec<ProviderExportCredentialInput>,
) -> Result<ProviderExport, ProviderAdminError> {
Err(unsupported_provider())
}
}
pub(super) fn dashboard_profile_provider() -> Arc<dyn ProviderAdmin> {
Arc::new(UnavailableProvider {
peer_enabled: false,
kind: ProviderKind::new("openai").expect("provider kind"),
dashboard_profile: Some(DashboardWireProfile {
provider: "openai".to_owned(),
product: "gateway-admin-test".to_owned(),
version: "test".to_owned(),
build: Some("test".to_owned()),
target: DashboardWireTarget {
os_type: "linux".to_owned(),
os_version: "test".to_owned(),
arch: "x86_64".to_owned(),
terminal: "test".to_owned(),
},
user_agent: "gateway-admin-test".to_owned(),
attributes: vec![DashboardWireAttribute {
key: "core".to_owned(),
value: "test".to_owned(),
}],
verified_at: Some(chrono::Utc::now()),
release: Some(DashboardDesktopRelease {
status: DesktopReleaseStatus::Unchecked,
checked_at: None,
latest_version: None,
latest_build: None,
published_at: None,
minimum_system_version: None,
hardware_requirements: None,
download_url: None,
download_size: None,
signature_present: None,
error: None,
}),
}),
calculated_billing: None,
})
}
pub(super) fn calculated_billing_provider() -> Arc<dyn ProviderAdmin> {
let amount = |value| gateway_admin::model::observability::CurrencyCost {
currency: "USD".to_owned(),
amount: gateway_admin::model::observability::DecimalAmount::from_str(value)
.expect("test billing amount"),
};
Arc::new(UnavailableProvider {
peer_enabled: false,
kind: ProviderKind::new("openai").expect("provider kind"),
dashboard_profile: None,
calculated_billing: Some(
gateway_admin::model::observability::CalculatedBillingBreakdown {
long_context_billing_applied: false,
custom_multiplier_bps: 10_000,
image: None,
input_amount: amount("0.8"),
output_amount: amount("0.2"),
cache_read_amount: amount("0"),
cache_write_amount: amount("0"),
standard_amount: amount("1"),
total_amount: amount("1.25"),
input_price_per_million: amount("0"),
output_price_per_million: amount("0"),
cache_read_price_per_million: amount("0"),
cache_write_price_per_million: amount("0"),
service_tier: None,
multiplier_percent: 125,
},
),
})
}
struct NoopSnapshot;
impl SnapshotControl for NoopSnapshot {
fn publish_committed(&self, _: ConfigRevision) -> BoxFuture<'_, ()> {
Box::pin(async {})
}
}
struct UnavailableProbe;
impl AccountProbe for UnavailableProbe {
fn probe(
&self,
_: AccountProbeRequest,
_: Option<Arc<gateway_core::routing::RuntimeSnapshot>>,
) -> BoxFuture<'_, Result<AccountProbeResult, AccountProbeError>> {
Box::pin(async {
Err(GatewayError::new(
GatewayErrorKind::Internal,
"test account probe is unavailable",
)
.into())
})
}
}
struct UnavailableSystem;
#[async_trait]
impl SystemOperations for UnavailableSystem {
async fn version(&self) -> Result<SystemVersion, SystemOperationError> {
Err(unavailable_system())
}
async fn update_detail(
&self,
_: gateway_admin::model::system::SystemUpdateCheck,
_: Option<gateway_admin::model::system::SystemUpdateChannel>,
) -> Result<SystemUpdateDetail, SystemOperationError> {
Err(unavailable_system())
}
fn update_events(&self) -> SystemUpdateEventStream {
Box::pin(futures::stream::empty())
}
async fn perform_update(
&self,
_: Option<String>,
_: Option<gateway_admin::model::system::SystemUpdateChannel>,
_: Arc<dyn gateway_admin::ports::system::SystemUpdatePreflight>,
) -> Result<SystemOperationAccepted, SystemOperationError> {
Err(unavailable_system())
}
async fn update_status(&self) -> Result<SystemUpdateStatus, SystemOperationError> {
Err(unavailable_system())
}
async fn rollback(
&self,
_: Arc<dyn gateway_admin::ports::system::SystemUpdatePreflight>,
) -> Result<SystemOperationAccepted, SystemOperationError> {
Err(unavailable_system())
}
async fn restart(
&self,
_preflight: Arc<dyn gateway_admin::ports::system::SystemRestartPreflight>,
) -> Result<SystemOperationAccepted, SystemOperationError> {
Err(unavailable_system())
}
}
fn unavailable(resource: &'static str) -> AdminStoreError {
AdminStoreError::new(
AdminStoreErrorKind::Unavailable,
resource,
"unavailable in this test",
)
}
fn unsupported_provider() -> ProviderAdminError {
ProviderAdminError::new(ProviderAdminErrorKind::Unsupported)
}
fn unavailable_system() -> SystemOperationError {
SystemOperationError::new(
SystemOperationErrorKind::Internal,
"unavailable in this test",
)
}
mod service_contract;
#[async_trait]
impl gateway_admin::ports::reset_credit_automation::ResetCreditAutomationStore
for UnavailableStore
{
async fn reset_credit_automation(
&self,
_: &str,
) -> AdminStoreResult<
Option<gateway_admin::model::reset_credit_automation::ResetCreditAutomation>,
> {
Ok(None)
}
async fn due_reset_credit_automations(
&self,
_: chrono::DateTime<chrono::Utc>,
_: u32,
) -> AdminStoreResult<Vec<String>> {
Ok(Vec::new())
}
async fn save_reset_credit_automation(
&self,
_: &gateway_admin::model::reset_credit_automation::ResetCreditAutomation,
_: Option<&gateway_admin::model::MutationContext>,
) -> AdminStoreResult<u64> {
Err(unavailable("reset-credit automation"))
}
}