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::read_routes::{build_admin_api_key_detail_response, build_admin_list_api_keys_response};
|
||||||
use self::shared::{
|
use self::shared::{
|
||||||
admin_api_key_total_tokens_by_ids, admin_api_keys_id_from_path, admin_api_keys_operator_id,
|
admin_api_keys_id_from_path, admin_api_keys_operator_id, admin_api_keys_parse_limit,
|
||||||
admin_api_keys_parse_limit, admin_api_keys_parse_skip, build_admin_api_key_detail_payload,
|
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_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,
|
build_admin_api_keys_data_unavailable_response, build_admin_api_keys_not_found_response,
|
||||||
AdminStandaloneApiKeyCreateRequest, AdminStandaloneApiKeyToggleRequest,
|
AdminStandaloneApiKeyCreateRequest, AdminStandaloneApiKeyToggleRequest,
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
use super::shared::{
|
use super::shared::{
|
||||||
admin_api_key_total_tokens_by_ids, admin_api_keys_id_from_path, admin_api_keys_operator_id,
|
admin_api_keys_id_from_path, admin_api_keys_operator_id, build_admin_api_key_detail_payload,
|
||||||
build_admin_api_key_detail_payload, build_admin_api_keys_bad_request_response,
|
build_admin_api_keys_bad_request_response, build_admin_api_keys_data_unavailable_response,
|
||||||
build_admin_api_keys_data_unavailable_response, build_admin_api_keys_not_found_response,
|
build_admin_api_keys_not_found_response, AdminStandaloneApiKeyCreateRequest,
|
||||||
AdminStandaloneApiKeyCreateRequest, AdminStandaloneApiKeyToggleRequest,
|
AdminStandaloneApiKeyToggleRequest, AdminStandaloneApiKeyUpdatePatch,
|
||||||
AdminStandaloneApiKeyUpdatePatch,
|
|
||||||
};
|
};
|
||||||
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
||||||
use crate::handlers::admin::shared::attach_admin_audit_response;
|
use crate::handlers::admin::shared::attach_admin_audit_response;
|
||||||
@@ -396,14 +395,7 @@ pub(super) async fn build_admin_update_api_key_response(
|
|||||||
))
|
))
|
||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
let total_tokens_by_api_key_id =
|
let mut payload = build_admin_api_key_detail_payload(state, &updated, wallet.as_ref());
|
||||||
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());
|
|
||||||
payload["message"] = json!("API密钥已更新");
|
payload["message"] = json!("API密钥已更新");
|
||||||
Ok(attach_admin_audit_response(
|
Ok(attach_admin_audit_response(
|
||||||
Json(payload).into_response(),
|
Json(payload).into_response(),
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
use super::shared::{
|
use super::shared::{
|
||||||
admin_api_key_total_tokens_by_ids, admin_api_keys_id_from_path, admin_api_keys_parse_limit,
|
admin_api_keys_id_from_path, admin_api_keys_parse_limit, admin_api_keys_parse_skip,
|
||||||
admin_api_keys_parse_skip, build_admin_api_key_detail_payload,
|
build_admin_api_key_detail_payload, build_admin_api_key_list_item_payload,
|
||||||
build_admin_api_key_list_item_payload, build_admin_api_keys_bad_request_response,
|
build_admin_api_keys_bad_request_response, build_admin_api_keys_data_unavailable_response,
|
||||||
build_admin_api_keys_data_unavailable_response, build_admin_api_keys_not_found_response,
|
build_admin_api_keys_not_found_response,
|
||||||
};
|
};
|
||||||
use super::{decrypt_catalog_secret_with_fallbacks, query_param_bool, query_param_optional_bool};
|
use super::{decrypt_catalog_secret_with_fallbacks, query_param_bool, query_param_optional_bool};
|
||||||
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
|
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)),
|
Err(detail) => return Ok(build_admin_api_keys_bad_request_response(detail)),
|
||||||
};
|
};
|
||||||
let is_active = query_param_optional_bool(query, "is_active");
|
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 {
|
let list_query = aether_data::repository::auth::StandaloneApiKeyExportListQuery {
|
||||||
skip,
|
skip,
|
||||||
@@ -63,13 +62,6 @@ pub(super) async fn build_admin_list_api_keys_response(
|
|||||||
})
|
})
|
||||||
.collect::<std::collections::BTreeMap<_, _>>();
|
.collect::<std::collections::BTreeMap<_, _>>();
|
||||||
let wallet_lookup_ms = wallet_lookup_started_at.elapsed().as_millis() as u64;
|
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
|
let api_keys = paged_records
|
||||||
.iter()
|
.iter()
|
||||||
@@ -77,9 +69,6 @@ pub(super) async fn build_admin_list_api_keys_response(
|
|||||||
build_admin_api_key_list_item_payload(
|
build_admin_api_key_list_item_payload(
|
||||||
state,
|
state,
|
||||||
record,
|
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),
|
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(),
|
trace_id = request_context.trace_id.as_str(),
|
||||||
returned_items = api_keys.len(),
|
returned_items = api_keys.len(),
|
||||||
total,
|
total,
|
||||||
include_usage_summary,
|
|
||||||
count_and_page_ms,
|
count_and_page_ms,
|
||||||
wallet_lookup_ms,
|
wallet_lookup_ms,
|
||||||
usage_summary_ms,
|
|
||||||
handler_ms = handler_started_at.elapsed().as_millis() as u64,
|
handler_ms = handler_started_at.elapsed().as_millis() as u64,
|
||||||
"measured admin api keys list handler timing"
|
"measured admin api keys list handler timing"
|
||||||
);
|
);
|
||||||
@@ -167,17 +154,10 @@ pub(super) async fn build_admin_api_key_detail_response(
|
|||||||
.await?
|
.await?
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.find(|wallet| wallet.api_key_id.as_deref() == Some(api_key_id.as_str()));
|
.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(
|
Ok(Json(build_admin_api_key_detail_payload(
|
||||||
state,
|
state,
|
||||||
&record,
|
&record,
|
||||||
total_tokens,
|
|
||||||
wallet.as_ref(),
|
wallet.as_ref(),
|
||||||
))
|
))
|
||||||
.into_response())
|
.into_response())
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ use crate::handlers::admin::shared::{query_param_value, AdminTypedObjectPatch};
|
|||||||
use crate::handlers::admin::users::{
|
use crate::handlers::admin::users::{
|
||||||
format_optional_unix_secs_iso8601, masked_user_api_key_display,
|
format_optional_unix_secs_iso8601, masked_user_api_key_display,
|
||||||
};
|
};
|
||||||
use crate::GatewayError;
|
|
||||||
use aether_admin::system::serialize_admin_system_users_export_wallet;
|
use aether_admin::system::serialize_admin_system_users_export_wallet;
|
||||||
use axum::{
|
use axum::{
|
||||||
body::Body,
|
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(
|
pub(super) fn build_admin_api_key_list_item_payload(
|
||||||
state: &AdminAppState<'_>,
|
state: &AdminAppState<'_>,
|
||||||
record: &aether_data::repository::auth::StoredAuthApiKeyExportRecord,
|
record: &aether_data::repository::auth::StoredAuthApiKeyExportRecord,
|
||||||
total_tokens: Option<u64>,
|
|
||||||
wallet: Option<&aether_data::repository::wallet::StoredWalletSnapshot>,
|
wallet: Option<&aether_data::repository::wallet::StoredWalletSnapshot>,
|
||||||
) -> serde_json::Value {
|
) -> serde_json::Value {
|
||||||
json!({
|
json!({
|
||||||
@@ -143,17 +141,17 @@ pub(super) fn build_admin_api_key_list_item_payload(
|
|||||||
"is_active": record.is_active,
|
"is_active": record.is_active,
|
||||||
"is_standalone": true,
|
"is_standalone": true,
|
||||||
"total_requests": record.total_requests,
|
"total_requests": record.total_requests,
|
||||||
"total_tokens": total_tokens,
|
"total_tokens": record.total_tokens,
|
||||||
"total_cost_usd": record.total_cost_usd,
|
"total_cost_usd": record.total_cost_usd,
|
||||||
"rate_limit": record.rate_limit,
|
"rate_limit": record.rate_limit,
|
||||||
"concurrent_limit": record.concurrent_limit,
|
"concurrent_limit": record.concurrent_limit,
|
||||||
"allowed_providers": record.allowed_providers,
|
"allowed_providers": record.allowed_providers,
|
||||||
"allowed_api_formats": record.allowed_api_formats,
|
"allowed_api_formats": record.allowed_api_formats,
|
||||||
"allowed_models": record.allowed_models,
|
"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),
|
"expires_at": format_optional_unix_secs_iso8601(record.expires_at_unix_secs),
|
||||||
"created_at": serde_json::Value::Null,
|
"created_at": format_optional_unix_secs_iso8601(record.created_at_unix_secs),
|
||||||
"updated_at": serde_json::Value::Null,
|
"updated_at": format_optional_unix_secs_iso8601(record.updated_at_unix_secs),
|
||||||
"auto_delete_on_expiry": record.auto_delete_on_expiry,
|
"auto_delete_on_expiry": record.auto_delete_on_expiry,
|
||||||
"wallet": serialize_admin_system_users_export_wallet(wallet),
|
"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(
|
pub(super) fn build_admin_api_key_detail_payload(
|
||||||
state: &AdminAppState<'_>,
|
state: &AdminAppState<'_>,
|
||||||
record: &aether_data::repository::auth::StoredAuthApiKeyExportRecord,
|
record: &aether_data::repository::auth::StoredAuthApiKeyExportRecord,
|
||||||
total_tokens: u64,
|
|
||||||
wallet: Option<&aether_data::repository::wallet::StoredWalletSnapshot>,
|
wallet: Option<&aether_data::repository::wallet::StoredWalletSnapshot>,
|
||||||
) -> serde_json::Value {
|
) -> serde_json::Value {
|
||||||
json!({
|
json!({
|
||||||
@@ -173,31 +170,18 @@ pub(super) fn build_admin_api_key_detail_payload(
|
|||||||
"is_active": record.is_active,
|
"is_active": record.is_active,
|
||||||
"is_standalone": true,
|
"is_standalone": true,
|
||||||
"total_requests": record.total_requests,
|
"total_requests": record.total_requests,
|
||||||
"total_tokens": total_tokens,
|
"total_tokens": record.total_tokens,
|
||||||
"total_cost_usd": record.total_cost_usd,
|
"total_cost_usd": record.total_cost_usd,
|
||||||
"rate_limit": record.rate_limit,
|
"rate_limit": record.rate_limit,
|
||||||
"concurrent_limit": record.concurrent_limit,
|
"concurrent_limit": record.concurrent_limit,
|
||||||
"allowed_providers": record.allowed_providers,
|
"allowed_providers": record.allowed_providers,
|
||||||
"allowed_api_formats": record.allowed_api_formats,
|
"allowed_api_formats": record.allowed_api_formats,
|
||||||
"allowed_models": record.allowed_models,
|
"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),
|
"expires_at": format_optional_unix_secs_iso8601(record.expires_at_unix_secs),
|
||||||
"created_at": serde_json::Value::Null,
|
"created_at": format_optional_unix_secs_iso8601(record.created_at_unix_secs),
|
||||||
"updated_at": serde_json::Value::Null,
|
"updated_at": format_optional_unix_secs_iso8601(record.updated_at_unix_secs),
|
||||||
"auto_delete_on_expiry": record.auto_delete_on_expiry,
|
"auto_delete_on_expiry": record.auto_delete_on_expiry,
|
||||||
"wallet": serialize_admin_system_users_export_wallet(wallet),
|
"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,
|
plaintext_key: &str,
|
||||||
is_active: bool,
|
is_active: bool,
|
||||||
) -> StoredAuthApiKeyExportRecord {
|
) -> StoredAuthApiKeyExportRecord {
|
||||||
StoredAuthApiKeyExportRecord::new(
|
let mut record = StoredAuthApiKeyExportRecord::new(
|
||||||
user_id.to_string(),
|
user_id.to_string(),
|
||||||
api_key_id.to_string(),
|
api_key_id.to_string(),
|
||||||
format!("hash-{api_key_id}"),
|
format!("hash-{api_key_id}"),
|
||||||
@@ -108,7 +108,11 @@ fn sample_standalone_export_record(
|
|||||||
1.25,
|
1.25,
|
||||||
true,
|
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 {
|
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")
|
json!("sk-key-1-p...text")
|
||||||
);
|
);
|
||||||
assert_eq!(payload["api_keys"][0]["total_requests"], json!(7));
|
assert_eq!(payload["api_keys"][0]["total_requests"], json!(7));
|
||||||
|
assert_eq!(payload["api_keys"][0]["total_tokens"], json!(0));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
payload["api_keys"][0]["total_tokens"],
|
payload["api_keys"][0]["created_at"],
|
||||||
serde_json::Value::Null
|
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!(
|
assert_eq!(
|
||||||
payload["api_keys"][0]["wallet"]["id"],
|
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() {
|
async fn gateway_handles_admin_api_keys_detail_locally_with_trusted_admin_principal() {
|
||||||
let (upstream_url, upstream_hits, upstream_handle) =
|
let (upstream_url, upstream_hits, upstream_handle) =
|
||||||
start_api_keys_upstream("/api/admin/api-keys/key-1").await;
|
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(
|
let auth_repository = Arc::new(
|
||||||
InMemoryAuthApiKeySnapshotRepository::seed(vec![(
|
InMemoryAuthApiKeySnapshotRepository::seed(vec![(
|
||||||
None,
|
None,
|
||||||
sample_standalone_api_key_snapshot("key-1", "user-1", true),
|
sample_standalone_api_key_snapshot("key-1", "user-1", true),
|
||||||
)])
|
)])
|
||||||
.with_export_records([sample_standalone_export_record(
|
.with_export_records([export]),
|
||||||
"key-1",
|
|
||||||
"user-1",
|
|
||||||
"sk-key-1-plaintext",
|
|
||||||
true,
|
|
||||||
)]),
|
|
||||||
);
|
);
|
||||||
let wallet_repository = Arc::new(InMemoryWalletRepository::seed(vec![
|
let wallet_repository = Arc::new(InMemoryWalletRepository::seed(vec![
|
||||||
sample_standalone_wallet("key-1"),
|
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"]["unlimited"], json!(true));
|
||||||
assert_eq!(payload["wallet"]["balance"], json!(20.0));
|
assert_eq!(payload["wallet"]["balance"], json!(20.0));
|
||||||
assert_eq!(payload["key_display"], json!("sk-key-1-p...text"));
|
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);
|
assert_eq!(*upstream_hits.lock().expect("mutex should lock"), 0);
|
||||||
|
|
||||||
gateway_handle.abort();
|
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() {
|
async fn gateway_includes_usage_summary_when_admin_api_keys_list_requests_it() {
|
||||||
let (_upstream_url, _upstream_hits, upstream_handle) =
|
let (_upstream_url, _upstream_hits, upstream_handle) =
|
||||||
start_api_keys_upstream("/api/admin/api-keys").await;
|
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(
|
let auth_repository = Arc::new(
|
||||||
InMemoryAuthApiKeySnapshotRepository::seed(vec![(
|
InMemoryAuthApiKeySnapshotRepository::seed(vec![(
|
||||||
None,
|
None,
|
||||||
sample_standalone_api_key_snapshot("key-1", "user-1", true),
|
sample_standalone_api_key_snapshot("key-1", "user-1", true),
|
||||||
)])
|
)])
|
||||||
.with_export_records([sample_standalone_export_record(
|
.with_export_records([export]),
|
||||||
"key-1",
|
|
||||||
"user-1",
|
|
||||||
"sk-key-1-plaintext",
|
|
||||||
true,
|
|
||||||
)]),
|
|
||||||
);
|
);
|
||||||
let usage_repository = Arc::new(InMemoryUsageReadRepository::seed(vec![sample_usage_row(
|
let usage_repository = Arc::new(InMemoryUsageReadRepository::seed(vec![sample_usage_row(
|
||||||
"usage-1", "req-1", "key-1", 90,
|
"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);
|
assert_eq!(response.status(), StatusCode::OK);
|
||||||
let payload: serde_json::Value = response.json().await.expect("json body should parse");
|
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();
|
gateway_handle.abort();
|
||||||
upstream_handle.abort();
|
upstream_handle.abort();
|
||||||
|
|||||||
@@ -152,6 +152,9 @@ SELECT
|
|||||||
api_keys.total_requests,
|
api_keys.total_requests,
|
||||||
COALESCE(api_keys.total_tokens, 0)::BIGINT AS total_tokens,
|
COALESCE(api_keys.total_tokens, 0)::BIGINT AS total_tokens,
|
||||||
COALESCE(CAST(api_keys.total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
COALESCE(CAST(api_keys.total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
||||||
|
CAST(EXTRACT(EPOCH FROM api_keys.last_used_at) AS BIGINT) AS last_used_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM api_keys.created_at) AS BIGINT) AS created_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM api_keys.updated_at) AS BIGINT) AS updated_at_unix_secs,
|
||||||
api_keys.is_standalone
|
api_keys.is_standalone
|
||||||
FROM api_keys
|
FROM api_keys
|
||||||
WHERE api_keys.user_id = ANY($1::TEXT[])
|
WHERE api_keys.user_id = ANY($1::TEXT[])
|
||||||
@@ -178,6 +181,9 @@ SELECT
|
|||||||
api_keys.total_requests,
|
api_keys.total_requests,
|
||||||
COALESCE(api_keys.total_tokens, 0)::BIGINT AS total_tokens,
|
COALESCE(api_keys.total_tokens, 0)::BIGINT AS total_tokens,
|
||||||
COALESCE(CAST(api_keys.total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
COALESCE(CAST(api_keys.total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
||||||
|
CAST(EXTRACT(EPOCH FROM api_keys.last_used_at) AS BIGINT) AS last_used_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM api_keys.created_at) AS BIGINT) AS created_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM api_keys.updated_at) AS BIGINT) AS updated_at_unix_secs,
|
||||||
api_keys.is_standalone
|
api_keys.is_standalone
|
||||||
FROM api_keys
|
FROM api_keys
|
||||||
WHERE api_keys.id = ANY($1::TEXT[])
|
WHERE api_keys.id = ANY($1::TEXT[])
|
||||||
@@ -203,6 +209,9 @@ SELECT
|
|||||||
api_keys.total_requests,
|
api_keys.total_requests,
|
||||||
COALESCE(api_keys.total_tokens, 0)::BIGINT AS total_tokens,
|
COALESCE(api_keys.total_tokens, 0)::BIGINT AS total_tokens,
|
||||||
COALESCE(CAST(api_keys.total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
COALESCE(CAST(api_keys.total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
||||||
|
CAST(EXTRACT(EPOCH FROM api_keys.last_used_at) AS BIGINT) AS last_used_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM api_keys.created_at) AS BIGINT) AS created_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM api_keys.updated_at) AS BIGINT) AS updated_at_unix_secs,
|
||||||
api_keys.is_standalone
|
api_keys.is_standalone
|
||||||
FROM api_keys
|
FROM api_keys
|
||||||
WHERE LOWER(COALESCE(api_keys.name, '')) LIKE $1
|
WHERE LOWER(COALESCE(api_keys.name, '')) LIKE $1
|
||||||
@@ -228,6 +237,9 @@ SELECT
|
|||||||
api_keys.total_requests,
|
api_keys.total_requests,
|
||||||
COALESCE(api_keys.total_tokens, 0)::BIGINT AS total_tokens,
|
COALESCE(api_keys.total_tokens, 0)::BIGINT AS total_tokens,
|
||||||
COALESCE(CAST(api_keys.total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
COALESCE(CAST(api_keys.total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
||||||
|
CAST(EXTRACT(EPOCH FROM api_keys.last_used_at) AS BIGINT) AS last_used_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM api_keys.created_at) AS BIGINT) AS created_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM api_keys.updated_at) AS BIGINT) AS updated_at_unix_secs,
|
||||||
api_keys.is_standalone
|
api_keys.is_standalone
|
||||||
FROM api_keys
|
FROM api_keys
|
||||||
WHERE api_keys.is_standalone = TRUE
|
WHERE api_keys.is_standalone = TRUE
|
||||||
@@ -253,6 +265,9 @@ SELECT
|
|||||||
api_keys.total_requests,
|
api_keys.total_requests,
|
||||||
COALESCE(api_keys.total_tokens, 0)::BIGINT AS total_tokens,
|
COALESCE(api_keys.total_tokens, 0)::BIGINT AS total_tokens,
|
||||||
COALESCE(CAST(api_keys.total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
COALESCE(CAST(api_keys.total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
||||||
|
CAST(EXTRACT(EPOCH FROM api_keys.last_used_at) AS BIGINT) AS last_used_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM api_keys.created_at) AS BIGINT) AS created_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM api_keys.updated_at) AS BIGINT) AS updated_at_unix_secs,
|
||||||
api_keys.is_standalone
|
api_keys.is_standalone
|
||||||
FROM api_keys
|
FROM api_keys
|
||||||
WHERE api_keys.is_standalone = TRUE
|
WHERE api_keys.is_standalone = TRUE
|
||||||
@@ -322,6 +337,9 @@ SELECT
|
|||||||
api_keys.total_requests,
|
api_keys.total_requests,
|
||||||
COALESCE(api_keys.total_tokens, 0)::BIGINT AS total_tokens,
|
COALESCE(api_keys.total_tokens, 0)::BIGINT AS total_tokens,
|
||||||
COALESCE(CAST(api_keys.total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
COALESCE(CAST(api_keys.total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
||||||
|
CAST(EXTRACT(EPOCH FROM api_keys.last_used_at) AS BIGINT) AS last_used_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM api_keys.created_at) AS BIGINT) AS created_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM api_keys.updated_at) AS BIGINT) AS updated_at_unix_secs,
|
||||||
api_keys.is_standalone
|
api_keys.is_standalone
|
||||||
FROM api_keys
|
FROM api_keys
|
||||||
WHERE api_keys.is_standalone = TRUE
|
WHERE api_keys.is_standalone = TRUE
|
||||||
@@ -400,6 +418,9 @@ RETURNING
|
|||||||
total_requests,
|
total_requests,
|
||||||
COALESCE(total_tokens, 0)::BIGINT AS total_tokens,
|
COALESCE(total_tokens, 0)::BIGINT AS total_tokens,
|
||||||
COALESCE(CAST(total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
COALESCE(CAST(total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
||||||
|
CAST(EXTRACT(EPOCH FROM last_used_at) AS BIGINT) AS last_used_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM created_at) AS BIGINT) AS created_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM updated_at) AS BIGINT) AS updated_at_unix_secs,
|
||||||
is_standalone
|
is_standalone
|
||||||
"#;
|
"#;
|
||||||
|
|
||||||
@@ -468,6 +489,9 @@ RETURNING
|
|||||||
total_requests,
|
total_requests,
|
||||||
COALESCE(total_tokens, 0)::BIGINT AS total_tokens,
|
COALESCE(total_tokens, 0)::BIGINT AS total_tokens,
|
||||||
COALESCE(CAST(total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
COALESCE(CAST(total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
||||||
|
CAST(EXTRACT(EPOCH FROM last_used_at) AS BIGINT) AS last_used_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM created_at) AS BIGINT) AS created_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM updated_at) AS BIGINT) AS updated_at_unix_secs,
|
||||||
is_standalone
|
is_standalone
|
||||||
"#;
|
"#;
|
||||||
|
|
||||||
@@ -499,6 +523,9 @@ RETURNING
|
|||||||
total_requests,
|
total_requests,
|
||||||
COALESCE(total_tokens, 0)::BIGINT AS total_tokens,
|
COALESCE(total_tokens, 0)::BIGINT AS total_tokens,
|
||||||
COALESCE(CAST(total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
COALESCE(CAST(total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
||||||
|
CAST(EXTRACT(EPOCH FROM last_used_at) AS BIGINT) AS last_used_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM created_at) AS BIGINT) AS created_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM updated_at) AS BIGINT) AS updated_at_unix_secs,
|
||||||
is_standalone
|
is_standalone
|
||||||
"#;
|
"#;
|
||||||
|
|
||||||
@@ -534,6 +561,9 @@ RETURNING
|
|||||||
total_requests,
|
total_requests,
|
||||||
COALESCE(total_tokens, 0)::BIGINT AS total_tokens,
|
COALESCE(total_tokens, 0)::BIGINT AS total_tokens,
|
||||||
COALESCE(CAST(total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
COALESCE(CAST(total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
||||||
|
CAST(EXTRACT(EPOCH FROM last_used_at) AS BIGINT) AS last_used_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM created_at) AS BIGINT) AS created_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM updated_at) AS BIGINT) AS updated_at_unix_secs,
|
||||||
is_standalone
|
is_standalone
|
||||||
"#;
|
"#;
|
||||||
|
|
||||||
@@ -563,6 +593,9 @@ RETURNING
|
|||||||
total_requests,
|
total_requests,
|
||||||
COALESCE(total_tokens, 0)::BIGINT AS total_tokens,
|
COALESCE(total_tokens, 0)::BIGINT AS total_tokens,
|
||||||
COALESCE(CAST(total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
COALESCE(CAST(total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
||||||
|
CAST(EXTRACT(EPOCH FROM last_used_at) AS BIGINT) AS last_used_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM created_at) AS BIGINT) AS created_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM updated_at) AS BIGINT) AS updated_at_unix_secs,
|
||||||
is_standalone
|
is_standalone
|
||||||
"#;
|
"#;
|
||||||
|
|
||||||
@@ -591,6 +624,9 @@ RETURNING
|
|||||||
total_requests,
|
total_requests,
|
||||||
COALESCE(total_tokens, 0)::BIGINT AS total_tokens,
|
COALESCE(total_tokens, 0)::BIGINT AS total_tokens,
|
||||||
COALESCE(CAST(total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
COALESCE(CAST(total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
||||||
|
CAST(EXTRACT(EPOCH FROM last_used_at) AS BIGINT) AS last_used_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM created_at) AS BIGINT) AS created_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM updated_at) AS BIGINT) AS updated_at_unix_secs,
|
||||||
is_standalone
|
is_standalone
|
||||||
"#;
|
"#;
|
||||||
|
|
||||||
@@ -630,6 +666,9 @@ RETURNING
|
|||||||
total_requests,
|
total_requests,
|
||||||
COALESCE(total_tokens, 0)::BIGINT AS total_tokens,
|
COALESCE(total_tokens, 0)::BIGINT AS total_tokens,
|
||||||
COALESCE(CAST(total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
COALESCE(CAST(total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
||||||
|
CAST(EXTRACT(EPOCH FROM last_used_at) AS BIGINT) AS last_used_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM created_at) AS BIGINT) AS created_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM updated_at) AS BIGINT) AS updated_at_unix_secs,
|
||||||
is_standalone
|
is_standalone
|
||||||
"#;
|
"#;
|
||||||
|
|
||||||
@@ -659,6 +698,9 @@ RETURNING
|
|||||||
total_requests,
|
total_requests,
|
||||||
COALESCE(total_tokens, 0)::BIGINT AS total_tokens,
|
COALESCE(total_tokens, 0)::BIGINT AS total_tokens,
|
||||||
COALESCE(CAST(total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
COALESCE(CAST(total_cost_usd AS DOUBLE PRECISION), 0) AS total_cost_usd,
|
||||||
|
CAST(EXTRACT(EPOCH FROM last_used_at) AS BIGINT) AS last_used_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM created_at) AS BIGINT) AS created_at_unix_secs,
|
||||||
|
CAST(EXTRACT(EPOCH FROM updated_at) AS BIGINT) AS updated_at_unix_secs,
|
||||||
is_standalone
|
is_standalone
|
||||||
"#;
|
"#;
|
||||||
|
|
||||||
@@ -1397,6 +1439,13 @@ fn map_auth_api_key_export_row(
|
|||||||
row_get(row, "total_cost_usd")?,
|
row_get(row, "total_cost_usd")?,
|
||||||
row_get(row, "is_standalone")?,
|
row_get(row, "is_standalone")?,
|
||||||
)
|
)
|
||||||
|
.and_then(|record| {
|
||||||
|
record.with_activity_timestamps(
|
||||||
|
row_get(row, "last_used_at_unix_secs")?,
|
||||||
|
row_get(row, "created_at_unix_secs")?,
|
||||||
|
row_get(row, "updated_at_unix_secs")?,
|
||||||
|
)
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@@ -268,6 +268,9 @@ pub struct StoredAuthApiKeyExportRecord {
|
|||||||
pub total_requests: u64,
|
pub total_requests: u64,
|
||||||
pub total_tokens: u64,
|
pub total_tokens: u64,
|
||||||
pub total_cost_usd: f64,
|
pub total_cost_usd: f64,
|
||||||
|
pub last_used_at_unix_secs: Option<u64>,
|
||||||
|
pub created_at_unix_secs: Option<u64>,
|
||||||
|
pub updated_at_unix_secs: Option<u64>,
|
||||||
pub is_standalone: bool,
|
pub is_standalone: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -337,9 +340,30 @@ impl StoredAuthApiKeyExportRecord {
|
|||||||
total_requests: parse_u64_i64(total_requests, "api_keys.total_requests")?,
|
total_requests: parse_u64_i64(total_requests, "api_keys.total_requests")?,
|
||||||
total_tokens: parse_u64_i64(total_tokens, "api_keys.total_tokens")?,
|
total_tokens: parse_u64_i64(total_tokens, "api_keys.total_tokens")?,
|
||||||
total_cost_usd,
|
total_cost_usd,
|
||||||
|
last_used_at_unix_secs: None,
|
||||||
|
created_at_unix_secs: None,
|
||||||
|
updated_at_unix_secs: None,
|
||||||
is_standalone,
|
is_standalone,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn with_activity_timestamps(
|
||||||
|
mut self,
|
||||||
|
last_used_at_unix_secs: Option<i64>,
|
||||||
|
created_at_unix_secs: Option<i64>,
|
||||||
|
updated_at_unix_secs: Option<i64>,
|
||||||
|
) -> Result<Self, crate::DataLayerError> {
|
||||||
|
self.last_used_at_unix_secs = last_used_at_unix_secs
|
||||||
|
.map(|value| parse_u64_i64(value, "api_keys.last_used_at_unix_secs"))
|
||||||
|
.transpose()?;
|
||||||
|
self.created_at_unix_secs = created_at_unix_secs
|
||||||
|
.map(|value| parse_u64_i64(value, "api_keys.created_at_unix_secs"))
|
||||||
|
.transpose()?;
|
||||||
|
self.updated_at_unix_secs = updated_at_unix_secs
|
||||||
|
.map(|value| parse_u64_i64(value, "api_keys.updated_at_unix_secs"))
|
||||||
|
.transpose()?;
|
||||||
|
Ok(self)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
|
||||||
|
|||||||
Reference in New Issue
Block a user