mirror of
https://github.com/fawney19/Aether.git
synced 2026-09-02 01:10:23 +08:00
fix(admin-api-keys): 独立余额 Key 统计与时间字段改为直读 api_keys 表 (#319)
- 列表/详情/更新响应中的 `total_requests`、`total_tokens`、`created_at`、`last_used_at` 统一直接读取 `api_keys` 导出记录字段 - 保持“已消费”继续走钱包字段(不改消费口径) - 在 auth 导出记录中补充 `last_used_at_unix_secs`、`created_at_unix_secs`、`updated_at_unix_secs` - 扩展 auth SQL 查询与 RETURNING 字段映射,确保时间字段完整回传 - 移除 admin api-keys 路由中对 usage summary token 聚合的依赖 - 更新 admin api-keys 控制层测试,校验 token/时间字段来源与格式
This commit is contained in:
@@ -29,8 +29,8 @@ use self::mutation_routes::{
|
||||
};
|
||||
use self::read_routes::{build_admin_api_key_detail_response, build_admin_list_api_keys_response};
|
||||
use self::shared::{
|
||||
admin_api_key_total_tokens_by_ids, admin_api_keys_id_from_path, admin_api_keys_operator_id,
|
||||
admin_api_keys_parse_limit, admin_api_keys_parse_skip, build_admin_api_key_detail_payload,
|
||||
admin_api_keys_id_from_path, admin_api_keys_operator_id, admin_api_keys_parse_limit,
|
||||
admin_api_keys_parse_skip, build_admin_api_key_detail_payload,
|
||||
build_admin_api_key_list_item_payload, build_admin_api_keys_bad_request_response,
|
||||
build_admin_api_keys_data_unavailable_response, build_admin_api_keys_not_found_response,
|
||||
AdminStandaloneApiKeyCreateRequest, AdminStandaloneApiKeyToggleRequest,
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
use super::shared::{
|
||||
admin_api_key_total_tokens_by_ids, admin_api_keys_id_from_path, admin_api_keys_operator_id,
|
||||
build_admin_api_key_detail_payload, build_admin_api_keys_bad_request_response,
|
||||
build_admin_api_keys_data_unavailable_response, build_admin_api_keys_not_found_response,
|
||||
AdminStandaloneApiKeyCreateRequest, AdminStandaloneApiKeyToggleRequest,
|
||||
AdminStandaloneApiKeyUpdatePatch,
|
||||
admin_api_keys_id_from_path, admin_api_keys_operator_id, build_admin_api_key_detail_payload,
|
||||
build_admin_api_keys_bad_request_response, build_admin_api_keys_data_unavailable_response,
|
||||
build_admin_api_keys_not_found_response, AdminStandaloneApiKeyCreateRequest,
|
||||
AdminStandaloneApiKeyToggleRequest, AdminStandaloneApiKeyUpdatePatch,
|
||||
};
|
||||
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
use crate::handlers::admin::shared::attach_admin_audit_response;
|
||||
@@ -396,14 +395,7 @@ pub(super) async fn build_admin_update_api_key_response(
|
||||
))
|
||||
.await?;
|
||||
}
|
||||
let total_tokens_by_api_key_id =
|
||||
admin_api_key_total_tokens_by_ids(state, std::slice::from_ref(&api_key_id)).await?;
|
||||
let total_tokens = total_tokens_by_api_key_id
|
||||
.get(&api_key_id)
|
||||
.copied()
|
||||
.unwrap_or(0);
|
||||
let mut payload =
|
||||
build_admin_api_key_detail_payload(state, &updated, total_tokens, wallet.as_ref());
|
||||
let mut payload = build_admin_api_key_detail_payload(state, &updated, wallet.as_ref());
|
||||
payload["message"] = json!("API密钥已更新");
|
||||
Ok(attach_admin_audit_response(
|
||||
Json(payload).into_response(),
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::shared::{
|
||||
admin_api_key_total_tokens_by_ids, admin_api_keys_id_from_path, admin_api_keys_parse_limit,
|
||||
admin_api_keys_parse_skip, build_admin_api_key_detail_payload,
|
||||
build_admin_api_key_list_item_payload, build_admin_api_keys_bad_request_response,
|
||||
build_admin_api_keys_data_unavailable_response, build_admin_api_keys_not_found_response,
|
||||
admin_api_keys_id_from_path, admin_api_keys_parse_limit, admin_api_keys_parse_skip,
|
||||
build_admin_api_key_detail_payload, build_admin_api_key_list_item_payload,
|
||||
build_admin_api_keys_bad_request_response, build_admin_api_keys_data_unavailable_response,
|
||||
build_admin_api_keys_not_found_response,
|
||||
};
|
||||
use super::{decrypt_catalog_secret_with_fallbacks, query_param_bool, query_param_optional_bool};
|
||||
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||
@@ -33,7 +33,6 @@ pub(super) async fn build_admin_list_api_keys_response(
|
||||
Err(detail) => return Ok(build_admin_api_keys_bad_request_response(detail)),
|
||||
};
|
||||
let is_active = query_param_optional_bool(query, "is_active");
|
||||
let include_usage_summary = query_param_bool(query, "include_usage_summary", false);
|
||||
|
||||
let list_query = aether_data::repository::auth::StandaloneApiKeyExportListQuery {
|
||||
skip,
|
||||
@@ -63,13 +62,6 @@ pub(super) async fn build_admin_list_api_keys_response(
|
||||
})
|
||||
.collect::<std::collections::BTreeMap<_, _>>();
|
||||
let wallet_lookup_ms = wallet_lookup_started_at.elapsed().as_millis() as u64;
|
||||
let usage_summary_started_at = Instant::now();
|
||||
let total_tokens_by_api_key_id = if include_usage_summary {
|
||||
Some(admin_api_key_total_tokens_by_ids(state, &api_key_ids).await?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let usage_summary_ms = usage_summary_started_at.elapsed().as_millis() as u64;
|
||||
|
||||
let api_keys = paged_records
|
||||
.iter()
|
||||
@@ -77,9 +69,6 @@ pub(super) async fn build_admin_list_api_keys_response(
|
||||
build_admin_api_key_list_item_payload(
|
||||
state,
|
||||
record,
|
||||
total_tokens_by_api_key_id
|
||||
.as_ref()
|
||||
.and_then(|totals| totals.get(&record.api_key_id).copied()),
|
||||
wallets_by_api_key_id.get(&record.api_key_id),
|
||||
)
|
||||
})
|
||||
@@ -91,10 +80,8 @@ pub(super) async fn build_admin_list_api_keys_response(
|
||||
trace_id = request_context.trace_id.as_str(),
|
||||
returned_items = api_keys.len(),
|
||||
total,
|
||||
include_usage_summary,
|
||||
count_and_page_ms,
|
||||
wallet_lookup_ms,
|
||||
usage_summary_ms,
|
||||
handler_ms = handler_started_at.elapsed().as_millis() as u64,
|
||||
"measured admin api keys list handler timing"
|
||||
);
|
||||
@@ -167,17 +154,10 @@ pub(super) async fn build_admin_api_key_detail_response(
|
||||
.await?
|
||||
.into_iter()
|
||||
.find(|wallet| wallet.api_key_id.as_deref() == Some(api_key_id.as_str()));
|
||||
let total_tokens_by_api_key_id =
|
||||
admin_api_key_total_tokens_by_ids(state, std::slice::from_ref(&api_key_id)).await?;
|
||||
let total_tokens = total_tokens_by_api_key_id
|
||||
.get(&api_key_id)
|
||||
.copied()
|
||||
.unwrap_or(0);
|
||||
|
||||
Ok(Json(build_admin_api_key_detail_payload(
|
||||
state,
|
||||
&record,
|
||||
total_tokens,
|
||||
wallet.as_ref(),
|
||||
))
|
||||
.into_response())
|
||||
|
||||
@@ -3,7 +3,6 @@ use crate::handlers::admin::shared::{query_param_value, AdminTypedObjectPatch};
|
||||
use crate::handlers::admin::users::{
|
||||
format_optional_unix_secs_iso8601, masked_user_api_key_display,
|
||||
};
|
||||
use crate::GatewayError;
|
||||
use aether_admin::system::serialize_admin_system_users_export_wallet;
|
||||
use axum::{
|
||||
body::Body,
|
||||
@@ -132,7 +131,6 @@ fn masked_admin_api_key_display(state: &AdminAppState<'_>, ciphertext: Option<&s
|
||||
pub(super) fn build_admin_api_key_list_item_payload(
|
||||
state: &AdminAppState<'_>,
|
||||
record: &aether_data::repository::auth::StoredAuthApiKeyExportRecord,
|
||||
total_tokens: Option<u64>,
|
||||
wallet: Option<&aether_data::repository::wallet::StoredWalletSnapshot>,
|
||||
) -> serde_json::Value {
|
||||
json!({
|
||||
@@ -143,17 +141,17 @@ pub(super) fn build_admin_api_key_list_item_payload(
|
||||
"is_active": record.is_active,
|
||||
"is_standalone": true,
|
||||
"total_requests": record.total_requests,
|
||||
"total_tokens": total_tokens,
|
||||
"total_tokens": record.total_tokens,
|
||||
"total_cost_usd": record.total_cost_usd,
|
||||
"rate_limit": record.rate_limit,
|
||||
"concurrent_limit": record.concurrent_limit,
|
||||
"allowed_providers": record.allowed_providers,
|
||||
"allowed_api_formats": record.allowed_api_formats,
|
||||
"allowed_models": record.allowed_models,
|
||||
"last_used_at": serde_json::Value::Null,
|
||||
"last_used_at": format_optional_unix_secs_iso8601(record.last_used_at_unix_secs),
|
||||
"expires_at": format_optional_unix_secs_iso8601(record.expires_at_unix_secs),
|
||||
"created_at": serde_json::Value::Null,
|
||||
"updated_at": serde_json::Value::Null,
|
||||
"created_at": format_optional_unix_secs_iso8601(record.created_at_unix_secs),
|
||||
"updated_at": format_optional_unix_secs_iso8601(record.updated_at_unix_secs),
|
||||
"auto_delete_on_expiry": record.auto_delete_on_expiry,
|
||||
"wallet": serialize_admin_system_users_export_wallet(wallet),
|
||||
})
|
||||
@@ -162,7 +160,6 @@ pub(super) fn build_admin_api_key_list_item_payload(
|
||||
pub(super) fn build_admin_api_key_detail_payload(
|
||||
state: &AdminAppState<'_>,
|
||||
record: &aether_data::repository::auth::StoredAuthApiKeyExportRecord,
|
||||
total_tokens: u64,
|
||||
wallet: Option<&aether_data::repository::wallet::StoredWalletSnapshot>,
|
||||
) -> serde_json::Value {
|
||||
json!({
|
||||
@@ -173,31 +170,18 @@ pub(super) fn build_admin_api_key_detail_payload(
|
||||
"is_active": record.is_active,
|
||||
"is_standalone": true,
|
||||
"total_requests": record.total_requests,
|
||||
"total_tokens": total_tokens,
|
||||
"total_tokens": record.total_tokens,
|
||||
"total_cost_usd": record.total_cost_usd,
|
||||
"rate_limit": record.rate_limit,
|
||||
"concurrent_limit": record.concurrent_limit,
|
||||
"allowed_providers": record.allowed_providers,
|
||||
"allowed_api_formats": record.allowed_api_formats,
|
||||
"allowed_models": record.allowed_models,
|
||||
"last_used_at": serde_json::Value::Null,
|
||||
"last_used_at": format_optional_unix_secs_iso8601(record.last_used_at_unix_secs),
|
||||
"expires_at": format_optional_unix_secs_iso8601(record.expires_at_unix_secs),
|
||||
"created_at": serde_json::Value::Null,
|
||||
"updated_at": serde_json::Value::Null,
|
||||
"created_at": format_optional_unix_secs_iso8601(record.created_at_unix_secs),
|
||||
"updated_at": format_optional_unix_secs_iso8601(record.updated_at_unix_secs),
|
||||
"auto_delete_on_expiry": record.auto_delete_on_expiry,
|
||||
"wallet": serialize_admin_system_users_export_wallet(wallet),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) async fn admin_api_key_total_tokens_by_ids(
|
||||
state: &AdminAppState<'_>,
|
||||
api_key_ids: &[String],
|
||||
) -> Result<std::collections::BTreeMap<String, u64>, GatewayError> {
|
||||
if api_key_ids.is_empty() || !state.has_usage_data_reader() {
|
||||
return Ok(std::collections::BTreeMap::new());
|
||||
}
|
||||
|
||||
state
|
||||
.summarize_usage_total_tokens_by_api_key_ids(api_key_ids)
|
||||
.await
|
||||
}
|
||||
|
||||
@@ -85,7 +85,7 @@ fn sample_standalone_export_record(
|
||||
plaintext_key: &str,
|
||||
is_active: bool,
|
||||
) -> StoredAuthApiKeyExportRecord {
|
||||
StoredAuthApiKeyExportRecord::new(
|
||||
let mut record = StoredAuthApiKeyExportRecord::new(
|
||||
user_id.to_string(),
|
||||
api_key_id.to_string(),
|
||||
format!("hash-{api_key_id}"),
|
||||
@@ -108,7 +108,11 @@ fn sample_standalone_export_record(
|
||||
1.25,
|
||||
true,
|
||||
)
|
||||
.expect("export record should build")
|
||||
.expect("export record should build");
|
||||
record.created_at_unix_secs = Some(1_711_000_100);
|
||||
record.updated_at_unix_secs = Some(1_711_000_101);
|
||||
record.last_used_at_unix_secs = Some(1_711_000_102);
|
||||
record
|
||||
}
|
||||
|
||||
fn sample_standalone_wallet(api_key_id: &str) -> StoredWalletSnapshot {
|
||||
@@ -236,9 +240,14 @@ async fn gateway_handles_admin_api_keys_list_locally_with_trusted_admin_principa
|
||||
json!("sk-key-1-p...text")
|
||||
);
|
||||
assert_eq!(payload["api_keys"][0]["total_requests"], json!(7));
|
||||
assert_eq!(payload["api_keys"][0]["total_tokens"], json!(0));
|
||||
assert_eq!(
|
||||
payload["api_keys"][0]["total_tokens"],
|
||||
serde_json::Value::Null
|
||||
payload["api_keys"][0]["created_at"],
|
||||
json!("2024-03-21T05:48:20+00:00")
|
||||
);
|
||||
assert_eq!(
|
||||
payload["api_keys"][0]["last_used_at"],
|
||||
json!("2024-03-21T05:48:22+00:00")
|
||||
);
|
||||
assert_eq!(
|
||||
payload["api_keys"][0]["wallet"]["id"],
|
||||
@@ -255,17 +264,14 @@ async fn gateway_handles_admin_api_keys_list_locally_with_trusted_admin_principa
|
||||
async fn gateway_handles_admin_api_keys_detail_locally_with_trusted_admin_principal() {
|
||||
let (upstream_url, upstream_hits, upstream_handle) =
|
||||
start_api_keys_upstream("/api/admin/api-keys/key-1").await;
|
||||
let mut export = sample_standalone_export_record("key-1", "user-1", "sk-key-1-plaintext", true);
|
||||
export.total_tokens = 77;
|
||||
let auth_repository = Arc::new(
|
||||
InMemoryAuthApiKeySnapshotRepository::seed(vec![(
|
||||
None,
|
||||
sample_standalone_api_key_snapshot("key-1", "user-1", true),
|
||||
)])
|
||||
.with_export_records([sample_standalone_export_record(
|
||||
"key-1",
|
||||
"user-1",
|
||||
"sk-key-1-plaintext",
|
||||
true,
|
||||
)]),
|
||||
.with_export_records([export]),
|
||||
);
|
||||
let wallet_repository = Arc::new(InMemoryWalletRepository::seed(vec![
|
||||
sample_standalone_wallet("key-1"),
|
||||
@@ -302,7 +308,9 @@ async fn gateway_handles_admin_api_keys_detail_locally_with_trusted_admin_princi
|
||||
assert_eq!(payload["wallet"]["unlimited"], json!(true));
|
||||
assert_eq!(payload["wallet"]["balance"], json!(20.0));
|
||||
assert_eq!(payload["key_display"], json!("sk-key-1-p...text"));
|
||||
assert_eq!(payload["total_tokens"], json!(150));
|
||||
assert_eq!(payload["total_tokens"], json!(77));
|
||||
assert_eq!(payload["created_at"], json!("2024-03-21T05:48:20+00:00"));
|
||||
assert_eq!(payload["last_used_at"], json!("2024-03-21T05:48:22+00:00"));
|
||||
assert_eq!(*upstream_hits.lock().expect("mutex should lock"), 0);
|
||||
|
||||
gateway_handle.abort();
|
||||
@@ -313,17 +321,14 @@ async fn gateway_handles_admin_api_keys_detail_locally_with_trusted_admin_princi
|
||||
async fn gateway_includes_usage_summary_when_admin_api_keys_list_requests_it() {
|
||||
let (_upstream_url, _upstream_hits, upstream_handle) =
|
||||
start_api_keys_upstream("/api/admin/api-keys").await;
|
||||
let mut export = sample_standalone_export_record("key-1", "user-1", "sk-key-1-plaintext", true);
|
||||
export.total_tokens = 42;
|
||||
let auth_repository = Arc::new(
|
||||
InMemoryAuthApiKeySnapshotRepository::seed(vec![(
|
||||
None,
|
||||
sample_standalone_api_key_snapshot("key-1", "user-1", true),
|
||||
)])
|
||||
.with_export_records([sample_standalone_export_record(
|
||||
"key-1",
|
||||
"user-1",
|
||||
"sk-key-1-plaintext",
|
||||
true,
|
||||
)]),
|
||||
.with_export_records([export]),
|
||||
);
|
||||
let usage_repository = Arc::new(InMemoryUsageReadRepository::seed(vec![sample_usage_row(
|
||||
"usage-1", "req-1", "key-1", 90,
|
||||
@@ -353,7 +358,7 @@ async fn gateway_includes_usage_summary_when_admin_api_keys_list_requests_it() {
|
||||
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let payload: serde_json::Value = response.json().await.expect("json body should parse");
|
||||
assert_eq!(payload["api_keys"][0]["total_tokens"], json!(90));
|
||||
assert_eq!(payload["api_keys"][0]["total_tokens"], json!(42));
|
||||
|
||||
gateway_handle.abort();
|
||||
upstream_handle.abort();
|
||||
|
||||
Reference in New Issue
Block a user