fix: align official quota windows

Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
zyycn
2026-06-26 00:27:21 +08:00
co-authored by Codex
parent cfe306f68c
commit 68deb10ea9
15 changed files with 1541 additions and 282 deletions
+286 -17
View File
@@ -36,6 +36,9 @@ use crate::{
};
const ACCOUNT_STATS_PAGE_LIMIT: u32 = 200;
const FIVE_HOUR_WINDOW_SECONDS: u64 = 18_000;
const WEEK_WINDOW_SECONDS: u64 = 604_800;
const MONTH_WINDOW_SECONDS: u64 = 2_592_000;
// ============================================================================
// Query / Request types
@@ -161,21 +164,28 @@ impl AdminAccountData {
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct AdminAccountQuotaData {
refreshed_at_display: String,
windows: Vec<AdminAccountQuotaWindowData>,
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
struct AdminAccountQuotaWindowData {
key: String,
group: String,
window_seconds: Option<u64>,
label_display: String,
used_percent: Option<f64>,
used_percent_display: String,
reset_at_display: String,
refreshed_at_display: String,
window_used_display: String,
}
impl Default for AdminAccountQuotaData {
fn default() -> Self {
Self {
used_percent: None,
used_percent_display: "-".to_string(),
reset_at_display: "-".to_string(),
refreshed_at_display: "-".to_string(),
window_used_display: "-".to_string(),
windows: Vec::new(),
}
}
}
@@ -1024,19 +1034,61 @@ fn model_usage_data(usage: ModelUsageAggregate) -> AdminAccountModelUsageData {
fn quota_data(quota_json: &str, fetched_at: Option<DateTime<Utc>>) -> AdminAccountQuotaData {
let quota = serde_json::from_str::<Value>(quota_json).unwrap_or(Value::Null);
let used_percent = quota
.pointer("/rate_limit/used_percent")
.and_then(number_value)
.map(|value| value.clamp(0.0, 100.0));
let reset_at = quota
.pointer("/rate_limit/reset_at")
.and_then(Value::as_i64)
.and_then(|value| DateTime::<Utc>::from_timestamp(value, 0));
let window_seconds = quota
.pointer("/rate_limit/limit_window_seconds")
.and_then(Value::as_u64);
let windows = quota_windows(&quota);
AdminAccountQuotaData {
refreshed_at_display: china_relative_time(fetched_at, Utc::now()),
windows,
}
}
fn quota_windows(quota: &Value) -> Vec<AdminAccountQuotaWindowData> {
let mut windows = Vec::new();
let has_monthly_limit = push_monthly_quota_window(&mut windows, quota.get("monthly_limit"));
if let Some(snapshots) = quota.get("snapshots").and_then(Value::as_array) {
for snapshot in snapshots {
push_snapshot_quota_windows(&mut windows, snapshot, has_monthly_limit);
}
}
windows.sort_by_key(quota_window_sort_key);
windows
}
fn push_monthly_quota_window(
windows: &mut Vec<AdminAccountQuotaWindowData>,
monthly_limit: Option<&Value>,
) -> bool {
let Some(monthly_limit) = monthly_limit.filter(|value| !value.is_null()) else {
return false;
};
let used_percent = monthly_limit
.get("used_percent")
.and_then(number_value)
.map(|value| value.clamp(0.0, 100.0));
let reset_at = monthly_limit
.get("reset_at")
.and_then(Value::as_i64)
.and_then(|value| DateTime::<Utc>::from_timestamp(value, 0));
let window_seconds = monthly_limit
.get("window_minutes")
.and_then(Value::as_u64)
.and_then(|minutes| minutes.checked_mul(60))
.or(Some(MONTH_WINDOW_SECONDS));
if used_percent.is_none() && reset_at.is_none() {
return false;
}
let key = monthly_limit
.get("key")
.and_then(Value::as_str)
.unwrap_or("monthly");
windows.push(AdminAccountQuotaWindowData {
key: quota_key_segment(key),
group: "monthly".to_string(),
window_seconds,
label_display: "月限额".to_string(),
used_percent,
used_percent_display: used_percent
.map(format_percent)
@@ -1045,8 +1097,210 @@ fn quota_data(quota_json: &str, fetched_at: Option<DateTime<Utc>>) -> AdminAccou
.as_ref()
.map(china_datetime)
.unwrap_or_else(|| "-".to_string()),
refreshed_at_display: china_relative_time(fetched_at, Utc::now()),
window_used_display: quota_window_used_display(reset_at, window_seconds),
});
true
}
fn push_snapshot_quota_windows(
windows: &mut Vec<AdminAccountQuotaWindowData>,
snapshot: &Value,
skip_core_monthly: bool,
) {
let source = snapshot
.get("source")
.and_then(Value::as_str)
.unwrap_or("quota");
let source_key = snapshot_source_key(source, snapshot);
let label_prefix = snapshot_label(snapshot);
for role in ["primary", "secondary"] {
let Some(window) = snapshot.get(role).filter(|value| !value.is_null()) else {
continue;
};
let window_seconds = window
.get("window_minutes")
.and_then(Value::as_u64)
.and_then(|minutes| minutes.checked_mul(60));
if skip_core_monthly
&& source == "core"
&& window_seconds
.is_some_and(|seconds| quota_window_matches(seconds, MONTH_WINDOW_SECONDS))
{
continue;
}
push_quota_window(
windows,
&source_key,
role,
label_prefix.as_deref(),
Some(window),
);
}
}
fn push_quota_window(
windows: &mut Vec<AdminAccountQuotaWindowData>,
source_key: &str,
role: &str,
label_prefix: Option<&str>,
window: Option<&Value>,
) {
let Some(window) = window.filter(|value| !value.is_null()) else {
return;
};
let used_percent = window
.get("used_percent")
.and_then(number_value)
.map(|value| value.clamp(0.0, 100.0));
let reset_at = window
.get("reset_at")
.and_then(Value::as_i64)
.and_then(|value| DateTime::<Utc>::from_timestamp(value, 0));
let window_seconds = window
.get("window_minutes")
.and_then(Value::as_u64)
.and_then(|minutes| minutes.checked_mul(60));
if used_percent.is_none() && reset_at.is_none() && window_seconds.is_none() {
return;
}
let base_label = quota_window_label_display(window_seconds);
let label_display = label_prefix
.filter(|value| !value.trim().is_empty())
.map(|value| format!("{} · {}", value.trim(), base_label))
.unwrap_or(base_label);
windows.push(AdminAccountQuotaWindowData {
key: unique_quota_window_key(windows, source_key, role, window_seconds),
group: quota_window_group(window_seconds).to_string(),
window_seconds,
label_display,
used_percent,
used_percent_display: used_percent
.map(format_percent)
.unwrap_or_else(|| "-".to_string()),
reset_at_display: reset_at
.as_ref()
.map(china_datetime)
.unwrap_or_else(|| "-".to_string()),
window_used_display: quota_window_used_display(reset_at, window_seconds),
});
}
fn snapshot_source_key(source: &str, snapshot: &Value) -> String {
let label = snapshot
.get("limit_name")
.and_then(Value::as_str)
.or_else(|| snapshot.get("metered_feature").and_then(Value::as_str))
.unwrap_or(source);
format!("{}-{}", quota_key_segment(source), quota_key_segment(label))
}
fn snapshot_label(snapshot: &Value) -> Option<String> {
let source = snapshot.get("source").and_then(Value::as_str);
if source == Some("core") {
return None;
}
let label = snapshot
.get("limit_name")
.and_then(Value::as_str)
.or_else(|| snapshot.get("metered_feature").and_then(Value::as_str))
.map(str::trim)
.filter(|value| !value.is_empty())?;
if label.eq_ignore_ascii_case("codex") {
return None;
}
if is_review_limit_label(Some(label)) {
return Some("代码审查".to_string());
}
Some(label.to_string())
}
fn unique_quota_window_key(
windows: &[AdminAccountQuotaWindowData],
source_key: &str,
role: &str,
window_seconds: Option<u64>,
) -> String {
let bucket = quota_window_key_part(window_seconds).unwrap_or(role);
let key = format!("{source_key}-{bucket}");
if windows.iter().any(|window| window.key == key) {
format!("{key}-{role}")
} else {
key
}
}
fn quota_window_key_part(window_seconds: Option<u64>) -> Option<&'static str> {
match window_seconds {
Some(seconds) if quota_window_matches(seconds, FIVE_HOUR_WINDOW_SECONDS) => {
Some("five-hour")
}
Some(seconds) if quota_window_matches(seconds, WEEK_WINDOW_SECONDS) => Some("weekly"),
Some(seconds) if quota_window_matches(seconds, MONTH_WINDOW_SECONDS) => Some("monthly"),
_ => None,
}
}
fn quota_key_segment(value: &str) -> String {
let mut segment = String::with_capacity(value.len());
for ch in value.chars() {
if ch.is_ascii_alphanumeric() {
segment.push(ch.to_ascii_lowercase());
} else if !segment.ends_with('-') {
segment.push('-');
}
}
let segment = segment.trim_matches('-');
if segment.is_empty() {
"quota".to_string()
} else {
segment.to_string()
}
}
fn quota_window_sort_key(window: &AdminAccountQuotaWindowData) -> (u8, u64, String) {
let group_order = match window.group.as_str() {
"monthly" => 0,
"shortTerm" => 1,
_ => 2,
};
(
group_order,
window.window_seconds.unwrap_or(0),
window.key.clone(),
)
}
fn quota_window_group(window_seconds: Option<u64>) -> &'static str {
match window_seconds {
Some(seconds) if quota_window_matches(seconds, MONTH_WINDOW_SECONDS) => "monthly",
Some(seconds)
if quota_window_matches(seconds, FIVE_HOUR_WINDOW_SECONDS)
|| quota_window_matches(seconds, WEEK_WINDOW_SECONDS) =>
{
"shortTerm"
}
_ => "other",
}
}
fn quota_window_matches(actual: u64, expected: u64) -> bool {
actual > 0 && actual.abs_diff(expected) <= expected / 20
}
fn quota_window_label_display(window_seconds: Option<u64>) -> String {
let Some(window_seconds) = window_seconds.filter(|seconds| *seconds > 0) else {
return "额度".to_string();
};
match window_seconds {
seconds if quota_window_matches(seconds, FIVE_HOUR_WINDOW_SECONDS) => {
"5小时限额".to_string()
}
seconds if quota_window_matches(seconds, WEEK_WINDOW_SECONDS) => "周限额".to_string(),
seconds if quota_window_matches(seconds, MONTH_WINDOW_SECONDS) => "月限额".to_string(),
seconds if seconds % 86_400 == 0 => format!("{}天限额", seconds / 86_400),
seconds if seconds % 3_600 == 0 => format!("{}小时限额", seconds / 3_600),
seconds => format!("{}分钟限额", seconds.div_ceil(60)),
}
}
@@ -1091,6 +1345,21 @@ fn number_value(value: &Value) -> Option<f64> {
value
.as_f64()
.or_else(|| value.as_str().and_then(|value| value.parse::<f64>().ok()))
.filter(|value| value.is_finite())
}
fn is_review_limit_label(value: Option<&str>) -> bool {
let normalized = value
.unwrap_or_default()
.trim()
.to_ascii_lowercase()
.replace(['-', ' '], "_");
normalized == "review"
|| normalized == "code_review"
|| normalized == "codex_review"
|| normalized == "codex_code_review"
|| normalized.contains("code_review")
|| normalized.contains("codex_review")
}
fn nonnegative_i64_to_u64(value: i64) -> u64 {
+48 -11
View File
@@ -70,15 +70,13 @@ impl AdminAccountService {
"level": "exhausted"
}));
} else {
// 按阈值检查 used_percent。
let mut check_threshold = |quota_key: &str, thresholds: &[u8]| {
let used_percent = quota
.get(quota_key)
.and_then(|v| v.get("used_percent"))
.and_then(serde_json::Value::as_u64)
.unwrap_or(0);
for (quota_key, used_percent, role) in quota_warning_windows(&quota) {
let thresholds = match role {
"secondary" => &self.quota_thresholds.secondary,
_ => &self.quota_thresholds.primary,
};
for threshold in thresholds {
if used_percent >= u64::from(*threshold) {
if used_percent >= f64::from(*threshold) {
warnings.push(serde_json::json!({
"accountId": snap.account_id,
"email": snap.email,
@@ -90,9 +88,7 @@ impl AdminAccountService {
break;
}
}
};
check_threshold("rate_limit", &self.quota_thresholds.primary);
check_threshold("secondary_rate_limit", &self.quota_thresholds.secondary);
}
}
}
@@ -199,3 +195,44 @@ impl AdminAccountService {
}))
}
}
fn quota_warning_windows(quota: &serde_json::Value) -> Vec<(String, f64, &'static str)> {
let mut windows = Vec::new();
if let Some(monthly) = quota.get("monthly_limit").filter(|value| !value.is_null()) {
if let Some(used_percent) = used_percent(monthly) {
windows.push(("monthly_limit".to_string(), used_percent, "primary"));
}
}
if let Some(snapshots) = quota.get("snapshots").and_then(serde_json::Value::as_array) {
for snapshot in snapshots {
let source = snapshot
.get("source")
.and_then(serde_json::Value::as_str)
.unwrap_or("quota");
let limit_name = snapshot
.get("limit_name")
.and_then(serde_json::Value::as_str)
.unwrap_or(source);
for role in ["primary", "secondary"] {
let Some(window) = snapshot.get(role).filter(|value| !value.is_null()) else {
continue;
};
if let Some(used_percent) = used_percent(window) {
windows.push((format!("{source}:{limit_name}:{role}"), used_percent, role));
}
}
}
}
windows
}
fn used_percent(value: &serde_json::Value) -> Option<f64> {
value
.get("used_percent")
.and_then(|value| {
value
.as_f64()
.or_else(|| value.as_str().and_then(|value| value.parse::<f64>().ok()))
})
.filter(|value| value.is_finite())
}
+20 -2
View File
@@ -925,9 +925,27 @@ async fn account_quota_used_percent_by_id(
fn quota_used_percent(quota_json: &str) -> Option<f64> {
let quota = serde_json::from_str::<Value>(quota_json).ok()?;
quota
.pointer("/rate_limit/used_percent")
let mut values = Vec::new();
if let Some(used_percent) = quota
.pointer("/monthly_limit/used_percent")
.and_then(percent_value)
{
values.push(used_percent);
}
if let Some(snapshots) = quota.get("snapshots").and_then(Value::as_array) {
for snapshot in snapshots {
for role in ["primary", "secondary"] {
if let Some(used_percent) = snapshot
.get(role)
.and_then(|window| window.get("used_percent"))
.and_then(percent_value)
{
values.push(used_percent);
}
}
}
}
values.into_iter().max_by(f64::total_cmp)
}
fn percent_value(value: &Value) -> Option<f64> {
+283 -127
View File
@@ -1,148 +1,139 @@
//! 配额检查策略。
use chrono::{DateTime, Utc};
use serde_json::{json, Map, Value};
use serde_json::{json, Value};
const MONTH_WINDOW_MINUTES: u64 = 43_200;
const MONTH_WINDOW_SECONDS: u64 = 2_592_000;
/// 判断配额百分比是否达到阈值。
pub fn quota_reached(used_percent: f64, threshold: f64) -> bool {
used_percent >= threshold
}
/// 判断配额快照的主 rate-limit 是否已经触顶。
/// 判断配额快照是否已经触顶。
pub fn quota_snapshot_limit_reached(quota: &Value) -> bool {
quota
.pointer("/rate_limit/limit_reached")
.and_then(Value::as_bool)
.unwrap_or(false)
core_snapshot_blocked(quota)
|| spend_control_limit_reached(quota)
|| monthly_limit_reached(quota)
|| credits_exhausted(quota)
}
/// 从配额快照读取主 rate-limit 的 UTC 重置时间。
/// 从配额快照读取 UTC 重置时间。
pub fn quota_snapshot_reset_at(quota: &Value) -> Option<DateTime<Utc>> {
let reset_at = quota
.pointer("/rate_limit/reset_at")
.and_then(Value::as_i64)
.filter(|value| *value > 0)?;
let reset_at = if monthly_limit_reached(quota) || spend_control_limit_reached(quota) {
quota
.pointer("/monthly_limit/reset_at")
.and_then(positive_i64)
.or_else(|| blocking_core_bucket(quota).and_then(bucket_reset_at))
} else {
blocking_core_bucket(quota).and_then(bucket_reset_at)
}?;
DateTime::<Utc>::from_timestamp(reset_at, 0)
}
/// 从配额快照读取主 rate-limit 窗口大小。
/// 从配额快照读取窗口大小。
pub fn quota_snapshot_limit_window_seconds(quota: &Value) -> Option<u64> {
quota
.pointer("/rate_limit/limit_window_seconds")
.and_then(Value::as_u64)
.filter(|value| *value > 0)
if monthly_limit_reached(quota) || spend_control_limit_reached(quota) {
return Some(MONTH_WINDOW_SECONDS);
}
blocking_core_bucket(quota)
.and_then(bucket_window_minutes)
.and_then(|minutes| minutes.checked_mul(60))
}
/// 从 Codex usage 响应中提取持久化配额快照。
pub fn quota_from_usage(usage: &Value) -> Value {
let additional = usage
.get("additional_rate_limits")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default();
let mut rate_limits_by_limit_id = Map::new();
for item in &additional {
let Some(limit_id) = item
.get("metered_feature")
.and_then(Value::as_str)
.map(str::trim)
.filter(|value| !value.is_empty())
else {
continue;
};
let quota = quota_from_rate_limit(item.get("rate_limit"));
if quota.is_null() {
continue;
}
rate_limits_by_limit_id.insert(
limit_id.to_string(),
json!({
"limit_id": limit_id,
"limit_name": item.get("limit_name").cloned().unwrap_or(Value::Null),
"allowed": quota.get("allowed").cloned().unwrap_or(Value::Null),
"limit_reached": quota.get("limit_reached").cloned().unwrap_or(Value::Null),
"used_percent": quota.get("used_percent").cloned().unwrap_or(Value::Null),
"remaining_percent": quota.get("remaining_percent").cloned().unwrap_or(Value::Null),
"reset_at": quota.get("reset_at").cloned().unwrap_or(Value::Null),
"limit_window_seconds": quota.get("limit_window_seconds").cloned().unwrap_or(Value::Null),
"secondary_rate_limit": secondary_quota_from_rate_limit(item.get("rate_limit")),
}),
);
let mut snapshots = Vec::new();
if let Some(snapshot) = quota_snapshot_from_rate_limit(
"core",
usage.get("rate_limit_name").and_then(trimmed_str),
usage.get("metered_feature").and_then(trimmed_str),
usage.get("rate_limit"),
) {
snapshots.push(snapshot);
}
let additional_review = additional.iter().find(|item| {
is_review_limit_id(item.get("metered_feature").and_then(Value::as_str))
|| is_review_limit_id(item.get("limit_name").and_then(Value::as_str))
});
let code_review_rate_limit = match quota_from_rate_limit(usage.get("code_review_rate_limit")) {
Value::Null => {
quota_from_rate_limit(additional_review.and_then(|item| item.get("rate_limit")))
if let Some(additional) = usage
.get("additional_rate_limits")
.and_then(Value::as_array)
{
for item in additional {
let Some(limit_name) = item.get("limit_name").and_then(trimmed_str) else {
continue;
};
if let Some(snapshot) = quota_snapshot_from_rate_limit(
"additional",
Some(limit_name),
item.get("metered_feature").and_then(trimmed_str),
item.get("rate_limit"),
) {
snapshots.push(snapshot);
}
}
quota => quota,
};
}
let monthly_limit = monthly_limit_from_spend_control(usage.get("spend_control"))
.or_else(|| monthly_limit_from_snapshots(&snapshots))
.unwrap_or(Value::Null);
json!({
"plan_type": usage.get("plan_type").cloned().unwrap_or(Value::Null),
"rate_limit": quota_from_rate_limit(usage.get("rate_limit")),
"secondary_rate_limit": secondary_quota_from_rate_limit(usage.get("rate_limit")),
"code_review_rate_limit": code_review_rate_limit,
"rate_limits_by_limit_id": if rate_limits_by_limit_id.is_empty() {
Value::Null
} else {
Value::Object(rate_limits_by_limit_id)
},
"snapshots": snapshots,
"monthly_limit": monthly_limit,
"credits": normalize_quota_credits(usage.get("credits")),
"spend_control": normalize_spend_control(usage.get("spend_control")),
})
}
fn quota_from_rate_limit(rate_limit: Option<&Value>) -> Value {
fn quota_snapshot_from_rate_limit(
source: &str,
limit_name: Option<&str>,
metered_feature: Option<&str>,
rate_limit: Option<&Value>,
) -> Option<Value> {
let Some(rate_limit) = rate_limit.filter(|value| !value.is_null()) else {
return Value::Null;
return None;
};
let primary = rate_limit.get("primary_window");
let used_percent = primary
.and_then(|window| window.get("used_percent"))
.cloned()
.unwrap_or(Value::Null);
json!({
let primary = window_from_rate_limit(rate_limit.get("primary_window"));
let secondary = window_from_rate_limit(rate_limit.get("secondary_window"));
if primary.is_null() && secondary.is_null() {
return None;
}
Some(json!({
"source": source,
"limit_name": limit_name,
"metered_feature": metered_feature,
"allowed": rate_limit.get("allowed").cloned().unwrap_or(Value::Null),
"limit_reached": rate_limit.get("limit_reached").cloned().unwrap_or(Value::Null),
"used_percent": used_percent,
"remaining_percent": remaining_percent(primary.and_then(|window| window.get("used_percent"))),
"reset_at": primary.and_then(|window| window.get("reset_at")).cloned().unwrap_or(Value::Null),
"limit_window_seconds": primary.and_then(|window| window.get("limit_window_seconds")).cloned().unwrap_or(Value::Null),
})
"blocked": rate_limit_blocked(rate_limit)
|| window_limit_reached(&primary)
|| window_limit_reached(&secondary),
"primary": primary,
"secondary": secondary,
}))
}
fn secondary_quota_from_rate_limit(rate_limit: Option<&Value>) -> Value {
let Some(secondary) = rate_limit
.and_then(|rate_limit| rate_limit.get("secondary_window"))
.filter(|value| !value.is_null())
else {
fn window_from_rate_limit(window: Option<&Value>) -> Value {
let Some(window) = window.filter(|value| !value.is_null()) else {
return Value::Null;
};
let used_percent = secondary
let used_percent = window
.get("used_percent")
.cloned()
.unwrap_or(Value::Null);
let limit_reached = secondary
.get("used_percent")
.and_then(Value::as_f64)
.map(|used| used >= 100.0)
.map(Value::Bool)
.or_else(|| {
rate_limit
.and_then(|rate_limit| rate_limit.get("limit_reached"))
.cloned()
})
.unwrap_or(Value::Null);
.and_then(number_value)
.unwrap_or(0.0)
.clamp(0.0, 100.0);
let window_minutes = window
.get("limit_window_seconds")
.and_then(number_value)
.filter(|seconds| *seconds > 0.0)
.map(|seconds| (seconds / 60.0).round() as u64);
json!({
"limit_reached": limit_reached,
"used_percent": used_percent,
"remaining_percent": remaining_percent(secondary.get("used_percent")),
"reset_at": secondary.get("reset_at").cloned().unwrap_or(Value::Null),
"limit_window_seconds": secondary.get("limit_window_seconds").cloned().unwrap_or(Value::Null),
"remaining_percent": remaining_percent(used_percent),
"reset_at": window.get("reset_at").and_then(positive_i64),
"window_minutes": window_minutes,
"limit_reached": used_percent >= 100.0,
})
}
@@ -150,41 +141,206 @@ fn normalize_quota_credits(raw: Option<&Value>) -> Value {
let Some(raw) = raw.filter(|value| !value.is_null()) else {
return Value::Null;
};
let Some(balance) = raw
.get("balance")
.and_then(Value::as_str)
.and_then(|value| value.parse::<f64>().ok())
.filter(|value| value.is_finite())
else {
return Value::Null;
};
json!({
"has_credits": raw.get("has_credits").and_then(Value::as_bool).unwrap_or(false),
"unlimited": raw.get("unlimited").and_then(Value::as_bool).unwrap_or(false),
"overage_limit_reached": raw.get("overage_limit_reached").and_then(Value::as_bool).unwrap_or(false),
"balance": balance,
"balance": raw.get("balance").cloned().unwrap_or(Value::Null),
})
}
fn remaining_percent(used_percent: Option<&Value>) -> Value {
let Some(used_percent) = used_percent.and_then(Value::as_f64) else {
fn normalize_spend_control(raw: Option<&Value>) -> Value {
let Some(raw) = raw.filter(|value| !value.is_null()) else {
return Value::Null;
};
json!((100.0 - used_percent.clamp(0.0, 100.0)).round() as i64)
raw.clone()
}
fn is_review_limit_id(value: Option<&str>) -> bool {
let normalized = value
.unwrap_or_default()
.trim()
.to_ascii_lowercase()
.replace(['-', ' '], "_");
normalized == "review"
|| normalized == "code_review"
|| normalized == "codex_review"
|| normalized == "codex_code_review"
|| normalized.contains("code_review")
|| normalized.contains("codex_review")
fn monthly_limit_from_spend_control(spend_control: Option<&Value>) -> Option<Value> {
let individual_limit = spend_control?
.get("individual_limit")
.filter(|value| !value.is_null())?;
let used_percent = individual_limit
.get("used_percent")
.and_then(number_value)
.unwrap_or(0.0)
.clamp(0.0, 100.0);
Some(json!({
"key": "spend-control-monthly",
"source": "spend_control",
"used_percent": used_percent,
"remaining_percent": individual_limit
.get("remaining_percent")
.and_then(number_value)
.unwrap_or_else(|| remaining_percent(used_percent) as f64),
"reset_at": individual_limit.get("reset_at").and_then(positive_i64),
"window_minutes": MONTH_WINDOW_MINUTES,
"limit_reached": spend_control_limit_reached_value(spend_control.unwrap_or(&Value::Null), used_percent),
"used_credits": individual_limit.get("used").cloned().unwrap_or(Value::Null),
"limit_credits": individual_limit.get("limit").cloned().unwrap_or(Value::Null),
}))
}
fn monthly_limit_from_snapshots(snapshots: &[Value]) -> Option<Value> {
for snapshot in snapshots {
if snapshot.get("source").and_then(Value::as_str) != Some("core") {
continue;
}
for key in ["primary", "secondary"] {
let Some(bucket) = snapshot.get(key).filter(|value| !value.is_null()) else {
continue;
};
if bucket
.get("window_minutes")
.and_then(Value::as_u64)
.is_some_and(|minutes| window_minutes_match(minutes, MONTH_WINDOW_MINUTES))
{
return Some(json!({
"key": "core-monthly",
"source": "rate_limit",
"used_percent": bucket.get("used_percent").cloned().unwrap_or(Value::Null),
"remaining_percent": bucket.get("remaining_percent").cloned().unwrap_or(Value::Null),
"reset_at": bucket.get("reset_at").cloned().unwrap_or(Value::Null),
"window_minutes": bucket.get("window_minutes").cloned().unwrap_or(Value::Null),
"limit_reached": bucket.get("limit_reached").cloned().unwrap_or(Value::Bool(false)),
"used_credits": Value::Null,
"limit_credits": Value::Null,
}));
}
}
}
None
}
fn remaining_percent(used_percent: f64) -> i64 {
(100.0 - used_percent.clamp(0.0, 100.0)).round() as i64
}
fn rate_limit_blocked(rate_limit: &Value) -> bool {
rate_limit
.get("limit_reached")
.and_then(Value::as_bool)
.unwrap_or(false)
|| rate_limit
.get("allowed")
.and_then(Value::as_bool)
.is_some_and(|allowed| !allowed)
}
fn window_limit_reached(window: &Value) -> bool {
window
.get("limit_reached")
.and_then(Value::as_bool)
.unwrap_or(false)
}
fn spend_control_limit_reached(quota: &Value) -> bool {
quota
.pointer("/spend_control/reached")
.and_then(Value::as_bool)
.unwrap_or(false)
|| quota
.pointer("/spend_control/individual_limit/used_percent")
.and_then(number_value)
.is_some_and(|used_percent| used_percent >= 100.0)
}
fn spend_control_limit_reached_value(spend_control: &Value, used_percent: f64) -> bool {
spend_control
.get("reached")
.and_then(Value::as_bool)
.unwrap_or(false)
|| used_percent >= 100.0
}
fn monthly_limit_reached(quota: &Value) -> bool {
quota
.pointer("/monthly_limit/limit_reached")
.and_then(Value::as_bool)
.unwrap_or(false)
}
fn core_snapshot_blocked(quota: &Value) -> bool {
quota
.get("snapshots")
.and_then(Value::as_array)
.into_iter()
.flatten()
.any(|snapshot| {
snapshot.get("source").and_then(Value::as_str) == Some("core")
&& snapshot
.get("blocked")
.and_then(Value::as_bool)
.unwrap_or(false)
})
}
fn blocking_core_bucket(quota: &Value) -> Option<&Value> {
quota
.get("snapshots")
.and_then(Value::as_array)?
.iter()
.filter(|snapshot| snapshot.get("source").and_then(Value::as_str) == Some("core"))
.flat_map(|snapshot| {
["primary", "secondary"]
.into_iter()
.filter_map(|key| snapshot.get(key))
})
.find(|bucket| {
!bucket.is_null()
&& bucket
.get("limit_reached")
.and_then(Value::as_bool)
.unwrap_or(false)
})
}
fn bucket_reset_at(bucket: &Value) -> Option<i64> {
bucket.get("reset_at").and_then(positive_i64)
}
fn bucket_window_minutes(bucket: &Value) -> Option<u64> {
bucket
.get("window_minutes")
.and_then(Value::as_u64)
.filter(|value| *value > 0)
}
fn credits_exhausted(quota: &Value) -> bool {
quota
.pointer("/credits/unlimited")
.and_then(Value::as_bool)
.is_some_and(|unlimited| !unlimited)
&& quota
.pointer("/credits/has_credits")
.and_then(Value::as_bool)
.is_some_and(|has_credits| !has_credits)
}
fn number_value(value: &Value) -> Option<f64> {
value
.as_f64()
.or_else(|| value.as_str().and_then(|value| value.parse::<f64>().ok()))
.filter(|value| value.is_finite())
}
fn positive_i64(value: &Value) -> Option<i64> {
value
.as_i64()
.filter(|value| *value > 0)
.or_else(|| value.as_u64().and_then(|value| i64::try_from(value).ok()))
.filter(|value| *value > 0)
}
fn trimmed_str(value: &Value) -> Option<&str> {
value
.as_str()
.map(str::trim)
.filter(|value| !value.is_empty())
}
fn window_minutes_match(actual: u64, expected: u64) -> bool {
actual > 0 && actual.abs_diff(expected) <= expected / 20
}
mod runtime;
+119 -31
View File
@@ -331,18 +331,65 @@ pub fn rate_limit_quota(
plan_type: Option<&str>,
existing_quota: Option<&Value>,
) -> Value {
let mut quota = json!({
"plan_type": plan_type.unwrap_or("unknown"),
"rate_limit": quota_window(rate_limits.primary, true),
"secondary_rate_limit": rate_limits.secondary.map(|window| quota_window(Some(window), false)).unwrap_or(Value::Null),
"code_review_rate_limit": rate_limits.code_review.map(code_review_quota_window).unwrap_or(Value::Null),
});
if let Some(credits) = existing_quota.and_then(|quota| quota.get("credits")) {
quota["credits"] = credits.clone();
let mut snapshots = Vec::new();
if let Some(snapshot) = quota_snapshot_from_windows(
"core",
None,
None,
rate_limits.primary,
rate_limits.secondary,
None,
None,
) {
snapshots.push(snapshot);
}
quota
let has_code_review_update = rate_limits.code_review.is_some();
if let Some(details) = rate_limits.code_review {
if let Some(snapshot) = quota_snapshot_from_windows(
"code_review",
Some("code_review"),
None,
details.primary,
details.secondary,
details.allowed,
details.limit_reached,
) {
snapshots.push(snapshot);
}
}
if let Some(existing_quota) = existing_quota {
if let Some(existing_snapshots) = existing_quota.get("snapshots").and_then(Value::as_array)
{
for snapshot in existing_snapshots {
let source = snapshot.get("source").and_then(Value::as_str);
if source == Some("additional")
|| (!has_code_review_update && source == Some("code_review"))
{
snapshots.push(snapshot.clone());
}
}
}
}
let monthly_limit = monthly_limit_from_snapshots(&snapshots)
.or_else(|| existing_quota.and_then(|quota| quota.get("monthly_limit").cloned()))
.unwrap_or(Value::Null);
let credits = existing_quota
.and_then(|quota| quota.get("credits").cloned())
.unwrap_or(Value::Null);
let spend_control = existing_quota
.and_then(|quota| quota.get("spend_control").cloned())
.unwrap_or(Value::Null);
json!({
"plan_type": plan_type.unwrap_or("unknown"),
"snapshots": snapshots,
"monthly_limit": monthly_limit,
"credits": credits,
"spend_control": spend_control,
})
}
/// 将限流状态转换回 HTTP 头键值对。
@@ -559,37 +606,78 @@ fn parse_window_from_object(value: &Value) -> Option<RateLimitWindow> {
})
}
fn quota_window(window: Option<RateLimitWindow>, include_allowed: bool) -> Value {
fn quota_snapshot_from_windows(
source: &str,
limit_name: Option<&str>,
metered_feature: Option<&str>,
primary: Option<RateLimitWindow>,
secondary: Option<RateLimitWindow>,
allowed: Option<bool>,
limit_reached: Option<bool>,
) -> Option<Value> {
if primary.is_none() && secondary.is_none() {
return None;
}
let blocked = limit_reached.unwrap_or_else(|| {
allowed.is_some_and(|allowed| !allowed)
|| primary.is_some_and(|window| window.used_percent >= 100.0)
|| secondary.is_some_and(|window| window.used_percent >= 100.0)
});
Some(json!({
"source": source,
"limit_name": limit_name,
"metered_feature": metered_feature,
"allowed": allowed,
"limit_reached": limit_reached,
"blocked": blocked,
"primary": quota_window(primary),
"secondary": quota_window(secondary),
}))
}
fn quota_window(window: Option<RateLimitWindow>) -> Value {
let Some(window) = window else {
return Value::Null;
};
let limit_reached = window.used_percent >= 100.0;
let mut value = json!({
json!({
"used_percent": window.used_percent,
"remaining_percent": remaining_percent(window.used_percent),
"reset_at": window.reset_at,
"limit_window_seconds": window.limit_window_seconds(),
"window_minutes": window.window_minutes,
"limit_reached": limit_reached,
});
if include_allowed {
value["allowed"] = Value::Bool(!limit_reached);
}
value
})
}
fn code_review_quota_window(details: RateLimitDetails) -> Value {
let used_percent = details.primary.map(|window| window.used_percent);
let limit_reached = details
.limit_reached
.unwrap_or_else(|| used_percent.is_some_and(|used| used >= 100.0));
json!({
"allowed": details.allowed.unwrap_or(true),
"limit_reached": limit_reached,
"used_percent": used_percent,
"remaining_percent": used_percent.map(remaining_percent),
"reset_at": details.primary.and_then(|window| window.reset_at),
"limit_window_seconds": details.primary.and_then(RateLimitWindow::limit_window_seconds),
})
fn monthly_limit_from_snapshots(snapshots: &[Value]) -> Option<Value> {
for snapshot in snapshots {
if snapshot.get("source").and_then(Value::as_str) != Some("core") {
continue;
}
for key in ["primary", "secondary"] {
let Some(bucket) = snapshot.get(key).filter(|value| !value.is_null()) else {
continue;
};
if bucket
.get("window_minutes")
.and_then(Value::as_u64)
.is_some_and(|minutes| minutes.abs_diff(43_200) <= 2_160)
{
return Some(json!({
"key": "core-monthly",
"source": "rate_limit",
"used_percent": bucket.get("used_percent").cloned().unwrap_or(Value::Null),
"remaining_percent": bucket.get("remaining_percent").cloned().unwrap_or(Value::Null),
"reset_at": bucket.get("reset_at").cloned().unwrap_or(Value::Null),
"window_minutes": bucket.get("window_minutes").cloned().unwrap_or(Value::Null),
"limit_reached": bucket.get("limit_reached").cloned().unwrap_or(Value::Bool(false)),
"used_credits": Value::Null,
"limit_credits": Value::Null,
}));
}
}
}
None
}
fn remaining_percent(used_percent: f64) -> i64 {