mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-12-06 08:01:57 +00:00
perf(store): optimize PostgreSQL reads and batch writes
Use existing indexes for usage and recovery queries, narrow account ranking to filtered candidates, and aggregate shared key memberships once per group. Batch audit and plugin state writes, streamline analytics queue maintenance, and verify export capabilities before retrieving credentials by provider. Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
1 parent
efd5357fac
commit
8fc756ffec
28 files changed
+818
-487
No files matched your search
@@ -1314,6 +1314,13 @@ pub struct ProviderExport {
|
||||
pub document: ProviderDocument,
|
||||
}
|
||||
|
||||
/// 判断账号能否导出凭据所需的公开事实
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CredentialExportScope {
|
||||
pub provider_kind: ProviderKind,
|
||||
pub authentication_kind: String,
|
||||
}
|
||||
|
||||
/// Store 为 Provider 导出序列化准备的最小输入;material 对公共层保持不透明
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ProviderExportCredentialInput {
|
||||
|
||||
@@ -36,9 +36,9 @@ use crate::model::{
|
||||
UsageSummaryObservation,
|
||||
},
|
||||
provider_credentials::{
|
||||
AuthorizationCommit, CredentialDetails, CredentialImportCommit, CredentialImportResult,
|
||||
CredentialMutationResult, CredentialRotationCommit, PluginAccountListQuery,
|
||||
PluginAccountPage, ProviderExportCredentialInput,
|
||||
AuthorizationCommit, CredentialDetails, CredentialExportScope, CredentialImportCommit,
|
||||
CredentialImportResult, CredentialMutationResult, CredentialRotationCommit,
|
||||
PluginAccountListQuery, PluginAccountPage, ProviderExportCredentialInput,
|
||||
},
|
||||
quota_forecast::QuotaForecastHistory,
|
||||
settings::{AdminApiKey, AdminApiKeyMutation, ReplaceRuntimeSettings, RuntimeSettings},
|
||||
@@ -216,10 +216,17 @@ pub trait AccountStore:
|
||||
account_id: &gateway_core::account::ProviderAccountId,
|
||||
) -> AdminStoreResult<Option<CredentialDetails>>;
|
||||
|
||||
/// 只读取所选账号的 Provider 和认证方式,缺失的 ID 不在结果中
|
||||
async fn credential_export_scopes(
|
||||
&self,
|
||||
account_ids: &[gateway_core::account::ProviderAccountId],
|
||||
) -> AdminStoreResult<BTreeMap<String, CredentialExportScope>>;
|
||||
|
||||
/// 按请求顺序读取凭据,同时复核每个账号仍属于获准的 Provider 和认证方式
|
||||
async fn load_credentials_for_export(
|
||||
&self,
|
||||
provider_kind: &gateway_core::routing::ProviderKind,
|
||||
account_ids: &[gateway_core::account::ProviderAccountId],
|
||||
accounts: &[(gateway_core::account::ProviderAccountId, String)],
|
||||
) -> AdminStoreResult<Vec<ProviderExportCredentialInput>>;
|
||||
|
||||
/// 插件凭据读取只接收账号 ID,不接受调用方另行声明 Provider
|
||||
|
||||
@@ -710,30 +710,40 @@ impl AccountsService for DefaultAccountsService {
|
||||
if account_ids.is_empty() || account_ids.len() > 200 {
|
||||
return Err(AdminError::invalid("账号导出数量必须在 1 到 200 之间"));
|
||||
}
|
||||
let exported_ids = account_ids.clone();
|
||||
if account_ids.iter().collect::<BTreeSet<_>>().len() != account_ids.len() {
|
||||
return Err(AdminError::invalid("账号导出列表包含重复 ID"));
|
||||
}
|
||||
let mut scopes = self
|
||||
.accounts
|
||||
.credential_export_scopes(&account_ids)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "provider account export"))?;
|
||||
let mut grouped = BTreeMap::new();
|
||||
// 混选时先检查每个账号的导出能力,再读取任何一组明文凭据
|
||||
for id in account_ids {
|
||||
let (item, provider) = self.provider_for_account(&id).await?;
|
||||
for id in &account_ids {
|
||||
let scope = scopes
|
||||
.remove(id.as_str())
|
||||
.ok_or_else(|| AdminError::not_found("服务商账号不存在"))?;
|
||||
let provider = self
|
||||
.providers
|
||||
.require(&scope.provider_kind)
|
||||
.map_err(|error| map_provider_error(error, "provider account"))?;
|
||||
if !provider
|
||||
.account_capabilities(&id, &item.account.authentication_kind)
|
||||
.account_capabilities(id, &scope.authentication_kind)
|
||||
.credential_export
|
||||
{
|
||||
return Err(AdminError::invalid("所选账号不支持导出"));
|
||||
}
|
||||
let (_, ids) = grouped
|
||||
.entry(item.account.provider_kind)
|
||||
let (_, accounts) = grouped
|
||||
.entry(scope.provider_kind)
|
||||
.or_insert_with(|| (provider, Vec::new()));
|
||||
if ids.contains(&id) {
|
||||
return Err(AdminError::invalid("账号导出列表包含重复 ID"));
|
||||
}
|
||||
ids.push(id);
|
||||
accounts.push((id.clone(), scope.authentication_kind));
|
||||
}
|
||||
let mut documents = Vec::with_capacity(grouped.len());
|
||||
for (provider_kind, (provider, ids)) in grouped {
|
||||
for (provider_kind, (provider, accounts)) in grouped {
|
||||
let credentials = self
|
||||
.accounts
|
||||
.load_credentials_for_export(&provider_kind, &ids)
|
||||
.load_credentials_for_export(&provider_kind, &accounts)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "provider account export"))?;
|
||||
documents.push(
|
||||
@@ -744,7 +754,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
);
|
||||
}
|
||||
self.accounts
|
||||
.record_credential_export(&exported_ids, context)
|
||||
.record_credential_export(&account_ids, context)
|
||||
.await
|
||||
.map_err(|error| map_store_error(error, "provider account export audit"))?;
|
||||
Ok(AccountExportBundle {
|
||||
|
||||
@@ -41,16 +41,16 @@ use gateway_admin::{
|
||||
AuthorizationCommit, AuthorizationCommitGuard, AuthorizationCredentialCommit,
|
||||
AuthorizationMutationTarget, AuthorizationStarted, CompleteAuthorization,
|
||||
ConsumeProviderResetCredit, CredentialChange, CredentialCommitGuard, CredentialDetails,
|
||||
CredentialImportCommit, CredentialImportResult, CredentialMutationResult,
|
||||
CredentialRotationCommit, PendingAuthorizationMutation, PrepareCredentialImport,
|
||||
PrepareCredentialRefresh, PrepareCredentialRotation, PreparedAuthorizationCommit,
|
||||
PreparedAuthorizationCredential, PreparedCredentialCreate, PreparedCredentialImport,
|
||||
PreparedCredentialRotation, PreparedCredentialRotationFacts, PreparedPluginAccountSave,
|
||||
ProviderDocument, ProviderExport, ProviderExportCredentialInput, ProviderModels,
|
||||
ProviderProfileActivityInsights, ProviderProfileStatistics,
|
||||
ProviderProfileStatisticsSummary, ProviderQuota, ProviderQuotaRequest,
|
||||
ProviderQuotaWindow, ProviderResetCreditResult, ProviderSubscription,
|
||||
QuotaLocalUsageAttribution,
|
||||
CredentialExportScope, CredentialImportCommit, CredentialImportResult,
|
||||
CredentialMutationResult, CredentialRotationCommit, PendingAuthorizationMutation,
|
||||
PrepareCredentialImport, PrepareCredentialRefresh, PrepareCredentialRotation,
|
||||
PreparedAuthorizationCommit, PreparedAuthorizationCredential, PreparedCredentialCreate,
|
||||
PreparedCredentialImport, PreparedCredentialRotation, PreparedCredentialRotationFacts,
|
||||
PreparedPluginAccountSave, ProviderDocument, ProviderExport,
|
||||
ProviderExportCredentialInput, ProviderModels, ProviderProfileActivityInsights,
|
||||
ProviderProfileStatistics, ProviderProfileStatisticsSummary, ProviderQuota,
|
||||
ProviderQuotaRequest, ProviderQuotaWindow, ProviderResetCreditResult,
|
||||
ProviderSubscription, QuotaLocalUsageAttribution,
|
||||
},
|
||||
quota_forecast::{QuotaForecastHistory, QuotaForecastUsage},
|
||||
settings::{
|
||||
@@ -966,32 +966,59 @@ impl AccountStore for FakeAccountStore {
|
||||
}))
|
||||
}
|
||||
|
||||
async fn credential_export_scopes(
|
||||
&self,
|
||||
ids: &[ProviderAccountId],
|
||||
) -> AdminStoreResult<BTreeMap<String, CredentialExportScope>> {
|
||||
self.record("store.credential_export_scopes");
|
||||
Ok(self
|
||||
.accounts
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|account| ids.iter().any(|id| id.as_str() == account.id))
|
||||
.map(|account| {
|
||||
(
|
||||
account.id.clone(),
|
||||
CredentialExportScope {
|
||||
provider_kind: account.provider_kind.clone(),
|
||||
authentication_kind: account.authentication_kind.clone(),
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn load_credentials_for_export(
|
||||
&self,
|
||||
provider_kind: &ProviderKind,
|
||||
account_ids: &[ProviderAccountId],
|
||||
selected: &[(ProviderAccountId, String)],
|
||||
) -> AdminStoreResult<Vec<ProviderExportCredentialInput>> {
|
||||
self.record("store.load_credentials_for_export");
|
||||
let accounts = self.accounts.lock().expect("accounts").clone();
|
||||
if accounts.iter().any(|account| {
|
||||
&account.provider_kind != provider_kind
|
||||
|| !account_ids
|
||||
let accounts = self.accounts.lock().expect("accounts");
|
||||
selected
|
||||
.iter()
|
||||
.map(|(id, auth)| {
|
||||
let account = accounts
|
||||
.iter()
|
||||
.any(|account_id| account_id.as_str() == account.id)
|
||||
}) {
|
||||
return Err(AdminStoreError::new(
|
||||
AdminStoreErrorKind::NotFound,
|
||||
"test account",
|
||||
"credential not found",
|
||||
));
|
||||
}
|
||||
Ok(accounts
|
||||
.into_iter()
|
||||
.map(|account| ProviderExportCredentialInput {
|
||||
account,
|
||||
provider_material: document(),
|
||||
.find(|account| {
|
||||
account.id == id.as_str()
|
||||
&& &account.provider_kind == provider_kind
|
||||
&& &account.authentication_kind == auth
|
||||
})
|
||||
.ok_or_else(|| {
|
||||
AdminStoreError::new(
|
||||
AdminStoreErrorKind::NotFound,
|
||||
"test account",
|
||||
"credential not found",
|
||||
)
|
||||
})?;
|
||||
Ok(ProviderExportCredentialInput {
|
||||
account: account.clone(),
|
||||
provider_material: document(),
|
||||
})
|
||||
})
|
||||
.collect())
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn load_credential_for_plugin(
|
||||
@@ -1209,7 +1236,7 @@ impl AccountStore for FakeAccountStore {
|
||||
) -> AdminStoreResult<()> {
|
||||
self.record("store.audit_export");
|
||||
self.record_context(context);
|
||||
Ok(())
|
||||
self.require_commit()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1528,22 +1555,43 @@ async fn connection_test_should_preserve_disabled_account_status() {
|
||||
#[tokio::test]
|
||||
async fn unsupported_account_export_stops_before_loading_credentials() {
|
||||
let calls = events();
|
||||
let provider = FakeProviderAdmin::new("fixture", calls.clone());
|
||||
let store = FakeAccountStore::new("fixture", calls.clone());
|
||||
let id = ProviderAccountId::new(store.accounts.lock().unwrap()[0].id.clone()).unwrap();
|
||||
let services = accounts_service(provider, store).await;
|
||||
let error = services
|
||||
.accounts()
|
||||
.export(&context("export-unsupported"), vec![id])
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), gateway_admin::model::AdminErrorKind::Invalid);
|
||||
assert!(
|
||||
!calls
|
||||
.lock()
|
||||
.unwrap()
|
||||
.contains(&"store.load_credentials_for_export")
|
||||
);
|
||||
let supported = FakeProviderAdmin::new("openai", calls.clone());
|
||||
supported.capabilities.lock().unwrap().credential_export = true;
|
||||
let unsupported = FakeProviderAdmin::new("fixture", calls.clone());
|
||||
let store = FakeAccountStore::new("openai", calls.clone());
|
||||
let mut another = account_record("fixture");
|
||||
another.id = "acct_unsupported".into();
|
||||
store.accounts.lock().unwrap().push(another);
|
||||
let services = super::AdminHarness::new()
|
||||
.accounts(store)
|
||||
.provider(supported)
|
||||
.provider(unsupported)
|
||||
.build()
|
||||
.await;
|
||||
let export = services.accounts();
|
||||
for (second, expected) in [
|
||||
(
|
||||
"acct_unsupported",
|
||||
gateway_admin::model::AdminErrorKind::Invalid,
|
||||
),
|
||||
(
|
||||
"acct_missing",
|
||||
gateway_admin::model::AdminErrorKind::NotFound,
|
||||
),
|
||||
] {
|
||||
calls.lock().unwrap().clear();
|
||||
let result = export
|
||||
.export(
|
||||
&context("export-unsupported"),
|
||||
vec![
|
||||
ProviderAccountId::new("acct_test").unwrap(),
|
||||
ProviderAccountId::new(second).unwrap(),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
assert_eq!(result.unwrap_err().kind(), expected);
|
||||
assert_eq!(*calls.lock().unwrap(), ["store.credential_export_scopes"]);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -1552,17 +1600,28 @@ async fn accounts_export_should_pass_store_loaded_timestamps_and_material_to_pro
|
||||
provider.capabilities.lock().unwrap().credential_export = true;
|
||||
let store = FakeAccountStore::new("openai", events());
|
||||
let expected = store.accounts.lock().expect("accounts")[0].clone();
|
||||
accounts_service(provider.clone(), store)
|
||||
.await
|
||||
let mut second = expected.clone();
|
||||
second.id = "acct_second".into();
|
||||
store.accounts.lock().unwrap().push(second.clone());
|
||||
let services = accounts_service(provider.clone(), store.clone()).await;
|
||||
let ids = vec![
|
||||
ProviderAccountId::new(second.id.clone()).unwrap(),
|
||||
ProviderAccountId::new(expected.id.clone()).unwrap(),
|
||||
];
|
||||
services
|
||||
.accounts()
|
||||
.export(
|
||||
&context("export-complete-input"),
|
||||
vec![ProviderAccountId::new(expected.id.clone()).expect("account ID")],
|
||||
)
|
||||
.export(&context("export-complete-input"), ids.clone())
|
||||
.await
|
||||
.expect("export credentials");
|
||||
|
||||
let inputs = provider.export_inputs();
|
||||
assert_eq!(
|
||||
inputs
|
||||
.iter()
|
||||
.map(|input| &input.account.id)
|
||||
.collect::<Vec<_>>(),
|
||||
[&second.id, &expected.id]
|
||||
);
|
||||
let input = inputs.first().expect("provider export input");
|
||||
assert_eq!(
|
||||
(
|
||||
@@ -1570,7 +1629,18 @@ async fn accounts_export_should_pass_store_loaded_timestamps_and_material_to_pro
|
||||
input.account.updated_at,
|
||||
&input.provider_material,
|
||||
),
|
||||
(expected.created_at, expected.updated_at, &document()),
|
||||
(second.created_at, second.updated_at, &document()),
|
||||
);
|
||||
|
||||
store.fail_next_commit();
|
||||
let error = services
|
||||
.accounts()
|
||||
.export(&context("export-failed-audit"), ids)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
error.kind(),
|
||||
gateway_admin::model::AdminErrorKind::Unavailable
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -53,11 +53,11 @@ use gateway_admin::{
|
||||
},
|
||||
provider_credentials::{
|
||||
AuthorizationCommit, AuthorizationStarted, CompleteAuthorization, CredentialDetails,
|
||||
CredentialImportCommit, CredentialImportResult, CredentialMutationResult,
|
||||
CredentialRotationCommit, PrepareCredentialImport, PrepareCredentialRefresh,
|
||||
PrepareCredentialRotation, PreparedAuthorizationCommit, PreparedCredentialImport,
|
||||
PreparedCredentialRotation, ProviderExport, ProviderExportCredentialInput,
|
||||
ProviderModels, ProviderQuota,
|
||||
CredentialExportScope, CredentialImportCommit, CredentialImportResult,
|
||||
CredentialMutationResult, CredentialRotationCommit, PrepareCredentialImport,
|
||||
PrepareCredentialRefresh, PrepareCredentialRotation, PreparedAuthorizationCommit,
|
||||
PreparedCredentialImport, PreparedCredentialRotation, ProviderExport,
|
||||
ProviderExportCredentialInput, ProviderModels, ProviderQuota,
|
||||
},
|
||||
settings::{AdminApiKey, AdminApiKeyMutation, ReplaceRuntimeSettings, RuntimeSettings},
|
||||
system::{SystemOperationAccepted, SystemUpdateDetail, SystemUpdateStatus, SystemVersion},
|
||||
@@ -579,10 +579,17 @@ impl AccountStore for UnavailableStore {
|
||||
Err(unavailable("credential"))
|
||||
}
|
||||
|
||||
async fn credential_export_scopes(
|
||||
&self,
|
||||
_: &[ProviderAccountId],
|
||||
) -> AdminStoreResult<BTreeMap<String, CredentialExportScope>> {
|
||||
Err(unavailable("credential export"))
|
||||
}
|
||||
|
||||
async fn load_credentials_for_export(
|
||||
&self,
|
||||
_: &ProviderKind,
|
||||
_: &[ProviderAccountId],
|
||||
_: &[(ProviderAccountId, String)],
|
||||
) -> AdminStoreResult<Vec<ProviderExportCredentialInput>> {
|
||||
Err(unavailable("credential export"))
|
||||
}
|
||||
|
||||
@@ -46,11 +46,11 @@ use gateway_admin::{
|
||||
},
|
||||
provider_credentials::{
|
||||
AuthorizationCommit, AuthorizationStarted, CompleteAuthorization, CredentialDetails,
|
||||
CredentialImportCommit, CredentialImportResult, CredentialMutationResult,
|
||||
CredentialRotationCommit, PrepareCredentialImport, PrepareCredentialRefresh,
|
||||
PrepareCredentialRotation, PreparedAuthorizationCommit, PreparedCredentialImport,
|
||||
PreparedCredentialRotation, ProviderExport, ProviderExportCredentialInput,
|
||||
ProviderModels, ProviderQuota,
|
||||
CredentialExportScope, CredentialImportCommit, CredentialImportResult,
|
||||
CredentialMutationResult, CredentialRotationCommit, PrepareCredentialImport,
|
||||
PrepareCredentialRefresh, PrepareCredentialRotation, PreparedAuthorizationCommit,
|
||||
PreparedCredentialImport, PreparedCredentialRotation, ProviderExport,
|
||||
ProviderExportCredentialInput, ProviderModels, ProviderQuota,
|
||||
},
|
||||
settings::{
|
||||
AdminApiKey, AdminApiKeyMutation, ModelMappings, ReplaceRuntimeSettings,
|
||||
@@ -1367,10 +1367,17 @@ impl AccountStore for UnusedStore {
|
||||
Err(unavailable("plugin credential"))
|
||||
}
|
||||
|
||||
async fn credential_export_scopes(
|
||||
&self,
|
||||
_: &[ProviderAccountId],
|
||||
) -> AdminStoreResult<BTreeMap<String, CredentialExportScope>> {
|
||||
Err(unavailable("credential export"))
|
||||
}
|
||||
|
||||
async fn load_credentials_for_export(
|
||||
&self,
|
||||
_: &ProviderKind,
|
||||
_: &[ProviderAccountId],
|
||||
_: &[(ProviderAccountId, String)],
|
||||
) -> AdminStoreResult<Vec<ProviderExportCredentialInput>> {
|
||||
Err(unavailable("credential export"))
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use async_trait::async_trait;
|
||||
use chrono::{DateTime, Utc};
|
||||
use gateway_admin::model::MutationContext;
|
||||
use sqlx::{PgPool, Postgres, Transaction};
|
||||
use sqlx::{Executor, PgPool, Postgres, QueryBuilder, Transaction};
|
||||
|
||||
use crate::{Revision, StoreError, StoreResult, postgres_unavailable, require_nonempty};
|
||||
|
||||
@@ -91,6 +91,12 @@ pub(crate) fn mutation_audit(
|
||||
entity_ref,
|
||||
}
|
||||
.event(context, changed_fields);
|
||||
unversioned_audit_event(event)
|
||||
}
|
||||
|
||||
pub(super) fn unversioned_audit_event(
|
||||
event: gateway_admin::model::auth::AdminAuditEvent,
|
||||
) -> AdminAuditEvent {
|
||||
AdminAuditEvent {
|
||||
id: event.id,
|
||||
actor_kind: event.actor_kind.into(),
|
||||
@@ -208,28 +214,7 @@ impl AdminSecurityAuditRepository for PgAdminSecurityAuditRepository {
|
||||
}
|
||||
|
||||
async fn append_admin_audit_event(&self, event: AdminAuditEvent) -> StoreResult<()> {
|
||||
event.validate()?;
|
||||
sqlx::query(
|
||||
"insert into admin_audit_events (
|
||||
id, actor_kind, actor_admin_user_id, actor_ref, admin_request_id,
|
||||
action, entity_kind, entity_ref, config_revision, changed_fields, created_at
|
||||
) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)",
|
||||
)
|
||||
.bind(event.id)
|
||||
.bind(event.actor_kind.as_str())
|
||||
.bind(event.actor_admin_user_id)
|
||||
.bind(event.actor_ref)
|
||||
.bind(event.admin_request_id)
|
||||
.bind(event.action)
|
||||
.bind(event.entity_kind)
|
||||
.bind(event.entity_ref)
|
||||
.bind(event.config_revision)
|
||||
.bind(event.changed_fields)
|
||||
.bind(event.created_at)
|
||||
.execute(&self.pool)
|
||||
.await
|
||||
.map_err(|source| postgres_unavailable("append admin audit event", source))?;
|
||||
Ok(())
|
||||
insert_admin_audit_events(&self.pool, &[event]).await
|
||||
}
|
||||
}
|
||||
|
||||
@@ -246,27 +231,43 @@ pub(crate) async fn append_admin_audit_event_in_transaction(
|
||||
})
|
||||
})
|
||||
.transpose()?;
|
||||
event.validate()?;
|
||||
sqlx::query(
|
||||
insert_admin_audit_events(&mut **transaction, &[event]).await
|
||||
}
|
||||
|
||||
pub(super) async fn insert_admin_audit_events<'e>(
|
||||
executor: impl Executor<'e, Database = Postgres>,
|
||||
events: &[AdminAuditEvent],
|
||||
) -> StoreResult<()> {
|
||||
if events.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
for event in events {
|
||||
event.validate()?;
|
||||
}
|
||||
let mut sql = QueryBuilder::<Postgres>::new(
|
||||
"insert into admin_audit_events (
|
||||
id, actor_kind, actor_admin_user_id, actor_ref, admin_request_id,
|
||||
action, entity_kind, entity_ref, config_revision, changed_fields, created_at
|
||||
) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)",
|
||||
)
|
||||
.bind(event.id)
|
||||
.bind(event.actor_kind.as_str())
|
||||
.bind(event.actor_admin_user_id)
|
||||
.bind(event.actor_ref)
|
||||
.bind(event.admin_request_id)
|
||||
.bind(event.action)
|
||||
.bind(event.entity_kind)
|
||||
.bind(event.entity_ref)
|
||||
.bind(event.config_revision)
|
||||
.bind(event.changed_fields)
|
||||
.bind(event.created_at)
|
||||
.execute(&mut **transaction)
|
||||
.await
|
||||
.map_err(|source| postgres_unavailable("append admin audit event in transaction", source))?;
|
||||
id, actor_kind, actor_admin_user_id, actor_ref, admin_request_id,
|
||||
action, entity_kind, entity_ref, config_revision, changed_fields, created_at
|
||||
) ",
|
||||
);
|
||||
sql.push_values(events, |mut row, event| {
|
||||
row.push_bind(&event.id)
|
||||
.push_bind(event.actor_kind.as_str())
|
||||
.push_bind(&event.actor_admin_user_id)
|
||||
.push_bind(&event.actor_ref)
|
||||
.push_bind(&event.admin_request_id)
|
||||
.push_bind(&event.action)
|
||||
.push_bind(&event.entity_kind)
|
||||
.push_bind(&event.entity_ref)
|
||||
.push_bind(event.config_revision)
|
||||
.push_bind(&event.changed_fields)
|
||||
.push_bind(event.created_at);
|
||||
});
|
||||
sql.build()
|
||||
.persistent(events.len() == 1)
|
||||
.execute(executor)
|
||||
.await
|
||||
.map_err(|source| postgres_unavailable("append admin audit event", source))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -1841,29 +1841,31 @@ async fn load_client_key_memberships(
|
||||
"with requested_keys(key_id) as (
|
||||
select unnest($1::text[])
|
||||
),
|
||||
global_providers as (
|
||||
select coalesce(array_agg(distinct provider_kind order by provider_kind), '{}')
|
||||
as provider_kinds
|
||||
from provider_accounts
|
||||
bindings as (
|
||||
select b.client_api_key_id, b.account_group_id
|
||||
from client_api_key_groups b
|
||||
where b.client_api_key_id = any($1::text[])
|
||||
),
|
||||
group_providers as (
|
||||
select m.account_group_id,
|
||||
array_agg(distinct a.provider_kind order by a.provider_kind) as provider_kinds
|
||||
from (select distinct account_group_id from bindings) b
|
||||
join account_groups g on g.id = b.account_group_id and g.enabled
|
||||
join account_group_accounts m on m.account_group_id = g.id
|
||||
join provider_accounts a on a.id = m.provider_account_id
|
||||
group by m.account_group_id
|
||||
)
|
||||
select requested_keys.key_id,
|
||||
groups.id as group_id, groups.name as group_name, groups.color as group_color,
|
||||
groups.enabled as group_enabled,
|
||||
global_providers.provider_kinds as global_provider_kinds,
|
||||
coalesce(array_agg(distinct accounts.provider_kind order by accounts.provider_kind)
|
||||
filter (where accounts.provider_kind is not null), '{}')
|
||||
as group_provider_kinds
|
||||
case when groups.id is null then
|
||||
(select coalesce(array_agg(distinct provider_kind order by provider_kind), '{}')
|
||||
from provider_accounts)
|
||||
else coalesce(group_providers.provider_kinds, '{}') end as provider_kinds
|
||||
from requested_keys
|
||||
cross join global_providers
|
||||
left join client_api_key_groups bindings
|
||||
on bindings.client_api_key_id = requested_keys.key_id
|
||||
left join bindings on bindings.client_api_key_id = requested_keys.key_id
|
||||
left join account_groups groups on groups.id = bindings.account_group_id
|
||||
left join account_group_accounts memberships
|
||||
on memberships.account_group_id = groups.id and groups.enabled
|
||||
left join provider_accounts accounts
|
||||
on accounts.id = memberships.provider_account_id
|
||||
group by requested_keys.key_id, global_providers.provider_kinds,
|
||||
groups.id, groups.name, groups.color, groups.enabled
|
||||
left join group_providers on group_providers.account_group_id = groups.id
|
||||
order by requested_keys.key_id, groups.id",
|
||||
)
|
||||
.bind(ids)
|
||||
@@ -1896,20 +1898,13 @@ async fn load_client_key_memberships(
|
||||
invalid("invalid client API key group state").with_source(source)
|
||||
})?,
|
||||
});
|
||||
providers.entry(key_id).or_default().extend(
|
||||
row.try_get::<Vec<String>, _>("group_provider_kinds")
|
||||
.map_err(|source| {
|
||||
invalid("invalid client API key provider kinds").with_source(source)
|
||||
})?,
|
||||
);
|
||||
} else {
|
||||
providers.entry(key_id).or_default().extend(
|
||||
row.try_get::<Vec<String>, _>("global_provider_kinds")
|
||||
.map_err(|source| {
|
||||
invalid("invalid global provider kinds").with_source(source)
|
||||
})?,
|
||||
);
|
||||
}
|
||||
providers.entry(key_id).or_default().extend(
|
||||
row.try_get::<Vec<String>, _>("provider_kinds")
|
||||
.map_err(|source| {
|
||||
invalid("invalid client API key provider kinds").with_source(source)
|
||||
})?,
|
||||
);
|
||||
}
|
||||
for record in records {
|
||||
record.groups = groups.remove(&record.id).unwrap_or_default();
|
||||
|
||||
@@ -678,8 +678,7 @@ impl ModelRequestRepository for PgExecutionStore {
|
||||
and prior.outcome in ('failed', 'incomplete')
|
||||
and prior.error_kind = 'continuation_recovery_required'
|
||||
and prior.recovered_at is null
|
||||
and current.started_at >= prior.completed_at
|
||||
and current.started_at <= prior.completed_at + interval '30 seconds'
|
||||
and prior.completed_at between current.started_at - interval '30 seconds' and current.started_at
|
||||
order by prior.completed_at desc, prior.id desc
|
||||
limit 1
|
||||
), recovery_update as (
|
||||
@@ -720,8 +719,7 @@ impl ModelRequestRepository for PgExecutionStore {
|
||||
and prior.upstream_send_state = 'ambiguous'
|
||||
and prior.downstream_committed_at is null
|
||||
and prior.recovered_at is null
|
||||
and current.started_at >= prior.completed_at
|
||||
and current.started_at <= prior.completed_at + interval '30 seconds'
|
||||
and prior.completed_at between current.started_at - interval '30 seconds' and current.started_at
|
||||
), session_transport_recovery_update as (
|
||||
update model_requests prior
|
||||
set recovery_attempt_count = prior.recovery_attempt_count + 1,
|
||||
|
||||
@@ -692,19 +692,19 @@ async fn retained_account_usage_range(
|
||||
pub(crate) async fn account_usage_sort_values(
|
||||
snapshot: &mut AnalyticsSnapshot<'_>,
|
||||
now: DateTime<Utc>,
|
||||
) -> StoreResult<(Vec<String>, Vec<i64>, Vec<Option<DateTime<Utc>>>)> {
|
||||
ids: &[String],
|
||||
) -> StoreResult<(Vec<i64>, Vec<Option<DateTime<Utc>>>)> {
|
||||
if ids.is_empty() {
|
||||
return Ok((Vec::new(), Vec::new()));
|
||||
}
|
||||
let range = retained_account_usage_range(snapshot, now).await?;
|
||||
let ids: Vec<String> = sqlx::query_scalar("select id from provider_accounts")
|
||||
.fetch_all(&mut *snapshot.tx)
|
||||
.await
|
||||
.map_err(|error| postgres_unavailable("read account usage sort identities", error))?;
|
||||
let mut totals = BTreeMap::<String, MetricState>::new();
|
||||
for ((account, _), state) in snapshot.account_states(range, &ids, false).await? {
|
||||
for ((account, _), state) in snapshot.account_states(range, ids, false).await? {
|
||||
totals.entry(account).or_default().merge(&state)?;
|
||||
}
|
||||
let mut tokens = Vec::with_capacity(ids.len());
|
||||
let mut latest = Vec::with_capacity(ids.len());
|
||||
for id in &ids {
|
||||
for id in ids {
|
||||
let state = totals.remove(id).unwrap_or_default();
|
||||
tokens.push(
|
||||
i64::try_from(state.count("window_total_tokens"))
|
||||
@@ -712,7 +712,7 @@ pub(crate) async fn account_usage_sort_values(
|
||||
);
|
||||
latest.push(state.last_used_at());
|
||||
}
|
||||
Ok((ids, tokens, latest))
|
||||
Ok((tokens, latest))
|
||||
}
|
||||
|
||||
pub(crate) async fn account_group_usage(
|
||||
|
||||
@@ -127,8 +127,8 @@ pub(super) async fn rebuild_bucket_batch(
|
||||
if phase == 1 {
|
||||
// 增量前缀判断使用 Rust 字节序,SQL 游标必须使用同一排序规则
|
||||
let statement = format!(
|
||||
"{} where mr.started_at >= $1 and mr.started_at < $1+interval '15 minutes' and (mr.started_at,mr.id collate \"C\")>($2,$3) order by mr.started_at,mr.id collate \"C\" limit $4",
|
||||
fact_select()
|
||||
"select {} from request_analytics_facts mr where mr.started_at >= $1 and mr.started_at < $1+interval '15 minutes' and (mr.started_at,mr.id collate \"C\")>($2,$3) order by mr.started_at,mr.id collate \"C\" limit $4",
|
||||
fact_columns()
|
||||
);
|
||||
let rows = sqlx::query(sqlx::AssertSqlSafe(statement))
|
||||
.bind(bucket)
|
||||
|
||||
@@ -56,9 +56,9 @@ pub(crate) async fn begin_snapshot(
|
||||
Ok(transaction)
|
||||
}
|
||||
|
||||
fn fact_select() -> String {
|
||||
fn fact_columns() -> String {
|
||||
format!(
|
||||
"select mr.*, mr.cost_amount::text as cost_amount_text, mr.standard_cost_amount::text as standard_cost_amount_text, mr.no_cache_cost_amount::text as no_cache_cost_amount_text, coalesce(({}),false) as is_completed_usage from request_analytics_facts mr",
|
||||
"mr.*, mr.cost_amount::text as cost_amount_text, mr.standard_cost_amount::text as standard_cost_amount_text, mr.no_cache_cost_amount::text as no_cache_cost_amount_text, coalesce(({}),false) as is_completed_usage",
|
||||
completed_usage_fact_predicate("mr")
|
||||
)
|
||||
}
|
||||
|
||||
@@ -54,7 +54,14 @@ pub(crate) async fn declare_usage_statistics(
|
||||
continue;
|
||||
}
|
||||
let (key, model, provider, account) = summary_columns(collection);
|
||||
let group = group_expression(request.group_by, key, model, "null::text", false);
|
||||
// 汇总以空串保存缺失维度,仅分组输出还原 NULL,筛选直接使用维度索引
|
||||
let group = group_expression(
|
||||
request.group_by,
|
||||
&format!("nullif({key},'')"),
|
||||
&format!("nullif({model},'')"),
|
||||
"null::text",
|
||||
false,
|
||||
);
|
||||
query.push(format!(" union all select names.name,a.counts,a.costs from {table} a cross join lateral (values ({group}),('null')) names(name) where a.collection="))
|
||||
.push_bind(collection).push(" and a.schema_version=").push_bind(SCHEMA_VERSION)
|
||||
.push(" and a.histogram_version=").push_bind(HISTOGRAM_VERSION);
|
||||
@@ -67,8 +74,9 @@ pub(crate) async fn declare_usage_statistics(
|
||||
] {
|
||||
if let Some(value) = value {
|
||||
query
|
||||
.push(format!(" and {column}="))
|
||||
.push_bind(value.clone());
|
||||
.push(format!(" and {column}=nullif("))
|
||||
.push_bind(value.clone())
|
||||
.push(",'')");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -208,28 +216,23 @@ fn collection(query: &QueryUsageStatistics) -> Option<&'static str> {
|
||||
|
||||
fn summary_columns(collection: &str) -> (&'static str, &'static str, &'static str, &'static str) {
|
||||
match collection {
|
||||
"key" => (
|
||||
"nullif(a.dimensions[1],'')",
|
||||
"null::text",
|
||||
"null::text",
|
||||
"null::text",
|
||||
),
|
||||
"key" => ("a.dimensions[1]", "null::text", "null::text", "null::text"),
|
||||
"key_model" => (
|
||||
"nullif(a.dimensions[1],'')",
|
||||
"nullif(a.dimensions[4],'')",
|
||||
"nullif(a.dimensions[2],'')",
|
||||
"a.dimensions[1]",
|
||||
"a.dimensions[4]",
|
||||
"a.dimensions[2]",
|
||||
"null::text",
|
||||
),
|
||||
"account_model" => (
|
||||
"null::text",
|
||||
"nullif(a.dimensions[4],'')",
|
||||
"nullif(a.dimensions[2],'')",
|
||||
"nullif(a.dimensions[1],'')",
|
||||
"a.dimensions[4]",
|
||||
"a.dimensions[2]",
|
||||
"a.dimensions[1]",
|
||||
),
|
||||
_ => (
|
||||
"null::text",
|
||||
"nullif(a.dimensions[3],'')",
|
||||
"nullif(a.dimensions[1],'')",
|
||||
"a.dimensions[3]",
|
||||
"a.dimensions[1]",
|
||||
"null::text",
|
||||
),
|
||||
}
|
||||
|
||||
@@ -120,15 +120,17 @@ impl PgRequestAnalyticsRepository {
|
||||
publish_generation(&mut transaction, true).await?;
|
||||
}
|
||||
transaction.commit().await.map_err(|error| postgres_unavailable("publish analytics maintenance", error))?;
|
||||
// 快照后提交的源版本会让 RR 下的行锁直接序列化失败,持续写入时整批投影会反复回滚
|
||||
// ACK 在投影提交后使用 READ COMMITTED,行锁按最新提交版本重新比较,已改写的版本不再匹配
|
||||
let mut transaction = connection.begin().await.map_err(|error| postgres_unavailable("begin analytics acknowledgement", error))?;
|
||||
sqlx::query("set local statement_timeout = '10s'").execute(&mut *transaction).await.map_err(|error| postgres_unavailable("set analytics query deadline", error))?;
|
||||
// ACK 跳过源事务持有的队列行,避免等待并发更新或删除
|
||||
// 被跳过的版本保留在持久队列中重放,只有精确匹配且已取得行锁的版本才确认
|
||||
sqlx::query("with acknowledged as materialized (select pending.request_id,pending.change_version from request_analytics_pending_requests pending join unnest($1::text[],$2::bigint[]) job(id,version) on pending.request_id=job.id and pending.change_version=job.version for update of pending skip locked) delete from request_analytics_pending_requests pending using acknowledged where pending.request_id=acknowledged.request_id and pending.change_version=acknowledged.change_version")
|
||||
.bind(ids).bind(versions).execute(&mut *transaction).await.map_err(|error| postgres_unavailable("confirm analytics request versions", error))?;
|
||||
transaction.commit().await.map_err(|error| postgres_unavailable("complete analytics acknowledgement", error))?;
|
||||
if !ids.is_empty() {
|
||||
// 快照后提交的源版本会让 RR 下的行锁直接序列化失败,持续写入时整批投影会反复回滚
|
||||
// ACK 在投影提交后使用 READ COMMITTED,行锁按最新提交版本重新比较,已改写的版本不再匹配
|
||||
let mut transaction = connection.begin().await.map_err(|error| postgres_unavailable("begin analytics acknowledgement", error))?;
|
||||
sqlx::query("set local statement_timeout = '10s'").execute(&mut *transaction).await.map_err(|error| postgres_unavailable("set analytics query deadline", error))?;
|
||||
// ACK 跳过源事务持有的队列行,避免等待并发更新或删除
|
||||
// 被跳过的版本保留在持久队列中重放,只有精确匹配且已取得行锁的版本才确认
|
||||
sqlx::query("with acknowledged as materialized (select pending.request_id,pending.change_version from request_analytics_pending_requests pending join unnest($1::text[],$2::bigint[]) job(id,version) on pending.request_id=job.id and pending.change_version=job.version for update of pending skip locked) delete from request_analytics_pending_requests pending using acknowledged where pending.request_id=acknowledged.request_id and pending.change_version=acknowledged.change_version")
|
||||
.bind(ids).bind(versions).execute(&mut *transaction).await.map_err(|error| postgres_unavailable("confirm analytics request versions", error))?;
|
||||
transaction.commit().await.map_err(|error| postgres_unavailable("complete analytics acknowledgement", error))?;
|
||||
}
|
||||
// 每个阶段使用独立短事务,聚合只锁自己的队列,不把读放大传递到请求终结
|
||||
let mut transaction = begin_snapshot(&mut connection).await?;
|
||||
let acquired: bool = sqlx::query_scalar("select pg_try_advisory_xact_lock(hashtextextended(current_schema()::text,382032))")
|
||||
@@ -158,19 +160,14 @@ impl PgRequestAnalyticsRepository {
|
||||
if ids.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let columns = fact_columns();
|
||||
let previous = sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
"{} where mr.id=any($1::text[])",
|
||||
fact_select()
|
||||
"delete from request_analytics_facts mr where mr.id=any($1::text[]) returning {columns}"
|
||||
)))
|
||||
.bind(ids)
|
||||
.fetch_all(&mut **tx)
|
||||
.await
|
||||
.map_err(|error| postgres_unavailable("read previous analytics contributions", error))?;
|
||||
sqlx::query("delete from request_analytics_facts where id=any($1::text[])")
|
||||
.bind(ids)
|
||||
.execute(&mut **tx)
|
||||
.await
|
||||
.map_err(|error| postgres_unavailable("replace analytics facts", error))?;
|
||||
.map_err(|error| postgres_unavailable("replace analytics facts", error))?;
|
||||
sqlx::query(PROJECT_REQUEST)
|
||||
.bind(ids)
|
||||
.execute(&mut **tx)
|
||||
@@ -178,8 +175,7 @@ impl PgRequestAnalyticsRepository {
|
||||
.map_err(|error| postgres_unavailable("project analytics facts", error))?;
|
||||
self.project_billing_batch(tx, ids).await?;
|
||||
let current = sqlx::query(sqlx::AssertSqlSafe(format!(
|
||||
"{} where mr.id=any($1::text[])",
|
||||
fact_select()
|
||||
"select {columns} from request_analytics_facts mr where mr.id=any($1::text[])"
|
||||
)))
|
||||
.bind(ids)
|
||||
.fetch_all(&mut **tx)
|
||||
|
||||
@@ -28,7 +28,7 @@ use gateway_admin::{
|
||||
store::{AdminStoreError, AdminStoreErrorKind, AdminStoreResult},
|
||||
},
|
||||
};
|
||||
use sqlx::{PgConnection, Postgres, Row as _, Transaction};
|
||||
use sqlx::{PgConnection, Postgres, QueryBuilder, Row as _, Transaction};
|
||||
use tokio::sync::OwnedSemaphorePermit;
|
||||
|
||||
use super::artifacts::PgPluginStore;
|
||||
@@ -872,21 +872,14 @@ impl PluginStateStore for PgPluginStore {
|
||||
let mut next_version = generation.next_record_version;
|
||||
let mut record_count = generation.record_count;
|
||||
let mut total_bytes = generation.total_bytes;
|
||||
for ((change, source), expected_key) in command
|
||||
.changes
|
||||
.iter()
|
||||
.zip(source_rows.iter())
|
||||
.zip(&command.expected_keys)
|
||||
{
|
||||
let value = match &change.action {
|
||||
let mut records = Vec::with_capacity(command.changes.len());
|
||||
for (change, source) in command.changes.into_iter().zip(source_rows) {
|
||||
let value = match change.action {
|
||||
PluginStateMigrationAction::Keep => {
|
||||
Some(source.try_get("value_json").map_err(|_| unavailable())?)
|
||||
source.try_get("value_json").map_err(|_| unavailable())?
|
||||
}
|
||||
PluginStateMigrationAction::Replace(value) => Some(value.clone()),
|
||||
PluginStateMigrationAction::Delete => None,
|
||||
};
|
||||
let Some(value) = value else {
|
||||
continue;
|
||||
PluginStateMigrationAction::Replace(value) => value,
|
||||
PluginStateMigrationAction::Delete => continue,
|
||||
};
|
||||
let bytes = u64::try_from(serde_json::to_vec(&value).map_err(|_| invalid())?.len())
|
||||
.map_err(|_| quota())?;
|
||||
@@ -900,28 +893,39 @@ impl PluginStateStore for PgPluginStore {
|
||||
}
|
||||
let version = next_version;
|
||||
next_version = next_version.checked_add(1).ok_or_else(quota)?;
|
||||
sqlx::query(
|
||||
"insert into plugin_state_records( \
|
||||
generation_id,state_key,value_json,value_bytes,record_version \
|
||||
) values ($1,$2,$3,$4,$5)",
|
||||
)
|
||||
.bind(generation.id)
|
||||
.bind(expected_key)
|
||||
.bind(value)
|
||||
.bind(i64::try_from(bytes).map_err(|_| quota())?)
|
||||
.bind(i64::try_from(version).map_err(|_| quota())?)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(|error| {
|
||||
if error
|
||||
.as_database_error()
|
||||
.is_some_and(|database| database.is_unique_violation())
|
||||
{
|
||||
conflict()
|
||||
} else {
|
||||
unavailable()
|
||||
}
|
||||
})?;
|
||||
records.push((
|
||||
change.key,
|
||||
value,
|
||||
i64::try_from(bytes).map_err(|_| quota())?,
|
||||
i64::try_from(version).map_err(|_| quota())?,
|
||||
));
|
||||
}
|
||||
if !records.is_empty() {
|
||||
let mut insert = QueryBuilder::<Postgres>::new(
|
||||
"insert into plugin_state_records(generation_id,state_key,value_json,value_bytes,record_version) ",
|
||||
);
|
||||
insert.push_values(records, |mut row, (key, value, bytes, version)| {
|
||||
row.push_bind(generation.id)
|
||||
.push_bind(key)
|
||||
.push_bind(value)
|
||||
.push_bind(bytes)
|
||||
.push_bind(version);
|
||||
});
|
||||
insert
|
||||
.build()
|
||||
.persistent(false)
|
||||
.execute(&mut *transaction)
|
||||
.await
|
||||
.map_err(|error| {
|
||||
if error
|
||||
.as_database_error()
|
||||
.is_some_and(|database| database.is_unique_violation())
|
||||
{
|
||||
conflict()
|
||||
} else {
|
||||
unavailable()
|
||||
}
|
||||
})?;
|
||||
}
|
||||
let complete = command.expected_keys.is_empty();
|
||||
let next_cursor = command.expected_keys.last().or(command.cursor.as_ref());
|
||||
|
||||
@@ -9,6 +9,17 @@ use gateway_core::provider_ports::ProviderCooldownPort;
|
||||
use super::*;
|
||||
use crate::postgres::ObservabilityQueryBudget;
|
||||
|
||||
fn credential_export_input(
|
||||
record: ProviderAccountRecord,
|
||||
) -> AdminStoreResult<ProviderExportCredentialInput> {
|
||||
Ok(ProviderExportCredentialInput {
|
||||
account: admin_account_record(record.summary)?,
|
||||
provider_material: ProviderDocument::new(OpaqueProviderData::new(
|
||||
record.provider_credentials_json.into_fields(),
|
||||
)),
|
||||
})
|
||||
}
|
||||
|
||||
fn account_capacity(
|
||||
account: &AccountRecord,
|
||||
default_concurrency: u64,
|
||||
@@ -541,45 +552,69 @@ impl AccountStore for PgAdminAccountStore {
|
||||
.transpose()
|
||||
}
|
||||
|
||||
async fn credential_export_scopes(
|
||||
&self,
|
||||
account_ids: &[CoreProviderAccountId],
|
||||
) -> AdminStoreResult<BTreeMap<String, CredentialExportScope>> {
|
||||
let ids = account_ids
|
||||
.iter()
|
||||
.map(CoreProviderAccountId::as_str)
|
||||
.collect::<Vec<_>>();
|
||||
let rows: Vec<(String, String, String)> = sqlx::query_as(
|
||||
"select id, provider_kind, authentication_kind from provider_accounts where id = any($1::text[])",
|
||||
)
|
||||
.bind(&ids)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.map_err(|source| {
|
||||
admin_store_error(ENTITY, postgres_unavailable("read credential export scopes", source))
|
||||
})?;
|
||||
rows.into_iter()
|
||||
.map(|(id, kind, authentication_kind)| {
|
||||
let provider_kind = ProviderKind::new(kind).map_err(|source| {
|
||||
admin_store_error(
|
||||
ENTITY,
|
||||
invalid("persisted Provider kind is invalid").with_source(source),
|
||||
)
|
||||
})?;
|
||||
Ok((
|
||||
id,
|
||||
CredentialExportScope {
|
||||
provider_kind,
|
||||
authentication_kind,
|
||||
},
|
||||
))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn load_credentials_for_export(
|
||||
&self,
|
||||
provider_kind: &ProviderKind,
|
||||
account_ids: &[CoreProviderAccountId],
|
||||
accounts: &[(CoreProviderAccountId, String)],
|
||||
) -> AdminStoreResult<Vec<ProviderExportCredentialInput>> {
|
||||
let ids = account_ids
|
||||
let ids = accounts
|
||||
.iter()
|
||||
.map(|id| id.as_str().to_owned())
|
||||
.map(|(id, _)| id.as_str().to_owned())
|
||||
.collect::<Vec<_>>();
|
||||
validate_admin_account_ids(&ids).map_err(|error| admin_store_error(ENTITY, error))?;
|
||||
let mut credentials = Vec::with_capacity(account_ids.len());
|
||||
for account_id in account_ids {
|
||||
let record = self
|
||||
.accounts
|
||||
.load_provider_account(account_id.as_str())
|
||||
.await
|
||||
.map_err(|error| admin_store_error(ENTITY, error))?
|
||||
.ok_or_else(|| {
|
||||
AdminStoreError::new(
|
||||
AdminStoreErrorKind::NotFound,
|
||||
ENTITY,
|
||||
"one or more exported credentials do not exist",
|
||||
)
|
||||
})?;
|
||||
if record.summary.provider_kind != provider_kind.as_str() {
|
||||
return Err(AdminStoreError::new(
|
||||
AdminStoreErrorKind::NotFound,
|
||||
ENTITY,
|
||||
"one or more exported credentials belong to another Provider",
|
||||
));
|
||||
}
|
||||
credentials.push(ProviderExportCredentialInput {
|
||||
account: admin_account_record(record.summary)?,
|
||||
provider_material: ProviderDocument::new(OpaqueProviderData::new(
|
||||
record.provider_credentials_json.fields().clone(),
|
||||
)),
|
||||
});
|
||||
let kinds = accounts
|
||||
.iter()
|
||||
.map(|(_, kind)| kind.as_str())
|
||||
.collect::<Vec<_>>();
|
||||
let records = self
|
||||
.accounts
|
||||
.load_export_records(provider_kind.as_str(), &ids, Some(&kinds))
|
||||
.await
|
||||
.map_err(|error| admin_store_error(ENTITY, error))?;
|
||||
if records.len() != ids.len() {
|
||||
return Err(AdminStoreError::new(
|
||||
AdminStoreErrorKind::NotFound,
|
||||
ENTITY,
|
||||
"one or more credentials are missing or outside the verified export scope",
|
||||
));
|
||||
}
|
||||
Ok(credentials)
|
||||
records.into_iter().map(credential_export_input).collect()
|
||||
}
|
||||
|
||||
async fn load_credential_for_plugin(
|
||||
@@ -590,14 +625,7 @@ impl AccountStore for PgAdminAccountStore {
|
||||
.load_provider_account(account_id.as_str())
|
||||
.await
|
||||
.map_err(|error| admin_store_error(ENTITY, error))?
|
||||
.map(|record| {
|
||||
Ok(ProviderExportCredentialInput {
|
||||
account: admin_account_record(record.summary)?,
|
||||
provider_material: ProviderDocument::new(OpaqueProviderData::new(
|
||||
record.provider_credentials_json.fields().clone(),
|
||||
)),
|
||||
})
|
||||
})
|
||||
.map(credential_export_input)
|
||||
.transpose()
|
||||
}
|
||||
|
||||
@@ -890,27 +918,6 @@ impl AccountStore for PgAdminAccountStore {
|
||||
.map(|id| id.as_str().to_owned())
|
||||
.collect::<Vec<_>>();
|
||||
validate_admin_account_ids(&ids).map_err(|error| admin_store_error(ENTITY, error))?;
|
||||
for account_id in &ids {
|
||||
if self
|
||||
.accounts
|
||||
.load_provider_account(account_id)
|
||||
.await
|
||||
.map_err(|error| admin_store_error(ENTITY, error))?
|
||||
.is_none()
|
||||
{
|
||||
return Err(AdminStoreError::new(
|
||||
AdminStoreErrorKind::NotFound,
|
||||
ENTITY,
|
||||
"one or more exported credentials do not exist",
|
||||
));
|
||||
}
|
||||
}
|
||||
let control_plane = self
|
||||
.control_plane
|
||||
.load_control_plane()
|
||||
.await
|
||||
.map_err(|error| admin_store_error(ENTITY, error))?;
|
||||
let revision = control_plane.settings.config_revision;
|
||||
let mut transaction = self.accounts.pool.begin().await.map_err(|source| {
|
||||
admin_store_error(
|
||||
ENTITY,
|
||||
@@ -918,20 +925,38 @@ impl AccountStore for PgAdminAccountStore {
|
||||
)
|
||||
})?;
|
||||
let result = async {
|
||||
for account_id in &ids {
|
||||
append_admin_audit_event_in_transaction(
|
||||
&mut transaction,
|
||||
mutation_audit(
|
||||
// 凭据序列化后重新确认账号存在,并阻止删除越过本次审计提交
|
||||
let (revision, locked_ids): (i64, Vec<String>) = sqlx::query_as(
|
||||
"select config_revision, array(
|
||||
select id from provider_accounts where id = any($1::text[]) order by id for key share
|
||||
) from runtime_settings where id = 1",
|
||||
)
|
||||
.bind(&ids)
|
||||
.fetch_one(&mut *transaction)
|
||||
.await
|
||||
.map_err(|source| postgres_unavailable("lock audited credential export accounts", source))?;
|
||||
let found = locked_ids.into_iter().collect::<BTreeSet<_>>();
|
||||
if let Some(id) = ids.iter().find(|id| !found.contains(*id)) {
|
||||
return Err(StoreError::NotFound {
|
||||
entity: ENTITY,
|
||||
id: id.clone(),
|
||||
source: None,
|
||||
});
|
||||
}
|
||||
let events = ids
|
||||
.iter()
|
||||
.map(|id| {
|
||||
let mut event = mutation_audit(
|
||||
context,
|
||||
MutationAuditOperation::ProviderAccountExportCredentials,
|
||||
account_id,
|
||||
id,
|
||||
Vec::new(),
|
||||
),
|
||||
revision,
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
Ok(())
|
||||
);
|
||||
event.config_revision = Some(revision);
|
||||
event
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
crate::postgres::insert_admin_audit_events(&mut *transaction, &events).await
|
||||
}
|
||||
.await;
|
||||
finish_admin_transaction(transaction, result, "credential export audit")
|
||||
|
||||
@@ -10,6 +10,47 @@ pub(crate) struct AdminAccountPageRows {
|
||||
pub(crate) summary: AccountSummary,
|
||||
}
|
||||
|
||||
// 目录筛选同时用于普通分页和用量排序的候选账号,分页前按相同条件确定集合
|
||||
const DIRECTORY_CTES: &str = "
|
||||
with account_statuses as (
|
||||
select a.id, a.provider_kind, a.name, a.email, a.upstream_account_id, a.plan_type, a.access_token_expires_at,
|
||||
case
|
||||
when not a.enabled then 'disabled'
|
||||
when a.credential_state <> 'ready'
|
||||
or a.access_token_expires_at <= $2 then 'error'
|
||||
when a.quota_access_state = 'exhausted'
|
||||
and (a.quota_exhaustion_deadline is null or a.quota_exhaustion_deadline > $2) then 'quota_exhausted'
|
||||
when a.id = any($1::text[]) or exists (
|
||||
select 1 from unnest($8::text[], $9::bigint[]) as limits(account_id, revision)
|
||||
where limits.account_id = a.id and limits.revision = a.credential_revision
|
||||
) then 'rate_limited'
|
||||
when a.quota_paused then 'quota_paused'
|
||||
else 'normal'
|
||||
end as admin_status
|
||||
from provider_accounts a
|
||||
),
|
||||
filtered as (
|
||||
select a.*
|
||||
from account_statuses a
|
||||
where ($3::text is null or a.provider_kind = $3)
|
||||
and ($4::text is null or
|
||||
lower(a.name) like $4 escape '\\' or
|
||||
lower(coalesce(a.email, '')) like $4 escape '\\')
|
||||
and ($5::text is null or a.admin_status = $5)
|
||||
and ($6::smallint = 0 or
|
||||
($6 = 1 and exists (
|
||||
select 1
|
||||
from account_group_accounts membership
|
||||
where membership.provider_account_id = a.id
|
||||
and membership.account_group_id = $7
|
||||
)) or
|
||||
($6 = 2 and not exists (
|
||||
select 1
|
||||
from account_group_accounts membership
|
||||
where membership.provider_account_id = a.id
|
||||
)))
|
||||
)";
|
||||
|
||||
pub(crate) async fn load_admin_account_page(
|
||||
pool: &PgPool,
|
||||
budget: &crate::postgres::ObservabilityQueryBudget,
|
||||
@@ -45,29 +86,14 @@ pub(crate) async fn load_admin_account_page(
|
||||
AdminAccountSortField::Usage | AdminAccountSortField::LastUsedAt
|
||||
)
|
||||
});
|
||||
let usage_join = if needs_usage {
|
||||
"left join usage_values usage on usage.provider_account_ref = a.id"
|
||||
let candidates = if needs_usage {
|
||||
"usage_values"
|
||||
} else {
|
||||
""
|
||||
"filtered"
|
||||
};
|
||||
|
||||
let statement = format!(
|
||||
"with usage_values as (select * from unnest($10::text[],$11::bigint[],$12::timestamptz[]) as usage(provider_account_ref,total_tokens,last_used_at)), account_statuses as (
|
||||
select a.id, a.provider_kind,
|
||||
case
|
||||
when not a.enabled then 'disabled'
|
||||
when a.credential_state <> 'ready'
|
||||
or a.access_token_expires_at <= $2 then 'error'
|
||||
when a.quota_access_state = 'exhausted'
|
||||
and (a.quota_exhaustion_deadline is null or a.quota_exhaustion_deadline > $2) then 'quota_exhausted'
|
||||
when a.id = any($1::text[]) or exists (
|
||||
select 1 from unnest($13::text[], $14::bigint[]) as limits(account_id, revision)
|
||||
where limits.account_id = a.id and limits.revision = a.credential_revision
|
||||
) then 'rate_limited'
|
||||
when a.quota_paused then 'quota_paused'
|
||||
else 'normal'
|
||||
end as admin_status
|
||||
from provider_accounts a
|
||||
let page_sql = format!(
|
||||
", usage_values as (
|
||||
select * from unnest($12::text[],$13::bigint[],$14::timestamptz[]) as usage(id,total_tokens,last_used_at)
|
||||
),
|
||||
global_summary as (
|
||||
select count(*)::bigint as summary_total,
|
||||
@@ -82,30 +108,8 @@ pub(crate) async fn load_admin_account_page(
|
||||
count(*) filter (where admin_status = 'error')::bigint as summary_error
|
||||
from account_statuses
|
||||
),
|
||||
filtered as materialized (
|
||||
select status.id, status.admin_status
|
||||
from account_statuses status
|
||||
join provider_accounts a on a.id = status.id
|
||||
where ($3::text is null or a.provider_kind = $3)
|
||||
and ($4::text is null or
|
||||
lower(a.name) like $4 escape '\\' or
|
||||
lower(coalesce(a.email, '')) like $4 escape '\\')
|
||||
and ($5::text is null or status.admin_status = $5)
|
||||
and ($6::smallint = 0 or
|
||||
($6 = 1 and exists (
|
||||
select 1
|
||||
from account_group_accounts membership
|
||||
where membership.provider_account_id = a.id
|
||||
and membership.account_group_id = $7
|
||||
)) or
|
||||
($6 = 2 and not exists (
|
||||
select 1
|
||||
from account_group_accounts membership
|
||||
where membership.provider_account_id = a.id
|
||||
)))
|
||||
),
|
||||
filtered_total as (
|
||||
select count(*)::bigint as filtered_total from filtered
|
||||
select count(*)::bigint as filtered_total from {candidates}
|
||||
),
|
||||
settings as (
|
||||
select config_revision, usage_retention_days, max_concurrent_per_account
|
||||
@@ -130,12 +134,10 @@ pub(crate) async fn load_admin_account_page(
|
||||
left join lateral (
|
||||
select ordered.*, row_number() over ()::bigint as page_position
|
||||
from (
|
||||
select filtered.id, filtered.admin_status
|
||||
from filtered
|
||||
join provider_accounts a on a.id = filtered.id
|
||||
{usage_join}
|
||||
select a.id
|
||||
from {candidates} a
|
||||
order by {order_by}
|
||||
limit $8 offset $9
|
||||
limit $10 offset $11
|
||||
) ordered
|
||||
) page on true
|
||||
left join provider_accounts a on a.id = page.id
|
||||
@@ -153,27 +155,43 @@ pub(crate) async fn load_admin_account_page(
|
||||
&mut connection,
|
||||
)
|
||||
.await?;
|
||||
let directory = |suffix: &str| {
|
||||
sqlx::query(sqlx::AssertSqlSafe(format!("{DIRECTORY_CTES}{suffix}")))
|
||||
.bind(&active_rate_limited_ids)
|
||||
.bind(now)
|
||||
.bind(&provider_kind)
|
||||
.bind(&search_pattern)
|
||||
.bind(&status)
|
||||
.bind(group_mode)
|
||||
.bind(&group_id)
|
||||
.bind(&model_account_ids)
|
||||
.bind(&model_revisions)
|
||||
};
|
||||
let (usage_ids, usage_tokens, usage_latest) = if needs_usage {
|
||||
crate::postgres::observability::account_usage_sort_values(&mut snapshot, now)
|
||||
.await?
|
||||
let ids: Vec<String> = directory(" select id from filtered")
|
||||
.try_map(|row| row.try_get("id"))
|
||||
.fetch_all(&mut *snapshot.tx)
|
||||
.await
|
||||
.map_err(|error| {
|
||||
postgres_unavailable("read account usage sort candidates", error)
|
||||
})?;
|
||||
let (tokens, latest) =
|
||||
crate::postgres::observability::account_usage_sort_values(
|
||||
&mut snapshot,
|
||||
now,
|
||||
&ids,
|
||||
)
|
||||
.await?;
|
||||
(ids, tokens, latest)
|
||||
} else {
|
||||
(Vec::new(), Vec::new(), Vec::new())
|
||||
};
|
||||
let rows = sqlx::query(sqlx::AssertSqlSafe(statement))
|
||||
.bind(active_rate_limited_ids)
|
||||
.bind(now)
|
||||
.bind(provider_kind)
|
||||
.bind(search_pattern)
|
||||
.bind(status)
|
||||
.bind(group_mode)
|
||||
.bind(group_id)
|
||||
let rows = directory(&page_sql)
|
||||
.bind(page_size)
|
||||
.bind(offset)
|
||||
.bind(usage_ids)
|
||||
.bind(usage_tokens)
|
||||
.bind(usage_latest)
|
||||
.bind(model_account_ids)
|
||||
.bind(model_revisions)
|
||||
.fetch_all(&mut *snapshot.tx)
|
||||
.await
|
||||
.map_err(|source| postgres_unavailable("load admin account page", source))?;
|
||||
@@ -266,11 +284,11 @@ fn admin_account_order(sort: Option<AdminAccountSort>) -> String {
|
||||
"lower(coalesce(nullif(btrim(a.name), ''), nullif(btrim(a.email), ''), a.upstream_account_id, a.id))"
|
||||
}
|
||||
AdminAccountSortField::Status => {
|
||||
"case filtered.admin_status when 'normal' then 0 when 'rate_limited' then 1 when 'quota_exhausted' then 2 when 'quota_paused' then 3 when 'error' then 4 else 5 end"
|
||||
"case a.admin_status when 'normal' then 0 when 'rate_limited' then 1 when 'quota_exhausted' then 2 when 'quota_paused' then 3 when 'error' then 4 else 5 end"
|
||||
}
|
||||
AdminAccountSortField::PlanType => "a.plan_type",
|
||||
AdminAccountSortField::Usage => "usage.total_tokens",
|
||||
AdminAccountSortField::LastUsedAt => "usage.last_used_at",
|
||||
AdminAccountSortField::Usage => "a.total_tokens",
|
||||
AdminAccountSortField::LastUsedAt => "a.last_used_at",
|
||||
AdminAccountSortField::ExpiresAt => "a.access_token_expires_at",
|
||||
};
|
||||
match sort.direction {
|
||||
|
||||
@@ -19,10 +19,10 @@ use gateway_admin::{
|
||||
observability::TimeRange,
|
||||
provider_credentials::{
|
||||
AuthorizationCommit, AuthorizationCredentialCommit, CredentialDetails,
|
||||
CredentialImportCommit, CredentialImportResult, CredentialMutationResult,
|
||||
CredentialRotationCommit, PluginAccountListQuery, PluginAccountPage,
|
||||
PreparedCredentialCreate, PreparedCredentialImport, PreparedCredentialRotationFacts,
|
||||
ProviderDocument, ProviderExportCredentialInput,
|
||||
CredentialExportScope, CredentialImportCommit, CredentialImportResult,
|
||||
CredentialMutationResult, CredentialRotationCommit, PluginAccountListQuery,
|
||||
PluginAccountPage, PreparedCredentialCreate, PreparedCredentialImport,
|
||||
PreparedCredentialRotationFacts, ProviderDocument, ProviderExportCredentialInput,
|
||||
},
|
||||
},
|
||||
ports::store::{AccountStore, AdminStoreError, AdminStoreErrorKind, AdminStoreResult},
|
||||
|
||||
@@ -99,6 +99,22 @@ impl PgProviderAccountRepository {
|
||||
self
|
||||
}
|
||||
|
||||
pub(super) async fn load_export_records(
|
||||
&self,
|
||||
provider_kind: &str,
|
||||
ids: &[String],
|
||||
authentication_kinds: Option<&[&str]>,
|
||||
) -> StoreResult<Vec<ProviderAccountRecord>> {
|
||||
let rows = sqlx::query(ACCOUNT_SELECT_BY_IDS)
|
||||
.bind(ids)
|
||||
.bind(provider_kind)
|
||||
.bind(authentication_kinds)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.map_err(|source| postgres_unavailable("export provider accounts", source))?;
|
||||
rows.into_iter().map(account_record_from_row).collect()
|
||||
}
|
||||
|
||||
pub(super) async fn list_provider_account_summaries(
|
||||
&self,
|
||||
provider_kind: Option<&str>,
|
||||
@@ -453,33 +469,15 @@ impl ProviderAccountAdminRepository for PgProviderAccountRepository {
|
||||
) -> StoreResult<Vec<ProviderAccountRecord>> {
|
||||
scope.validate()?;
|
||||
validate_admin_account_ids(&account_ids)?;
|
||||
let rows = sqlx::query(ACCOUNT_SELECT_BY_IDS)
|
||||
.bind(&account_ids)
|
||||
.bind(&scope.provider_kind)
|
||||
.fetch_all(&self.pool)
|
||||
.await
|
||||
.map_err(|source| postgres_unavailable("export provider accounts", source))?;
|
||||
let records = rows
|
||||
.into_iter()
|
||||
.map(account_record_from_row)
|
||||
.collect::<StoreResult<Vec<_>>>()?;
|
||||
let records = self
|
||||
.load_export_records(&scope.provider_kind, &account_ids, None)
|
||||
.await?;
|
||||
if records.len() != account_ids.len() {
|
||||
return Err(invalid(
|
||||
"one or more exported accounts are missing or outside the Provider scope",
|
||||
));
|
||||
}
|
||||
let by_id = records
|
||||
.into_iter()
|
||||
.map(|record| (record.summary.id.clone(), record))
|
||||
.collect::<std::collections::HashMap<_, _>>();
|
||||
account_ids
|
||||
.into_iter()
|
||||
.map(|id| {
|
||||
by_id.get(&id).cloned().ok_or_else(|| {
|
||||
invalid("one or more exported accounts are missing after loading")
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
Ok(records)
|
||||
}
|
||||
|
||||
async fn import_provider_accounts(
|
||||
|
||||
@@ -353,8 +353,10 @@ pub(crate) const ACCOUNT_SELECT_BY_IDS: &str = "select coalesce(proxy_enabled, t
|
||||
from provider_accounts
|
||||
left join (select id as location_proxy_id, enabled as proxy_enabled, max_websocket_connections, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone from outbound_proxies) proxy_location
|
||||
on outbound_proxy_id = location_proxy_id
|
||||
where id = any($1::text[]) and provider_kind = $2
|
||||
order by id";
|
||||
join unnest($1::text[], $3::text[]) with ordinality as selected(account_id, expected_auth, position)
|
||||
on id = selected.account_id and ($3::text[] is null or authentication_kind = selected.expected_auth)
|
||||
where provider_kind = $2
|
||||
order by selected.position";
|
||||
|
||||
pub(crate) const REFRESH_CANDIDATES_SELECT: &str = "select coalesce(proxy_enabled, true) as outbound_proxy_enabled, coalesce(max_websocket_connections, 0) as outbound_proxy_max_websocket_connections, auto_location, detected_location_json, location_country, location_region, location_city, location_timezone, outbound_proxy_id, outbound_proxy_url, id, provider_kind, name, notes, email, upstream_user_id,
|
||||
upstream_account_id, plan_type, authentication_kind, provider_credentials_json, credential_revision,
|
||||
|
||||
@@ -58,12 +58,14 @@ impl UsageDataStore for PgUsageDataStore {
|
||||
|mut connection| async move {
|
||||
let mut tx = begin(&mut connection).await?;
|
||||
let mut changed_ids = Vec::with_capacity(command.changes.len());
|
||||
let mut events = Vec::with_capacity(command.changes.len());
|
||||
for (change, event) in command.changes {
|
||||
if records::write(&mut tx, &change).await? {
|
||||
changed_ids.push(change.id().to_owned());
|
||||
}
|
||||
audit(&mut tx, event).await?;
|
||||
events.push(super::unversioned_audit_event(event));
|
||||
}
|
||||
audit(&mut tx, &events).await?;
|
||||
tx.commit().await.map_err(db_error)?;
|
||||
Ok(UsageWriteResult { changed_ids })
|
||||
},
|
||||
@@ -91,18 +93,24 @@ impl UsageDataStore for PgUsageDataStore {
|
||||
&self,
|
||||
command: StoredAggregateWrite,
|
||||
) -> UsageDataResult<UsageAggregateWriteResult> {
|
||||
self.budget.run(&self.pool, "write usage aggregates", |mut connection| async move {
|
||||
let mut tx = begin(&mut connection).await?;
|
||||
let mut changed=Vec::with_capacity(command.changes.len());
|
||||
for (change,event) in command.changes {
|
||||
changed.push(aggregates::write(&mut tx,change).await?);
|
||||
audit(&mut tx,event).await?;
|
||||
}
|
||||
// 沿用现有统计发布代次,让读缓存能观察到直接维护的聚合值
|
||||
sqlx::query("update request_analytics_build_state set generation=generation+1,updated_at=clock_timestamp() where singleton").execute(&mut *tx).await.map_err(db_error)?;
|
||||
tx.commit().await.map_err(db_error)?;
|
||||
Ok(UsageAggregateWriteResult { changed })
|
||||
}).await.map_err(public_error)
|
||||
self.budget
|
||||
.run(&self.pool, "write usage aggregates", |mut connection| async move {
|
||||
let mut tx = begin(&mut connection).await?;
|
||||
let mut changed = Vec::with_capacity(command.changes.len());
|
||||
let mut events = Vec::with_capacity(command.changes.len());
|
||||
for (change, event) in command.changes {
|
||||
changed.push(aggregates::write(&mut tx, change).await?);
|
||||
events.push(super::unversioned_audit_event(event));
|
||||
}
|
||||
audit(&mut tx, &events).await?;
|
||||
// 沿用现有统计发布代次,让读缓存能观察到直接维护的聚合值
|
||||
sqlx::query("update request_analytics_build_state set generation=generation+1,updated_at=clock_timestamp() where singleton")
|
||||
.execute(&mut *tx).await.map_err(db_error)?;
|
||||
tx.commit().await.map_err(db_error)?;
|
||||
Ok(UsageAggregateWriteResult { changed })
|
||||
})
|
||||
.await
|
||||
.map_err(public_error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,24 +166,10 @@ fn public_error(error: StoreError) -> UsageDataError {
|
||||
}
|
||||
async fn audit(
|
||||
tx: &mut Transaction<'_, Postgres>,
|
||||
event: gateway_admin::model::auth::AdminAuditEvent,
|
||||
events: &[super::AdminAuditEvent],
|
||||
) -> StoreResult<()> {
|
||||
super::append_admin_audit_event_in_transaction(
|
||||
tx,
|
||||
super::AdminAuditEvent {
|
||||
id: event.id,
|
||||
actor_kind: event.actor_kind.into(),
|
||||
actor_admin_user_id: event.actor_admin_user_id,
|
||||
actor_ref: event.actor_ref,
|
||||
admin_request_id: event.request_id,
|
||||
action: event.action,
|
||||
entity_kind: event.entity_kind,
|
||||
entity_ref: event.entity_ref,
|
||||
config_revision: None,
|
||||
changed_fields: event.changed_fields,
|
||||
created_at: event.occurred_at,
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
for batch in events.chunks(USAGE_DATA_MAX_TARGETS) {
|
||||
super::insert_admin_audit_events(&mut **tx, batch).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -73,8 +73,8 @@ pub(crate) fn push_usage_read_filter(query: &mut QueryBuilder<Postgres>, filter:
|
||||
}
|
||||
if let Some(group) = &filter.routing_group_ref {
|
||||
query
|
||||
.push(" and ")
|
||||
.push(" and mr.routing_group_refs @> array[")
|
||||
.push_bind(group.clone())
|
||||
.push("=any(mr.routing_group_refs)");
|
||||
.push("]::text[]");
|
||||
}
|
||||
}
|
||||
@@ -90,6 +90,10 @@ impl JsonObject {
|
||||
pub fn fields(&self) -> &Map<String, Value> {
|
||||
&self.0
|
||||
}
|
||||
|
||||
pub(crate) fn into_fields(self) -> Map<String, Value> {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for JsonObject {
|
||||
|
||||
@@ -1059,7 +1059,7 @@ async fn successful_replay_recovers_only_the_incomplete_request_that_required_it
|
||||
let affinity_hash = "a".repeat(64);
|
||||
let replay_at = Utc::now() - Duration::seconds(1);
|
||||
for (id, seconds_before_replay, reason) in [
|
||||
("req_rotated", 11, Some("account_rotated")),
|
||||
("req_rotated", 30, Some("account_rotated")),
|
||||
("req_overloaded", 4, None),
|
||||
] {
|
||||
let completed_at = replay_at - Duration::seconds(seconds_before_replay);
|
||||
@@ -1117,8 +1117,9 @@ async fn successful_http_downgrade_should_mark_pending_websocket_failures_recove
|
||||
return;
|
||||
};
|
||||
let affinity_hash = "d".repeat(64);
|
||||
let first_failure_at = Utc::now() - Duration::seconds(8);
|
||||
let second_failure_at = first_failure_at + Duration::seconds(1);
|
||||
let recovery_started_at = Utc::now() - Duration::seconds(4);
|
||||
let first_failure_at = recovery_started_at - Duration::seconds(30);
|
||||
let second_failure_at = recovery_started_at;
|
||||
seed_websocket_transport_failure(
|
||||
&database.pool,
|
||||
"req_websocket_failed_first",
|
||||
@@ -1149,7 +1150,6 @@ async fn successful_http_downgrade_should_mark_pending_websocket_failures_recove
|
||||
.await
|
||||
.expect("mark control failure delivered downstream");
|
||||
|
||||
let recovery_started_at = first_failure_at + Duration::seconds(4);
|
||||
seed_transport_recovery_request(
|
||||
&database.pool,
|
||||
"req_http_fallback_succeeded",
|
||||
@@ -1188,7 +1188,7 @@ async fn successful_http_downgrade_should_mark_pending_websocket_failures_recove
|
||||
let delivered = &recovered[0];
|
||||
assert_eq!(delivered.0, "req_websocket_failed_after_delivery");
|
||||
assert_eq!((&delivered.1, delivered.2, delivered.3), (&None, None, 0));
|
||||
for (row, expected_delay_ms) in recovered[1..].iter().zip([4_000, 3_000]) {
|
||||
for (row, expected_delay_ms) in recovered[1..].iter().zip([30_000, 0]) {
|
||||
assert_eq!(row.1.as_deref(), Some("req_http_fallback_succeeded"));
|
||||
assert!(row.2.is_some());
|
||||
assert_eq!(row.3, 1);
|
||||
@@ -1265,7 +1265,7 @@ async fn websocket_success_or_late_http_success_should_not_hide_transport_failur
|
||||
&database.pool,
|
||||
"req_http_late_success",
|
||||
&late_affinity,
|
||||
failure_at + Duration::seconds(31),
|
||||
failure_at + Duration::seconds(30) + Duration::microseconds(1),
|
||||
)
|
||||
.await;
|
||||
let mut late_recovery = successful_core_finalization("req_http_late_success");
|
||||
@@ -1342,7 +1342,7 @@ async fn failed_or_late_new_chain_should_leave_continuation_failure_unresolved()
|
||||
&database.pool,
|
||||
"req_continuation_retry_late",
|
||||
&affinity_hash,
|
||||
failure_completed_at + Duration::seconds(31),
|
||||
failure_completed_at + Duration::seconds(30) + Duration::microseconds(1),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -919,6 +919,8 @@ async fn state_cas_quota_and_fence_are_independent_from_global_revision() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn migration_promotes_atomically_and_incomplete_staging_cannot_replace_active_state() {
|
||||
use PluginStateMigrationAction::{Delete, Keep, Replace};
|
||||
|
||||
let Some(database) = TestDatabase::create("plugin_state_migration").await else {
|
||||
return;
|
||||
};
|
||||
@@ -945,7 +947,7 @@ async fn migration_promotes_atomically_and_incomplete_staging_cannot_replace_act
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
for (key, value) in [("a", 1), ("b", 2)] {
|
||||
for (key, value) in [("a", 1), ("b", 2), ("c", 3), ("d", 4)] {
|
||||
store
|
||||
.put(
|
||||
&first_owner,
|
||||
@@ -960,7 +962,7 @@ async fn migration_promotes_atomically_and_incomplete_staging_cannot_replace_act
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let second_state = configuration(schema(2, vec![1], 4));
|
||||
let second_state = configuration(schema(2, vec![1], 2));
|
||||
assert!(
|
||||
store
|
||||
.transition_required(&saved.instance.id, &second_state)
|
||||
@@ -977,7 +979,7 @@ async fn migration_promotes_atomically_and_incomplete_staging_cannot_replace_act
|
||||
.await
|
||||
.unwrap();
|
||||
let batch = store
|
||||
.migration_batch(&transition.id, "cache", 64)
|
||||
.migration_batch(&transition.id, "cache", 3)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
@@ -986,25 +988,57 @@ async fn migration_promotes_atomically_and_incomplete_staging_cannot_replace_act
|
||||
.iter()
|
||||
.map(|record| record.key.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
["a", "b"]
|
||||
["a", "b", "c"]
|
||||
);
|
||||
store
|
||||
.apply_migration_batch(ApplyPluginStateMigration {
|
||||
let migration = |cursor: Option<String>, actions: Vec<(&str, PluginStateMigrationAction)>| {
|
||||
ApplyPluginStateMigration {
|
||||
transition_id: transition.id.clone(),
|
||||
namespace: "cache".into(),
|
||||
cursor: batch.cursor,
|
||||
expected_keys: vec!["a".into(), "b".into()],
|
||||
changes: vec![
|
||||
PluginStateMigrationChange {
|
||||
key: "a".into(),
|
||||
action: PluginStateMigrationAction::Keep,
|
||||
},
|
||||
PluginStateMigrationChange {
|
||||
key: "b".into(),
|
||||
action: PluginStateMigrationAction::Replace(json!({"value": 20})),
|
||||
},
|
||||
cursor,
|
||||
expected_keys: actions.iter().map(|(key, _)| (*key).to_owned()).collect(),
|
||||
changes: actions
|
||||
.into_iter()
|
||||
.map(|(key, action)| PluginStateMigrationChange {
|
||||
key: key.to_owned(),
|
||||
action,
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
};
|
||||
for (actions, expected_error) in [
|
||||
(
|
||||
vec![("a", Keep), ("a", Keep)],
|
||||
PluginStateStoreErrorKind::Invalid,
|
||||
),
|
||||
(
|
||||
vec![("a", Keep), ("b", Keep), ("c", Keep)],
|
||||
PluginStateStoreErrorKind::Quota,
|
||||
),
|
||||
] {
|
||||
let error = store
|
||||
.apply_migration_batch(migration(batch.cursor.clone(), actions))
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.kind(), expected_error);
|
||||
}
|
||||
store
|
||||
.apply_migration_batch(migration(
|
||||
batch.cursor,
|
||||
vec![
|
||||
("a", Keep),
|
||||
("b", Delete),
|
||||
("c", Replace(json!({"value": 20}))),
|
||||
],
|
||||
})
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
let remaining = store
|
||||
.migration_batch(&transition.id, "cache", 64)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(remaining.cursor.as_deref(), Some("c"));
|
||||
store
|
||||
.apply_migration_batch(migration(remaining.cursor, vec![("d", Delete)]))
|
||||
.await
|
||||
.unwrap();
|
||||
let terminal = store
|
||||
@@ -1012,14 +1046,9 @@ async fn migration_promotes_atomically_and_incomplete_staging_cannot_replace_act
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(terminal.records.is_empty());
|
||||
assert_eq!(terminal.cursor.as_deref(), Some("d"));
|
||||
store
|
||||
.apply_migration_batch(ApplyPluginStateMigration {
|
||||
transition_id: transition.id.clone(),
|
||||
namespace: "cache".into(),
|
||||
cursor: terminal.cursor,
|
||||
expected_keys: vec![],
|
||||
changes: vec![],
|
||||
})
|
||||
.apply_migration_batch(migration(terminal.cursor, vec![]))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
@@ -1049,11 +1078,27 @@ async fn migration_promotes_atomically_and_incomplete_staging_cannot_replace_act
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let migrated = store
|
||||
.get(&second_owner, "cache", "b")
|
||||
let kept = store
|
||||
.get(&second_owner, "cache", "a")
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!((kept.version, kept.value), (1, json!({"value": 1})));
|
||||
for key in ["b", "d"] {
|
||||
assert!(
|
||||
store
|
||||
.get(&second_owner, "cache", key)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
let migrated = store
|
||||
.get(&second_owner, "cache", "c")
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(migrated.version, 2);
|
||||
assert_eq!(migrated.schema_version, 2);
|
||||
assert_eq!(migrated.value, json!({"value": 20}));
|
||||
drop(transition);
|
||||
@@ -1091,7 +1136,7 @@ async fn migration_promotes_atomically_and_incomplete_staging_cannot_replace_act
|
||||
store.abort_transition(&incomplete.id).await.unwrap();
|
||||
assert_eq!(
|
||||
store
|
||||
.get(&second_owner, "cache", "b")
|
||||
.get(&second_owner, "cache", "c")
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
|
||||
@@ -2,6 +2,94 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn credential_export_checks_selected_scopes_and_audits_every_existing_account() {
|
||||
use gateway_admin::ports::store::AdminStoreErrorKind;
|
||||
|
||||
let Some(db) = TestDatabase::create("account_export").await else {
|
||||
return;
|
||||
};
|
||||
let repository = PgProviderAccountRepository::new(db.pool.clone());
|
||||
let store = admin_account_store(&db.pool);
|
||||
let provider = ProviderKind::new("openai").unwrap();
|
||||
let ids = ["acct_b", "acct_a"].map(|id| ProviderAccountId::new(id).unwrap());
|
||||
for id in &ids {
|
||||
repository
|
||||
.insert_provider_account(account(id.as_str(), id.as_str()))
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let scopes = store.credential_export_scopes(&ids).await.unwrap();
|
||||
let selected = ids.clone().map(|id| {
|
||||
let scope = &scopes[id.as_str()];
|
||||
assert_eq!(scope.provider_kind, provider);
|
||||
(id, scope.authentication_kind.clone())
|
||||
});
|
||||
let inputs = store
|
||||
.load_credentials_for_export(&provider, &selected)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
inputs
|
||||
.iter()
|
||||
.map(|input| input.account.id.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
["acct_b", "acct_a"]
|
||||
);
|
||||
|
||||
let mut stale = selected.clone();
|
||||
stale[0].1 = "api_key".to_string();
|
||||
assert_eq!(
|
||||
store
|
||||
.load_credentials_for_export(&provider, &stale)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
AdminStoreErrorKind::NotFound
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.load_credentials_for_export(&ProviderKind::new("other").unwrap(), &selected)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
AdminStoreErrorKind::NotFound
|
||||
);
|
||||
|
||||
let context = MutationContext {
|
||||
actor: MutationActor::System,
|
||||
request_id: "audit_batch_export".into(),
|
||||
};
|
||||
store
|
||||
.record_credential_export(&ids, &context)
|
||||
.await
|
||||
.unwrap();
|
||||
let rows: Vec<(String,i64)> = sqlx::query_as("select entity_ref, config_revision from admin_audit_events where admin_request_id=$1 and action='export_credentials' order by entity_ref")
|
||||
.bind(&context.request_id).fetch_all(&db.pool).await.unwrap();
|
||||
assert_eq!(rows, [("acct_a".into(), 1), ("acct_b".into(), 1)]);
|
||||
|
||||
// Provider 准备好导出文档后账号被删,整批审计失败
|
||||
sqlx::query("delete from provider_accounts where id=$1")
|
||||
.bind(ids[0].as_str())
|
||||
.execute(&db.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let context = MutationContext {
|
||||
request_id: "audit_deleted_export".into(),
|
||||
..context
|
||||
};
|
||||
assert_eq!(
|
||||
store
|
||||
.record_credential_export(&ids, &context)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
AdminStoreErrorKind::NotFound
|
||||
);
|
||||
assert_eq!(audit_count(&db.pool, &context.request_id).await, 0);
|
||||
db.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn quota_deadline_agrees_across_account_filters_summary_and_detail() {
|
||||
let Some(database) = TestDatabase::create("quota_deadline").await else {
|
||||
|
||||
@@ -1172,24 +1172,53 @@ async fn terminal_admin_list_filters_and_sorts_before_pagination_with_retained_u
|
||||
assert_eq!(email_domain_page.items.len(), 2);
|
||||
assert_eq!(email_domain_page.summary, usage_page.summary);
|
||||
|
||||
let error_filter = AccountListQuery {
|
||||
page: 1,
|
||||
page_size: PageSize::new(10).expect("page size"),
|
||||
provider_kind: None,
|
||||
group_filter: None,
|
||||
search: None,
|
||||
status: Some(AccountStatus::Error),
|
||||
sort: None,
|
||||
};
|
||||
let error_accounts = store
|
||||
.list_accounts(
|
||||
AccountListQuery {
|
||||
page: 1,
|
||||
page_size: PageSize::new(10).expect("page size"),
|
||||
provider_kind: None,
|
||||
group_filter: None,
|
||||
search: None,
|
||||
status: Some(AccountStatus::Error),
|
||||
sort: None,
|
||||
},
|
||||
Default::default(),
|
||||
)
|
||||
.list_accounts(error_filter.clone(), Default::default())
|
||||
.await
|
||||
.expect("filter error accounts");
|
||||
assert_eq!(error_accounts.items.len(), 2);
|
||||
assert_eq!(error_accounts.items[0].account.id, "acct_beta");
|
||||
assert_eq!(error_accounts.items[1].account.id, "acct_invalid");
|
||||
|
||||
// 候选账号的导入贡献参与排序,筛选范围外的超额负修正不能干扰本页
|
||||
sqlx::query(
|
||||
"insert into request_analytics_1h
|
||||
(bucket_start,collection,dimensions,outcome,schema_version,histogram_version,counts,costs,distributions)
|
||||
select date_trunc('hour',$1::timestamptz),'usage_contribution',
|
||||
array['openai','',id,'','','','import'],'',0,0,jsonb_build_object('total_tokens',tokens),'{}','{}'
|
||||
from (values ('acct_invalid',80),('acct_disabled',-1)) imported(id,tokens)",
|
||||
)
|
||||
.bind(now - TimeDelta::hours(1))
|
||||
.execute(&database.pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let ranked_errors = store
|
||||
.list_accounts(
|
||||
AccountListQuery {
|
||||
page_size: PageSize::new(1).expect("page size"),
|
||||
sort: Some(AccountSort {
|
||||
field: AccountSortField::Usage,
|
||||
direction: SortDirection::Desc,
|
||||
}),
|
||||
..error_filter
|
||||
},
|
||||
Default::default(),
|
||||
)
|
||||
.await
|
||||
.expect("rank filtered accounts with aggregate contributions");
|
||||
assert_eq!(ranked_errors.total, 2);
|
||||
assert_eq!(ranked_errors.summary, usage_page.summary);
|
||||
assert_eq!(ranked_errors.items.len(), 1);
|
||||
assert_eq!(ranked_errors.items[0].account.id, "acct_invalid");
|
||||
// 上游耗尽优先展示,不重复计入本地额度暂停
|
||||
sqlx::query("update provider_accounts set quota_paused = true where id in ('acct_alpha', 'acct_charlie')")
|
||||
.execute(&database.pool).await.unwrap();
|
||||
|
||||
@@ -124,6 +124,29 @@ async fn detail_crud_is_retry_safe_atomic_and_updates_native_statistics() {
|
||||
.write_records(records(vec![put("a", 10)]))
|
||||
.await
|
||||
.unwrap();
|
||||
// 两次业务写入都成功后,审计主键冲突仍须回滚整批,包括已修改的明细
|
||||
let mut conflict = records(vec![put("a", 99), put("audit-conflict", 35)]);
|
||||
let repeated_id = conflict.changes[0].1.id.clone();
|
||||
conflict.changes[1].1.id.clone_from(&repeated_id);
|
||||
assert!(store.write_records(conflict).await.is_err());
|
||||
assert_eq!(
|
||||
sqlx::query_scalar::<_, i64>("select count(*) from admin_audit_events where id=$1")
|
||||
.bind(repeated_id)
|
||||
.fetch_one(&db.pool)
|
||||
.await
|
||||
.unwrap(),
|
||||
0
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.get_record(GetUsageRecord {
|
||||
id: "audit-conflict".into()
|
||||
})
|
||||
.await
|
||||
.unwrap_err()
|
||||
.kind,
|
||||
UsageErrorKind::NotFound
|
||||
);
|
||||
let first = store
|
||||
.list_records(ListUsageRecords {
|
||||
filter: filter(),
|
||||
|
||||
Reference in new issue
Block a user