mirror of
https://github.com/fawney19/Aether.git
synced 2026-09-02 01:10:23 +08:00
fix: use codex quota refresh for account checks
This commit is contained in:
@@ -3,10 +3,9 @@ pub(crate) use crate::handlers::admin::{
|
|||||||
build_internal_control_error_response, create_provider_oauth_catalog_key,
|
build_internal_control_error_response, create_provider_oauth_catalog_key,
|
||||||
find_duplicate_provider_oauth_key, maybe_build_local_admin_pool_response,
|
find_duplicate_provider_oauth_key, maybe_build_local_admin_pool_response,
|
||||||
maybe_build_local_admin_response, persist_provider_quota_refresh_state,
|
maybe_build_local_admin_response, persist_provider_quota_refresh_state,
|
||||||
provider_account_self_check_endpoint_for_provider,
|
|
||||||
provider_oauth_maintenance_endpoint_for_provider, provider_oauth_runtime_endpoint_for_provider,
|
provider_oauth_maintenance_endpoint_for_provider, provider_oauth_runtime_endpoint_for_provider,
|
||||||
provider_quota_refresh_endpoint_for_provider, provider_type_supports_account_self_check,
|
provider_quota_refresh_endpoint_for_provider, provider_type_supports_quota_refresh,
|
||||||
provider_type_supports_quota_refresh, reconcile_admin_fixed_provider_template_endpoints,
|
reconcile_admin_fixed_provider_template_endpoints,
|
||||||
refresh_provider_oauth_account_state_after_update, refresh_provider_pool_quota_locally,
|
refresh_provider_oauth_account_state_after_update, refresh_provider_pool_quota_locally,
|
||||||
update_existing_provider_oauth_catalog_key, AdminAppState,
|
update_existing_provider_oauth_catalog_key, AdminAppState,
|
||||||
AdminGatewayProviderTransportSnapshot, AdminLocalOAuthRefreshError, AdminRequestContext,
|
AdminGatewayProviderTransportSnapshot, AdminLocalOAuthRefreshError, AdminRequestContext,
|
||||||
|
|||||||
@@ -27,8 +27,7 @@ pub(crate) use self::provider::oauth::provisioning::{
|
|||||||
};
|
};
|
||||||
pub(crate) use self::provider::oauth::quota::dispatch::refresh_provider_pool_quota_locally;
|
pub(crate) use self::provider::oauth::quota::dispatch::refresh_provider_pool_quota_locally;
|
||||||
pub(crate) use self::provider::oauth::quota::shared::{
|
pub(crate) use self::provider::oauth::quota::shared::{
|
||||||
persist_provider_quota_refresh_state, provider_account_self_check_endpoint_for_provider,
|
persist_provider_quota_refresh_state, provider_quota_refresh_endpoint_for_provider,
|
||||||
provider_quota_refresh_endpoint_for_provider, provider_type_supports_account_self_check,
|
|
||||||
provider_type_supports_quota_refresh,
|
provider_type_supports_quota_refresh,
|
||||||
};
|
};
|
||||||
pub(crate) use self::provider::oauth::runtime::{
|
pub(crate) use self::provider::oauth::runtime::{
|
||||||
|
|||||||
@@ -8,7 +8,8 @@ use self::invalid::{
|
|||||||
codex_structured_invalid_reason,
|
codex_structured_invalid_reason,
|
||||||
};
|
};
|
||||||
use self::parse::{
|
use self::parse::{
|
||||||
parse_codex_backend_me_response, parse_codex_usage_headers, parse_codex_wham_usage_response,
|
build_codex_quota_exhausted_fallback_metadata, parse_codex_usage_headers,
|
||||||
|
parse_codex_wham_usage_response,
|
||||||
};
|
};
|
||||||
use self::plan::{build_codex_quota_request_spec, execute_codex_quota_plan};
|
use self::plan::{build_codex_quota_request_spec, execute_codex_quota_plan};
|
||||||
use super::shared::{
|
use super::shared::{
|
||||||
@@ -110,7 +111,7 @@ pub(crate) async fn refresh_codex_provider_quota_locally(
|
|||||||
"key_id": key.id,
|
"key_id": key.id,
|
||||||
"key_name": key.name,
|
"key_name": key.name,
|
||||||
"status": "error",
|
"status": "error",
|
||||||
"message": format!("backend-api/me 请求执行失败: {detail}"),
|
"message": format!("wham/usage 请求执行失败: {detail}"),
|
||||||
"status_code": 502,
|
"status_code": 502,
|
||||||
}));
|
}));
|
||||||
continue;
|
continue;
|
||||||
@@ -137,9 +138,7 @@ pub(crate) async fn refresh_codex_provider_quota_locally(
|
|||||||
.as_ref()
|
.as_ref()
|
||||||
.and_then(|body| body.json_body.as_ref())
|
.and_then(|body| body.json_body.as_ref())
|
||||||
{
|
{
|
||||||
if let Some(parsed) = parse_codex_backend_me_response(body_json, now_unix_secs)
|
if let Some(parsed) = parse_codex_wham_usage_response(body_json, now_unix_secs) {
|
||||||
.or_else(|| parse_codex_wham_usage_response(body_json, now_unix_secs))
|
|
||||||
{
|
|
||||||
metadata_update = Some(json!({
|
metadata_update = Some(json!({
|
||||||
"codex": merge_codex_quota_metadata(header_metadata.as_ref(), &parsed)
|
"codex": merge_codex_quota_metadata(header_metadata.as_ref(), &parsed)
|
||||||
}));
|
}));
|
||||||
@@ -152,21 +151,21 @@ pub(crate) async fn refresh_codex_provider_quota_locally(
|
|||||||
status = "success".to_string();
|
status = "success".to_string();
|
||||||
} else {
|
} else {
|
||||||
status = "no_metadata".to_string();
|
status = "no_metadata".to_string();
|
||||||
message = Some("backend-api/me 响应中未包含账号信息".to_string());
|
message = Some("响应中未包含限额信息".to_string());
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
message = Some("无法解析 backend-api/me API 响应".to_string());
|
message = Some("无法解析 wham/usage API 响应".to_string());
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
let err_msg = extract_execution_error_message(&result);
|
let err_msg = extract_execution_error_message(&result);
|
||||||
message = Some(match err_msg.as_deref() {
|
message = Some(match err_msg.as_deref() {
|
||||||
Some(detail) if !detail.is_empty() => {
|
Some(detail) if !detail.is_empty() => {
|
||||||
format!(
|
format!(
|
||||||
"backend-api/me API 返回状态码 {}: {}",
|
"wham/usage API 返回状态码 {}: {}",
|
||||||
result.status_code, detail
|
result.status_code, detail
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
_ => format!("backend-api/me API 返回状态码 {}", result.status_code),
|
_ => format!("wham/usage API 返回状态码 {}", result.status_code),
|
||||||
});
|
});
|
||||||
|
|
||||||
match result.status_code {
|
match result.status_code {
|
||||||
@@ -223,14 +222,26 @@ pub(crate) async fn refresh_codex_provider_quota_locally(
|
|||||||
oauth_invalid_reason = reason;
|
oauth_invalid_reason = reason;
|
||||||
status = "workspace_deactivated".to_string();
|
status = "workspace_deactivated".to_string();
|
||||||
} else {
|
} else {
|
||||||
let (at, reason) = codex_build_invalid_state(
|
let plan_type = transport
|
||||||
&key,
|
.key
|
||||||
codex_structured_invalid_reason(402, err_msg.as_deref()),
|
.decrypted_auth_config
|
||||||
now_unix_secs,
|
.as_deref()
|
||||||
);
|
.and_then(|raw| serde_json::from_str::<serde_json::Value>(raw).ok())
|
||||||
oauth_invalid_at_unix_secs = at;
|
.and_then(|value| {
|
||||||
oauth_invalid_reason = reason;
|
value
|
||||||
status = "payment_required".to_string();
|
.get("plan_type")
|
||||||
|
.and_then(serde_json::Value::as_str)
|
||||||
|
.map(ToOwned::to_owned)
|
||||||
|
});
|
||||||
|
metadata_update = Some(json!({
|
||||||
|
"codex": build_codex_quota_exhausted_fallback_metadata(
|
||||||
|
plan_type.as_deref(),
|
||||||
|
now_unix_secs,
|
||||||
|
)
|
||||||
|
}));
|
||||||
|
(oauth_invalid_at_unix_secs, oauth_invalid_reason) =
|
||||||
|
quota_refresh_success_invalid_state(&key);
|
||||||
|
status = "quota_exhausted".to_string();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
403 => {
|
403 => {
|
||||||
|
|||||||
@@ -22,13 +22,6 @@ pub(super) fn parse_codex_wham_usage_response(
|
|||||||
admin_provider_quota_pure::parse_codex_wham_usage_response(value, updated_at_unix_secs)
|
admin_provider_quota_pure::parse_codex_wham_usage_response(value, updated_at_unix_secs)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) fn parse_codex_backend_me_response(
|
|
||||||
value: &serde_json::Value,
|
|
||||||
updated_at_unix_secs: u64,
|
|
||||||
) -> Option<serde_json::Value> {
|
|
||||||
admin_provider_quota_pure::parse_codex_backend_me_response(value, updated_at_unix_secs)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn parse_codex_usage_headers(
|
pub(super) fn parse_codex_usage_headers(
|
||||||
headers: &BTreeMap<String, String>,
|
headers: &BTreeMap<String, String>,
|
||||||
updated_at_unix_secs: u64,
|
updated_at_unix_secs: u64,
|
||||||
|
|||||||
@@ -84,22 +84,6 @@ pub(crate) fn provider_quota_refresh_endpoint_for_provider(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn provider_type_supports_account_self_check(provider_type: &str) -> bool {
|
|
||||||
ProviderPoolService::with_builtin_adapters().supports_account_self_check(provider_type)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn provider_account_self_check_endpoint_for_provider(
|
|
||||||
provider_type: &str,
|
|
||||||
endpoints: &[StoredProviderCatalogEndpoint],
|
|
||||||
include_inactive: bool,
|
|
||||||
) -> Option<StoredProviderCatalogEndpoint> {
|
|
||||||
ProviderPoolService::with_builtin_adapters().account_self_check_endpoint_for_provider(
|
|
||||||
provider_type,
|
|
||||||
endpoints,
|
|
||||||
include_inactive,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn provider_quota_refresh_missing_endpoint_message(provider_type: &str) -> String {
|
pub(crate) fn provider_quota_refresh_missing_endpoint_message(provider_type: &str) -> String {
|
||||||
ProviderPoolService::with_builtin_adapters()
|
ProviderPoolService::with_builtin_adapters()
|
||||||
.quota_refresh_missing_endpoint_message(provider_type)
|
.quota_refresh_missing_endpoint_message(provider_type)
|
||||||
|
|||||||
@@ -226,7 +226,7 @@ pub(crate) struct AdminProviderUpdateRequest {
|
|||||||
|
|
||||||
pub(crate) type AdminProviderUpdatePatch = AdminTypedObjectPatch<AdminProviderUpdateRequest>;
|
pub(crate) type AdminProviderUpdatePatch = AdminTypedObjectPatch<AdminProviderUpdateRequest>;
|
||||||
|
|
||||||
pub(crate) const CODEX_WHAM_USAGE_URL: &str = "https://chatgpt.com/backend-api/me";
|
pub(crate) const CODEX_WHAM_USAGE_URL: &str = "https://chatgpt.com/backend-api/wham/usage";
|
||||||
pub(crate) const KIRO_USAGE_LIMITS_PATH: &str = "/getUsageLimits";
|
pub(crate) const KIRO_USAGE_LIMITS_PATH: &str = "/getUsageLimits";
|
||||||
pub(crate) const KIRO_USAGE_SDK_VERSION: &str = "1.0.0";
|
pub(crate) const KIRO_USAGE_SDK_VERSION: &str = "1.0.0";
|
||||||
pub(crate) const ANTIGRAVITY_FETCH_AVAILABLE_MODELS_PATH: &str = "/v1internal:fetchAvailableModels";
|
pub(crate) const ANTIGRAVITY_FETCH_AVAILABLE_MODELS_PATH: &str = "/v1internal:fetchAvailableModels";
|
||||||
|
|||||||
@@ -14,8 +14,8 @@ use serde_json::{json, Value};
|
|||||||
use tracing::{debug, info, warn};
|
use tracing::{debug, info, warn};
|
||||||
|
|
||||||
use crate::admin_api::{
|
use crate::admin_api::{
|
||||||
admin_provider_pool_config, provider_account_self_check_endpoint_for_provider,
|
admin_provider_pool_config, provider_quota_refresh_endpoint_for_provider,
|
||||||
provider_type_supports_account_self_check, refresh_provider_pool_quota_locally, AdminAppState,
|
provider_type_supports_quota_refresh, refresh_provider_pool_quota_locally, AdminAppState,
|
||||||
};
|
};
|
||||||
use crate::{AppState, GatewayError};
|
use crate::{AppState, GatewayError};
|
||||||
|
|
||||||
@@ -547,7 +547,7 @@ fn endpoint_for_self_check(
|
|||||||
provider_type: &str,
|
provider_type: &str,
|
||||||
endpoints: &[StoredProviderCatalogEndpoint],
|
endpoints: &[StoredProviderCatalogEndpoint],
|
||||||
) -> Option<StoredProviderCatalogEndpoint> {
|
) -> Option<StoredProviderCatalogEndpoint> {
|
||||||
provider_account_self_check_endpoint_for_provider(provider_type, endpoints, true)
|
provider_quota_refresh_endpoint_for_provider(provider_type, endpoints, true)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn gateway_error_message(err: GatewayError) -> String {
|
fn gateway_error_message(err: GatewayError) -> String {
|
||||||
@@ -637,7 +637,7 @@ pub(crate) async fn perform_account_self_check_once_with_config(
|
|||||||
summary.providers_skipped = summary.providers_skipped.saturating_add(1);
|
summary.providers_skipped = summary.providers_skipped.saturating_add(1);
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
if !provider_type_supports_account_self_check(&provider_type) {
|
if !provider_type_supports_quota_refresh(&provider_type) {
|
||||||
summary.providers_skipped = summary.providers_skipped.saturating_add(1);
|
summary.providers_skipped = summary.providers_skipped.saturating_add(1);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,7 +29,6 @@ async fn gateway_refreshes_admin_provider_quota_locally_for_codex_with_trusted_a
|
|||||||
struct SeenExecutionRuntimeRequest {
|
struct SeenExecutionRuntimeRequest {
|
||||||
url: String,
|
url: String,
|
||||||
authorization: String,
|
authorization: String,
|
||||||
accept: String,
|
|
||||||
provider_api_format: String,
|
provider_api_format: String,
|
||||||
total_ms: Option<u64>,
|
total_ms: Option<u64>,
|
||||||
}
|
}
|
||||||
@@ -69,7 +68,6 @@ async fn gateway_refreshes_admin_provider_quota_locally_for_codex_with_trusted_a
|
|||||||
.get("authorization")
|
.get("authorization")
|
||||||
.cloned()
|
.cloned()
|
||||||
.unwrap_or_default(),
|
.unwrap_or_default(),
|
||||||
accept: plan.headers.get("accept").cloned().unwrap_or_default(),
|
|
||||||
provider_api_format: plan.provider_api_format.clone(),
|
provider_api_format: plan.provider_api_format.clone(),
|
||||||
total_ms: plan
|
total_ms: plan
|
||||||
.timeouts
|
.timeouts
|
||||||
@@ -80,22 +78,41 @@ async fn gateway_refreshes_admin_provider_quota_locally_for_codex_with_trusted_a
|
|||||||
request_id: plan.request_id,
|
request_id: plan.request_id,
|
||||||
candidate_id: None,
|
candidate_id: None,
|
||||||
status_code: 200,
|
status_code: 200,
|
||||||
headers: BTreeMap::new(),
|
headers: BTreeMap::from([
|
||||||
|
(
|
||||||
|
"x-codex-primary-reset-after-seconds".to_string(),
|
||||||
|
"18000".to_string(),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"x-codex-primary-reset-at".to_string(),
|
||||||
|
"1900000000".to_string(),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"x-codex-secondary-reset-after-seconds".to_string(),
|
||||||
|
"604800".to_string(),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"x-codex-secondary-reset-at".to_string(),
|
||||||
|
"1900500000".to_string(),
|
||||||
|
),
|
||||||
|
]),
|
||||||
body: Some(aether_contracts::ResponseBody {
|
body: Some(aether_contracts::ResponseBody {
|
||||||
json_body: Some(json!({
|
json_body: Some(json!({
|
||||||
"user": {
|
"plan_type": "plus",
|
||||||
"id": "user-codex-123",
|
"rate_limit": {
|
||||||
"email": "codex@example.com",
|
"primary_window": {
|
||||||
"name": "Codex User"
|
"used_percent": 12.5,
|
||||||
|
"window_minutes": 300
|
||||||
|
},
|
||||||
|
"secondary_window": {
|
||||||
|
"used_percent": 55.0,
|
||||||
|
"window_minutes": 10080
|
||||||
|
}
|
||||||
},
|
},
|
||||||
"account": {
|
"credits": {
|
||||||
"id": "acct-codex-123",
|
"has_credits": true,
|
||||||
"name": "Personal",
|
"balance": 42.0,
|
||||||
"plan_type": "plus"
|
"unlimited": false
|
||||||
},
|
|
||||||
"plan": {
|
|
||||||
"type": "Plus",
|
|
||||||
"title": "ChatGPT Plus"
|
|
||||||
}
|
}
|
||||||
})),
|
})),
|
||||||
body_bytes_b64: None,
|
body_bytes_b64: None,
|
||||||
@@ -167,22 +184,18 @@ async fn gateway_refreshes_admin_provider_quota_locally_for_codex_with_trusted_a
|
|||||||
);
|
);
|
||||||
assert_eq!(payload["results"][0]["quota_snapshot"]["plan_type"], "plus");
|
assert_eq!(payload["results"][0]["quota_snapshot"]["plan_type"], "plus");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
payload["results"][0]["quota_snapshot"]["exhausted"],
|
payload["results"][0]["quota_snapshot"]["reset_at"],
|
||||||
json!(false)
|
1_900_000_000u64
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
payload["results"][0]["quota_snapshot"]["credits"]["balance"],
|
||||||
|
json!(42.0)
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
payload["results"][0]["quota_snapshot"]["windows"]
|
payload["results"][0]["quota_snapshot"]["windows"]
|
||||||
.as_array()
|
.as_array()
|
||||||
.map(Vec::len),
|
.map(Vec::len),
|
||||||
Some(0usize)
|
Some(2usize)
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
payload["results"][0]["metadata"]["email"],
|
|
||||||
"codex@example.com"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
payload["results"][0]["metadata"]["account_id"],
|
|
||||||
"acct-codex-123"
|
|
||||||
);
|
);
|
||||||
assert_eq!(*upstream_hits.lock().expect("mutex should lock"), 0);
|
assert_eq!(*upstream_hits.lock().expect("mutex should lock"), 0);
|
||||||
|
|
||||||
@@ -193,13 +206,12 @@ async fn gateway_refreshes_admin_provider_quota_locally_for_codex_with_trusted_a
|
|||||||
.expect("execution runtime request should be captured");
|
.expect("execution runtime request should be captured");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
seen_execution_runtime_request.url,
|
seen_execution_runtime_request.url,
|
||||||
"https://chatgpt.com/backend-api/me"
|
"https://chatgpt.com/backend-api/wham/usage"
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
seen_execution_runtime_request.authorization,
|
seen_execution_runtime_request.authorization,
|
||||||
"Bearer sk-codex-123"
|
"Bearer sk-codex-123"
|
||||||
);
|
);
|
||||||
assert_eq!(seen_execution_runtime_request.accept, "application/json");
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
seen_execution_runtime_request.provider_api_format,
|
seen_execution_runtime_request.provider_api_format,
|
||||||
"openai:responses"
|
"openai:responses"
|
||||||
@@ -225,23 +237,33 @@ async fn gateway_refreshes_admin_provider_quota_locally_for_codex_with_trusted_a
|
|||||||
.upstream_metadata
|
.upstream_metadata
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.and_then(|value| value.get("codex"))
|
.and_then(|value| value.get("codex"))
|
||||||
.and_then(|value| value.get("email")),
|
.and_then(|value| value.get("primary_used_percent")),
|
||||||
Some(&json!("codex@example.com"))
|
Some(&json!(55.0))
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
reloaded[0]
|
reloaded[0]
|
||||||
.upstream_metadata
|
.upstream_metadata
|
||||||
.as_ref()
|
.as_ref()
|
||||||
.and_then(|value| value.get("codex"))
|
.and_then(|value| value.get("codex"))
|
||||||
.and_then(|value| value.get("account_id")),
|
.and_then(|value| value.get("primary_reset_at")),
|
||||||
Some(&json!("acct-codex-123"))
|
Some(&json!(1_900_500_000u64))
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
reloaded[0]
|
||||||
|
.upstream_metadata
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|value| value.get("codex"))
|
||||||
|
.and_then(|value| value.get("secondary_used_percent")),
|
||||||
|
Some(&json!(12.5))
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
reloaded[0]
|
||||||
|
.upstream_metadata
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|value| value.get("codex"))
|
||||||
|
.and_then(|value| value.get("secondary_reset_at")),
|
||||||
|
Some(&json!(1_900_000_000u64))
|
||||||
);
|
);
|
||||||
assert!(reloaded[0]
|
|
||||||
.upstream_metadata
|
|
||||||
.as_ref()
|
|
||||||
.and_then(|value| value.get("codex"))
|
|
||||||
.and_then(|value| value.get("primary_used_percent"))
|
|
||||||
.is_none());
|
|
||||||
|
|
||||||
gateway_handle.abort();
|
gateway_handle.abort();
|
||||||
execution_runtime_handle.abort();
|
execution_runtime_handle.abort();
|
||||||
@@ -249,7 +271,7 @@ async fn gateway_refreshes_admin_provider_quota_locally_for_codex_with_trusted_a
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn gateway_marks_codex_key_invalid_when_backend_me_returns_payment_required() {
|
async fn gateway_marks_codex_quota_exhausted_when_wham_usage_returns_payment_required() {
|
||||||
let upstream = Router::new().route(
|
let upstream = Router::new().route(
|
||||||
"/api/admin/endpoints/providers/provider-codex/refresh-quota",
|
"/api/admin/endpoints/providers/provider-codex/refresh-quota",
|
||||||
any(move |_request: Request| async move {
|
any(move |_request: Request| async move {
|
||||||
@@ -337,18 +359,31 @@ async fn gateway_marks_codex_key_invalid_when_backend_me_returns_payment_require
|
|||||||
let payload: serde_json::Value = response.json().await.expect("json body should parse");
|
let payload: serde_json::Value = response.json().await.expect("json body should parse");
|
||||||
assert_eq!(payload["success"], 0);
|
assert_eq!(payload["success"], 0);
|
||||||
assert_eq!(payload["failed"], 1);
|
assert_eq!(payload["failed"], 1);
|
||||||
assert_eq!(payload["results"][0]["status"], "payment_required");
|
assert_eq!(payload["results"][0]["status"], "quota_exhausted");
|
||||||
assert_eq!(payload["results"][0]["status_code"], 402);
|
assert_eq!(payload["results"][0]["status_code"], 402);
|
||||||
|
assert_eq!(
|
||||||
|
payload["results"][0]["quota_snapshot"]["provider_type"],
|
||||||
|
"codex"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
payload["results"][0]["quota_snapshot"]["exhausted"],
|
||||||
|
json!(true)
|
||||||
|
);
|
||||||
|
|
||||||
let reloaded = provider_catalog_repository
|
let reloaded = provider_catalog_repository
|
||||||
.list_keys_by_ids(&["key-codex-a".to_string()])
|
.list_keys_by_ids(&["key-codex-a".to_string()])
|
||||||
.await
|
.await
|
||||||
.expect("keys should read");
|
.expect("keys should read");
|
||||||
assert_eq!(reloaded.len(), 1);
|
assert_eq!(reloaded.len(), 1);
|
||||||
assert!(reloaded[0].oauth_invalid_at_unix_secs.is_some());
|
assert_eq!(reloaded[0].oauth_invalid_at_unix_secs, None);
|
||||||
|
assert_eq!(reloaded[0].oauth_invalid_reason, None);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
reloaded[0].oauth_invalid_reason.as_deref(),
|
reloaded[0]
|
||||||
Some("[ACCOUNT_BLOCK] payment required")
|
.upstream_metadata
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|value| value.get("codex"))
|
||||||
|
.and_then(|value| value.get("primary_used_percent")),
|
||||||
|
Some(&json!(100.0))
|
||||||
);
|
);
|
||||||
|
|
||||||
gateway_handle.abort();
|
gateway_handle.abort();
|
||||||
@@ -1345,7 +1380,7 @@ async fn gateway_reports_codex_quota_runtime_failures_locally_without_falling_ba
|
|||||||
assert!(payload["results"][0]["message"]
|
assert!(payload["results"][0]["message"]
|
||||||
.as_str()
|
.as_str()
|
||||||
.expect("message should be string")
|
.expect("message should be string")
|
||||||
.contains("backend-api/me 请求执行失败: execution runtime returned HTTP 500"));
|
.contains("wham/usage 请求执行失败: execution runtime returned HTTP 500"));
|
||||||
assert_eq!(*upstream_hits.lock().expect("mutex should lock"), 0);
|
assert_eq!(*upstream_hits.lock().expect("mutex should lock"), 0);
|
||||||
|
|
||||||
let reloaded = provider_catalog_repository
|
let reloaded = provider_catalog_repository
|
||||||
|
|||||||
@@ -2454,9 +2454,8 @@ async fn gateway_completes_admin_provider_oauth_key_locally_with_trusted_admin_p
|
|||||||
.as_str()
|
.as_str()
|
||||||
.expect("account_state_recheck_error should be string when recheck is attempted");
|
.expect("account_state_recheck_error should be string when recheck is attempted");
|
||||||
assert!(
|
assert!(
|
||||||
account_state_recheck_error == "backend-api/me API 返回状态码 401"
|
account_state_recheck_error == "wham/usage API 返回状态码 401"
|
||||||
|| account_state_recheck_error == "backend-api/me API 返回状态码 403"
|
|| account_state_recheck_error.starts_with("wham/usage 请求执行失败:"),
|
||||||
|| account_state_recheck_error.starts_with("backend-api/me 请求执行失败:"),
|
|
||||||
"unexpected account_state_recheck_error: {account_state_recheck_error}"
|
"unexpected account_state_recheck_error: {account_state_recheck_error}"
|
||||||
);
|
);
|
||||||
assert_eq!(*upstream_hits.lock().expect("mutex should lock"), 0);
|
assert_eq!(*upstream_hits.lock().expect("mutex should lock"), 0);
|
||||||
@@ -4926,9 +4925,8 @@ async fn gateway_refreshes_admin_provider_oauth_key_locally_with_trusted_admin_p
|
|||||||
.as_str()
|
.as_str()
|
||||||
.expect("account_state_recheck_error should be string when attempted");
|
.expect("account_state_recheck_error should be string when attempted");
|
||||||
assert!(
|
assert!(
|
||||||
account_state_recheck_error == "backend-api/me API 返回状态码 401"
|
account_state_recheck_error == "wham/usage API 返回状态码 401"
|
||||||
|| account_state_recheck_error == "backend-api/me API 返回状态码 403"
|
|| account_state_recheck_error.starts_with("wham/usage 请求执行失败:"),
|
||||||
|| account_state_recheck_error.starts_with("backend-api/me 请求执行失败:"),
|
|
||||||
"unexpected account_state_recheck_error: {account_state_recheck_error}"
|
"unexpected account_state_recheck_error: {account_state_recheck_error}"
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
@@ -4946,7 +4944,7 @@ async fn gateway_refreshes_admin_provider_oauth_key_locally_with_trusted_admin_p
|
|||||||
.expect("execution runtime request should be captured");
|
.expect("execution runtime request should be captured");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
seen_execution_runtime_request.url,
|
seen_execution_runtime_request.url,
|
||||||
"https://chatgpt.com/backend-api/me"
|
"https://chatgpt.com/backend-api/wham/usage"
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
seen_execution_runtime_request.authorization,
|
seen_execution_runtime_request.authorization,
|
||||||
@@ -4970,7 +4968,7 @@ async fn gateway_refreshes_admin_provider_oauth_key_locally_with_trusted_admin_p
|
|||||||
.expect("refreshed api key should decrypt");
|
.expect("refreshed api key should decrypt");
|
||||||
assert_eq!(decrypted_api_key, "refreshed-codex-access-token");
|
assert_eq!(decrypted_api_key, "refreshed-codex-access-token");
|
||||||
if account_state_recheck_attempted
|
if account_state_recheck_attempted
|
||||||
&& payload["account_state_recheck_error"] == "backend-api/me API 返回状态码 401"
|
&& payload["account_state_recheck_error"] == "wham/usage API 返回状态码 401"
|
||||||
{
|
{
|
||||||
assert!(stored_key.oauth_invalid_at_unix_secs.is_some());
|
assert!(stored_key.oauth_invalid_at_unix_secs.is_some());
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
|
|||||||
@@ -21,8 +21,8 @@ pub use providers::{
|
|||||||
AntigravityProviderPoolAdapter, ChatGptWebProviderPoolAdapter, CodexProviderPoolAdapter,
|
AntigravityProviderPoolAdapter, ChatGptWebProviderPoolAdapter, CodexProviderPoolAdapter,
|
||||||
DefaultProviderPoolAdapter, KiroPoolQuotaAuthInput, KiroProviderPoolAdapter,
|
DefaultProviderPoolAdapter, KiroPoolQuotaAuthInput, KiroProviderPoolAdapter,
|
||||||
UnsupportedQuotaProviderPoolAdapter, ANTIGRAVITY_FETCH_AVAILABLE_MODELS_PATH,
|
UnsupportedQuotaProviderPoolAdapter, ANTIGRAVITY_FETCH_AVAILABLE_MODELS_PATH,
|
||||||
CHATGPT_WEB_CONVERSATION_INIT_PATH, CHATGPT_WEB_DEFAULT_BASE_URL, CODEX_BACKEND_ME_URL,
|
CHATGPT_WEB_CONVERSATION_INIT_PATH, CHATGPT_WEB_DEFAULT_BASE_URL, CODEX_WHAM_USAGE_URL,
|
||||||
CODEX_WHAM_USAGE_URL, KIRO_USAGE_LIMITS_PATH, KIRO_USAGE_SDK_VERSION,
|
KIRO_USAGE_LIMITS_PATH, KIRO_USAGE_SDK_VERSION,
|
||||||
};
|
};
|
||||||
pub use quota::{
|
pub use quota::{
|
||||||
provider_pool_key_account_quota_exhausted, provider_pool_key_scheduling_label,
|
provider_pool_key_account_quota_exhausted, provider_pool_key_scheduling_label,
|
||||||
@@ -87,8 +87,6 @@ mod tests {
|
|||||||
assert!(service.supports_quota_refresh("codex"));
|
assert!(service.supports_quota_refresh("codex"));
|
||||||
assert!(service.supports_quota_refresh("antigravity"));
|
assert!(service.supports_quota_refresh("antigravity"));
|
||||||
assert!(!service.supports_quota_refresh("gemini_cli"));
|
assert!(!service.supports_quota_refresh("gemini_cli"));
|
||||||
assert!(service.supports_account_self_check("codex"));
|
|
||||||
assert!(!service.supports_account_self_check("gemini_cli"));
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
service.quota_refresh_unsupported_message("claude_code"),
|
service.quota_refresh_unsupported_message("claude_code"),
|
||||||
"Claude Code 暂不支持自动刷新额度:上游没有稳定可用的账号额度查询接口"
|
"Claude Code 暂不支持自动刷新额度:上游没有稳定可用的账号额度查询接口"
|
||||||
@@ -119,7 +117,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn codex_quota_request_uses_backend_me_probe_endpoint() {
|
fn codex_quota_request_uses_wham_usage_endpoint() {
|
||||||
let spec = build_codex_pool_quota_request(
|
let spec = build_codex_pool_quota_request(
|
||||||
"key-1",
|
"key-1",
|
||||||
Some(("authorization".to_string(), "Bearer access".to_string())),
|
Some(("authorization".to_string(), "Bearer access".to_string())),
|
||||||
@@ -129,7 +127,7 @@ mod tests {
|
|||||||
.expect("spec should build");
|
.expect("spec should build");
|
||||||
|
|
||||||
assert_eq!(spec.method, "GET");
|
assert_eq!(spec.method, "GET");
|
||||||
assert_eq!(spec.url, "https://chatgpt.com/backend-api/me");
|
assert_eq!(spec.url, "https://chatgpt.com/backend-api/wham/usage");
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
spec.headers.get("authorization").map(String::as_str),
|
spec.headers.get("authorization").map(String::as_str),
|
||||||
Some("Bearer access")
|
Some("Bearer access")
|
||||||
@@ -138,7 +136,7 @@ mod tests {
|
|||||||
spec.headers.get("accept").map(String::as_str),
|
spec.headers.get("accept").map(String::as_str),
|
||||||
Some("application/json")
|
Some("application/json")
|
||||||
);
|
);
|
||||||
assert_eq!(spec.model_name.as_deref(), Some("codex-backend-me"));
|
assert_eq!(spec.model_name.as_deref(), Some("codex-wham-usage"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -53,21 +53,6 @@ pub trait ProviderPoolAdapter: Send + Sync {
|
|||||||
"找不到有效端点".to_string()
|
"找不到有效端点".to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn supports_account_self_check(&self) -> bool {
|
|
||||||
self.supports_quota_refresh()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn account_self_check_endpoint(
|
|
||||||
&self,
|
|
||||||
endpoints: &[StoredProviderCatalogEndpoint],
|
|
||||||
include_inactive: bool,
|
|
||||||
) -> Option<StoredProviderCatalogEndpoint> {
|
|
||||||
if !self.supports_account_self_check() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
self.quota_refresh_endpoint(endpoints, include_inactive)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn normalize_plan_tier(&self, value: &str) -> Option<String> {
|
fn normalize_plan_tier(&self, value: &str) -> Option<String> {
|
||||||
normalize_provider_plan_tier(value, self.provider_type())
|
normalize_provider_plan_tier(value, self.provider_type())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,8 +15,7 @@ use crate::quota::{
|
|||||||
};
|
};
|
||||||
use crate::quota_refresh::ProviderPoolQuotaRequestSpec;
|
use crate::quota_refresh::ProviderPoolQuotaRequestSpec;
|
||||||
|
|
||||||
pub const CODEX_BACKEND_ME_URL: &str = "https://chatgpt.com/backend-api/me";
|
pub const CODEX_WHAM_USAGE_URL: &str = "https://chatgpt.com/backend-api/wham/usage";
|
||||||
pub const CODEX_WHAM_USAGE_URL: &str = CODEX_BACKEND_ME_URL;
|
|
||||||
const PLACEHOLDER_API_KEY: &str = "__placeholder__";
|
const PLACEHOLDER_API_KEY: &str = "__placeholder__";
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default)]
|
#[derive(Debug, Clone, Default)]
|
||||||
@@ -111,13 +110,13 @@ pub fn build_codex_pool_quota_request(
|
|||||||
provider_name: "codex".to_string(),
|
provider_name: "codex".to_string(),
|
||||||
quota_kind: "codex".to_string(),
|
quota_kind: "codex".to_string(),
|
||||||
method: "GET".to_string(),
|
method: "GET".to_string(),
|
||||||
url: CODEX_BACKEND_ME_URL.to_string(),
|
url: CODEX_WHAM_USAGE_URL.to_string(),
|
||||||
headers,
|
headers,
|
||||||
content_type: None,
|
content_type: None,
|
||||||
json_body: None,
|
json_body: None,
|
||||||
client_api_format: "openai:responses".to_string(),
|
client_api_format: "openai:responses".to_string(),
|
||||||
provider_api_format: "openai:responses".to_string(),
|
provider_api_format: "openai:responses".to_string(),
|
||||||
model_name: Some("codex-backend-me".to_string()),
|
model_name: Some("codex-wham-usage".to_string()),
|
||||||
accept_invalid_certs: false,
|
accept_invalid_certs: false,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ pub use chatgpt_web::{
|
|||||||
CHATGPT_WEB_DEFAULT_BASE_URL,
|
CHATGPT_WEB_DEFAULT_BASE_URL,
|
||||||
};
|
};
|
||||||
pub use codex::CodexProviderPoolAdapter;
|
pub use codex::CodexProviderPoolAdapter;
|
||||||
pub use codex::{build_codex_pool_quota_request, CODEX_BACKEND_ME_URL, CODEX_WHAM_USAGE_URL};
|
pub use codex::{build_codex_pool_quota_request, CODEX_WHAM_USAGE_URL};
|
||||||
pub use default::DefaultProviderPoolAdapter;
|
pub use default::DefaultProviderPoolAdapter;
|
||||||
pub use kiro::KiroProviderPoolAdapter;
|
pub use kiro::KiroProviderPoolAdapter;
|
||||||
pub use kiro::{
|
pub use kiro::{
|
||||||
|
|||||||
@@ -104,20 +104,6 @@ impl ProviderPoolService {
|
|||||||
.quota_refresh_missing_endpoint_message()
|
.quota_refresh_missing_endpoint_message()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn supports_account_self_check(&self, provider_type: &str) -> bool {
|
|
||||||
self.adapter(provider_type).supports_account_self_check()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn account_self_check_endpoint_for_provider(
|
|
||||||
&self,
|
|
||||||
provider_type: &str,
|
|
||||||
endpoints: &[StoredProviderCatalogEndpoint],
|
|
||||||
include_inactive: bool,
|
|
||||||
) -> Option<StoredProviderCatalogEndpoint> {
|
|
||||||
self.adapter(provider_type)
|
|
||||||
.account_self_check_endpoint(endpoints, include_inactive)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn normalize_scheduling_presets(
|
pub fn normalize_scheduling_presets(
|
||||||
&self,
|
&self,
|
||||||
provider_type: &str,
|
provider_type: &str,
|
||||||
|
|||||||
@@ -82,4 +82,16 @@ describe('oauthRefreshFeedback', () => {
|
|||||||
message: 'Token 刷新成功,已重新检查额度/账号状态',
|
message: 'Token 刷新成功,已重新检查额度/账号状态',
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it('includes the recheck failure detail after a successful token refresh', () => {
|
||||||
|
expect(
|
||||||
|
getOAuthRefreshFeedback({
|
||||||
|
accountStateRecheckAttempted: true,
|
||||||
|
accountStateRecheckError: 'wham/usage API 返回状态码 401',
|
||||||
|
}),
|
||||||
|
).toEqual({
|
||||||
|
tone: 'warning',
|
||||||
|
message: 'Token 刷新成功,但额度/账号状态复检失败:wham/usage API 返回状态码 401',
|
||||||
|
})
|
||||||
|
})
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -20,6 +20,13 @@ function normalizeText(value: unknown): string | null {
|
|||||||
return text || null
|
return text || null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function formatRecheckError(value: string): string {
|
||||||
|
const collapsed = value.replace(/\s+/g, ' ').trim()
|
||||||
|
const maxLength = 180
|
||||||
|
if (collapsed.length <= maxLength) return collapsed
|
||||||
|
return `${collapsed.slice(0, maxLength - 3).trimEnd()}...`
|
||||||
|
}
|
||||||
|
|
||||||
export function resolveOAuthAccountBlockDisplay(
|
export function resolveOAuthAccountBlockDisplay(
|
||||||
snapshot: ProviderKeyStatusCarrier,
|
snapshot: ProviderKeyStatusCarrier,
|
||||||
): OAuthAccountBlockDisplay {
|
): OAuthAccountBlockDisplay {
|
||||||
@@ -45,7 +52,7 @@ export function getOAuthRefreshFeedback(
|
|||||||
if (recheckError) {
|
if (recheckError) {
|
||||||
return {
|
return {
|
||||||
tone: 'warning',
|
tone: 'warning',
|
||||||
message: 'Token 刷新成功,但额度/账号状态复检失败',
|
message: `Token 刷新成功,但额度/账号状态复检失败:${formatRecheckError(recheckError)}`,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (blockedLabel) {
|
if (blockedLabel) {
|
||||||
|
|||||||
Reference in New Issue
Block a user