refactor: 大规模模块拆分与重组,新增 aether-admin crate

- 新建独立 aether-admin crate 承载 admin 相关共享契约与纯辅助函数
- 拆分 ai_pipeline 下 kiro/private_envelope/conversion/planner 等大文件为子模块目录
- 重组 admin handlers 各业务域(billing/oauth/provider/system/users 等)为目录结构,移除 shared.rs/builders.rs 等反模式
- 移除 ai_pipeline runtime adapters 旧实现(claude/openai/gemini/kiro/vertex/antigravity 等),改由 provider transport 统一承载
- 移除 control_facade/execution_facade/auth_snapshot_facade 等冗余 facade 层
- 拆分 query/billing 与 query/monitoring 模块、state/runtime/payments 与 security 模块
- 扩展架构测试覆盖 admin_billing/admin_model/admin_users 等新模块
- 删除 docs/architecture/refactor-execution-plan.md 已完成的执行计划文档
This commit is contained in:
fawney19
2026-04-09 00:10:38 +08:00
parent 4fb9882b54
commit 4fc95adfb9
663 changed files with 48471 additions and 40232 deletions

View File

@@ -0,0 +1,13 @@
use crate::handlers::admin::request::{AdminRouteRequest, AdminRouteResult};
use crate::handlers::public;
pub(crate) async fn maybe_build_local_admin_announcements_response(
request: AdminRouteRequest<'_>,
) -> AdminRouteResult {
public::maybe_build_local_admin_announcements_response(
request.state().app(),
&request.request_context(),
request.request_body(),
)
.await
}

View File

@@ -4,13 +4,12 @@ use super::super::users::{
normalize_admin_optional_api_key_name, normalize_admin_user_api_formats,
normalize_admin_user_string_list,
};
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::{
decrypt_catalog_secret_with_fallbacks, encrypt_catalog_secret_with_fallbacks, query_param_bool,
query_param_optional_bool, query_param_value,
};
use crate::handlers::admin::system::shared::configs::serialize_admin_system_users_export_wallet;
use crate::{AppState, GatewayError};
use crate::GatewayError;
use axum::{
body::Body,
http,
@@ -19,8 +18,6 @@ use axum::{
};
use serde_json::json;
const ADMIN_API_KEYS_DATA_UNAVAILABLE_DETAIL: &str = "Admin standalone API key data unavailable";
mod mutation_routes;
mod read_routes;
mod routes;
@@ -41,8 +38,8 @@ use self::shared::{
};
pub(crate) async fn maybe_build_local_admin_api_keys_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&axum::body::Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
routes::maybe_build_local_admin_api_keys_routes_response(state, request_context, request_body)

View File

@@ -5,15 +5,15 @@ use super::shared::{
AdminStandaloneApiKeyCreateRequest, AdminStandaloneApiKeyFieldPresence,
AdminStandaloneApiKeyToggleRequest, AdminStandaloneApiKeyUpdateRequest,
};
use super::{
default_admin_user_api_key_name, encrypt_catalog_secret_with_fallbacks,
format_optional_unix_secs_iso8601, generate_admin_user_api_key_plaintext,
hash_admin_user_api_key, masked_user_api_key_display, normalize_admin_optional_api_key_name,
normalize_admin_user_api_formats, normalize_admin_user_string_list,
};
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::attach_admin_audit_response;
use crate::{AppState, GatewayError};
use crate::handlers::admin::users::{
default_admin_user_api_key_name, format_optional_unix_secs_iso8601,
generate_admin_user_api_key_plaintext, hash_admin_user_api_key, masked_user_api_key_display,
normalize_admin_optional_api_key_name, normalize_admin_user_api_formats,
normalize_admin_user_string_list,
};
use crate::GatewayError;
use axum::{
body::Body,
http,
@@ -23,11 +23,11 @@ use axum::{
use serde_json::json;
pub(super) async fn build_admin_create_api_key_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&axum::body::Bytes>,
) -> Result<Response<Body>, GatewayError> {
if !state.data.has_auth_api_key_writer() {
if !state.has_auth_api_key_writer() {
return Ok(build_admin_api_keys_data_unavailable_response());
}
@@ -44,7 +44,7 @@ pub(super) async fn build_admin_create_api_key_response(
Err(_) => {
return Ok(build_admin_api_keys_bad_request_response(
"请求数据验证失败",
))
));
}
};
if payload.initial_balance_usd.is_some()
@@ -85,7 +85,7 @@ pub(super) async fn build_admin_create_api_key_response(
}
let plaintext_key = generate_admin_user_api_key_plaintext();
let Some(key_encrypted) = encrypt_catalog_secret_with_fallbacks(state, &plaintext_key) else {
let Some(key_encrypted) = state.encrypt_catalog_secret_with_fallbacks(&plaintext_key) else {
return Ok((
http::StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({ "detail": "API密钥加密失败" })),
@@ -138,15 +138,15 @@ pub(super) async fn build_admin_create_api_key_response(
}
pub(super) async fn build_admin_update_api_key_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&axum::body::Bytes>,
) -> Result<Response<Body>, GatewayError> {
if !state.data.has_auth_api_key_writer() {
if !state.has_auth_api_key_writer() {
return Ok(build_admin_api_keys_data_unavailable_response());
}
let Some(api_key_id) = admin_api_keys_id_from_path(&request_context.request_path) else {
let Some(api_key_id) = admin_api_keys_id_from_path(request_context.path()) else {
return Ok(build_admin_api_keys_data_unavailable_response());
};
let Some(request_body) = request_body else {
@@ -159,7 +159,7 @@ pub(super) async fn build_admin_update_api_key_response(
_ => {
return Ok(build_admin_api_keys_bad_request_response(
"请求数据验证失败",
))
));
}
};
let field_presence = AdminStandaloneApiKeyFieldPresence {
@@ -174,7 +174,7 @@ pub(super) async fn build_admin_update_api_key_response(
Err(_) => {
return Ok(build_admin_api_keys_bad_request_response(
"请求数据验证失败",
))
));
}
};
if payload.initial_balance_usd.is_some()
@@ -262,15 +262,15 @@ pub(super) async fn build_admin_update_api_key_response(
}
pub(super) async fn build_admin_toggle_api_key_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&axum::body::Bytes>,
) -> Result<Response<Body>, GatewayError> {
if !state.data.has_auth_api_key_writer() {
if !state.has_auth_api_key_writer() {
return Ok(build_admin_api_keys_data_unavailable_response());
}
let Some(api_key_id) = admin_api_keys_id_from_path(&request_context.request_path) else {
let Some(api_key_id) = admin_api_keys_id_from_path(request_context.path()) else {
return Ok(build_admin_api_keys_data_unavailable_response());
};
@@ -283,17 +283,15 @@ pub(super) async fn build_admin_toggle_api_key_response(
Err(_) => {
return Ok(build_admin_api_keys_bad_request_response(
"请求数据验证失败",
))
));
}
}
}
};
let Some(snapshot) = state
.data
.list_auth_api_key_snapshots_by_ids(std::slice::from_ref(&api_key_id))
.await
.map_err(|err| GatewayError::Internal(err.to_string()))?
.await?
.into_iter()
.find(|snapshot| snapshot.api_key_id == api_key_id)
else {
@@ -326,14 +324,14 @@ pub(super) async fn build_admin_toggle_api_key_response(
}
pub(super) async fn build_admin_delete_api_key_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
if !state.data.has_auth_api_key_writer() {
if !state.has_auth_api_key_writer() {
return Ok(build_admin_api_keys_data_unavailable_response());
}
let Some(api_key_id) = admin_api_keys_id_from_path(&request_context.request_path) else {
let Some(api_key_id) = admin_api_keys_id_from_path(request_context.path()) else {
return Ok(build_admin_api_keys_data_unavailable_response());
};

View File

@@ -5,9 +5,9 @@ use super::shared::{
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::control::GatewayPublicRequestContext;
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::attach_admin_audit_response;
use crate::{AppState, GatewayError};
use crate::GatewayError;
use axum::{
body::Body,
http,
@@ -19,11 +19,11 @@ use std::time::Instant;
use tracing::info;
pub(super) async fn build_admin_list_api_keys_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
let handler_started_at = Instant::now();
let query = request_context.request_query_string.as_deref();
let query = request_context.query_string();
let skip = match admin_api_keys_parse_skip(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_api_keys_bad_request_response(detail)),
@@ -109,18 +109,16 @@ pub(super) async fn build_admin_list_api_keys_response(
}
pub(super) async fn build_admin_api_key_detail_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
let Some(api_key_id) = admin_api_keys_id_from_path(&request_context.request_path) else {
let Some(api_key_id) = admin_api_keys_id_from_path(request_context.path()) else {
return Ok(build_admin_api_keys_data_unavailable_response());
};
if state
.data
.list_auth_api_key_snapshots_by_ids(std::slice::from_ref(&api_key_id))
.await
.map_err(|err| GatewayError::Internal(err.to_string()))?
.await?
.into_iter()
.any(|snapshot| snapshot.api_key_id == api_key_id && !snapshot.api_key_is_standalone)
{
@@ -136,11 +134,7 @@ pub(super) async fn build_admin_api_key_detail_response(
return Ok(build_admin_api_keys_not_found_response());
};
if query_param_bool(
request_context.request_query_string.as_deref(),
"include_key",
false,
) {
if query_param_bool(request_context.query_string(), "include_key", false) {
let Some(ciphertext) = record
.key_encrypted
.as_deref()

View File

@@ -4,16 +4,16 @@ use super::mutation_routes::{
};
use super::read_routes::{build_admin_api_key_detail_response, build_admin_list_api_keys_response};
use super::shared::build_admin_api_keys_data_unavailable_response;
use crate::control::GatewayPublicRequestContext;
use crate::{AppState, GatewayError};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::GatewayError;
use axum::{body::Body, http, response::Response};
pub(super) async fn maybe_build_local_admin_api_keys_routes_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&axum::body::Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
let Some(decision) = request_context.control_decision.as_ref() else {
let Some(decision) = request_context.decision() else {
return Ok(None);
};
@@ -21,7 +21,7 @@ pub(super) async fn maybe_build_local_admin_api_keys_routes_response(
return Ok(None);
}
let path = request_context.request_path.as_str();
let path = request_context.path();
let is_api_keys_route = matches!(path, "/api/admin/api-keys" | "/api/admin/api-keys/")
|| (path.starts_with("/api/admin/api-keys/") && path.matches('/').count() == 4);
@@ -31,7 +31,7 @@ pub(super) async fn maybe_build_local_admin_api_keys_routes_response(
match decision.route_kind.as_deref() {
Some("list_api_keys")
if request_context.request_method == http::Method::GET
if request_context.method() == http::Method::GET
&& matches!(path, "/api/admin/api-keys" | "/api/admin/api-keys/") =>
{
Ok(Some(
@@ -39,7 +39,7 @@ pub(super) async fn maybe_build_local_admin_api_keys_routes_response(
))
}
Some("api_key_detail")
if request_context.request_method == http::Method::GET
if request_context.method() == http::Method::GET
&& path.starts_with("/api/admin/api-keys/") =>
{
Ok(Some(
@@ -47,7 +47,7 @@ pub(super) async fn maybe_build_local_admin_api_keys_routes_response(
))
}
Some("create_api_key")
if request_context.request_method == http::Method::POST
if request_context.method() == http::Method::POST
&& matches!(path, "/api/admin/api-keys" | "/api/admin/api-keys/") =>
{
Ok(Some(
@@ -55,7 +55,7 @@ pub(super) async fn maybe_build_local_admin_api_keys_routes_response(
))
}
Some("update_api_key")
if request_context.request_method == http::Method::PUT
if request_context.method() == http::Method::PUT
&& path.starts_with("/api/admin/api-keys/") =>
{
Ok(Some(
@@ -63,7 +63,7 @@ pub(super) async fn maybe_build_local_admin_api_keys_routes_response(
))
}
Some("toggle_api_key")
if request_context.request_method == http::Method::PATCH
if request_context.method() == http::Method::PATCH
&& path.starts_with("/api/admin/api-keys/") =>
{
Ok(Some(
@@ -71,7 +71,7 @@ pub(super) async fn maybe_build_local_admin_api_keys_routes_response(
))
}
Some("delete_api_key")
if request_context.request_method == http::Method::DELETE
if request_context.method() == http::Method::DELETE
&& path.starts_with("/api/admin/api-keys/") =>
{
Ok(Some(

View File

@@ -1,9 +1,19 @@
use super::ADMIN_API_KEYS_DATA_UNAVAILABLE_DETAIL;
use super::{
format_optional_unix_secs_iso8601, http, json, masked_user_api_key_display, query_param_value,
serialize_admin_system_users_export_wallet, AppState, Body, GatewayError,
GatewayPublicRequestContext, IntoResponse, Json, Response,
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::query_param_value;
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,
http,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
const ADMIN_API_KEYS_DATA_UNAVAILABLE_DETAIL: &str = "Admin standalone API key data unavailable";
#[derive(Debug, Default, serde::Deserialize)]
pub(super) struct AdminStandaloneApiKeyCreateRequest {
@@ -85,11 +95,10 @@ pub(super) fn admin_api_keys_id_from_path(request_path: &str) -> Option<String>
}
pub(super) fn admin_api_keys_operator_id(
request_context: &GatewayPublicRequestContext,
request_context: &AdminRequestContext<'_>,
) -> Option<String> {
request_context
.control_decision
.as_ref()
.decision()
.and_then(|decision| decision.admin_principal.as_ref())
.map(|principal| principal.user_id.clone())
}
@@ -118,8 +127,12 @@ pub(super) fn admin_api_keys_parse_limit(query: Option<&str>) -> Result<usize, S
}
}
fn masked_admin_api_key_display(state: &AdminAppState<'_>, ciphertext: Option<&str>) -> String {
masked_user_api_key_display(state, ciphertext)
}
pub(super) fn build_admin_api_key_list_item_payload(
state: &AppState,
state: &AdminAppState<'_>,
record: &aether_data::repository::auth::StoredAuthApiKeyExportRecord,
total_tokens: Option<u64>,
wallet: Option<&aether_data::repository::wallet::StoredWalletSnapshot>,
@@ -128,7 +141,7 @@ pub(super) fn build_admin_api_key_list_item_payload(
"id": record.api_key_id,
"user_id": record.user_id,
"name": record.name,
"key_display": masked_user_api_key_display(state, record.key_encrypted.as_deref()),
"key_display": masked_admin_api_key_display(state, record.key_encrypted.as_deref()),
"is_active": record.is_active,
"is_standalone": true,
"total_requests": record.total_requests,
@@ -148,7 +161,7 @@ pub(super) fn build_admin_api_key_list_item_payload(
}
pub(super) fn build_admin_api_key_detail_payload(
state: &AppState,
state: &AdminAppState<'_>,
record: &aether_data::repository::auth::StoredAuthApiKeyExportRecord,
total_tokens: u64,
wallet: Option<&aether_data::repository::wallet::StoredWalletSnapshot>,
@@ -157,7 +170,7 @@ pub(super) fn build_admin_api_key_detail_payload(
"id": record.api_key_id,
"user_id": record.user_id,
"name": record.name,
"key_display": masked_user_api_key_display(state, record.key_encrypted.as_deref()),
"key_display": masked_admin_api_key_display(state, record.key_encrypted.as_deref()),
"is_active": record.is_active,
"is_standalone": true,
"total_requests": record.total_requests,
@@ -176,7 +189,7 @@ pub(super) fn build_admin_api_key_detail_payload(
}
pub(super) async fn admin_api_key_total_tokens_by_ids(
state: &AppState,
state: &AdminAppState<'_>,
api_key_ids: &[String],
) -> Result<std::collections::BTreeMap<String, u64>, GatewayError> {
if api_key_ids.is_empty() || !state.has_usage_data_reader() {

View File

@@ -1,8 +1,6 @@
use super::shared::*;
use crate::handlers::admin::shared::{
decrypt_catalog_secret_with_fallbacks, encrypt_catalog_secret_with_fallbacks,
};
use crate::{AppState, GatewayError};
use crate::handlers::admin::request::AdminAppState;
use crate::GatewayError;
use serde::Deserialize;
#[derive(Debug, Deserialize)]
@@ -69,7 +67,7 @@ pub(super) struct AdminLdapConnectionTestConfig {
}
pub(super) async fn build_admin_ldap_update_config(
state: &AppState,
state: &AdminAppState<'_>,
payload: AdminLdapConfigUpdateRequest,
) -> Result<aether_data::repository::auth_modules::StoredLdapModuleConfig, String> {
let server_url = admin_ldap_trim_required(payload.server_url, "LDAP 服务器地址不能为空")?;
@@ -139,7 +137,7 @@ pub(super) async fn build_admin_ldap_update_config(
let bind_password_encrypted = match bind_password {
Some(value) if value.is_empty() => None,
Some(value) => encrypt_catalog_secret_with_fallbacks(state, &value),
Some(value) => state.encrypt_catalog_secret_with_fallbacks(&value),
None => existing.and_then(|config| config.bind_password_encrypted),
};
if bind_password_update_requested && bind_password_encrypted.is_none() {
@@ -165,7 +163,7 @@ pub(super) async fn build_admin_ldap_update_config(
}
pub(super) async fn build_admin_ldap_test_config(
state: &AppState,
state: &AdminAppState<'_>,
payload: AdminLdapConfigTestRequest,
) -> Result<Option<AdminLdapConnectionTestConfig>, String> {
if let Some(value) = payload.user_search_filter.as_deref() {
@@ -337,7 +335,7 @@ fn admin_ldap_validate_search_filter(value: &str) -> Result<(), String> {
}
fn admin_ldap_read_saved_bind_password(
state: &AppState,
state: &AdminAppState<'_>,
config: &aether_data::repository::auth_modules::StoredLdapModuleConfig,
) -> Option<String> {
config
@@ -346,7 +344,8 @@ fn admin_ldap_read_saved_bind_password(
.map(str::trim)
.filter(|value| !value.is_empty())
.and_then(|value| {
decrypt_catalog_secret_with_fallbacks(state.encryption_key(), value)
state
.decrypt_catalog_secret_with_fallbacks(value)
.or_else(|| Some(value.to_string()))
})
.filter(|value| !value.trim().is_empty())

View File

@@ -1,5 +1,5 @@
use crate::control::GatewayPublicRequestContext;
use crate::{AppState, GatewayError};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::GatewayError;
use axum::{
body::{Body, Bytes},
response::Response,
@@ -10,8 +10,8 @@ mod routes;
mod shared;
pub(crate) async fn maybe_build_local_admin_ldap_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
routes::maybe_build_local_admin_ldap_response(state, request_context, request_body).await

View File

@@ -3,9 +3,9 @@ use super::builders::{
AdminLdapConfigTestRequest, AdminLdapConfigUpdateRequest,
};
use super::shared::*;
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::attach_admin_audit_response;
use crate::{AppState, GatewayError};
use crate::GatewayError;
use axum::{
body::{Body, Bytes},
http,
@@ -15,11 +15,11 @@ use axum::{
use serde_json::json;
pub(super) async fn maybe_build_local_admin_ldap_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
let Some(decision) = request_context.control_decision.as_ref() else {
let Some(decision) = request_context.decision() else {
return Ok(None);
};
if decision.route_family.as_deref() != Some("ldap_manage") {
@@ -28,8 +28,8 @@ pub(super) async fn maybe_build_local_admin_ldap_response(
match decision.route_kind.as_deref() {
Some("get_config")
if request_context.request_method == http::Method::GET
&& is_admin_ldap_config_root(&request_context.request_path) =>
if request_context.method() == http::Method::GET
&& is_admin_ldap_config_root(request_context.path()) =>
{
return Ok(Some(attach_admin_audit_response(
Json(build_admin_ldap_config_payload(
@@ -43,8 +43,8 @@ pub(super) async fn maybe_build_local_admin_ldap_response(
)));
}
Some("set_config")
if request_context.request_method == http::Method::PUT
&& is_admin_ldap_config_root(&request_context.request_path) =>
if request_context.method() == http::Method::PUT
&& is_admin_ldap_config_root(request_context.path()) =>
{
if !state.has_auth_module_writer() {
return Ok(Some(admin_ldap_unavailable_response()));
@@ -70,8 +70,8 @@ pub(super) async fn maybe_build_local_admin_ldap_response(
));
}
Some("test_connection")
if request_context.request_method == http::Method::POST
&& is_admin_ldap_test_root(&request_context.request_path) =>
if request_context.method() == http::Method::POST
&& is_admin_ldap_test_root(request_context.path()) =>
{
let payload = match request_body {
Some(body) if !body.is_empty() => match serde_json::from_slice::<

View File

@@ -2,13 +2,11 @@ mod api_keys;
mod ldap;
mod oauth_config;
mod oauth_routes;
mod routes;
mod security;
pub(crate) use self::api_keys::maybe_build_local_admin_api_keys_response;
pub(crate) use self::ldap::maybe_build_local_admin_ldap_response;
pub(crate) use self::oauth_config::{
build_admin_oauth_provider_payload, build_admin_oauth_supported_types_payload,
build_admin_oauth_upsert_record,
};
pub(crate) use self::oauth_routes::maybe_build_local_admin_oauth_response;
pub(super) use self::api_keys::maybe_build_local_admin_api_keys_response;
pub(super) use self::ldap::maybe_build_local_admin_ldap_response;
pub(super) use self::oauth_routes::maybe_build_local_admin_oauth_response;
pub(super) use self::routes::maybe_build_local_admin_auth_response;
pub(crate) use self::security::maybe_build_local_admin_security_response;

View File

@@ -1,5 +1,4 @@
use crate::handlers::admin::shared::encrypt_catalog_secret_with_fallbacks;
use crate::AppState;
use crate::handlers::admin::request::AdminAppState;
use aether_data::repository::oauth_providers::{
EncryptedSecretUpdate, UpsertOAuthProviderConfigRecord,
};
@@ -10,31 +9,31 @@ use url::Url;
#[derive(Debug, Deserialize)]
pub(crate) struct AdminOAuthProviderUpsertRequest {
pub(crate) display_name: String,
pub(crate) client_id: String,
pub(super) display_name: String,
pub(super) client_id: String,
#[serde(default)]
pub(crate) client_secret: Option<String>,
pub(super) client_secret: Option<String>,
#[serde(default)]
pub(crate) authorization_url_override: Option<String>,
pub(super) authorization_url_override: Option<String>,
#[serde(default)]
pub(crate) token_url_override: Option<String>,
pub(super) token_url_override: Option<String>,
#[serde(default)]
pub(crate) userinfo_url_override: Option<String>,
pub(super) userinfo_url_override: Option<String>,
#[serde(default)]
pub(crate) scopes: Option<Vec<String>>,
pub(crate) redirect_uri: String,
pub(crate) frontend_callback_url: String,
pub(super) scopes: Option<Vec<String>>,
pub(super) redirect_uri: String,
pub(super) frontend_callback_url: String,
#[serde(default)]
pub(crate) attribute_mapping: Option<serde_json::Value>,
pub(super) attribute_mapping: Option<serde_json::Value>,
#[serde(default)]
pub(crate) extra_config: Option<serde_json::Value>,
pub(super) extra_config: Option<serde_json::Value>,
#[serde(default)]
pub(crate) is_enabled: bool,
pub(super) is_enabled: bool,
#[serde(default)]
pub(crate) force: bool,
pub(super) force: bool,
}
pub(crate) fn build_admin_oauth_supported_types_payload() -> Vec<serde_json::Value> {
pub(super) fn build_admin_oauth_supported_types_payload() -> Vec<serde_json::Value> {
vec![json!({
"provider_type": "linuxdo",
"display_name": "Linux Do",
@@ -45,7 +44,7 @@ pub(crate) fn build_admin_oauth_supported_types_payload() -> Vec<serde_json::Val
})]
}
pub(crate) fn build_admin_oauth_provider_payload(
pub(super) fn build_admin_oauth_provider_payload(
provider: &aether_data::repository::oauth_providers::StoredOAuthProviderConfig,
) -> serde_json::Value {
json!({
@@ -135,8 +134,8 @@ fn validate_admin_oauth_url_override(url: &str, allowed_domains: &[&str]) -> Res
Ok(())
}
pub(crate) fn build_admin_oauth_upsert_record(
state: &AppState,
pub(super) fn build_admin_oauth_upsert_record(
state: &AdminAppState<'_>,
provider_type: &str,
payload: AdminOAuthProviderUpsertRequest,
) -> Result<UpsertOAuthProviderConfigRecord, String> {
@@ -213,7 +212,8 @@ pub(crate) fn build_admin_oauth_upsert_record(
} else if secret.is_empty() {
EncryptedSecretUpdate::Preserve
} else {
let encrypted = encrypt_catalog_secret_with_fallbacks(state, secret)
let encrypted = state
.encrypt_catalog_secret_with_fallbacks(secret)
.ok_or_else(|| "gateway 未配置 OAuth provider 加密密钥".to_string())?;
EncryptedSecretUpdate::Set(encrypted)
}

View File

@@ -3,9 +3,9 @@ use super::oauth_config::{
build_admin_oauth_provider_payload, build_admin_oauth_supported_types_payload,
build_admin_oauth_upsert_record, AdminOAuthProviderUpsertRequest,
};
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::{attach_admin_audit_response, build_proxy_error_response};
use crate::{AppState, GatewayError};
use crate::GatewayError;
use axum::{
body::{Body, Bytes},
http,
@@ -15,11 +15,11 @@ use axum::{
use serde_json::json;
pub(crate) async fn maybe_build_local_admin_oauth_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
let Some(decision) = request_context.control_decision.as_ref() else {
let Some(decision) = request_context.decision() else {
return Ok(None);
};
if decision.route_family.as_deref() != Some("oauth_manage") {
@@ -27,8 +27,8 @@ pub(crate) async fn maybe_build_local_admin_oauth_response(
}
if decision.route_kind.as_deref() == Some("supported_types")
&& request_context.request_method == http::Method::GET
&& request_context.request_path == "/api/admin/oauth/supported-types"
&& request_context.method() == http::Method::GET
&& request_context.path() == "/api/admin/oauth/supported-types"
{
return Ok(Some(
Json(build_admin_oauth_supported_types_payload()).into_response(),
@@ -36,9 +36,9 @@ pub(crate) async fn maybe_build_local_admin_oauth_response(
}
if decision.route_kind.as_deref() == Some("list_providers")
&& request_context.request_method == http::Method::GET
&& request_context.method() == http::Method::GET
&& matches!(
request_context.request_path.as_str(),
request_context.path(),
"/api/admin/oauth/providers" | "/api/admin/oauth/providers/"
)
{
@@ -59,10 +59,9 @@ pub(crate) async fn maybe_build_local_admin_oauth_response(
}
if decision.route_kind.as_deref() == Some("get_provider")
&& request_context.request_method == http::Method::GET
&& request_context.method() == http::Method::GET
{
let Some(provider_type) =
admin_oauth_provider_type_from_path(&request_context.request_path)
let Some(provider_type) = admin_oauth_provider_type_from_path(request_context.path())
else {
return Ok(Some(
(
@@ -91,10 +90,9 @@ pub(crate) async fn maybe_build_local_admin_oauth_response(
}
if decision.route_kind.as_deref() == Some("upsert_provider")
&& request_context.request_method == http::Method::PUT
&& request_context.method() == http::Method::PUT
{
let Some(provider_type) =
admin_oauth_provider_type_from_path(&request_context.request_path)
let Some(provider_type) = admin_oauth_provider_type_from_path(request_context.path())
else {
return Ok(Some(build_proxy_error_response(
http::StatusCode::BAD_REQUEST,
@@ -172,10 +170,9 @@ pub(crate) async fn maybe_build_local_admin_oauth_response(
}
if decision.route_kind.as_deref() == Some("delete_provider")
&& request_context.request_method == http::Method::DELETE
&& request_context.method() == http::Method::DELETE
{
let Some(provider_type) =
admin_oauth_provider_type_from_path(&request_context.request_path)
let Some(provider_type) = admin_oauth_provider_type_from_path(request_context.path())
else {
return Ok(Some(build_proxy_error_response(
http::StatusCode::BAD_REQUEST,
@@ -229,10 +226,9 @@ pub(crate) async fn maybe_build_local_admin_oauth_response(
}
if decision.route_kind.as_deref() == Some("test_provider")
&& request_context.request_method == http::Method::POST
&& request_context.method() == http::Method::POST
{
let Some(provider_type) =
admin_oauth_test_provider_type_from_path(&request_context.request_path)
let Some(provider_type) = admin_oauth_test_provider_type_from_path(request_context.path())
else {
return Ok(Some(
(

View File

@@ -0,0 +1,48 @@
use super::{api_keys, ldap, oauth_routes, security};
use crate::handlers::admin::request::{AdminRouteRequest, AdminRouteResult};
pub(crate) async fn maybe_build_local_admin_auth_response(
request: AdminRouteRequest<'_>,
) -> AdminRouteResult {
if let Some(response) = security::maybe_build_local_admin_security_response(
&request.state(),
&request.request_context(),
request.request_body(),
)
.await?
{
return Ok(Some(response));
}
if let Some(response) = api_keys::maybe_build_local_admin_api_keys_response(
&request.state(),
&request.request_context(),
request.request_body(),
)
.await?
{
return Ok(Some(response));
}
if let Some(response) = ldap::maybe_build_local_admin_ldap_response(
&request.state(),
&request.request_context(),
request.request_body(),
)
.await?
{
return Ok(Some(response));
}
if let Some(response) = oauth_routes::maybe_build_local_admin_oauth_response(
&request.state(),
&request.request_context(),
request.request_body(),
)
.await?
{
return Ok(Some(response));
}
Ok(None)
}

View File

@@ -1,6 +1,6 @@
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::attach_admin_audit_response;
use crate::{AppState, GatewayError};
use crate::GatewayError;
use axum::{
body::{Body, Bytes},
http,
@@ -98,7 +98,7 @@ fn admin_security_validate_ip_or_cidr(value: &str) -> bool {
}
async fn build_admin_security_blacklist_add_response(
state: &AppState,
state: &AdminAppState<'_>,
request_body: Option<&Bytes>,
) -> Result<Response<Body>, GatewayError> {
let Some(request_body) = request_body else {
@@ -113,7 +113,7 @@ async fn build_admin_security_blacklist_add_response(
_ => {
return Ok(build_admin_security_bad_request_response(
"请求数据验证失败",
))
));
}
};
@@ -148,11 +148,10 @@ async fn build_admin_security_blacklist_add_response(
}
async fn build_admin_security_blacklist_remove_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
let Some(ip_address) = admin_security_blacklist_ip_from_path(&request_context.request_path)
else {
let Some(ip_address) = admin_security_blacklist_ip_from_path(request_context.path()) else {
return Ok(build_admin_security_bad_request_response("缺少 ip_address"));
};
@@ -176,7 +175,7 @@ async fn build_admin_security_blacklist_remove_response(
}
async fn build_admin_security_blacklist_stats_response(
state: &AppState,
state: &AdminAppState<'_>,
) -> Result<Response<Body>, GatewayError> {
let (available, total, error) = state.admin_security_blacklist_stats().await?;
let mut payload = json!({
@@ -196,7 +195,7 @@ async fn build_admin_security_blacklist_stats_response(
}
async fn build_admin_security_blacklist_list_response(
state: &AppState,
state: &AdminAppState<'_>,
) -> Result<Response<Body>, GatewayError> {
let entries = state.list_admin_security_blacklist().await?;
let total = entries.len();
@@ -210,7 +209,7 @@ async fn build_admin_security_blacklist_list_response(
}
async fn build_admin_security_whitelist_add_response(
state: &AppState,
state: &AdminAppState<'_>,
request_body: Option<&Bytes>,
) -> Result<Response<Body>, GatewayError> {
let Some(request_body) = request_body else {
@@ -223,7 +222,7 @@ async fn build_admin_security_whitelist_add_response(
Err(_) => {
return Ok(build_admin_security_bad_request_response(
"请求数据验证失败",
))
));
}
};
let ip_address = payload.ip_address.trim();
@@ -249,11 +248,10 @@ async fn build_admin_security_whitelist_add_response(
}
async fn build_admin_security_whitelist_remove_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
let Some(ip_address) = admin_security_whitelist_ip_from_path(&request_context.request_path)
else {
let Some(ip_address) = admin_security_whitelist_ip_from_path(request_context.path()) else {
return Ok(build_admin_security_bad_request_response("缺少 ip_address"));
};
@@ -277,7 +275,7 @@ async fn build_admin_security_whitelist_remove_response(
}
async fn build_admin_security_whitelist_list_response(
state: &AppState,
state: &AdminAppState<'_>,
) -> Result<Response<Body>, GatewayError> {
let whitelist = state.list_admin_security_whitelist().await?;
let total = whitelist.len();
@@ -295,11 +293,11 @@ async fn build_admin_security_whitelist_list_response(
}
pub(crate) async fn maybe_build_local_admin_security_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
let Some(decision) = request_context.control_decision.as_ref() else {
let Some(decision) = request_context.decision() else {
return Ok(None);
};

View File

@@ -1,392 +0,0 @@
use super::{
admin_billing_optional_bool_filter, admin_billing_optional_filter, admin_billing_pages,
admin_billing_parse_page, admin_billing_parse_page_size,
admin_billing_validate_safe_expression, build_admin_billing_bad_request_response,
build_admin_billing_not_found_response, build_admin_billing_read_only_response,
default_admin_billing_true, normalize_admin_billing_optional_text,
normalize_admin_billing_required_text,
};
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::shared::unix_secs_to_rfc3339;
use crate::{AppState, GatewayError};
use axum::{
body::{Body, Bytes},
http,
response::{IntoResponse, Response},
Json,
};
use serde::Deserialize;
use serde_json::json;
fn default_admin_billing_collector_value_type() -> String {
"float".to_string()
}
#[derive(Debug, Deserialize)]
struct AdminBillingCollectorUpsertRequest {
api_format: String,
task_type: String,
dimension_name: String,
source_type: String,
#[serde(default)]
source_path: Option<String>,
#[serde(default = "default_admin_billing_collector_value_type")]
value_type: String,
#[serde(default)]
transform_expression: Option<String>,
#[serde(default)]
default_value: Option<String>,
#[serde(default)]
priority: i32,
#[serde(default = "default_admin_billing_true")]
is_enabled: bool,
}
fn build_admin_billing_collector_payload_from_record(
record: &crate::AdminBillingCollectorRecord,
) -> serde_json::Value {
json!({
"id": record.id,
"api_format": record.api_format,
"task_type": record.task_type,
"dimension_name": record.dimension_name,
"source_type": record.source_type,
"source_path": record.source_path,
"value_type": record.value_type,
"transform_expression": record.transform_expression,
"default_value": record.default_value,
"priority": record.priority,
"is_enabled": record.is_enabled,
"created_at": unix_secs_to_rfc3339(record.created_at_unix_secs),
"updated_at": unix_secs_to_rfc3339(record.updated_at_unix_secs),
})
}
fn admin_billing_collector_id_from_path(request_path: &str) -> Option<String> {
let value = request_path
.strip_prefix("/api/admin/billing/collectors/")?
.trim()
.trim_matches('/')
.to_string();
if value.is_empty() || value.contains('/') {
None
} else {
Some(value)
}
}
async fn build_admin_list_dimension_collectors_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
) -> Result<Response<Body>, GatewayError> {
let query = request_context.request_query_string.as_deref();
let page = match admin_billing_parse_page(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_billing_bad_request_response(detail)),
};
let page_size = match admin_billing_parse_page_size(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_billing_bad_request_response(detail)),
};
let api_format = admin_billing_optional_filter(query, "api_format");
let task_type = admin_billing_optional_filter(query, "task_type");
let dimension_name = admin_billing_optional_filter(query, "dimension_name");
let is_enabled = match admin_billing_optional_bool_filter(query, "is_enabled") {
Ok(value) => value,
Err(detail) => return Ok(build_admin_billing_bad_request_response(detail)),
};
let (items, total) = state
.list_admin_billing_collectors(
api_format.as_deref(),
task_type.as_deref(),
dimension_name.as_deref(),
is_enabled,
page,
page_size,
)
.await?
.unwrap_or_default();
Ok(Json(json!({
"items": items
.iter()
.map(build_admin_billing_collector_payload_from_record)
.collect::<Vec<_>>(),
"total": total,
"page": page,
"page_size": page_size,
"pages": admin_billing_pages(total, page_size),
}))
.into_response())
}
async fn build_admin_get_dimension_collector_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
) -> Result<Response<Body>, GatewayError> {
let Some(collector_id) = admin_billing_collector_id_from_path(&request_context.request_path)
else {
return Ok(build_admin_billing_bad_request_response(
"缺少 collector_id",
));
};
match state.read_admin_billing_collector(&collector_id).await? {
Some(record) => {
Ok(Json(build_admin_billing_collector_payload_from_record(&record)).into_response())
}
None => Ok(build_admin_billing_not_found_response(
"Dimension collector not found",
)),
}
}
async fn parse_admin_billing_collector_request(
state: &AppState,
request_body: Option<&Bytes>,
existing_id: Option<&str>,
) -> Result<crate::AdminBillingCollectorWriteInput, Response<Body>> {
let Some(request_body) = request_body else {
return Err(build_admin_billing_bad_request_response("请求体不能为空"));
};
let request = match serde_json::from_slice::<AdminBillingCollectorUpsertRequest>(request_body) {
Ok(value) => value,
Err(err) => {
return Err(build_admin_billing_bad_request_response(format!(
"Invalid request body: {err}"
)))
}
};
let api_format =
match normalize_admin_billing_required_text(&request.api_format, "api_format", 50) {
Ok(value) => value.to_ascii_uppercase(),
Err(detail) => return Err(build_admin_billing_bad_request_response(detail)),
};
let task_type = match normalize_admin_billing_required_text(&request.task_type, "task_type", 20)
{
Ok(value) => value.to_ascii_lowercase(),
Err(detail) => return Err(build_admin_billing_bad_request_response(detail)),
};
let dimension_name =
match normalize_admin_billing_required_text(&request.dimension_name, "dimension_name", 100)
{
Ok(value) => value,
Err(detail) => return Err(build_admin_billing_bad_request_response(detail)),
};
let source_type = request.source_type.trim().to_ascii_lowercase();
if !matches!(
source_type.as_str(),
"request" | "response" | "metadata" | "computed"
) {
return Err(build_admin_billing_bad_request_response(
"source_type must be one of request, response, metadata, computed",
));
}
let value_type = request.value_type.trim().to_ascii_lowercase();
if !matches!(value_type.as_str(), "float" | "int" | "string") {
return Err(build_admin_billing_bad_request_response(
"value_type must be one of float, int, string",
));
}
let source_path = match normalize_admin_billing_optional_text(request.source_path, 200) {
Ok(value) => value,
Err(detail) => return Err(build_admin_billing_bad_request_response(detail)),
};
let transform_expression =
match normalize_admin_billing_optional_text(request.transform_expression, 4096) {
Ok(value) => value,
Err(detail) => return Err(build_admin_billing_bad_request_response(detail)),
};
let default_value = match normalize_admin_billing_optional_text(request.default_value, 100) {
Ok(value) => value,
Err(detail) => return Err(build_admin_billing_bad_request_response(detail)),
};
if source_type == "computed" {
if source_path.is_some() {
return Err(build_admin_billing_bad_request_response(
"computed collector must have source_path=null",
));
}
if transform_expression.is_none() {
return Err(build_admin_billing_bad_request_response(
"computed collector must have transform_expression",
));
}
} else if source_path.is_none() {
return Err(build_admin_billing_bad_request_response(
"non-computed collector must have source_path",
));
}
if let Some(transform_expression) = transform_expression.as_deref() {
if let Err(detail) = admin_billing_validate_safe_expression(transform_expression) {
return Err(build_admin_billing_bad_request_response(format!(
"Invalid transform_expression: {detail}"
)));
}
}
if default_value.is_some() && request.is_enabled {
match state
.admin_billing_enabled_default_value_exists(
&api_format,
&task_type,
&dimension_name,
existing_id,
)
.await
{
Ok(true) => {
return Err(build_admin_billing_bad_request_response(
"default_value already exists for this (api_format, task_type, dimension_name)",
))
}
Ok(false) => {}
Err(err) => {
let detail = match err {
GatewayError::Internal(message) => message,
other => format!("{other:?}"),
};
return Err((
http::StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({ "detail": detail })),
)
.into_response());
}
}
}
Ok(crate::AdminBillingCollectorWriteInput {
api_format,
task_type,
dimension_name,
source_type,
source_path,
value_type,
transform_expression,
default_value,
priority: request.priority,
is_enabled: request.is_enabled,
})
}
async fn build_admin_create_dimension_collector_response(
state: &AppState,
request_body: Option<&Bytes>,
) -> Result<Response<Body>, GatewayError> {
let input = match parse_admin_billing_collector_request(state, request_body, None).await {
Ok(value) => value,
Err(response) => return Ok(response),
};
match state.create_admin_billing_collector(&input).await? {
crate::LocalMutationOutcome::Applied(record) => {
Ok(Json(build_admin_billing_collector_payload_from_record(&record)).into_response())
}
crate::LocalMutationOutcome::Invalid(detail) => {
Ok(build_admin_billing_bad_request_response(detail))
}
crate::LocalMutationOutcome::NotFound => Ok(build_admin_billing_not_found_response(
"Dimension collector not found",
)),
crate::LocalMutationOutcome::Unavailable => Ok(build_admin_billing_read_only_response(
"当前为只读模式,无法创建维度采集器",
)),
}
}
async fn build_admin_update_dimension_collector_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
request_body: Option<&Bytes>,
) -> Result<Response<Body>, GatewayError> {
let Some(collector_id) = admin_billing_collector_id_from_path(&request_context.request_path)
else {
return Ok(build_admin_billing_bad_request_response(
"缺少 collector_id",
));
};
let input =
match parse_admin_billing_collector_request(state, request_body, Some(&collector_id)).await
{
Ok(value) => value,
Err(response) => return Ok(response),
};
match state
.update_admin_billing_collector(&collector_id, &input)
.await?
{
crate::LocalMutationOutcome::Applied(record) => {
Ok(Json(build_admin_billing_collector_payload_from_record(&record)).into_response())
}
crate::LocalMutationOutcome::NotFound => Ok(build_admin_billing_not_found_response(
"Dimension collector not found",
)),
crate::LocalMutationOutcome::Invalid(detail) => {
Ok(build_admin_billing_bad_request_response(detail))
}
crate::LocalMutationOutcome::Unavailable => Ok(build_admin_billing_read_only_response(
"当前为只读模式,无法更新维度采集器",
)),
}
}
pub(super) async fn maybe_build_local_admin_billing_collectors_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
request_body: Option<&Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
let Some(decision) = request_context.control_decision.as_ref() else {
return Ok(None);
};
let path = request_context.request_path.as_str();
match decision.route_kind.as_deref() {
Some("list_collectors")
if request_context.request_method == http::Method::GET
&& matches!(
path,
"/api/admin/billing/collectors" | "/api/admin/billing/collectors/"
) =>
{
Ok(Some(
build_admin_list_dimension_collectors_response(state, request_context).await?,
))
}
Some("get_collector")
if request_context.request_method == http::Method::GET
&& path.starts_with("/api/admin/billing/collectors/") =>
{
Ok(Some(
build_admin_get_dimension_collector_response(state, request_context).await?,
))
}
Some("create_collector")
if request_context.request_method == http::Method::POST
&& matches!(
path,
"/api/admin/billing/collectors" | "/api/admin/billing/collectors/"
) =>
{
Ok(Some(
build_admin_create_dimension_collector_response(state, request_body).await?,
))
}
Some("update_collector")
if request_context.request_method == http::Method::PUT
&& path.starts_with("/api/admin/billing/collectors/") =>
{
Ok(Some(
build_admin_update_dimension_collector_response(
state,
request_context,
request_body,
)
.await?,
))
}
_ => Ok(None),
}
}

View File

@@ -0,0 +1,71 @@
mod reads;
mod support;
mod writes;
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::GatewayError;
use axum::{
body::{Body, Bytes},
http,
response::Response,
};
pub(super) async fn maybe_build_local_admin_billing_collectors_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
let Some(decision) = request_context.decision() else {
return Ok(None);
};
let path = request_context.path();
match decision.route_kind.as_deref() {
Some("list_collectors")
if request_context.method() == http::Method::GET
&& matches!(
path,
"/api/admin/billing/collectors" | "/api/admin/billing/collectors/"
) =>
{
Ok(Some(
reads::build_admin_list_dimension_collectors_response(state, request_context)
.await?,
))
}
Some("get_collector")
if request_context.method() == http::Method::GET
&& path.starts_with("/api/admin/billing/collectors/") =>
{
Ok(Some(
reads::build_admin_get_dimension_collector_response(state, request_context).await?,
))
}
Some("create_collector")
if request_context.method() == http::Method::POST
&& matches!(
path,
"/api/admin/billing/collectors" | "/api/admin/billing/collectors/"
) =>
{
Ok(Some(
writes::build_admin_create_dimension_collector_response(state, request_body)
.await?,
))
}
Some("update_collector")
if request_context.method() == http::Method::PUT
&& path.starts_with("/api/admin/billing/collectors/") =>
{
Ok(Some(
writes::build_admin_update_dimension_collector_response(
state,
request_context,
request_body,
)
.await?,
))
}
_ => Ok(None),
}
}

View File

@@ -0,0 +1,80 @@
use super::support::{
admin_billing_collector_id_from_path, admin_billing_optional_bool_filter,
admin_billing_optional_filter, admin_billing_pages, admin_billing_parse_page,
admin_billing_parse_page_size, build_admin_billing_bad_request_response,
build_admin_billing_collector_payload_from_record, build_admin_billing_not_found_response,
};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::GatewayError;
use axum::{
body::Body,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
pub(super) async fn build_admin_list_dimension_collectors_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
let query = request_context.query_string();
let page = match admin_billing_parse_page(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_billing_bad_request_response(detail)),
};
let page_size = match admin_billing_parse_page_size(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_billing_bad_request_response(detail)),
};
let api_format = admin_billing_optional_filter(query, "api_format");
let task_type = admin_billing_optional_filter(query, "task_type");
let dimension_name = admin_billing_optional_filter(query, "dimension_name");
let is_enabled = match admin_billing_optional_bool_filter(query, "is_enabled") {
Ok(value) => value,
Err(detail) => return Ok(build_admin_billing_bad_request_response(detail)),
};
let (items, total) = state
.list_admin_billing_collectors(
api_format.as_deref(),
task_type.as_deref(),
dimension_name.as_deref(),
is_enabled,
page,
page_size,
)
.await?
.unwrap_or_default();
Ok(Json(json!({
"items": items
.iter()
.map(build_admin_billing_collector_payload_from_record)
.collect::<Vec<_>>(),
"total": total,
"page": page,
"page_size": page_size,
"pages": admin_billing_pages(total, page_size),
}))
.into_response())
}
pub(super) async fn build_admin_get_dimension_collector_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
let Some(collector_id) = admin_billing_collector_id_from_path(request_context.path()) else {
return Ok(build_admin_billing_bad_request_response(
"缺少 collector_id",
));
};
match state.read_admin_billing_collector(&collector_id).await? {
Some(record) => {
Ok(Json(build_admin_billing_collector_payload_from_record(&record)).into_response())
}
None => Ok(build_admin_billing_not_found_response(
"Dimension collector not found",
)),
}
}

View File

@@ -0,0 +1,247 @@
use super::super::{
admin_billing_validate_safe_expression, default_admin_billing_true,
normalize_admin_billing_optional_text, normalize_admin_billing_required_text,
};
use crate::handlers::admin::request::AdminAppState;
use crate::handlers::admin::shared::unix_secs_to_rfc3339;
use crate::GatewayError;
use axum::{
body::{Body, Bytes},
http,
response::{IntoResponse, Response},
Json,
};
use serde::Deserialize;
use serde_json::json;
fn default_admin_billing_collector_value_type() -> String {
"float".to_string()
}
#[derive(Debug, Deserialize)]
pub(super) struct AdminBillingCollectorUpsertRequest {
pub(super) api_format: String,
pub(super) task_type: String,
pub(super) dimension_name: String,
pub(super) source_type: String,
#[serde(default)]
pub(super) source_path: Option<String>,
#[serde(default = "default_admin_billing_collector_value_type")]
pub(super) value_type: String,
#[serde(default)]
pub(super) transform_expression: Option<String>,
#[serde(default)]
pub(super) default_value: Option<String>,
#[serde(default)]
pub(super) priority: i32,
#[serde(default = "default_admin_billing_true")]
pub(super) is_enabled: bool,
}
pub(super) fn build_admin_billing_collector_payload_from_record(
record: &crate::AdminBillingCollectorRecord,
) -> serde_json::Value {
json!({
"id": record.id,
"api_format": record.api_format,
"task_type": record.task_type,
"dimension_name": record.dimension_name,
"source_type": record.source_type,
"source_path": record.source_path,
"value_type": record.value_type,
"transform_expression": record.transform_expression,
"default_value": record.default_value,
"priority": record.priority,
"is_enabled": record.is_enabled,
"created_at": unix_secs_to_rfc3339(record.created_at_unix_secs),
"updated_at": unix_secs_to_rfc3339(record.updated_at_unix_secs),
})
}
pub(super) fn admin_billing_collector_id_from_path(request_path: &str) -> Option<String> {
let value = request_path
.strip_prefix("/api/admin/billing/collectors/")?
.trim()
.trim_matches('/')
.to_string();
if value.is_empty() || value.contains('/') {
None
} else {
Some(value)
}
}
pub(super) async fn parse_admin_billing_collector_request(
state: &AdminAppState<'_>,
request_body: Option<&Bytes>,
existing_id: Option<&str>,
) -> Result<crate::AdminBillingCollectorWriteInput, Response<Body>> {
let Some(request_body) = request_body else {
return Err(build_admin_billing_bad_request_response("请求体不能为空"));
};
let request = match serde_json::from_slice::<AdminBillingCollectorUpsertRequest>(request_body) {
Ok(value) => value,
Err(err) => {
return Err(build_admin_billing_bad_request_response(format!(
"Invalid request body: {err}"
)));
}
};
let api_format =
match normalize_admin_billing_required_text(&request.api_format, "api_format", 50) {
Ok(value) => value.to_ascii_uppercase(),
Err(detail) => return Err(build_admin_billing_bad_request_response(detail)),
};
let task_type = match normalize_admin_billing_required_text(&request.task_type, "task_type", 20)
{
Ok(value) => value.to_ascii_lowercase(),
Err(detail) => return Err(build_admin_billing_bad_request_response(detail)),
};
let dimension_name =
match normalize_admin_billing_required_text(&request.dimension_name, "dimension_name", 100)
{
Ok(value) => value,
Err(detail) => return Err(build_admin_billing_bad_request_response(detail)),
};
let source_type = request.source_type.trim().to_ascii_lowercase();
if !matches!(
source_type.as_str(),
"request" | "response" | "metadata" | "computed"
) {
return Err(build_admin_billing_bad_request_response(
"source_type must be one of request, response, metadata, computed",
));
}
let value_type = request.value_type.trim().to_ascii_lowercase();
if !matches!(value_type.as_str(), "float" | "int" | "string") {
return Err(build_admin_billing_bad_request_response(
"value_type must be one of float, int, string",
));
}
let source_path = match normalize_admin_billing_optional_text(request.source_path, 200) {
Ok(value) => value,
Err(detail) => return Err(build_admin_billing_bad_request_response(detail)),
};
let transform_expression =
match normalize_admin_billing_optional_text(request.transform_expression, 4096) {
Ok(value) => value,
Err(detail) => return Err(build_admin_billing_bad_request_response(detail)),
};
let default_value = match normalize_admin_billing_optional_text(request.default_value, 100) {
Ok(value) => value,
Err(detail) => return Err(build_admin_billing_bad_request_response(detail)),
};
if source_type == "computed" {
if source_path.is_some() {
return Err(build_admin_billing_bad_request_response(
"computed collector must have source_path=null",
));
}
if transform_expression.is_none() {
return Err(build_admin_billing_bad_request_response(
"computed collector must have transform_expression",
));
}
} else if source_path.is_none() {
return Err(build_admin_billing_bad_request_response(
"non-computed collector must have source_path",
));
}
if let Some(transform_expression) = transform_expression.as_deref() {
if let Err(detail) = admin_billing_validate_safe_expression(transform_expression) {
return Err(build_admin_billing_bad_request_response(format!(
"Invalid transform_expression: {detail}"
)));
}
}
if default_value.is_some() && request.is_enabled {
match state
.admin_billing_enabled_default_value_exists(
&api_format,
&task_type,
&dimension_name,
existing_id,
)
.await
{
Ok(true) => {
return Err(build_admin_billing_bad_request_response(
"default_value already exists for this (api_format, task_type, dimension_name)",
));
}
Ok(false) => {}
Err(err) => {
let detail = match err {
GatewayError::Internal(message) => message,
other => format!("{other:?}"),
};
return Err((
http::StatusCode::INTERNAL_SERVER_ERROR,
Json(json!({ "detail": detail })),
)
.into_response());
}
}
}
Ok(crate::AdminBillingCollectorWriteInput {
api_format,
task_type,
dimension_name,
source_type,
source_path,
value_type,
transform_expression,
default_value,
priority: request.priority,
is_enabled: request.is_enabled,
})
}
pub(in super::super) fn admin_billing_parse_page(query: Option<&str>) -> Result<u32, String> {
super::super::admin_billing_parse_page(query)
}
pub(in super::super) fn admin_billing_parse_page_size(query: Option<&str>) -> Result<u32, String> {
super::super::admin_billing_parse_page_size(query)
}
pub(in super::super) fn admin_billing_optional_filter(
query: Option<&str>,
key: &str,
) -> Option<String> {
super::super::admin_billing_optional_filter(query, key)
}
pub(in super::super) fn admin_billing_optional_bool_filter(
query: Option<&str>,
key: &str,
) -> Result<Option<bool>, String> {
super::super::admin_billing_optional_bool_filter(query, key)
}
pub(in super::super) fn admin_billing_pages(total: u64, page_size: u32) -> u64 {
super::super::admin_billing_pages(total, page_size)
}
pub(in super::super) fn build_admin_billing_bad_request_response(
detail: impl Into<String>,
) -> Response<Body> {
super::super::build_admin_billing_bad_request_response(detail)
}
pub(in super::super) fn build_admin_billing_not_found_response(
detail: &'static str,
) -> Response<Body> {
super::super::build_admin_billing_not_found_response(detail)
}
pub(in super::super) fn build_admin_billing_read_only_response(
detail: &'static str,
) -> Response<Body> {
super::super::build_admin_billing_read_only_response(detail)
}

View File

@@ -0,0 +1,71 @@
use super::support::{
admin_billing_collector_id_from_path, build_admin_billing_bad_request_response,
build_admin_billing_collector_payload_from_record, build_admin_billing_not_found_response,
build_admin_billing_read_only_response, parse_admin_billing_collector_request,
};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::GatewayError;
use axum::{
body::{Body, Bytes},
response::{IntoResponse, Response},
Json,
};
pub(super) async fn build_admin_create_dimension_collector_response(
state: &AdminAppState<'_>,
request_body: Option<&Bytes>,
) -> Result<Response<Body>, GatewayError> {
let input = match parse_admin_billing_collector_request(state, request_body, None).await {
Ok(value) => value,
Err(response) => return Ok(response),
};
match state.create_admin_billing_collector(&input).await? {
crate::LocalMutationOutcome::Applied(record) => {
Ok(Json(build_admin_billing_collector_payload_from_record(&record)).into_response())
}
crate::LocalMutationOutcome::Invalid(detail) => {
Ok(build_admin_billing_bad_request_response(detail))
}
crate::LocalMutationOutcome::NotFound => Ok(build_admin_billing_not_found_response(
"Dimension collector not found",
)),
crate::LocalMutationOutcome::Unavailable => Ok(build_admin_billing_read_only_response(
"当前为只读模式,无法创建维度采集器",
)),
}
}
pub(super) async fn build_admin_update_dimension_collector_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&Bytes>,
) -> Result<Response<Body>, GatewayError> {
let Some(collector_id) = admin_billing_collector_id_from_path(request_context.path()) else {
return Ok(build_admin_billing_bad_request_response(
"缺少 collector_id",
));
};
let input =
match parse_admin_billing_collector_request(state, request_body, Some(&collector_id)).await
{
Ok(value) => value,
Err(response) => return Ok(response),
};
match state
.update_admin_billing_collector(&collector_id, &input)
.await?
{
crate::LocalMutationOutcome::Applied(record) => {
Ok(Json(build_admin_billing_collector_payload_from_record(&record)).into_response())
}
crate::LocalMutationOutcome::NotFound => Ok(build_admin_billing_not_found_response(
"Dimension collector not found",
)),
crate::LocalMutationOutcome::Invalid(detail) => {
Ok(build_admin_billing_bad_request_response(detail))
}
crate::LocalMutationOutcome::Unavailable => Ok(build_admin_billing_read_only_response(
"当前为只读模式,无法更新维度采集器",
)),
}
}

View File

@@ -1,6 +1,6 @@
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::{query_param_value, unix_secs_to_rfc3339};
use crate::{AppState, GatewayError};
use crate::GatewayError;
use axum::{
body::{Body, Bytes},
http,
@@ -16,11 +16,13 @@ const ADMIN_BILLING_DATA_UNAVAILABLE_DETAIL: &str = "Admin billing data unavaila
mod collectors;
mod payments;
mod presets;
mod routes;
mod rules;
mod wallets;
pub(crate) use self::payments::maybe_build_local_admin_payments_response;
pub(crate) use self::wallets::maybe_build_local_admin_wallets_response;
pub(super) use self::payments::maybe_build_local_admin_payments_response;
pub(super) use self::routes::maybe_build_local_admin_billing_routes_response;
pub(super) use self::wallets::maybe_build_local_admin_wallets_response;
fn default_admin_billing_true() -> bool {
true
@@ -198,11 +200,11 @@ fn admin_billing_optional_epoch_value(
}
pub(crate) async fn maybe_build_local_admin_billing_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
let Some(decision) = request_context.control_decision.as_ref() else {
let Some(decision) = request_context.decision() else {
return Ok(None);
};
@@ -210,47 +212,47 @@ pub(crate) async fn maybe_build_local_admin_billing_response(
return Ok(None);
}
let path = request_context.request_path.as_str();
let is_billing_route = (request_context.request_method == http::Method::GET
let path = request_context.path();
let is_billing_route = (request_context.method() == http::Method::GET
&& matches!(
path,
"/api/admin/billing/presets" | "/api/admin/billing/presets/"
))
|| (request_context.request_method == http::Method::POST
|| (request_context.method() == http::Method::POST
&& matches!(
path,
"/api/admin/billing/presets/apply" | "/api/admin/billing/presets/apply/"
))
|| (request_context.request_method == http::Method::GET
|| (request_context.method() == http::Method::GET
&& matches!(
path,
"/api/admin/billing/rules" | "/api/admin/billing/rules/"
))
|| (request_context.request_method == http::Method::GET
|| (request_context.method() == http::Method::GET
&& path.starts_with("/api/admin/billing/rules/")
&& path.matches('/').count() == 5)
|| (request_context.request_method == http::Method::POST
|| (request_context.method() == http::Method::POST
&& matches!(
path,
"/api/admin/billing/rules" | "/api/admin/billing/rules/"
))
|| (request_context.request_method == http::Method::PUT
|| (request_context.method() == http::Method::PUT
&& path.starts_with("/api/admin/billing/rules/")
&& path.matches('/').count() == 5)
|| (request_context.request_method == http::Method::GET
|| (request_context.method() == http::Method::GET
&& matches!(
path,
"/api/admin/billing/collectors" | "/api/admin/billing/collectors/"
))
|| (request_context.request_method == http::Method::GET
|| (request_context.method() == http::Method::GET
&& path.starts_with("/api/admin/billing/collectors/")
&& path.matches('/').count() == 5)
|| (request_context.request_method == http::Method::POST
|| (request_context.method() == http::Method::POST
&& matches!(
path,
"/api/admin/billing/collectors" | "/api/admin/billing/collectors/"
))
|| (request_context.request_method == http::Method::PUT
|| (request_context.method() == http::Method::PUT
&& path.starts_with("/api/admin/billing/collectors/")
&& path.matches('/').count() == 5);

View File

@@ -3,9 +3,9 @@ use super::{
build_admin_payments_bad_request_response, parse_admin_payments_limit,
parse_admin_payments_offset,
};
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::query_param_value;
use crate::{AppState, GatewayError};
use crate::GatewayError;
use axum::{
body::Body,
response::{IntoResponse, Response},
@@ -14,8 +14,8 @@ use axum::{
use serde_json::json;
pub(super) async fn maybe_build_local_admin_payment_callbacks_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
route_kind: Option<&str>,
) -> Result<Option<Response<Body>>, GatewayError> {
match route_kind {
@@ -27,10 +27,10 @@ pub(super) async fn maybe_build_local_admin_payment_callbacks_response(
}
async fn build_admin_payment_callbacks_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
let query = request_context.request_query_string.as_deref();
let query = request_context.query_string();
let limit = match parse_admin_payments_limit(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_payments_bad_request_response(detail)),

View File

@@ -1,5 +1,5 @@
use crate::control::GatewayPublicRequestContext;
use crate::{AppState, GatewayError};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::GatewayError;
use axum::{body::Body, response::Response};
mod callbacks;
@@ -21,8 +21,8 @@ use self::shared::{
};
pub(crate) async fn maybe_build_local_admin_payments_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&axum::body::Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
routes::maybe_build_local_admin_payments_response(state, request_context, request_body).await

View File

@@ -7,9 +7,9 @@ use super::{
normalize_admin_payment_positive_number, parse_admin_payments_limit,
parse_admin_payments_offset, AdminPaymentOrderCreditRequest,
};
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::{attach_admin_audit_response, query_param_value};
use crate::{AppState, GatewayError};
use crate::GatewayError;
use axum::{
body::Body,
response::{IntoResponse, Response},
@@ -18,8 +18,8 @@ use axum::{
use serde_json::json;
pub(super) async fn maybe_build_local_admin_payment_orders_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&axum::body::Bytes>,
route_kind: Option<&str>,
) -> Result<Option<Response<Body>>, GatewayError> {
@@ -44,10 +44,10 @@ pub(super) async fn maybe_build_local_admin_payment_orders_response(
}
async fn build_admin_payment_list_orders_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
let query = request_context.request_query_string.as_deref();
let query = request_context.query_string();
let limit = match parse_admin_payments_limit(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_payments_bad_request_response(detail)),
@@ -83,11 +83,10 @@ async fn build_admin_payment_list_orders_response(
}
async fn build_admin_payment_get_order_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
let Some(order_id) = admin_payment_order_id_from_detail_path(&request_context.request_path)
else {
let Some(order_id) = admin_payment_order_id_from_detail_path(request_context.path()) else {
return Ok(build_admin_payment_order_not_found_response());
};
match state.read_admin_payment_order(&order_id).await? {
@@ -110,11 +109,10 @@ async fn build_admin_payment_get_order_response(
}
async fn build_admin_payment_expire_order_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
let Some(order_id) =
admin_payment_order_id_from_suffix_path(&request_context.request_path, "/expire")
let Some(order_id) = admin_payment_order_id_from_suffix_path(request_context.path(), "/expire")
else {
return Ok(build_admin_payment_order_not_found_response());
};
@@ -147,12 +145,11 @@ async fn build_admin_payment_expire_order_response(
}
async fn build_admin_payment_credit_order_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&axum::body::Bytes>,
) -> Result<Response<Body>, GatewayError> {
let Some(order_id) =
admin_payment_order_id_from_suffix_path(&request_context.request_path, "/credit")
let Some(order_id) = admin_payment_order_id_from_suffix_path(request_context.path(), "/credit")
else {
return Ok(build_admin_payment_order_not_found_response());
};
@@ -241,11 +238,10 @@ async fn build_admin_payment_credit_order_response(
}
async fn build_admin_payment_fail_order_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
let Some(order_id) =
admin_payment_order_id_from_suffix_path(&request_context.request_path, "/fail")
let Some(order_id) = admin_payment_order_id_from_suffix_path(request_context.path(), "/fail")
else {
return Ok(build_admin_payment_order_not_found_response());
};

View File

@@ -3,16 +3,16 @@ use super::{
callbacks::maybe_build_local_admin_payment_callbacks_response,
orders::maybe_build_local_admin_payment_orders_response,
};
use crate::control::GatewayPublicRequestContext;
use crate::{AppState, GatewayError};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::GatewayError;
use axum::{body::Body, http, response::Response};
pub(super) async fn maybe_build_local_admin_payments_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&axum::body::Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
let Some(decision) = request_context.control_decision.as_ref() else {
let Some(decision) = request_context.decision() else {
return Ok(None);
};
@@ -20,30 +20,30 @@ pub(super) async fn maybe_build_local_admin_payments_response(
return Ok(None);
}
let normalized_path = request_context.request_path.trim_end_matches('/');
let normalized_path = request_context.path().trim_end_matches('/');
let path = if normalized_path.is_empty() {
request_context.request_path.as_str()
request_context.path()
} else {
normalized_path
};
let is_payments_route = (request_context.request_method == http::Method::GET
let is_payments_route = (request_context.method() == http::Method::GET
&& path == "/api/admin/payments/orders")
|| (request_context.request_method == http::Method::GET
|| (request_context.method() == http::Method::GET
&& path.starts_with("/api/admin/payments/orders/")
&& path.matches('/').count() == 5)
|| (request_context.request_method == http::Method::POST
|| (request_context.method() == http::Method::POST
&& path.starts_with("/api/admin/payments/orders/")
&& path.ends_with("/expire")
&& path.matches('/').count() == 6)
|| (request_context.request_method == http::Method::POST
|| (request_context.method() == http::Method::POST
&& path.starts_with("/api/admin/payments/orders/")
&& path.ends_with("/credit")
&& path.matches('/').count() == 6)
|| (request_context.request_method == http::Method::POST
|| (request_context.method() == http::Method::POST
&& path.starts_with("/api/admin/payments/orders/")
&& path.ends_with("/fail")
&& path.matches('/').count() == 6)
|| (request_context.request_method == http::Method::GET
|| (request_context.method() == http::Method::GET
&& path == "/api/admin/payments/callbacks");
if !is_payments_route {

View File

@@ -1,4 +1,4 @@
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::request::AdminRequestContext;
use crate::handlers::admin::shared::{query_param_value, unix_secs_to_rfc3339};
use crate::{GatewayAdminPaymentCallbackView, GatewayError};
use axum::{
@@ -175,11 +175,10 @@ pub(super) fn normalize_admin_payment_positive_number(
}
pub(super) fn admin_payment_operator_id(
request_context: &GatewayPublicRequestContext,
request_context: &AdminRequestContext<'_>,
) -> Option<String> {
request_context
.control_decision
.as_ref()
.decision()
.and_then(|decision| decision.admin_principal.as_ref())
.map(|principal| principal.user_id.clone())
}

View File

@@ -0,0 +1,74 @@
use super::super::{
build_admin_billing_bad_request_response, build_admin_billing_not_found_response,
build_admin_billing_read_only_response,
};
use super::support::{
parse_admin_billing_preset_apply_request, resolve_admin_billing_preset_collectors,
};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::attach_admin_audit_response;
use crate::GatewayError;
use axum::{
body::{Body, Bytes},
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
pub(super) async fn build_admin_apply_billing_preset_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&Bytes>,
) -> Result<Response<Body>, GatewayError> {
let (preset, mode) = match parse_admin_billing_preset_apply_request(request_body) {
Ok(value) => value,
Err(response) => return Ok(response),
};
let Some((resolved_preset, collectors)) = resolve_admin_billing_preset_collectors(&preset)
else {
let payload = json!({
"ok": false,
"preset": preset,
"mode": mode,
"created": 0,
"updated": 0,
"skipped": 0,
"errors": ["Unknown preset: available presets are aether-core"],
});
return Ok(Json(payload).into_response());
};
match state
.apply_admin_billing_preset(resolved_preset, &mode, &collectors)
.await?
{
crate::LocalMutationOutcome::Applied(result) => {
let response = Json(json!({
"ok": result.errors.is_empty(),
"preset": result.preset,
"mode": result.mode,
"created": result.created,
"updated": result.updated,
"skipped": result.skipped,
"errors": result.errors,
}))
.into_response();
Ok(attach_admin_audit_response(
response,
"admin_billing_preset_applied",
"apply_billing_preset",
"billing_preset",
resolved_preset,
))
}
crate::LocalMutationOutcome::Unavailable => Ok(build_admin_billing_read_only_response(
"当前为只读模式,无法应用计费预设",
)),
crate::LocalMutationOutcome::Invalid(detail) => {
Ok(build_admin_billing_bad_request_response(detail))
}
crate::LocalMutationOutcome::NotFound => Ok(build_admin_billing_not_found_response(
"Billing preset not found",
)),
}
}

View File

@@ -0,0 +1,53 @@
mod apply;
mod support;
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::GatewayError;
use axum::{
body::{Body, Bytes},
http,
response::{IntoResponse, Response},
Json,
};
pub(super) async fn maybe_build_local_admin_billing_presets_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
let Some(decision) = request_context.decision() else {
return Ok(None);
};
let path = request_context.path();
match decision.route_kind.as_deref() {
Some("list_presets")
if request_context.method() == http::Method::GET
&& matches!(
path,
"/api/admin/billing/presets" | "/api/admin/billing/presets/"
) =>
{
Ok(Some(
Json(support::build_admin_billing_presets_payload()).into_response(),
))
}
Some("apply_preset")
if request_context.method() == http::Method::POST
&& matches!(
path,
"/api/admin/billing/presets/apply" | "/api/admin/billing/presets/apply/"
) =>
{
Ok(Some(
apply::build_admin_apply_billing_preset_response(
state,
request_context,
request_body,
)
.await?,
))
}
_ => Ok(None),
}
}

View File

@@ -1,14 +1,9 @@
use super::{
build_admin_billing_bad_request_response, build_admin_billing_not_found_response,
build_admin_billing_read_only_response, normalize_admin_billing_required_text,
use super::super::{
build_admin_billing_bad_request_response, normalize_admin_billing_required_text,
};
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::shared::attach_admin_audit_response;
use crate::{AppState, GatewayError};
use axum::{
body::{Body, Bytes},
response::{IntoResponse, Response},
Json,
response::Response,
};
use serde::Deserialize;
use serde_json::json;
@@ -24,7 +19,7 @@ struct AdminBillingPresetApplyRequest {
mode: String,
}
fn build_admin_billing_presets_payload() -> serde_json::Value {
pub(super) fn build_admin_billing_presets_payload() -> serde_json::Value {
json!({
"items": [
{
@@ -234,7 +229,7 @@ fn build_admin_billing_aether_core_collectors() -> Vec<crate::AdminBillingCollec
]
}
fn resolve_admin_billing_preset_collectors(
pub(super) fn resolve_admin_billing_preset_collectors(
preset: &str,
) -> Option<(&'static str, Vec<crate::AdminBillingCollectorWriteInput>)> {
let normalized = preset.trim().to_ascii_lowercase();
@@ -246,7 +241,7 @@ fn resolve_admin_billing_preset_collectors(
}
}
fn parse_admin_billing_preset_apply_request(
pub(super) fn parse_admin_billing_preset_apply_request(
request_body: Option<&Bytes>,
) -> Result<(String, String), Response<Body>> {
let Some(request_body) = request_body else {
@@ -272,99 +267,3 @@ fn parse_admin_billing_preset_apply_request(
}
Ok((preset, mode))
}
async fn build_admin_apply_billing_preset_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
request_body: Option<&Bytes>,
) -> Result<Response<Body>, GatewayError> {
let (preset, mode) = match parse_admin_billing_preset_apply_request(request_body) {
Ok(value) => value,
Err(response) => return Ok(response),
};
let Some((resolved_preset, collectors)) = resolve_admin_billing_preset_collectors(&preset)
else {
let payload = json!({
"ok": false,
"preset": preset,
"mode": mode,
"created": 0,
"updated": 0,
"skipped": 0,
"errors": ["Unknown preset: available presets are aether-core"],
});
return Ok(Json(payload).into_response());
};
match state
.apply_admin_billing_preset(resolved_preset, &mode, &collectors)
.await?
{
crate::LocalMutationOutcome::Applied(result) => {
let response = Json(json!({
"ok": result.errors.is_empty(),
"preset": result.preset,
"mode": result.mode,
"created": result.created,
"updated": result.updated,
"skipped": result.skipped,
"errors": result.errors,
}))
.into_response();
Ok(attach_admin_audit_response(
response,
"admin_billing_preset_applied",
"apply_billing_preset",
"billing_preset",
resolved_preset,
))
}
crate::LocalMutationOutcome::Unavailable => Ok(build_admin_billing_read_only_response(
"当前为只读模式,无法应用计费预设",
)),
crate::LocalMutationOutcome::Invalid(detail) => {
Ok(build_admin_billing_bad_request_response(detail))
}
crate::LocalMutationOutcome::NotFound => Ok(build_admin_billing_not_found_response(
"Billing preset not found",
)),
}
}
pub(super) async fn maybe_build_local_admin_billing_presets_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
request_body: Option<&Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
let Some(decision) = request_context.control_decision.as_ref() else {
return Ok(None);
};
let path = request_context.request_path.as_str();
match decision.route_kind.as_deref() {
Some("list_presets")
if request_context.request_method == http::Method::GET
&& matches!(
path,
"/api/admin/billing/presets" | "/api/admin/billing/presets/"
) =>
{
Ok(Some(
Json(build_admin_billing_presets_payload()).into_response(),
))
}
Some("apply_preset")
if request_context.request_method == http::Method::POST
&& matches!(
path,
"/api/admin/billing/presets/apply" | "/api/admin/billing/presets/apply/"
) =>
{
Ok(Some(
build_admin_apply_billing_preset_response(state, request_context, request_body)
.await?,
))
}
_ => Ok(None),
}
}

View File

@@ -0,0 +1,38 @@
use super::{maybe_build_local_admin_billing_response, payments, wallets};
use crate::handlers::admin::request::{AdminRouteRequest, AdminRouteResult};
pub(crate) async fn maybe_build_local_admin_billing_routes_response(
request: AdminRouteRequest<'_>,
) -> AdminRouteResult {
if let Some(response) = maybe_build_local_admin_billing_response(
&request.state(),
&request.request_context(),
request.request_body(),
)
.await?
{
return Ok(Some(response));
}
if let Some(response) = payments::maybe_build_local_admin_payments_response(
&request.state(),
&request.request_context(),
request.request_body(),
)
.await?
{
return Ok(Some(response));
}
if let Some(response) = wallets::maybe_build_local_admin_wallets_response(
&request.state(),
&request.request_context(),
request.request_body(),
)
.await?
{
return Ok(Some(response));
}
Ok(None)
}

View File

@@ -6,9 +6,9 @@ use super::{
default_admin_billing_json_object, default_admin_billing_true,
normalize_admin_billing_optional_text, normalize_admin_billing_required_text,
};
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::unix_secs_to_rfc3339;
use crate::{AppState, GatewayError};
use crate::GatewayError;
use axum::{
body::{Body, Bytes},
http,
@@ -170,10 +170,10 @@ fn parse_admin_billing_rule_request(
}
async fn build_admin_list_billing_rules_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
let query = request_context.request_query_string.as_deref();
let query = request_context.query_string();
let page = match admin_billing_parse_page(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_billing_bad_request_response(detail)),
@@ -214,10 +214,10 @@ async fn build_admin_list_billing_rules_response(
}
async fn build_admin_get_billing_rule_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
let Some(rule_id) = admin_billing_rule_id_from_path(&request_context.request_path) else {
let Some(rule_id) = admin_billing_rule_id_from_path(request_context.path()) else {
return Ok(build_admin_billing_bad_request_response("缺少 rule_id"));
};
match state.read_admin_billing_rule(&rule_id).await? {
@@ -231,7 +231,7 @@ async fn build_admin_get_billing_rule_response(
}
async fn build_admin_create_billing_rule_response(
state: &AppState,
state: &AdminAppState<'_>,
request_body: Option<&Bytes>,
) -> Result<Response<Body>, GatewayError> {
let input = match parse_admin_billing_rule_request(request_body) {
@@ -255,11 +255,11 @@ async fn build_admin_create_billing_rule_response(
}
async fn build_admin_update_billing_rule_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&Bytes>,
) -> Result<Response<Body>, GatewayError> {
let Some(rule_id) = admin_billing_rule_id_from_path(&request_context.request_path) else {
let Some(rule_id) = admin_billing_rule_id_from_path(request_context.path()) else {
return Ok(build_admin_billing_bad_request_response("缺少 rule_id"));
};
let input = match parse_admin_billing_rule_request(request_body) {
@@ -283,18 +283,18 @@ async fn build_admin_update_billing_rule_response(
}
pub(super) async fn maybe_build_local_admin_billing_rules_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
let Some(decision) = request_context.control_decision.as_ref() else {
let Some(decision) = request_context.decision() else {
return Ok(None);
};
let path = request_context.request_path.as_str();
let path = request_context.path();
match decision.route_kind.as_deref() {
Some("list_rules")
if request_context.request_method == http::Method::GET
if request_context.method() == http::Method::GET
&& matches!(
path,
"/api/admin/billing/rules" | "/api/admin/billing/rules/"
@@ -305,7 +305,7 @@ pub(super) async fn maybe_build_local_admin_billing_rules_response(
))
}
Some("get_rule")
if request_context.request_method == http::Method::GET
if request_context.method() == http::Method::GET
&& path.starts_with("/api/admin/billing/rules/") =>
{
Ok(Some(
@@ -313,7 +313,7 @@ pub(super) async fn maybe_build_local_admin_billing_rules_response(
))
}
Some("create_rule")
if request_context.request_method == http::Method::POST
if request_context.method() == http::Method::POST
&& matches!(
path,
"/api/admin/billing/rules" | "/api/admin/billing/rules/"
@@ -324,7 +324,7 @@ pub(super) async fn maybe_build_local_admin_billing_rules_response(
))
}
Some("update_rule")
if request_context.request_method == http::Method::PUT
if request_context.method() == http::Method::PUT
&& path.starts_with("/api/admin/billing/rules/") =>
{
Ok(Some(

View File

@@ -1,5 +1,5 @@
use crate::control::GatewayPublicRequestContext;
use crate::{AppState, GatewayError};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::GatewayError;
use axum::{body::Body, response::Response};
mod mutations;
@@ -8,8 +8,8 @@ mod routes;
mod shared;
pub(crate) async fn maybe_build_local_admin_wallets_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&axum::body::Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
routes::maybe_build_local_admin_wallets_routes_response(state, request_context, request_body)

View File

@@ -1,474 +0,0 @@
use super::shared::{
admin_wallet_id_from_suffix_path, admin_wallet_operator_id,
admin_wallet_refund_ids_from_suffix_path, build_admin_wallet_not_found_response,
build_admin_wallet_payment_order_payload, build_admin_wallet_refund_not_found_response,
build_admin_wallet_refund_payload, build_admin_wallet_summary_payload,
build_admin_wallet_transaction_payload, build_admin_wallets_bad_request_response,
build_admin_wallets_data_unavailable_response, normalize_admin_wallet_balance_type,
normalize_admin_wallet_description, normalize_admin_wallet_non_zero_amount,
normalize_admin_wallet_optional_text, normalize_admin_wallet_payment_method,
normalize_admin_wallet_positive_amount, normalize_admin_wallet_required_text,
resolve_admin_wallet_owner_summary, AdminWalletAdjustRequest, AdminWalletRechargeRequest,
AdminWalletRefundCompleteRequest, AdminWalletRefundFailRequest,
ADMIN_WALLETS_API_KEY_GIFT_ADJUST_DETAIL, ADMIN_WALLETS_API_KEY_RECHARGE_DETAIL,
ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
};
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::shared::{attach_admin_audit_response, unix_secs_to_rfc3339};
use crate::{AppState, GatewayError};
use axum::{
body::Body,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
pub(super) async fn build_admin_wallet_adjust_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
request_body: Option<&axum::body::Bytes>,
) -> Result<Response<Body>, GatewayError> {
let Some(wallet_id) =
admin_wallet_id_from_suffix_path(&request_context.request_path, "/adjust")
else {
return Ok(build_admin_wallets_bad_request_response("wallet_id 无效"));
};
let Some(request_body) = request_body else {
return Ok(build_admin_wallets_bad_request_response("请求体不能为空"));
};
let payload = match serde_json::from_slice::<AdminWalletAdjustRequest>(request_body) {
Ok(value) => value,
Err(_) => return Ok(build_admin_wallets_bad_request_response("请求体格式无效")),
};
let amount_usd = match normalize_admin_wallet_non_zero_amount(payload.amount_usd, "amount_usd")
{
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let balance_type = match normalize_admin_wallet_balance_type(payload.balance_type) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let description = match normalize_admin_wallet_description(payload.description) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let Some(existing_wallet) = state
.find_wallet(aether_data::repository::wallet::WalletLookupKey::WalletId(
&wallet_id,
))
.await?
else {
return Ok(build_admin_wallet_not_found_response());
};
if existing_wallet.api_key_id.is_some() && balance_type == "gift" {
return Ok(build_admin_wallets_bad_request_response(
ADMIN_WALLETS_API_KEY_GIFT_ADJUST_DETAIL,
));
}
let operator_id = admin_wallet_operator_id(request_context);
let has_postgres = state.postgres_pool().is_some();
let Some((wallet, transaction)) = state
.admin_adjust_wallet_balance(
&wallet_id,
amount_usd,
&balance_type,
operator_id.as_deref(),
description.as_deref(),
)
.await?
else {
return if has_postgres {
Ok(build_admin_wallet_not_found_response())
} else {
Ok(build_admin_wallets_data_unavailable_response())
};
};
let owner = resolve_admin_wallet_owner_summary(state, &wallet).await?;
let wallet_payload = build_admin_wallet_summary_payload(&wallet, &owner);
let transaction_payload = build_admin_wallet_transaction_payload(
&wallet,
&owner,
transaction.id,
&transaction.category,
&transaction.reason_code,
transaction.amount,
transaction.balance_before,
transaction.balance_after,
transaction.recharge_balance_before,
transaction.recharge_balance_after,
transaction.gift_balance_before,
transaction.gift_balance_after,
transaction.link_type.as_deref(),
transaction.link_id.as_deref(),
transaction.operator_id.as_deref(),
transaction.description.as_deref(),
unix_secs_to_rfc3339(transaction.created_at_unix_secs),
);
let response = Json(json!({
"wallet": wallet_payload,
"transaction": transaction_payload,
}))
.into_response();
Ok(attach_admin_audit_response(
response,
"admin_wallet_balance_adjusted",
"adjust_wallet_balance",
"wallet",
&wallet_id,
))
}
pub(super) async fn build_admin_wallet_recharge_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
request_body: Option<&axum::body::Bytes>,
) -> Result<Response<Body>, GatewayError> {
let Some(wallet_id) =
admin_wallet_id_from_suffix_path(&request_context.request_path, "/recharge")
else {
return Ok(build_admin_wallets_bad_request_response("wallet_id 无效"));
};
let Some(request_body) = request_body else {
return Ok(build_admin_wallets_bad_request_response("请求体不能为空"));
};
let payload = match serde_json::from_slice::<AdminWalletRechargeRequest>(request_body) {
Ok(value) => value,
Err(_) => return Ok(build_admin_wallets_bad_request_response("请求体格式无效")),
};
let amount_usd = match normalize_admin_wallet_positive_amount(payload.amount_usd, "amount_usd")
{
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let payment_method = match normalize_admin_wallet_payment_method(payload.payment_method) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let description = match normalize_admin_wallet_description(payload.description) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let Some(existing_wallet) = state
.find_wallet(aether_data::repository::wallet::WalletLookupKey::WalletId(
&wallet_id,
))
.await?
else {
return Ok(build_admin_wallet_not_found_response());
};
if existing_wallet.api_key_id.is_some() {
return Ok(build_admin_wallets_bad_request_response(
ADMIN_WALLETS_API_KEY_RECHARGE_DETAIL,
));
}
let operator_id = admin_wallet_operator_id(request_context);
let has_postgres = state.postgres_pool().is_some();
let Some((wallet, payment_order)) = state
.admin_create_manual_wallet_recharge(
&wallet_id,
amount_usd,
&payment_method,
operator_id.as_deref(),
description.as_deref(),
)
.await?
else {
return if has_postgres {
Ok(build_admin_wallet_not_found_response())
} else {
Ok(build_admin_wallets_data_unavailable_response())
};
};
let owner = resolve_admin_wallet_owner_summary(state, &wallet).await?;
let response = Json(json!({
"wallet": build_admin_wallet_summary_payload(&wallet, &owner),
"payment_order": build_admin_wallet_payment_order_payload(
payment_order.id,
payment_order.order_no,
payment_order.amount_usd,
payment_order.payment_method,
payment_order.status,
unix_secs_to_rfc3339(payment_order.created_at_unix_secs),
payment_order
.credited_at_unix_secs
.and_then(unix_secs_to_rfc3339),
),
}))
.into_response();
Ok(attach_admin_audit_response(
response,
"admin_wallet_manual_recharge_created",
"create_manual_wallet_recharge",
"wallet",
&wallet_id,
))
}
pub(super) async fn build_admin_wallet_process_refund_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
) -> Result<Response<Body>, GatewayError> {
let Some((wallet_id, refund_id)) =
admin_wallet_refund_ids_from_suffix_path(&request_context.request_path, "/process")
else {
return Ok(build_admin_wallets_bad_request_response(
"wallet_id 或 refund_id 无效",
));
};
let Some(existing_wallet) = state
.find_wallet(aether_data::repository::wallet::WalletLookupKey::WalletId(
&wallet_id,
))
.await?
else {
return Ok(build_admin_wallet_not_found_response());
};
if existing_wallet.api_key_id.is_some() {
return Ok(build_admin_wallets_bad_request_response(
ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
));
}
let operator_id = admin_wallet_operator_id(request_context);
match state
.admin_process_wallet_refund(&wallet_id, &refund_id, operator_id.as_deref())
.await?
{
crate::AdminWalletMutationOutcome::Applied((wallet, refund, transaction)) => {
let owner = resolve_admin_wallet_owner_summary(state, &wallet).await?;
let response = Json(json!({
"wallet": build_admin_wallet_summary_payload(&wallet, &owner),
"refund": build_admin_wallet_refund_payload(&wallet, &owner, &refund),
"transaction": build_admin_wallet_transaction_payload(
&wallet,
&owner,
transaction.id,
&transaction.category,
&transaction.reason_code,
transaction.amount,
transaction.balance_before,
transaction.balance_after,
transaction.recharge_balance_before,
transaction.recharge_balance_after,
transaction.gift_balance_before,
transaction.gift_balance_after,
transaction.link_type.as_deref(),
transaction.link_id.as_deref(),
transaction.operator_id.as_deref(),
transaction.description.as_deref(),
unix_secs_to_rfc3339(transaction.created_at_unix_secs),
),
}))
.into_response();
Ok(attach_admin_audit_response(
response,
"admin_wallet_refund_processed",
"process_wallet_refund",
"wallet_refund",
&refund_id,
))
}
crate::AdminWalletMutationOutcome::NotFound => {
Ok(build_admin_wallet_refund_not_found_response())
}
crate::AdminWalletMutationOutcome::Invalid(detail) => {
Ok(build_admin_wallets_bad_request_response(detail))
}
crate::AdminWalletMutationOutcome::Unavailable => {
Ok(build_admin_wallets_data_unavailable_response())
}
}
}
pub(super) async fn build_admin_wallet_complete_refund_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
request_body: Option<&axum::body::Bytes>,
) -> Result<Response<Body>, GatewayError> {
let Some((wallet_id, refund_id)) =
admin_wallet_refund_ids_from_suffix_path(&request_context.request_path, "/complete")
else {
return Ok(build_admin_wallets_bad_request_response(
"wallet_id 或 refund_id 无效",
));
};
let Some(request_body) = request_body else {
return Ok(build_admin_wallets_bad_request_response("请求体不能为空"));
};
let payload = match serde_json::from_slice::<AdminWalletRefundCompleteRequest>(request_body) {
Ok(value) => value,
Err(_) => return Ok(build_admin_wallets_bad_request_response("请求体格式无效")),
};
let gateway_refund_id = match normalize_admin_wallet_optional_text(
payload.gateway_refund_id,
"gateway_refund_id",
128,
) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let payout_reference = match normalize_admin_wallet_optional_text(
payload.payout_reference,
"payout_reference",
255,
) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
if payload
.payout_proof
.as_ref()
.is_some_and(|value| !value.is_object())
{
return Ok(build_admin_wallets_bad_request_response(
"payout_proof 必须为对象",
));
}
let Some(wallet) = state
.find_wallet(aether_data::repository::wallet::WalletLookupKey::WalletId(
&wallet_id,
))
.await?
else {
return Ok(build_admin_wallet_not_found_response());
};
if wallet.api_key_id.is_some() {
return Ok(build_admin_wallets_bad_request_response(
ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
));
}
let owner = resolve_admin_wallet_owner_summary(state, &wallet).await?;
match state
.admin_complete_wallet_refund(
&wallet_id,
&refund_id,
gateway_refund_id.as_deref(),
payout_reference.as_deref(),
payload.payout_proof,
)
.await?
{
crate::AdminWalletMutationOutcome::Applied(refund) => {
let response = Json(json!({
"refund": build_admin_wallet_refund_payload(&wallet, &owner, &refund),
}))
.into_response();
Ok(attach_admin_audit_response(
response,
"admin_wallet_refund_completed",
"complete_wallet_refund",
"wallet_refund",
&refund_id,
))
}
crate::AdminWalletMutationOutcome::NotFound => {
Ok(build_admin_wallet_refund_not_found_response())
}
crate::AdminWalletMutationOutcome::Invalid(detail) => {
let detail = if detail == "refund status must be processing before completion" {
"只有 processing 状态的退款可以标记完成".to_string()
} else {
detail
};
Ok(build_admin_wallets_bad_request_response(detail))
}
crate::AdminWalletMutationOutcome::Unavailable => {
Ok(build_admin_wallets_data_unavailable_response())
}
}
}
pub(super) async fn build_admin_wallet_fail_refund_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
request_body: Option<&axum::body::Bytes>,
) -> Result<Response<Body>, GatewayError> {
let Some((wallet_id, refund_id)) =
admin_wallet_refund_ids_from_suffix_path(&request_context.request_path, "/fail")
else {
return Ok(build_admin_wallets_bad_request_response(
"wallet_id 或 refund_id 无效",
));
};
let Some(request_body) = request_body else {
return Ok(build_admin_wallets_bad_request_response("请求体不能为空"));
};
let payload = match serde_json::from_slice::<AdminWalletRefundFailRequest>(request_body) {
Ok(value) => value,
Err(_) => return Ok(build_admin_wallets_bad_request_response("请求体格式无效")),
};
let reason = match normalize_admin_wallet_required_text(payload.reason, "reason", 500) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let Some(existing_wallet) = state
.find_wallet(aether_data::repository::wallet::WalletLookupKey::WalletId(
&wallet_id,
))
.await?
else {
return Ok(build_admin_wallet_not_found_response());
};
if existing_wallet.api_key_id.is_some() {
return Ok(build_admin_wallets_bad_request_response(
ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
));
}
let operator_id = admin_wallet_operator_id(request_context);
match state
.admin_fail_wallet_refund(&wallet_id, &refund_id, &reason, operator_id.as_deref())
.await?
{
crate::AdminWalletMutationOutcome::Applied((wallet, refund, transaction)) => {
let owner = resolve_admin_wallet_owner_summary(state, &wallet).await?;
let response = Json(json!({
"wallet": build_admin_wallet_summary_payload(&wallet, &owner),
"refund": build_admin_wallet_refund_payload(&wallet, &owner, &refund),
"transaction": transaction.map(|transaction| build_admin_wallet_transaction_payload(
&wallet,
&owner,
transaction.id,
&transaction.category,
&transaction.reason_code,
transaction.amount,
transaction.balance_before,
transaction.balance_after,
transaction.recharge_balance_before,
transaction.recharge_balance_after,
transaction.gift_balance_before,
transaction.gift_balance_after,
transaction.link_type.as_deref(),
transaction.link_id.as_deref(),
transaction.operator_id.as_deref(),
transaction.description.as_deref(),
unix_secs_to_rfc3339(transaction.created_at_unix_secs),
)).unwrap_or(serde_json::Value::Null),
}))
.into_response();
Ok(attach_admin_audit_response(
response,
"admin_wallet_refund_failed",
"fail_wallet_refund",
"wallet_refund",
&refund_id,
))
}
crate::AdminWalletMutationOutcome::NotFound => {
Ok(build_admin_wallet_refund_not_found_response())
}
crate::AdminWalletMutationOutcome::Invalid(detail) => {
Ok(build_admin_wallets_bad_request_response(detail))
}
crate::AdminWalletMutationOutcome::Unavailable => {
Ok(build_admin_wallets_data_unavailable_response())
}
}
}

View File

@@ -0,0 +1,114 @@
use super::super::shared::{
admin_wallet_id_from_suffix_path, admin_wallet_operator_id,
build_admin_wallet_not_found_response, build_admin_wallet_summary_payload,
build_admin_wallet_transaction_payload, build_admin_wallets_bad_request_response,
build_admin_wallets_data_unavailable_response, normalize_admin_wallet_balance_type,
normalize_admin_wallet_description, normalize_admin_wallet_non_zero_amount,
resolve_admin_wallet_owner_summary, AdminWalletAdjustRequest,
ADMIN_WALLETS_API_KEY_GIFT_ADJUST_DETAIL,
};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::{attach_admin_audit_response, unix_secs_to_rfc3339};
use crate::GatewayError;
use axum::{
body::Body,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
pub(in super::super) async fn build_admin_wallet_adjust_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&axum::body::Bytes>,
) -> Result<Response<Body>, GatewayError> {
let Some(wallet_id) = admin_wallet_id_from_suffix_path(request_context.path(), "/adjust")
else {
return Ok(build_admin_wallets_bad_request_response("wallet_id 无效"));
};
let Some(request_body) = request_body else {
return Ok(build_admin_wallets_bad_request_response("请求体不能为空"));
};
let payload = match serde_json::from_slice::<AdminWalletAdjustRequest>(request_body) {
Ok(value) => value,
Err(_) => return Ok(build_admin_wallets_bad_request_response("请求体格式无效")),
};
let amount_usd = match normalize_admin_wallet_non_zero_amount(payload.amount_usd, "amount_usd")
{
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let balance_type = match normalize_admin_wallet_balance_type(payload.balance_type) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let description = match normalize_admin_wallet_description(payload.description) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let Some(existing_wallet) = state
.find_wallet(aether_data::repository::wallet::WalletLookupKey::WalletId(
&wallet_id,
))
.await?
else {
return Ok(build_admin_wallet_not_found_response());
};
if existing_wallet.api_key_id.is_some() && balance_type == "gift" {
return Ok(build_admin_wallets_bad_request_response(
ADMIN_WALLETS_API_KEY_GIFT_ADJUST_DETAIL,
));
}
let operator_id = admin_wallet_operator_id(request_context);
let has_postgres = state.has_postgres_pool();
let Some((wallet, transaction)) = state
.admin_adjust_wallet_balance(
&wallet_id,
amount_usd,
&balance_type,
operator_id.as_deref(),
description.as_deref(),
)
.await?
else {
return if has_postgres {
Ok(build_admin_wallet_not_found_response())
} else {
Ok(build_admin_wallets_data_unavailable_response())
};
};
let owner = resolve_admin_wallet_owner_summary(state, &wallet).await?;
let wallet_payload = build_admin_wallet_summary_payload(&wallet, &owner);
let transaction_payload = build_admin_wallet_transaction_payload(
&wallet,
&owner,
transaction.id,
&transaction.category,
&transaction.reason_code,
transaction.amount,
transaction.balance_before,
transaction.balance_after,
transaction.recharge_balance_before,
transaction.recharge_balance_after,
transaction.gift_balance_before,
transaction.gift_balance_after,
transaction.link_type.as_deref(),
transaction.link_id.as_deref(),
transaction.operator_id.as_deref(),
transaction.description.as_deref(),
unix_secs_to_rfc3339(transaction.created_at_unix_secs),
);
let response = Json(json!({
"wallet": wallet_payload,
"transaction": transaction_payload,
}))
.into_response();
Ok(attach_admin_audit_response(
response,
"admin_wallet_balance_adjusted",
"adjust_wallet_balance",
"wallet",
&wallet_id,
))
}

View File

@@ -0,0 +1,116 @@
use super::super::shared::{
admin_wallet_refund_ids_from_suffix_path, build_admin_wallet_not_found_response,
build_admin_wallet_refund_not_found_response, build_admin_wallet_refund_payload,
build_admin_wallets_bad_request_response, build_admin_wallets_data_unavailable_response,
normalize_admin_wallet_optional_text, resolve_admin_wallet_owner_summary,
AdminWalletRefundCompleteRequest, ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::attach_admin_audit_response;
use crate::GatewayError;
use axum::{
body::Body,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
pub(in super::super) async fn build_admin_wallet_complete_refund_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&axum::body::Bytes>,
) -> Result<Response<Body>, GatewayError> {
let Some((wallet_id, refund_id)) =
admin_wallet_refund_ids_from_suffix_path(request_context.path(), "/complete")
else {
return Ok(build_admin_wallets_bad_request_response(
"wallet_id 或 refund_id 无效",
));
};
let Some(request_body) = request_body else {
return Ok(build_admin_wallets_bad_request_response("请求体不能为空"));
};
let payload = match serde_json::from_slice::<AdminWalletRefundCompleteRequest>(request_body) {
Ok(value) => value,
Err(_) => return Ok(build_admin_wallets_bad_request_response("请求体格式无效")),
};
let gateway_refund_id = match normalize_admin_wallet_optional_text(
payload.gateway_refund_id,
"gateway_refund_id",
128,
) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let payout_reference = match normalize_admin_wallet_optional_text(
payload.payout_reference,
"payout_reference",
255,
) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
if payload
.payout_proof
.as_ref()
.is_some_and(|value| !value.is_object())
{
return Ok(build_admin_wallets_bad_request_response(
"payout_proof 必须为对象",
));
}
let Some(wallet) = state
.find_wallet(aether_data::repository::wallet::WalletLookupKey::WalletId(
&wallet_id,
))
.await?
else {
return Ok(build_admin_wallet_not_found_response());
};
if wallet.api_key_id.is_some() {
return Ok(build_admin_wallets_bad_request_response(
ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
));
}
let owner = resolve_admin_wallet_owner_summary(state, &wallet).await?;
match state
.admin_complete_wallet_refund(
&wallet_id,
&refund_id,
gateway_refund_id.as_deref(),
payout_reference.as_deref(),
payload.payout_proof,
)
.await?
{
crate::AdminWalletMutationOutcome::Applied(refund) => {
let response = Json(json!({
"refund": build_admin_wallet_refund_payload(&wallet, &owner, &refund),
}))
.into_response();
Ok(attach_admin_audit_response(
response,
"admin_wallet_refund_completed",
"complete_wallet_refund",
"wallet_refund",
&refund_id,
))
}
crate::AdminWalletMutationOutcome::NotFound => {
Ok(build_admin_wallet_refund_not_found_response())
}
crate::AdminWalletMutationOutcome::Invalid(detail) => {
let detail = if detail == "refund status must be processing before completion" {
"只有 processing 状态的退款可以标记完成".to_string()
} else {
detail
};
Ok(build_admin_wallets_bad_request_response(detail))
}
crate::AdminWalletMutationOutcome::Unavailable => {
Ok(build_admin_wallets_data_unavailable_response())
}
}
}

View File

@@ -0,0 +1,111 @@
use super::super::shared::{
admin_wallet_operator_id, admin_wallet_refund_ids_from_suffix_path,
build_admin_wallet_not_found_response, build_admin_wallet_refund_not_found_response,
build_admin_wallet_refund_payload, build_admin_wallet_summary_payload,
build_admin_wallet_transaction_payload, build_admin_wallets_bad_request_response,
build_admin_wallets_data_unavailable_response, normalize_admin_wallet_required_text,
resolve_admin_wallet_owner_summary, AdminWalletRefundFailRequest,
ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::{attach_admin_audit_response, unix_secs_to_rfc3339};
use crate::GatewayError;
use axum::{
body::Body,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
pub(in super::super) async fn build_admin_wallet_fail_refund_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&axum::body::Bytes>,
) -> Result<Response<Body>, GatewayError> {
let Some((wallet_id, refund_id)) =
admin_wallet_refund_ids_from_suffix_path(request_context.path(), "/fail")
else {
return Ok(build_admin_wallets_bad_request_response(
"wallet_id 或 refund_id 无效",
));
};
let Some(request_body) = request_body else {
return Ok(build_admin_wallets_bad_request_response("请求体不能为空"));
};
let payload = match serde_json::from_slice::<AdminWalletRefundFailRequest>(request_body) {
Ok(value) => value,
Err(_) => return Ok(build_admin_wallets_bad_request_response("请求体格式无效")),
};
let reason = match normalize_admin_wallet_required_text(payload.reason, "reason", 500) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let Some(existing_wallet) = state
.find_wallet(aether_data::repository::wallet::WalletLookupKey::WalletId(
&wallet_id,
))
.await?
else {
return Ok(build_admin_wallet_not_found_response());
};
if existing_wallet.api_key_id.is_some() {
return Ok(build_admin_wallets_bad_request_response(
ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
));
}
let operator_id = admin_wallet_operator_id(request_context);
match state
.admin_fail_wallet_refund(&wallet_id, &refund_id, &reason, operator_id.as_deref())
.await?
{
crate::AdminWalletMutationOutcome::Applied((wallet, refund, transaction)) => {
let owner = resolve_admin_wallet_owner_summary(state, &wallet).await?;
let response = Json(json!({
"wallet": build_admin_wallet_summary_payload(&wallet, &owner),
"refund": build_admin_wallet_refund_payload(&wallet, &owner, &refund),
"transaction": transaction
.map(|transaction| {
build_admin_wallet_transaction_payload(
&wallet,
&owner,
transaction.id,
&transaction.category,
&transaction.reason_code,
transaction.amount,
transaction.balance_before,
transaction.balance_after,
transaction.recharge_balance_before,
transaction.recharge_balance_after,
transaction.gift_balance_before,
transaction.gift_balance_after,
transaction.link_type.as_deref(),
transaction.link_id.as_deref(),
transaction.operator_id.as_deref(),
transaction.description.as_deref(),
unix_secs_to_rfc3339(transaction.created_at_unix_secs),
)
})
.unwrap_or(serde_json::Value::Null),
}))
.into_response();
Ok(attach_admin_audit_response(
response,
"admin_wallet_refund_failed",
"fail_wallet_refund",
"wallet_refund",
&refund_id,
))
}
crate::AdminWalletMutationOutcome::NotFound => {
Ok(build_admin_wallet_refund_not_found_response())
}
crate::AdminWalletMutationOutcome::Invalid(detail) => {
Ok(build_admin_wallets_bad_request_response(detail))
}
crate::AdminWalletMutationOutcome::Unavailable => {
Ok(build_admin_wallets_data_unavailable_response())
}
}
}

View File

@@ -0,0 +1,11 @@
mod adjust;
mod complete_refund;
mod fail_refund;
mod process_refund;
mod recharge;
pub(super) use adjust::build_admin_wallet_adjust_response;
pub(super) use complete_refund::build_admin_wallet_complete_refund_response;
pub(super) use fail_refund::build_admin_wallet_fail_refund_response;
pub(super) use process_refund::build_admin_wallet_process_refund_response;
pub(super) use recharge::build_admin_wallet_recharge_response;

View File

@@ -0,0 +1,94 @@
use super::super::shared::{
admin_wallet_operator_id, admin_wallet_refund_ids_from_suffix_path,
build_admin_wallet_not_found_response, build_admin_wallet_refund_not_found_response,
build_admin_wallet_refund_payload, build_admin_wallet_summary_payload,
build_admin_wallet_transaction_payload, build_admin_wallets_bad_request_response,
build_admin_wallets_data_unavailable_response, resolve_admin_wallet_owner_summary,
ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::{attach_admin_audit_response, unix_secs_to_rfc3339};
use crate::GatewayError;
use axum::{
body::Body,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
pub(in super::super) async fn build_admin_wallet_process_refund_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
let Some((wallet_id, refund_id)) =
admin_wallet_refund_ids_from_suffix_path(request_context.path(), "/process")
else {
return Ok(build_admin_wallets_bad_request_response(
"wallet_id 或 refund_id 无效",
));
};
let Some(existing_wallet) = state
.find_wallet(aether_data::repository::wallet::WalletLookupKey::WalletId(
&wallet_id,
))
.await?
else {
return Ok(build_admin_wallet_not_found_response());
};
if existing_wallet.api_key_id.is_some() {
return Ok(build_admin_wallets_bad_request_response(
ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
));
}
let operator_id = admin_wallet_operator_id(request_context);
match state
.admin_process_wallet_refund(&wallet_id, &refund_id, operator_id.as_deref())
.await?
{
crate::AdminWalletMutationOutcome::Applied((wallet, refund, transaction)) => {
let owner = resolve_admin_wallet_owner_summary(state, &wallet).await?;
let response = Json(json!({
"wallet": build_admin_wallet_summary_payload(&wallet, &owner),
"refund": build_admin_wallet_refund_payload(&wallet, &owner, &refund),
"transaction": build_admin_wallet_transaction_payload(
&wallet,
&owner,
transaction.id,
&transaction.category,
&transaction.reason_code,
transaction.amount,
transaction.balance_before,
transaction.balance_after,
transaction.recharge_balance_before,
transaction.recharge_balance_after,
transaction.gift_balance_before,
transaction.gift_balance_after,
transaction.link_type.as_deref(),
transaction.link_id.as_deref(),
transaction.operator_id.as_deref(),
transaction.description.as_deref(),
unix_secs_to_rfc3339(transaction.created_at_unix_secs),
),
}))
.into_response();
Ok(attach_admin_audit_response(
response,
"admin_wallet_refund_processed",
"process_wallet_refund",
"wallet_refund",
&refund_id,
))
}
crate::AdminWalletMutationOutcome::NotFound => {
Ok(build_admin_wallet_refund_not_found_response())
}
crate::AdminWalletMutationOutcome::Invalid(detail) => {
Ok(build_admin_wallets_bad_request_response(detail))
}
crate::AdminWalletMutationOutcome::Unavailable => {
Ok(build_admin_wallets_data_unavailable_response())
}
}
}

View File

@@ -0,0 +1,104 @@
use super::super::shared::{
admin_wallet_id_from_suffix_path, admin_wallet_operator_id,
build_admin_wallet_not_found_response, build_admin_wallet_payment_order_payload,
build_admin_wallet_summary_payload, build_admin_wallets_bad_request_response,
build_admin_wallets_data_unavailable_response, normalize_admin_wallet_description,
normalize_admin_wallet_payment_method, normalize_admin_wallet_positive_amount,
resolve_admin_wallet_owner_summary, AdminWalletRechargeRequest,
ADMIN_WALLETS_API_KEY_RECHARGE_DETAIL,
};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::{attach_admin_audit_response, unix_secs_to_rfc3339};
use crate::GatewayError;
use axum::{
body::Body,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
pub(in super::super) async fn build_admin_wallet_recharge_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&axum::body::Bytes>,
) -> Result<Response<Body>, GatewayError> {
let Some(wallet_id) = admin_wallet_id_from_suffix_path(request_context.path(), "/recharge")
else {
return Ok(build_admin_wallets_bad_request_response("wallet_id 无效"));
};
let Some(request_body) = request_body else {
return Ok(build_admin_wallets_bad_request_response("请求体不能为空"));
};
let payload = match serde_json::from_slice::<AdminWalletRechargeRequest>(request_body) {
Ok(value) => value,
Err(_) => return Ok(build_admin_wallets_bad_request_response("请求体格式无效")),
};
let amount_usd = match normalize_admin_wallet_positive_amount(payload.amount_usd, "amount_usd")
{
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let payment_method = match normalize_admin_wallet_payment_method(payload.payment_method) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let description = match normalize_admin_wallet_description(payload.description) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let Some(existing_wallet) = state
.find_wallet(aether_data::repository::wallet::WalletLookupKey::WalletId(
&wallet_id,
))
.await?
else {
return Ok(build_admin_wallet_not_found_response());
};
if existing_wallet.api_key_id.is_some() {
return Ok(build_admin_wallets_bad_request_response(
ADMIN_WALLETS_API_KEY_RECHARGE_DETAIL,
));
}
let operator_id = admin_wallet_operator_id(request_context);
let has_postgres = state.has_postgres_pool();
let Some((wallet, payment_order)) = state
.admin_create_manual_wallet_recharge(
&wallet_id,
amount_usd,
&payment_method,
operator_id.as_deref(),
description.as_deref(),
)
.await?
else {
return if has_postgres {
Ok(build_admin_wallet_not_found_response())
} else {
Ok(build_admin_wallets_data_unavailable_response())
};
};
let owner = resolve_admin_wallet_owner_summary(state, &wallet).await?;
let response = Json(json!({
"wallet": build_admin_wallet_summary_payload(&wallet, &owner),
"payment_order": build_admin_wallet_payment_order_payload(
payment_order.id,
payment_order.order_no,
payment_order.amount_usd,
payment_order.payment_method,
payment_order.status,
unix_secs_to_rfc3339(payment_order.created_at_unix_secs),
payment_order
.credited_at_unix_secs
.and_then(unix_secs_to_rfc3339),
),
}))
.into_response();
Ok(attach_admin_audit_response(
response,
"admin_wallet_manual_recharge_created",
"create_manual_wallet_recharge",
"wallet",
&wallet_id,
))
}

View File

@@ -1,388 +0,0 @@
use super::shared::{
admin_wallet_id_from_detail_path, admin_wallet_id_from_suffix_path,
build_admin_wallet_not_found_response, build_admin_wallet_refund_payload,
build_admin_wallet_summary_payload, build_admin_wallets_bad_request_response,
parse_admin_wallets_limit, parse_admin_wallets_offset, parse_admin_wallets_owner_type_filter,
resolve_admin_wallet_owner_summary, wallet_owner_summary_from_fields,
ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
};
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::shared::{query_param_value, unix_secs_to_rfc3339};
use crate::{AppState, GatewayError};
use axum::{
body::Body,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
pub(super) async fn build_admin_wallet_detail_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
) -> Result<Response<Body>, GatewayError> {
let Some(wallet_id) = admin_wallet_id_from_detail_path(&request_context.request_path) else {
return Ok(build_admin_wallets_bad_request_response("wallet_id 无效"));
};
let Some(wallet) = state
.find_wallet(aether_data::repository::wallet::WalletLookupKey::WalletId(
&wallet_id,
))
.await?
else {
return Ok(build_admin_wallet_not_found_response());
};
let owner = resolve_admin_wallet_owner_summary(state, &wallet).await?;
let mut payload = build_admin_wallet_summary_payload(&wallet, &owner);
if let Some(object) = payload.as_object_mut() {
object.insert("pending_refund_count".to_string(), serde_json::Value::Null);
}
Ok(Json(payload).into_response())
}
pub(super) async fn build_admin_wallet_list_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
) -> Result<Response<Body>, GatewayError> {
let query = request_context.request_query_string.as_deref();
let limit = match parse_admin_wallets_limit(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let offset = match parse_admin_wallets_offset(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let status = query_param_value(query, "status");
let owner_type = parse_admin_wallets_owner_type_filter(query);
let (wallets, total) = state
.list_admin_wallets(status.as_deref(), owner_type.as_deref(), limit, offset)
.await?;
let items = wallets
.into_iter()
.map(|wallet| {
let owner = wallet_owner_summary_from_fields(
wallet.user_id.as_deref(),
wallet.user_name.clone(),
wallet.api_key_id.as_deref(),
wallet.api_key_name.clone(),
);
json!({
"id": wallet.id,
"user_id": wallet.user_id,
"api_key_id": wallet.api_key_id,
"owner_type": owner.owner_type,
"owner_name": owner.owner_name,
"balance": wallet.balance + wallet.gift_balance,
"recharge_balance": wallet.balance,
"gift_balance": wallet.gift_balance,
"refundable_balance": wallet.balance,
"currency": wallet.currency,
"status": wallet.status,
"limit_mode": wallet.limit_mode.clone(),
"unlimited": wallet.limit_mode.eq_ignore_ascii_case("unlimited"),
"total_recharged": wallet.total_recharged,
"total_consumed": wallet.total_consumed,
"total_refunded": wallet.total_refunded,
"total_adjusted": wallet.total_adjusted,
"created_at": wallet.created_at_unix_secs.and_then(unix_secs_to_rfc3339),
"updated_at": wallet.updated_at_unix_secs.and_then(unix_secs_to_rfc3339),
})
})
.collect::<Vec<_>>();
Ok(Json(json!({
"items": items,
"total": total,
"limit": limit,
"offset": offset,
}))
.into_response())
}
pub(super) async fn build_admin_wallet_ledger_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
) -> Result<Response<Body>, GatewayError> {
let query = request_context.request_query_string.as_deref();
let limit = match parse_admin_wallets_limit(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let offset = match parse_admin_wallets_offset(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let category = query_param_value(query, "category");
let reason_code = query_param_value(query, "reason_code");
let owner_type = parse_admin_wallets_owner_type_filter(query);
let (ledger, total) = state
.list_admin_wallet_ledger(
category.as_deref(),
reason_code.as_deref(),
owner_type.as_deref(),
limit,
offset,
)
.await?;
let items = ledger
.into_iter()
.map(|entry| {
let owner = wallet_owner_summary_from_fields(
entry.wallet_user_id.as_deref(),
entry.wallet_user_name.clone(),
entry.wallet_api_key_id.as_deref(),
entry.api_key_name.clone(),
);
json!({
"id": entry.id,
"wallet_id": entry.wallet_id,
"owner_type": owner.owner_type,
"owner_name": owner.owner_name,
"wallet_status": entry.wallet_status,
"category": entry.category,
"reason_code": entry.reason_code,
"amount": entry.amount,
"balance_before": entry.balance_before,
"balance_after": entry.balance_after,
"recharge_balance_before": entry.recharge_balance_before,
"recharge_balance_after": entry.recharge_balance_after,
"gift_balance_before": entry.gift_balance_before,
"gift_balance_after": entry.gift_balance_after,
"link_type": entry.link_type,
"link_id": entry.link_id,
"operator_id": entry.operator_id,
"operator_name": entry.operator_name,
"operator_email": entry.operator_email,
"description": entry.description,
"created_at": entry.created_at_unix_secs.and_then(unix_secs_to_rfc3339),
})
})
.collect::<Vec<_>>();
Ok(Json(json!({
"items": items,
"total": total,
"limit": limit,
"offset": offset,
}))
.into_response())
}
pub(super) async fn build_admin_wallet_refund_requests_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
) -> Result<Response<Body>, GatewayError> {
let query = request_context.request_query_string.as_deref();
let limit = match parse_admin_wallets_limit(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let offset = match parse_admin_wallets_offset(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let status = query_param_value(query, "status");
let owner_type = parse_admin_wallets_owner_type_filter(query);
if owner_type.as_deref() == Some("api_key") {
return Ok(build_admin_wallets_bad_request_response(
ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
));
}
let (refunds, total) = state
.list_admin_wallet_refund_requests(status.as_deref(), limit, offset)
.await?;
let mut items = Vec::with_capacity(refunds.len());
for refund in refunds {
let mut owner = wallet_owner_summary_from_fields(
refund.wallet_user_id.as_deref(),
refund.wallet_user_name.clone(),
refund.wallet_api_key_id.as_deref(),
refund.api_key_name.clone(),
);
if owner.owner_name.is_none() {
if let Some(wallet) = state
.find_wallet(aether_data::repository::wallet::WalletLookupKey::WalletId(
&refund.wallet_id,
))
.await?
{
owner = resolve_admin_wallet_owner_summary(state, &wallet).await?;
}
}
items.push(json!({
"id": refund.id,
"refund_no": refund.refund_no,
"wallet_id": refund.wallet_id,
"owner_type": owner.owner_type,
"owner_name": owner.owner_name,
"wallet_status": refund.wallet_status,
"user_id": refund.user_id,
"payment_order_id": refund.payment_order_id,
"source_type": refund.source_type,
"source_id": refund.source_id,
"refund_mode": refund.refund_mode,
"amount_usd": refund.amount_usd,
"status": refund.status,
"reason": refund.reason,
"failure_reason": refund.failure_reason,
"gateway_refund_id": refund.gateway_refund_id,
"payout_method": refund.payout_method,
"payout_reference": refund.payout_reference,
"payout_proof": refund.payout_proof,
"requested_by": refund.requested_by,
"approved_by": refund.approved_by,
"processed_by": refund.processed_by,
"created_at": refund.created_at_unix_secs.and_then(unix_secs_to_rfc3339),
"updated_at": refund.updated_at_unix_secs.and_then(unix_secs_to_rfc3339),
"processed_at": refund.processed_at_unix_secs.and_then(unix_secs_to_rfc3339),
"completed_at": refund.completed_at_unix_secs.and_then(unix_secs_to_rfc3339),
}));
}
Ok(Json(json!({
"items": items,
"total": total,
"limit": limit,
"offset": offset,
}))
.into_response())
}
pub(super) async fn build_admin_wallet_transactions_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
) -> Result<Response<Body>, GatewayError> {
let Some(wallet_id) =
admin_wallet_id_from_suffix_path(&request_context.request_path, "/transactions")
else {
return Ok(build_admin_wallets_bad_request_response("wallet_id 无效"));
};
let limit = match parse_admin_wallets_limit(request_context.request_query_string.as_deref()) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let offset = match parse_admin_wallets_offset(request_context.request_query_string.as_deref()) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let Some(wallet) = state
.find_wallet(aether_data::repository::wallet::WalletLookupKey::WalletId(
&wallet_id,
))
.await?
else {
return Ok(build_admin_wallet_not_found_response());
};
let owner = resolve_admin_wallet_owner_summary(state, &wallet).await?;
let wallet_payload = build_admin_wallet_summary_payload(&wallet, &owner);
let (transactions, total) = state
.list_admin_wallet_transactions(&wallet.id, limit, offset)
.await?;
let mut items = Vec::with_capacity(transactions.len());
for transaction in transactions {
let (operator_name, operator_email) =
if transaction.operator_name.is_some() || transaction.operator_email.is_some() {
(transaction.operator_name, transaction.operator_email)
} else {
match transaction.operator_id.as_deref() {
Some(operator_id) => state
.find_user_auth_by_id(operator_id)
.await?
.map(|user| (Some(user.username), user.email))
.unwrap_or((None, None)),
None => (None, None),
}
};
items.push(json!({
"id": transaction.id,
"wallet_id": transaction.wallet_id,
"owner_type": owner.owner_type,
"owner_name": owner.owner_name.clone(),
"wallet_status": wallet.status.clone(),
"category": transaction.category,
"reason_code": transaction.reason_code,
"amount": transaction.amount,
"balance_before": transaction.balance_before,
"balance_after": transaction.balance_after,
"recharge_balance_before": transaction.recharge_balance_before,
"recharge_balance_after": transaction.recharge_balance_after,
"gift_balance_before": transaction.gift_balance_before,
"gift_balance_after": transaction.gift_balance_after,
"link_type": transaction.link_type,
"link_id": transaction.link_id,
"operator_id": transaction.operator_id,
"operator_name": operator_name,
"operator_email": operator_email,
"description": transaction.description,
"created_at": transaction.created_at_unix_secs.and_then(unix_secs_to_rfc3339),
}));
}
Ok(Json(json!({
"wallet": wallet_payload,
"items": items,
"total": total,
"limit": limit,
"offset": offset,
}))
.into_response())
}
pub(super) async fn build_admin_wallet_refunds_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
) -> Result<Response<Body>, GatewayError> {
let Some(wallet_id) =
admin_wallet_id_from_suffix_path(&request_context.request_path, "/refunds")
else {
return Ok(build_admin_wallets_bad_request_response("wallet_id 无效"));
};
let limit = match parse_admin_wallets_limit(request_context.request_query_string.as_deref()) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let offset = match parse_admin_wallets_offset(request_context.request_query_string.as_deref()) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let Some(wallet) = state
.find_wallet(aether_data::repository::wallet::WalletLookupKey::WalletId(
&wallet_id,
))
.await?
else {
return Ok(build_admin_wallet_not_found_response());
};
if wallet.api_key_id.is_some() {
return Ok(build_admin_wallets_bad_request_response(
ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
));
}
let owner = resolve_admin_wallet_owner_summary(state, &wallet).await?;
let wallet_payload = build_admin_wallet_summary_payload(&wallet, &owner);
let (refunds, total) = state
.list_admin_wallet_refunds(&wallet.id, limit, offset)
.await?;
let items = refunds
.into_iter()
.map(|refund| build_admin_wallet_refund_payload(&wallet, &owner, &refund))
.collect::<Vec<_>>();
Ok(Json(json!({
"wallet": wallet_payload,
"items": items,
"total": total,
"limit": limit,
"offset": offset,
}))
.into_response())
}

View File

@@ -0,0 +1,37 @@
use super::super::shared::{
admin_wallet_id_from_detail_path, build_admin_wallet_not_found_response,
build_admin_wallet_summary_payload, build_admin_wallets_bad_request_response,
resolve_admin_wallet_owner_summary,
};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::GatewayError;
use axum::{
body::Body,
response::{IntoResponse, Response},
Json,
};
pub(in super::super) async fn build_admin_wallet_detail_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
let Some(wallet_id) = admin_wallet_id_from_detail_path(request_context.path()) else {
return Ok(build_admin_wallets_bad_request_response("wallet_id 无效"));
};
let Some(wallet) = state
.find_wallet(aether_data::repository::wallet::WalletLookupKey::WalletId(
&wallet_id,
))
.await?
else {
return Ok(build_admin_wallet_not_found_response());
};
let owner = resolve_admin_wallet_owner_summary(state, &wallet).await?;
let mut payload = build_admin_wallet_summary_payload(&wallet, &owner);
if let Some(object) = payload.as_object_mut() {
object.insert("pending_refund_count".to_string(), serde_json::Value::Null);
}
Ok(Json(payload).into_response())
}

View File

@@ -0,0 +1,84 @@
use super::super::shared::{
build_admin_wallets_bad_request_response, parse_admin_wallets_limit,
parse_admin_wallets_offset, parse_admin_wallets_owner_type_filter,
wallet_owner_summary_from_fields,
};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::{query_param_value, unix_secs_to_rfc3339};
use crate::GatewayError;
use axum::{
body::Body,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
pub(in super::super) async fn build_admin_wallet_ledger_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
let query = request_context.query_string();
let limit = match parse_admin_wallets_limit(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let offset = match parse_admin_wallets_offset(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let category = query_param_value(query, "category");
let reason_code = query_param_value(query, "reason_code");
let owner_type = parse_admin_wallets_owner_type_filter(query);
let (ledger, total) = state
.list_admin_wallet_ledger(
category.as_deref(),
reason_code.as_deref(),
owner_type.as_deref(),
limit,
offset,
)
.await?;
let items = ledger
.into_iter()
.map(|entry| {
let owner = wallet_owner_summary_from_fields(
entry.wallet_user_id.as_deref(),
entry.wallet_user_name.clone(),
entry.wallet_api_key_id.as_deref(),
entry.api_key_name.clone(),
);
json!({
"id": entry.id,
"wallet_id": entry.wallet_id,
"owner_type": owner.owner_type,
"owner_name": owner.owner_name,
"wallet_status": entry.wallet_status,
"category": entry.category,
"reason_code": entry.reason_code,
"amount": entry.amount,
"balance_before": entry.balance_before,
"balance_after": entry.balance_after,
"recharge_balance_before": entry.recharge_balance_before,
"recharge_balance_after": entry.recharge_balance_after,
"gift_balance_before": entry.gift_balance_before,
"gift_balance_after": entry.gift_balance_after,
"link_type": entry.link_type,
"link_id": entry.link_id,
"operator_id": entry.operator_id,
"operator_name": entry.operator_name,
"operator_email": entry.operator_email,
"description": entry.description,
"created_at": entry.created_at_unix_secs.and_then(unix_secs_to_rfc3339),
})
})
.collect::<Vec<_>>();
Ok(Json(json!({
"items": items,
"total": total,
"limit": limit,
"offset": offset,
}))
.into_response())
}

View File

@@ -0,0 +1,75 @@
use super::super::shared::{
build_admin_wallets_bad_request_response, parse_admin_wallets_limit,
parse_admin_wallets_offset, parse_admin_wallets_owner_type_filter,
wallet_owner_summary_from_fields,
};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::{query_param_value, unix_secs_to_rfc3339};
use crate::GatewayError;
use axum::{
body::Body,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
pub(in super::super) async fn build_admin_wallet_list_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
let query = request_context.query_string();
let limit = match parse_admin_wallets_limit(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let offset = match parse_admin_wallets_offset(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let status = query_param_value(query, "status");
let owner_type = parse_admin_wallets_owner_type_filter(query);
let (wallets, total) = state
.list_admin_wallets(status.as_deref(), owner_type.as_deref(), limit, offset)
.await?;
let items = wallets
.into_iter()
.map(|wallet| {
let owner = wallet_owner_summary_from_fields(
wallet.user_id.as_deref(),
wallet.user_name.clone(),
wallet.api_key_id.as_deref(),
wallet.api_key_name.clone(),
);
json!({
"id": wallet.id,
"user_id": wallet.user_id,
"api_key_id": wallet.api_key_id,
"owner_type": owner.owner_type,
"owner_name": owner.owner_name,
"balance": wallet.balance + wallet.gift_balance,
"recharge_balance": wallet.balance,
"gift_balance": wallet.gift_balance,
"refundable_balance": wallet.balance,
"currency": wallet.currency,
"status": wallet.status,
"limit_mode": wallet.limit_mode.clone(),
"unlimited": wallet.limit_mode.eq_ignore_ascii_case("unlimited"),
"total_recharged": wallet.total_recharged,
"total_consumed": wallet.total_consumed,
"total_refunded": wallet.total_refunded,
"total_adjusted": wallet.total_adjusted,
"created_at": wallet.created_at_unix_secs.and_then(unix_secs_to_rfc3339),
"updated_at": wallet.updated_at_unix_secs.and_then(unix_secs_to_rfc3339),
})
})
.collect::<Vec<_>>();
Ok(Json(json!({
"items": items,
"total": total,
"limit": limit,
"offset": offset,
}))
.into_response())
}

View File

@@ -0,0 +1,13 @@
mod detail;
mod ledger;
mod list;
mod refund_requests;
mod refunds;
mod transactions;
pub(super) use detail::build_admin_wallet_detail_response;
pub(super) use ledger::build_admin_wallet_ledger_response;
pub(super) use list::build_admin_wallet_list_response;
pub(super) use refund_requests::build_admin_wallet_refund_requests_response;
pub(super) use refunds::build_admin_wallet_refunds_response;
pub(super) use transactions::build_admin_wallet_transactions_response;

View File

@@ -0,0 +1,96 @@
use super::super::shared::{
build_admin_wallets_bad_request_response, parse_admin_wallets_limit,
parse_admin_wallets_offset, parse_admin_wallets_owner_type_filter,
resolve_admin_wallet_owner_summary, wallet_owner_summary_from_fields,
ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::{query_param_value, unix_secs_to_rfc3339};
use crate::GatewayError;
use axum::{
body::Body,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
pub(in super::super) async fn build_admin_wallet_refund_requests_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
let query = request_context.query_string();
let limit = match parse_admin_wallets_limit(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let offset = match parse_admin_wallets_offset(query) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let status = query_param_value(query, "status");
let owner_type = parse_admin_wallets_owner_type_filter(query);
if owner_type.as_deref() == Some("api_key") {
return Ok(build_admin_wallets_bad_request_response(
ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
));
}
let (refunds, total) = state
.list_admin_wallet_refund_requests(status.as_deref(), limit, offset)
.await?;
let mut items = Vec::with_capacity(refunds.len());
for refund in refunds {
let mut owner = wallet_owner_summary_from_fields(
refund.wallet_user_id.as_deref(),
refund.wallet_user_name.clone(),
refund.wallet_api_key_id.as_deref(),
refund.api_key_name.clone(),
);
if owner.owner_name.is_none() {
if let Some(wallet) = state
.find_wallet(aether_data::repository::wallet::WalletLookupKey::WalletId(
&refund.wallet_id,
))
.await?
{
owner = resolve_admin_wallet_owner_summary(state, &wallet).await?;
}
}
items.push(json!({
"id": refund.id,
"refund_no": refund.refund_no,
"wallet_id": refund.wallet_id,
"owner_type": owner.owner_type,
"owner_name": owner.owner_name,
"wallet_status": refund.wallet_status,
"user_id": refund.user_id,
"payment_order_id": refund.payment_order_id,
"source_type": refund.source_type,
"source_id": refund.source_id,
"refund_mode": refund.refund_mode,
"amount_usd": refund.amount_usd,
"status": refund.status,
"reason": refund.reason,
"failure_reason": refund.failure_reason,
"gateway_refund_id": refund.gateway_refund_id,
"payout_method": refund.payout_method,
"payout_reference": refund.payout_reference,
"payout_proof": refund.payout_proof,
"requested_by": refund.requested_by,
"approved_by": refund.approved_by,
"processed_by": refund.processed_by,
"created_at": refund.created_at_unix_secs.and_then(unix_secs_to_rfc3339),
"updated_at": refund.updated_at_unix_secs.and_then(unix_secs_to_rfc3339),
"processed_at": refund.processed_at_unix_secs.and_then(unix_secs_to_rfc3339),
"completed_at": refund.completed_at_unix_secs.and_then(unix_secs_to_rfc3339),
}));
}
Ok(Json(json!({
"items": items,
"total": total,
"limit": limit,
"offset": offset,
}))
.into_response())
}

View File

@@ -0,0 +1,66 @@
use super::super::shared::{
admin_wallet_id_from_suffix_path, build_admin_wallet_not_found_response,
build_admin_wallet_refund_payload, build_admin_wallet_summary_payload,
build_admin_wallets_bad_request_response, parse_admin_wallets_limit,
parse_admin_wallets_offset, resolve_admin_wallet_owner_summary,
ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::GatewayError;
use axum::{
body::Body,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
pub(in super::super) async fn build_admin_wallet_refunds_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
let Some(wallet_id) = admin_wallet_id_from_suffix_path(request_context.path(), "/refunds")
else {
return Ok(build_admin_wallets_bad_request_response("wallet_id 无效"));
};
let limit = match parse_admin_wallets_limit(request_context.query_string()) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let offset = match parse_admin_wallets_offset(request_context.query_string()) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let Some(wallet) = state
.find_wallet(aether_data::repository::wallet::WalletLookupKey::WalletId(
&wallet_id,
))
.await?
else {
return Ok(build_admin_wallet_not_found_response());
};
if wallet.api_key_id.is_some() {
return Ok(build_admin_wallets_bad_request_response(
ADMIN_WALLETS_API_KEY_REFUND_DETAIL,
));
}
let owner = resolve_admin_wallet_owner_summary(state, &wallet).await?;
let wallet_payload = build_admin_wallet_summary_payload(&wallet, &owner);
let (refunds, total) = state
.list_admin_wallet_refunds(&wallet.id, limit, offset)
.await?;
let items = refunds
.into_iter()
.map(|refund| build_admin_wallet_refund_payload(&wallet, &owner, &refund))
.collect::<Vec<_>>();
Ok(Json(json!({
"wallet": wallet_payload,
"items": items,
"total": total,
"limit": limit,
"offset": offset,
}))
.into_response())
}

View File

@@ -0,0 +1,95 @@
use super::super::shared::{
admin_wallet_id_from_suffix_path, build_admin_wallet_not_found_response,
build_admin_wallet_summary_payload, build_admin_wallets_bad_request_response,
parse_admin_wallets_limit, parse_admin_wallets_offset, resolve_admin_wallet_owner_summary,
};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::unix_secs_to_rfc3339;
use crate::GatewayError;
use axum::{
body::Body,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
pub(in super::super) async fn build_admin_wallet_transactions_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
let Some(wallet_id) = admin_wallet_id_from_suffix_path(request_context.path(), "/transactions")
else {
return Ok(build_admin_wallets_bad_request_response("wallet_id 无效"));
};
let limit = match parse_admin_wallets_limit(request_context.query_string()) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let offset = match parse_admin_wallets_offset(request_context.query_string()) {
Ok(value) => value,
Err(detail) => return Ok(build_admin_wallets_bad_request_response(detail)),
};
let Some(wallet) = state
.find_wallet(aether_data::repository::wallet::WalletLookupKey::WalletId(
&wallet_id,
))
.await?
else {
return Ok(build_admin_wallet_not_found_response());
};
let owner = resolve_admin_wallet_owner_summary(state, &wallet).await?;
let wallet_payload = build_admin_wallet_summary_payload(&wallet, &owner);
let (transactions, total) = state
.list_admin_wallet_transactions(&wallet.id, limit, offset)
.await?;
let mut items = Vec::with_capacity(transactions.len());
for transaction in transactions {
let (operator_name, operator_email) =
if transaction.operator_name.is_some() || transaction.operator_email.is_some() {
(transaction.operator_name, transaction.operator_email)
} else {
match transaction.operator_id.as_deref() {
Some(operator_id) => state
.find_user_auth_by_id(operator_id)
.await?
.map(|user| (Some(user.username), user.email))
.unwrap_or((None, None)),
None => (None, None),
}
};
items.push(json!({
"id": transaction.id,
"wallet_id": transaction.wallet_id,
"owner_type": owner.owner_type,
"owner_name": owner.owner_name.clone(),
"wallet_status": wallet.status.clone(),
"category": transaction.category,
"reason_code": transaction.reason_code,
"amount": transaction.amount,
"balance_before": transaction.balance_before,
"balance_after": transaction.balance_after,
"recharge_balance_before": transaction.recharge_balance_before,
"recharge_balance_after": transaction.recharge_balance_after,
"gift_balance_before": transaction.gift_balance_before,
"gift_balance_after": transaction.gift_balance_after,
"link_type": transaction.link_type,
"link_id": transaction.link_id,
"operator_id": transaction.operator_id,
"operator_name": operator_name,
"operator_email": operator_email,
"description": transaction.description,
"created_at": transaction.created_at_unix_secs.and_then(unix_secs_to_rfc3339),
}));
}
Ok(Json(json!({
"wallet": wallet_payload,
"items": items,
"total": total,
"limit": limit,
"offset": offset,
}))
.into_response())
}

View File

@@ -9,16 +9,16 @@ use super::reads::{
build_admin_wallet_refunds_response, build_admin_wallet_transactions_response,
};
use super::shared::build_admin_wallets_data_unavailable_response;
use crate::control::GatewayPublicRequestContext;
use crate::{AppState, GatewayError};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::GatewayError;
use axum::{body::Body, http, response::Response};
pub(super) async fn maybe_build_local_admin_wallets_routes_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&axum::body::Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
let Some(decision) = request_context.control_decision.as_ref() else {
let Some(decision) = request_context.decision() else {
return Ok(None);
};
@@ -26,31 +26,31 @@ pub(super) async fn maybe_build_local_admin_wallets_routes_response(
return Ok(None);
}
let path = request_context.request_path.as_str();
let is_wallets_route = (request_context.request_method == http::Method::GET
let path = request_context.path();
let is_wallets_route = (request_context.method() == http::Method::GET
&& matches!(path, "/api/admin/wallets" | "/api/admin/wallets/"))
|| (request_context.request_method == http::Method::GET
|| (request_context.method() == http::Method::GET
&& matches!(
path,
"/api/admin/wallets/ledger" | "/api/admin/wallets/ledger/"
))
|| (request_context.request_method == http::Method::GET
|| (request_context.method() == http::Method::GET
&& matches!(
path,
"/api/admin/wallets/refund-requests" | "/api/admin/wallets/refund-requests/"
))
|| (request_context.request_method == http::Method::GET
|| (request_context.method() == http::Method::GET
&& path.starts_with("/api/admin/wallets/")
&& path.ends_with("/transactions"))
|| (request_context.request_method == http::Method::GET
|| (request_context.method() == http::Method::GET
&& path.starts_with("/api/admin/wallets/")
&& path.ends_with("/refunds"))
|| (request_context.request_method == http::Method::GET
|| (request_context.method() == http::Method::GET
&& path.starts_with("/api/admin/wallets/")
&& !path.ends_with("/transactions")
&& !path.ends_with("/refunds")
&& path.matches('/').count() == 4)
|| (request_context.request_method == http::Method::POST
|| (request_context.method() == http::Method::POST
&& matches!(
decision.route_kind.as_deref(),
Some(
@@ -67,70 +67,70 @@ pub(super) async fn maybe_build_local_admin_wallets_routes_response(
}
if decision.route_kind.as_deref() == Some("wallet_detail")
&& request_context.request_method == http::Method::GET
&& request_context.method() == http::Method::GET
{
return Ok(Some(
build_admin_wallet_detail_response(state, request_context).await?,
));
}
if decision.route_kind.as_deref() == Some("list_wallets")
&& request_context.request_method == http::Method::GET
&& request_context.method() == http::Method::GET
{
return Ok(Some(
build_admin_wallet_list_response(state, request_context).await?,
));
}
if decision.route_kind.as_deref() == Some("ledger")
&& request_context.request_method == http::Method::GET
&& request_context.method() == http::Method::GET
{
return Ok(Some(
build_admin_wallet_ledger_response(state, request_context).await?,
));
}
if decision.route_kind.as_deref() == Some("list_refund_requests")
&& request_context.request_method == http::Method::GET
&& request_context.method() == http::Method::GET
{
return Ok(Some(
build_admin_wallet_refund_requests_response(state, request_context).await?,
));
}
if decision.route_kind.as_deref() == Some("list_wallet_transactions")
&& request_context.request_method == http::Method::GET
&& request_context.method() == http::Method::GET
{
return Ok(Some(
build_admin_wallet_transactions_response(state, request_context).await?,
));
}
if decision.route_kind.as_deref() == Some("list_wallet_refunds")
&& request_context.request_method == http::Method::GET
&& request_context.method() == http::Method::GET
{
return Ok(Some(
build_admin_wallet_refunds_response(state, request_context).await?,
));
}
if decision.route_kind.as_deref() == Some("adjust_balance")
&& request_context.request_method == http::Method::POST
&& request_context.method() == http::Method::POST
{
return Ok(Some(
build_admin_wallet_adjust_response(state, request_context, request_body).await?,
));
}
if decision.route_kind.as_deref() == Some("recharge_balance")
&& request_context.request_method == http::Method::POST
&& request_context.method() == http::Method::POST
{
return Ok(Some(
build_admin_wallet_recharge_response(state, request_context, request_body).await?,
));
}
if decision.route_kind.as_deref() == Some("process_refund")
&& request_context.request_method == http::Method::POST
&& request_context.method() == http::Method::POST
{
return Ok(Some(
build_admin_wallet_process_refund_response(state, request_context).await?,
));
}
if decision.route_kind.as_deref() == Some("complete_refund")
&& request_context.request_method == http::Method::POST
&& request_context.method() == http::Method::POST
{
return Ok(Some(
build_admin_wallet_complete_refund_response(state, request_context, request_body)
@@ -138,7 +138,7 @@ pub(super) async fn maybe_build_local_admin_wallets_routes_response(
));
}
if decision.route_kind.as_deref() == Some("fail_refund")
&& request_context.request_method == http::Method::POST
&& request_context.method() == http::Method::POST
{
return Ok(Some(
build_admin_wallet_fail_refund_response(state, request_context, request_body).await?,

View File

@@ -1,580 +0,0 @@
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::shared::{query_param_value, unix_secs_to_rfc3339};
use crate::{AppState, GatewayError};
use axum::{
body::Body,
http,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
use sqlx::Row;
pub(super) const ADMIN_WALLETS_DATA_UNAVAILABLE_DETAIL: &str = "Admin wallets data unavailable";
pub(super) const ADMIN_WALLETS_API_KEY_REFUND_DETAIL: &str = "独立密钥钱包不支持退款审批";
pub(super) const ADMIN_WALLETS_API_KEY_RECHARGE_DETAIL: &str = "独立密钥钱包不支持充值,请使用调账";
pub(super) const ADMIN_WALLETS_API_KEY_GIFT_ADJUST_DETAIL: &str = "独立密钥钱包不支持赠款调账";
#[derive(Debug, serde::Deserialize)]
pub(super) struct AdminWalletRechargeRequest {
pub(super) amount_usd: f64,
#[serde(default = "default_admin_wallet_payment_method")]
pub(super) payment_method: String,
#[serde(default)]
pub(super) description: Option<String>,
}
#[derive(Debug, serde::Deserialize)]
pub(super) struct AdminWalletAdjustRequest {
pub(super) amount_usd: f64,
#[serde(default = "default_admin_wallet_balance_type")]
pub(super) balance_type: String,
#[serde(default)]
pub(super) description: Option<String>,
}
#[derive(Debug, serde::Deserialize)]
pub(super) struct AdminWalletRefundFailRequest {
pub(super) reason: String,
}
#[derive(Debug, serde::Deserialize)]
pub(super) struct AdminWalletRefundCompleteRequest {
#[serde(default)]
pub(super) gateway_refund_id: Option<String>,
#[serde(default)]
pub(super) payout_reference: Option<String>,
#[serde(default)]
pub(super) payout_proof: Option<serde_json::Value>,
}
fn default_admin_wallet_payment_method() -> String {
"admin_manual".to_string()
}
fn default_admin_wallet_balance_type() -> String {
"recharge".to_string()
}
pub(super) fn build_admin_wallets_data_unavailable_response() -> Response<Body> {
(
http::StatusCode::SERVICE_UNAVAILABLE,
Json(json!({ "detail": ADMIN_WALLETS_DATA_UNAVAILABLE_DETAIL })),
)
.into_response()
}
pub(super) fn build_admin_wallets_bad_request_response(
detail: impl Into<String>,
) -> Response<Body> {
(
http::StatusCode::BAD_REQUEST,
Json(json!({ "detail": detail.into() })),
)
.into_response()
}
pub(super) fn build_admin_wallet_not_found_response() -> Response<Body> {
(
http::StatusCode::NOT_FOUND,
Json(json!({ "detail": "Wallet not found" })),
)
.into_response()
}
pub(super) fn build_admin_wallet_refund_not_found_response() -> Response<Body> {
(
http::StatusCode::NOT_FOUND,
Json(json!({ "detail": "Refund request not found" })),
)
.into_response()
}
pub(super) fn build_admin_wallet_payment_order_payload(
order_id: String,
order_no: String,
amount_usd: f64,
payment_method: String,
status: String,
created_at: Option<String>,
credited_at: Option<String>,
) -> serde_json::Value {
json!({
"id": order_id,
"order_no": order_no,
"amount_usd": amount_usd,
"payment_method": payment_method,
"status": status,
"created_at": created_at,
"credited_at": credited_at,
})
}
#[allow(clippy::too_many_arguments)]
pub(super) fn build_admin_wallet_transaction_payload(
wallet: &aether_data::repository::wallet::StoredWalletSnapshot,
owner: &AdminWalletOwnerSummary,
transaction_id: String,
category: &str,
reason_code: &str,
amount: f64,
balance_before: f64,
balance_after: f64,
recharge_balance_before: f64,
recharge_balance_after: f64,
gift_balance_before: f64,
gift_balance_after: f64,
link_type: Option<&str>,
link_id: Option<&str>,
operator_id: Option<&str>,
description: Option<&str>,
created_at: Option<String>,
) -> serde_json::Value {
json!({
"id": transaction_id,
"wallet_id": wallet.id,
"owner_type": owner.owner_type,
"owner_name": owner.owner_name.clone(),
"wallet_status": wallet.status,
"category": category,
"reason_code": reason_code,
"amount": amount,
"balance_before": balance_before,
"balance_after": balance_after,
"recharge_balance_before": recharge_balance_before,
"recharge_balance_after": recharge_balance_after,
"gift_balance_before": gift_balance_before,
"gift_balance_after": gift_balance_after,
"link_type": link_type,
"link_id": link_id,
"operator_id": operator_id,
"operator_name": serde_json::Value::Null,
"operator_email": serde_json::Value::Null,
"description": description,
"created_at": created_at,
})
}
pub(super) fn admin_wallet_build_order_no(now: chrono::DateTime<chrono::Utc>) -> String {
format!(
"po_{}_{}",
now.format("%Y%m%d%H%M%S%6f"),
&uuid::Uuid::new_v4().simple().to_string()[..12]
)
}
pub(super) fn normalize_admin_wallet_description(
value: Option<String>,
) -> Result<Option<String>, String> {
match value {
None => Ok(None),
Some(value) => {
let trimmed = value.trim();
if trimmed.is_empty() {
return Ok(None);
}
Ok(Some(trimmed.chars().take(500).collect()))
}
}
}
pub(super) fn normalize_admin_wallet_required_text(
value: String,
field_name: &str,
max_len: usize,
) -> Result<String, String> {
let trimmed = value.trim();
if trimmed.is_empty() {
return Err(format!("{field_name} 不能为空"));
}
if trimmed.chars().count() > max_len {
return Err(format!("{field_name} 长度不能超过 {max_len}"));
}
Ok(trimmed.to_string())
}
pub(super) fn normalize_admin_wallet_optional_text(
value: Option<String>,
field_name: &str,
max_len: usize,
) -> Result<Option<String>, String> {
match value {
None => Ok(None),
Some(value) => {
let trimmed = value.trim();
if trimmed.is_empty() {
return Ok(None);
}
if trimmed.chars().count() > max_len {
return Err(format!("{field_name} 长度不能超过 {max_len}"));
}
Ok(Some(trimmed.to_string()))
}
}
}
pub(super) fn normalize_admin_wallet_payment_method(value: String) -> Result<String, String> {
let normalized = value.trim();
if normalized.is_empty() {
return Err("payment_method 不能为空".to_string());
}
Ok(normalized.chars().take(30).collect())
}
pub(super) fn normalize_admin_wallet_balance_type(value: String) -> Result<String, String> {
let normalized = value.trim().to_ascii_lowercase();
match normalized.as_str() {
"recharge" | "gift" => Ok(normalized),
_ => Err("balance_type 必须为 recharge 或 gift".to_string()),
}
}
pub(super) fn normalize_admin_wallet_positive_amount(
value: f64,
field_name: &str,
) -> Result<f64, String> {
if !value.is_finite() || value <= 0.0 {
return Err(format!("{field_name} 必须为大于 0 的有限数字"));
}
Ok(value)
}
pub(super) fn normalize_admin_wallet_non_zero_amount(
value: f64,
field_name: &str,
) -> Result<f64, String> {
if !value.is_finite() || value == 0.0 {
return Err(format!("{field_name} 不能为 0且必须为有限数字"));
}
Ok(value)
}
pub(super) fn admin_wallet_operator_id(
request_context: &GatewayPublicRequestContext,
) -> Option<String> {
request_context
.control_decision
.as_ref()
.and_then(|decision| decision.admin_principal.as_ref())
.map(|principal| principal.user_id.clone())
}
pub(super) fn admin_wallet_recharge_reason_code(payment_method: &str) -> &'static str {
match payment_method {
"card_code" | "gift_code" | "card_recharge" => "topup_card_code",
_ => "topup_admin_manual",
}
}
pub(super) fn admin_wallet_apply_manual_recharge_to_snapshot(
wallet: &mut aether_data::repository::wallet::StoredWalletSnapshot,
amount_usd: f64,
) -> (f64, f64, f64, f64, f64, f64) {
let recharge_before = wallet.balance;
let gift_before = wallet.gift_balance;
let balance_before = recharge_before + gift_before;
wallet.balance += amount_usd;
wallet.total_recharged += amount_usd;
wallet.updated_at_unix_secs = chrono::Utc::now().timestamp().max(0) as u64;
let recharge_after = wallet.balance;
let gift_after = wallet.gift_balance;
let balance_after = recharge_after + gift_after;
(
balance_before,
balance_after,
recharge_before,
recharge_after,
gift_before,
gift_after,
)
}
pub(super) fn admin_wallet_apply_adjust_to_snapshot(
wallet: &mut aether_data::repository::wallet::StoredWalletSnapshot,
amount_usd: f64,
balance_type: &str,
) -> Result<(f64, f64, f64, f64, f64, f64), String> {
if amount_usd == 0.0 {
return Err("adjust amount must not be zero".to_string());
}
if balance_type == "gift" && wallet.api_key_id.is_some() {
return Err(ADMIN_WALLETS_API_KEY_GIFT_ADJUST_DETAIL.to_string());
}
let recharge_before = wallet.balance;
let gift_before = wallet.gift_balance;
let balance_before = recharge_before + gift_before;
let mut recharge_after = recharge_before;
let mut gift_after = gift_before;
if amount_usd > 0.0 {
if balance_type == "gift" {
gift_after += amount_usd;
} else {
recharge_after += amount_usd;
}
} else {
let mut remaining = -amount_usd;
let consume_positive_bucket = |balance: &mut f64, remaining: &mut f64| {
if *remaining <= 0.0 {
return;
}
let available = balance.max(0.0);
let consumed = available.min(*remaining);
*balance -= consumed;
*remaining -= consumed;
};
if balance_type == "gift" {
consume_positive_bucket(&mut gift_after, &mut remaining);
consume_positive_bucket(&mut recharge_after, &mut remaining);
} else {
consume_positive_bucket(&mut recharge_after, &mut remaining);
consume_positive_bucket(&mut gift_after, &mut remaining);
}
if remaining > 0.0 {
recharge_after -= remaining;
}
if gift_after < 0.0 {
return Err("gift balance cannot be negative".to_string());
}
}
wallet.balance = recharge_after;
wallet.gift_balance = gift_after;
wallet.total_adjusted += amount_usd;
wallet.updated_at_unix_secs = chrono::Utc::now().timestamp().max(0) as u64;
Ok((
balance_before,
recharge_after + gift_after,
recharge_before,
recharge_after,
gift_before,
gift_after,
))
}
pub(super) fn admin_wallet_id_from_detail_path(request_path: &str) -> Option<String> {
request_path
.strip_prefix("/api/admin/wallets/")?
.trim()
.trim_matches('/')
.split('/')
.next()
.map(str::trim)
.filter(|value| !value.is_empty())
.filter(|value| !value.contains('/'))
.map(ToOwned::to_owned)
}
pub(super) fn admin_wallet_id_from_suffix_path(request_path: &str, suffix: &str) -> Option<String> {
request_path
.strip_prefix("/api/admin/wallets/")?
.strip_suffix(suffix)
.map(|value| value.trim().trim_matches('/').to_string())
.filter(|value| !value.is_empty() && !value.contains('/'))
}
pub(super) fn admin_wallet_refund_ids_from_suffix_path(
request_path: &str,
suffix: &str,
) -> Option<(String, String)> {
let trimmed = request_path
.strip_prefix("/api/admin/wallets/")?
.strip_suffix(suffix)?
.trim()
.trim_matches('/');
let mut segments = trimmed.split('/');
let wallet_id = segments.next()?.trim();
let literal = segments.next()?.trim();
let refund_id = segments.next()?.trim();
if literal != "refunds"
|| wallet_id.is_empty()
|| refund_id.is_empty()
|| wallet_id.contains('/')
|| refund_id.contains('/')
|| segments.next().is_some()
{
return None;
}
Some((wallet_id.to_string(), refund_id.to_string()))
}
pub(super) fn parse_admin_wallets_limit(query: Option<&str>) -> Result<usize, String> {
match query_param_value(query, "limit") {
Some(value) => {
let parsed = value
.parse::<usize>()
.map_err(|_| "limit must be an integer between 1 and 200".to_string())?;
if (1..=200).contains(&parsed) {
Ok(parsed)
} else {
Err("limit must be an integer between 1 and 200".to_string())
}
}
None => Ok(50),
}
}
pub(super) fn parse_admin_wallets_offset(query: Option<&str>) -> Result<usize, String> {
match query_param_value(query, "offset") {
Some(value) => value
.parse::<usize>()
.map_err(|_| "offset must be a non-negative integer".to_string()),
None => Ok(0),
}
}
pub(super) fn parse_admin_wallets_owner_type_filter(query: Option<&str>) -> Option<String> {
match query_param_value(query, "owner_type") {
Some(value) if value.eq_ignore_ascii_case("user") => Some("user".to_string()),
Some(value) if value.eq_ignore_ascii_case("api_key") => Some("api_key".to_string()),
_ => None,
}
}
pub(super) fn wallet_owner_summary_from_fields(
user_id: Option<&str>,
user_name: Option<String>,
api_key_id: Option<&str>,
api_key_name: Option<String>,
) -> AdminWalletOwnerSummary {
if user_id.is_some() {
return AdminWalletOwnerSummary {
owner_type: "user",
owner_name: user_name,
};
}
if let Some(api_key_id) = api_key_id {
return AdminWalletOwnerSummary {
owner_type: "api_key",
owner_name: api_key_name
.filter(|value| !value.trim().is_empty())
.or_else(|| Some(format!("Key-{}", &api_key_id[..api_key_id.len().min(8)]))),
};
}
AdminWalletOwnerSummary {
owner_type: "orphaned",
owner_name: None,
}
}
pub(super) fn optional_epoch_value(
row: &sqlx::postgres::PgRow,
key: &str,
) -> Result<Option<String>, GatewayError> {
Ok(row
.try_get::<Option<i64>, _>(key)
.map_err(|err| GatewayError::Internal(err.to_string()))?
.and_then(|value| u64::try_from(value).ok())
.and_then(unix_secs_to_rfc3339))
}
#[derive(Clone)]
pub(super) struct AdminWalletOwnerSummary {
pub(super) owner_type: &'static str,
pub(super) owner_name: Option<String>,
}
pub(super) async fn resolve_admin_wallet_owner_summary(
state: &AppState,
wallet: &aether_data::repository::wallet::StoredWalletSnapshot,
) -> Result<AdminWalletOwnerSummary, GatewayError> {
if let Some(user_id) = wallet.user_id.as_deref() {
let user = state.find_user_auth_by_id(user_id).await?;
Ok(AdminWalletOwnerSummary {
owner_type: "user",
owner_name: user.map(|record| record.username),
})
} else if let Some(api_key_id) = wallet.api_key_id.as_deref() {
let api_key_ids = vec![api_key_id.to_string()];
let snapshots = state
.data
.list_auth_api_key_snapshots_by_ids(&api_key_ids)
.await
.map_err(|err| GatewayError::Internal(err.to_string()))?;
let owner_name = snapshots
.into_iter()
.find(|snapshot| snapshot.api_key_id == api_key_id)
.and_then(|snapshot| snapshot.api_key_name)
.filter(|value| !value.trim().is_empty())
.or_else(|| Some(format!("Key-{}", &api_key_id[..api_key_id.len().min(8)])));
Ok(AdminWalletOwnerSummary {
owner_type: "api_key",
owner_name,
})
} else {
Ok(AdminWalletOwnerSummary {
owner_type: "orphaned",
owner_name: None,
})
}
}
pub(super) fn build_admin_wallet_summary_payload(
wallet: &aether_data::repository::wallet::StoredWalletSnapshot,
owner: &AdminWalletOwnerSummary,
) -> serde_json::Value {
json!({
"id": wallet.id.clone(),
"user_id": wallet.user_id.clone(),
"api_key_id": wallet.api_key_id.clone(),
"owner_type": owner.owner_type,
"owner_name": owner.owner_name.clone(),
"balance": wallet.balance + wallet.gift_balance,
"recharge_balance": wallet.balance,
"gift_balance": wallet.gift_balance,
"refundable_balance": wallet.balance,
"currency": wallet.currency.clone(),
"status": wallet.status.clone(),
"limit_mode": wallet.limit_mode.clone(),
"unlimited": wallet.limit_mode.eq_ignore_ascii_case("unlimited"),
"total_recharged": wallet.total_recharged,
"total_consumed": wallet.total_consumed,
"total_refunded": wallet.total_refunded,
"total_adjusted": wallet.total_adjusted,
"created_at": serde_json::Value::Null,
"updated_at": unix_secs_to_rfc3339(wallet.updated_at_unix_secs),
})
}
pub(super) fn build_admin_wallet_refund_payload(
wallet: &aether_data::repository::wallet::StoredWalletSnapshot,
owner: &AdminWalletOwnerSummary,
refund: &crate::AdminWalletRefundRecord,
) -> serde_json::Value {
json!({
"id": refund.id.clone(),
"refund_no": refund.refund_no.clone(),
"wallet_id": refund.wallet_id.clone(),
"owner_type": owner.owner_type,
"owner_name": owner.owner_name.clone(),
"wallet_status": wallet.status.clone(),
"user_id": refund.user_id.clone(),
"payment_order_id": refund.payment_order_id.clone(),
"source_type": refund.source_type.clone(),
"source_id": refund.source_id.clone(),
"refund_mode": refund.refund_mode.clone(),
"amount_usd": refund.amount_usd,
"status": refund.status.clone(),
"reason": refund.reason.clone(),
"failure_reason": refund.failure_reason.clone(),
"gateway_refund_id": refund.gateway_refund_id.clone(),
"payout_method": refund.payout_method.clone(),
"payout_reference": refund.payout_reference.clone(),
"payout_proof": refund.payout_proof.clone(),
"requested_by": refund.requested_by.clone(),
"approved_by": refund.approved_by.clone(),
"processed_by": refund.processed_by.clone(),
"created_at": unix_secs_to_rfc3339(refund.created_at_unix_secs),
"updated_at": unix_secs_to_rfc3339(refund.updated_at_unix_secs),
"processed_at": refund.processed_at_unix_secs.and_then(unix_secs_to_rfc3339),
"completed_at": refund.completed_at_unix_secs.and_then(unix_secs_to_rfc3339),
})
}

View File

@@ -0,0 +1,11 @@
mod normalizers;
mod payloads;
mod requests;
mod responses;
mod support;
pub(super) use normalizers::*;
pub(super) use payloads::*;
pub(super) use requests::*;
pub(super) use responses::*;
pub(super) use support::*;

View File

@@ -0,0 +1,89 @@
pub(in super::super) fn normalize_admin_wallet_description(
value: Option<String>,
) -> Result<Option<String>, String> {
match value {
None => Ok(None),
Some(value) => {
let trimmed = value.trim();
if trimmed.is_empty() {
return Ok(None);
}
Ok(Some(trimmed.chars().take(500).collect()))
}
}
}
pub(in super::super) fn normalize_admin_wallet_required_text(
value: String,
field_name: &str,
max_len: usize,
) -> Result<String, String> {
let trimmed = value.trim();
if trimmed.is_empty() {
return Err(format!("{field_name} 不能为空"));
}
if trimmed.chars().count() > max_len {
return Err(format!("{field_name} 长度不能超过 {max_len}"));
}
Ok(trimmed.to_string())
}
pub(in super::super) fn normalize_admin_wallet_optional_text(
value: Option<String>,
field_name: &str,
max_len: usize,
) -> Result<Option<String>, String> {
match value {
None => Ok(None),
Some(value) => {
let trimmed = value.trim();
if trimmed.is_empty() {
return Ok(None);
}
if trimmed.chars().count() > max_len {
return Err(format!("{field_name} 长度不能超过 {max_len}"));
}
Ok(Some(trimmed.to_string()))
}
}
}
pub(in super::super) fn normalize_admin_wallet_payment_method(
value: String,
) -> Result<String, String> {
let normalized = value.trim();
if normalized.is_empty() {
return Err("payment_method 不能为空".to_string());
}
Ok(normalized.chars().take(30).collect())
}
pub(in super::super) fn normalize_admin_wallet_balance_type(
value: String,
) -> Result<String, String> {
let normalized = value.trim().to_ascii_lowercase();
match normalized.as_str() {
"recharge" | "gift" => Ok(normalized),
_ => Err("balance_type 必须为 recharge 或 gift".to_string()),
}
}
pub(in super::super) fn normalize_admin_wallet_positive_amount(
value: f64,
field_name: &str,
) -> Result<f64, String> {
if !value.is_finite() || value <= 0.0 {
return Err(format!("{field_name} 必须为大于 0 的有限数字"));
}
Ok(value)
}
pub(in super::super) fn normalize_admin_wallet_non_zero_amount(
value: f64,
field_name: &str,
) -> Result<f64, String> {
if !value.is_finite() || value == 0.0 {
return Err(format!("{field_name} 不能为 0且必须为有限数字"));
}
Ok(value)
}

View File

@@ -0,0 +1,196 @@
use crate::handlers::admin::request::AdminAppState;
use crate::handlers::admin::shared::unix_secs_to_rfc3339;
use crate::GatewayError;
use serde_json::json;
#[derive(Clone)]
pub(in super::super) struct AdminWalletOwnerSummary {
pub(in super::super) owner_type: &'static str,
pub(in super::super) owner_name: Option<String>,
}
pub(in super::super) fn build_admin_wallet_payment_order_payload(
order_id: String,
order_no: String,
amount_usd: f64,
payment_method: String,
status: String,
created_at: Option<String>,
credited_at: Option<String>,
) -> serde_json::Value {
json!({
"id": order_id,
"order_no": order_no,
"amount_usd": amount_usd,
"payment_method": payment_method,
"status": status,
"created_at": created_at,
"credited_at": credited_at,
})
}
#[allow(clippy::too_many_arguments)]
pub(in super::super) fn build_admin_wallet_transaction_payload(
wallet: &aether_data::repository::wallet::StoredWalletSnapshot,
owner: &AdminWalletOwnerSummary,
transaction_id: String,
category: &str,
reason_code: &str,
amount: f64,
balance_before: f64,
balance_after: f64,
recharge_balance_before: f64,
recharge_balance_after: f64,
gift_balance_before: f64,
gift_balance_after: f64,
link_type: Option<&str>,
link_id: Option<&str>,
operator_id: Option<&str>,
description: Option<&str>,
created_at: Option<String>,
) -> serde_json::Value {
json!({
"id": transaction_id,
"wallet_id": wallet.id,
"owner_type": owner.owner_type,
"owner_name": owner.owner_name.clone(),
"wallet_status": wallet.status,
"category": category,
"reason_code": reason_code,
"amount": amount,
"balance_before": balance_before,
"balance_after": balance_after,
"recharge_balance_before": recharge_balance_before,
"recharge_balance_after": recharge_balance_after,
"gift_balance_before": gift_balance_before,
"gift_balance_after": gift_balance_after,
"link_type": link_type,
"link_id": link_id,
"operator_id": operator_id,
"operator_name": serde_json::Value::Null,
"operator_email": serde_json::Value::Null,
"description": description,
"created_at": created_at,
})
}
pub(in super::super) fn wallet_owner_summary_from_fields(
user_id: Option<&str>,
user_name: Option<String>,
api_key_id: Option<&str>,
api_key_name: Option<String>,
) -> AdminWalletOwnerSummary {
if user_id.is_some() {
return AdminWalletOwnerSummary {
owner_type: "user",
owner_name: user_name,
};
}
if let Some(api_key_id) = api_key_id {
return AdminWalletOwnerSummary {
owner_type: "api_key",
owner_name: api_key_name
.filter(|value| !value.trim().is_empty())
.or_else(|| Some(format!("Key-{}", &api_key_id[..api_key_id.len().min(8)]))),
};
}
AdminWalletOwnerSummary {
owner_type: "orphaned",
owner_name: None,
}
}
pub(in super::super) async fn resolve_admin_wallet_owner_summary(
state: &AdminAppState<'_>,
wallet: &aether_data::repository::wallet::StoredWalletSnapshot,
) -> Result<AdminWalletOwnerSummary, GatewayError> {
if let Some(user_id) = wallet.user_id.as_deref() {
let user = state.find_user_auth_by_id(user_id).await?;
Ok(AdminWalletOwnerSummary {
owner_type: "user",
owner_name: user.map(|record| record.username),
})
} else if let Some(api_key_id) = wallet.api_key_id.as_deref() {
let api_key_ids = vec![api_key_id.to_string()];
let snapshots = state
.list_auth_api_key_snapshots_by_ids(&api_key_ids)
.await?;
let owner_name = snapshots
.into_iter()
.find(|snapshot| snapshot.api_key_id == api_key_id)
.and_then(|snapshot| snapshot.api_key_name)
.filter(|value| !value.trim().is_empty())
.or_else(|| Some(format!("Key-{}", &api_key_id[..api_key_id.len().min(8)])));
Ok(AdminWalletOwnerSummary {
owner_type: "api_key",
owner_name,
})
} else {
Ok(AdminWalletOwnerSummary {
owner_type: "orphaned",
owner_name: None,
})
}
}
pub(in super::super) fn build_admin_wallet_summary_payload(
wallet: &aether_data::repository::wallet::StoredWalletSnapshot,
owner: &AdminWalletOwnerSummary,
) -> serde_json::Value {
json!({
"id": wallet.id.clone(),
"user_id": wallet.user_id.clone(),
"api_key_id": wallet.api_key_id.clone(),
"owner_type": owner.owner_type,
"owner_name": owner.owner_name.clone(),
"balance": wallet.balance + wallet.gift_balance,
"recharge_balance": wallet.balance,
"gift_balance": wallet.gift_balance,
"refundable_balance": wallet.balance,
"currency": wallet.currency.clone(),
"status": wallet.status.clone(),
"limit_mode": wallet.limit_mode.clone(),
"unlimited": wallet.limit_mode.eq_ignore_ascii_case("unlimited"),
"total_recharged": wallet.total_recharged,
"total_consumed": wallet.total_consumed,
"total_refunded": wallet.total_refunded,
"total_adjusted": wallet.total_adjusted,
"created_at": serde_json::Value::Null,
"updated_at": unix_secs_to_rfc3339(wallet.updated_at_unix_secs),
})
}
pub(in super::super) fn build_admin_wallet_refund_payload(
wallet: &aether_data::repository::wallet::StoredWalletSnapshot,
owner: &AdminWalletOwnerSummary,
refund: &crate::AdminWalletRefundRecord,
) -> serde_json::Value {
json!({
"id": refund.id.clone(),
"refund_no": refund.refund_no.clone(),
"wallet_id": refund.wallet_id.clone(),
"owner_type": owner.owner_type,
"owner_name": owner.owner_name.clone(),
"wallet_status": wallet.status.clone(),
"user_id": refund.user_id.clone(),
"payment_order_id": refund.payment_order_id.clone(),
"source_type": refund.source_type.clone(),
"source_id": refund.source_id.clone(),
"refund_mode": refund.refund_mode.clone(),
"amount_usd": refund.amount_usd,
"status": refund.status.clone(),
"reason": refund.reason.clone(),
"failure_reason": refund.failure_reason.clone(),
"gateway_refund_id": refund.gateway_refund_id.clone(),
"payout_method": refund.payout_method.clone(),
"payout_reference": refund.payout_reference.clone(),
"payout_proof": refund.payout_proof.clone(),
"requested_by": refund.requested_by.clone(),
"approved_by": refund.approved_by.clone(),
"processed_by": refund.processed_by.clone(),
"created_at": unix_secs_to_rfc3339(refund.created_at_unix_secs),
"updated_at": unix_secs_to_rfc3339(refund.updated_at_unix_secs),
"processed_at": refund.processed_at_unix_secs.and_then(unix_secs_to_rfc3339),
"completed_at": refund.completed_at_unix_secs.and_then(unix_secs_to_rfc3339),
})
}

View File

@@ -0,0 +1,48 @@
pub(in super::super) const ADMIN_WALLETS_DATA_UNAVAILABLE_DETAIL: &str =
"Admin wallets data unavailable";
pub(in super::super) const ADMIN_WALLETS_API_KEY_REFUND_DETAIL: &str = "独立密钥钱包不支持退款审批";
pub(in super::super) const ADMIN_WALLETS_API_KEY_RECHARGE_DETAIL: &str =
"独立密钥钱包不支持充值,请使用调账";
pub(in super::super) const ADMIN_WALLETS_API_KEY_GIFT_ADJUST_DETAIL: &str =
"独立密钥钱包不支持赠款调账";
#[derive(Debug, serde::Deserialize)]
pub(in super::super) struct AdminWalletRechargeRequest {
pub(in super::super) amount_usd: f64,
#[serde(default = "default_admin_wallet_payment_method")]
pub(in super::super) payment_method: String,
#[serde(default)]
pub(in super::super) description: Option<String>,
}
#[derive(Debug, serde::Deserialize)]
pub(in super::super) struct AdminWalletAdjustRequest {
pub(in super::super) amount_usd: f64,
#[serde(default = "default_admin_wallet_balance_type")]
pub(in super::super) balance_type: String,
#[serde(default)]
pub(in super::super) description: Option<String>,
}
#[derive(Debug, serde::Deserialize)]
pub(in super::super) struct AdminWalletRefundFailRequest {
pub(in super::super) reason: String,
}
#[derive(Debug, serde::Deserialize)]
pub(in super::super) struct AdminWalletRefundCompleteRequest {
#[serde(default)]
pub(in super::super) gateway_refund_id: Option<String>,
#[serde(default)]
pub(in super::super) payout_reference: Option<String>,
#[serde(default)]
pub(in super::super) payout_proof: Option<serde_json::Value>,
}
fn default_admin_wallet_payment_method() -> String {
"admin_manual".to_string()
}
fn default_admin_wallet_balance_type() -> String {
"recharge".to_string()
}

View File

@@ -0,0 +1,42 @@
use super::requests::ADMIN_WALLETS_DATA_UNAVAILABLE_DETAIL;
use axum::{
body::Body,
http,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
pub(in super::super) fn build_admin_wallets_data_unavailable_response() -> Response<Body> {
(
http::StatusCode::SERVICE_UNAVAILABLE,
Json(json!({ "detail": ADMIN_WALLETS_DATA_UNAVAILABLE_DETAIL })),
)
.into_response()
}
pub(in super::super) fn build_admin_wallets_bad_request_response(
detail: impl Into<String>,
) -> Response<Body> {
(
http::StatusCode::BAD_REQUEST,
Json(json!({ "detail": detail.into() })),
)
.into_response()
}
pub(in super::super) fn build_admin_wallet_not_found_response() -> Response<Body> {
(
http::StatusCode::NOT_FOUND,
Json(json!({ "detail": "Wallet not found" })),
)
.into_response()
}
pub(in super::super) fn build_admin_wallet_refund_not_found_response() -> Response<Body> {
(
http::StatusCode::NOT_FOUND,
Json(json!({ "detail": "Refund request not found" })),
)
.into_response()
}

View File

@@ -0,0 +1,218 @@
use super::requests::ADMIN_WALLETS_API_KEY_GIFT_ADJUST_DETAIL;
use crate::handlers::admin::request::AdminRequestContext;
use crate::handlers::admin::shared::query_param_value;
use crate::GatewayError;
use sqlx::Row;
pub(in super::super) fn admin_wallet_operator_id(
request_context: &AdminRequestContext<'_>,
) -> Option<String> {
request_context
.decision()
.and_then(|decision| decision.admin_principal.as_ref())
.map(|principal| principal.user_id.clone())
}
pub(in super::super) fn admin_wallet_recharge_reason_code(payment_method: &str) -> &'static str {
match payment_method {
"card_code" | "gift_code" | "card_recharge" => "topup_card_code",
_ => "topup_admin_manual",
}
}
pub(in super::super) fn admin_wallet_apply_manual_recharge_to_snapshot(
wallet: &mut aether_data::repository::wallet::StoredWalletSnapshot,
amount_usd: f64,
) -> (f64, f64, f64, f64, f64, f64) {
let recharge_before = wallet.balance;
let gift_before = wallet.gift_balance;
let balance_before = recharge_before + gift_before;
wallet.balance += amount_usd;
wallet.total_recharged += amount_usd;
wallet.updated_at_unix_secs = chrono::Utc::now().timestamp().max(0) as u64;
let recharge_after = wallet.balance;
let gift_after = wallet.gift_balance;
let balance_after = recharge_after + gift_after;
(
balance_before,
balance_after,
recharge_before,
recharge_after,
gift_before,
gift_after,
)
}
pub(in super::super) fn admin_wallet_apply_adjust_to_snapshot(
wallet: &mut aether_data::repository::wallet::StoredWalletSnapshot,
amount_usd: f64,
balance_type: &str,
) -> Result<(f64, f64, f64, f64, f64, f64), String> {
if amount_usd == 0.0 {
return Err("adjust amount must not be zero".to_string());
}
if balance_type == "gift" && wallet.api_key_id.is_some() {
return Err(ADMIN_WALLETS_API_KEY_GIFT_ADJUST_DETAIL.to_string());
}
let recharge_before = wallet.balance;
let gift_before = wallet.gift_balance;
let balance_before = recharge_before + gift_before;
let mut recharge_after = recharge_before;
let mut gift_after = gift_before;
if amount_usd > 0.0 {
if balance_type == "gift" {
gift_after += amount_usd;
} else {
recharge_after += amount_usd;
}
} else {
let mut remaining = -amount_usd;
let consume_positive_bucket = |balance: &mut f64, remaining: &mut f64| {
if *remaining <= 0.0 {
return;
}
let available = balance.max(0.0);
let consumed = available.min(*remaining);
*balance -= consumed;
*remaining -= consumed;
};
if balance_type == "gift" {
consume_positive_bucket(&mut gift_after, &mut remaining);
consume_positive_bucket(&mut recharge_after, &mut remaining);
} else {
consume_positive_bucket(&mut recharge_after, &mut remaining);
consume_positive_bucket(&mut gift_after, &mut remaining);
}
if remaining > 0.0 {
recharge_after -= remaining;
}
if gift_after < 0.0 {
return Err("gift balance cannot be negative".to_string());
}
}
wallet.balance = recharge_after;
wallet.gift_balance = gift_after;
wallet.total_adjusted += amount_usd;
wallet.updated_at_unix_secs = chrono::Utc::now().timestamp().max(0) as u64;
Ok((
balance_before,
recharge_after + gift_after,
recharge_before,
recharge_after,
gift_before,
gift_after,
))
}
pub(in super::super) fn admin_wallet_id_from_detail_path(request_path: &str) -> Option<String> {
request_path
.strip_prefix("/api/admin/wallets/")?
.trim()
.trim_matches('/')
.split('/')
.next()
.map(str::trim)
.filter(|value| !value.is_empty())
.filter(|value| !value.contains('/'))
.map(ToOwned::to_owned)
}
pub(in super::super) fn admin_wallet_id_from_suffix_path(
request_path: &str,
suffix: &str,
) -> Option<String> {
request_path
.strip_prefix("/api/admin/wallets/")?
.strip_suffix(suffix)
.map(|value| value.trim().trim_matches('/').to_string())
.filter(|value| !value.is_empty() && !value.contains('/'))
}
pub(in super::super) fn admin_wallet_refund_ids_from_suffix_path(
request_path: &str,
suffix: &str,
) -> Option<(String, String)> {
let trimmed = request_path
.strip_prefix("/api/admin/wallets/")?
.strip_suffix(suffix)?
.trim()
.trim_matches('/');
let mut segments = trimmed.split('/');
let wallet_id = segments.next()?.trim();
let literal = segments.next()?.trim();
let refund_id = segments.next()?.trim();
if literal != "refunds"
|| wallet_id.is_empty()
|| refund_id.is_empty()
|| wallet_id.contains('/')
|| refund_id.contains('/')
|| segments.next().is_some()
{
return None;
}
Some((wallet_id.to_string(), refund_id.to_string()))
}
pub(in super::super) fn parse_admin_wallets_limit(query: Option<&str>) -> Result<usize, String> {
match query_param_value(query, "limit") {
Some(value) => {
let parsed = value
.parse::<usize>()
.map_err(|_| "limit must be an integer between 1 and 200".to_string())?;
if (1..=200).contains(&parsed) {
Ok(parsed)
} else {
Err("limit must be an integer between 1 and 200".to_string())
}
}
None => Ok(50),
}
}
pub(in super::super) fn parse_admin_wallets_offset(query: Option<&str>) -> Result<usize, String> {
match query_param_value(query, "offset") {
Some(value) => value
.parse::<usize>()
.map_err(|_| "offset must be a non-negative integer".to_string()),
None => Ok(0),
}
}
pub(in super::super) fn parse_admin_wallets_owner_type_filter(
query: Option<&str>,
) -> Option<String> {
match query_param_value(query, "owner_type") {
Some(value) if value.eq_ignore_ascii_case("user") => Some("user".to_string()),
Some(value) if value.eq_ignore_ascii_case("api_key") => Some("api_key".to_string()),
_ => None,
}
}
pub(in super::super) fn optional_epoch_value(
row: &sqlx::postgres::PgRow,
key: &str,
) -> Result<Option<String>, GatewayError> {
Ok(row
.try_get::<Option<i64>, _>(key)
.map_err(|err| GatewayError::Internal(err.to_string()))?
.and_then(|value| u64::try_from(value).ok())
.and_then(crate::handlers::admin::shared::unix_secs_to_rfc3339))
}
pub(in super::super) fn admin_wallet_build_order_no(now: chrono::DateTime<chrono::Utc>) -> String {
format!(
"po_{}_{}",
now.format("%Y%m%d%H%M%S%6f"),
&uuid::Uuid::new_v4().simple().to_string()[..12]
)
}

View File

@@ -1,14 +1,8 @@
use super::extractors::{admin_health_key_id, admin_recover_key_id};
use super::health_builders::{
build_admin_endpoint_health_status_payload, build_admin_health_summary_payload,
build_admin_key_health_payload, recover_admin_key_health, recover_all_admin_key_health,
};
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::query_param_value;
use crate::handlers::public::{
build_api_format_health_monitor_payload, ApiFormatHealthMonitorOptions,
};
use crate::{AppState, GatewayError};
use crate::handlers::public::ApiFormatHealthMonitorOptions;
use crate::GatewayError;
use axum::{
body::Body,
http,
@@ -29,21 +23,21 @@ fn build_admin_endpoint_health_data_unavailable_response() -> Response<Body> {
}
pub(super) async fn maybe_build_local_admin_endpoints_health_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Option<Response<Body>>, GatewayError> {
let Some(decision) = request_context.control_decision.as_ref() else {
let Some(decision) = request_context.decision() else {
return Ok(None);
};
if decision.route_family.as_deref() == Some("endpoints_health")
&& decision.route_kind.as_deref() == Some("health_summary")
&& request_context.request_path == "/api/admin/endpoints/health/summary"
&& request_context.path() == "/api/admin/endpoints/health/summary"
{
if !state.has_provider_catalog_data_reader() {
return Ok(Some(build_admin_endpoint_health_data_unavailable_response()));
}
let Some(payload) = build_admin_health_summary_payload(state).await else {
let Some(payload) = state.build_admin_health_summary_payload().await else {
return Ok(Some(build_admin_endpoint_health_data_unavailable_response()));
};
return Ok(Some(Json(payload).into_response()));
@@ -58,7 +52,7 @@ pub(super) async fn maybe_build_local_admin_endpoints_health_response(
if !state.has_provider_catalog_data_reader() {
return Ok(Some(build_admin_endpoint_health_data_unavailable_response()));
}
let Some(key_id) = admin_health_key_id(&request_context.request_path) else {
let Some(key_id) = admin_health_key_id(request_context.path()) else {
return Ok(Some(
(
http::StatusCode::NOT_FOUND,
@@ -67,12 +61,12 @@ pub(super) async fn maybe_build_local_admin_endpoints_health_response(
.into_response(),
));
};
let api_format = query_param_value(
request_context.request_query_string.as_deref(),
"api_format",
);
let api_format = query_param_value(request_context.query_string(), "api_format");
return Ok(Some(
match build_admin_key_health_payload(state, &key_id, api_format.as_deref()).await {
match state
.build_admin_key_health_payload(&key_id, api_format.as_deref())
.await
{
Some(payload) => Json(payload).into_response(),
None => (
http::StatusCode::NOT_FOUND,
@@ -92,7 +86,7 @@ pub(super) async fn maybe_build_local_admin_endpoints_health_response(
if !state.has_provider_catalog_data_reader() || !state.has_provider_catalog_data_writer() {
return Ok(Some(build_admin_endpoint_health_data_unavailable_response()));
}
let Some(key_id) = admin_recover_key_id(&request_context.request_path) else {
let Some(key_id) = admin_recover_key_id(request_context.path()) else {
return Ok(Some(
(
http::StatusCode::NOT_FOUND,
@@ -101,12 +95,12 @@ pub(super) async fn maybe_build_local_admin_endpoints_health_response(
.into_response(),
));
};
let api_format = query_param_value(
request_context.request_query_string.as_deref(),
"api_format",
);
let api_format = query_param_value(request_context.query_string(), "api_format");
return Ok(Some(
match recover_admin_key_health(state, &key_id, api_format.as_deref()).await {
match state
.recover_admin_key_health(&key_id, api_format.as_deref())
.await
{
Some(payload) => Json(payload).into_response(),
None => (
http::StatusCode::NOT_FOUND,
@@ -119,12 +113,12 @@ pub(super) async fn maybe_build_local_admin_endpoints_health_response(
if decision.route_family.as_deref() == Some("endpoints_health")
&& decision.route_kind.as_deref() == Some("recover_all_keys_health")
&& request_context.request_path == "/api/admin/endpoints/health/keys"
&& request_context.path() == "/api/admin/endpoints/health/keys"
{
if !state.has_provider_catalog_data_reader() || !state.has_provider_catalog_data_writer() {
return Ok(Some(build_admin_endpoint_health_data_unavailable_response()));
}
let Some(payload) = recover_all_admin_key_health(state).await else {
let Some(payload) = state.recover_all_admin_key_health().await else {
return Ok(Some(build_admin_endpoint_health_data_unavailable_response()));
};
return Ok(Some(Json(payload).into_response()));
@@ -132,36 +126,31 @@ pub(super) async fn maybe_build_local_admin_endpoints_health_response(
if decision.route_family.as_deref() == Some("endpoints_health")
&& decision.route_kind.as_deref() == Some("health_api_formats")
&& request_context.request_path == "/api/admin/endpoints/health/api-formats"
&& request_context.path() == "/api/admin/endpoints/health/api-formats"
{
if !state.has_provider_catalog_data_reader() || !state.has_request_candidate_data_reader() {
return Ok(Some(build_admin_endpoint_health_data_unavailable_response()));
}
let lookback_hours = query_param_value(
request_context.request_query_string.as_deref(),
"lookback_hours",
)
.and_then(|value| value.parse::<u64>().ok())
.filter(|value| (1..=72).contains(value))
.unwrap_or(6);
let per_format_limit = query_param_value(
request_context.request_query_string.as_deref(),
"per_format_limit",
)
.and_then(|value| value.parse::<usize>().ok())
.filter(|value| (10..=200).contains(value))
.unwrap_or(60);
let Some(payload) = build_api_format_health_monitor_payload(
state,
lookback_hours,
per_format_limit,
ApiFormatHealthMonitorOptions {
include_api_path: false,
include_provider_count: true,
include_key_count: true,
},
)
.await
let lookback_hours = query_param_value(request_context.query_string(), "lookback_hours")
.and_then(|value| value.parse::<u64>().ok())
.filter(|value| (1..=72).contains(value))
.unwrap_or(6);
let per_format_limit =
query_param_value(request_context.query_string(), "per_format_limit")
.and_then(|value| value.parse::<usize>().ok())
.filter(|value| (10..=200).contains(value))
.unwrap_or(60);
let Some(payload) = state
.build_api_format_health_monitor_payload(
lookback_hours,
per_format_limit,
ApiFormatHealthMonitorOptions {
include_api_path: false,
include_provider_count: true,
include_key_count: true,
},
)
.await
else {
return Ok(Some(build_admin_endpoint_health_data_unavailable_response()));
};
@@ -170,19 +159,18 @@ pub(super) async fn maybe_build_local_admin_endpoints_health_response(
if decision.route_family.as_deref() == Some("endpoints_health")
&& decision.route_kind.as_deref() == Some("health_status")
&& request_context.request_path == "/api/admin/endpoints/health/status"
&& request_context.path() == "/api/admin/endpoints/health/status"
{
if !state.has_provider_catalog_data_reader() || !state.has_request_candidate_data_reader() {
return Ok(Some(build_admin_endpoint_health_data_unavailable_response()));
}
let lookback_hours = query_param_value(
request_context.request_query_string.as_deref(),
"lookback_hours",
)
.and_then(|value| value.parse::<u64>().ok())
.filter(|value| (1..=72).contains(value))
.unwrap_or(6);
let Some(payload) = build_admin_endpoint_health_status_payload(state, lookback_hours).await
let lookback_hours = query_param_value(request_context.query_string(), "lookback_hours")
.and_then(|value| value.parse::<u64>().ok())
.filter(|value| (1..=72).contains(value))
.unwrap_or(6);
let Some(payload) = state
.build_admin_endpoint_health_status_payload(lookback_hours)
.await
else {
return Ok(Some(build_admin_endpoint_health_data_unavailable_response()));
};

View File

@@ -1,11 +1,11 @@
use crate::handlers::admin::request::AdminAppState;
use crate::handlers::public::provider_key_api_formats;
use crate::AppState;
use aether_scheduler_core::count_recent_rpm_requests_for_provider_key_since;
use serde_json::json;
use std::time::{SystemTime, UNIX_EPOCH};
pub(crate) async fn build_admin_key_health_payload(
state: &AppState,
state: &AdminAppState<'_>,
key_id: &str,
api_format: Option<&str>,
) -> Option<serde_json::Value> {
@@ -172,7 +172,7 @@ pub(crate) async fn build_admin_key_health_payload(
}
pub(crate) async fn build_admin_key_rpm_payload(
state: &AppState,
state: &AdminAppState<'_>,
key_id: &str,
) -> Option<serde_json::Value> {
if !state.has_provider_catalog_data_reader() {
@@ -225,7 +225,7 @@ fn default_key_circuit_payload() -> serde_json::Value {
}
pub(crate) async fn recover_admin_key_health(
state: &AppState,
state: &AdminAppState<'_>,
key_id: &str,
api_format: Option<&str>,
) -> Option<serde_json::Value> {
@@ -295,7 +295,9 @@ pub(crate) async fn recover_admin_key_health(
}))
}
pub(crate) async fn recover_all_admin_key_health(state: &AppState) -> Option<serde_json::Value> {
pub(crate) async fn recover_all_admin_key_health(
state: &AdminAppState<'_>,
) -> Option<serde_json::Value> {
if !state.has_provider_catalog_data_reader() {
return None;
}

View File

@@ -1,9 +1,9 @@
mod keys;
mod status;
pub(super) use self::keys::{
pub(crate) use self::keys::{
build_admin_key_health_payload, build_admin_key_rpm_payload, recover_admin_key_health,
recover_all_admin_key_health,
};
pub(crate) use self::status::build_admin_endpoint_health_status_payload;
pub(super) use self::status::build_admin_health_summary_payload;
pub(crate) use self::status::build_admin_health_summary_payload;

View File

@@ -1,8 +1,8 @@
use crate::handlers::admin::request::AdminAppState;
use crate::handlers::admin::shared::unix_secs_to_rfc3339;
use crate::handlers::public::{
api_format_display_name, build_public_health_timeline, provider_key_api_formats,
};
use crate::AppState;
use aether_data_contracts::repository::candidates::PublicHealthTimelineBucket;
use aether_scheduler_core::{is_provider_key_circuit_open, provider_key_health_score};
use serde_json::json;
@@ -10,7 +10,7 @@ use std::collections::{BTreeMap, BTreeSet};
use std::time::{SystemTime, UNIX_EPOCH};
pub(crate) async fn build_admin_endpoint_health_status_payload(
state: &AppState,
state: &AdminAppState<'_>,
lookback_hours: u64,
) -> Option<serde_json::Value> {
if !state.has_provider_catalog_data_reader() || !state.has_request_candidate_data_reader() {
@@ -210,7 +210,7 @@ pub(crate) async fn build_admin_endpoint_health_status_payload(
}
pub(crate) async fn build_admin_health_summary_payload(
state: &AppState,
state: &AdminAppState<'_>,
) -> Option<serde_json::Value> {
if !state.has_provider_catalog_data_reader() {
return None;

View File

@@ -1,52 +1,13 @@
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::provider::{endpoint_keys, endpoints_admin};
use crate::{AppState, GatewayError};
use axum::body::{Body, Bytes};
use axum::http::Response;
mod extractors;
mod health;
mod health_builders;
mod routes;
mod rpm;
pub(crate) use self::health_builders::build_admin_endpoint_health_status_payload;
pub(crate) async fn maybe_build_local_admin_endpoints_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
request_body: Option<&Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
if let Some(response) =
health::maybe_build_local_admin_endpoints_health_response(state, request_context).await?
{
return Ok(Some(response));
}
if let Some(response) =
rpm::maybe_build_local_admin_endpoints_rpm_response(state, request_context).await?
{
return Ok(Some(response));
}
if let Some(response) = endpoint_keys::maybe_build_local_admin_endpoints_keys_response(
state,
request_context,
request_body,
)
.await?
{
return Ok(Some(response));
}
if let Some(response) = endpoints_admin::maybe_build_local_admin_endpoints_routes_response(
state,
request_context,
request_body,
)
.await?
{
return Ok(Some(response));
}
Ok(None)
}
pub(super) use self::health_builders::build_admin_health_summary_payload;
pub(super) use self::health_builders::build_admin_key_health_payload;
pub(super) use self::health_builders::build_admin_key_rpm_payload;
pub(super) use self::health_builders::recover_admin_key_health;
pub(super) use self::health_builders::recover_all_admin_key_health;
pub(super) use self::routes::maybe_build_local_admin_endpoints_response;

View File

@@ -0,0 +1,47 @@
use super::{health, rpm};
use crate::handlers::admin::provider::{endpoint_keys, endpoints_admin};
use crate::handlers::admin::request::{AdminRouteRequest, AdminRouteResult};
pub(crate) async fn maybe_build_local_admin_endpoints_response(
request: AdminRouteRequest<'_>,
) -> AdminRouteResult {
if let Some(response) = health::maybe_build_local_admin_endpoints_health_response(
&request.state(),
&request.request_context(),
)
.await?
{
return Ok(Some(response));
}
if let Some(response) = rpm::maybe_build_local_admin_endpoints_rpm_response(
&request.state(),
&request.request_context(),
)
.await?
{
return Ok(Some(response));
}
if let Some(response) = endpoint_keys::maybe_build_local_admin_endpoints_keys_response(
&request.state(),
&request.request_context(),
request.request_body(),
)
.await?
{
return Ok(Some(response));
}
if let Some(response) = endpoints_admin::maybe_build_local_admin_endpoints_routes_response(
&request.state(),
&request.request_context(),
request.request_body(),
)
.await?
{
return Ok(Some(response));
}
Ok(None)
}

View File

@@ -1,7 +1,6 @@
use super::extractors::admin_rpm_key_id;
use super::health_builders::build_admin_key_rpm_payload;
use crate::control::GatewayPublicRequestContext;
use crate::{AppState, GatewayError};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::GatewayError;
use axum::{
body::Body,
http,
@@ -12,20 +11,20 @@ use serde_json::json;
use std::time::{SystemTime, UNIX_EPOCH};
pub(super) async fn maybe_build_local_admin_endpoints_rpm_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Option<Response<Body>>, GatewayError> {
let Some(decision) = request_context.control_decision.as_ref() else {
let Some(decision) = request_context.decision() else {
return Ok(None);
};
if decision.route_family.as_deref() == Some("endpoints_rpm")
&& decision.route_kind.as_deref() == Some("key_rpm")
&& request_context
.request_path
.path()
.starts_with("/api/admin/endpoints/rpm/key/")
{
let Some(key_id) = admin_rpm_key_id(&request_context.request_path) else {
let Some(key_id) = admin_rpm_key_id(request_context.path()) else {
return Ok(Some(
(
http::StatusCode::NOT_FOUND,
@@ -35,7 +34,7 @@ pub(super) async fn maybe_build_local_admin_endpoints_rpm_response(
));
};
return Ok(Some(
match build_admin_key_rpm_payload(state, &key_id).await {
match state.build_admin_key_rpm_payload(&key_id).await {
Some(payload) => Json(payload).into_response(),
None => (
http::StatusCode::NOT_FOUND,
@@ -48,12 +47,12 @@ pub(super) async fn maybe_build_local_admin_endpoints_rpm_response(
if decision.route_family.as_deref() == Some("endpoints_rpm")
&& decision.route_kind.as_deref() == Some("reset_key_rpm")
&& request_context.request_method == http::Method::DELETE
&& request_context.method() == http::Method::DELETE
&& request_context
.request_path
.path()
.starts_with("/api/admin/endpoints/rpm/key/")
{
let Some(key_id) = admin_rpm_key_id(&request_context.request_path) else {
let Some(key_id) = admin_rpm_key_id(request_context.path()) else {
return Ok(Some(
(
http::StatusCode::NOT_FOUND,

View File

@@ -1,5 +1,5 @@
use crate::control::GatewayPublicRequestContext;
use crate::{AppState, GatewayError};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::GatewayError;
use aether_data_contracts::repository::provider_catalog::StoredProviderCatalogKey;
use axum::body::{Body, Bytes};
use axum::http::{self, Response};
@@ -18,11 +18,11 @@ mod read_routes;
mod upload;
pub(crate) async fn maybe_build_local_admin_gemini_files_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
let Some(decision) = request_context.control_decision.as_ref() else {
let Some(decision) = request_context.decision() else {
return Ok(None);
};
if decision.route_family.as_deref() != Some("gemini_files_manage") {

View File

@@ -4,13 +4,13 @@ use super::{
ADMIN_GEMINI_FILES_DEFAULT_PAGE, ADMIN_GEMINI_FILES_DEFAULT_PAGE_SIZE,
ADMIN_GEMINI_FILES_MAX_PAGE_SIZE,
};
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::{
admin_gemini_file_mapping_id_from_path, is_admin_gemini_files_capable_keys_root,
is_admin_gemini_files_mappings_root, is_admin_gemini_files_stats_root,
query_param_optional_bool, query_param_value, unix_secs_to_rfc3339,
};
use crate::{AppState, GatewayError};
use crate::GatewayError;
use aether_data_contracts::repository::provider_catalog::StoredProviderCatalogKey;
use axum::body::Body;
use axum::http::{self, Response};
@@ -28,9 +28,9 @@ struct AdminGeminiFilesPageQuery {
}
fn admin_gemini_files_page_query(
request_context: &GatewayPublicRequestContext,
request_context: &AdminRequestContext<'_>,
) -> Result<Option<AdminGeminiFilesPageQuery>, GatewayError> {
let query = request_context.request_query_string.as_deref();
let query = request_context.query_string();
let page = match query_param_value(query, "page") {
Some(raw) => raw.parse::<usize>().ok().filter(|value| *value >= 1),
None => Some(ADMIN_GEMINI_FILES_DEFAULT_PAGE),
@@ -62,7 +62,7 @@ fn admin_gemini_files_page_query(
}
async fn admin_gemini_files_key_name_map(
state: &AppState,
state: &AdminAppState<'_>,
) -> Result<BTreeMap<String, String>, GatewayError> {
let capable_keys = admin_gemini_files_all_keys(state).await?;
Ok(capable_keys
@@ -72,7 +72,7 @@ async fn admin_gemini_files_key_name_map(
}
async fn admin_gemini_files_username_map<'a, I>(
state: &AppState,
state: &AdminAppState<'_>,
mappings: I,
) -> Result<BTreeMap<String, String>, GatewayError>
where
@@ -91,7 +91,7 @@ where
}
async fn admin_gemini_files_capable_keys(
state: &AppState,
state: &AdminAppState<'_>,
) -> Result<Vec<serde_json::Value>, GatewayError> {
let providers = state.list_provider_catalog_providers(false).await?;
let provider_name_by_id = providers
@@ -113,7 +113,7 @@ async fn admin_gemini_files_capable_keys(
}
async fn admin_gemini_files_all_keys(
state: &AppState,
state: &AdminAppState<'_>,
) -> Result<Vec<StoredProviderCatalogKey>, GatewayError> {
let providers = state.list_provider_catalog_providers(false).await?;
let provider_ids = providers
@@ -147,19 +147,18 @@ fn build_admin_gemini_file_mapping_payload(
}
pub(super) async fn maybe_build_local_admin_gemini_files_read_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Option<Response<Body>>, GatewayError> {
let now_unix_secs = admin_gemini_files_now_unix_secs();
match request_context
.control_decision
.as_ref()
.decision()
.and_then(|decision| decision.route_kind.as_deref())
{
Some("list_mappings")
if request_context.request_method == http::Method::GET
&& is_admin_gemini_files_mappings_root(&request_context.request_path) =>
if request_context.method() == http::Method::GET
&& is_admin_gemini_files_mappings_root(request_context.path()) =>
{
if !state.has_gemini_file_mapping_data_reader() {
return Ok(Some(admin_gemini_files_error_response(
@@ -212,8 +211,8 @@ pub(super) async fn maybe_build_local_admin_gemini_files_read_response(
))
}
Some("stats")
if request_context.request_method == http::Method::GET
&& is_admin_gemini_files_stats_root(&request_context.request_path) =>
if request_context.method() == http::Method::GET
&& is_admin_gemini_files_stats_root(request_context.path()) =>
{
if !state.has_gemini_file_mapping_data_reader() {
return Ok(Some(admin_gemini_files_error_response(
@@ -240,9 +239,9 @@ pub(super) async fn maybe_build_local_admin_gemini_files_read_response(
))
}
Some("delete_mapping")
if request_context.request_method == http::Method::DELETE
if request_context.method() == http::Method::DELETE
&& request_context
.request_path
.path()
.starts_with("/api/admin/gemini-files/mappings/") =>
{
if !state.has_gemini_file_mapping_data_writer() {
@@ -251,8 +250,7 @@ pub(super) async fn maybe_build_local_admin_gemini_files_read_response(
ADMIN_GEMINI_FILES_DATA_UNAVAILABLE_DETAIL,
)));
}
let Some(mapping_id) =
admin_gemini_file_mapping_id_from_path(&request_context.request_path)
let Some(mapping_id) = admin_gemini_file_mapping_id_from_path(request_context.path())
else {
return Ok(Some(admin_gemini_files_error_response(
http::StatusCode::NOT_FOUND,
@@ -274,8 +272,8 @@ pub(super) async fn maybe_build_local_admin_gemini_files_read_response(
))
}
Some("cleanup_mappings")
if request_context.request_method == http::Method::DELETE
&& is_admin_gemini_files_mappings_root(&request_context.request_path) =>
if request_context.method() == http::Method::DELETE
&& is_admin_gemini_files_mappings_root(request_context.path()) =>
{
if !state.has_gemini_file_mapping_data_writer() {
return Ok(Some(admin_gemini_files_error_response(
@@ -295,8 +293,8 @@ pub(super) async fn maybe_build_local_admin_gemini_files_read_response(
))
}
Some("capable_keys")
if request_context.request_method == http::Method::GET
&& is_admin_gemini_files_capable_keys_root(&request_context.request_path) =>
if request_context.method() == http::Method::GET
&& is_admin_gemini_files_capable_keys_root(request_context.path()) =>
{
let capable_keys = admin_gemini_files_capable_keys(state).await?;
Ok(Some(Json(capable_keys).into_response()))

View File

@@ -1,586 +0,0 @@
use super::{
admin_gemini_files_error_response, admin_gemini_files_key_capable,
ADMIN_GEMINI_FILES_DATA_UNAVAILABLE_DETAIL,
};
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::shared::{is_admin_gemini_files_upload_root, query_param_value};
use crate::{AppState, GatewayError};
use aether_contracts::{ExecutionPlan, ExecutionResult, RequestBody};
use aether_data_contracts::repository::provider_catalog::{
StoredProviderCatalogEndpoint, StoredProviderCatalogKey,
};
use axum::body::{Body, Bytes};
use axum::http::{self, Response};
use axum::response::IntoResponse;
use axum::Json;
use base64::Engine as _;
use serde_json::json;
use std::collections::{BTreeMap, BTreeSet};
#[derive(Debug, Clone)]
struct AdminGeminiFilesUploadRequest {
display_name: String,
mime_type: String,
body_bytes: Vec<u8>,
body_bytes_b64: String,
}
#[derive(Debug, Clone)]
struct AdminGeminiFilesUploadExecutionSuccess {
file_name: String,
display_name: Option<String>,
mime_type: Option<String>,
}
pub(super) async fn maybe_build_local_admin_gemini_files_upload_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
request_body: Option<&Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
match request_context
.control_decision
.as_ref()
.and_then(|decision| decision.route_kind.as_deref())
{
Some("upload")
if request_context.request_method == http::Method::POST
&& is_admin_gemini_files_upload_root(&request_context.request_path) =>
{
if !state.has_gemini_file_mapping_data_writer() {
return Ok(Some(admin_gemini_files_error_response(
http::StatusCode::SERVICE_UNAVAILABLE,
ADMIN_GEMINI_FILES_DATA_UNAVAILABLE_DETAIL,
)));
}
let upload =
match admin_gemini_files_parse_upload_request(request_context, request_body) {
Ok(upload) => upload,
Err(detail) => {
return Ok(Some(admin_gemini_files_error_response(
http::StatusCode::BAD_REQUEST,
detail,
)));
}
};
let key_ids = admin_gemini_files_query_key_ids(request_context);
if key_ids.is_empty() {
return Ok(Some(admin_gemini_files_error_response(
http::StatusCode::BAD_REQUEST,
"key_ids 不能为空",
)));
}
let response = admin_gemini_files_upload_across_keys(
state,
"",
request_context.trace_id.as_str(),
&upload,
&key_ids,
)
.await?;
Ok(Some(Json(response).into_response()))
}
_ => Ok(None),
}
}
fn admin_gemini_files_query_key_ids(request_context: &GatewayPublicRequestContext) -> Vec<String> {
let mut key_ids = Vec::new();
let mut seen = BTreeSet::new();
let Some(raw) = query_param_value(request_context.request_query_string.as_deref(), "key_ids")
else {
return key_ids;
};
for key_id in raw.split(',') {
let trimmed = key_id.trim();
if trimmed.is_empty() || !seen.insert(trimmed.to_string()) {
continue;
}
key_ids.push(trimmed.to_string());
}
key_ids
}
fn admin_gemini_files_parse_upload_request(
request_context: &GatewayPublicRequestContext,
request_body: Option<&axum::body::Bytes>,
) -> Result<AdminGeminiFilesUploadRequest, String> {
let content_type = request_context
.request_content_type
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.ok_or_else(|| "Content-Type 缺失".to_string())?;
let boundary = admin_gemini_files_multipart_boundary(content_type)?;
let body = request_body
.filter(|body| !body.is_empty())
.ok_or_else(|| "上传文件不能为空".to_string())?;
let (display_name, mime_type, body_bytes) =
admin_gemini_files_extract_file_part(body.as_ref(), &boundary)?;
Ok(AdminGeminiFilesUploadRequest {
display_name,
mime_type,
body_bytes_b64: base64::engine::general_purpose::STANDARD.encode(&body_bytes),
body_bytes,
})
}
fn admin_gemini_files_multipart_boundary(content_type: &str) -> Result<String, String> {
let normalized = content_type.trim();
if !normalized
.to_ascii_lowercase()
.starts_with("multipart/form-data")
{
return Err("Content-Type 必须是 multipart/form-data".to_string());
}
for part in normalized.split(';').skip(1) {
let Some((key, value)) = part.trim().split_once('=') else {
continue;
};
if !key.trim().eq_ignore_ascii_case("boundary") {
continue;
}
let boundary = value.trim().trim_matches('"').trim();
if !boundary.is_empty() {
return Ok(boundary.to_string());
}
}
Err("multipart boundary 缺失".to_string())
}
fn admin_gemini_files_extract_file_part(
body: &[u8],
boundary: &str,
) -> Result<(String, String, Vec<u8>), String> {
let boundary_marker = format!("--{boundary}");
let next_boundary_marker = format!("\r\n--{boundary}");
let boundary_bytes = boundary_marker.as_bytes();
let next_boundary_bytes = next_boundary_marker.as_bytes();
let mut cursor = 0usize;
while cursor < body.len() {
if !body[cursor..].starts_with(boundary_bytes) {
return Err("multipart body 格式无效".to_string());
}
cursor += boundary_bytes.len();
if body[cursor..].starts_with(b"--") {
break;
}
if !body[cursor..].starts_with(b"\r\n") {
return Err("multipart body 缺少头部分隔符".to_string());
}
cursor += 2;
let Some(headers_end_rel) = admin_gemini_files_find_subslice(&body[cursor..], b"\r\n\r\n")
else {
return Err("multipart part 缺少头部".to_string());
};
let headers_end = cursor + headers_end_rel;
let headers_text = std::str::from_utf8(&body[cursor..headers_end])
.map_err(|_| "multipart part 头部编码无效".to_string())?;
cursor = headers_end + 4;
let Some(next_boundary_rel) =
admin_gemini_files_find_subslice(&body[cursor..], next_boundary_bytes)
else {
return Err("multipart body 缺少结束边界".to_string());
};
let content_end = cursor + next_boundary_rel;
let content = &body[cursor..content_end];
cursor = content_end + 2;
let Some((field_name, file_name, mime_type)) =
admin_gemini_files_parse_part_headers(headers_text)
else {
continue;
};
if field_name != "file" {
continue;
}
return Ok((
file_name.unwrap_or_else(|| "uploaded-file".to_string()),
mime_type.unwrap_or_else(|| "application/octet-stream".to_string()),
content.to_vec(),
));
}
Err("multipart body 中缺少 file 字段".to_string())
}
fn admin_gemini_files_parse_part_headers(
headers_text: &str,
) -> Option<(String, Option<String>, Option<String>)> {
let mut field_name = None;
let mut file_name = None;
let mut mime_type = None;
for line in headers_text.split("\r\n") {
let Some((header_name, header_value)) = line.split_once(':') else {
continue;
};
let header_name = header_name.trim();
let header_value = header_value.trim();
if header_name.eq_ignore_ascii_case("content-disposition") {
for part in header_value.split(';').skip(1) {
let Some((key, value)) = part.trim().split_once('=') else {
continue;
};
let key = key.trim();
let value = value.trim().trim_matches('"').trim();
if key.eq_ignore_ascii_case("name") && !value.is_empty() {
field_name = Some(value.to_string());
} else if key.eq_ignore_ascii_case("filename") && !value.is_empty() {
file_name = Some(value.to_string());
}
}
} else if header_name.eq_ignore_ascii_case("content-type") && !header_value.is_empty() {
mime_type = Some(header_value.to_string());
}
}
field_name.map(|field_name| (field_name, file_name, mime_type))
}
fn admin_gemini_files_find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
if haystack.is_empty() || needle.is_empty() || haystack.len() < needle.len() {
return None;
}
haystack
.windows(needle.len())
.position(|window| window == needle)
}
async fn admin_gemini_files_upload_across_keys(
state: &AppState,
execution_runtime_base_url: &str,
trace_id: &str,
upload: &AdminGeminiFilesUploadRequest,
requested_key_ids: &[String],
) -> Result<serde_json::Value, GatewayError> {
let keys = state
.read_provider_catalog_keys_by_ids(requested_key_ids)
.await?;
let key_by_id = keys
.iter()
.map(|key| (key.id.as_str(), key))
.collect::<BTreeMap<_, _>>();
let provider_ids = keys
.iter()
.map(|key| key.provider_id.clone())
.collect::<BTreeSet<_>>()
.into_iter()
.collect::<Vec<_>>();
let endpoints = state
.list_provider_catalog_endpoints_by_provider_ids(&provider_ids)
.await?;
let endpoints_by_provider_id = endpoints.into_iter().fold(
BTreeMap::<String, Vec<StoredProviderCatalogEndpoint>>::new(),
|mut out, endpoint| {
out.entry(endpoint.provider_id.clone())
.or_default()
.push(endpoint);
out
},
);
let mut results = Vec::new();
let mut success_count = 0usize;
let mut fail_count = 0usize;
for key_id in requested_key_ids {
let Some(key) = key_by_id.get(key_id.as_str()) else {
fail_count += 1;
results.push(json!({
"key_id": key_id,
"key_name": serde_json::Value::Null,
"success": false,
"file_name": serde_json::Value::Null,
"error": "Key 不存在",
}));
continue;
};
let key_name = Some(key.name.clone());
let outcome = admin_gemini_files_upload_single_key(
state,
execution_runtime_base_url,
trace_id,
upload,
key,
endpoints_by_provider_id.get(&key.provider_id),
)
.await;
match outcome {
Ok(success) => {
success_count += 1;
results.push(json!({
"key_id": key.id,
"key_name": key_name,
"success": true,
"file_name": success.file_name,
"error": serde_json::Value::Null,
}));
}
Err(error) => {
fail_count += 1;
results.push(json!({
"key_id": key.id,
"key_name": key_name,
"success": false,
"file_name": serde_json::Value::Null,
"error": error,
}));
}
}
}
Ok(json!({
"display_name": upload.display_name,
"mime_type": upload.mime_type,
"size_bytes": upload.body_bytes.len(),
"results": results,
"success_count": success_count,
"fail_count": fail_count,
}))
}
async fn admin_gemini_files_upload_single_key(
state: &AppState,
_execution_runtime_base_url: &str,
trace_id: &str,
upload: &AdminGeminiFilesUploadRequest,
key: &StoredProviderCatalogKey,
endpoints: Option<&Vec<StoredProviderCatalogEndpoint>>,
) -> Result<AdminGeminiFilesUploadExecutionSuccess, String> {
if !admin_gemini_files_key_capable(key) {
return Err("Key 不支持 Gemini Files".to_string());
}
let Some(endpoint) = endpoints.and_then(|endpoints| {
endpoints.iter().find(|endpoint| {
endpoint.is_active
&& endpoint
.api_format
.trim()
.eq_ignore_ascii_case("gemini:chat")
})
}) else {
return Err("找不到有效的 gemini:chat 端点".to_string());
};
let transport = state
.read_provider_transport_snapshot(&key.provider_id, &endpoint.id, &key.id)
.await
.map_err(|err| format!("{err:?}"))?
.ok_or_else(|| "无法读取 Key 传输配置".to_string())?;
if !crate::provider_transport::policy::supports_local_gemini_transport_with_network(
&transport,
"gemini:chat",
) {
return Err("Key 传输配置不支持 Gemini Files 上传".to_string());
}
if transport.endpoint.body_rules.is_some() {
return Err("Gemini Files 二进制上传暂不支持 endpoint body_rules".to_string());
}
let (auth_header, auth_value) =
crate::provider_transport::auth::resolve_local_gemini_auth(&transport)
.ok_or_else(|| "Key 缺少可用的 Gemini 认证信息".to_string())?;
let mut provider_request_headers =
crate::provider_transport::auth::build_passthrough_headers_with_auth(
&http::HeaderMap::new(),
&auth_header,
&auth_value,
&BTreeMap::new(),
);
provider_request_headers.insert("content-type".to_string(), upload.mime_type.clone());
let original_request_body = json!({
"body_bytes_b64": upload.body_bytes_b64,
});
if !crate::provider_transport::apply_local_header_rules(
&mut provider_request_headers,
transport.endpoint.header_rules.as_ref(),
&[auth_header.as_str(), "content-type"],
&original_request_body,
Some(&original_request_body),
) {
return Err("Key 端点 header_rules 应用失败".to_string());
}
let upload_path = transport
.endpoint
.custom_path
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.unwrap_or("/upload/v1beta/files");
let upload_query = if upload_path.contains("uploadType=") {
None
} else {
Some("uploadType=resumable")
};
let upstream_url = crate::provider_transport::url::build_gemini_files_passthrough_url(
&transport.endpoint.base_url,
upload_path,
upload_query,
)
.ok_or_else(|| "无法构建 Gemini Files 上传地址".to_string())?;
let plan = ExecutionPlan {
request_id: format!("{trace_id}:admin-gemini-upload:{}", key.id),
candidate_id: None,
provider_name: Some(transport.provider.name.clone()),
provider_id: transport.provider.id.clone(),
endpoint_id: transport.endpoint.id.clone(),
key_id: transport.key.id.clone(),
method: "POST".to_string(),
url: upstream_url,
headers: provider_request_headers,
content_type: Some(upload.mime_type.clone()),
content_encoding: None,
body: RequestBody {
json_body: None,
body_bytes_b64: Some(upload.body_bytes_b64.clone()),
body_ref: None,
},
stream: false,
client_api_format: "gemini:files".to_string(),
provider_api_format: "gemini:files".to_string(),
model_name: Some("gemini-files".to_string()),
proxy: crate::provider_transport::resolve_transport_proxy_snapshot_with_tunnel_affinity(
state, &transport,
)
.await,
tls_profile: crate::provider_transport::resolve_transport_tls_profile(&transport),
timeouts: crate::provider_transport::resolve_transport_execution_timeouts(&transport),
};
let result = admin_gemini_files_execute_upload_plan(state, trace_id, &plan)
.await
.map_err(|error| format!("{error:?}"))?;
if result.status_code >= 400 {
return Err(admin_gemini_files_execution_error_message(&result));
}
let body_json = admin_gemini_files_execution_json_body(&result)
.ok_or_else(|| "上传成功但上游响应缺少 JSON body".to_string())?;
let success = admin_gemini_files_upload_success_from_body(&body_json, upload)
.ok_or_else(|| admin_gemini_files_execution_error_message(&result))?;
crate::usage::reporting::store_local_gemini_file_mapping(
state,
success.file_name.as_str(),
key.id.as_str(),
None,
success
.display_name
.as_deref()
.or(Some(upload.display_name.as_str())),
success
.mime_type
.as_deref()
.or(Some(upload.mime_type.as_str())),
)
.await
.map_err(|err| format!("上传成功但本地映射写入失败: {err:?}"))?;
Ok(success)
}
async fn admin_gemini_files_execute_upload_plan(
state: &AppState,
trace_id: &str,
plan: &ExecutionPlan,
) -> Result<ExecutionResult, GatewayError> {
crate::execution_runtime::execute_execution_runtime_sync_plan(state, Some(trace_id), plan).await
}
fn admin_gemini_files_execution_json_body(result: &ExecutionResult) -> Option<serde_json::Value> {
if let Some(body_json) = result
.body
.as_ref()
.and_then(|body| body.json_body.as_ref())
{
return Some(body_json.clone());
}
let content_type = result
.headers
.iter()
.find(|(key, _)| key.eq_ignore_ascii_case("content-type"))
.map(|(_, value)| value.trim().to_ascii_lowercase());
if !content_type
.as_deref()
.is_some_and(|value| value.starts_with("application/json"))
{
return None;
}
let body_bytes_b64 = result
.body
.as_ref()
.and_then(|body| body.body_bytes_b64.as_deref())?;
let decoded = base64::engine::general_purpose::STANDARD
.decode(body_bytes_b64)
.ok()?;
serde_json::from_slice(&decoded).ok()
}
fn admin_gemini_files_upload_success_from_body(
body_json: &serde_json::Value,
upload: &AdminGeminiFilesUploadRequest,
) -> Option<AdminGeminiFilesUploadExecutionSuccess> {
let file_object = body_json
.get("file")
.and_then(serde_json::Value::as_object)
.or_else(|| body_json.as_object())?;
let file_name = file_object
.get("name")
.and_then(serde_json::Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())?;
let display_name = file_object
.get("displayName")
.or_else(|| file_object.get("display_name"))
.and_then(serde_json::Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.map(ToOwned::to_owned)
.or_else(|| Some(upload.display_name.clone()));
let mime_type = file_object
.get("mimeType")
.or_else(|| file_object.get("mime_type"))
.and_then(serde_json::Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.map(ToOwned::to_owned)
.or_else(|| Some(upload.mime_type.clone()));
Some(AdminGeminiFilesUploadExecutionSuccess {
file_name: file_name.to_string(),
display_name,
mime_type,
})
}
fn admin_gemini_files_execution_error_message(result: &ExecutionResult) -> String {
if let Some(body_json) = admin_gemini_files_execution_json_body(result) {
if let Some(message) = body_json
.get("error")
.and_then(serde_json::Value::as_object)
.and_then(|error| error.get("message"))
.and_then(serde_json::Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
{
return message.to_string();
}
if let Some(message) = body_json
.get("message")
.and_then(serde_json::Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
{
return message.to_string();
}
}
if let Some(error) = result
.error
.as_ref()
.map(|error| error.message.trim())
.filter(|value| !value.is_empty())
{
return error.to_string();
}
format!("上传失败,状态码 {}", result.status_code)
}

View File

@@ -0,0 +1,65 @@
use super::{admin_gemini_files_error_response, ADMIN_GEMINI_FILES_DATA_UNAVAILABLE_DETAIL};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::is_admin_gemini_files_upload_root;
use crate::GatewayError;
use axum::body::{Body, Bytes};
use axum::http::{self, Response};
use axum::response::IntoResponse;
use axum::Json;
mod request;
mod stage;
mod support;
pub(super) async fn maybe_build_local_admin_gemini_files_upload_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
match request_context
.decision()
.and_then(|decision| decision.route_kind.as_deref())
{
Some("upload")
if request_context.method() == http::Method::POST
&& is_admin_gemini_files_upload_root(request_context.path()) =>
{
if !state.has_gemini_file_mapping_data_writer() {
return Ok(Some(admin_gemini_files_error_response(
http::StatusCode::SERVICE_UNAVAILABLE,
ADMIN_GEMINI_FILES_DATA_UNAVAILABLE_DETAIL,
)));
}
let upload = match request::admin_gemini_files_parse_upload_request(
state,
request_context,
request_body,
) {
Ok(upload) => upload,
Err(detail) => {
return Ok(Some(admin_gemini_files_error_response(
http::StatusCode::BAD_REQUEST,
detail,
)));
}
};
let key_ids = support::admin_gemini_files_query_key_ids(state, request_context);
if key_ids.is_empty() {
return Ok(Some(admin_gemini_files_error_response(
http::StatusCode::BAD_REQUEST,
"key_ids 不能为空",
)));
}
let response = stage::admin_gemini_files_upload_across_keys(
state,
"",
request_context.trace_id(),
&upload,
&key_ids,
)
.await?;
Ok(Some(Json(response).into_response()))
}
_ => Ok(None),
}
}

View File

@@ -0,0 +1,159 @@
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use axum::body::Bytes;
use base64::Engine as _;
#[derive(Debug, Clone)]
pub(super) struct AdminGeminiFilesUploadRequest {
pub(super) display_name: String,
pub(super) mime_type: String,
pub(super) body_bytes: Vec<u8>,
pub(super) body_bytes_b64: String,
}
pub(super) fn admin_gemini_files_parse_upload_request(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&Bytes>,
) -> Result<AdminGeminiFilesUploadRequest, String> {
let _ = state;
let content_type = request_context
.content_type()
.map(str::trim)
.filter(|value| !value.is_empty())
.ok_or_else(|| "Content-Type 缺失".to_string())?;
let boundary = admin_gemini_files_multipart_boundary(content_type)?;
let body = request_body
.filter(|body| !body.is_empty())
.ok_or_else(|| "上传文件不能为空".to_string())?;
let (display_name, mime_type, body_bytes) =
admin_gemini_files_extract_file_part(body.as_ref(), &boundary)?;
Ok(AdminGeminiFilesUploadRequest {
display_name,
mime_type,
body_bytes_b64: base64::engine::general_purpose::STANDARD.encode(&body_bytes),
body_bytes,
})
}
fn admin_gemini_files_multipart_boundary(content_type: &str) -> Result<String, String> {
let normalized = content_type.trim();
if !normalized
.to_ascii_lowercase()
.starts_with("multipart/form-data")
{
return Err("Content-Type 必须是 multipart/form-data".to_string());
}
for part in normalized.split(';').skip(1) {
let Some((key, value)) = part.trim().split_once('=') else {
continue;
};
if !key.trim().eq_ignore_ascii_case("boundary") {
continue;
}
let boundary = value.trim().trim_matches('"').trim();
if !boundary.is_empty() {
return Ok(boundary.to_string());
}
}
Err("multipart boundary 缺失".to_string())
}
fn admin_gemini_files_extract_file_part(
body: &[u8],
boundary: &str,
) -> Result<(String, String, Vec<u8>), String> {
let boundary_marker = format!("--{boundary}");
let next_boundary_marker = format!("\r\n--{boundary}");
let boundary_bytes = boundary_marker.as_bytes();
let next_boundary_bytes = next_boundary_marker.as_bytes();
let mut cursor = 0usize;
while cursor < body.len() {
if !body[cursor..].starts_with(boundary_bytes) {
return Err("multipart body 格式无效".to_string());
}
cursor += boundary_bytes.len();
if body[cursor..].starts_with(b"--") {
break;
}
if !body[cursor..].starts_with(b"\r\n") {
return Err("multipart body 缺少头部分隔符".to_string());
}
cursor += 2;
let Some(headers_end_rel) = admin_gemini_files_find_subslice(&body[cursor..], b"\r\n\r\n")
else {
return Err("multipart part 缺少头部".to_string());
};
let headers_end = cursor + headers_end_rel;
let headers_text = std::str::from_utf8(&body[cursor..headers_end])
.map_err(|_| "multipart part 头部编码无效".to_string())?;
cursor = headers_end + 4;
let Some(next_boundary_rel) =
admin_gemini_files_find_subslice(&body[cursor..], next_boundary_bytes)
else {
return Err("multipart body 缺少结束边界".to_string());
};
let content_end = cursor + next_boundary_rel;
let content = &body[cursor..content_end];
cursor = content_end + 2;
let Some((field_name, file_name, mime_type)) =
admin_gemini_files_parse_part_headers(headers_text)
else {
continue;
};
if field_name != "file" {
continue;
}
return Ok((
file_name.unwrap_or_else(|| "uploaded-file".to_string()),
mime_type.unwrap_or_else(|| "application/octet-stream".to_string()),
content.to_vec(),
));
}
Err("multipart body 中缺少 file 字段".to_string())
}
fn admin_gemini_files_parse_part_headers(
headers_text: &str,
) -> Option<(String, Option<String>, Option<String>)> {
let mut field_name = None;
let mut file_name = None;
let mut mime_type = None;
for line in headers_text.split("\r\n") {
let Some((header_name, header_value)) = line.split_once(':') else {
continue;
};
let header_name = header_name.trim();
let header_value = header_value.trim();
if header_name.eq_ignore_ascii_case("content-disposition") {
for part in header_value.split(';').skip(1) {
let Some((key, value)) = part.trim().split_once('=') else {
continue;
};
let key = key.trim();
let value = value.trim().trim_matches('"').trim();
if key.eq_ignore_ascii_case("name") && !value.is_empty() {
field_name = Some(value.to_string());
} else if key.eq_ignore_ascii_case("filename") && !value.is_empty() {
file_name = Some(value.to_string());
}
}
} else if header_name.eq_ignore_ascii_case("content-type") && !header_value.is_empty() {
mime_type = Some(header_value.to_string());
}
}
field_name.map(|field_name| (field_name, file_name, mime_type))
}
fn admin_gemini_files_find_subslice(haystack: &[u8], needle: &[u8]) -> Option<usize> {
if haystack.is_empty() || needle.is_empty() || haystack.len() < needle.len() {
return None;
}
haystack
.windows(needle.len())
.position(|window| window == needle)
}

View File

@@ -0,0 +1,351 @@
use super::super::admin_gemini_files_key_capable;
use super::request::AdminGeminiFilesUploadRequest;
use crate::handlers::admin::request::AdminAppState;
use crate::GatewayError;
use aether_contracts::{ExecutionPlan, ExecutionResult, RequestBody};
use aether_data_contracts::repository::provider_catalog::{
StoredProviderCatalogEndpoint, StoredProviderCatalogKey,
};
use axum::http;
use base64::Engine;
use serde_json::json;
use std::collections::{BTreeMap, BTreeSet};
#[derive(Debug)]
struct AdminGeminiFilesUploadExecutionSuccess {
file_name: String,
display_name: Option<String>,
mime_type: Option<String>,
}
pub(super) async fn admin_gemini_files_upload_across_keys(
state: &AdminAppState<'_>,
execution_runtime_base_url: &str,
trace_id: &str,
upload: &AdminGeminiFilesUploadRequest,
requested_key_ids: &[String],
) -> Result<serde_json::Value, GatewayError> {
let keys = state
.read_provider_catalog_keys_by_ids(requested_key_ids)
.await?;
let key_by_id = keys
.iter()
.map(|key| (key.id.as_str(), key))
.collect::<BTreeMap<_, _>>();
let provider_ids = keys
.iter()
.map(|key| key.provider_id.clone())
.collect::<BTreeSet<_>>()
.into_iter()
.collect::<Vec<_>>();
let endpoints = state
.list_provider_catalog_endpoints_by_provider_ids(&provider_ids)
.await?;
let endpoints_by_provider_id = endpoints.into_iter().fold(
BTreeMap::<String, Vec<StoredProviderCatalogEndpoint>>::new(),
|mut out, endpoint| {
out.entry(endpoint.provider_id.clone())
.or_default()
.push(endpoint);
out
},
);
let mut results = Vec::new();
let mut success_count = 0usize;
let mut fail_count = 0usize;
for key_id in requested_key_ids {
let Some(key) = key_by_id.get(key_id.as_str()) else {
fail_count += 1;
results.push(json!({
"key_id": key_id,
"key_name": serde_json::Value::Null,
"success": false,
"file_name": serde_json::Value::Null,
"error": "Key 不存在",
}));
continue;
};
let key_name = Some(key.name.clone());
let outcome = admin_gemini_files_upload_single_key(
state,
execution_runtime_base_url,
trace_id,
upload,
key,
endpoints_by_provider_id.get(&key.provider_id),
)
.await;
match outcome {
Ok(success) => {
success_count += 1;
results.push(json!({
"key_id": key.id,
"key_name": key_name,
"success": true,
"file_name": success.file_name,
"error": serde_json::Value::Null,
}));
}
Err(error) => {
fail_count += 1;
results.push(json!({
"key_id": key.id,
"key_name": key_name,
"success": false,
"file_name": serde_json::Value::Null,
"error": error,
}));
}
}
}
Ok(json!({
"display_name": upload.display_name,
"mime_type": upload.mime_type,
"size_bytes": upload.body_bytes.len(),
"results": results,
"success_count": success_count,
"fail_count": fail_count,
}))
}
async fn admin_gemini_files_upload_single_key(
state: &AdminAppState<'_>,
_execution_runtime_base_url: &str,
trace_id: &str,
upload: &AdminGeminiFilesUploadRequest,
key: &StoredProviderCatalogKey,
endpoints: Option<&Vec<StoredProviderCatalogEndpoint>>,
) -> Result<AdminGeminiFilesUploadExecutionSuccess, String> {
if !admin_gemini_files_key_capable(key) {
return Err("Key 不支持 Gemini Files".to_string());
}
let Some(endpoint) = endpoints.and_then(|endpoints| {
endpoints.iter().find(|endpoint| {
endpoint.is_active
&& endpoint
.api_format
.trim()
.eq_ignore_ascii_case("gemini:chat")
})
}) else {
return Err("找不到有效的 gemini:chat 端点".to_string());
};
let transport = state
.read_provider_transport_snapshot(&key.provider_id, &endpoint.id, &key.id)
.await
.map_err(|err| format!("{err:?}"))?
.ok_or_else(|| "无法读取 Key 传输配置".to_string())?;
if !state.supports_local_gemini_transport_with_network(&transport, "gemini:chat") {
return Err("Key 传输配置不支持 Gemini Files 上传".to_string());
}
if transport.endpoint.body_rules.is_some() {
return Err("Gemini Files 二进制上传暂不支持 endpoint body_rules".to_string());
}
let (auth_header, auth_value) = state
.resolve_local_gemini_auth(&transport)
.ok_or_else(|| "Key 缺少可用的 Gemini 认证信息".to_string())?;
let mut provider_request_headers = state.build_passthrough_headers_with_auth(
&http::HeaderMap::new(),
&auth_header,
&auth_value,
&BTreeMap::new(),
);
provider_request_headers.insert("content-type".to_string(), upload.mime_type.clone());
let original_request_body = json!({
"body_bytes_b64": upload.body_bytes_b64,
});
if !state.apply_local_header_rules(
&mut provider_request_headers,
transport.endpoint.header_rules.as_ref(),
&[auth_header.as_str(), "content-type"],
&original_request_body,
Some(&original_request_body),
) {
return Err("Key 端点 header_rules 应用失败".to_string());
}
let upload_path = transport
.endpoint
.custom_path
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.unwrap_or("/upload/v1beta/files");
let upload_query = if upload_path.contains("uploadType=") {
None
} else {
Some("uploadType=resumable")
};
let upstream_url = state
.build_gemini_files_passthrough_url(&transport.endpoint.base_url, upload_path, upload_query)
.ok_or_else(|| "无法构建 Gemini Files 上传地址".to_string())?;
let plan = ExecutionPlan {
request_id: format!("{trace_id}:admin-gemini-upload:{}", key.id),
candidate_id: None,
provider_name: Some(transport.provider.name.clone()),
provider_id: transport.provider.id.clone(),
endpoint_id: transport.endpoint.id.clone(),
key_id: transport.key.id.clone(),
method: "POST".to_string(),
url: upstream_url,
headers: provider_request_headers,
content_type: Some(upload.mime_type.clone()),
content_encoding: None,
body: RequestBody {
json_body: None,
body_bytes_b64: Some(upload.body_bytes_b64.clone()),
body_ref: None,
},
stream: false,
client_api_format: "gemini:files".to_string(),
provider_api_format: "gemini:files".to_string(),
model_name: Some("gemini-files".to_string()),
proxy: state
.resolve_transport_proxy_snapshot_with_tunnel_affinity(&transport)
.await,
tls_profile: state.resolve_transport_tls_profile(&transport),
timeouts: state.resolve_transport_execution_timeouts(&transport),
};
let result = admin_gemini_files_execute_upload_plan(state, trace_id, &plan)
.await
.map_err(|error| format!("{error:?}"))?;
if result.status_code >= 400 {
return Err(admin_gemini_files_execution_error_message(&result));
}
let body_json = admin_gemini_files_execution_json_body(&result)
.ok_or_else(|| "上传成功但上游响应缺少 JSON body".to_string())?;
let success = admin_gemini_files_upload_success_from_body(&body_json, upload)
.ok_or_else(|| admin_gemini_files_execution_error_message(&result))?;
state
.store_local_gemini_file_mapping(
success.file_name.as_str(),
key.id.as_str(),
None,
success
.display_name
.as_deref()
.or(Some(upload.display_name.as_str())),
success
.mime_type
.as_deref()
.or(Some(upload.mime_type.as_str())),
)
.await
.map_err(|err| format!("上传成功但本地映射写入失败: {err:?}"))?;
Ok(success)
}
async fn admin_gemini_files_execute_upload_plan(
state: &AdminAppState<'_>,
trace_id: &str,
plan: &ExecutionPlan,
) -> Result<ExecutionResult, GatewayError> {
state
.execute_execution_runtime_sync_plan(Some(trace_id), plan)
.await
}
fn admin_gemini_files_execution_json_body(result: &ExecutionResult) -> Option<serde_json::Value> {
if let Some(body_json) = result
.body
.as_ref()
.and_then(|body| body.json_body.as_ref())
{
return Some(body_json.clone());
}
let content_type = result
.headers
.iter()
.find(|(key, _)| key.eq_ignore_ascii_case("content-type"))
.map(|(_, value)| value.trim().to_ascii_lowercase());
if !content_type
.as_deref()
.is_some_and(|value| value.starts_with("application/json"))
{
return None;
}
let body_bytes_b64 = result
.body
.as_ref()
.and_then(|body| body.body_bytes_b64.as_deref())?;
let decoded = base64::engine::general_purpose::STANDARD
.decode(body_bytes_b64)
.ok()?;
serde_json::from_slice(&decoded).ok()
}
fn admin_gemini_files_upload_success_from_body(
body_json: &serde_json::Value,
upload: &AdminGeminiFilesUploadRequest,
) -> Option<AdminGeminiFilesUploadExecutionSuccess> {
let file_object = body_json
.get("file")
.and_then(serde_json::Value::as_object)
.or_else(|| body_json.as_object())?;
let file_name = file_object
.get("name")
.and_then(serde_json::Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())?;
let display_name = file_object
.get("displayName")
.or_else(|| file_object.get("display_name"))
.and_then(serde_json::Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.map(ToOwned::to_owned)
.or_else(|| Some(upload.display_name.clone()));
let mime_type = file_object
.get("mimeType")
.or_else(|| file_object.get("mime_type"))
.and_then(serde_json::Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
.map(ToOwned::to_owned)
.or_else(|| Some(upload.mime_type.clone()));
Some(AdminGeminiFilesUploadExecutionSuccess {
file_name: file_name.to_string(),
display_name,
mime_type,
})
}
fn admin_gemini_files_execution_error_message(result: &ExecutionResult) -> String {
if let Some(body_json) = admin_gemini_files_execution_json_body(result) {
if let Some(message) = body_json
.get("error")
.and_then(serde_json::Value::as_object)
.and_then(|error| error.get("message"))
.and_then(serde_json::Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
{
return message.to_string();
}
if let Some(message) = body_json
.get("message")
.and_then(serde_json::Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
{
return message.to_string();
}
}
if let Some(error) = result
.error
.as_ref()
.map(|error| error.message.trim())
.filter(|value| !value.is_empty())
{
return error.to_string();
}
format!("上传失败,状态码 {}", result.status_code)
}

View File

@@ -0,0 +1,22 @@
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::query_param_value;
pub(super) fn admin_gemini_files_query_key_ids(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Vec<String> {
let _ = state;
let mut key_ids = Vec::new();
let mut seen = std::collections::BTreeSet::new();
let Some(raw) = query_param_value(request_context.query_string(), "key_ids") else {
return key_ids;
};
for key_id in raw.split(',') {
let trimmed = key_id.trim();
if trimmed.is_empty() || !seen.insert(trimmed.to_string()) {
continue;
}
key_ids.push(trimmed.to_string());
}
key_ids
}

View File

@@ -1,5 +1,7 @@
mod gemini_files;
mod routes;
mod video_tasks;
pub(crate) use self::gemini_files::maybe_build_local_admin_gemini_files_response;
pub(super) use self::gemini_files::maybe_build_local_admin_gemini_files_response;
pub(super) use self::routes::maybe_build_local_admin_features_response;
pub(crate) use self::video_tasks::maybe_build_local_admin_video_tasks_response;

View File

@@ -0,0 +1,27 @@
use super::{gemini_files, video_tasks};
use crate::handlers::admin::request::{AdminRouteRequest, AdminRouteResult};
pub(crate) async fn maybe_build_local_admin_features_response(
request: AdminRouteRequest<'_>,
) -> AdminRouteResult {
if let Some(response) = video_tasks::maybe_build_local_admin_video_tasks_response(
&request.state(),
&request.request_context(),
)
.await?
{
return Ok(Some(response));
}
if let Some(response) = gemini_files::maybe_build_local_admin_gemini_files_response(
&request.state(),
&request.request_context(),
request.request_body(),
)
.await?
{
return Ok(Some(response));
}
Ok(None)
}

View File

@@ -1,4 +1,5 @@
use crate::{AppState, GatewayError};
use crate::handlers::admin::request::AdminAppState;
use crate::GatewayError;
use aether_data_contracts::repository::video_tasks::{StoredVideoTask, VideoTaskStatus};
use axum::http;
use chrono::{SecondsFormat, Utc};
@@ -41,7 +42,7 @@ pub(super) fn truncate_admin_video_task_prompt(prompt: Option<&str>) -> Option<S
}
pub(super) async fn build_admin_video_task_provider_names(
state: &AppState,
state: &AdminAppState<'_>,
tasks: &[StoredVideoTask],
) -> Result<BTreeMap<String, String>, GatewayError> {
let provider_ids = tasks
@@ -55,6 +56,7 @@ pub(super) async fn build_admin_video_task_provider_names(
return Ok(BTreeMap::new());
}
Ok(state
.app()
.read_provider_catalog_providers_by_ids(&provider_ids)
.await?
.into_iter()

View File

@@ -1,13 +1,13 @@
use crate::control::GatewayPublicRequestContext;
use crate::{AppState, GatewayError};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::GatewayError;
use axum::{body::Body, response::Response};
mod builders;
mod routes;
pub(crate) async fn maybe_build_local_admin_video_tasks_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Option<Response<Body>>, GatewayError> {
routes::maybe_build_local_admin_video_tasks_response(state, request_context).await
}

View File

@@ -1,9 +1,10 @@
use crate::async_task;
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::request::{
AdminAppState, AdminCancelVideoTaskError, AdminRequestContext,
};
use crate::handlers::admin::shared::{
attach_admin_audit_response, build_proxy_error_response, query_param_value,
};
use crate::{AppState, GatewayError};
use crate::GatewayError;
use aether_data_contracts::repository::video_tasks::{VideoTaskQueryFilter, VideoTaskStatus};
use axum::{
body::Body,
@@ -20,54 +21,46 @@ use super::builders::{
};
pub(super) async fn maybe_build_local_admin_video_tasks_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Option<Response<Body>>, GatewayError> {
let Some(decision) = request_context.control_decision.as_ref() else {
return Ok(None);
};
if decision.route_family.as_deref() != Some("video_tasks_manage") {
if request_context.route_family() != Some("video_tasks_manage") {
return Ok(None);
}
if request_context.request_method == http::Method::GET
if request_context.method() == http::Method::GET
&& matches!(
request_context.request_path.as_str(),
request_context.path(),
"/api/admin/video-tasks" | "/api/admin/video-tasks/"
)
{
let status =
match query_param_value(request_context.request_query_string.as_deref(), "status") {
Some(value) => match VideoTaskStatus::from_database(&value) {
Ok(status) => Some(status),
Err(err) => {
return Ok(Some(build_proxy_error_response(
http::StatusCode::BAD_REQUEST,
"invalid_request",
err.to_string(),
None,
)));
}
},
None => None,
};
let status = match query_param_value(request_context.query_string(), "status") {
Some(value) => match VideoTaskStatus::from_database(&value) {
Ok(status) => Some(status),
Err(err) => {
return Ok(Some(build_proxy_error_response(
http::StatusCode::BAD_REQUEST,
"invalid_request",
err.to_string(),
None,
)));
}
},
None => None,
};
let filter = VideoTaskQueryFilter {
user_id: query_param_value(request_context.request_query_string.as_deref(), "user_id"),
user_id: query_param_value(request_context.query_string(), "user_id"),
status,
model_substring: query_param_value(
request_context.request_query_string.as_deref(),
"model",
),
model_substring: query_param_value(request_context.query_string(), "model"),
client_api_format: None,
};
let page = query_param_value(request_context.request_query_string.as_deref(), "page")
let page = query_param_value(request_context.query_string(), "page")
.and_then(|value| value.parse::<usize>().ok())
.unwrap_or(1);
let page_size =
query_param_value(request_context.request_query_string.as_deref(), "page_size")
.and_then(|value| value.parse::<usize>().ok())
.unwrap_or(20);
let response = async_task::read_video_task_page(state, &filter, page, page_size).await?;
let page_size = query_param_value(request_context.query_string(), "page_size")
.and_then(|value| value.parse::<usize>().ok())
.unwrap_or(20);
let response = state.read_video_task_page(&filter, page, page_size).await?;
let provider_names = build_admin_video_task_provider_names(state, &response.items).await?;
return Ok(Some(
Json(json!({
@@ -85,9 +78,9 @@ pub(super) async fn maybe_build_local_admin_video_tasks_response(
));
}
if request_context.request_method == http::Method::GET
if request_context.method() == http::Method::GET
&& matches!(
request_context.request_path.as_str(),
request_context.path(),
"/api/admin/video-tasks/stats" | "/api/admin/video-tasks/stats/"
)
{
@@ -97,9 +90,9 @@ pub(super) async fn maybe_build_local_admin_video_tasks_response(
model_substring: None,
client_api_format: None,
};
let stats =
async_task::read_video_task_stats(state, &filter, current_admin_video_task_unix_secs())
.await?;
let stats = state
.read_video_task_stats(&filter, current_admin_video_task_unix_secs())
.await?;
let active_users = state.count_distinct_video_task_users(&filter).await?;
return Ok(Some(
Json(json!({
@@ -114,15 +107,14 @@ pub(super) async fn maybe_build_local_admin_video_tasks_response(
));
}
if request_context.request_method == http::Method::POST {
let Some(task_id) =
admin_video_task_nested_id_from_path(&request_context.request_path, "/cancel")
if request_context.method() == http::Method::POST {
let Some(task_id) = admin_video_task_nested_id_from_path(request_context.path(), "/cancel")
else {
return Ok(None);
};
let stored = match async_task::cancel_video_task_record(state, task_id).await {
let stored = match state.cancel_video_task_record(task_id).await {
Ok(stored) => stored,
Err(async_task::CancelVideoTaskError::NotFound) => {
Err(AdminCancelVideoTaskError::NotFound) => {
return Ok(Some(
(
http::StatusCode::NOT_FOUND,
@@ -131,7 +123,7 @@ pub(super) async fn maybe_build_local_admin_video_tasks_response(
.into_response(),
));
}
Err(async_task::CancelVideoTaskError::InvalidStatus(status)) => {
Err(AdminCancelVideoTaskError::InvalidStatus(status)) => {
return Ok(Some(
(
http::StatusCode::BAD_REQUEST,
@@ -145,10 +137,10 @@ pub(super) async fn maybe_build_local_admin_video_tasks_response(
.into_response(),
));
}
Err(async_task::CancelVideoTaskError::Response(response)) => {
Err(AdminCancelVideoTaskError::Response(response)) => {
return Ok(Some(response));
}
Err(async_task::CancelVideoTaskError::Gateway(err)) => {
Err(AdminCancelVideoTaskError::Gateway(err)) => {
return Err(err);
}
};
@@ -166,15 +158,13 @@ pub(super) async fn maybe_build_local_admin_video_tasks_response(
)));
}
if request_context.request_method == http::Method::GET {
let Some(task_id) =
admin_video_task_nested_id_from_path(&request_context.request_path, "/video")
if request_context.method() == http::Method::GET {
let Some(task_id) = admin_video_task_nested_id_from_path(request_context.path(), "/video")
else {
let Some(task_id) = admin_video_task_detail_id_from_path(&request_context.request_path)
else {
let Some(task_id) = admin_video_task_detail_id_from_path(request_context.path()) else {
return Ok(None);
};
let Some(task) = async_task::read_video_task_detail(state, task_id).await? else {
let Some(task) = state.read_video_task_detail(task_id).await? else {
return Ok(Some(
(
http::StatusCode::NOT_FOUND,
@@ -306,7 +296,7 @@ pub(super) async fn maybe_build_local_admin_video_tasks_response(
&task.id,
)));
};
let Some(task) = async_task::read_video_task_detail(state, task_id).await? else {
let Some(task) = state.read_video_task_detail(task_id).await? else {
return Ok(Some(
(
http::StatusCode::NOT_FOUND,
@@ -330,7 +320,7 @@ pub(super) async fn maybe_build_local_admin_video_tasks_response(
.into_response(),
));
}
let Some(source) = async_task::read_video_task_video_source(state, task_id).await? else {
let Some(source) = state.read_video_task_video_source(task_id).await? else {
return Ok(Some(
(
http::StatusCode::NOT_FOUND,
@@ -340,7 +330,9 @@ pub(super) async fn maybe_build_local_admin_video_tasks_response(
));
};
return Ok(Some(attach_admin_audit_response(
async_task::build_video_task_video_response(state, task_id, source).await?,
state
.build_video_task_video_response(task_id, source)
.await?,
"admin_video_task_video_viewed",
"view_video_task_video",
"video_task_video",

View File

@@ -1,11 +1,33 @@
pub(crate) mod shared;
mod announcements;
pub(super) mod auth;
mod billing;
pub(super) mod endpoint;
pub(super) mod features;
mod model;
pub(super) mod observability;
pub(super) mod provider;
mod system;
mod users;
pub(crate) mod auth;
pub(crate) mod billing;
pub(crate) mod endpoint;
pub(crate) mod features;
pub(crate) mod model;
pub(crate) mod observability;
pub(crate) mod provider;
pub(crate) mod system;
pub(crate) mod users;
pub(super) mod request;
pub(super) mod routes;
mod shared;
pub(crate) use self::auth::maybe_build_local_admin_security_response;
pub(crate) use self::endpoint::build_admin_endpoint_health_status_payload;
pub(crate) use self::features::maybe_build_local_admin_video_tasks_response;
pub(crate) use self::observability::{
admin_stats_bad_request_response, list_usage_for_optional_range,
maybe_build_local_admin_usage_response, parse_bounded_u32, round_to, AdminStatsTimeRange,
AdminStatsUsageFilter,
};
pub(crate) use self::provider::oauth::errors::build_internal_control_error_response;
pub(crate) use self::provider::ops::providers::actions::admin_provider_ops_local_action_response;
pub(crate) use self::provider::pool_admin::maybe_build_local_admin_pool_response;
pub(crate) use self::provider::{
maybe_build_local_admin_provider_oauth_response, maybe_build_local_admin_providers_response,
};
pub(crate) use self::request::{
AdminAppState, AdminRequestContext, AdminRouteRequest, AdminRouteResponse, AdminRouteResult,
};
pub(crate) use self::routes::maybe_build_local_admin_response;

View File

@@ -1,9 +1,6 @@
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::model::{
build_admin_model_catalog_payload, clear_admin_external_models_cache,
read_admin_external_models_cache,
};
use crate::{AppState, GatewayError};
use crate::handlers::admin::model::build_admin_model_catalog_payload;
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::GatewayError;
use axum::{
body::Body,
http,
@@ -23,17 +20,17 @@ fn build_admin_model_catalog_data_unavailable_response() -> Response<Body> {
}
pub(crate) async fn maybe_build_local_admin_model_catalog_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Option<Response<Body>>, GatewayError> {
let Some(decision) = request_context.control_decision.as_ref() else {
let Some(decision) = request_context.decision() else {
return Ok(None);
};
if decision.route_family.as_deref() == Some("model_catalog_manage")
&& decision.route_kind.as_deref() == Some("catalog")
&& request_context.request_method == http::Method::GET
&& request_context.request_path == "/api/admin/models/catalog"
&& request_context.method() == http::Method::GET
&& request_context.path() == "/api/admin/models/catalog"
{
if !state.has_global_model_data_reader() || !state.has_provider_catalog_data_reader() {
return Ok(Some(build_admin_model_catalog_data_unavailable_response()));
@@ -46,11 +43,11 @@ pub(crate) async fn maybe_build_local_admin_model_catalog_response(
if decision.route_family.as_deref() == Some("model_external_manage")
&& decision.route_kind.as_deref() == Some("external")
&& request_context.request_method == http::Method::GET
&& request_context.request_path == "/api/admin/models/external"
&& request_context.method() == http::Method::GET
&& request_context.path() == "/api/admin/models/external"
{
return Ok(Some(
match read_admin_external_models_cache(state).await? {
match state.read_admin_external_models_cache().await? {
Some(payload) => Json(payload).into_response(),
None => (
http::StatusCode::SERVICE_UNAVAILABLE,
@@ -65,11 +62,11 @@ pub(crate) async fn maybe_build_local_admin_model_catalog_response(
if decision.route_family.as_deref() == Some("model_external_manage")
&& decision.route_kind.as_deref() == Some("clear_external_cache")
&& request_context.request_method == http::Method::DELETE
&& request_context.request_path == "/api/admin/models/external/cache"
&& request_context.method() == http::Method::DELETE
&& request_context.path() == "/api/admin/models/external/cache"
{
return Ok(Some(
Json(clear_admin_external_models_cache(state).await?).into_response(),
Json(state.clear_admin_external_models_cache().await?).into_response(),
));
}

View File

@@ -1,5 +1,6 @@
use crate::handlers::admin::request::AdminAppState;
use crate::handlers::shared::mark_external_models_official_providers;
use crate::{AppState, GatewayError};
use crate::GatewayError;
use serde_json::json;
use tracing::warn;
@@ -21,7 +22,7 @@ fn normalize_admin_external_models_payload(payload: serde_json::Value) -> serde_
}
async fn store_admin_external_models_cache(
state: &AppState,
state: &AdminAppState<'_>,
payload: &serde_json::Value,
) -> Result<(), GatewayError> {
let Some(runner) = state.redis_kv_runner() else {
@@ -41,11 +42,11 @@ async fn store_admin_external_models_cache(
}
async fn fetch_admin_external_models_from_source(
state: &AppState,
state: &AdminAppState<'_>,
) -> Result<serde_json::Value, GatewayError> {
let url = admin_external_models_source_url();
let response = state
.client
.http_client()
.get(&url)
.send()
.await
@@ -61,7 +62,7 @@ async fn fetch_admin_external_models_from_source(
}
pub(crate) async fn read_admin_external_models_cache(
state: &AppState,
state: &AdminAppState<'_>,
) -> Result<Option<serde_json::Value>, GatewayError> {
if let Some(runner) = state.redis_kv_runner() {
match runner.client().get_multiplexed_async_connection().await {
@@ -113,7 +114,7 @@ pub(crate) async fn read_admin_external_models_cache(
}
pub(crate) async fn clear_admin_external_models_cache(
state: &AppState,
state: &AdminAppState<'_>,
) -> Result<serde_json::Value, GatewayError> {
let Some(runner) = state.redis_kv_runner() else {
return Ok(json!({
@@ -137,14 +138,22 @@ mod tests {
admin_external_models_source_url, normalize_admin_external_models_payload,
read_admin_external_models_cache, ADMIN_EXTERNAL_MODELS_SOURCE_URL_ENV,
};
use crate::handlers::admin::request::AdminAppState;
use crate::tests::{start_server, AppState};
use axum::routing::get;
use axum::{Json, Router};
use serde_json::json;
use std::sync::{Mutex, MutexGuard, OnceLock};
fn admin_external_models_env_lock() -> &'static Mutex<()> {
static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
LOCK.get_or_init(|| Mutex::new(()))
}
struct TestEnvVarGuard {
key: &'static str,
previous: Option<String>,
_lock: Option<MutexGuard<'static, ()>>,
}
impl Drop for TestEnvVarGuard {
@@ -158,9 +167,14 @@ mod tests {
}
fn set_test_env_var(key: &'static str, value: &str) -> TestEnvVarGuard {
let lock = admin_external_models_env_lock().lock().ok();
let previous = std::env::var(key).ok();
std::env::set_var(key, value);
TestEnvVarGuard { key, previous }
TestEnvVarGuard {
key,
previous,
_lock: lock,
}
}
#[test]
@@ -218,7 +232,7 @@ mod tests {
);
let state = AppState::new().expect("gateway should build");
let payload = read_admin_external_models_cache(&state)
let payload = read_admin_external_models_cache(&AdminAppState::new(&state))
.await
.expect("external models read should succeed")
.expect("payload should be fetched");

View File

@@ -0,0 +1,110 @@
use super::super::payloads::{
admin_provider_model_effective_input_price, admin_provider_model_effective_output_price,
model_tiered_pricing_first_tier_value,
};
use crate::handlers::admin::request::AdminAppState;
use aether_data_contracts::repository::global_models::{
StoredAdminGlobalModel, StoredAdminProviderModel,
};
use futures_util::stream::{self, StreamExt};
use serde_json::json;
use std::collections::{BTreeMap, BTreeSet};
use std::time::{SystemTime, UNIX_EPOCH};
pub(crate) async fn resolve_admin_global_model_by_id_or_err(
state: &AdminAppState<'_>,
global_model_id: &str,
) -> Result<StoredAdminGlobalModel, String> {
state
.get_admin_global_model_by_id(global_model_id)
.await
.map_err(|err| format!("{err:?}"))?
.ok_or_else(|| format!("GlobalModel {global_model_id} 不存在"))
}
pub(super) fn admin_global_models_now_unix_secs() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.ok()
.map(|duration| duration.as_secs())
.unwrap_or(0)
}
pub(super) fn admin_global_model_provider_counts(
provider_models: &[StoredAdminProviderModel],
) -> (usize, usize, usize) {
let total_models = provider_models.len();
let total_providers = provider_models
.iter()
.map(|model| model.provider_id.clone())
.collect::<BTreeSet<_>>()
.len();
let active_provider_count = provider_models
.iter()
.filter(|model| model.is_active && model.is_available)
.map(|model| model.provider_id.clone())
.collect::<BTreeSet<_>>()
.len();
(total_models, total_providers, active_provider_count)
}
pub(super) fn build_admin_global_model_price_range(
global_model: &StoredAdminGlobalModel,
provider_models: &[StoredAdminProviderModel],
) -> serde_json::Value {
let mut input_values = provider_models
.iter()
.filter_map(admin_provider_model_effective_input_price)
.collect::<Vec<_>>();
let mut output_values = provider_models
.iter()
.filter_map(admin_provider_model_effective_output_price)
.collect::<Vec<_>>();
if input_values.is_empty() {
if let Some(value) = model_tiered_pricing_first_tier_value(
global_model.default_tiered_pricing.as_ref(),
"input_price_per_1m",
) {
input_values.push(value);
}
}
if output_values.is_empty() {
if let Some(value) = model_tiered_pricing_first_tier_value(
global_model.default_tiered_pricing.as_ref(),
"output_price_per_1m",
) {
output_values.push(value);
}
}
json!({
"min_input": input_values.iter().copied().reduce(f64::min),
"max_input": input_values.iter().copied().reduce(f64::max),
"min_output": output_values.iter().copied().reduce(f64::min),
"max_output": output_values.iter().copied().reduce(f64::max),
})
}
pub(super) async fn admin_global_model_provider_models_by_global_model_id(
state: &AdminAppState<'_>,
global_model_ids: &[String],
) -> BTreeMap<String, Vec<StoredAdminProviderModel>> {
let state = *state;
stream::iter(global_model_ids.iter().cloned().map(|global_model_id| {
let state = state;
async move {
let provider_models = state
.list_admin_provider_models_by_global_model_id(&global_model_id)
.await
.ok()
.unwrap_or_default();
(global_model_id, provider_models)
}
}))
.buffer_unordered(32)
.collect::<Vec<_>>()
.await
.into_iter()
.collect()
}

View File

@@ -0,0 +1,12 @@
mod helpers;
mod payloads;
mod providers;
pub(crate) use helpers::resolve_admin_global_model_by_id_or_err;
pub(crate) use payloads::{
build_admin_global_model_payload, build_admin_global_model_response,
build_admin_global_models_payload,
};
pub(crate) use providers::{
build_admin_global_model_providers_payload, build_admin_model_catalog_payload,
};

View File

@@ -0,0 +1,113 @@
use super::super::super::shared::json_string_list;
use super::super::payloads::timestamp_or_now;
use super::helpers::{
admin_global_model_provider_counts, admin_global_model_provider_models_by_global_model_id,
admin_global_models_now_unix_secs, build_admin_global_model_price_range,
};
use crate::handlers::admin::request::AdminAppState;
use aether_data_contracts::repository::global_models::{
AdminGlobalModelListQuery, StoredAdminGlobalModel, StoredAdminProviderModel,
};
use serde_json::json;
pub(crate) fn build_admin_global_model_response(
global_model: &StoredAdminGlobalModel,
provider_models: &[StoredAdminProviderModel],
now_unix_secs: u64,
) -> serde_json::Value {
let (_, provider_count, active_provider_count) =
admin_global_model_provider_counts(provider_models);
json!({
"id": &global_model.id,
"name": &global_model.name,
"display_name": &global_model.display_name,
"is_active": global_model.is_active,
"default_price_per_request": global_model.default_price_per_request,
"default_tiered_pricing": global_model.default_tiered_pricing.clone(),
"supported_capabilities": json_string_list(global_model.supported_capabilities.as_ref()),
"config": global_model.config.clone(),
"provider_count": provider_count,
"active_provider_count": active_provider_count,
"created_at": timestamp_or_now(global_model.created_at_unix_secs, now_unix_secs),
"updated_at": timestamp_or_now(global_model.updated_at_unix_secs, now_unix_secs),
})
}
pub(crate) async fn build_admin_global_models_payload(
state: &AdminAppState<'_>,
skip: usize,
limit: usize,
is_active: Option<bool>,
search: Option<String>,
) -> Option<serde_json::Value> {
if !state.has_global_model_data_reader() {
return None;
}
let page = state
.list_admin_global_models(&AdminGlobalModelListQuery {
offset: skip,
limit,
is_active,
search,
})
.await
.ok()?;
let now_unix_secs = admin_global_models_now_unix_secs();
let mut models = page.items;
models.sort_by(|left, right| {
left.name
.cmp(&right.name)
.then_with(|| left.id.cmp(&right.id))
});
let global_model_ids = models
.iter()
.map(|model| model.id.clone())
.collect::<Vec<_>>();
let mut provider_models_by_global_model =
admin_global_model_provider_models_by_global_model_id(state, &global_model_ids).await;
let mut payload_models = Vec::with_capacity(models.len());
for model in models {
let provider_models = provider_models_by_global_model
.remove(&model.id)
.unwrap_or_default();
payload_models.push(build_admin_global_model_response(
&model,
&provider_models,
now_unix_secs,
));
}
Some(json!({
"models": payload_models,
"total": page.total,
}))
}
pub(crate) async fn build_admin_global_model_payload(
state: &AdminAppState<'_>,
global_model_id: &str,
) -> Option<serde_json::Value> {
if !state.has_global_model_data_reader() {
return None;
}
let model = state
.get_admin_global_model_by_id(global_model_id)
.await
.ok()??;
let provider_models = state
.list_admin_provider_models_by_global_model_id(&model.id)
.await
.ok()
.unwrap_or_default();
let now_unix_secs = admin_global_models_now_unix_secs();
let (total_models, total_providers, _) = admin_global_model_provider_counts(&provider_models);
let mut payload = build_admin_global_model_response(&model, &provider_models, now_unix_secs);
if let Some(object) = payload.as_object_mut() {
object.insert("total_models".to_string(), json!(total_models));
object.insert("total_providers".to_string(), json!(total_providers));
object.insert(
"price_range".to_string(),
build_admin_global_model_price_range(&model, &provider_models),
);
}
Some(payload)
}

View File

@@ -1,220 +1,15 @@
use super::payloads::{
use super::super::payloads::{
admin_provider_model_effective_capability, admin_provider_model_effective_input_price,
admin_provider_model_effective_output_price, model_tiered_pricing_first_tier_value,
timestamp_or_now,
admin_provider_model_effective_output_price,
};
use crate::handlers::admin::shared::json_string_list;
use crate::AppState;
use aether_data_contracts::repository::global_models::{
AdminGlobalModelListQuery, StoredAdminGlobalModel, StoredAdminProviderModel,
};
use futures_util::stream::{self, StreamExt};
use super::helpers::build_admin_global_model_price_range;
use crate::handlers::admin::request::AdminAppState;
use aether_data_contracts::repository::global_models::AdminGlobalModelListQuery;
use serde_json::json;
use std::collections::{BTreeMap, BTreeSet};
use std::time::{SystemTime, UNIX_EPOCH};
pub(crate) async fn resolve_admin_global_model_by_id_or_err(
state: &AppState,
global_model_id: &str,
) -> Result<StoredAdminGlobalModel, String> {
state
.get_admin_global_model_by_id(global_model_id)
.await
.map_err(|err| format!("{err:?}"))?
.ok_or_else(|| format!("GlobalModel {global_model_id} 不存在"))
}
fn admin_global_model_provider_counts(
provider_models: &[StoredAdminProviderModel],
) -> (usize, usize, usize) {
let total_models = provider_models.len();
let total_providers = provider_models
.iter()
.map(|model| model.provider_id.clone())
.collect::<BTreeSet<_>>()
.len();
let active_provider_count = provider_models
.iter()
.filter(|model| model.is_active && model.is_available)
.map(|model| model.provider_id.clone())
.collect::<BTreeSet<_>>()
.len();
(total_models, total_providers, active_provider_count)
}
fn build_admin_global_model_price_range(
global_model: &StoredAdminGlobalModel,
provider_models: &[StoredAdminProviderModel],
) -> serde_json::Value {
let mut input_values = provider_models
.iter()
.filter_map(admin_provider_model_effective_input_price)
.collect::<Vec<_>>();
let mut output_values = provider_models
.iter()
.filter_map(admin_provider_model_effective_output_price)
.collect::<Vec<_>>();
if input_values.is_empty() {
if let Some(value) = model_tiered_pricing_first_tier_value(
global_model.default_tiered_pricing.as_ref(),
"input_price_per_1m",
) {
input_values.push(value);
}
}
if output_values.is_empty() {
if let Some(value) = model_tiered_pricing_first_tier_value(
global_model.default_tiered_pricing.as_ref(),
"output_price_per_1m",
) {
output_values.push(value);
}
}
json!({
"min_input": input_values.iter().copied().reduce(f64::min),
"max_input": input_values.iter().copied().reduce(f64::max),
"min_output": output_values.iter().copied().reduce(f64::min),
"max_output": output_values.iter().copied().reduce(f64::max),
})
}
async fn admin_global_model_provider_models_by_global_model_id(
state: &AppState,
global_model_ids: &[String],
) -> BTreeMap<String, Vec<StoredAdminProviderModel>> {
let state = state.clone();
stream::iter(global_model_ids.iter().cloned().map(|global_model_id| {
let state = state.clone();
async move {
let provider_models = state
.list_admin_provider_models_by_global_model_id(&global_model_id)
.await
.ok()
.unwrap_or_default();
(global_model_id, provider_models)
}
}))
.buffer_unordered(32)
.collect::<Vec<_>>()
.await
.into_iter()
.collect()
}
pub(crate) fn build_admin_global_model_response(
global_model: &StoredAdminGlobalModel,
provider_models: &[StoredAdminProviderModel],
now_unix_secs: u64,
) -> serde_json::Value {
let (_, provider_count, active_provider_count) =
admin_global_model_provider_counts(provider_models);
json!({
"id": &global_model.id,
"name": &global_model.name,
"display_name": &global_model.display_name,
"is_active": global_model.is_active,
"default_price_per_request": global_model.default_price_per_request,
"default_tiered_pricing": global_model.default_tiered_pricing.clone(),
"supported_capabilities": json_string_list(global_model.supported_capabilities.as_ref()),
"config": global_model.config.clone(),
"provider_count": provider_count,
"active_provider_count": active_provider_count,
"created_at": timestamp_or_now(global_model.created_at_unix_secs, now_unix_secs),
"updated_at": timestamp_or_now(global_model.updated_at_unix_secs, now_unix_secs),
})
}
pub(crate) async fn build_admin_global_models_payload(
state: &AppState,
skip: usize,
limit: usize,
is_active: Option<bool>,
search: Option<String>,
) -> Option<serde_json::Value> {
if !state.has_global_model_data_reader() {
return None;
}
let page = state
.list_admin_global_models(&AdminGlobalModelListQuery {
offset: skip,
limit,
is_active,
search,
})
.await
.ok()?;
let now_unix_secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.ok()
.map(|duration| duration.as_secs())
.unwrap_or(0);
let mut models = page.items;
models.sort_by(|left, right| {
left.name
.cmp(&right.name)
.then_with(|| left.id.cmp(&right.id))
});
let global_model_ids = models
.iter()
.map(|model| model.id.clone())
.collect::<Vec<_>>();
let mut provider_models_by_global_model =
admin_global_model_provider_models_by_global_model_id(state, &global_model_ids).await;
let mut payload_models = Vec::with_capacity(models.len());
for model in models {
let provider_models = provider_models_by_global_model
.remove(&model.id)
.unwrap_or_default();
payload_models.push(build_admin_global_model_response(
&model,
&provider_models,
now_unix_secs,
));
}
Some(json!({
"models": payload_models,
"total": page.total,
}))
}
pub(crate) async fn build_admin_global_model_payload(
state: &AppState,
global_model_id: &str,
) -> Option<serde_json::Value> {
if !state.has_global_model_data_reader() {
return None;
}
let model = state
.get_admin_global_model_by_id(global_model_id)
.await
.ok()??;
let provider_models = state
.list_admin_provider_models_by_global_model_id(&model.id)
.await
.ok()
.unwrap_or_default();
let now_unix_secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.ok()
.map(|duration| duration.as_secs())
.unwrap_or(0);
let (total_models, total_providers, _) = admin_global_model_provider_counts(&provider_models);
let mut payload = build_admin_global_model_response(&model, &provider_models, now_unix_secs);
if let Some(object) = payload.as_object_mut() {
object.insert("total_models".to_string(), json!(total_models));
object.insert("total_providers".to_string(), json!(total_providers));
object.insert(
"price_range".to_string(),
build_admin_global_model_price_range(&model, &provider_models),
);
}
Some(payload)
}
use std::collections::BTreeMap;
pub(crate) async fn build_admin_global_model_providers_payload(
state: &AppState,
state: &AdminAppState<'_>,
global_model_id: &str,
) -> Option<serde_json::Value> {
if !state.has_global_model_data_reader() || !state.has_provider_catalog_data_reader() {
@@ -279,7 +74,7 @@ pub(crate) async fn build_admin_global_model_providers_payload(
}
pub(crate) async fn build_admin_model_catalog_payload(
state: &AppState,
state: &AdminAppState<'_>,
) -> Option<serde_json::Value> {
if !state.has_global_model_data_reader() || !state.has_provider_catalog_data_reader() {
return None;

View File

@@ -1,525 +0,0 @@
use super::super::{
build_admin_assign_global_model_to_providers_payload, build_admin_global_model_create_record,
build_admin_global_model_payload, build_admin_global_model_providers_payload,
build_admin_global_model_response, build_admin_global_model_routing_payload,
build_admin_global_model_update_record, build_admin_global_models_payload,
resolve_admin_global_model_by_id_or_err,
};
use super::helpers::{
build_admin_global_models_data_unavailable_response,
ADMIN_GLOBAL_MODELS_DATA_UNAVAILABLE_DETAIL,
};
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::model::shared::{
admin_global_model_assign_to_providers_id, admin_global_model_id_from_path,
admin_global_model_providers_id, admin_global_model_routing_id, is_admin_global_models_root,
AdminBatchAssignToProvidersRequest, AdminBatchDeleteIdsRequest, AdminGlobalModelCreateRequest,
AdminGlobalModelUpdateRequest,
};
use crate::handlers::admin::shared::attach_admin_audit_response;
use crate::handlers::admin::shared::{query_param_optional_bool, query_param_value};
use crate::{AppState, GatewayError};
use axum::{
body::{Body, Bytes},
http,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
use std::time::{SystemTime, UNIX_EPOCH};
pub(crate) async fn maybe_build_local_admin_global_models_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
request_body: Option<&Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
let Some(decision) = request_context.control_decision.as_ref() else {
return Ok(None);
};
if decision.route_family.as_deref() == Some("global_models_manage")
&& decision.route_kind.as_deref() == Some("routing_preview")
&& request_context.request_method == http::Method::GET
{
if !state.has_global_model_data_reader() || !state.has_provider_catalog_data_reader() {
return Ok(Some(build_admin_global_models_data_unavailable_response()));
}
let Some(global_model_id) = admin_global_model_routing_id(&request_context.request_path)
else {
return Ok(Some(
(
http::StatusCode::NOT_FOUND,
Json(json!({ "detail": "GlobalModel 不存在" })),
)
.into_response(),
));
};
return Ok(Some(
match build_admin_global_model_routing_payload(state, &global_model_id).await {
Some(payload) => Json(payload).into_response(),
None => (
http::StatusCode::NOT_FOUND,
Json(json!({ "detail": format!("GlobalModel {global_model_id} 不存在") })),
)
.into_response(),
},
));
}
if decision.route_family.as_deref() == Some("global_models_manage")
&& decision.route_kind.as_deref() == Some("list_global_models")
&& is_admin_global_models_root(&request_context.request_path)
{
if !state.has_global_model_data_reader() {
return Ok(Some(build_admin_global_models_data_unavailable_response()));
}
let skip = query_param_value(request_context.request_query_string.as_deref(), "skip")
.and_then(|value| value.parse::<usize>().ok())
.unwrap_or(0);
let limit = query_param_value(request_context.request_query_string.as_deref(), "limit")
.and_then(|value| value.parse::<usize>().ok())
.filter(|value| *value > 0 && *value <= 1000)
.unwrap_or(100);
let is_active =
query_param_optional_bool(request_context.request_query_string.as_deref(), "is_active");
let search = query_param_value(request_context.request_query_string.as_deref(), "search");
let Some(payload) =
build_admin_global_models_payload(state, skip, limit, is_active, search).await
else {
return Ok(Some(build_admin_global_models_data_unavailable_response()));
};
return Ok(Some(Json(payload).into_response()));
}
if decision.route_family.as_deref() == Some("global_models_manage")
&& decision.route_kind.as_deref() == Some("get_global_model")
&& request_context.request_method == http::Method::GET
{
if !state.has_global_model_data_reader() {
return Ok(Some(build_admin_global_models_data_unavailable_response()));
}
let Some(global_model_id) = admin_global_model_id_from_path(&request_context.request_path)
else {
return Ok(Some(
(
http::StatusCode::NOT_FOUND,
Json(json!({ "detail": "GlobalModel 不存在" })),
)
.into_response(),
));
};
return Ok(Some(
match build_admin_global_model_payload(state, &global_model_id).await {
Some(payload) => Json(payload).into_response(),
None => (
http::StatusCode::NOT_FOUND,
Json(json!({ "detail": format!("GlobalModel {global_model_id} 不存在") })),
)
.into_response(),
},
));
}
if decision.route_family.as_deref() == Some("global_models_manage")
&& decision.route_kind.as_deref() == Some("create_global_model")
&& request_context.request_method == http::Method::POST
&& is_admin_global_models_root(&request_context.request_path)
{
if !state.has_global_model_data_reader() || !state.has_global_model_data_writer() {
return Ok(Some(build_admin_global_models_data_unavailable_response()));
}
let Some(request_body) = request_body else {
return Ok(Some(
(
http::StatusCode::BAD_REQUEST,
Json(json!({ "detail": "请求体不能为空" })),
)
.into_response(),
));
};
let payload = match serde_json::from_slice::<AdminGlobalModelCreateRequest>(request_body) {
Ok(payload) => payload,
Err(_) => {
return Ok(Some(
(
http::StatusCode::BAD_REQUEST,
Json(json!({ "detail": "请求体必须是合法的 JSON 对象" })),
)
.into_response(),
));
}
};
let record = match build_admin_global_model_create_record(state, payload).await {
Ok(record) => record,
Err(detail) => {
return Ok(Some(
(
http::StatusCode::BAD_REQUEST,
Json(json!({ "detail": detail })),
)
.into_response(),
));
}
};
return Ok(Some(
match state.create_admin_global_model(&record).await? {
Some(created) => {
let provider_models = state
.list_admin_provider_models_by_global_model_id(&created.id)
.await
.unwrap_or_default();
let now_unix_secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.ok()
.map(|duration| duration.as_secs())
.unwrap_or(0);
attach_admin_audit_response(
(
http::StatusCode::CREATED,
Json(build_admin_global_model_response(
&created,
&provider_models,
now_unix_secs,
)),
)
.into_response(),
"admin_global_model_created",
"create_global_model",
"global_model",
&created.id,
)
}
None => (
http::StatusCode::SERVICE_UNAVAILABLE,
Json(json!({ "detail": ADMIN_GLOBAL_MODELS_DATA_UNAVAILABLE_DETAIL })),
)
.into_response(),
},
));
}
if decision.route_family.as_deref() == Some("global_models_manage")
&& decision.route_kind.as_deref() == Some("update_global_model")
&& request_context.request_method == http::Method::PATCH
{
if !state.has_global_model_data_reader() || !state.has_global_model_data_writer() {
return Ok(Some(build_admin_global_models_data_unavailable_response()));
}
let Some(global_model_id) = admin_global_model_id_from_path(&request_context.request_path)
else {
return Ok(Some(
(
http::StatusCode::NOT_FOUND,
Json(json!({ "detail": "GlobalModel 不存在" })),
)
.into_response(),
));
};
let existing = match resolve_admin_global_model_by_id_or_err(state, &global_model_id).await
{
Ok(model) => model,
Err(detail) => {
return Ok(Some(
(
http::StatusCode::NOT_FOUND,
Json(json!({ "detail": detail })),
)
.into_response(),
));
}
};
let Some(request_body) = request_body else {
return Ok(Some(
(
http::StatusCode::BAD_REQUEST,
Json(json!({ "detail": "请求体不能为空" })),
)
.into_response(),
));
};
let raw_value = match serde_json::from_slice::<serde_json::Value>(request_body) {
Ok(value) => value,
Err(_) => {
return Ok(Some(
(
http::StatusCode::BAD_REQUEST,
Json(json!({ "detail": "请求体必须是合法的 JSON 对象" })),
)
.into_response(),
));
}
};
let Some(raw_payload) = raw_value.as_object().cloned() else {
return Ok(Some(
(
http::StatusCode::BAD_REQUEST,
Json(json!({ "detail": "请求体必须是合法的 JSON 对象" })),
)
.into_response(),
));
};
let payload = match serde_json::from_value::<AdminGlobalModelUpdateRequest>(raw_value) {
Ok(payload) => payload,
Err(_) => {
return Ok(Some(
(
http::StatusCode::BAD_REQUEST,
Json(json!({ "detail": "请求体必须是合法的 JSON 对象" })),
)
.into_response(),
));
}
};
let record =
match build_admin_global_model_update_record(state, &existing, &raw_payload, payload)
.await
{
Ok(record) => record,
Err(detail) => {
return Ok(Some(
(
http::StatusCode::BAD_REQUEST,
Json(json!({ "detail": detail })),
)
.into_response(),
));
}
};
return Ok(Some(
match state.update_admin_global_model(&record).await? {
Some(updated) => {
let provider_models = state
.list_admin_provider_models_by_global_model_id(&updated.id)
.await
.unwrap_or_default();
let now_unix_secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.ok()
.map(|duration| duration.as_secs())
.unwrap_or(0);
attach_admin_audit_response(
Json(build_admin_global_model_response(
&updated,
&provider_models,
now_unix_secs,
))
.into_response(),
"admin_global_model_updated",
"update_global_model",
"global_model",
&updated.id,
)
}
None => (
http::StatusCode::NOT_FOUND,
Json(json!({ "detail": format!("GlobalModel {} 不存在", existing.id) })),
)
.into_response(),
},
));
}
if decision.route_family.as_deref() == Some("global_models_manage")
&& decision.route_kind.as_deref() == Some("delete_global_model")
&& request_context.request_method == http::Method::DELETE
{
if !state.has_global_model_data_reader() || !state.has_global_model_data_writer() {
return Ok(Some(build_admin_global_models_data_unavailable_response()));
}
let Some(global_model_id) = admin_global_model_id_from_path(&request_context.request_path)
else {
return Ok(Some(
(
http::StatusCode::NOT_FOUND,
Json(json!({ "detail": "GlobalModel 不存在" })),
)
.into_response(),
));
};
let existing = match resolve_admin_global_model_by_id_or_err(state, &global_model_id).await
{
Ok(model) => model,
Err(detail) => {
return Ok(Some(
(
http::StatusCode::NOT_FOUND,
Json(json!({ "detail": detail })),
)
.into_response(),
));
}
};
if !state.delete_admin_global_model(&existing.id).await? {
return Ok(Some(
(
http::StatusCode::NOT_FOUND,
Json(json!({ "detail": format!("GlobalModel {} 不存在", existing.id) })),
)
.into_response(),
));
}
return Ok(Some(attach_admin_audit_response(
http::StatusCode::NO_CONTENT.into_response(),
"admin_global_model_deleted",
"delete_global_model",
"global_model",
&existing.id,
)));
}
if decision.route_family.as_deref() == Some("global_models_manage")
&& decision.route_kind.as_deref() == Some("batch_delete_global_models")
&& request_context.request_method == http::Method::POST
&& request_context.request_path == "/api/admin/models/global/batch-delete"
{
if !state.has_global_model_data_reader() || !state.has_global_model_data_writer() {
return Ok(Some(build_admin_global_models_data_unavailable_response()));
}
let Some(request_body) = request_body else {
return Ok(Some(
(
http::StatusCode::BAD_REQUEST,
Json(json!({ "detail": "请求体不能为空" })),
)
.into_response(),
));
};
let payload = match serde_json::from_slice::<AdminBatchDeleteIdsRequest>(request_body) {
Ok(payload) => payload,
Err(_) => {
return Ok(Some(
(
http::StatusCode::BAD_REQUEST,
Json(json!({ "detail": "请求体必须是合法的 JSON 对象" })),
)
.into_response(),
));
}
};
let mut success_count = 0usize;
let mut failed = Vec::new();
for id in payload.ids {
let trimmed = id.trim();
if trimmed.is_empty() {
failed.push(json!({"id": id, "error": "not found"}));
continue;
}
let Some(existing) = state.get_admin_global_model_by_id(trimmed).await? else {
failed.push(json!({"id": trimmed, "error": "not found"}));
continue;
};
if state.delete_admin_global_model(&existing.id).await? {
success_count += 1;
} else {
failed.push(json!({"id": existing.id, "error": "delete failed"}));
}
}
return Ok(Some(attach_admin_audit_response(
Json(json!({
"success_count": success_count,
"failed": failed,
}))
.into_response(),
"admin_global_models_batch_deleted",
"batch_delete_global_models",
"global_models_batch",
"batch",
)));
}
if decision.route_family.as_deref() == Some("global_models_manage")
&& decision.route_kind.as_deref() == Some("assign_to_providers")
&& request_context.request_method == http::Method::POST
{
let Some(global_model_id) =
admin_global_model_assign_to_providers_id(&request_context.request_path)
else {
return Ok(Some(
(
http::StatusCode::NOT_FOUND,
Json(json!({ "detail": "GlobalModel 不存在" })),
)
.into_response(),
));
};
let Some(request_body) = request_body else {
return Ok(Some(
(
http::StatusCode::BAD_REQUEST,
Json(json!({ "detail": "请求体不能为空" })),
)
.into_response(),
));
};
let payload =
match serde_json::from_slice::<AdminBatchAssignToProvidersRequest>(request_body) {
Ok(payload) => payload,
Err(_) => {
return Ok(Some(
(
http::StatusCode::BAD_REQUEST,
Json(json!({ "detail": "请求体必须是合法的 JSON 对象" })),
)
.into_response(),
));
}
};
let payload = match build_admin_assign_global_model_to_providers_payload(
state,
&global_model_id,
payload.provider_ids,
payload.create_models.unwrap_or(false),
)
.await
{
Ok(payload) => payload,
Err(detail) => {
return Ok(Some(
(
http::StatusCode::BAD_REQUEST,
Json(json!({ "detail": detail })),
)
.into_response(),
));
}
};
return Ok(Some(attach_admin_audit_response(
Json(payload).into_response(),
"admin_global_model_assigned_to_providers",
"assign_global_model_to_providers",
"global_model",
&global_model_id,
)));
}
if decision.route_family.as_deref() == Some("global_models_manage")
&& decision.route_kind.as_deref() == Some("global_model_providers")
&& request_context.request_method == http::Method::GET
{
if !state.has_global_model_data_reader() || !state.has_provider_catalog_data_reader() {
return Ok(Some(build_admin_global_models_data_unavailable_response()));
}
let Some(global_model_id) = admin_global_model_providers_id(&request_context.request_path)
else {
return Ok(Some(
(
http::StatusCode::NOT_FOUND,
Json(json!({ "detail": "GlobalModel 不存在" })),
)
.into_response(),
));
};
return Ok(Some(
match build_admin_global_model_providers_payload(state, &global_model_id).await {
Some(payload) => Json(payload).into_response(),
None => (
http::StatusCode::NOT_FOUND,
Json(json!({ "detail": format!("GlobalModel {global_model_id} 不存在") })),
)
.into_response(),
},
));
}
Ok(None)
}

View File

@@ -0,0 +1,34 @@
mod reads;
mod shared;
mod writes;
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::GatewayError;
use axum::{
body::{Body, Bytes},
response::Response,
};
pub(crate) async fn maybe_build_local_admin_global_models_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
if let Some(response) =
reads::maybe_build_local_admin_global_models_read_response(state, request_context).await?
{
return Ok(Some(response));
}
if let Some(response) = writes::maybe_build_local_admin_global_models_write_response(
state,
request_context,
request_body,
)
.await?
{
return Ok(Some(response));
}
Ok(None)
}

View File

@@ -0,0 +1,145 @@
use super::super::super::super::{
build_admin_global_model_payload, build_admin_global_model_providers_payload,
build_admin_global_model_routing_payload, build_admin_global_models_payload,
};
use super::super::super::helpers::build_admin_global_models_data_unavailable_response;
use super::shared::{global_model_missing_response, global_model_not_found_response};
use crate::handlers::admin::model::shared::{
admin_global_model_id_from_path, admin_global_model_providers_id,
admin_global_model_routing_id, is_admin_global_models_root,
};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::{query_param_optional_bool, query_param_value};
use crate::GatewayError;
use axum::{
body::Body,
http,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
pub(super) async fn maybe_build_local_admin_global_models_read_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Option<Response<Body>>, GatewayError> {
let Some(decision) = request_context.decision() else {
return Ok(None);
};
if decision.route_family.as_deref() == Some("global_models_manage")
&& decision.route_kind.as_deref() == Some("routing_preview")
&& request_context.method() == http::Method::GET
{
return Ok(Some(
build_routing_preview_response(state, request_context).await?,
));
}
if decision.route_family.as_deref() == Some("global_models_manage")
&& decision.route_kind.as_deref() == Some("list_global_models")
&& is_admin_global_models_root(request_context.path())
{
return Ok(Some(
build_list_global_models_response(state, request_context).await?,
));
}
if decision.route_family.as_deref() == Some("global_models_manage")
&& decision.route_kind.as_deref() == Some("get_global_model")
&& request_context.method() == http::Method::GET
{
return Ok(Some(
build_get_global_model_response(state, request_context).await?,
));
}
if decision.route_family.as_deref() == Some("global_models_manage")
&& decision.route_kind.as_deref() == Some("global_model_providers")
&& request_context.method() == http::Method::GET
{
return Ok(Some(
build_global_model_providers_response(state, request_context).await?,
));
}
Ok(None)
}
async fn build_routing_preview_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
if !state.has_global_model_data_reader() || !state.has_provider_catalog_data_reader() {
return Ok(build_admin_global_models_data_unavailable_response());
}
let Some(global_model_id) = admin_global_model_routing_id(request_context.path()) else {
return Ok(global_model_missing_response());
};
Ok(
match build_admin_global_model_routing_payload(state, &global_model_id).await {
Some(payload) => Json::<serde_json::Value>(payload).into_response(),
None => global_model_not_found_response(&global_model_id),
},
)
}
async fn build_list_global_models_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
if !state.has_global_model_data_reader() {
return Ok(build_admin_global_models_data_unavailable_response());
}
let skip = query_param_value(request_context.query_string(), "skip")
.and_then(|value| value.parse::<usize>().ok())
.unwrap_or(0);
let limit = query_param_value(request_context.query_string(), "limit")
.and_then(|value| value.parse::<usize>().ok())
.filter(|value| *value > 0 && *value <= 1000)
.unwrap_or(100);
let is_active = query_param_optional_bool(request_context.query_string(), "is_active");
let search = query_param_value(request_context.query_string(), "search");
let Some(payload): Option<serde_json::Value> =
build_admin_global_models_payload(state, skip, limit, is_active, search).await
else {
return Ok(build_admin_global_models_data_unavailable_response());
};
Ok(Json(payload).into_response())
}
async fn build_get_global_model_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
if !state.has_global_model_data_reader() {
return Ok(build_admin_global_models_data_unavailable_response());
}
let Some(global_model_id) = admin_global_model_id_from_path(request_context.path()) else {
return Ok(global_model_missing_response());
};
Ok(
match build_admin_global_model_payload(state, &global_model_id).await {
Some(payload) => Json::<serde_json::Value>(payload).into_response(),
None => global_model_not_found_response(&global_model_id),
},
)
}
async fn build_global_model_providers_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
if !state.has_global_model_data_reader() || !state.has_provider_catalog_data_reader() {
return Ok(build_admin_global_models_data_unavailable_response());
}
let Some(global_model_id) = admin_global_model_providers_id(request_context.path()) else {
return Ok(global_model_missing_response());
};
Ok(
match build_admin_global_model_providers_payload(state, &global_model_id).await {
Some(payload) => Json::<serde_json::Value>(payload).into_response(),
None => global_model_not_found_response(&global_model_id),
},
)
}

View File

@@ -0,0 +1,76 @@
use axum::{
body::{Body, Bytes},
http,
response::{IntoResponse, Response},
Json,
};
use serde::de::DeserializeOwned;
use serde_json::{json, Map, Value};
use std::time::{SystemTime, UNIX_EPOCH};
pub(super) fn global_model_missing_response() -> Response<Body> {
(
http::StatusCode::NOT_FOUND,
Json(json!({ "detail": "GlobalModel 不存在" })),
)
.into_response()
}
pub(super) fn global_model_not_found_response(global_model_id: &str) -> Response<Body> {
(
http::StatusCode::NOT_FOUND,
Json(json!({ "detail": format!("GlobalModel {global_model_id} 不存在") })),
)
.into_response()
}
pub(super) fn not_found_detail_response(detail: impl Into<String>) -> Response<Body> {
(
http::StatusCode::NOT_FOUND,
Json(json!({ "detail": detail.into() })),
)
.into_response()
}
pub(super) fn bad_request_response(detail: impl Into<String>) -> Response<Body> {
(
http::StatusCode::BAD_REQUEST,
Json(json!({ "detail": detail.into() })),
)
.into_response()
}
pub(super) fn parse_required_json_body<T: DeserializeOwned>(
request_body: Option<&Bytes>,
) -> Result<T, Response<Body>> {
let Some(request_body) = request_body else {
return Err(bad_request_response("请求体不能为空"));
};
serde_json::from_slice::<T>(request_body)
.map_err(|_| bad_request_response("请求体必须是合法的 JSON 对象"))
}
pub(super) fn parse_required_json_value(
request_body: Option<&Bytes>,
) -> Result<Value, Response<Body>> {
let Some(request_body) = request_body else {
return Err(bad_request_response("请求体不能为空"));
};
serde_json::from_slice::<Value>(request_body)
.map_err(|_| bad_request_response("请求体必须是合法的 JSON 对象"))
}
pub(super) fn require_json_object(value: &Value) -> Result<Map<String, Value>, Response<Body>> {
value
.as_object()
.cloned()
.ok_or_else(|| bad_request_response("请求体必须是合法的 JSON 对象"))
}
pub(super) fn current_unix_secs() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.ok()
.map(|duration| duration.as_secs())
.unwrap_or(0)
}

View File

@@ -0,0 +1,297 @@
use super::super::super::super::{
build_admin_assign_global_model_to_providers_payload, build_admin_global_model_create_record,
build_admin_global_model_response, build_admin_global_model_update_record,
resolve_admin_global_model_by_id_or_err,
};
use super::super::super::helpers::{
build_admin_global_models_data_unavailable_response,
ADMIN_GLOBAL_MODELS_DATA_UNAVAILABLE_DETAIL,
};
use super::shared::{
bad_request_response, current_unix_secs, global_model_missing_response,
global_model_not_found_response, not_found_detail_response, parse_required_json_body,
parse_required_json_value, require_json_object,
};
use crate::handlers::admin::model::shared::{
admin_global_model_assign_to_providers_id, admin_global_model_id_from_path,
is_admin_global_models_root, AdminBatchAssignToProvidersRequest, AdminBatchDeleteIdsRequest,
AdminGlobalModelCreateRequest, AdminGlobalModelUpdateRequest,
};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::handlers::admin::shared::attach_admin_audit_response;
use crate::GatewayError;
use axum::{
body::{Body, Bytes},
http,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
pub(super) async fn maybe_build_local_admin_global_models_write_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&Bytes>,
) -> Result<Option<Response<Body>>, GatewayError> {
let Some(decision) = request_context.decision() else {
return Ok(None);
};
if decision.route_family.as_deref() == Some("global_models_manage")
&& decision.route_kind.as_deref() == Some("create_global_model")
&& request_context.method() == http::Method::POST
&& is_admin_global_models_root(request_context.path())
{
return Ok(Some(
build_create_global_model_response(state, request_body).await?,
));
}
if decision.route_family.as_deref() == Some("global_models_manage")
&& decision.route_kind.as_deref() == Some("update_global_model")
&& request_context.method() == http::Method::PATCH
{
return Ok(Some(
build_update_global_model_response(state, request_context, request_body).await?,
));
}
if decision.route_family.as_deref() == Some("global_models_manage")
&& decision.route_kind.as_deref() == Some("delete_global_model")
&& request_context.method() == http::Method::DELETE
{
return Ok(Some(
build_delete_global_model_response(state, request_context).await?,
));
}
if decision.route_family.as_deref() == Some("global_models_manage")
&& decision.route_kind.as_deref() == Some("batch_delete_global_models")
&& request_context.method() == http::Method::POST
&& request_context.path() == "/api/admin/models/global/batch-delete"
{
return Ok(Some(
build_batch_delete_global_models_response(state, request_body).await?,
));
}
if decision.route_family.as_deref() == Some("global_models_manage")
&& decision.route_kind.as_deref() == Some("assign_to_providers")
&& request_context.method() == http::Method::POST
{
return Ok(Some(
build_assign_to_providers_response(state, request_context, request_body).await?,
));
}
Ok(None)
}
async fn build_create_global_model_response(
state: &AdminAppState<'_>,
request_body: Option<&Bytes>,
) -> Result<Response<Body>, GatewayError> {
if !state.has_global_model_data_reader() || !state.has_global_model_data_writer() {
return Ok(build_admin_global_models_data_unavailable_response());
}
let payload = match parse_required_json_body::<AdminGlobalModelCreateRequest>(request_body) {
Ok(payload) => payload,
Err(response) => return Ok(response),
};
let record = match build_admin_global_model_create_record(state, payload).await {
Ok(record) => record,
Err(detail) => return Ok(bad_request_response(detail)),
};
Ok(match state.create_admin_global_model(&record).await? {
Some(created) => {
let provider_models = state
.list_admin_provider_models_by_global_model_id(&created.id)
.await
.unwrap_or_default();
attach_admin_audit_response(
(
http::StatusCode::CREATED,
Json(build_admin_global_model_response(
&created,
&provider_models,
current_unix_secs(),
)),
)
.into_response(),
"admin_global_model_created",
"create_global_model",
"global_model",
&created.id,
)
}
None => (
http::StatusCode::SERVICE_UNAVAILABLE,
Json(json!({ "detail": ADMIN_GLOBAL_MODELS_DATA_UNAVAILABLE_DETAIL })),
)
.into_response(),
})
}
async fn build_update_global_model_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&Bytes>,
) -> Result<Response<Body>, GatewayError> {
if !state.has_global_model_data_reader() || !state.has_global_model_data_writer() {
return Ok(build_admin_global_models_data_unavailable_response());
}
let Some(global_model_id) = admin_global_model_id_from_path(request_context.path()) else {
return Ok(global_model_missing_response());
};
let existing = match resolve_admin_global_model_by_id_or_err(state, &global_model_id).await {
Ok(model) => model,
Err(detail) => return Ok(not_found_detail_response(detail)),
};
let raw_value = match parse_required_json_value(request_body) {
Ok(value) => value,
Err(response) => return Ok(response),
};
let raw_payload = match require_json_object(&raw_value) {
Ok(payload) => payload,
Err(response) => return Ok(response),
};
let payload = match serde_json::from_value::<AdminGlobalModelUpdateRequest>(raw_value) {
Ok(payload) => payload,
Err(_) => return Ok(bad_request_response("请求体必须是合法的 JSON 对象")),
};
let record =
match build_admin_global_model_update_record(state, &existing, &raw_payload, payload).await
{
Ok(record) => record,
Err(detail) => return Ok(bad_request_response(detail)),
};
Ok(match state.update_admin_global_model(&record).await? {
Some(updated) => {
let provider_models = state
.list_admin_provider_models_by_global_model_id(&updated.id)
.await
.unwrap_or_default();
attach_admin_audit_response(
Json(build_admin_global_model_response(
&updated,
&provider_models,
current_unix_secs(),
))
.into_response(),
"admin_global_model_updated",
"update_global_model",
"global_model",
&updated.id,
)
}
None => global_model_not_found_response(&existing.id),
})
}
async fn build_delete_global_model_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
if !state.has_global_model_data_reader() || !state.has_global_model_data_writer() {
return Ok(build_admin_global_models_data_unavailable_response());
}
let Some(global_model_id) = admin_global_model_id_from_path(request_context.path()) else {
return Ok(global_model_missing_response());
};
let existing = match resolve_admin_global_model_by_id_or_err(state, &global_model_id).await {
Ok(model) => model,
Err(detail) => return Ok(not_found_detail_response(detail)),
};
if !state.delete_admin_global_model(&existing.id).await? {
return Ok(global_model_not_found_response(&existing.id));
}
Ok(attach_admin_audit_response(
http::StatusCode::NO_CONTENT.into_response(),
"admin_global_model_deleted",
"delete_global_model",
"global_model",
&existing.id,
))
}
async fn build_batch_delete_global_models_response(
state: &AdminAppState<'_>,
request_body: Option<&Bytes>,
) -> Result<Response<Body>, GatewayError> {
if !state.has_global_model_data_reader() || !state.has_global_model_data_writer() {
return Ok(build_admin_global_models_data_unavailable_response());
}
let payload = match parse_required_json_body::<AdminBatchDeleteIdsRequest>(request_body) {
Ok(payload) => payload,
Err(response) => return Ok(response),
};
let mut success_count = 0usize;
let mut failed = Vec::new();
for id in payload.ids {
let trimmed = id.trim();
if trimmed.is_empty() {
failed.push(json!({"id": id, "error": "not found"}));
continue;
}
let Some(existing) = state.get_admin_global_model_by_id(trimmed).await? else {
failed.push(json!({"id": trimmed, "error": "not found"}));
continue;
};
if state.delete_admin_global_model(&existing.id).await? {
success_count += 1;
} else {
failed.push(json!({"id": existing.id, "error": "delete failed"}));
}
}
Ok(attach_admin_audit_response(
Json(json!({
"success_count": success_count,
"failed": failed,
}))
.into_response(),
"admin_global_models_batch_deleted",
"batch_delete_global_models",
"global_models_batch",
"batch",
))
}
async fn build_assign_to_providers_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
request_body: Option<&Bytes>,
) -> Result<Response<Body>, GatewayError> {
let Some(global_model_id) = admin_global_model_assign_to_providers_id(request_context.path())
else {
return Ok(global_model_missing_response());
};
let payload = match parse_required_json_body::<AdminBatchAssignToProvidersRequest>(request_body)
{
Ok(payload) => payload,
Err(response) => return Ok(response),
};
let payload: serde_json::Value = match build_admin_assign_global_model_to_providers_payload(
state,
&global_model_id,
payload.provider_ids,
payload.create_models.unwrap_or(false),
)
.await
{
Ok(payload) => payload,
Err(detail) => return Ok(bad_request_response(detail)),
};
Ok(attach_admin_audit_response(
Json(payload).into_response(),
"admin_global_model_assigned_to_providers",
"assign_global_model_to_providers",
"global_model",
&global_model_id,
))
}

View File

@@ -0,0 +1,3 @@
mod core;
pub(crate) use core::maybe_build_local_admin_global_models_response;

View File

@@ -5,22 +5,24 @@ mod external_cache;
mod global;
mod global_models;
mod payloads;
mod routes;
mod routing;
mod write;
pub(crate) use self::catalog_routes::maybe_build_local_admin_model_catalog_response;
pub(crate) use self::external_cache::{
pub(super) use self::catalog_routes::maybe_build_local_admin_model_catalog_response;
pub(super) use self::external_cache::{
clear_admin_external_models_cache, read_admin_external_models_cache,
};
pub(crate) use self::global::{
pub(super) use self::global::{
build_admin_global_model_payload, build_admin_global_model_providers_payload,
build_admin_global_model_response, build_admin_global_models_payload,
build_admin_model_catalog_payload, resolve_admin_global_model_by_id_or_err,
};
pub(crate) use self::global_models::maybe_build_local_admin_global_models_response;
pub(crate) use self::routing::{
pub(super) use self::global_models::maybe_build_local_admin_global_models_response;
pub(super) use self::routes::maybe_build_local_admin_model_response;
pub(super) use self::routing::{
build_admin_assign_global_model_to_providers_payload, build_admin_global_model_routing_payload,
};
pub(crate) use self::write::{
pub(super) use self::write::{
build_admin_global_model_create_record, build_admin_global_model_update_record,
};

View File

@@ -0,0 +1,27 @@
use super::{catalog_routes, global_models};
use crate::handlers::admin::request::{AdminRouteRequest, AdminRouteResult};
pub(crate) async fn maybe_build_local_admin_model_response(
request: AdminRouteRequest<'_>,
) -> AdminRouteResult {
if let Some(response) = catalog_routes::maybe_build_local_admin_model_catalog_response(
&request.state(),
&request.request_context(),
)
.await?
{
return Ok(Some(response));
}
if let Some(response) = global_models::maybe_build_local_admin_global_models_response(
&request.state(),
&request.request_context(),
request.request_body(),
)
.await?
{
return Ok(Some(response));
}
Ok(None)
}

View File

@@ -1,8 +1,6 @@
use super::resolve_admin_global_model_by_id_or_err;
use crate::handlers::admin::shared::{
json_string_list, masked_catalog_api_key, provider_catalog_key_supports_format,
};
use crate::AppState;
use crate::handlers::admin::request::AdminAppState;
use crate::handlers::admin::shared::{json_string_list, provider_catalog_key_supports_format};
use aether_data_contracts::repository::global_models::{
AdminProviderModelListQuery, UpsertAdminProviderModelRecord,
};
@@ -15,7 +13,7 @@ use std::collections::BTreeMap;
use uuid::Uuid;
pub(crate) async fn build_admin_global_model_routing_payload(
state: &AppState,
state: &AdminAppState<'_>,
global_model_id: &str,
) -> Option<serde_json::Value> {
if !state.has_global_model_data_reader() || !state.has_provider_catalog_data_reader() {
@@ -155,7 +153,7 @@ pub(crate) async fn build_admin_global_model_routing_payload(
let payload = json!({
"id": key.id,
"name": key.name,
"masked_key": masked_catalog_api_key(state, key),
"masked_key": state.masked_catalog_api_key(key),
"is_active": key.is_active,
"is_adaptive": is_adaptive,
"effective_rpm": effective_rpm,
@@ -168,7 +166,7 @@ pub(crate) async fn build_admin_global_model_routing_payload(
all_keys_whitelist.push(json!({
"key_id": &key.id,
"key_name": &key.name,
"masked_key": masked_catalog_api_key(state, key),
"masked_key": state.masked_catalog_api_key(key),
"provider_id": &provider.id,
"provider_name": &provider.name,
"allowed_models": json_string_list(key.allowed_models.as_ref()),
@@ -249,7 +247,7 @@ pub(crate) async fn build_admin_global_model_routing_payload(
}
pub(crate) async fn build_admin_assign_global_model_to_providers_payload(
state: &AppState,
state: &AdminAppState<'_>,
global_model_id: &str,
provider_ids: Vec<String>,
create_models: bool,

View File

@@ -2,8 +2,8 @@ use super::payloads::{normalize_optional_price, normalize_required_trimmed_strin
use crate::handlers::admin::model::shared::{
AdminGlobalModelCreateRequest, AdminGlobalModelUpdateRequest,
};
use crate::handlers::admin::request::AdminAppState;
use crate::handlers::admin::shared::{normalize_json_object, normalize_string_list};
use crate::AppState;
use aether_data_contracts::repository::global_models::{
CreateAdminGlobalModelRecord, StoredAdminGlobalModel, UpdateAdminGlobalModelRecord,
};
@@ -11,7 +11,7 @@ use serde_json::json;
use uuid::Uuid;
pub(crate) async fn build_admin_global_model_create_record(
state: &AppState,
state: &AdminAppState<'_>,
payload: AdminGlobalModelCreateRequest,
) -> Result<CreateAdminGlobalModelRecord, String> {
let name = normalize_required_trimmed_string(&payload.name, "name")?;
@@ -47,7 +47,7 @@ pub(crate) async fn build_admin_global_model_create_record(
}
pub(crate) async fn build_admin_global_model_update_record(
_state: &AppState,
_state: &AdminAppState<'_>,
existing: &StoredAdminGlobalModel,
raw_payload: &serde_json::Map<String, serde_json::Value>,
payload: AdminGlobalModelUpdateRequest,

View File

@@ -1,7 +1,13 @@
mod monitoring;
pub(crate) mod stats;
mod routes;
mod stats;
mod usage;
pub(crate) use self::monitoring::maybe_build_local_admin_monitoring_response;
pub(crate) use self::stats::maybe_build_local_admin_stats_response;
pub(super) use self::monitoring::maybe_build_local_admin_monitoring_response;
pub(super) use self::routes::maybe_build_local_admin_observability_response;
pub(crate) use self::stats::{
admin_stats_bad_request_response, list_usage_for_optional_range, list_usage_for_range,
maybe_build_local_admin_stats_response, parse_bounded_u32, round_to,
};
pub(crate) use self::stats::{AdminStatsTimeRange, AdminStatsUsageFilter};
pub(crate) use self::usage::maybe_build_local_admin_usage_response;

View File

@@ -1,4 +1,3 @@
use super::responses::admin_monitoring_bad_request_response;
use super::route_filters::{
admin_monitoring_escape_like_pattern, parse_admin_monitoring_days,
parse_admin_monitoring_event_type_filter, parse_admin_monitoring_hours,
@@ -7,102 +6,24 @@ use super::route_filters::{
};
use super::usage_helpers::admin_monitoring_usage_is_error;
use crate::constants::INTERNAL_GATEWAY_PATH_PREFIXES;
use crate::control::GatewayPublicRequestContext;
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::query::monitoring as monitoring_query;
use crate::{AppState, GatewayError};
use aether_data_contracts::repository::usage::UsageAuditListQuery;
use axum::{
body::Body,
response::{IntoResponse, Response},
Json,
use crate::GatewayError;
use aether_admin::observability::monitoring::{
admin_monitoring_bad_request_response, admin_monitoring_user_behavior_user_id_from_path,
build_admin_monitoring_audit_logs_payload_response,
build_admin_monitoring_suspicious_activities_payload_response,
build_admin_monitoring_system_status_payload_response,
build_admin_monitoring_user_behavior_payload_response,
};
use serde_json::json;
fn build_admin_monitoring_audit_logs_payload(
items: Vec<serde_json::Value>,
total: usize,
limit: usize,
offset: usize,
username: Option<String>,
event_type: Option<String>,
days: i64,
) -> Response<Body> {
let count = items.len();
Json(json!({
"items": items,
"meta": {
"total": total,
"limit": limit,
"offset": offset,
"count": count,
},
"filters": {
"username": username,
"event_type": event_type,
"days": days,
},
}))
.into_response()
}
fn build_admin_monitoring_suspicious_activities_payload(
activities: Vec<serde_json::Value>,
hours: i64,
) -> Response<Body> {
let count = activities.len();
Json(json!({
"activities": activities,
"count": count,
"time_range_hours": hours,
}))
.into_response()
}
fn build_admin_monitoring_user_behavior_payload(
user_id: String,
days: i64,
event_counts: std::collections::BTreeMap<String, u64>,
failed_requests: u64,
success_requests: u64,
suspicious_activities: u64,
) -> Response<Body> {
let total_requests = success_requests.saturating_add(failed_requests);
let success_rate = if total_requests == 0 {
0.0
} else {
success_requests as f64 / total_requests as f64
};
Json(json!({
"user_id": user_id,
"period_days": days,
"event_counts": event_counts,
"failed_requests": failed_requests,
"success_requests": success_requests,
"success_rate": success_rate,
"suspicious_activities": suspicious_activities,
"analysis_time": chrono::Utc::now().to_rfc3339(),
}))
.into_response()
}
fn admin_monitoring_user_behavior_user_id_from_path(request_path: &str) -> Option<String> {
let value = request_path
.strip_prefix("/api/admin/monitoring/user-behavior/")?
.trim()
.trim_matches('/')
.to_string();
if value.is_empty() || value.contains('/') {
None
} else {
Some(value)
}
}
use aether_data_contracts::repository::usage::UsageAuditListQuery;
use axum::{body::Body, response::Response};
pub(super) async fn build_admin_monitoring_audit_logs_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
let state = state.as_ref();
let query = request_context.request_query_string.as_deref();
let username = parse_admin_monitoring_username_filter(query);
let event_type = parse_admin_monitoring_event_type_filter(query);
@@ -120,7 +41,7 @@ pub(super) async fn build_admin_monitoring_audit_logs_response(
};
let Some(pool) = state.postgres_pool() else {
return Ok(build_admin_monitoring_audit_logs_payload(
return Ok(build_admin_monitoring_audit_logs_payload_response(
Vec::new(),
0,
limit,
@@ -147,15 +68,16 @@ pub(super) async fn build_admin_monitoring_audit_logs_response(
)
.await?;
Ok(build_admin_monitoring_audit_logs_payload(
Ok(build_admin_monitoring_audit_logs_payload_response(
items, total, limit, offset, username, event_type, days,
))
}
pub(super) async fn build_admin_monitoring_suspicious_activities_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
let state = state.as_ref();
let query = request_context.request_query_string.as_deref();
let hours = match parse_admin_monitoring_hours(query) {
Ok(value) => value,
@@ -163,24 +85,22 @@ pub(super) async fn build_admin_monitoring_suspicious_activities_response(
};
let Some(pool) = state.postgres_pool() else {
return Ok(build_admin_monitoring_suspicious_activities_payload(
Vec::new(),
hours,
));
return Ok(
build_admin_monitoring_suspicious_activities_payload_response(Vec::new(), hours),
);
};
let cutoff_time = chrono::Utc::now() - chrono::Duration::hours(hours);
let activities = monitoring_query::list_admin_suspicious_activities(&pool, cutoff_time).await?;
Ok(build_admin_monitoring_suspicious_activities_payload(
activities, hours,
))
Ok(build_admin_monitoring_suspicious_activities_payload_response(activities, hours))
}
pub(super) async fn build_admin_monitoring_user_behavior_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
let state = state.as_ref();
let Some(user_id) =
admin_monitoring_user_behavior_user_id_from_path(&request_context.request_path)
else {
@@ -192,7 +112,7 @@ pub(super) async fn build_admin_monitoring_user_behavior_response(
};
let Some(pool) = state.postgres_pool() else {
return Ok(build_admin_monitoring_user_behavior_payload(
return Ok(build_admin_monitoring_user_behavior_payload_response(
user_id,
days,
std::collections::BTreeMap::new(),
@@ -227,7 +147,7 @@ pub(super) async fn build_admin_monitoring_user_behavior_response(
.unwrap_or_default(),
);
Ok(build_admin_monitoring_user_behavior_payload(
Ok(build_admin_monitoring_user_behavior_payload_response(
user_id,
days,
event_counts,
@@ -238,8 +158,9 @@ pub(super) async fn build_admin_monitoring_user_behavior_response(
}
pub(super) async fn build_admin_monitoring_system_status_response(
state: &AppState,
state: &AdminAppState<'_>,
) -> Result<Response<Body>, GatewayError> {
let state = state.as_ref();
let now = chrono::Utc::now();
let today_start = now
.date_naive()
@@ -301,35 +222,21 @@ pub(super) async fn build_admin_monitoring_system_status_response(
.count();
let tunnel = state.tunnel.stats();
Ok(Json(json!({
"timestamp": now.to_rfc3339(),
"users": {
"total": total_users,
"active": active_users,
},
"providers": {
"total": total_providers,
"active": active_providers,
},
"api_keys": {
"total": total_api_keys,
"active": active_api_keys,
},
"today_stats": {
"requests": today_requests,
"tokens": today_tokens,
"cost_usd": format!("${today_cost:.4}"),
},
"tunnel": {
"proxy_connections": tunnel.proxy_connections,
"nodes": tunnel.nodes,
"active_streams": tunnel.active_streams,
},
"internal_gateway": {
"status": "rust_native_control_plane",
"path_prefixes": INTERNAL_GATEWAY_PATH_PREFIXES,
},
"recent_errors": recent_errors,
}))
.into_response())
Ok(build_admin_monitoring_system_status_payload_response(
now,
total_users,
active_users,
total_providers,
active_providers,
total_api_keys,
active_api_keys,
today_requests,
today_tokens,
today_cost,
tunnel.proxy_connections,
tunnel.nodes,
tunnel.active_streams,
INTERNAL_GATEWAY_PATH_PREFIXES,
recent_errors,
))
}

View File

@@ -8,7 +8,8 @@ use super::cache_config::{
ADMIN_MONITORING_DYNAMIC_RESERVATION_STABLE_MIN_RESERVATION,
};
use super::cache_store::build_admin_monitoring_cache_snapshot;
use crate::{AppState, GatewayError};
use crate::handlers::admin::request::AdminAppState;
use crate::GatewayError;
use axum::{
body::Body,
http,
@@ -18,7 +19,7 @@ use axum::{
use serde_json::json;
pub(super) async fn build_admin_monitoring_cache_stats_response(
state: &AppState,
state: &AdminAppState<'_>,
) -> Result<Response<Body>, GatewayError> {
let snapshot = build_admin_monitoring_cache_snapshot(state).await?;
@@ -64,7 +65,7 @@ pub(super) async fn build_admin_monitoring_cache_stats_response(
}
pub(super) async fn build_admin_monitoring_cache_metrics_response(
state: &AppState,
state: &AdminAppState<'_>,
) -> Result<Response<Body>, GatewayError> {
let snapshot = build_admin_monitoring_cache_snapshot(state).await?;
let metrics = [

View File

@@ -1,5 +1,6 @@
use super::cache_types::AdminMonitoringCacheAffinityRecord;
use crate::{AppState, GatewayError};
use crate::handlers::admin::request::AdminAppState;
use crate::GatewayError;
fn parse_admin_monitoring_cache_affinity_key(raw_key: &str) -> Option<(String, String, String)> {
let parts = raw_key.split(':').collect::<Vec<_>>();
@@ -92,7 +93,7 @@ pub(super) fn admin_monitoring_cache_affinity_record(
}
pub(super) fn clear_admin_monitoring_scheduler_affinity_entries(
state: &AppState,
state: &AdminAppState<'_>,
records: &[AdminMonitoringCacheAffinityRecord],
) {
let scheduler_keys = records
@@ -100,28 +101,32 @@ pub(super) fn clear_admin_monitoring_scheduler_affinity_entries(
.filter_map(admin_monitoring_scheduler_affinity_cache_key)
.collect::<std::collections::BTreeSet<_>>();
for scheduler_key in scheduler_keys {
let _ = state.remove_scheduler_affinity_cache_entry(&scheduler_key);
let _ = state
.as_ref()
.remove_scheduler_affinity_cache_entry(&scheduler_key);
}
}
#[cfg(test)]
pub(super) fn delete_admin_monitoring_cache_affinity_entries_for_tests(
state: &AppState,
state: &AdminAppState<'_>,
raw_keys: &[String],
) -> usize {
state.remove_admin_monitoring_cache_affinity_entries_for_tests(raw_keys)
state
.as_ref()
.remove_admin_monitoring_cache_affinity_entries_for_tests(raw_keys)
}
#[cfg(not(test))]
pub(super) fn delete_admin_monitoring_cache_affinity_entries_for_tests(
_state: &AppState,
_state: &AdminAppState<'_>,
_raw_keys: &[String],
) -> usize {
0
}
pub(super) async fn delete_admin_monitoring_cache_affinity_raw_keys(
state: &AppState,
state: &AdminAppState<'_>,
raw_keys: &[String],
) -> Result<usize, GatewayError> {
if raw_keys.is_empty() {

View File

@@ -15,10 +15,10 @@ use super::cache_store::{
list_admin_monitoring_cache_affinity_records,
list_admin_monitoring_cache_affinity_records_by_affinity_keys,
};
use super::responses::admin_monitoring_bad_request_response;
use super::route_filters::{parse_admin_monitoring_limit, parse_admin_monitoring_offset};
use crate::control::GatewayPublicRequestContext;
use crate::{AppState, GatewayError};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::GatewayError;
use aether_admin::observability::monitoring::admin_monitoring_bad_request_response;
use axum::{
body::Body,
response::{IntoResponse, Response},
@@ -31,8 +31,8 @@ fn normalize_keyword<'a>(keyword: Option<&'a String>) -> Option<String> {
}
pub(super) async fn build_admin_monitoring_cache_affinities_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
let limit = match parse_admin_monitoring_limit(request_context.request_query_string.as_deref())
{
@@ -106,26 +106,20 @@ pub(super) async fn build_admin_monitoring_cache_affinities_response(
.collect::<Vec<_>>();
let provider_by_id = state
.data
.list_provider_catalog_providers_by_ids(&provider_ids)
.await
.map_err(|err| GatewayError::Internal(err.to_string()))?
.read_provider_catalog_providers_by_ids(&provider_ids)
.await?
.into_iter()
.map(|item| (item.id.clone(), item))
.collect::<std::collections::BTreeMap<_, _>>();
let endpoint_by_id = state
.data
.list_provider_catalog_endpoints_by_ids(&endpoint_ids)
.await
.map_err(|err| GatewayError::Internal(err.to_string()))?
.read_provider_catalog_endpoints_by_ids(&endpoint_ids)
.await?
.into_iter()
.map(|item| (item.id.clone(), item))
.collect::<std::collections::BTreeMap<_, _>>();
let key_by_id = state
.data
.list_provider_catalog_keys_by_ids(&key_ids)
.await
.map_err(|err| GatewayError::Internal(err.to_string()))?
.await?
.into_iter()
.map(|item| (item.id.clone(), item))
.collect::<std::collections::BTreeMap<_, _>>();
@@ -242,8 +236,8 @@ pub(super) async fn build_admin_monitoring_cache_affinities_response(
}
pub(super) async fn build_admin_monitoring_cache_affinity_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
let Some(user_identifier) =
admin_monitoring_cache_affinity_user_identifier_from_path(&request_context.request_path)

View File

@@ -1,8 +1,9 @@
use super::cache_types::AdminMonitoringCacheAffinityRecord;
use crate::{AppState, GatewayError};
use crate::handlers::admin::request::AdminAppState;
use crate::GatewayError;
pub(super) async fn admin_monitoring_list_export_api_key_records_by_ids(
state: &AppState,
state: &AdminAppState<'_>,
api_key_ids: &[String],
) -> Result<
std::collections::BTreeMap<String, aether_data::repository::auth::StoredAuthApiKeyExportRecord>,
@@ -21,7 +22,7 @@ pub(super) async fn admin_monitoring_list_export_api_key_records_by_ids(
}
async fn admin_monitoring_list_user_summaries_by_ids(
state: &AppState,
state: &AdminAppState<'_>,
user_ids: &[String],
) -> Result<
std::collections::BTreeMap<String, aether_data::repository::users::StoredUserSummary>,
@@ -40,7 +41,7 @@ async fn admin_monitoring_list_user_summaries_by_ids(
}
pub(super) async fn admin_monitoring_load_affinity_identity_maps(
state: &AppState,
state: &AdminAppState<'_>,
affinities: &[AdminMonitoringCacheAffinityRecord],
) -> Result<
(
@@ -71,7 +72,7 @@ pub(super) async fn admin_monitoring_load_affinity_identity_maps(
}
pub(super) async fn admin_monitoring_find_user_summary_by_id(
state: &AppState,
state: &AdminAppState<'_>,
user_id: &str,
) -> Result<Option<aether_data::repository::users::StoredUserSummary>, GatewayError> {
if user_id.trim().is_empty() {

View File

@@ -2,7 +2,7 @@ use super::cache_config::ADMIN_MONITORING_REDIS_CACHE_CATEGORIES;
use super::cache_store::{
admin_monitoring_has_test_redis_keys, list_admin_monitoring_namespaced_keys,
};
use crate::AppState;
use crate::handlers::admin::request::AdminAppState;
use crate::GatewayError;
use axum::{
body::Body,
@@ -12,7 +12,7 @@ use axum::{
use serde_json::json;
pub(super) async fn build_admin_monitoring_model_mapping_stats_response(
state: &AppState,
state: &AdminAppState<'_>,
) -> Result<Response<Body>, GatewayError> {
if state.redis_kv_runner().is_none() && !admin_monitoring_has_test_redis_keys(state) {
return Ok(Json(json!({
@@ -67,7 +67,7 @@ pub(super) async fn build_admin_monitoring_model_mapping_stats_response(
}
pub(super) async fn build_admin_monitoring_redis_cache_categories_response(
state: &AppState,
state: &AdminAppState<'_>,
) -> Result<Response<Body>, GatewayError> {
if state.redis_kv_runner().is_none() && !admin_monitoring_has_test_redis_keys(state) {
return Ok(Json(json!({

View File

@@ -1,400 +0,0 @@
use super::cache_affinity::{
clear_admin_monitoring_scheduler_affinity_entries,
delete_admin_monitoring_cache_affinity_raw_keys,
};
use super::cache_config::ADMIN_MONITORING_REDIS_CACHE_CATEGORIES;
use super::cache_identity::{
admin_monitoring_find_user_summary_by_id, admin_monitoring_list_export_api_key_records_by_ids,
};
use super::cache_route_helpers::{
admin_monitoring_cache_affinity_delete_params_from_path,
admin_monitoring_cache_affinity_unavailable_response,
admin_monitoring_cache_model_mapping_provider_params_from_path,
admin_monitoring_cache_model_name_from_path, admin_monitoring_cache_provider_id_from_path,
admin_monitoring_cache_redis_category_from_path,
admin_monitoring_cache_users_not_found_response,
admin_monitoring_cache_users_user_identifier_from_path,
admin_monitoring_redis_unavailable_response,
};
use super::cache_store::{
admin_monitoring_has_test_redis_keys, delete_admin_monitoring_namespaced_keys,
list_admin_monitoring_cache_affinity_records,
list_admin_monitoring_cache_affinity_records_by_affinity_keys,
list_admin_monitoring_namespaced_keys, load_admin_monitoring_cache_affinity_entries_for_tests,
};
use super::responses::{
admin_monitoring_bad_request_response, admin_monitoring_not_found_response,
};
use crate::control::GatewayPublicRequestContext;
use crate::{AppState, GatewayError};
use axum::{
body::Body,
http,
response::{IntoResponse, Response},
Json,
};
use serde_json::json;
pub(super) async fn build_admin_monitoring_cache_users_delete_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
) -> Result<Response<Body>, GatewayError> {
let Some(user_identifier) =
admin_monitoring_cache_users_user_identifier_from_path(&request_context.request_path)
else {
return Ok(admin_monitoring_bad_request_response(
"缺少 user_identifier",
));
};
if state.redis_kv_runner().is_none()
&& load_admin_monitoring_cache_affinity_entries_for_tests(state).is_empty()
{
return Ok(admin_monitoring_cache_affinity_unavailable_response());
}
let direct_api_key_by_id =
admin_monitoring_list_export_api_key_records_by_ids(state, &[user_identifier.clone()])
.await?;
if let Some(api_key) = direct_api_key_by_id.get(&user_identifier) {
let target_affinity_keys =
std::iter::once(user_identifier.clone()).collect::<std::collections::BTreeSet<_>>();
let target_affinities = list_admin_monitoring_cache_affinity_records_by_affinity_keys(
state,
&target_affinity_keys,
)
.await?;
let raw_keys = target_affinities
.iter()
.map(|item| item.raw_key.clone())
.collect::<Vec<_>>();
let _ = delete_admin_monitoring_cache_affinity_raw_keys(state, &raw_keys).await?;
clear_admin_monitoring_scheduler_affinity_entries(state, &target_affinities);
let user = admin_monitoring_find_user_summary_by_id(state, &api_key.user_id).await?;
let api_key_name = api_key
.name
.clone()
.unwrap_or_else(|| user_identifier.clone());
return Ok(Json(json!({
"status": "ok",
"message": format!("已清除 API Key {api_key_name} 的缓存亲和性"),
"user_info": {
"user_id": Some(api_key.user_id.clone()),
"username": user.as_ref().map(|item| item.username.clone()),
"email": user.and_then(|item| item.email),
"api_key_id": user_identifier,
"api_key_name": api_key.name.clone(),
},
}))
.into_response());
}
let Some(user) = state.find_user_auth_by_identifier(&user_identifier).await? else {
return Ok(admin_monitoring_cache_users_not_found_response(
&user_identifier,
));
};
let user_api_key_ids = state
.list_auth_api_key_export_records_by_user_ids(std::slice::from_ref(&user.id))
.await?
.into_iter()
.map(|item| item.api_key_id.clone())
.collect::<std::collections::BTreeSet<_>>();
let target_affinities =
list_admin_monitoring_cache_affinity_records_by_affinity_keys(state, &user_api_key_ids)
.await?;
let raw_keys = target_affinities
.iter()
.map(|item| item.raw_key.clone())
.collect::<Vec<_>>();
let _ = delete_admin_monitoring_cache_affinity_raw_keys(state, &raw_keys).await?;
clear_admin_monitoring_scheduler_affinity_entries(state, &target_affinities);
Ok(Json(json!({
"status": "ok",
"message": format!("已清除用户 {} 的所有缓存亲和性", user.username),
"user_info": {
"user_id": user.id,
"username": user.username,
"email": user.email,
},
}))
.into_response())
}
pub(super) async fn build_admin_monitoring_cache_affinity_delete_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
) -> Result<Response<Body>, GatewayError> {
let Some((affinity_key, endpoint_id, model_id, api_format)) =
admin_monitoring_cache_affinity_delete_params_from_path(&request_context.request_path)
else {
return Ok(admin_monitoring_bad_request_response(
"缺少 affinity_key、endpoint_id、model_id 或 api_format",
));
};
if state.redis_kv_runner().is_none()
&& load_admin_monitoring_cache_affinity_entries_for_tests(state).is_empty()
{
return Ok(admin_monitoring_cache_affinity_unavailable_response());
}
let target_affinity_keys =
std::iter::once(affinity_key.clone()).collect::<std::collections::BTreeSet<_>>();
let target_affinity =
list_admin_monitoring_cache_affinity_records_by_affinity_keys(state, &target_affinity_keys)
.await?
.into_iter()
.find(|item| {
item.affinity_key == affinity_key
&& item.endpoint_id.as_deref() == Some(endpoint_id.as_str())
&& item.model_name == model_id
&& item.api_format.eq_ignore_ascii_case(&api_format)
});
let Some(target_affinity) = target_affinity else {
return Ok(admin_monitoring_not_found_response(
"未找到指定的缓存亲和性记录",
));
};
let _ = delete_admin_monitoring_cache_affinity_raw_keys(
state,
std::slice::from_ref(&target_affinity.raw_key),
)
.await?;
clear_admin_monitoring_scheduler_affinity_entries(
state,
std::slice::from_ref(&target_affinity),
);
let mut api_key_by_id = admin_monitoring_list_export_api_key_records_by_ids(
state,
std::slice::from_ref(&affinity_key),
)
.await?;
let api_key_name = api_key_by_id
.remove(&affinity_key)
.and_then(|item| item.name)
.unwrap_or_else(|| affinity_key.chars().take(8).collect::<String>());
Ok(Json(json!({
"status": "ok",
"message": format!("已清除缓存亲和性: {api_key_name}"),
"affinity_key": affinity_key,
"endpoint_id": endpoint_id,
"model_id": model_id,
}))
.into_response())
}
pub(super) async fn build_admin_monitoring_cache_flush_response(
state: &AppState,
) -> Result<Response<Body>, GatewayError> {
let raw_affinities = list_admin_monitoring_cache_affinity_records(state).await?;
if state.redis_kv_runner().is_none() && raw_affinities.is_empty() {
return Ok(admin_monitoring_cache_affinity_unavailable_response());
}
let raw_keys = raw_affinities
.iter()
.map(|item| item.raw_key.clone())
.collect::<Vec<_>>();
let deleted = delete_admin_monitoring_cache_affinity_raw_keys(state, &raw_keys).await?;
clear_admin_monitoring_scheduler_affinity_entries(state, &raw_affinities);
Ok(Json(json!({
"status": "ok",
"message": "已清除全部缓存亲和性",
"deleted_affinities": deleted,
}))
.into_response())
}
pub(super) async fn build_admin_monitoring_cache_provider_delete_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
) -> Result<Response<Body>, GatewayError> {
let Some(provider_id) =
admin_monitoring_cache_provider_id_from_path(&request_context.request_path)
else {
return Ok(admin_monitoring_bad_request_response("缺少 provider_id"));
};
let raw_affinities = list_admin_monitoring_cache_affinity_records(state).await?;
if state.redis_kv_runner().is_none() && raw_affinities.is_empty() {
return Ok(admin_monitoring_cache_affinity_unavailable_response());
}
let target_affinities = raw_affinities
.into_iter()
.filter(|item| item.provider_id.as_deref() == Some(provider_id.as_str()))
.collect::<Vec<_>>();
if target_affinities.is_empty() {
return Ok((
http::StatusCode::NOT_FOUND,
Json(json!({
"detail": format!("未找到 provider {provider_id} 的缓存亲和性记录")
})),
)
.into_response());
}
let raw_keys = target_affinities
.iter()
.map(|item| item.raw_key.clone())
.collect::<Vec<_>>();
let deleted = delete_admin_monitoring_cache_affinity_raw_keys(state, &raw_keys).await?;
clear_admin_monitoring_scheduler_affinity_entries(state, &target_affinities);
Ok(Json(json!({
"status": "ok",
"message": format!("已清除 provider {provider_id} 的缓存亲和性"),
"provider_id": provider_id,
"deleted_affinities": deleted,
}))
.into_response())
}
pub(super) async fn build_admin_monitoring_model_mapping_delete_response(
state: &AppState,
) -> Result<Response<Body>, GatewayError> {
if state.redis_kv_runner().is_none() && !admin_monitoring_has_test_redis_keys(state) {
return Ok(admin_monitoring_redis_unavailable_response());
}
let mut raw_keys = list_admin_monitoring_namespaced_keys(state, "model:*").await?;
raw_keys.extend(list_admin_monitoring_namespaced_keys(state, "global_model:*").await?);
raw_keys.sort();
raw_keys.dedup();
let deleted_count = delete_admin_monitoring_namespaced_keys(state, &raw_keys).await?;
Ok(Json(json!({
"status": "ok",
"message": "已清除所有模型映射缓存",
"deleted_count": deleted_count,
}))
.into_response())
}
pub(super) async fn build_admin_monitoring_model_mapping_delete_model_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
) -> Result<Response<Body>, GatewayError> {
let Some(model_name) =
admin_monitoring_cache_model_name_from_path(&request_context.request_path)
else {
return Ok(admin_monitoring_bad_request_response("缺少 model_name"));
};
if state.redis_kv_runner().is_none() && !admin_monitoring_has_test_redis_keys(state) {
return Ok(admin_monitoring_redis_unavailable_response());
}
let candidate_keys = [
format!("global_model:resolve:{model_name}"),
format!("global_model:name:{model_name}"),
];
let mut existing_keys = Vec::new();
for key in candidate_keys {
let matches = list_admin_monitoring_namespaced_keys(state, key.as_str()).await?;
existing_keys.extend(matches);
}
existing_keys.sort();
existing_keys.dedup();
let deleted_count = delete_admin_monitoring_namespaced_keys(state, &existing_keys).await?;
let deleted_keys = if deleted_count == 0 {
Vec::new()
} else {
existing_keys
};
Ok(Json(json!({
"status": "ok",
"message": format!("已清除模型 {model_name} 的映射缓存"),
"model_name": model_name,
"deleted_keys": deleted_keys,
}))
.into_response())
}
pub(super) async fn build_admin_monitoring_model_mapping_delete_provider_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
) -> Result<Response<Body>, GatewayError> {
let Some((provider_id, global_model_id)) =
admin_monitoring_cache_model_mapping_provider_params_from_path(
&request_context.request_path,
)
else {
return Ok(admin_monitoring_bad_request_response(
"缺少 provider_id 或 global_model_id",
));
};
if state.redis_kv_runner().is_none() && !admin_monitoring_has_test_redis_keys(state) {
return Ok(admin_monitoring_redis_unavailable_response());
}
let candidate_keys = [
format!("model:provider_global:{provider_id}:{global_model_id}"),
format!("model:provider_global:hits:{provider_id}:{global_model_id}"),
];
let mut existing_keys = Vec::new();
for key in candidate_keys {
let matches = list_admin_monitoring_namespaced_keys(state, key.as_str()).await?;
existing_keys.extend(matches);
}
existing_keys.sort();
existing_keys.dedup();
let _ = delete_admin_monitoring_namespaced_keys(state, &existing_keys).await?;
Ok(Json(json!({
"status": "ok",
"message": "已清除 Provider 模型映射缓存",
"provider_id": provider_id,
"global_model_id": global_model_id,
"deleted_keys": existing_keys,
}))
.into_response())
}
pub(super) async fn build_admin_monitoring_redis_keys_delete_response(
state: &AppState,
request_context: &GatewayPublicRequestContext,
) -> Result<Response<Body>, GatewayError> {
let Some(category) =
admin_monitoring_cache_redis_category_from_path(&request_context.request_path)
else {
return Ok(admin_monitoring_bad_request_response("缺少 category"));
};
let Some((cat_key, name, pattern, _description)) = ADMIN_MONITORING_REDIS_CACHE_CATEGORIES
.iter()
.find(|(cat_key, _, _, _)| *cat_key == category)
else {
return Ok((
http::StatusCode::NOT_FOUND,
Json(json!({ "detail": format!("未知的缓存分类: {category}") })),
)
.into_response());
};
if state.redis_kv_runner().is_none() && !admin_monitoring_has_test_redis_keys(state) {
return Ok(admin_monitoring_redis_unavailable_response());
}
let raw_keys = list_admin_monitoring_namespaced_keys(state, pattern).await?;
let deleted_count = delete_admin_monitoring_namespaced_keys(state, &raw_keys).await?;
Ok(Json(json!({
"status": "ok",
"message": format!("已清除 {name} 缓存"),
"category": cat_key,
"deleted_count": deleted_count,
}))
.into_response())
}

View File

@@ -0,0 +1,86 @@
use super::super::cache_affinity::{
clear_admin_monitoring_scheduler_affinity_entries,
delete_admin_monitoring_cache_affinity_raw_keys,
};
use super::super::cache_identity::admin_monitoring_list_export_api_key_records_by_ids;
use super::super::cache_route_helpers::{
admin_monitoring_cache_affinity_delete_params_from_path,
admin_monitoring_cache_affinity_unavailable_response,
};
use super::super::cache_store::{
list_admin_monitoring_cache_affinity_records_by_affinity_keys,
load_admin_monitoring_cache_affinity_entries_for_tests,
};
use crate::handlers::admin::request::{AdminAppState, AdminRequestContext};
use crate::GatewayError;
use aether_admin::observability::monitoring::{
admin_monitoring_bad_request_response, admin_monitoring_not_found_response,
build_admin_monitoring_cache_affinity_delete_success_response,
};
use axum::{body::Body, response::Response};
pub(in super::super) async fn build_admin_monitoring_cache_affinity_delete_response(
state: &AdminAppState<'_>,
request_context: &AdminRequestContext<'_>,
) -> Result<Response<Body>, GatewayError> {
let Some((affinity_key, endpoint_id, model_id, api_format)) =
admin_monitoring_cache_affinity_delete_params_from_path(&request_context.request_path)
else {
return Ok(admin_monitoring_bad_request_response(
"缺少 affinity_key、endpoint_id、model_id 或 api_format",
));
};
if state.redis_kv_runner().is_none()
&& load_admin_monitoring_cache_affinity_entries_for_tests(state).is_empty()
{
return Ok(admin_monitoring_cache_affinity_unavailable_response());
}
let target_affinity_keys =
std::iter::once(affinity_key.clone()).collect::<std::collections::BTreeSet<_>>();
let target_affinity =
list_admin_monitoring_cache_affinity_records_by_affinity_keys(state, &target_affinity_keys)
.await?
.into_iter()
.find(|item| {
item.affinity_key == affinity_key
&& item.endpoint_id.as_deref() == Some(endpoint_id.as_str())
&& item.model_name == model_id
&& item.api_format.eq_ignore_ascii_case(&api_format)
});
let Some(target_affinity) = target_affinity else {
return Ok(admin_monitoring_not_found_response(
"未找到指定的缓存亲和性记录",
));
};
let _ = delete_admin_monitoring_cache_affinity_raw_keys(
state,
std::slice::from_ref(&target_affinity.raw_key),
)
.await?;
clear_admin_monitoring_scheduler_affinity_entries(
state,
std::slice::from_ref(&target_affinity),
);
let mut api_key_by_id = admin_monitoring_list_export_api_key_records_by_ids(
state,
std::slice::from_ref(&affinity_key),
)
.await?;
let api_key_name = api_key_by_id
.remove(&affinity_key)
.and_then(|item| item.name)
.unwrap_or_else(|| affinity_key.chars().take(8).collect::<String>());
Ok(
build_admin_monitoring_cache_affinity_delete_success_response(
affinity_key,
endpoint_id,
model_id,
api_key_name,
),
)
}

View File

@@ -0,0 +1,28 @@
use super::super::cache_affinity::{
clear_admin_monitoring_scheduler_affinity_entries,
delete_admin_monitoring_cache_affinity_raw_keys,
};
use super::super::cache_route_helpers::admin_monitoring_cache_affinity_unavailable_response;
use super::super::cache_store::list_admin_monitoring_cache_affinity_records;
use crate::handlers::admin::request::AdminAppState;
use crate::GatewayError;
use aether_admin::observability::monitoring::build_admin_monitoring_cache_flush_success_response;
use axum::{body::Body, response::Response};
pub(in super::super) async fn build_admin_monitoring_cache_flush_response(
state: &AdminAppState<'_>,
) -> Result<Response<Body>, GatewayError> {
let raw_affinities = list_admin_monitoring_cache_affinity_records(state).await?;
if state.redis_kv_runner().is_none() && raw_affinities.is_empty() {
return Ok(admin_monitoring_cache_affinity_unavailable_response());
}
let raw_keys = raw_affinities
.iter()
.map(|item| item.raw_key.clone())
.collect::<Vec<_>>();
let deleted = delete_admin_monitoring_cache_affinity_raw_keys(state, &raw_keys).await?;
clear_admin_monitoring_scheduler_affinity_entries(state, &raw_affinities);
Ok(build_admin_monitoring_cache_flush_success_response(deleted))
}

Some files were not shown because too many files have changed in this diff Show More