mirror of
https://github.com/fawney19/Aether.git
synced 2026-09-02 17:30:23 +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:
290
crates/aether-admin/src/provider/endpoints.rs
Normal file
290
crates/aether-admin/src/provider/endpoints.rs
Normal file
@@ -0,0 +1,290 @@
|
||||
use aether_data_contracts::repository::provider_catalog::{
|
||||
StoredProviderCatalogEndpoint, StoredProviderCatalogKey,
|
||||
};
|
||||
use chrono::{TimeZone, Utc};
|
||||
use serde_json::{json, Map, Value};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
fn unix_secs_to_rfc3339(unix_secs: u64) -> Option<String> {
|
||||
Utc.timestamp_opt(unix_secs as i64, 0)
|
||||
.single()
|
||||
.map(|value| value.to_rfc3339())
|
||||
}
|
||||
|
||||
pub fn key_api_formats_without_entry(
|
||||
key: &StoredProviderCatalogKey,
|
||||
api_format: &str,
|
||||
) -> Option<Vec<String>> {
|
||||
let current_formats = key
|
||||
.api_formats
|
||||
.as_ref()
|
||||
.and_then(serde_json::Value::as_array)
|
||||
.map(|values| {
|
||||
values
|
||||
.iter()
|
||||
.filter_map(serde_json::Value::as_str)
|
||||
.map(ToOwned::to_owned)
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
if !current_formats
|
||||
.iter()
|
||||
.any(|candidate| candidate == api_format)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(
|
||||
current_formats
|
||||
.into_iter()
|
||||
.filter(|candidate| candidate != api_format)
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn endpoint_key_counts_by_format(
|
||||
keys: &[StoredProviderCatalogKey],
|
||||
) -> (BTreeMap<String, usize>, BTreeMap<String, usize>) {
|
||||
let mut total = BTreeMap::new();
|
||||
let mut active = BTreeMap::new();
|
||||
for key in keys {
|
||||
let Some(formats) = key
|
||||
.api_formats
|
||||
.as_ref()
|
||||
.and_then(serde_json::Value::as_array)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
for api_format in formats.iter().filter_map(serde_json::Value::as_str) {
|
||||
*total.entry(api_format.to_string()).or_insert(0) += 1;
|
||||
if key.is_active {
|
||||
*active.entry(api_format.to_string()).or_insert(0) += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
(total, active)
|
||||
}
|
||||
|
||||
fn masked_proxy_value(proxy: Option<&serde_json::Value>) -> serde_json::Value {
|
||||
let Some(proxy) = proxy.and_then(serde_json::Value::as_object) else {
|
||||
return serde_json::Value::Null;
|
||||
};
|
||||
let mut masked = proxy.clone();
|
||||
if masked
|
||||
.get("password")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.is_some_and(|value| !value.trim().is_empty())
|
||||
{
|
||||
masked.insert("password".to_string(), json!("***"));
|
||||
}
|
||||
serde_json::Value::Object(masked)
|
||||
}
|
||||
|
||||
fn endpoint_timestamp_or_now(value: Option<u64>, now_unix_secs: u64) -> serde_json::Value {
|
||||
unix_secs_to_rfc3339(value.unwrap_or(now_unix_secs))
|
||||
.map(serde_json::Value::String)
|
||||
.unwrap_or(serde_json::Value::Null)
|
||||
}
|
||||
|
||||
pub fn build_admin_provider_endpoint_response(
|
||||
endpoint: &StoredProviderCatalogEndpoint,
|
||||
provider_name: &str,
|
||||
total_keys: usize,
|
||||
active_keys: usize,
|
||||
now_unix_secs: u64,
|
||||
) -> serde_json::Value {
|
||||
json!({
|
||||
"id": endpoint.id,
|
||||
"provider_id": endpoint.provider_id,
|
||||
"provider_name": provider_name,
|
||||
"api_format": endpoint.api_format,
|
||||
"base_url": endpoint.base_url,
|
||||
"custom_path": endpoint.custom_path,
|
||||
"header_rules": endpoint.header_rules,
|
||||
"body_rules": endpoint.body_rules,
|
||||
"max_retries": endpoint.max_retries.unwrap_or(2),
|
||||
"is_active": endpoint.is_active,
|
||||
"config": endpoint.config,
|
||||
"proxy": masked_proxy_value(endpoint.proxy.as_ref()),
|
||||
"format_acceptance_config": endpoint.format_acceptance_config,
|
||||
"total_keys": total_keys,
|
||||
"active_keys": active_keys,
|
||||
"created_at": endpoint_timestamp_or_now(endpoint.created_at_unix_secs, now_unix_secs),
|
||||
"updated_at": endpoint_timestamp_or_now(endpoint.updated_at_unix_secs, now_unix_secs),
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct AdminProviderEndpointUpdateFields {
|
||||
pub base_url: Option<String>,
|
||||
pub custom_path: Option<String>,
|
||||
pub header_rules: Option<Value>,
|
||||
pub body_rules: Option<Value>,
|
||||
pub max_retries: Option<i32>,
|
||||
pub is_active: Option<bool>,
|
||||
pub config: Option<Value>,
|
||||
pub proxy: Option<Value>,
|
||||
pub format_acceptance_config: Option<Value>,
|
||||
}
|
||||
|
||||
fn trimmed_non_empty_string(value: Option<String>) -> Option<String> {
|
||||
value.and_then(|value| {
|
||||
let trimmed = value.trim().to_string();
|
||||
(!trimmed.is_empty()).then_some(trimmed)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn build_admin_provider_endpoint_record(
|
||||
id: String,
|
||||
provider_id: String,
|
||||
normalized_api_format: String,
|
||||
api_family: String,
|
||||
endpoint_kind: String,
|
||||
base_url: String,
|
||||
custom_path: Option<String>,
|
||||
header_rules: Option<Value>,
|
||||
body_rules: Option<Value>,
|
||||
max_retries: i32,
|
||||
config: Option<Value>,
|
||||
proxy: Option<Value>,
|
||||
format_acceptance_config: Option<Value>,
|
||||
now_unix_secs: u64,
|
||||
) -> Result<StoredProviderCatalogEndpoint, String> {
|
||||
StoredProviderCatalogEndpoint::new(
|
||||
id,
|
||||
provider_id,
|
||||
normalized_api_format,
|
||||
Some(api_family),
|
||||
Some(endpoint_kind),
|
||||
true,
|
||||
)
|
||||
.map_err(|err| err.to_string())?
|
||||
.with_timestamps(Some(now_unix_secs), Some(now_unix_secs))
|
||||
.with_transport_fields(
|
||||
base_url,
|
||||
header_rules,
|
||||
body_rules,
|
||||
Some(max_retries),
|
||||
trimmed_non_empty_string(custom_path),
|
||||
config,
|
||||
format_acceptance_config,
|
||||
proxy,
|
||||
)
|
||||
.map_err(|err| err.to_string())
|
||||
}
|
||||
|
||||
pub fn apply_admin_provider_endpoint_update_fields(
|
||||
existing_endpoint: &StoredProviderCatalogEndpoint,
|
||||
raw_payload: &Map<String, Value>,
|
||||
payload: &AdminProviderEndpointUpdateFields,
|
||||
) -> Result<StoredProviderCatalogEndpoint, String> {
|
||||
let mut updated = existing_endpoint.clone();
|
||||
|
||||
if let Some(value) = raw_payload.get("base_url") {
|
||||
let Some(base_url) = payload.base_url.as_deref() else {
|
||||
return Err(if value.is_null() {
|
||||
"base_url 不能为空".to_string()
|
||||
} else {
|
||||
"base_url 必须是字符串".to_string()
|
||||
});
|
||||
};
|
||||
updated.base_url = base_url.to_string();
|
||||
}
|
||||
|
||||
if raw_payload.contains_key("custom_path") {
|
||||
updated.custom_path = payload.custom_path.clone();
|
||||
}
|
||||
|
||||
if let Some(value) = raw_payload.get("header_rules") {
|
||||
if !value.is_null() && !value.is_array() {
|
||||
return Err("header_rules 必须是数组或 null".to_string());
|
||||
}
|
||||
updated.header_rules = if value.is_null() {
|
||||
None
|
||||
} else {
|
||||
payload.header_rules.clone()
|
||||
};
|
||||
}
|
||||
|
||||
if let Some(value) = raw_payload.get("body_rules") {
|
||||
if !value.is_null() && !value.is_array() {
|
||||
return Err("body_rules 必须是数组或 null".to_string());
|
||||
}
|
||||
updated.body_rules = if value.is_null() {
|
||||
None
|
||||
} else {
|
||||
payload.body_rules.clone()
|
||||
};
|
||||
}
|
||||
|
||||
if let Some(value) = raw_payload.get("max_retries") {
|
||||
let Some(max_retries) = payload.max_retries else {
|
||||
return Err(if value.is_null() {
|
||||
"max_retries 必须是 0 到 999 之间的整数".to_string()
|
||||
} else {
|
||||
"max_retries 必须是整数".to_string()
|
||||
});
|
||||
};
|
||||
if !(0..=999).contains(&max_retries) {
|
||||
return Err("max_retries 必须在 0 到 999 之间".to_string());
|
||||
}
|
||||
updated.max_retries = Some(max_retries);
|
||||
}
|
||||
|
||||
if raw_payload.contains_key("is_active") {
|
||||
let Some(is_active) = payload.is_active else {
|
||||
return Err("is_active 必须是布尔值".to_string());
|
||||
};
|
||||
updated.is_active = is_active;
|
||||
}
|
||||
|
||||
if let Some(value) = raw_payload.get("config") {
|
||||
if !value.is_null() && !value.is_object() {
|
||||
return Err("config 必须是对象或 null".to_string());
|
||||
}
|
||||
updated.config = if value.is_null() {
|
||||
None
|
||||
} else {
|
||||
payload.config.clone()
|
||||
};
|
||||
}
|
||||
|
||||
if let Some(value) = raw_payload.get("proxy") {
|
||||
if value.is_null() {
|
||||
updated.proxy = None;
|
||||
} else {
|
||||
let Some(mut proxy) = payload
|
||||
.proxy
|
||||
.clone()
|
||||
.and_then(|value| value.as_object().cloned())
|
||||
else {
|
||||
return Err("proxy 必须是对象或 null".to_string());
|
||||
};
|
||||
if !proxy.contains_key("password") {
|
||||
if let Some(old_password) = existing_endpoint
|
||||
.proxy
|
||||
.as_ref()
|
||||
.and_then(Value::as_object)
|
||||
.and_then(|proxy| proxy.get("password"))
|
||||
.and_then(Value::as_str)
|
||||
.filter(|value| !value.is_empty())
|
||||
{
|
||||
proxy.insert("password".to_string(), json!(old_password));
|
||||
}
|
||||
}
|
||||
updated.proxy = Some(Value::Object(proxy));
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(value) = raw_payload.get("format_acceptance_config") {
|
||||
if !value.is_null() && !value.is_object() {
|
||||
return Err("format_acceptance_config 必须是对象或 null".to_string());
|
||||
}
|
||||
updated.format_acceptance_config = if value.is_null() {
|
||||
None
|
||||
} else {
|
||||
payload.format_acceptance_config.clone()
|
||||
};
|
||||
}
|
||||
|
||||
Ok(updated)
|
||||
}
|
||||
9
crates/aether-admin/src/provider/mod.rs
Normal file
9
crates/aether-admin/src/provider/mod.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
pub mod endpoints;
|
||||
pub mod models;
|
||||
pub mod models_write;
|
||||
pub mod oauth;
|
||||
pub mod ops;
|
||||
pub mod pool;
|
||||
pub mod quota;
|
||||
pub mod state;
|
||||
pub mod verify;
|
||||
232
crates/aether-admin/src/provider/models.rs
Normal file
232
crates/aether-admin/src/provider/models.rs
Normal file
@@ -0,0 +1,232 @@
|
||||
use aether_data_contracts::repository::global_models::StoredAdminProviderModel;
|
||||
use chrono::{SecondsFormat, Utc};
|
||||
use serde_json::{json, Map, Value};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
fn unix_secs_to_rfc3339(unix_secs: u64) -> Option<String> {
|
||||
let timestamp = i64::try_from(unix_secs).ok()?;
|
||||
Some(
|
||||
chrono::DateTime::<Utc>::from_timestamp(timestamp, 0)?
|
||||
.to_rfc3339_opts(SecondsFormat::Secs, true),
|
||||
)
|
||||
}
|
||||
|
||||
fn model_tiered_pricing_first_tier_value(
|
||||
tiered_pricing: Option<&Value>,
|
||||
field_name: &str,
|
||||
) -> Option<f64> {
|
||||
tiered_pricing
|
||||
.and_then(|value| value.get("tiers"))
|
||||
.and_then(Value::as_array)
|
||||
.and_then(|tiers| tiers.first())
|
||||
.and_then(|tier| tier.get(field_name))
|
||||
.and_then(Value::as_f64)
|
||||
}
|
||||
|
||||
fn model_effective_capability(
|
||||
explicit: Option<bool>,
|
||||
global_model_config: Option<&Value>,
|
||||
config_key: &str,
|
||||
) -> bool {
|
||||
explicit.unwrap_or_else(|| {
|
||||
global_model_config
|
||||
.and_then(|value| value.get(config_key))
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false)
|
||||
})
|
||||
}
|
||||
|
||||
fn merge_json_values(base: &mut Value, overlay: Value) {
|
||||
match (base, overlay) {
|
||||
(Value::Object(base_map), Value::Object(overlay_map)) => {
|
||||
for (key, value) in overlay_map {
|
||||
match base_map.get_mut(&key) {
|
||||
Some(existing) => merge_json_values(existing, value),
|
||||
None => {
|
||||
base_map.insert(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(base, overlay) => *base = overlay,
|
||||
}
|
||||
}
|
||||
|
||||
fn merge_admin_provider_model_effective_config(model: &StoredAdminProviderModel) -> Option<Value> {
|
||||
let mut merged = match model.global_model_config.clone() {
|
||||
Some(Value::Object(map)) => Value::Object(map),
|
||||
Some(other) => other,
|
||||
None => Value::Object(Map::new()),
|
||||
};
|
||||
|
||||
if let Some(config) = model.config.clone() {
|
||||
merge_json_values(&mut merged, config);
|
||||
}
|
||||
|
||||
match merged {
|
||||
Value::Null => None,
|
||||
Value::Object(ref map) if map.is_empty() => None,
|
||||
value => Some(value),
|
||||
}
|
||||
}
|
||||
|
||||
fn timestamp_or_now(value: Option<u64>, now_unix_secs: u64) -> Value {
|
||||
unix_secs_to_rfc3339(value.unwrap_or(now_unix_secs))
|
||||
.map(Value::String)
|
||||
.unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
pub fn admin_provider_model_effective_input_price(model: &StoredAdminProviderModel) -> Option<f64> {
|
||||
model_tiered_pricing_first_tier_value(model.tiered_pricing.as_ref(), "input_price_per_1m")
|
||||
.or_else(|| {
|
||||
model_tiered_pricing_first_tier_value(
|
||||
model.global_model_default_tiered_pricing.as_ref(),
|
||||
"input_price_per_1m",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn admin_provider_model_effective_output_price(
|
||||
model: &StoredAdminProviderModel,
|
||||
) -> Option<f64> {
|
||||
model_tiered_pricing_first_tier_value(model.tiered_pricing.as_ref(), "output_price_per_1m")
|
||||
.or_else(|| {
|
||||
model_tiered_pricing_first_tier_value(
|
||||
model.global_model_default_tiered_pricing.as_ref(),
|
||||
"output_price_per_1m",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn admin_provider_model_effective_capability(
|
||||
model: &StoredAdminProviderModel,
|
||||
capability: &str,
|
||||
) -> bool {
|
||||
match capability {
|
||||
"vision" => model_effective_capability(
|
||||
model.supports_vision,
|
||||
model.global_model_config.as_ref(),
|
||||
"vision",
|
||||
),
|
||||
"function_calling" => model_effective_capability(
|
||||
model.supports_function_calling,
|
||||
model.global_model_config.as_ref(),
|
||||
"function_calling",
|
||||
),
|
||||
"streaming" => model_effective_capability(
|
||||
model.supports_streaming,
|
||||
model.global_model_config.as_ref(),
|
||||
"streaming",
|
||||
),
|
||||
"extended_thinking" => model_effective_capability(
|
||||
model.supports_extended_thinking,
|
||||
model.global_model_config.as_ref(),
|
||||
"extended_thinking",
|
||||
),
|
||||
"image_generation" => model_effective_capability(
|
||||
model.supports_image_generation,
|
||||
model.global_model_config.as_ref(),
|
||||
"image_generation",
|
||||
),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_admin_provider_model_response(
|
||||
model: &StoredAdminProviderModel,
|
||||
now_unix_secs: u64,
|
||||
) -> Value {
|
||||
let effective_tiered_pricing = model
|
||||
.tiered_pricing
|
||||
.clone()
|
||||
.or_else(|| model.global_model_default_tiered_pricing.clone());
|
||||
let effective_config = merge_admin_provider_model_effective_config(model);
|
||||
|
||||
json!({
|
||||
"id": &model.id,
|
||||
"provider_id": &model.provider_id,
|
||||
"global_model_id": &model.global_model_id,
|
||||
"provider_model_name": &model.provider_model_name,
|
||||
"provider_model_mappings": model.provider_model_mappings.clone(),
|
||||
"price_per_request": model.price_per_request,
|
||||
"tiered_pricing": model.tiered_pricing.clone(),
|
||||
"effective_tiered_pricing": effective_tiered_pricing,
|
||||
"effective_input_price": admin_provider_model_effective_input_price(model),
|
||||
"effective_output_price": admin_provider_model_effective_output_price(model),
|
||||
"effective_price_per_request": model
|
||||
.price_per_request
|
||||
.or(model.global_model_default_price_per_request),
|
||||
"supports_vision": model.supports_vision,
|
||||
"supports_function_calling": model.supports_function_calling,
|
||||
"supports_streaming": model.supports_streaming,
|
||||
"supports_extended_thinking": model.supports_extended_thinking,
|
||||
"supports_image_generation": model.supports_image_generation,
|
||||
"effective_supports_vision": admin_provider_model_effective_capability(model, "vision"),
|
||||
"effective_supports_function_calling": admin_provider_model_effective_capability(
|
||||
model,
|
||||
"function_calling",
|
||||
),
|
||||
"effective_supports_streaming": admin_provider_model_effective_capability(model, "streaming"),
|
||||
"effective_supports_extended_thinking": admin_provider_model_effective_capability(
|
||||
model,
|
||||
"extended_thinking",
|
||||
),
|
||||
"effective_supports_image_generation": admin_provider_model_effective_capability(
|
||||
model,
|
||||
"image_generation",
|
||||
),
|
||||
"is_active": model.is_active,
|
||||
"is_available": model.is_available,
|
||||
"config": model.config.clone(),
|
||||
"effective_config": effective_config,
|
||||
"global_model_name": model.global_model_name.clone(),
|
||||
"global_model_display_name": model.global_model_display_name.clone(),
|
||||
"created_at": timestamp_or_now(model.created_at_unix_secs, now_unix_secs),
|
||||
"updated_at": timestamp_or_now(model.updated_at_unix_secs, now_unix_secs),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn build_admin_provider_available_source_models_payload(
|
||||
models: Vec<StoredAdminProviderModel>,
|
||||
) -> Value {
|
||||
let mut by_global_model = BTreeMap::<String, StoredAdminProviderModel>::new();
|
||||
for model in models {
|
||||
by_global_model
|
||||
.entry(model.global_model_id.clone())
|
||||
.or_insert(model);
|
||||
}
|
||||
let mut payload_models = by_global_model
|
||||
.into_values()
|
||||
.map(|model| {
|
||||
json!({
|
||||
"global_model_name": model.global_model_name,
|
||||
"display_name": model.global_model_display_name,
|
||||
"provider_model_name": model.provider_model_name,
|
||||
"model_id": model.id,
|
||||
"price": {
|
||||
"input_price_per_1m": admin_provider_model_effective_input_price(&model),
|
||||
"output_price_per_1m": admin_provider_model_effective_output_price(&model),
|
||||
"cache_creation_price_per_1m": Value::Null,
|
||||
"cache_read_price_per_1m": Value::Null,
|
||||
"price_per_request": model.price_per_request.or(model.global_model_default_price_per_request),
|
||||
},
|
||||
"capabilities": json!({
|
||||
"supports_vision": admin_provider_model_effective_capability(&model, "vision"),
|
||||
"supports_function_calling": admin_provider_model_effective_capability(&model, "function_calling"),
|
||||
"supports_streaming": admin_provider_model_effective_capability(&model, "streaming"),
|
||||
}),
|
||||
"is_active": model.is_active,
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let total = payload_models.len();
|
||||
payload_models.sort_by(|left, right| {
|
||||
left.get("global_model_name")
|
||||
.and_then(Value::as_str)
|
||||
.cmp(&right.get("global_model_name").and_then(Value::as_str))
|
||||
});
|
||||
json!({
|
||||
"models": payload_models,
|
||||
"total": total,
|
||||
})
|
||||
}
|
||||
188
crates/aether-admin/src/provider/models_write.rs
Normal file
188
crates/aether-admin/src/provider/models_write.rs
Normal file
@@ -0,0 +1,188 @@
|
||||
use aether_data_contracts::repository::global_models::{
|
||||
CreateAdminGlobalModelRecord, StoredAdminProviderModel, UpsertAdminProviderModelRecord,
|
||||
};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
pub fn normalize_required_trimmed_string(value: &str, field_name: &str) -> Result<String, String> {
|
||||
let trimmed = value.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Err(format!("{field_name} 不能为空"));
|
||||
}
|
||||
Ok(trimmed.to_string())
|
||||
}
|
||||
|
||||
pub fn normalize_optional_price(
|
||||
value: Option<f64>,
|
||||
field_name: &str,
|
||||
) -> Result<Option<f64>, String> {
|
||||
let Some(value) = value else {
|
||||
return Ok(None);
|
||||
};
|
||||
if !value.is_finite() || value < 0.0 {
|
||||
return Err(format!("{field_name} 必须是非负数"));
|
||||
}
|
||||
Ok(Some(value))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn build_admin_provider_model_create_record(
|
||||
id: String,
|
||||
provider_id: String,
|
||||
global_model_id: String,
|
||||
provider_model_name: String,
|
||||
provider_model_mappings: Option<serde_json::Value>,
|
||||
price_per_request: Option<f64>,
|
||||
tiered_pricing: Option<serde_json::Value>,
|
||||
supports_vision: Option<bool>,
|
||||
supports_function_calling: Option<bool>,
|
||||
supports_streaming: Option<bool>,
|
||||
supports_extended_thinking: Option<bool>,
|
||||
is_active: Option<bool>,
|
||||
config: Option<serde_json::Value>,
|
||||
) -> Result<UpsertAdminProviderModelRecord, String> {
|
||||
UpsertAdminProviderModelRecord::new(
|
||||
id,
|
||||
provider_id,
|
||||
global_model_id,
|
||||
provider_model_name,
|
||||
provider_model_mappings,
|
||||
price_per_request,
|
||||
tiered_pricing,
|
||||
supports_vision,
|
||||
supports_function_calling,
|
||||
supports_streaming,
|
||||
supports_extended_thinking,
|
||||
None,
|
||||
is_active.unwrap_or(true),
|
||||
true,
|
||||
config,
|
||||
)
|
||||
.map_err(|err| err.to_string())
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn build_admin_provider_model_update_record(
|
||||
existing: &StoredAdminProviderModel,
|
||||
global_model_id: String,
|
||||
provider_model_name: String,
|
||||
provider_model_mappings: Option<serde_json::Value>,
|
||||
price_per_request: Option<f64>,
|
||||
tiered_pricing: Option<serde_json::Value>,
|
||||
supports_vision: Option<bool>,
|
||||
supports_function_calling: Option<bool>,
|
||||
supports_streaming: Option<bool>,
|
||||
supports_extended_thinking: Option<bool>,
|
||||
is_active: bool,
|
||||
is_available: bool,
|
||||
config: Option<serde_json::Value>,
|
||||
) -> Result<UpsertAdminProviderModelRecord, String> {
|
||||
UpsertAdminProviderModelRecord::new(
|
||||
existing.id.clone(),
|
||||
existing.provider_id.clone(),
|
||||
global_model_id,
|
||||
provider_model_name,
|
||||
provider_model_mappings,
|
||||
price_per_request,
|
||||
tiered_pricing,
|
||||
supports_vision,
|
||||
supports_function_calling,
|
||||
supports_streaming,
|
||||
supports_extended_thinking,
|
||||
existing.supports_image_generation,
|
||||
is_active,
|
||||
is_available,
|
||||
config,
|
||||
)
|
||||
.map_err(|err| err.to_string())
|
||||
}
|
||||
|
||||
pub fn normalize_admin_import_model_id(model_id: &str) -> Result<String, String> {
|
||||
let trimmed = model_id.trim();
|
||||
if trimmed.is_empty() || trimmed.len() > 100 {
|
||||
return Err("Invalid model_id: must be 1-100 characters".to_string());
|
||||
}
|
||||
Ok(trimmed.to_string())
|
||||
}
|
||||
|
||||
pub fn default_admin_import_tiered_pricing() -> Value {
|
||||
json!({
|
||||
"tiers": [{
|
||||
"up_to": null,
|
||||
"input_price_per_1m": 0.0,
|
||||
"output_price_per_1m": 0.0,
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
pub fn build_admin_import_global_model_record(
|
||||
id: String,
|
||||
model_name: String,
|
||||
price_per_request: Option<f64>,
|
||||
tiered_pricing: Option<Value>,
|
||||
) -> Result<CreateAdminGlobalModelRecord, String> {
|
||||
CreateAdminGlobalModelRecord::new(
|
||||
id,
|
||||
model_name.clone(),
|
||||
model_name,
|
||||
true,
|
||||
price_per_request,
|
||||
tiered_pricing.or_else(|| Some(default_admin_import_tiered_pricing())),
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.map_err(|err| err.to_string())
|
||||
}
|
||||
|
||||
pub fn build_admin_import_provider_model_record(
|
||||
id: String,
|
||||
provider_id: String,
|
||||
global_model_id: String,
|
||||
provider_model_name: String,
|
||||
price_per_request: Option<f64>,
|
||||
tiered_pricing: Option<Value>,
|
||||
) -> Result<UpsertAdminProviderModelRecord, String> {
|
||||
UpsertAdminProviderModelRecord::new(
|
||||
id,
|
||||
provider_id,
|
||||
global_model_id,
|
||||
provider_model_name,
|
||||
None,
|
||||
price_per_request,
|
||||
tiered_pricing,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
true,
|
||||
true,
|
||||
None,
|
||||
)
|
||||
.map_err(|err| err.to_string())
|
||||
}
|
||||
|
||||
pub fn build_admin_batch_assign_provider_model_record(
|
||||
id: String,
|
||||
provider_id: String,
|
||||
global_model_id: String,
|
||||
provider_model_name: String,
|
||||
) -> Result<UpsertAdminProviderModelRecord, String> {
|
||||
UpsertAdminProviderModelRecord::new(
|
||||
id,
|
||||
provider_id,
|
||||
global_model_id,
|
||||
provider_model_name,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
true,
|
||||
true,
|
||||
None,
|
||||
)
|
||||
.map_err(|err| err.to_string())
|
||||
}
|
||||
132
crates/aether-admin/src/provider/oauth.rs
Normal file
132
crates/aether-admin/src/provider/oauth.rs
Normal file
@@ -0,0 +1,132 @@
|
||||
use serde_json::{json, Value};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
pub fn build_kiro_batch_import_key_name(
|
||||
email: Option<&str>,
|
||||
auth_method: Option<&str>,
|
||||
refresh_token: Option<&str>,
|
||||
) -> String {
|
||||
let method = auth_method
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.unwrap_or("social");
|
||||
let base = email
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
.unwrap_or_else(|| {
|
||||
let hash = Sha256::digest(refresh_token.unwrap_or_default().as_bytes());
|
||||
let hex = hash
|
||||
.iter()
|
||||
.map(|byte| format!("{byte:02x}"))
|
||||
.collect::<String>();
|
||||
format!("kiro_{}", &hex[..6])
|
||||
});
|
||||
format!("{base} ({method})")
|
||||
}
|
||||
|
||||
pub fn coerce_admin_provider_oauth_import_str(value: Option<&Value>) -> Option<String> {
|
||||
value
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
}
|
||||
|
||||
fn normalize_admin_provider_oauth_kiro_import_item(item: &Value) -> Option<Value> {
|
||||
match item {
|
||||
Value::String(value) => {
|
||||
let refresh_token = value.trim();
|
||||
if refresh_token.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(json!({ "refresh_token": refresh_token }))
|
||||
}
|
||||
}
|
||||
Value::Object(object) => {
|
||||
if let Some(nested) = object
|
||||
.get("auth_config")
|
||||
.or_else(|| object.get("authConfig"))
|
||||
.and_then(Value::as_object)
|
||||
{
|
||||
let mut merged = nested.clone();
|
||||
for key in [
|
||||
"provider_type",
|
||||
"providerType",
|
||||
"auth_method",
|
||||
"authMethod",
|
||||
"auth_type",
|
||||
"authType",
|
||||
"refresh_token",
|
||||
"refreshToken",
|
||||
"expires_at",
|
||||
"expiresAt",
|
||||
"profile_arn",
|
||||
"profileArn",
|
||||
"region",
|
||||
"auth_region",
|
||||
"authRegion",
|
||||
"api_region",
|
||||
"apiRegion",
|
||||
"client_id",
|
||||
"clientId",
|
||||
"client_secret",
|
||||
"clientSecret",
|
||||
"machine_id",
|
||||
"machineId",
|
||||
"kiro_version",
|
||||
"kiroVersion",
|
||||
"system_version",
|
||||
"systemVersion",
|
||||
"node_version",
|
||||
"nodeVersion",
|
||||
"email",
|
||||
"access_token",
|
||||
"accessToken",
|
||||
] {
|
||||
if let Some(value) = object.get(key) {
|
||||
if !value.is_null()
|
||||
&& !(value.is_string()
|
||||
&& value.as_str().is_some_and(|inner| inner.trim().is_empty()))
|
||||
{
|
||||
merged.insert(key.to_string(), value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
return Some(Value::Object(merged));
|
||||
}
|
||||
Some(Value::Object(object.clone()))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_admin_provider_oauth_kiro_batch_import_entries(raw_credentials: &str) -> Vec<Value> {
|
||||
let raw = raw_credentials.trim();
|
||||
if raw.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
if raw.starts_with('[') {
|
||||
if let Ok(Value::Array(items)) = serde_json::from_str::<Value>(raw) {
|
||||
return items
|
||||
.iter()
|
||||
.filter_map(normalize_admin_provider_oauth_kiro_import_item)
|
||||
.collect();
|
||||
}
|
||||
}
|
||||
|
||||
if raw.starts_with('{') {
|
||||
if let Ok(value) = serde_json::from_str::<Value>(raw) {
|
||||
return normalize_admin_provider_oauth_kiro_import_item(&value)
|
||||
.into_iter()
|
||||
.collect();
|
||||
}
|
||||
}
|
||||
|
||||
raw.lines()
|
||||
.map(str::trim)
|
||||
.filter(|line| !line.is_empty() && !line.starts_with('#'))
|
||||
.map(|refresh_token| json!({ "refreshToken": refresh_token }))
|
||||
.collect()
|
||||
}
|
||||
156
crates/aether-admin/src/provider/ops.rs
Normal file
156
crates/aether-admin/src/provider/ops.rs
Normal file
@@ -0,0 +1,156 @@
|
||||
use aether_data_contracts::repository::provider_catalog::{
|
||||
StoredProviderCatalogEndpoint, StoredProviderCatalogProvider,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
pub fn admin_provider_ops_config_object(
|
||||
provider: &StoredProviderCatalogProvider,
|
||||
) -> Option<&serde_json::Map<String, serde_json::Value>> {
|
||||
provider
|
||||
.config
|
||||
.as_ref()
|
||||
.and_then(serde_json::Value::as_object)
|
||||
.and_then(|config| config.get("provider_ops"))
|
||||
.and_then(serde_json::Value::as_object)
|
||||
}
|
||||
|
||||
pub fn admin_provider_ops_connector_object(
|
||||
provider_ops_config: &serde_json::Map<String, serde_json::Value>,
|
||||
) -> Option<&serde_json::Map<String, serde_json::Value>> {
|
||||
provider_ops_config
|
||||
.get("connector")
|
||||
.and_then(serde_json::Value::as_object)
|
||||
}
|
||||
|
||||
pub fn admin_provider_ops_is_supported_auth_type(auth_type: &str) -> bool {
|
||||
matches!(
|
||||
auth_type,
|
||||
"api_key" | "session_login" | "oauth" | "cookie" | "none"
|
||||
)
|
||||
}
|
||||
|
||||
pub fn admin_provider_ops_uses_python_verify_fallback(
|
||||
architecture_id: &str,
|
||||
config: &serde_json::Map<String, serde_json::Value>,
|
||||
) -> bool {
|
||||
let _ = architecture_id;
|
||||
config
|
||||
.get("proxy_enabled")
|
||||
.and_then(serde_json::Value::as_bool)
|
||||
.unwrap_or(false)
|
||||
|| config
|
||||
.get("proxy_node_id")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map(str::trim)
|
||||
.is_some_and(|value| !value.is_empty())
|
||||
}
|
||||
|
||||
pub fn admin_provider_ops_sensitive_placeholder_or_empty(
|
||||
value: Option<&serde_json::Value>,
|
||||
) -> bool {
|
||||
match value {
|
||||
None | Some(serde_json::Value::Null) => true,
|
||||
Some(serde_json::Value::String(raw)) => raw.is_empty() || raw.chars().all(|ch| ch == '*'),
|
||||
Some(serde_json::Value::Array(items)) => items.is_empty(),
|
||||
Some(serde_json::Value::Object(map)) => map.is_empty(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resolve_admin_provider_ops_base_url(
|
||||
provider: &StoredProviderCatalogProvider,
|
||||
endpoints: &[StoredProviderCatalogEndpoint],
|
||||
provider_ops_config: Option<&serde_json::Map<String, serde_json::Value>>,
|
||||
) -> Option<String> {
|
||||
let from_saved_config = provider_ops_config
|
||||
.and_then(|config| config.get("base_url"))
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(ToOwned::to_owned);
|
||||
if from_saved_config.is_some() {
|
||||
return from_saved_config;
|
||||
}
|
||||
|
||||
if let Some(base_url) = endpoints.iter().find_map(|endpoint| {
|
||||
let value = endpoint.base_url.trim();
|
||||
(!value.is_empty()).then(|| value.to_string())
|
||||
}) {
|
||||
return Some(base_url);
|
||||
}
|
||||
|
||||
let from_provider_config = provider
|
||||
.config
|
||||
.as_ref()
|
||||
.and_then(serde_json::Value::as_object)
|
||||
.and_then(|config| config.get("base_url"))
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(ToOwned::to_owned);
|
||||
if from_provider_config.is_some() {
|
||||
return from_provider_config;
|
||||
}
|
||||
|
||||
provider
|
||||
.website
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
}
|
||||
|
||||
pub fn build_admin_provider_ops_status_payload(
|
||||
provider_id: &str,
|
||||
provider: Option<&StoredProviderCatalogProvider>,
|
||||
) -> serde_json::Value {
|
||||
let provider_ops_config = provider.and_then(admin_provider_ops_config_object);
|
||||
let auth_type = provider_ops_config
|
||||
.and_then(admin_provider_ops_connector_object)
|
||||
.and_then(|connector| connector.get("auth_type"))
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.unwrap_or_else(|| {
|
||||
if provider_ops_config.is_some() {
|
||||
"api_key"
|
||||
} else {
|
||||
"none"
|
||||
}
|
||||
});
|
||||
let mut enabled_actions = provider_ops_config
|
||||
.and_then(|config| config.get("actions"))
|
||||
.and_then(serde_json::Value::as_object)
|
||||
.map(|actions| {
|
||||
actions
|
||||
.iter()
|
||||
.filter_map(|(action_type, config)| {
|
||||
let enabled = config
|
||||
.as_object()
|
||||
.and_then(|config| config.get("enabled"))
|
||||
.and_then(serde_json::Value::as_bool)
|
||||
.unwrap_or(true);
|
||||
enabled.then(|| serde_json::Value::String(action_type.clone()))
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
enabled_actions.sort_by(|left, right| left.as_str().cmp(&right.as_str()));
|
||||
|
||||
json!({
|
||||
"provider_id": provider_id,
|
||||
"is_configured": provider_ops_config.is_some(),
|
||||
"architecture_id": provider_ops_config.map(|config| {
|
||||
config
|
||||
.get("architecture_id")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.unwrap_or("generic_api")
|
||||
}),
|
||||
"connection_status": {
|
||||
"status": "disconnected",
|
||||
"auth_type": auth_type,
|
||||
"connected_at": serde_json::Value::Null,
|
||||
"expires_at": serde_json::Value::Null,
|
||||
"last_error": serde_json::Value::Null,
|
||||
},
|
||||
"enabled_actions": enabled_actions,
|
||||
})
|
||||
}
|
||||
848
crates/aether-admin/src/provider/pool.rs
Normal file
848
crates/aether-admin/src/provider/pool.rs
Normal file
@@ -0,0 +1,848 @@
|
||||
use aether_data_contracts::repository::provider_catalog::{
|
||||
StoredProviderCatalogEndpoint, StoredProviderCatalogKey, StoredProviderCatalogKeyStats,
|
||||
StoredProviderCatalogProvider,
|
||||
};
|
||||
use chrono::{TimeZone, Utc};
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
#[derive(Debug, Default, Clone, serde::Deserialize)]
|
||||
pub struct AdminPoolResolveSelectionRequest {
|
||||
#[serde(default)]
|
||||
pub search: String,
|
||||
#[serde(default)]
|
||||
pub quick_selectors: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, serde::Deserialize)]
|
||||
pub struct AdminPoolBatchActionRequest {
|
||||
#[serde(default)]
|
||||
pub key_ids: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub action: String,
|
||||
#[serde(default)]
|
||||
pub payload: Option<Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AdminPoolBatchActionKind {
|
||||
Enable,
|
||||
Disable,
|
||||
ClearProxy,
|
||||
SetProxy,
|
||||
RegenerateFingerprint,
|
||||
Delete,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AdminPoolBatchActionPlan {
|
||||
pub key_ids: Vec<String>,
|
||||
pub action: AdminPoolBatchActionKind,
|
||||
pub action_label: &'static str,
|
||||
pub proxy_payload: Option<Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct AdminPoolKeyPayloadContext {
|
||||
pub cooldown_reason: Option<String>,
|
||||
pub cooldown_ttl_seconds: Option<u64>,
|
||||
pub cost_window_usage: u64,
|
||||
pub sticky_sessions: usize,
|
||||
pub lru_score: Option<f64>,
|
||||
pub cost_limit: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, serde::Deserialize)]
|
||||
pub struct AdminPoolBatchImportRequest {
|
||||
#[serde(default)]
|
||||
pub keys: Vec<AdminPoolBatchImportItem>,
|
||||
#[serde(default)]
|
||||
pub proxy_node_id: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, serde::Deserialize)]
|
||||
pub struct AdminPoolBatchImportItem {
|
||||
#[serde(default)]
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub api_key: String,
|
||||
#[serde(default)]
|
||||
pub auth_type: String,
|
||||
}
|
||||
|
||||
fn admin_pool_reason_indicates_ban(reason: &str) -> bool {
|
||||
let normalized = reason.trim().to_ascii_lowercase();
|
||||
!normalized.is_empty()
|
||||
&& [
|
||||
"banned",
|
||||
"forbidden",
|
||||
"blocked",
|
||||
"suspend",
|
||||
"deactivated",
|
||||
"disabled",
|
||||
"verification",
|
||||
"workspace",
|
||||
"受限",
|
||||
"封",
|
||||
"禁",
|
||||
]
|
||||
.iter()
|
||||
.any(|hint| normalized.contains(hint))
|
||||
}
|
||||
|
||||
fn admin_pool_has_proxy(key: &StoredProviderCatalogKey) -> bool {
|
||||
match key.proxy.as_ref() {
|
||||
Some(Value::Object(values)) => !values.is_empty(),
|
||||
Some(Value::String(value)) => !value.trim().is_empty(),
|
||||
Some(Value::Bool(value)) => *value,
|
||||
Some(Value::Number(_)) => true,
|
||||
Some(Value::Array(values)) => !values.is_empty(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn admin_pool_string_list(value: Option<&Value>) -> Option<Vec<String>> {
|
||||
let values = value
|
||||
.and_then(Value::as_array)
|
||||
.map(|items| {
|
||||
items
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.map(ToOwned::to_owned)
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
if values.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(values)
|
||||
}
|
||||
}
|
||||
|
||||
fn admin_pool_json_object(value: Option<&Value>) -> Option<serde_json::Map<String, Value>> {
|
||||
value
|
||||
.and_then(Value::as_object)
|
||||
.cloned()
|
||||
.filter(|value| !value.is_empty())
|
||||
}
|
||||
|
||||
fn admin_pool_health_score(key: &StoredProviderCatalogKey) -> f64 {
|
||||
let scores = key
|
||||
.health_by_format
|
||||
.as_ref()
|
||||
.and_then(Value::as_object)
|
||||
.map(|formats| {
|
||||
formats
|
||||
.values()
|
||||
.filter_map(Value::as_object)
|
||||
.filter_map(|item| item.get("health_score"))
|
||||
.filter_map(Value::as_f64)
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
if scores.is_empty() {
|
||||
1.0
|
||||
} else {
|
||||
scores.into_iter().fold(1.0, f64::min)
|
||||
}
|
||||
}
|
||||
|
||||
fn admin_pool_circuit_breaker_open(key: &StoredProviderCatalogKey) -> bool {
|
||||
key.circuit_breaker_by_format
|
||||
.as_ref()
|
||||
.and_then(Value::as_object)
|
||||
.map(|formats| {
|
||||
formats
|
||||
.values()
|
||||
.filter_map(Value::as_object)
|
||||
.any(|item| item.get("open").and_then(Value::as_bool).unwrap_or(false))
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn unix_secs_to_rfc3339(unix_secs: u64) -> Option<String> {
|
||||
Utc.timestamp_opt(unix_secs as i64, 0)
|
||||
.single()
|
||||
.map(|value| value.to_rfc3339())
|
||||
}
|
||||
|
||||
fn admin_pool_scheduling_payload(
|
||||
key: &StoredProviderCatalogKey,
|
||||
cooldown_reason: Option<&str>,
|
||||
cooldown_ttl_seconds: Option<u64>,
|
||||
health_score: f64,
|
||||
circuit_breaker_open: bool,
|
||||
) -> (String, String, String, Vec<Value>) {
|
||||
if !key.is_active {
|
||||
return (
|
||||
"blocked".to_string(),
|
||||
"inactive".to_string(),
|
||||
"已禁用".to_string(),
|
||||
vec![json!({
|
||||
"code": "inactive",
|
||||
"label": "已禁用",
|
||||
"blocking": true,
|
||||
"source": "manual",
|
||||
"ttl_seconds": Value::Null,
|
||||
"detail": Value::Null,
|
||||
})],
|
||||
);
|
||||
}
|
||||
if let Some(reason) = cooldown_reason {
|
||||
return (
|
||||
"degraded".to_string(),
|
||||
"cooldown".to_string(),
|
||||
"冷却中".to_string(),
|
||||
vec![json!({
|
||||
"code": "cooldown",
|
||||
"label": "冷却中",
|
||||
"blocking": true,
|
||||
"source": "pool",
|
||||
"ttl_seconds": cooldown_ttl_seconds,
|
||||
"detail": reason,
|
||||
})],
|
||||
);
|
||||
}
|
||||
if circuit_breaker_open {
|
||||
return (
|
||||
"degraded".to_string(),
|
||||
"circuit_breaker".to_string(),
|
||||
"熔断中".to_string(),
|
||||
vec![json!({
|
||||
"code": "circuit_breaker",
|
||||
"label": "熔断中",
|
||||
"blocking": true,
|
||||
"source": "health",
|
||||
"ttl_seconds": Value::Null,
|
||||
"detail": Value::Null,
|
||||
})],
|
||||
);
|
||||
}
|
||||
if health_score < 0.5 {
|
||||
return (
|
||||
"degraded".to_string(),
|
||||
"health_low".to_string(),
|
||||
"健康度较低".to_string(),
|
||||
vec![json!({
|
||||
"code": "health_low",
|
||||
"label": "健康度较低",
|
||||
"blocking": false,
|
||||
"source": "health",
|
||||
"ttl_seconds": Value::Null,
|
||||
"detail": Value::Null,
|
||||
})],
|
||||
);
|
||||
}
|
||||
(
|
||||
"available".to_string(),
|
||||
"available".to_string(),
|
||||
"可用".to_string(),
|
||||
Vec::new(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn admin_pool_normalize_text(value: impl AsRef<str>) -> String {
|
||||
value.as_ref().trim().to_ascii_lowercase()
|
||||
}
|
||||
|
||||
pub fn admin_pool_is_oauth_invalid(key: &StoredProviderCatalogKey, now_unix_secs: u64) -> bool {
|
||||
if key.auth_type.trim() != "oauth" {
|
||||
return false;
|
||||
}
|
||||
if key
|
||||
.oauth_invalid_reason
|
||||
.as_deref()
|
||||
.is_some_and(|value| !value.trim().is_empty())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
key.expires_at_unix_secs
|
||||
.is_some_and(|value| value > 0 && value <= now_unix_secs)
|
||||
}
|
||||
|
||||
pub fn admin_pool_matches_quick_selector(
|
||||
key: &StoredProviderCatalogKey,
|
||||
selector: &str,
|
||||
oauth_plan_type: Option<&str>,
|
||||
now_unix_secs: u64,
|
||||
) -> bool {
|
||||
match selector {
|
||||
"banned" => admin_pool_key_is_known_banned(key),
|
||||
"oauth_invalid" => admin_pool_is_oauth_invalid(key, now_unix_secs),
|
||||
"proxy_unset" => !admin_pool_has_proxy(key),
|
||||
"proxy_set" => admin_pool_has_proxy(key),
|
||||
"disabled" => !key.is_active,
|
||||
"enabled" => key.is_active,
|
||||
"plan_free" => oauth_plan_type.is_some_and(|value| value.contains("free")),
|
||||
"plan_team" => oauth_plan_type.is_some_and(|value| value.contains("team")),
|
||||
"no_5h_limit" | "no_weekly_limit" => false,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn admin_pool_matches_search(
|
||||
key: &StoredProviderCatalogKey,
|
||||
search: Option<&str>,
|
||||
oauth_plan_type: Option<&str>,
|
||||
) -> bool {
|
||||
let Some(search) = search else {
|
||||
return true;
|
||||
};
|
||||
let search = admin_pool_normalize_text(search);
|
||||
if search.is_empty() {
|
||||
return true;
|
||||
}
|
||||
|
||||
let mut search_fields = vec![
|
||||
key.id.clone(),
|
||||
key.name.clone(),
|
||||
key.auth_type.clone(),
|
||||
if key.is_active {
|
||||
"已启用".to_string()
|
||||
} else {
|
||||
"已禁用".to_string()
|
||||
},
|
||||
if admin_pool_has_proxy(key) {
|
||||
"独立代理".to_string()
|
||||
} else {
|
||||
"未配置代理".to_string()
|
||||
},
|
||||
];
|
||||
if let Some(reason) = key.oauth_invalid_reason.as_ref() {
|
||||
search_fields.push(reason.clone());
|
||||
}
|
||||
if let Some(note) = key.note.as_ref() {
|
||||
search_fields.push(note.clone());
|
||||
}
|
||||
if let Some(plan_type) = oauth_plan_type {
|
||||
search_fields.push(plan_type.to_string());
|
||||
}
|
||||
|
||||
search_fields
|
||||
.into_iter()
|
||||
.any(|value| admin_pool_normalize_text(&value).contains(&search))
|
||||
}
|
||||
|
||||
pub fn admin_pool_key_is_known_banned(key: &StoredProviderCatalogKey) -> bool {
|
||||
if key
|
||||
.oauth_invalid_reason
|
||||
.as_deref()
|
||||
.is_some_and(admin_pool_reason_indicates_ban)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
let Some(account) = key
|
||||
.status_snapshot
|
||||
.as_ref()
|
||||
.and_then(Value::as_object)
|
||||
.and_then(|snapshot| snapshot.get("account"))
|
||||
.and_then(Value::as_object)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
|
||||
if !account
|
||||
.get("blocked")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
account
|
||||
.get("code")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(admin_pool_reason_indicates_ban)
|
||||
|| account
|
||||
.get("reason")
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(admin_pool_reason_indicates_ban)
|
||||
}
|
||||
|
||||
pub fn admin_pool_sort_keys(keys: &mut [StoredProviderCatalogKey]) {
|
||||
keys.sort_by(|left, right| {
|
||||
left.internal_priority
|
||||
.cmp(&right.internal_priority)
|
||||
.then(left.name.cmp(&right.name))
|
||||
.then(left.id.cmp(&right.id))
|
||||
});
|
||||
}
|
||||
|
||||
pub fn admin_pool_now_unix_secs() -> u64 {
|
||||
Utc::now().timestamp().max(0) as u64
|
||||
}
|
||||
|
||||
pub fn admin_pool_api_formats(key: &StoredProviderCatalogKey) -> Vec<String> {
|
||||
key.api_formats
|
||||
.as_ref()
|
||||
.and_then(Value::as_array)
|
||||
.map(|values| {
|
||||
values
|
||||
.iter()
|
||||
.filter_map(Value::as_str)
|
||||
.map(ToOwned::to_owned)
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn admin_pool_key_proxy_value(proxy_node_id: Option<&str>) -> Option<Value> {
|
||||
proxy_node_id
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(|value| json!({ "node_id": value, "enabled": true }))
|
||||
}
|
||||
|
||||
pub fn build_admin_pool_batch_action_plan(
|
||||
payload: AdminPoolBatchActionRequest,
|
||||
) -> Result<AdminPoolBatchActionPlan, String> {
|
||||
let action = payload.action.trim().to_ascii_lowercase();
|
||||
let (action_kind, action_label) = match action.as_str() {
|
||||
"enable" => (AdminPoolBatchActionKind::Enable, "enabled"),
|
||||
"disable" => (AdminPoolBatchActionKind::Disable, "disabled"),
|
||||
"clear_proxy" => (AdminPoolBatchActionKind::ClearProxy, "proxy cleared"),
|
||||
"set_proxy" => (AdminPoolBatchActionKind::SetProxy, "proxy set"),
|
||||
"regenerate_fingerprint" => (
|
||||
AdminPoolBatchActionKind::RegenerateFingerprint,
|
||||
"fingerprint regenerated",
|
||||
),
|
||||
"delete" => (AdminPoolBatchActionKind::Delete, "deleted"),
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"Invalid action: {action}. Supported locally: enable, disable, clear_proxy, set_proxy, regenerate_fingerprint, delete"
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let key_ids = payload
|
||||
.key_ids
|
||||
.into_iter()
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
.collect::<BTreeSet<_>>()
|
||||
.into_iter()
|
||||
.collect::<Vec<_>>();
|
||||
if key_ids.is_empty() {
|
||||
return Err("key_ids should not be empty".to_string());
|
||||
}
|
||||
|
||||
let proxy_payload = if action_kind == AdminPoolBatchActionKind::SetProxy {
|
||||
match payload.payload {
|
||||
Some(Value::Object(map)) if !map.is_empty() => Some(Value::Object(map)),
|
||||
_ => {
|
||||
return Err(
|
||||
"set_proxy action requires a non-empty payload with proxy config".to_string(),
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Ok(AdminPoolBatchActionPlan {
|
||||
key_ids,
|
||||
action: action_kind,
|
||||
action_label,
|
||||
proxy_payload,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn build_admin_pool_batch_action_result_payload(affected: usize, action_label: &str) -> Value {
|
||||
json!({
|
||||
"affected": affected,
|
||||
"message": format!("{affected} keys {action_label}"),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn admin_pool_resolved_api_formats(
|
||||
endpoints: &[StoredProviderCatalogEndpoint],
|
||||
existing_keys: &[StoredProviderCatalogKey],
|
||||
) -> Vec<String> {
|
||||
let mut formats = Vec::new();
|
||||
let mut seen = BTreeSet::new();
|
||||
for endpoint in endpoints.iter().filter(|endpoint| endpoint.is_active) {
|
||||
let api_format = endpoint.api_format.trim();
|
||||
if api_format.is_empty() || !seen.insert(api_format.to_string()) {
|
||||
continue;
|
||||
}
|
||||
formats.push(api_format.to_string());
|
||||
}
|
||||
if !formats.is_empty() {
|
||||
return formats;
|
||||
}
|
||||
|
||||
for key in existing_keys {
|
||||
for api_format in admin_pool_api_formats(key) {
|
||||
if !seen.insert(api_format.clone()) {
|
||||
continue;
|
||||
}
|
||||
formats.push(api_format);
|
||||
}
|
||||
}
|
||||
formats
|
||||
}
|
||||
|
||||
pub fn admin_pool_sanitize_quick_selectors(selectors: Vec<String>) -> Vec<String> {
|
||||
let mut selectors = selectors
|
||||
.into_iter()
|
||||
.map(admin_pool_normalize_text)
|
||||
.filter(|value| {
|
||||
matches!(
|
||||
value.as_str(),
|
||||
"banned"
|
||||
| "no_5h_limit"
|
||||
| "no_weekly_limit"
|
||||
| "plan_free"
|
||||
| "plan_team"
|
||||
| "oauth_invalid"
|
||||
| "proxy_unset"
|
||||
| "proxy_set"
|
||||
| "disabled"
|
||||
| "enabled"
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
selectors.sort();
|
||||
selectors.dedup();
|
||||
selectors
|
||||
}
|
||||
|
||||
pub fn build_admin_pool_selection_payload(keys: &[StoredProviderCatalogKey]) -> Value {
|
||||
let items = keys
|
||||
.iter()
|
||||
.map(|key| {
|
||||
json!({
|
||||
"key_id": key.id,
|
||||
"key_name": key.name,
|
||||
"auth_type": key.auth_type,
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
json!({
|
||||
"total": items.len(),
|
||||
"items": items,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn build_admin_pool_key_payload(
|
||||
key: &StoredProviderCatalogKey,
|
||||
context: &AdminPoolKeyPayloadContext,
|
||||
) -> Value {
|
||||
let health_score = admin_pool_health_score(key);
|
||||
let circuit_breaker_open = admin_pool_circuit_breaker_open(key);
|
||||
let (scheduling_status, scheduling_reason, scheduling_label, scheduling_reasons) =
|
||||
admin_pool_scheduling_payload(
|
||||
key,
|
||||
context.cooldown_reason.as_deref(),
|
||||
context.cooldown_ttl_seconds,
|
||||
health_score,
|
||||
circuit_breaker_open,
|
||||
);
|
||||
|
||||
json!({
|
||||
"key_id": key.id,
|
||||
"key_name": key.name,
|
||||
"is_active": key.is_active,
|
||||
"auth_type": key.auth_type,
|
||||
"status_snapshot": key.status_snapshot.clone().unwrap_or_else(|| json!({})),
|
||||
"health_score": health_score,
|
||||
"circuit_breaker_open": circuit_breaker_open,
|
||||
"api_formats": admin_pool_api_formats(key),
|
||||
"rate_multipliers": admin_pool_json_object(key.rate_multipliers.as_ref()),
|
||||
"internal_priority": key.internal_priority,
|
||||
"rpm_limit": key.rpm_limit,
|
||||
"cache_ttl_minutes": key.cache_ttl_minutes,
|
||||
"max_probe_interval_minutes": key.max_probe_interval_minutes,
|
||||
"note": key.note,
|
||||
"allowed_models": admin_pool_string_list(key.allowed_models.as_ref()),
|
||||
"capabilities": admin_pool_json_object(key.capabilities.as_ref()),
|
||||
"auto_fetch_models": key.auto_fetch_models,
|
||||
"locked_models": admin_pool_string_list(key.locked_models.as_ref()),
|
||||
"model_include_patterns": admin_pool_string_list(key.model_include_patterns.as_ref()),
|
||||
"model_exclude_patterns": admin_pool_string_list(key.model_exclude_patterns.as_ref()),
|
||||
"proxy": key.proxy.clone(),
|
||||
"fingerprint": key.fingerprint.clone(),
|
||||
"cooldown_reason": context.cooldown_reason,
|
||||
"cooldown_ttl_seconds": context.cooldown_ttl_seconds,
|
||||
"cost_window_usage": context.cost_window_usage,
|
||||
"cost_limit": context.cost_limit,
|
||||
"request_count": key.request_count.unwrap_or(0),
|
||||
"total_tokens": 0,
|
||||
"total_cost_usd": "0.00000000",
|
||||
"sticky_sessions": context.sticky_sessions,
|
||||
"lru_score": context.lru_score,
|
||||
"created_at": key.created_at_unix_secs.and_then(unix_secs_to_rfc3339),
|
||||
"last_used_at": key.last_used_at_unix_secs.and_then(unix_secs_to_rfc3339),
|
||||
"scheduling_status": scheduling_status,
|
||||
"scheduling_reason": scheduling_reason,
|
||||
"scheduling_label": scheduling_label,
|
||||
"scheduling_reasons": scheduling_reasons,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn build_admin_pool_scheduling_presets_payload() -> Value {
|
||||
json!([
|
||||
{
|
||||
"name": "lru",
|
||||
"label": "LRU 轮转",
|
||||
"description": "最久未使用的 Key 优先",
|
||||
"providers": [],
|
||||
"modes": Value::Null,
|
||||
"default_mode": Value::Null,
|
||||
"mutex_group": "distribution_mode",
|
||||
"evidence_hint": "依据 LRU 时间戳(最近未使用优先)",
|
||||
},
|
||||
{
|
||||
"name": "cache_affinity",
|
||||
"label": "缓存亲和",
|
||||
"description": "优先复用最近使用过的 Key,利用 Prompt Caching",
|
||||
"providers": [],
|
||||
"modes": Value::Null,
|
||||
"default_mode": Value::Null,
|
||||
"mutex_group": "distribution_mode",
|
||||
"evidence_hint": "依据 LRU 时间戳(最近使用优先,与 LRU 轮转相反)",
|
||||
},
|
||||
{
|
||||
"name": "cost_first",
|
||||
"label": "成本优先",
|
||||
"description": "优先选择窗口消耗更低的账号",
|
||||
"providers": [],
|
||||
"modes": Value::Null,
|
||||
"default_mode": Value::Null,
|
||||
"mutex_group": Value::Null,
|
||||
"evidence_hint": "依据窗口成本/Token 用量,缺失时回退配额使用率",
|
||||
},
|
||||
{
|
||||
"name": "free_first",
|
||||
"label": "Free 优先",
|
||||
"description": "优先消耗 Free 账号(依赖 plan_type)",
|
||||
"providers": ["codex", "kiro"],
|
||||
"modes": Value::Null,
|
||||
"default_mode": Value::Null,
|
||||
"mutex_group": Value::Null,
|
||||
"evidence_hint": "依据 plan_type(Free 账号优先调度)",
|
||||
},
|
||||
{
|
||||
"name": "health_first",
|
||||
"label": "健康优先",
|
||||
"description": "优先选择健康分更高、失败更少的账号",
|
||||
"providers": [],
|
||||
"modes": Value::Null,
|
||||
"default_mode": Value::Null,
|
||||
"mutex_group": Value::Null,
|
||||
"evidence_hint": "依据 health_by_format 聚合分(含熔断/失败衰减)",
|
||||
},
|
||||
{
|
||||
"name": "latency_first",
|
||||
"label": "延迟优先",
|
||||
"description": "优先选择最近延迟更低的账号",
|
||||
"providers": [],
|
||||
"modes": Value::Null,
|
||||
"default_mode": Value::Null,
|
||||
"mutex_group": Value::Null,
|
||||
"evidence_hint": "依据号池延迟窗口均值(latency_window_seconds)",
|
||||
},
|
||||
{
|
||||
"name": "load_balance",
|
||||
"label": "负载均衡",
|
||||
"description": "随机分散 Key 使用,均匀分摊负载",
|
||||
"providers": [],
|
||||
"modes": Value::Null,
|
||||
"default_mode": Value::Null,
|
||||
"mutex_group": "distribution_mode",
|
||||
"evidence_hint": "每次随机分值,实现完全均匀分散",
|
||||
},
|
||||
{
|
||||
"name": "plus_first",
|
||||
"label": "Plus 优先",
|
||||
"description": "优先消耗 Plus/Pro 账号(依赖 plan_type)",
|
||||
"providers": ["codex", "kiro"],
|
||||
"modes": Value::Null,
|
||||
"default_mode": Value::Null,
|
||||
"mutex_group": Value::Null,
|
||||
"evidence_hint": "依据 plan_type(Plus/Pro 账号优先调度)",
|
||||
},
|
||||
{
|
||||
"name": "priority_first",
|
||||
"label": "优先级优先",
|
||||
"description": "按账号优先级顺序调度(数字越小越优先)",
|
||||
"providers": [],
|
||||
"modes": Value::Null,
|
||||
"default_mode": Value::Null,
|
||||
"mutex_group": Value::Null,
|
||||
"evidence_hint": "依据 internal_priority(支持拖拽/手工编辑)",
|
||||
},
|
||||
{
|
||||
"name": "quota_balanced",
|
||||
"label": "额度平均",
|
||||
"description": "优先选额度消耗最少的账号",
|
||||
"providers": [],
|
||||
"modes": Value::Null,
|
||||
"default_mode": Value::Null,
|
||||
"mutex_group": Value::Null,
|
||||
"evidence_hint": "依据账号配额使用率;无配额时回退到窗口成本使用",
|
||||
},
|
||||
{
|
||||
"name": "recent_refresh",
|
||||
"label": "额度刷新优先",
|
||||
"description": "优先选即将刷新额度的账号",
|
||||
"providers": ["codex", "kiro"],
|
||||
"modes": Value::Null,
|
||||
"default_mode": Value::Null,
|
||||
"mutex_group": Value::Null,
|
||||
"evidence_hint": "依据账号额度重置倒计时(next_reset / reset_seconds)",
|
||||
},
|
||||
{
|
||||
"name": "single_account",
|
||||
"label": "单号优先",
|
||||
"description": "集中使用同一账号(反向 LRU)",
|
||||
"providers": [],
|
||||
"modes": Value::Null,
|
||||
"default_mode": Value::Null,
|
||||
"mutex_group": "distribution_mode",
|
||||
"evidence_hint": "先按账号优先级(internal_priority),同级再按反向 LRU 集中",
|
||||
},
|
||||
{
|
||||
"name": "team_first",
|
||||
"label": "Team 优先",
|
||||
"description": "优先消耗 Team 账号(依赖 plan_type)",
|
||||
"providers": ["codex", "kiro"],
|
||||
"modes": Value::Null,
|
||||
"default_mode": Value::Null,
|
||||
"mutex_group": Value::Null,
|
||||
"evidence_hint": "依据 plan_type(Team 账号优先调度)",
|
||||
}
|
||||
])
|
||||
}
|
||||
|
||||
pub fn admin_pool_batch_delete_task_parts(request_path: &str) -> Option<(String, String)> {
|
||||
let raw = request_path.strip_prefix("/api/admin/pool/")?;
|
||||
let (provider_id, suffix) = raw.split_once("/keys/batch-delete-task/")?;
|
||||
let provider_id = provider_id.trim();
|
||||
let task_id = suffix.trim().trim_matches('/');
|
||||
if provider_id.is_empty()
|
||||
|| provider_id.contains('/')
|
||||
|| task_id.is_empty()
|
||||
|| task_id.contains('/')
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some((provider_id.to_string(), task_id.to_string()))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn build_admin_pool_batch_delete_task_payload(
|
||||
task_id: &str,
|
||||
provider_id: &str,
|
||||
status: &str,
|
||||
stage: &str,
|
||||
total_keys: usize,
|
||||
deleted_keys: usize,
|
||||
total_endpoints: usize,
|
||||
deleted_endpoints: usize,
|
||||
message: &str,
|
||||
) -> Value {
|
||||
json!({
|
||||
"task_id": task_id,
|
||||
"provider_id": provider_id,
|
||||
"status": status,
|
||||
"stage": stage,
|
||||
"total_keys": total_keys,
|
||||
"deleted_keys": deleted_keys,
|
||||
"total_endpoints": total_endpoints,
|
||||
"deleted_endpoints": deleted_endpoints,
|
||||
"message": message,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn build_admin_pool_overview_payload(
|
||||
providers: &[StoredProviderCatalogProvider],
|
||||
key_stats_by_provider: &BTreeMap<String, StoredProviderCatalogKeyStats>,
|
||||
cooldown_counts_by_provider: &BTreeMap<String, usize>,
|
||||
) -> Value {
|
||||
let items = providers
|
||||
.iter()
|
||||
.map(|provider| {
|
||||
let stats = key_stats_by_provider.get(&provider.id);
|
||||
let total_keys = stats.map(|item| item.total_keys as usize).unwrap_or(0);
|
||||
let active_keys = stats.map(|item| item.active_keys as usize).unwrap_or(0);
|
||||
let cooldown_count = cooldown_counts_by_provider
|
||||
.get(&provider.id)
|
||||
.copied()
|
||||
.unwrap_or(0);
|
||||
json!({
|
||||
"provider_id": provider.id,
|
||||
"provider_name": provider.name,
|
||||
"provider_type": provider.provider_type,
|
||||
"total_keys": total_keys,
|
||||
"active_keys": active_keys,
|
||||
"cooldown_count": cooldown_count,
|
||||
"pool_enabled": true,
|
||||
})
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
json!({ "items": items })
|
||||
}
|
||||
|
||||
pub fn build_admin_pool_batch_import_key_record(
|
||||
id: String,
|
||||
provider_id: String,
|
||||
name: String,
|
||||
auth_type: String,
|
||||
api_formats: Vec<String>,
|
||||
encrypted_api_key: String,
|
||||
proxy: Option<Value>,
|
||||
now_unix_secs: u64,
|
||||
) -> Result<StoredProviderCatalogKey, String> {
|
||||
let mut record = StoredProviderCatalogKey::new(id, provider_id, name, auth_type, None, true)
|
||||
.map_err(|err| err.to_string())?;
|
||||
record = record
|
||||
.with_transport_fields(
|
||||
Some(json!(api_formats)),
|
||||
encrypted_api_key,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
proxy,
|
||||
None,
|
||||
)
|
||||
.map_err(|err| err.to_string())?;
|
||||
record.request_count = Some(0);
|
||||
record.success_count = Some(0);
|
||||
record.error_count = Some(0);
|
||||
record.total_response_time_ms = Some(0);
|
||||
record.health_by_format = Some(json!({}));
|
||||
record.circuit_breaker_by_format = Some(json!({}));
|
||||
record.created_at_unix_secs = Some(now_unix_secs);
|
||||
record.updated_at_unix_secs = Some(now_unix_secs);
|
||||
Ok(record)
|
||||
}
|
||||
|
||||
pub fn build_admin_pool_batch_import_result_payload(
|
||||
imported: usize,
|
||||
skipped: usize,
|
||||
errors: Vec<Value>,
|
||||
) -> Value {
|
||||
json!({
|
||||
"imported": imported,
|
||||
"skipped": skipped,
|
||||
"errors": errors,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn build_admin_pool_cleanup_empty_payload(message: &str) -> Value {
|
||||
json!({
|
||||
"affected": 0,
|
||||
"message": message,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn build_admin_pool_cleanup_result_payload(affected: usize) -> Value {
|
||||
json!({
|
||||
"affected": affected,
|
||||
"message": format!("已清理 {affected} 个异常账号"),
|
||||
})
|
||||
}
|
||||
639
crates/aether-admin/src/provider/quota.rs
Normal file
639
crates/aether-admin/src/provider/quota.rs
Normal file
@@ -0,0 +1,639 @@
|
||||
use aether_contracts::ExecutionResult;
|
||||
use aether_data_contracts::repository::provider_catalog::StoredProviderCatalogKey;
|
||||
use serde_json::json;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
const OAUTH_ACCOUNT_BLOCK_PREFIX: &str = "[ACCOUNT_BLOCK] ";
|
||||
const OAUTH_REFRESH_FAILED_PREFIX: &str = "[REFRESH_FAILED] ";
|
||||
const OAUTH_EXPIRED_PREFIX: &str = "[OAUTH_EXPIRED] ";
|
||||
const OAUTH_REQUEST_FAILED_PREFIX: &str = "[REQUEST_FAILED] ";
|
||||
|
||||
pub fn provider_auto_remove_banned_keys(config: Option<&serde_json::Value>) -> bool {
|
||||
config
|
||||
.and_then(|value| value.get("pool_advanced"))
|
||||
.and_then(serde_json::Value::as_object)
|
||||
.and_then(|object| object.get("auto_remove_banned_keys"))
|
||||
.and_then(serde_json::Value::as_bool)
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
pub fn should_auto_remove_structured_reason(reason: Option<&str>) -> bool {
|
||||
reason
|
||||
.map(str::trim)
|
||||
.is_some_and(|value| value.starts_with(OAUTH_ACCOUNT_BLOCK_PREFIX))
|
||||
}
|
||||
|
||||
pub fn normalize_string_id_list(values: Option<Vec<String>>) -> Option<Vec<String>> {
|
||||
let mut out = Vec::new();
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
for value in values.into_iter().flatten() {
|
||||
let trimmed = value.trim();
|
||||
if trimmed.is_empty() || !seen.insert(trimmed.to_string()) {
|
||||
continue;
|
||||
}
|
||||
out.push(trimmed.to_string());
|
||||
}
|
||||
(!out.is_empty()).then_some(out)
|
||||
}
|
||||
|
||||
pub fn coerce_json_u64(value: &serde_json::Value) -> Option<u64> {
|
||||
match value {
|
||||
serde_json::Value::Number(number) => number.as_u64(),
|
||||
serde_json::Value::String(text) => text.trim().parse::<u64>().ok(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn coerce_json_f64(value: &serde_json::Value) -> Option<f64> {
|
||||
match value {
|
||||
serde_json::Value::Number(number) => number.as_f64(),
|
||||
serde_json::Value::String(text) => text.trim().parse::<f64>().ok(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn coerce_json_bool(value: &serde_json::Value) -> Option<bool> {
|
||||
match value {
|
||||
serde_json::Value::Bool(value) => Some(*value),
|
||||
serde_json::Value::String(text) => match text.trim().to_ascii_lowercase().as_str() {
|
||||
"true" | "1" => Some(true),
|
||||
"false" | "0" => Some(false),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn coerce_json_string(value: Option<&serde_json::Value>) -> Option<String> {
|
||||
value
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
}
|
||||
|
||||
pub fn extract_execution_error_message(result: &ExecutionResult) -> Option<String> {
|
||||
if let Some(body_json) = result
|
||||
.body
|
||||
.as_ref()
|
||||
.and_then(|body| body.json_body.as_ref())
|
||||
.and_then(serde_json::Value::as_object)
|
||||
{
|
||||
if let Some(error) = body_json
|
||||
.get("error")
|
||||
.and_then(serde_json::Value::as_object)
|
||||
{
|
||||
if let Some(message) = error.get("message").and_then(serde_json::Value::as_str) {
|
||||
let trimmed = message.trim();
|
||||
if !trimmed.is_empty() {
|
||||
return Some(trimmed.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(message) = body_json.get("message").and_then(serde_json::Value::as_str) {
|
||||
let trimmed = message.trim();
|
||||
if !trimmed.is_empty() {
|
||||
return Some(trimmed.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
result
|
||||
.error
|
||||
.as_ref()
|
||||
.map(|error| error.message.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
}
|
||||
|
||||
pub fn quota_refresh_success_invalid_state(
|
||||
key: &StoredProviderCatalogKey,
|
||||
) -> (Option<u64>, Option<String>) {
|
||||
let current_reason = key
|
||||
.oauth_invalid_reason
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.unwrap_or_default();
|
||||
if current_reason.starts_with(OAUTH_REFRESH_FAILED_PREFIX) {
|
||||
return (
|
||||
key.oauth_invalid_at_unix_secs,
|
||||
(!current_reason.is_empty()).then_some(current_reason.to_string()),
|
||||
);
|
||||
}
|
||||
(None, None)
|
||||
}
|
||||
|
||||
pub fn parse_antigravity_usage_response(
|
||||
value: &serde_json::Value,
|
||||
updated_at_unix_secs: u64,
|
||||
) -> Option<serde_json::Value> {
|
||||
let models = value.get("models")?.as_object()?;
|
||||
let mut quota_by_model = serde_json::Map::new();
|
||||
|
||||
for (model_id, model_value) in models {
|
||||
let mut payload = serde_json::Map::new();
|
||||
if let Some(display_name) = coerce_json_string(
|
||||
model_value
|
||||
.get("displayName")
|
||||
.or_else(|| model_value.get("display_name")),
|
||||
) {
|
||||
payload.insert("display_name".to_string(), json!(display_name));
|
||||
}
|
||||
|
||||
let quota_info = model_value
|
||||
.get("quotaInfo")
|
||||
.and_then(serde_json::Value::as_object);
|
||||
let remaining_fraction = quota_info
|
||||
.and_then(|object| object.get("remainingFraction"))
|
||||
.and_then(coerce_json_f64);
|
||||
let used_percent = remaining_fraction
|
||||
.map(|value| ((1.0 - value).max(0.0) * 100.0).min(100.0))
|
||||
.unwrap_or(100.0);
|
||||
payload.insert(
|
||||
"remaining_fraction".to_string(),
|
||||
json!(remaining_fraction.unwrap_or(0.0)),
|
||||
);
|
||||
payload.insert("used_percent".to_string(), json!(used_percent));
|
||||
if let Some(reset_time) = quota_info
|
||||
.and_then(|object| object.get("resetTime"))
|
||||
.cloned()
|
||||
.filter(|value| !value.is_null())
|
||||
{
|
||||
payload.insert("reset_time".to_string(), reset_time);
|
||||
}
|
||||
quota_by_model.insert(model_id.clone(), serde_json::Value::Object(payload));
|
||||
}
|
||||
|
||||
Some(json!({
|
||||
"updated_at": updated_at_unix_secs,
|
||||
"is_forbidden": false,
|
||||
"forbidden_reason": serde_json::Value::Null,
|
||||
"forbidden_at": serde_json::Value::Null,
|
||||
"models": quota_by_model,
|
||||
}))
|
||||
}
|
||||
|
||||
pub fn normalize_codex_plan_type(value: Option<&str>) -> Option<String> {
|
||||
value
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(|value| value.to_ascii_lowercase())
|
||||
}
|
||||
|
||||
pub fn build_codex_quota_exhausted_fallback_metadata(
|
||||
plan_type: Option<&str>,
|
||||
updated_at_unix_secs: u64,
|
||||
) -> serde_json::Value {
|
||||
let mut object = serde_json::Map::new();
|
||||
if let Some(plan_type) = normalize_codex_plan_type(plan_type) {
|
||||
object.insert(
|
||||
"plan_type".to_string(),
|
||||
serde_json::Value::String(plan_type),
|
||||
);
|
||||
}
|
||||
object.insert("updated_at".to_string(), json!(updated_at_unix_secs));
|
||||
object.insert("primary_used_percent".to_string(), json!(100.0));
|
||||
if normalize_codex_plan_type(plan_type) != Some("free".to_string()) {
|
||||
object.insert("secondary_used_percent".to_string(), json!(100.0));
|
||||
}
|
||||
serde_json::Value::Object(object)
|
||||
}
|
||||
|
||||
fn codex_write_window(
|
||||
target: &mut serde_json::Map<String, serde_json::Value>,
|
||||
source: &serde_json::Map<String, serde_json::Value>,
|
||||
target_prefix: &str,
|
||||
) {
|
||||
if let Some(value) = source.get("used_percent").and_then(coerce_json_f64) {
|
||||
target.insert(format!("{target_prefix}_used_percent"), json!(value));
|
||||
}
|
||||
if let Some(value) = source.get("reset_after_seconds").and_then(coerce_json_u64) {
|
||||
target.insert(format!("{target_prefix}_reset_after_seconds"), json!(value));
|
||||
}
|
||||
if let Some(value) = source.get("reset_at").and_then(coerce_json_u64) {
|
||||
target.insert(format!("{target_prefix}_reset_at"), json!(value));
|
||||
}
|
||||
if let Some(value) = source.get("window_minutes").and_then(coerce_json_u64) {
|
||||
target.insert(format!("{target_prefix}_window_minutes"), json!(value));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_codex_wham_usage_response(
|
||||
value: &serde_json::Value,
|
||||
updated_at_unix_secs: u64,
|
||||
) -> Option<serde_json::Value> {
|
||||
let root = value.as_object()?;
|
||||
if root.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut result = serde_json::Map::new();
|
||||
let plan_type =
|
||||
normalize_codex_plan_type(root.get("plan_type").and_then(serde_json::Value::as_str));
|
||||
if let Some(plan_type) = plan_type.as_ref() {
|
||||
result.insert("plan_type".to_string(), json!(plan_type));
|
||||
}
|
||||
|
||||
let rate_limit = root
|
||||
.get("rate_limit")
|
||||
.and_then(serde_json::Value::as_object)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let primary_window = rate_limit
|
||||
.get("primary_window")
|
||||
.and_then(serde_json::Value::as_object)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let secondary_window = rate_limit
|
||||
.get("secondary_window")
|
||||
.and_then(serde_json::Value::as_object)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
|
||||
let use_paid_windows = !secondary_window.is_empty() && plan_type.as_deref() != Some("free");
|
||||
if use_paid_windows {
|
||||
codex_write_window(&mut result, &secondary_window, "primary");
|
||||
codex_write_window(&mut result, &primary_window, "secondary");
|
||||
} else {
|
||||
codex_write_window(&mut result, &primary_window, "primary");
|
||||
}
|
||||
|
||||
if let Some(credits) = root.get("credits").and_then(serde_json::Value::as_object) {
|
||||
if let Some(value) = credits.get("has_credits").and_then(coerce_json_bool) {
|
||||
result.insert("has_credits".to_string(), json!(value));
|
||||
}
|
||||
if let Some(value) = credits.get("balance").and_then(coerce_json_f64) {
|
||||
result.insert("credits_balance".to_string(), json!(value));
|
||||
}
|
||||
if let Some(value) = credits.get("unlimited").and_then(coerce_json_bool) {
|
||||
result.insert("credits_unlimited".to_string(), json!(value));
|
||||
}
|
||||
}
|
||||
|
||||
if result.is_empty() {
|
||||
return None;
|
||||
}
|
||||
result.insert("updated_at".to_string(), json!(updated_at_unix_secs));
|
||||
Some(serde_json::Value::Object(result))
|
||||
}
|
||||
|
||||
pub fn parse_codex_usage_headers(
|
||||
headers: &BTreeMap<String, String>,
|
||||
updated_at_unix_secs: u64,
|
||||
) -> Option<serde_json::Value> {
|
||||
let mut result = serde_json::Map::new();
|
||||
let normalized = headers
|
||||
.iter()
|
||||
.map(|(key, value)| (key.trim().to_ascii_lowercase(), value.trim().to_string()))
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
if !normalized.keys().any(|key| key.starts_with("x-codex-")) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let plan_type =
|
||||
normalize_codex_plan_type(normalized.get("x-codex-plan-type").map(String::as_str));
|
||||
if let Some(plan_type) = plan_type.as_ref() {
|
||||
result.insert("plan_type".to_string(), json!(plan_type));
|
||||
}
|
||||
|
||||
let read_window = |prefix: &str| -> serde_json::Map<String, serde_json::Value> {
|
||||
let mut object = serde_json::Map::new();
|
||||
let used_key = format!("x-codex-{prefix}-used-percent");
|
||||
let reset_after_key = format!("x-codex-{prefix}-reset-after-seconds");
|
||||
let reset_at_key = format!("x-codex-{prefix}-reset-at");
|
||||
let window_minutes_key = format!("x-codex-{prefix}-window-minutes");
|
||||
if let Some(value) = normalized
|
||||
.get(&used_key)
|
||||
.and_then(|value| value.parse::<f64>().ok())
|
||||
{
|
||||
object.insert("used_percent".to_string(), json!(value));
|
||||
}
|
||||
if let Some(value) = normalized
|
||||
.get(&reset_after_key)
|
||||
.and_then(|value| value.parse::<u64>().ok())
|
||||
{
|
||||
object.insert("reset_after_seconds".to_string(), json!(value));
|
||||
}
|
||||
if let Some(value) = normalized
|
||||
.get(&reset_at_key)
|
||||
.and_then(|value| value.parse::<u64>().ok())
|
||||
{
|
||||
object.insert("reset_at".to_string(), json!(value));
|
||||
}
|
||||
if let Some(value) = normalized
|
||||
.get(&window_minutes_key)
|
||||
.and_then(|value| value.parse::<u64>().ok())
|
||||
{
|
||||
object.insert("window_minutes".to_string(), json!(value));
|
||||
}
|
||||
object
|
||||
};
|
||||
|
||||
let primary_window = read_window("primary");
|
||||
let secondary_window = read_window("secondary");
|
||||
let use_paid_windows = !secondary_window.is_empty() && plan_type.as_deref() != Some("free");
|
||||
if use_paid_windows {
|
||||
codex_write_window(&mut result, &secondary_window, "primary");
|
||||
codex_write_window(&mut result, &primary_window, "secondary");
|
||||
} else {
|
||||
codex_write_window(&mut result, &primary_window, "primary");
|
||||
}
|
||||
|
||||
if let Some(value) = normalized
|
||||
.get("x-codex-primary-over-secondary-limit-percent")
|
||||
.and_then(|value| value.parse::<f64>().ok())
|
||||
{
|
||||
result.insert(
|
||||
"primary_over_secondary_limit_percent".to_string(),
|
||||
json!(value),
|
||||
);
|
||||
}
|
||||
if let Some(value) = normalized
|
||||
.get("x-codex-credits-has-credits")
|
||||
.and_then(|value| match value.to_ascii_lowercase().as_str() {
|
||||
"true" | "1" => Some(true),
|
||||
"false" | "0" => Some(false),
|
||||
_ => None,
|
||||
})
|
||||
{
|
||||
result.insert("has_credits".to_string(), json!(value));
|
||||
}
|
||||
if let Some(value) = normalized
|
||||
.get("x-codex-credits-balance")
|
||||
.and_then(|value| value.parse::<f64>().ok())
|
||||
{
|
||||
result.insert("credits_balance".to_string(), json!(value));
|
||||
}
|
||||
if let Some(value) = normalized
|
||||
.get("x-codex-credits-unlimited")
|
||||
.and_then(|value| match value.to_ascii_lowercase().as_str() {
|
||||
"true" | "1" => Some(true),
|
||||
"false" | "0" => Some(false),
|
||||
_ => None,
|
||||
})
|
||||
{
|
||||
result.insert("credits_unlimited".to_string(), json!(value));
|
||||
}
|
||||
|
||||
if result.is_empty() {
|
||||
return None;
|
||||
}
|
||||
result.insert("updated_at".to_string(), json!(updated_at_unix_secs));
|
||||
Some(serde_json::Value::Object(result))
|
||||
}
|
||||
|
||||
fn codex_current_invalid_reason(key: &StoredProviderCatalogKey) -> String {
|
||||
key.oauth_invalid_reason
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.unwrap_or_default()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
fn codex_merge_invalid_reason(current: &str, candidate_reason: &str) -> String {
|
||||
if current.is_empty() {
|
||||
return candidate_reason.to_string();
|
||||
}
|
||||
if current.starts_with(OAUTH_ACCOUNT_BLOCK_PREFIX) {
|
||||
return current.to_string();
|
||||
}
|
||||
if current.starts_with(OAUTH_EXPIRED_PREFIX)
|
||||
&& candidate_reason.starts_with(OAUTH_REQUEST_FAILED_PREFIX)
|
||||
{
|
||||
return current.to_string();
|
||||
}
|
||||
candidate_reason.to_string()
|
||||
}
|
||||
|
||||
pub fn codex_build_invalid_state(
|
||||
key: &StoredProviderCatalogKey,
|
||||
candidate_reason: String,
|
||||
now_unix_secs: u64,
|
||||
) -> (Option<u64>, Option<String>) {
|
||||
let current_reason = codex_current_invalid_reason(key);
|
||||
let merged_reason = codex_merge_invalid_reason(¤t_reason, &candidate_reason);
|
||||
if merged_reason == current_reason {
|
||||
return (key.oauth_invalid_at_unix_secs, Some(merged_reason));
|
||||
}
|
||||
(Some(now_unix_secs), Some(merged_reason))
|
||||
}
|
||||
|
||||
pub fn codex_looks_like_token_invalidated(message: Option<&str>) -> bool {
|
||||
let lowered = message.unwrap_or_default().trim().to_ascii_lowercase();
|
||||
lowered.contains("token invalid")
|
||||
|| lowered.contains("token invalidated")
|
||||
|| lowered.contains("session has expired")
|
||||
|| lowered.contains("session expired")
|
||||
}
|
||||
|
||||
fn codex_looks_like_account_deactivated(message: Option<&str>) -> bool {
|
||||
let lowered = message.unwrap_or_default().trim().to_ascii_lowercase();
|
||||
lowered.contains("account has been deactivated") || lowered.contains("account deactivated")
|
||||
}
|
||||
|
||||
pub fn codex_looks_like_workspace_deactivated(message: Option<&str>) -> bool {
|
||||
let lowered = message.unwrap_or_default().trim().to_ascii_lowercase();
|
||||
lowered.contains("deactivated_workspace")
|
||||
|| (lowered.contains("workspace") && lowered.contains("deactivated"))
|
||||
}
|
||||
|
||||
pub fn codex_structured_invalid_reason(status_code: u16, upstream_message: Option<&str>) -> String {
|
||||
let message = upstream_message.unwrap_or_default().trim();
|
||||
if status_code == 402 && codex_looks_like_workspace_deactivated(Some(message)) {
|
||||
return format!("{OAUTH_ACCOUNT_BLOCK_PREFIX}工作区已停用 (deactivated_workspace)");
|
||||
}
|
||||
if codex_looks_like_account_deactivated(Some(message)) {
|
||||
let detail = if message.is_empty() {
|
||||
"OpenAI 账号已停用"
|
||||
} else {
|
||||
message
|
||||
};
|
||||
return format!("{OAUTH_ACCOUNT_BLOCK_PREFIX}{detail}");
|
||||
}
|
||||
if codex_looks_like_token_invalidated(Some(message)) {
|
||||
let detail = if message.is_empty() {
|
||||
"Codex Token 无效或已过期"
|
||||
} else {
|
||||
message
|
||||
};
|
||||
return format!("{OAUTH_EXPIRED_PREFIX}{detail}");
|
||||
}
|
||||
if status_code == 401 {
|
||||
let detail = if message.is_empty() {
|
||||
"Codex Token 无效或已过期 (401)"
|
||||
} else {
|
||||
message
|
||||
};
|
||||
return format!("{OAUTH_EXPIRED_PREFIX}{detail}");
|
||||
}
|
||||
if status_code == 403 {
|
||||
let detail = if message.is_empty() {
|
||||
"Codex 账户访问受限 (403)"
|
||||
} else {
|
||||
message
|
||||
};
|
||||
return format!("{OAUTH_ACCOUNT_BLOCK_PREFIX}{detail}");
|
||||
}
|
||||
message.to_string()
|
||||
}
|
||||
|
||||
pub fn codex_soft_request_failure_reason(
|
||||
status_code: u16,
|
||||
upstream_message: Option<&str>,
|
||||
) -> String {
|
||||
let detail = upstream_message
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
.unwrap_or_else(|| format!("Codex 请求失败 ({status_code})"));
|
||||
format!("{OAUTH_REQUEST_FAILED_PREFIX}{detail}")
|
||||
}
|
||||
|
||||
fn compute_kiro_total_usage_limit(breakdown: &serde_json::Value) -> f64 {
|
||||
let mut total = breakdown
|
||||
.get("usageLimitWithPrecision")
|
||||
.and_then(coerce_json_f64)
|
||||
.unwrap_or(0.0);
|
||||
|
||||
if breakdown
|
||||
.get("freeTrialInfo")
|
||||
.and_then(serde_json::Value::as_object)
|
||||
.is_some_and(|free_trial| {
|
||||
free_trial
|
||||
.get("freeTrialStatus")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map(str::trim)
|
||||
.is_some_and(|value| value.eq_ignore_ascii_case("ACTIVE"))
|
||||
})
|
||||
{
|
||||
total += breakdown
|
||||
.get("freeTrialInfo")
|
||||
.and_then(|value| value.get("usageLimitWithPrecision"))
|
||||
.and_then(coerce_json_f64)
|
||||
.unwrap_or(0.0);
|
||||
}
|
||||
|
||||
if let Some(bonuses) = breakdown
|
||||
.get("bonuses")
|
||||
.and_then(serde_json::Value::as_array)
|
||||
{
|
||||
for bonus in bonuses {
|
||||
let is_active = bonus
|
||||
.get("status")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map(str::trim)
|
||||
.is_some_and(|value| value.eq_ignore_ascii_case("ACTIVE"));
|
||||
if is_active {
|
||||
total += bonus
|
||||
.get("usageLimit")
|
||||
.and_then(coerce_json_f64)
|
||||
.unwrap_or(0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
total
|
||||
}
|
||||
|
||||
fn compute_kiro_current_usage(breakdown: &serde_json::Value) -> f64 {
|
||||
let mut total = breakdown
|
||||
.get("currentUsageWithPrecision")
|
||||
.and_then(coerce_json_f64)
|
||||
.unwrap_or(0.0);
|
||||
|
||||
if breakdown
|
||||
.get("freeTrialInfo")
|
||||
.and_then(serde_json::Value::as_object)
|
||||
.is_some_and(|free_trial| {
|
||||
free_trial
|
||||
.get("freeTrialStatus")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map(str::trim)
|
||||
.is_some_and(|value| value.eq_ignore_ascii_case("ACTIVE"))
|
||||
})
|
||||
{
|
||||
total += breakdown
|
||||
.get("freeTrialInfo")
|
||||
.and_then(|value| value.get("currentUsageWithPrecision"))
|
||||
.and_then(coerce_json_f64)
|
||||
.unwrap_or(0.0);
|
||||
}
|
||||
|
||||
if let Some(bonuses) = breakdown
|
||||
.get("bonuses")
|
||||
.and_then(serde_json::Value::as_array)
|
||||
{
|
||||
for bonus in bonuses {
|
||||
let is_active = bonus
|
||||
.get("status")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map(str::trim)
|
||||
.is_some_and(|value| value.eq_ignore_ascii_case("ACTIVE"));
|
||||
if is_active {
|
||||
total += bonus
|
||||
.get("currentUsage")
|
||||
.and_then(coerce_json_f64)
|
||||
.unwrap_or(0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
total
|
||||
}
|
||||
|
||||
pub fn parse_kiro_usage_response(
|
||||
value: &serde_json::Value,
|
||||
updated_at_unix_secs: u64,
|
||||
) -> Option<serde_json::Value> {
|
||||
let root = value.as_object()?;
|
||||
let breakdown = root
|
||||
.get("usageBreakdownList")
|
||||
.and_then(serde_json::Value::as_array)
|
||||
.and_then(|items| items.first())?;
|
||||
|
||||
let usage_limit = compute_kiro_total_usage_limit(breakdown);
|
||||
let current_usage = compute_kiro_current_usage(breakdown);
|
||||
let remaining = (usage_limit - current_usage).max(0.0);
|
||||
let usage_percentage = if usage_limit > 0.0 {
|
||||
((current_usage / usage_limit) * 100.0).min(100.0)
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
|
||||
let mut result = serde_json::Map::new();
|
||||
result.insert("current_usage".to_string(), json!(current_usage));
|
||||
result.insert("usage_limit".to_string(), json!(usage_limit));
|
||||
result.insert("remaining".to_string(), json!(remaining));
|
||||
result.insert("usage_percentage".to_string(), json!(usage_percentage));
|
||||
result.insert("updated_at".to_string(), json!(updated_at_unix_secs));
|
||||
|
||||
if let Some(subscription_title) = root
|
||||
.get("subscriptionInfo")
|
||||
.and_then(|value| value.get("subscriptionTitle"))
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
{
|
||||
result.insert("subscription_title".to_string(), json!(subscription_title));
|
||||
}
|
||||
|
||||
if let Some(next_reset_at) = root
|
||||
.get("nextDateReset")
|
||||
.and_then(coerce_json_f64)
|
||||
.or_else(|| breakdown.get("nextDateReset").and_then(coerce_json_f64))
|
||||
{
|
||||
result.insert("next_reset_at".to_string(), json!(next_reset_at));
|
||||
}
|
||||
|
||||
let email = root
|
||||
.get("desktopUserInfo")
|
||||
.and_then(|value| value.get("email"))
|
||||
.or_else(|| root.get("userInfo").and_then(|value| value.get("email")))
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty());
|
||||
if let Some(email) = email {
|
||||
result.insert("email".to_string(), json!(email));
|
||||
}
|
||||
|
||||
Some(serde_json::Value::Object(result))
|
||||
}
|
||||
309
crates/aether-admin/src/provider/state.rs
Normal file
309
crates/aether-admin/src/provider/state.rs
Normal file
@@ -0,0 +1,309 @@
|
||||
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
|
||||
use serde_json::{json, Map, Value};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::BTreeMap;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
use url::{form_urlencoded, Url};
|
||||
use uuid::Uuid;
|
||||
|
||||
const KIRO_DEVICE_DEFAULT_START_URL: &str = "https://view.awsapps.com/start";
|
||||
const KIRO_DEVICE_DEFAULT_REGION: &str = "us-east-1";
|
||||
|
||||
pub fn current_unix_secs() -> u64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.ok()
|
||||
.map(|duration| duration.as_secs())
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
pub fn generate_provider_oauth_nonce() -> String {
|
||||
format!("{}{}", Uuid::new_v4().simple(), Uuid::new_v4().simple())
|
||||
}
|
||||
|
||||
pub fn generate_provider_oauth_pkce_verifier() -> String {
|
||||
format!(
|
||||
"{}{}{}",
|
||||
Uuid::new_v4().simple(),
|
||||
Uuid::new_v4().simple(),
|
||||
Uuid::new_v4().simple()
|
||||
)
|
||||
}
|
||||
|
||||
pub fn provider_oauth_pkce_s256(verifier: &str) -> String {
|
||||
let digest = Sha256::digest(verifier.as_bytes());
|
||||
URL_SAFE_NO_PAD.encode(digest)
|
||||
}
|
||||
|
||||
pub fn parse_provider_oauth_callback_params(callback_url: &str) -> BTreeMap<String, String> {
|
||||
let mut merged = BTreeMap::new();
|
||||
let Ok(url) = Url::parse(callback_url.trim()) else {
|
||||
return merged;
|
||||
};
|
||||
for (key, value) in url.query_pairs() {
|
||||
merged.insert(key.into_owned(), value.into_owned());
|
||||
}
|
||||
if let Some(fragment) = url.fragment() {
|
||||
for (key, value) in form_urlencoded::parse(fragment.as_bytes()) {
|
||||
merged
|
||||
.entry(key.into_owned())
|
||||
.or_insert_with(|| value.into_owned());
|
||||
}
|
||||
}
|
||||
if let Some(code) = merged.get("code").cloned() {
|
||||
if let Some((code_part, state_part)) = code.split_once("#state=") {
|
||||
merged.insert("code".to_string(), code_part.to_string());
|
||||
merged
|
||||
.entry("state".to_string())
|
||||
.or_insert_with(|| state_part.to_string());
|
||||
}
|
||||
}
|
||||
merged
|
||||
}
|
||||
|
||||
pub fn json_non_empty_string(value: Option<&Value>) -> Option<String> {
|
||||
value
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(ToOwned::to_owned)
|
||||
}
|
||||
|
||||
pub fn json_u64_value(value: Option<&Value>) -> Option<u64> {
|
||||
match value? {
|
||||
Value::Number(number) => number.as_u64(),
|
||||
Value::String(value) => value.trim().parse::<u64>().ok(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn decode_jwt_claims(token: &str) -> Option<Map<String, Value>> {
|
||||
let payload = token.split('.').nth(1)?;
|
||||
let bytes = URL_SAFE_NO_PAD.decode(payload.as_bytes()).ok()?;
|
||||
serde_json::from_slice::<Value>(&bytes)
|
||||
.ok()?
|
||||
.as_object()
|
||||
.cloned()
|
||||
}
|
||||
|
||||
fn merge_missing_auth_config_fields(
|
||||
auth_config: &mut Map<String, Value>,
|
||||
source: &Map<String, Value>,
|
||||
fields: &[&str],
|
||||
) {
|
||||
for field in fields {
|
||||
if auth_config.contains_key(*field) {
|
||||
continue;
|
||||
}
|
||||
if let Some(value) = source.get(*field).cloned() {
|
||||
auth_config.insert((*field).to_string(), value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn first_json_non_empty_string(values: impl IntoIterator<Item = Option<Value>>) -> Option<String> {
|
||||
values.into_iter().find_map(|value| match value {
|
||||
Some(Value::String(value)) => {
|
||||
let normalized = value.trim();
|
||||
(!normalized.is_empty()).then(|| normalized.to_string())
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
|
||||
fn extract_codex_auth_fields_from_object(source: &Map<String, Value>) -> Map<String, Value> {
|
||||
let auth = source
|
||||
.get("https://api.openai.com/auth")
|
||||
.and_then(Value::as_object);
|
||||
let mut result = Map::new();
|
||||
|
||||
if let Some(email) = first_json_non_empty_string([
|
||||
source.get("email").cloned(),
|
||||
auth.and_then(|value| value.get("email")).cloned(),
|
||||
]) {
|
||||
result.insert("email".to_string(), json!(email));
|
||||
}
|
||||
|
||||
if let Some(account_id) = first_json_non_empty_string([
|
||||
auth.and_then(|value| value.get("chatgpt_account_id"))
|
||||
.cloned(),
|
||||
auth.and_then(|value| value.get("chatgptAccountId"))
|
||||
.cloned(),
|
||||
auth.and_then(|value| value.get("account_id")).cloned(),
|
||||
auth.and_then(|value| value.get("accountId")).cloned(),
|
||||
source.get("chatgpt_account_id").cloned(),
|
||||
source.get("chatgptAccountId").cloned(),
|
||||
source.get("account_id").cloned(),
|
||||
source.get("accountId").cloned(),
|
||||
]) {
|
||||
result.insert("account_id".to_string(), json!(account_id));
|
||||
}
|
||||
|
||||
if let Some(account_user_id) = first_json_non_empty_string([
|
||||
auth.and_then(|value| value.get("chatgpt_account_user_id"))
|
||||
.cloned(),
|
||||
auth.and_then(|value| value.get("chatgptAccountUserId"))
|
||||
.cloned(),
|
||||
auth.and_then(|value| value.get("account_user_id")).cloned(),
|
||||
auth.and_then(|value| value.get("accountUserId")).cloned(),
|
||||
source.get("chatgpt_account_user_id").cloned(),
|
||||
source.get("chatgptAccountUserId").cloned(),
|
||||
source.get("account_user_id").cloned(),
|
||||
source.get("accountUserId").cloned(),
|
||||
]) {
|
||||
result.insert("account_user_id".to_string(), json!(account_user_id));
|
||||
}
|
||||
|
||||
if let Some(plan_type) = first_json_non_empty_string([
|
||||
auth.and_then(|value| value.get("chatgpt_plan_type"))
|
||||
.cloned(),
|
||||
auth.and_then(|value| value.get("chatgptPlanType")).cloned(),
|
||||
auth.and_then(|value| value.get("plan_type")).cloned(),
|
||||
auth.and_then(|value| value.get("planType")).cloned(),
|
||||
source.get("chatgpt_plan_type").cloned(),
|
||||
source.get("chatgptPlanType").cloned(),
|
||||
source.get("plan_type").cloned(),
|
||||
source.get("planType").cloned(),
|
||||
]) {
|
||||
result.insert("plan_type".to_string(), json!(plan_type));
|
||||
}
|
||||
|
||||
if let Some(user_id) = first_json_non_empty_string([
|
||||
auth.and_then(|value| value.get("chatgpt_user_id")).cloned(),
|
||||
auth.and_then(|value| value.get("chatgptUserId")).cloned(),
|
||||
auth.and_then(|value| value.get("user_id")).cloned(),
|
||||
auth.and_then(|value| value.get("userId")).cloned(),
|
||||
source.get("chatgpt_user_id").cloned(),
|
||||
source.get("chatgptUserId").cloned(),
|
||||
source.get("user_id").cloned(),
|
||||
source.get("userId").cloned(),
|
||||
source.get("sub").cloned(),
|
||||
]) {
|
||||
result.insert("user_id".to_string(), json!(user_id));
|
||||
}
|
||||
|
||||
if let Some(organizations) = auth
|
||||
.and_then(|value| value.get("organizations"))
|
||||
.and_then(Value::as_array)
|
||||
.filter(|value| !value.is_empty())
|
||||
{
|
||||
result.insert(
|
||||
"organizations".to_string(),
|
||||
Value::Array(organizations.clone()),
|
||||
);
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
pub fn enrich_admin_provider_oauth_auth_config(
|
||||
provider_type: &str,
|
||||
auth_config: &mut Map<String, Value>,
|
||||
token_payload: &Value,
|
||||
) {
|
||||
let Some(token_payload_object) = token_payload.as_object() else {
|
||||
return;
|
||||
};
|
||||
|
||||
merge_missing_auth_config_fields(
|
||||
auth_config,
|
||||
token_payload_object,
|
||||
&[
|
||||
"email",
|
||||
"account_id",
|
||||
"account_user_id",
|
||||
"plan_type",
|
||||
"user_id",
|
||||
"account_name",
|
||||
],
|
||||
);
|
||||
|
||||
if !provider_type.eq_ignore_ascii_case("codex") {
|
||||
return;
|
||||
}
|
||||
|
||||
let codex_fields = extract_codex_auth_fields_from_object(token_payload_object);
|
||||
merge_missing_auth_config_fields(
|
||||
auth_config,
|
||||
&codex_fields,
|
||||
&[
|
||||
"email",
|
||||
"account_id",
|
||||
"account_user_id",
|
||||
"plan_type",
|
||||
"user_id",
|
||||
"organizations",
|
||||
],
|
||||
);
|
||||
|
||||
for token_field in ["id_token", "idToken", "access_token", "accessToken"] {
|
||||
let Some(token) = json_non_empty_string(token_payload.get(token_field)) else {
|
||||
continue;
|
||||
};
|
||||
let Some(claims) = decode_jwt_claims(&token) else {
|
||||
continue;
|
||||
};
|
||||
merge_missing_auth_config_fields(
|
||||
auth_config,
|
||||
&claims,
|
||||
&[
|
||||
"email",
|
||||
"account_id",
|
||||
"account_user_id",
|
||||
"plan_type",
|
||||
"user_id",
|
||||
"account_name",
|
||||
],
|
||||
);
|
||||
let codex_claim_fields = extract_codex_auth_fields_from_object(&claims);
|
||||
merge_missing_auth_config_fields(
|
||||
auth_config,
|
||||
&codex_claim_fields,
|
||||
&[
|
||||
"email",
|
||||
"account_id",
|
||||
"account_user_id",
|
||||
"plan_type",
|
||||
"user_id",
|
||||
"organizations",
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn default_kiro_device_start_url() -> String {
|
||||
KIRO_DEVICE_DEFAULT_START_URL.to_string()
|
||||
}
|
||||
|
||||
pub fn default_kiro_device_region() -> String {
|
||||
KIRO_DEVICE_DEFAULT_REGION.to_string()
|
||||
}
|
||||
|
||||
pub fn normalize_kiro_device_region(value: Option<&str>) -> Option<String> {
|
||||
let value = value
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.unwrap_or(KIRO_DEVICE_DEFAULT_REGION);
|
||||
value
|
||||
.chars()
|
||||
.all(|ch| ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '-')
|
||||
.then(|| value.to_string())
|
||||
}
|
||||
|
||||
pub fn build_kiro_device_key_name(email: Option<&str>, refresh_token: Option<&str>) -> String {
|
||||
if let Some(email) = email.map(str::trim).filter(|value| !value.is_empty()) {
|
||||
return format!("{email} (idc)");
|
||||
}
|
||||
let fallback = refresh_token
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(|value| {
|
||||
let digest = Sha256::digest(value.as_bytes());
|
||||
digest[..3]
|
||||
.iter()
|
||||
.map(|byte| format!("{byte:02x}"))
|
||||
.collect::<String>()
|
||||
})
|
||||
.unwrap_or_else(|| "unknown".to_string());
|
||||
format!("kiro_{fallback} (idc)")
|
||||
}
|
||||
635
crates/aether-admin/src/provider/verify.rs
Normal file
635
crates/aether-admin/src/provider/verify.rs
Normal file
@@ -0,0 +1,635 @@
|
||||
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
|
||||
use http::StatusCode;
|
||||
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
const ADMIN_PROVIDER_OPS_ANYROUTER_XOR_KEY: &str = "3000176000856006061501533003690027800375";
|
||||
const ADMIN_PROVIDER_OPS_ANYROUTER_UNSBOX_TABLE: [usize; 40] = [
|
||||
0xF, 0x23, 0x1D, 0x18, 0x21, 0x10, 0x1, 0x26, 0xA, 0x9, 0x13, 0x1F, 0x28, 0x1B, 0x16, 0x17,
|
||||
0x19, 0xD, 0x6, 0xB, 0x27, 0x12, 0x14, 0x8, 0xE, 0x15, 0x20, 0x1A, 0x2, 0x1E, 0x7, 0x4, 0x11,
|
||||
0x5, 0x3, 0x1C, 0x22, 0x25, 0xC, 0x24,
|
||||
];
|
||||
|
||||
pub fn admin_provider_ops_normalized_verify_architecture_id(architecture_id: &str) -> &str {
|
||||
match architecture_id.trim() {
|
||||
"" => "generic_api",
|
||||
"generic_api" | "new_api" | "cubence" | "yescode" | "nekocode" | "anyrouter"
|
||||
| "sub2api" => architecture_id.trim(),
|
||||
_ => "generic_api",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn admin_provider_ops_extract_cookie_value(cookie_input: &str, key: &str) -> String {
|
||||
if cookie_input.contains(&format!("{key}=")) {
|
||||
for part in cookie_input.split(';') {
|
||||
let trimmed = part.trim();
|
||||
if let Some(value) = trimmed.strip_prefix(&format!("{key}=")) {
|
||||
return value.trim().to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
cookie_input.trim().to_string()
|
||||
}
|
||||
|
||||
pub fn admin_provider_ops_yescode_cookie_header(cookie_input: &str) -> String {
|
||||
if cookie_input.contains("yescode_auth=") {
|
||||
let mut parts = Vec::new();
|
||||
for part in cookie_input.split(';') {
|
||||
let trimmed = part.trim();
|
||||
if let Some(value) = trimmed.strip_prefix("yescode_auth=") {
|
||||
parts.push(format!("yescode_auth={}", value.trim()));
|
||||
} else if let Some(value) = trimmed.strip_prefix("yescode_csrf=") {
|
||||
parts.push(format!("yescode_csrf={}", value.trim()));
|
||||
}
|
||||
}
|
||||
return parts.join("; ");
|
||||
}
|
||||
format!("yescode_auth={}", cookie_input.trim())
|
||||
}
|
||||
|
||||
pub fn admin_provider_ops_anyrouter_compute_acw_sc_v2(arg1: &str) -> Option<String> {
|
||||
if arg1.len() != 40 || !arg1.chars().all(|ch| ch.is_ascii_hexdigit()) {
|
||||
return None;
|
||||
}
|
||||
let chars = arg1.chars().collect::<Vec<_>>();
|
||||
let unsboxed = ADMIN_PROVIDER_OPS_ANYROUTER_UNSBOX_TABLE
|
||||
.iter()
|
||||
.map(|index| chars.get(index.saturating_sub(1)).copied())
|
||||
.collect::<Option<String>>()?;
|
||||
|
||||
let mut result = String::with_capacity(40);
|
||||
for i in (0..40).step_by(2) {
|
||||
let a = u8::from_str_radix(&unsboxed[i..i + 2], 16).ok()?;
|
||||
let b = u8::from_str_radix(&ADMIN_PROVIDER_OPS_ANYROUTER_XOR_KEY[i..i + 2], 16).ok()?;
|
||||
result.push_str(&format!("{:02x}", a ^ b));
|
||||
}
|
||||
Some(result)
|
||||
}
|
||||
|
||||
pub fn admin_provider_ops_anyrouter_parse_session_user_id(cookie_input: &str) -> Option<String> {
|
||||
let session_cookie = admin_provider_ops_extract_cookie_value(cookie_input, "session");
|
||||
let decoded = URL_SAFE_NO_PAD.decode(session_cookie.as_bytes()).ok()?;
|
||||
let text = String::from_utf8_lossy(&decoded);
|
||||
let mut parts = text.split('|');
|
||||
let _timestamp = parts.next()?;
|
||||
let gob_b64 = parts.next()?;
|
||||
let gob_data = URL_SAFE_NO_PAD.decode(gob_b64.as_bytes()).ok()?;
|
||||
|
||||
let id_pattern = b"\x02id\x03int";
|
||||
let id_idx = gob_data
|
||||
.windows(id_pattern.len())
|
||||
.position(|window| window == id_pattern)?;
|
||||
let value_start = id_idx + id_pattern.len() + 2;
|
||||
let first_byte = *gob_data.get(value_start)?;
|
||||
if first_byte != 0 {
|
||||
return None;
|
||||
}
|
||||
let marker = *gob_data.get(value_start + 1)?;
|
||||
if marker < 0x80 {
|
||||
return None;
|
||||
}
|
||||
let length = 256usize.saturating_sub(marker as usize);
|
||||
let end = value_start + 2 + length;
|
||||
let bytes = gob_data.get(value_start + 2..end)?;
|
||||
let val = bytes
|
||||
.iter()
|
||||
.fold(0u64, |acc, byte| (acc << 8) | (*byte as u64));
|
||||
Some((val >> 1).to_string())
|
||||
}
|
||||
|
||||
pub fn admin_provider_ops_verify_failure(message: impl Into<String>) -> Value {
|
||||
json!({
|
||||
"success": false,
|
||||
"message": message.into(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn admin_provider_ops_verify_success(
|
||||
data: Value,
|
||||
updated_credentials: Option<Map<String, Value>>,
|
||||
) -> Value {
|
||||
let mut payload = Map::from_iter([
|
||||
("success".to_string(), Value::Bool(true)),
|
||||
("data".to_string(), data),
|
||||
]);
|
||||
if let Some(credentials) = updated_credentials.filter(|value| !value.is_empty()) {
|
||||
payload.insert(
|
||||
"updated_credentials".to_string(),
|
||||
Value::Object(credentials),
|
||||
);
|
||||
}
|
||||
Value::Object(payload)
|
||||
}
|
||||
|
||||
pub fn admin_provider_ops_verify_user_payload(
|
||||
username: Option<String>,
|
||||
display_name: Option<String>,
|
||||
email: Option<String>,
|
||||
quota: Option<f64>,
|
||||
extra: Option<Map<String, Value>>,
|
||||
) -> Value {
|
||||
let resolved_username = username.filter(|value| !value.trim().is_empty());
|
||||
let resolved_display_name = display_name
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
.or_else(|| resolved_username.clone());
|
||||
let mut payload = Map::new();
|
||||
payload.insert(
|
||||
"username".to_string(),
|
||||
resolved_username.map(Value::String).unwrap_or(Value::Null),
|
||||
);
|
||||
payload.insert(
|
||||
"display_name".to_string(),
|
||||
resolved_display_name
|
||||
.map(Value::String)
|
||||
.unwrap_or(Value::Null),
|
||||
);
|
||||
payload.insert(
|
||||
"email".to_string(),
|
||||
email.map(Value::String).unwrap_or(Value::Null),
|
||||
);
|
||||
payload.insert(
|
||||
"quota".to_string(),
|
||||
quota
|
||||
.and_then(serde_json::Number::from_f64)
|
||||
.map(Value::Number)
|
||||
.unwrap_or(Value::Null),
|
||||
);
|
||||
if let Some(extra) = extra.filter(|value| !value.is_empty()) {
|
||||
payload.insert("extra".to_string(), Value::Object(extra));
|
||||
}
|
||||
Value::Object(payload)
|
||||
}
|
||||
|
||||
pub fn admin_provider_ops_value_as_f64(value: Option<&Value>) -> Option<f64> {
|
||||
match value {
|
||||
Some(Value::Number(number)) => number.as_f64(),
|
||||
Some(Value::String(raw)) => raw.trim().parse::<f64>().ok(),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn admin_provider_ops_json_object(value: &Value) -> Option<&serde_json::Map<String, Value>> {
|
||||
value.as_object()
|
||||
}
|
||||
|
||||
pub fn admin_provider_ops_frontend_updated_credentials(
|
||||
credentials: Map<String, Value>,
|
||||
) -> Option<Map<String, Value>> {
|
||||
let filtered = credentials
|
||||
.into_iter()
|
||||
.filter(|(key, value)| {
|
||||
!key.starts_with('_')
|
||||
&& !matches!(value, Value::Null)
|
||||
&& !value.as_str().is_some_and(|raw| raw.trim().is_empty())
|
||||
})
|
||||
.collect::<Map<String, Value>>();
|
||||
(!filtered.is_empty()).then_some(filtered)
|
||||
}
|
||||
|
||||
fn admin_provider_ops_insert_header(
|
||||
headers: &mut HeaderMap,
|
||||
name: &str,
|
||||
value: &str,
|
||||
) -> Result<(), String> {
|
||||
let header_name =
|
||||
HeaderName::from_bytes(name.as_bytes()).map_err(|_| format!("无效的请求头: {name}"))?;
|
||||
let header_value =
|
||||
HeaderValue::from_str(value).map_err(|_| format!("无效的请求头值: {name}"))?;
|
||||
headers.insert(header_name, header_value);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn admin_provider_ops_verify_headers(
|
||||
architecture_id: &str,
|
||||
config: &serde_json::Map<String, Value>,
|
||||
credentials: &serde_json::Map<String, Value>,
|
||||
) -> Result<HeaderMap, String> {
|
||||
let mut headers = HeaderMap::new();
|
||||
match architecture_id {
|
||||
"generic_api" => {
|
||||
let api_key = credentials
|
||||
.get("api_key")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default()
|
||||
.trim();
|
||||
if !api_key.is_empty() {
|
||||
let auth_method = config
|
||||
.get("auth_method")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("bearer");
|
||||
if auth_method == "header" {
|
||||
let header_name = config
|
||||
.get("header_name")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("X-API-Key");
|
||||
admin_provider_ops_insert_header(&mut headers, header_name, api_key)?;
|
||||
} else {
|
||||
admin_provider_ops_insert_header(
|
||||
&mut headers,
|
||||
"Authorization",
|
||||
&format!("Bearer {api_key}"),
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
"new_api" => {
|
||||
for (name, value) in [
|
||||
(
|
||||
"User-Agent",
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.7339.249 Electron/38.7.0 Safari/537.36",
|
||||
),
|
||||
("Accept", "application/json"),
|
||||
("Accept-Encoding", "gzip, deflate, br"),
|
||||
("Accept-Language", "zh-CN"),
|
||||
("sec-ch-ua", "\"Not=A?Brand\";v=\"24\", \"Chromium\";v=\"140\""),
|
||||
("sec-ch-ua-mobile", "?0"),
|
||||
("sec-ch-ua-platform", "\"macOS\""),
|
||||
("Sec-Fetch-Site", "cross-site"),
|
||||
("Sec-Fetch-Mode", "cors"),
|
||||
("Sec-Fetch-Dest", "empty"),
|
||||
] {
|
||||
admin_provider_ops_insert_header(&mut headers, name, value)?;
|
||||
}
|
||||
if let Some(api_key) = credentials.get("api_key").and_then(Value::as_str) {
|
||||
if !api_key.trim().is_empty() {
|
||||
admin_provider_ops_insert_header(
|
||||
&mut headers,
|
||||
"Authorization",
|
||||
&format!("Bearer {}", api_key.trim()),
|
||||
)?;
|
||||
}
|
||||
}
|
||||
if let Some(user_id) = credentials.get("user_id").and_then(Value::as_str) {
|
||||
if !user_id.trim().is_empty() {
|
||||
admin_provider_ops_insert_header(&mut headers, "New-Api-User", user_id.trim())?;
|
||||
}
|
||||
}
|
||||
if let Some(cookie) = credentials.get("cookie").and_then(Value::as_str) {
|
||||
if !cookie.trim().is_empty() {
|
||||
admin_provider_ops_insert_header(&mut headers, "Cookie", cookie.trim())?;
|
||||
}
|
||||
}
|
||||
}
|
||||
"cubence" => {
|
||||
if let Some(token_cookie) = credentials
|
||||
.get("token_cookie")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
{
|
||||
let token = admin_provider_ops_extract_cookie_value(token_cookie, "token");
|
||||
admin_provider_ops_insert_header(
|
||||
&mut headers,
|
||||
"Cookie",
|
||||
&format!("token={token}"),
|
||||
)?;
|
||||
}
|
||||
}
|
||||
"yescode" => {
|
||||
if let Some(auth_cookie) = credentials
|
||||
.get("auth_cookie")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
{
|
||||
admin_provider_ops_insert_header(
|
||||
&mut headers,
|
||||
"Cookie",
|
||||
&admin_provider_ops_yescode_cookie_header(auth_cookie),
|
||||
)?;
|
||||
}
|
||||
}
|
||||
"nekocode" => {
|
||||
if let Some(session_cookie) = credentials
|
||||
.get("session_cookie")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
{
|
||||
let session = admin_provider_ops_extract_cookie_value(session_cookie, "session");
|
||||
admin_provider_ops_insert_header(
|
||||
&mut headers,
|
||||
"Cookie",
|
||||
&format!("session={session}"),
|
||||
)?;
|
||||
}
|
||||
}
|
||||
"anyrouter" => {
|
||||
let mut cookies = Vec::new();
|
||||
if let Some(acw_cookie) = config
|
||||
.get("acw_cookie")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
{
|
||||
cookies.push(acw_cookie.to_string());
|
||||
}
|
||||
if let Some(session_cookie) = credentials
|
||||
.get("session_cookie")
|
||||
.and_then(Value::as_str)
|
||||
.filter(|value| !value.trim().is_empty())
|
||||
{
|
||||
let session = admin_provider_ops_extract_cookie_value(session_cookie, "session");
|
||||
cookies.push(format!("session={session}"));
|
||||
if let Some(user_id) =
|
||||
admin_provider_ops_anyrouter_parse_session_user_id(session_cookie)
|
||||
{
|
||||
admin_provider_ops_insert_header(&mut headers, "New-Api-User", user_id.trim())?;
|
||||
}
|
||||
}
|
||||
if !cookies.is_empty() {
|
||||
admin_provider_ops_insert_header(&mut headers, "Cookie", &cookies.join("; "))?;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(headers)
|
||||
}
|
||||
|
||||
pub fn admin_provider_ops_generic_verify_payload(
|
||||
status: StatusCode,
|
||||
response_json: &Value,
|
||||
) -> Value {
|
||||
if status == StatusCode::UNAUTHORIZED {
|
||||
return admin_provider_ops_verify_failure("认证失败:无效的凭据");
|
||||
}
|
||||
if status == StatusCode::FORBIDDEN {
|
||||
return admin_provider_ops_verify_failure("认证失败:权限不足");
|
||||
}
|
||||
if status != StatusCode::OK {
|
||||
return admin_provider_ops_verify_failure(format!("验证失败:HTTP {}", status.as_u16()));
|
||||
}
|
||||
|
||||
let user_data = if response_json.get("success").and_then(Value::as_bool) == Some(true)
|
||||
&& response_json.get("data").is_some_and(Value::is_object)
|
||||
{
|
||||
response_json.get("data")
|
||||
} else if response_json.get("success").and_then(Value::as_bool) == Some(false) {
|
||||
return admin_provider_ops_verify_failure(
|
||||
response_json
|
||||
.get("message")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("验证失败"),
|
||||
);
|
||||
} else {
|
||||
Some(response_json)
|
||||
};
|
||||
|
||||
let Some(user_data) = user_data.and_then(admin_provider_ops_json_object) else {
|
||||
return admin_provider_ops_verify_failure("响应格式无效");
|
||||
};
|
||||
|
||||
let mut extra = Map::new();
|
||||
for (key, value) in user_data {
|
||||
if matches!(
|
||||
key.as_str(),
|
||||
"username" | "display_name" | "email" | "quota" | "used_quota" | "request_count"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
extra.insert(key.clone(), value.clone());
|
||||
}
|
||||
|
||||
admin_provider_ops_verify_success(
|
||||
admin_provider_ops_verify_user_payload(
|
||||
user_data
|
||||
.get("username")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
user_data
|
||||
.get("display_name")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
user_data
|
||||
.get("email")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
admin_provider_ops_value_as_f64(user_data.get("quota")),
|
||||
Some(extra),
|
||||
),
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn admin_provider_ops_cubence_verify_payload(
|
||||
status: StatusCode,
|
||||
response_json: &Value,
|
||||
) -> Value {
|
||||
if status == StatusCode::UNAUTHORIZED {
|
||||
return admin_provider_ops_verify_failure("Cookie 已失效,请重新配置");
|
||||
}
|
||||
if status == StatusCode::FORBIDDEN {
|
||||
return admin_provider_ops_verify_failure("Cookie 已失效或无权限");
|
||||
}
|
||||
if status != StatusCode::OK {
|
||||
return admin_provider_ops_verify_failure(format!("验证失败:HTTP {}", status.as_u16()));
|
||||
}
|
||||
|
||||
let Some(payload) = admin_provider_ops_json_object(response_json) else {
|
||||
return admin_provider_ops_verify_failure("响应格式无效");
|
||||
};
|
||||
let user_info = payload
|
||||
.get("user")
|
||||
.and_then(Value::as_object)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let balance_info = payload
|
||||
.get("balance")
|
||||
.and_then(Value::as_object)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
|
||||
let mut extra = Map::new();
|
||||
if let Some(role) = user_info.get("role") {
|
||||
extra.insert("role".to_string(), role.clone());
|
||||
}
|
||||
if let Some(invite_code) = user_info.get("invite_code") {
|
||||
extra.insert("invite_code".to_string(), invite_code.clone());
|
||||
}
|
||||
|
||||
admin_provider_ops_verify_success(
|
||||
admin_provider_ops_verify_user_payload(
|
||||
user_info
|
||||
.get("username")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
user_info
|
||||
.get("username")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
None,
|
||||
admin_provider_ops_value_as_f64(balance_info.get("total_balance_dollar")),
|
||||
Some(extra),
|
||||
),
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn admin_provider_ops_yescode_verify_payload(
|
||||
status: StatusCode,
|
||||
response_json: &Value,
|
||||
) -> Value {
|
||||
if status == StatusCode::UNAUTHORIZED {
|
||||
return admin_provider_ops_verify_failure("Cookie 已失效,请重新配置");
|
||||
}
|
||||
if status == StatusCode::FORBIDDEN {
|
||||
return admin_provider_ops_verify_failure("Cookie 已失效或无权限");
|
||||
}
|
||||
if status != StatusCode::OK {
|
||||
return admin_provider_ops_verify_failure(format!("验证失败:HTTP {}", status.as_u16()));
|
||||
}
|
||||
|
||||
let Some(payload) = admin_provider_ops_json_object(response_json) else {
|
||||
return admin_provider_ops_verify_failure("响应格式无效");
|
||||
};
|
||||
let Some(username) = payload
|
||||
.get("username")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned)
|
||||
else {
|
||||
return admin_provider_ops_verify_failure("响应格式无效");
|
||||
};
|
||||
|
||||
let pay_as_you_go =
|
||||
admin_provider_ops_value_as_f64(payload.get("pay_as_you_go_balance")).unwrap_or(0.0);
|
||||
let subscription =
|
||||
admin_provider_ops_value_as_f64(payload.get("subscription_balance")).unwrap_or(0.0);
|
||||
let plan = payload
|
||||
.get("subscription_plan")
|
||||
.and_then(Value::as_object)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let weekly_limit = admin_provider_ops_value_as_f64(
|
||||
payload
|
||||
.get("weekly_limit")
|
||||
.or_else(|| plan.get("weekly_limit")),
|
||||
);
|
||||
let weekly_spent = admin_provider_ops_value_as_f64(
|
||||
payload
|
||||
.get("weekly_spent_balance")
|
||||
.or_else(|| payload.get("current_week_spend")),
|
||||
)
|
||||
.unwrap_or(0.0);
|
||||
let subscription_available = weekly_limit
|
||||
.map(|limit| (limit - weekly_spent).max(0.0).min(subscription))
|
||||
.unwrap_or(subscription);
|
||||
|
||||
admin_provider_ops_verify_success(
|
||||
admin_provider_ops_verify_user_payload(
|
||||
Some(username.clone()),
|
||||
Some(username),
|
||||
payload
|
||||
.get("email")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
Some(pay_as_you_go + subscription_available),
|
||||
None,
|
||||
),
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn admin_provider_ops_nekocode_verify_payload(
|
||||
status: StatusCode,
|
||||
response_json: &Value,
|
||||
) -> Value {
|
||||
if status == StatusCode::UNAUTHORIZED {
|
||||
return admin_provider_ops_verify_failure("Cookie 已失效,请重新配置");
|
||||
}
|
||||
if status == StatusCode::FORBIDDEN {
|
||||
return admin_provider_ops_verify_failure("Cookie 已失效或无权限");
|
||||
}
|
||||
if status != StatusCode::OK {
|
||||
return admin_provider_ops_verify_failure(format!("验证失败:HTTP {}", status.as_u16()));
|
||||
}
|
||||
|
||||
let user_data = if response_json.get("success").and_then(Value::as_bool) == Some(true)
|
||||
&& response_json.get("data").is_some_and(Value::is_object)
|
||||
{
|
||||
response_json.get("data")
|
||||
} else {
|
||||
Some(response_json)
|
||||
};
|
||||
let Some(user_data) = user_data.and_then(admin_provider_ops_json_object) else {
|
||||
return admin_provider_ops_verify_failure("响应格式无效");
|
||||
};
|
||||
|
||||
admin_provider_ops_verify_success(
|
||||
admin_provider_ops_verify_user_payload(
|
||||
user_data
|
||||
.get("username")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
user_data
|
||||
.get("display_name")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
user_data
|
||||
.get("email")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
admin_provider_ops_value_as_f64(user_data.get("balance")),
|
||||
None,
|
||||
),
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn admin_provider_ops_sub2api_verify_payload(
|
||||
status: StatusCode,
|
||||
response_json: &Value,
|
||||
updated_credentials: Option<Map<String, Value>>,
|
||||
) -> Value {
|
||||
if status == StatusCode::UNAUTHORIZED {
|
||||
return admin_provider_ops_verify_failure("认证失败:无效的凭据");
|
||||
}
|
||||
if status == StatusCode::FORBIDDEN {
|
||||
return admin_provider_ops_verify_failure("认证失败:权限不足");
|
||||
}
|
||||
if status != StatusCode::OK {
|
||||
return admin_provider_ops_verify_failure(format!("验证失败:HTTP {}", status.as_u16()));
|
||||
}
|
||||
|
||||
let Some(payload) = admin_provider_ops_json_object(response_json) else {
|
||||
return admin_provider_ops_verify_failure("响应格式无效");
|
||||
};
|
||||
if payload.get("code").and_then(Value::as_i64).unwrap_or(-1) != 0 {
|
||||
return admin_provider_ops_verify_failure(
|
||||
payload
|
||||
.get("message")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("验证失败"),
|
||||
);
|
||||
}
|
||||
|
||||
let Some(user_data) = payload.get("data").and_then(Value::as_object) else {
|
||||
return admin_provider_ops_verify_failure("响应格式无效");
|
||||
};
|
||||
let balance = admin_provider_ops_value_as_f64(user_data.get("balance")).unwrap_or(0.0);
|
||||
let points = admin_provider_ops_value_as_f64(user_data.get("points")).unwrap_or(0.0);
|
||||
let mut extra = Map::new();
|
||||
for key in ["balance", "points", "status", "concurrency"] {
|
||||
if let Some(value) = user_data.get(key) {
|
||||
extra.insert(key.to_string(), value.clone());
|
||||
}
|
||||
}
|
||||
|
||||
admin_provider_ops_verify_success(
|
||||
admin_provider_ops_verify_user_payload(
|
||||
user_data
|
||||
.get("username")
|
||||
.or_else(|| user_data.get("email"))
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
user_data
|
||||
.get("username")
|
||||
.or_else(|| user_data.get("email"))
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
user_data
|
||||
.get("email")
|
||||
.and_then(Value::as_str)
|
||||
.map(ToOwned::to_owned),
|
||||
Some(balance + points),
|
||||
Some(extra),
|
||||
),
|
||||
updated_credentials,
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user