Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1600,6 +1600,7 @@ mod tests {
user_is_active: true,
user_is_deleted: false,
user_rate_limit: None,
user_daily_usage_limit_usd: None,
user_allowed_providers: None,
user_allowed_api_formats: None,
user_allowed_models: None,
Expand All @@ -1609,6 +1610,7 @@ mod tests {
api_key_is_locked: false,
api_key_is_standalone: false,
api_key_rate_limit: None,
api_key_daily_usage_limit_usd: None,
api_key_concurrent_limit: None,
api_key_expires_at_unix_secs: None,
api_key_allowed_providers: None,
Expand Down
2 changes: 2 additions & 0 deletions apps/aether-gateway/src/ai_serving/planner/decision_input.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1125,6 +1125,7 @@ mod tests {
user_is_active: true,
user_is_deleted: false,
user_rate_limit: None,
user_daily_usage_limit_usd: None,
user_allowed_providers: None,
user_allowed_api_formats: None,
user_allowed_models: None,
Expand All @@ -1134,6 +1135,7 @@ mod tests {
api_key_is_locked: false,
api_key_is_standalone: false,
api_key_rate_limit: None,
api_key_daily_usage_limit_usd: None,
api_key_concurrent_limit: None,
api_key_expires_at_unix_secs: None,
api_key_allowed_providers: None,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,7 @@ mod tests {
user_is_active: true,
user_is_deleted: false,
user_rate_limit: None,
user_daily_usage_limit_usd: None,
user_allowed_providers: None,
user_allowed_api_formats: None,
user_allowed_models: None,
Expand All @@ -349,6 +350,7 @@ mod tests {
api_key_is_locked: false,
api_key_is_standalone: false,
api_key_rate_limit: None,
api_key_daily_usage_limit_usd: None,
api_key_concurrent_limit: None,
api_key_expires_at_unix_secs: None,
api_key_allowed_providers: None,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2158,6 +2158,7 @@ mod tests {
user_is_active: true,
user_is_deleted: false,
user_rate_limit: None,
user_daily_usage_limit_usd: None,
user_allowed_providers: None,
user_allowed_api_formats: None,
user_allowed_models: None,
Expand All @@ -2167,6 +2168,7 @@ mod tests {
api_key_is_locked: false,
api_key_is_standalone: false,
api_key_rate_limit: None,
api_key_daily_usage_limit_usd: None,
api_key_concurrent_limit: None,
api_key_expires_at_unix_secs: None,
api_key_allowed_providers: None,
Expand Down
104 changes: 104 additions & 0 deletions apps/aether-gateway/src/api/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ use crate::ai_serving::{build_core_error_body_for_client_format, LocalCoreSyncEr
use crate::constants::*;
use crate::control::GatewayControlDecision;
use crate::control::GatewayLocalAuthRejection;
use crate::daily_usage_limit::{DailyUsageLimitedResponse, FrontdoorDailyUsageRejection};
use crate::headers::should_skip_response_header;
use crate::rate_limit::FrontdoorUserRpmRejection;
use crate::{insert_header_if_missing, GatewayError};
Expand Down Expand Up @@ -258,6 +259,74 @@ pub(crate) fn build_local_user_rpm_limited_response(
)
}

pub(crate) fn build_local_daily_usage_limited_response(
trace_id: &str,
control_decision: Option<&GatewayControlDecision>,
rejection: &FrontdoorDailyUsageRejection,
) -> Result<Response<Body>, GatewayError> {
let message = "已达到每日使用上限,请在额度重置后重试";
let fallback_payload = json!({
"error": {
"type": "daily_usage_limit_exceeded",
"message": message,
"details": {
"limit_usd": rejection.limit_usd,
"used_usd": rejection.used_usd,
"remaining_usd": rejection.remaining_usd,
"scope": rejection.scope,
"reset_at": rejection.reset_at_unix_secs,
"timezone": rejection.timezone,
}
}
});
let payload = if local_error_uses_claude_format(control_decision, None) {
build_core_error_body_for_client_format(
"claude:messages",
message,
Some("daily_usage_limit_exceeded"),
LocalCoreSyncErrorKind::RateLimit,
)
.unwrap_or(fallback_payload)
} else {
fallback_payload
};
let body =
serde_json::to_vec(&payload).map_err(|err| GatewayError::Internal(err.to_string()))?;
let headers = BTreeMap::from([
("content-type".to_string(), "application/json".to_string()),
("Retry-After".to_string(), rejection.retry_after.to_string()),
(
"X-Daily-Usage-Limit-USD".to_string(),
format!("{:.8}", rejection.limit_usd),
),
(
"X-Daily-Usage-Used-USD".to_string(),
format!("{:.8}", rejection.used_usd),
),
(
"X-Daily-Usage-Remaining-USD".to_string(),
format!("{:.8}", rejection.remaining_usd),
),
(
"X-Daily-Usage-Scope".to_string(),
rejection.scope.to_string(),
),
(
"X-Daily-Usage-Reset".to_string(),
rejection.reset_at_unix_secs.to_string(),
),
]);
let mut response = build_client_response_from_parts(
StatusCode::TOO_MANY_REQUESTS.as_u16(),
&headers,
Body::from(body),
trace_id,
control_decision,
)?;
response.extensions_mut().insert(DailyUsageLimitedResponse);
Ok(response)
}

pub(crate) fn build_local_http_error_response(
trace_id: &str,
control_decision: Option<&GatewayControlDecision>,
Expand Down Expand Up @@ -455,10 +524,12 @@ fn local_error_kind_for_status(status: StatusCode) -> LocalCoreSyncErrorKind {
mod tests {
use super::{
build_client_response_from_parts, build_local_auth_rejection_response,
build_local_daily_usage_limited_response,
build_local_http_error_response_with_request_path, build_local_overloaded_response,
build_local_user_rpm_limited_response,
};
use crate::control::{GatewayControlDecision, GatewayLocalAuthRejection};
use crate::daily_usage_limit::FrontdoorDailyUsageRejection;
use crate::rate_limit::FrontdoorUserRpmRejection;
use axum::body::{to_bytes, Body};
use std::collections::BTreeMap;
Expand Down Expand Up @@ -547,6 +618,39 @@ mod tests {
assert_eq!(overloaded["error"]["type"], "overloaded_error");
}

#[tokio::test]
async fn daily_usage_limit_response_has_dedicated_error_and_reset_headers() {
let response = build_local_daily_usage_limited_response(
"trace-daily-limit",
None,
&FrontdoorDailyUsageRejection {
scope: "user",
limit_usd: 10.0,
used_usd: 10.25,
remaining_usd: 0.0,
retry_after: 120,
reset_at_unix_secs: 1_800_000_000,
timezone: "Asia/Shanghai".to_string(),
},
)
.expect("daily limit response should build");

assert_eq!(response.status(), http::StatusCode::TOO_MANY_REQUESTS);
assert_eq!(response.headers()["retry-after"], "120");
assert_eq!(response.headers()["x-daily-usage-limit-usd"], "10.00000000");
assert_eq!(response.headers()["x-daily-usage-used-usd"], "10.25000000");
assert_eq!(
response.headers()["x-daily-usage-remaining-usd"],
"0.00000000"
);
assert_eq!(response.headers()["x-daily-usage-scope"], "user");
assert_eq!(response.headers()["x-daily-usage-reset"], "1800000000");

let payload = response_json(response).await;
assert_eq!(payload["error"]["type"], "daily_usage_limit_exceeded");
assert_eq!(payload["error"]["details"]["timezone"], "Asia/Shanghai");
}

#[tokio::test]
async fn claude_path_shapes_pre_control_http_errors_and_413() {
for path in ["/v1/messages", "/v1/messages/count_tokens"] {
Expand Down
104 changes: 104 additions & 0 deletions apps/aether-gateway/src/app_timezone.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
use std::sync::LazyLock;

use chrono::{DateTime, LocalResult, NaiveDate, TimeZone, Utc};
use chrono_tz::Tz;
use tracing::warn;

pub(crate) const DEFAULT_APP_TIMEZONE: &str = "Asia/Shanghai";

static APP_TIMEZONE: LazyLock<Tz> = LazyLock::new(|| {
let configured = std::env::var("APP_TIMEZONE")
.ok()
.map(|value| value.trim().to_string())
.filter(|value| !value.is_empty())
.unwrap_or_else(|| DEFAULT_APP_TIMEZONE.to_string());
configured.parse().unwrap_or_else(|_| {
warn!(
timezone = %configured,
fallback = DEFAULT_APP_TIMEZONE,
"gateway APP_TIMEZONE invalid; falling back"
);
DEFAULT_APP_TIMEZONE
.parse()
.expect("default application timezone should parse")
})
});

pub(crate) fn app_timezone() -> Tz {
*APP_TIMEZONE
}

pub(crate) fn local_day_window(
now_utc: DateTime<Utc>,
timezone: Tz,
) -> (NaiveDate, DateTime<Utc>, DateTime<Utc>) {
let local_date = now_utc.with_timezone(&timezone).date_naive();
let next_date = local_date
.succ_opt()
.expect("application local date should have a successor");
(
local_date,
local_midnight_utc(local_date, timezone),
local_midnight_utc(next_date, timezone),
)
}

fn local_midnight_utc(date: NaiveDate, timezone: Tz) -> DateTime<Utc> {
let midnight = date
.and_hms_opt(0, 0, 0)
.expect("local midnight should be valid");
match timezone.from_local_datetime(&midnight) {
LocalResult::Single(value) => value.with_timezone(&Utc),
LocalResult::Ambiguous(first, second) => first.min(second).with_timezone(&Utc),
LocalResult::None => {
for minute in 1..=180 {
let candidate = midnight + chrono::Duration::minutes(minute);
match timezone.from_local_datetime(&candidate) {
LocalResult::Single(value) => return value.with_timezone(&Utc),
LocalResult::Ambiguous(first, second) => {
return first.min(second).with_timezone(&Utc)
}
LocalResult::None => {}
}
}
panic!("local day start should resolve within three hours")
}
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn default_timezone_uses_shanghai_natural_day() {
let timezone: Tz = DEFAULT_APP_TIMEZONE.parse().unwrap();
let (_, start, end) = local_day_window(
DateTime::parse_from_rfc3339("2026-08-03T12:00:00Z")
.unwrap()
.with_timezone(&Utc),
timezone,
);
assert_eq!(start.to_rfc3339(), "2026-08-02T16:00:00+00:00");
assert_eq!(end.to_rfc3339(), "2026-08-03T16:00:00+00:00");
}

#[test]
fn dst_days_use_natural_local_midnights() {
let timezone: Tz = "America/New_York".parse().unwrap();
let spring = local_day_window(
DateTime::parse_from_rfc3339("2026-03-08T12:00:00Z")
.unwrap()
.with_timezone(&Utc),
timezone,
);
assert_eq!((spring.2 - spring.1).num_hours(), 23);
let fall = local_day_window(
DateTime::parse_from_rfc3339("2026-11-01T12:00:00Z")
.unwrap()
.with_timezone(&Utc),
timezone,
);
assert_eq!((fall.2 - fall.1).num_hours(), 25);
}
}
3 changes: 3 additions & 0 deletions apps/aether-gateway/src/cache/auth_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -417,8 +417,11 @@ mod tests {
access_allowed: true,
user_rate_limit: None,
api_key_rate_limit: None,
user_daily_usage_limit_usd: None,
api_key_daily_usage_limit_usd: None,
api_key_is_standalone: false,
admin_bypass_limits: false,
ip_bypass_limits: false,
local_rejection: None,
allowed_models: None,
ip_rules: None,
Expand Down
2 changes: 2 additions & 0 deletions apps/aether-gateway/src/cache/candidate_page.rs
Original file line number Diff line number Diff line change
Expand Up @@ -542,6 +542,7 @@ mod tests {
user_is_active: true,
user_is_deleted: false,
user_rate_limit: None,
user_daily_usage_limit_usd: None,
user_allowed_providers: None,
user_allowed_api_formats: None,
user_allowed_models: None,
Expand All @@ -551,6 +552,7 @@ mod tests {
api_key_is_locked: false,
api_key_is_standalone: false,
api_key_rate_limit: None,
api_key_daily_usage_limit_usd: None,
api_key_concurrent_limit: None,
api_key_expires_at_unix_secs: None,
api_key_allowed_providers: None,
Expand Down
Loading
Loading