mirror of
https://github.com/fawney19/Aether.git
synced 2026-09-10 05:00:19 +08:00
Merge pull request #681 from zhefox/main
Codex 重置功能和显示缓存修复以及批量key的导入和管理功能
This commit is contained in:
@@ -51,14 +51,6 @@ fn merge_codex_quota_metadata(
|
||||
serde_json::Value::Object(merged)
|
||||
}
|
||||
|
||||
fn codex_reset_credits_available_count(metadata: &Map<String, Value>) -> Option<u64> {
|
||||
metadata
|
||||
.get("reset_credits")
|
||||
.and_then(Value::as_object)
|
||||
.and_then(|reset_credits| reset_credits.get("available_count"))
|
||||
.and_then(aether_admin::provider::quota::coerce_json_u64)
|
||||
}
|
||||
|
||||
fn truncate_codex_reset_credit_detail_error(message: impl Into<String>) -> String {
|
||||
let message = message.into();
|
||||
let mut sanitized = message.replace('\n', " ");
|
||||
@@ -85,11 +77,7 @@ fn merge_codex_reset_credit_detail_metadata(
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
|
||||
let has_usage_available_count = reset_credits.contains_key("available_count");
|
||||
for (key, value) in detail_reset_credits {
|
||||
if key == "available_count" && has_usage_available_count {
|
||||
continue;
|
||||
}
|
||||
reset_credits.insert(key.clone(), value.clone());
|
||||
}
|
||||
codex_metadata.insert("reset_credits".to_string(), Value::Object(reset_credits));
|
||||
@@ -97,6 +85,7 @@ fn merge_codex_reset_credit_detail_metadata(
|
||||
|
||||
fn mark_codex_reset_credit_detail_failed(
|
||||
codex_metadata: &mut Map<String, Value>,
|
||||
updated_at_unix_secs: u64,
|
||||
detail_error: impl Into<String>,
|
||||
) {
|
||||
let mut reset_credits = codex_metadata
|
||||
@@ -104,6 +93,7 @@ fn mark_codex_reset_credit_detail_failed(
|
||||
.and_then(Value::as_object)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
reset_credits.insert("updated_at".to_string(), json!(updated_at_unix_secs));
|
||||
reset_credits.insert("detail_source".to_string(), json!("wham_readonly"));
|
||||
reset_credits.insert("detail_status".to_string(), json!("failed"));
|
||||
reset_credits.insert(
|
||||
@@ -124,16 +114,11 @@ async fn enrich_codex_reset_credit_details(
|
||||
codex_metadata: &mut Map<String, Value>,
|
||||
now_unix_secs: u64,
|
||||
) -> Result<(), GatewayError> {
|
||||
let available_count = codex_reset_credits_available_count(codex_metadata).unwrap_or(0);
|
||||
if available_count == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let request_spec = match build_codex_reset_credits_request_spec(transport, resolved_oauth_auth)
|
||||
{
|
||||
Ok(request_spec) => request_spec,
|
||||
Err(message) => {
|
||||
mark_codex_reset_credit_detail_failed(codex_metadata, message);
|
||||
mark_codex_reset_credit_detail_failed(codex_metadata, now_unix_secs, message);
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
@@ -146,6 +131,7 @@ async fn enrich_codex_reset_credit_details(
|
||||
ProviderQuotaExecutionOutcome::Failure(detail) => {
|
||||
mark_codex_reset_credit_detail_failed(
|
||||
codex_metadata,
|
||||
now_unix_secs,
|
||||
format!("reset credit detail 请求执行失败: {detail}"),
|
||||
);
|
||||
return Ok(());
|
||||
@@ -157,6 +143,7 @@ async fn enrich_codex_reset_credit_details(
|
||||
.unwrap_or_else(|| format!("HTTP {}", result.status_code));
|
||||
mark_codex_reset_credit_detail_failed(
|
||||
codex_metadata,
|
||||
now_unix_secs,
|
||||
format!(
|
||||
"reset credit detail 返回状态码 {}: {detail}",
|
||||
result.status_code
|
||||
@@ -170,7 +157,11 @@ async fn enrich_codex_reset_credit_details(
|
||||
.as_ref()
|
||||
.and_then(|body| body.json_body.as_ref())
|
||||
else {
|
||||
mark_codex_reset_credit_detail_failed(codex_metadata, "无法解析 reset credit detail 响应");
|
||||
mark_codex_reset_credit_detail_failed(
|
||||
codex_metadata,
|
||||
now_unix_secs,
|
||||
"无法解析 reset credit detail 响应",
|
||||
);
|
||||
return Ok(());
|
||||
};
|
||||
if let Some(detail_metadata) =
|
||||
@@ -178,7 +169,11 @@ async fn enrich_codex_reset_credit_details(
|
||||
{
|
||||
merge_codex_reset_credit_detail_metadata(codex_metadata, &detail_metadata);
|
||||
} else {
|
||||
mark_codex_reset_credit_detail_failed(codex_metadata, "reset credit detail 响应为空");
|
||||
mark_codex_reset_credit_detail_failed(
|
||||
codex_metadata,
|
||||
now_unix_secs,
|
||||
"reset credit detail 响应为空",
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -776,3 +771,52 @@ pub(crate) async fn refresh_codex_provider_quota_locally(
|
||||
"auto_removed_hard_banned": auto_removed_hard_banned_count,
|
||||
})))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn codex_reset_credit_detail_count_overrides_usage_count() {
|
||||
let mut metadata = json!({
|
||||
"reset_credits": {
|
||||
"available_count": 0,
|
||||
"detail_source": "wham_usage"
|
||||
}
|
||||
})
|
||||
.as_object()
|
||||
.cloned()
|
||||
.expect("metadata object");
|
||||
let detail = json!({
|
||||
"reset_credits": {
|
||||
"available_count": 2,
|
||||
"detail_source": "wham_readonly"
|
||||
}
|
||||
});
|
||||
|
||||
merge_codex_reset_credit_detail_metadata(&mut metadata, &detail);
|
||||
|
||||
assert_eq!(
|
||||
metadata
|
||||
.get("reset_credits")
|
||||
.and_then(Value::as_object)
|
||||
.and_then(|credits| credits.get("available_count")),
|
||||
Some(&json!(2u64))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_reset_credit_detail_failure_records_attempt_time() {
|
||||
let mut metadata = Map::new();
|
||||
|
||||
mark_codex_reset_credit_detail_failed(&mut metadata, 1_777_000_000, "request failed");
|
||||
|
||||
assert_eq!(
|
||||
metadata
|
||||
.get("reset_credits")
|
||||
.and_then(Value::as_object)
|
||||
.and_then(|credits| credits.get("updated_at")),
|
||||
Some(&json!(1_777_000_000u64))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,13 +55,6 @@ pub(super) async fn build_admin_pool_batch_import_response(
|
||||
}
|
||||
};
|
||||
|
||||
if payload.keys.len() > 500 {
|
||||
return Ok(build_admin_pool_error_response(
|
||||
http::StatusCode::BAD_REQUEST,
|
||||
"keys length must be less than or equal to 500",
|
||||
));
|
||||
}
|
||||
|
||||
state
|
||||
.build_admin_pool_batch_import_response(&provider_id, payload)
|
||||
.await
|
||||
|
||||
@@ -12,7 +12,8 @@ use axum::{
|
||||
response::{IntoResponse, Response},
|
||||
Json,
|
||||
};
|
||||
use serde_json::json;
|
||||
use serde_json::{json, Map, Value};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
impl<'a> AdminAppState<'a> {
|
||||
pub(crate) async fn clear_admin_provider_pool_cooldown(&self, provider_id: &str, key_id: &str) {
|
||||
@@ -105,9 +106,9 @@ impl<'a> AdminAppState<'a> {
|
||||
let existing_keys = self
|
||||
.list_provider_catalog_keys_by_provider_ids(std::slice::from_ref(&provider.id))
|
||||
.await?;
|
||||
let api_formats =
|
||||
let available_api_formats =
|
||||
admin_provider_pool_pure::admin_pool_resolved_api_formats(&endpoints, &existing_keys);
|
||||
if api_formats.is_empty() {
|
||||
if available_api_formats.is_empty() {
|
||||
return Ok((
|
||||
http::StatusCode::BAD_REQUEST,
|
||||
Json(json!({ "detail": "Provider 没有可用 endpoint 或现有 key,无法推断 api_formats" })),
|
||||
@@ -115,8 +116,74 @@ impl<'a> AdminAppState<'a> {
|
||||
.into_response());
|
||||
}
|
||||
|
||||
let proxy =
|
||||
admin_provider_pool_pure::admin_pool_key_proxy_value(payload.proxy_node_id.as_deref());
|
||||
let requested_api_formats = payload
|
||||
.api_formats
|
||||
.iter()
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
.collect::<BTreeSet<_>>()
|
||||
.into_iter()
|
||||
.collect::<Vec<_>>();
|
||||
let available_api_format_set = available_api_formats
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect::<BTreeSet<_>>();
|
||||
let api_formats = if requested_api_formats.is_empty() {
|
||||
available_api_formats.clone()
|
||||
} else {
|
||||
if let Some(unsupported) = requested_api_formats
|
||||
.iter()
|
||||
.find(|value| !available_api_format_set.contains(*value))
|
||||
{
|
||||
return Ok((
|
||||
http::StatusCode::BAD_REQUEST,
|
||||
Json(json!({ "detail": format!("Provider 不支持 api_format: {unsupported}") })),
|
||||
)
|
||||
.into_response());
|
||||
}
|
||||
requested_api_formats
|
||||
};
|
||||
|
||||
let mut settings_map = match payload.settings {
|
||||
Some(Value::Object(map)) => map,
|
||||
Some(_) => {
|
||||
return Ok((
|
||||
http::StatusCode::BAD_REQUEST,
|
||||
Json(json!({ "detail": "settings payload must be an object" })),
|
||||
)
|
||||
.into_response());
|
||||
}
|
||||
None => Map::new(),
|
||||
};
|
||||
if let Some(proxy_node_id) = payload.proxy_node_id {
|
||||
settings_map
|
||||
.entry("proxy_node_id".to_string())
|
||||
.or_insert(Value::String(proxy_node_id));
|
||||
}
|
||||
let shared_settings = (!settings_map.is_empty()).then_some(Value::Object(settings_map));
|
||||
if let Some(settings) = shared_settings.as_ref() {
|
||||
if let Err(detail) =
|
||||
admin_provider_pool_pure::validate_admin_pool_key_settings_payload(settings)
|
||||
{
|
||||
return Ok((
|
||||
http::StatusCode::BAD_REQUEST,
|
||||
Json(json!({ "detail": detail })),
|
||||
)
|
||||
.into_response());
|
||||
}
|
||||
}
|
||||
|
||||
let mut known_names = existing_keys
|
||||
.iter()
|
||||
.map(|key| key.name.trim().to_string())
|
||||
.filter(|name| !name.is_empty())
|
||||
.collect::<BTreeSet<_>>();
|
||||
let mut known_api_keys = existing_keys
|
||||
.iter()
|
||||
.filter_map(|key| key.encrypted_api_key.as_deref())
|
||||
.filter_map(|ciphertext| self.decrypt_catalog_secret_with_fallbacks(ciphertext))
|
||||
.filter(|value| value != "__placeholder__")
|
||||
.collect::<BTreeSet<_>>();
|
||||
let mut imported = 0usize;
|
||||
let skipped = 0usize;
|
||||
let mut errors = Vec::new();
|
||||
@@ -136,6 +203,79 @@ impl<'a> AdminAppState<'a> {
|
||||
continue;
|
||||
}
|
||||
|
||||
let name = item.name.trim();
|
||||
if name.is_empty() {
|
||||
errors.push(json!({
|
||||
"index": index,
|
||||
"reason": "name is empty",
|
||||
}));
|
||||
continue;
|
||||
}
|
||||
if known_names.contains(name) {
|
||||
errors.push(json!({
|
||||
"index": index,
|
||||
"reason": "该名称已存在于当前 Provider 或本次导入中",
|
||||
}));
|
||||
continue;
|
||||
}
|
||||
|
||||
let auth_type = item.auth_type.trim().to_ascii_lowercase();
|
||||
let auth_type = if auth_type.is_empty() {
|
||||
"api_key".to_string()
|
||||
} else {
|
||||
auth_type
|
||||
};
|
||||
if !matches!(auth_type.as_str(), "api_key" | "bearer") {
|
||||
errors.push(json!({
|
||||
"index": index,
|
||||
"reason": "auth_type must be api_key or bearer",
|
||||
}));
|
||||
continue;
|
||||
}
|
||||
let requested_item_api_formats = item
|
||||
.api_formats
|
||||
.iter()
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
.collect::<BTreeSet<_>>()
|
||||
.into_iter()
|
||||
.collect::<Vec<_>>();
|
||||
let item_api_formats = if requested_item_api_formats.is_empty() {
|
||||
api_formats.clone()
|
||||
} else {
|
||||
if let Some(unsupported) = requested_item_api_formats
|
||||
.iter()
|
||||
.find(|value| !available_api_format_set.contains(*value))
|
||||
{
|
||||
errors.push(json!({
|
||||
"index": index,
|
||||
"reason": format!("Provider 不支持 api_format: {unsupported}"),
|
||||
}));
|
||||
continue;
|
||||
}
|
||||
requested_item_api_formats
|
||||
};
|
||||
let item_settings = match admin_provider_pool_pure::resolve_admin_pool_key_settings(
|
||||
shared_settings.as_ref(),
|
||||
item.settings.as_ref(),
|
||||
) {
|
||||
Ok(value) => value,
|
||||
Err(detail) => {
|
||||
errors.push(json!({
|
||||
"index": index,
|
||||
"reason": detail,
|
||||
}));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if known_api_keys.contains(api_key) {
|
||||
errors.push(json!({
|
||||
"index": index,
|
||||
"reason": "该 API Key 已存在于当前 Provider 或本次导入中",
|
||||
}));
|
||||
continue;
|
||||
}
|
||||
|
||||
let Some(encrypted_api_key) = self.encrypt_catalog_secret_with_fallbacks(api_key)
|
||||
else {
|
||||
errors.push(json!({
|
||||
@@ -144,26 +284,15 @@ impl<'a> AdminAppState<'a> {
|
||||
}));
|
||||
continue;
|
||||
};
|
||||
|
||||
let auth_type = item.auth_type.trim().to_ascii_lowercase();
|
||||
let auth_type = if auth_type.is_empty() {
|
||||
"api_key".to_string()
|
||||
} else {
|
||||
auth_type
|
||||
};
|
||||
let name = item.name.trim();
|
||||
let record = match admin_provider_pool_pure::build_admin_pool_batch_import_key_record(
|
||||
uuid::Uuid::new_v4().to_string(),
|
||||
provider.id.clone(),
|
||||
if name.is_empty() {
|
||||
format!("imported-{index}")
|
||||
} else {
|
||||
name.to_string()
|
||||
},
|
||||
name.to_string(),
|
||||
auth_type,
|
||||
api_formats.clone(),
|
||||
item_api_formats,
|
||||
encrypted_api_key,
|
||||
proxy.clone(),
|
||||
None,
|
||||
item_settings.as_ref(),
|
||||
now_unix_secs,
|
||||
) {
|
||||
Ok(value) => value,
|
||||
@@ -175,7 +304,6 @@ impl<'a> AdminAppState<'a> {
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let Some(_) = self.create_provider_catalog_key(&record).await? else {
|
||||
return Ok((
|
||||
http::StatusCode::SERVICE_UNAVAILABLE,
|
||||
@@ -185,6 +313,8 @@ impl<'a> AdminAppState<'a> {
|
||||
)
|
||||
.into_response());
|
||||
};
|
||||
known_names.insert(name.to_string());
|
||||
known_api_keys.insert(api_key.to_string());
|
||||
imported += 1;
|
||||
}
|
||||
|
||||
@@ -473,6 +603,12 @@ impl<'a> AdminAppState<'a> {
|
||||
AdminPoolBatchActionKind::Disable => key.is_active = false,
|
||||
AdminPoolBatchActionKind::ClearProxy => key.proxy = None,
|
||||
AdminPoolBatchActionKind::SetProxy => key.proxy = plan.proxy_payload.clone(),
|
||||
AdminPoolBatchActionKind::UpdateSettings => {
|
||||
if let Some(settings) = plan.settings_payload.as_ref() {
|
||||
admin_provider_pool_pure::apply_admin_pool_key_settings(&mut key, settings)
|
||||
.map_err(GatewayError::Internal)?;
|
||||
}
|
||||
}
|
||||
AdminPoolBatchActionKind::RegenerateFingerprint => {
|
||||
key.fingerprint =
|
||||
Some(aether_provider_transport::claude_code::generate_random_fingerprint())
|
||||
|
||||
@@ -2054,6 +2054,29 @@ fn quota_snapshot_has_materialized_data(
|
||||
})
|
||||
}
|
||||
|
||||
fn codex_upstream_metadata_is_at_least_as_fresh(
|
||||
quota_snapshot: Option<&Map<String, Value>>,
|
||||
upstream_metadata: Option<&Value>,
|
||||
) -> bool {
|
||||
let Some(metadata) = provider_quota_metadata_bucket(upstream_metadata, "codex") else {
|
||||
return false;
|
||||
};
|
||||
let Some(metadata_updated_at) = metadata
|
||||
.get("updated_at")
|
||||
.and_then(admin_provider_quota_pure::coerce_json_u64)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let snapshot_updated_at = quota_snapshot.and_then(|quota| {
|
||||
quota
|
||||
.get("updated_at")
|
||||
.or_else(|| quota.get("observed_at"))
|
||||
.and_then(admin_provider_quota_pure::coerce_json_u64)
|
||||
});
|
||||
|
||||
snapshot_updated_at.is_none_or(|updated_at| metadata_updated_at >= updated_at)
|
||||
}
|
||||
|
||||
fn windsurf_quota_snapshot_has_stale_cooldown(quota_snapshot: &Map<String, Value>) -> bool {
|
||||
let code = quota_snapshot
|
||||
.get("code")
|
||||
@@ -2121,8 +2144,15 @@ pub(crate) fn provider_key_status_snapshot_payload(
|
||||
.and_then(Value::as_object)
|
||||
.and_then(|snapshot| snapshot.get("quota"))
|
||||
.and_then(Value::as_object);
|
||||
let refresh_codex_snapshot = provider_type.trim().eq_ignore_ascii_case("codex")
|
||||
&& codex_upstream_metadata_is_at_least_as_fresh(
|
||||
quota_snapshot,
|
||||
key.upstream_metadata.as_ref(),
|
||||
);
|
||||
|
||||
let payload = if quota_snapshot_has_materialized_data(quota_snapshot, provider_type) {
|
||||
let payload = if quota_snapshot_has_materialized_data(quota_snapshot, provider_type)
|
||||
&& !refresh_codex_snapshot
|
||||
{
|
||||
status_snapshot
|
||||
.cloned()
|
||||
.unwrap_or_else(default_provider_key_status_snapshot)
|
||||
@@ -3512,6 +3542,58 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provider_key_status_snapshot_payload_restores_complete_codex_cache() {
|
||||
let mut key = sample_catalog_key();
|
||||
key.upstream_metadata = Some(json!({
|
||||
"codex": {
|
||||
"updated_at": 200u64,
|
||||
"plan_type": "plus",
|
||||
"primary_used_percent": 89.0,
|
||||
"primary_reset_at": 1_900_000_000u64,
|
||||
"spark_primary_used_percent": 40.0,
|
||||
"spark_primary_reset_at": 1_900_100_000u64,
|
||||
"reset_credits": {
|
||||
"available_count": 3,
|
||||
"updated_at": 200u64,
|
||||
"detail_status": "available",
|
||||
"credits": []
|
||||
}
|
||||
}
|
||||
}));
|
||||
key.status_snapshot = Some(json!({
|
||||
"quota": {
|
||||
"version": 2,
|
||||
"provider_type": "codex",
|
||||
"updated_at": 200u64,
|
||||
"windows": [{
|
||||
"code": "weekly",
|
||||
"used_ratio": 1.0,
|
||||
"reset_at": 1_900_000_000u64
|
||||
}]
|
||||
}
|
||||
}));
|
||||
|
||||
let payload = provider_key_status_snapshot_payload(&key, "codex");
|
||||
let windows = payload["quota"]["windows"]
|
||||
.as_array()
|
||||
.expect("quota windows should exist");
|
||||
|
||||
assert_eq!(payload.pointer("/quota/plan_type"), Some(&json!("plus")));
|
||||
assert_eq!(
|
||||
payload.pointer("/quota/reset_credits/available_count"),
|
||||
Some(&json!(3u64))
|
||||
);
|
||||
assert!(windows.iter().any(|window| window["code"] == "spark_5h"));
|
||||
assert_eq!(
|
||||
windows
|
||||
.iter()
|
||||
.find(|window| window["code"] == "weekly")
|
||||
.and_then(|window| window.get("used_ratio")),
|
||||
Some(&json!(0.89))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sync_provider_key_quota_status_snapshot_preserves_codex_usage_state() {
|
||||
let current_status_snapshot = json!({
|
||||
|
||||
@@ -70,7 +70,7 @@ async fn gateway_refreshes_admin_provider_quota_locally_for_codex_with_trusted_a
|
||||
}),
|
||||
);
|
||||
|
||||
let seen_execution_runtime = Arc::new(Mutex::new(None::<SeenExecutionRuntimeRequest>));
|
||||
let seen_execution_runtime = Arc::new(Mutex::new(Vec::<SeenExecutionRuntimeRequest>::new()));
|
||||
let seen_execution_runtime_clone = Arc::clone(&seen_execution_runtime);
|
||||
let execution_runtime = Router::new().route(
|
||||
"/v1/execute/sync",
|
||||
@@ -83,21 +83,22 @@ async fn gateway_refreshes_admin_provider_quota_locally_for_codex_with_trusted_a
|
||||
.expect("body should read"),
|
||||
)
|
||||
.expect("plan should parse");
|
||||
*seen_execution_runtime_inner
|
||||
seen_execution_runtime_inner
|
||||
.lock()
|
||||
.expect("mutex should lock") = Some(SeenExecutionRuntimeRequest {
|
||||
url: plan.url.clone(),
|
||||
authorization: plan
|
||||
.headers
|
||||
.get("authorization")
|
||||
.cloned()
|
||||
.unwrap_or_default(),
|
||||
provider_api_format: plan.provider_api_format.clone(),
|
||||
total_ms: plan
|
||||
.timeouts
|
||||
.as_ref()
|
||||
.and_then(|timeouts| timeouts.total_ms),
|
||||
});
|
||||
.expect("mutex should lock")
|
||||
.push(SeenExecutionRuntimeRequest {
|
||||
url: plan.url.clone(),
|
||||
authorization: plan
|
||||
.headers
|
||||
.get("authorization")
|
||||
.cloned()
|
||||
.unwrap_or_default(),
|
||||
provider_api_format: plan.provider_api_format.clone(),
|
||||
total_ms: plan
|
||||
.timeouts
|
||||
.as_ref()
|
||||
.and_then(|timeouts| timeouts.total_ms),
|
||||
});
|
||||
let result = aether_contracts::ExecutionResult {
|
||||
request_id: plan.request_id,
|
||||
candidate_id: None,
|
||||
@@ -223,24 +224,24 @@ async fn gateway_refreshes_admin_provider_quota_locally_for_codex_with_trusted_a
|
||||
);
|
||||
assert_eq!(*upstream_hits.lock().expect("mutex should lock"), 0);
|
||||
|
||||
let seen_execution_runtime_request = seen_execution_runtime
|
||||
let seen_execution_runtime_requests = seen_execution_runtime
|
||||
.lock()
|
||||
.expect("mutex should lock")
|
||||
.clone()
|
||||
.expect("execution runtime request should be captured");
|
||||
.clone();
|
||||
assert_eq!(seen_execution_runtime_requests.len(), 2);
|
||||
assert_eq!(
|
||||
seen_execution_runtime_request.url,
|
||||
seen_execution_runtime_requests[0].url,
|
||||
"https://chatgpt.com/backend-api/wham/usage"
|
||||
);
|
||||
assert_eq!(
|
||||
seen_execution_runtime_request.authorization,
|
||||
"Bearer sk-codex-123"
|
||||
seen_execution_runtime_requests[1].url,
|
||||
"https://chatgpt.com/backend-api/wham/rate-limit-reset-credits"
|
||||
);
|
||||
assert_eq!(
|
||||
seen_execution_runtime_request.provider_api_format,
|
||||
"openai:responses"
|
||||
);
|
||||
assert_eq!(seen_execution_runtime_request.total_ms, Some(30_000));
|
||||
for request in seen_execution_runtime_requests {
|
||||
assert_eq!(request.authorization, "Bearer sk-codex-123");
|
||||
assert_eq!(request.provider_api_format, "openai:responses");
|
||||
assert_eq!(request.total_ms, Some(30_000));
|
||||
}
|
||||
|
||||
let reloaded = provider_catalog_repository
|
||||
.list_keys_by_ids(&["key-codex-a".to_string()])
|
||||
@@ -679,7 +680,10 @@ async fn gateway_refreshes_admin_provider_quota_locally_for_requested_codex_keys
|
||||
.lock()
|
||||
.expect("mutex should lock")
|
||||
.clone(),
|
||||
vec!["Bearer sk-codex-a".to_string()]
|
||||
vec![
|
||||
"Bearer sk-codex-a".to_string(),
|
||||
"Bearer sk-codex-a".to_string(),
|
||||
]
|
||||
);
|
||||
|
||||
let reloaded = provider_catalog_repository
|
||||
|
||||
@@ -3,7 +3,7 @@ use aether_data_contracts::repository::provider_catalog::{
|
||||
StoredProviderCatalogProvider,
|
||||
};
|
||||
use chrono::{TimeZone, Utc};
|
||||
use serde_json::{json, Value};
|
||||
use serde_json::{json, Map, Value};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use super::status as provider_status;
|
||||
@@ -32,6 +32,7 @@ pub enum AdminPoolBatchActionKind {
|
||||
Disable,
|
||||
ClearProxy,
|
||||
SetProxy,
|
||||
UpdateSettings,
|
||||
RegenerateFingerprint,
|
||||
Delete,
|
||||
}
|
||||
@@ -42,6 +43,7 @@ pub struct AdminPoolBatchActionPlan {
|
||||
pub action: AdminPoolBatchActionKind,
|
||||
pub action_label: &'static str,
|
||||
pub proxy_payload: Option<Value>,
|
||||
pub settings_payload: Option<Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
@@ -60,6 +62,10 @@ pub struct AdminPoolBatchImportRequest {
|
||||
pub keys: Vec<AdminPoolBatchImportItem>,
|
||||
#[serde(default)]
|
||||
pub proxy_node_id: Option<String>,
|
||||
#[serde(default)]
|
||||
pub api_formats: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub settings: Option<Value>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, serde::Deserialize)]
|
||||
@@ -70,6 +76,10 @@ pub struct AdminPoolBatchImportItem {
|
||||
pub api_key: String,
|
||||
#[serde(default)]
|
||||
pub auth_type: String,
|
||||
#[serde(default)]
|
||||
pub api_formats: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub settings: Option<Value>,
|
||||
}
|
||||
|
||||
fn admin_pool_reason_indicates_ban(reason: &str) -> bool {
|
||||
@@ -356,6 +366,137 @@ pub fn admin_pool_key_proxy_value(proxy_node_id: Option<&str>) -> Option<Value>
|
||||
.map(|value| json!({ "node_id": value, "enabled": true }))
|
||||
}
|
||||
|
||||
const ADMIN_POOL_KEY_SETTING_FIELDS: &[&str] = &[
|
||||
"internal_priority",
|
||||
"rpm_limit",
|
||||
"concurrent_limit",
|
||||
"cache_ttl_minutes",
|
||||
"max_probe_interval_minutes",
|
||||
"is_active",
|
||||
"note",
|
||||
"proxy_node_id",
|
||||
];
|
||||
|
||||
fn admin_pool_settings_object(payload: &Value) -> Result<&Map<String, Value>, String> {
|
||||
let settings = payload
|
||||
.as_object()
|
||||
.filter(|value| !value.is_empty())
|
||||
.ok_or_else(|| "settings payload must be a non-empty object".to_string())?;
|
||||
if let Some(field) = settings
|
||||
.keys()
|
||||
.find(|field| !ADMIN_POOL_KEY_SETTING_FIELDS.contains(&field.as_str()))
|
||||
{
|
||||
return Err(format!("Unsupported key setting: {field}"));
|
||||
}
|
||||
Ok(settings)
|
||||
}
|
||||
|
||||
fn admin_pool_setting_i64(
|
||||
settings: &Map<String, Value>,
|
||||
field: &str,
|
||||
min: i64,
|
||||
max: i64,
|
||||
) -> Result<Option<i64>, String> {
|
||||
let Some(value) = settings.get(field) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let number = value
|
||||
.as_i64()
|
||||
.ok_or_else(|| format!("{field} must be an integer"))?;
|
||||
if !(min..=max).contains(&number) {
|
||||
return Err(format!("{field} must be between {min} and {max}"));
|
||||
}
|
||||
Ok(Some(number))
|
||||
}
|
||||
|
||||
pub fn validate_admin_pool_key_settings_payload(payload: &Value) -> Result<(), String> {
|
||||
let settings = admin_pool_settings_object(payload)?;
|
||||
admin_pool_setting_i64(settings, "internal_priority", 0, i32::MAX as i64)?;
|
||||
if settings
|
||||
.get("rpm_limit")
|
||||
.is_some_and(|value| !value.is_null())
|
||||
{
|
||||
admin_pool_setting_i64(settings, "rpm_limit", 1, 10_000)?;
|
||||
}
|
||||
if settings
|
||||
.get("concurrent_limit")
|
||||
.is_some_and(|value| !value.is_null())
|
||||
{
|
||||
admin_pool_setting_i64(settings, "concurrent_limit", 0, i32::MAX as i64)?;
|
||||
}
|
||||
admin_pool_setting_i64(settings, "cache_ttl_minutes", 0, 60)?;
|
||||
admin_pool_setting_i64(settings, "max_probe_interval_minutes", 0, 32)?;
|
||||
if settings
|
||||
.get("is_active")
|
||||
.is_some_and(|value| !value.is_boolean())
|
||||
{
|
||||
return Err("is_active must be a boolean".to_string());
|
||||
}
|
||||
if settings
|
||||
.get("note")
|
||||
.is_some_and(|value| !value.is_null() && !value.is_string())
|
||||
{
|
||||
return Err("note must be a string or null".to_string());
|
||||
}
|
||||
if settings
|
||||
.get("proxy_node_id")
|
||||
.is_some_and(|value| !value.is_null() && !value.is_string())
|
||||
{
|
||||
return Err("proxy_node_id must be a string or null".to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn apply_admin_pool_key_settings(
|
||||
key: &mut StoredProviderCatalogKey,
|
||||
payload: &Value,
|
||||
) -> Result<(), String> {
|
||||
validate_admin_pool_key_settings_payload(payload)?;
|
||||
let settings = admin_pool_settings_object(payload)?;
|
||||
if let Some(value) = admin_pool_setting_i64(settings, "internal_priority", 0, i32::MAX as i64)?
|
||||
{
|
||||
key.internal_priority = value as i32;
|
||||
}
|
||||
if let Some(value) = settings.get("rpm_limit") {
|
||||
key.rpm_limit = if value.is_null() {
|
||||
None
|
||||
} else {
|
||||
Some(value.as_u64().expect("validated rpm_limit") as u32)
|
||||
};
|
||||
}
|
||||
if let Some(value) = settings.get("concurrent_limit") {
|
||||
key.concurrent_limit = if value.is_null() || value.as_i64() == Some(0) {
|
||||
None
|
||||
} else {
|
||||
Some(value.as_i64().expect("validated concurrent_limit") as i32)
|
||||
};
|
||||
}
|
||||
if let Some(value) = admin_pool_setting_i64(settings, "cache_ttl_minutes", 0, 60)? {
|
||||
key.cache_ttl_minutes = value as i32;
|
||||
}
|
||||
if let Some(value) = admin_pool_setting_i64(settings, "max_probe_interval_minutes", 0, 32)? {
|
||||
key.max_probe_interval_minutes = value as i32;
|
||||
}
|
||||
if let Some(value) = settings.get("is_active").and_then(Value::as_bool) {
|
||||
key.is_active = value;
|
||||
}
|
||||
if let Some(value) = settings.get("note") {
|
||||
key.note = value
|
||||
.as_str()
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(ToOwned::to_owned);
|
||||
}
|
||||
if let Some(value) = settings.get("proxy_node_id") {
|
||||
key.proxy = if value.is_null() {
|
||||
None
|
||||
} else {
|
||||
admin_pool_key_proxy_value(value.as_str())
|
||||
};
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn build_admin_pool_batch_action_plan(
|
||||
payload: AdminPoolBatchActionRequest,
|
||||
) -> Result<AdminPoolBatchActionPlan, String> {
|
||||
@@ -365,6 +506,7 @@ pub fn build_admin_pool_batch_action_plan(
|
||||
"disable" => (AdminPoolBatchActionKind::Disable, "disabled"),
|
||||
"clear_proxy" => (AdminPoolBatchActionKind::ClearProxy, "proxy cleared"),
|
||||
"set_proxy" => (AdminPoolBatchActionKind::SetProxy, "proxy set"),
|
||||
"update_settings" => (AdminPoolBatchActionKind::UpdateSettings, "settings updated"),
|
||||
"regenerate_fingerprint" => (
|
||||
AdminPoolBatchActionKind::RegenerateFingerprint,
|
||||
"fingerprint regenerated",
|
||||
@@ -372,7 +514,7 @@ pub fn build_admin_pool_batch_action_plan(
|
||||
"delete" => (AdminPoolBatchActionKind::Delete, "deleted"),
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"Invalid action: {action}. Supported locally: enable, disable, clear_proxy, set_proxy, regenerate_fingerprint, delete"
|
||||
"Invalid action: {action}. Supported locally: enable, disable, clear_proxy, set_proxy, update_settings, regenerate_fingerprint, delete"
|
||||
));
|
||||
}
|
||||
};
|
||||
@@ -389,9 +531,10 @@ pub fn build_admin_pool_batch_action_plan(
|
||||
return Err("key_ids should not be empty".to_string());
|
||||
}
|
||||
|
||||
let action_payload = payload.payload;
|
||||
let proxy_payload = if action_kind == AdminPoolBatchActionKind::SetProxy {
|
||||
match payload.payload {
|
||||
Some(Value::Object(map)) if !map.is_empty() => Some(Value::Object(map)),
|
||||
match action_payload.as_ref() {
|
||||
Some(Value::Object(map)) if !map.is_empty() => Some(Value::Object(map.clone())),
|
||||
_ => {
|
||||
return Err(
|
||||
"set_proxy action requires a non-empty payload with proxy config".to_string(),
|
||||
@@ -401,12 +544,21 @@ pub fn build_admin_pool_batch_action_plan(
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let settings_payload = if action_kind == AdminPoolBatchActionKind::UpdateSettings {
|
||||
let settings = action_payload
|
||||
.ok_or_else(|| "update_settings action requires a settings payload".to_string())?;
|
||||
validate_admin_pool_key_settings_payload(&settings)?;
|
||||
Some(settings)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Ok(AdminPoolBatchActionPlan {
|
||||
key_ids,
|
||||
action: action_kind,
|
||||
action_label,
|
||||
proxy_payload,
|
||||
settings_payload,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -492,7 +644,10 @@ pub fn build_admin_pool_selection_payload(keys: &[StoredProviderCatalogKey]) ->
|
||||
mod tests {
|
||||
use super::{
|
||||
admin_pool_key_account_quota_exhausted, admin_pool_key_is_known_banned,
|
||||
build_admin_pool_key_payload, AdminPoolKeyPayloadContext,
|
||||
apply_admin_pool_key_settings, build_admin_pool_batch_action_plan,
|
||||
build_admin_pool_batch_import_key_record, build_admin_pool_key_payload,
|
||||
resolve_admin_pool_key_settings, validate_admin_pool_key_settings_payload,
|
||||
AdminPoolBatchActionKind, AdminPoolBatchActionRequest, AdminPoolKeyPayloadContext,
|
||||
};
|
||||
use aether_data_contracts::repository::provider_catalog::StoredProviderCatalogKey;
|
||||
use serde_json::json;
|
||||
@@ -698,6 +853,108 @@ mod tests {
|
||||
assert_eq!(payload["scheduling_reason"], json!("available"));
|
||||
assert_eq!(payload["scheduling_label"], json!("可用"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_and_applies_shared_key_settings() {
|
||||
let settings = json!({
|
||||
"internal_priority": 12,
|
||||
"rpm_limit": 600,
|
||||
"concurrent_limit": 8,
|
||||
"cache_ttl_minutes": 10,
|
||||
"max_probe_interval_minutes": 16,
|
||||
"is_active": false,
|
||||
"note": " imported ",
|
||||
"proxy_node_id": "proxy-1"
|
||||
});
|
||||
let mut key = sample_key(None);
|
||||
|
||||
validate_admin_pool_key_settings_payload(&settings).expect("settings should validate");
|
||||
apply_admin_pool_key_settings(&mut key, &settings).expect("settings should apply");
|
||||
|
||||
assert_eq!(key.internal_priority, 12);
|
||||
assert_eq!(key.rpm_limit, Some(600));
|
||||
assert_eq!(key.concurrent_limit, Some(8));
|
||||
assert_eq!(key.cache_ttl_minutes, 10);
|
||||
assert_eq!(key.max_probe_interval_minutes, 16);
|
||||
assert!(!key.is_active);
|
||||
assert_eq!(key.note.as_deref(), Some("imported"));
|
||||
assert_eq!(
|
||||
key.proxy,
|
||||
Some(json!({ "node_id": "proxy-1", "enabled": true }))
|
||||
);
|
||||
|
||||
assert!(validate_admin_pool_key_settings_payload(&json!({ "rpm_limit": 0 })).is_err());
|
||||
assert!(validate_admin_pool_key_settings_payload(&json!({ "unknown": true })).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_update_settings_action_plan() {
|
||||
let settings = json!({ "rpm_limit": null, "proxy_node_id": "proxy-1" });
|
||||
let plan = build_admin_pool_batch_action_plan(AdminPoolBatchActionRequest {
|
||||
key_ids: vec![
|
||||
"key-2".to_string(),
|
||||
"key-1".to_string(),
|
||||
"key-1".to_string(),
|
||||
],
|
||||
action: "update_settings".to_string(),
|
||||
payload: Some(settings.clone()),
|
||||
})
|
||||
.expect("action plan should build");
|
||||
|
||||
assert_eq!(plan.action, AdminPoolBatchActionKind::UpdateSettings);
|
||||
assert_eq!(plan.key_ids, vec!["key-1", "key-2"]);
|
||||
assert_eq!(plan.settings_payload, Some(settings));
|
||||
assert!(plan.proxy_payload.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_import_record_applies_shared_settings() {
|
||||
let record = build_admin_pool_batch_import_key_record(
|
||||
"key-1".to_string(),
|
||||
"provider-1".to_string(),
|
||||
"1".to_string(),
|
||||
"api_key".to_string(),
|
||||
vec!["openai:chat".to_string()],
|
||||
"encrypted".to_string(),
|
||||
None,
|
||||
Some(&json!({
|
||||
"rpm_limit": 900,
|
||||
"cache_ttl_minutes": 0,
|
||||
"max_probe_interval_minutes": 4,
|
||||
"is_active": false
|
||||
})),
|
||||
1_700_000_000,
|
||||
)
|
||||
.expect("record should build");
|
||||
|
||||
assert_eq!(record.name, "1");
|
||||
assert_eq!(record.rpm_limit, Some(900));
|
||||
assert_eq!(record.cache_ttl_minutes, 0);
|
||||
assert_eq!(record.max_probe_interval_minutes, 4);
|
||||
assert!(!record.is_active);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batch_import_item_settings_override_shared_values() {
|
||||
let resolved = resolve_admin_pool_key_settings(
|
||||
Some(&json!({
|
||||
"rpm_limit": 900,
|
||||
"cache_ttl_minutes": 5,
|
||||
"is_active": true
|
||||
})),
|
||||
Some(&json!({
|
||||
"rpm_limit": 120,
|
||||
"is_active": false
|
||||
})),
|
||||
)
|
||||
.expect("item settings should override shared values")
|
||||
.expect("resolved settings should exist");
|
||||
|
||||
assert_eq!(resolved["rpm_limit"], 120);
|
||||
assert_eq!(resolved["cache_ttl_minutes"], 5);
|
||||
assert_eq!(resolved["is_active"], false);
|
||||
assert!(resolve_admin_pool_key_settings(None, Some(&json!([]))).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_admin_pool_key_payload(
|
||||
@@ -827,6 +1084,25 @@ pub fn build_admin_pool_overview_payload(
|
||||
json!({ "items": items })
|
||||
}
|
||||
|
||||
pub fn resolve_admin_pool_key_settings(
|
||||
shared: Option<&Value>,
|
||||
overrides: Option<&Value>,
|
||||
) -> Result<Option<Value>, String> {
|
||||
let mut resolved = Map::new();
|
||||
for settings in [shared, overrides].into_iter().flatten() {
|
||||
let Value::Object(values) = settings else {
|
||||
return Err("settings payload must be an object".to_string());
|
||||
};
|
||||
resolved.extend(values.clone());
|
||||
}
|
||||
if resolved.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let resolved = Value::Object(resolved);
|
||||
validate_admin_pool_key_settings_payload(&resolved)?;
|
||||
Ok(Some(resolved))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn build_admin_pool_batch_import_key_record(
|
||||
id: String,
|
||||
@@ -836,6 +1112,7 @@ pub fn build_admin_pool_batch_import_key_record(
|
||||
api_formats: Vec<String>,
|
||||
encrypted_api_key: String,
|
||||
proxy: Option<Value>,
|
||||
settings: Option<&Value>,
|
||||
now_unix_secs: u64,
|
||||
) -> Result<StoredProviderCatalogKey, String> {
|
||||
let mut record = StoredProviderCatalogKey::new(id, provider_id, name, auth_type, None, true)
|
||||
@@ -859,6 +1136,9 @@ pub fn build_admin_pool_batch_import_key_record(
|
||||
record.total_response_time_ms = Some(0);
|
||||
record.health_by_format = Some(json!({}));
|
||||
record.circuit_breaker_by_format = Some(json!({}));
|
||||
if let Some(settings) = settings {
|
||||
apply_admin_pool_key_settings(&mut record, settings)?;
|
||||
}
|
||||
record.created_at_unix_ms = Some(now_unix_secs);
|
||||
record.updated_at_unix_secs = Some(now_unix_secs);
|
||||
Ok(record)
|
||||
|
||||
@@ -787,6 +787,10 @@ fn parse_codex_reset_credit_timestamp(value: Option<&serde_json::Value>) -> Opti
|
||||
}
|
||||
|
||||
fn codex_reset_credit_detail_items(value: &serde_json::Value) -> Option<&Vec<serde_json::Value>> {
|
||||
if let Some(items) = value.as_array() {
|
||||
return Some(items);
|
||||
}
|
||||
|
||||
first_json_value_by_paths(
|
||||
value,
|
||||
&[
|
||||
@@ -799,6 +803,10 @@ fn codex_reset_credit_detail_items(value: &serde_json::Value) -> Option<&Vec<ser
|
||||
&["rateLimitResetCredits", "data"],
|
||||
&["reset_credits", "credits"],
|
||||
&["resetCredits", "credits"],
|
||||
&["rate_limit_reset_credits"],
|
||||
&["rateLimitResetCredits"],
|
||||
&["reset_credits"],
|
||||
&["resetCredits"],
|
||||
],
|
||||
)
|
||||
.and_then(serde_json::Value::as_array)
|
||||
@@ -833,10 +841,28 @@ fn codex_reset_credit_status(
|
||||
.find_map(|key| coerce_json_string(object.get(*key)))
|
||||
}
|
||||
|
||||
fn codex_reset_credit_is_available(object: &serde_json::Map<String, serde_json::Value>) -> bool {
|
||||
let reset_type = ["reset_type", "resetType"]
|
||||
.iter()
|
||||
.find_map(|key| coerce_json_string(object.get(*key)));
|
||||
if reset_type
|
||||
.as_deref()
|
||||
.is_some_and(|value| !value.trim().eq_ignore_ascii_case("codex_rate_limits"))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
codex_reset_credit_status(object).is_none_or(|status| {
|
||||
let status = status.trim();
|
||||
status.eq_ignore_ascii_case("available") || status.eq_ignore_ascii_case("active")
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_codex_reset_credit_detail_item(item: &serde_json::Value) -> Option<serde_json::Value> {
|
||||
let object = item.as_object()?;
|
||||
let id = codex_reset_credit_id(object)?;
|
||||
let display_key = codex_reset_credit_display_key(&id)?;
|
||||
if !codex_reset_credit_is_available(object) {
|
||||
return None;
|
||||
}
|
||||
let expires_at = parse_codex_reset_credit_timestamp(
|
||||
object
|
||||
.get("expires_at")
|
||||
@@ -853,8 +879,12 @@ fn parse_codex_reset_credit_detail_item(item: &serde_json::Value) -> Option<serd
|
||||
);
|
||||
|
||||
let mut out = serde_json::Map::new();
|
||||
out.insert("id".to_string(), json!(id));
|
||||
out.insert("display_key".to_string(), json!(display_key));
|
||||
if let Some(id) = codex_reset_credit_id(object) {
|
||||
if let Some(display_key) = codex_reset_credit_display_key(&id) {
|
||||
out.insert("display_key".to_string(), json!(display_key));
|
||||
}
|
||||
out.insert("id".to_string(), json!(id));
|
||||
}
|
||||
if let Some(status) = codex_reset_credit_status(object) {
|
||||
out.insert("status".to_string(), json!(status));
|
||||
}
|
||||
@@ -869,8 +899,35 @@ pub fn parse_codex_wham_reset_credits_detail_response(
|
||||
value: &serde_json::Value,
|
||||
updated_at_unix_secs: u64,
|
||||
) -> Option<serde_json::Value> {
|
||||
value.as_object()?;
|
||||
let mut credits = codex_reset_credit_detail_items(value)
|
||||
let root = value.as_object();
|
||||
let detail_items = codex_reset_credit_detail_items(value);
|
||||
if root.is_none() && detail_items.is_none() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let available_item_count = detail_items
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(serde_json::Value::as_object)
|
||||
.filter(|item| codex_reset_credit_is_available(item))
|
||||
.count();
|
||||
let available_count = root
|
||||
.and_then(codex_reset_credits_available_count)
|
||||
.or_else(|| {
|
||||
root.and_then(|root| {
|
||||
[
|
||||
"available_count",
|
||||
"availableCount",
|
||||
"available",
|
||||
"remaining",
|
||||
"count",
|
||||
]
|
||||
.iter()
|
||||
.find_map(|key| root.get(*key).and_then(coerce_json_u64))
|
||||
})
|
||||
})
|
||||
.or_else(|| detail_items.and_then(|_| u64::try_from(available_item_count).ok()));
|
||||
let mut credits = detail_items
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(parse_codex_reset_credit_detail_item)
|
||||
@@ -881,10 +938,10 @@ pub fn parse_codex_wham_reset_credits_detail_response(
|
||||
.unwrap_or(u64::MAX)
|
||||
});
|
||||
|
||||
let detail_status = if credits.is_empty() {
|
||||
"empty"
|
||||
} else {
|
||||
let detail_status = if available_count.is_some_and(|count| count > 0) {
|
||||
"available"
|
||||
} else {
|
||||
"empty"
|
||||
};
|
||||
let mut reset_credits = serde_json::Map::new();
|
||||
reset_credits.insert("updated_at".to_string(), json!(updated_at_unix_secs));
|
||||
@@ -892,20 +949,8 @@ pub fn parse_codex_wham_reset_credits_detail_response(
|
||||
reset_credits.insert("detail_status".to_string(), json!(detail_status));
|
||||
reset_credits.insert("credits".to_string(), serde_json::Value::Array(credits));
|
||||
|
||||
if let Some(root) = value.as_object() {
|
||||
if let Some(available_count) = codex_reset_credits_available_count(root).or_else(|| {
|
||||
[
|
||||
"available_count",
|
||||
"availableCount",
|
||||
"available",
|
||||
"remaining",
|
||||
"count",
|
||||
]
|
||||
.iter()
|
||||
.find_map(|key| root.get(*key).and_then(coerce_json_u64))
|
||||
}) {
|
||||
reset_credits.insert("available_count".to_string(), json!(available_count));
|
||||
}
|
||||
if let Some(available_count) = available_count {
|
||||
reset_credits.insert("available_count".to_string(), json!(available_count));
|
||||
}
|
||||
|
||||
Some(json!({ "reset_credits": reset_credits }))
|
||||
@@ -2534,6 +2579,61 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_codex_reset_credit_detail_without_explicit_count_or_ids() {
|
||||
let parsed = parse_codex_wham_reset_credits_detail_response(
|
||||
&json!({
|
||||
"rate_limit_reset_credits": [
|
||||
{
|
||||
"resetType": "codex_rate_limits",
|
||||
"status": "available",
|
||||
"expiresAt": "2030-01-02T00:00:00Z"
|
||||
},
|
||||
{
|
||||
"reset_type": "codex_rate_limits",
|
||||
"status": "available"
|
||||
},
|
||||
{
|
||||
"reset_type": "codex_rate_limits",
|
||||
"status": "redeemed",
|
||||
"expires_at": "2030-01-03T00:00:00Z"
|
||||
}
|
||||
]
|
||||
}),
|
||||
1_777_000_000,
|
||||
)
|
||||
.expect("detail array should parse");
|
||||
|
||||
assert_eq!(
|
||||
parsed.pointer("/reset_credits/available_count"),
|
||||
Some(&json!(2u64))
|
||||
);
|
||||
assert_eq!(
|
||||
parsed.pointer("/reset_credits/credits/0/expires_at"),
|
||||
Some(&json!(1_893_542_400u64))
|
||||
);
|
||||
assert_eq!(parsed.pointer("/reset_credits/credits/0/id"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_codex_reset_credit_detail_from_top_level_array() {
|
||||
let parsed = parse_codex_wham_reset_credits_detail_response(
|
||||
&json!([
|
||||
{
|
||||
"status": "available",
|
||||
"expires_at": "2030-01-04T00:00:00Z"
|
||||
}
|
||||
]),
|
||||
1_777_000_000,
|
||||
)
|
||||
.expect("top-level detail array should parse");
|
||||
|
||||
assert_eq!(
|
||||
parsed.pointer("/reset_credits/available_count"),
|
||||
Some(&json!(1u64))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalizes_codex_reset_credit_consume_outcome() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -337,9 +337,39 @@ export interface PoolBatchAction {
|
||||
| 'delete'
|
||||
| 'clear_proxy'
|
||||
| 'set_proxy'
|
||||
| 'update_settings'
|
||||
payload?: Record<string, unknown> | null
|
||||
}
|
||||
|
||||
export interface PoolKeySettingsPatch {
|
||||
internal_priority?: number
|
||||
rpm_limit?: number | null
|
||||
concurrent_limit?: number | null
|
||||
cache_ttl_minutes?: number
|
||||
max_probe_interval_minutes?: number
|
||||
is_active?: boolean
|
||||
note?: string | null
|
||||
proxy_node_id?: string | null
|
||||
}
|
||||
|
||||
export interface PoolBatchImportRequest {
|
||||
keys: Array<{
|
||||
name: string
|
||||
api_key: string
|
||||
auth_type: 'api_key' | 'bearer'
|
||||
api_formats?: string[]
|
||||
settings?: PoolKeySettingsPatch
|
||||
}>
|
||||
api_formats?: string[]
|
||||
settings?: PoolKeySettingsPatch
|
||||
}
|
||||
|
||||
export interface PoolBatchImportResult {
|
||||
imported: number
|
||||
skipped: number
|
||||
errors: Array<{ index: number; reason: string }>
|
||||
}
|
||||
|
||||
interface PoolReadOptions {
|
||||
cacheTtlMs?: number
|
||||
}
|
||||
@@ -442,6 +472,18 @@ export async function batchActionPoolKeys(
|
||||
return response.data
|
||||
}
|
||||
|
||||
export async function batchImportPoolKeys(
|
||||
providerId: string,
|
||||
body: PoolBatchImportRequest,
|
||||
): Promise<PoolBatchImportResult> {
|
||||
const response = await client.post<PoolBatchImportResult>(
|
||||
`/api/admin/pool/${providerId}/keys/batch-import`,
|
||||
body,
|
||||
{ timeout: POOL_BATCH_ACTION_TIMEOUT_MS },
|
||||
)
|
||||
return response.data
|
||||
}
|
||||
|
||||
export interface BatchDeleteTaskStatus {
|
||||
task_id: string
|
||||
status: 'pending' | 'running' | 'completed' | 'failed'
|
||||
|
||||
@@ -210,30 +210,228 @@
|
||||
<div class="text-xs font-medium text-foreground">
|
||||
执行动作
|
||||
</div>
|
||||
<div class="text-[11px] text-muted-foreground">
|
||||
代理节点(仅“配置代理”动作生效)
|
||||
</div>
|
||||
<ProxyNodeSelect
|
||||
:model-value="proxyNodeIdForAction"
|
||||
trigger-class="h-8"
|
||||
@update:model-value="(v: string) => proxyNodeIdForAction = v"
|
||||
/>
|
||||
<div class="grid gap-2 sm:grid-cols-2 lg:grid-cols-1">
|
||||
<Button
|
||||
v-for="item in ACTION_OPTIONS"
|
||||
:key="item.value"
|
||||
class="h-8 w-full px-3 text-xs"
|
||||
class="h-9 w-full px-3 text-xs"
|
||||
:variant="getActionButtonVariant(item)"
|
||||
:disabled="!canExecuteSpecifiedAction(item.value)"
|
||||
@click="confirmAndExecuteAction(item.value)"
|
||||
:disabled="!canSelectAction(item.value)"
|
||||
@click="handleActionButtonClick(item.value)"
|
||||
>
|
||||
{{ item.label }}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="selectedAction === 'set_proxy'"
|
||||
class="space-y-2 border-t border-border/60 pt-3"
|
||||
>
|
||||
<div class="text-[11px] text-muted-foreground">选择要绑定的代理节点</div>
|
||||
<ProxyNodeSelect
|
||||
:model-value="proxyNodeIdForAction"
|
||||
trigger-class="h-9"
|
||||
@update:model-value="(v: string) => proxyNodeIdForAction = v"
|
||||
/>
|
||||
<Button
|
||||
class="h-9 w-full text-xs"
|
||||
:disabled="!canExecuteSpecifiedAction('set_proxy')"
|
||||
@click="confirmAndExecuteAction('set_proxy')"
|
||||
>
|
||||
应用代理设置
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section
|
||||
v-if="selectedAction === 'update_settings'"
|
||||
class="space-y-3 rounded-lg border border-primary/25 bg-primary/5 p-3 sm:p-4"
|
||||
>
|
||||
<div class="flex flex-wrap items-start justify-between gap-2">
|
||||
<div>
|
||||
<h3 class="text-sm font-semibold">更多设置</h3>
|
||||
<p class="text-[11px] text-muted-foreground">仅更新已勾选字段,未勾选配置保持不变</p>
|
||||
</div>
|
||||
<Badge variant="outline" class="tabular-nums">已选 {{ selectedSettingsCount }} 项</Badge>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<div class="space-y-2 rounded-md border bg-background p-3">
|
||||
<div class="flex min-h-6 items-center gap-2">
|
||||
<Checkbox
|
||||
:checked="settingsSelection.internal_priority"
|
||||
@update:checked="settingsSelection.internal_priority = $event === true"
|
||||
/>
|
||||
<Label class="text-xs">优先级</Label>
|
||||
</div>
|
||||
<Input
|
||||
v-model.number="settingsDraft.internal_priority"
|
||||
type="number"
|
||||
min="0"
|
||||
class="h-9"
|
||||
:disabled="!settingsSelection.internal_priority"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2 rounded-md border bg-background p-3">
|
||||
<div class="flex min-h-6 items-center gap-2">
|
||||
<Checkbox
|
||||
:checked="settingsSelection.rpm_limit"
|
||||
@update:checked="settingsSelection.rpm_limit = $event === true"
|
||||
/>
|
||||
<Label class="text-xs">RPM 限制</Label>
|
||||
</div>
|
||||
<Input
|
||||
:model-value="settingsDraft.rpm_limit ?? ''"
|
||||
type="number"
|
||||
min="1"
|
||||
max="10000"
|
||||
class="h-9"
|
||||
placeholder="留空为自适应"
|
||||
:disabled="!settingsSelection.rpm_limit"
|
||||
@update:model-value="settingsDraft.rpm_limit = parseNullableNumberInput($event, { min: 1, max: 10000 })"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2 rounded-md border bg-background p-3">
|
||||
<div class="flex min-h-6 items-center gap-2">
|
||||
<Checkbox
|
||||
:checked="settingsSelection.concurrent_limit"
|
||||
@update:checked="settingsSelection.concurrent_limit = $event === true"
|
||||
/>
|
||||
<Label class="text-xs">并发请求上限</Label>
|
||||
</div>
|
||||
<Input
|
||||
:model-value="settingsDraft.concurrent_limit ?? ''"
|
||||
type="number"
|
||||
min="0"
|
||||
class="h-9"
|
||||
placeholder="留空为不限制"
|
||||
:disabled="!settingsSelection.concurrent_limit"
|
||||
@update:model-value="settingsDraft.concurrent_limit = parseNullableNumberInput($event, { min: 0 })"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2 rounded-md border bg-background p-3">
|
||||
<div class="flex min-h-6 items-center gap-2">
|
||||
<Checkbox
|
||||
:checked="settingsSelection.cache_ttl_minutes"
|
||||
@update:checked="settingsSelection.cache_ttl_minutes = $event === true"
|
||||
/>
|
||||
<Label class="text-xs">缓存 TTL(分钟)</Label>
|
||||
</div>
|
||||
<Input
|
||||
:model-value="settingsDraft.cache_ttl_minutes"
|
||||
type="number"
|
||||
min="0"
|
||||
max="60"
|
||||
class="h-9"
|
||||
:disabled="!settingsSelection.cache_ttl_minutes"
|
||||
@update:model-value="settingsDraft.cache_ttl_minutes = parseNumberInput($event, { min: 0, max: 60 }) ?? 5"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2 rounded-md border bg-background p-3">
|
||||
<div class="flex min-h-6 items-center gap-2">
|
||||
<Checkbox
|
||||
:checked="settingsSelection.max_probe_interval_minutes"
|
||||
@update:checked="settingsSelection.max_probe_interval_minutes = $event === true"
|
||||
/>
|
||||
<Label class="text-xs">熔断探测(分钟)</Label>
|
||||
</div>
|
||||
<Input
|
||||
:model-value="settingsDraft.max_probe_interval_minutes"
|
||||
type="number"
|
||||
min="0"
|
||||
max="32"
|
||||
class="h-9"
|
||||
:disabled="!settingsSelection.max_probe_interval_minutes"
|
||||
@update:model-value="settingsDraft.max_probe_interval_minutes = parseNumberInput($event, { min: 0, max: 32 }) ?? 32"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2 rounded-md border bg-background p-3">
|
||||
<div class="flex min-h-6 items-center gap-2">
|
||||
<Checkbox
|
||||
:checked="settingsSelection.is_active"
|
||||
@update:checked="settingsSelection.is_active = $event === true"
|
||||
/>
|
||||
<Label class="text-xs">启用状态</Label>
|
||||
</div>
|
||||
<Select v-model="settingsStatus" :disabled="!settingsSelection.is_active">
|
||||
<SelectTrigger class="h-9"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="enabled">启用</SelectItem>
|
||||
<SelectItem value="disabled">停用</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2 rounded-md border bg-background p-3 sm:col-span-2">
|
||||
<div class="flex min-h-6 items-center gap-2">
|
||||
<Checkbox
|
||||
:checked="settingsSelection.proxy_node_id"
|
||||
@update:checked="settingsSelection.proxy_node_id = $event === true"
|
||||
/>
|
||||
<Label class="text-xs">账号代理</Label>
|
||||
</div>
|
||||
<div class="grid gap-2 sm:grid-cols-[9rem_minmax(0,1fr)]">
|
||||
<Select v-model="settingsDraft.proxy_mode" :disabled="!settingsSelection.proxy_node_id">
|
||||
<SelectTrigger class="h-9"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="set">设置节点</SelectItem>
|
||||
<SelectItem value="clear">清除代理</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<ProxyNodeSelect
|
||||
v-if="settingsDraft.proxy_mode === 'set'"
|
||||
:model-value="settingsDraft.proxy_node_id"
|
||||
trigger-class="h-9"
|
||||
:class="!settingsSelection.proxy_node_id ? 'pointer-events-none opacity-50' : ''"
|
||||
@update:model-value="(value: string) => settingsDraft.proxy_node_id = value"
|
||||
/>
|
||||
<div
|
||||
v-else
|
||||
class="flex h-9 items-center rounded-md border bg-muted/30 px-3 text-xs text-muted-foreground"
|
||||
>
|
||||
回退到 Provider 默认代理
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2 rounded-md border bg-background p-3">
|
||||
<div class="flex min-h-6 items-center gap-2">
|
||||
<Checkbox
|
||||
:checked="settingsSelection.note"
|
||||
@update:checked="settingsSelection.note = $event === true"
|
||||
/>
|
||||
<Label class="text-xs">备注</Label>
|
||||
</div>
|
||||
<Input
|
||||
v-model="settingsDraft.note"
|
||||
class="h-9"
|
||||
placeholder="留空清除备注"
|
||||
:disabled="!settingsSelection.note"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
<p class="min-h-5 text-xs text-destructive">
|
||||
{{ settingsErrors[0] || '' }}
|
||||
</p>
|
||||
<Button
|
||||
class="min-h-10 sm:min-w-36"
|
||||
:disabled="!canExecuteSpecifiedAction('update_settings')"
|
||||
@click="confirmAndExecuteAction('update_settings')"
|
||||
>
|
||||
应用更多设置
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div
|
||||
v-if="executing && progressTotal > 0"
|
||||
class="space-y-1"
|
||||
@@ -270,8 +468,20 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue'
|
||||
import { Dialog, Button, Input, Checkbox, Badge } from '@/components/ui'
|
||||
import { computed, onBeforeUnmount, reactive, ref, watch } from 'vue'
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
Checkbox,
|
||||
Dialog,
|
||||
Input,
|
||||
Label,
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui'
|
||||
import ProxyNodeSelect from '@/features/providers/components/ProxyNodeSelect.vue'
|
||||
import { RefreshCw, ChevronLeft, ChevronRight, ChevronsLeft, ChevronsRight } from 'lucide-vue-next'
|
||||
import { useToast } from '@/composables/useToast'
|
||||
@@ -302,6 +512,13 @@ import {
|
||||
} from '@/utils/providerKeyStatus'
|
||||
import { getQuotaDisplayText } from '@/utils/providerKeyQuota'
|
||||
import { runChunkedBatchAction } from '@/utils/batchAction'
|
||||
import { parseNullableNumberInput, parseNumberInput } from '@/utils/form'
|
||||
import {
|
||||
buildPoolKeySettingsPatch,
|
||||
createPoolKeyBatchSettingSelection,
|
||||
createPoolKeyBatchSettingsDraft,
|
||||
validatePoolKeyBatchSettings,
|
||||
} from '@/features/pool/utils/poolKeyBatchSettings'
|
||||
|
||||
type QuickSelectorValue =
|
||||
| 'banned'
|
||||
@@ -322,6 +539,7 @@ type BatchActionValue =
|
||||
| 'refresh_quota'
|
||||
| 'clear_proxy'
|
||||
| 'set_proxy'
|
||||
| 'update_settings'
|
||||
| 'enable'
|
||||
| 'disable'
|
||||
|
||||
@@ -373,6 +591,7 @@ const ACTION_OPTIONS: BatchActionOption[] = [
|
||||
{ value: 'refresh_quota', label: '刷新额度', hint: '调用额度刷新接口,适合核对最新配额状态。' },
|
||||
{ value: 'refresh_oauth', label: '刷新 OAuth', hint: '仅对 OAuth 账号有效,非 OAuth 账号会自动跳过。' },
|
||||
{ value: 'set_proxy', label: '配置代理', hint: '为选中账号绑定独立代理节点。' },
|
||||
{ value: 'update_settings', label: '更多设置', hint: '选择性修改 RPM、并发、熔断、备注和代理等配置。' },
|
||||
{ value: 'clear_proxy', label: '清除代理', hint: '移除账号独立代理,回退到提供商默认代理。' },
|
||||
{ value: 'enable', label: '启用', hint: '批量启用账号,恢复可调度状态。' },
|
||||
{ value: 'disable', label: '禁用', hint: '批量禁用账号,保留数据但停止调度。' },
|
||||
@@ -394,6 +613,12 @@ const selectAllFiltered = ref(false)
|
||||
const searchText = ref('')
|
||||
const selectedAction = ref<BatchActionValue>('refresh_quota')
|
||||
const proxyNodeIdForAction = ref('')
|
||||
const settingsSelection = reactive(createPoolKeyBatchSettingSelection())
|
||||
const settingsDraft = reactive(createPoolKeyBatchSettingsDraft())
|
||||
const settingsStatus = computed({
|
||||
get: () => settingsDraft.is_active ? 'enabled' : 'disabled',
|
||||
set: (value: string) => { settingsDraft.is_active = value === 'enabled' },
|
||||
})
|
||||
const lastResultMessage = ref('')
|
||||
const progressTotal = ref(0)
|
||||
const progressDone = ref(0)
|
||||
@@ -448,6 +673,8 @@ const isCurrentPageFullySelected = computed(() => {
|
||||
})
|
||||
const canClearSelection = computed(() => selectAllFiltered.value || selectedKeyIds.value.length > 0)
|
||||
const activeQuickSelectorSet = computed(() => new Set(activeQuickSelectors.value))
|
||||
const settingsErrors = computed(() => validatePoolKeyBatchSettings(settingsSelection, settingsDraft))
|
||||
const selectedSettingsCount = computed(() => Object.values(settingsSelection).filter(Boolean).length)
|
||||
|
||||
function sanitizeFileNamePart(value: unknown, fallback: string): string {
|
||||
const sanitized = String(value || '')
|
||||
@@ -706,14 +933,33 @@ function toggleQuickSelector(selector: QuickSelectorValue): void {
|
||||
function canExecuteSpecifiedAction(action: BatchActionValue): boolean {
|
||||
if (executing.value || loading.value || selectedCount.value === 0) return false
|
||||
if (action === 'set_proxy') return Boolean(proxyNodeIdForAction.value)
|
||||
if (action === 'update_settings') return settingsErrors.value.length === 0
|
||||
return true
|
||||
}
|
||||
|
||||
function canSelectAction(action: BatchActionValue): boolean {
|
||||
if (executing.value || loading.value) return false
|
||||
if (action === 'set_proxy' || action === 'update_settings') return true
|
||||
return selectedCount.value > 0
|
||||
}
|
||||
|
||||
function getActionButtonVariant(option: BatchActionOption): 'default' | 'destructive' | 'outline' {
|
||||
if (option.destructive) return 'destructive'
|
||||
if (
|
||||
option.value === selectedAction.value
|
||||
&& (option.value === 'set_proxy' || option.value === 'update_settings')
|
||||
) return 'default'
|
||||
return 'outline'
|
||||
}
|
||||
|
||||
function handleActionButtonClick(action: BatchActionValue): void {
|
||||
if (action === 'set_proxy' || action === 'update_settings') {
|
||||
selectedAction.value = action
|
||||
return
|
||||
}
|
||||
void confirmAndExecuteAction(action)
|
||||
}
|
||||
|
||||
async function confirmAndExecuteAction(action: BatchActionValue): Promise<void> {
|
||||
selectedAction.value = action
|
||||
if (selectedCount.value === 0) {
|
||||
@@ -724,6 +970,10 @@ async function confirmAndExecuteAction(action: BatchActionValue): Promise<void>
|
||||
warning('请先选择代理节点')
|
||||
return
|
||||
}
|
||||
if (action === 'update_settings' && settingsErrors.value.length > 0) {
|
||||
warning(settingsErrors.value[0])
|
||||
return
|
||||
}
|
||||
if (!canExecuteSpecifiedAction(action)) return
|
||||
|
||||
const actionOption = ACTION_OPTIONS.find((item) => item.value === action)
|
||||
@@ -809,6 +1059,10 @@ async function executeAction(actionOverride?: BatchActionValue): Promise<void> {
|
||||
warning('请先选择代理节点')
|
||||
return
|
||||
}
|
||||
if (selectedAction.value === 'update_settings' && settingsErrors.value.length > 0) {
|
||||
warning(settingsErrors.value[0])
|
||||
return
|
||||
}
|
||||
|
||||
executing.value = true
|
||||
let successCount = 0
|
||||
@@ -930,7 +1184,7 @@ async function executeAction(actionOverride?: BatchActionValue): Promise<void> {
|
||||
|
||||
progressDone.value = Math.min(i + BATCH_SIZE, targetIds.length)
|
||||
}
|
||||
} else if (['enable', 'disable', 'clear_proxy', 'set_proxy'].includes(selectedAction.value)) {
|
||||
} else if (['enable', 'disable', 'clear_proxy', 'set_proxy', 'update_settings'].includes(selectedAction.value)) {
|
||||
const targetIds = selectedKeys.map((key) => key.key_id)
|
||||
const BATCH_SIZE = 2000
|
||||
const totalBatches = Math.ceil(targetIds.length / BATCH_SIZE)
|
||||
@@ -944,12 +1198,14 @@ async function executeAction(actionOverride?: BatchActionValue): Promise<void> {
|
||||
|
||||
const payload = selectedAction.value === 'set_proxy'
|
||||
? { node_id: proxyNodeIdForAction.value, enabled: true }
|
||||
: undefined
|
||||
: selectedAction.value === 'update_settings'
|
||||
? buildPoolKeySettingsPatch(settingsSelection, settingsDraft)
|
||||
: undefined
|
||||
|
||||
try {
|
||||
const result = await batchActionPoolKeys(props.providerId, {
|
||||
key_ids: batch,
|
||||
action: selectedAction.value as 'enable' | 'disable' | 'clear_proxy' | 'set_proxy',
|
||||
action: selectedAction.value as 'enable' | 'disable' | 'clear_proxy' | 'set_proxy' | 'update_settings',
|
||||
...(payload ? { payload } : {}),
|
||||
})
|
||||
successCount += result.affected
|
||||
@@ -1049,6 +1305,8 @@ watch(
|
||||
activeQuickSelectors.value = []
|
||||
selectedAction.value = 'refresh_quota'
|
||||
proxyNodeIdForAction.value = ''
|
||||
Object.assign(settingsSelection, createPoolKeyBatchSettingSelection())
|
||||
Object.assign(settingsDraft, createPoolKeyBatchSettingsDraft())
|
||||
resetSelection(true)
|
||||
filteredTotal.value = 0
|
||||
pageKeys.value = []
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
buildPoolKeySettingsPatch,
|
||||
createPoolKeyBatchSettingSelection,
|
||||
createPoolKeyBatchSettingsDraft,
|
||||
validatePoolKeyBatchSettings,
|
||||
} from '../poolKeyBatchSettings'
|
||||
|
||||
describe('pool key batch settings', () => {
|
||||
it('only includes explicitly selected fields', () => {
|
||||
const selection = createPoolKeyBatchSettingSelection()
|
||||
const draft = createPoolKeyBatchSettingsDraft()
|
||||
selection.rpm_limit = true
|
||||
selection.proxy_node_id = true
|
||||
draft.rpm_limit = 800
|
||||
draft.proxy_mode = 'clear'
|
||||
|
||||
expect(buildPoolKeySettingsPatch(selection, draft)).toEqual({
|
||||
rpm_limit: 800,
|
||||
proxy_node_id: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('supports adaptive RPM and unlimited concurrency', () => {
|
||||
const selection = createPoolKeyBatchSettingSelection()
|
||||
const draft = createPoolKeyBatchSettingsDraft()
|
||||
selection.rpm_limit = true
|
||||
selection.concurrent_limit = true
|
||||
|
||||
expect(validatePoolKeyBatchSettings(selection, draft)).toEqual([])
|
||||
expect(buildPoolKeySettingsPatch(selection, draft)).toEqual({
|
||||
rpm_limit: null,
|
||||
concurrent_limit: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('requires a selected field and a proxy node for set mode', () => {
|
||||
const selection = createPoolKeyBatchSettingSelection()
|
||||
const draft = createPoolKeyBatchSettingsDraft()
|
||||
|
||||
expect(validatePoolKeyBatchSettings(selection, draft)).toEqual(['请至少选择一个要修改的设置'])
|
||||
|
||||
selection.proxy_node_id = true
|
||||
expect(validatePoolKeyBatchSettings(selection, draft)).toEqual(['请选择要设置的代理节点'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,109 @@
|
||||
import type { PoolKeySettingsPatch } from '@/api/endpoints/pool'
|
||||
|
||||
export type PoolKeyBatchSettingField =
|
||||
| 'internal_priority'
|
||||
| 'rpm_limit'
|
||||
| 'concurrent_limit'
|
||||
| 'cache_ttl_minutes'
|
||||
| 'max_probe_interval_minutes'
|
||||
| 'is_active'
|
||||
| 'note'
|
||||
| 'proxy_node_id'
|
||||
|
||||
export type PoolKeyBatchSettingSelection = Record<PoolKeyBatchSettingField, boolean>
|
||||
|
||||
export interface PoolKeyBatchSettingsDraft {
|
||||
internal_priority: number
|
||||
rpm_limit: number | null
|
||||
concurrent_limit: number | null
|
||||
cache_ttl_minutes: number
|
||||
max_probe_interval_minutes: number
|
||||
is_active: boolean
|
||||
note: string
|
||||
proxy_mode: 'set' | 'clear'
|
||||
proxy_node_id: string
|
||||
}
|
||||
|
||||
export function createPoolKeyBatchSettingSelection(): PoolKeyBatchSettingSelection {
|
||||
return {
|
||||
internal_priority: false,
|
||||
rpm_limit: false,
|
||||
concurrent_limit: false,
|
||||
cache_ttl_minutes: false,
|
||||
max_probe_interval_minutes: false,
|
||||
is_active: false,
|
||||
note: false,
|
||||
proxy_node_id: false,
|
||||
}
|
||||
}
|
||||
|
||||
export function createPoolKeyBatchSettingsDraft(): PoolKeyBatchSettingsDraft {
|
||||
return {
|
||||
internal_priority: 50,
|
||||
rpm_limit: null,
|
||||
concurrent_limit: null,
|
||||
cache_ttl_minutes: 5,
|
||||
max_probe_interval_minutes: 32,
|
||||
is_active: true,
|
||||
note: '',
|
||||
proxy_mode: 'set',
|
||||
proxy_node_id: '',
|
||||
}
|
||||
}
|
||||
|
||||
export function validatePoolKeyBatchSettings(
|
||||
selection: PoolKeyBatchSettingSelection,
|
||||
draft: PoolKeyBatchSettingsDraft,
|
||||
): string[] {
|
||||
const errors: string[] = []
|
||||
if (!Object.values(selection).some(Boolean)) errors.push('请至少选择一个要修改的设置')
|
||||
if (selection.internal_priority && (!Number.isInteger(draft.internal_priority) || draft.internal_priority < 0)) {
|
||||
errors.push('优先级必须是大于等于 0 的整数')
|
||||
}
|
||||
if (selection.rpm_limit && draft.rpm_limit !== null && (
|
||||
!Number.isInteger(draft.rpm_limit) || draft.rpm_limit < 1 || draft.rpm_limit > 10_000
|
||||
)) {
|
||||
errors.push('RPM 必须在 1 到 10000 之间,留空表示自适应')
|
||||
}
|
||||
if (selection.concurrent_limit && draft.concurrent_limit !== null && (
|
||||
!Number.isInteger(draft.concurrent_limit) || draft.concurrent_limit < 0
|
||||
)) {
|
||||
errors.push('并发上限必须是大于等于 0 的整数')
|
||||
}
|
||||
if (selection.cache_ttl_minutes && (
|
||||
!Number.isInteger(draft.cache_ttl_minutes) || draft.cache_ttl_minutes < 0 || draft.cache_ttl_minutes > 60
|
||||
)) {
|
||||
errors.push('缓存 TTL 必须在 0 到 60 分钟之间')
|
||||
}
|
||||
if (selection.max_probe_interval_minutes && (
|
||||
!Number.isInteger(draft.max_probe_interval_minutes)
|
||||
|| draft.max_probe_interval_minutes < 0
|
||||
|| draft.max_probe_interval_minutes > 32
|
||||
)) {
|
||||
errors.push('熔断探测必须在 0 到 32 分钟之间')
|
||||
}
|
||||
if (selection.proxy_node_id && draft.proxy_mode === 'set' && !draft.proxy_node_id.trim()) {
|
||||
errors.push('请选择要设置的代理节点')
|
||||
}
|
||||
return errors
|
||||
}
|
||||
|
||||
export function buildPoolKeySettingsPatch(
|
||||
selection: PoolKeyBatchSettingSelection,
|
||||
draft: PoolKeyBatchSettingsDraft,
|
||||
): PoolKeySettingsPatch {
|
||||
const patch: PoolKeySettingsPatch = {}
|
||||
if (selection.internal_priority) patch.internal_priority = draft.internal_priority
|
||||
if (selection.rpm_limit) patch.rpm_limit = draft.rpm_limit
|
||||
if (selection.concurrent_limit) patch.concurrent_limit = draft.concurrent_limit
|
||||
if (selection.cache_ttl_minutes) patch.cache_ttl_minutes = draft.cache_ttl_minutes
|
||||
if (selection.max_probe_interval_minutes) {
|
||||
patch.max_probe_interval_minutes = draft.max_probe_interval_minutes
|
||||
}
|
||||
if (selection.is_active) patch.is_active = draft.is_active
|
||||
if (selection.note) patch.note = draft.note.trim() || null
|
||||
if (selection.proxy_node_id) {
|
||||
patch.proxy_node_id = draft.proxy_mode === 'clear' ? null : draft.proxy_node_id.trim()
|
||||
}
|
||||
return patch
|
||||
}
|
||||
@@ -60,12 +60,22 @@
|
||||
<h3 class="text-sm font-semibold">
|
||||
{{ legacyT(isKeyManagedProviderType(provider.provider_type) ? '密钥管理' : '账号管理') }}
|
||||
</h3>
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="flex flex-wrap items-center justify-end gap-2">
|
||||
<Button
|
||||
v-if="endpoints.length > 0 && provider.provider_type === 'custom'"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
class="h-9"
|
||||
@click="keyBatchImportDialogOpen = true"
|
||||
>
|
||||
<ListPlus class="mr-1.5 h-3.5 w-3.5" />
|
||||
批量导入
|
||||
</Button>
|
||||
<Button
|
||||
v-if="endpoints.length > 0"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
class="h-8"
|
||||
class="h-9"
|
||||
@click="handleAddKeyToFirstEndpoint"
|
||||
>
|
||||
<Plus class="w-3.5 h-3.5 mr-1.5" />
|
||||
@@ -279,7 +289,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-if="getCodexResetCreditsDisplay(key)"
|
||||
v-if="getCodexResetCreditAvailableCount(key) !== null"
|
||||
class="mt-3 border-t border-border/60 pt-2"
|
||||
>
|
||||
<div class="flex flex-wrap items-center gap-x-1 gap-y-1 text-[10px] leading-4 text-muted-foreground">
|
||||
@@ -823,6 +833,16 @@
|
||||
@saved="handleKeyChanged"
|
||||
/>
|
||||
|
||||
<ProviderKeyBatchImportDialog
|
||||
v-if="open && provider?.provider_type === 'custom'"
|
||||
:open="keyBatchImportDialogOpen"
|
||||
:provider-id="provider.id"
|
||||
:provider-name="provider.name"
|
||||
:available-api-formats="availableKeyApiFormats"
|
||||
@close="keyBatchImportDialogOpen = false"
|
||||
@saved="handleKeyChanged"
|
||||
/>
|
||||
|
||||
<!-- OAuth 账号对话框 -->
|
||||
<OAuthAccountDialog
|
||||
v-if="open && provider"
|
||||
@@ -913,6 +933,7 @@ import { ref, watch, computed, nextTick } from 'vue'
|
||||
import {
|
||||
Plus,
|
||||
Key,
|
||||
ListPlus,
|
||||
Loader2,
|
||||
GripVertical,
|
||||
ShieldX,
|
||||
@@ -951,6 +972,7 @@ import AlertDialog from '@/components/common/AlertDialog.vue'
|
||||
import AntigravityQuotaDialog from '@/features/providers/components/AntigravityQuotaDialog.vue'
|
||||
import FailoverRulesDialog from '@/features/providers/components/FailoverRulesDialog.vue'
|
||||
import ProviderDetailHeader from '@/features/providers/components/ProviderDetailHeader.vue'
|
||||
import ProviderKeyBatchImportDialog from '@/features/providers/components/ProviderKeyBatchImportDialog.vue'
|
||||
import ProviderKeyActionCluster from '@/features/providers/components/ProviderKeyActionCluster.vue'
|
||||
import ProviderKeyIdentityBlock from '@/features/providers/components/ProviderKeyIdentityBlock.vue'
|
||||
import ProviderMonthlyQuotaCard from '@/features/providers/components/ProviderMonthlyQuotaCard.vue'
|
||||
@@ -1014,6 +1036,7 @@ import {
|
||||
} from '@/utils/providerKeyStatus'
|
||||
import { getGeminiCliAccountCreditsText } from '@/utils/providerKeyQuota'
|
||||
import {
|
||||
createCodexResetCreditIdempotencyKey,
|
||||
formatCodexResetCreditCount as formatCodexResetCreditCountLabel,
|
||||
formatCodexResetCreditDays,
|
||||
getCodexResetCreditAvailableCount as getCodexResetCreditAvailableCountFromSnapshot,
|
||||
@@ -1082,6 +1105,7 @@ const endpointDialogOpen = ref(false)
|
||||
|
||||
// 密钥相关状态
|
||||
const keyFormDialogOpen = ref(false)
|
||||
const keyBatchImportDialogOpen = ref(false)
|
||||
const keyPermissionsDialogOpen = ref(false)
|
||||
const oauthAccountDialogOpen = ref(false)
|
||||
const oauthKeyEditDialogOpen = ref(false)
|
||||
@@ -1170,6 +1194,7 @@ const multiplierSaving = ref(false)
|
||||
const hasBlockingDialogOpen = computed(() =>
|
||||
endpointDialogOpen.value ||
|
||||
keyFormDialogOpen.value ||
|
||||
keyBatchImportDialogOpen.value ||
|
||||
keyPermissionsDialogOpen.value ||
|
||||
oauthAccountDialogOpen.value ||
|
||||
oauthKeyEditDialogOpen.value ||
|
||||
@@ -1316,6 +1341,7 @@ watch(
|
||||
// 重置所有对话框状态
|
||||
endpointDialogOpen.value = false
|
||||
keyFormDialogOpen.value = false
|
||||
keyBatchImportDialogOpen.value = false
|
||||
keyPermissionsDialogOpen.value = false
|
||||
oauthAccountDialogOpen.value = false
|
||||
oauthKeyEditDialogOpen.value = false
|
||||
@@ -1670,13 +1696,6 @@ async function handleClearOAuthInvalid(key: EndpointAPIKey) {
|
||||
}
|
||||
}
|
||||
|
||||
function createCodexResetCreditIdempotencyKey(): string {
|
||||
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
|
||||
return crypto.randomUUID()
|
||||
}
|
||||
throw new Error('浏览器不支持 crypto.randomUUID,无法生成安全幂等 ID')
|
||||
}
|
||||
|
||||
function codexResetCreditOutcomeFeedback(
|
||||
result: Awaited<ReturnType<typeof consumeCodexResetCredit>>,
|
||||
): { tone: 'success' | 'warning'; message: string } {
|
||||
@@ -2449,7 +2468,7 @@ function shouldAutoRefreshCodexQuota(): boolean {
|
||||
|
||||
if (isTokenExpiringSoon(key, now)) return true
|
||||
|
||||
// 只要有一个活跃 key 没有配额数据,就刷新一次
|
||||
// reset-credit 独立于 Token 刷新;这里只按账号配额缓存决定是否后台更新
|
||||
if (!hasCodexQuotaDisplayData(key)) {
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -0,0 +1,585 @@
|
||||
<template>
|
||||
<Dialog
|
||||
:model-value="open"
|
||||
title="批量导入 Key"
|
||||
:description="providerName ? `${providerName} · 名称和 Key 均为必填` : '名称和 Key 均为必填'"
|
||||
:icon="ListPlus"
|
||||
size="4xl"
|
||||
persistent
|
||||
@update:model-value="handleDialogUpdate"
|
||||
>
|
||||
<div class="space-y-3.5">
|
||||
<nav class="grid grid-cols-3 gap-1.5 rounded-xl bg-muted/40 p-1.5" aria-label="批量导入步骤">
|
||||
<button
|
||||
v-for="step in steps"
|
||||
:key="step.id"
|
||||
type="button"
|
||||
class="flex min-h-10 items-center justify-center gap-2 rounded-lg px-2 text-xs font-medium transition-[background-color,box-shadow,color,scale] active:scale-[0.96] disabled:cursor-default disabled:opacity-50 sm:text-sm"
|
||||
:class="currentStep === step.id
|
||||
? 'bg-background text-foreground shadow-[0_0_0_1px_rgb(0_0_0/0.06),0_1px_2px_rgb(0_0_0/0.06)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.08)]'
|
||||
: 'text-muted-foreground hover:bg-background/60 hover:text-foreground'"
|
||||
:disabled="!canNavigateToStep(step.id)"
|
||||
@click="goToStep(step.id)"
|
||||
>
|
||||
<span
|
||||
class="flex h-5 w-5 shrink-0 items-center justify-center rounded-md text-[10px] tabular-nums"
|
||||
:class="currentStep === step.id ? 'bg-foreground text-background' : 'bg-muted text-muted-foreground'"
|
||||
>{{ step.id }}</span>
|
||||
<span class="truncate">{{ step.label }}</span>
|
||||
</button>
|
||||
</nav>
|
||||
|
||||
<section
|
||||
v-if="currentStep === 1"
|
||||
class="overflow-hidden rounded-xl bg-background shadow-[0_0_0_1px_rgb(0_0_0/0.07),0_1px_2px_-1px_rgb(0_0_0/0.08),0_3px_8px_-3px_rgb(0_0_0/0.08)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.09)]"
|
||||
>
|
||||
<header class="flex min-h-14 items-center justify-between gap-3 border-b border-border/60 bg-muted/15 px-4 py-3">
|
||||
<div class="flex min-w-0 items-center gap-3">
|
||||
<span class="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-foreground text-xs font-semibold text-background">1</span>
|
||||
<div class="min-w-0">
|
||||
<h3 class="text-balance text-sm font-semibold text-foreground">粘贴名称与 Key</h3>
|
||||
<p class="text-pretty text-[11px] leading-4 text-muted-foreground">每行一条,仅接受四个短横线分隔</p>
|
||||
</div>
|
||||
</div>
|
||||
<Badge
|
||||
:variant="parsed.errors.length > 0 ? 'destructive' : parsed.items.length > 0 ? 'success' : 'secondary'"
|
||||
class="shrink-0 tabular-nums"
|
||||
>
|
||||
{{ inputStatusText }}
|
||||
</Badge>
|
||||
</header>
|
||||
|
||||
<div class="min-w-0">
|
||||
<Label for="provider-key-batch-input" class="sr-only">Key 列表</Label>
|
||||
<Textarea
|
||||
id="provider-key-batch-input"
|
||||
v-model="inputText"
|
||||
class="h-[280px] min-h-[220px] max-h-[520px] !resize-y !rounded-none !border-0 !bg-transparent !px-4 !py-4 font-mono text-[13px] leading-6 !shadow-none !ring-0 focus-visible:!ring-0"
|
||||
spellcheck="false"
|
||||
placeholder="主账号----sk-xxxx 备用账号----sk-yyyy"
|
||||
/>
|
||||
<div
|
||||
v-if="parsed.errors.length > 0"
|
||||
class="mx-4 mb-3 space-y-1 rounded-lg bg-destructive/5 px-3 py-2 text-[11px] text-destructive ring-1 ring-destructive/20"
|
||||
>
|
||||
<div
|
||||
v-for="(item, index) in parsed.errors.slice(0, 6)"
|
||||
:key="`${item.lineNumber}-${index}`"
|
||||
>
|
||||
{{ item.lineNumber ? `第 ${item.lineNumber} 行:` : '' }}{{ item.message }}
|
||||
</div>
|
||||
<div v-if="parsed.errors.length > 6" class="font-medium">
|
||||
另有 {{ parsed.errors.length - 6 }} 个问题
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-2 border-t border-border/50 bg-muted/10 px-4 py-2.5 text-[11px] text-muted-foreground">
|
||||
<span class="rounded-md bg-muted px-2 py-1 font-mono text-foreground/80">名称----Key</span>
|
||||
<span>名称和 Key 都不能为空</span>
|
||||
<span class="ml-auto hidden tabular-nums sm:inline">已识别 {{ parsed.items.length }} 条</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section
|
||||
v-else-if="currentStep === 2"
|
||||
class="overflow-hidden rounded-xl bg-background shadow-[0_0_0_1px_rgb(0_0_0/0.07),0_1px_2px_-1px_rgb(0_0_0/0.08),0_3px_8px_-3px_rgb(0_0_0/0.08)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.09)]"
|
||||
>
|
||||
<header class="flex min-h-[72px] items-center gap-3 px-4 py-3">
|
||||
<span class="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-foreground text-xs font-semibold text-background">
|
||||
2
|
||||
</span>
|
||||
<span class="min-w-0 flex-1">
|
||||
<span class="block text-sm font-semibold">统一配置</span>
|
||||
<span class="mt-1 flex flex-wrap gap-1.5">
|
||||
<span
|
||||
v-for="item in settingsSummaryItems"
|
||||
:key="item"
|
||||
class="rounded-md bg-muted px-2 py-0.5 text-[10px] leading-4 text-muted-foreground"
|
||||
>{{ item }}</span>
|
||||
</span>
|
||||
</span>
|
||||
<Badge :variant="selectedApiFormats.length > 0 ? 'success' : 'destructive'" class="ml-auto shrink-0 tabular-nums">
|
||||
{{ selectedApiFormats.length }} 种格式
|
||||
</Badge>
|
||||
</header>
|
||||
|
||||
<div class="border-t border-border/60 bg-muted/10 p-3 sm:p-4">
|
||||
<ProviderKeyImportSettingsFields
|
||||
:auth-type="authType"
|
||||
:api-formats="selectedApiFormats"
|
||||
:settings="settings"
|
||||
:available-api-formats="availableApiFormats"
|
||||
@update:auth-type="authType = $event"
|
||||
@update:api-formats="selectedApiFormats = $event"
|
||||
@update:settings="updateGlobalSettings"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section
|
||||
v-else
|
||||
class="overflow-hidden rounded-xl bg-background shadow-[0_0_0_1px_rgb(0_0_0/0.07),0_1px_2px_-1px_rgb(0_0_0/0.08),0_3px_8px_-3px_rgb(0_0_0/0.08)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.09)]"
|
||||
>
|
||||
<header class="flex min-h-[72px] items-center gap-3 border-b border-border/60 bg-muted/15 px-4 py-3">
|
||||
<span class="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-foreground text-xs font-semibold text-background">3</span>
|
||||
<div class="min-w-0 flex-1">
|
||||
<h3 class="text-balance text-sm font-semibold">逐项确认</h3>
|
||||
<p class="text-pretty text-[11px] leading-4 text-muted-foreground">展开任意 Key 可修改内容或设置单独配置</p>
|
||||
</div>
|
||||
<div class="shrink-0 text-right text-[11px] text-muted-foreground">
|
||||
<div><span class="font-semibold tabular-nums text-foreground">{{ reviewItems.length }}</span> 个 Key</div>
|
||||
<div v-if="customizedItemCount > 0"><span class="tabular-nums">{{ customizedItemCount }}</span> 个单独配置</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div
|
||||
v-if="reviewErrorItemCount > 0"
|
||||
class="border-b border-destructive/15 bg-destructive/5 px-4 py-2 text-xs text-destructive"
|
||||
>
|
||||
{{ reviewErrorItemCount }} 个 Key 需要修正后才能导入
|
||||
</div>
|
||||
|
||||
<div class="max-h-[min(52vh,520px)] divide-y divide-border/50 overflow-y-auto overscroll-contain">
|
||||
<article
|
||||
v-for="entry in pagedReviewItems"
|
||||
:key="entry.item.lineNumber"
|
||||
class="bg-background"
|
||||
>
|
||||
<div class="flex min-h-14 items-center gap-3 px-3 py-2 sm:px-4">
|
||||
<span class="flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-muted text-[10px] tabular-nums text-muted-foreground">
|
||||
{{ entry.index + 1 }}
|
||||
</span>
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex min-w-0 items-center gap-2">
|
||||
<span class="truncate text-xs font-semibold">{{ entry.item.name || '未填写名称' }}</span>
|
||||
<Badge
|
||||
v-if="reviewErrorsByIndex.has(entry.index)"
|
||||
variant="destructive"
|
||||
class="shrink-0 text-[10px]"
|
||||
>需修正</Badge>
|
||||
</div>
|
||||
<div class="mt-0.5 truncate font-mono text-[10px] text-muted-foreground">{{ maskSecret(entry.item.apiKey) }}</div>
|
||||
</div>
|
||||
<div class="hidden shrink-0 items-center gap-1.5 sm:flex">
|
||||
<span class="rounded-md bg-muted px-2 py-0.5 text-[10px] text-muted-foreground">{{ effectiveAuthLabel(entry.item) }}</span>
|
||||
<span class="rounded-md bg-muted px-2 py-0.5 text-[10px] text-muted-foreground">{{ effectiveFormatCount(entry.item) }} 种格式</span>
|
||||
<span
|
||||
class="rounded-md px-2 py-0.5 text-[10px]"
|
||||
:class="entry.item.customized ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground'"
|
||||
>{{ entry.item.customized ? '单独配置' : '统一配置' }}</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="flex h-10 w-10 shrink-0 items-center justify-center rounded-lg text-muted-foreground transition-[background-color,color,scale] hover:bg-muted hover:text-foreground active:scale-[0.96]"
|
||||
:aria-label="`编辑 ${entry.item.name || `第 ${entry.index + 1} 项`}`"
|
||||
:title="editingItemIndex === entry.index ? '收起编辑' : '编辑此 Key'"
|
||||
@click="toggleItemEditor(entry.index)"
|
||||
>
|
||||
<Pencil class="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="editingItemIndex === entry.index"
|
||||
class="space-y-4 border-t border-border/50 bg-muted/10 p-3 sm:p-4"
|
||||
>
|
||||
<div class="grid gap-3 sm:grid-cols-2">
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">名称</Label>
|
||||
<Input v-model="entry.item.name" class="h-10" placeholder="必填" />
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">Key</Label>
|
||||
<Input v-model="entry.item.apiKey" class="h-10 font-mono text-xs" placeholder="必填" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex min-h-12 items-center justify-between gap-3 rounded-lg bg-background px-3 shadow-[0_0_0_1px_rgb(0_0_0/0.06)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.08)]">
|
||||
<div>
|
||||
<div class="text-xs font-medium">单独配置此 Key</div>
|
||||
<div class="text-[11px] text-muted-foreground">开启后覆盖第二步中的统一配置</div>
|
||||
</div>
|
||||
<Switch
|
||||
:model-value="entry.item.customized"
|
||||
@update:model-value="setItemCustomized(entry.item, $event)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ProviderKeyImportSettingsFields
|
||||
v-if="entry.item.customized"
|
||||
:auth-type="entry.item.authType"
|
||||
:api-formats="entry.item.apiFormats"
|
||||
:settings="entry.item.settings"
|
||||
:available-api-formats="availableApiFormats"
|
||||
@update:auth-type="entry.item.authType = $event"
|
||||
@update:api-formats="entry.item.apiFormats = $event"
|
||||
@update:settings="entry.item.settings = $event"
|
||||
/>
|
||||
|
||||
<div
|
||||
v-if="reviewErrorsByIndex.has(entry.index)"
|
||||
class="space-y-1 rounded-lg bg-destructive/5 px-3 py-2 text-[11px] text-destructive"
|
||||
>
|
||||
<div v-for="message in reviewErrorsByIndex.get(entry.index)" :key="message">{{ message }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="reviewPageCount > 1"
|
||||
class="flex min-h-12 items-center justify-between gap-3 border-t border-border/60 bg-muted/10 px-3 sm:px-4"
|
||||
>
|
||||
<Button variant="ghost" size="sm" class="h-9" :disabled="reviewPage === 1" @click="changeReviewPage(reviewPage - 1)">
|
||||
<ChevronLeft class="mr-1 h-4 w-4" />
|
||||
上一页
|
||||
</Button>
|
||||
<span class="text-[11px] tabular-nums text-muted-foreground">{{ reviewPage }} / {{ reviewPageCount }}</span>
|
||||
<Button variant="ghost" size="sm" class="h-9" :disabled="reviewPage === reviewPageCount" @click="changeReviewPage(reviewPage + 1)">
|
||||
下一页
|
||||
<ChevronRight class="ml-1 h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<template #footer>
|
||||
<div class="flex w-full flex-col-reverse gap-2 sm:flex-row sm:justify-end">
|
||||
<Button class="w-full sm:w-auto" variant="outline" :disabled="importing" @click="handleBack">
|
||||
<ArrowLeft v-if="currentStep > 1" class="mr-2 h-4 w-4" />
|
||||
{{ currentStep === 1 ? '取消' : '上一步' }}
|
||||
</Button>
|
||||
<Button class="w-full sm:w-auto" :disabled="primaryActionDisabled" @click="handlePrimaryAction">
|
||||
<Loader2 v-if="importing" class="mr-2 h-4 w-4 animate-spin" />
|
||||
<ListPlus v-else-if="currentStep === 3" class="mr-2 h-4 w-4" />
|
||||
<ArrowRight v-else class="mr-2 h-4 w-4" />
|
||||
{{ primaryActionLabel }}
|
||||
</Button>
|
||||
</div>
|
||||
</template>
|
||||
</Dialog>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, reactive, ref, watch } from 'vue'
|
||||
import {
|
||||
ArrowLeft,
|
||||
ArrowRight,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
ListPlus,
|
||||
Loader2,
|
||||
Pencil,
|
||||
} from 'lucide-vue-next'
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
Dialog,
|
||||
Input,
|
||||
Label,
|
||||
Switch,
|
||||
Textarea,
|
||||
} from '@/components/ui'
|
||||
import ProviderKeyImportSettingsFields from './ProviderKeyImportSettingsFields.vue'
|
||||
import { batchImportPoolKeys, type PoolKeySettingsPatch } from '@/api/endpoints/pool'
|
||||
import { useToast } from '@/composables/useToast'
|
||||
import { parseApiError } from '@/utils/errorParser'
|
||||
import { parseProviderKeyBatchImport } from '@/features/providers/utils/providerKeyBatchImport'
|
||||
|
||||
type WizardStep = 1 | 2 | 3
|
||||
type AuthType = 'api_key' | 'bearer'
|
||||
type ImportSettings = Required<Pick<PoolKeySettingsPatch,
|
||||
'internal_priority' | 'rpm_limit' | 'concurrent_limit' | 'cache_ttl_minutes'
|
||||
| 'max_probe_interval_minutes' | 'is_active' | 'note' | 'proxy_node_id'
|
||||
>>
|
||||
|
||||
interface ReviewImportItem {
|
||||
lineNumber: number
|
||||
name: string
|
||||
apiKey: string
|
||||
customized: boolean
|
||||
authType: AuthType
|
||||
apiFormats: string[]
|
||||
settings: ImportSettings
|
||||
}
|
||||
|
||||
const REVIEW_PAGE_SIZE = 50
|
||||
const steps: ReadonlyArray<{ id: WizardStep; label: string }> = [
|
||||
{ id: 1, label: '导入内容' },
|
||||
{ id: 2, label: '统一配置' },
|
||||
{ id: 3, label: '逐项确认' },
|
||||
]
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean
|
||||
providerId: string
|
||||
providerName?: string
|
||||
availableApiFormats: string[]
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: []
|
||||
saved: []
|
||||
}>()
|
||||
|
||||
const { success, warning, error: showError } = useToast()
|
||||
const currentStep = ref<WizardStep>(1)
|
||||
const inputText = ref('')
|
||||
const importing = ref(false)
|
||||
const authType = ref<AuthType>('api_key')
|
||||
const selectedApiFormats = ref<string[]>([])
|
||||
const settings = reactive<ImportSettings>(createDefaultSettings())
|
||||
const reviewItems = ref<ReviewImportItem[]>([])
|
||||
const reviewPage = ref(1)
|
||||
const editingItemIndex = ref<number | null>(null)
|
||||
|
||||
const parsed = computed(() => parseProviderKeyBatchImport(inputText.value))
|
||||
const canContinueInput = computed(() => (
|
||||
parsed.value.items.length > 0 && parsed.value.errors.length === 0
|
||||
))
|
||||
const canContinueSettings = computed(() => selectedApiFormats.value.length > 0)
|
||||
const inputStatusText = computed(() => {
|
||||
if (parsed.value.errors.length > 0) return `${parsed.value.errors.length} 个问题`
|
||||
if (parsed.value.items.length > 0) return `${parsed.value.items.length} 条有效`
|
||||
return '等待输入'
|
||||
})
|
||||
const reviewErrorsByIndex = computed(() => {
|
||||
const errors = new Map<number, string[]>()
|
||||
const seenNames = new Set<string>()
|
||||
const seenKeys = new Set<string>()
|
||||
|
||||
reviewItems.value.forEach((item, index) => {
|
||||
const messages: string[] = []
|
||||
const name = item.name.trim()
|
||||
const apiKey = item.apiKey.trim()
|
||||
if (!name) messages.push('名称不能为空')
|
||||
else if (name.length > 100) messages.push('名称不能超过 100 个字符')
|
||||
else if (seenNames.has(name)) messages.push('名称与前面的 Key 重复')
|
||||
else seenNames.add(name)
|
||||
|
||||
if (!apiKey) messages.push('Key 不能为空')
|
||||
else if (seenKeys.has(apiKey)) messages.push('Key 与前面的 Key 重复')
|
||||
else seenKeys.add(apiKey)
|
||||
|
||||
if (item.customized && item.apiFormats.length === 0) {
|
||||
messages.push('单独配置时至少选择一种 API 格式')
|
||||
}
|
||||
if (messages.length > 0) errors.set(index, messages)
|
||||
})
|
||||
return errors
|
||||
})
|
||||
const reviewErrorItemCount = computed(() => reviewErrorsByIndex.value.size)
|
||||
const customizedItemCount = computed(() => (
|
||||
reviewItems.value.filter(item => item.customized).length
|
||||
))
|
||||
const reviewPageCount = computed(() => (
|
||||
Math.max(1, Math.ceil(reviewItems.value.length / REVIEW_PAGE_SIZE))
|
||||
))
|
||||
const pagedReviewItems = computed(() => {
|
||||
const start = (reviewPage.value - 1) * REVIEW_PAGE_SIZE
|
||||
return reviewItems.value
|
||||
.slice(start, start + REVIEW_PAGE_SIZE)
|
||||
.map((item, offset) => ({ item, index: start + offset }))
|
||||
})
|
||||
const canImport = computed(() => (
|
||||
!importing.value
|
||||
&& reviewItems.value.length > 0
|
||||
&& reviewErrorsByIndex.value.size === 0
|
||||
&& canContinueSettings.value
|
||||
))
|
||||
const primaryActionDisabled = computed(() => {
|
||||
if (importing.value) return true
|
||||
if (currentStep.value === 1) return !canContinueInput.value
|
||||
if (currentStep.value === 2) return !canContinueSettings.value
|
||||
return !canImport.value
|
||||
})
|
||||
const primaryActionLabel = computed(() => {
|
||||
if (importing.value) return '正在导入...'
|
||||
if (currentStep.value === 1) return '下一步:统一配置'
|
||||
if (currentStep.value === 2) return '下一步:逐项确认'
|
||||
return `导入 ${reviewItems.value.length} 个 Key`
|
||||
})
|
||||
const settingsSummaryItems = computed(() => {
|
||||
const rpm = settings.rpm_limit == null ? 'RPM 自适应' : `RPM ${settings.rpm_limit}`
|
||||
const concurrent = settings.concurrent_limit == null || settings.concurrent_limit === 0
|
||||
? '不限并发'
|
||||
: `并发 ${settings.concurrent_limit}`
|
||||
const proxy = settings.proxy_node_id ? '独立代理' : '沿用 Provider 代理'
|
||||
return [authType.value === 'bearer' ? 'Bearer' : 'API Key', rpm, concurrent, proxy]
|
||||
})
|
||||
|
||||
watch(
|
||||
() => props.open,
|
||||
(open) => {
|
||||
if (!open) return
|
||||
currentStep.value = 1
|
||||
inputText.value = ''
|
||||
importing.value = false
|
||||
authType.value = 'api_key'
|
||||
selectedApiFormats.value = [...props.availableApiFormats]
|
||||
Object.assign(settings, createDefaultSettings())
|
||||
reviewItems.value = []
|
||||
reviewPage.value = 1
|
||||
editingItemIndex.value = null
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
watch(inputText, () => {
|
||||
reviewItems.value = []
|
||||
reviewPage.value = 1
|
||||
editingItemIndex.value = null
|
||||
})
|
||||
|
||||
function createDefaultSettings(): ImportSettings {
|
||||
return {
|
||||
internal_priority: 50,
|
||||
rpm_limit: null,
|
||||
concurrent_limit: null,
|
||||
cache_ttl_minutes: 5,
|
||||
max_probe_interval_minutes: 32,
|
||||
is_active: true,
|
||||
note: '',
|
||||
proxy_node_id: '',
|
||||
}
|
||||
}
|
||||
|
||||
function copySettings(source: ImportSettings): ImportSettings {
|
||||
return { ...source }
|
||||
}
|
||||
|
||||
function buildSettingsPayload(
|
||||
source: ImportSettings,
|
||||
includeEmptyProxy = false,
|
||||
): PoolKeySettingsPatch {
|
||||
return {
|
||||
internal_priority: source.internal_priority,
|
||||
rpm_limit: source.rpm_limit,
|
||||
concurrent_limit: source.concurrent_limit,
|
||||
cache_ttl_minutes: source.cache_ttl_minutes,
|
||||
max_probe_interval_minutes: source.max_probe_interval_minutes,
|
||||
is_active: source.is_active,
|
||||
note: source.note.trim() || null,
|
||||
...((source.proxy_node_id || includeEmptyProxy)
|
||||
? { proxy_node_id: source.proxy_node_id || null }
|
||||
: {}),
|
||||
}
|
||||
}
|
||||
|
||||
function handleDialogUpdate(value: boolean): void {
|
||||
if (!value) emit('close')
|
||||
}
|
||||
|
||||
function canNavigateToStep(step: WizardStep): boolean {
|
||||
return step <= currentStep.value
|
||||
}
|
||||
|
||||
function goToStep(step: WizardStep): void {
|
||||
if (canNavigateToStep(step)) currentStep.value = step
|
||||
}
|
||||
|
||||
function handleBack(): void {
|
||||
if (currentStep.value === 1) {
|
||||
emit('close')
|
||||
return
|
||||
}
|
||||
currentStep.value = (currentStep.value - 1) as WizardStep
|
||||
}
|
||||
|
||||
function handlePrimaryAction(): void {
|
||||
if (primaryActionDisabled.value) return
|
||||
if (currentStep.value === 1) {
|
||||
currentStep.value = 2
|
||||
return
|
||||
}
|
||||
if (currentStep.value === 2) {
|
||||
prepareReviewItems()
|
||||
currentStep.value = 3
|
||||
return
|
||||
}
|
||||
void submitImport()
|
||||
}
|
||||
|
||||
function prepareReviewItems(): void {
|
||||
if (reviewItems.value.length > 0) return
|
||||
reviewItems.value = parsed.value.items.map(item => ({
|
||||
lineNumber: item.lineNumber,
|
||||
name: item.name,
|
||||
apiKey: item.apiKey,
|
||||
customized: false,
|
||||
authType: authType.value,
|
||||
apiFormats: [...selectedApiFormats.value],
|
||||
settings: copySettings(settings),
|
||||
}))
|
||||
reviewPage.value = 1
|
||||
editingItemIndex.value = null
|
||||
}
|
||||
|
||||
function toggleItemEditor(index: number): void {
|
||||
editingItemIndex.value = editingItemIndex.value === index ? null : index
|
||||
}
|
||||
|
||||
function setItemCustomized(item: ReviewImportItem, customized: boolean): void {
|
||||
item.customized = customized
|
||||
if (!customized) return
|
||||
item.authType = authType.value
|
||||
item.apiFormats = [...selectedApiFormats.value]
|
||||
item.settings = copySettings(settings)
|
||||
}
|
||||
|
||||
function changeReviewPage(page: number): void {
|
||||
reviewPage.value = Math.min(Math.max(page, 1), reviewPageCount.value)
|
||||
editingItemIndex.value = null
|
||||
}
|
||||
|
||||
function effectiveAuthLabel(item: ReviewImportItem): string {
|
||||
const resolved = item.customized ? item.authType : authType.value
|
||||
return resolved === 'bearer' ? 'Bearer' : 'API Key'
|
||||
}
|
||||
|
||||
function effectiveFormatCount(item: ReviewImportItem): number {
|
||||
return item.customized ? item.apiFormats.length : selectedApiFormats.value.length
|
||||
}
|
||||
|
||||
function updateGlobalSettings(nextSettings: ImportSettings): void {
|
||||
Object.assign(settings, nextSettings)
|
||||
}
|
||||
|
||||
function maskSecret(secret: string): string {
|
||||
if (secret.length <= 10) return `${secret.slice(0, 3)}•••`
|
||||
return `${secret.slice(0, 6)}••••${secret.slice(-4)}`
|
||||
}
|
||||
|
||||
async function submitImport(): Promise<void> {
|
||||
if (!canImport.value) return
|
||||
importing.value = true
|
||||
try {
|
||||
const result = await batchImportPoolKeys(props.providerId, {
|
||||
keys: reviewItems.value.map(item => ({
|
||||
name: item.name.trim(),
|
||||
api_key: item.apiKey.trim(),
|
||||
auth_type: item.customized ? item.authType : authType.value,
|
||||
...(item.customized
|
||||
? {
|
||||
api_formats: item.apiFormats,
|
||||
settings: buildSettingsPayload(item.settings, true),
|
||||
}
|
||||
: {}),
|
||||
})),
|
||||
api_formats: selectedApiFormats.value,
|
||||
settings: buildSettingsPayload(settings),
|
||||
})
|
||||
if (result.imported > 0) emit('saved')
|
||||
if (result.errors.length > 0) {
|
||||
warning(`已导入 ${result.imported} 个,${result.errors.length} 个失败`)
|
||||
return
|
||||
}
|
||||
success(`已导入 ${result.imported} 个 Key`)
|
||||
emit('close')
|
||||
} catch (error) {
|
||||
showError(parseApiError(error, '批量导入 Key 失败'))
|
||||
} finally {
|
||||
importing.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,181 @@
|
||||
<template>
|
||||
<div class="space-y-4">
|
||||
<div class="space-y-2">
|
||||
<Label class="text-xs font-medium">支持的 API 格式</Label>
|
||||
<div class="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<label
|
||||
v-for="format in availableApiFormats"
|
||||
:key="format"
|
||||
class="flex min-h-10 cursor-pointer items-center gap-2 rounded-lg bg-background px-3 text-xs transition-[box-shadow,background-color]"
|
||||
:class="apiFormats.includes(format)
|
||||
? 'bg-primary/5 shadow-[0_0_0_1px_rgb(0_0_0/0.10),0_1px_2px_rgb(0_0_0/0.04)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.12)]'
|
||||
: 'shadow-[0_0_0_1px_rgb(0_0_0/0.06)] hover:bg-muted/30 hover:shadow-[0_0_0_1px_rgb(0_0_0/0.10)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.08)]'"
|
||||
>
|
||||
<Checkbox
|
||||
:checked="apiFormats.includes(format)"
|
||||
@update:checked="(checked) => toggleApiFormat(format, checked === true)"
|
||||
/>
|
||||
<span class="truncate">{{ formatApiFormat(format) }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">认证类型</Label>
|
||||
<Select v-model="authTypeModel">
|
||||
<SelectTrigger class="h-10">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="api_key">API Key</SelectItem>
|
||||
<SelectItem value="bearer">Bearer Token</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">优先级</Label>
|
||||
<Input
|
||||
:model-value="settings.internal_priority"
|
||||
type="number"
|
||||
min="0"
|
||||
class="h-10"
|
||||
@update:model-value="updateSetting('internal_priority', parseNumberInput($event, { min: 0 }) ?? 50)"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">RPM 限制</Label>
|
||||
<Input
|
||||
:model-value="settings.rpm_limit ?? ''"
|
||||
type="number"
|
||||
min="1"
|
||||
max="10000"
|
||||
class="h-10"
|
||||
placeholder="自适应"
|
||||
@update:model-value="updateSetting('rpm_limit', parseNullableNumberInput($event, { min: 1, max: 10000 }))"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">并发请求上限</Label>
|
||||
<Input
|
||||
:model-value="settings.concurrent_limit ?? ''"
|
||||
type="number"
|
||||
min="0"
|
||||
class="h-10"
|
||||
placeholder="不限制"
|
||||
@update:model-value="updateSetting('concurrent_limit', parseNullableNumberInput($event, { min: 0 }))"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">缓存 TTL(分钟)</Label>
|
||||
<Input
|
||||
:model-value="settings.cache_ttl_minutes"
|
||||
type="number"
|
||||
min="0"
|
||||
max="60"
|
||||
class="h-10"
|
||||
@update:model-value="updateSetting('cache_ttl_minutes', parseNumberInput($event, { min: 0, max: 60 }) ?? 5)"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">熔断探测(分钟)</Label>
|
||||
<Input
|
||||
:model-value="settings.max_probe_interval_minutes"
|
||||
type="number"
|
||||
min="0"
|
||||
max="32"
|
||||
class="h-10"
|
||||
@update:model-value="updateSetting('max_probe_interval_minutes', parseNumberInput($event, { min: 0, max: 32 }) ?? 32)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-3 sm:grid-cols-2">
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">代理节点</Label>
|
||||
<ProxyNodeSelect
|
||||
:model-value="settings.proxy_node_id"
|
||||
trigger-class="h-10"
|
||||
@update:model-value="updateSetting('proxy_node_id', $event)"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-xs">备注</Label>
|
||||
<Input
|
||||
:model-value="settings.note"
|
||||
class="h-10"
|
||||
placeholder="可选"
|
||||
@update:model-value="updateSetting('note', String($event))"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex min-h-12 items-center justify-between gap-3 rounded-lg bg-background px-3 shadow-[0_0_0_1px_rgb(0_0_0/0.06),0_1px_2px_rgb(0_0_0/0.04)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.08)]">
|
||||
<div>
|
||||
<div class="text-xs font-medium">导入后立即启用</div>
|
||||
<div class="text-[11px] text-muted-foreground">关闭后仍会创建,但不会进入调度</div>
|
||||
</div>
|
||||
<Switch
|
||||
:model-value="settings.is_active"
|
||||
@update:model-value="updateSetting('is_active', $event)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import {
|
||||
Checkbox,
|
||||
Input,
|
||||
Label,
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
Switch,
|
||||
} from '@/components/ui'
|
||||
import type { PoolKeySettingsPatch } from '@/api/endpoints/pool'
|
||||
import { formatApiFormat } from '@/api/endpoints/types/api-format'
|
||||
import { parseNullableNumberInput, parseNumberInput } from '@/utils/form'
|
||||
import ProxyNodeSelect from './ProxyNodeSelect.vue'
|
||||
|
||||
type AuthType = 'api_key' | 'bearer'
|
||||
type ImportSettings = Required<Pick<PoolKeySettingsPatch,
|
||||
'internal_priority' | 'rpm_limit' | 'concurrent_limit' | 'cache_ttl_minutes'
|
||||
| 'max_probe_interval_minutes' | 'is_active' | 'note' | 'proxy_node_id'
|
||||
>>
|
||||
|
||||
const props = defineProps<{
|
||||
authType: AuthType
|
||||
apiFormats: string[]
|
||||
settings: ImportSettings
|
||||
availableApiFormats: string[]
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:authType': [value: AuthType]
|
||||
'update:apiFormats': [value: string[]]
|
||||
'update:settings': [value: ImportSettings]
|
||||
}>()
|
||||
|
||||
const authTypeModel = computed<AuthType>({
|
||||
get: () => props.authType,
|
||||
set: value => emit('update:authType', value),
|
||||
})
|
||||
|
||||
function toggleApiFormat(format: string, checked: boolean): void {
|
||||
const selected = new Set(props.apiFormats)
|
||||
if (checked) selected.add(format)
|
||||
else selected.delete(format)
|
||||
emit('update:apiFormats', props.availableApiFormats.filter(item => selected.has(item)))
|
||||
}
|
||||
|
||||
function updateSetting<Key extends keyof ImportSettings>(
|
||||
key: Key,
|
||||
value: ImportSettings[Key],
|
||||
): void {
|
||||
emit('update:settings', { ...props.settings, [key]: value })
|
||||
}
|
||||
</script>
|
||||
+19
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
createCodexResetCreditIdempotencyKey,
|
||||
formatCodexResetCreditCount,
|
||||
formatCodexResetCreditDays,
|
||||
getCodexResetCreditAvailableCount,
|
||||
@@ -108,4 +109,22 @@ describe('codex reset credit display helpers', () => {
|
||||
expect(formatCodexResetCreditDays(1)).toBe('1天')
|
||||
expect(formatCodexResetCreditDays(86_401)).toBe('2天')
|
||||
})
|
||||
|
||||
it('generates a UUID v4 with secure random bytes when randomUUID is unavailable', () => {
|
||||
const idempotencyKey = createCodexResetCreditIdempotencyKey({
|
||||
getRandomValues(array) {
|
||||
array.set(Array.from({ length: 16 }, (_, index) => index))
|
||||
return array
|
||||
},
|
||||
})
|
||||
|
||||
expect(idempotencyKey).toBe('00010203-0405-4607-8809-0a0b0c0d0e0f')
|
||||
})
|
||||
|
||||
it('prefers the browser randomUUID implementation when available', () => {
|
||||
expect(createCodexResetCreditIdempotencyKey({
|
||||
randomUUID: () => 'existing-random-uuid',
|
||||
getRandomValues: array => array,
|
||||
})).toBe('existing-random-uuid')
|
||||
})
|
||||
})
|
||||
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { resolve } from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
function readSource(path: string): string {
|
||||
return readFileSync(resolve(process.cwd(), path), 'utf8')
|
||||
}
|
||||
|
||||
describe('provider key batch import UI contract', () => {
|
||||
it('shows the entry only for custom providers', () => {
|
||||
const source = readSource('src/features/providers/components/ProviderDetailDrawer.vue')
|
||||
|
||||
expect(source).toContain("provider.provider_type === 'custom'")
|
||||
expect(source).toContain('<ProviderKeyBatchImportDialog')
|
||||
expect(source).toContain('keyBatchImportDialogOpen')
|
||||
})
|
||||
|
||||
it('uses a three-step flow with per-key review overrides', () => {
|
||||
const source = readSource('src/features/providers/components/ProviderKeyBatchImportDialog.vue')
|
||||
|
||||
expect(source).toContain('parseProviderKeyBatchImport')
|
||||
expect(source).toContain("{ id: 3, label: '逐项确认' }")
|
||||
expect(source).toContain('ProviderKeyImportSettingsFields')
|
||||
expect(source).toContain('REVIEW_PAGE_SIZE')
|
||||
expect(source).toContain('item.customized')
|
||||
expect(source).toContain('api_formats: item.apiFormats')
|
||||
expect(source).toContain('batchImportPoolKeys')
|
||||
expect(source).not.toContain('MAX_BATCH_IMPORT_KEYS')
|
||||
|
||||
const fieldsSource = readSource('src/features/providers/components/ProviderKeyImportSettingsFields.vue')
|
||||
expect(fieldsSource).toContain('settings.max_probe_interval_minutes')
|
||||
expect(fieldsSource).toContain('settings.proxy_node_id')
|
||||
})
|
||||
|
||||
it('uses selective update_settings in pool batch management', () => {
|
||||
const source = readSource('src/features/pool/components/PoolAccountBatchDialog.vue')
|
||||
|
||||
expect(source).toContain("selectedAction === 'update_settings'")
|
||||
expect(source).toContain('buildPoolKeySettingsPatch')
|
||||
expect(source).toContain("confirmAndExecuteAction('update_settings')")
|
||||
expect(source).toContain('仅更新已勾选字段')
|
||||
})
|
||||
})
|
||||
@@ -61,6 +61,27 @@ export function formatCodexResetCreditCount(count: number | null | undefined): s
|
||||
return `共 ${count ?? 0} 次机会`
|
||||
}
|
||||
|
||||
interface CodexResetCreditCrypto {
|
||||
randomUUID?: () => string
|
||||
getRandomValues: (array: Uint8Array) => Uint8Array
|
||||
}
|
||||
|
||||
export function createCodexResetCreditIdempotencyKey(
|
||||
cryptoSource: CodexResetCreditCrypto | undefined = globalThis.crypto,
|
||||
): string {
|
||||
const randomUUID = cryptoSource?.randomUUID?.bind(cryptoSource)
|
||||
if (randomUUID) return randomUUID()
|
||||
if (!cryptoSource) {
|
||||
throw new Error('浏览器不支持安全随机数,无法生成幂等 ID')
|
||||
}
|
||||
|
||||
const bytes = cryptoSource.getRandomValues(new Uint8Array(16))
|
||||
bytes[6] = (bytes[6] & 0x0f) | 0x40
|
||||
bytes[8] = (bytes[8] & 0x3f) | 0x80
|
||||
const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('')
|
||||
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
|
||||
}
|
||||
|
||||
function codexResetCreditRemainingSeconds(
|
||||
item: QuotaResetCreditSnapshot,
|
||||
snapshot: QuotaResetCreditsSnapshot,
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { parseProviderKeyBatchImport } from '../providerKeyBatchImport'
|
||||
|
||||
describe('provider key batch import parser', () => {
|
||||
it('parses required names and keys separated by four hyphens', () => {
|
||||
const result = parseProviderKeyBatchImport([
|
||||
'primary----sk-primary',
|
||||
'backup----sk-backup',
|
||||
'night----sk-night----suffix',
|
||||
'# ignored comment',
|
||||
].join('\n'))
|
||||
|
||||
expect(result.errors).toEqual([])
|
||||
expect(result.items).toEqual([
|
||||
{ lineNumber: 1, name: 'primary', apiKey: 'sk-primary' },
|
||||
{ lineNumber: 2, name: 'backup', apiKey: 'sk-backup' },
|
||||
{ lineNumber: 3, name: 'night', apiKey: 'sk-night----suffix' },
|
||||
])
|
||||
})
|
||||
|
||||
it('reports invalid format, missing fields and duplicates', () => {
|
||||
const result = parseProviderKeyBatchImport([
|
||||
'one----sk-1',
|
||||
'two----sk-1',
|
||||
'one----sk-2',
|
||||
'----sk-3',
|
||||
'three----',
|
||||
'sk-without-name',
|
||||
].join('\n'))
|
||||
|
||||
expect(result.items).toHaveLength(1)
|
||||
expect(result.errors.map(error => error.message)).toEqual([
|
||||
'Key 与前面行重复',
|
||||
'名称与前面行重复',
|
||||
'名称不能为空',
|
||||
'Key 不能为空',
|
||||
'格式应为 名称----Key',
|
||||
])
|
||||
})
|
||||
|
||||
it('does not impose a client-side item limit', () => {
|
||||
const input = Array.from({ length: 750 }, (_, index) => `key-${index}----sk-${index}`).join('\n')
|
||||
const result = parseProviderKeyBatchImport(input)
|
||||
|
||||
expect(result.items).toHaveLength(750)
|
||||
expect(result.errors).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,73 @@
|
||||
export interface ProviderKeyBatchImportItem {
|
||||
lineNumber: number
|
||||
name: string
|
||||
apiKey: string
|
||||
}
|
||||
|
||||
export interface ProviderKeyBatchImportError {
|
||||
lineNumber: number | null
|
||||
message: string
|
||||
}
|
||||
|
||||
export interface ProviderKeyBatchImportParseResult {
|
||||
items: ProviderKeyBatchImportItem[]
|
||||
errors: ProviderKeyBatchImportError[]
|
||||
}
|
||||
|
||||
export const PROVIDER_KEY_BATCH_SEPARATOR = '----'
|
||||
|
||||
function splitNamedKey(line: string): { name: string; apiKey: string } | null {
|
||||
const separatorIndex = line.indexOf(PROVIDER_KEY_BATCH_SEPARATOR)
|
||||
if (separatorIndex < 0) return null
|
||||
return {
|
||||
name: line.slice(0, separatorIndex),
|
||||
apiKey: line.slice(separatorIndex + PROVIDER_KEY_BATCH_SEPARATOR.length),
|
||||
}
|
||||
}
|
||||
|
||||
export function parseProviderKeyBatchImport(input: string): ProviderKeyBatchImportParseResult {
|
||||
const items: ProviderKeyBatchImportItem[] = []
|
||||
const errors: ProviderKeyBatchImportError[] = []
|
||||
const seenKeys = new Set<string>()
|
||||
const seenNames = new Set<string>()
|
||||
|
||||
for (const [index, rawLine] of input.split(/\r?\n/).entries()) {
|
||||
const lineNumber = index + 1
|
||||
const line = rawLine.trim()
|
||||
if (!line || line.startsWith('#')) continue
|
||||
|
||||
const named = splitNamedKey(line)
|
||||
if (!named) {
|
||||
errors.push({ lineNumber, message: `格式应为 名称${PROVIDER_KEY_BATCH_SEPARATOR}Key` })
|
||||
continue
|
||||
}
|
||||
const name = named.name.trim()
|
||||
const apiKey = named.apiKey.trim()
|
||||
if (!name) {
|
||||
errors.push({ lineNumber, message: '名称不能为空' })
|
||||
continue
|
||||
}
|
||||
if (!apiKey) {
|
||||
errors.push({ lineNumber, message: 'Key 不能为空' })
|
||||
continue
|
||||
}
|
||||
if (name.length > 100) {
|
||||
errors.push({ lineNumber, message: '名称不能超过 100 个字符' })
|
||||
continue
|
||||
}
|
||||
if (seenKeys.has(apiKey)) {
|
||||
errors.push({ lineNumber, message: 'Key 与前面行重复' })
|
||||
continue
|
||||
}
|
||||
if (seenNames.has(name)) {
|
||||
errors.push({ lineNumber, message: '名称与前面行重复' })
|
||||
continue
|
||||
}
|
||||
|
||||
seenKeys.add(apiKey)
|
||||
seenNames.add(name)
|
||||
items.push({ lineNumber, name, apiKey })
|
||||
}
|
||||
|
||||
return { items, errors }
|
||||
}
|
||||
Reference in New Issue
Block a user