mirror of
https://github.com/zyycn/codex-proxy-rs.git
synced 2026-12-05 08:00:53 +00:00
feat(openai): track turn rate limits per account and model
Preserve session scheduling and retry hints while a model cools down. Show active model limits and their recovery times in the account list. Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
1 parent
c71e6176c5
commit
2ddcd7c936
41 files changed
+941
-183
No files matched your search
@@ -92,6 +92,9 @@ pub struct AccountListQuery {
|
||||
/// Admin query service 从运行态存储取得的当前账号冷却快照
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct AccountRuntimeSnapshot {
|
||||
/// 模型维度冷却独立于整账号冷却,不能据此阻断其他模型
|
||||
pub model_cooldowns:
|
||||
BTreeMap<String, Vec<gateway_core::provider_ports::ProviderScopedCooldown>>,
|
||||
pub protection_rules: BTreeMap<String, Vec<gateway_core::account::AccountProtectionMatch>>,
|
||||
pub cooldown: BTreeMap<String, gateway_core::account::AccountCooldown>,
|
||||
/// `None` 表示实时 lease 存储不可用;`Some` 中未出现的账号当前使用量为零
|
||||
@@ -223,6 +226,7 @@ pub struct AccountPage {
|
||||
/// 同一状态快照下的账号事实与唯一状态投影
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AccountPageItem {
|
||||
pub model_cooldowns: Vec<gateway_core::provider_ports::ProviderScopedCooldown>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>,
|
||||
pub account: AccountRecord,
|
||||
|
||||
@@ -1319,6 +1319,7 @@ impl fmt::Debug for ProviderExport {
|
||||
/// 统一账号目录的一行完整结果
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct AccountDirectoryItem {
|
||||
pub model_cooldowns: Vec<gateway_core::provider_ports::ProviderScopedCooldown>,
|
||||
pub platform_icon: Option<String>,
|
||||
pub protection_rules: Vec<gateway_core::account::AccountProtectionMatch>,
|
||||
pub account: AccountRecord,
|
||||
|
||||
@@ -513,6 +513,7 @@ impl DefaultAccountsService {
|
||||
lookback,
|
||||
);
|
||||
Ok(AccountDirectoryItem {
|
||||
model_cooldowns: stored.model_cooldowns,
|
||||
platform_icon: stored.platform_icon,
|
||||
protection_rules: stored.protection_rules,
|
||||
capacity: super::peer_link::upstream::account_capacity(
|
||||
@@ -648,6 +649,7 @@ impl AccountsService for DefaultAccountsService {
|
||||
lookback,
|
||||
);
|
||||
Ok(AccountDirectoryItem {
|
||||
model_cooldowns: item.model_cooldowns,
|
||||
platform_icon: item.platform_icon,
|
||||
protection_rules: item.protection_rules,
|
||||
capacity: crate::model::accounts::AccountCapacity {
|
||||
|
||||
@@ -315,6 +315,7 @@ impl AccountRuntimeStore for FakeRuntimeStore {
|
||||
) -> AdminStoreResult<AccountRuntimeSnapshot> {
|
||||
*self.requested_accounts.lock().expect("requested accounts") = account_ids.to_vec();
|
||||
Ok(AccountRuntimeSnapshot {
|
||||
model_cooldowns: BTreeMap::new(),
|
||||
protection_rules: std::collections::BTreeMap::new(),
|
||||
cooldown: BTreeMap::from([(
|
||||
"acct_limited".to_owned(),
|
||||
|
||||
@@ -740,6 +740,7 @@ impl FakeAccountStore {
|
||||
last_error_message: account.last_error_message.clone(),
|
||||
};
|
||||
AccountPageItem {
|
||||
model_cooldowns: Vec::new(),
|
||||
platform_icon: None,
|
||||
protection_rules: Vec::new(),
|
||||
capacity: gateway_admin::model::accounts::AccountCapacity {
|
||||
|
||||
@@ -67,6 +67,7 @@ pub(super) fn account_view(
|
||||
time: crate::time::TimePresenter,
|
||||
) -> AccountView {
|
||||
let AccountDirectoryItem {
|
||||
model_cooldowns,
|
||||
platform_icon,
|
||||
account,
|
||||
capacity,
|
||||
@@ -111,6 +112,17 @@ pub(super) fn account_view(
|
||||
.map(|value| super::upstream_info::view(value, now, time));
|
||||
let (mut quota, refresh_token_expires_at) = account_quota_view(quota, cooldown, now, time);
|
||||
quota.protection_rules = protection_rules;
|
||||
quota.model_rate_limits = model_cooldowns
|
||||
.into_iter()
|
||||
.map(|cooldown| {
|
||||
let until: DateTime<Utc> = cooldown.until().into();
|
||||
AccountModelRateLimitView {
|
||||
model: cooldown.scope().value().to_owned(),
|
||||
until: time.rfc3339(&until),
|
||||
until_display: time.datetime(&until),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
AccountView {
|
||||
platform_icon,
|
||||
quota_settings: account.quota_settings,
|
||||
@@ -271,6 +283,7 @@ pub(super) fn account_quota_view(
|
||||
let recovery_probe_required = cooldown.is_some_and(|value| value.kind.requires_probe());
|
||||
(
|
||||
AccountQuotaView {
|
||||
model_rate_limits: Vec::new(),
|
||||
paused_windows: quota.paused_windows,
|
||||
refreshed_at: quota.observed_at.map(|value| time.rfc3339(&value)),
|
||||
refreshed_at_relative: quota
|
||||
|
||||
@@ -382,6 +382,7 @@ pub use crate::admin::account_groups::AccountGroupRefView;
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AccountQuotaView {
|
||||
pub model_rate_limits: Vec<AccountModelRateLimitView>,
|
||||
pub paused_windows: Vec<String>,
|
||||
pub refreshed_at: Option<String>,
|
||||
pub refreshed_at_relative: Option<crate::time::RelativeTimeView>,
|
||||
@@ -397,6 +398,14 @@ pub struct AccountQuotaView {
|
||||
pub credits: Option<AccountQuotaCreditsView>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct AccountModelRateLimitView {
|
||||
pub model: String,
|
||||
pub until: String,
|
||||
pub until_display: String,
|
||||
}
|
||||
|
||||
/// 上游点数安全视图,不透出额度响应中的其他 Provider 字段
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -119,22 +119,24 @@ pub fn gateway_error_response(error: &GatewayError) -> Response {
|
||||
}
|
||||
let mut response = (status, Json(body)).into_response();
|
||||
response.extensions_mut().insert(error.clone());
|
||||
if let Some(delay) = error.retry_after()
|
||||
&& let Ok(value) = HeaderValue::from_str(
|
||||
&delay
|
||||
.as_secs()
|
||||
.saturating_add(u64::from(delay.subsec_nanos() > 0))
|
||||
.max(1)
|
||||
.to_string(),
|
||||
)
|
||||
{
|
||||
if let Some(seconds) = retry_after_seconds(error) {
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(axum::http::header::RETRY_AFTER, value);
|
||||
.insert(axum::http::header::RETRY_AFTER, HeaderValue::from(seconds));
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
/// HTTP 和 WS 的等待秒数均向上取整,避免客户端在冷却到期前重新发起请求
|
||||
pub(crate) fn retry_after_seconds(error: &GatewayError) -> Option<u64> {
|
||||
error.retry_after().map(|delay| {
|
||||
delay
|
||||
.as_secs()
|
||||
.saturating_add(u64::from(delay.subsec_nanos() > 0))
|
||||
.max(1)
|
||||
})
|
||||
}
|
||||
|
||||
/// Gateway 错误稳定映射,供 HTTP、SSE 和 WebSocket 共用
|
||||
#[must_use]
|
||||
pub const fn gateway_error_contract(
|
||||
|
||||
@@ -185,6 +185,9 @@ pub(super) fn initial_engine_error_event(
|
||||
response_event_headers(response_headers)
|
||||
};
|
||||
if upstream.is_none() {
|
||||
if let Some(seconds) = crate::client_error::retry_after_seconds(&gateway) {
|
||||
headers.insert("retry-after".to_owned(), Value::String(seconds.to_string()));
|
||||
}
|
||||
// 会话 opening 身份不证明当前失败属于该请求;仅保留其他允许的会话头
|
||||
for name in RESPONSE_REQUEST_ID_HEADERS {
|
||||
headers.remove(name);
|
||||
|
||||
@@ -255,6 +255,18 @@ async fn account_cooldown_returns_an_instant_and_server_formatted_recovery() {
|
||||
last_error_message: None,
|
||||
};
|
||||
let mut item = account_page_item(facts, now, "oauth");
|
||||
let model_until = now + Duration::seconds(8);
|
||||
item.model_cooldowns = vec![gateway_core::provider_ports::ProviderScopedCooldown::new(
|
||||
gateway_core::account::ProviderAccountId::new(item.account.id.clone()).unwrap(),
|
||||
gateway_core::account::CredentialRevision::new(
|
||||
item.account.credential_revision.get(),
|
||||
)
|
||||
.unwrap(),
|
||||
gateway_core::provider_ports::ProviderCooldownScope::upstream_model(
|
||||
gateway_core::routing::UpstreamModelId::new("gpt-5.4").unwrap(),
|
||||
),
|
||||
model_until.into(),
|
||||
)];
|
||||
if kind.is_error_protection() {
|
||||
item.protection_rules = vec![gateway_core::account::AccountProtectionMatch {
|
||||
id: "removed-rule".to_owned(),
|
||||
@@ -278,6 +290,14 @@ async fn account_cooldown_returns_an_instant_and_server_formatted_recovery() {
|
||||
let body = to_bytes(response.into_body(), 32768).await.unwrap();
|
||||
let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
|
||||
let quota = &value["data"]["items"][0]["quota"];
|
||||
assert_eq!(
|
||||
quota["modelRateLimits"],
|
||||
serde_json::json!([{
|
||||
"model": "gpt-5.4",
|
||||
"until": zone.local(model_until).to_rfc3339(),
|
||||
"untilDisplay": zone.local(model_until).format("%Y-%m-%d %H:%M:%S").to_string(),
|
||||
}])
|
||||
);
|
||||
if kind.is_error_protection() {
|
||||
assert_eq!(quota["rateLimitReason"], "error_protection");
|
||||
assert_eq!(
|
||||
@@ -411,6 +431,7 @@ fn account_page_item(
|
||||
use gateway_core::account::resolve_account_status;
|
||||
|
||||
AccountPageItem {
|
||||
model_cooldowns: Vec::new(),
|
||||
platform_icon: None,
|
||||
protection_rules: Vec::new(),
|
||||
account: AccountRecord {
|
||||
|
||||
@@ -564,6 +564,7 @@ mod provider {
|
||||
last_error_message: None,
|
||||
};
|
||||
AccountPageItem {
|
||||
model_cooldowns: Vec::new(),
|
||||
platform_icon: None,
|
||||
protection_rules: Vec::new(),
|
||||
capacity: gateway_admin::model::accounts::AccountCapacity {
|
||||
|
||||
@@ -1484,6 +1484,7 @@ impl AccountRuntimeStore for UnusedStore {
|
||||
|
||||
async fn active_rate_limits(&self) -> AdminStoreResult<AccountRuntimeSnapshot> {
|
||||
Ok(AccountRuntimeSnapshot {
|
||||
model_cooldowns: BTreeMap::new(),
|
||||
cooldown: BTreeMap::new(),
|
||||
protection_rules: BTreeMap::new(),
|
||||
in_flight: Some(BTreeMap::new()),
|
||||
@@ -1492,6 +1493,7 @@ impl AccountRuntimeStore for UnusedStore {
|
||||
|
||||
async fn account_runtime(&self, _: &[String]) -> AdminStoreResult<AccountRuntimeSnapshot> {
|
||||
Ok(AccountRuntimeSnapshot {
|
||||
model_cooldowns: BTreeMap::new(),
|
||||
cooldown: BTreeMap::new(),
|
||||
protection_rules: BTreeMap::new(),
|
||||
in_flight: Some(BTreeMap::new()),
|
||||
|
||||
@@ -384,10 +384,14 @@ fn engine_provider_error_should_preserve_retry_classification() {
|
||||
|
||||
#[test]
|
||||
fn local_provider_capacity_exhaustion_should_map_to_service_unavailable() {
|
||||
let error = EngineError::Provider(ProviderError::new(
|
||||
ProviderErrorKind::AccountCapacityUnavailable,
|
||||
UpstreamSendState::NotSent,
|
||||
));
|
||||
let error = EngineError::Provider(
|
||||
ProviderError::new(
|
||||
ProviderErrorKind::AccountCapacityUnavailable,
|
||||
UpstreamSendState::NotSent,
|
||||
)
|
||||
.with_retry_after(std::time::Duration::from_millis(7100)),
|
||||
);
|
||||
assert_eq!(engine_error_response(&error).headers()["retry-after"], "8");
|
||||
|
||||
let projected = gateway_error_from_engine(&error);
|
||||
assert_eq!(
|
||||
|
||||
@@ -91,6 +91,7 @@ async fn fixture(sharing: ClientPeerSharing, plaintext: &str) -> (AdminTestFixtu
|
||||
last_error_message: None,
|
||||
};
|
||||
*fixture.account.lock().unwrap() = Some(AccountPageItem {
|
||||
model_cooldowns: Vec::new(),
|
||||
platform_icon: None,
|
||||
protection_rules: Vec::new(),
|
||||
capacity: AccountCapacity {
|
||||
|
||||
@@ -1586,6 +1586,11 @@ impl GatewayError {
|
||||
),
|
||||
};
|
||||
let mut gateway = gateway;
|
||||
if gateway.kind() == GatewayErrorKind::AccountCapacityUnavailable
|
||||
&& let Some(delay) = error.retry_after()
|
||||
{
|
||||
gateway = gateway.with_retry_after(delay);
|
||||
}
|
||||
if gateway.kind() == GatewayErrorKind::InvalidRequest
|
||||
&& let Some(details) = error
|
||||
.failure_observation
|
||||
|
||||
@@ -113,6 +113,7 @@ pub struct ProviderScopedCooldown {
|
||||
credential_revision: CredentialRevision,
|
||||
scope: ProviderCooldownScope,
|
||||
until: SystemTime,
|
||||
rate_limited_until: Option<SystemTime>,
|
||||
}
|
||||
|
||||
impl ProviderScopedCooldown {
|
||||
@@ -128,6 +129,7 @@ impl ProviderScopedCooldown {
|
||||
credential_revision,
|
||||
scope,
|
||||
until,
|
||||
rate_limited_until: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,6 +143,18 @@ impl ProviderScopedCooldown {
|
||||
self.credential_revision
|
||||
}
|
||||
|
||||
/// 选号冷却可能还包含模型拒绝;目录只展示实际限流期限
|
||||
#[must_use]
|
||||
pub fn with_rate_limited_until(mut self, until: Option<SystemTime>) -> Self {
|
||||
self.rate_limited_until = until.map(|until| until.min(self.until));
|
||||
self
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn rate_limited_until(&self) -> Option<SystemTime> {
|
||||
self.rate_limited_until
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub const fn scope(&self) -> &ProviderCooldownScope {
|
||||
&self.scope
|
||||
|
||||
@@ -325,19 +325,36 @@ impl AccountStore for PgAdminAccountStore {
|
||||
));
|
||||
}
|
||||
let now = Utc::now();
|
||||
let cooldown = runtime.cooldown;
|
||||
let now_system_time = std::time::SystemTime::from(now);
|
||||
let active_rate_limited_ids = cooldown
|
||||
let active_rate_limited_ids = runtime
|
||||
.cooldown
|
||||
.iter()
|
||||
.filter(|(_, cooldown)| cooldown.is_active(now_system_time))
|
||||
.map(|(account_id, _)| account_id.clone())
|
||||
.collect::<Vec<_>>();
|
||||
let active_model_revisions = runtime
|
||||
.model_cooldowns
|
||||
.iter()
|
||||
.flat_map(|(account, models)| {
|
||||
models
|
||||
.iter()
|
||||
.filter(|model| model.until() > now_system_time)
|
||||
.filter_map(|model| {
|
||||
i64::try_from(model.credential_revision().get())
|
||||
.ok()
|
||||
.map(|revision| (account.clone(), revision))
|
||||
})
|
||||
})
|
||||
.collect::<std::collections::BTreeSet<_>>()
|
||||
.into_iter()
|
||||
.collect();
|
||||
let page = load_admin_account_page(
|
||||
&self.pool,
|
||||
&self.query_budget,
|
||||
&query,
|
||||
now,
|
||||
active_rate_limited_ids,
|
||||
active_model_revisions,
|
||||
)
|
||||
.await?;
|
||||
let item_ids = page
|
||||
@@ -351,14 +368,12 @@ impl AccountStore for PgAdminAccountStore {
|
||||
.into_iter()
|
||||
.map(|(summary, platform_icon)| {
|
||||
let account_id = summary.id.clone();
|
||||
let projection = account_status_projection(
|
||||
&summary,
|
||||
now.into(),
|
||||
cooldown.get(&account_id).copied(),
|
||||
);
|
||||
let (projection, model_cooldowns) =
|
||||
super::runtime::account_directory_projection(&summary, now.into(), &runtime);
|
||||
let mut account = admin_account_record(summary)?;
|
||||
account.groups = groups_by_account.remove(&account_id).unwrap_or_default();
|
||||
Ok(AccountPageItem {
|
||||
model_cooldowns,
|
||||
platform_icon,
|
||||
protection_rules: runtime
|
||||
.protection_rules
|
||||
@@ -397,8 +412,8 @@ impl AccountStore for PgAdminAccountStore {
|
||||
return Ok(None);
|
||||
};
|
||||
let now = Utc::now();
|
||||
let cooldown = runtime.cooldown.get(account_id).copied();
|
||||
let projection = account_status_projection(&record.summary, now.into(), cooldown);
|
||||
let (projection, model_cooldowns) =
|
||||
super::runtime::account_directory_projection(&record.summary, now.into(), &runtime);
|
||||
let account_id = record.summary.id.clone();
|
||||
let mut groups = self
|
||||
.account_groups_by_account(std::slice::from_ref(&account_id))
|
||||
@@ -424,6 +439,7 @@ impl AccountStore for PgAdminAccountStore {
|
||||
)
|
||||
})?;
|
||||
Ok(Some(AccountPageItem {
|
||||
model_cooldowns,
|
||||
platform_icon,
|
||||
protection_rules: runtime
|
||||
.protection_rules
|
||||
|
||||
@@ -16,7 +16,10 @@ pub(crate) async fn load_admin_account_page(
|
||||
query: &AdminAccountListQuery,
|
||||
now: DateTime<Utc>,
|
||||
active_rate_limited_ids: Vec<String>,
|
||||
active_model_revisions: Vec<(String, i64)>,
|
||||
) -> AdminStoreResult<AdminAccountPageRows> {
|
||||
let (model_account_ids, model_revisions): (Vec<_>, Vec<_>) =
|
||||
active_model_revisions.into_iter().unzip();
|
||||
validate_group_filter(pool, query.group_filter.as_ref()).await?;
|
||||
|
||||
let provider_kind = query
|
||||
@@ -56,7 +59,10 @@ pub(crate) async fn load_admin_account_page(
|
||||
when a.credential_state <> 'ready'
|
||||
or a.access_token_expires_at <= $2 then 'error'
|
||||
when a.quota_access_state = 'exhausted' then 'quota_exhausted'
|
||||
when a.id = any($1::text[]) then 'rate_limited'
|
||||
when a.id = any($1::text[]) or exists (
|
||||
select 1 from unnest($13::text[], $14::bigint[]) as limits(account_id, revision)
|
||||
where limits.account_id = a.id and limits.revision = a.credential_revision
|
||||
) then 'rate_limited'
|
||||
when a.quota_paused then 'quota_paused'
|
||||
else 'normal'
|
||||
end as admin_status
|
||||
@@ -165,6 +171,8 @@ pub(crate) async fn load_admin_account_page(
|
||||
.bind(usage_ids)
|
||||
.bind(usage_tokens)
|
||||
.bind(usage_latest)
|
||||
.bind(model_account_ids)
|
||||
.bind(model_revisions)
|
||||
.fetch_all(&mut *snapshot.tx)
|
||||
.await
|
||||
.map_err(|source| postgres_unavailable("load admin account page", source))?;
|
||||
|
||||
@@ -12,6 +12,40 @@ use gateway_core::{
|
||||
|
||||
use super::ProviderAccountSummary;
|
||||
|
||||
pub(crate) fn account_directory_projection(
|
||||
account: &ProviderAccountSummary,
|
||||
now: SystemTime,
|
||||
runtime: &gateway_admin::model::accounts::AccountRuntimeSnapshot,
|
||||
) -> (
|
||||
AccountStatusProjection,
|
||||
Vec<gateway_core::provider_ports::ProviderScopedCooldown>,
|
||||
) {
|
||||
let models = runtime
|
||||
.model_cooldowns
|
||||
.get(&account.id)
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|cooldown| {
|
||||
cooldown.credential_revision().get() == account.credential_revision.get()
|
||||
&& cooldown.until() > now
|
||||
})
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
let mut projection =
|
||||
account_status_projection(account, now, runtime.cooldown.get(&account.id).copied());
|
||||
// 目录汇总展示部分模型受限,不将其写入整账号 cooldown 或用于其他模型的调度
|
||||
if !models.is_empty()
|
||||
&& matches!(
|
||||
projection.status,
|
||||
gateway_core::account::AccountStatus::Normal
|
||||
| gateway_core::account::AccountStatus::QuotaPaused
|
||||
)
|
||||
{
|
||||
projection.status = gateway_core::account::AccountStatus::RateLimited;
|
||||
}
|
||||
(projection, models)
|
||||
}
|
||||
|
||||
#[must_use]
|
||||
pub(crate) fn account_status_projection(
|
||||
account: &ProviderAccountSummary,
|
||||
|
||||
@@ -11,7 +11,7 @@ use gateway_core::{
|
||||
},
|
||||
};
|
||||
use redis::{Script, aio::ConnectionManager};
|
||||
use std::{collections::BTreeMap, sync::LazyLock};
|
||||
use std::{collections::BTreeMap, sync::LazyLock, time::SystemTime};
|
||||
|
||||
use crate::{Revision, StoreError, StoreResult, redis_unavailable, require_nonempty};
|
||||
|
||||
@@ -55,6 +55,42 @@ static WRITE_ACCOUNT: LazyLock<Script> = LazyLock::new(|| {
|
||||
)
|
||||
});
|
||||
|
||||
// 模型事实与目录索引同次写入;普通成功只清整账号冷却,不触碰这里的期限
|
||||
const WRITE_SCOPED: &str = r#"
|
||||
local current = tonumber(redis.call('HGET', KEYS[1], 'revision') or '0')
|
||||
local incoming = tonumber(ARGV[1])
|
||||
local until_ms = tonumber(ARGV[2])
|
||||
local limited_ms = tonumber(ARGV[4])
|
||||
local clock = redis.call('TIME')
|
||||
local now_ms = tonumber(clock[1]) * 1000 + math.floor(tonumber(clock[2]) / 1000)
|
||||
if current > incoming or until_ms <= now_ms then return 0 end
|
||||
if current == incoming then
|
||||
local previous = tonumber(redis.call('HGET', KEYS[1], 'until_ms') or '0')
|
||||
local limited = tonumber(redis.call('HGET', KEYS[1], 'rate_limited_until_ms') or '0')
|
||||
if previous >= until_ms and limited >= limited_ms then return 0 end
|
||||
until_ms = math.max(previous, until_ms)
|
||||
limited_ms = math.max(limited, limited_ms)
|
||||
end
|
||||
redis.call('HSET', KEYS[1], 'revision', incoming, 'until_ms', until_ms, 'rate_limited_until_ms', limited_ms)
|
||||
redis.call('PEXPIREAT', KEYS[1], until_ms + 60000)
|
||||
if limited_ms > now_ms then
|
||||
redis.call('ZADD', KEYS[2], limited_ms, ARGV[3])
|
||||
local latest = redis.call('ZRANGE', KEYS[2], -1, -1, 'WITHSCORES')
|
||||
redis.call('PEXPIREAT', KEYS[2], tonumber(latest[2]) + 60000)
|
||||
redis.call('ZADD', KEYS[3], 'GT', latest[2], ARGV[5])
|
||||
else
|
||||
redis.call('ZREM', KEYS[2], ARGV[3])
|
||||
end
|
||||
return 1
|
||||
"#;
|
||||
|
||||
const ACTIVE_SCOPES: &str = r#"
|
||||
local clock = redis.call('TIME')
|
||||
local now_ms = tonumber(clock[1]) * 1000 + math.floor(tonumber(clock[2]) / 1000)
|
||||
redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', now_ms)
|
||||
return redis.call('ZRANGE', KEYS[1], 0, -1)
|
||||
"#;
|
||||
|
||||
const READ_SCOPED: &str = r#"
|
||||
local revision = redis.call('HGET', KEYS[1], 'revision')
|
||||
local until_ms = redis.call('HGET', KEYS[1], 'until_ms')
|
||||
@@ -62,9 +98,9 @@ local clock = redis.call('TIME')
|
||||
local now_ms = (tonumber(clock[1]) * 1000) + math.floor(tonumber(clock[2]) / 1000)
|
||||
if not revision or not until_ms or tonumber(until_ms) <= now_ms then
|
||||
redis.call('DEL', KEYS[1])
|
||||
return {0, '0', '0'}
|
||||
return {0, '0', '0', '0'}
|
||||
end
|
||||
return {1, revision, until_ms}
|
||||
return {1, revision, until_ms, redis.call('HGET', KEYS[1], 'rate_limited_until_ms') or '0'}
|
||||
"#;
|
||||
|
||||
const INVALIDATE_SCRIPT: &str = r#"
|
||||
@@ -132,6 +168,73 @@ impl RedisCredentialCooldownRepository {
|
||||
format!("{}:account:active-cooldowns", self.namespace)
|
||||
}
|
||||
|
||||
fn model_index_key(&self, account: &str) -> StoreResult<String> {
|
||||
Ok(format!("{}:models", self.key(account)?))
|
||||
}
|
||||
|
||||
fn active_model_index_key(&self) -> String {
|
||||
format!("{}:account:active-model-cooldowns", self.namespace)
|
||||
}
|
||||
|
||||
async fn read_model_cooldowns(
|
||||
&self,
|
||||
account: &str,
|
||||
) -> StoreResult<Vec<ProviderScopedCooldown>> {
|
||||
let models: Vec<String> = Script::new(ACTIVE_SCOPES)
|
||||
.key(self.model_index_key(account)?)
|
||||
.invoke_async(&mut self.connection.clone())
|
||||
.await
|
||||
.map_err(|source| redis_unavailable("list account model cooldowns", source))?;
|
||||
let account =
|
||||
ProviderAccountId::new(account).map_err(|_| invalid("invalid cooldown account"))?;
|
||||
let scopes = models
|
||||
.into_iter()
|
||||
.map(|model| {
|
||||
gateway_core::routing::UpstreamModelId::new(model)
|
||||
.map(ProviderCooldownScope::upstream_model)
|
||||
.map_err(|_| invalid("invalid cooldown model"))
|
||||
})
|
||||
.collect::<StoreResult<Vec<_>>>()?;
|
||||
let mut cooldowns = Vec::new();
|
||||
for scopes in scopes.chunks(COOLDOWN_READ_BATCH_SIZE) {
|
||||
let script = Script::new(READ_SCOPED);
|
||||
let commands = scopes
|
||||
.iter()
|
||||
.map(|scope| {
|
||||
let mut command = redis::cmd("EVALSHA");
|
||||
command
|
||||
.arg(script.get_hash())
|
||||
.arg(1)
|
||||
.arg(self.scoped_key(account.as_str(), scope)?);
|
||||
Ok(command)
|
||||
})
|
||||
.collect();
|
||||
for (scope, value) in scopes
|
||||
.iter()
|
||||
.zip(self.read_script_batch(&script, commands).await)
|
||||
{
|
||||
let value = redis::from_redis_value(value?)
|
||||
.map_err(|source| redis_unavailable("decode model cooldown", source))?;
|
||||
if let Some(cooldown) = parse_scoped_cooldown(value, &account, scope)?
|
||||
&& let Some(until) = cooldown
|
||||
.rate_limited_until()
|
||||
.filter(|until| *until > SystemTime::now())
|
||||
{
|
||||
cooldowns.push(
|
||||
ProviderScopedCooldown::new(
|
||||
account.clone(),
|
||||
cooldown.credential_revision(),
|
||||
scope.clone(),
|
||||
until,
|
||||
)
|
||||
.with_rate_limited_until(Some(until)),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(cooldowns)
|
||||
}
|
||||
|
||||
fn capacity_failures_key(&self, provider_account_id: &str) -> StoreResult<String> {
|
||||
let fingerprint = resource_fingerprint("credential cooldown", provider_account_id)?;
|
||||
Ok(format!(
|
||||
@@ -168,49 +271,27 @@ impl RedisCredentialCooldownRepository {
|
||||
credential_revision: Revision,
|
||||
cooldown_until: DateTime<Utc>,
|
||||
kind: ProviderCooldownKind,
|
||||
index_member: Option<&str>,
|
||||
index_member: &str,
|
||||
) -> StoreResult<bool> {
|
||||
let until_ms = cooldown_until.timestamp_millis();
|
||||
if until_ms <= 0 {
|
||||
return Err(invalid("cooldown expiry must be positive"));
|
||||
}
|
||||
let mut connection = self.connection.clone();
|
||||
let written = if let Some(index_member) = index_member {
|
||||
WRITE_ACCOUNT
|
||||
.key(key)
|
||||
.key(self.active_index_key())
|
||||
.key(self.protection_key(index_member)?)
|
||||
.key(self.protection_index_key())
|
||||
.arg(credential_revision.get())
|
||||
.arg(until_ms)
|
||||
.arg(index_member)
|
||||
.arg(kind.as_str())
|
||||
.arg(uuid::Uuid::new_v4().to_string())
|
||||
.invoke_async::<i64>(&mut connection)
|
||||
.await
|
||||
} else {
|
||||
Script::new(WRITE_SCRIPT)
|
||||
.key(key)
|
||||
.arg(credential_revision.get())
|
||||
.arg(until_ms)
|
||||
.arg("")
|
||||
.arg(kind.as_str())
|
||||
.arg(uuid::Uuid::new_v4().to_string())
|
||||
.invoke_async::<i64>(&mut connection)
|
||||
.await
|
||||
}
|
||||
.map_err(|source| redis_unavailable("cache credential cooldown", source))?;
|
||||
Ok(written == 1)
|
||||
}
|
||||
|
||||
async fn read_scoped_key(&self, key: String) -> StoreResult<Option<(Revision, DateTime<Utc>)>> {
|
||||
let result = Script::new(READ_SCOPED)
|
||||
let written = WRITE_ACCOUNT
|
||||
.key(key)
|
||||
.invoke_async(&mut self.connection.clone())
|
||||
.await;
|
||||
parse_scoped_cooldown(
|
||||
result.map_err(|source| redis_unavailable("read credential cooldown", source))?,
|
||||
)
|
||||
.key(self.active_index_key())
|
||||
.key(self.protection_key(index_member)?)
|
||||
.key(self.protection_index_key())
|
||||
.arg(credential_revision.get())
|
||||
.arg(until_ms)
|
||||
.arg(index_member)
|
||||
.arg(kind.as_str())
|
||||
.arg(uuid::Uuid::new_v4().to_string())
|
||||
.invoke_async::<i64>(&mut connection)
|
||||
.await
|
||||
.map_err(|source| redis_unavailable("cache credential cooldown", source))?;
|
||||
Ok(written == 1)
|
||||
}
|
||||
|
||||
/// 保留每条命令的错误,脚本失效时只补发尚未执行的 NOSCRIPT 项
|
||||
@@ -294,26 +375,18 @@ impl RedisCredentialCooldownRepository {
|
||||
&self,
|
||||
key: String,
|
||||
through_revision: Revision,
|
||||
index_member: Option<&str>,
|
||||
index_key: String,
|
||||
index_member: &str,
|
||||
) -> StoreResult<bool> {
|
||||
let mut connection = self.connection.clone();
|
||||
let removed = if let Some(index_member) = index_member {
|
||||
Script::new(INVALIDATE_SCRIPT)
|
||||
.key(key)
|
||||
.key(self.active_index_key())
|
||||
.arg(through_revision.get())
|
||||
.arg(index_member)
|
||||
.invoke_async::<i64>(&mut connection)
|
||||
.await
|
||||
} else {
|
||||
Script::new(INVALIDATE_SCRIPT)
|
||||
.key(key)
|
||||
.arg(through_revision.get())
|
||||
.arg("")
|
||||
.invoke_async::<i64>(&mut connection)
|
||||
.await
|
||||
}
|
||||
.map_err(|source| redis_unavailable("invalidate credential cooldown", source))?;
|
||||
let removed = Script::new(INVALIDATE_SCRIPT)
|
||||
.key(key)
|
||||
.key(index_key)
|
||||
.arg(through_revision.get())
|
||||
.arg(index_member)
|
||||
.invoke_async::<i64>(&mut connection)
|
||||
.await
|
||||
.map_err(|source| redis_unavailable("invalidate credential cooldown", source))?;
|
||||
Ok(removed == 1)
|
||||
}
|
||||
|
||||
@@ -337,8 +410,16 @@ impl RedisCredentialCooldownRepository {
|
||||
}
|
||||
|
||||
pub(crate) async fn active_cooldowns(&self) -> StoreResult<AccountRuntimeSnapshot> {
|
||||
self.read_cooldown_accounts(self.all_cooldown_accounts().await?)
|
||||
let mut accounts = self.all_cooldown_accounts().await?;
|
||||
let model_accounts: Vec<String> = Script::new(ACTIVE_SCOPES)
|
||||
.key(self.active_model_index_key())
|
||||
.invoke_async(&mut self.connection.clone())
|
||||
.await
|
||||
.map_err(|source| redis_unavailable("list model cooldown accounts", source))?;
|
||||
accounts.extend(model_accounts);
|
||||
accounts.sort_unstable();
|
||||
accounts.dedup();
|
||||
self.read_cooldown_accounts(accounts).await
|
||||
}
|
||||
|
||||
pub(crate) async fn account_cooldowns(
|
||||
@@ -349,13 +430,16 @@ impl RedisCredentialCooldownRepository {
|
||||
return Ok(AccountRuntimeSnapshot::default());
|
||||
}
|
||||
// 索引与冷却事实由 Lua 原子维护,只读取范围内实际有状态的账号
|
||||
let (cooldowns, protections): (Vec<Option<f64>>, Vec<Option<f64>>) = redis::pipe()
|
||||
let [cooldowns, protections, models]: [Vec<Option<f64>>; 3] = redis::pipe()
|
||||
.cmd("ZMSCORE")
|
||||
.arg(self.active_index_key())
|
||||
.arg(accounts)
|
||||
.cmd("ZMSCORE")
|
||||
.arg(self.protection_index_key())
|
||||
.arg(accounts)
|
||||
.cmd("ZMSCORE")
|
||||
.arg(self.active_model_index_key())
|
||||
.arg(accounts)
|
||||
.query_async(&mut self.connection.clone())
|
||||
.await
|
||||
.map_err(|error| redis_unavailable("read scoped account cooldown index", error))?;
|
||||
@@ -363,8 +447,11 @@ impl RedisCredentialCooldownRepository {
|
||||
.iter()
|
||||
.zip(cooldowns)
|
||||
.zip(protections)
|
||||
.filter(|((_, cooldown), protection)| cooldown.is_some() || protection.is_some())
|
||||
.map(|((account, _), _)| account.clone())
|
||||
.zip(models)
|
||||
.filter(|(((_, cooldown), protection), model)| {
|
||||
cooldown.is_some() || protection.is_some() || model.is_some()
|
||||
})
|
||||
.map(|(((account, _), _), _)| account.clone())
|
||||
.collect();
|
||||
self.read_cooldown_accounts(active).await
|
||||
}
|
||||
@@ -376,15 +463,20 @@ impl RedisCredentialCooldownRepository {
|
||||
use futures::{StreamExt as _, TryStreamExt as _};
|
||||
let reads = futures::stream::iter(accounts)
|
||||
.map(|account| async move {
|
||||
self.read_account_runtime(&account)
|
||||
.await
|
||||
.map(|runtime| (account, runtime))
|
||||
let (runtime, models) = tokio::try_join!(
|
||||
self.read_account_runtime(&account),
|
||||
self.read_model_cooldowns(&account),
|
||||
)?;
|
||||
Ok((account, runtime, models))
|
||||
})
|
||||
.buffer_unordered(32)
|
||||
.try_collect::<Vec<_>>()
|
||||
.await?;
|
||||
let mut snapshot = AccountRuntimeSnapshot::default();
|
||||
for (account, (cooldown, freeze)) in reads {
|
||||
for (account, (cooldown, freeze), models) in reads {
|
||||
if !models.is_empty() {
|
||||
snapshot.model_cooldowns.insert(account.clone(), models);
|
||||
}
|
||||
if let Some(cooldown) = cooldown {
|
||||
snapshot.cooldown.insert(
|
||||
account.clone(),
|
||||
@@ -446,7 +538,7 @@ impl CredentialCooldownRepository for RedisCredentialCooldownRepository {
|
||||
cooldown.credential_revision,
|
||||
cooldown.cooldown_until,
|
||||
cooldown.kind,
|
||||
Some(&cooldown.provider_account_id),
|
||||
&cooldown.provider_account_id,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -480,7 +572,8 @@ impl CredentialCooldownRepository for RedisCredentialCooldownRepository {
|
||||
.invalidate_at_key(
|
||||
self.key(provider_account_id)?,
|
||||
through_revision,
|
||||
Some(provider_account_id),
|
||||
self.active_index_key(),
|
||||
provider_account_id,
|
||||
)
|
||||
.await?;
|
||||
Ok(protection_cleared || cooldown_cleared)
|
||||
@@ -530,6 +623,7 @@ impl CredentialCooldownRepository for RedisCredentialCooldownRepository {
|
||||
local removed = 0
|
||||
for i = 2, #KEYS do removed = removed + redis.call('DEL', KEYS[i]) end
|
||||
redis.call('ZREM', ARGV[2], ARGV[1])
|
||||
redis.call('ZREM', ARGV[3], ARGV[1])
|
||||
return removed + redis.call('ZREM', KEYS[1], ARGV[1])
|
||||
"#,
|
||||
)
|
||||
@@ -537,6 +631,7 @@ impl CredentialCooldownRepository for RedisCredentialCooldownRepository {
|
||||
.key(keys)
|
||||
.arg(provider_account_id)
|
||||
.arg(self.protection_index_key())
|
||||
.arg(self.active_model_index_key())
|
||||
.invoke_async(&mut connection)
|
||||
.await
|
||||
.map_err(|source| redis_unavailable("delete account cooldowns and index", source))?;
|
||||
@@ -686,18 +781,37 @@ impl ProviderCooldownPort for RedisCredentialCooldownRepository {
|
||||
Box::pin(async move {
|
||||
let revision = Revision::new(cooldown.credential_revision().get())
|
||||
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?;
|
||||
self.cache_at_key(
|
||||
self.scoped_key(cooldown.account_id().as_str(), cooldown.scope())
|
||||
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?,
|
||||
revision,
|
||||
cooldown.until().into(),
|
||||
ProviderCooldownKind::RateLimit,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.map_err(|source| {
|
||||
crate::provider_unavailable("cache scoped credential cooldown", source)
|
||||
})
|
||||
let account = cooldown.account_id().as_str();
|
||||
let key = self
|
||||
.scoped_key(account, cooldown.scope())
|
||||
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?;
|
||||
let index = self
|
||||
.model_index_key(account)
|
||||
.map_err(|_| provider_invalid("encode model cooldown index"))?;
|
||||
let until: DateTime<Utc> = cooldown.until().into();
|
||||
let written: i64 = Script::new(WRITE_SCOPED)
|
||||
.key(key)
|
||||
.key(index)
|
||||
.key(self.active_model_index_key())
|
||||
.arg(revision.get())
|
||||
.arg(until.timestamp_millis())
|
||||
.arg(cooldown.scope().value())
|
||||
.arg(
|
||||
cooldown
|
||||
.rate_limited_until()
|
||||
.map(DateTime::<Utc>::from)
|
||||
.map_or(0, |time| time.timestamp_millis()),
|
||||
)
|
||||
.arg(account)
|
||||
.invoke_async(&mut self.connection.clone())
|
||||
.await
|
||||
.map_err(|source| {
|
||||
crate::provider_unavailable(
|
||||
"cache scoped credential cooldown",
|
||||
redis_unavailable("write model cooldown", source),
|
||||
)
|
||||
})?;
|
||||
Ok(written == 1)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -708,24 +822,18 @@ impl ProviderCooldownPort for RedisCredentialCooldownRepository {
|
||||
) -> futures::future::BoxFuture<'a, Result<Option<ProviderScopedCooldown>, ProviderStoreError>>
|
||||
{
|
||||
Box::pin(async move {
|
||||
self.read_scoped_key(
|
||||
self.scoped_key(account_id.as_str(), scope)
|
||||
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?,
|
||||
)
|
||||
.await
|
||||
.map_err(|source| {
|
||||
let key = self
|
||||
.scoped_key(account_id.as_str(), scope)
|
||||
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?;
|
||||
let value = Script::new(READ_SCOPED)
|
||||
.key(key)
|
||||
.invoke_async(&mut self.connection.clone())
|
||||
.await
|
||||
.map_err(|source| redis_unavailable("read scoped cooldown", source))
|
||||
.and_then(|value| parse_scoped_cooldown(value, account_id, scope));
|
||||
value.map_err(|source| {
|
||||
crate::provider_unavailable("read scoped credential cooldown", source)
|
||||
})?
|
||||
.map(|(revision, until)| {
|
||||
Ok(ProviderScopedCooldown::new(
|
||||
account_id.clone(),
|
||||
CredentialRevision::new(revision.get())
|
||||
.map_err(|_| provider_invalid("decode scoped credential cooldown"))?,
|
||||
scope.clone(),
|
||||
until.into(),
|
||||
))
|
||||
})
|
||||
.transpose()
|
||||
})
|
||||
}
|
||||
|
||||
@@ -754,28 +862,16 @@ impl ProviderCooldownPort for RedisCredentialCooldownRepository {
|
||||
.collect();
|
||||
let values = self.read_script_batch(&script, commands).await;
|
||||
results.extend(batch.iter().zip(values).map(|(account, value)| {
|
||||
let value = value
|
||||
value
|
||||
.and_then(|value| {
|
||||
redis::from_redis_value(value).map_err(|source| {
|
||||
redis_unavailable("decode scoped cooldown", source)
|
||||
})
|
||||
})
|
||||
.and_then(parse_scoped_cooldown)
|
||||
.and_then(|value| parse_scoped_cooldown(value, account, scope))
|
||||
.map_err(|source| {
|
||||
crate::provider_unavailable("read scoped credential cooldown", source)
|
||||
})?;
|
||||
value
|
||||
.map(|(revision, until)| {
|
||||
Ok(ProviderScopedCooldown::new(
|
||||
account.clone(),
|
||||
CredentialRevision::new(revision.get()).map_err(|_| {
|
||||
provider_invalid("decode scoped credential cooldown")
|
||||
})?,
|
||||
scope.clone(),
|
||||
until.into(),
|
||||
))
|
||||
})
|
||||
.transpose()
|
||||
}));
|
||||
}
|
||||
results
|
||||
@@ -795,7 +891,9 @@ impl ProviderCooldownPort for RedisCredentialCooldownRepository {
|
||||
self.scoped_key(account_id.as_str(), scope)
|
||||
.map_err(|_| provider_invalid("encode scoped credential cooldown"))?,
|
||||
revision,
|
||||
None,
|
||||
self.model_index_key(account_id.as_str())
|
||||
.map_err(|_| provider_invalid("encode model cooldown index"))?,
|
||||
scope.value(),
|
||||
)
|
||||
.await
|
||||
.map_err(|source| {
|
||||
@@ -858,21 +956,35 @@ pub(super) fn invalid(message: &str) -> StoreError {
|
||||
}
|
||||
}
|
||||
|
||||
type ScopedCooldownReply = (i64, String, i64, i64);
|
||||
|
||||
fn parse_scoped_cooldown(
|
||||
(present, revision, until_ms): (i64, String, String),
|
||||
) -> StoreResult<Option<(Revision, DateTime<Utc>)>> {
|
||||
(present, revision, until_ms, limited_ms): ScopedCooldownReply,
|
||||
account: &ProviderAccountId,
|
||||
scope: &ProviderCooldownScope,
|
||||
) -> StoreResult<Option<ProviderScopedCooldown>> {
|
||||
if present == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let revision = revision
|
||||
.parse::<u64>()
|
||||
.map_err(|source| invalid("cached cooldown revision is invalid").with_source(source))?;
|
||||
let until_ms = until_ms
|
||||
.parse::<i64>()
|
||||
.map_err(|source| invalid("cached cooldown expiry is invalid").with_source(source))?;
|
||||
let cooldown_until = DateTime::from_timestamp_millis(until_ms)
|
||||
.ok_or_else(|| invalid("cached cooldown expiry is invalid"))?;
|
||||
Ok(Some((Revision::new(revision)?, cooldown_until)))
|
||||
let revision =
|
||||
CredentialRevision::new(revision).map_err(|_| invalid("invalid cooldown revision"))?;
|
||||
let deadline = |ms| {
|
||||
DateTime::from_timestamp_millis(ms)
|
||||
.map(SystemTime::from)
|
||||
.ok_or_else(|| invalid("cached cooldown expiry is invalid"))
|
||||
};
|
||||
Ok(Some(
|
||||
ProviderScopedCooldown::new(
|
||||
account.clone(),
|
||||
revision,
|
||||
scope.clone(),
|
||||
deadline(until_ms)?,
|
||||
)
|
||||
.with_rate_limited_until((limited_ms > 0).then(|| deadline(limited_ms)).transpose()?),
|
||||
))
|
||||
}
|
||||
|
||||
fn provider_cooldown(record: CredentialCooldown) -> Result<ProviderCooldown, ProviderStoreError> {
|
||||
|
||||
@@ -2,6 +2,76 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn model_cooldown_status_filter_and_details_share_revision_and_expiry_rules() {
|
||||
use gateway_core::provider_ports::{ProviderCooldownScope, ProviderScopedCooldown};
|
||||
let Some(database) = TestDatabase::create("account_model_cooldown").await else {
|
||||
return;
|
||||
};
|
||||
let repository = PgProviderAccountRepository::new(database.pool.clone());
|
||||
let ids = ["acct_active", "acct_stale", "acct_expired", "acct_disabled"];
|
||||
for id in ids {
|
||||
let mut record = account(id, id);
|
||||
record.enabled = id != "acct_disabled";
|
||||
repository.insert_provider_account(record).await.unwrap();
|
||||
}
|
||||
let mut runtime = AccountRuntimeSnapshot::default();
|
||||
for id in ids {
|
||||
let stored = repository.load_provider_account(id).await.unwrap().unwrap();
|
||||
let revision = stored.summary.credential_revision.get();
|
||||
let revision = if id == "acct_stale" {
|
||||
revision + 1
|
||||
} else {
|
||||
revision
|
||||
};
|
||||
let until = Utc::now() + TimeDelta::seconds(if id == "acct_expired" { -1 } else { 60 });
|
||||
runtime.model_cooldowns.insert(
|
||||
id.into(),
|
||||
vec![ProviderScopedCooldown::new(
|
||||
ProviderAccountId::new(id).unwrap(),
|
||||
gateway_core::account::CredentialRevision::new(revision).unwrap(),
|
||||
ProviderCooldownScope::upstream_model(
|
||||
gateway_core::routing::UpstreamModelId::new("gpt-5.4").unwrap(),
|
||||
),
|
||||
until.into(),
|
||||
)],
|
||||
);
|
||||
}
|
||||
let store = admin_account_store(&database.pool);
|
||||
let page = store
|
||||
.list_accounts(
|
||||
AccountListQuery {
|
||||
page: 1,
|
||||
page_size: PageSize::new(20).unwrap(),
|
||||
provider_kind: None,
|
||||
group_filter: None,
|
||||
search: None,
|
||||
status: Some(AccountStatus::RateLimited),
|
||||
sort: None,
|
||||
},
|
||||
runtime.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(page.total, 1);
|
||||
assert_eq!(page.summary.rate_limited, 1);
|
||||
assert_eq!(page.summary.normal, 2);
|
||||
assert_eq!(page.summary.disabled, 1);
|
||||
let item = &page.items[0];
|
||||
assert_eq!(item.account.id, "acct_active");
|
||||
assert_eq!(item.projection.status, AccountStatus::RateLimited);
|
||||
assert!(item.projection.cooldown.is_none());
|
||||
assert_eq!(item.model_cooldowns.len(), 1);
|
||||
let detail = store
|
||||
.load_account("acct_active", runtime)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(detail.projection, item.projection);
|
||||
assert_eq!(detail.model_cooldowns, item.model_cooldowns);
|
||||
database.close().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn import_name_only_overrides_a_single_account_and_keeps_batch_names() {
|
||||
use gateway_admin::model::accounts::AccountImportSettings;
|
||||
|
||||
@@ -940,6 +940,7 @@ async fn terminal_admin_list_filters_and_sorts_before_pagination_with_retained_u
|
||||
sort: None,
|
||||
},
|
||||
AccountRuntimeSnapshot {
|
||||
model_cooldowns: BTreeMap::new(),
|
||||
protection_rules: std::collections::BTreeMap::new(),
|
||||
cooldown: BTreeMap::from([(
|
||||
"acct_alpha".to_owned(),
|
||||
|
||||
@@ -313,7 +313,12 @@ async fn scoped_cooldown_isolated_by_model_and_revision_fenced() {
|
||||
.is_some()
|
||||
);
|
||||
let keys = namespace_keys(&mut connection, &namespace).await;
|
||||
assert_eq!(keys.len(), 1);
|
||||
assert_eq!(
|
||||
keys.iter()
|
||||
.filter(|key| key.contains(":cooldown:model:"))
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
assert!(!keys[0].contains(account_id.as_str()));
|
||||
assert!(!keys[0].contains(model_b.value()));
|
||||
}
|
||||
@@ -516,6 +521,142 @@ fn runtime_store(
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn model_cooldowns_are_visible_in_runtime_without_blocking_the_entire_account() {
|
||||
use gateway_admin::ports::store::AccountRuntimeStore as _;
|
||||
let Some((repository, connection, namespace)) = repository().await else {
|
||||
return;
|
||||
};
|
||||
let runtime = runtime_store(&repository, connection, &namespace);
|
||||
let id = ProviderAccountId::new("acct_model_limit").unwrap();
|
||||
let revision = CredentialRevision::new(1).unwrap();
|
||||
let models = ["gpt-5.4", "gpt-5.5"].map(|model| {
|
||||
ProviderCooldownScope::upstream_model(
|
||||
gateway_core::routing::UpstreamModelId::new(model).unwrap(),
|
||||
)
|
||||
});
|
||||
let until: SystemTime = millisecond_precision(Utc::now() + Duration::seconds(60)).into();
|
||||
// 不支持的模型仍影响选号,但不能让目录误报限流;两种期限可重叠
|
||||
let unsupported_until = until + std::time::Duration::from_secs(1800);
|
||||
repository
|
||||
.put_scoped_if_later(ProviderScopedCooldown::new(
|
||||
id.clone(),
|
||||
revision,
|
||||
models[0].clone(),
|
||||
unsupported_until,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
runtime
|
||||
.active_rate_limits()
|
||||
.await
|
||||
.unwrap()
|
||||
.model_cooldowns
|
||||
.is_empty()
|
||||
);
|
||||
for scope in &models {
|
||||
repository
|
||||
.put_scoped_if_later(
|
||||
ProviderScopedCooldown::new(id.clone(), revision, scope.clone(), until)
|
||||
.with_rate_limited_until(Some(until)),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
repository.clear_after_success(&id, revision).await.unwrap();
|
||||
let snapshot = runtime.active_rate_limits().await.unwrap();
|
||||
assert!(snapshot.cooldown.is_empty());
|
||||
assert_eq!(snapshot.model_cooldowns[id.as_str()].len(), 2);
|
||||
assert!(
|
||||
snapshot.model_cooldowns[id.as_str()]
|
||||
.iter()
|
||||
.all(|model| model.until() == until)
|
||||
);
|
||||
assert_eq!(
|
||||
repository
|
||||
.read_scoped(&id, &models[0])
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.until(),
|
||||
unsupported_until
|
||||
);
|
||||
let scoped = runtime
|
||||
.account_rate_limits(&[id.to_string()])
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(scoped.model_cooldowns, snapshot.model_cooldowns);
|
||||
repository
|
||||
.clear_scoped(&id, &models[0], revision)
|
||||
.await
|
||||
.unwrap();
|
||||
let snapshot = runtime.active_rate_limits().await.unwrap();
|
||||
assert_eq!(snapshot.model_cooldowns[id.as_str()].len(), 1);
|
||||
assert_eq!(snapshot.model_cooldowns[id.as_str()][0].scope(), &models[1]);
|
||||
repository
|
||||
.delete_account_cooldowns(id.as_str())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
runtime
|
||||
.active_rate_limits()
|
||||
.await
|
||||
.unwrap()
|
||||
.model_cooldowns
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn expired_model_cooldown_disappears_from_the_directory_even_during_redis_grace() {
|
||||
use gateway_admin::ports::store::AccountRuntimeStore as _;
|
||||
let Some((repository, mut connection, namespace)) = repository().await else {
|
||||
return;
|
||||
};
|
||||
let runtime = runtime_store(&repository, connection.clone(), &namespace);
|
||||
let id = ProviderAccountId::new("acct_model_expired").unwrap();
|
||||
let until = (Utc::now() + Duration::minutes(1)).into();
|
||||
repository
|
||||
.put_scoped_if_later(
|
||||
ProviderScopedCooldown::new(
|
||||
id.clone(),
|
||||
CredentialRevision::new(1).unwrap(),
|
||||
ProviderCooldownScope::upstream_model(
|
||||
gateway_core::routing::UpstreamModelId::new("gpt-5.4").unwrap(),
|
||||
),
|
||||
until,
|
||||
)
|
||||
.with_rate_limited_until(Some(until)),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let key = namespace_keys(&mut connection, &namespace)
|
||||
.await
|
||||
.into_iter()
|
||||
.find(|key| key.contains(":cooldown:model:"))
|
||||
.unwrap();
|
||||
redis::cmd("HSET")
|
||||
.arg(key)
|
||||
.arg("until_ms")
|
||||
.arg(Utc::now().timestamp_millis() - 1000)
|
||||
.query_async::<i64>(&mut connection)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
runtime
|
||||
.active_rate_limits()
|
||||
.await
|
||||
.unwrap()
|
||||
.model_cooldowns
|
||||
.is_empty()
|
||||
);
|
||||
repository
|
||||
.delete_account_cooldowns(id.as_str())
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn capacity_freeze_survives_due_time_and_runtime_restart_until_probe_succeeds() {
|
||||
use gateway_admin::ports::store::AccountRuntimeStore as _;
|
||||
|
||||
@@ -60,13 +60,13 @@ pub use oauth::{
|
||||
pub use profile_statistics::{
|
||||
CodexCredentialProfileService, CodexProfileAvatarError, CodexProfileStatisticsError,
|
||||
};
|
||||
pub(crate) use quota::observed_quota_window;
|
||||
pub use quota::{
|
||||
CodexAccountQuotaSnapshot, CodexCredentialQuotaError, CodexCredentialQuotaService,
|
||||
CodexInitialSyncDelays, CodexQuotaFact, CodexQuotaRefreshPolicy, CodexQuotaSyncSummary,
|
||||
CodexQuotaWindow, CodexQuotaWindowKind, CodexQuotaWindowRole, CodexResetCreditsError,
|
||||
parse_codex_quota_usage,
|
||||
};
|
||||
pub(crate) use quota::{DEFAULT_RATE_LIMIT_COOLDOWN, observed_quota_window};
|
||||
pub use refresh::{
|
||||
CodexCredentialRefreshError, CodexCredentialRefreshOutcome, CodexCredentialRefreshService,
|
||||
DueCodexCredential,
|
||||
|
||||
@@ -75,7 +75,7 @@ use snapshot::{
|
||||
// 同一份上游观测只重做本地合并,高并发时不无限争抢写入
|
||||
const QUOTA_MERGE_ATTEMPTS: usize = 3;
|
||||
const LIMIT_EVIDENCE_FIELD: &str = "_cpr_quota_limit_evidence";
|
||||
const DEFAULT_RATE_LIMIT_COOLDOWN: Duration = Duration::from_secs(60);
|
||||
pub(crate) const DEFAULT_RATE_LIMIT_COOLDOWN: Duration = Duration::from_secs(60);
|
||||
pub(crate) const QUOTA_SCHEDULING_TTL: Duration = Duration::from_secs(10 * 60);
|
||||
const QUOTA_HYDRATION_FAILURE_TTL: Duration = Duration::from_secs(5);
|
||||
const PERIODIC_QUOTA_REFRESH_RETRY_INTERVAL: Duration = Duration::from_secs(30 * 60);
|
||||
|
||||
@@ -62,8 +62,6 @@ const SESSION_AFFINITY_TIMEOUT: Duration = Duration::from_millis(500);
|
||||
const CYBER_POLICY_TIMEOUT: Duration = Duration::from_millis(100);
|
||||
const CYBER_POLICY_SESSION_TTL: Duration = Duration::from_secs(60 * 60);
|
||||
const MAX_ACCOUNT_SNAPSHOT_RETRIES: u32 = 3;
|
||||
// 套餐权限可能变化,明确拒绝只作有界的账号模型排除,不冻结整个账号
|
||||
const MODEL_UNSUPPORTED_COOLDOWN: Duration = Duration::from_secs(30 * 60);
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CodexAccountFailure {
|
||||
@@ -665,7 +663,10 @@ impl CodexCredentialSelector {
|
||||
account_ids: &[ProviderAccountId],
|
||||
native_accounts: &BTreeSet<ProviderAccountId>,
|
||||
model: CodexSelectionModel<'_>,
|
||||
) -> HashMap<ProviderAccountId, AccountCooldown> {
|
||||
) -> (
|
||||
HashMap<ProviderAccountId, AccountCooldown>,
|
||||
BTreeSet<ProviderAccountId>,
|
||||
) {
|
||||
let native = accounts
|
||||
.iter()
|
||||
.filter(|account| native_accounts.contains(account.id()));
|
||||
@@ -693,11 +694,15 @@ impl CodexCredentialSelector {
|
||||
.then(|| (id.clone(), state))
|
||||
})
|
||||
.collect();
|
||||
let mut unsupported = BTreeSet::new();
|
||||
for (account, cooldown) in native.zip(model_cooldowns) {
|
||||
if let Some(cooldown) = cooldown.ok().flatten().filter(|cooldown| {
|
||||
cooldown.credential_revision() == account.revision()
|
||||
&& cooldown.until() > SystemTime::now()
|
||||
}) {
|
||||
if cooldown.rate_limited_until() != Some(cooldown.until()) {
|
||||
unsupported.insert(account.id().clone());
|
||||
}
|
||||
// 两种冷却取较晚期限,保留账号级冷却的恢复探测语义
|
||||
active
|
||||
.entry(account.id().clone())
|
||||
@@ -708,7 +713,7 @@ impl CodexCredentialSelector {
|
||||
});
|
||||
}
|
||||
}
|
||||
active
|
||||
(active, unsupported)
|
||||
}
|
||||
|
||||
async fn select_inner_loop(
|
||||
@@ -1093,8 +1098,8 @@ impl CodexCredentialSelector {
|
||||
continue 'capacity;
|
||||
}
|
||||
let follow_only = follow_only && image_primary_to_keep.is_none();
|
||||
let rate_limits = if diagnostic {
|
||||
HashMap::new()
|
||||
let (rate_limits, unsupported_models) = if diagnostic {
|
||||
Default::default()
|
||||
} else {
|
||||
self.load_candidate_cooldowns(&accounts, &account_ids, &native_accounts, model)
|
||||
.await
|
||||
@@ -1468,6 +1473,31 @@ impl CodexCredentialSelector {
|
||||
}
|
||||
// 只判断本次账号范围;空池、认证失效和租约失败不能伪装成额度耗尽
|
||||
// 策略排除与临时容量阻塞分开,保留繁忙账号的可恢复语义
|
||||
// 冷却在选号前就会排除账号;等待期限也须服从本轮插件裁决后的范围
|
||||
let cooldown_retry = candidates
|
||||
.iter()
|
||||
.filter(|candidate| !unsupported_models.contains(candidate.account.id()))
|
||||
.filter(|candidate| {
|
||||
!context.excluded_accounts.contains(candidate.account.id())
|
||||
})
|
||||
.filter(|candidate| {
|
||||
context
|
||||
.account_scope
|
||||
.as_ref()
|
||||
.is_none_or(|scope| scope.allows(candidate.account.id()))
|
||||
})
|
||||
.filter(|candidate| {
|
||||
candidate
|
||||
.account
|
||||
.status_projection(context.now, candidate.signals.cooldown)
|
||||
.status
|
||||
== AccountStatus::RateLimited
|
||||
})
|
||||
.filter_map(|candidate| candidate.signals.cooldown)
|
||||
.filter(|cooldown| cooldown.kind == AccountCooldownKind::RateLimit)
|
||||
.filter_map(|cooldown| cooldown.until.duration_since(context.now).ok())
|
||||
.min();
|
||||
shortest_retry = minimum_duration(shortest_retry, cooldown_retry);
|
||||
let mut statuses = candidates
|
||||
.iter()
|
||||
.filter(|candidate| {
|
||||
@@ -1690,20 +1720,11 @@ impl CodexCredentialSelector {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn record_model_unsupported(
|
||||
pub(crate) async fn record_model_cooldown(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
model: &gateway_core::routing::UpstreamModelId,
|
||||
cooldown: ProviderScopedCooldown,
|
||||
) -> Result<(), ProviderStoreError> {
|
||||
let now = SystemTime::now();
|
||||
self.cooldowns
|
||||
.put_scoped_if_later(ProviderScopedCooldown::new(
|
||||
account.id().clone(),
|
||||
account.revision(),
|
||||
ProviderCooldownScope::upstream_model(model.clone()),
|
||||
now.checked_add(MODEL_UNSUPPORTED_COOLDOWN).unwrap_or(now),
|
||||
))
|
||||
.await?;
|
||||
self.cooldowns.put_scoped_if_later(cooldown).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
use super::*;
|
||||
use crate::transport::protocol::responses::is_replaceable_response_prelude;
|
||||
use gateway_core::error::{ProxyConnectionHint, TransientRetryPolicy};
|
||||
use gateway_core::provider_ports::{ProviderCooldownScope, ProviderScopedCooldown};
|
||||
use gateway_protocol::http::preferred_response_request_id;
|
||||
|
||||
/// OpenAI 失败对 Smart 账号分数的结构化 reason 闭集
|
||||
@@ -41,6 +42,34 @@ pub fn openai_failure_affects_account_score(error: &ProviderError) -> bool {
|
||||
openai_account_score_failure_reason(error).is_some_and(is_openai_account_score_failure_reason)
|
||||
}
|
||||
|
||||
pub(super) enum ModelCooldown {
|
||||
Unsupported,
|
||||
RateLimited(std::time::SystemTime),
|
||||
}
|
||||
|
||||
impl ModelCooldown {
|
||||
fn for_account(
|
||||
&self,
|
||||
account: &ProviderAccount,
|
||||
model: &UpstreamModelId,
|
||||
) -> ProviderScopedCooldown {
|
||||
let (until, rate_limit) = match self {
|
||||
Self::Unsupported => (
|
||||
std::time::SystemTime::now() + Duration::from_secs(30 * 60),
|
||||
None,
|
||||
),
|
||||
Self::RateLimited(until) => (*until, Some(*until)),
|
||||
};
|
||||
ProviderScopedCooldown::new(
|
||||
account.id().clone(),
|
||||
account.revision(),
|
||||
ProviderCooldownScope::upstream_model(model.clone()),
|
||||
until,
|
||||
)
|
||||
.with_rate_limited_until(rate_limit)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct MappedProviderFailure {
|
||||
pub(super) error: ProviderError,
|
||||
pub(super) websocket_transport_retryable: bool,
|
||||
@@ -48,7 +77,7 @@ pub(super) struct MappedProviderFailure {
|
||||
/// 原始上游错误描述,仅在凭据错误状态下持久化
|
||||
pub(super) error_message: Option<String>,
|
||||
pub(super) cyber_policy_failure: bool,
|
||||
pub(super) model_unsupported: bool,
|
||||
pub(super) model_cooldown: Option<ModelCooldown>,
|
||||
pub(super) set_cookie_headers: Vec<String>,
|
||||
pub(super) response_origin: Option<Url>,
|
||||
pub(super) rate_limit_headers: Vec<(String, String)>,
|
||||
@@ -65,7 +94,7 @@ impl MappedProviderFailure {
|
||||
account_failure: None,
|
||||
error_message: None,
|
||||
cyber_policy_failure: false,
|
||||
model_unsupported: false,
|
||||
model_cooldown: None,
|
||||
set_cookie_headers: Vec::new(),
|
||||
response_origin: None,
|
||||
rate_limit_headers: Vec::new(),
|
||||
@@ -350,11 +379,11 @@ pub(super) async fn apply_failure(
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
if failure.model_unsupported
|
||||
if let Some(model_cooldown) = &failure.model_cooldown
|
||||
&& let Some(model) = context.upstream_model
|
||||
&& let Err(error) = context
|
||||
.selector
|
||||
.record_model_unsupported(account, model)
|
||||
.record_model_cooldown(model_cooldown.for_account(account, model))
|
||||
.await
|
||||
{
|
||||
tracing::warn!(account_id = %account.id(), error = %error,
|
||||
@@ -554,7 +583,7 @@ pub(super) fn apply_websocket_recovery_policy(
|
||||
return;
|
||||
}
|
||||
// 明确账号拒绝走已有换号路径,业务瞬态失败走请求内退避,不消耗 WS 传输预算
|
||||
if failure.model_unsupported
|
||||
if matches!(failure.model_cooldown, Some(ModelCooldown::Unsupported))
|
||||
|| (failure.error.replay_is_safe()
|
||||
&& (failure.account_failure.is_some()
|
||||
|| matches!(
|
||||
@@ -1629,7 +1658,21 @@ pub(super) fn map_upstream_failure(
|
||||
account_failure: account_failure(&failure),
|
||||
error_message: failure.client_message,
|
||||
cyber_policy_failure,
|
||||
model_unsupported: category == CodexFailureCategory::ModelUnsupported,
|
||||
model_cooldown: match category {
|
||||
CodexFailureCategory::ModelUnsupported => Some(ModelCooldown::Unsupported),
|
||||
CodexFailureCategory::TurnRateLimited => {
|
||||
// 流内错误的 Retry-After 从错误发生时计时,不能使用早先的连接响应头时间
|
||||
let now = std::time::SystemTime::now();
|
||||
let duration = failure
|
||||
.retry_after_seconds
|
||||
.map(Duration::from_secs)
|
||||
.unwrap_or(crate::credential::DEFAULT_RATE_LIMIT_COOLDOWN);
|
||||
Some(ModelCooldown::RateLimited(
|
||||
now.checked_add(duration).unwrap_or(now),
|
||||
))
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
// 普通 5xx 与未知流内错误不足以证明容量拒绝,不能用于冻结账号
|
||||
set_cookie_headers: failure.set_cookie_headers,
|
||||
response_origin: failure.response_origin,
|
||||
@@ -1689,7 +1732,7 @@ fn upstream_failure_summary(
|
||||
}
|
||||
CodexFailureCategory::RateLimited => (ProviderErrorKind::RateLimited, "上游请求频率受限"),
|
||||
CodexFailureCategory::TurnRateLimited => {
|
||||
(ProviderErrorKind::RateLimited, "当前对话轮次受到限流")
|
||||
(ProviderErrorKind::RateLimited, "当前账号的模型请求频率受限")
|
||||
}
|
||||
CodexFailureCategory::CloudflareChallenge => {
|
||||
(ProviderErrorKind::Unavailable, "Cloudflare 要求验证请求")
|
||||
|
||||
@@ -326,3 +326,129 @@ async fn shorter_account_cooldown_cannot_unmask_an_active_model_cooldown_during_
|
||||
assert!(cooldowns.cooldowns.lock().unwrap()[account.id()].until() < SystemTime::now());
|
||||
assert_eq!(selected.account_id().as_str(), "acct_second");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn model_cooldown_survives_success_and_only_blocks_the_matching_account_and_model() {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
create_account(&store, "acct_first", "test-first");
|
||||
create_account(&store, "acct_second", "test-second");
|
||||
let account = store.account("acct_first").unwrap();
|
||||
let cooldowns = Arc::new(MemoryCooldownPort::new());
|
||||
let scope = ProviderCooldownScope::upstream_model(UpstreamModelId::new("gpt-5.4").unwrap());
|
||||
let until = SystemTime::now() + Duration::from_secs(60);
|
||||
cooldowns
|
||||
.put_scoped_if_later(
|
||||
ProviderScopedCooldown::new(
|
||||
account.id().clone(),
|
||||
account.revision(),
|
||||
scope.clone(),
|
||||
until,
|
||||
)
|
||||
.with_rate_limited_until(Some(until)),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let selector = selector_with_runtime(
|
||||
&store,
|
||||
Arc::new(TestLeaseCoordinator::default()),
|
||||
Arc::new(MemorySessionAffinity::default()),
|
||||
Arc::new(AccountFeedbackStats::default()),
|
||||
cooldowns.clone(),
|
||||
);
|
||||
selector.record_success(&account).await;
|
||||
let request_url = Url::parse(OFFICIAL_CODEX_BASE_URL).unwrap();
|
||||
let new_session = attempt(BTreeSet::new());
|
||||
let request = SelectCodexCredential {
|
||||
protocol: gateway_protocol::openai::OPENAI_PROTOCOL,
|
||||
upstream_model: "gpt-5.4",
|
||||
request_url: &request_url,
|
||||
attempt: &new_session,
|
||||
session_affinity_key: None,
|
||||
};
|
||||
let selected = selector.select(&request).await.unwrap();
|
||||
assert_eq!(selected.account_id().as_str(), "acct_second");
|
||||
drop(selected);
|
||||
let same_account = attempt_with_required(BTreeSet::new(), Some(account.id().clone()));
|
||||
let other_model = selector
|
||||
.select(&SelectCodexCredential {
|
||||
upstream_model: "gpt-5.5",
|
||||
attempt: &same_account,
|
||||
..request
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(other_model.account_id(), account.id());
|
||||
assert!(
|
||||
cooldowns
|
||||
.read_scoped(account.id(), &scope)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_some()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pinned_model_cooldown_returns_retry_after_without_rotating_or_entering_capacity_queue() {
|
||||
let store = Arc::new(MemoryAccountStore::default());
|
||||
create_account(&store, "acct_original", "test-original");
|
||||
create_account(&store, "acct_primary", "test-free");
|
||||
let account = store.account("acct_original").unwrap();
|
||||
let cooldowns = Arc::new(MemoryCooldownPort::new());
|
||||
let scope = ProviderCooldownScope::upstream_model(UpstreamModelId::new("gpt-5.4").unwrap());
|
||||
let until = SystemTime::now() + Duration::from_secs(60);
|
||||
cooldowns
|
||||
.put_scoped_if_later(
|
||||
ProviderScopedCooldown::new(
|
||||
account.id().clone(),
|
||||
account.revision(),
|
||||
scope.clone(),
|
||||
until,
|
||||
)
|
||||
.with_rate_limited_until(Some(until)),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let selector = selector_with_runtime(
|
||||
&store,
|
||||
Arc::new(TestLeaseCoordinator::default()),
|
||||
Arc::new(MemorySessionAffinity::default()),
|
||||
Arc::new(AccountFeedbackStats::default()),
|
||||
cooldowns.clone(),
|
||||
);
|
||||
let attempt = AttemptContext::new(
|
||||
RequestAttemptContext::new(
|
||||
ModelRequestId::new("req_model_wait").unwrap(),
|
||||
ClientApiKeyId::new("key_codex_contract").unwrap(),
|
||||
),
|
||||
NonZeroU32::new(1).unwrap(),
|
||||
SystemTime::now() + Duration::from_secs(5),
|
||||
account_policy().with_queue(gateway_core::concurrency::ConcurrencyQueuePolicy {
|
||||
max_waiting: 1,
|
||||
timeout: Duration::from_secs(2),
|
||||
}),
|
||||
AccountAttemptContext::new(BTreeSet::new(), Some(account.id().clone()), None)
|
||||
.with_account_scope(contract_account_scope()),
|
||||
None,
|
||||
CancellationToken::new(),
|
||||
);
|
||||
let request_url = Url::parse(OFFICIAL_CODEX_BASE_URL).unwrap();
|
||||
let request = SelectCodexCredential {
|
||||
protocol: gateway_protocol::openai::OPENAI_PROTOCOL,
|
||||
upstream_model: "gpt-5.4",
|
||||
request_url: &request_url,
|
||||
attempt: &attempt,
|
||||
session_affinity_key: None,
|
||||
};
|
||||
selector.record_success(&account).await;
|
||||
let error = selector.select(&request).await.unwrap_err();
|
||||
assert!(
|
||||
matches!(error, CredentialSelectionError::CapacityUnavailable { retry_after: Some(duration) } if duration > Duration::from_secs(55) && duration <= Duration::from_secs(60)),
|
||||
"{error:?}"
|
||||
);
|
||||
cooldowns
|
||||
.clear_scoped(account.id(), &scope, account.revision())
|
||||
.await
|
||||
.unwrap();
|
||||
let selected = selector.select(&request).await.unwrap();
|
||||
assert_eq!(selected.account_id(), account.id());
|
||||
}
|
||||
@@ -9372,7 +9372,7 @@ async fn capacity_http_and_websocket_opening_rejections_use_bounded_business_ret
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn request_rejections_should_not_retry_or_cool_down_accounts() {
|
||||
async fn request_rejections_should_not_retry_or_cool_down_entire_accounts() {
|
||||
use gateway_core::provider_ports::ProviderCooldownPort as _;
|
||||
use provider_openai::credential::ResponsesTransport;
|
||||
for (use_websocket, (code, error_type, expected_kind)) in
|
||||
@@ -9486,6 +9486,16 @@ async fn request_rejections_should_not_retry_or_cool_down_accounts() {
|
||||
}
|
||||
);
|
||||
assert!(cooldowns.read(account.id()).await.unwrap().is_none());
|
||||
let scope = gateway_core::provider_ports::ProviderCooldownScope::upstream_model(
|
||||
gateway_core::routing::UpstreamModelId::new("gpt-5.4").unwrap(),
|
||||
);
|
||||
let model_cooldown = cooldowns.read_scoped(account.id(), &scope).await.unwrap();
|
||||
assert_eq!(model_cooldown.is_some(), code == "turn_rate_limit_exceeded");
|
||||
if let Some(cooldown) = model_cooldown {
|
||||
assert_eq!(cooldown.rate_limited_until(), Some(cooldown.until()));
|
||||
let remaining = cooldown.until().duration_since(SystemTime::now()).unwrap();
|
||||
assert!(remaining > Duration::from_secs(295) && remaining <= Duration::from_secs(300));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9908,6 +9918,15 @@ async fn stream_failures_preserve_error_fields_independent_of_retry_classificati
|
||||
assert!(error.retry_is_prohibited());
|
||||
assert_eq!(error.retry_after(), Some(Duration::from_secs(7)));
|
||||
}
|
||||
if code == "turn_rate_limit_exceeded" {
|
||||
use gateway_core::provider_ports::{ProviderCooldownPort as _, ProviderCooldownScope};
|
||||
let account = store.account("acct_provider_contract").unwrap();
|
||||
let scope = ProviderCooldownScope::upstream_model(gateway_core::routing::UpstreamModelId::new("gpt-5.4").unwrap());
|
||||
let cooldown = cooldowns.read_scoped(account.id(), &scope).await.unwrap().expect("model cooldown");
|
||||
let remaining = cooldown.until().duration_since(SystemTime::now()).unwrap();
|
||||
assert!(remaining > Duration::from_secs(5) && remaining <= Duration::from_secs(7));
|
||||
assert!(cooldowns.read(account.id()).await.unwrap().is_none());
|
||||
}
|
||||
if expected_kind == ProviderErrorKind::QuotaExhausted {
|
||||
assert_eq!(store.account("acct_provider_contract").unwrap().quota().access(), QuotaAccessState::Exhausted);
|
||||
}
|
||||
|
||||
@@ -708,6 +708,7 @@ async fn upstream_model_rejection_cools_only_that_model_across_requests_and_tran
|
||||
.err()
|
||||
.expect("model cooldown must survive the first request");
|
||||
assert_eq!(blocked.kind(), ProviderErrorKind::NoEligibleAccount);
|
||||
assert!(blocked.retry_after().is_none());
|
||||
assert!(cooldowns.cooldowns.lock().unwrap().is_empty());
|
||||
server.reset().await;
|
||||
Mock::given(method("POST"))
|
||||
|
||||
@@ -1688,11 +1688,21 @@ impl ProviderCooldownPort for MemoryCooldownPort {
|
||||
|
||||
fn clear_scoped<'a>(
|
||||
&'a self,
|
||||
_account_id: &'a ProviderAccountId,
|
||||
_scope: &'a ProviderCooldownScope,
|
||||
_through_revision: CredentialRevision,
|
||||
account_id: &'a ProviderAccountId,
|
||||
scope: &'a ProviderCooldownScope,
|
||||
through_revision: CredentialRevision,
|
||||
) -> BoxFuture<'a, Result<bool, ProviderStoreError>> {
|
||||
Box::pin(async { Ok(false) })
|
||||
Box::pin(async move {
|
||||
let mut scoped = self.scoped.lock().unwrap();
|
||||
let key = (account_id.clone(), scope.clone());
|
||||
if scoped
|
||||
.get(&key)
|
||||
.is_some_and(|cooldown| cooldown.credential_revision() > through_revision)
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
Ok(scoped.remove(&key).is_some())
|
||||
})
|
||||
}
|
||||
|
||||
fn clear_all<'a>(
|
||||
|
||||
+8
-2
@@ -878,8 +878,10 @@ HTTP 瞬时建连失败(含 TLS 握手 EOF),或 WebSocket 新请求在发
|
||||
再次失败刷新有效期,成功结束后解除限制。其他重试策略不受影响,缺少有效身份、状态过期或状态存储不可用时沿用原策略。
|
||||
这是一项轮次重试预算控制,不是客户端重试意图的精确检测;状态与交付顺序见[数据面请求生命周期](architecture.md#4-数据面请求生命周期)
|
||||
|
||||
`turn_rate_limit_exceeded` 保留原始错误和 `Retry-After`,由客户端按自身重试预算等待。
|
||||
代理不因此写入账号冷却、换号或透明重试,其他会话仍可使用该账号
|
||||
OpenAI 原生链路的 `turn_rate_limit_exceeded` 按账号与上游模型记录临时冷却,期限采用 `Retry-After`,缺失时使用 60 秒。
|
||||
新请求选号避开受限组合,其他模型和已在输出的请求不受影响;并发请求的成功反馈不会提前清除此冷却。
|
||||
已有会话沿用亲和、固定归属与排队策略:允许重选时可换号,后代线程跟随主会话等待,固定账号的普通冷却请求返回剩余等待时间。
|
||||
本次错误保留原始错误和 `Retry-After`,不因记录冷却而透明重放,由客户端按自身重试预算等待
|
||||
|
||||
`/v1/responses` 流式请求尚未发出数据或心跳时,若上游 WS `error` 明确返回 400,
|
||||
且网关判定为普通请求参数错误,客户端收到 HTTP 400 和原始 `error` 对象。
|
||||
@@ -1377,6 +1379,10 @@ config 返回 `{ name, plaintextKey }`,仅读取服务端会话绑定的当前
|
||||
未要求探测时,该字段表示冷却结束时间。`protectionRules` 返回触发时的规则快照 `[{ id, name }]`,
|
||||
没有保护原因时为空数组,修改或删除当前规则不改写此快照。错误保护与上游限流独立恢复,解除保护不保证其他限制已经解除
|
||||
|
||||
`quota.modelRateLimits` 只列出有效的模型限流,每项包含上游 `model`、RFC 3339 格式的 `until` 和按部署时区格式化的 `untilDisplay`。
|
||||
存在模型限流时,账号列表、状态筛选和统计归入 `rate_limited`,停用、凭据错误和额度耗尽仍优先显示;仅模型受限时整账号的 `rateLimitedUntil` 与 `rateLimitReason` 保持 `null`。
|
||||
管理端状态详情展示受限模型、剩余秒数与恢复时间,到期回读列表。模型不受支持时不显示限流;该汇总状态不阻断其他模型
|
||||
|
||||
OpenAI OAuth 账号的 `capabilities.quotaSettingsSupported` 为真。通过 `POST /api/admin/accounts/batch-update`
|
||||
提交 `{"accountIds":["acct_1"],"quotaSettings":{"codex:18000s":{"limitPercent":99,"warmup":null},"codex:604800s":{"limitPercent":95,"warmup":{"model":"gpt-5.5"}}}}`。
|
||||
键取自该账号 `quota.windows` 中 `accountWide: true` 的窗口 `key`,这里只配置通用额度桶。
|
||||
|
||||
@@ -776,6 +776,9 @@ xAI 的 OAuth 套餐目录保持严格一致;与独立 API 目录合并时,
|
||||
该反馈不冻结整个账号,不改写管理员模型政策,也不占用 WS 传输恢复预算;重试仍遵守交付边界与原生续写固定账号约束。
|
||||
管理员诊断旁路目录资格与模型拒绝冷却,OpenAI 的受管上游适配器不继承这两项原生限制
|
||||
|
||||
OpenAI 原生 `turn_rate_limit_exceeded` 复用账号、凭据版本与上游模型的冷却合同,等待期限从错误发生时起算。
|
||||
模型冷却只参与匹配模型的选号,普通成功反馈不清除;当前失败的重放边界不变,已有会话沿用亲和和排队策略,等待时长见[容量拒绝与重试](api.md#容量拒绝与重试)
|
||||
|
||||
账号编辑在一个事务中更新调度事实,批量更新只应用显式提供的字段。导入与首次 OAuth 可携带统一账号设置,由 Admin 传递给 Store,
|
||||
与凭据在同一事务中提交;Provider 仍独占凭据解析。未附带设置的导入、重新授权和后台刷新保留已有分组、
|
||||
权重、并发与模型政策。模型政策变更推进配置 revision,不推进 credential revision。管理端导入和账号编辑共用设置表单,凭据输入独立于设置
|
||||
@@ -1098,6 +1101,9 @@ Host 监督进程和后台任务,各所有者负责传播取消及收尾;连
|
||||
|
||||
错误保护与上游限流分别保存恢复事实并聚合冷却投影,探测恢复由 Admin 负责,详见[Worker 与账号冻结](#worker-与账号冻结)
|
||||
|
||||
账号目录仅将实际模型限流汇总为 `rate_limited`,详情单独携带模型和期限;整账号冷却事实不混入模型冷却。
|
||||
Redis 分别保存选号冷却与模型限流的期限,原子维护限流到期索引,目录查询按当前凭据版本过滤;列表筛选、统计和详情使用相同的版本与到期规则
|
||||
|
||||
PostgreSQL schema 由迁移目录按编号管理;冻结、升级与校验规则统一维护在[迁移文档](../backend/migrations/README.md)
|
||||
|
||||
<a id="9-credential额度与主动重置"></a>
|
||||
|
||||
@@ -44,6 +44,7 @@ export interface AccountProtectionRule {
|
||||
}
|
||||
|
||||
export interface AccountQuota {
|
||||
modelRateLimits: { model: string, until: string, untilDisplay: string }[]
|
||||
refreshedAt: string | null
|
||||
refreshedAtRelative: RelativeTimeView | null
|
||||
refreshedAtDisplay: string
|
||||
|
||||
@@ -596,6 +596,9 @@
|
||||
"attentionHelp": "This account needs attention",
|
||||
"retestHelp": "Test the connection again to update the status",
|
||||
"rateLimitedHelp": "The upstream service rate limited this account, cooldown is in progress",
|
||||
"limitedModels": "Limited models · Expected recovery",
|
||||
"modelCooldownRemaining": "{seconds} seconds remaining",
|
||||
"modelCooldownEnded": "Cooldown ended",
|
||||
"cooldownHelp": "Scheduling resumes automatically after cooldown",
|
||||
"credentialsHelp": "This account is excluded from scheduling, update its credentials and test the connection again",
|
||||
"reauthorizeHelp": "Reauthorize the account to resume scheduling",
|
||||
|
||||
@@ -596,6 +596,9 @@
|
||||
"attentionHelp": "该账号当前状态需要关注",
|
||||
"retestHelp": "重新测试连接以获取最新状态",
|
||||
"rateLimitedHelp": "上游暂时限制了请求频率,系统正在冷却该账号",
|
||||
"limitedModels": "受限模型 · 预计恢复",
|
||||
"modelCooldownRemaining": "剩余 {seconds} 秒",
|
||||
"modelCooldownEnded": "冷却已结束",
|
||||
"cooldownHelp": "冷却结束后,系统会自动恢复调度",
|
||||
"credentialsHelp": "该账号暂不参与调度,处理凭据后可重新测试连接",
|
||||
"reauthorizeHelp": "重新授权后,账号会重新参与调度",
|
||||
|
||||
@@ -596,6 +596,9 @@
|
||||
"attentionHelp": "該賬號當前狀態需要關注",
|
||||
"retestHelp": "重新測試連接以獲取最新狀態",
|
||||
"rateLimitedHelp": "上游暫時限制了請求頻率,系統正在冷卻該賬號",
|
||||
"limitedModels": "受限模型 · 預計恢復",
|
||||
"modelCooldownRemaining": "剩餘 {seconds} 秒",
|
||||
"modelCooldownEnded": "冷卻已結束",
|
||||
"cooldownHelp": "冷卻結束後,系統會自動恢復調度",
|
||||
"credentialsHelp": "該賬號暫不參與調度,處理憑據後可重新測試連接",
|
||||
"reauthorizeHelp": "重新授權後,賬號會重新參與調度",
|
||||
|
||||
@@ -64,7 +64,8 @@ const presentation = computed(() =>
|
||||
:aria-label="presentation.hasDetail ? presentation.triggerLabel : undefined"
|
||||
:aria-expanded="presentation.hasDetail ? open : undefined"
|
||||
:aria-haspopup="presentation.hasDetail ? 'dialog' : undefined"
|
||||
class="group inline-flex min-w-0 cursor-default border-0 bg-transparent p-0 text-left outline-none"
|
||||
class="group inline-flex min-w-0 border-0 bg-transparent p-0 text-left outline-none"
|
||||
:class="presentation.hasDetail ? 'cursor-pointer' : 'cursor-default'"
|
||||
>
|
||||
<span
|
||||
v-if="variant === 'pill'"
|
||||
@@ -111,7 +112,7 @@ const presentation = computed(() =>
|
||||
</header>
|
||||
|
||||
<div class="grid gap-3 px-4 py-3 text-z-sm leading-5">
|
||||
<p class="m-0 text-pretty font-emphasis text-z-text-secondary">
|
||||
<p v-if="presentation.description" class="m-0 text-pretty font-emphasis text-z-text-secondary">
|
||||
{{ presentation.description }}
|
||||
</p>
|
||||
|
||||
@@ -133,6 +134,23 @@ const presentation = computed(() =>
|
||||
<span class="font-mono font-emphasis tabular-nums text-z-text">{{ time.value }}</span>
|
||||
</div>
|
||||
|
||||
<div v-if="presentation.modelRateLimits.length" class="grid gap-1.5">
|
||||
<span class="text-z-xs font-emphasis text-z-text-tertiary">{{ t('accounts.status.limitedModels') }}</span>
|
||||
<ZScrollbar max-height="192px">
|
||||
<dl class="m-0 grid gap-2">
|
||||
<div v-for="limit in presentation.modelRateLimits" :key="limit.model" class="rounded-z bg-z-fill-quaternary px-3 py-2">
|
||||
<dt class="font-mono font-emphasis wrap-anywhere text-z-text">
|
||||
{{ limit.model }}
|
||||
</dt>
|
||||
<dd class="m-0 mt-1 flex flex-wrap justify-between gap-x-3 gap-y-1 text-z-xs tabular-nums text-z-text-secondary">
|
||||
<span>{{ limit.remaining }}</span>
|
||||
<span>{{ limit.untilDisplay }}</span>
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</ZScrollbar>
|
||||
</div>
|
||||
|
||||
<div class="rounded-z bg-z-fill-quaternary px-3 py-2.5">
|
||||
<p class="m-0 text-z-xs leading-none font-heavy text-z-text-tertiary">
|
||||
{{ t('accounts.status.recommendedAction') }}
|
||||
|
||||
@@ -39,6 +39,7 @@ interface AccountStatusPresentation {
|
||||
errorText: string | null
|
||||
times: { key: string, label: string, value: string }[]
|
||||
protectionRules: AccountProtectionRule[]
|
||||
modelRateLimits: { model: string, remaining: string, untilDisplay: string }[]
|
||||
triggerLabel: string
|
||||
}
|
||||
|
||||
@@ -162,6 +163,16 @@ export function resolveAccountStatusPresentation(
|
||||
? 'refresh_backoff'
|
||||
: input.status
|
||||
const quota = input.quota
|
||||
const modelRateLimits = (quota?.modelRateLimits ?? []).map((limit) => {
|
||||
const seconds = Math.max(0, Math.ceil((Date.parse(limit.until) - input.now) / 1000))
|
||||
return {
|
||||
model: limit.model,
|
||||
remaining: seconds > 0
|
||||
? t('accounts.status.modelCooldownRemaining', { seconds })
|
||||
: t('accounts.status.modelCooldownEnded'),
|
||||
untilDisplay: limit.untilDisplay,
|
||||
}
|
||||
})
|
||||
const pausedWindows = mode === 'quota_paused' && quota
|
||||
? quota.pausedWindows.map((key) => {
|
||||
const window = quota.windows.find(w => w.key === key)
|
||||
@@ -185,7 +196,12 @@ export function resolveAccountStatusPresentation(
|
||||
? t('accounts.status.recoveryProbeHelp')
|
||||
: t('accounts.status.recoveryHelp'),
|
||||
}
|
||||
: displayDefinitions.value[mode]
|
||||
: mode === 'rate_limited' && modelRateLimits.length && !quota?.rateLimitedUntil
|
||||
? {
|
||||
...displayDefinitions.value.rate_limited,
|
||||
description: '',
|
||||
}
|
||||
: displayDefinitions.value[mode]
|
||||
const nextRefreshDisplay = isBackoff ? input.nextRefreshAtDisplay : null
|
||||
const reasonLabel = input.errorReason ? errorReasonLabels.value[input.errorReason] : null
|
||||
const title = definition.title ?? reasonLabel ?? definition.label
|
||||
@@ -227,11 +243,15 @@ export function resolveAccountStatusPresentation(
|
||||
&& input.errorReason
|
||||
? errorRecoveryHints.value[input.errorReason]
|
||||
: definition.recoveryHint
|
||||
const hasDetail = input.status === 'error' || mode === 'rate_limited' || isBackoff || mode === 'quota_paused'
|
||||
const hasDetail = input.status === 'error' || mode === 'rate_limited' || isBackoff || mode === 'quota_paused' || modelRateLimits.length > 0
|
||||
const retry = nextRefreshDisplay
|
||||
? t('accounts.status.nextAttempt', { nextRefreshDisplay })
|
||||
: ''
|
||||
const triggerLabel = t('accounts.status.clickOrFocusToViewDetails', { title, description, retry })
|
||||
const triggerLabel = t('accounts.status.clickOrFocusToViewDetails', {
|
||||
title,
|
||||
description: description || modelRateLimits.map(limit => limit.model).join(' / '),
|
||||
retry,
|
||||
})
|
||||
|
||||
return {
|
||||
mode,
|
||||
@@ -244,6 +264,7 @@ export function resolveAccountStatusPresentation(
|
||||
hasDetail,
|
||||
errorText: input.errorMessage || null,
|
||||
times,
|
||||
modelRateLimits,
|
||||
protectionRules: isProtected
|
||||
? input.protectionRules
|
||||
: [],
|
||||
|
||||
@@ -2,6 +2,6 @@ import { createSharedComposable, useIntervalFn, useNow } from '@vueuse/core'
|
||||
|
||||
export const useStatusClock = createSharedComposable(() =>
|
||||
useNow({
|
||||
scheduler: callback => useIntervalFn(callback, 30_000),
|
||||
scheduler: callback => useIntervalFn(callback, 1000),
|
||||
}),
|
||||
)
|
||||
@@ -47,6 +47,17 @@ export function useAccountsQuery() {
|
||||
total: query.total.value,
|
||||
}))
|
||||
|
||||
watch(() => Math.min(...query.items.value.flatMap(account =>
|
||||
(account.quota.modelRateLimits ?? []).map(limit => Date.parse(limit.until)),
|
||||
)), (until, _previous, onCleanup) => {
|
||||
const delay = until - Date.now() + 100
|
||||
if (!Number.isFinite(delay) || delay > 2_147_483_647)
|
||||
return
|
||||
// 到期回读同时校准状态、筛选和统计;不在前端推测账号是否已恢复
|
||||
const timer = setTimeout(() => void query.execute({ background: true, silent: true }), Math.max(0, delay))
|
||||
onCleanup(() => clearTimeout(timer))
|
||||
})
|
||||
|
||||
function handlePageChange(page: number) {
|
||||
void query.execute({ page })
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user