mirror of
https://github.com/fawney19/Aether.git
synced 2026-10-08 02:17:46 +08:00
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:
@@ -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(),
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
@@ -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)
|
||||
}
|
||||
+8
-213
@@ -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;
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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),
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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,
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
mod core;
|
||||
|
||||
pub(crate) use core::maybe_build_local_admin_global_models_response;
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user